smolerclaw 1.3.1 → 1.3.3
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 +271 -208
- 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 XQ=Object.defineProperty;var KQ=($)=>$;function zQ($,Z){this[$]=KQ.bind(null,Z)}var FZ=($,Z)=>{for(var J in Z)XQ($,J,{get:Z[J],enumerable:!0,configurable:!0,set:zQ.bind(Z,J)})};var r4=($,Z)=>()=>($&&(Z=$($=0)),Z);import{existsSync as qQ,appendFileSync as WQ,mkdirSync as zq}from"fs";import{join as TZ}from"path";import{homedir as UQ}from"os";function T8($,Z,J){if(!n7)return;let Y=new Date().toISOString(),Q=J?`[${Y}] [${$}] ${Z} ${JSON.stringify(J)}
|
|
4
4
|
`:`[${Y}] [${$}] ${Z}
|
|
5
|
-
`;try{
|
|
6
|
-
... (truncated, ${Z.length} total chars)`;return Z}function
|
|
5
|
+
`;try{WQ(MQ,Q)}catch{}}function AZ($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function IZ($){let Z=$.replace(/\//g,"\\");return AZ(Z)}async function i1($){let Z=a1.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(qQ($)){let Y={exists:!0,path:$};return a1.set($.toLowerCase(),Y),Y}return{exists:!1,error:`File not found: ${$}`}}let J=`(Get-Command '${$}' -ErrorAction SilentlyContinue).Source`;try{let Y=await G$(J,{timeout:5000});if(Y.exitCode===0&&Y.stdout.trim()){let X={exists:!0,path:Y.stdout.trim()};return a1.set($.toLowerCase(),X),X}let Q={exists:!1,error:`'${$}' not found in PATH`};return a1.set($.toLowerCase(),Q),Q}catch(Y){return{exists:!1,error:Y instanceof Error?Y.message:String(Y)}}}async function G$($,Z={}){let{timeout:J=PZ,cwd:Y,debug:Q=n7,sta:X=!1}=Z,K=performance.now(),V=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,G=["powershell",...CQ];if(X)G.push("-STA");if(G.push("-Command",V),Q)T8("INFO","Executing PowerShell command",{command:$.slice(0,500),timeout:J,cwd:Y,sta:X});let H;try{H=Bun.spawn(G,{stdout:"pipe",stderr:"pipe",cwd:Y})}catch(B){let M={stdout:"",stderr:`Failed to spawn PowerShell: ${B instanceof Error?B.message:String(B)}`,exitCode:1,duration:Math.round(performance.now()-K),timedOut:!1};if(Q)T8("ERROR","Failed to spawn process",{error:M.stderr});return M}let z=!1,U=setTimeout(()=>{z=!0;try{H.kill()}catch{}},J);try{let[B,M]=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(U);let L=Math.round(performance.now()-K),T={stdout:r1(B),stderr:r1(M),exitCode:z?-1:O,duration:L,timedOut:z};if(Q)T8(T.exitCode===0?"INFO":"WARN","Command completed",{exitCode:T.exitCode,duration:L,timedOut:z,stdoutLength:T.stdout.length,stderrLength:T.stderr.length});return T}catch(B){clearTimeout(U);let M={stdout:"",stderr:`Execution error: ${B instanceof Error?B.message:String(B)}`,exitCode:1,duration:Math.round(performance.now()-K),timedOut:z};if(Q)T8("ERROR","Execution failed",{error:M.stderr,timedOut:z});return M}}async function xZ($,Z={}){let Y=`& ${IZ($)}`;return G$(Y,Z)}async function s7($,Z={}){let{timeout:J=PZ,cwd:Y,debug:Q=n7}=Z,X=performance.now();if(Q)T8("INFO","Executing command",{args:$,timeout:J,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{}},J);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():""]),U=await K.exited;return clearTimeout(G),{stdout:r1(H),stderr:r1(z),exitCode:V?-1:U,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 t7($,Z={}){return G$($,{...Z,sta:!0})}async function n1($,Z,J=[],Y={}){let Q=["schtasks",`/${$}`,"/TN",Z,...J],X=Y.timeout??1e4;return s7(Q,{...Y,timeout:X})}async function e7($,Z,J={}){let Y=AZ($),Q=Z?`Start-Process ${Y} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Y}`;return G$(Q,J)}async function SZ($,Z={}){let J=IZ($);return G$(`Invoke-Item ${J}`,Z)}async function J4($,Z,J={}){let Y=DZ($),Q=DZ(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">${Q}</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=J.timeout??1e4;return G$(X,{...J,timeout:K})}async function s1($,Z={}){let Y=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await G$(Y,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function wZ($=15,Z={}){let J=`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 G$(J,Z)}function r1($){let Z=$.replace(BQ,"");if(Z.length>LZ)return Z.slice(0,LZ)+`
|
|
6
|
+
... (truncated, ${Z.length} total chars)`;return Z}function DZ($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function kZ($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var PZ=15000,LZ=1e5,BQ,NQ,MQ,CQ,n7=!1,a1;var Y4=r4(()=>{BQ=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,NQ=TZ(UQ(),".smolerclaw","logs"),MQ=TZ(NQ,"windows-executor.log"),CQ=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];a1=new Map});import{existsSync as jQ}from"fs";function i4(){if(I)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&jQ($))return[$,"-c"];return["bash","-c"]}function yZ(){if(I)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function OQ($){if(I)return(await i1($)).exists;try{return(await s7(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function _Z(){if(t1!==null)return t1;return t1=await OQ("rg"),t1}function $5($){let Z=$.replace(/\\/g,"/");return P8.some((J)=>Z.includes(`/${J}/`)||Z.startsWith(`${J}/`))}var I,bZ,Nq,t1=null,P8;var $$=r4(()=>{Y4();I=process.platform==="win32",bZ=process.platform==="darwin",Nq=process.platform==="linux";P8=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as FQ}from"events";class vZ{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new FQ,this.emitter.setMaxListeners($.maxListeners??20),this.debug=$.debug??!!process.env.DEBUG}on($,Z,J={}){let Y={listener:Z,once:!1,async:J.async??!1},Q=this.listeners.get($)??[];if(Q.push(Y),this.listeners.set($,Q),this.debug)console.log(`[event-bus] Registered listener for '${$}'`);return()=>this.off($,Z)}once($,Z,J={}){let Y={listener:Z,once:!0,async:J.async??!1},Q=this.listeners.get($)??[];if(Q.push(Y),this.listeners.set($,Q),this.debug)console.log(`[event-bus] Registered once listener for '${$}'`);return()=>this.off($,Z)}off($,Z){let J=this.listeners.get($);if(!J)return;let Y=J.filter((Q)=>Q.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 J=this.listeners.get($);if(!J||J.length===0){if(this.debug)console.log(`[event-bus] No listeners for '${$}'`);return}if(this.debug)console.log(`[event-bus] Emitting '${$}' to ${J.length} listener(s)`);let Y=[];for(let Q of J)try{let X=Q.listener(Z);if(Q.async&&X instanceof Promise)X.catch((K)=>{this.handleError(K,$,Z)});if(Q.once)Y.push(Q)}catch(X){this.handleError(X instanceof Error?X:Error(String(X)),$,Z)}if(Y.length>0){let Q=J.filter((X)=>!Y.includes(X));if(Q.length===0)this.listeners.delete($);else this.listeners.set($,Q)}}async emitAsync($,Z){let J=this.listeners.get($);if(!J||J.length===0)return;if(this.debug)console.log(`[event-bus] Emitting async '${$}' to ${J.length} listener(s)`);let Y=[],Q=[];for(let X of J)try{let K=X.listener(Z);if(K instanceof Promise)Q.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(Q),Y.length>0){let X=J.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,J){if(this.debug||process.env.DEBUG)console.error(`[event-bus] Error in '${Z}' listener:`,$.message);for(let Y of this.errorHandlers)try{Y($,Z,J)}catch{}}}function Q4($){if(!Z5)Z5=new vZ($);return Z5}var Z5=null,H$;var A8=r4(()=>{H$=Q4()});import{existsSync as f$,mkdirSync as J5,readFileSync as $0,writeFileSync as I8,renameSync as fZ,statSync as RQ}from"fs";import{join as B$,dirname as hZ,relative as EQ}from"path";import{createHash as LQ,randomUUID as gZ}from"crypto";function dZ($,Z){if(h$=$,uZ=Z,Z$=B$($,".backup"),TQ(),Q5=!0,T4=f$(B$(Z$,".git")),T4)Y5=IQ()}function x8(){return Q5}function x($,Z){let J=hZ($);if(!f$(J))J5(J,{recursive:!0});let Y=B$(J,`.smolerclaw-${gZ().slice(0,8)}.tmp`);I8(Y,Z),fZ(Y,$);let Q=!1;if(Q5){let K=AQ($);if(K&&Z0.includes(K))DQ(K,Z),Q=!0}let X={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:Q,timestamp:Date.now()};H$.emit("file:saved",X)}function lZ($){return LQ("sha256").update($).digest("hex")}function DQ($,Z){let J=lZ(Z),Y=new Date().toISOString(),Q=Buffer.byteLength(Z,"utf-8");X4=[...X4.filter((X)=>X.file!==$),{file:$,sha256:J,size:Q,updatedAt:Y}],PQ()}function TQ(){let $=B$(h$,cZ);if(!f$($)){X4=[];return}try{let Z=JSON.parse($0($,"utf-8"));if(Z.version!==mZ){X4=[];return}X4=Z.checksums||[]}catch{X4=[]}}function PQ(){if(!h$)return;let $=B$(h$,cZ),Z={checksums:X4,version:mZ},J=B$(h$,`.vault-${gZ().slice(0,8)}.tmp`);I8(J,JSON.stringify(Z,null,2)),fZ(J,$)}function AQ($){try{let Z=EQ(h$,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function J0(){let $=[],Z=0;for(let J of Z0){let Y=B$(h$,J),Q=f$(Y);if(!Q){$.push({file:J,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let X=0,K="";try{let H=RQ(Y);X=H.size,K=H.mtime.toISOString()}catch{}let V=X4.find((H)=>H.file===J),G=null;if(V)try{let H=$0(Y,"utf-8");if(G=lZ(H)===V.sha256,!G)Z++}catch{G=!1,Z++}$.push({file:J,exists:Q,checksumValid:G,size:X,lastModified:K})}return{files:$,lastBackup:Y5,backupEnabled:T4,totalFiles:$.filter((J)=>J.exists).length,corruptFiles:Z}}function Y0($){let Z=["=== Vault Status ==="],J=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${J}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${Z0.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
|
|
7
7
|
--- Arquivos ---`);for(let Y of $.files){if(!Y.exists){Z.push(` ${Y.file.padEnd(30)} (nao existe)`);continue}let Q=(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)} ${Q.padStart(8)} KB [${X}] ${K}`)}return Z.join(`
|
|
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;J.push("```"),J.push(G),J.push("```")}}if(Z.findings.length>0){let K=[...Z.findings].sort((V,G)=>(X[V.severity]??4)-(X[G.severity]??4));J.push(""),J.push(`## Conclusoes (${Z.findings.length})`);for(let V of K){let G=
|
|
14
|
-
`)}function
|
|
8
|
+
`)}async function Q0(){if(!h$)return"Error: vault not initialized.";if(!f$(Z$))J5(Z$,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
|
|
9
|
+
`);if(I8(B$(Z$,".gitignore"),$),!f$(B$(Z$,".git"))){let Z=await K4(["git","init","-b",pZ],Z$);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await K4(["git","config","user.email","vault@smolerclaw.local"],Z$),await K4(["git","config","user.name","smolerclaw-vault"],Z$)}return T4=!0,"Shadow backup inicializado."}async function n4($){if(!T4)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let V of Z0){let G=B$(h$,V);if(!f$(G))continue;let H=B$(Z$,V),z=hZ(H);if(!f$(z))J5(z,{recursive:!0});I8(H,$0(G,"utf-8"))}let J=B$(uZ,"config.json");if(f$(J))I8(B$(Z$,"config.json"),$0(J,"utf-8"));if(await K4(["git","add","-A"],Z$),!(await K4(["git","status","--porcelain"],Z$)).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 H$.emit("task:completed",V),"Nenhuma mudanca para backup."}let Q=$||`backup ${new Date().toISOString().slice(0,19)}`,X=await K4(["git","commit","-m",Q],Z$);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 H$.emit("task:completed",V),`Backup commit falhou: ${X.stderr}`}Y5=new Date().toISOString();let K={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:`Backup concluido: ${Q}`,duration:Date.now()-Z,timestamp:Date.now()};return H$.emit("task:completed",K),`Backup concluido: ${Q}`}catch(J){let Y=J instanceof Error?J.message:String(J),Q={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Backup falhou: ${Y}`,duration:Date.now()-Z,timestamp:Date.now()};return H$.emit("task:completed",Q),`Backup falhou: ${Y}`}}async function X0(){if(!T4)return"Backup nao ativado.";if(!(await K4(["git","remote","-v"],Z$)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await K4(["git","push","-u","origin",pZ],Z$);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function IQ(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:Z$,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function K4($,Z){let J=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Y,Q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),X=await J.exited;return{stdout:Y.trim(),stderr:Q.trim(),ok:X===0}}function oZ($=30){if(X5(),!T4)return;e1=setInterval(()=>{n4("auto-backup").catch(()=>{})},$*60*1000)}function X5(){if(e1)clearInterval(e1),e1=null}var mZ=1,cZ="vault-checksums.json",pZ="smolerclaw-backup",Z0,h$="",uZ="",X4,Z$="",T4=!1,Y5=null,Q5=!1,e1=null;var r=r4(()=>{A8();Z0=["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"],X4=[]});var t2={};FZ(t2,{openUrl:()=>y4,openFile:()=>F1,openApp:()=>b4,getSystemInfo:()=>_4,getRunningApps:()=>R1,getOutlookEvents:()=>b$,getKnownApps:()=>l5,getDateTimeInfo:()=>v4});function d5($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(IX.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function b4($,Z){let J=$.toLowerCase().replace(/\s+/g,""),Y=u5[J];if(!Y){let Q=Object.keys(u5).join(", ");return`Unknown app: "${$}". Available: ${Q}`}if(Z){let Q=d5(Z,"argument");if(Q)return Q}if(!I)return"Error: this command is only available on Windows.";if(!Y.includes(":")){let Q=await i1(Y);if(!Q.exists)return`Error: ${Y} not found. ${Q.error||""}`}try{let Q=await e7(Y,Z);if(Q.exitCode!==0&&Q.stderr.trim())return`Error opening ${$}: ${Q.stderr.trim()}`;if(Q.timedOut)return`Error opening ${$}: timeout (application may have opened but response was delayed)`;return`Opened: ${$}`}catch(Q){return`Error opening ${$}: ${Q instanceof Error?Q.message:String(Q)}`}}async function y4($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=d5($,"URL");if(Z)return Z;if(!I)return"Error: this command is only available on Windows.";try{let J=await e7($);if(J.exitCode!==0&&J.stderr.trim())return`Error: ${J.stderr.trim()}`;if(J.timedOut)return"Error: timeout opening URL (browser may have opened but response was delayed)";return`Opened in browser: ${$}`}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}async function F1($){let Z=d5($,"file path");if(Z)return Z;if(!I)return"Error: this command is only available on Windows.";try{let J=await SZ($);if(J.exitCode!==0&&J.stderr.trim())return`Error: ${J.stderr.trim()}`;if(J.timedOut)return"Error: timeout opening file (application may have opened but response was delayed)";return`Opened: ${$}`}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}async function R1(){if(!I)return"Error: this command is only available on Windows.";try{let $=await wZ(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 _4(){if(!I)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 G$($.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 v4(){let $=new Date,Z=[],J=$.toLocaleDateString("pt-BR",{weekday:"long"}),Y=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),Q=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${J}, ${Y} \u2014 ${Q}`);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 b$(){if(!I)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 G$($,{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 l5(){return Object.keys(u5)}var IX,u5;var f4=r4(()=>{$$();Y4();IX=/[";`$\n\r|&<>{}()]/;u5={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 H9={};FZ(H9,{searchInvestigations:()=>K9,openInvestigation:()=>$9,listInvestigations:()=>X9,initInvestigations:()=>e5,getInvestigation:()=>Q9,generateReport:()=>z9,formatInvestigationList:()=>e0,formatInvestigationDetail:()=>V9,formatEvidenceDetail:()=>SK,collectEvidence:()=>Z9,closeInvestigation:()=>Y9,addFinding:()=>J9});import{existsSync as S6,mkdirSync as TK,readFileSync as PK}from"fs";import{join as AK}from"path";import{randomUUID as IK}from"crypto";function t0(){x(k6(),JSON.stringify(X$,null,2))}function xK(){let $=k6();if(!S6($)){X$=[];return}try{X$=JSON.parse(PK($,"utf-8"))}catch{X$=[]}}function e5($){if(w6=$,!S6($))TK($,{recursive:!0});xK()}function $9($,Z,J,Y=[]){let Q=new Date().toISOString(),X={id:G9(),title:$.trim(),type:Z,status:"aberta",hypothesis:J?.trim(),tags:Y.map((K)=>K.toLowerCase()),evidence:[],findings:[],created:Q,updated:Q};return X$=[...X$,X],t0(),X}function Z9($,Z,J,Y,Q){let X=P1($);if(!X)return null;let K=Y.trim();if(K.length>x6)K=K.slice(0,x6)+`
|
|
12
|
+
...(truncated, ${Y.length} total chars)`;let V={id:G9(),source:Z,label:J.trim(),content:K,path:Q?.trim(),timestamp:new Date().toISOString()},G={...X,evidence:[...X.evidence,V],status:X.status==="aberta"?"em_andamento":X.status,updated:new Date().toISOString()};return X$=X$.map((H)=>H.id===X.id?G:H),t0(),V}function J9($,Z,J,Y,Q=[]){let X=P1($);if(!X)return null;let K=Q.filter((H)=>X.evidence.some((z)=>z.id===H)),V={id:G9(),severity:Z,title:J.trim(),description:Y.trim(),evidence_ids:K,timestamp:new Date().toISOString()},G={...X,findings:[...X.findings,V],updated:new Date().toISOString()};return X$=X$.map((H)=>H.id===X.id?G:H),t0(),V}function Y9($,Z,J){let Y=P1($);if(!Y)return null;let Q={...Y,status:"concluida",summary:Z.trim(),recommendations:J?.trim(),updated:new Date().toISOString()};return X$=X$.map((X)=>X.id===Y.id?Q:X),t0(),Q}function Q9($){return P1($)}function X9($,Z,J=20){let Y=[...X$];if($)Y=Y.filter((Q)=>Q.status===$);if(Z)Y=Y.filter((Q)=>Q.type===Z);return Y.sort((Q,X)=>new Date(X.updated).getTime()-new Date(Q.updated).getTime()).slice(0,J)}function K9($){let Z=$.toLowerCase();return X$.filter((J)=>J.title.toLowerCase().includes(Z)||J.hypothesis?.toLowerCase().includes(Z)||J.tags.some((Y)=>Y.includes(Z))||J.findings.some((Y)=>Y.title.toLowerCase().includes(Z))||J.summary?.toLowerCase().includes(Z)).sort((J,Y)=>new Date(Y.updated).getTime()-new Date(J.updated).getTime())}function z9($){let Z=P1($);if(!Z)return null;let J=[],Y=(K)=>new Date(K).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),Q={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(J.push(`# Investigacao: ${Z.title}`),J.push(""),J.push(`**Tipo:** ${Q[Z.type]}`),J.push(`**Status:** ${Z.status}`),J.push(`**Abertura:** ${Y(Z.created)}`),J.push(`**Ultima atualizacao:** ${Y(Z.updated)}`),Z.tags.length)J.push(`**Tags:** ${Z.tags.join(", ")}`);if(J.push(`**ID:** ${Z.id}`),Z.hypothesis)J.push(""),J.push("## Hipotese"),J.push(Z.hypothesis);if(Z.evidence.length>0){J.push(""),J.push(`## Evidencias (${Z.evidence.length})`);for(let K of Z.evidence){let V=Y(K.timestamp);J.push(""),J.push(`### [${K.id}] ${K.label}`),J.push(`- Fonte: ${K.source}${K.path?` (${K.path})`:""}`),J.push(`- Coletada: ${V}`);let G=K.content.length>2000?K.content.slice(0,2000)+`
|
|
13
|
+
... (truncado)`:K.content;J.push("```"),J.push(G),J.push("```")}}if(Z.findings.length>0){let K=[...Z.findings].sort((V,G)=>(X[V.severity]??4)-(X[G.severity]??4));J.push(""),J.push(`## Conclusoes (${Z.findings.length})`);for(let V of K){let G=y6(V.severity);if(J.push(""),J.push(`### ${G} ${V.title}`),J.push(V.description),V.evidence_ids.length>0)J.push(`- Evidencias: ${V.evidence_ids.join(", ")}`)}}if(Z.summary)J.push(""),J.push("## Resumo"),J.push(Z.summary);if(Z.recommendations)J.push(""),J.push("## Recomendacoes"),J.push(Z.recommendations);return J.join(`
|
|
14
|
+
`)}function e0($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((J)=>{let Y=new Date(J.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=b6(J.status),X=J.evidence.length,K=J.findings.length,V=J.tags.length>0?` [${J.tags.join(", ")}]`:"";return` ${Q} [${Y}] ${J.title} (${J.type}) \u2014 ${X} ev, ${K} concl${V} {${J.id}}`});return`Investigacoes (${$.length}):
|
|
15
15
|
${Z.join(`
|
|
16
|
-
`)}`}function
|
|
16
|
+
`)}`}function V9($){let Z=(Q)=>new Date(Q).toLocaleDateString("pt-BR"),J=b6($.status),Y=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${J}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)Y.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)Y.push(`Tags: ${$.tags.join(", ")}`);Y.push(`
|
|
17
17
|
Evidencias: ${$.evidence.length}`);for(let Q of $.evidence.slice(-5)){let X=Q.content.slice(0,80).replace(/\n/g," ");Y.push(` [${Q.id}] ${Q.source}: ${Q.label} \u2014 "${X}..."`)}if($.evidence.length>5)Y.push(` ... (${$.evidence.length-5} mais)`);Y.push(`
|
|
18
|
-
Conclusoes: ${$.findings.length}`);for(let Q of $.findings)Y.push(` ${
|
|
18
|
+
Conclusoes: ${$.findings.length}`);for(let Q of $.findings)Y.push(` ${y6(Q.severity)} ${Q.title}`);if($.summary)Y.push(`
|
|
19
19
|
Resumo: ${$.summary}`);if($.recommendations)Y.push(`Recomendacoes: ${$.recommendations}`);return Y.join(`
|
|
20
|
-
`)}function
|
|
20
|
+
`)}function SK($){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 P1($){let Z=$.toLowerCase().trim(),J=X$.find((Q)=>Q.id===Z);if(J)return J;return X$.filter((Q)=>Q.title.toLowerCase().includes(Z)).sort((Q,X)=>new Date(X.updated).getTime()-new Date(Q.updated).getTime())[0]||null}function b6($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function y6($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function G9(){return IK().slice(0,8)}var w6="",X$,k6=()=>AK(w6,"investigations.json"),x6=50000;var A1=r4(()=>{r();X$=[]});import{readFileSync as VQ}from"fs";import{join as GQ,dirname as HQ}from"path";function RZ($){let Z={help:!1,version:!1,noTools:!1,print:!1},J=[],Y=0;while(Y<$.length){let Q=$[Y];switch(Q){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)l1("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Y],!Z.session)l1("--session requires a value");break;case"--max-tokens":let X=Number($[++Y]);if(!X||X<=0)l1("--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(Q.startsWith("-"))l1(`Unknown option: ${Q}. Try --help`);J.push(Q)}Y++}if(J.length>0)Z.prompt=J.join(" ");return Z}function o1(){return"1.3.3"}function EZ(){let $=o1();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 _0($){console.error(`smolerclaw: ${$}`),process.exit(2)}e();a();import{existsSync as s0,mkdirSync as sY,readFileSync as yZ}from"fs";import{homedir as tY}from"os";import{join as h$}from"path";var D8=tY(),t0=I?h$(process.env.APPDATA||h$(D8,"AppData","Roaming"),"smolerclaw"):h$(D8,".config","smolerclaw"),t7=I?h$(process.env.LOCALAPPDATA||h$(D8,"AppData","Local"),"smolerclaw"):h$(D8,".local","share","smolerclaw"),Q4=h$(t0,"config.json"),a4={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:t7,toolApproval:"auto",language:"auto",maxSessionCost:0};function P8($){if(!s0($))sY($,{recursive:!0})}function _Z(){if(P8(t0),P8(t7),P8(h$(t7,"sessions")),I)$Q();if(!s0(Q4))return S(Q4,JSON.stringify(a4,null,2)),{...a4};let $;try{$=JSON.parse(yZ(Q4,"utf-8"))}catch{return S(Q4,JSON.stringify(a4,null,2)),{...a4}}return eY({...a4,...$})}function eY($){let Z={...a4};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 e0($){P8(t0),S(Q4,JSON.stringify($,null,2))}function e7(){return Q4}function $Q(){let $=h$(D8,".config","smolerclaw","config.json");if(s0($)&&!s0(Q4))try{let Z=yZ($,"utf-8");P8(t0),S(Q4,Z)}catch{}}import{existsSync as ZQ,readFileSync as JQ}from"fs";import{homedir as YQ}from"os";import{join as QQ}from"path";var vZ=QQ(YQ(),".claude",".credentials.json");function $5(){let $=XQ();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 XQ(){if(!ZQ(vZ))return null;try{let Z=JSON.parse(JQ(vZ,"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 Z5(){try{return $5()}catch{return null}}function fZ($){return`sub:${$.subscriptionType||"pro"}`}function L($,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 J5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return J5=$.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 g$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var T8=($)=>{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 D extends Error{}class n extends D{constructor($,Z,J,Y){super(`${n.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 R4({message:J,cause:T8(Z)});let Q=Z;if($===400)return new A8($,Q,J,Y);if($===401)return new x8($,Q,J,Y);if($===403)return new S8($,Q,J,Y);if($===404)return new w8($,Q,J,Y);if($===409)return new k8($,Q,J,Y);if($===422)return new b8($,Q,J,Y);if($===429)return new y8($,Q,J,Y);if($>=500)return new _8($,Q,J,Y);return new n($,Q,J,Y)}}class Y$ extends n{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class R4 extends n{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class I8 extends R4{constructor({message:$}={}){super({message:$??"Request timed out."})}}class A8 extends n{}class x8 extends n{}class S8 extends n{}class w8 extends n{}class k8 extends n{}class b8 extends n{}class y8 extends n{}class _8 extends n{}var zQ=/^[a-z][a-z0-9+.-]*:/i,hZ=($)=>{return zQ.test($)},Y5=($)=>(Y5=Array.isArray,Y5($)),Q5=Y5;function $1($){if(typeof $!=="object")return{};return $??{}}function X5($){if(!$)return!0;for(let Z in $)return!1;return!0}function gZ($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var mZ=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new D(`${$} must be an integer`);if(Z<0)throw new D(`${$} must be a positive integer`);return Z};var Z1=($)=>{try{return JSON.parse($)}catch(Z){return}};var pZ=($)=>new Promise((Z)=>setTimeout(Z,$));var X4="0.80.0";var lZ=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function VQ(){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 GQ=()=>{let $=VQ();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":X4,"X-Stainless-OS":uZ(Deno.build.os),"X-Stainless-Arch":cZ(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":X4,"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":X4,"X-Stainless-OS":uZ(globalThis.process.platform??"unknown"),"X-Stainless-Arch":cZ(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=HQ();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":X4,"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":X4,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function HQ(){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 cZ=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},uZ=($)=>{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"},dZ,oZ=()=>{return dZ??(dZ=GQ())};function aZ(){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 K5(...$){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 J1($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return K5({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 v8($){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 nZ($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),J=Z.cancel();Z.releaseLock(),await J}var rZ=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function iZ($){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 D(`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 eZ($){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 sZ;function f8($){let Z;return(sZ??(Z=new globalThis.TextEncoder,sZ=Z.encode.bind(Z)))($)}var tZ;function z5($){let Z;return(tZ??(Z=new globalThis.TextDecoder,tZ=Z.decode.bind(Z)))($)}var B$,N$;class K4{constructor(){B$.set(this,void 0),N$.set(this,void 0),L(this,B$,new Uint8Array,"f"),L(this,N$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?f8($):$;L(this,B$,eZ([C(this,B$,"f"),Z]),"f");let J=[],Y;while((Y=UQ(C(this,B$,"f"),C(this,N$,"f")))!=null){if(Y.carriage&&C(this,N$,"f")==null){L(this,N$,Y.index,"f");continue}if(C(this,N$,"f")!=null&&(Y.index!==C(this,N$,"f")+1||Y.carriage)){J.push(z5(C(this,B$,"f").subarray(0,C(this,N$,"f")-1))),L(this,B$,C(this,B$,"f").subarray(C(this,N$,"f")),"f"),L(this,N$,null,"f");continue}let Q=C(this,N$,"f")!==null?Y.preceding-1:Y.preceding,X=z5(C(this,B$,"f").subarray(0,Q));J.push(X),L(this,B$,C(this,B$,"f").subarray(Y.index),"f"),L(this,N$,null,"f")}return J}flush(){if(!C(this,B$,"f").length)return[];return this.decode(`
|
|
51
|
-
`)}}
|
|
52
|
-
`,"\r"]);
|
|
53
|
-
`);J.enqueue(X)}catch(Y){J.error(Y)}},async cancel(){await Z.return?.()}})}}async function*
|
|
54
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Q}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,J,Y]=
|
|
55
|
-
${X.map((
|
|
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
|
+
`)}}N$=new WeakMap,M$=new WeakMap;G4.NEWLINE_CHARS=new Set([`
|
|
52
|
+
`,"\r"]);G4.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function lQ($,Z){for(let Q=Z??0;Q<$.length;Q++){if($[Q]===10)return{preceding:Q,index:Q+1,carriage:!1};if($[Q]===13)return{preceding:Q,index:Q+1,carriage:!0}}return null}function U2($){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 U0={off:0,error:200,warn:300,info:400,debug:500},M5=($,Z,J)=>{if(!$)return;if(tZ(U0,$))return $;t(J).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(U0))}`);return};function d8(){}function W0($,Z,J){if(!Z||U0[$]>U0[J])return d8;else return Z[$].bind(Z)}var oQ={error:d8,warn:d8,info:d8,debug:d8},B2=new WeakMap;function t($){let Z=$.logger,J=$.logLevel??"off";if(!Z)return oQ;let Y=B2.get(Z);if(Y&&Y[0]===J)return Y[1];let Q={error:W0("error",Z,J),warn:W0("warn",Z,J),info:W0("info",Z,J),debug:W0("debug",Z,J)};return B2.set(Z,[J,Q]),Q}var c$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,J])=>[Z,Z.toLowerCase()==="x-api-key"||Z.toLowerCase()==="authorization"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":J]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var l8;class C${constructor($,Z,J){this.iterator=$,l8.set(this,void 0),this.controller=Z,D(this,l8,J,"f")}static fromSSEResponse($,Z,J){let Y=!1,Q=J?t(J):console;async function*X(){if(Y)throw new P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let K=!1;try{for await(let V of aQ($,Z)){if(V.event==="completion")try{yield JSON.parse(V.data)}catch(G){throw Q.error("Could not parse message into JSON:",V.data),Q.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 Q.error("Could not parse message into JSON:",V.data),Q.error("From chunk:",V.raw),G}if(V.event==="ping")continue;if(V.event==="error")throw new i(void 0,H0(V.data)??V.data,void 0,$.headers)}K=!0}catch(V){if(m$(V))return;throw V}finally{if(!K)Z.abort()}}return new C$(X,Z,J)}static fromReadableStream($,Z,J){let Y=!1;async function*Q(){let K=new G4,V=p8($);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 P("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let K=!1;try{for await(let V of Q()){if(K)continue;if(V)yield JSON.parse(V)}K=!0}catch(V){if(m$(V))return;throw V}finally{if(!K)Z.abort()}}return new C$(X,Z,J)}[(l8=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],J=this.iterator(),Y=(Q)=>{return{next:()=>{if(Q.length===0){let X=J.next();$.push(X),Z.push(X)}return Q.shift()}}};return[new C$(()=>Y($),this.controller,C(this,l8,"f")),new C$(()=>Y(Z),this.controller,C(this,l8,"f"))]}toReadableStream(){let $=this,Z;return B5({async start(){Z=$[Symbol.asyncIterator]()},async pull(J){try{let{value:Y,done:Q}=await Z.next();if(Q)return J.close();let X=u8(JSON.stringify(Y)+`
|
|
53
|
+
`);J.enqueue(X)}catch(Y){J.error(Y)}},async cancel(){await Z.return?.()}})}}async function*aQ($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new P("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new P("Attempted to iterate over a response with no body")}let J=new N2,Y=new G4,Q=p8($.body);for await(let X of rQ(Q))for(let K of Y.decode(X)){let V=J.decode(K);if(V)yield V}for(let X of Y.flush()){let K=J.decode(X);if(K)yield K}}async function*rQ($){let Z=new Uint8Array;for await(let J of $){if(J==null)continue;let Y=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?u8(J):J,Q=new Uint8Array(Z.length+Y.length);Q.set(Z),Q.set(Y,Z.length),Z=Q;let X;while((X=U2(Z))!==-1)yield Z.slice(0,X),Z=Z.slice(X)}if(Z.length>0)yield Z}class N2{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 Q={event:this.event,data:this.data.join(`
|
|
54
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Q}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,J,Y]=iQ($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function iQ($,Z){let J=$.indexOf(Z);if(J!==-1)return[$.substring(0,J),Z,$.substring(J+Z.length)];return[$,"",""]}async function B0($,Z){let{response:J,requestLogID:Y,retryOfRequestLogID:Q,startTime:X}=Z,K=await(async()=>{if(Z.options.stream){if(t($).debug("response",J.status,J.url,J.headers,J.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(J,Z.controller);return C$.fromSSEResponse(J,Z.controller)}if(J.status===204)return null;if(Z.options.__binaryResponse)return J;let G=J.headers.get("content-type")?.split(";")[0]?.trim();if(G?.includes("application/json")||G?.endsWith("+json")){if(J.headers.get("content-length")==="0")return;let B=await J.json();return C5(B,J)}return await J.text()})();return t($).debug(`[${Y}] response parsed`,c$({retryOfRequestLogID:Q,url:J.url,status:J.status,body:K,durationMs:Date.now()-X})),K}function C5($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var o8;class A4 extends Promise{constructor($,Z,J=B0){super((Y)=>{Y(null)});this.responsePromise=Z,this.parseResponse=J,o8.set(this,void 0),D(this,o8,$,"f")}_thenUnwrap($){return new A4(C(this,o8,"f"),this.responsePromise,async(Z,J)=>C5($(await this.parseResponse(Z,J),J),J.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(C(this,o8,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}o8=new WeakMap;var N0;class j5{constructor($,Z,J,Y){N0.set(this,void 0),D(this,N0,$,"f"),this.options=Y,this.response=Z,this.body=J}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new P("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,N0,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(N0=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class M0 extends A4{constructor($,Z,J){super($,Z,async(Y,Q)=>new J(Y,Q.response,await B0(Y,Q),Q.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class I$ extends j5{constructor($,Z,J,Y){super($,Z,J,Y);this.data=J.data||[],this.has_more=J.has_more||!1,this.first_id=J.first_id||null,this.last_id=J.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:{...G0(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...G0(this.options.query),after_id:$}}}}class a8 extends j5{constructor($,Z,J,Y){super($,Z,J,Y);this.data=J.data||[],this.has_more=J.has_more||!1,this.next_page=J.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:{...G0(this.options.query),page:$}}}}var F5=()=>{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 I4($,Z,J){return F5(),new File($,Z??"unknown_file",J)}function r8($,Z){let J=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?J.split(/[\\/]/).pop()||void 0:J}var R5=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var t4=async($,Z,J=!0)=>{return{...$,body:await tQ($.body,Z,J)}},M2=new WeakMap;function sQ($){let Z=typeof $==="function"?$:$.fetch,J=M2.get(Z);if(J)return J;let Y=(async()=>{try{let Q="Response"in Z?Z.Response:(await Z("data:,")).constructor,X=new FormData;if(X.toString()===await new Q(X).text())return!1;return!0}catch{return!0}})();return M2.set(Z,Y),Y}var tQ=async($,Z,J=!0)=>{if(!await sQ(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(([Q,X])=>O5(Y,Q,X,J))),Y},eQ=($)=>$ instanceof Blob&&("name"in $);var O5=async($,Z,J,Y)=>{if(J===void 0)return;if(J==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof J==="string"||typeof J==="number"||typeof J==="boolean")$.append(Z,String(J));else if(J instanceof Response){let Q={},X=J.headers.get("Content-Type");if(X)Q={type:X};$.append(Z,I4([await J.blob()],r8(J,Y),Q))}else if(R5(J))$.append(Z,I4([await new Response(q0(J)).blob()],r8(J,Y)));else if(eQ(J))$.append(Z,I4([J],r8(J,Y),{type:J.type}));else if(Array.isArray(J))await Promise.all(J.map((Q)=>O5($,Z+"[]",Q,Y)));else if(typeof J==="object")await Promise.all(Object.entries(J).map(([Q,X])=>O5($,`${Z}[${Q}]`,X,Y)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${J} instead`)};var C2=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",$X=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&C2($),ZX=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function C0($,Z,J){if(F5(),$=await $,Z||(Z=r8($,!0)),$X($)){if($ instanceof File&&Z==null&&J==null)return $;return I4([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...J})}if(ZX($)){let Q=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),I4(await E5(Q),Z,J)}let Y=await E5($);if(!J?.type){let Q=Y.find((X)=>typeof X==="object"&&("type"in X)&&X.type);if(typeof Q==="string")J={...J,type:Q}}return I4(Y,Z,J)}async function E5($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(C2($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(R5($))for await(let J of $)Z.push(...await E5(J));else{let J=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${J?`; constructor: ${J}`:""}${JX($)}`)}return Z}function JX($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((J)=>`"${J}"`).join(", ")}]`}class p{constructor($){this._client=$}}var j2=Symbol.for("brand.privateNullableHeaders");function*QX($){if(!$)return;if(j2 in $){let{values:Y,nulls:Q}=$;yield*Y.entries();for(let X of Q)yield[X,null];return}let Z=!1,J;if($ instanceof Headers)J=$.entries();else if(W5($))J=$;else Z=!0,J=Object.entries($??{});for(let Y of J){let Q=Y[0];if(typeof Q!=="string")throw TypeError("expected header name to be a string");let X=W5(Y[1])?Y[1]:[Y[1]],K=!1;for(let V of X){if(V===void 0)continue;if(Z&&!K)K=!0,yield[Q,null];yield[Q,V]}}}var S=($)=>{let Z=new Headers,J=new Set;for(let Y of $){let Q=new Set;for(let[X,K]of QX(Y)){let V=X.toLowerCase();if(!Q.has(V))Z.delete(X),Q.add(V);if(K===null)Z.delete(X),J.add(V);else Z.append(X,K),J.delete(V)}}return{[j2]:!0,values:Z,nulls:J}};var i8=Symbol("anthropic.sdk.stainlessHelper");function j0($){return typeof $==="object"&&$!==null&&i8 in $}function L5($,Z){let J=new Set;if($){for(let Y of $)if(j0(Y))J.add(Y[i8])}if(Z)for(let Y of Z){if(j0(Y))J.add(Y[i8]);if(Array.isArray(Y.content)){for(let Q of Y.content)if(j0(Q))J.add(Q[i8])}}return Array.from(J)}function O0($,Z){let J=L5($,Z);if(J.length===0)return{};return{"x-stainless-helper":J.join(", ")}}function O2($){if(j0($))return{"x-stainless-helper":$[i8]};return{}}function R2($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var F2=Object.freeze(Object.create(null)),XX=($=R2)=>function(J,...Y){if(J.length===1)return J[0];let Q=!1,X=[],K=J.reduce((z,U,B)=>{if(/[?#]/.test(U))Q=!0;let M=Y[B],O=(Q?encodeURIComponent:$)(""+M);if(B!==Y.length&&(M==null||typeof M==="object"&&M.toString===Object.getPrototypeOf(Object.getPrototypeOf(M.hasOwnProperty??F2)??F2)?.toString))O=M+"",X.push({start:z.length+U.length,length:O.length,error:`Value of type ${Object.prototype.toString.call(M).slice(8,-1)} is not a valid path parameter`});return z+U+(B===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,U)=>z.start-U.start),X.length>0){let z=0,U=X.reduce((B,M)=>{let O=" ".repeat(M.start-z),L="^".repeat(M.length);return z=M.start+M.length,B+O+L},"");throw new P(`Path parameters result in path with invalid segments:
|
|
55
|
+
${X.map((B)=>B.error).join(`
|
|
56
56
|
`)}
|
|
57
57
|
${K}
|
|
58
|
-
${B}`)}return K},g=IQ(V2);class d8 extends m{list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/files",I$,{query:Y,...Z,headers:A([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(g`/v1/files/${$}`,{...J,headers:A([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},J?.headers])})}download($,Z={},J){let{betas:Y}=Z??{};return this._client.get(g`/v1/files/${$}/content`,{...J,headers:A([{"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(g`/v1/files/${$}`,{...J,headers:A([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},J?.headers])})}upload($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/files",n4({body:Y,...Z,headers:A([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},K2(Y.file),Z?.headers])},this._client))}}class l8 extends m{retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(g`/v1/models/${$}?beta=true`,{...J,headers:A([{...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:A([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers])})}}var q1={"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 G2($){return $?.output_format??$?.output_config?.format}function M5($,Z,J){let Y=G2(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 C5($,Z,J)}function C5($,Z,J){let Y=null,Q=$.content.map((X)=>{if(X.type==="text"){let K=SQ(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 SQ($,Z){let J=G2($);if(J?.type!=="json_schema")return null;try{if("parse"in J)return J.parse(Z);return JSON.parse(Z)}catch(Y){throw new D(`Failed to parse structured output: ${Y}`)}}var wQ=($)=>{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},r4=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),r4($);break;case"number":let J=Z.value[Z.value.length-1];if(J==="."||J==="-")return $=$.slice(0,$.length-1),r4($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),r4($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),r4($);break;case"delimiter":return $=$.slice(0,$.length-1),r4($);break}return $},kQ=($)=>{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 $},bQ=($)=>{let Z="";return $.map((J)=>{switch(J.type){case"string":Z+='"'+J.value+'"';break;default:Z+=J.value;break}}),Z},W1=($)=>JSON.parse(bQ(kQ(r4(wQ($)))));var R$,z4,i4,o8,U1,a8,n8,B1,r8,p$,i8,N1,M1,D4,C1,j1,s8,j5,H2,O1,O5,F5,E5,q2,W2="__json_buf";function U2($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class t8{constructor($,Z){R$.add(this),this.messages=[],this.receivedMessages=[],z4.set(this,void 0),i4.set(this,null),this.controller=new AbortController,o8.set(this,void 0),U1.set(this,()=>{}),a8.set(this,()=>{}),n8.set(this,void 0),B1.set(this,()=>{}),r8.set(this,()=>{}),p$.set(this,{}),i8.set(this,!1),N1.set(this,!1),M1.set(this,!1),D4.set(this,!1),C1.set(this,void 0),j1.set(this,void 0),s8.set(this,void 0),O1.set(this,(J)=>{if(L(this,N1,!0,"f"),g$(J))J=new Y$;if(J instanceof Y$)return L(this,M1,!0,"f"),this._emit("abort",J);if(J instanceof D)return this._emit("error",J);if(J instanceof Error){let Y=new D(J.message);return Y.cause=J,this._emit("error",Y)}return this._emit("error",new D(String(J)))}),L(this,o8,new Promise((J,Y)=>{L(this,U1,J,"f"),L(this,a8,Y,"f")}),"f"),L(this,n8,new Promise((J,Y)=>{L(this,B1,J,"f"),L(this,r8,Y,"f")}),"f"),C(this,o8,"f").catch(()=>{}),C(this,n8,"f").catch(()=>{}),L(this,i4,$,"f"),L(this,s8,Z?.logger??console,"f")}get response(){return C(this,C1,"f")}get request_id(){return C(this,j1,"f")}async withResponse(){L(this,D4,!0,"f");let $=await C(this,o8,"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 t8(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,J,{logger:Y}={}){let Q=new t8(Z,{logger:Y});for(let X of Z.messages)Q._addMessageParam(X);return L(Q,i4,{...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,O1,"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,R$,"m",O5).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,R$,"m",F5).call(this,V);if(K.controller.signal?.aborted)throw new Y$;C(this,R$,"m",E5).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,C1,$,"f"),L(this,j1,$?.headers.get("request-id"),"f"),C(this,U1,"f").call(this,$),this._emit("connect")}get ended(){return C(this,i8,"f")}get errored(){return C(this,N1,"f")}get aborted(){return C(this,M1,"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(L(this,D4,!0,"f"),$!=="error")this.once("error",J);this.once($,Z)})}async done(){L(this,D4,!0,"f"),await C(this,n8,"f")}get currentMessage(){return C(this,z4,"f")}async finalMessage(){return await this.done(),C(this,R$,"m",j5).call(this)}async finalText(){return await this.done(),C(this,R$,"m",H2).call(this)}_emit($,...Z){if(C(this,i8,"f"))return;if($==="end")L(this,i8,!0,"f"),C(this,B1,"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,D4,"f")&&!J?.length)Promise.reject(Y);C(this,a8,"f").call(this,Y),C(this,r8,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!C(this,D4,"f")&&!J?.length)Promise.reject(Y);C(this,a8,"f").call(this,Y),C(this,r8,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,R$,"m",j5).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,R$,"m",O5).call(this),this._connected(null);let Q=M$.fromReadableStream($,this.controller);for await(let X of Q)C(this,R$,"m",F5).call(this,X);if(Q.controller.signal?.aborted)throw new Y$;C(this,R$,"m",E5).call(this)}finally{if(J&&Y)J.removeEventListener("abort",Y)}}[(z4=new WeakMap,i4=new WeakMap,o8=new WeakMap,U1=new WeakMap,a8=new WeakMap,n8=new WeakMap,B1=new WeakMap,r8=new WeakMap,p$=new WeakMap,i8=new WeakMap,N1=new WeakMap,M1=new WeakMap,D4=new WeakMap,C1=new WeakMap,j1=new WeakMap,s8=new WeakMap,O1=new WeakMap,R$=new WeakSet,j5=function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},H2=function(){if(this.receivedMessages.length===0)throw new D("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 D("stream ended without producing a content block with type=text");return Z.join(" ")},O5=function(){if(this.ended)return;L(this,z4,void 0,"f")},F5=function(Z){if(this.ended)return;let J=C(this,R$,"m",q2).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(U2(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:B2(Z.delta)}break}case"message_stop":{this._addMessageParam(J),this._addMessage(M5(J,C(this,i4,"f"),{logger:C(this,s8,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",J.content.at(-1));break}case"message_start":{L(this,z4,J,"f");break}case"content_block_start":case"message_delta":break}},E5=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");let Z=C(this,z4,"f");if(!Z)throw new D("request ended without sending any chunks");return L(this,z4,void 0,"f"),M5(Z,C(this,i4,"f"),{logger:C(this,s8,"f")})},q2=function(Z){let J=C(this,z4,"f");if(Z.type==="message_start"){if(J)throw new D(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!J)throw new D(`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&&U2(Y)){let Q=Y[W2]||"";Q+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,W2,{value:Q,enumerable:!1,writable:!0}),Q)try{X.input=W1(Q)}catch(K){let V=new D(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${K}. JSON: ${Q}`);C(this,O1,"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:B2(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 M$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function B2($){}class s4 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 N2=1e5,M2=`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
|
+
${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:
|
|
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,89 @@ 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 vQ&&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=q1[Q.model]??void 0;X=this._client.calculateNonstreamingTimeout(Q.max_tokens,V)}let K=H1(Q.tools,Q.messages);return this._client.post("/v1/messages?beta=true",{body:Q,timeout:X??600000,...Z,headers:A([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},K,Z?.headers]),stream:J.stream??!1})}parse($,Z){return Z={...Z,headers:A([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((J)=>C5(J,$,{logger:this._client.logger??console}))}stream($,Z){return t8.createMessage(this,$,Z)}countTokens($,Z){let J=F2($),{betas:Y,...Q}=J;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...Z,headers:A([{"anthropic-beta":[...Y??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new J0(this._client,$,Z)}}function F2($){if(!$.output_format)return $;if($.output_config?.format)throw new D("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}}}G4.Batches=Y0;G4.BetaToolRunner=J0;G4.ToolError=s4;class Q0 extends m{create($,Z={},J){let{betas:Y,...Q}=Z??{};return this._client.post(g`/v1/skills/${$}/versions?beta=true`,n4({body:Q,...J,headers:A([{"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(g`/v1/skills/${Y}/versions/${$}?beta=true`,{...J,headers:A([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},J?.headers])})}list($,Z={},J){let{betas:Y,...Q}=Z??{};return this._client.getAPIList(g`/v1/skills/${$}/versions?beta=true`,p8,{query:Q,...J,headers:A([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}delete($,Z,J){let{skill_id:Y,betas:Q}=Z;return this._client.delete(g`/v1/skills/${Y}/versions/${$}?beta=true`,{...J,headers:A([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},J?.headers])})}}class $8 extends m{constructor(){super(...arguments);this.versions=new Q0(this._client)}create($={},Z){let{betas:J,...Y}=$??{};return this._client.post("/v1/skills?beta=true",n4({body:Y,...Z,headers:A([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(g`/v1/skills/${$}?beta=true`,{...J,headers:A([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/skills?beta=true",p8,{query:Y,...Z,headers:A([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(g`/v1/skills/${$}?beta=true`,{...J,headers:A([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}}$8.Versions=Q0;class S$ extends m{constructor(){super(...arguments);this.models=new l8(this._client),this.messages=new G4(this._client),this.files=new d8(this._client),this.skills=new $8(this._client)}}S$.Models=l8;S$.Messages=G4;S$.Files=d8;S$.Skills=$8;class Z8 extends m{create($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/complete",{body:Y,timeout:this._client._options.timeout??600000,...Z,headers:A([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function E2($){return $?.output_config?.format}function L5($,Z,J){let Y=E2(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 P5($,Z,J)}function P5($,Z,J){let Y=null,Q=$.content.map((X)=>{if(X.type==="text"){let K=mQ(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 mQ($,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 D(`Failed to parse structured output: ${Y}`)}}var L$,H4,J8,X0,F1,K0,z0,E1,V0,u$,G0,R1,L1,I4,P1,D1,H0,D5,R2,T5,I5,A5,x5,L2,P2="__json_buf";function D2($){return $.type==="tool_use"||$.type==="server_tool_use"}class q0{constructor($,Z){L$.add(this),this.messages=[],this.receivedMessages=[],H4.set(this,void 0),J8.set(this,null),this.controller=new AbortController,X0.set(this,void 0),F1.set(this,()=>{}),K0.set(this,()=>{}),z0.set(this,void 0),E1.set(this,()=>{}),V0.set(this,()=>{}),u$.set(this,{}),G0.set(this,!1),R1.set(this,!1),L1.set(this,!1),I4.set(this,!1),P1.set(this,void 0),D1.set(this,void 0),H0.set(this,void 0),T5.set(this,(J)=>{if(L(this,R1,!0,"f"),g$(J))J=new Y$;if(J instanceof Y$)return L(this,L1,!0,"f"),this._emit("abort",J);if(J instanceof D)return this._emit("error",J);if(J instanceof Error){let Y=new D(J.message);return Y.cause=J,this._emit("error",Y)}return this._emit("error",new D(String(J)))}),L(this,X0,new Promise((J,Y)=>{L(this,F1,J,"f"),L(this,K0,Y,"f")}),"f"),L(this,z0,new Promise((J,Y)=>{L(this,E1,J,"f"),L(this,V0,Y,"f")}),"f"),C(this,X0,"f").catch(()=>{}),C(this,z0,"f").catch(()=>{}),L(this,J8,$,"f"),L(this,H0,Z?.logger??console,"f")}get response(){return C(this,P1,"f")}get request_id(){return C(this,D1,"f")}async withResponse(){L(this,I4,!0,"f");let $=await C(this,X0,"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 q0(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,J,{logger:Y}={}){let Q=new q0(Z,{logger:Y});for(let X of Z.messages)Q._addMessageParam(X);return L(Q,J8,{...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,T5,"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",I5).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",A5).call(this,V);if(K.controller.signal?.aborted)throw new Y$;C(this,L$,"m",x5).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,P1,$,"f"),L(this,D1,$?.headers.get("request-id"),"f"),C(this,F1,"f").call(this,$),this._emit("connect")}get ended(){return C(this,G0,"f")}get errored(){return C(this,R1,"f")}get aborted(){return C(this,L1,"f")}abort(){this.controller.abort()}on($,Z){return(C(this,u$,"f")[$]||(C(this,u$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let J=C(this,u$,"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,u$,"f")[$]||(C(this,u$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,J)=>{if(L(this,I4,!0,"f"),$!=="error")this.once("error",J);this.once($,Z)})}async done(){L(this,I4,!0,"f"),await C(this,z0,"f")}get currentMessage(){return C(this,H4,"f")}async finalMessage(){return await this.done(),C(this,L$,"m",D5).call(this)}async finalText(){return await this.done(),C(this,L$,"m",R2).call(this)}_emit($,...Z){if(C(this,G0,"f"))return;if($==="end")L(this,G0,!0,"f"),C(this,E1,"f").call(this);let J=C(this,u$,"f")[$];if(J)C(this,u$,"f")[$]=J.filter((Y)=>!Y.once),J.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!C(this,I4,"f")&&!J?.length)Promise.reject(Y);C(this,K0,"f").call(this,Y),C(this,V0,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!C(this,I4,"f")&&!J?.length)Promise.reject(Y);C(this,K0,"f").call(this,Y),C(this,V0,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,L$,"m",D5).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",I5).call(this),this._connected(null);let Q=M$.fromReadableStream($,this.controller);for await(let X of Q)C(this,L$,"m",A5).call(this,X);if(Q.controller.signal?.aborted)throw new Y$;C(this,L$,"m",x5).call(this)}finally{if(J&&Y)J.removeEventListener("abort",Y)}}[(H4=new WeakMap,J8=new WeakMap,X0=new WeakMap,F1=new WeakMap,K0=new WeakMap,z0=new WeakMap,E1=new WeakMap,V0=new WeakMap,u$=new WeakMap,G0=new WeakMap,R1=new WeakMap,L1=new WeakMap,I4=new WeakMap,P1=new WeakMap,D1=new WeakMap,H0=new WeakMap,T5=new WeakMap,L$=new WeakSet,D5=function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},R2=function(){if(this.receivedMessages.length===0)throw new D("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 D("stream ended without producing a content block with type=text");return Z.join(" ")},I5=function(){if(this.ended)return;L(this,H4,void 0,"f")},A5=function(Z){if(this.ended)return;let J=C(this,L$,"m",L2).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(D2(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:T2(Z.delta)}break}case"message_stop":{this._addMessageParam(J),this._addMessage(L5(J,C(this,J8,"f"),{logger:C(this,H0,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",J.content.at(-1));break}case"message_start":{L(this,H4,J,"f");break}case"content_block_start":case"message_delta":break}},x5=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");let Z=C(this,H4,"f");if(!Z)throw new D("request ended without sending any chunks");return L(this,H4,void 0,"f"),L5(Z,C(this,J8,"f"),{logger:C(this,H0,"f")})},L2=function(Z){let J=C(this,H4,"f");if(Z.type==="message_start"){if(J)throw new D(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!J)throw new D(`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&&D2(Y)){let Q=Y[P2]||"";Q+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,P2,{value:Q,enumerable:!1,writable:!0}),Q)X.input=W1(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:T2(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 M$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function T2($){}class W0 extends m{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(g`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",I$,{query:$,...Z})}delete($,Z){return this._client.delete(g`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(g`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let J=await this.retrieve($);if(!J.results_url)throw new D(`No batch \`results_url\`; Has it finished processing? ${J.processing_status} - ${J.id}`);return this._client.get(J.results_url,{...Z,headers:A([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,Q)=>e4.fromResponse(Q.response,Q.controller))}}class A4 extends m{constructor(){super(...arguments);this.batches=new W0(this._client)}create($,Z){if($.model in I2)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${I2[$.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 X1,J8,S4,n,K1,j$,u$,q4,z1,S2,S5;function w2(){let $,Z;return{promise:new Promise((Y,Q)=>{$=Y,Z=Q}),resolve:$,reject:Z}}class V1{constructor($,Z,J){X1.add(this),this.client=$,J8.set(this,!1),S4.set(this,!1),n.set(this,void 0),K1.set(this,void 0),j$.set(this,void 0),u$.set(this,void 0),q4.set(this,void 0),z1.set(this,0),D(this,n,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let Q=["BetaToolRunner",...L5(Z.tools,Z.messages)].join(", ");D(this,K1,{...J,headers:S([{"x-stainless-helper":Q},J?.headers])},"f"),D(this,q4,w2(),"f")}async*[(J8=new WeakMap,S4=new WeakMap,n=new WeakMap,K1=new WeakMap,j$=new WeakMap,u$=new WeakMap,q4=new WeakMap,z1=new WeakMap,X1=new WeakSet,S2=async function(){let Z=C(this,n,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let J=0;if(C(this,j$,"f")!==void 0)try{let G=await C(this,j$,"f");J=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(J<Y)return!1;let Q=Z.model??C(this,n,"f").params.model,X=Z.summaryPrompt??x2,K=C(this,n,"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:Q,messages:[...K,{role:"user",content:[{type:"text",text:X}]}],max_tokens:C(this,n,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(V.content[0]?.type!=="text")throw new P("Expected text response for compaction");return C(this,n,"f").params.messages=[{role:"user",content:V.content}],!0},Symbol.asyncIterator)](){var $;if(C(this,J8,"f"))throw new P("Cannot iterate over a consumed stream");D(this,J8,!0,"f"),D(this,S4,!0,"f"),D(this,u$,void 0,"f");try{while(!0){let Z;try{if(C(this,n,"f").params.max_iterations&&C(this,z1,"f")>=C(this,n,"f").params.max_iterations)break;D(this,S4,!1,"f"),D(this,u$,void 0,"f"),D(this,z1,($=C(this,z1,"f"),$++,$),"f"),D(this,j$,void 0,"f");let{max_iterations:J,compactionControl:Y,...Q}=C(this,n,"f").params;if(Q.stream)Z=this.client.beta.messages.stream({...Q},C(this,K1,"f")),D(this,j$,Z.finalMessage(),"f"),C(this,j$,"f").catch(()=>{}),yield Z;else D(this,j$,this.client.beta.messages.create({...Q,stream:!1},C(this,K1,"f")),"f"),yield C(this,j$,"f");if(!await C(this,X1,"m",S2).call(this)){if(!C(this,S4,"f")){let{role:V,content:G}=await C(this,j$,"f");C(this,n,"f").params.messages.push({role:V,content:G})}let K=await C(this,X1,"m",S5).call(this,C(this,n,"f").params.messages.at(-1));if(K)C(this,n,"f").params.messages.push(K);else if(!C(this,S4,"f"))break}}finally{if(Z)Z.abort()}}if(!C(this,j$,"f"))throw new P("ToolRunner concluded without a message from the server");C(this,q4,"f").resolve(await C(this,j$,"f"))}catch(Z){throw D(this,J8,!1,"f"),C(this,q4,"f").promise.catch(()=>{}),C(this,q4,"f").reject(Z),D(this,q4,w2(),"f"),Z}}setMessagesParams($){if(typeof $==="function")C(this,n,"f").params=$(C(this,n,"f").params);else C(this,n,"f").params=$;D(this,S4,!0,"f"),D(this,u$,void 0,"f")}async generateToolResponse(){let $=await C(this,j$,"f")??this.params.messages.at(-1);if(!$)return null;return C(this,X1,"m",S5).call(this,$)}done(){return C(this,q4,"f").promise}async runUntilDone(){if(!C(this,J8,"f"))for await(let $ of this);return this.done()}get params(){return C(this,n,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}S5=async function(Z){if(C(this,u$,"f")!==void 0)return C(this,u$,"f");return D(this,u$,WX(C(this,n,"f").params,Z),"f"),C(this,u$,"f")};async function WX($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let J=Z.content.filter((Q)=>Q.type==="tool_use");if(J.length===0)return null;return{role:"user",content:await Promise.all(J.map(async(Q)=>{let X=$.tools.find((K)=>("name"in K?K.name:K.mcp_server_name)===Q.name);if(!X||!("run"in X))return{type:"tool_result",tool_use_id:Q.id,content:`Error: Tool '${Q.name}' not found`,is_error:!0};try{let K=Q.input;if("parse"in X&&X.parse)K=X.parse(K);let V=await X.run(K);return{type:"tool_result",tool_use_id:Q.id,content:V}}catch(K){return{type:"tool_result",tool_use_id:Q.id,content:K instanceof Z8?K.content:`Error: ${K instanceof Error?K.message:String(K)}`,is_error:!0}}}))}}class Y8{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new G4;for await(let Z of this.iterator)for(let J of $.decode(Z))yield JSON.parse(J);for(let Z of $.flush())yield JSON.parse(Z)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new P("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new P("Attempted to iterate over a response with no body")}return new Y8(p8($.body),Z)}}class G1 extends p{create($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Y,...Z,headers:S([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/messages/batches/${$}?beta=true`,{...J,headers:S([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",I$,{query:Y,...Z,headers:S([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(m`/v1/messages/batches/${$}?beta=true`,{...J,headers:S([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},J?.headers])})}cancel($,Z={},J){let{betas:Y}=Z??{};return this._client.post(m`/v1/messages/batches/${$}/cancel?beta=true`,{...J,headers:S([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},J?.headers])})}async results($,Z={},J){let Y=await this.retrieve($);if(!Y.results_url)throw new P(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);let{betas:Q}=Z??{};return this._client.get(Y.results_url,{...J,headers:S([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},J?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((X,K)=>Y8.fromResponse(K.response,K.controller))}}var k2={"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"},BX=["claude-opus-4-6"];class W4 extends p{constructor(){super(...arguments);this.batches=new G1(this._client)}create($,Z){let J=b2($),{betas:Y,...Q}=J;if(Q.model in k2)console.warn(`The model '${Q.model}' is deprecated and will reach end-of-life on ${k2[Q.model]}
|
|
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 FX&&$.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 J=this._client._options.timeout;if(!$.stream&&J==null){let Q=F0[$.model]??void 0;J=this._client.calculateNonstreamingTimeout($.max_tokens,Q)}let Y=O0($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:J??600000,...Z,headers:S([Y,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((J)=>k5(J,$,{logger:this._client.logger??console}))}stream($,Z){return C1.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var m2={"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"},FX=["claude-opus-4-6"];k4.Batches=j1;class z8 extends p{retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/models/${$}`,{...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",I$,{query:Y,...Z,headers:S([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers])})}}var O1=($)=>{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 h5,g5,_0,c2,p2="\\n\\nHuman:",u2="\\n\\nAssistant:";class u{constructor({baseURL:$=O1("ANTHROPIC_BASE_URL"),apiKey:Z=O1("ANTHROPIC_API_KEY")??null,authToken:J=O1("ANTHROPIC_AUTH_TOKEN")??null,...Y}={}){h5.add(this),_0.set(this,void 0);let Q={apiKey:Z,authToken:J,...Y,baseURL:$||"https://api.anthropic.com"};if(!Q.dangerouslyAllowBrowser&&Q2())throw new P(`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??w5.DEFAULT_TIMEOUT,this.logger=Q.logger??console;let X="warn";this.logLevel=X,this.logLevel=V5(Q.logLevel,"ClientOptions.logLevel",this)??V5(U0("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??X,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??aZ(),L(this,T1,rZ,"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 A([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return A([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return A([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return iZ($)}getUserAgent(){return`${this.constructor.name}/JS ${X4}`}defaultIdempotencyKey(){return`stainless-node-retry-${J5()}`}makeStatusError($,Z,J,Y){return n.generate($,Z,J,Y)}buildURL($,Z,J){let Y=!C(this,S5,"m",A2).call(this)&&J||this.baseURL,Q=hZ($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery(),K=Object.fromEntries(Q.searchParams);if(!X5(X)||!X5(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 D("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 L4(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(s(this).debug(`[${G}] sending request`,m$({retryOfRequestLogID:J,method:Y.method,url:K,options:Y,headers:X.headers})),Y.signal?.aborted)throw new Y$;let B=new AbortController,U=await this.fetchWithTimeout(K,X,V,B).catch(T8),M=Date.now();if(U instanceof globalThis.Error){let T=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new Y$;let y=g$(U)||/timed? ?out/i.test(String(U)+("cause"in U?String(U.cause):""));if(Z)return s(this).info(`[${G}] connection ${y?"timed out":"failed"} - ${T}`),s(this).debug(`[${G}] connection ${y?"timed out":"failed"} (${T})`,m$({retryOfRequestLogID:J,url:K,durationMs:M-z,message:U.message})),this.retryRequest(Y,Z,J??G);if(s(this).info(`[${G}] connection ${y?"timed out":"failed"} - error; no more retries left`),s(this).debug(`[${G}] connection ${y?"timed out":"failed"} (error; no more retries left)`,m$({retryOfRequestLogID:J,url:K,durationMs:M-z,message:U.message})),y)throw new I8;throw new R4({cause:U})}let O=[...U.headers.entries()].filter(([T])=>T==="request-id").map(([T,y])=>", "+T+": "+JSON.stringify(y)).join(""),P=`[${G}${H}${O}] ${X.method} ${K} ${U.ok?"succeeded":"failed"} with status ${U.status} in ${M-z}ms`;if(!U.ok){let T=await this.shouldRetry(U);if(Z&&T){let u=`retrying, ${Z} attempts remaining`;return await nZ(U.body),s(this).info(`${P} - ${u}`),s(this).debug(`[${G}] response error (${u})`,m$({retryOfRequestLogID:J,url:U.url,status:U.status,headers:U.headers,durationMs:M-z})),this.retryRequest(Y,Z,J??G,U.headers)}let y=T?"error; no more retries left":"error; not retryable";s(this).info(`${P} - ${y}`);let K$=await U.text().catch((u)=>T8(u).message),i=Z1(K$),b=i?void 0:K$;throw s(this).debug(`[${G}] response error (${y})`,m$({retryOfRequestLogID:J,url:U.url,status:U.status,headers:U.headers,message:b,durationMs:Date.now()-z})),this.makeStatusError(U.status,i,b,U.headers)}return s(this).info(P),s(this).debug(`[${G}] response start`,m$({retryOfRequestLogID:J,url:U.url,status:U.status,headers:U.headers,durationMs:M-z})),{response:U,options:Y,controller:B,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 z1(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 pZ(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 D("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)mZ("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=A([Q,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...oZ(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,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=A([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:J1($)};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,T1,"f").call(this,{body:$,headers:J})}}w5=c,T1=new WeakMap,S5=new WeakSet,A2=function(){return this.baseURL!=="https://api.anthropic.com"};c.Anthropic=w5;c.HUMAN_PROMPT=x2;c.AI_PROMPT=S2;c.DEFAULT_TIMEOUT=600000;c.AnthropicError=D;c.APIError=n;c.APIConnectionError=R4;c.APIConnectionTimeoutError=I8;c.APIUserAbortError=Y$;c.NotFoundError=w8;c.ConflictError=k8;c.RateLimitError=y8;c.BadRequestError=A8;c.AuthenticationError=x8;c.InternalServerError=_8;c.PermissionDeniedError=S8;c.UnprocessableEntityError=b8;c.toFile=V1;class w$ extends c{constructor(){super(...arguments);this.completions=new Z8(this),this.messages=new A4(this),this.models=new Y8(this),this.beta=new S$(this)}}w$.Completions=Z8;w$.Messages=A4;w$.Models=Y8;w$.Beta=S$;a();e();import{existsSync as I0,readdirSync as zV,readFileSync as x9,writeFileSync as VV,statSync as $3,realpathSync as GV}from"fs";import{resolve as A$,join as Z3,sep as N8}from"path";import{existsSync as dQ,readFileSync as lQ,writeFileSync as oQ}from"fs";import{basename as k5}from"path";var w2=50;class b5{entries=[];saveState($){let Z=dQ($),J=Z?lQ($,"utf-8"):"";if(this.entries.push({path:$,content:J,timestamp:Date.now(),existed:Z}),this.entries.length>w2)this.entries=this.entries.slice(-w2)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${k5($.path)} was a new file. Remove it manually if needed.`;oQ($.path,$.content);let Z=$.content.split(`
|
|
90
|
-
`).length;return`Undo: restored ${
|
|
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 ${m5($.path)} (${Z} lines, from ${l2($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${m5($.path)} (${l2($.timestamp)})`}}function l2($){let Z=Math.floor((Date.now()-$)/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;return`${Math.floor(J/60)}h ago`}$$();import{existsSync as o2,readdirSync as TX,readFileSync as PX,mkdirSync as AX}from"fs";import{join as p5}from"path";function a2($){if(!o2($))return[];let Z=[],J=TX($).filter((Y)=>Y.endsWith(".json"));for(let Y of J)try{let Q=JSON.parse(PX(p5($,Y),"utf-8"));if(!Q.name||!Q.description||!Q.command)continue;if(typeof Q.name!=="string"||typeof Q.command!=="string")continue;if(Q.command.includes("$(")||Q.command.includes("`"))continue;Z.push({name:Q.name,description:Q.description,inputSchema:Q.input_schema||{type:"object",properties:{},required:[]},command:Q.command,source:p5($,Y)})}catch{}return Z}function r2($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function i2($,Z){let J=$.command;for(let[z,U]of Object.entries(Z)){let B=String(U).replace(/[;&|`$()]/g,"");J=J.replace(new RegExp(`\\{\\{input\\.${z}\\}\\}`,"g"),B)}J=J.replace(/\{\{input\.\w+\}\}/g,"");let Y=i4(),Q=Bun.spawn([...Y,J],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>Q.kill(),30000),[K,V]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),G=await Q.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 n2($){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 s2($){let Z=p5($,"plugins");if(!o2(Z))AX(Z,{recursive:!0});return Z}f4();r();import{existsSync as xX,readFileSync as SX}from"fs";import{join as wX}from"path";var V8=[{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}],v0="",q$=[],O$=new Set,J6=()=>wX(v0,"news-feeds.json");function f0(){if(!v0)return;let $={custom:q$,disabled:[...O$]};x(J6(),JSON.stringify($,null,2))}function kX(){if(!v0)return;let $=J6();if(!xX($)){q$=[],O$=new Set;return}try{let Z=JSON.parse(SX($,"utf-8"));q$=Z.custom||[],O$=new Set(Z.disabled||[])}catch{q$=[],O$=new Set}}function Y6($){v0=$,kX()}function a5(){return[...V8.filter((Z)=>!O$.has(Z.url)),...q$]}function h0($,Z,J){let Y=$.trim();if(!Y||Y.length>100)return"Error: nome invalido (1-100 caracteres).";let Q=J.trim().toLowerCase();if(!Q||Q.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([...V8,...q$].some((G)=>G.url===X))return"Error: essa URL ja esta cadastrada.";let V={name:Y,url:X,category:Q};return q$=[...q$,V],f0(),V}function g0($){let Z=$.toLowerCase().trim(),J=q$.findIndex((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(J===-1)return!1;return q$=[...q$.slice(0,J),...q$.slice(J+1)],f0(),!0}function m0($){let Z=$.toLowerCase().trim(),J=V8.find((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(!J)return!1;if(O$.has(J.url))return!1;return O$=new Set([...O$,J.url]),f0(),!0}function c0($){let Z=$.toLowerCase().trim(),J=V8.find((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(!J)return!1;if(!O$.has(J.url))return!1;return O$=new Set([...O$].filter((Y)=>Y!==J.url)),f0(),!0}function p0(){let $=["Fontes de noticias:"];$.push(`
|
|
95
|
+
--- Built-in ---`);for(let Z of V8){let J=O$.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${J} \u2014 ${Z.url}`)}if(q$.length>0){$.push(`
|
|
96
|
+
--- Custom ---`);for(let Z of q$)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
|
|
97
|
+
Total: ${a5().length} ativas (${V8.length} built-in, ${q$.length} custom, ${O$.size} desativadas)`),$.join(`
|
|
98
|
+
`)}var e2=2097152,o5=10,bX=1e4;function yX($,Z,J){let Y=[],Q=/<item[\s>]([\s\S]*?)<\/item>/gi,X;while((X=Q.exec($))!==null){let K=X[1],V=$6(K,Z,J);if(V)Y.push(V);if(Y.length>=o5)break}if(Y.length===0){let K=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((X=K.exec($))!==null){let V=X[1],G=$6(V,Z,J);if(G)Y.push(G);if(Y.length>=o5)break}}return Y}function $6($,Z,J){let Y=E1($,"title");if(!Y)return null;let Q=E1($,"link")||gX($),X=_X(Q),K=E1($,"pubDate")||E1($,"published")||E1($,"updated"),V;if(K){let G=new Date(K);V=isNaN(G.getTime())?void 0:G}return{title:cX(Y),link:X,source:Z,category:J,pubDate:V}}function _X($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function vX($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function E1($,Z){let J=vX(Z),Q=new RegExp(`<${J}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${J}>`,"i").exec($);if(Q)return Q[1].trim();let K=new RegExp(`<${J}[^>]*>([\\s\\S]*?)</${J}>`,"i").exec($);return K?K[1].trim():null}function fX($,Z){let J=hX($,Z);try{return new TextDecoder(J).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function hX($,Z){if(Z){let Q=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(Q)return Z6(Q[1])}let Y=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Y)return Z6(Y[1]);return"utf-8"}function Z6($){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 gX($){let J=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return J?J[1]:null}var mX={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 cX($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,J)=>mX[J]??Z).replace(/&#(\d+);/g,(Z,J)=>String.fromCharCode(Number(J))).replace(/&#x([0-9a-fA-F]+);/g,(Z,J)=>String.fromCharCode(parseInt(J,16))).trim()}async function r5($,Z=5){let J=Math.max(1,Math.min(Z,o5));if($&&$.length===0)return{items:[],errors:[]};let Y=a5(),Q=$?Y.filter((G)=>$.includes(G.category)):Y,X=await Promise.allSettled(Q.map((G)=>uX(G,J))),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(`${Q[G].name}: ${pX(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 B4($,Z=5){if($&&$.length===0)return lX();let{items:J,errors:Y}=await r5($,Z);if(J.length===0)return Y.length>0?`Nenhuma noticia encontrada.
|
|
99
|
+
Falhas: ${Y.join(", ")}`:"Nenhuma noticia encontrada.";return dX(J,Y)}function pX($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function uX($,Z){let J=new AbortController,Y=setTimeout(()=>J.abort(),bX);try{let Q=await fetch($.url,{signal:J.signal,headers:{"User-Agent":"smolerclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(Y),!Q.ok)return[];let X=Q.headers.get("content-length");if(X&&Number(X)>e2)return[];let K=Q.body?.getReader();if(!K)return[];let V=[],G=0;while(!0){let{done:B,value:M}=await K.read();if(B)break;if(G+=M.byteLength,G>e2)return K.cancel(),[];V.push(M)}let H=Buffer.concat(V),z=fX(H,Q.headers.get("content-type"));return yX(z,$.name,$.category).slice(0,Z)}catch(Q){throw clearTimeout(Y),Q}}function dX($,Z){let J={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 Q=[],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=J[V],z=G.slice(0,8).map((U)=>{let B=U.pubDate?U.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${B?`[${B}]`:""} ${U.title} (${U.source})`});Q.push(`--- ${H} ---
|
|
100
100
|
${z.join(`
|
|
101
101
|
`)}`)}let K=Q.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 lX(){let $=a5();return`Categorias: ${[...new Set($.map((J)=>J.category))].sort().join(", ")}
|
|
106
|
+
Uso: /news [categoria]`}$$();r();Y4();import{existsSync as Q6,mkdirSync as oX,readFileSync as aX}from"fs";import{join as rX}from"path";import{randomUUID as iX}from"crypto";var X6="",o=[],G8=null,K6=null,z6=()=>rX(X6,"tasks.json");function u0(){x(z6(),JSON.stringify(o,null,2))}function nX(){let $=z6();if(!Q6($)){o=[];return}try{o=JSON.parse(aX($,"utf-8"))}catch{o=[]}}function V6($,Z){if(X6=$,K6=Z,!Q6($))oX($,{recursive:!0});if(nX(),G8)clearInterval(G8);G8=setInterval(sX,30000),$K().catch(()=>{})}function G6(){if(G8)clearInterval(G8),G8=null}function d0($,Z){let J={id:ZK(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(o=[...o,J],u0(),Z&&I)i5(J).catch(()=>{});return J}function l0($){let Z=$.toLowerCase(),J=o.find((Y)=>Y.id===$||Y.title.toLowerCase().includes(Z));if(!J||J.done)return null;if(o=o.map((Y)=>Y.id===J.id?{...Y,done:!0}:Y),u0(),J.dueAt&&I)q6(J.id).catch(()=>{});return o.find((Y)=>Y.id===J.id)||null}function H6($){let Z=$.toLowerCase(),J=o.findIndex((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(J===-1)return!1;let Y=o[J];if(o=[...o.slice(0,J),...o.slice(J+1)],u0(),Y.dueAt&&I)q6(Y.id).catch(()=>{});return!0}function l$($=!1){return $?[...o]:o.filter((Z)=>!Z.done)}function h4($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((J)=>{let Y=J.done?"[x]":"[ ]",Q=J.dueAt?` (${JK(J.dueAt)})`:"";return` ${Y} ${J.title}${Q} [${J.id}]`});return`Tarefas (${$.length}):
|
|
107
107
|
${Z.join(`
|
|
108
|
-
`)}`}function
|
|
108
|
+
`)}`}function L1($){let Z=new Date,J=$.toLowerCase().trim(),Y=J.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 Q=new Date(Z);if(J.includes("amanha")||J.includes("amanh\xE3"))Q.setDate(Q.getDate()+1);let X=J.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(Q.setHours(K,V,0,0),Q<=Z&&!J.includes("amanha")&&!J.includes("amanh\xE3"))Q.setDate(Q.getDate()+1);return Q}}return null}function sX(){let $=new Date,Z=!1;for(let J of o){if(J.done||J.notified||!J.dueAt)continue;let Y=new Date(J.dueAt);if(isNaN(Y.getTime()))continue;let Q=$.getTime()-Y.getTime();if(Q>=0&&Q<300000)o=o.map((X)=>X.id===J.id?{...X,notified:!0}:X),Z=!0,eX(J),K6?.(J)}if(Z)u0()}function tX($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function eX($){if(!I)return;try{await J4("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var n5="smolerclaw-reminder-";async function i5($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let J=`${n5}${$.id}`,Y=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),Q=[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"">${kZ(tX($.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 n1("Create",J,["/SC","ONCE","/SD",Y,"/ST",Q,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${K}"`,"/F"])}catch{}}async function q6($){let Z=`${n5}${$}`;try{await n1("Delete",Z,["/F"])}catch{}}async function $K(){if(!I)return;let $=Date.now();for(let Z of o){if(Z.done||Z.notified||!Z.dueAt)continue;let J=new Date(Z.dueAt);if(isNaN(J.getTime())||J.getTime()<=$)continue;try{if((await n1("Query",`${n5}${Z.id}`)).exitCode!==0)await i5(Z)}catch{await i5(Z)}}}function ZK(){return iX().slice(0,8)}function JK($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let J=new Date,Y=new Date(J.getFullYear(),J.getMonth(),J.getDate()),Q=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),X=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(Q.getTime()===Y.getTime())return`hoje ${X}`;let K=new Date(Y);if(K.setDate(K.getDate()+1),Q.getTime()===K.getTime())return`amanha ${X}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${X}`}r();import{existsSync as W6,mkdirSync as YK,readFileSync as QK}from"fs";import{join as XK}from"path";import{randomUUID as KK}from"crypto";var U6="",W$=[],B6=()=>XK(U6,"memos.json");function N6(){x(B6(),JSON.stringify(W$,null,2))}function zK(){let $=B6();if(!W6($)){W$=[];return}try{W$=JSON.parse(QK($,"utf-8"))}catch{W$=[]}}function M6($){if(U6=$,!W6($))YK($,{recursive:!0});zK()}function o0($,Z=[]){let J=new Date().toISOString(),Y=$.match(/#(\w+)/g)?.map((K)=>K.slice(1).toLowerCase())||[],Q=[...new Set([...Z.map((K)=>K.toLowerCase()),...Y])],X={id:GK(),content:$.trim(),tags:Q,createdAt:J,updatedAt:J};return W$=[...W$,X],N6(),X}function C6($){let Z=W$.findIndex((J)=>J.id===$);if(Z===-1)return!1;return W$=[...W$.slice(0,Z),...W$.slice(Z+1)],N6(),!0}function a0($){let Z=$.toLowerCase().trim();if(!Z)return[...W$];let J=Z.startsWith("#"),Y=J?Z.slice(1):Z;return W$.filter((Q)=>{if(J)return Q.tags.some((X)=>X.includes(Y));return Q.content.toLowerCase().includes(Y)||Q.tags.some((X)=>X.includes(Y))}).sort((Q,X)=>new Date(X.updatedAt).getTime()-new Date(Q.updatedAt).getTime())}function D1($=20){return[...W$].reverse().sort((Z,J)=>new Date(J.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function VK(){let $=new Map;for(let Z of W$)for(let J of Z.tags)$.set(J,($.get(J)||0)+1);return[...$.entries()].map(([Z,J])=>({tag:Z,count:J})).sort((Z,J)=>J.count-Z.count)}function g4($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((J)=>{let Y=new Date(J.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=J.tags.length>0?` [${J.tags.map((K)=>`#${K}`).join(" ")}]`:"",X=J.content.length>80?J.content.slice(0,80).replace(/\n/g," ")+"...":J.content.replace(/\n/g," ");return` [${Y}] ${X}${Q} {${J.id}}`});return`Memos (${$.length}):
|
|
109
109
|
${Z.join(`
|
|
110
|
-
`)}`}function
|
|
110
|
+
`)}`}function j6(){let $=VK();if($.length===0)return"Nenhuma tag.";return`Tags:
|
|
111
111
|
${$.map((J)=>` #${J.tag} (${J.count})`).join(`
|
|
112
|
-
`)}`}function
|
|
113
|
-
`);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
|
|
114
|
-
`)}
|
|
115
|
-
`)}function
|
|
112
|
+
`)}`}function GK(){return KK().slice(0,8)}$$();async function r0($){if(I)return HK($);return s5($)}async function HK($){let Z=$.to.replace(/'/g,"''"),J=$.subject.replace(/'/g,"''"),Y=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),Q=$.cc?.replace(/'/g,"''")||"",X=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${J}'`,` $mail.Body = '${Y}'`,Q?` $mail.CC = '${Q}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
|
|
113
|
+
`);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 s5($);return H||"Email aberto no Outlook."}catch{return s5($)}}async function s5($){let Z=[];if($.subject)Z.push(`subject=${encodeURIComponent($.subject)}`);if($.body)Z.push(`body=${encodeURIComponent($.body)}`);if($.cc)Z.push(`cc=${encodeURIComponent($.cc)}`);let J=`mailto:${encodeURIComponent($.to)}${Z.length?"?"+Z.join("&"):""}`;try{let Y=I?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${J}'`]:["xdg-open",J],Q=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>Q.kill(),1e4);return await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),await Q.exited,clearTimeout(X),"Email aberto no cliente de email padrao."}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}function i0($){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(`
|
|
114
|
+
`)}r();import{existsSync as F6,mkdirSync as qK,readFileSync as WK}from"fs";import{join as UK}from"path";import{randomUUID as BK}from"crypto";var R6="",N4=[],E6=()=>UK(R6,"finance.json");function NK(){x(E6(),JSON.stringify(N4,null,2))}function MK(){let $=E6();if(!F6($)){N4=[];return}try{N4=JSON.parse(WK($,"utf-8"))}catch{N4=[]}}function L6($){if(R6=$,!F6($))qK($,{recursive:!0});MK()}function T1($,Z,J,Y){let Q={id:CK(),type:$,amount:Math.abs(Z),category:J.toLowerCase().trim(),description:Y.trim(),date:new Date().toISOString()};return N4=[...N4,Q],NK(),Q}function n0($,Z){let J=new Date,Y=$||J.getFullYear(),Q=Z!==void 0?Z:J.getMonth(),X=N4.filter((U)=>{let B=new Date(U.date);return B.getFullYear()===Y&&B.getMonth()===Q});if(X.length===0)return`Nenhuma transacao em ${O6(Q)}/${Y}.`;let K=X.filter((U)=>U.type==="entrada").reduce((U,B)=>U+B.amount,0),V=X.filter((U)=>U.type==="saida").reduce((U,B)=>U+B.amount,0),G=K-V,H=new Map;for(let U of X.filter((B)=>B.type==="saida"))H.set(U.category,(H.get(U.category)||0)+U.amount);let z=[`--- Resumo ${O6(Q)}/${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 U=[...H.entries()].sort((B,M)=>M[1]-B[1]);for(let[B,M]of U){let O=V>0?Math.round(M/V*100):0;z.push(` ${B.padEnd(15)} R$ ${M.toFixed(2)} (${O}%)`)}}return z.join(`
|
|
115
|
+
`)}function t5($=10){let Z=[...N4].sort((Y,Q)=>new Date(Q.date).getTime()-new Date(Y.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
|
|
116
116
|
${Z.map((Y)=>{let Q=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.type==="entrada"?"+":"-";return` [${Q}] ${X} R$ ${Y.amount.toFixed(2)} ${Y.category} \u2014 ${Y.description} [${Y.id}]`}).join(`
|
|
117
|
-
`)}`}function
|
|
117
|
+
`)}`}function CK(){return BK().slice(0,8)}function O6($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}r();import{existsSync as D6,mkdirSync as jK,readFileSync as OK}from"fs";import{join as FK}from"path";import{randomUUID as RK}from"crypto";var T6="",M4=[],P6=()=>FK(T6,"decisions.json");function EK(){x(P6(),JSON.stringify(M4,null,2))}function LK(){let $=P6();if(!D6($)){M4=[];return}try{M4=JSON.parse(OK($,"utf-8"))}catch{M4=[]}}function A6($){if(T6=$,!D6($))jK($,{recursive:!0});LK()}function I6($,Z,J,Y,Q=[]){let X={id:DK(),title:$.trim(),context:Z.trim(),chosen:J.trim(),alternatives:Y?.trim(),tags:Q.map((K)=>K.toLowerCase()),date:new Date().toISOString()};return M4=[...M4,X],EK(),X}function m4($){let Z=$.toLowerCase();return M4.filter((J)=>J.title.toLowerCase().includes(Z)||J.chosen.toLowerCase().includes(Z)||J.context.toLowerCase().includes(Z)||J.tags.some((Y)=>Y.includes(Z))).sort((J,Y)=>new Date(Y.date).getTime()-new Date(J.date).getTime())}function s0($=15){return[...M4].sort((Z,J)=>new Date(J.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function H8($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((J)=>{let Y=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=J.tags.length>0?` [${J.tags.join(", ")}]`:"";return` [${Y}] ${J.title}${Q} {${J.id}}`});return`Decisoes (${$.length}):
|
|
118
118
|
${Z.join(`
|
|
119
|
-
`)}`}function
|
|
119
|
+
`)}`}function DK(){return RK().slice(0,8)}A1();r();import{existsSync as _6,mkdirSync as wK,readFileSync as kK}from"fs";import{join as bK}from"path";import{randomUUID as yK}from"crypto";var v6="",f={people:[],interactions:[],delegations:[]},f6=()=>bK(v6,"people.json");function $7(){x(f6(),JSON.stringify(f,null,2))}function _K(){let $=f6();if(!_6($)){f={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(kK($,"utf-8"));f={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{f={people:[],interactions:[],delegations:[]}}}function h6($){if(v6=$,!_6($))wK($,{recursive:!0});_K()}function Z7($,Z,J,Y){let Q={id:q9(),name:$.trim(),group:Z,role:J?.trim(),contact:Y?.trim(),createdAt:new Date().toISOString()};return f={...f,people:[...f.people,Q]},$7(),Q}function o$($){let Z=$.toLowerCase();return f.people.find((J)=>J.id===$||J.name.toLowerCase().includes(Z))||null}function J7($){if($)return f.people.filter((Z)=>Z.group===$);return[...f.people]}function g6($,Z,J,Y){let Q=o$($);if(!Q)return null;let X={id:q9(),personId:Q.id,date:new Date().toISOString(),type:Z,summary:J.trim(),followUpDate:Y?.toISOString(),followUpDone:!1};return f={...f,interactions:[...f.interactions,X]},$7(),X}function vK($,Z=10){let J=o$($);if(!J)return[];return[...f.interactions].filter((Y)=>Y.personId===J.id).reverse().sort((Y,Q)=>new Date(Q.date).getTime()-new Date(Y.date).getTime()).slice(0,Z)}function q8(){let $=new Date,Z=[];for(let J of f.interactions){if(J.followUpDone||!J.followUpDate)continue;let Y=new Date(J.followUpDate);if(isNaN(Y.getTime()))continue;if(Y<=$){let Q=f.people.find((X)=>X.id===J.personId);if(Q)Z.push({person:Q,interaction:J})}}return Z.sort((J,Y)=>new Date(J.interaction.followUpDate).getTime()-new Date(Y.interaction.followUpDate).getTime())}function Y7($,Z,J){let Y=o$($);if(!Y)return null;let Q={id:q9(),personId:Y.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:J?.toISOString(),status:"pendente"};return f={...f,delegations:[...f.delegations,Q]},$7(),Q}function m6($,Z,J){if(!f.delegations.find((Q)=>Q.id===$))return null;return f={...f,delegations:f.delegations.map((Q)=>Q.id===$?{...Q,status:Z,notes:J||Q.notes}:Q)},$7(),f.delegations.find((Q)=>Q.id===$)||null}function c4($,Z=!0){let J=[...f.delegations];if($){let Q=o$($);if(!Q)return[];J=J.filter((X)=>X.personId===Q.id)}if(Z)J=J.filter((Q)=>Q.status!=="concluido");let Y=new Date;return J=J.map((Q)=>{if(Q.status==="pendente"&&Q.dueDate){let X=new Date(Q.dueDate);if(!isNaN(X.getTime())&&X<Y)return{...Q,status:"atrasado"}}return Q}),J.sort((Q,X)=>{if(Q.status==="atrasado"&&X.status!=="atrasado")return-1;if(X.status==="atrasado"&&Q.status!=="atrasado")return 1;let K=Q.dueDate?new Date(Q.dueDate).getTime():1/0,V=X.dueDate?new Date(X.dueDate).getTime():1/0;return K-V})}var c6={equipe:"Equipe",familia:"Familia",contato:"Contato"};function Q7($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let Q of $){let X=Z.get(Q.group)||[];Z.set(Q.group,[...X,Q])}let J=[],Y=["equipe","familia","contato"];for(let Q of Y){let X=Z.get(Q);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}]`});J.push(`--- ${c6[Q]} ---
|
|
120
120
|
${K.join(`
|
|
121
121
|
`)}`)}return J.join(`
|
|
122
122
|
|
|
123
|
-
`)}function
|
|
124
|
-
Interacoes recentes:`);for(let Q of J){let X=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${X}] ${Q.type}: ${Q.summary}`)}}let Y=
|
|
125
|
-
Tarefas delegadas:`);for(let Q of Y){let X=Q.status==="atrasado"?"!!":Q.status==="em_andamento"?">>":" ",K=Q.dueDate?` (${
|
|
126
|
-
`)}function
|
|
123
|
+
`)}function X7($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${c6[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let J=vK($.id,5);if(J.length>0){Z.push(`
|
|
124
|
+
Interacoes recentes:`);for(let Q of J){let X=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${X}] ${Q.type}: ${Q.summary}`)}}let Y=c4($.id);if(Y.length>0){Z.push(`
|
|
125
|
+
Tarefas delegadas:`);for(let Q of Y){let X=Q.status==="atrasado"?"!!":Q.status==="em_andamento"?">>":" ",K=Q.dueDate?` (${W9(Q.dueDate)})`:"";Z.push(` ${X} ${Q.task}${K} [${Q.status}]`)}}return Z.join(`
|
|
126
|
+
`)}function K7($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((J)=>{let Q=f.people.find((V)=>V.id===J.personId)?.name||"?",X=J.status==="atrasado"?"!! ":J.status==="em_andamento"?">> ":" ",K=J.dueDate?` (${W9(J.dueDate)})`:"";return`${X}${Q}: ${J.task}${K} [${J.status}] [${J.id}]`});return`Delegacoes (${$.length}):
|
|
127
127
|
${Z.join(`
|
|
128
|
-
`)}`}function
|
|
128
|
+
`)}`}function z7($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:J,interaction:Y})=>{return` [${W9(Y.followUpDate)}] ${J.name}: ${Y.summary} [${Y.id}]`});return`Follow-ups pendentes (${$.length}):
|
|
129
129
|
${Z.join(`
|
|
130
|
-
`)}`}function
|
|
131
|
-
`);let Z=
|
|
132
|
-
!! ${Q.length} follow-up(s) pendente(s):`);for(let{person:H,interaction:z}of Q.slice(0,5))$.push(` ${H.name}: ${z.summary}`)}let X=
|
|
133
|
-
!! ${K.length} delegacao(oes) atrasada(s):`);for(let H of K.slice(0,5)){let z=
|
|
134
|
-
${V.length} delegacao(oes) em andamento`);let G=[...
|
|
135
|
-
Ultimas interacoes:`);for(let H of G){let z=
|
|
130
|
+
`)}`}function V7(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
|
|
131
|
+
`);let Z=f.people.filter((H)=>H.group==="equipe").length,J=f.people.filter((H)=>H.group==="familia").length,Y=f.people.filter((H)=>H.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${J} | Contatos: ${Y}`);let Q=q8();if(Q.length>0){$.push(`
|
|
132
|
+
!! ${Q.length} follow-up(s) pendente(s):`);for(let{person:H,interaction:z}of Q.slice(0,5))$.push(` ${H.name}: ${z.summary}`)}let X=c4(),K=X.filter((H)=>H.status==="atrasado"),V=X.filter((H)=>H.status==="pendente"||H.status==="em_andamento");if(K.length>0){$.push(`
|
|
133
|
+
!! ${K.length} delegacao(oes) atrasada(s):`);for(let H of K.slice(0,5)){let z=f.people.find((U)=>U.id===H.personId);$.push(` ${z?.name}: ${H.task}`)}}if(V.length>0)$.push(`
|
|
134
|
+
${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((B)=>B.id===H.personId),U=new Date(H.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${U}] ${z?.name}: ${H.summary}`)}}return $.push(`
|
|
136
136
|
========================`),$.join(`
|
|
137
|
-
`)}function
|
|
137
|
+
`)}function q9(){return yK().slice(0,8)}function W9($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let J=new Date,Y=new Date(J.getFullYear(),J.getMonth(),J.getDate()),Q=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(Q.getTime()===Y.getTime())return"hoje";let X=new Date(Y);if(X.setDate(X.getDate()+1),Q.getTime()===X.getTime())return"amanha";let K=Math.floor((Q.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"})}r();import{existsSync as p6,mkdirSync as fK,readFileSync as hK}from"fs";import{join as gK}from"path";import{randomUUID as mK}from"crypto";var u6="",a=[],d6=()=>gK(u6,"materials.json");function U9(){x(d6(),JSON.stringify(a,null,2))}function cK(){let $=d6();if(!p6($)){a=[];return}try{a=JSON.parse(hK($,"utf-8"))}catch{a=[]}}function l6($){if(u6=$,!p6($))fK($,{recursive:!0});cK()}function G7($,Z,J="geral",Y=[]){let Q=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:pK(),title:$.trim(),content:Z.trim(),category:J.toLowerCase().trim(),tags:V,createdAt:Q,updatedAt:Q};return a=[...a,G],U9(),G}function o6($,Z){let J=a.find((H)=>H.id===$);if(!J)return null;let Y=Z.content??J.content,Q=Z.title??J.title,X=Y.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],K=Q.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],V=Z.tags??J.tags,G=[...new Set([...V.map((H)=>H.toLowerCase()),...X,...K])];return a=a.map((H)=>H.id===$?{...H,title:Q.trim(),content:Y.trim(),category:(Z.category??H.category).toLowerCase().trim(),tags:G,updatedAt:new Date().toISOString()}:H),U9(),a.find((H)=>H.id===$)||null}function H7($){let Z=a.findIndex((J)=>J.id===$);if(Z===-1)return!1;return a=[...a.slice(0,Z),...a.slice(Z+1)],U9(),!0}function a6($){return a.find((Z)=>Z.id===$)||null}function W8($){let Z=$.toLowerCase().trim();if(!Z)return[...a];let J=Z.startsWith("#"),Y=Z.startsWith("@"),Q=J||Y?Z.slice(1):Z;return a.filter((X)=>{if(J)return X.tags.some((K)=>K.includes(Q));if(Y)return X.category.includes(Q);return X.title.toLowerCase().includes(Q)||X.content.toLowerCase().includes(Q)||X.category.toLowerCase().includes(Q)||X.tags.some((K)=>K.includes(Q))}).sort((X,K)=>new Date(K.updatedAt).getTime()-new Date(X.updatedAt).getTime())}function U8($=30,Z){let J=[...a];if(Z){let Y=Z.toLowerCase().trim();J=J.filter((Q)=>Q.category===Y)}return J.sort((Y,Q)=>new Date(Q.updatedAt).getTime()-new Date(Y.updatedAt).getTime()).slice(0,$)}function r6(){let $=new Map;for(let Z of a)$.set(Z.category,($.get(Z.category)||0)+1);return[...$.entries()].map(([Z,J])=>({category:Z,count:J})).sort((Z,J)=>J.count-Z.count)}function i6(){if(a.length===0)return"";let $=r6(),Z=["--- Materiais do Assistente ---"];for(let{category:J}of $){let Y=a.filter((Q)=>Q.category===J).sort((Q,X)=>new Date(X.updatedAt).getTime()-new Date(Q.updatedAt).getTime());Z.push(`
|
|
138
138
|
[${J}]`);for(let Q of Y){let X=Q.content.length>200?Q.content.slice(0,200).replace(/\n/g," ")+"...":Q.content.replace(/\n/g," "),K=Q.tags.length>0?` [${Q.tags.map((V)=>`#${V}`).join(" ")}]`:"";Z.push(` \u2022 ${Q.title}: ${X}${K}`)}}return Z.join(`
|
|
139
|
-
`)}function
|
|
139
|
+
`)}function C4($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((J)=>{let Y=new Date(J.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=J.tags.length>0?` [${J.tags.map((K)=>`#${K}`).join(" ")}]`:"",X=J.content.length>60?J.content.slice(0,60).replace(/\n/g," ")+"...":J.content.replace(/\n/g," ");return` [${Y}] (${J.category}) ${J.title} \u2014 ${X}${Q} {${J.id}}`});return`Materiais (${$.length}):
|
|
140
140
|
${Z.join(`
|
|
141
|
-
`)}`}function
|
|
141
|
+
`)}`}function n6($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),J=new Date($.updatedAt).toLocaleDateString("pt-BR"),Y=$.tags.length>0?`Tags: ${$.tags.map((X)=>`#${X}`).join(" ")}`:"",Q=Z===J?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${J}`;return`--- Material {${$.id}} ---
|
|
142
142
|
Titulo: ${$.title}
|
|
143
143
|
Categoria: ${$.category}
|
|
144
144
|
|
|
145
145
|
${$.content}
|
|
146
146
|
|
|
147
147
|
${Y}
|
|
148
|
-
${Q}`}function
|
|
148
|
+
${Q}`}function s6(){let $=r6();if($.length===0)return"Nenhuma categoria.";return`Categorias:
|
|
149
149
|
${$.map((J)=>` @${J.category} (${J.count})`).join(`
|
|
150
|
-
`)}`}function
|
|
150
|
+
`)}`}function pK(){return mK().slice(0,8)}r();import{existsSync as u4,mkdirSync as uK,readFileSync as B8,readdirSync as dK}from"fs";import{join as p4}from"path";import{createHash as lK}from"crypto";var $J=1,B9=400,oK=80,t6=1.5,e6=0.75,aK=10,rK=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"]),I1="",q7="",J$=[],a$={},r$=0,i$={},W7=!1,M9=()=>p4(q7,"rag-index.json");function ZJ($){if(I1=$,q7=p4($,"rag"),!u4(q7))uK(q7,{recursive:!0});Zz(),W7=!0}function U7(){return W7}function B7(){return{chunks:J$.length,sources:Object.keys(i$).length,builtAt:J$.length>0?Jz()?.builtAt??null:null}}function N7(){if(!W7)throw Error("Memory not initialized. Call initMemory() first.");let $=tK(),Z=0,J=0,Y={},Q=new Set;for(let[K,V]of Object.entries($)){let G=Yz(V);if(Y[K]=G,i$[K]!==G)Q.add(K)}let X=Object.keys(i$).filter((K)=>!(K in $));if(Q.size===0&&X.length===0)return{indexed:0,skipped:Object.keys($).length,total:J$.length};J$=J$.filter((K)=>{let V=`${K.source}:${K.sourceId}`;return!Q.has(V)&&!X.includes(V)});for(let K of Q){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 B=Qz(H,z,V),M=sK(V,H,z,B);J$=[...J$,...M],Z++}return J=Object.keys($).length-Z,eK(),i$=Y,$z(),{indexed:Z,skipped:J,total:J$.length}}function M7($,Z=3){if(J$.length===0)return[];let J=N9($);if(J.length===0)return[];return J$.map((Q)=>{let X=iK(J,Q),K=nK(J,Q),V=0.6*X+0.4*K;return{chunk:Q,score:V}}).filter((Q)=>Q.score>0).sort((Q,X)=>X.score-Q.score).slice(0,Math.min(Z,aK))}function C7($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((J,Y)=>{let Q=Xz(J.chunk.source),X=(J.score*100).toFixed(1),K=J.chunk.content.length>300?J.chunk.content.slice(0,300).replace(/\n/g," ")+"...":J.chunk.content.replace(/\n/g," ");return`[${Y+1}] ${Q}: ${J.chunk.title} (relevancia: ${X}%)
|
|
151
151
|
${K}`});return`Resultados da memoria (${$.length}):
|
|
152
152
|
|
|
153
153
|
${Z.join(`
|
|
154
154
|
|
|
155
|
-
`)}`}function
|
|
155
|
+
`)}`}function iK($,Z){let J=Z.tokens.length;if(J===0||r$===0)return 0;let Y=new Map;for(let X of Z.tokens)Y.set(X,(Y.get(X)??0)+1);let Q=0;for(let X of $){let K=Y.get(X)??0;if(K===0)continue;let V=a$[X]??0;if(V===0)continue;let G=K*(t6+1),H=K+t6*(1-e6+e6*(J/r$));Q+=V*(G/H)}return Q}function nK($,Z){let J=new Map;for(let H of $)J.set(H,(J.get(H)??0)+1);let Y=new Map;for(let H of Z.tokens)Y.set(H,(Y.get(H)??0)+1);let Q=new Set([...$,...Z.tokens]),X=0,K=0,V=0;for(let H of Q){let z=a$[H]??0,U=(J.get(H)??0)*z,B=(Y.get(H)??0)*z;X+=U*B,K+=U*U,V+=B*B}let G=Math.sqrt(K)*Math.sqrt(V);return G>0?X/G:0}function N9($){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&&!rK.has(Z))}function sK($,Z,J,Y){let Q=$.trim();if(Q.length===0)return[];if(Q.length<=B9)return[{id:`${Z}:${J}:0`,source:Z,sourceId:J,title:Y,content:Q,tokens:N9(Q)}];let X=[],K=0,V=0;while(K<Q.length){let G=Math.min(K+B9,Q.length),H=Q.slice(K,G);X.push({id:`${Z}:${J}:${V}`,source:Z,sourceId:J,title:Y,content:H,tokens:N9(H)}),K+=B9-oK,V++}return X}function tK(){let $={},Z=p4(I1,"memos.json");if(u4(Z))try{let X=JSON.parse(B8(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 J=p4(I1,"materials.json");if(u4(J))try{let X=JSON.parse(B8(J,"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
156
|
${G}
|
|
157
|
-
${V.content}${H}`}}catch{}let Y=
|
|
158
|
-
`)}}catch{}let Q=
|
|
157
|
+
${V.content}${H}`}}catch{}let Y=p4(I1,"decisions.json");if(u4(Y))try{let X=JSON.parse(B8(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(`
|
|
158
|
+
`)}}catch{}let Q=p4(I1,"sessions");if(u4(Q))try{let X=dK(Q,{withFileTypes:!0}).filter((K)=>K.isFile()&&K.name.endsWith(".json")&&!K.name.startsWith(".")).map((K)=>K.name);for(let K of X){let V=p4(Q,K);try{let G=JSON.parse(B8(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 U=z;return U.role==="assistant"&&typeof U.content==="string"&&U.content.length>50}).map((z)=>z.content).join(`
|
|
159
159
|
---
|
|
160
|
-
`);if(H.length>0)$[`session:${G.id}`]=H}catch{}}}catch{}return $}function
|
|
160
|
+
`);if(H.length>0)$[`session:${G.id}`]=H}catch{}}}catch{}return $}function eK(){let $=J$.length;if($===0){a$={},r$=0;return}let Z=new Map,J=0;for(let Q of J$){let X=new Set;for(let K of Q.tokens)if(!X.has(K))Z.set(K,(Z.get(K)??0)+1),X.add(K);J+=Q.tokens.length}r$=J/$;let Y={};for(let[Q,X]of Z)Y[Q]=Math.log(($-X+0.5)/(X+0.5)+1);a$=Y}function $z(){if(!W7)return;let $={chunks:J$,idf:a$,avgDocLength:r$,sourceHashes:i$,builtAt:new Date().toISOString(),version:$J};x(M9(),JSON.stringify($))}function Zz(){let $=M9();if(!u4($)){J$=[],a$={},r$=0,i$={};return}try{let Z=JSON.parse(B8($,"utf-8"));if(Z.version!==$J){J$=[],a$={},r$=0,i$={};return}J$=Z.chunks,a$=Z.idf,r$=Z.avgDocLength,i$=Z.sourceHashes}catch{J$=[],a$={},r$=0,i$={}}}function Jz(){let $=M9();if(!u4($))return null;try{return{builtAt:JSON.parse(B8($,"utf-8")).builtAt}}catch{return null}}function Yz($){return lK("sha256").update($).digest("hex").slice(0,16)}function Qz($,Z,J){switch($){case"material":{let Y=J.split(`
|
|
161
161
|
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"memo":return J.slice(0,60).replace(/\n/g," ")+(J.length>60?"...":"");case"decision":{let Y=J.split(`
|
|
162
|
-
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"session":return`Sessao ${Z}`;default:return Z}}function
|
|
162
|
+
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"session":return`Sessao ${Z}`;default:return Z}}function Xz($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}$$();A8();Y4();import{writeFileSync as Kz,unlinkSync as zz,existsSync as Vz}from"fs";import{join as Gz}from"path";import{tmpdir as Hz}from"os";import{randomUUID as qz}from"crypto";var Wz=30000,JJ=50000;var Uz=[{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)"}],Bz=[{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 C9($){for(let{pattern:Z,reason:J}of Uz)if(Z.test($))return{safe:!1,blocked:!0,reason:J};for(let{pattern:Z,reason:J}of Bz)if(Z.test($))return{safe:!1,blocked:!1,reason:J};return{safe:!0,blocked:!1}}async function j7($){if(!I)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>JJ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${JJ}).`,exitCode:1,duration:0};let Z=C9($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};let J=qz().slice(0,8),Y=Gz(Hz(),`smolerclaw-${J}.ps1`);try{Kz(Y,$,"utf-8");let Q=await xZ(Y,{timeout:Wz});return{stdout:Q.stdout,stderr:Q.timedOut?"Script timeout exceeded":Q.stderr,exitCode:Q.exitCode,duration:Q.duration}}finally{try{if(Vz(Y))zz(Y)}catch{}}}async function O7(){if(!I)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await Nz();if($.type==="text")return $;return await Mz()}async function Nz(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await t7($,{timeout:1e4});if(Z.timedOut)return{type:"error",text:"Clipboard read timeout."};let J=Z.stdout.trim();if(J==="___EMPTY___"||!J)return{type:"empty",text:""};return{type:"text",text:J}}catch{return{type:"error",text:"Failed to read clipboard text."}}}async function Mz(){try{let Z=await t7(`
|
|
163
163
|
Add-Type -AssemblyName System.Windows.Forms
|
|
164
164
|
$img = [System.Windows.Forms.Clipboard]::GetImage()
|
|
165
165
|
if (-not $img) {
|
|
@@ -210,7 +210,7 @@ try {
|
|
|
210
210
|
if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
|
|
211
211
|
}
|
|
212
212
|
`,{timeout:20000});if(Z.timedOut)return{type:"error",text:"OCR timeout."};let J=Z.stdout.trim();if(J==="___NO_IMAGE___")return{type:"empty",text:""};if(J==="___NO_TEXT___")return{type:"image",text:"(Imagem detectada no clipboard, mas sem texto reconhecivel)"};if(J.startsWith("___OCR_ERROR___"))return{type:"error",text:`OCR falhou: ${J.replace("___OCR_ERROR___: ","")}`};if(J)return{type:"image",text:`[OCR do clipboard]
|
|
213
|
-
${J}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function
|
|
213
|
+
${J}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function F7(){if(!I)return"Error: screen context analysis only available on Windows.";let $=`
|
|
214
214
|
$sig = @'
|
|
215
215
|
[DllImport("user32.dll")]
|
|
216
216
|
public static extern IntPtr GetForegroundWindow();
|
|
@@ -243,100 +243,156 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
|
|
|
243
243
|
$marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
|
|
244
244
|
Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
|
|
245
245
|
}
|
|
246
|
-
`;try{let Z=await
|
|
247
|
-
${Z}`.trim():K.notes}:K),
|
|
248
|
-
`).filter(Boolean),Q=[...new Set(Y.map((O)=>O.split("|||")[0]))],X=Y.map((O)=>O.split("|||")[1]||"").filter(Boolean),K=await
|
|
249
|
-
`)){let
|
|
250
|
-
`).filter(Boolean))
|
|
251
|
-
`)}function
|
|
246
|
+
`;try{let Z=await G$($,{timeout:15000});if(Z.timedOut)return"Error: screen context analysis timeout";let J=Z.stdout.trim();if(!J&&Z.stderr.trim())return`Error: ${Z.stderr.trim()}`;return J||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}r();import{existsSync as T$,mkdirSync as Cz,readFileSync as E7}from"fs";import{join as U$,basename as jz}from"path";import{randomUUID as Oz}from"crypto";var N8="",A$=[],P$=[],y$=[],j4=null,YJ=()=>U$(N8,"projects.json"),QJ=()=>U$(N8,"work-sessions.json"),XJ=()=>U$(N8,"opportunities.json"),KJ=()=>U$(N8,"active-project.txt");function Fz(){x(YJ(),JSON.stringify(A$,null,2))}function O9(){x(QJ(),JSON.stringify(P$,null,2))}function zJ(){x(XJ(),JSON.stringify(y$,null,2))}function Rz(){x(KJ(),j4||"")}function Ez(){A$=j9(YJ,[]),P$=j9(QJ,[]),y$=j9(XJ,[]);let $=KJ();if(T$($))try{j4=E7($,"utf-8").trim()||null}catch{j4=null}}function j9($,Z){let J=$();if(!T$(J))return Z;try{return JSON.parse(E7(J,"utf-8"))}catch(Y){if(process.env.DEBUG)console.error(`[projects] Failed to load ${J}: ${Y instanceof Error?Y.message:Y}`);return Z}}function VJ($){if(N8=$,!T$($))Cz($,{recursive:!0});Ez()}function F9($,Z,J="",Y=[],Q=[]){let X={id:R9(),name:$.trim(),path:Z.trim(),description:J.trim(),tags:Y.map((K)=>K.trim().toLowerCase()).filter(Boolean),techStack:Q.map((K)=>K.trim().toLowerCase()).filter(Boolean),createdAt:new Date().toISOString(),active:!0};return A$=[...A$,X],Fz(),X}function L7($){let Z=$.toLowerCase().trim();return A$.find((J)=>J.id===$)||A$.find((J)=>J.name.toLowerCase()===Z)||A$.find((J)=>J.name.toLowerCase().includes(Z))||null}function M8($=!1){return($?A$.filter((J)=>J.active):[...A$]).sort((J,Y)=>new Date(Y.createdAt).getTime()-new Date(J.createdAt).getTime())}function C8($){let Z=L7($);if(!Z)return null;return j4=Z.id,Rz(),Z}function O4(){if(!j4)return null;return A$.find(($)=>$.id===j4)||null}function D7($,Z=""){if(!A$.find((Q)=>Q.id===$))return null;Lz($);let Y={id:R9(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return P$=[...P$,Y],O9(),Y}function T7($,Z){let J=P$.find((K)=>K.id===$);if(!J||J.endedAt)return null;let Y=new Date,Q=new Date(J.startedAt),X=Math.round((Y.getTime()-Q.getTime())/60000);return P$=P$.map((K)=>K.id===$?{...K,endedAt:Y.toISOString(),durationMinutes:X,notes:Z?`${K.notes}
|
|
247
|
+
${Z}`.trim():K.notes}:K),O9(),P$.find((K)=>K.id===$)||null}function Lz($){let Z=new Date;P$=P$.map((J)=>{if(J.projectId===$&&!J.endedAt){let Y=new Date(J.startedAt),Q=Math.round((Z.getTime()-Y.getTime())/60000);return{...J,endedAt:Z.toISOString(),durationMinutes:Q}}return J}),O9()}function F4($){return P$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function Dz($,Z,J){let Y=J||new Date;return P$.filter((Q)=>{if(Q.projectId!==$)return!1;let X=new Date(Q.startedAt);return X>=Z&&X<=Y})}async function Tz($,Z="1 day ago"){if(!T$(U$($,".git")))return null;try{let J=await R7(["git","log",`--since=${Z}`,"--format=%an|||%s","--no-merges"],$);if(!J.ok||!J.stdout.trim())return{commits:0,authors:[],filesChanged:0,insertions:0,deletions:0,topFiles:[],messages:[]};let Y=J.stdout.trim().split(`
|
|
248
|
+
`).filter(Boolean),Q=[...new Set(Y.map((O)=>O.split("|||")[0]))],X=Y.map((O)=>O.split("|||")[1]||"").filter(Boolean),K=await R7(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),V=await R7(["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(`
|
|
249
|
+
`)){let L=O.match(/(\d+)\s+files?\s+changed/),T=O.match(/(\d+)\s+insertions?/),_=O.match(/(\d+)\s+deletions?/);if(L)G+=parseInt(L[1]);if(T)H+=parseInt(T[1]);if(_)z+=parseInt(_[1])}let U=await R7(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),B=new Map;if(U.ok&&U.stdout.trim())for(let O of U.stdout.trim().split(`
|
|
250
|
+
`).filter(Boolean))B.set(O,(B.get(O)||0)+1);let M=[...B.entries()].sort((O,L)=>L[1]-O[1]).slice(0,10).map(([O])=>O);return{commits:Y.length,authors:Q,filesChanged:G,insertions:H,deletions:z,topFiles:M,messages:X}}catch{return null}}async function R7($,Z){let J=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Y,Q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),X=await J.exited;return{stdout:Y.trim(),stderr:Q.trim(),ok:X===0}}function GJ($,Z,J,Y=[],Q="media",X=null){let K=new Date().toISOString(),V={id:R9(),title:$.trim(),description:Z.trim(),source:J.trim(),techRequired:Y.map((G)=>G.toLowerCase()),priority:Q,status:"nova",deadline:X,createdAt:K,updatedAt:K};return y$=[...y$,V],zJ(),V}function HJ($,Z){if(!y$.find((Y)=>Y.id===$))return null;return y$=y$.map((Y)=>Y.id===$?{...Y,status:Z,updatedAt:new Date().toISOString()}:Y),zJ(),y$.find((Y)=>Y.id===$)||null}function P7($,Z){let J=[...y$];if($)J=J.filter((Y)=>Y.status===$);if(Z&&Z.length>0){let Y=Z.map((Q)=>Q.toLowerCase());J=J.filter((Q)=>Q.techRequired.some((X)=>Y.includes(X)))}return J.sort((Y,Q)=>{let X={alta:3,media:2,baixa:1};return(X[Q.priority]||0)-(X[Y.priority]||0)})}async function A7($,Z="today",J="pt"){let Y=L7($);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 Tz(Y.path,K),G=Dz(Y.id,X),H=G.reduce((B,M)=>B+M.durationMinutes,0),z=0;try{let B=U$(N8,"tasks.json");if(T$(B))z=JSON.parse(E7(B,"utf-8")).filter((O)=>{if(!O.done)return!1;return new Date(O.createdAt)>=X}).length}catch{}let U=Pz(Y,Z,V,G,H,z,J);return{project:Y,period:Z,gitSummary:V,sessions:G,totalMinutes:H,completedTasks:z,markdown:U}}function Pz($,Z,J,Y,Q,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 U=Math.floor(Q/60),B=Q%60;if(G.push(`## ${V?"Tempo Trabalhado":"Time Tracked"}`),G.push(`- **${V?"Total":"Total"}:** ${U}h ${B}m`),G.push(`- **${V?"Sessoes":"Sessions"}:** ${Y.length}`),X>0)G.push(`- **${V?"Tarefas concluidas":"Tasks completed"}:** ${X}`);if(G.push(""),J&&J.commits>0){if(G.push(`## ${V?"Atividade Git":"Git Activity"}`),G.push(`- **Commits:** ${J.commits}`),J.authors.length>0)G.push(`- **${V?"Autores":"Authors"}:** ${J.authors.join(", ")}`);if(G.push(`- **${V?"Arquivos alterados":"Files changed"}:** ${J.filesChanged}`),G.push(`- **${V?"Linhas":"Lines"}:** +${J.insertions} / -${J.deletions}`),J.messages.length>0){G.push(""),G.push(`### ${V?"Commits recentes":"Recent commits"}`);for(let M of J.messages.slice(0,15))G.push(`- ${M}`)}if(J.topFiles.length>0){G.push(""),G.push(`### ${V?"Arquivos mais alterados":"Most changed files"}`);for(let M of J.topFiles.slice(0,8))G.push(`- \`${M}\``)}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 M of Y){let O=new Date(M.startedAt).toLocaleTimeString(V?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),L=M.durationMinutes>0?`${M.durationMinutes}m`:V?"em andamento":"ongoing",T=M.notes?` \u2014 ${M.notes}`:"";G.push(`- ${O} (${L})${T}`)}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(`
|
|
251
|
+
`)}function I7($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((J)=>{let Y=J.id===j4?" [ATIVO]":"",Q=J.active?"":" (inativo)",X=J.techStack.length>0?` [${J.techStack.join(", ")}]`:"";return` ${J.name}${Y}${Q}${X} \u2014 ${J.path} {${J.id}}`});return`Projetos (${$.length}):
|
|
252
252
|
${Z.join(`
|
|
253
|
-
`)}`}function
|
|
254
|
-
`)}function
|
|
253
|
+
`)}`}function x7($){let Z=$.id===j4?" [ATIVO]":"",J=[`--- Projeto {${$.id}}${Z} ---`,`Nome: ${$.name}`,`Caminho: ${$.path}`];if($.description)J.push(`Descricao: ${$.description}`);if($.techStack.length>0)J.push(`Tech: ${$.techStack.join(", ")}`);if($.tags.length>0)J.push(`Tags: ${$.tags.map((Q)=>`#${Q}`).join(" ")}`);J.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),J.push(`Status: ${$.active?"ativo":"inativo"}`);let Y=F4($.id);if(Y){let Q=new Date(Y.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});J.push(`Sessao aberta: desde ${Q}`)}return J.join(`
|
|
254
|
+
`)}function S7($){if($.length===0)return"Nenhuma oportunidade encontrada.";let Z=$.map((J)=>{let Y={alta:"!!!",media:"!!",baixa:"!"}[J.priority],Q=J.techRequired.length>0?` [${J.techRequired.join(", ")}]`:"",X=J.deadline?` \u2014 prazo: ${J.deadline}`:"";return` ${Y} (${J.status}) ${J.title}${Q}${X} \u2014 ${J.source} {${J.id}}`});return`Oportunidades (${$.length}):
|
|
255
255
|
${Z.join(`
|
|
256
|
-
`)}`}function
|
|
257
|
-
`)}function
|
|
258
|
-
`);Q.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${
|
|
259
|
-
`)}function
|
|
260
|
-
`)}function
|
|
261
|
-
`)}function
|
|
262
|
-
`)}
|
|
263
|
-
`)}function
|
|
264
|
-
${Z}`:$,Y=
|
|
265
|
-
`)}function
|
|
256
|
+
`)}`}function w7(){let $=O4();if(!$)return"";let Z=F4($.id),J=y$.filter((Q)=>Q.status==="nova").length,Y=["--- Projetos ---"];if(Y.push(`Projeto ativo: ${$.name} (${$.path})`),Z){let Q=new Date(Z.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Y.push(`Sessao aberta desde ${Q}`)}if(J>0)Y.push(`${J} oportunidade(s) nova(s) pendente(s)`);return Y.join(`
|
|
257
|
+
`)}function k7($){let Z=A$.find((Q)=>Q.path===$);if(Z)return Z;if(!T$(U$($,".git")))return null;let J=[];if(T$(U$($,"package.json")))try{let Q=JSON.parse(E7(U$($,"package.json"),"utf-8"));if(Q.dependencies?.typescript||Q.devDependencies?.typescript)J.push("typescript");if(Q.dependencies?.react)J.push("react");if(Q.dependencies?.next)J.push("nextjs");if(Q.dependencies?.vue)J.push("vue");if(T$(U$($,"bun.lock")))J.push("bun");else J.push("node")}catch{}if(T$(U$($,"Cargo.toml")))J.push("rust");if(T$(U$($,"go.mod")))J.push("go");if(T$(U$($,"requirements.txt"))||T$(U$($,"pyproject.toml")))J.push("python");let Y=jz($);return F9(Y,$,"",[],J)}function R9(){return Oz().slice(0,8)}r();$$();import{existsSync as D9,mkdirSync as Az,readFileSync as UJ}from"fs";import{join as BJ,basename as Iz}from"path";var NJ=2,MJ="pitwall-baselines.json",xz=0.1,Sz=0.05,wz=5000000,kz=512000,qJ=2048,bz=120000,_7="",e=[];function CJ($){if(_7=$,!D9($))Az($,{recursive:!0});cz()}async function WJ($,Z){let Y=[...i4(),$],Q=process.cpuUsage(),X=Bun.nanoseconds(),K=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe",cwd:Z}),V=setTimeout(()=>K.kill(),bz),G=K.pid,H=yz(G),[,z]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]),U=await K.exited;clearTimeout(V);let B=Bun.nanoseconds(),M=process.cpuUsage(Q),O=await H,L=z.length>qJ?`...${z.slice(-qJ)}`:z;return{durationNs:B-X,peakMemoryBytes:O,cpuUserUs:M.user,cpuSystemUs:M.system,exitCode:U,stderr:L.trim()}}async function T9($,Z={}){let J=Z.cwd||process.cwd(),Y=Math.min(Math.max(Z.iterations||1,1),10),Q=Z.scriptKey||mz($);if(Z.warmup&&Y>1)await WJ($,J);let X=[];for(let z=0;z<Y;z++)X.push(await WJ($,J));let K=X[X.length-1],V=X.map((z)=>z.durationNs),G={durationNs:E9(V),peakMemoryBytes:Math.max(...X.map((z)=>z.peakMemoryBytes)),cpuUserUs:E9(X.map((z)=>z.cpuUserUs)),cpuSystemUs:E9(X.map((z)=>z.cpuSystemUs))},H=Y>1?{min:Math.min(...V),max:Math.max(...V),median:G.durationNs,stddev:gz(V)}:null;return{scriptKey:Q,command:$,metrics:G,spread:H,exitCode:K.exitCode,stderr:K.stderr,timestamp:new Date().toISOString(),iterations:Y}}async function yz($){try{if(I){let Z=`(Get-Process -Id ${$} -ErrorAction SilentlyContinue).PeakWorkingSet64`,J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>J.kill(),5000),Q=await new Response(J.stdout).text();await J.exited,clearTimeout(Y);let X=parseInt(Q.trim(),10);if(!isNaN(X)&&X>0)return X}else{let Z=`/proc/${$}/status`;if(D9(Z)){let Y=UJ(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Y)return parseInt(Y[1],10)*1024}}}catch{}return process.memoryUsage().rss}function jJ($,Z=[]){let J=e.find((X)=>X.scriptKey===$.scriptKey),Y=new Date().toISOString();if(J){let X=J.runs+1,K={durationNs:Math.round((J.metrics.durationNs*J.runs+$.metrics.durationNs)/X),peakMemoryBytes:Math.round((J.metrics.peakMemoryBytes*J.runs+$.metrics.peakMemoryBytes)/X),cpuUserUs:Math.round((J.metrics.cpuUserUs*J.runs+$.metrics.cpuUserUs)/X),cpuSystemUs:Math.round((J.metrics.cpuSystemUs*J.runs+$.metrics.cpuSystemUs)/X)},V={...J,metrics:K,spread:$.spread||J.spread,updatedAt:Y,runs:X,tags:[...new Set([...J.tags,...Z])]};return e=e.map((G)=>G.scriptKey===$.scriptKey?V:G),v7(),V}let Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return e=[...e,Q],v7(),Q}function _z($){return e.find((Z)=>Z.scriptKey===$)||null}function OJ(){return[...e].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function P9($){let Z=e.findIndex((J)=>J.scriptKey===$);if(Z===-1)return!1;return e=[...e.slice(0,Z),...e.slice(Z+1)],v7(),!0}function FJ($,Z=[]){P9($.scriptKey);let J=new Date().toISOString(),Y={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:J,updatedAt:J,runs:1,tags:Z};return e=[...e,Y],v7(),Y}function A9($){let Z=_z($.scriptKey),J=[];if(Z)J.push(b7("duration",Z.metrics.durationNs,$.metrics.durationNs,wz),b7("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,kz),b7("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),b7("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Y=J.some((X)=>X.severity==="regression"),Q=hz($,Z,J,Y);return{run:$,baseline:Z,alerts:J,hasRegression:Y,markdown:Q}}function b7($,Z,J,Y){let Q=J-Z;if(Z===0||Math.abs(Q)<Y)return{metric:$,baselineValue:Z,currentValue:J,deltaPercent:0,absoluteDelta:Q,severity:"ok"};let X=Q/Z,K="ok";if(X>xz)K="regression";else if(X>Sz)K="warning";return{metric:$,baselineValue:Z,currentValue:J,deltaPercent:Math.round(X*1e4)/100,absoluteDelta:Q,severity:K}}function n$($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function L9($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function y7($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function vz($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function fz($){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 hz($,Z,J,Y){let Q=[];if(Y)Q.push("=== PIT WALL: REGRESSAO DETECTADA ===");else Q.push("=== Pit Wall: Relatorio de Performance ===");if(Q.push(`Script: ${$.scriptKey}`),Q.push(`Comando: ${$.command}`),Q.push(`Execucoes: ${$.iterations}`),$.exitCode!==0)Q.push(`Exit code: ${$.exitCode} (FALHA)`);if(Q.push(""),Q.push("--- Metricas Atuais ---"),Q.push(` Duracao: ${n$($.metrics.durationNs)}`),Q.push(` Memoria: ${L9($.metrics.peakMemoryBytes)}`),Q.push(` CPU (user): ${y7($.metrics.cpuUserUs)}`),Q.push(` CPU (sys): ${y7($.metrics.cpuSystemUs)}`),$.spread){Q.push(""),Q.push("--- Dispersao ---"),Q.push(` Min: ${n$($.spread.min)}`),Q.push(` Max: ${n$($.spread.max)}`),Q.push(` Mediana: ${n$($.spread.median)}`),Q.push(` Stddev: ${n$($.spread.stddev)}`);let X=$.spread.median>0?($.spread.stddev/$.spread.median*100).toFixed(1):"0";if(Q.push(` CV: ${X}%`),parseFloat(X)>15)Q.push(" (!) Alta variancia \u2014 resultados podem ser inst\xE1veis")}if($.exitCode!==0&&$.stderr)Q.push(""),Q.push("--- Stderr ---"),Q.push($.stderr.slice(0,500));if(Q.push(""),!Z)return Q.push("Nenhum baseline salvo para este script."),Q.push("Use pitwall_save_baseline para definir o baseline atual."),Q.join(`
|
|
258
|
+
`);Q.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${RJ(Z.updatedAt)}) ---`),Q.push(` Duracao: ${n$(Z.metrics.durationNs)}`),Q.push(` Memoria: ${L9(Z.metrics.peakMemoryBytes)}`),Q.push(` CPU (user): ${y7(Z.metrics.cpuUserUs)}`),Q.push(` CPU (sys): ${y7(Z.metrics.cpuSystemUs)}`),Q.push(""),Q.push("--- Comparacao ---");for(let X of J){let K=X.deltaPercent>=0?"+":"",V=fz(X.metric);Q.push(` ${vz(X.severity)} ${V}: ${K}${X.deltaPercent}%`)}if(Q.push(""),Y)Q.push("*** ALERTA: Regressao de performance > 10% detectada! ***"),Q.push("Revise as mudancas recentes no codigo.");else if(J.some((X)=>X.severity==="warning"))Q.push("Atencao: algumas metricas estao proximas do limite (5-10%).");else Q.push("Performance dentro do esperado.");return Q.join(`
|
|
259
|
+
`)}function RJ($){let Z=Date.now()-new Date($).getTime(),J=Math.floor(Z/60000);if(J<60)return`ha ${J}min`;let Y=Math.floor(J/60);if(Y<24)return`ha ${Y}h`;return`ha ${Math.floor(Y/24)}d`}function EJ($){if($.length===0)return"Nenhum baseline salvo no Pit Wall.";let Z=["=== Pit Wall: Baselines ===",""];for(let J of $){let Y=J.tags.length>0?` [${J.tags.join(", ")}]`:"",Q=RJ(J.updatedAt);if(Z.push(` ${J.scriptKey}`),Z.push(` Duracao: ${n$(J.metrics.durationNs)} | Memoria: ${L9(J.metrics.peakMemoryBytes)} | ${J.runs} runs | ${Q}${Y}`),J.spread){let X=J.spread.median>0?(J.spread.stddev/J.spread.median*100).toFixed(1):"0";Z.push(` Spread: ${n$(J.spread.min)} ~ ${n$(J.spread.max)} (CV ${X}%)`)}Z.push("")}return Z.join(`
|
|
260
|
+
`)}function E9($){if($.length===0)return 0;let Z=[...$].sort((Y,Q)=>Y-Q),J=Math.floor(Z.length/2);return Z.length%2!==0?Z[J]:Math.round((Z[J-1]+Z[J])/2)}function gz($){if($.length<2)return 0;let Z=$.reduce((Y,Q)=>Y+Q,0)/$.length,J=$.reduce((Y,Q)=>Y+(Q-Z)**2,0)/($.length-1);return Math.round(Math.sqrt(J))}function mz($){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 Iz(Z[0])}function cz(){let $=BJ(_7,MJ);if(!D9($)){e=[];return}try{let Z=JSON.parse(UJ($,"utf-8"));if(Z.version!==NJ&&Z.version!==1){e=[];return}e=(Z.baselines||[]).map(pz)}catch{e=[]}}function pz($){let{durationMs:Z,...J}=$.metrics;return{...$,metrics:J,spread:$.spread||null}}function v7(){if(!_7)return;let $=BJ(_7,MJ);x($,JSON.stringify({baselines:e,version:NJ},null,2))}$$();import{readdirSync as uz,readFileSync as dz,lstatSync as lz}from"fs";import{join as oz,resolve as x1,relative as I9,dirname as az,extname as rz}from"path";var iz=[".ts",".tsx",".mts",".cts"],nz=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],sz=new Set(P8),LJ=5000,tz=5000,DJ=new Map;function ez($){let Z=DJ.get($);if(Z&&Date.now()-Z.ts<tz)return Z.graph;return null}function $V($,Z){DJ.set($,{graph:Z,ts:Date.now()})}var ZV=[/^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 JV($){let Z=new Set,J=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Y of ZV){Y.lastIndex=0;let Q;while((Q=Y.exec(J))!==null){let X=Q[1];if(X.startsWith("./")||X.startsWith("../"))Z.add(X)}}return[...Z]}function YV($){let Z=[];function J(Y){if(Z.length>=LJ)return;let Q;try{Q=uz(Y)}catch{return}for(let X of Q){if(Z.length>=LJ)return;if(sz.has(X))continue;let K=oz(Y,X),V;try{V=lz(K)}catch{continue}if(V.isSymbolicLink())continue;if(V.isDirectory())J(K);else if(V.isFile()&&iz.includes(rz(X)))Z.push(K)}}return J($),Z}function QV($,Z,J){let Y=az(Z),Q=x1(Y,$);if(J.has(Q))return Q;for(let X of nz){let K=Q+X;if(J.has(K))return K}return null}function x9($){let Z=x1($),J=ez(Z);if(J)return J;let Y=YV(Z),Q=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=dz(G,"utf-8")}catch{continue}let z=JV(H),U=X.get(G);for(let B of z){let M=QV(B,G,Q);if(M){U.add(M);let O=K.get(M)||new Set;O.add(G),K.set(M,O)}}}let V={imports:X,importedBy:K,files:Y,root:Z};return $V(Z,V),V}function S9($,Z){let J=x1(Z),Y=$.importedBy.get(J)||new Set,Q=[...Y],X=new Set([J]),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:L}=K[z++];if(L>G)G=L;if(!Y.has(O))H.push(O);let T=$.importedBy.get(O)||new Set;for(let _ of T)if(!X.has(_))X.add(_),V.set(_,L+1),K.push({file:_,depth:L+1})}let U=TJ(J,$.importedBy,new Set,0),B=(O)=>I9($.root,O).replace(/\\/g,"/"),M=new Map;for(let[O,L]of V)M.set(B(O),L);return{target:B(J),directDependents:Q.map(B),transitiveDependents:H.map(B),depthMap:M,totalAffected:Q.length+H.length,depth:G,tree:PJ(U,$.root)}}function TJ($,Z,J,Y){J.add($);let Q=Z.get($)||new Set,X=[];for(let K of Q)if(!J.has(K))X.push(TJ(K,Z,J,Y+1));return{file:$,depth:Y,children:X}}function PJ($,Z){return{file:I9(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((J)=>PJ(J,Z))}}function AJ($,Z){let J=x1(Z),Y=S9($,Z),Q=(O)=>x1($.root,O),X=new Set([...Y.directDependents.map(Q),...Y.transitiveDependents.map(Q)]);X.add(J);let K=new Map;for(let O of X)K.set(O,0);for(let O of X){let L=$.importedBy.get(O)||new Set;for(let T of L)if(X.has(T)&&T!==O)K.set(O,(K.get(O)||0)+1)}let V=[];for(let[O,L]of K)if(L===0&&O!==J)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 L=$.imports.get(O)||new Set;for(let T of L)if(X.has(T)&&!H.has(T)&&T!==J){let _=(K.get(T)||1)-1;if(K.set(T,_),_===0)V.push(T)}}for(let O of X)if(!H.has(O)&&O!==J)G.push(O);let U=[J,...G],B=(O)=>I9($.root,O).replace(/\\/g,"/"),M=U.map((O)=>{let T=[...$.imports.get(O)||new Set].filter((s)=>X.has(s)).map(B),_=B(O),V$=O===J?0:Y.depthMap.get(_)||1;return{file:_,depth:V$,dependsOn:T}});return{target:B(J),order:M,totalFiles:M.length}}function IJ($){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 J of $.directDependents)Z.push(` ${J}`);Z.push("")}if($.transitiveDependents.length>0){Z.push(`--- Dependentes transitivos (${$.transitiveDependents.length}) ---`);for(let J of $.transitiveDependents){let Y=$.depthMap.get(J)||0;Z.push(` ${J} (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 ---"),xJ($.tree,Z,"",!0),Z.join(`
|
|
261
|
+
`)}function xJ($,Z,J,Y){let Q=Y?"\u2514\u2500 ":"\u251C\u2500 ",X=$.depth===0?`[ALVO] ${$.file}`:$.file;Z.push(`${J}${Q}${X}`);let K=J+(Y?" ":"\u2502 ");for(let V=0;V<$.children.length;V++)xJ($.children[V],Z,K,V===$.children.length-1)}function SJ($){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 J=0;J<$.order.length;J++){let Y=$.order[J],Q=`${J+1}`.padStart(3),X=Y.depth===0?"[ALVO]":`[depth ${Y.depth}]`;if(Z.push(` ${Q}. ${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(`
|
|
262
|
+
`)}r();import{existsSync as w9,mkdirSync as XV,readFileSync as kJ}from"fs";import{join as bJ}from"path";import{randomUUID as KV}from"crypto";var k9=[{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"}],b9="",s$=[],t$=[],yJ=()=>bJ(b9,"engine-tradeoffs.json"),_J=()=>bJ(b9,"engine-incidents.json");function zV(){x(yJ(),JSON.stringify(s$,null,2))}function VV(){x(_J(),JSON.stringify(t$,null,2))}function GV(){let $=yJ();if(!w9($)){s$=[];return}try{s$=JSON.parse(kJ($,"utf-8"))}catch{s$=[]}}function HV(){let $=_J();if(!w9($)){t$=[];return}try{t$=JSON.parse(kJ($,"utf-8"))}catch{t$=[]}}function vJ($){if(b9=$,!w9($))XV($,{recursive:!0});GV(),HV()}function fJ($,Z,J=k9){let Y=J.reduce((z,U)=>z+U.weight,0);if(Math.abs(Y-1)>0.01)J=J.map((U)=>({...U,weight:U.weight/Y}));let Q={};for(let z of Z){let U=0;for(let B of J){let M=z.scores[B.name]??3;U+=M*B.weight}Q[z.name]=Math.round(U*100)/100}let K=Object.entries(Q).sort(([,z],[,U])=>U-z)[0]?.[0]||Z[0]?.name||"N/A",V=Z.find((z)=>z.name===K),G=qV($,Z,J,Q,K,V),H={id:aJ(),context:$,options:Z,criteria:J,recommendation:K,weightedScores:Q,adr:G,createdAt:new Date().toISOString()};return s$=[...s$,H],zV(),H}function qV($,Z,J,Y,Q,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 U of $.constraints)G.push(`- ${U}`);G.push("")}if($.stakeholders.length>0){G.push("### Stakeholders"),G.push("");for(let U of $.stakeholders)G.push(`- ${U}`);G.push("")}G.push("## Options Considered"),G.push("");for(let U of Z){if(G.push(`### ${U.name}`),G.push(""),G.push(U.description),G.push(""),U.pros.length>0){G.push("**Pros:**");for(let B of U.pros)G.push(`- ${B}`);G.push("")}if(U.cons.length>0){G.push("**Cons:**");for(let B of U.cons)G.push(`- ${B}`);G.push("")}}G.push("## Evaluation Matrix"),G.push("");let H=["Criterion (Weight)",...Z.map((U)=>U.name)];G.push(`| ${H.join(" | ")} |`),G.push(`| ${H.map(()=>"---").join(" | ")} |`);for(let U of J){let B=Math.round(U.weight*100),M=[`${U.name} (${B}%)`,...Z.map((O)=>{return`${O.scores[U.name]??3}/5`})];G.push(`| ${M.join(" | ")} |`)}let z=["**Weighted Total**",...Z.map((U)=>`**${Y[U.name]?.toFixed(2)??"0.00"}**`)];if(G.push(`| ${z.join(" | ")} |`),G.push(""),G.push("## Decision"),G.push(""),G.push(`**Recommended:** ${Q}`),G.push(""),X){if(G.push(`Based on the weighted evaluation, **${Q}** scores highest with a weighted total of ${Y[Q]?.toFixed(2)}.`),G.push(""),X.pros.length>0){G.push("Key advantages:");for(let U of X.pros.slice(0,3))G.push(`- ${U}`);G.push("")}}if(G.push("## Consequences"),G.push(""),G.push("### Positive"),G.push(""),X&&X.pros.length>0)for(let U of X.pros)G.push(`- ${U}`);else G.push("- *To be determined based on implementation*");if(G.push(""),G.push("### Negative"),G.push(""),X&&X.cons.length>0)for(let U of X.cons)G.push(`- ${U}`);else G.push("- *To be determined based on implementation*");return G.push(""),G.push("---"),G.push(""),G.push("*Generated by Decision Engine*"),G.join(`
|
|
263
|
+
`)}function wJ($){let Z=$.toLowerCase(),J=[/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 J){let H=Z.match(G);if(H)for(let z of H)Y.add(z.toLowerCase())}let Q=/[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/g,X=$.match(Q)||[];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 WV($,Z){if($.length===0||Z.length===0)return 0;let J=new Set($),Y=new Set(Z),Q=0;for(let K of J)if(Y.has(K))Q++;let X=J.size+Y.size-Q;return X>0?Q/X:0}function hJ($,Z){let J=Z?`${$}
|
|
264
|
+
${Z}`:$,Y=wJ(J),Q=[];for(let G of t$){let H=`${G.title} ${G.description} ${G.stacktrace||""} ${G.rootCause} ${G.solution}`,z=wJ(H),U=WV(Y,z);if(U>0.1){let B=Y.filter((L)=>z.includes(L)),M=[];for(let L of G.relatedDecisions){let T=m4(L);if(T.length>0)M.push(T[0])}let O=[];if(G.solution)O.push(`Apply solution: ${G.solution}`);if(G.rootCause)O.push(`Investigate root cause: ${G.rootCause}`);for(let L of M)O.push(`Review decision: ${L.title}`);Q.push({incident:G,similarity:U,matchedKeywords:B,relatedDecisions:M,suggestedActions:O})}}Q.sort((G,H)=>H.similarity-G.similarity);let X=m4($.slice(0,50)),K=W8($.slice(0,50)),V=UV($,Q,X,K);return{query:$,matches:Q.slice(0,5),materialsFound:K.slice(0,5),summary:V}}function UV($,Z,J,Y){let Q=["# Incident Correlation Report",""];if(Q.push("## Query"),Q.push(""),Q.push("```"),Q.push($.slice(0,500)),Q.push("```"),Q.push(""),Z.length>0){Q.push("## Similar Past Incidents"),Q.push("");for(let X of Z.slice(0,3)){let K=Math.round(X.similarity*100);if(Q.push(`### ${X.incident.title} (${K}% match)`),Q.push(""),Q.push(`**Root Cause:** ${X.incident.rootCause}`),Q.push(""),Q.push(`**Solution:** ${X.incident.solution}`),Q.push(""),X.matchedKeywords.length>0)Q.push(`**Matched Keywords:** ${X.matchedKeywords.slice(0,5).join(", ")}`),Q.push("");if(X.suggestedActions.length>0){Q.push("**Suggested Actions:**");for(let V of X.suggestedActions.slice(0,3))Q.push(`- ${V}`);Q.push("")}}}else Q.push("## Similar Past Incidents"),Q.push(""),Q.push("*No matching incidents found in the database.*"),Q.push("");if(J.length>0){Q.push("## Related Decisions"),Q.push("");for(let X of J.slice(0,3))Q.push(`- **${X.title}** (${X.date.split("T")[0]}): ${X.chosen}`);Q.push("")}if(Y.length>0){Q.push("## Relevant Materials"),Q.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," ");Q.push(`- **${X.title}** (${X.category}): ${K}`)}Q.push("")}return Q.push("---"),Q.push(""),Q.push("*Generated by Decision Engine Post-Mortem Correlator*"),Q.join(`
|
|
265
|
+
`)}function gJ($,Z,J,Y,Q,X=[],K=[]){let V={id:aJ(),title:$.trim(),description:Z.trim(),stacktrace:Q?.trim(),rootCause:J.trim(),solution:Y.trim(),relatedDecisions:X,tags:K.map((G)=>G.toLowerCase()),createdAt:new Date().toISOString()};return t$=[...t$,V],VV(),V}function mJ($){let Z=$.toLowerCase();return t$.filter((J)=>J.title.toLowerCase().includes(Z)||J.description.toLowerCase().includes(Z)||J.rootCause.toLowerCase().includes(Z)||J.solution.toLowerCase().includes(Z)||J.tags.some((Y)=>Y.includes(Z))).sort((J,Y)=>new Date(Y.createdAt).getTime()-new Date(J.createdAt).getTime())}function cJ($=10){return[...t$].sort((Z,J)=>new Date(J.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function pJ($=10){return[...s$].sort((Z,J)=>new Date(J.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function uJ($){let Z=$.toLowerCase();return s$.filter((J)=>J.context.title.toLowerCase().includes(Z)||J.context.background.toLowerCase().includes(Z)||J.recommendation.toLowerCase().includes(Z)||J.options.some((Y)=>Y.name.toLowerCase().includes(Z)||Y.description.toLowerCase().includes(Z))).sort((J,Y)=>new Date(Y.createdAt).getTime()-new Date(J.createdAt).getTime())}function dJ($){return s$.find((Z)=>Z.id===$)||null}function lJ($){if($.length===0)return"Nenhuma analise de trade-off registrada.";let Z=$.map((J)=>{return` [${new Date(J.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}] ${J.context.title} \u2192 ${J.recommendation} {${J.id}}`});return`Trade-offs (${$.length}):
|
|
266
266
|
${Z.join(`
|
|
267
|
-
`)}`}function
|
|
267
|
+
`)}`}function oJ($){if($.length===0)return"Nenhum incidente registrado.";let Z=$.map((J)=>{let Y=new Date(J.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=J.resolvedAt?"\u2713":"\u25CB",X=J.tags.length>0?` [${J.tags.join(", ")}]`:"";return` ${Q} [${Y}] ${J.title}${X} {${J.id}}`});return`Incidentes (${$.length}):
|
|
268
268
|
${Z.join(`
|
|
269
|
-
`)}`}function
|
|
270
|
-
`),$}function
|
|
271
|
-
`)});return["# Manual de Uso Otimizado","",`Baseado em ${
|
|
272
|
-
`)}var
|
|
273
|
-
`)}function
|
|
269
|
+
`)}`}function aJ(){return KV().slice(0,8)}r();import{existsSync as w1,mkdirSync as rJ,readFileSync as y9,readdirSync as BV,writeFileSync as iJ}from"fs";import{join as l4}from"path";import{homedir as NV}from"os";import{createHash as MV}from"crypto";var CV=20,nJ=3,jV=0.6,OV={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"]},FV={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."}},S1="",R4="",R$={events:[],sessionStart:Date.now()},d4=new Map,e$=[],F$=[],j8=!1,sJ=null,tJ=()=>l4(S1,"usage-patterns.json"),eJ=()=>l4(S1,"insights.json");function $3($,Z){if(S1=l4($,"docs-engine"),R4=l4(NV(),".config","smolerclaw","materials","manual"),sJ=Z||null,!w1(S1))rJ(S1,{recursive:!0});if(!w1(R4))rJ(R4,{recursive:!0});bV(),_V(),vV(),R$={events:[],sessionStart:Date.now()},j8=!0}function _9($){if(!j8)return;let Z={...$,timestamp:Date.now()},J=[...R$.events,Z].slice(-CV);R$={...R$,events:J},RV(Z),setImmediate(()=>EV(Z))}function RV($){let Z=`${$.type}:${$.name}`,J=d4.get(Z);if(J){let Y=J.count+1,Q=J.avgDurationMs?(J.avgDurationMs*J.count+($.durationMs||0))/Y:$.durationMs||0;d4.set(Z,{action:Z,count:Y,avgDurationMs:Q,lastUsed:$.timestamp})}else d4.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function EV($){let Z=R$.events.slice(-5).map((J)=>J.name).join(" ");for(let[J,{pattern:Y,suggestion:Q}]of Object.entries(FV))if(Y.test(Z)){if(!e$.find((K)=>K.type==="inefficient_pattern"&&K.relatedActions.includes($.name)&&Date.now()-new Date(K.createdAt).getTime()<3600000)){let K={id:o4(),type:"inefficient_pattern",title:`Padrao detectado: ${J.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:Q,relatedActions:R$.events.slice(-5).map((V)=>V.name),confidence:0.8,createdAt:new Date().toISOString()};Z3(K)}}}async function k1(){if(!j8)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=LV();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let J=DV();$.insightsGenerated+=J.length;let Y=TV();$.insightsGenerated+=Y.length;for(let Q of[...Z,...J,...Y])if(Z3(Q),await AV(Q))$.manualUpdates++;return kV(),yV(),R$={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
|
|
270
|
+
`),$}function LV(){let $=[],Z=PV(R$.events);for(let J of Z)if(J.count>=nJ){let Y={id:o4(),type:"repetitive_task",title:`Tarefa repetitiva: ${J.actions.slice(0,3).join(" -> ")}`,description:`Este padrao de acoes foi executado ${J.count} vezes nesta sessao.`,recommendation:"Considere criar um workflow para automatizar esta sequencia.",relatedActions:J.actions,confidence:Math.min(0.5+J.count*0.1,1),createdAt:new Date().toISOString()};$.push(Y)}return $}function DV(){let $=[],Z=new Set;for(let J of R$.events)if(J.type==="tool:executed")Z.add(J.name);for(let[J,Y]of Object.entries(OV)){let Q=Y.filter((K)=>Z.has(K)),X=Y.filter((K)=>!Z.has(K));if(Q.length>0&&X.length>0){let K=Q.length/Y.length;if(K>=jV){let V={id:o4(),type:"underutilized_tool",title:`Ferramentas subutilizadas: ${J}`,description:`Voce usa ${Q.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 TV(){let $=[];if(Date.now()-R$.sessionStart>1800000&&!R$.events.some((Y)=>Y.name==="save_memo"))$.push({id:o4(),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 J=R$.events.filter((Y)=>Y.name==="run_command").length;if(J>=5&&!R$.events.some((Y)=>Y.name.includes("workflow")))$.push({id:o4(),type:"tip",title:"Dica: Automatize com workflows",description:`${J} 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 PV($){let Z=new Map,J=$.map((Y)=>Y.name);for(let Y=2;Y<=4;Y++)for(let Q=0;Q<=J.length-Y;Q++){let X=J.slice(Q,Q+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>=nJ)}function Z3($){if(!e$.some((J)=>J.type===$.type&&J.title===$.title&&Date.now()-new Date(J.createdAt).getTime()<86400000))e$=[...e$,$],sJ?.($)}function J3($=5){return[...e$].sort((Z,J)=>new Date(J.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function AV($){try{let Z=SV($.type),J=`${$.id}.md`,Y=l4(R4,J),Q=F$.find((G)=>G.id===$.id),X=Q?Q.version+1:1,K={id:$.id,title:$.title,category:Z,content:xV($),tags:wV($),source:"auto_generated",version:X,createdAt:Q?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},V=K3(K);return iJ(Y,V,"utf-8"),F$=F$.filter((G)=>G.id!==K.id),F$=[...F$,K],!0}catch{return!1}}async function Y3($,Z,J="best_practice",Y=[]){if(!j8)return{success:!1,path:""};try{let Q=o4(),X=`${hV($)}-${Q.slice(0,4)}.md`,K=l4(R4,X),V={id:Q,title:$,category:J,content:Z,tags:Y,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},G=K3(V);return iJ(K,G,"utf-8"),F$=[...F$,V],{success:!0,path:K,entry:V}}catch{return{success:!1,path:""}}}function IV($){let J=$.toLowerCase().split(/\s+/).filter((Y)=>Y.length>2);return F$.map((Y)=>{let Q=0,X=`${Y.title} ${Y.content} ${Y.tags.join(" ")}`.toLowerCase();for(let K of J)if(X.includes(K))Q++;return{entry:Y,score:Q}}).filter((Y)=>Y.score>0).sort((Y,Q)=>Q.score-Y.score).map((Y)=>Y.entry)}function Q3($){let Z=$?IV($):F$;if(Z.length===0)return"Nenhum conteudo encontrado no manual. Execute /reflect para gerar insights baseados no seu uso.";let J=Z.slice(0,5).map((Y)=>{let Q=X3[Y.category]||Y.category;return[`## ${Y.title}`,`*Categoria: ${Q}*`,"",Y.content,"",Y.tags.length>0?`Tags: ${Y.tags.map((X)=>`#${X}`).join(" ")}`:""].filter(Boolean).join(`
|
|
271
|
+
`)});return["# Manual de Uso Otimizado","",`Baseado em ${F$.length} entradas do manual vivo.`,"",...J].join(`
|
|
272
|
+
`)}var X3={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function xV($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
|
|
273
|
+
`)}function K3($){let Z=X3[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
|
|
274
274
|
Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`:""].filter(Boolean).join(`
|
|
275
|
-
`)}function
|
|
275
|
+
`)}function SV($){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 wV($){let Z=new Set;Z.add($.type.replace(/_/g,"-"));for(let J of $.relatedActions)if(J.includes("_"))Z.add(J.split("_")[0]);return[...Z]}function z3($){return $.summary}function V3($){if($.length===0)return"Nenhum insight disponivel.";let Z=$.map((J)=>{return[`[${{repetitive_task:"Tarefa Repetitiva",underutilized_tool:"Ferramenta Subutilizada",inefficient_pattern:"Padrao Ineficiente",tip:"Dica"}[J.type]||J.type}] ${J.title}`,` ${J.recommendation}`,` Confianca: ${Math.round(J.confidence*100)}%`].join(`
|
|
276
276
|
`)});return`Insights (${$.length}):
|
|
277
277
|
|
|
278
278
|
${Z.join(`
|
|
279
279
|
|
|
280
|
-
`)}`}function
|
|
281
|
-
`),Y=J[0]?.replace(/^#\s*/,"")||$.replace(".md",""),Q="best_practice",X=1,K=[];for(let
|
|
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 c4(){return hz("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function KV($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}var C8=new b5,J3=[];function Y3($){J3=$}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"]}}],Q3=[{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:[]}}],HV=[{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:[]}}],qV=[{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:[]}}],WV=[{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"]}}],UV={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"]}},BV=[{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"]}}],NV=[{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:[]}}],MV=[{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"]}}],CV=[{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:[]}}],jV=[{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"]}}],OV=[{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"]}}],FV=[{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"]}}],EV=[{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"]}}],RV=[{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:[]}}],LV=[{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"]}}],PV=[{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:[]}}],DV=[{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:[]}}],TV=[{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:[]}}],IV=Q3.find(($)=>$.name==="get_news"),iJ=!1,e$=null;function X3($){e$=$}function K3(){if(iJ)return;if(iJ=!0,I)p.push(...Q3),p.push(...RV);else p.push(IV);p.push(...HV),p.push(...qV),p.push(...WV),p.push(UV),p.push(...BV),p.push(...NV),p.push(...MV),p.push(...PV),p.push(...LV),p.push(...CV),p.push(...jV),p.push(...OV),p.push(...FV),p.push(...DV),p.push(...EV),p.push(...TV)}var A7=50000;async function S9($,Z){let J=performance.now();try{let Y=await AV($,Z);return setImmediate(()=>{I9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!Y.startsWith("Error:")})}),Y}catch(Y){return setImmediate(()=>{I9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-J),success:!1})}),`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function AV($,Z){switch($){case"read_file":return xV(Z);case"write_file":return SV(Z);case"edit_file":return wV(Z);case"search_files":return await kV(Z);case"find_files":return await _V(Z);case"list_directory":return vV(Z);case"run_command":return await fV(Z);case"fetch_url":return await hV(Z);case"open_application":return await x4(Z.name,Z.argument);case"open_file_default":return await B0(Z.path);case"open_url_browser":return await S4(Z.url);case"get_running_apps":return await N0();case"get_system_info":return await w4();case"get_calendar_events":return await k$();case"get_news":{let J=Z.category;return await q4(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?C0(Y):void 0,X=_1(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=v1(J);return Y?`Concluida: "${Y.title}"`:`Tarefa nao encontrada: "${J}"`}case"list_tasks":{let J=Z.show_done||!1,Y=d$(J);return y4(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=o1(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=l$(J);if(!Y)return`Pessoa nao encontrada: "${J}"`;return i1(Y)}case"list_people":{let J=Z.group,Y=a1(J);return r1(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?eJ(X):void 0;if(!T6(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?eJ(Q):void 0,K=n1(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=I6(J,Y,Z.notes);if(!Q)return`Delegacao nao encontrada: "${J}"`;return`Delegacao atualizada: "${Q.task}" -> ${Y}`}case"get_people_dashboard":return e1();case"save_memo":{let J=Z.content;if(!J?.trim())return"Error: content is required.";let Y=Z.tags||[],Q=f1(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 _4(j0());let Y=h1(J);return _4(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=O0(J,Y,Q,X);return`${K.type==="entrada"?"+":"-"} R$ ${K.amount.toFixed(2)} (${K.category}) \u2014 ${K.description} [${K.id}]`}case"financial_summary":return p1();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=N6(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 K8(c1());return K8(v4(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=o5(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=a5(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=n5(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=r5(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=i5(J);if(!Y)return`Investigacao nao encontrada: "${J}"`;return $9(Y)}case"investigation_report":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let Y=e5(J);if(!Y)return`Investigacao nao encontrada: "${J}"`;return Y}case"list_investigations":{let J=Z.query;if(J?.trim())return d1(t5(J));let{status:Y,type:Q}=Z;return d1(s5(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=m1(X),V=await g1(X);return`${K}
|
|
280
|
+
`)}`}function kV(){if(!j8)return;let $=Object.fromEntries(d4);x(tJ(),JSON.stringify($,null,2))}function bV(){let $=tJ();if(!w1($)){d4=new Map;return}try{let Z=JSON.parse(y9($,"utf-8"));d4=new Map(Object.entries(Z))}catch{d4=new Map}}function yV(){if(!j8)return;x(eJ(),JSON.stringify(e$,null,2))}function _V(){let $=eJ();if(!w1($)){e$=[];return}try{let Z=JSON.parse(y9($,"utf-8"));e$=Array.isArray(Z)?Z:[]}catch{e$=[]}}function vV(){if(!w1(R4)){F$=[];return}try{let $=BV(R4,{withFileTypes:!0}).filter((J)=>J.isFile()&&J.name.endsWith(".md")),Z=[];for(let J of $){let Y=l4(R4,J.name),Q=y9(Y,"utf-8"),X=fV(J.name,Q);if(X)Z.push(X)}F$=Z}catch{F$=[]}}function fV($,Z){try{let J=Z.split(`
|
|
281
|
+
`),Y=J[0]?.replace(/^#\s*/,"")||$.replace(".md",""),Q="best_practice",X=1,K=[];for(let U of J.slice(1,6)){if(U.startsWith("> Categoria:")){let B=U.replace("> Categoria:","").trim().toLowerCase();if(B==="workflow"||B==="tool"||B==="shortcut"||B==="best_practice")Q=B}if(U.startsWith("> Versao:"))X=parseInt(U.replace("> Versao:","").trim())||1}let G=J.slice(-3).join(`
|
|
282
|
+
`).match(/Tags:\s*(.+)/);if(G){let B=G[1].match(/#[\w-]+/g);if(B)K.push(...B.map((M)=>M.slice(1)))}let H=$.match(/-([a-z0-9]{4,8})\.md$/);return{id:H?H[1]:o4(),title:Y,category:Q,content:J.slice(5).join(`
|
|
283
|
+
`).trim(),tags:K,source:"auto_generated",version:X,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function o4(){return MV("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function hV($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}r();A8();import{join as gV}from"path";import{createHash as mV}from"crypto";var cV={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},b1={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"]},pV=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],uV="",A=null,v9=[],W3={...cV},U3=!1,G3=null,dV=()=>gV(uV,"plan-history.json");function $4(){return U3}function f9($,Z){let J=$.toLowerCase(),Y=lV(J),Q=Z?.files||[],X=Z?.modules||[],K=[],V=[];for(let z of Q)for(let U of pV)if(U.test(z))K.push(`Modifying sensitive file: ${z}`);if(Q.length>3)K.push(`Affects ${Q.length} files \u2014 higher coordination risk`);if(X.length>1)K.push(`Spans ${X.length} modules \u2014 may have cascading effects`);if(J.includes("api"))V.push("API contract may need versioning consideration");if(J.includes("database")||J.includes("schema"))V.push("Database changes may require migration");if(J.includes("auth")||J.includes("security"))V.push("Security changes require thorough review");let G=W3.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:Q,modulesAffected:X,risks:K,assumptions:V,requiresApproval:G,reason:H}}function lV($){for(let Z of b1.architectural)if($.includes(Z))return"architectural";for(let Z of b1.complex)if($.includes(Z))return"complex";for(let Z of b1.moderate)if($.includes(Z))return"moderate";for(let Z of b1.simple)if($.includes(Z))return"simple";for(let Z of b1.trivial)if($.includes(Z))return"trivial";return"moderate"}function B3($,Z,J){let Y=f9($),Q={id:q3(),objective:$,strategy:Z.map((X,K)=>({...X,id:q3(),order:K+1,status:"pending"})),assumptions:[...J?.assumptions||[],...Y.assumptions],risks:[...J?.risks||[],...Y.risks],status:"draft",complexity:Y.complexity,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return A=Q,Q4().emit("planning:started",{planId:Q.id,objective:$}),Q}async function N3(){if(!A)return{success:!1,plan:null,message:"No active plan to submit"};if(A.status!=="draft")return{success:!1,plan:A,message:`Plan already in status: ${A.status}`};if(A={...A,status:"pending_approval",updatedAt:new Date().toISOString()},W3.autoApproveComplexity.includes(A.complexity))return H3("Auto-approved based on complexity classification");if(G3)if(await G3(A))return H3("Approved by user");else return oV("Rejected by user");return{success:!0,plan:A,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function H3($){if(!A)return{success:!1,plan:null,message:"No active plan to approve"};if(A.status!=="pending_approval"&&A.status!=="draft")return{success:!1,plan:A,message:`Cannot approve plan in status: ${A.status}`};return A={...A,status:"approved",approvedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),userFeedback:$},Q4().emit("planning:approved",{planId:A.id,feedback:$}),{success:!0,plan:A,message:"Plan approved \u2014 execution may proceed"}}function oV($){if(!A)return{success:!1,plan:null,message:"No active plan to reject"};return A={...A,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},Q4().emit("planning:rejected",{planId:A.id,feedback:$}),F3(A),A=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function M3(){if(!A)return{allowed:!0,reason:"No plan required \u2014 trivial operation"};if(A.status==="approved"||A.status==="executing")return{allowed:!0,reason:"Plan approved \u2014 execution permitted"};if(A.status==="draft"||A.status==="pending_approval")return{allowed:!1,reason:`Execution blocked \u2014 plan awaiting approval (status: ${A.status})`};return{allowed:!1,reason:`Execution blocked \u2014 plan status: ${A.status}`}}function C3($,Z){if(!A)return{success:!1,message:"No active plan"};let J=A.strategy.findIndex((V)=>V.id===$);if(J===-1)return{success:!1,message:`Step not found: ${$}`};let Y=A.strategy.map((V,G)=>G===J?{...V,status:"completed",result:Z}:V);A={...A,strategy:Y,updatedAt:new Date().toISOString()},Q4().emit("planning:step_completed",{planId:A.id,stepId:$,result:Z});let Q=A.strategy.find((V)=>V.status==="pending"),X=A.strategy[J].action;if(A.strategy.every((V)=>V.status==="completed"||V.status==="skipped"))aV();return{success:!0,message:`Step completed: ${X}`,nextStep:Q}}function j3($,Z,J){if(!A)return{success:!1,message:"No active plan"};let Y=A.strategy.findIndex((X)=>X.id===$);if(Y===-1)return{success:!1,message:`Step not found: ${$}`};let Q=A.strategy.map((X,K)=>K===Y?{...X,status:"blocked",blockedReason:Z}:X);return A={...A,strategy:Q,status:"blocked",blockedAt:new Date().toISOString(),blockedReason:Z,updatedAt:new Date().toISOString()},Q4().emit("planning:blocked",{planId:A.id,stepId:$,reason:Z,proposedAlternative:J}),{success:!0,message:J?`Step blocked: ${Z}. Proposed alternative: ${J}`:`Step blocked: ${Z}. Awaiting user guidance.`}}function aV(){if(!A)return;A={...A,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},Q4().emit("planning:completed",{planId:A.id,stepsCompleted:A.strategy.filter(($)=>$.status==="completed").length}),F3(A),A=null}function y1(){return A?{...A}:null}function h9($){let Z=$.strategy.map((Q)=>{return`${Q.status==="completed"?"\u2713":Q.status==="in_progress"?"\u2192":Q.status==="blocked"?"\u2717":"\u25CB"} Passo ${Q.order}: ${Q.action} \u2192 ${Q.target}`}),J=$.assumptions.length>0?$.assumptions.map((Q)=>` - ${Q}`).join(`
|
|
284
|
+
`):" (nenhuma)",Y=$.risks.length>0?$.risks.map((Q)=>` - ${Q}`).join(`
|
|
285
|
+
`):" (nenhum identificado)";return[`**Objetivo:** ${$.objective}`,"",`**Complexidade:** ${$.complexity}`,"","**Estrat\xE9gia T\xE9cnica:**",...Z,"","**Premissas/Riscos:**",J,Y,"","**Bloqueio:** Posso prosseguir com este plano ou deseja ajustar algum detalhe?"].join(`
|
|
286
|
+
`)}function O3($){let Z=$.strategy.filter((Q)=>Q.status==="completed").length,J=$.strategy.length,Y=$.strategy.find((Q)=>Q.status==="in_progress"||Q.status==="pending");return[`Plano: ${$.objective}`,`Status: ${$.status}`,`Progresso: ${Z}/${J} passos`,Y?`Pr\xF3ximo: ${Y.action}`:""].filter(Boolean).join(`
|
|
287
|
+
`)}function F3($){let Z={planId:$.id,objective:$.objective,status:$.status,complexity:$.complexity,stepsCompleted:$.strategy.filter((J)=>J.status==="completed").length,totalSteps:$.strategy.length,createdAt:$.createdAt,completedAt:$.completedAt};v9=[...v9,Z],rV()}function rV(){if(!U3)return;x(dV(),JSON.stringify(v9,null,2))}function q3(){return mV("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function R3(){return`
|
|
288
|
+
## Protocolo de Alta Ag\xEAncia
|
|
284
289
|
|
|
285
|
-
|
|
286
|
-
|
|
290
|
+
Voc\xEA opera sob o protocolo "Draft-then-Commit" que requer planejamento expl\xEDcito antes de execu\xE7\xE3o.
|
|
291
|
+
|
|
292
|
+
### Regras Fundamentais
|
|
293
|
+
|
|
294
|
+
1. **An\xE1lise de Impacto Silenciosa**: Antes de responder, avalie internamente as depend\xEAncias e efeitos colaterais.
|
|
295
|
+
|
|
296
|
+
2. **Proposta de Plano (The Draft)**: Para tarefas n\xE3o-triviais, apresente sua inten\xE7\xE3o de forma t\xE9cnica e opinativa:
|
|
297
|
+
- Use a ferramenta \`propose_plan\` para estruturar o plano
|
|
298
|
+
- N\xE3o pergunte o que fazer; diga o que voc\xEA decidiu fazer e por qu\xEA
|
|
299
|
+
- Aguarde confirma\xE7\xE3o antes de executar
|
|
300
|
+
|
|
301
|
+
3. **Proibi\xE7\xE3o de Escrita Precoce**: \xC9 TERMINANTEMENTE PROIBIDO:
|
|
302
|
+
- Modificar arquivos antes da aprova\xE7\xE3o do plano
|
|
303
|
+
- Executar comandos destrutivos sem confirma\xE7\xE3o
|
|
304
|
+
- Fazer chamadas de API de escrita sem autoriza\xE7\xE3o
|
|
305
|
+
|
|
306
|
+
4. **Alta Ag\xEAncia na Decis\xE3o**:
|
|
307
|
+
- Se houver m\xFAltiplas formas de implementar, escolha a que segue Clean Code e performance
|
|
308
|
+
- Justifique brevemente sua escolha na estrat\xE9gia t\xE9cnica
|
|
309
|
+
- Seja opinativo mas fundamentado
|
|
310
|
+
|
|
311
|
+
5. **Auto-Corre\xE7\xE3o**: Se encontrar um obst\xE1culo que invalide o plano:
|
|
312
|
+
- PARE imediatamente a execu\xE7\xE3o
|
|
313
|
+
- Use \`report_plan_deviation\` para explicar o desvio
|
|
314
|
+
- Proponha uma alternativa antes de continuar
|
|
315
|
+
|
|
316
|
+
### Classifica\xE7\xE3o de Complexidade
|
|
317
|
+
|
|
318
|
+
- **trivial/simple**: Pode executar diretamente (typos, formatting, renames)
|
|
319
|
+
- **moderate**: Requer plano breve, pode auto-aprovar se baixo risco
|
|
320
|
+
- **complex/architectural**: OBRIGAT\xD3RIO apresentar plano e aguardar aprova\xE7\xE3o
|
|
321
|
+
|
|
322
|
+
### Formato do Plano
|
|
323
|
+
|
|
324
|
+
Ao usar \`propose_plan\`, estruture assim:
|
|
325
|
+
- **Objetivo**: Descri\xE7\xE3o concisa do resultado final
|
|
326
|
+
- **Estrat\xE9gia T\xE9cnica**: Lista ordenada de passos com arquivos-alvo
|
|
327
|
+
- **Premissas/Riscos**: Depend\xEAncias assumidas e potenciais quebras
|
|
328
|
+
- **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}
|
|
330
|
+
|
|
331
|
+
${V}`}case"save_material":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let Q=Z.category||"geral",X=Z.tags||[],K=G7(J,Y,Q,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 J=Z.query;if(!J?.trim())return C4(U8());let Y=W8(J);return C4(Y)}case"list_materials":{let J=Z.category,Y=Z.limit||30,Q=U8(Y,J);return C4(Q)}case"update_material":{let J=Z.id;if(!J?.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 Q=o6(J,Y);if(!Q)return`Material nao encontrado: "${J}"`;return`Material atualizado: "${Q.title}" (${Q.category}) {${Q.id}}`}case"delete_material":{let J=Z.id;if(!J?.trim())return"Error: id is required.";return H7(J)?"Material removido.":`Material nao encontrado: "${J}"`}case"execute_powershell_script":{let J=Z.script;if(!J?.trim())return"Error: script is required.";let Y=C9(J);if(Y.blocked)return`BLOCKED: ${Y.reason}
|
|
332
|
+
Esse tipo de operacao nao e permitido.`;if(!Y.safe&&Y.reason);let Q=await j7(J),X=[];if(Q.stdout.trim())X.push(`stdout:
|
|
287
333
|
${Q.stdout.trim()}`);if(Q.stderr.trim())X.push(`stderr:
|
|
288
334
|
${Q.stderr.trim()}`);return X.push(`exit: ${Q.exitCode} (${Q.duration}ms)`),X.join(`
|
|
289
335
|
|
|
290
|
-
`)}case"analyze_screen_context":return await
|
|
291
|
-
${J.text}`;case"image":return J.text;case"empty":return"Clipboard vazio.";case"error":return`Erro ao ler clipboard: ${J.text}`}}case"manage_news_feeds":switch(Z.action){case"list":return
|
|
336
|
+
`)}case"analyze_screen_context":return await F7();case"read_clipboard_content":{let J=await O7();switch(J.type){case"text":return`Clipboard (texto):
|
|
337
|
+
${J.text}`;case"image":return J.text;case"empty":return"Clipboard vazio.";case"error":return`Erro ao ler clipboard: ${J.text}`}}case"manage_news_feeds":switch(Z.action){case"list":return p0();case"add":{let{name:Y,url:Q,category:X}=Z;if(!Y?.trim())return"Error: name is required for add.";if(!Q?.trim())return"Error: url is required for add.";if(!X?.trim())return"Error: category is required for add.";let K=h0(Y,Q,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 g0(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 m0(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 c0(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(!U7())return"Error: memory not initialized. Run /indexar first.";let J=Z.query;if(!J?.trim())return"Error: query is required.";let Y=Math.min(Math.max(Z.top_k||3,1),10),Q=M7(J,Y);return C7(Q)}case"index_memory":{if(!U7())return"Error: memory not initialized.";let J=N7();return`Indexacao concluida: ${J.indexed} fonte(s) indexada(s), ${J.skipped} sem alteracao. Total: ${J.total} chunks.`}case"memory_status":{if(!U7())return"Memory: nao inicializada.";let J=B7(),Y=J.builtAt?new Date(J.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
|
|
292
338
|
Chunks: ${J.chunks}
|
|
293
339
|
Fontes: ${J.sources}
|
|
294
|
-
Ultima indexacao: ${Y}`}case"vault_status":{if(!
|
|
340
|
+
Ultima indexacao: ${Y}`}case"vault_status":{if(!x8())return"Vault nao inicializado.";return Y0(J0())}case"vault_backup":{if(!x8())return"Vault nao inicializado.";let J=Z.message||void 0;return await n4(J)}case"sync_cloud_context":{if(!x8())return"Vault nao inicializado.";return await X0()}case"vault_init_backup":{if(!x8())return"Vault nao inicializado.";return await Q0()}case"set_active_project":{let J=Z.name_or_id;if(!J?.trim())return"Error: name_or_id is required.";if(J==="auto"){let Q=k7(process.cwd());if(!Q)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return C8(Q.id),`Projeto ativo: "${Q.name}" (${Q.path}) \u2014 auto-detectado [${Q.id}]`}let Y=C8(J);if(!Y)return`Projeto nao encontrado: "${J}". Use /projetos para listar ou add_project para criar.`;return`Projeto ativo: "${Y.name}" (${Y.path}) [${Y.id}]`}case"report_work_progress":{let J=Z.project||"",Y=Z.period||"today",Q=Z.lang||"pt",X=Z.save_to_file,K=J;if(!K){let G=O4();if(!G)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=G.id}let V=await A7(K,Y,Q);if(!V)return`Projeto nao encontrado: "${K}"`;if(X)return nV(X,V.markdown,"utf-8"),`Relatorio salvo em: ${X}
|
|
295
341
|
|
|
296
|
-
${V.markdown}`;return V.markdown}case"manage_work_session":{let J=Z.action,Y=Z.notes||"",Q=
|
|
342
|
+
${V.markdown}`;return V.markdown}case"manage_work_session":{let J=Z.action,Y=Z.notes||"",Q=O4();if(!Q)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(J){case"start":{let X=D7(Q.id,Y);if(!X)return"Erro ao iniciar sessao.";return`Sessao iniciada para "${Q.name}" as ${new Date().toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}. [${X.id}]`}case"stop":{let X=F4(Q.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=T7(X.id,Y);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${Q.name}".`}case"status":{let X=F4(Q.id);if(!X)return`Nenhuma sessao aberta para "${Q.name}".`;let K=new Date(X.startedAt),V=Math.round((Date.now()-K.getTime())/60000);return`Sessao aberta: "${Q.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 J=Z.name;if(!J?.trim())return"Error: name is required.";let Y=Z.path;if(!Y?.trim())return"Error: path is required.";let Q=Z.description||"",X=Z.tech_stack||[],K=Z.tags||[],V=F9(J,Y,Q,K,X);return`Projeto registrado: "${V.name}" (${V.path}) [${V.id}]`}case"list_projects":{let J=Z.active_only||!1;return I7(M8(J))}case"fetch_opportunities":{let{status:J,tech:Y}=Z,Q=P7(J,Y);return S7(Q)}case"add_opportunity":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.description;if(!Y?.trim())return"Error: description is required.";let Q=Z.source;if(!Q?.trim())return"Error: source is required.";let X=Z.tech_required||[],K=Z.priority||"media",V=Z.deadline||null,G=GJ(J,Y,Q,X,K,V);return`Oportunidade registrada: "${G.title}" (${G.priority}) [${G.id}]`}case"update_opportunity_status":{let J=Z.id;if(!J?.trim())return"Error: id is required.";let Y=Z.status,Q=HJ(J,Y);if(!Q)return`Oportunidade nao encontrada: "${J}"`;return`Oportunidade atualizada: "${Q.title}" -> ${Y}`}case"pitwall_benchmark":{let J=Z.command;if(!J?.trim())return"Error: command is required.";let Y=Z.key,Q=Math.min(Math.max(Z.iterations||1,1),10),X=Z.warmup||!1,K=Z.cwd,V=await T9(J,{scriptKey:Y,cwd:K,iterations:Q,warmup:X});if(V.exitCode!==0){let G=A9(V);return`AVISO: Comando terminou com exit code ${V.exitCode}. Metricas podem nao ser confiaveis.
|
|
297
343
|
|
|
298
|
-
${G.markdown}`}return
|
|
299
|
-
`+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let H=K?
|
|
344
|
+
${G.markdown}`}return A9(V).markdown}case"pitwall_save_baseline":{let J=Z.command;if(!J?.trim())return"Error: command is required.";let Y=Z.key,Q=Math.min(Math.max(Z.iterations||3,1),10),X=Z.tags||[],K=Z.reset||!1,V=Z.cwd,G=await T9(J,{scriptKey:Y,cwd:V,iterations:Q,warmup:!0});if(G.exitCode!==0)return`Error: Comando falhou (exit code ${G.exitCode}). Corrija o comando antes de salvar baseline.
|
|
345
|
+
`+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let H=K?FJ(G,X):jJ(G,X),z=H.metrics.durationNs/1e6;return`Baseline salvo: "${H.scriptKey}" (${H.runs} run${H.runs>1?"s":""})
|
|
300
346
|
Duracao: ${z.toFixed(2)}ms
|
|
301
347
|
Memoria: ${(H.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
|
|
302
|
-
CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return
|
|
348
|
+
CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return EJ(OJ());case"pitwall_remove_baseline":{let J=Z.key;if(!J?.trim())return"Error: key is required.";return P9(J)?`Baseline removido: "${J}"`:`Baseline nao encontrado: "${J}"`}case"analyze_blast_radius":{let J=Z.file;if(!J?.trim())return"Error: file is required.";let Y=x$(Z.project_dir||process.cwd()),Q=x$(Y,J);if(!Q.startsWith(Y+O8))return"Error: file must be inside project_dir.";try{let X=x9(Y),K=S9(X,Q);return IJ(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"plan_refactor":{let J=Z.file;if(!J?.trim())return"Error: file is required.";let Y=x$(Z.project_dir||process.cwd()),Q=x$(Y,J);if(!Q.startsWith(Y+O8))return"Error: file must be inside project_dir.";try{let X=x9(Y),K=AJ(X,Q);return SJ(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"archive_session":{if(!Z4)return"Error: session manager not initialized.";let J=Z.name;if(!J?.trim())return"Error: name is required.";if(J==="all"){let Y=Z4.archiveAll();return Y.length>0?`Arquivadas ${Y.length} sessoes: ${Y.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return Z4.archive(J)?`Sessao arquivada: "${J}"`:`Falha ao arquivar "${J}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!Z4)return"Error: session manager not initialized.";let J=Z.name;if(!J?.trim())return"Error: name is required.";return Z4.unarchive(J)?`Sessao restaurada: "${J}"`:`Sessao arquivada nao encontrada: "${J}"`}case"list_archived_sessions":{if(!Z4)return"Error: session manager not initialized.";let J=Z4.listArchived();if(J.length===0)return"Nenhuma sessao arquivada.";let Y=J.map((Q)=>{let X=Z4.getArchivedInfo(Q),K=X?new Date(X.updated).toLocaleDateString("pt-BR"):"",V=X?`${X.messageCount} msgs`:"";return` ${Q.padEnd(20)} ${V.padEnd(10)} ${K}`});return`Sessoes arquivadas (${J.length}):
|
|
303
349
|
${Y.join(`
|
|
304
|
-
`)}`}case"evaluate_architecture_tradeoffs":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.background;if(!Y?.trim())return"Error: background is required.";let Q=Z.options;if(!Q||Q.length<2)return"Error: at least 2 options are required.";let X={title:J.trim(),background:Y.trim(),constraints:Z.constraints||[],stakeholders:Z.stakeholders||[]},K=Q.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:
|
|
350
|
+
`)}`}case"evaluate_architecture_tradeoffs":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.background;if(!Y?.trim())return"Error: background is required.";let Q=Z.options;if(!Q||Q.length<2)return"Error: at least 2 options are required.";let X={title:J.trim(),background:Y.trim(),constraints:Z.constraints||[],stakeholders:Z.stakeholders||[]},K=Q.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:k9;return fJ(X,K,G).adr}case"correlate_incident":{let J=Z.description;if(!J?.trim())return"Error: description is required.";let Y=Z.stacktrace;return hJ(J,Y).summary}case"log_incident":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.description;if(!Y?.trim())return"Error: description is required.";let Q=Z.root_cause;if(!Q?.trim())return"Error: root_cause is required.";let X=Z.solution;if(!X?.trim())return"Error: solution is required.";let K=gJ(J,Y,Q,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
|
|
305
351
|
Causa: ${K.rootCause.slice(0,80)}${K.rootCause.length>80?"...":""}
|
|
306
|
-
Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let J=Z.limit||10,Y=Z.query,Q=Y?
|
|
307
|
-
Arquivo: ${K.path}`}case"explain_optimal_usage":{let J=Z.topic;return
|
|
308
|
-
|
|
309
|
-
`),
|
|
310
|
-
|
|
311
|
-
|
|
352
|
+
Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let J=Z.limit||10,Y=Z.query,Q=Y?uJ(Y).slice(0,J):pJ(J);return lJ(Q)}case"list_incidents":{let J=Z.limit||10,Y=Z.query,Q=Y?mJ(Y).slice(0,J):cJ(J);return oJ(Q)}case"get_tradeoff_adr":{let J=Z.id;if(!J?.trim())return"Error: id is required.";let Y=dJ(J);if(!Y)return`Trade-off nao encontrado: "${J}"`;return Y.adr}case"update_living_manual":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let Q=Z.category||"best_practice",X=Z.tags||[],K=await Y3(J,Y,Q,X);if(!K.success)return"Falha ao atualizar o manual. Verifique se o docs-engine foi inicializado.";return`Manual atualizado: "${J}" (${Q})
|
|
353
|
+
Arquivo: ${K.path}`}case"explain_optimal_usage":{let J=Z.topic;return Q3(J)}case"trigger_self_reflection":{let J=await k1();return z3(J)}case"get_usage_insights":{let J=Math.min(Math.max(Z.count||5,1),20),Y=J3(J);return V3(Y)}case"propose_plan":{if(!$4())return"Error: Agency engine not initialized. Planning features unavailable.";let J=Z.objective;if(!J?.trim())return"Error: objective is required.";let Y=Z.steps;if(!Y?.length)return"Error: at least one step is required.";let Q=Y.map((G)=>({action:G.action,target:G.target,description:G.description,estimatedImpact:G.estimatedImpact||"low",dependencies:G.dependencies||[]})),X=B3(J,Q,{assumptions:Z.assumptions,risks:Z.risks}),K=await N3();if(!K.success)return`Error creating plan: ${K.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
|
|
354
|
+
|
|
355
|
+
${h9(X)}`}case"check_plan_status":{if(!$4())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let J=M3(),Y=y1();if(!Y)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${O3(Y)}
|
|
356
|
+
|
|
357
|
+
Execu\xE7\xE3o: ${J.allowed?"PERMITIDA":"BLOQUEADA"}
|
|
358
|
+
Motivo: ${J.reason}`}case"report_plan_deviation":{if(!$4())return"Error: Agency engine not initialized.";let{obstacle:J,impact:Y,alternative:Q}=Z;if(!J?.trim())return"Error: obstacle is required.";if(!Y?.trim())return"Error: impact is required.";if(!Q?.trim())return"Error: alternative is required.";let X=y1();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)j3(V.id,J,Q);return["**Desvio Detectado**","",`**Obst\xE1culo:** ${J}`,`**Impacto no Plano:** ${Y}`,"","**Alternativa Proposta:**",Q,"","**Status:** Execu\xE7\xE3o BLOQUEADA. Aguardando aprova\xE7\xE3o da alternativa.","","**Bloqueio:** Posso prosseguir com esta alternativa?"].join(`
|
|
359
|
+
`)}case"complete_plan_step":{if(!$4())return"Error: Agency engine not initialized.";let J=Z.step_id;if(!J?.trim())return"Error: step_id is required.";let Y=C3(J,Z.result);if(!Y.success)return`Error: ${Y.message}`;let Q=y1(),X=Q?`Progresso: ${Q.strategy.filter((V)=>V.status==="completed").length}/${Q.strategy.length}`:"",K=Y.nextStep?`
|
|
360
|
+
Pr\xF3ximo passo: ${Y.nextStep.action} \u2192 ${Y.nextStep.target}`:`
|
|
361
|
+
Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${Y.message}
|
|
362
|
+
${X}${K}`}case"get_current_plan":{if(!$4())return"Agency engine not initialized. No planning features available.";let J=y1();if(!J)return"Nenhum plano ativo no momento.";return h9(J)}case"analyze_task_complexity":{if(!$4())return"Agency engine not initialized. Cannot analyze complexity.";let J=Z.task;if(!J?.trim())return"Error: task is required.";let Y=f9(J,{files:Z.files,modules:Z.modules}),Q=["**An\xE1lise de Complexidade**","",`**Tarefa:** ${J}`,`**Classifica\xE7\xE3o:** ${Y.complexity}`,`**Requer Aprova\xE7\xE3o:** ${Y.requiresApproval?"SIM":"N\xC3O"}`,"",`**Motivo:** ${Y.reason}`];if(Y.risks.length>0){Q.push("","**Riscos Identificados:**");for(let X of Y.risks)Q.push(` - ${X}`)}if(Y.assumptions.length>0){Q.push("","**Premissas:**");for(let X of Y.assumptions)Q.push(` - ${X}`)}if(Y.requiresApproval)Q.push("","**Recomenda\xE7\xE3o:** Use `propose_plan` antes de executar esta tarefa.");return Q.join(`
|
|
363
|
+
`)}default:{let J=I3.find((Y)=>Y.name===$);if(J)return await i2(J,Z);return`Error: unknown tool "${$}"`}}}var L3=10485760;function E8($){let Z=x$($),J=process.cwd();if(Z!==J&&!Z.startsWith(J+O8))return`Error: path outside working directory is not permitted: ${Z}`;try{if(_1(Z)){let Y=sV(Z);if(Y!==J&&!Y.startsWith(J+O8))return`Error: symlink target is outside working directory: ${Y}`}}catch{}return null}function L8($,Z){let J=$[Z];if(typeof J!=="string"||J.trim().length===0)return`Error: '${Z}' is required and must be a non-empty string.`;return null}function jG($){let Z=L8($,"path");if(Z)return Z;let J=x$($.path),Y=E8(J);if(Y)return Y;if(!_1(J))return`Error: file not found: ${J}`;let Q=P3(J).size;if(Q>L3)return`Error: file too large (${g9(Q)}). Max is ${g9(L3)}.`;let K=m9(J,"utf-8").split(`
|
|
364
|
+
`),V=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),U=K.slice(V-1,V-1+G).map((M,O)=>`${String(V+O).padStart(4)} ${M}`).join(`
|
|
365
|
+
`),B=K.length-(V-1+G);if(B>0)U+=`
|
|
366
|
+
... (${B} more lines, total ${K.length})`;return F8(U)}function OG($){let Z=L8($,"path");if(Z)return Z;let J=x$($.path),Y=E8(J);if(Y)return Y;let Q=$.content,X=_1(J);R8.saveState(J),x(J,Q);let K=Q.split(`
|
|
367
|
+
`).length;return`${X?"Updated":"Created"}: ${J} (${K} lines)`}function FG($){let Z=L8($,"path");if(Z)return Z;let J=x$($.path),Y=E8(J);if(Y)return Y;if(!_1(J))return`Error: file not found: ${J}`;let Q=m9(J,"utf-8"),X=$.old_text,K=$.new_text,V=Q.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.`;R8.saveState(J);let G=Q.split(X).join(K);x(J,G);let H=X.split(`
|
|
312
368
|
`).length,z=K.split(`
|
|
313
|
-
`).length;return`Edited: ${J} (replaced ${H} lines with ${z} lines)`}async function
|
|
369
|
+
`).length;return`Edited: ${J} (replaced ${H} lines with ${z} lines)`}async function RG($){let Z=L8($,"pattern");if(Z)return Z;let J=$.pattern,Y=x$($.path||"."),Q=E8(Y);if(Q)return Q;let X=$.include;if(await _Z())return EG(J,Y,X);return LG(J,Y,X)}async function EG($,Z,J){let Y=["rg","--no-heading","--line-number","--color=never"];if(J)Y.push("--glob",J);for(let V of P8)Y.push("--glob",`!${V}`);Y.push("-e",$,Z);let Q=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe"}),X=await new Response(Q.stdout).text(),K=await new Response(Q.stderr).text();if(await Q.exited,!X.trim()&&!K.trim())return"No matches found.";if(K.trim()&&!X.trim())return`Error: ${K.trim()}`;return xG(X,Z)}async function LG($,Z,J){let Y;try{Y=new RegExp($)}catch(z){return`Error: invalid regex pattern: ${z instanceof Error?z.message:$}`}let Q=J||"**/*",X=new Bun.Glob(Q),K=[],V=0,G=5000;for await(let z of X.scan({cwd:Z,onlyFiles:!0})){if($5(z))continue;if(++V>G){K.push(`... (stopped after scanning ${G} files)`);break}let U=A3(Z,z);try{let M=m9(U,"utf-8").split(`
|
|
314
370
|
`);for(let O=0;O<M.length;O++)if(Y.test(M[O])){if(K.push(`${z}:${O+1}:${M[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(`
|
|
315
371
|
`);if(K.length>100)H+=`
|
|
316
|
-
... (showing first 100 matches)`;return
|
|
372
|
+
... (showing first 100 matches)`;return F8(H)}async function DG($){let Z=L8($,"pattern");if(Z)return Z;let J=$.pattern,Y=x$($.path||"."),Q=E8(Y);if(Q)return Q;let X=new Bun.Glob(J),K=[];for await(let G of X.scan({cwd:Y,onlyFiles:!0})){if($5(G))continue;if(K.push(G),K.length>=200)break}if(K.length===0)return"No files found.";let V=K.join(`
|
|
317
373
|
`);if(K.length>=200)V+=`
|
|
318
|
-
... (showing first 200 files)`;return V}function
|
|
319
|
-
`)}async function
|
|
374
|
+
... (showing first 200 files)`;return V}function TG($){let Z=x$($.path||"."),J=E8(Z);if(J)return J;if(!_1(Z))return`Error: not found: ${Z}`;return iV(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=P3(A3(Z,X.name)),V=g9(K.size);return`f ${X.name} ${V}`}catch{return`f ${X.name}`}}).join(`
|
|
375
|
+
`)}async function PG($){let Z=L8($,"command");if(Z)return Z;let J=$.command,Y=Math.min(120,Math.max(5,$.timeout||30)),Q=i4(),X=Bun.spawn([...Q,J],{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?`
|
|
320
376
|
`:"")+`STDERR:
|
|
321
377
|
`+G.trim();if(H!==0)z+=(z?`
|
|
322
|
-
`:"")+`Exit code: ${H}`;return
|
|
323
|
-
(Use fetch_url on the redirect target if needed)`}let H=`${G.status} ${G.statusText}`,z=G.headers.get("content-type")||"";if(J==="HEAD"){let M=[...G.headers.entries()].map(([O,
|
|
378
|
+
`:"")+`Exit code: ${H}`;return F8(z||"(no output)")}async function AG($){let Z=$.url,J=$.method||"GET",Y=$.headers||{},Q=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let X=D3(Z);if(X)return X;try{let K=new AbortController,V=setTimeout(()=>K.abort(),30000),G=await fetch(Z,{method:J,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Y},body:Q&&J!=="GET"&&J!=="HEAD"?Q:void 0,signal:K.signal});if(clearTimeout(V),G.status>=300&&G.status<400){let M=G.headers.get("location");if(!M)return`Status: ${G.status} (redirect with no location header)`;let O=D3(M);if(O)return`Redirect blocked: ${O}`;return`Status: ${G.status} -> Redirect to: ${M}
|
|
379
|
+
(Use fetch_url on the redirect target if needed)`}let H=`${G.status} ${G.statusText}`,z=G.headers.get("content-type")||"";if(J==="HEAD"){let M=[...G.headers.entries()].map(([O,L])=>`${O}: ${L}`).join(`
|
|
324
380
|
`);return`Status: ${H}
|
|
325
|
-
${M}`}let
|
|
381
|
+
${M}`}let U=G.headers.get("content-length");if(U&&Number(U)>f7*2)return`Status: ${H}
|
|
326
382
|
|
|
327
|
-
Error: response body too large (${
|
|
383
|
+
Error: response body too large (${U} bytes). Max is ${f7*2} bytes.`;let B=await G.text();if(z.includes("text/html")){let M=IG(B);return F8(`Status: ${H}
|
|
328
384
|
|
|
329
|
-
${M}`)}return
|
|
385
|
+
${M}`)}return F8(`Status: ${H}
|
|
330
386
|
|
|
331
|
-
${
|
|
387
|
+
${B}`)}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 D3($){try{let Z=new URL($),J=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(J))return"Error: requests to localhost are blocked for security.";if(J.endsWith(".local")||J.endsWith(".internal"))return"Error: requests to internal hostnames are blocked.";if(J==="metadata.google.internal"||J==="metadata.gcp.internal")return"Error: requests to cloud metadata endpoints are blocked.";let Q=J.split(".").map(Number);if(Q.length===4&&Q.every((X)=>!isNaN(X)&&X>=0&&X<=255)){if(Q[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(Q[0]===172&&Q[1]>=16&&Q[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(Q[0]===192&&Q[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(Q[0]===169&&Q[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(Q[0]===0)return"Error: requests to 0.x IPs are blocked."}if(J.startsWith("::ffff:")||J.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function IG($){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,`
|
|
332
388
|
`).replace(/<(br|hr)[^>]*\/?>/gi,`
|
|
333
389
|
`).replace(/<[^>]+>/g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
334
390
|
|
|
335
|
-
`).trim()}function
|
|
391
|
+
`).trim()}function xG($,Z){let J=process.cwd(),Y=J+O8,Q=Z+O8,K=$.trim().split(`
|
|
336
392
|
`).map((H)=>{if(H.startsWith(Y))return"."+H.slice(J.length).replace(/\\/g,"/");if(H.startsWith(Q))return"."+H.slice(Z.length).replace(/\\/g,"/");return H}),V=K.length,G=K.slice(0,100).join(`
|
|
337
393
|
`);if(V>100)G+=`
|
|
338
|
-
... (${V-100} more matches)`;return
|
|
339
|
-
... (output truncated)`}function
|
|
394
|
+
... (${V-100} more matches)`;return F8(G)}function F8($){if($.length<=f7)return $;return $.slice(0,f7)+`
|
|
395
|
+
... (output truncated)`}function g9($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function T3($){let Z=$.toLowerCase().trim(),J=new Date;if(Z==="hoje")return J;if(Z==="amanha"||Z==="amanh\xE3"){let V=new Date(J);return V.setDate(V.getDate()+1),V}let Y=Z.match(/em\s+(\d+)\s*dias?/);if(Y){let V=new Date(J);return V.setDate(V.getDate()+parseInt(Y[1])),V}let Q=Z.match(/em\s+(\d+)\s*semanas?/);if(Q){let V=new Date(J);return V.setDate(V.getDate()+parseInt(Q[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(J),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):J.getFullYear(),z=new Date(H,G,V);if(!isNaN(z.getTime()))return z}return L1(Z)}var SG=new Set([429,500,502,503,529]);async function y3($,Z={}){let J=Z.maxRetries??3,Y=Z.baseDelayMs??1000,Q;for(let X=0;X<=J;X++)try{return await $()}catch(K){if(Q=K,Z.signal?.aborted)throw K;if(X>=J)throw K;if(wG(K)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(X+1,500,"Auth refreshed, retrying..."),await b3(500,Z.signal);continue}}if(!kG(K))throw K;let G=bG(K)??Y*Math.pow(2,X),H=K instanceof Error?K.message:String(K);Z.onRetry?.(X+1,G,H),await b3(G,Z.signal)}throw Q}function wG($){if(!($ instanceof Error))return!1;return $.status===401}function kG($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&SG.has(Z))return!0;let J=$.message.toLowerCase();if(J.includes("econnreset")||J.includes("econnrefused"))return!0;if(J.includes("etimedout")||J.includes("socket hang up"))return!0;if(J.includes("overloaded"))return!0;return!1}function bG($){let Z=$.headers;if(!Z)return null;let J=Z["retry-after"];if(!J)return null;let Y=Number(J);if(!isNaN(Y)&&Y>0)return Math.min(Y,60)*1000;return null}function b3($,Z){return new Promise((J,Y)=>{let Q=setTimeout(J,$);Z?.addEventListener("abort",()=>{clearTimeout(Q),Y(Error("Aborted"))},{once:!0})})}var yG={haiku:200000,sonnet:200000,opus:200000};function E4($){return Math.ceil($.length/3.5)}function p9($){let Z=0;for(let J of $){if(Z+=E4(J.content),J.toolCalls)for(let Y of J.toolCalls)Z+=E4(JSON.stringify(Y.input)),Z+=E4(Y.result);Z+=10}return Z}function u9($){let Z=$.toLowerCase();for(let[J,Y]of Object.entries(yG))if(Z.includes(J))return Y;return 200000}function _3($,Z,J){let Y=u9(Z)-20000-J;if(p9($)<=Y)return $;let X=[],K=Y,V=[...$].reverse(),G=[];for(let z of V){let U=E4(z.content)+(z.toolCalls?.reduce((B,M)=>B+E4(JSON.stringify(M.input))+E4(M.result),0)??0)+10;if(K-U<0)break;K-=U,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 v3($,Z,J){let Y=u9(Z)-20000-J;return p9($)>Y*0.7}function f3($,Z,J){let Y=u9(Z)-20000-J;if(p9($)<=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 h3($){return`Summarize this conversation concisely. Focus on:
|
|
340
396
|
1. Key decisions made
|
|
341
397
|
2. Files created or modified
|
|
342
398
|
3. Important context the user shared
|
|
@@ -348,18 +404,18 @@ Be brief but preserve actionable information. Output ONLY the summary.
|
|
|
348
404
|
${$.map((J)=>{let Y=`[${J.role}]: ${J.content.slice(0,500)}`;if(J.toolCalls?.length)Y+=`
|
|
349
405
|
Tools used: ${J.toolCalls.map((Q)=>Q.name).join(", ")}`;return Y}).join(`
|
|
350
406
|
|
|
351
|
-
`)}`}function
|
|
407
|
+
`)}`}function g3($,Z=2000){return $.map((J)=>{if(!J.toolCalls?.length)return J;let Y=J.toolCalls.map((Q)=>{if(Q.result.length<=Z)return Q;let X=Q.result.split(`
|
|
352
408
|
`),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(`
|
|
353
|
-
`);return{...Q,result:z}});return{...J,toolCalls:Y}})}var
|
|
354
|
-
Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${
|
|
409
|
+
`);return{...Q,result:z}});return{...J,toolCalls:Y}})}var _G=[/\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],vG=[/\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 m3($,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 J=String(Z.command||"");for(let Y of _G)if(Y.test(J))return{level:"dangerous",reason:J};for(let Y of vG)if(Y.test(J))return{level:"moderate",reason:J};return{level:"moderate",reason:J}}case"execute_powershell_script":return{level:"dangerous",reason:"PowerShell script execution"};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function d9($){if(!($ instanceof Error))return String($);let{status:Z,message:J}=$;if(Z)switch(Z){case 400:if(J.includes("context_length")||J.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: ${fG(J)}`;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.
|
|
410
|
+
Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${hG(J)}" may not exist or be unavailable.
|
|
355
411
|
Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
|
|
356
|
-
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=J.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 J}function
|
|
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=J.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 J}function fG($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function hG($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function c3($,Z,J){if($==="auto")return!1;if(J==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command","execute_powershell_script"].includes(Z);if($==="confirm-all")return J!=="safe";return!1}function p3($,Z){switch($){case"write_file":return`Write file: ${Z.path}`;case"edit_file":return`Edit file: ${Z.path}`;case"run_command":{let J=String(Z.command||"");return`Run: ${J.length>60?J.slice(0,57)+"...":J}`}case"execute_powershell_script":{let J=String(Z.script||""),Y=J.split(`
|
|
357
413
|
`)[0]||"",Q=J.split(`
|
|
358
|
-
`).length;return`PowerShell (${Q} line${Q>1?"s":""}): ${Y.length>50?Y.slice(0,47)+"...":Y}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function
|
|
414
|
+
`).length;return`PowerShell (${Q} line${Q>1?"s":""}): ${Y.length>50?Y.slice(0,47)+"...":Y}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function u3($,Z,J=20){let Y=$.split(`
|
|
359
415
|
`),Q=Z.split(`
|
|
360
|
-
`),X=[],K=Y.slice(0,J);for(let G of K)X.push(` \x1B[31m- ${G}\x1B[0m`);if(Y.length>J)X.push(` \x1B[2m ... (${Y.length-J} more removed)\x1B[0m`);let V=Q.slice(0,J);for(let G of V)X.push(` \x1B[32m+ ${G}\x1B[0m`);if(Q.length>J)X.push(` \x1B[2m ... (${Q.length-J} more added)\x1B[0m`);return X}class
|
|
361
|
-
${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=
|
|
362
|
-
`)}function
|
|
416
|
+
`),X=[],K=Y.slice(0,J);for(let G of K)X.push(` \x1B[31m- ${G}\x1B[0m`);if(Y.length>J)X.push(` \x1B[2m ... (${Y.length-J} more removed)\x1B[0m`);let V=Q.slice(0,J);for(let G of V)X.push(` \x1B[32m+ ${G}\x1B[0m`);if(Q.length>J)X.push(` \x1B[2m ... (${Q.length-J} more added)\x1B[0m`);return X}class l9{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,J,Y="auto"){this.model=Z;this.maxTokens=J;this.client=new k$({apiKey:$}),this.approvalMode=Y}updateApiKey($){this.client=new k$({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,J=!0){let Y=g3($),Q=E4(Z);if(v3(Y,this.model,Q)){let G=f3(Y,this.model,Q);if(G)try{let z={role:"assistant",content:`[Conversation summary]
|
|
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=_3(Y,this.model,Q),K=gG(X),V=J?c:void 0;try{yield*this.streamLoop(K,Z,V)}catch(G){yield{type:"error",error:d9(G)}}}async generateSummary($){let Z=h3($),Y=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((Q)=>Q.type==="text");return Y?.type==="text"?Y.text:"Summary unavailable."}async*streamLoop($,Z,J){let Q=[...$],X=0;while(X++<25){let K;try{K=await y3(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:Q,...J?.length?{tools:J}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(z){yield{type:"error",error:d9(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");Q.push({role:"assistant",content:V.content});let H=[];for(let z of G){let U=z.input,B=m3(z.name,U);if(B.level==="dangerous"){yield{type:"tool_blocked",id:z.id,name:z.name,reason:`Blocked dangerous operation: ${B.reason}`},H.push({type:"tool_result",tool_use_id:z.id,content:`Error: Operation blocked for safety. Reason: ${B.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&c3(this.approvalMode,z.name,B.level)&&this.approvalCallback){if(yield{type:"tool_call",id:z.id,name:z.name,input:z.input},!await this.approvalCallback(z.name,U,B.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 L=await c9(z.name,U);yield{type:"tool_result",id:z.id,name:z.name,result:L},H.push({type:"tool_result",tool_use_id:z.id,content:L});continue}yield{type:"tool_call",id:z.id,name:z.name,input:z.input};let M=await c9(z.name,U);yield{type:"tool_result",id:z.id,name:z.name,result:M},H.push({type:"tool_result",tool_use_id:z.id,content:M})}Q.push({role:"user",content:H})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function gG($){let Z=[];for(let J of $)if(J.role==="user")if(J.images?.length){let Y=J.images.map((Q)=>({type:"image",source:{type:"base64",media_type:Q.mediaType,data:Q.base64}}));Y.push({type:"text",text:J.content}),Z.push({role:"user",content:Y})}else Z.push({role:"user",content:J.content});else if(J.role==="assistant")if(J.toolCalls?.length){let Y=[];if(J.content)Y.push({type:"text",text:J.content});for(let Q of J.toolCalls)Y.push({type:"tool_use",id:Q.id,name:Q.name,input:Q.input});Z.push({role:"assistant",content:Y}),Z.push({role:"user",content:J.toolCalls.map((Q)=>({type:"tool_result",tool_use_id:Q.id,content:Q.result}))})}else Z.push({role:"assistant",content:J.content});return Z}r();import{existsSync as E$,mkdirSync as d3,readdirSync as l3,readFileSync as h7,unlinkSync as o3,renameSync as o9}from"fs";import{join as Y$}from"path";class a9{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=Y$($,"sessions"),this.archiveDir=Y$($,"sessions","archive"),!E$(this.sessionsDir))d3(this.sessionsDir,{recursive:!0});if(!E$(this.archiveDir))d3(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(!E$(this.sessionsDir))return[];return l3(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=Y$(this.sessionsDir,`${$}.json`);if(!E$(Z))return null;try{let J=JSON.parse(h7(Z,"utf-8"));return{messageCount:J.messages.length,updated:J.updated}}catch{return null}}delete($){let Z=Y$(this.sessionsDir,`${$}.json`);if(E$(Z))return o3(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},J=Y$(this.sessionsDir,`${$}.json`);return x(J,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=Y$(this.sessionsDir,`${$}.json`);if(!E$(Z))return!1;let J=Y$(this.archiveDir,`${$}.json`);return o9(Z,J),!0}archiveAll(){let $=[],Z=this.list().filter((J)=>J!==this.current.name);for(let J of Z)if(this.archive(J))$.push(J);return $}unarchive($){let Z=Y$(this.archiveDir,`${$}.json`);if(!E$(Z))return!1;let J=Y$(this.sessionsDir,`${$}.json`);return o9(Z,J),!0}listArchived(){if(!E$(this.archiveDir))return[];return l3(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=Y$(this.archiveDir,`${$}.json`);if(!E$(Z))return null;try{let J=JSON.parse(h7(Z,"utf-8"));return{messageCount:J.messages.length,updated:J.updated}}catch{return null}}deleteArchived($){let Z=Y$(this.archiveDir,`${$}.json`);if(E$(Z))return o3(Z),!0;return!1}loadOrCreate($){let Z=Y$(this.sessionsDir,`${$}.json`);if(E$(Z))try{return JSON.parse(h7(Z,"utf-8"))}catch{let Y=Y$(this.sessionsDir,`${$}.corrupt.json`);try{o9(Z,Y)}catch{}}let J={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return x(Z,JSON.stringify(J,null,2)),J}saveLastSession(){let $=Y$(this.sessionsDir,"..","last-session.txt");x($,this.current.name)}getLastSession(){let $=Y$(this.sessionsDir,"..","last-session.txt");if(!E$($))return null;try{let Z=h7($,"utf-8").trim();if(!Z||!E$(Y$(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}save(){let $=Y$(this.sessionsDir,`${this.current.name}.json`);x($,JSON.stringify(this.current,null,2))}}import{existsSync as i3,readdirSync as uG,readFileSync as n3}from"fs";import{join as i9}from"path";$$();import{existsSync as r9,readFileSync as a3}from"fs";import{basename as mG,join as g7}from"path";function r3(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${yZ()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),I)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let J=cG($);if(J)Z.push(`Project: ${J}`);let Y=pG($);if(Y)Z.push(Y);return Z.join(`
|
|
418
|
+
`)}function cG($){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"]],J=[];for(let[Q,X]of Z)if(r9(g7($,Q)))J.push(X);if(J.length===0)return null;let Y=mG($);try{let Q=g7($,"package.json");if(r9(Q)){let X=JSON.parse(a3(Q,"utf-8"));if(X.name)Y=X.name}}catch{}return`Project: ${Y} (${J.join(", ")})`}function pG($){if(!r9(g7($,".git")))return null;let Z=[];try{let J=a3(g7($,".git","HEAD"),"utf-8").trim(),Y=J.startsWith("ref: refs/heads/")?J.slice(16):J.slice(0,8);Z.push(`Git branch: ${Y}`)}catch{return Z.push("Git: initialized"),Z.join(`
|
|
363
419
|
`)}try{let J=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(J.exitCode===0){let Y=new TextDecoder().decode(J.stdout).trim();if(Y)Z.push(`Last commit: ${Y}`)}}catch{}try{let J=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(J.exitCode===0){let Y=new TextDecoder().decode(J.stdout).trim();if(Y){let Q=Y.split(`
|
|
364
420
|
`),X=Q.slice(0,15);if(Q.length>15)X.push(`... and ${Q.length-15} more files`);Z.push(`Uncommitted changes:
|
|
365
421
|
`+X.join(`
|
|
@@ -367,10 +423,11 @@ ${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};Y=[{role:"us
|
|
|
367
423
|
`).slice(0,10);Z.push(`Staged:
|
|
368
424
|
`+Q.join(`
|
|
369
425
|
`))}}}catch{}return Z.length>0?Z.join(`
|
|
370
|
-
`):null}function
|
|
426
|
+
`):null}function s3($,Z){if(!i3($))return[];let J=[],Y=uG($,{withFileTypes:!0});for(let Q of Y)if(Q.isFile()&&Q.name.endsWith(".md")){let X=n3(i9($,Q.name),"utf-8");J.push({name:Q.name.replace(".md",""),content:X.trim(),source:Z})}else if(Q.isDirectory()){let X=i9($,Q.name,"SKILL.md");if(i3(X)){let K=n3(X,"utf-8");J.push({name:Q.name,content:K.trim(),source:Z})}}return J}function t3($){let Z=s3($,"global"),J=i9(process.cwd(),".smolerclaw","skills"),Y=s3(J,"local"),Q=new Map;for(let X of Z)Q.set(X.name,X);for(let X of Y)Q.set(X.name,X);return[...Q.values()]}function e3($){if($.length===0)return"No skills loaded.";return`Skills:
|
|
371
427
|
`+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
|
|
372
|
-
`)}function
|
|
373
|
-
ALWAYS respond in ${X}. This is a hard requirement.`)}if(Y.push(`---
|
|
428
|
+
`)}function n9($,Z,J="auto"){let Y=[];for(let Q of Z)Y.push(Q.content);if(J&&J!=="auto"){let X={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[J]||J;Y.push(`## Language Override
|
|
429
|
+
ALWAYS respond in ${X}. This is a hard requirement.`)}if($4())Y.push(`---
|
|
430
|
+
`+R3());if(Y.push(`---
|
|
374
431
|
## Meta-Learning & Self-Awareness
|
|
375
432
|
You are aware of your own updates and capabilities. Your usage patterns are being observed to improve your helpfulness.
|
|
376
433
|
|
|
@@ -390,34 +447,34 @@ You are aware of your own updates and capabilities. Your usage patterns are bein
|
|
|
390
447
|
## Environment
|
|
391
448
|
The user's current working directory and project info. Use this context when they ask about code or files.
|
|
392
449
|
|
|
393
|
-
`+
|
|
450
|
+
`+r3()),$)Y.push(`## User Instructions
|
|
394
451
|
`+$);return Y.join(`
|
|
395
452
|
|
|
396
|
-
`)}var
|
|
397
|
-
`)){if(
|
|
398
|
-
`),
|
|
399
|
-
`).filter(Boolean).slice(-
|
|
453
|
+
`)}var dG=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function _$($){return dG?"":$}var W={altOn:_$("\x1B[?1049h"),altOff:_$("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:_$("\x1B[1m"),dim:_$("\x1B[2m"),italic:_$("\x1B[3m"),underline:_$("\x1B[4m"),reset:_$("\x1B[0m"),inv:_$("\x1B[7m"),fg:($)=>_$(`\x1B[38;5;${$}m`),bg:($)=>_$(`\x1B[48;5;${$}m`)};var b={user:W.fg(75),ai:W.fg(114),tool:W.fg(215),err:W.fg(196),sys:W.fg(245),prompt:W.fg(220),code:W.fg(180),heading:W.fg(75),link:W.fg(39),quote:W.fg(245)},lG={primary:W.fg(75),secondary:W.fg(39),accent:W.fg(220),muted:W.fg(245),header:W.fg(81)},oG={primary:W.fg(215),secondary:W.fg(220),accent:W.fg(196),muted:W.fg(245),header:W.fg(214)},aG={primary:W.fg(183),secondary:W.fg(157),accent:W.fg(147),muted:W.fg(242),header:W.fg(183)};function s9($){switch($){case"productivity":return lG;case"spillover_alert":return oG;case"sharpen_or_relax":return aG}}function R($){process.stdout.write($)}var rG=/\x1b\[[0-9;]*[a-zA-Z]/g;function L4($){return $.replace(rG,"")}function iG($){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 K$($){let Z=L4($),J=0;for(let Y of Z)J+=iG(Y);return J}function D4($,Z){if(Z<10)Z=10;let J=[];for(let Y of $.split(`
|
|
454
|
+
`)){if(K$(Y)<=Z){J.push(Y);continue}let K=L4(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=nG(Y);for(let z=0;z<V.length;z++)if(H&&z===0)V[z]=H+V[z]+W.reset;else if(H)V[z]=H+V[z]+W.reset;J.push(...V)}return J}function nG($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function m7($,Z){let J=Z??(process.stdout.columns||80),Y=$.split(`
|
|
455
|
+
`),Q=[],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 M=K?` ${K}`:"";Q.push(` ${W.dim}\u250C\u2500\u2500${M}${"\u2500".repeat(Math.max(1,40-M.length))}${W.reset}`)}else X=!1,K="",Q.push(` ${W.dim}\u2514${"\u2500".repeat(42)}${W.reset}`);continue}if(X){Q.push(` ${W.dim}\u2502${W.reset} ${b.code}${G}${W.reset}`);continue}if(!G.trim()){Q.push("");continue}let H=G.match(/^(#{1,3})\s+(.+)/);if(H){let M=H[1].length,O=H[2],L=M===1?"\u2501":M===2?"\u2500":"\xB7";Q.push(` ${b.heading}${W.bold}${L} ${v1(O)}${W.reset}`);continue}if(G.trimStart().startsWith(">")){let M=G.replace(/^\s*>\s?/,"");t9(Q,` ${b.quote}\u2502 ${v1(M)}${W.reset}`,J);continue}let z=G.match(/^(\s*)([-*+])\s+(.+)/);if(z){let M=Math.floor(z[1].length/2),O=z[3],L=" ".repeat(M);t9(Q,` ${L}${W.dim}\u2022${W.reset} ${v1(O)}`,J);continue}let U=G.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(U){let M=Math.floor(U[1].length/2),O=U[2],L=U[3],T=" ".repeat(M);t9(Q,` ${T}${W.dim}${O}.${W.reset} ${v1(L)}`,J);continue}if(/^[-*_]{3,}\s*$/.test(G.trim())){Q.push(` ${W.dim}${"\u2500".repeat(40)}${W.reset}`);continue}let B=` ${v1(G)}`;if(K$(B)>J)for(let M of D4(B,J))Q.push(M);else Q.push(B)}if(X)Q.push(` ${W.dim}\u2514${"\u2500".repeat(42)}${W.reset}`);return Q}function t9($,Z,J){if(K$(Z)>J)for(let Y of D4(Z,J))$.push(Y);else $.push(Z)}function v1($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${W.inv} $1 ${W.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${W.bold}${W.italic}$1${W.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${W.bold}$1${W.reset}`),Z=Z.replace(/__(.+?)__/g,`${W.bold}$1${W.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${W.italic}$1${W.reset}`),Z=Z.replace(/_(.+?)_/g,`${W.italic}$1${W.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${W.underline}$1${W.reset} ${b.link}($2)${W.reset}`),Z}import{existsSync as sG,readFileSync as tG,writeFileSync as eG}from"fs";var e9=500;class $Z{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>e9)this.entries=this.entries.slice(-e9);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(sG(this.filePath)){let $=tG(this.filePath,"utf-8");this.entries=$.split(`
|
|
456
|
+
`).filter(Boolean).slice(-e9)}}catch{}}save(){try{eG(this.filePath,this.entries.join(`
|
|
400
457
|
`)+`
|
|
401
|
-
`)}catch{}}}import{join as DG}from"path";var HG=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],qG=" ";function u9($,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=RG($,J),G=Q-Y||1,z=V.map((U)=>{if(U===0&&Y===0)return qG;let M=(U-Y)/G,O=Math.min(7,Math.floor(M*8));return HG[O]}).join(""),B=X?`${X}${z}${W.reset}`:z;if(K)return`${W.dim}${Y.toFixed(0)}${W.reset}${B}${W.dim}${Q.toFixed(0)}${W.reset}`;return B}var WG="\u2588",UG="\u2589",BG="\u258A",NG="\u258B",MG="\u258C",CG="\u258D",jG="\u258E",OG="\u258F",FG="\u2591",EG=[" ",OG,jG,CG,MG,NG,BG,UG];function d9($,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),B=WG.repeat(G);if(z>0&&G<J)B+=EG[z];let U=J-W$(B);B+=FG.repeat(Math.max(0,U));let M=X?`${X}${B}${W.reset}`:B,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 x0($,Z){let J=[];if(J.push(`${k.ai}${$.model}${W.reset}`),$.project)J.push(`${k.heading}${$.project}${W.reset}`);if($.tokens){let{input:K,output:V}=$.tokens;J.push(`${W.dim}${S3(K)}/${S3(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=W$(Y),X=Math.max(0,Z-Q-2);return`${W.inv} ${Y}${" ".repeat(X)} ${W.reset}`}function l9($,Z=40){let J=[];J.push(`${W.dim}${"\u2500".repeat(Z)}${W.reset}`),J.push(`${k.heading}${W.bold} System${W.reset}`);let Y=u9($.cpu,{width:15,color:W.fg(75)}),Q=d9($.currentCpu,{width:10,showValue:!1,color:W.fg(75)});J.push(` ${W.dim}CPU:${W.reset} ${Y} ${Q} ${$.currentCpu.toFixed(0)}%`);let X=u9($.memory,{width:15,color:W.fg(114)}),K=d9($.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 RG($,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 S3($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function S0($,Z,J={}){let{title:Y="",padding:Q=1,borderColor:X=W.dim,titleColor:K=k.heading}=J,V=Z-2-Q*2,G=[];if(Y){let z=W$(Y),B=2,U=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(U)}\u2510${W.reset}`)}else G.push(`${X}\u250C${"\u2500".repeat(Z-2)}\u2510${W.reset}`);let H=" ".repeat(Q);for(let z of $){let B=W$(z)>V?x3(z,V):z,U=W$(B),M=Math.max(0,V-U);G.push(`${X}\u2502${W.reset}${H}${B}${" ".repeat(M)}${H}${X}\u2502${W.reset}`)}return G.push(`${X}\u2514${"\u2500".repeat(Z-2)}\u2518${W.reset}`),G}function o9($,Z,J,Y,Q={}){let X=S0($,Y,Q);for(let K=0;K<X.length;K++)F(W.to(Z+K,J)),F(X[K])}var b7={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},LG={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function a9($,Z={}){let{width:J=60,showActions:Y=!0,compact:Q=!1}=Z,X=[],K=LG[$.category]||"\uD83D\uDCA1",V=b7.dimYellow+b7.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=w7($.explanation,G);for(let z of H)X.push(` ${V} ${_$(z)}${W.reset}`);if($.suggestedAction)X.push(` ${b7.dimCyan} \u2192 ${$.suggestedAction.label}${W.reset}`);if(Y)X.push(` ${W.dim} [Y] Aceitar [N] Ignorar${W.reset}`);return X}function w3($,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} ${b7.dimYellow}${H}${W.reset}`);let z=Z-4,B=X.description.length>z?X.description.slice(0,z-3)+"...":X.description;J.push(` ${W.dim}${B}${W.reset}`);let U=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 y7($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:w3($,Z)}}class w0{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;F(W.to($,1)),F(x0(this.statusConfig,this.width))}clearScreen(){F(W.clear),F(W.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)F(W.to(Z,1)),F(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,B=H.col??V,U=H.width??X,M=H.height??Math.floor(Q/Math.ceil($.length/Z));if(this.drawDashboardPanel(H,z,B,U,M),(G+1)%Z===0)K+=M+J,V=1+J;else V+=U+J}this.renderStatusBar()}drawDashboardPanel($,Z,J,Y,Q){let X=Q-2,K=$.content.slice(0,X);o9(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:l9($,35)}],columns:1,gap:1}}}function _7($,Z){F(`\x1B[${$};${Z}r`)}function v7(){F("\x1B[r")}var PG=new w0;u0();class n9{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=m9("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 w0}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 c9(DG(this.dataDir,"history"));this.setupEventListeners(),F(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(V$.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(V$.on("status:update",($)=>{let Z=$.level==="error"?k.err:$.level==="warning"?k.prompt:$.level==="success"?k.sys:W.dim;if(this.lines.push({text:` ${Z}[${$.source}]${W.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(V$.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${k.prompt}\u26A0 ${$.message}${W.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${k.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(V$.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:` ${k.sys}[pomodoro] ${$.message}${W.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${k.err}[${$.taskType}] ${$.message}${W.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(V$.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(V$.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(),F(W.show),F(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=k7(this.streamBuf).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=k7(this.streamBuf).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:` ${k.tool}\u2699 ${$}${W.reset} ${W.dim}${Y}${W.reset}`}),this.renderMessages()}showToolResult($,Z){let J=Z.split(`
|
|
402
|
-
`),Y=8,Q=J.slice(0,8);for(let X of Q){let K=X.length>this.width-6?X.slice(0,this.width-9)+"...":X;this.lines.push({text:` ${W.dim}${K}${W.reset}`})}if(J.length>8)this.lines.push({text:` ${W.dim}... (${J.length-8} more lines)${W.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${
|
|
403
|
-
`)process.stdin.removeListener("data",J),this.lines.push({text:` ${
|
|
404
|
-
`){if(
|
|
405
|
-
`){if(O.length>0&&J<O.length)z(O[J].link);return}if(M==="\x1B[A"||M==="w"&&!Q){if(J>0)J--,H();return}if(M==="\x1B[B"||M==="s"&&!Q){if(J<O.length-1)J++,H();return}if(M==="\t"){if(!X)X=K[0]||"";else{let
|
|
406
|
-
`))this.lines.push({text:` ${
|
|
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=J.slice(0,8);for(let X of Q){let K=X.length>this.width-6?X.slice(0,this.width-9)+"...":X;this.lines.push({text:` ${W.dim}${K}${W.reset}`})}if(J.length>8)this.lines.push({text:` ${W.dim}... (${J.length-8} more lines)${W.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${b.prompt}? ${$}${W.reset} ${W.dim}[y]es / [n]o / [a]ll${W.reset}`}),this.renderAll(),new Promise((Z)=>{let J=(Y)=>{let Q=Y.toString().toLowerCase();if(Q==="y"||Q==="\r"||Q===`
|
|
460
|
+
`)process.stdin.removeListener("data",J),this.lines.push({text:` ${b.sys}approved${W.reset}`}),this.renderAll(),Z(!0);else if(Q==="n"||Q==="\x1B")process.stdin.removeListener("data",J),this.lines.push({text:` ${b.err}rejected${W.reset}`}),this.renderAll(),Z(!1);else if(Q==="a")process.stdin.removeListener("data",J),this.lines.push({text:` ${b.sys}approved all for this session${W.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",J),setTimeout(()=>{process.stdin.removeListener("data",J),this.lines.push({text:` ${W.dim}timeout \u2014 auto-rejected${W.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let J=$.findIndex((H)=>H.isCurrent);if(J<0)J=0;let Y="",Q=!1,X=()=>{if(!Y)return $;let H=Y.toLowerCase();return $.filter((z)=>z.name.toLowerCase().includes(H))},K=()=>{let U=this.height-2-2,B=X();if(J>=B.length)J=Math.max(0,B.length-1);let M=2,O=2,L=U-M-O,T=Math.max(1,L),_=0;if(B.length>T)_=Math.max(0,J-Math.floor(T/2)),_=Math.min(_,B.length-T);let V$=B.slice(_,_+T);if(R(W.hide),R(W.to(3,1)),R(W.clearLine),Q)R(` ${b.heading}${W.bold}Sessions${W.reset} ${W.dim}filter: ${Y}\u2588${W.reset}`);else R(` ${b.heading}${W.bold}Sessions${W.reset} ${W.dim}(${B.length})${W.reset}`);R(W.to(4,1)),R(W.clearLine);for(let v=0;v<T;v++){let d=2+M+v+1;if(R(W.to(d,1)),R(W.clearLine),v>=V$.length)continue;let F=V$[v],N=_+v===J,j=F.isCurrent?"*":" ",E=F.isArchived?`${W.dim}[arch] ${W.reset}`:" ",w=`${F.messageCount} msgs`.padEnd(10),k=CH(F.updated);if(N)R(` ${b.prompt}${W.bold}\u203A ${j} ${E}${b.prompt}${W.bold}${F.name.padEnd(20)}${W.reset} ${W.dim}${w} ${k}${W.reset}`);else{let l=F.isArchived?W.dim:b.sys;R(` ${j} ${E}${l}${F.name.padEnd(20)}${W.reset} ${W.dim}${w} ${k}${W.reset}`)}}for(let v=V$.length;v<T;v++){let d=2+M+v+1;R(W.to(d,1)),R(W.clearLine)}let s=2+M+T+1;if(R(W.to(s,1)),R(W.clearLine),B.length>T){let v=Math.round((J+1)/B.length*100);R(` ${W.dim}${_>0?"\u2191":" "} ${v}% ${_+T<B.length?"\u2193":" "}${W.reset}`)}let y=this.height-2;R(W.to(y,1)),R(W.clearLine),R(` ${W.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${W.reset}`)},V=(H)=>{this.pickerActive=!1,process.stdin.removeListener("data",G),this.renderAll(),Z(H)},G=(H)=>{let z=H.toString("utf-8"),U=X();if(z==="\x1B"&&H.length===1){if(Q)Q=!1,Y="",K();else V(null);return}if(z==="\x03"){V(null);return}if(z==="\r"||z===`
|
|
461
|
+
`){if(U.length>0&&J<U.length)V({action:"load",name:U[J].name});return}if(z==="\x1B[A"||z==="w"&&!Q){if(J>0)J--,K();return}if(z==="\x1B[B"||z==="s"&&!Q){if(J<U.length-1)J++,K();return}if(z==="d"&&Q===!1){if(U.length>0&&J<U.length){let B=U[J];if(!B.isCurrent)V({action:"delete",name:B.name,isArchived:B.isArchived})}return}if(z==="a"&&Q===!1){if(U.length>0&&J<U.length){let B=U[J];if(!B.isCurrent){let M=B.isArchived?"unarchive":"archive";V({action:M,name:B.name})}}return}if(z==="/"&&Q===!1){Q=!0,Y="",K();return}if(Q){if(z==="\x7F"||z==="\b"){if(Y.length>0)Y=Y.slice(0,-1),J=0,K();else Q=!1,K();return}if(z.length===1&&z>=" "){Y+=z,J=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 J=0,Y="",Q=!1,X="",K=[...new Set($.map((B)=>B.category))].sort(),V=()=>{let B=X?$.filter((M)=>M.category===X):$;if(Y){let M=Y.toLowerCase();B=B.filter((O)=>O.title.toLowerCase().includes(M)||O.source.toLowerCase().includes(M))}return B},G=(B)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[B]||B},H=()=>{let O=this.height-2-2,L=V();if(J>=L.length)J=Math.max(0,L.length-1);let T=2,_=2,V$=O-T-_,s=Math.max(1,V$),y=0;if(L.length>s)y=Math.max(0,J-Math.floor(s/2)),y=Math.min(y,L.length-s);let v=L.slice(y,y+s);if(R(W.hide),R(W.to(3,1)),R(W.clearLine),Q)R(` ${b.heading}${W.bold}Noticias${W.reset} ${W.dim}filtro: ${Y}\u2588${W.reset}`);else{let q=X?G(X):"Todas";R(` ${b.heading}${W.bold}Noticias${W.reset} ${W.dim}(${L.length}) ${q}${W.reset}`)}R(W.to(4,1)),R(W.clearLine);for(let q=0;q<s;q++){let N=2+T+q+1;if(R(W.to(N,1)),R(W.clearLine),q>=v.length)continue;let j=v[q],E=y+q===J,w=j.time?`[${j.time}]`:" ",k=this.width-30,l=j.title.length>k?j.title.slice(0,k-1)+"\u2026":j.title;if(E)R(` ${b.prompt}${W.bold}\u203A ${w} ${l}${W.reset} ${W.dim}(${j.source})${W.reset}`);else R(` ${W.dim}${w}${W.reset} ${b.sys}${l}${W.reset} ${W.dim}(${j.source})${W.reset}`)}for(let q=v.length;q<s;q++){let N=2+T+q+1;R(W.to(N,1)),R(W.clearLine)}let d=2+T+s+1;if(R(W.to(d,1)),R(W.clearLine),L.length>s){let q=Math.round((J+1)/L.length*100);R(` ${W.dim}${y>0?"\u2191":" "} ${q}% ${y+s<L.length?"\u2193":" "}${W.reset}`)}let F=this.height-2;R(W.to(F,1)),R(W.clearLine),R(` ${W.dim}W/S or \u2191\u2193 navigate Enter open Esc cancel / filter Tab category${W.reset}`)},z=(B)=>{this.pickerActive=!1,process.stdin.removeListener("data",U),this.renderAll(),Z(B)},U=(B)=>{let M=B.toString("utf-8"),O=V();if(M==="\x1B"&&B.length===1){if(Q)Q=!1,Y="",H();else z(null);return}if(M==="\x03"){z(null);return}if(M==="\r"||M===`
|
|
462
|
+
`){if(O.length>0&&J<O.length)z(O[J].link);return}if(M==="\x1B[A"||M==="w"&&!Q){if(J>0)J--,H();return}if(M==="\x1B[B"||M==="s"&&!Q){if(J<O.length-1)J++,H();return}if(M==="\t"){if(!X)X=K[0]||"";else{let L=K.indexOf(X);X=L<K.length-1?K[L+1]:""}J=0,H();return}if(M==="/"&&!Q){Q=!0,Y="",H();return}if(Q){if(M==="\x7F"||M==="\b"){if(Y.length>0)Y=Y.slice(0,-1),J=0,H();else Q=!1,H();return}if(M.length===1&&M>=" "){Y+=M,J=0,H();return}}};process.stdin.on("data",U),H()})}showUsage($){this.lines.push({text:` ${W.dim}tokens: ${$}${W.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${b.err}\u2717 ${$}${W.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
|
|
463
|
+
`))this.lines.push({text:` ${b.sys}${Z}${W.reset}`});this.lines.push({text:""}),this.renderAll()}clearMessages(){this.lines=[],this.renderAll()}updateModel($){this.model=$,this.renderHeader()}updateSession($){this.sessionName=$,this.renderHeader()}enableInput(){this.inputBuf="",this.inputPos=0,this.isStreaming=!1,this.history?.reset(),this.renderInput()}disableInput(){R(W.hide)}getViewMode(){return this.viewMode}enterChatMode(){if(this.viewMode==="chat")return;this.viewMode="chat",this.viewManager.enterChatMode(),d7(),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,Q=p7(this.metaLearningEntries,Y);Z=[...Z,Q]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),u7(3,this.height-2),this.renderDashboard()}updateDashboardPanel($,Z){let J=this.dashboardContent.find((Y)=>Y.id===$);if(J){if(J.content=Z,this.viewMode==="dashboard")this.renderDashboard()}}updateStatusBar($){if($.project!==void 0)this.activeProject=$.project;if($.inputTokens!==void 0)this.inputTokens=$.inputTokens;if($.outputTokens!==void 0)this.outputTokens=$.outputTokens;if($.vaultStatus!==void 0)this.vaultStatus=$.vaultStatus;this.renderStickyStatusBar()}setStatusBarEnabled($){this.statusBarEnabled=$,this.render()}showInsight($){if(this.activeInsight)this.dismissInsight();this.activeInsight=$;let Z=XZ($,{width:this.width-4,showActions:!0});this.insightSnippetLines=Z.length,this.renderInsightDisplay(Z),this.insightDisplayed=!0}renderInsightDisplay($){let Z=this.height-1-this.insightSnippetLines-1;R(W.hide);for(let J=0;J<$.length;J++)R(W.to(Z+J,1)),R(W.clearLine),R($[J]);R(W.show)}dismissInsight(){if(!this.activeInsight||!this.insightDisplayed)return;let $=this.height-1-this.insightSnippetLines-1;R(W.hide);for(let Z=0;Z<this.insightSnippetLines;Z++)R(W.to($+Z,1)),R(W.clearLine);R(W.show),this.activeInsight=null,this.insightSnippetLines=0,this.insightDisplayed=!1,this.renderMessages()}acceptInsight(){if(!this.activeInsight)return;let $=this.activeInsight,Z={insightId:$.id,insight:$,timestamp:Date.now()};if(H$.emit("insight:accepted",Z),this.lines.push({text:` ${b.sys}\u2713 Dica aceita: ${$.title}${W.reset}`}),$.suggestedAction)this.lines.push({text:` ${W.dim}Executando: ${$.suggestedAction.command}${W.reset}`});this.dismissInsight()}hasActiveInsight(){return this.activeInsight!==null&&this.insightDisplayed}updateMetaLearningEntries($){if(this.metaLearningEntries=$,this.viewMode==="dashboard"){let Z=p7($,Math.floor(this.width/2)-4);this.updateDashboardPanel("meta-learning",Z.content)}}setPersonaMode($){if(this.personaMode=$,this.palette=s9($),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((J)=>J.title===$.title))this.metaLearningEntries=this.metaLearningEntries.map((J)=>J.title===$.title?{...J,frequency:J.frequency+1,lastSeen:Date.now()}:J);else this.metaLearningEntries=[...this.metaLearningEntries,{...$,frequency:1,lastSeen:Date.now()}]}renderDashboard(){R(W.hide),R(W.clear),this.renderHeader();let $=2,Z=2+(this.statusBarEnabled?1:0),J=this.height-$-Z,Y=this.dashboardContent,Q=Math.min(2,Y.length),X=Math.ceil(Y.length/Q),K=1,V=Math.floor((this.width-K*(Q+1))/Q),G=Math.floor((J-K*(X+1))/X),H=0;for(let z=0;z<X;z++)for(let U=0;U<Q&&H<Y.length;U++){let B=Y[H],M=$+K+z*(G+K)+1,O=K+U*(V+K)+1;this.drawDashboardPanel(B,M,O,V,G),H++}if(this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),R(W.show)}drawDashboardPanel($,Z,J,Y,Q){let X=this.personaMode==="sharpen_or_relax"?this.palette.muted:W.dim,K=this.palette.primary,V=h1($.content.slice(0,Q-2),Y,{title:$.title,borderColor:X,titleColor:K});for(let G=0;G<V.length&&G<Q;G++)R(W.to(Z+G,J)),R(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 J={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};R(W.to($,1)),R(this.renderPersonaAwareStatusBar(J))}renderPersonaAwareStatusBar($){let Z=f1($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${L4(Z)}${W.reset}`;return Z}render(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(R(W.hide),R(W.clear),this.renderHeader(),this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),R(W.show)}renderAll(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput()}renderHeader(){R(W.to(1,1));let $=this.palette.header,Z=this.getHeaderBgColor();R(Z),R(W.inv);let Y=` smolerclaw${this.personaMode!=="productivity"?` [${this.getPersonaLabel()}]`:""}`,Q=[this.model,this.sessionName];if(this.sessionCost)Q.push(this.sessionCost);if(this.authInfo)Q.push(this.authInfo);let X=Q.join(" | ")+" ",K=Math.max(1,this.width-K$(Y)-X.length);R(Y+" ".repeat(K)+X),R(W.reset),R(W.to(2,1));let V=this.personaMode==="sharpen_or_relax"?this.palette.muted:W.dim;R(`${V}${"\u2500".repeat(this.width)}${W.reset}`)}getHeaderBgColor(){switch(this.personaMode){case"productivity":return"";case"spillover_alert":return W.bg(52);case"sharpen_or_relax":return W.bg(53)}}renderMessages(){let J=2+(this.statusBarEnabled?1:0),Y=this.height-2-J,Q=[...this.lines,...this.streamLines],X=Q.length,K=Math.max(0,X-Y-this.scrollOffset),V=Math.min(X,K+Y),G=Q.slice(K,V);R(W.hide);for(let H=0;H<Y;H++)if(R(W.to(2+H+1,1)),R(W.clearLine),H<G.length)R(G[H].text)}completeInput($){let Z=$.split(" "),J=Z[0];if(Z.length===1){let K=this.commands.filter((V)=>V.startsWith(J));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[J];if(!Y||Y.length===0)return null;let Q=Z[Z.length-1].toLowerCase(),X=Y.filter((K)=>K.toLowerCase().startsWith(Q));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>Q.length)return Z[Z.length-1]=K,{value:Z.join(" "),options:X.join(" ")};return{value:$,options:X.join(" ")}}if(!Q&&Y.length>0)return{value:$,options:Y.join(" ")};return null}renderInput(){let $=this.height-1,Z=this.height;if(R(W.to($,1)),R(W.clearLine),R(`${W.dim}${"\u2500".repeat(this.width)}${W.reset}`),R(W.to(Z,1)),R(W.clearLine),this.isStreaming){let J=((Date.now()-this.streamStartTime)/1000).toFixed(1);R(` ${b.ai}${this.getSpinnerChar()}${W.reset} ${W.dim}streaming... ${J}s${W.reset}`),R(W.hide)}else{let J=K$(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;R(`${b.prompt}\u276F${W.reset} ${J}`);let Y=this.inputBuf.slice(0,this.inputPos),Q=K$(Y)+3;R(W.to(Z,Math.min(Q,this.width))),R(W.show)}}onKey($){if(this.pickerActive)return;let Z=$.toString("utf-8");if(this.hasActiveInsight()){let J=Z.toLowerCase();if(J==="y"){this.acceptInsight();return}if(J==="n"||Z==="\x1B"){this.dismissInsight();return}this.dismissInsight()}if(Z==="\x03"){if(this.isStreaming){this.onCancel?.();return}let J=Date.now(),Y=1500;if(this.inputBuf.length>0){this.inputBuf="",this.inputPos=0,this.lastCtrlCTime=J,this.renderInput();return}if(J-this.lastCtrlCTime<Y){this.onExit?.();return}this.lastCtrlCTime=J,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 J=this.completeInput(this.inputBuf);if(J){if(this.inputBuf=J.value,this.inputPos=this.inputBuf.length,this.renderInput(),J.options)this.showSystem(J.options)}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!QY(Z)){let J=Z.replace(/\r?\n/g," ").trim();if(J.length>0)this.inputBuf=this.inputBuf.slice(0,this.inputPos)+J+this.inputBuf.slice(this.inputPos),this.inputPos+=J.length,this.renderInput();return}if(Z==="\r"||Z===`
|
|
407
464
|
`){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
|
|
408
|
-
`,this.inputPos=this.inputBuf.length,this.renderInput();return}let J=this.inputBuf.trim();if(J)this.history?.add(J),this.inputBuf="",this.inputPos=0,this.scrollOffset=0,this.onSubmit?.(J);return}if(Z==="\x7F"||Z==="\b"){if(this.inputPos>0){let J=
|
|
465
|
+
`,this.inputPos=this.inputBuf.length,this.renderInput();return}let J=this.inputBuf.trim();if(J)this.history?.add(J),this.inputBuf="",this.inputPos=0,this.scrollOffset=0,this.onSubmit?.(J);return}if(Z==="\x7F"||Z==="\b"){if(this.inputPos>0){let J=JY(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-J)+this.inputBuf.slice(this.inputPos),this.inputPos-=J,this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=JY(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=YY(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=YY(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Y),this.renderInput()}break}}return}if(MH(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")u7(3,this.height-2);else d7();this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${b.user}${W.bold} You${W.reset} ${W.dim}${Z}${W.reset}`});else this.lines.push({text:`${b.ai}${W.bold} Claude${W.reset} ${W.dim}${Z}${W.reset}`})}startSpinner(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];this.spinnerFrame=0,this.spinnerTimer=setInterval(()=>{this.spinnerFrame=(this.spinnerFrame+1)%$.length,this.renderInput()},80)}stopSpinner(){if(this.spinnerTimer)clearInterval(this.spinnerTimer),this.spinnerTimer=null}getSpinnerChar(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];return $[this.spinnerFrame%$.length]}addWrapped($){let Z=D4(" "+$,this.width-2);for(let J of Z)this.lines.push({text:J})}addMarkdown($){let Z=m7($,this.width);for(let J of Z)this.lines.push({text:J})}}function QY($){return[...$].length===1}function MH($){if(!QY($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function JY($,Z){if(Z<=0)return 0;if(Z>=2){let J=$.charCodeAt(Z-1),Y=$.charCodeAt(Z-2);if(J>=56320&&J<=57343&&Y>=55296&&Y<=56319)return 2}return 1}function YY($,Z){if(Z>=$.length)return 0;let J=$.charCodeAt(Z);if(J>=55296&&J<=56319&&Z+1<$.length)return 2;return 1}function CH($){let Z=Date.now()-$,J=Math.floor(Z/1000);if(J<60)return"just now";let Y=Math.floor(J/60);if(Y<60)return`${Y}m ago`;let Q=Math.floor(Y/60);if(Q<24)return`${Q}h ago`;let X=Math.floor(Q/24);if(X<30)return`${X}d ago`;return`${Math.floor(X/30)}mo ago`}var m1={"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}},jH={input:3,output:15};function XY($,Z){let J=OH(Z),Y=$.inputTokens/1e6*J.input*100,Q=$.outputTokens/1e6*J.output*100;return{inputCostCents:Y,outputCostCents:Q,totalCostCents:Y+Q}}function OH($){if(m1[$])return m1[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return m1["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return m1["claude-opus-4-20250514"];if(Z.includes("sonnet"))return m1["claude-sonnet-4-20250514"];return jH}class zZ{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=XY($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=XY($,this.model);return`${l7($.inputTokens)} in / ${l7($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${l7(this.totalInput)} in / ${l7(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function l7($){return $.toLocaleString("en-US")}function KY($,Z={}){let{includeToolCalls:J=!0,includeTimestamps:Y=!0}=Z,Q=[];Q.push(`# smolerclaw session: ${$.name}`),Q.push(`Created: ${new Date($.created).toLocaleString()}`),Q.push(""),Q.push("---"),Q.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")Q.push(`## You${K}`),Q.push(""),Q.push(X.content),Q.push("");else{if(Q.push(`## Claude${K}`),Q.push(""),Q.push(X.content),J&&X.toolCalls?.length){Q.push("");for(let V of X.toolCalls){let G=FH(V.name,V.input);Q.push(`> **Tool:** \`${V.name}\`${G}`);let H=V.result.split(`
|
|
409
466
|
`).slice(0,5).join(`
|
|
410
467
|
`);if(H.trim()){Q.push("> ```");for(let z of H.split(`
|
|
411
468
|
`))Q.push(`> ${z}`);Q.push("> ```")}}}if(X.usage)Q.push(""),Q.push(`*Tokens: ${X.usage.inputTokens} in / ${X.usage.outputTokens} out (~$${(X.usage.costCents/100).toFixed(4)})*`);Q.push("")}Q.push("---"),Q.push("")}return Q.join(`
|
|
412
|
-
`)}function
|
|
413
|
-
`)}function
|
|
414
|
-
`)}class
|
|
415
|
-
`);V=
|
|
469
|
+
`)}function FH($,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 o7=[{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 VZ($){let Z=o7.find((X)=>X.id===$);if(Z)return Z.id;let J=$.toLowerCase(),Y=o7.find((X)=>X.alias===J);if(Y)return Y.id;let Q=o7.find((X)=>X.id.includes(J)||X.name.toLowerCase().includes(J));if(Q)return Q.id;return $}function zY($){let Z=["Available models:"];for(let J of o7){let Y=J.id===$?" *":" ",Q=J.tier==="fast"?"\u26A1":J.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${Y} ${J.alias.padEnd(12)} ${Q} ${J.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
|
|
470
|
+
`)}function GZ($){if($.includes(":")){let[J,...Y]=$.split(":");return{provider:J.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 RH={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 VY(){let $=["Providers:"];for(let[Z,J]of Object.entries(RH)){let Y=J.envKey?` (${J.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${J.description}${Y}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
|
|
471
|
+
`)}class HZ{name;apiKey;baseUrl;model;maxTokens;approvalMode="auto";approvalCallback=null;autoApproveAll=!1;constructor($,Z,J){if(this.name=$,this.model=Z,this.maxTokens=J,$==="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,J=!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((Q)=>({role:Q.role,content:Q.content}))];try{let Q=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(!Q.ok){let z=await Q.text();yield{type:"error",error:`${this.name} API error ${Q.status}: ${z.slice(0,200)}`};return}if(!Q.body){yield{type:"error",error:"No response body"};return}let X=Q.body.getReader(),K=new TextDecoder,V="",G=Z.length+$.reduce((z,U)=>z+U.content.length,0),H=0;while(!0){let{done:z,value:U}=await X.read();if(z)break;V+=K.decode(U,{stream:!0});let B=V.split(`
|
|
472
|
+
`);V=B.pop()||"";for(let M of B){if(!M.startsWith("data: "))continue;let O=M.slice(6).trim();if(O==="[DONE]")continue;try{let T=JSON.parse(O).choices?.[0]?.delta;if(T?.content)yield{type:"text",text:T.content},H+=T.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(G/3.5),outputTokens:Math.ceil(H/3.5)},yield{type:"done"}}catch(Q){yield{type:"error",error:Q instanceof Error?Q.message:String(Q)}}}}async function a4(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[J,Y]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),Q=await Z.exited;return{stdout:J.trim(),stderr:Y.trim(),ok:Q===0}}async function GY(){let $=await a4("git","diff","--cached"),Z=await a4("git","diff"),J=await a4("git","ls-files","--others","--exclude-standard"),Y=[];if($.stdout)Y.push(`=== STAGED ===
|
|
416
473
|
`+$.stdout);if(Z.stdout)Y.push(`=== UNSTAGED ===
|
|
417
474
|
`+Z.stdout);if(J.stdout)Y.push(`=== UNTRACKED ===
|
|
418
475
|
`+J.stdout);return Y.join(`
|
|
419
476
|
|
|
420
|
-
`)||"(no changes)"}async function
|
|
477
|
+
`)||"(no changes)"}async function HY(){let $=await a4("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function qY(){return(await a4("git","add","-A")).ok}async function WY($){let Z=await a4("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function UY(){let $=await a4("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var BY={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.
|
|
421
478
|
|
|
422
479
|
Behavior:
|
|
423
480
|
- Write clean, production-grade code. No shortcuts.
|
|
@@ -448,102 +505,108 @@ Behavior:
|
|
|
448
505
|
- Be specific. Show the line, explain the problem, suggest the fix.
|
|
449
506
|
- Check for: error handling, input validation, edge cases, naming, complexity.
|
|
450
507
|
- Don't nitpick formatting unless it affects readability.
|
|
451
|
-
- Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function
|
|
452
|
-
`)}
|
|
508
|
+
- Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function NY($){return BY[$.toLowerCase()]||null}function MY($){let Z=["Personas:"];for(let[J,Y]of Object.entries(BY)){let Q=J===$?" *":" ";Z.push(`${Q} ${J.padEnd(12)} ${Y.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
|
|
509
|
+
`)}$$();async function CY($){try{let Z=I?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:bZ?["pbcopy"]:["xclip","-selection","clipboard"],J=Bun.spawn(Z,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});return J.stdin.write($),J.stdin.end(),await J.exited===0}catch{return!1}}import{existsSync as jY,readFileSync as OY,statSync as FY}from"fs";import{basename as EH,extname as RY,resolve as EY}from"path";var LY=new Set([".png",".jpg",".jpeg",".gif",".webp"]),LH=20971520,DH=new Set([".txt",".md",".markdown",".json",".jsonl",".csv",".tsv",".xml",".yaml",".yml",".toml",".ini",".cfg",".conf",".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".c",".cpp",".h",".hpp",".cs",".html",".htm",".css",".scss",".sass",".less",".sql",".sh",".bash",".zsh",".ps1",".bat",".cmd",".env",".gitignore",".dockerignore",".editorconfig",".log",".diff",".patch",".vue",".svelte",".astro"]),TH=1048576;function DY($){let Z=[],J=$.split(/\s+/),Y=[];for(let Q of J){let X=Q.replace(/^["']|["']$/g,""),K=RY(X).toLowerCase();if(LY.has(K)){let V=EY(X);if(jY(V))try{if(FY(V).size>LH){Y.push(`[image too large: ${X}]`);continue}let z=OY(V).toString("base64"),U=PH(K);Z.push({path:V,mediaType:U,base64:z}),Y.push(`[image: ${X}]`)}catch{Y.push(Q)}else Y.push(Q)}else Y.push(Q)}return{text:Y.join(" "),images:Z}}function PH($){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 TY($){let Z=[],J=$.split(/\s+/),Y=[];for(let Q of J){let X=Q.replace(/^["']|["']$/g,""),K=RY(X).toLowerCase();if(LY.has(K)){Y.push(Q);continue}if(!(DH.has(K)||(X.includes("/")||X.includes("\\"))&&K.length>0)){Y.push(Q);continue}let G=EY(X);if(!jY(G)){Y.push(Q);continue}try{let H=FY(G);if(!H.isFile()){Y.push(Q);continue}if(H.size>TH){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=OY(G,"utf-8"),U=EH(G);Z.push({path:G,name:U,content:z,size:H.size}),Y.push(`[file: ${U}]`)}catch{Y.push(Q)}}return{text:Y.join(" "),files:Z}}f4();f4();import{existsSync as PY,readFileSync as AH}from"fs";import{join as AY}from"path";$$();function IH(){let $=new Date().getDay();return $===0||$===6}function xH(){return IH()?"weekend":"weekday"}async function SH($){let Z=[],J=[],Y=[],Q=new Date,X=new Date(Q);X.setHours(23,59,59,999);let K=AY($,"tasks.json");if(PY(K))try{let H=JSON.parse(AH(K,"utf-8"));for(let z of H){if(z.done)continue;if(z.dueAt){let U=new Date(z.dueAt),B=U<Q,M=!B&&U<=X;if(B)J.push({id:z.id,title:z.title,dueAt:z.dueAt,isOverdue:!0});else if(M)Z.push({id:z.id,title:z.title,dueAt:z.dueAt,isOverdue:!1})}}}catch{}let V=M8(!0);for(let H of V.slice(0,5)){let z=await wH(H);if(z)Y.push(z)}return{hasSpillover:Z.length>0||J.length>0||Y.length>0,urgentTasks:Z,overdueTasks:J,pendingCommits:Y}}async function wH($){if(!PY(AY($.path,".git")))return null;try{let Z=Bun.spawn(["git","status","--porcelain"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),J=await new Response(Z.stdout).text();await Z.exited;let Y=J.trim().length>0,Q=Bun.spawn(["git","rev-list","--count","@{u}..HEAD"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),X=await new Response(Q.stdout).text(),V=await Q.exited===0?parseInt(X.trim())||0:0;if(Y||V>0)return{projectName:$.name,projectPath:$.path,uncommittedChanges:Y,unpushedCommits:V}}catch{}return null}function kH($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function a7($){let Z=xH(),J=await SH($),Y=kH(Z,J.hasSpillover);return{dayType:Z,workloadState:J.hasSpillover?"spillover":"clear",persona:Y,urgentTasks:J.urgentTasks,overdueTasks:J.overdueTasks,pendingCommits:J.pendingCommits}}function bH($){let J=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${J}
|
|
453
510
|
Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${J}
|
|
454
511
|
\u26A0 Trabalho escorrido detectado.`;case"sharpen_or_relax":return`=== BRIEFING DIARIO === ${J}
|
|
455
|
-
Modo: Sharpen or Relax`}}function
|
|
512
|
+
Modo: Sharpen or Relax`}}function yH($){let Z=[];if($.overdueTasks.length>0){Z.push(`
|
|
456
513
|
--- Tarefas Atrasadas ---`);for(let J of $.overdueTasks.slice(0,5)){let Y=J.dueAt?new Date(J.dueAt).toLocaleDateString("pt-BR"):"";Z.push(` \u26A0 ${J.title} (venceu ${Y})`)}}if($.urgentTasks.length>0){Z.push(`
|
|
457
514
|
--- Tarefas Urgentes (Hoje) ---`);for(let J of $.urgentTasks.slice(0,5)){let Y=J.dueAt?new Date(J.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";Z.push(` ! ${J.title} (${Y})`)}}if($.pendingCommits.length>0){Z.push(`
|
|
458
515
|
--- Git Pendente ---`);for(let J of $.pendingCommits){let Y=[];if(J.uncommittedChanges)Y.push("uncommitted");if(J.unpushedCommits>0)Y.push(`${J.unpushedCommits} unpushed`);Z.push(` ${J.projectName}: ${Y.join(", ")}`)}}return Z.join(`
|
|
459
|
-
`)}function
|
|
516
|
+
`)}function _H($){if($.persona!=="sharpen_or_relax")return"";return`
|
|
460
517
|
--- Fim de Semana Livre ---
|
|
461
518
|
|
|
462
519
|
[A] Amolar o Machado
|
|
463
520
|
Estudo de arquitetura, refatoracao, melhoria do CLI
|
|
464
521
|
|
|
465
522
|
[B] Descompressao Criativa
|
|
466
|
-
Projetos paralelos sem prazo, foco pessoal/familia`}function
|
|
523
|
+
Projetos paralelos sem prazo, foco pessoal/familia`}function vH($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
|
|
467
524
|
--- Sugestao: Timebox ---
|
|
468
525
|
Liquidar pendencias em ${Math.min(90,Z*15)} minutos.
|
|
469
|
-
Depois: descanso merecido.`}async function
|
|
526
|
+
Depois: descanso merecido.`}async function IY($){let Z=[],J=null;if($)J=await a7($),Z.push(bH(J));else Z.push("=== BRIEFING DIARIO ===");let Y=await v4();if(Z.push(Y),J&&J.workloadState==="spillover"){let X=yH(J);if(X)Z.push(X);let K=vH(J);if(K)Z.push(K)}if(J){let X=_H(J);if(X)Z.push(X)}if(I)try{let X=await b$();Z.push(`
|
|
470
527
|
--- Agenda ---
|
|
471
528
|
${X}`)}catch{Z.push(`
|
|
472
529
|
--- Agenda ---
|
|
473
|
-
Outlook nao disponivel.`)}if(I)try{let X=await
|
|
530
|
+
Outlook nao disponivel.`)}if(I)try{let X=await _4();Z.push(`
|
|
474
531
|
--- Sistema ---
|
|
475
|
-
${X}`)}catch{}let Q=J?.persona==="sharpen_or_relax"?2:3;try{let X=await
|
|
532
|
+
${X}`)}catch{}let Q=J?.persona==="sharpen_or_relax"?2:3;try{let X=await B4(["finance","business","tech"],Q);Z.push(`
|
|
476
533
|
${X}`)}catch{Z.push(`
|
|
477
534
|
--- Noticias ---
|
|
478
535
|
Falha ao carregar noticias.`)}return Z.push(`
|
|
479
536
|
======================`),Z.join(`
|
|
480
|
-
`)}
|
|
481
|
-
`);let Y=await
|
|
482
|
-
--- Tarefas do dia ---`),$.push(
|
|
483
|
-
--- Follow-ups pendentes ---`),$.push(
|
|
484
|
-
--- Delegacoes atrasadas ---`),$.push(
|
|
485
|
-
${H}`);if(I)try{let
|
|
486
|
-
--- Agenda ---`),$.push(
|
|
487
|
-
`+
|
|
537
|
+
`)}f4();import{existsSync as fH,readFileSync as hH,writeFileSync as gH}from"fs";import{join as mH}from"path";$$();var xY="",SY=()=>mH(xY,"last-morning.txt");function wY($){xY=$;let Z=SY(),J=new Date().toISOString().split("T")[0];if(!fH(Z))return!0;try{return hH(Z,"utf-8").trim()!==J}catch{return!0}}function kY(){let $=new Date().toISOString().split("T")[0];gH(SY(),$)}async function bY(){let $=[],Z=new Date().getHours(),J=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${J}! Briefing do dia`),$.push(`==============================
|
|
538
|
+
`);let Y=await v4();$.push(Y);let X=l$().filter((U)=>{if(!U.dueAt)return!1;let B=new Date(U.dueAt),M=new Date;return B.toDateString()===M.toDateString()});if(X.length>0)$.push(`
|
|
539
|
+
--- Tarefas do dia ---`),$.push(h4(X));let K=q8();if(K.length>0)$.push(`
|
|
540
|
+
--- Follow-ups pendentes ---`),$.push(z7(K));let G=c4().filter((U)=>U.status==="atrasado");if(G.length>0)$.push(`
|
|
541
|
+
--- Delegacoes atrasadas ---`),$.push(K7(G));let H=w7();if(H)$.push(`
|
|
542
|
+
${H}`);if(I)try{let U=await b$();$.push(`
|
|
543
|
+
--- Agenda ---`),$.push(U)}catch{}try{let U=await B4(["finance","business","tech"],2);$.push(`
|
|
544
|
+
`+U)}catch{}let z=l$();if(z.length>0&&X.length!==z.length)$.push(`
|
|
488
545
|
${z.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
|
|
489
546
|
==============================`),$.join(`
|
|
490
|
-
`)}
|
|
547
|
+
`)}$$();Y4();var g=null,r7=null,qZ=null,WZ=0;function vY($){qZ=$}function fY($="foco",Z=25,J=5){if(g)return`Pomodoro ja ativo: "${g.label}" (${mY()}). Use /pomodoro stop para parar.`;return g={startedAt:Date.now(),durationMs:Z*60000,breakMs:J*60000,label:$,type:"work"},WZ++,gY(),`Pomodoro #${WZ} iniciado: "${$}" (${Z}min trabalho / ${J}min pausa)`}function hY(){if(!g)return"Nenhum pomodoro ativo.";let $=g.label,Z=Math.floor((Date.now()-g.startedAt)/60000);return i7(),g=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function UZ(){if(!g)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=mY();return`${g.type==="work"?"Trabalhando":"Pausa"}: "${g.label}" \u2014 ${$} restante(s) (ciclo #${WZ})`}function gY(){if(!g)return;i7();let $=g.startedAt+g.durationMs-Date.now();if($<=0){yY();return}r7=setTimeout(yY,$)}function yY(){if(!g)return;if(g.type==="work"){let $=`Pomodoro: "${g.label}" concluido! Hora da pausa (${g.breakMs/60000}min).`;_Y("Pausa!",`"${g.label}" concluido. Descanse ${g.breakMs/60000} minutos.`),qZ?.($),g={...g,type:"break",startedAt:Date.now(),durationMs:g.breakMs},gY()}else _Y("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),qZ?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),i7(),g=null}function i7(){if(r7)clearTimeout(r7),r7=null}function mY(){if(!g)return"0min";let $=Math.max(0,g.startedAt+g.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function _Y($,Z){if(!I)return;try{await J4($,Z,{timeout:1e4})}catch{}}function cY(){i7(),g=null}r();f4();$$();Y4();import{existsSync as pY,mkdirSync as cH,readFileSync as pH}from"fs";import{join as uH}from"path";import{randomUUID as dH}from"crypto";var uY="",z$=[],dY=()=>uH(uY,"workflows.json");function c1(){x(dY(),JSON.stringify(z$,null,2))}function lH(){let $=dY();if(!pY($)){z$=BZ(),c1();return}try{let Z=JSON.parse(pH($,"utf-8"));if(!Array.isArray(Z)){z$=BZ(),c1();return}z$=Z.map((J)=>({id:J.id||NZ(),name:J.name||"unnamed",description:J.description||"",steps:Array.isArray(J.steps)?J.steps:[],tags:Array.isArray(J.tags)?J.tags:[],enabled:J.enabled!==!1,createdAt:J.createdAt||new Date().toISOString(),updatedAt:J.updatedAt||new Date().toISOString()}))}catch{z$=BZ(),c1()}}function BZ(){let $=new Date().toISOString();return[{id:NZ(),name:"iniciar-dia",description:"Abrir apps de trabalho: terminal e ferramentas",steps:[{action:"notify",target:"Iniciando ambiente de trabalho..."},{action:"open_app",target:"terminal",label:"Terminal"},{action:"wait",target:"2"},{action:"open_app",target:"vscode",label:"VS Code",on_error:"skip"},{action:"notify",target:"Ambiente pronto!"}],tags:["trabalho","diario"],enabled:!0,createdAt:$,updatedAt:$},{id:NZ(),name:"dev",description:"Ambiente de desenvolvimento: VSCode + Terminal",steps:[{action:"open_app",target:"vscode",label:"VS Code"},{action:"wait",target:"1"},{action:"open_app",target:"terminal",label:"Terminal"}],tags:["dev"],enabled:!0,createdAt:$,updatedAt:$}]}function lY($){if(uY=$,!pY($))cH($,{recursive:!0});lH()}function p1($){let Z=$.toLowerCase().trim();return z$.find((J)=>J.id===$)||z$.find((J)=>J.name.toLowerCase()===Z)||z$.find((J)=>J.name.toLowerCase().includes(Z))||null}function oY($){let Z=[...z$];if($){let J=$.toLowerCase();Z=Z.filter((Y)=>Y.tags.some((Q)=>Q.toLowerCase()===J))}return Z}function MZ($,Z){let J=p1($);if(!J)return null;return z$=z$.map((Y)=>Y.id===J.id?{...Y,...Z,updatedAt:new Date().toISOString()}:Y),c1(),z$.find((Y)=>Y.id===J.id)||null}function aY($){let Z=p1($);if(!Z)return!1;return z$=z$.filter((J)=>J.id!==Z.id),c1(),!0}async function CZ($,Z){let J=p1($);if(!J){let Q=z$.map((X)=>X.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${Q}`}if(!J.enabled)return`Workflow "${J.name}" esta desativado.`;let Y=await rY(J.name,J.steps,Z);return aH(Y)}async function rY($,Z,J){let Y=performance.now(),Q=[`Executando workflow: "${$}"`],X=0,K=0,V=0,G=!0;for(let H=0;H<Z.length;H++){let z=Z[H],U=z.label||`${z.action}:${z.target}`,B=`[${H+1}/${Z.length}]`,M=z.on_error||"continue";J?.(`${B} ${U}...`);try{let O=await oH(z,J);Q.push(` ${B} ${O}`),X++}catch(O){let L=O instanceof Error?O.message:String(O);switch(V++,M){case"stop":return Q.push(` ${B} ERRO (parando): ${L}`),G=!1,{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:Q,duration:Math.round(performance.now()-Y)};case"skip":Q.push(` ${B} ERRO (pulado): ${L}`),K++;break;case"continue":default:Q.push(` ${B} ERRO (continuando): ${L}`);break}}}return{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:Q,duration:Math.round(performance.now()-Y)}}async function oH($,Z){switch($.action){case"open_app":{if(!I)return`skip: ${$.target} (not Windows)`;return await b4($.target)}case"open_url":{if(!I)return`skip: ${$.target} (not Windows)`;let J=$.target.trim();if(!J.startsWith("http://")&&!J.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${J}`);return await y4(J)}case"run_command":{if(!I)return"skip: command (not Windows)";let J=$.target;if(!J.trim())throw Error("Comando vazio");let Y=await G$(J,{timeout:30000});if(Y.timedOut)throw Error("Command timeout (30s)");if(Y.exitCode!==0&&Y.stderr.trim())throw Error(`exit ${Y.exitCode}: ${Y.stderr.trim().slice(0,200)}`);let Q=Y.stdout.trim().slice(0,200);return`Command: ${J.slice(0,60)}${Q?" -> "+Q:""}`}case"wait":{let J=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((Y)=>setTimeout(Y,J*1000)),`Wait: ${J}s`}case"notify":{if(I)try{J4("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!I)return"skip: condition (not Windows)";let J=$.target.toLowerCase(),Y=await s1(J,{timeout:5000});if(Y&&$.condition_steps&&$.condition_steps.length>0){let Q=await rY(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${J} running=true, ran ${Q.stepsRun} sub-steps`}return`Condition: ${J} running=${Y}${!Y?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function iY($){let Z=$||z$;if(Z.length===0)return"Nenhum workflow configurado.";let J=Z.map((Y)=>{let Q=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}${Q}${X} \u2014 ${Y.description}
|
|
491
548
|
${" ".repeat(4)}${K} {${Y.id}}`});return`Workflows (${Z.length}):
|
|
492
549
|
${J.join(`
|
|
493
550
|
|
|
494
|
-
`)}`}function
|
|
495
|
-
`)}function
|
|
496
|
-
`)}function
|
|
551
|
+
`)}`}function nY($){let Z=$.enabled?"ativo":"desativado",J=$.tags.length>0?`Tags: ${$.tags.map((Q)=>`#${Q}`).join(" ")}`:"",Y=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(J)Y.push(J);return Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(""),Y.push("Steps:"),$.steps.forEach((Q,X)=>{let K=Q.label?` (${Q.label})`:"",V=Q.on_error&&Q.on_error!=="continue"?` [on_error: ${Q.on_error}]`:"";if(Y.push(` ${X+1}. ${Q.action}: ${Q.target}${K}${V}`),Q.action==="if_app_running"&&Q.condition_steps)for(let G of Q.condition_steps)Y.push(` \u21B3 ${G.action}: ${G.target}`)}),Y.join(`
|
|
552
|
+
`)}function aH($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
|
|
553
|
+
`)}function NZ(){return dH().slice(0,8)}$$();Y4();var S$=new Map,jZ=null;function tY($){jZ=$}function eY($,Z=60){if(!I)return"Error: monitor is only available on Windows.";let J=$.toLowerCase();if(S$.has(J))return`"${$}" ja esta sendo monitorado.`;let Y=setInterval(()=>sY(J),Z*1000);return S$.set(J,{name:$,interval:Y,lastSeen:!0}),sY(J),`Monitorando "${$}" a cada ${Z}s.`}function $Q($){let Z=$.toLowerCase(),J=S$.get(Z);if(!J)return`"${$}" nao esta sendo monitorado.`;return clearInterval(J.interval),S$.delete(Z),`Monitor parado: "${$}"`}function ZQ(){if(S$.size===0)return"Nenhum processo monitorado.";let $=[...S$.values()].map((Z)=>{let J=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${J}]`});return`Processos monitorados (${S$.size}):
|
|
497
554
|
${$.join(`
|
|
498
|
-
`)}`}function
|
|
555
|
+
`)}`}function JQ(){for(let $ of S$.values())clearInterval($.interval);S$.clear()}async function sY($){let Z=S$.get($);if(!Z)return;let J=await s1(Z.name,{timeout:1e4});if(Z.lastSeen&&!J){let Y=`ALERTA: "${Z.name}" parou de rodar!`;J4("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),jZ?.(Y)}else if(!Z.lastSeen&&J){let Y=`"${Z.name}" voltou a rodar.`;jZ?.(Y)}S$.set($,{...Z,lastSeen:J})}A1();r();import{writeFileSync as rH}from"fs";import{join as iH}from"path";async function nH(){let $=RZ(process.argv.slice(2));if($.help)EZ(),process.exit(0);if($.version)console.log(`smolerclaw v${o1()}`),process.exit(0);let Z=rZ();if($.model)Z.model=VZ($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let J;try{J=V5()}catch(O){console.error("smolerclaw:",O instanceof Error?O.message:O),process.exit(1)}let{provider:Y,model:Q}=GZ(Z.model),X;if(Y==="openai"||Y==="ollama")X=new HZ(Y,Q,Z.maxTokens);else{let O=new l9(J.token,Z.model,Z.maxTokens,Z.toolApproval);O.setAuthRefresh(()=>{let L=G5();if(L&&L.token!==J.token)return J=L,O.updateApiKey(L.token),!0;return!1}),X=O}let K=new a9(Z.dataDir),V=$.session||K.getLastSession()||"default";if(V!=="default")K.switchTo(V);let G=t3(Z.skillsDir),H=n9(Z.systemPrompt,G,Z.language),z=!$.noTools;k3();let U=s2(iH(Z.dataDir,"..")),B=a2(U);if(B.length>0)x3(B),c.push(...r2(B));let M=!process.stdin.isTTY;if($.print||M)await sH(X,K,H,z,$.prompt,M),process.exit(0);await eH(X,K,Z,J,G,H,z,B,$.prompt)}async function sH($,Z,J,Y,Q,X){let K=Q||"";if(X){let z=await tH();K=K?`${K}
|
|
499
556
|
|
|
500
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,J,Y))if(z.type==="text")process.stdout.write(z.text),G+=z.text;else if(z.type==="error")console.error(`
|
|
501
558
|
smolerclaw error: ${z.error}`);if(G&&!G.endsWith(`
|
|
502
559
|
`))process.stdout.write(`
|
|
503
|
-
`);let H={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(H)}async function
|
|
504
|
-
|
|
505
|
-
${
|
|
506
|
-
*** ${
|
|
507
|
-
`)),
|
|
508
|
-
*** Meta-Insight: ${
|
|
509
|
-
${
|
|
510
|
-
`)}),
|
|
511
|
-
*** ${
|
|
512
|
-
`)),
|
|
513
|
-
*** LEMBRETE: ${
|
|
514
|
-
`)});let O=null;try{O=await
|
|
560
|
+
`);let H={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(H)}async function tH(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}async function eH($,Z,J,Y,Q,X,K,V,G){let H=new zZ(J.model),z=new KZ(J.model,Z.session.name,nZ(Y),J.dataDir),U="default",B=i6(),M=B?`${X}
|
|
561
|
+
|
|
562
|
+
${B}`:X;dZ(J.dataDir,z5().replace(/[/\\]config\.json$/,"")),h6(J.dataDir),M6(J.dataDir),l6(J.dataDir),Y6(J.dataDir),w3(Z),L6(J.dataDir),A6(J.dataDir),vY((y)=>z.showSystem(`
|
|
563
|
+
*** ${y} ***
|
|
564
|
+
`)),lY(J.dataDir),e5(J.dataDir),ZJ(J.dataDir),VJ(J.dataDir),CJ(J.dataDir),vJ(J.dataDir),$3(J.dataDir,(y)=>{z.showSystem(`
|
|
565
|
+
*** Meta-Insight: ${y.title} ***
|
|
566
|
+
${y.recommendation}
|
|
567
|
+
`)}),tY((y)=>z.showSystem(`
|
|
568
|
+
*** ${y} ***
|
|
569
|
+
`)),V6(J.dataDir,(y)=>{z.showSystem(`
|
|
570
|
+
*** LEMBRETE: ${y.title} ***
|
|
571
|
+
`)});let O=null;try{O=await a7(J.dataDir),z.setTimeContext(O)}catch{z.setPersonaMode("productivity")}if(J.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(y,v,d)=>{if(y==="edit_file"&&v.old_text&&v.new_text){let N=u3(String(v.old_text),String(v.new_text));for(let j of N)z.showSystem(j)}let F=p3(y,v),q=await z.promptApproval(F);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 L=null;async function T(y){if(y.startsWith("/")){await _(y);return}if(J.maxSessionCost>0){let h=H.totals.costCents;if(h>=J.maxSessionCost){z.showError(`Budget exceeded (~$${(h/100).toFixed(4)} / $${(J.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(h>=J.maxSessionCost*0.8)z.showSystem(`Budget: ${Math.round(h/J.maxSessionCost*100)}% used`)}let{text:v,images:d}=DY(y),{text:F,files:q}=TY(v),N=F;if(q.length>0)N=`${q.map((d1)=>`<file name="${d1.name}" path="${d1.path}" size="${d1.size}">
|
|
572
|
+
${d1.content}
|
|
573
|
+
</file>`).join(`
|
|
574
|
+
|
|
575
|
+
`)}
|
|
576
|
+
|
|
577
|
+
${F}`;let j={role:"user",content:N,images:d.length>0?d.map((h)=>({mediaType:h.mediaType,base64:h.base64})):void 0,files:q.length>0?q:void 0,timestamp:Date.now()};Z.addMessage(j);let E=[];if(d.length>0)E.push(`${d.length} image${d.length>1?"s":""}`);if(q.length>0)E.push(`${q.length} file${q.length>1?"s":""}`);let w=E.length>0?`${F} (${E.join(", ")})`:F;z.addUserMessage(w),z.disableInput(),z.startStream();let k="",l=[],v$={},D8=0,u1=0;L=new AbortController;try{for await(let h of $.chat(Z.messages,M,K)){if(L.signal.aborted)break;switch(h.type){case"text":z.appendStream(h.text),k+=h.text;break;case"tool_call":z.flushStream(),z.showToolCall(h.name,h.input),v$=h.input;break;case"tool_result":z.showToolResult(h.name,h.result),l.push({id:h.id,name:h.name,input:v$,result:h.result}),v$={},z.resetStreamBuffer();break;case"tool_blocked":z.showError(h.reason);break;case"usage":D8+=h.inputTokens,u1+=h.outputTokens;break;case"error":z.showError(h.error);break;case"done":break}}}catch(h){if(!L.signal.aborted)z.showError(h instanceof Error?h.message:String(h))}L=null,z.endStream();let OZ={inputTokens:D8,outputTokens:u1},YQ=H.add(OZ);if(D8>0||u1>0)z.showUsage(H.formatUsage(OZ)),z.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let QQ={role:"assistant",content:k,toolCalls:l.length>0?l:void 0,usage:D8>0?{inputTokens:D8,outputTokens:u1,costCents:YQ.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(QQ),Z.trimHistory(J.maxHistory),z.enableInput()}async function _(y){let v=y.slice(1).split(" "),d=v[0].toLowerCase(),F=v.slice(1);switch(d){case"exit":case"quit":case"sair":case"q":V$();break;case"clear":case"limpar":Z.clear(),z.clearMessages(),z.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let q=F[0]||`s-${Date.now()}`;Z.switchTo(q),z.clearMessages(),z.updateSession(q),z.showSystem(`New session: ${q}`);break}case"load":case"carregar":{let q=F[0];if(!q){z.showError("Usage: /load <name>");break}Z.switchTo(q),z.clearMessages();for(let N of Z.messages)if(N.role==="user")z.addUserMessage(N.content);else z.addAssistantMessage(N.content);z.updateSession(q),z.showSystem(`Loaded: ${q}`);break}case"sessions":case"sessoes":case"ls":{let q=Z.list().map((E)=>{let w=Z.getInfo(E);return{name:E,messageCount:w?.messageCount??0,updated:w?.updated??0,isCurrent:E===Z.session.name,isArchived:!1}}),N=Z.listArchived().map((E)=>{let w=Z.getArchivedInfo(E);return{name:E,messageCount:w?.messageCount??0,updated:w?.updated??0,isCurrent:!1,isArchived:!0}}),j=await z.promptSessionPicker([...q,...N]);if(j)switch(j.action){case"load":{let E=j.name;if(N.some((k)=>k.name===E))Z.unarchive(E);Z.switchTo(E),z.clearMessages();for(let k of Z.messages)if(k.role==="user")z.addUserMessage(k.content);else z.addAssistantMessage(k.content);z.updateSession(E),z.showSystem(`Loaded: ${E}`);break}case"delete":{let E=j.name;if(j.isArchived?Z.deleteArchived(E):Z.delete(E))z.showSystem(`Deleted: ${E}`);else z.showError(`Not found: ${E}`);break}case"archive":if(Z.archive(j.name))z.showSystem(`Archived: ${j.name}`);else z.showError(`Failed to archive: ${j.name}`);break;case"unarchive":if(Z.unarchive(j.name))z.showSystem(`Restored: ${j.name}`);else z.showError(`Not found in archive: ${j.name}`);break}break}case"delete":case"deletar":case"rm":{let q=F[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=F[0];if(!q){z.showError("Uso: /archive <nome> ou /archive all");break}if(q==="all"||q==="todas"){let N=Z.archiveAll();if(N.length>0)z.showSystem(`Arquivadas ${N.length} sessoes: ${N.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=F[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 N=q.map((j)=>{let E=Z.getArchivedInfo(j),w=E?Zq(E.updated):"",k=E?`${E.messageCount} msgs`:"";return` ${j.padEnd(20)} ${k.padEnd(10)} ${w}`});z.showSystem(`Sessoes arquivadas (${q.length}):
|
|
515
578
|
${N.join(`
|
|
516
|
-
`)}`);break}case"model":case"modelo":{let q=
|
|
579
|
+
`)}`);break}case"model":case"modelo":{let q=F[0];if(!q){z.showSystem(zY(J.model)+`
|
|
517
580
|
|
|
518
|
-
`+
|
|
519
|
-
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"}),N=setTimeout(()=>q.kill(),15000);await q.exited,clearTimeout(N);let j=
|
|
520
|
-
`));break;case"commit":case"commitar":{if(!await
|
|
581
|
+
`+VY());break}let{provider:N,model:j}=GZ(q),E=N==="anthropic"?VZ(j):j;if(J.model=N==="anthropic"?E:`${N}:${E}`,V0(J),N==="anthropic")$.setModel(E);else z.showSystem(`Note: ${N} provider selected. Restart smolerclaw for full provider switch.`);H.setModel(E),z.updateModel(J.model),z.showSystem(`Model -> ${J.model}`);break}case"skills":case"habilidades":{z.showSystem(e3(Q));break}case"auth":z.showSystem(`Auth: subscription (${Y.subscriptionType})
|
|
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"}),N=setTimeout(()=>q.kill(),15000);await q.exited,clearTimeout(N);let j=G5();if(j){if(Y=j,"updateApiKey"in $)$.updateApiKey(j.token);z.showSystem(`Sessao renovada. Expira: ${new Date(j.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: ${z5()}`);break;case"export":case"exportar":{let q=new Date().toISOString().split("T")[0],N=F[0]||`smolerclaw-${Z.session.name}-${q}.md`;try{let j=KY(Z.session);rH(N,j),z.showSystem(`Exported to: ${N}`)}catch(j){z.showError(`Export failed: ${j instanceof Error?j.message:j}`)}break}case"cost":case"custo":z.showSystem(`Session: ${H.formatSession()}`);break;case"retry":case"repetir":{let q=[...Z.messages].reverse().find((w)=>w.role==="user");if(!q){z.showError("No previous message to retry.");break}let N=Z.messages,j=0;if(N.length>0&&N[N.length-1].role==="assistant")j++;if(N.length>j&&N[N.length-1-j].role==="user")j++;if(j>0)Z.popMessages(j);z.showSystem("Retrying...");let E=q.images?.length?q.content:q.content;await T(E);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(`
|
|
583
|
+
`));break;case"commit":case"commitar":{if(!await UY()){z.showError("Not a git repository.");break}let q=await HY();if(q==="(clean)"){z.showSystem("Nothing to commit \u2014 working tree clean.");break}z.showSystem(`Changes:
|
|
521
584
|
`+q),z.disableInput();try{let j=`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.
|
|
522
585
|
|
|
523
586
|
Diff:
|
|
524
|
-
${(await
|
|
587
|
+
${(await GY()).slice(0,8000)}`;z.startStream();let E="";for await(let k of $.chat([{role:"user",content:j,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(k.type==="text")E+=k.text,z.appendStream(k.text);else if(k.type==="error")z.showError(k.error);if(z.endStream(),E=E.trim().replace(/^["']|["']$/g,""),!E){z.showError("Failed to generate commit message. Aborting.");break}await qY();let w=await WY(E);if(w.ok)z.showSystem(`Committed: ${E}`);else z.showError(`Commit failed: ${w.output}`)}catch(N){z.showError(`Commit error: ${N instanceof Error?N.message:String(N)}`)}z.enableInput();break}case"persona":case"modo":{let q=F[0];if(!q){z.showSystem(MY(U));break}let N=NY(q);if(!N){z.showError(`Unknown persona: ${q}. Try /persona to see options.`);break}if(U=N.name,N.systemPrompt)M=n9(N.systemPrompt,Q,J.language);else M=X;z.showSystem(`Persona -> ${N.name}: ${N.description}`);break}case"copy":case"copiar":{let q=[...Z.messages].reverse().find((j)=>j.role==="assistant");if(!q){z.showError("No assistant message to copy.");break}if(await CY(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=F.join(" ");if(!q){z.showError("Usage: /ask <question>");break}z.addUserMessage(`(ephemeral) ${q}`),z.disableInput(),z.startStream();let N="";for await(let j of $.chat([{role:"user",content:q,timestamp:Date.now()}],M,!1))if(j.type==="text")N+=j.text,z.appendStream(j.text);else if(j.type==="error")z.showError(j.error);else if(j.type==="usage")z.showUsage(`${j.inputTokens} in / ${j.outputTokens} out (ephemeral)`);z.endStream(),z.enableInput();break}case"fork":{let q=F[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(n2(V));break}case"budget":case"orcamento":{let q=F[0];if(!q){let j=J.maxSessionCost,E=H.totals.costCents;if(j===0)z.showSystem(`Budget: unlimited (spent ~$${(E/100).toFixed(4)})`);else{let w=Math.round(E/j*100);z.showSystem(`Budget: ~$${(E/100).toFixed(4)} / $${(j/100).toFixed(4)} (${w}%)`)}break}let N=Number(q);if(isNaN(N)||N<0){z.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}J.maxSessionCost=N,V0(J),z.showSystem(N===0?"Budget: unlimited":`Budget set: $${(N/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!R8.peek()){z.showError("Nothing to undo.");break}let N=R8.undo();if(N)z.showSystem(N);break}case"search":case"buscar":{let q=F.join(" ").toLowerCase();if(!q){z.showError("Usage: /search <text>");break}let N=[];for(let j of Z.messages)if(j.content.toLowerCase().includes(q)){let E=j.content.slice(0,100).replace(/\n/g," "),w=new Date(j.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});N.push(` [${j.role} ${w}] ${E}${j.content.length>100?"...":""}`)}z.showSystem(N.length>0?`Found ${N.length} match${N.length>1?"es":""}:
|
|
525
588
|
${N.join(`
|
|
526
|
-
`)}`:`No matches for "${q}".`);break}case"lang":case"language":case"idioma":{let q=
|
|
527
|
-
Falhas: ${j.join(", ")}`:"Nenhuma noticia encontrada."),z.enableInput();break}let
|
|
528
|
-
Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let q=
|
|
529
|
-
Uso: /open <app> ou /open <app> <arquivo>`);break}let N=
|
|
589
|
+
`)}`:`No matches for "${q}".`);break}case"lang":case"language":case"idioma":{let q=F[0];if(!q){z.showSystem(`Language: ${J.language} (auto = match user's language)`);break}J.language=q,V0(J),z.showSystem(`Language -> ${q}`);break}case"briefing":case"resumo":{z.showSystem("Carregando briefing..."),z.disableInput();try{let q=await IY(J.dataDir);z.showSystem(q);let N=await a7(J.dataDir);z.setTimeContext(N),O=N}catch(q){z.showError(`Briefing falhou: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"news":case"noticias":{let q=F[0];if(q)z.showSystem(`Buscando noticias (${q})...`);else z.showSystem("Buscando noticias...");z.disableInput();try{let{items:N,errors:j}=await r5(q?[q]:void 0);if(N.length===0){z.showSystem(j.length>0?`Nenhuma noticia encontrada.
|
|
590
|
+
Falhas: ${j.join(", ")}`:"Nenhuma noticia encontrada."),z.enableInput();break}let E=N.map((k)=>({title:k.title,link:k.link,source:k.source,category:k.category,time:k.pubDate?k.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),w=await z.promptNewsPicker(E);if(w){let{openUrl:k}=await Promise.resolve().then(() => (f4(),t2));k(w),z.showSystem(`Abrindo: ${w}`)}}catch(N){z.showError(`Falha ao buscar noticias: ${N instanceof Error?N.message:String(N)}`)}z.enableInput();break}case"feeds":case"fontes":{z.showSystem(p0());break}case"addfeed":case"novafonte":{if(F.length<3){z.showError(`Uso: /addfeed <nome> <url> <categoria>
|
|
591
|
+
Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let q=F[0],N=F[1],j=F[2],E=h0(q,N,j);if(typeof E==="string")z.showError(E);else z.showSystem(`Fonte adicionada: ${E.name} (${E.category}) \u2014 ${E.url}`);break}case"rmfeed":case"rmfonte":{let q=F.join(" ");if(!q){z.showError("Uso: /rmfeed <nome ou url>");break}if(g0(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=F.join(" ");if(!q){z.showError("Uso: /disablefeed <nome ou url>");break}if(m0(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=F.join(" ");if(!q){z.showError("Uso: /enablefeed <nome ou url>");break}if(c0(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(!F.join(" ")){z.showSystem(`Apps disponiveis: ${l5().join(", ")}
|
|
592
|
+
Uso: /open <app> ou /open <app> <arquivo>`);break}let N=F.length>1?F.slice(1).join(" "):void 0,j=await b4(F[0],N);z.showSystem(j);break}case"openfile":case"abrirarquivo":{let q=F.join(" ");if(!q){z.showError("Uso: /openfile <caminho>");break}let N=await F1(q);z.showSystem(N);break}case"openurl":{let q=F[0];if(!q){z.showError("Uso: /openurl <url>");break}let N=await y4(q);z.showSystem(N);break}case"apps":case"programas":{z.disableInput();try{let q=await R1();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 _4();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 v4(),N=await b$();z.showSystem(`${q}
|
|
530
593
|
|
|
531
594
|
--- Agenda ---
|
|
532
|
-
${N}`)}catch(q){z.showError(`Calendar: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"monitor":case"vigiar":{let q=
|
|
595
|
+
${N}`)}catch(q){z.showError(`Calendar: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"monitor":case"vigiar":{let q=F[0]?.toLowerCase();if(!q||q==="list"||q==="listar")z.showSystem(ZQ());else if(q==="stop"||q==="parar"){let N=F[1];if(!N){z.showError("Uso: /monitor stop <processo>");break}z.showSystem($Q(N))}else{let N=parseInt(F[1])||60;z.showSystem(eY(q,N))}break}case"workflow":case"fluxo":{let q=F[0]?.toLowerCase();if(!q||q==="list"||q==="listar"){let N=F[1];z.showSystem(iY(oY(N)))}else if(q==="run"||q==="rodar"){let N=F[1];if(!N){z.showError("Uso: /workflow run <nome>");break}z.disableInput();try{let j=await CZ(N,(E)=>z.showSystem(E));z.showSystem(j)}catch(j){z.showError(`Workflow: ${j instanceof Error?j.message:String(j)}`)}z.enableInput()}else if(q==="info"||q==="detalhe"){let N=F[1];if(!N){z.showError("Uso: /workflow info <nome>");break}let j=p1(N);if(j)z.showSystem(nY(j));else z.showError(`Workflow nao encontrado: ${N}`)}else if(q==="delete"||q==="deletar"){let N=F[1];if(!N){z.showError("Uso: /workflow delete <nome>");break}if(aY(N))z.showSystem(`Workflow removido: ${N}`);else z.showError(`Workflow nao encontrado: ${N}`)}else if(q==="enable"||q==="ativar"){let N=F[1];if(!N){z.showError("Uso: /workflow enable <nome>");break}let j=MZ(N,{enabled:!0});if(j)z.showSystem(`Workflow ativado: ${j.name}`);else z.showError(`Workflow nao encontrado: ${N}`)}else if(q==="disable"||q==="desativar"){let N=F[1];if(!N){z.showError("Uso: /workflow disable <nome>");break}let j=MZ(N,{enabled:!1});if(j)z.showSystem(`Workflow desativado: ${j.name}`);else z.showError(`Workflow nao encontrado: ${N}`)}else{z.disableInput();try{let N=await CZ(q,(j)=>z.showSystem(j));z.showSystem(N)}catch(N){z.showError(`Workflow: ${N instanceof Error?N.message:String(N)}`)}z.enableInput()}break}case"pomodoro":case"foco":{let q=F[0]?.toLowerCase();if(q==="stop"||q==="parar")z.showSystem(hY());else if(q==="status")z.showSystem(UZ());else if(!q)z.showSystem(UZ());else{let N=F.join(" "),j=25,E=5;z.showSystem(fY(N,25,5))}break}case"entrada":case"income":{let q=parseFloat(F[0]);if(isNaN(q)||F.length<3){z.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let N=T1("entrada",q,F[1],F.slice(2).join(" "));z.showSystem(`+ R$ ${N.amount.toFixed(2)} (${N.category}) \u2014 ${N.description}`);break}case"saida":case"expense":{let q=parseFloat(F[0]);if(isNaN(q)||F.length<3){z.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let N=T1("saida",q,F[1],F.slice(2).join(" "));z.showSystem(`- R$ ${N.amount.toFixed(2)} (${N.category}) \u2014 ${N.description}`);break}case"finance":case"financas":case"balanco":{let q=F[0];if(q==="recent"||q==="recentes")z.showSystem(t5());else z.showSystem(n0()+`
|
|
533
596
|
|
|
534
|
-
`+
|
|
535
|
-
Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let N=
|
|
536
|
-
Use | para separar assunto do corpo.`);break}let
|
|
537
|
-
Ou peca a IA: "salva esse material sobre..."`);break}let j=q.slice(0,N).trim(),
|
|
597
|
+
`+t5(5));break}case"decisions":case"decisoes":{let q=F.join(" ");if(q){let N=m4(q);z.showSystem(H8(N))}else z.showSystem(H8(s0()));break}case"investigar":case"investigate":case"investigacoes":{let q=F.join(" ");if(q){let{searchInvestigations:N,formatInvestigationList:j}=await Promise.resolve().then(() => (A1(),H9));z.showSystem(j(N(q)))}else{let{listInvestigations:N,formatInvestigationList:j}=await Promise.resolve().then(() => (A1(),H9));z.showSystem(j(N()))}break}case"email":case"rascunho":{if(!F.join(" ")){z.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
|
|
598
|
+
Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let N=F[0],j=F.slice(1).join(" "),E=j.indexOf("|");if(E===-1){z.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
|
|
599
|
+
Use | para separar assunto do corpo.`);break}let w=j.slice(0,E).trim(),k=j.slice(E+1).trim();if(!w||!k){z.showError("Assunto e corpo sao obrigatorios.");break}let l={to:N,subject:w,body:k};z.showSystem(i0(l)),z.disableInput();try{let v$=await r0(l);z.showSystem(v$)}catch(v$){z.showError(`Email: ${v$ instanceof Error?v$.message:String(v$)}`)}z.enableInput();break}case"memo":case"anotar":case"note":{let q=F.join(" ");if(!q){let E=D1();z.showSystem(g4(E));break}let N=o0(q),j=N.tags.length>0?` [${N.tags.map((E)=>"#"+E).join(" ")}]`:"";z.showSystem(`Memo salvo${j} {${N.id}}`);break}case"memos":case"notas":{let q=F.join(" ");if(q){let N=a0(q);z.showSystem(g4(N))}else{let N=D1();z.showSystem(g4(N))}break}case"memotags":case"tags":{z.showSystem(j6());break}case"rmmemo":case"rmnota":{let q=F[0];if(!q){z.showError("Uso: /rmmemo <id>");break}if(C6(q))z.showSystem("Memo removido.");else z.showError(`Memo nao encontrado: ${q}`);break}case"material":case"mat":{let q=F.join(" ");if(!q){let l=U8(10);z.showSystem(C4(l));break}if(/^[a-z0-9]{6}$/.test(q)){let l=a6(q);if(l)z.showSystem(n6(l));else z.showError(`Material nao encontrado: ${q}`);break}let N=q.indexOf("|");if(N===-1){z.showSystem(`Uso: /material <titulo> | <conteudo>
|
|
600
|
+
Ou peca a IA: "salva esse material sobre..."`);break}let j=q.slice(0,N).trim(),E=q.slice(N+1).trim();if(!j||!E){z.showError("Titulo e conteudo sao obrigatorios.");break}let w=G7(j,E),k=w.tags.length>0?` [${w.tags.map((l)=>"#"+l).join(" ")}]`:"";z.showSystem(`Material salvo: "${w.title}" (${w.category})${k} {${w.id}}`);break}case"materials":case"materiais":{let q=F.join(" ");if(q){let N=W8(q);z.showSystem(C4(N))}else{let N=U8();z.showSystem(C4(N))}break}case"matcats":case"categorias":{z.showSystem(s6());break}case"rmmat":case"rmmaterial":{let q=F[0];if(!q){z.showError("Uso: /rmmat <id>");break}if(H7(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 k1();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=N7();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=F.join(" ");if(q){let N=M7(q);z.showSystem(C7(N))}else{let N=B7(),j=N.builtAt?new Date(N.builtAt).toLocaleString("pt-BR"):"nunca";z.showSystem(`Memory RAG Index:
|
|
538
601
|
Chunks: ${N.chunks}
|
|
539
602
|
Fontes: ${N.sources}
|
|
540
|
-
Ultima indexacao: ${j}`)}break}case"vault":{let q=
|
|
541
|
-
${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
|
|
542
|
-
`));break}case"projeto":case"project":{let q=
|
|
543
|
-
Ex: /addperson equipe Joao dev frontend`);break}let j=
|
|
544
|
-
Ex: /delegate Joao revisar relatorio`);break}let N=
|
|
545
|
-
${
|
|
546
|
-
Type /ajuda for commands.`)
|
|
547
|
-
`).filter((
|
|
548
|
-
`).filter((
|
|
549
|
-
`).filter((
|
|
603
|
+
Ultima indexacao: ${j}`)}break}case"vault":{let q=F[0]?.toLowerCase();if(!q||q==="status")z.showSystem(Y0(J0()));else if(q==="backup"){z.showSystem("Realizando backup...");let N=F.slice(1).join(" ")||void 0,j=await n4(N);z.showSystem(j)}else if(q==="sync"||q==="push"){z.showSystem("Sincronizando com remote...");let N=await X0();z.showSystem(N)}else if(q==="init"){let N=await Q0();z.showSystem(N),oZ(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 n4();z.showSystem(q);break}case"clipboard":case"area":{z.showSystem("Lendo clipboard...");let q=await O7();switch(q.type){case"text":z.showSystem(`Clipboard (texto):
|
|
604
|
+
${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 F7();z.showSystem(q);break}case"ps1":{let q=F.join(" ");if(!q.trim()){z.showError("Uso: /ps1 <script powershell>");break}z.showSystem("Executando script...");let N=await j7(q),j=[];if(N.stdout.trim())j.push(N.stdout.trim());if(N.stderr.trim())j.push(`stderr: ${N.stderr.trim()}`);j.push(`(exit: ${N.exitCode}, ${N.duration}ms)`),z.showSystem(j.join(`
|
|
605
|
+
`));break}case"projeto":case"project":{let q=F.join(" ");if(q){let N=L7(q);if(N)C8(N.id),z.showSystem(x7(N));else if(q==="auto"){let j=k7(process.cwd());if(j)C8(j.id),z.showSystem(`Projeto detectado: ${x7(j)}`);else z.showError("Nenhum projeto detectado no diretorio atual.")}else z.showError(`Projeto nao encontrado: "${q}"`)}else{let N=O4();if(N)z.showSystem(x7(N));else z.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{z.showSystem(I7(M8()));break}case"sessao":case"session":{let q=F[0],N=O4();if(!N){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(q==="start"||q==="iniciar"){let j=F.slice(1).join(" "),E=D7(N.id,j);if(E)z.showSystem(`Sessao iniciada para "${N.name}" [${E.id}]`)}else if(q==="stop"||q==="parar"){let j=F4(N.id);if(j){let E=T7(j.id,F.slice(1).join(" "));if(E)z.showSystem(`Sessao encerrada: ${E.durationMinutes} minutos em "${N.name}"`)}else z.showSystem("Nenhuma sessao aberta.")}else{let j=F4(N.id);if(j){let E=Math.round((Date.now()-new Date(j.startedAt).getTime())/60000);z.showSystem(`Sessao aberta: ${E} minutos em "${N.name}"`)}else z.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let q=O4();if(!q){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let N=F[0]||"today";z.showSystem("Gerando relatorio...");let j=await A7(q.id,N,"pt");if(j)z.showSystem(j.markdown);else z.showError("Falha ao gerar relatorio.");break}case"oportunidades":case"opportunities":{let q=F[0]||void 0,N=P7(q);z.showSystem(S7(N));break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let N={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[d]||F[0],j=J7(N);z.showSystem(Q7(j));break}case"person":case"pessoa":{let q=F.join(" ");if(!q){z.showError("Uso: /person <nome>");break}let N=o$(q);if(!N){z.showError(`Pessoa nao encontrada: "${q}"`);break}z.showSystem(X7(N));break}case"addperson":case"addpessoa":case"novapessoa":{let q=F[0];if(!q||!["equipe","familia","contato"].includes(q)){z.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
|
|
606
|
+
Ex: /addperson equipe Joao dev frontend`);break}let j=F.slice(1).join(" ");if(!j){z.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[E,...w]=j.split(","),k=w.join(",").trim()||void 0,l=Z7(E.trim(),q,k);z.showSystem(`Adicionado: ${l.name} (${q}) [${l.id}]`);break}case"delegate":case"delegar":{let q=F[0];if(!q||F.length<2){z.showSystem(`Uso: /delegate <pessoa> <tarefa>
|
|
607
|
+
Ex: /delegate Joao revisar relatorio`);break}let N=F.slice(1).join(" "),j=Y7(q,N);if(!j){z.showError(`Pessoa nao encontrada: "${q}"`);break}z.showSystem(`Delegado para ${q}: "${N}" [${j.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let q=F[0],N=c4(q);z.showSystem(K7(N));break}case"followups":{let q=q8();z.showSystem(z7(q));break}case"dashboard":case"painel":{z.showSystem(V7());break}case"task":case"tarefa":{let q=F.join(" ");if(!q){let k=l$();z.showSystem(h4(k));break}let N=L1(q),j=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(!j)j=q;let E=d0(j,N||void 0),w=N?` \u2014 lembrete: ${N.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";z.showSystem(`Tarefa criada: "${E.title}"${w} [${E.id}]`);break}case"tasks":case"tarefas":{let q=F[0]==="all"||F[0]==="todas",N=l$(q);z.showSystem(h4(N));break}case"done":case"feito":case"concluido":{let q=F.join(" ");if(!q){z.showError("Uso: /done <id ou parte do titulo>");break}let N=l0(q);if(N)z.showSystem(`Concluida: "${N.title}"`);else z.showError(`Tarefa nao encontrada: "${q}"`);break}case"rmtask":case"rmtarefa":{let q=F.join(" ");if(!q){z.showError("Uso: /rmtask <id ou parte do titulo>");break}if(H6(q))z.showSystem("Tarefa removida.");else z.showError(`Tarefa nao encontrada: "${q}"`);break}default:z.showError(`Unknown command: /${d}. Try /help`)}}function V$(){Z.saveLastSession(),G6(),cY(),JQ(),X5(),k1().catch(()=>{}),z.stop(),process.exit(0)}process.on("SIGINT",V$),process.on("SIGTERM",V$),z.start({onSubmit:T,onCancel:()=>{L?.abort(),z.endStream(),z.showSystem("Cancelled."),z.enableInput()},onExit:V$});let s=`Authenticated via Claude ${Y.subscriptionType} subscription.`;if(z.showSystem(`smolerclaw v${o1()} \u2014 the micro AI assistant.
|
|
608
|
+
${s}
|
|
609
|
+
Type /ajuda for commands.`),wY(J.dataDir))try{let y=await $q();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 bY();z.showSystem(v)}kY()}catch{}if(G)await T(G)}async function $q(){let $=[],Z=new Date().getHours(),J=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE",Y=new Date().toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),Q=l$(),X=Q.filter((z)=>{if(!z.dueAt)return!0;let U=new Date(z.dueAt),B=new Date;return U.toDateString()===B.toDateString()});if(X.length>0||Q.length>0){let z=X.slice(0,8).map((U)=>{let B=U.dueAt?new Date(U.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return`${B?`[${B}] `:""}${U.title}`});if(Q.length>X.length)z.push(`... +${Q.length-X.length} outras`);$.push({id:"tasks",title:`${J}! Tarefas (${X.length})`,content:z.length>0?z:["Nenhuma tarefa para hoje"]})}let K=q8();if(K.length>0){let z=K.slice(0,6).map((U)=>{let B=U.person.name||"Alguem",M=U.interaction.summary||"Follow-up pendente";return`${B}: ${M.slice(0,30)}...`});$.push({id:"followups",title:`Follow-ups (${K.length})`,content:z})}let G=c4().filter((z)=>z.status==="atrasado");if(G.length>0){let z=G.slice(0,5).map((U)=>{return`${o$(U.personId)?.name||"Alguem"}: ${U.task.slice(0,25)}...`});$.push({id:"delegations",title:`Atrasados (${G.length})`,content:z})}try{let U=(await b$()).split(`
|
|
610
|
+
`).filter((B)=>B.trim()).slice(0,6);if(U.length>0)$.push({id:"calendar",title:"Agenda",content:U})}catch{}let H=w7();if(H){let z=H.split(`
|
|
611
|
+
`).filter((U)=>U.trim()).slice(0,5);$.push({id:"project",title:"Projetos",content:z})}try{let U=(await B4(["finance","business","tech"],2)).split(`
|
|
612
|
+
`).filter((B)=>B.trim()).slice(0,6);if(U.length>0)$.push({id:"news",title:"Noticias",content:U})}catch{}if($.length===0)$.push({id:"greeting",title:J,content:[Y,"","Nenhuma tarefa ou evento pendente.","Use /ajuda para ver comandos dispon\xEDveis."]});return{panels:$,columns:Math.min(2,$.length),gap:1}}function Zq($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let J=Math.floor(Z/60000);if(J<1)return"just now";if(J<60)return`${J}m ago`;let Y=Math.floor(J/60);if(Y<24)return`${Y}h ago`;let Q=Math.floor(Y/24);if(Q>365)return`${Math.floor(Q/365)}y ago`;return`${Q}d ago`}nH().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
|