smolerclaw 1.3.6 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/index.js +349 -348
- 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
|
|
4
|
-
`:`[${
|
|
5
|
-
`;try{
|
|
6
|
-
... (truncated, ${Z.length} total chars)`;return Z}function
|
|
7
|
-
--- Arquivos ---`);for(let
|
|
8
|
-
`)}async function
|
|
9
|
-
`);if(
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
... (truncado)`:K.content;Q.push("```"),Q.push(G),Q.push("```")}}if(Z.findings.length>0){let K=[...Z.findings].sort((V,G)=>(X[V.severity]??4)-(X[G.severity]??4));Q.push(""),Q.push(`## Conclusoes (${Z.findings.length})`);for(let V of K){let G=W3(V.severity);if(Q.push(""),Q.push(`### ${G} ${V.title}`),Q.push(V.description),V.evidence_ids.length>0)Q.push(`- Evidencias: ${V.evidence_ids.join(", ")}`)}}if(Z.summary)Q.push(""),Q.push("## Resumo"),Q.push(Z.summary);if(Z.recommendations)Q.push(""),Q.push("## Recomendacoes"),Q.push(Z.recommendations);return Q.join(`
|
|
14
|
-
`)}function E7($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Q)=>{let Y=new Date(Q.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=U3(Q.status),X=Q.evidence.length,K=Q.findings.length,V=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"";return` ${J} [${Y}] ${Q.title} (${Q.type}) \u2014 ${X} ev, ${K} concl${V} {${Q.id}}`});return`Investigacoes (${$.length}):
|
|
3
|
+
var _z=Object.defineProperty;var xz=($)=>$;function fz($,Z){this[$]=xz.bind(null,Z)}var OZ=($,Z)=>{for(var Y in Z)_z($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:fz.bind(Z,Y)})};var s0=($,Z)=>()=>($&&(Z=$($=0)),Z);import{existsSync as mz,appendFileSync as uz,mkdirSync as _H}from"fs";import{join as jZ}from"path";import{homedir as pz}from"os";function I1($,Z,Y){if(!u5)return;let Q=new Date().toISOString(),J=Y?`[${Q}] [${$}] ${Z} ${JSON.stringify(Y)}
|
|
4
|
+
`:`[${Q}] [${$}] ${Z}
|
|
5
|
+
`;try{uz(lz,J)}catch{}}function PZ($){if($.startsWith('"')&&$.endsWith('"')||$.startsWith("'")&&$.endsWith("'"))return $;return`'${$.replace(/'/g,"''")}'`}function TZ($){let Z=$.replace(/\//g,"\\");return PZ(Z)}async function Q4($){let Z=Z4.get($.toLowerCase());if(Z)return Z;if($.includes("\\")||$.includes("/")){if(mz($)){let Q={exists:!0,path:$};return Z4.set($.toLowerCase(),Q),Q}return{exists:!1,error:`File not found: ${$}`}}let Y=`(Get-Command '${$}' -ErrorAction SilentlyContinue).Source`;try{let Q=await J$(Y,{timeout:5000});if(Q.exitCode===0&&Q.stdout.trim()){let z={exists:!0,path:Q.stdout.trim()};return Z4.set($.toLowerCase(),z),z}let J={exists:!1,error:`'${$}' not found in PATH`};return Z4.set($.toLowerCase(),J),J}catch(Q){return{exists:!1,error:Q instanceof Error?Q.message:String(Q)}}}async function J$($,Z={}){let{timeout:Y=DZ,cwd:Q,debug:J=u5,sta:z=!1}=Z,K=performance.now(),X=`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${$}`,V=["powershell",...oz];if(z)V.push("-STA");if(V.push("-Command",X),J)I1("INFO","Executing PowerShell command",{command:$.slice(0,500),timeout:Y,cwd:Q,sta:z});let G;try{G=Bun.spawn(V,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(W){let B={stdout:"",stderr:`Failed to spawn PowerShell: ${W instanceof Error?W.message:String(W)}`,exitCode:1,duration:Math.round(performance.now()-K),timedOut:!1};if(J)I1("ERROR","Failed to spawn process",{error:B.stderr});return B}let q=!1,U=setTimeout(()=>{q=!0;try{G.kill()}catch{}},Y);try{let[W,B]=await Promise.all([G.stdout instanceof ReadableStream?new Response(G.stdout).text():"",G.stderr instanceof ReadableStream?new Response(G.stderr).text():""]),M=await G.exited;clearTimeout(U);let O=Math.round(performance.now()-K),R={stdout:Y4(W),stderr:Y4(B),exitCode:q?-1:M,duration:O,timedOut:q};if(J)I1(R.exitCode===0?"INFO":"WARN","Command completed",{exitCode:R.exitCode,duration:O,timedOut:q,stdoutLength:R.stdout.length,stderrLength:R.stderr.length});return R}catch(W){clearTimeout(U);let B={stdout:"",stderr:`Execution error: ${W instanceof Error?W.message:String(W)}`,exitCode:1,duration:Math.round(performance.now()-K),timedOut:q};if(J)I1("ERROR","Execution failed",{error:B.stderr,timedOut:q});return B}}async function AZ($,Z={}){let Q=`& ${TZ($)}`;return J$(Q,Z)}async function p5($,Z={}){let{timeout:Y=DZ,cwd:Q,debug:J=u5}=Z,z=performance.now();if(J)I1("INFO","Executing command",{args:$,timeout:Y,cwd:Q});let K;try{K=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Q})}catch(G){return{stdout:"",stderr:`Failed to spawn: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-z),timedOut:!1}}let X=!1,V=setTimeout(()=>{X=!0;try{K.kill()}catch{}},Y);try{let[G,q]=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(V),{stdout:Y4(G),stderr:Y4(q),exitCode:X?-1:U,duration:Math.round(performance.now()-z),timedOut:X}}catch(G){return clearTimeout(V),{stdout:"",stderr:`Execution error: ${G instanceof Error?G.message:String(G)}`,exitCode:1,duration:Math.round(performance.now()-z),timedOut:X}}}async function d5($,Z={}){return J$($,{...Z,sta:!0})}async function x$($,Z,Y=[],Q={}){let J=["schtasks",`/${$}`,"/TN",Z,...Y],z=Q.timeout??1e4;return p5(J,{...Q,timeout:z})}async function c5($,Z,Y={}){let Q=PZ($),J=Z?`Start-Process ${Q} -ArgumentList '${Z.replace(/'/g,"''")}'`:`Start-Process ${Q}`;return J$(J,Y)}async function IZ($,Z={}){let Y=TZ($);return J$(`Invoke-Item ${Y}`,Z)}async function J0($,Z,Y={}){let Q=LZ($),J=LZ(Z),z=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Q}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("smolerclaw").Show($toast)'].join("; "),K=Y.timeout??1e4;return J$(z,{...Y,timeout:K})}async function J4($,Z={}){let Q=`(Get-Process -Name '${$.replace(/'/g,"''")}' -ErrorAction SilentlyContinue) -ne $null`;return(await J$(Q,{...Z,timeout:Z.timeout??5000})).stdout.trim().toLowerCase()==="true"}async function SZ($=15,Z={}){let Y=`Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First ${$} Name, @{N='Memory(MB)';E={[math]::Round($_.WorkingSet64/1MB,1)}}, MainWindowTitle | Format-Table -AutoSize | Out-String -Width 200`;return J$(Y,Z)}function Y4($){let Z=$.replace(dz,"");if(Z.length>EZ)return Z.slice(0,EZ)+`
|
|
6
|
+
... (truncated, ${Z.length} total chars)`;return Z}function LZ($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function wZ($){return $.replace(/"/g,'""').replace(/`/g,"``").replace(/\$/g,"`$")}var DZ=15000,EZ=1e5,dz,cz,lz,oz,u5=!1,Z4;var f$=s0(()=>{dz=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,cz=jZ(pz(),".smolerclaw","logs"),lz=jZ(cz,"windows-executor.log"),oz=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass"];Z4=new Map});import{existsSync as iz}from"fs";function t0(){if(L)return["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-Command"];let $=process.env.SHELL;if($&&iz($))return[$,"-c"];return["bash","-c"]}function yZ(){if(L)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function nz($){if(L)return(await Q4($)).exists;try{return(await p5(["which",$],{timeout:5000})).exitCode===0}catch{return!1}}async function bZ(){if(z4!==null)return z4;return z4=await nz("rg"),z4}function l5($){let Z=$.replace(/\\/g,"/");return S1.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var L,kZ,pH,z4=null,S1;var p=s0(()=>{f$();L=process.platform==="win32",kZ=process.platform==="darwin",pH=process.platform==="linux";S1=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{EventEmitter as az}from"events";class _Z{emitter;listeners=new Map;debug;errorHandlers=[];constructor($={}){this.emitter=new az,this.emitter.setMaxListeners($.maxListeners??20),this.debug=$.debug??!!process.env.DEBUG}on($,Z,Y={}){let Q={listener:Z,once:!1,async:Y.async??!1},J=this.listeners.get($)??[];if(J.push(Q),this.listeners.set($,J),this.debug)console.log(`[event-bus] Registered listener for '${$}'`);return()=>this.off($,Z)}once($,Z,Y={}){let Q={listener:Z,once:!0,async:Y.async??!1},J=this.listeners.get($)??[];if(J.push(Q),this.listeners.set($,J),this.debug)console.log(`[event-bus] Registered once listener for '${$}'`);return()=>this.off($,Z)}off($,Z){let Y=this.listeners.get($);if(!Y)return;let Q=Y.filter((J)=>J.listener!==Z);if(Q.length===0)this.listeners.delete($);else this.listeners.set($,Q);if(this.debug)console.log(`[event-bus] Removed listener from '${$}'`)}emit($,Z){let Y=this.listeners.get($);if(!Y||Y.length===0){if(this.debug)console.log(`[event-bus] No listeners for '${$}'`);return}if(this.debug)console.log(`[event-bus] Emitting '${$}' to ${Y.length} listener(s)`);let Q=[];for(let J of Y)try{let z=J.listener(Z);if(J.async&&z instanceof Promise)z.catch((K)=>{this.handleError(K,$,Z)});if(J.once)Q.push(J)}catch(z){this.handleError(z instanceof Error?z:Error(String(z)),$,Z)}if(Q.length>0){let J=Y.filter((z)=>!Q.includes(z));if(J.length===0)this.listeners.delete($);else this.listeners.set($,J)}}async emitAsync($,Z){let Y=this.listeners.get($);if(!Y||Y.length===0)return;if(this.debug)console.log(`[event-bus] Emitting async '${$}' to ${Y.length} listener(s)`);let Q=[],J=[];for(let z of Y)try{let K=z.listener(Z);if(K instanceof Promise)J.push(K.catch((X)=>{this.handleError(X instanceof Error?X:Error(String(X)),$,Z)}));if(z.once)Q.push(z)}catch(K){this.handleError(K instanceof Error?K:Error(String(K)),$,Z)}if(await Promise.all(J),Q.length>0){let z=Y.filter((K)=>!Q.includes(K));if(z.length===0)this.listeners.delete($);else this.listeners.set($,z)}}onError($){return this.errorHandlers.push($),()=>{let Z=this.errorHandlers.indexOf($);if(Z>=0)this.errorHandlers.splice(Z,1)}}listenerCount($){return this.listeners.get($)?.length??0}eventNames(){return Array.from(this.listeners.keys())}removeAllListeners($){if($)this.listeners.delete($);else this.listeners.clear();if(this.debug)console.log(`[event-bus] Removed all listeners${$?` for '${$}'`:""}`)}handleError($,Z,Y){if(this.debug||process.env.DEBUG)console.error(`[event-bus] Error in '${Z}' listener:`,$.message);for(let Q of this.errorHandlers)try{Q($,Z,Y)}catch{}}}function z0($){if(!o5)o5=new _Z($);return o5}var o5=null,z$;var w1=s0(()=>{z$=z0()});import{existsSync as v$,mkdirSync as i5,readFileSync as X4,writeFileSync as k1,renameSync as xZ,statSync as rz}from"fs";import{join as U$,dirname as fZ,relative as sz}from"path";import{createHash as tz,randomUUID as vZ}from"crypto";function pZ($,Z){if(h$=$,uZ=Z,a=U$($,".backup"),$K(),a5=!0,I0=v$(U$(a,".git")),I0)n5=QK()}function y1(){return a5}function D($,Z){let Y=fZ($);if(!v$(Y))i5(Y,{recursive:!0});let Q=U$(Y,`.smolerclaw-${vZ().slice(0,8)}.tmp`);k1(Q,Z),xZ(Q,$);let J=!1;if(a5){let K=YK($);if(K&&V4.includes(K))ez(K,Z),J=!0}let z={filePath:$,size:Buffer.byteLength(Z,"utf-8"),isTracked:J,timestamp:Date.now()};z$.emit("file:saved",z)}function dZ($){return tz("sha256").update($).digest("hex")}function ez($,Z){let Y=dZ(Z),Q=new Date().toISOString(),J=Buffer.byteLength(Z,"utf-8");K0=[...K0.filter((z)=>z.file!==$),{file:$,sha256:Y,size:J,updatedAt:Q}],ZK()}function $K(){let $=U$(h$,gZ);if(!v$($)){K0=[];return}try{let Z=JSON.parse(X4($,"utf-8"));if(Z.version!==hZ){K0=[];return}K0=Z.checksums||[]}catch{K0=[]}}function ZK(){if(!h$)return;let $=U$(h$,gZ),Z={checksums:K0,version:hZ},Y=U$(h$,`.vault-${vZ().slice(0,8)}.tmp`);k1(Y,JSON.stringify(Z,null,2)),xZ(Y,$)}function YK($){try{let Z=sz(h$,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function G4(){let $=[],Z=0;for(let Y of V4){let Q=U$(h$,Y),J=v$(Q);if(!J){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let z=0,K="";try{let G=rz(Q);z=G.size,K=G.mtime.toISOString()}catch{}let X=K0.find((G)=>G.file===Y),V=null;if(X)try{let G=X4(Q,"utf-8");if(V=dZ(G)===X.sha256,!V)Z++}catch{V=!1,Z++}$.push({file:Y,exists:J,checksumValid:V,size:z,lastModified:K})}return{files:$,lastBackup:n5,backupEnabled:I0,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function q4($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${V4.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
|
|
7
|
+
--- Arquivos ---`);for(let Q of $.files){if(!Q.exists){Z.push(` ${Q.file.padEnd(30)} (nao existe)`);continue}let J=(Q.size/1024).toFixed(1),z=Q.checksumValid===null?"?":Q.checksumValid?"OK":"CORROMPIDO",K=Q.lastModified?new Date(Q.lastModified).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${Q.file.padEnd(30)} ${J.padStart(8)} KB [${z}] ${K}`)}return Z.join(`
|
|
8
|
+
`)}async function U4(){if(!h$)return"Error: vault not initialized.";if(!v$(a))i5(a,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
|
|
9
|
+
`);if(k1(U$(a,".gitignore"),$),!v$(U$(a,".git"))){let Z=await X0(["git","init","-b",mZ],a);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await X0(["git","config","user.email","vault@smolerclaw.local"],a),await X0(["git","config","user.name","smolerclaw-vault"],a)}return I0=!0,"Shadow backup inicializado."}async function e0($){if(!I0)return"Backup nao ativado. Use vault_init_backup primeiro.";let Z=Date.now();try{for(let X of V4){let V=U$(h$,X);if(!v$(V))continue;let G=U$(a,X),q=fZ(G);if(!v$(q))i5(q,{recursive:!0});k1(G,X4(V,"utf-8"))}let Y=U$(uZ,"config.json");if(v$(Y))k1(U$(a,"config.json"),X4(Y,"utf-8"));if(await X0(["git","add","-A"],a),!(await X0(["git","status","--porcelain"],a)).stdout.trim()){let X={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:"Nenhuma mudanca para backup",duration:Date.now()-Z,timestamp:Date.now()};return z$.emit("task:completed",X),"Nenhuma mudanca para backup."}let J=$||`backup ${new Date().toISOString().slice(0,19)}`,z=await X0(["git","commit","-m",J],a);if(!z.ok){let X={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Commit falhou: ${z.stderr}`,duration:Date.now()-Z,timestamp:Date.now()};return z$.emit("task:completed",X),`Backup commit falhou: ${z.stderr}`}n5=new Date().toISOString();let K={taskId:`backup-${Date.now()}`,taskType:"backup",success:!0,message:`Backup concluido: ${J}`,duration:Date.now()-Z,timestamp:Date.now()};return z$.emit("task:completed",K),`Backup concluido: ${J}`}catch(Y){let Q=Y instanceof Error?Y.message:String(Y),J={taskId:`backup-${Date.now()}`,taskType:"backup",success:!1,message:`Backup falhou: ${Q}`,duration:Date.now()-Z,timestamp:Date.now()};return z$.emit("task:completed",J),`Backup falhou: ${Q}`}}async function H4(){if(!I0)return"Backup nao ativado.";if(!(await X0(["git","remote","-v"],a)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await X0(["git","push","-u","origin",mZ],a);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function QK(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:a,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function X0($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Q,J]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),z=await Y.exited;return{stdout:Q.trim(),stderr:J.trim(),ok:z===0}}function cZ($=30){if(r5(),!I0)return;K4=setInterval(()=>{e0("auto-backup").catch(()=>{})},$*60*1000)}function r5(){if(K4)clearInterval(K4),K4=null}var hZ=1,gZ="vault-checksums.json",mZ="smolerclaw-backup",V4,h$="",uZ="",K0,a="",I0=!1,n5=null,a5=!1,K4=null;var f=s0(()=>{w1();V4=["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"],K0=[]});var t2={};OZ(t2,{searchInvestigations:()=>n2,openInvestigation:()=>p2,listInvestigations:()=>i2,initInvestigations:()=>u2,getInvestigation:()=>o2,generateReport:()=>a2,formatInvestigationList:()=>P7,formatInvestigationDetail:()=>r2,formatEvidenceDetail:()=>OV,collectEvidence:()=>d2,closeInvestigation:()=>l2,addFinding:()=>c2});import{existsSync as b3,mkdirSync as WV,readFileSync as BV}from"fs";import{join as MV}from"path";import{randomUUID as CV}from"crypto";function D7(){D(x3(),JSON.stringify($$,null,2))}function NV(){let $=x3();if(!b3($)){$$=[];return}try{$$=JSON.parse(BV($,"utf-8"))}catch{$$=[]}}function u2($){if(_3=$,!b3($))WV($,{recursive:!0});NV()}function p2($,Z,Y,Q=[]){let J=new Date().toISOString(),z={id:s2(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:Q.map((K)=>K.toLowerCase()),evidence:[],findings:[],created:J,updated:J};return $$=[...$$,z],D7(),z}function d2($,Z,Y,Q,J){let z=k8($);if(!z)return null;let K=Q.trim();if(K.length>y3)K=K.slice(0,y3)+`
|
|
10
|
+
...(truncated, ${Q.length} total chars)`;let X={id:s2(),source:Z,label:Y.trim(),content:K,path:J?.trim(),timestamp:new Date().toISOString()},V={...z,evidence:[...z.evidence,X],status:z.status==="aberta"?"em_andamento":z.status,updated:new Date().toISOString()};return $$=$$.map((G)=>G.id===z.id?V:G),D7(),X}function c2($,Z,Y,Q,J=[]){let z=k8($);if(!z)return null;let K=J.filter((G)=>z.evidence.some((q)=>q.id===G)),X={id:s2(),severity:Z,title:Y.trim(),description:Q.trim(),evidence_ids:K,timestamp:new Date().toISOString()},V={...z,findings:[...z.findings,X],updated:new Date().toISOString()};return $$=$$.map((G)=>G.id===z.id?V:G),D7(),X}function l2($,Z,Y){let Q=k8($);if(!Q)return null;let J={...Q,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return $$=$$.map((z)=>z.id===Q.id?J:z),D7(),J}function o2($){return k8($)}function i2($,Z,Y=20){let Q=[...$$];if($)Q=Q.filter((J)=>J.status===$);if(Z)Q=Q.filter((J)=>J.type===Z);return Q.sort((J,z)=>new Date(z.updated).getTime()-new Date(J.updated).getTime()).slice(0,Y)}function n2($){let Z=$.toLowerCase();return $$.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.hypothesis?.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))||Y.findings.some((Q)=>Q.title.toLowerCase().includes(Z))||Y.summary?.toLowerCase().includes(Z)).sort((Y,Q)=>new Date(Q.updated).getTime()-new Date(Y.updated).getTime())}function a2($){let Z=k8($);if(!Z)return null;let Y=[],Q=(K)=>new Date(K).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),J={bug:"Bug / Mal funcionamento",feature:"Construcao de funcionalidade",test:"Material para testes",audit:"Auditoria",incident:"Incidente"},z={critical:0,high:1,medium:2,low:3,info:4};if(Y.push(`# Investigacao: ${Z.title}`),Y.push(""),Y.push(`**Tipo:** ${J[Z.type]}`),Y.push(`**Status:** ${Z.status}`),Y.push(`**Abertura:** ${Q(Z.created)}`),Y.push(`**Ultima atualizacao:** ${Q(Z.updated)}`),Z.tags.length)Y.push(`**Tags:** ${Z.tags.join(", ")}`);if(Y.push(`**ID:** ${Z.id}`),Z.hypothesis)Y.push(""),Y.push("## Hipotese"),Y.push(Z.hypothesis);if(Z.evidence.length>0){Y.push(""),Y.push(`## Evidencias (${Z.evidence.length})`);for(let K of Z.evidence){let X=Q(K.timestamp);Y.push(""),Y.push(`### [${K.id}] ${K.label}`),Y.push(`- Fonte: ${K.source}${K.path?` (${K.path})`:""}`),Y.push(`- Coletada: ${X}`);let V=K.content.length>2000?K.content.slice(0,2000)+`
|
|
11
|
+
... (truncado)`:K.content;Y.push("```"),Y.push(V),Y.push("```")}}if(Z.findings.length>0){let K=[...Z.findings].sort((X,V)=>(z[X.severity]??4)-(z[V.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let X of K){let V=v3(X.severity);if(Y.push(""),Y.push(`### ${V} ${X.title}`),Y.push(X.description),X.evidence_ids.length>0)Y.push(`- Evidencias: ${X.evidence_ids.join(", ")}`)}}if(Z.summary)Y.push(""),Y.push("## Resumo"),Y.push(Z.summary);if(Z.recommendations)Y.push(""),Y.push("## Recomendacoes"),Y.push(Z.recommendations);return Y.join(`
|
|
12
|
+
`)}function P7($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Y)=>{let Q=new Date(Y.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=f3(Y.status),z=Y.evidence.length,K=Y.findings.length,X=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${J} [${Q}] ${Y.title} (${Y.type}) \u2014 ${z} ev, ${K} concl${X} {${Y.id}}`});return`Investigacoes (${$.length}):
|
|
15
13
|
${Z.join(`
|
|
16
|
-
`)}`}function
|
|
17
|
-
Evidencias: ${$.evidence.length}`);for(let J of $.evidence.slice(-5)){let
|
|
18
|
-
Conclusoes: ${$.findings.length}`);for(let J of $.findings)
|
|
19
|
-
Resumo: ${$.summary}`);if($.recommendations)
|
|
20
|
-
`)}function
|
|
14
|
+
`)}`}function r2($){let Z=(J)=>new Date(J).toLocaleDateString("pt-BR"),Y=f3($.status),Q=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${Y}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)Q.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)Q.push(`Tags: ${$.tags.join(", ")}`);Q.push(`
|
|
15
|
+
Evidencias: ${$.evidence.length}`);for(let J of $.evidence.slice(-5)){let z=J.content.slice(0,80).replace(/\n/g," ");Q.push(` [${J.id}] ${J.source}: ${J.label} \u2014 "${z}..."`)}if($.evidence.length>5)Q.push(` ... (${$.evidence.length-5} mais)`);Q.push(`
|
|
16
|
+
Conclusoes: ${$.findings.length}`);for(let J of $.findings)Q.push(` ${v3(J.severity)} ${J.title}`);if($.summary)Q.push(`
|
|
17
|
+
Resumo: ${$.summary}`);if($.recommendations)Q.push(`Recomendacoes: ${$.recommendations}`);return Q.join(`
|
|
18
|
+
`)}function OV($){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
19
|
... (truncado)`:$.content].join(`
|
|
22
|
-
`)}function
|
|
20
|
+
`)}function k8($){let Z=$.toLowerCase().trim(),Y=$$.find((J)=>J.id===Z);if(Y)return Y;return $$.filter((J)=>J.title.toLowerCase().includes(Z)).sort((J,z)=>new Date(z.updated).getTime()-new Date(J.updated).getTime())[0]||null}function f3($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function v3($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function s2(){return CV().slice(0,8)}var _3="",$$,x3=()=>MV(_3,"investigations.json"),y3=50000;var y8=s0(()=>{f();$$=[]});var VQ={};OZ(VQ,{openUrl:()=>c0,openFile:()=>f8,openApp:()=>d0,getSystemInfo:()=>l0,getRunningApps:()=>v8,getOutlookEvents:()=>k$,getKnownApps:()=>L9,getDateTimeInfo:()=>o0});function E9($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(eG.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function d0($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),Q=R9[Y];if(!Q){let J=Object.keys(R9).join(", ");return`Unknown app: "${$}". Available: ${J}`}if(Z){let J=E9(Z,"argument");if(J)return J}if(!L)return"Error: this command is only available on Windows.";if(!Q.includes(":")){let J=await Q4(Q);if(!J.exists)return`Error: ${Q} not found. ${J.error||""}`}try{let J=await c5(Q,Z);if(J.exitCode!==0&&J.stderr.trim())return`Error opening ${$}: ${J.stderr.trim()}`;if(J.timedOut)return`Error opening ${$}: timeout (application may have opened but response was delayed)`;return`Opened: ${$}`}catch(J){return`Error opening ${$}: ${J instanceof Error?J.message:String(J)}`}}async function c0($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=E9($,"URL");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await c5($);if(Y.exitCode!==0&&Y.stderr.trim())return`Error: ${Y.stderr.trim()}`;if(Y.timedOut)return"Error: timeout opening URL (browser may have opened but response was delayed)";return`Opened in browser: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function f8($){let Z=E9($,"file path");if(Z)return Z;if(!L)return"Error: this command is only available on Windows.";try{let Y=await IZ($);if(Y.exitCode!==0&&Y.stderr.trim())return`Error: ${Y.stderr.trim()}`;if(Y.timedOut)return"Error: timeout opening file (application may have opened but response was delayed)";return`Opened: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function v8(){if(!L)return"Error: this command is only available on Windows.";try{let $=await SZ(15);if($.stderr.trim())return`Error: ${$.stderr.trim()}`;if($.timedOut)return"Error: timeout getting process list";return $.stdout.trim()||"No windowed applications running."}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}async function l0(){if(!L)return"Error: this command is only available on Windows.";let $=['$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average; "CPU: $cpu%"','$os = Get-CimInstance Win32_OperatingSystem; $total = [math]::Round($os.TotalVisibleMemorySize/1MB,1); $free = [math]::Round($os.FreePhysicalMemory/1MB,1); $used = $total - $free; "RAM: $used GB / $total GB (Free: $free GB)"','Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { $free = [math]::Round($_.FreeSpace/1GB,1); $total = [math]::Round($_.Size/1GB,1); "$($_.DeviceID) $free GB free / $total GB" }','$uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime; "Uptime: $($uptime.Days)d $($uptime.Hours)h $($uptime.Minutes)m"','$b = Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue; if ($b) { "Battery: $($b.EstimatedChargeRemaining)%" } else { "Battery: N/A (desktop)" }'];try{let Z=await J$($.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 o0(){let $=new Date,Z=[],Y=$.toLocaleDateString("pt-BR",{weekday:"long"}),Q=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),J=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${Y}, ${Q} \u2014 ${J}`);let z=new Date($.valueOf());z.setDate(z.getDate()+3-(z.getDay()+6)%7);let K=new Date(z.getFullYear(),0,4),X=1+Math.round(((z.getTime()-K.getTime())/86400000-3+(K.getDay()+6)%7)/7);Z.push(`Semana ${X} do ano`);let V=$.getHours();if(V>=8&&V<18)Z.push("Status: horario comercial");else if(V>=18&&V<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
|
|
21
|
+
`)}async function k$(){if(!L)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(`
|
|
22
|
+
`);try{let Z=await J$($,{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 L9(){return Object.keys(R9)}var eG,R9;var i0=s0(()=>{p();f$();eG=/[";`$\n\r|&<>{}()]/;R9={excel:"excel",word:"winword",powerpoint:"powerpnt",outlook:"ms-outlook:",onenote:"onenote",teams:"msteams:",edge:"msedge",chrome:"chrome",firefox:"firefox",calculator:"calc",notepad:"notepad",terminal:"wt",explorer:"explorer",taskmanager:"taskmgr",settings:"ms-settings:",paint:"mspaint",snip:"snippingtool",vscode:"code",cursor:"cursor",postman:"Postman"}});import{readFileSync as vz}from"fs";import{join as hz,dirname as gz}from"path";function FZ($){let Z={help:!1,version:!1,noTools:!1,print:!1},Y=[],Q=0;while(Q<$.length){let J=$[Q];switch(J){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++Q],!Z.model)$4("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Q],!Z.session)$4("--session requires a value");break;case"--max-tokens":let z=Number($[++Q]);if(!z||z<=0)$4("--max-tokens requires a positive number");Z.maxTokens=z;break;case"--no-tools":Z.noTools=!0;break;case"-p":case"--print":Z.print=!0;break;default:if(J.startsWith("-"))$4(`Unknown option: ${J}. Try --help`);Y.push(J)}Q++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function A1(){return"1.4.0"}function RZ(){let $=A1();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
|
|
23
23
|
|
|
24
24
|
Usage:
|
|
25
25
|
smolerclaw [options] [prompt]
|
|
@@ -47,15 +47,16 @@ 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 Q0($){console.error(`smolerclaw: ${$}`),process.exit(2)}Z$();n();import{existsSync as N0,mkdirSync as GX,readFileSync as C2}from"fs";import{homedir as HX}from"os";import{join as a$}from"path";var h8=HX(),M0=A?a$(process.env.APPDATA||a$(h8,"AppData","Roaming"),"smolerclaw"):a$(h8,".config","smolerclaw"),T5=A?a$(process.env.LOCALAPPDATA||a$(h8,"AppData","Local"),"smolerclaw"):a$(h8,".local","share","smolerclaw"),B4=a$(M0,"config.json"),J8={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:T5,toolApproval:"auto",language:"auto",maxSessionCost:0};function f8($){if(!N0($))GX($,{recursive:!0})}function N2(){if(f8(M0),f8(T5),f8(a$(T5,"sessions")),A)UX();if(!N0(B4))return S(B4,JSON.stringify(J8,null,2)),{...J8};let $;try{$=JSON.parse(C2(B4,"utf-8"))}catch{return S(B4,JSON.stringify(J8,null,2)),{...J8}}return qX({...J8,...$})}function qX($){let Z={...J8};if(typeof $.model==="string"&&$.model.trim())Z.model=$.model;if(typeof $.maxTokens==="number"&&$.maxTokens>0&&$.maxTokens<=1e5)Z.maxTokens=$.maxTokens;if(typeof $.maxHistory==="number"&&$.maxHistory>0&&$.maxHistory<=1000)Z.maxHistory=$.maxHistory;if(typeof $.systemPrompt==="string")Z.systemPrompt=$.systemPrompt;if(typeof $.skillsDir==="string"&&$.skillsDir.trim())Z.skillsDir=$.skillsDir;if(typeof $.dataDir==="string"&&$.dataDir.trim())Z.dataDir=$.dataDir;let Q=["auto","confirm-writes","confirm-all"];if(typeof $.toolApproval==="string"&&Q.includes($.toolApproval))Z.toolApproval=$.toolApproval;if(typeof $.language==="string")Z.language=$.language;if(typeof $.maxSessionCost==="number"&&$.maxSessionCost>=0)Z.maxSessionCost=$.maxSessionCost;return Z}function F0($){f8(M0),S(B4,JSON.stringify($,null,2))}function A5(){return B4}function UX(){let $=a$(h8,".config","smolerclaw","config.json");if(N0($)&&!N0(B4))try{let Z=C2($,"utf-8");f8(M0),S(B4,Z)}catch{}}import{existsSync as WX,readFileSync as BX}from"fs";import{homedir as CX}from"os";import{join as NX}from"path";var M2=NX(CX(),".claude",".credentials.json");function I5(){let $=MX();if($)return $;throw Error("Claude Code subscription not found or expired.\nInstall Claude Code with a Pro/Max subscription and run `claude` to authenticate.")}function MX(){if(!WX(M2))return null;try{let Z=JSON.parse(BX(M2,"utf-8")).claudeAiOauth;if(!Z?.accessToken)return null;if(Date.now()>Z.expiresAt-60000)return null;return{token:Z.accessToken,subscriptionType:Z.subscriptionType,expiresAt:Z.expiresAt}}catch{return null}}function x5(){try{return I5()}catch{return null}}function F2($){return`sub:${$.subscriptionType||"pro"}`}function D($,Z,Q,Y,J){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!J:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?J.call($,Q):J?J.value=Q:Z.set($,Q),Q}function M($,Z,Q,Y){if(Q==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Q==="m"?Y:Q==="a"?Y.call($):Y?Y.value:Z.get($)}var S5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return S5=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),Q=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^Q()&15>>+Y/4).toString(16))};function n$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var g8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class T extends Error{}class t extends T{constructor($,Z,Q,Y){super(`${t.makeMessage($,Z,Q)}`);this.status=$,this.headers=Y,this.requestID=Y?.get("request-id"),this.error=Z}static makeMessage($,Z,Q){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Q;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,Q,Y){if(!$||!Y)return new y4({message:Q,cause:g8(Z)});let J=Z;if($===400)return new p8($,J,Q,Y);if($===401)return new c8($,J,Q,Y);if($===403)return new u8($,J,Q,Y);if($===404)return new d8($,J,Q,Y);if($===409)return new l8($,J,Q,Y);if($===422)return new o8($,J,Q,Y);if($===429)return new a8($,J,Q,Y);if($>=500)return new n8($,J,Q,Y);return new t($,J,Q,Y)}}class z$ extends t{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class y4 extends t{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class m8 extends y4{constructor({message:$}={}){super({message:$??"Request timed out."})}}class p8 extends t{}class c8 extends t{}class u8 extends t{}class d8 extends t{}class l8 extends t{}class o8 extends t{}class a8 extends t{}class n8 extends t{}var OX=/^[a-z][a-z0-9+.-]*:/i,O2=($)=>{return OX.test($)},w5=($)=>(w5=Array.isArray,w5($)),k5=w5;function O0($){if(typeof $!=="object")return{};return $??{}}function y5($){if(!$)return!0;for(let Z in $)return!1;return!0}function R2($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var E2=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new T(`${$} must be an integer`);if(Z<0)throw new T(`${$} must be a positive integer`);return Z};var R0=($)=>{try{return JSON.parse($)}catch(Z){return}};var L2=($)=>new Promise((Z)=>setTimeout(Z,$));var C4="0.80.0";var T2=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function RX(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var EX=()=>{let $=RX();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C4,"X-Stainless-OS":D2(Deno.build.os),"X-Stainless-Arch":j2(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C4,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if($==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C4,"X-Stainless-OS":D2(globalThis.process.platform??"unknown"),"X-Stainless-Arch":j2(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=LX();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C4,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${Z.browser}`,"X-Stainless-Runtime-Version":Z.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":C4,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function LX(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:Q}of $){let Y=Q.exec(navigator.userAgent);if(Y){let J=Y[1]||0,X=Y[2]||0,K=Y[3]||0;return{browser:Z,version:`${J}.${X}.${K}`}}}return null}var j2=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},D2=($)=>{if($=$.toLowerCase(),$.includes("ios"))return"iOS";if($==="android")return"Android";if($==="darwin")return"MacOS";if($==="win32")return"Windows";if($==="freebsd")return"FreeBSD";if($==="openbsd")return"OpenBSD";if($==="linux")return"Linux";if($)return`Other:${$}`;return"Unknown"},P2,A2=()=>{return P2??(P2=EX())};function I2(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function b5(...$){let Z=globalThis.ReadableStream;if(typeof Z>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new Z(...$)}function E0($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return b5({start(){},async pull(Q){let{done:Y,value:J}=await Z.next();if(Y)Q.close();else Q.enqueue(J)},async cancel(){await Z.return?.()}})}function r8($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let Q=await Z.read();if(Q?.done)Z.releaseLock();return Q}catch(Q){throw Z.releaseLock(),Q}},async return(){let Q=Z.cancel();return Z.releaseLock(),await Q,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function x2($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Q=Z.cancel();Z.releaseLock(),await Q}var S2=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function w2($){return Object.entries($).filter(([Z,Q])=>typeof Q<"u").map(([Z,Q])=>{if(typeof Q==="string"||typeof Q==="number"||typeof Q==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(Q)}`;if(Q===null)return`${encodeURIComponent(Z)}=`;throw new T(`Cannot stringify type ${typeof Q}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function b2($){let Z=0;for(let J of $)Z+=J.length;let Q=new Uint8Array(Z),Y=0;for(let J of $)Q.set(J,Y),Y+=J.length;return Q}var k2;function i8($){let Z;return(k2??(Z=new globalThis.TextEncoder,k2=Z.encode.bind(Z)))($)}var y2;function _5($){let Z;return(y2??(Z=new globalThis.TextDecoder,y2=Z.decode.bind(Z)))($)}var F$,O$;class N4{constructor(){F$.set(this,void 0),O$.set(this,void 0),D(this,F$,new Uint8Array,"f"),D(this,O$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?i8($):$;D(this,F$,b2([M(this,F$,"f"),Z]),"f");let Q=[],Y;while((Y=PX(M(this,F$,"f"),M(this,O$,"f")))!=null){if(Y.carriage&&M(this,O$,"f")==null){D(this,O$,Y.index,"f");continue}if(M(this,O$,"f")!=null&&(Y.index!==M(this,O$,"f")+1||Y.carriage)){Q.push(_5(M(this,F$,"f").subarray(0,M(this,O$,"f")-1))),D(this,F$,M(this,F$,"f").subarray(M(this,O$,"f")),"f"),D(this,O$,null,"f");continue}let J=M(this,O$,"f")!==null?Y.preceding-1:Y.preceding,X=_5(M(this,F$,"f").subarray(0,J));Q.push(X),D(this,F$,M(this,F$,"f").subarray(Y.index),"f"),D(this,O$,null,"f")}return Q}flush(){if(!M(this,F$,"f").length)return[];return this.decode(`
|
|
51
|
-
`)}}
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
`)
|
|
55
|
-
${
|
|
50
|
+
/export Export markdown /exit Quit`)}function $4($){console.error(`smolerclaw: ${$}`),process.exit(2)}p();f();import{existsSync as W4,mkdirSync as JK,readFileSync as lZ}from"fs";import{homedir as zK}from"os";import{join as g$}from"path";var _1=zK(),B4=L?g$(process.env.APPDATA||g$(_1,"AppData","Roaming"),"smolerclaw"):g$(_1,".config","smolerclaw"),s5=L?g$(process.env.LOCALAPPDATA||g$(_1,"AppData","Local"),"smolerclaw"):g$(_1,".local","share","smolerclaw"),V0=g$(B4,"config.json"),$1={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:s5,toolApproval:"auto",language:"auto",maxSessionCost:0};function b1($){if(!W4($))JK($,{recursive:!0})}function oZ(){if(b1(B4),b1(s5),b1(g$(s5,"sessions")),L)XK();if(!W4(V0))return D(V0,JSON.stringify($1,null,2)),{...$1};let $;try{$=JSON.parse(lZ(V0,"utf-8"))}catch{return D(V0,JSON.stringify($1,null,2)),{...$1}}return KK({...$1,...$})}function KK($){let Z={...$1};if(typeof $.model==="string"&&$.model.trim())Z.model=$.model;if(typeof $.maxTokens==="number"&&$.maxTokens>0&&$.maxTokens<=1e5)Z.maxTokens=$.maxTokens;if(typeof $.maxHistory==="number"&&$.maxHistory>0&&$.maxHistory<=1000)Z.maxHistory=$.maxHistory;if(typeof $.systemPrompt==="string")Z.systemPrompt=$.systemPrompt;if(typeof $.skillsDir==="string"&&$.skillsDir.trim())Z.skillsDir=$.skillsDir;if(typeof $.dataDir==="string"&&$.dataDir.trim())Z.dataDir=$.dataDir;let Y=["auto","confirm-writes","confirm-all"];if(typeof $.toolApproval==="string"&&Y.includes($.toolApproval))Z.toolApproval=$.toolApproval;if(typeof $.language==="string")Z.language=$.language;if(typeof $.maxSessionCost==="number"&&$.maxSessionCost>=0)Z.maxSessionCost=$.maxSessionCost;return Z}function M4($){b1(B4),D(V0,JSON.stringify($,null,2))}function C4(){return V0}function XK(){let $=g$(_1,".config","smolerclaw","config.json");if(W4($)&&!W4(V0))try{let Z=lZ($,"utf-8");b1(B4),D(V0,Z)}catch{}}import{existsSync as VK,readFileSync as GK}from"fs";import{homedir as qK}from"os";import{join as UK}from"path";var iZ=UK(qK(),".claude",".credentials.json");function t5(){let $=HK();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 HK(){if(!VK(iZ))return null;try{let Z=JSON.parse(GK(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 N4(){try{return t5()}catch{return null}}function nZ($){return`sub:${$.subscriptionType||"pro"}`}var O4=[{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 F4($){let Z=O4.find((z)=>z.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),Q=O4.find((z)=>z.alias===Y);if(Q)return Q.id;let J=O4.find((z)=>z.id.includes(Y)||z.name.toLowerCase().includes(Y));if(J)return J.id;return $}function aZ($){let Z=["Available models:"];for(let Y of O4){let Q=Y.id===$?" *":" ",J=Y.tier==="fast"?"\u26A1":Y.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${Q} ${Y.alias.padEnd(12)} ${J} ${Y.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
|
|
51
|
+
`)}function F($,Z,Y,Q,J){if(Q==="m")throw TypeError("Private method is not writable");if(Q==="a"&&!J)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!J:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Q==="a"?J.call($,Y):J?J.value=Y:Z.set($,Y),Y}function C($,Z,Y,Q){if(Y==="a"&&!Q)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Q:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?Q:Y==="a"?Q.call($):Q?Q.value:Z.get($)}var e5=function(){let{crypto:$}=globalThis;if($?.randomUUID)return e5=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),Y=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Q)=>(+Q^Y()&15>>+Q/4).toString(16))};function m$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var x1=($)=>{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 E extends Error{}class d extends E{constructor($,Z,Y,Q){super(`${d.makeMessage($,Z,Y)}`);this.status=$,this.headers=Q,this.requestID=Q?.get("request-id"),this.error=Z}static makeMessage($,Z,Y){let Q=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Y;if($&&Q)return`${$} ${Q}`;if($)return`${$} status code (no body)`;if(Q)return Q;return"(no status code or body)"}static generate($,Z,Y,Q){if(!$||!Q)return new S0({message:Y,cause:x1(Z)});let J=Z;if($===400)return new v1($,J,Y,Q);if($===401)return new h1($,J,Y,Q);if($===403)return new g1($,J,Y,Q);if($===404)return new m1($,J,Y,Q);if($===409)return new u1($,J,Y,Q);if($===422)return new p1($,J,Y,Q);if($===429)return new d1($,J,Y,Q);if($>=500)return new c1($,J,Y,Q);return new d($,J,Y,Q)}}class e extends d{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class S0 extends d{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class f1 extends S0{constructor({message:$}={}){super({message:$??"Request timed out."})}}class v1 extends d{}class h1 extends d{}class g1 extends d{}class m1 extends d{}class u1 extends d{}class p1 extends d{}class d1 extends d{}class c1 extends d{}var BK=/^[a-z][a-z0-9+.-]*:/i,rZ=($)=>{return BK.test($)},$2=($)=>($2=Array.isArray,$2($)),Z2=$2;function R4($){if(typeof $!=="object")return{};return $??{}}function Y2($){if(!$)return!0;for(let Z in $)return!1;return!0}function sZ($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var tZ=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new E(`${$} must be an integer`);if(Z<0)throw new E(`${$} must be a positive integer`);return Z};var E4=($)=>{try{return JSON.parse($)}catch(Z){return}};var eZ=($)=>new Promise((Z)=>setTimeout(Z,$));var G0="0.80.0";var Q6=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function MK(){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 CK=()=>{let $=MK();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":G0,"X-Stainless-OS":Z6(Deno.build.os),"X-Stainless-Arch":$6(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":G0,"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":G0,"X-Stainless-OS":Z6(globalThis.process.platform??"unknown"),"X-Stainless-Arch":$6(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=NK();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":G0,"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":G0,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function NK(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:Y}of $){let Q=Y.exec(navigator.userAgent);if(Q){let J=Q[1]||0,z=Q[2]||0,K=Q[3]||0;return{browser:Z,version:`${J}.${z}.${K}`}}}return null}var $6=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},Z6=($)=>{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"},Y6,J6=()=>{return Y6??(Y6=CK())};function z6(){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 Q2(...$){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 L4($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return Q2({start(){},async pull(Y){let{done:Q,value:J}=await Z.next();if(Q)Y.close();else Y.enqueue(J)},async cancel(){await Z.return?.()}})}function l1($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let Y=await Z.read();if(Y?.done)Z.releaseLock();return Y}catch(Y){throw Z.releaseLock(),Y}},async return(){let Y=Z.cancel();return Z.releaseLock(),await Y,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function K6($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var X6=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function V6($){return Object.entries($).filter(([Z,Y])=>typeof Y<"u").map(([Z,Y])=>{if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(Y)}`;if(Y===null)return`${encodeURIComponent(Z)}=`;throw new E(`Cannot stringify type ${typeof Y}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function U6($){let Z=0;for(let J of $)Z+=J.length;let Y=new Uint8Array(Z),Q=0;for(let J of $)Y.set(J,Q),Q+=J.length;return Y}var G6;function o1($){let Z;return(G6??(Z=new globalThis.TextEncoder,G6=Z.encode.bind(Z)))($)}var q6;function J2($){let Z;return(q6??(Z=new globalThis.TextDecoder,q6=Z.decode.bind(Z)))($)}var H$,W$;class q0{constructor(){H$.set(this,void 0),W$.set(this,void 0),F(this,H$,new Uint8Array,"f"),F(this,W$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?o1($):$;F(this,H$,U6([C(this,H$,"f"),Z]),"f");let Y=[],Q;while((Q=RK(C(this,H$,"f"),C(this,W$,"f")))!=null){if(Q.carriage&&C(this,W$,"f")==null){F(this,W$,Q.index,"f");continue}if(C(this,W$,"f")!=null&&(Q.index!==C(this,W$,"f")+1||Q.carriage)){Y.push(J2(C(this,H$,"f").subarray(0,C(this,W$,"f")-1))),F(this,H$,C(this,H$,"f").subarray(C(this,W$,"f")),"f"),F(this,W$,null,"f");continue}let J=C(this,W$,"f")!==null?Q.preceding-1:Q.preceding,z=J2(C(this,H$,"f").subarray(0,J));Y.push(z),F(this,H$,C(this,H$,"f").subarray(Q.index),"f"),F(this,W$,null,"f")}return Y}flush(){if(!C(this,H$,"f").length)return[];return this.decode(`
|
|
52
|
+
`)}}H$=new WeakMap,W$=new WeakMap;q0.NEWLINE_CHARS=new Set([`
|
|
53
|
+
`,"\r"]);q0.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function RK($,Z){for(let J=Z??0;J<$.length;J++){if($[J]===10)return{preceding:J,index:J+1,carriage:!1};if($[J]===13)return{preceding:J,index:J+1,carriage:!0}}return null}function H6($){for(let Q=0;Q<$.length-1;Q++){if($[Q]===10&&$[Q+1]===10)return Q+2;if($[Q]===13&&$[Q+1]===13)return Q+2;if($[Q]===13&&$[Q+1]===10&&Q+3<$.length&&$[Q+2]===13&&$[Q+3]===10)return Q+4}return-1}var D4={off:0,error:200,warn:300,info:400,debug:500},z2=($,Z,Y)=>{if(!$)return;if(sZ(D4,$))return $;o(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(D4))}`);return};function i1(){}function j4($,Z,Y){if(!Z||D4[$]>D4[Y])return i1;else return Z[$].bind(Z)}var EK={error:i1,warn:i1,info:i1,debug:i1},W6=new WeakMap;function o($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return EK;let Q=W6.get(Z);if(Q&&Q[0]===Y)return Q[1];let J={error:j4("error",Z,Y),warn:j4("warn",Z,Y),info:j4("info",Z,Y),debug:j4("debug",Z,Y)};return W6.set(Z,[Y,J]),J}var u$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,Y])=>[Z,Z.toLowerCase()==="x-api-key"||Z.toLowerCase()==="authorization"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":Y]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var n1;class B${constructor($,Z,Y){this.iterator=$,n1.set(this,void 0),this.controller=Z,F(this,n1,Y,"f")}static fromSSEResponse($,Z,Y){let Q=!1,J=Y?o(Y):console;async function*z(){if(Q)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let K=!1;try{for await(let X of LK($,Z)){if(X.event==="completion")try{yield JSON.parse(X.data)}catch(V){throw J.error("Could not parse message into JSON:",X.data),J.error("From chunk:",X.raw),V}if(X.event==="message_start"||X.event==="message_delta"||X.event==="message_stop"||X.event==="content_block_start"||X.event==="content_block_delta"||X.event==="content_block_stop")try{yield JSON.parse(X.data)}catch(V){throw J.error("Could not parse message into JSON:",X.data),J.error("From chunk:",X.raw),V}if(X.event==="ping")continue;if(X.event==="error")throw new d(void 0,E4(X.data)??X.data,void 0,$.headers)}K=!0}catch(X){if(m$(X))return;throw X}finally{if(!K)Z.abort()}}return new B$(z,Z,Y)}static fromReadableStream($,Z,Y){let Q=!1;async function*J(){let K=new q0,X=l1($);for await(let V of X)for(let G of K.decode(V))yield G;for(let V of K.flush())yield V}async function*z(){if(Q)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Q=!0;let K=!1;try{for await(let X of J()){if(K)continue;if(X)yield JSON.parse(X)}K=!0}catch(X){if(m$(X))return;throw X}finally{if(!K)Z.abort()}}return new B$(z,Z,Y)}[(n1=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Y=this.iterator(),Q=(J)=>{return{next:()=>{if(J.length===0){let z=Y.next();$.push(z),Z.push(z)}return J.shift()}}};return[new B$(()=>Q($),this.controller,C(this,n1,"f")),new B$(()=>Q(Z),this.controller,C(this,n1,"f"))]}toReadableStream(){let $=this,Z;return Q2({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:Q,done:J}=await Z.next();if(J)return Y.close();let z=o1(JSON.stringify(Q)+`
|
|
54
|
+
`);Y.enqueue(z)}catch(Q){Y.error(Q)}},async cancel(){await Z.return?.()}})}}async function*LK($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new E("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 E("Attempted to iterate over a response with no body")}let Y=new B6,Q=new q0,J=l1($.body);for await(let z of jK(J))for(let K of Q.decode(z)){let X=Y.decode(K);if(X)yield X}for(let z of Q.flush()){let K=Y.decode(z);if(K)yield K}}async function*jK($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let Q=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?o1(Y):Y,J=new Uint8Array(Z.length+Q.length);J.set(Z),J.set(Q,Z.length),Z=J;let z;while((z=H6(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class B6{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let J={event:this.event,data:this.data.join(`
|
|
55
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],J}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,Q]=DK($,":");if(Q.startsWith(" "))Q=Q.substring(1);if(Z==="event")this.event=Q;else if(Z==="data")this.data.push(Q);return null}}function DK($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function P4($,Z){let{response:Y,requestLogID:Q,retryOfRequestLogID:J,startTime:z}=Z,K=await(async()=>{if(Z.options.stream){if(o($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return B$.fromSSEResponse(Y,Z.controller)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let V=Y.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){if(Y.headers.get("content-length")==="0")return;let W=await Y.json();return K2(W,Y)}return await Y.text()})();return o($).debug(`[${Q}] response parsed`,u$({retryOfRequestLogID:J,url:Y.url,status:Y.status,body:K,durationMs:Date.now()-z})),K}function K2($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var a1;class w0 extends Promise{constructor($,Z,Y=P4){super((Q)=>{Q(null)});this.responsePromise=Z,this.parseResponse=Y,a1.set(this,void 0),F(this,a1,$,"f")}_thenUnwrap($){return new w0(C(this,a1,"f"),this.responsePromise,async(Z,Y)=>K2($(await this.parseResponse(Z,Y),Y),Y.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(C(this,a1,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}a1=new WeakMap;var T4;class X2{constructor($,Z,Y,Q){T4.set(this,void 0),F(this,T4,$,"f"),this.options=Q,this.response=Z,this.body=Y}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new E("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,T4,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(T4=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class A4 extends w0{constructor($,Z,Y){super($,Z,async(Q,J)=>new Y(Q,J.response,await P4(Q,J),J.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class P$ extends X2{constructor($,Z,Y,Q){super($,Z,Y,Q);this.data=Y.data||[],this.has_more=Y.has_more||!1,this.first_id=Y.first_id||null,this.last_id=Y.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let Z=this.first_id;if(!Z)return null;return{...this.options,query:{...R4(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...R4(this.options.query),after_id:$}}}}class r1 extends X2{constructor($,Z,Y,Q){super($,Z,Y,Q);this.data=Y.data||[],this.has_more=Y.has_more||!1,this.next_page=Y.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.next_page;if(!$)return null;return{...this.options,query:{...R4(this.options.query),page:$}}}}var G2=()=>{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 k0($,Z,Y){return G2(),new File($,Z??"unknown_file",Y)}function s1($,Z){let Y=typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"";return Z?Y.split(/[\\/]/).pop()||void 0:Y}var q2=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var Z1=async($,Z,Y=!0)=>{return{...$,body:await AK($.body,Z,Y)}},M6=new WeakMap;function TK($){let Z=typeof $==="function"?$:$.fetch,Y=M6.get(Z);if(Y)return Y;let Q=(async()=>{try{let J="Response"in Z?Z.Response:(await Z("data:,")).constructor,z=new FormData;if(z.toString()===await new J(z).text())return!1;return!0}catch{return!0}})();return M6.set(Z,Q),Q}var AK=async($,Z,Y=!0)=>{if(!await TK(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Q=new FormData;return await Promise.all(Object.entries($||{}).map(([J,z])=>V2(Q,J,z,Y))),Q},IK=($)=>$ instanceof Blob&&("name"in $);var V2=async($,Z,Y,Q)=>{if(Y===void 0)return;if(Y==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")$.append(Z,String(Y));else if(Y instanceof Response){let J={},z=Y.headers.get("Content-Type");if(z)J={type:z};$.append(Z,k0([await Y.blob()],s1(Y,Q),J))}else if(q2(Y))$.append(Z,k0([await new Response(L4(Y)).blob()],s1(Y,Q)));else if(IK(Y))$.append(Z,k0([Y],s1(Y,Q),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((J)=>V2($,Z+"[]",J,Q)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([J,z])=>V2($,`${Z}[${J}]`,z,Q)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var C6=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",SK=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&C6($),wK=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function I4($,Z,Y){if(G2(),$=await $,Z||(Z=s1($,!0)),SK($)){if($ instanceof File&&Z==null&&Y==null)return $;return k0([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(wK($)){let J=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),k0(await U2(J),Z,Y)}let Q=await U2($);if(!Y?.type){let J=Q.find((z)=>typeof z==="object"&&("type"in z)&&z.type);if(typeof J==="string")Y={...Y,type:J}}return k0(Q,Z,Y)}async function U2($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(C6($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(q2($))for await(let Y of $)Z.push(...await U2(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${kK($)}`)}return Z}function kK($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class h{constructor($){this._client=$}}var N6=Symbol.for("brand.privateNullableHeaders");function*bK($){if(!$)return;if(N6 in $){let{values:Q,nulls:J}=$;yield*Q.entries();for(let z of J)yield[z,null];return}let Z=!1,Y;if($ instanceof Headers)Y=$.entries();else if(Z2($))Y=$;else Z=!0,Y=Object.entries($??{});for(let Q of Y){let J=Q[0];if(typeof J!=="string")throw TypeError("expected header name to be a string");let z=Z2(Q[1])?Q[1]:[Q[1]],K=!1;for(let X of z){if(X===void 0)continue;if(Z&&!K)K=!0,yield[J,null];yield[J,X]}}}var T=($)=>{let Z=new Headers,Y=new Set;for(let Q of $){let J=new Set;for(let[z,K]of bK(Q)){let X=z.toLowerCase();if(!J.has(X))Z.delete(z),J.add(X);if(K===null)Z.delete(z),Y.add(X);else Z.append(z,K),Y.delete(X)}}return{[N6]:!0,values:Z,nulls:Y}};var t1=Symbol("anthropic.sdk.stainlessHelper");function S4($){return typeof $==="object"&&$!==null&&t1 in $}function H2($,Z){let Y=new Set;if($){for(let Q of $)if(S4(Q))Y.add(Q[t1])}if(Z)for(let Q of Z){if(S4(Q))Y.add(Q[t1]);if(Array.isArray(Q.content)){for(let J of Q.content)if(S4(J))Y.add(J[t1])}}return Array.from(Y)}function w4($,Z){let Y=H2($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function O6($){if(S4($))return{"x-stainless-helper":$[t1]};return{}}function R6($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var F6=Object.freeze(Object.create(null)),_K=($=R6)=>function(Y,...Q){if(Y.length===1)return Y[0];let J=!1,z=[],K=Y.reduce((q,U,W)=>{if(/[?#]/.test(U))J=!0;let B=Q[W],M=(J?encodeURIComponent:$)(""+B);if(W!==Q.length&&(B==null||typeof B==="object"&&B.toString===Object.getPrototypeOf(Object.getPrototypeOf(B.hasOwnProperty??F6)??F6)?.toString))M=B+"",z.push({start:q.length+U.length,length:M.length,error:`Value of type ${Object.prototype.toString.call(B).slice(8,-1)} is not a valid path parameter`});return q+U+(W===Q.length?"":M)},""),X=K.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,G;while((G=V.exec(X))!==null)z.push({start:G.index,length:G[0].length,error:`Value "${G[0]}" can't be safely passed as a path parameter`});if(z.sort((q,U)=>q.start-U.start),z.length>0){let q=0,U=z.reduce((W,B)=>{let M=" ".repeat(B.start-q),O="^".repeat(B.length);return q=B.start+B.length,W+M+O},"");throw new E(`Path parameters result in path with invalid segments:
|
|
56
|
+
${z.map((W)=>W.error).join(`
|
|
56
57
|
`)}
|
|
57
58
|
${K}
|
|
58
|
-
${B}`)}return K},d=gX(u2);class Y1 extends l{list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/files",y$,{query:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Q){let{betas:Y}=Z??{};return this._client.delete(d`/v1/files/${$}`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Q?.headers])})}download($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/files/${$}/content`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Q?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/files/${$}`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Q?.headers])})}upload($,Z){let{betas:Q,...Y}=$;return this._client.post("/v1/files",X8({body:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},p2(Y.file),Z?.headers])},this._client))}}class J1 extends l{retrieve($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/models/${$}?beta=true`,{...Q,headers:k([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Q?.headers])})}list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/models?beta=true",y$,{query:Y,...Z,headers:k([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Z?.headers])})}}var S0={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192};function d2($){return $?.output_format??$?.output_config?.format}function d5($,Z,Q){let Y=d2(Z);if(!Z||!("parse"in(Y??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text"){let X=Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(X,"parsed",{get(){return Q.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return J}),parsed_output:null};return l5($,Z,Q)}function l5($,Z,Q){let Y=null,J=$.content.map((X)=>{if(X.type==="text"){let K=cX(Z,X.text);if(Y===null)Y=K;let V=Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1});return Object.defineProperty(V,"parsed",{get(){return Q.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),K},enumerable:!1})}return X});return{...$,content:J,parsed_output:Y}}function cX($,Z){let Q=d2($);if(Q?.type!=="json_schema")return null;try{if("parse"in Q)return Q.parse(Z);return JSON.parse(Z)}catch(Y){throw new T(`Failed to parse structured output: ${Y}`)}}var uX=($)=>{let Z=0,Q=[];while(Z<$.length){let Y=$[Z];if(Y==="\\"){Z++;continue}if(Y==="{"){Q.push({type:"brace",value:"{"}),Z++;continue}if(Y==="}"){Q.push({type:"brace",value:"}"}),Z++;continue}if(Y==="["){Q.push({type:"paren",value:"["}),Z++;continue}if(Y==="]"){Q.push({type:"paren",value:"]"}),Z++;continue}if(Y===":"){Q.push({type:"separator",value:":"}),Z++;continue}if(Y===","){Q.push({type:"delimiter",value:","}),Z++;continue}if(Y==='"'){let V="",G=!1;Y=$[++Z];while(Y!=='"'){if(Z===$.length){G=!0;break}if(Y==="\\"){if(Z++,Z===$.length){G=!0;break}V+=Y+$[Z],Y=$[++Z]}else V+=Y,Y=$[++Z]}if(Y=$[++Z],!G)Q.push({type:"string",value:V});continue}if(Y&&/\s/.test(Y)){Z++;continue}let X=/[0-9]/;if(Y&&X.test(Y)||Y==="-"||Y==="."){let V="";if(Y==="-")V+=Y,Y=$[++Z];while(Y&&X.test(Y)||Y===".")V+=Y,Y=$[++Z];Q.push({type:"number",value:V});continue}let K=/[a-z]/i;if(Y&&K.test(Y)){let V="";while(Y&&K.test(Y)){if(Z===$.length)break;V+=Y,Y=$[++Z]}if(V=="true"||V=="false"||V==="null")Q.push({type:"name",value:V});else{Z++;continue}continue}Z++}return Q},K8=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),K8($);break;case"number":let Q=Z.value[Z.value.length-1];if(Q==="."||Q==="-")return $=$.slice(0,$.length-1),K8($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),K8($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),K8($);break;case"delimiter":return $=$.slice(0,$.length-1),K8($);break}return $},dX=($)=>{let Z=[];if($.map((Q)=>{if(Q.type==="brace")if(Q.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(Q.type==="paren")if(Q.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((Q)=>{if(Q==="}")$.push({type:"brace",value:"}"});else if(Q==="]")$.push({type:"paren",value:"]"})});return $},lX=($)=>{let Z="";return $.map((Q)=>{switch(Q.type){case"string":Z+='"'+Q.value+'"';break;default:Z+=Q.value;break}}),Z},w0=($)=>JSON.parse(lX(dX(K8(uX($)))));var T$,M4,z8,X1,k0,K1,z1,y0,V1,i$,G1,b0,_0,v4,v0,f0,H1,o5,l2,h0,a5,n5,r5,o2,a2="__json_buf";function n2($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class q1{constructor($,Z){T$.add(this),this.messages=[],this.receivedMessages=[],M4.set(this,void 0),z8.set(this,null),this.controller=new AbortController,X1.set(this,void 0),k0.set(this,()=>{}),K1.set(this,()=>{}),z1.set(this,void 0),y0.set(this,()=>{}),V1.set(this,()=>{}),i$.set(this,{}),G1.set(this,!1),b0.set(this,!1),_0.set(this,!1),v4.set(this,!1),v0.set(this,void 0),f0.set(this,void 0),H1.set(this,void 0),h0.set(this,(Q)=>{if(D(this,b0,!0,"f"),n$(Q))Q=new z$;if(Q instanceof z$)return D(this,_0,!0,"f"),this._emit("abort",Q);if(Q instanceof T)return this._emit("error",Q);if(Q instanceof Error){let Y=new T(Q.message);return Y.cause=Q,this._emit("error",Y)}return this._emit("error",new T(String(Q)))}),D(this,X1,new Promise((Q,Y)=>{D(this,k0,Q,"f"),D(this,K1,Y,"f")}),"f"),D(this,z1,new Promise((Q,Y)=>{D(this,y0,Q,"f"),D(this,V1,Y,"f")}),"f"),M(this,X1,"f").catch(()=>{}),M(this,z1,"f").catch(()=>{}),D(this,z8,$,"f"),D(this,H1,Z?.logger??console,"f")}get response(){return M(this,v0,"f")}get request_id(){return M(this,f0,"f")}async withResponse(){D(this,v4,!0,"f");let $=await M(this,X1,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new q1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Q,{logger:Y}={}){let J=new q1(Z,{logger:Y});for(let X of Z.messages)J._addMessageParam(X);return D(J,z8,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Q,headers:{...Q?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},M(this,h0,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Q){let Y=Q?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{M(this,T$,"m",a5).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...Q,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)M(this,T$,"m",n5).call(this,V);if(K.controller.signal?.aborted)throw new z$;M(this,T$,"m",r5).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}_connected($){if(this.ended)return;D(this,v0,$,"f"),D(this,f0,$?.headers.get("request-id"),"f"),M(this,k0,"f").call(this,$),this._emit("connect")}get ended(){return M(this,G1,"f")}get errored(){return M(this,b0,"f")}get aborted(){return M(this,_0,"f")}abort(){this.controller.abort()}on($,Z){return(M(this,i$,"f")[$]||(M(this,i$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Q=M(this,i$,"f")[$];if(!Q)return this;let Y=Q.findIndex((J)=>J.listener===Z);if(Y>=0)Q.splice(Y,1);return this}once($,Z){return(M(this,i$,"f")[$]||(M(this,i$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Q)=>{if(D(this,v4,!0,"f"),$!=="error")this.once("error",Q);this.once($,Z)})}async done(){D(this,v4,!0,"f"),await M(this,z1,"f")}get currentMessage(){return M(this,M4,"f")}async finalMessage(){return await this.done(),M(this,T$,"m",o5).call(this)}async finalText(){return await this.done(),M(this,T$,"m",l2).call(this)}_emit($,...Z){if(M(this,G1,"f"))return;if($==="end")D(this,G1,!0,"f"),M(this,y0,"f").call(this);let Q=M(this,i$,"f")[$];if(Q)M(this,i$,"f")[$]=Q.filter((Y)=>!Y.once),Q.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!M(this,v4,"f")&&!Q?.length)Promise.reject(Y);M(this,K1,"f").call(this,Y),M(this,V1,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!M(this,v4,"f")&&!Q?.length)Promise.reject(Y);M(this,K1,"f").call(this,Y),M(this,V1,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",M(this,T$,"m",o5).call(this))}async _fromReadableStream($,Z){let Q=Z?.signal,Y;if(Q){if(Q.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Q.addEventListener("abort",Y)}try{M(this,T$,"m",a5).call(this),this._connected(null);let J=R$.fromReadableStream($,this.controller);for await(let X of J)M(this,T$,"m",n5).call(this,X);if(J.controller.signal?.aborted)throw new z$;M(this,T$,"m",r5).call(this)}finally{if(Q&&Y)Q.removeEventListener("abort",Y)}}[(M4=new WeakMap,z8=new WeakMap,X1=new WeakMap,k0=new WeakMap,K1=new WeakMap,z1=new WeakMap,y0=new WeakMap,V1=new WeakMap,i$=new WeakMap,G1=new WeakMap,b0=new WeakMap,_0=new WeakMap,v4=new WeakMap,v0=new WeakMap,f0=new WeakMap,H1=new WeakMap,h0=new WeakMap,T$=new WeakSet,o5=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},l2=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Q)=>Q.type==="text").map((Q)=>Q.text);if(Z.length===0)throw new T("stream ended without producing a content block with type=text");return Z.join(" ")},a5=function(){if(this.ended)return;D(this,M4,void 0,"f")},n5=function(Z){if(this.ended)return;let Q=M(this,T$,"m",o2).call(this,Z);switch(this._emit("streamEvent",Z,Q),Z.type){case"content_block_delta":{let Y=Q.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(n2(Y)&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}case"compaction_delta":{if(Y.type==="compaction"&&Y.content)this._emit("compaction",Y.content);break}default:r2(Z.delta)}break}case"message_stop":{this._addMessageParam(Q),this._addMessage(d5(Q,M(this,z8,"f"),{logger:M(this,H1,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Q.content.at(-1));break}case"message_start":{D(this,M4,Q,"f");break}case"content_block_start":case"message_delta":break}},r5=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let Z=M(this,M4,"f");if(!Z)throw new T("request ended without sending any chunks");return D(this,M4,void 0,"f"),d5(Z,M(this,z8,"f"),{logger:M(this,H1,"f")})},o2=function(Z){let Q=M(this,M4,"f");if(Z.type==="message_start"){if(Q)throw new T(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Q)throw new T(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Q;case"message_delta":if(Q.container=Z.delta.container,Q.stop_reason=Z.delta.stop_reason,Q.stop_sequence=Z.delta.stop_sequence,Q.usage.output_tokens=Z.usage.output_tokens,Q.context_management=Z.context_management,Z.usage.input_tokens!=null)Q.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Q.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Q.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Q.usage.server_tool_use=Z.usage.server_tool_use;if(Z.usage.iterations!=null)Q.usage.iterations=Z.usage.iterations;return Q;case"content_block_start":return Q.content.push(Z.content_block),Q;case"content_block_delta":{let Y=Q.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&n2(Y)){let J=Y[a2]||"";J+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,a2,{value:J,enumerable:!1,writable:!0}),J)try{X.input=w0(J)}catch(K){let V=new T(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${K}. JSON: ${J}`);M(this,h0,"f").call(this,V)}Q.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,signature:Z.delta.signature};break}case"compaction_delta":{if(Y?.type==="compaction")Q.content[Z.index]={...Y,content:(Y.content||"")+Z.delta.content};break}default:r2(Z.delta)}return Q}case"content_block_stop":return Q}},Symbol.asyncIterator)](){let $=[],Z=[],Q=!1;return this.on("streamEvent",(Y)=>{let J=Z.shift();if(J)J.resolve(Y);else $.push(Y)}),this.on("end",()=>{Q=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),this.on("error",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(Q)return{value:void 0,done:!0};return new Promise((J,X)=>Z.push({resolve:J,reject:X})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new R$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function r2($){}class V8 extends Error{constructor($){let Z=typeof $==="string"?$:$.map((Q)=>{if(Q.type==="text")return Q.text;return`[${Q.type}]`}).join(" ");super(Z);this.name="ToolError",this.content=$}}var i2=1e5,s2=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
|
|
59
|
+
${U}`)}return K},v=_K(R6);class e1 extends h{list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/files",P$,{query:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(v`/v1/files/${$}`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(v`/v1/files/${$}/content`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(v`/v1/files/${$}`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/files",Z1({body:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},O6(Q.file),Z?.headers])},this._client))}}class $8 extends h{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(v`/v1/models/${$}?beta=true`,{...Y,headers:T([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models?beta=true",P$,{query:Q,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var k4={"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 E6($){return $?.output_format??$?.output_config?.format}function W2($,Z,Y){let Q=E6(Z);if(!Z||!("parse"in(Q??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text"){let z=Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(z,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return J}),parsed_output:null};return B2($,Z,Y)}function B2($,Z,Y){let Q=null,J=$.content.map((z)=>{if(z.type==="text"){let K=vK(Z,z.text);if(Q===null)Q=K;let X=Object.defineProperty({...z},"parsed_output",{value:K,enumerable:!1});return Object.defineProperty(X,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),K},enumerable:!1})}return z});return{...$,content:J,parsed_output:Q}}function vK($,Z){let Y=E6($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new E(`Failed to parse structured output: ${Q}`)}}var hK=($)=>{let Z=0,Y=[];while(Z<$.length){let Q=$[Z];if(Q==="\\"){Z++;continue}if(Q==="{"){Y.push({type:"brace",value:"{"}),Z++;continue}if(Q==="}"){Y.push({type:"brace",value:"}"}),Z++;continue}if(Q==="["){Y.push({type:"paren",value:"["}),Z++;continue}if(Q==="]"){Y.push({type:"paren",value:"]"}),Z++;continue}if(Q===":"){Y.push({type:"separator",value:":"}),Z++;continue}if(Q===","){Y.push({type:"delimiter",value:","}),Z++;continue}if(Q==='"'){let X="",V=!1;Q=$[++Z];while(Q!=='"'){if(Z===$.length){V=!0;break}if(Q==="\\"){if(Z++,Z===$.length){V=!0;break}X+=Q+$[Z],Q=$[++Z]}else X+=Q,Q=$[++Z]}if(Q=$[++Z],!V)Y.push({type:"string",value:X});continue}if(Q&&/\s/.test(Q)){Z++;continue}let z=/[0-9]/;if(Q&&z.test(Q)||Q==="-"||Q==="."){let X="";if(Q==="-")X+=Q,Q=$[++Z];while(Q&&z.test(Q)||Q===".")X+=Q,Q=$[++Z];Y.push({type:"number",value:X});continue}let K=/[a-z]/i;if(Q&&K.test(Q)){let X="";while(Q&&K.test(Q)){if(Z===$.length)break;X+=Q,Q=$[++Z]}if(X=="true"||X=="false"||X==="null")Y.push({type:"name",value:X});else{Z++;continue}continue}Z++}return Y},Y1=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),Y1($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),Y1($);case"string":let Q=$[$.length-2];if(Q?.type==="delimiter")return $=$.slice(0,$.length-1),Y1($);else if(Q?.type==="brace"&&Q.value==="{")return $=$.slice(0,$.length-1),Y1($);break;case"delimiter":return $=$.slice(0,$.length-1),Y1($);break}return $},gK=($)=>{let Z=[];if($.map((Y)=>{if(Y.type==="brace")if(Y.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(Y.type==="paren")if(Y.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((Y)=>{if(Y==="}")$.push({type:"brace",value:"}"});else if(Y==="]")$.push({type:"paren",value:"]"})});return $},mK=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},y4=($)=>JSON.parse(mK(gK(Y1(hK($)))));var R$,U0,Q1,Z8,b4,Y8,Q8,_4,J8,p$,z8,x4,f4,y0,v4,h4,K8,M2,L6,g4,C2,N2,O2,j6,D6="__json_buf";function P6($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class X8{constructor($,Z){R$.add(this),this.messages=[],this.receivedMessages=[],U0.set(this,void 0),Q1.set(this,null),this.controller=new AbortController,Z8.set(this,void 0),b4.set(this,()=>{}),Y8.set(this,()=>{}),Q8.set(this,void 0),_4.set(this,()=>{}),J8.set(this,()=>{}),p$.set(this,{}),z8.set(this,!1),x4.set(this,!1),f4.set(this,!1),y0.set(this,!1),v4.set(this,void 0),h4.set(this,void 0),K8.set(this,void 0),g4.set(this,(Y)=>{if(F(this,x4,!0,"f"),m$(Y))Y=new e;if(Y instanceof e)return F(this,f4,!0,"f"),this._emit("abort",Y);if(Y instanceof E)return this._emit("error",Y);if(Y instanceof Error){let Q=new E(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new E(String(Y)))}),F(this,Z8,new Promise((Y,Q)=>{F(this,b4,Y,"f"),F(this,Y8,Q,"f")}),"f"),F(this,Q8,new Promise((Y,Q)=>{F(this,_4,Y,"f"),F(this,J8,Q,"f")}),"f"),C(this,Z8,"f").catch(()=>{}),C(this,Q8,"f").catch(()=>{}),F(this,Q1,$,"f"),F(this,K8,Z?.logger??console,"f")}get response(){return C(this,v4,"f")}get request_id(){return C(this,h4,"f")}async withResponse(){F(this,y0,!0,"f");let $=await C(this,Z8,"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 X8(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let J=new X8(Z,{logger:Q});for(let z of Z.messages)J._addMessageParam(z);return F(J,Q1,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},C(this,g4,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let Q=Y?.signal,J;if(Q){if(Q.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Q.addEventListener("abort",J)}try{C(this,R$,"m",C2).call(this);let{response:z,data:K}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let X of K)C(this,R$,"m",N2).call(this,X);if(K.controller.signal?.aborted)throw new e;C(this,R$,"m",O2).call(this)}finally{if(Q&&J)Q.removeEventListener("abort",J)}}_connected($){if(this.ended)return;F(this,v4,$,"f"),F(this,h4,$?.headers.get("request-id"),"f"),C(this,b4,"f").call(this,$),this._emit("connect")}get ended(){return C(this,z8,"f")}get errored(){return C(this,x4,"f")}get aborted(){return C(this,f4,"f")}abort(){this.controller.abort()}on($,Z){return(C(this,p$,"f")[$]||(C(this,p$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=C(this,p$,"f")[$];if(!Y)return this;let Q=Y.findIndex((J)=>J.listener===Z);if(Q>=0)Y.splice(Q,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,Y)=>{if(F(this,y0,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){F(this,y0,!0,"f"),await C(this,Q8,"f")}get currentMessage(){return C(this,U0,"f")}async finalMessage(){return await this.done(),C(this,R$,"m",M2).call(this)}async finalText(){return await this.done(),C(this,R$,"m",L6).call(this)}_emit($,...Z){if(C(this,z8,"f"))return;if($==="end")F(this,z8,!0,"f"),C(this,_4,"f").call(this);let Y=C(this,p$,"f")[$];if(Y)C(this,p$,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!C(this,y0,"f")&&!Y?.length)Promise.reject(Q);C(this,Y8,"f").call(this,Q),C(this,J8,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!C(this,y0,"f")&&!Y?.length)Promise.reject(Q);C(this,Y8,"f").call(this,Q),C(this,J8,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,R$,"m",M2).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{C(this,R$,"m",C2).call(this),this._connected(null);let J=B$.fromReadableStream($,this.controller);for await(let z of J)C(this,R$,"m",N2).call(this,z);if(J.controller.signal?.aborted)throw new e;C(this,R$,"m",O2).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(U0=new WeakMap,Q1=new WeakMap,Z8=new WeakMap,b4=new WeakMap,Y8=new WeakMap,Q8=new WeakMap,_4=new WeakMap,J8=new WeakMap,p$=new WeakMap,z8=new WeakMap,x4=new WeakMap,f4=new WeakMap,y0=new WeakMap,v4=new WeakMap,h4=new WeakMap,K8=new WeakMap,g4=new WeakMap,R$=new WeakSet,M2=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},L6=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Y)=>Y.type==="text").map((Y)=>Y.text);if(Z.length===0)throw new E("stream ended without producing a content block with type=text");return Z.join(" ")},C2=function(){if(this.ended)return;F(this,U0,void 0,"f")},N2=function(Z){if(this.ended)return;let Y=C(this,R$,"m",j6).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let Q=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Z.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Z.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(P6(Q)&&Q.input)this._emit("inputJson",Z.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Z.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}case"compaction_delta":{if(Q.type==="compaction"&&Q.content)this._emit("compaction",Q.content);break}default:T6(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(W2(Y,C(this,Q1,"f"),{logger:C(this,K8,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{F(this,U0,Y,"f");break}case"content_block_start":case"message_delta":break}},O2=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let Z=C(this,U0,"f");if(!Z)throw new E("request ended without sending any chunks");return F(this,U0,void 0,"f"),W2(Z,C(this,Q1,"f"),{logger:C(this,K8,"f")})},j6=function(Z){let Y=C(this,U0,"f");if(Z.type==="message_start"){if(Y)throw new E(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new E(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Y;case"message_delta":if(Y.container=Z.delta.container,Y.stop_reason=Z.delta.stop_reason,Y.stop_sequence=Z.delta.stop_sequence,Y.usage.output_tokens=Z.usage.output_tokens,Y.context_management=Z.context_management,Z.usage.input_tokens!=null)Y.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Y.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Y.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Y.usage.server_tool_use=Z.usage.server_tool_use;if(Z.usage.iterations!=null)Y.usage.iterations=Z.usage.iterations;return Y;case"content_block_start":return Y.content.push(Z.content_block),Y;case"content_block_delta":{let Q=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,text:(Q.text||"")+Z.delta.text};break}case"citations_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,citations:[...Q.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Q&&P6(Q)){let J=Q[D6]||"";J+=Z.delta.partial_json;let z={...Q};if(Object.defineProperty(z,D6,{value:J,enumerable:!1,writable:!0}),J)try{z.input=y4(J)}catch(K){let X=new E(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${K}. JSON: ${J}`);C(this,g4,"f").call(this,X)}Y.content[Z.index]=z}break}case"thinking_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,thinking:Q.thinking+Z.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,signature:Z.delta.signature};break}case"compaction_delta":{if(Q?.type==="compaction")Y.content[Z.index]={...Q,content:(Q.content||"")+Z.delta.content};break}default:T6(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(Q)=>{let J=Z.shift();if(J)J.resolve(Q);else $.push(Q)}),this.on("end",()=>{Y=!0;for(let Q of Z)Q.resolve(void 0);Z.length=0}),this.on("abort",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),this.on("error",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((J,z)=>Z.push({resolve:J,reject:z})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new B$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function T6($){}class J1 extends Error{constructor($){let Z=typeof $==="string"?$:$.map((Y)=>{if(Y.type==="text")return Y.text;return`[${Y.type}]`}).join(" ");super(Z);this.name="ToolError",this.content=$}}var A6=1e5,I6=`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
60
|
1. Task Overview
|
|
60
61
|
The user's core request and success criteria
|
|
61
62
|
Any clarifications or constraints they specified
|
|
@@ -77,48 +78,44 @@ User preferences or style requirements
|
|
|
77
78
|
Domain-specific details that aren't obvious
|
|
78
79
|
Any promises made to the user
|
|
79
80
|
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(J.model in nX&&J.thinking&&J.thinking.type==="enabled")console.warn(`Using Claude with ${J.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let X=this._client._options.timeout;if(!J.stream&&X==null){let V=S0[J.model]??void 0;X=this._client.calculateNonstreamingTimeout(J.max_tokens,V)}let K=x0(J.tools,J.messages);return this._client.post("/v1/messages?beta=true",{body:J,timeout:X??600000,...Z,headers:k([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},K,Z?.headers]),stream:Q.stream??!1})}parse($,Z){return Z={...Z,headers:k([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Q)=>l5(Q,$,{logger:this._client.logger??console}))}stream($,Z){return q1.createMessage(this,$,Z)}countTokens($,Z){let Q=Z6($),{betas:Y,...J}=Q;return this._client.post("/v1/messages/count_tokens?beta=true",{body:J,...Z,headers:k([{"anthropic-beta":[...Y??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new C1(this._client,$,Z)}}function Z6($){if(!$.output_format)return $;if($.output_config?.format)throw new T("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Z,...Q}=$;return{...Q,output_config:{...$.output_config,format:Z}}}O4.Batches=N1;O4.BetaToolRunner=C1;O4.ToolError=V8;class M1 extends l{create($,Z={},Q){let{betas:Y,...J}=Z??{};return this._client.post(d`/v1/skills/${$}/versions?beta=true`,X8({body:J,...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])},this._client))}retrieve($,Z,Q){let{skill_id:Y,betas:J}=Z;return this._client.get(d`/v1/skills/${Y}/versions/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Q?.headers])})}list($,Z={},Q){let{betas:Y,...J}=Z??{};return this._client.getAPIList(d`/v1/skills/${$}/versions?beta=true`,$1,{query:J,...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])})}delete($,Z,Q){let{skill_id:Y,betas:J}=Z;return this._client.delete(d`/v1/skills/${Y}/versions/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Q?.headers])})}}class q8 extends l{constructor(){super(...arguments);this.versions=new M1(this._client)}create($={},Z){let{betas:Q,...Y}=$??{};return this._client.post("/v1/skills?beta=true",X8({body:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Q){let{betas:Y}=Z??{};return this._client.get(d`/v1/skills/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])})}list($={},Z){let{betas:Q,...Y}=$??{};return this._client.getAPIList("/v1/skills?beta=true",$1,{query:Y,...Z,headers:k([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Q){let{betas:Y}=Z??{};return this._client.delete(d`/v1/skills/${$}?beta=true`,{...Q,headers:k([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Q?.headers])})}}q8.Versions=M1;class v$ extends l{constructor(){super(...arguments);this.models=new J1(this._client),this.messages=new O4(this._client),this.files=new Y1(this._client),this.skills=new q8(this._client)}}v$.Models=J1;v$.Messages=O4;v$.Files=Y1;v$.Skills=q8;class U8 extends l{create($,Z){let{betas:Q,...Y}=$;return this._client.post("/v1/complete",{body:Y,timeout:this._client._options.timeout??600000,...Z,headers:k([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function Q6($){return $?.output_config?.format}function s5($,Z,Q){let Y=Q6(Z);if(!Z||!("parse"in(Y??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text")return Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return J}),parsed_output:null};return t5($,Z,Q)}function t5($,Z,Q){let Y=null,J=$.content.map((X)=>{if(X.type==="text"){let K=tX(Z,X.text);if(Y===null)Y=K;return Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1})}return X});return{...$,content:J,parsed_output:Y}}function tX($,Z){let Q=Q6($);if(Q?.type!=="json_schema")return null;try{if("parse"in Q)return Q.parse(Z);return JSON.parse(Z)}catch(Y){throw new T(`Failed to parse structured output: ${Y}`)}}var A$,R4,W8,F1,g0,O1,R1,m0,E1,t$,L1,p0,c0,h4,u0,d0,j1,e5,Y6,$9,Z9,Q9,Y9,J6,X6="__json_buf";function K6($){return $.type==="tool_use"||$.type==="server_tool_use"}class D1{constructor($,Z){A$.add(this),this.messages=[],this.receivedMessages=[],R4.set(this,void 0),W8.set(this,null),this.controller=new AbortController,F1.set(this,void 0),g0.set(this,()=>{}),O1.set(this,()=>{}),R1.set(this,void 0),m0.set(this,()=>{}),E1.set(this,()=>{}),t$.set(this,{}),L1.set(this,!1),p0.set(this,!1),c0.set(this,!1),h4.set(this,!1),u0.set(this,void 0),d0.set(this,void 0),j1.set(this,void 0),$9.set(this,(Q)=>{if(D(this,p0,!0,"f"),n$(Q))Q=new z$;if(Q instanceof z$)return D(this,c0,!0,"f"),this._emit("abort",Q);if(Q instanceof T)return this._emit("error",Q);if(Q instanceof Error){let Y=new T(Q.message);return Y.cause=Q,this._emit("error",Y)}return this._emit("error",new T(String(Q)))}),D(this,F1,new Promise((Q,Y)=>{D(this,g0,Q,"f"),D(this,O1,Y,"f")}),"f"),D(this,R1,new Promise((Q,Y)=>{D(this,m0,Q,"f"),D(this,E1,Y,"f")}),"f"),M(this,F1,"f").catch(()=>{}),M(this,R1,"f").catch(()=>{}),D(this,W8,$,"f"),D(this,j1,Z?.logger??console,"f")}get response(){return M(this,u0,"f")}get request_id(){return M(this,d0,"f")}async withResponse(){D(this,h4,!0,"f");let $=await M(this,F1,"f");if(!$)throw Error("Could not resolve a `Response` object");return{data:this,response:$,request_id:$.headers.get("request-id")}}static fromReadableStream($){let Z=new D1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Q,{logger:Y}={}){let J=new D1(Z,{logger:Y});for(let X of Z.messages)J._addMessageParam(X);return D(J,W8,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Q,headers:{...Q?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},M(this,$9,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Q){let Y=Q?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{M(this,A$,"m",Z9).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...Q,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)M(this,A$,"m",Q9).call(this,V);if(K.controller.signal?.aborted)throw new z$;M(this,A$,"m",Y9).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}_connected($){if(this.ended)return;D(this,u0,$,"f"),D(this,d0,$?.headers.get("request-id"),"f"),M(this,g0,"f").call(this,$),this._emit("connect")}get ended(){return M(this,L1,"f")}get errored(){return M(this,p0,"f")}get aborted(){return M(this,c0,"f")}abort(){this.controller.abort()}on($,Z){return(M(this,t$,"f")[$]||(M(this,t$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Q=M(this,t$,"f")[$];if(!Q)return this;let Y=Q.findIndex((J)=>J.listener===Z);if(Y>=0)Q.splice(Y,1);return this}once($,Z){return(M(this,t$,"f")[$]||(M(this,t$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Q)=>{if(D(this,h4,!0,"f"),$!=="error")this.once("error",Q);this.once($,Z)})}async done(){D(this,h4,!0,"f"),await M(this,R1,"f")}get currentMessage(){return M(this,R4,"f")}async finalMessage(){return await this.done(),M(this,A$,"m",e5).call(this)}async finalText(){return await this.done(),M(this,A$,"m",Y6).call(this)}_emit($,...Z){if(M(this,L1,"f"))return;if($==="end")D(this,L1,!0,"f"),M(this,m0,"f").call(this);let Q=M(this,t$,"f")[$];if(Q)M(this,t$,"f")[$]=Q.filter((Y)=>!Y.once),Q.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!M(this,h4,"f")&&!Q?.length)Promise.reject(Y);M(this,O1,"f").call(this,Y),M(this,E1,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!M(this,h4,"f")&&!Q?.length)Promise.reject(Y);M(this,O1,"f").call(this,Y),M(this,E1,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",M(this,A$,"m",e5).call(this))}async _fromReadableStream($,Z){let Q=Z?.signal,Y;if(Q){if(Q.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),Q.addEventListener("abort",Y)}try{M(this,A$,"m",Z9).call(this),this._connected(null);let J=R$.fromReadableStream($,this.controller);for await(let X of J)M(this,A$,"m",Q9).call(this,X);if(J.controller.signal?.aborted)throw new z$;M(this,A$,"m",Y9).call(this)}finally{if(Q&&Y)Q.removeEventListener("abort",Y)}}[(R4=new WeakMap,W8=new WeakMap,F1=new WeakMap,g0=new WeakMap,O1=new WeakMap,R1=new WeakMap,m0=new WeakMap,E1=new WeakMap,t$=new WeakMap,L1=new WeakMap,p0=new WeakMap,c0=new WeakMap,h4=new WeakMap,u0=new WeakMap,d0=new WeakMap,j1=new WeakMap,$9=new WeakMap,A$=new WeakSet,e5=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Y6=function(){if(this.receivedMessages.length===0)throw new T("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Q)=>Q.type==="text").map((Q)=>Q.text);if(Z.length===0)throw new T("stream ended without producing a content block with type=text");return Z.join(" ")},Z9=function(){if(this.ended)return;D(this,R4,void 0,"f")},Q9=function(Z){if(this.ended)return;let Q=M(this,A$,"m",J6).call(this,Z);switch(this._emit("streamEvent",Z,Q),Z.type){case"content_block_delta":{let Y=Q.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(K6(Y)&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:z6(Z.delta)}break}case"message_stop":{this._addMessageParam(Q),this._addMessage(s5(Q,M(this,W8,"f"),{logger:M(this,j1,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Q.content.at(-1));break}case"message_start":{D(this,R4,Q,"f");break}case"content_block_start":case"message_delta":break}},Y9=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let Z=M(this,R4,"f");if(!Z)throw new T("request ended without sending any chunks");return D(this,R4,void 0,"f"),s5(Z,M(this,W8,"f"),{logger:M(this,j1,"f")})},J6=function(Z){let Q=M(this,R4,"f");if(Z.type==="message_start"){if(Q)throw new T(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Q)throw new T(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Q;case"message_delta":if(Q.stop_reason=Z.delta.stop_reason,Q.stop_sequence=Z.delta.stop_sequence,Q.usage.output_tokens=Z.usage.output_tokens,Z.usage.input_tokens!=null)Q.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Q.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Q.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Q.usage.server_tool_use=Z.usage.server_tool_use;return Q;case"content_block_start":return Q.content.push({...Z.content_block}),Q;case"content_block_delta":{let Y=Q.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")Q.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&K6(Y)){let J=Y[X6]||"";J+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,X6,{value:J,enumerable:!1,writable:!0}),J)X.input=w0(J);Q.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")Q.content[Z.index]={...Y,signature:Z.delta.signature};break}default:z6(Z.delta)}return Q}case"content_block_stop":return Q}},Symbol.asyncIterator)](){let $=[],Z=[],Q=!1;return this.on("streamEvent",(Y)=>{let J=Z.shift();if(J)J.resolve(Y);else $.push(Y)}),this.on("end",()=>{Q=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),this.on("error",(Y)=>{Q=!0;for(let J of Z)J.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(Q)return{value:void 0,done:!0};return new Promise((J,X)=>Z.push({resolve:J,reject:X})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new R$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function z6($){}class P1 extends l{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(d`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",y$,{query:$,...Z})}delete($,Z){return this._client.delete(d`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(d`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Q=await this.retrieve($);if(!Q.results_url)throw new T(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);return this._client.get(Q.results_url,{...Z,headers:k([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,J)=>H8.fromResponse(J.response,J.controller))}}class g4 extends l{constructor(){super(...arguments);this.batches=new P1(this._client)}create($,Z){if($.model in V6)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${V6[$.model]}
|
|
82
|
-
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in
|
|
81
|
+
Wrap your summary in <summary></summary> tags.`;var V8,z1,b0,c,G8,M$,d$,H0,q8,S6,F2;function w6(){let $,Z;return{promise:new Promise((Q,J)=>{$=Q,Z=J}),resolve:$,reject:Z}}class U8{constructor($,Z,Y){V8.add(this),this.client=$,z1.set(this,!1),b0.set(this,!1),c.set(this,void 0),G8.set(this,void 0),M$.set(this,void 0),d$.set(this,void 0),H0.set(this,void 0),q8.set(this,0),F(this,c,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let J=["BetaToolRunner",...H2(Z.tools,Z.messages)].join(", ");F(this,G8,{...Y,headers:T([{"x-stainless-helper":J},Y?.headers])},"f"),F(this,H0,w6(),"f")}async*[(z1=new WeakMap,b0=new WeakMap,c=new WeakMap,G8=new WeakMap,M$=new WeakMap,d$=new WeakMap,H0=new WeakMap,q8=new WeakMap,V8=new WeakSet,S6=async function(){let Z=C(this,c,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(C(this,M$,"f")!==void 0)try{let V=await C(this,M$,"f");Y=V.usage.input_tokens+(V.usage.cache_creation_input_tokens??0)+(V.usage.cache_read_input_tokens??0)+V.usage.output_tokens}catch{return!1}let Q=Z.contextTokenThreshold??A6;if(Y<Q)return!1;let J=Z.model??C(this,c,"f").params.model,z=Z.summaryPrompt??I6,K=C(this,c,"f").params.messages;if(K[K.length-1].role==="assistant"){let V=K[K.length-1];if(Array.isArray(V.content)){let G=V.content.filter((q)=>q.type!=="tool_use");if(G.length===0)K.pop();else V.content=G}}let X=await this.client.beta.messages.create({model:J,messages:[...K,{role:"user",content:[{type:"text",text:z}]}],max_tokens:C(this,c,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(X.content[0]?.type!=="text")throw new E("Expected text response for compaction");return C(this,c,"f").params.messages=[{role:"user",content:X.content}],!0},Symbol.asyncIterator)](){var $;if(C(this,z1,"f"))throw new E("Cannot iterate over a consumed stream");F(this,z1,!0,"f"),F(this,b0,!0,"f"),F(this,d$,void 0,"f");try{while(!0){let Z;try{if(C(this,c,"f").params.max_iterations&&C(this,q8,"f")>=C(this,c,"f").params.max_iterations)break;F(this,b0,!1,"f"),F(this,d$,void 0,"f"),F(this,q8,($=C(this,q8,"f"),$++,$),"f"),F(this,M$,void 0,"f");let{max_iterations:Y,compactionControl:Q,...J}=C(this,c,"f").params;if(J.stream)Z=this.client.beta.messages.stream({...J},C(this,G8,"f")),F(this,M$,Z.finalMessage(),"f"),C(this,M$,"f").catch(()=>{}),yield Z;else F(this,M$,this.client.beta.messages.create({...J,stream:!1},C(this,G8,"f")),"f"),yield C(this,M$,"f");if(!await C(this,V8,"m",S6).call(this)){if(!C(this,b0,"f")){let{role:X,content:V}=await C(this,M$,"f");C(this,c,"f").params.messages.push({role:X,content:V})}let K=await C(this,V8,"m",F2).call(this,C(this,c,"f").params.messages.at(-1));if(K)C(this,c,"f").params.messages.push(K);else if(!C(this,b0,"f"))break}}finally{if(Z)Z.abort()}}if(!C(this,M$,"f"))throw new E("ToolRunner concluded without a message from the server");C(this,H0,"f").resolve(await C(this,M$,"f"))}catch(Z){throw F(this,z1,!1,"f"),C(this,H0,"f").promise.catch(()=>{}),C(this,H0,"f").reject(Z),F(this,H0,w6(),"f"),Z}}setMessagesParams($){if(typeof $==="function")C(this,c,"f").params=$(C(this,c,"f").params);else C(this,c,"f").params=$;F(this,b0,!0,"f"),F(this,d$,void 0,"f")}async generateToolResponse(){let $=await C(this,M$,"f")??this.params.messages.at(-1);if(!$)return null;return C(this,V8,"m",F2).call(this,$)}done(){return C(this,H0,"f").promise}async runUntilDone(){if(!C(this,z1,"f"))for await(let $ of this);return this.done()}get params(){return C(this,c,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}F2=async function(Z){if(C(this,d$,"f")!==void 0)return C(this,d$,"f");return F(this,d$,uK(C(this,c,"f").params,Z),"f"),C(this,d$,"f")};async function uK($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let Y=Z.content.filter((J)=>J.type==="tool_use");if(Y.length===0)return null;return{role:"user",content:await Promise.all(Y.map(async(J)=>{let z=$.tools.find((K)=>("name"in K?K.name:K.mcp_server_name)===J.name);if(!z||!("run"in z))return{type:"tool_result",tool_use_id:J.id,content:`Error: Tool '${J.name}' not found`,is_error:!0};try{let K=J.input;if("parse"in z&&z.parse)K=z.parse(K);let X=await z.run(K);return{type:"tool_result",tool_use_id:J.id,content:X}}catch(K){return{type:"tool_result",tool_use_id:J.id,content:K instanceof J1?K.content:`Error: ${K instanceof Error?K.message:String(K)}`,is_error:!0}}}))}}class K1{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new q0;for await(let Z of this.iterator)for(let Y of $.decode(Z))yield JSON.parse(Y);for(let Z of $.flush())yield JSON.parse(Z)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new E("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 E("Attempted to iterate over a response with no body")}return new K1(l1($.body),Z)}}class H8 extends h{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(v`/v1/messages/batches/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",P$,{query:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(v`/v1/messages/batches/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:Q}=Z??{};return this._client.post(v`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}async results($,Z={},Y){let Q=await this.retrieve($);if(!Q.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);let{betas:J}=Z??{};return this._client.get(Q.results_url,{...Y,headers:T([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((z,K)=>K1.fromResponse(K.response,K.controller))}}var k6={"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"},dK=["claude-opus-4-6"];class W0 extends h{constructor(){super(...arguments);this.batches=new H8(this._client)}create($,Z){let Y=y6($),{betas:Q,...J}=Y;if(J.model in k6)console.warn(`The model '${J.model}' is deprecated and will reach end-of-life on ${k6[J.model]}
|
|
82
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(J.model in dK&&J.thinking&&J.thinking.type==="enabled")console.warn(`Using Claude with ${J.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let z=this._client._options.timeout;if(!J.stream&&z==null){let X=k4[J.model]??void 0;z=this._client.calculateNonstreamingTimeout(J.max_tokens,X)}let K=w4(J.tools,J.messages);return this._client.post("/v1/messages?beta=true",{body:J,timeout:z??600000,...Z,headers:T([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},K,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:T([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>B2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return X8.createMessage(this,$,Z)}countTokens($,Z){let Y=y6($),{betas:Q,...J}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:J,...Z,headers:T([{"anthropic-beta":[...Q??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new U8(this._client,$,Z)}}function y6($){if(!$.output_format)return $;if($.output_config?.format)throw new E("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Z,...Y}=$;return{...Y,output_config:{...$.output_config,format:Z}}}W0.Batches=H8;W0.BetaToolRunner=U8;W0.ToolError=J1;class W8 extends h{create($,Z={},Y){let{betas:Q,...J}=Z??{};return this._client.post(v`/v1/skills/${$}/versions?beta=true`,Z1({body:J,...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve($,Z,Y){let{skill_id:Q,betas:J}=Z;return this._client.get(v`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:Q,...J}=Z??{};return this._client.getAPIList(v`/v1/skills/${$}/versions?beta=true`,r1,{query:J,...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:Q,betas:J}=Z;return this._client.delete(v`/v1/skills/${Q}/versions/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class X1 extends h{constructor(){super(...arguments);this.versions=new W8(this._client)}create($={},Z){let{betas:Y,...Q}=$??{};return this._client.post("/v1/skills?beta=true",Z1({body:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(v`/v1/skills/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/skills?beta=true",r1,{query:Q,...Z,headers:T([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:Q}=Z??{};return this._client.delete(v`/v1/skills/${$}?beta=true`,{...Y,headers:T([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}X1.Versions=W8;class I$ extends h{constructor(){super(...arguments);this.models=new $8(this._client),this.messages=new W0(this._client),this.files=new e1(this._client),this.skills=new X1(this._client)}}I$.Models=$8;I$.Messages=W0;I$.Files=e1;I$.Skills=X1;class V1 extends h{create($,Z){let{betas:Y,...Q}=$;return this._client.post("/v1/complete",{body:Q,timeout:this._client._options.timeout??600000,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function b6($){return $?.output_config?.format}function R2($,Z,Y){let Q=b6(Z);if(!Z||!("parse"in(Q??{})))return{...$,content:$.content.map((J)=>{if(J.type==="text")return Object.defineProperty({...J},"parsed_output",{value:null,enumerable:!1});return J}),parsed_output:null};return E2($,Z,Y)}function E2($,Z,Y){let Q=null,J=$.content.map((z)=>{if(z.type==="text"){let K=iK(Z,z.text);if(Q===null)Q=K;return Object.defineProperty({...z},"parsed_output",{value:K,enumerable:!1})}return z});return{...$,content:J,parsed_output:Q}}function iK($,Z){let Y=b6($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(Q){throw new E(`Failed to parse structured output: ${Q}`)}}var E$,B0,G1,B8,m4,M8,C8,u4,N8,c$,O8,p4,d4,_0,c4,l4,F8,L2,_6,j2,D2,P2,T2,x6,f6="__json_buf";function v6($){return $.type==="tool_use"||$.type==="server_tool_use"}class R8{constructor($,Z){E$.add(this),this.messages=[],this.receivedMessages=[],B0.set(this,void 0),G1.set(this,null),this.controller=new AbortController,B8.set(this,void 0),m4.set(this,()=>{}),M8.set(this,()=>{}),C8.set(this,void 0),u4.set(this,()=>{}),N8.set(this,()=>{}),c$.set(this,{}),O8.set(this,!1),p4.set(this,!1),d4.set(this,!1),_0.set(this,!1),c4.set(this,void 0),l4.set(this,void 0),F8.set(this,void 0),j2.set(this,(Y)=>{if(F(this,p4,!0,"f"),m$(Y))Y=new e;if(Y instanceof e)return F(this,d4,!0,"f"),this._emit("abort",Y);if(Y instanceof E)return this._emit("error",Y);if(Y instanceof Error){let Q=new E(Y.message);return Q.cause=Y,this._emit("error",Q)}return this._emit("error",new E(String(Y)))}),F(this,B8,new Promise((Y,Q)=>{F(this,m4,Y,"f"),F(this,M8,Q,"f")}),"f"),F(this,C8,new Promise((Y,Q)=>{F(this,u4,Y,"f"),F(this,N8,Q,"f")}),"f"),C(this,B8,"f").catch(()=>{}),C(this,C8,"f").catch(()=>{}),F(this,G1,$,"f"),F(this,F8,Z?.logger??console,"f")}get response(){return C(this,c4,"f")}get request_id(){return C(this,l4,"f")}async withResponse(){F(this,_0,!0,"f");let $=await C(this,B8,"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 R8(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:Q}={}){let J=new R8(Z,{logger:Q});for(let z of Z.messages)J._addMessageParam(z);return F(J,G1,{...Z,stream:!0},"f"),J._run(()=>J._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),J}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},C(this,j2,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let Q=Y?.signal,J;if(Q){if(Q.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Q.addEventListener("abort",J)}try{C(this,E$,"m",D2).call(this);let{response:z,data:K}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let X of K)C(this,E$,"m",P2).call(this,X);if(K.controller.signal?.aborted)throw new e;C(this,E$,"m",T2).call(this)}finally{if(Q&&J)Q.removeEventListener("abort",J)}}_connected($){if(this.ended)return;F(this,c4,$,"f"),F(this,l4,$?.headers.get("request-id"),"f"),C(this,m4,"f").call(this,$),this._emit("connect")}get ended(){return C(this,O8,"f")}get errored(){return C(this,p4,"f")}get aborted(){return C(this,d4,"f")}abort(){this.controller.abort()}on($,Z){return(C(this,c$,"f")[$]||(C(this,c$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=C(this,c$,"f")[$];if(!Y)return this;let Q=Y.findIndex((J)=>J.listener===Z);if(Q>=0)Y.splice(Q,1);return this}once($,Z){return(C(this,c$,"f")[$]||(C(this,c$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(F(this,_0,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){F(this,_0,!0,"f"),await C(this,C8,"f")}get currentMessage(){return C(this,B0,"f")}async finalMessage(){return await this.done(),C(this,E$,"m",L2).call(this)}async finalText(){return await this.done(),C(this,E$,"m",_6).call(this)}_emit($,...Z){if(C(this,O8,"f"))return;if($==="end")F(this,O8,!0,"f"),C(this,u4,"f").call(this);let Y=C(this,c$,"f")[$];if(Y)C(this,c$,"f")[$]=Y.filter((Q)=>!Q.once),Y.forEach(({listener:Q})=>Q(...Z));if($==="abort"){let Q=Z[0];if(!C(this,_0,"f")&&!Y?.length)Promise.reject(Q);C(this,M8,"f").call(this,Q),C(this,N8,"f").call(this,Q),this._emit("end");return}if($==="error"){let Q=Z[0];if(!C(this,_0,"f")&&!Y?.length)Promise.reject(Q);C(this,M8,"f").call(this,Q),C(this,N8,"f").call(this,Q),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",C(this,E$,"m",L2).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{C(this,E$,"m",D2).call(this),this._connected(null);let J=B$.fromReadableStream($,this.controller);for await(let z of J)C(this,E$,"m",P2).call(this,z);if(J.controller.signal?.aborted)throw new e;C(this,E$,"m",T2).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}[(B0=new WeakMap,G1=new WeakMap,B8=new WeakMap,m4=new WeakMap,M8=new WeakMap,C8=new WeakMap,u4=new WeakMap,N8=new WeakMap,c$=new WeakMap,O8=new WeakMap,p4=new WeakMap,d4=new WeakMap,_0=new WeakMap,c4=new WeakMap,l4=new WeakMap,F8=new WeakMap,j2=new WeakMap,E$=new WeakSet,L2=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},_6=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((Y)=>Y.type==="text").map((Y)=>Y.text);if(Z.length===0)throw new E("stream ended without producing a content block with type=text");return Z.join(" ")},D2=function(){if(this.ended)return;F(this,B0,void 0,"f")},P2=function(Z){if(this.ended)return;let Y=C(this,E$,"m",x6).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let Q=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Q.type==="text")this._emit("text",Z.delta.text,Q.text||"");break}case"citations_delta":{if(Q.type==="text")this._emit("citation",Z.delta.citation,Q.citations??[]);break}case"input_json_delta":{if(v6(Q)&&Q.input)this._emit("inputJson",Z.delta.partial_json,Q.input);break}case"thinking_delta":{if(Q.type==="thinking")this._emit("thinking",Z.delta.thinking,Q.thinking);break}case"signature_delta":{if(Q.type==="thinking")this._emit("signature",Q.signature);break}default:h6(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(R2(Y,C(this,G1,"f"),{logger:C(this,F8,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{F(this,B0,Y,"f");break}case"content_block_start":case"message_delta":break}},T2=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let Z=C(this,B0,"f");if(!Z)throw new E("request ended without sending any chunks");return F(this,B0,void 0,"f"),R2(Z,C(this,G1,"f"),{logger:C(this,F8,"f")})},x6=function(Z){let Y=C(this,B0,"f");if(Z.type==="message_start"){if(Y)throw new E(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new E(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return Y;case"message_delta":if(Y.stop_reason=Z.delta.stop_reason,Y.stop_sequence=Z.delta.stop_sequence,Y.usage.output_tokens=Z.usage.output_tokens,Z.usage.input_tokens!=null)Y.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)Y.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)Y.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)Y.usage.server_tool_use=Z.usage.server_tool_use;return Y;case"content_block_start":return Y.content.push({...Z.content_block}),Y;case"content_block_delta":{let Q=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,text:(Q.text||"")+Z.delta.text};break}case"citations_delta":{if(Q?.type==="text")Y.content[Z.index]={...Q,citations:[...Q.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Q&&v6(Q)){let J=Q[f6]||"";J+=Z.delta.partial_json;let z={...Q};if(Object.defineProperty(z,f6,{value:J,enumerable:!1,writable:!0}),J)z.input=y4(J);Y.content[Z.index]=z}break}case"thinking_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,thinking:Q.thinking+Z.delta.thinking};break}case"signature_delta":{if(Q?.type==="thinking")Y.content[Z.index]={...Q,signature:Z.delta.signature};break}default:h6(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(Q)=>{let J=Z.shift();if(J)J.resolve(Q);else $.push(Q)}),this.on("end",()=>{Y=!0;for(let Q of Z)Q.resolve(void 0);Z.length=0}),this.on("abort",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),this.on("error",(Q)=>{Y=!0;for(let J of Z)J.reject(Q);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((J,z)=>Z.push({resolve:J,reject:z})).then((J)=>J?{value:J,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new B$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function h6($){}class E8 extends h{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(v`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",P$,{query:$,...Z})}delete($,Z){return this._client.delete(v`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(v`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:T([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Q,J)=>K1.fromResponse(J.response,J.controller))}}class x0 extends h{constructor(){super(...arguments);this.batches=new E8(this._client)}create($,Z){if($.model in g6)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${g6[$.model]}
|
|
83
|
+
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in aK&&$.thinking&&$.thinking.type==="enabled")console.warn(`Using Claude with ${$.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let Y=this._client._options.timeout;if(!$.stream&&Y==null){let J=k4[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,J)}let Q=w4($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:T([Q,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>E2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return R8.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var g6={"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"},aK=["claude-opus-4-6"];x0.Batches=E8;class q1 extends h{retrieve($,Z={},Y){let{betas:Q}=Z??{};return this._client.get(v`/v1/models/${$}`,{...Y,headers:T([{...Q?.toString()!=null?{"anthropic-beta":Q?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...Q}=$??{};return this._client.getAPIList("/v1/models",P$,{query:Q,...Z,headers:T([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var L8=($)=>{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 A2,I2,o4,m6,u6="\\n\\nHuman:",p6="\\n\\nAssistant:";class g{constructor({baseURL:$=L8("ANTHROPIC_BASE_URL"),apiKey:Z=L8("ANTHROPIC_API_KEY")??null,authToken:Y=L8("ANTHROPIC_AUTH_TOKEN")??null,...Q}={}){A2.add(this),o4.set(this,void 0);let J={apiKey:Z,authToken:Y,...Q,baseURL:$||"https://api.anthropic.com"};if(!J.dangerouslyAllowBrowser&&Q6())throw new E(`It looks like you're running in a browser-like environment.
|
|
83
84
|
|
|
84
85
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
85
86
|
If you understand the risks and have appropriate mitigations in place,
|
|
86
87
|
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
87
88
|
|
|
88
89
|
new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
|
|
89
|
-
`);this.baseURL=J.baseURL,this.timeout=J.timeout??X9.DEFAULT_TIMEOUT,this.logger=J.logger??console;let X="warn";this.logLevel=X,this.logLevel=v5(J.logLevel,"ClientOptions.logLevel",this)??v5(T1("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??X,this.fetchOptions=J.fetchOptions,this.maxRetries=J.maxRetries??2,this.fetch=J.fetch??I2(),D(this,l0,S2,"f"),this._options=J,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Q}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return k([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return k([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return k([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return w2($)}getUserAgent(){return`${this.constructor.name}/JS ${C4}`}defaultIdempotencyKey(){return`stainless-node-retry-${S5()}`}makeStatusError($,Z,Q,Y){return t.generate($,Z,Q,Y)}buildURL($,Z,Q){let Y=!M(this,J9,"m",G6).call(this)&&Q||this.baseURL,J=O2($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery(),K=Object.fromEntries(J.searchParams);if(!y5(X)||!y5(K))Z={...K,...X,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))J.search=this.stringifyQuery(Z);return J.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new T("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:Q}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,Q){return this.request(Promise.resolve(Q).then((Y)=>{return{method:$,path:Z,...Y}}))}request($,Z=null){return new b4(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Q){let Y=await $,J=Y.maxRetries??this.maxRetries;if(Z==null)Z=J;await this.prepareOptions(Y);let{req:X,url:K,timeout:V}=await this.buildRequest(Y,{retryCount:J-Z});await this.prepareRequest(X,{url:K,options:Y});let G="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Q===void 0?"":`, retryOf: ${Q}`,z=Date.now();if(Q$(this).debug(`[${G}] sending request`,r$({retryOfRequestLogID:Q,method:Y.method,url:K,options:Y,headers:X.headers})),Y.signal?.aborted)throw new z$;let B=new AbortController,W=await this.fetchWithTimeout(K,X,V,B).catch(g8),N=Date.now();if(W instanceof globalThis.Error){let P=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new z$;let _=n$(W)||/timed? ?out/i.test(String(W)+("cause"in W?String(W.cause):""));if(Z)return Q$(this).info(`[${G}] connection ${_?"timed out":"failed"} - ${P}`),Q$(this).debug(`[${G}] connection ${_?"timed out":"failed"} (${P})`,r$({retryOfRequestLogID:Q,url:K,durationMs:N-z,message:W.message})),this.retryRequest(Y,Z,Q??G);if(Q$(this).info(`[${G}] connection ${_?"timed out":"failed"} - error; no more retries left`),Q$(this).debug(`[${G}] connection ${_?"timed out":"failed"} (error; no more retries left)`,r$({retryOfRequestLogID:Q,url:K,durationMs:N-z,message:W.message})),_)throw new m8;throw new y4({cause:W})}let O=[...W.headers.entries()].filter(([P])=>P==="request-id").map(([P,_])=>", "+P+": "+JSON.stringify(_)).join(""),j=`[${G}${H}${O}] ${X.method} ${K} ${W.ok?"succeeded":"failed"} with status ${W.status} in ${N-z}ms`;if(!W.ok){let P=await this.shouldRetry(W);if(Z&&P){let a=`retrying, ${Z} attempts remaining`;return await x2(W.body),Q$(this).info(`${j} - ${a}`),Q$(this).debug(`[${G}] response error (${a})`,r$({retryOfRequestLogID:Q,url:W.url,status:W.status,headers:W.headers,durationMs:N-z})),this.retryRequest(Y,Z,Q??G,W.headers)}let _=P?"error; no more retries left":"error; not retryable";Q$(this).info(`${j} - ${_}`);let q$=await W.text().catch((a)=>g8(a).message),$$=R0(q$),y=$$?void 0:q$;throw Q$(this).debug(`[${G}] response error (${_})`,r$({retryOfRequestLogID:Q,url:W.url,status:W.status,headers:W.headers,message:y,durationMs:Date.now()-z})),this.makeStatusError(W.status,$$,y,W.headers)}return Q$(this).info(j),Q$(this).debug(`[${G}] response start`,r$({retryOfRequestLogID:Q,url:W.url,status:W.status,headers:W.headers,durationMs:N-z})),{response:W,options:Y,controller:B,requestLogID:G,retryOfRequestLogID:Q,startTime:z}}getAPIList($,Z,Q){return this.requestAPIList(Z,Q&&"then"in Q?Q.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...Q})}requestAPIList($,Z){let Q=this.makeRequest(Z,null,void 0);return new T0(this,Q,$)}async fetchWithTimeout($,Z,Q,Y){let{signal:J,method:X,...K}=Z||{},V=this._makeAbort(Y);if(J)J.addEventListener("abort",V,{once:!0});let G=setTimeout(V,Q),H=globalThis.ReadableStream&&K.body instanceof globalThis.ReadableStream||typeof K.body==="object"&&K.body!==null&&Symbol.asyncIterator in K.body,z={signal:Y.signal,...H?{duplex:"half"}:{},method:"GET",...K};if(X)z.method=X.toUpperCase();try{return await this.fetch.call(void 0,$,z)}finally{clearTimeout(G)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Q,Y){let J,X=Y?.get("retry-after-ms");if(X){let V=parseFloat(X);if(!Number.isNaN(V))J=V}let K=Y?.get("retry-after");if(K&&!J){let V=parseFloat(K);if(!Number.isNaN(V))J=V*1000;else J=Date.parse(K)-Date.now()}if(J===void 0){let V=$.maxRetries??this.maxRetries;J=this.calculateDefaultRetryTimeoutMillis(Z,V)}return await L2(J),this.makeRequest($,Z-1,Q)}calculateDefaultRetryTimeoutMillis($,Z){let J=Z-$,X=Math.min(0.5*Math.pow(2,J),8),K=1-Math.random()*0.25;return X*K*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new T("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let Q={...$},{method:Y,path:J,query:X,defaultBaseURL:K}=Q,V=this.buildURL(J,X,K);if("timeout"in Q)E2("timeout",Q.timeout);Q.timeout=Q.timeout??this.timeout;let{bodyHeaders:G,body:H}=this.buildBody({options:Q}),z=await this.buildHeaders({options:$,method:Y,bodyHeaders:G,retryCount:Z});return{req:{method:Y,headers:z,...Q.signal&&{signal:Q.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Q.fetchOptions??{}},url:V,timeout:Q.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Q,retryCount:Y}){let J={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=$.idempotencyKey}let X=k([J,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...A2(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Q,$.headers]);return this.validateHeaders(X),X.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Q=k([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Q.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:E0($)};else if(typeof $==="object"&&Q.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return M(this,l0,"f").call(this,{body:$,headers:Q})}}X9=o,l0=new WeakMap,J9=new WeakSet,G6=function(){return this.baseURL!=="https://api.anthropic.com"};o.Anthropic=X9;o.HUMAN_PROMPT=H6;o.AI_PROMPT=q6;o.DEFAULT_TIMEOUT=600000;o.AnthropicError=T;o.APIError=t;o.APIConnectionError=y4;o.APIConnectionTimeoutError=m8;o.APIUserAbortError=z$;o.NotFoundError=d8;o.ConflictError=l8;o.RateLimitError=a8;o.BadRequestError=p8;o.AuthenticationError=c8;o.InternalServerError=n8;o.PermissionDeniedError=u8;o.UnprocessableEntityError=o8;o.toFile=A0;class f$ extends o{constructor(){super(...arguments);this.completions=new U8(this),this.messages=new g4(this),this.models=new B8(this),this.beta=new v$(this)}}f$.Completions=U8;f$.Messages=g4;f$.Models=B8;f$.Beta=v$;n();Z$();import{existsSync as a1,readdirSync as oG,readFileSync as GZ,writeFileSync as aG,statSync as zY,realpathSync as nG}from"fs";import{resolve as b$,join as VY,sep as A8}from"path";import{existsSync as QK,readFileSync as YK,writeFileSync as JK}from"fs";import{basename as K9}from"path";var U6=50;class z9{entries=[];saveState($){let Z=QK($),Q=Z?YK($,"utf-8"):"";if(this.entries.push({path:$,content:Q,timestamp:Date.now(),existed:Z}),this.entries.length>U6)this.entries=this.entries.slice(-U6)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${K9($.path)} was a new file. Remove it manually if needed.`;JK($.path,$.content);let Z=$.content.split(`
|
|
90
|
-
`).length;return`Undo: restored ${K9($.path)} (${Z} lines, from ${W6($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${K9($.path)} (${W6($.timestamp)})`}}function W6($){let Z=Math.floor((Date.now()-$)/1000);if(Z<60)return`${Z}s ago`;let Q=Math.floor(Z/60);if(Q<60)return`${Q}m ago`;return`${Math.floor(Q/60)}h ago`}Z$();import{existsSync as B6,readdirSync as XK,readFileSync as KK,mkdirSync as zK}from"fs";import{join as V9}from"path";function C6($){if(!B6($))return[];let Z=[],Q=XK($).filter((Y)=>Y.endsWith(".json"));for(let Y of Q)try{let J=JSON.parse(KK(V9($,Y),"utf-8"));if(!J.name||!J.description||!J.command)continue;if(typeof J.name!=="string"||typeof J.command!=="string")continue;if(J.command.includes("$(")||J.command.includes("`"))continue;Z.push({name:J.name,description:J.description,inputSchema:J.input_schema||{type:"object",properties:{},required:[]},command:J.command,source:V9($,Y)})}catch{}return Z}function N6($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function M6($,Z){let Q=$.command;for(let[z,B]of Object.entries(Z)){let W=String(B).replace(/[;&|`$()]/g,"");Q=Q.replace(new RegExp(`\\{\\{input\\.${z}\\}\\}`,"g"),W)}Q=Q.replace(/\{\{input\.\w+\}\}/g,"");let Y=Q8(),J=Bun.spawn([...Y,Q],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>J.kill(),30000),[K,V]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),G=await J.exited;clearTimeout(X);let H=K.trim();if(V.trim())H+=(H?`
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
`)}function
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
Total: ${W9().length} ativas (${C8.length} built-in, ${B$.length} custom, ${L$.size} desativadas)`),$.join(`
|
|
98
|
-
`)}var E6=2097152,U9=10,WK=1e4;function BK($,Z,Q){let Y=[],J=/<item[\s>]([\s\S]*?)<\/item>/gi,X;while((X=J.exec($))!==null){let K=X[1],V=L6(K,Z,Q);if(V)Y.push(V);if(Y.length>=U9)break}if(Y.length===0){let K=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((X=K.exec($))!==null){let V=X[1],G=L6(V,Z,Q);if(G)Y.push(G);if(Y.length>=U9)break}}return Y}function L6($,Z,Q){let Y=x1($,"title");if(!Y)return null;let J=x1($,"link")||OK($),X=CK(J),K=x1($,"pubDate")||x1($,"published")||x1($,"updated"),V;if(K){let G=new Date(K);V=isNaN(G.getTime())?void 0:G}return{title:w1(Y),link:X,source:Z,category:Q,pubDate:V}}function CK($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function NK($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function x1($,Z){let Q=NK(Z),J=new RegExp(`<${Q}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Q}>`,"i").exec($);if(J)return J[1].trim();let K=new RegExp(`<${Q}[^>]*>([\\s\\S]*?)</${Q}>`,"i").exec($);return K?K[1].trim():null}function MK($,Z){let Q=FK($,Z);try{return new TextDecoder(Q).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function FK($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return S1(J[1])}let Y=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Y)return S1(Y[1]);return"utf-8"}function S1($){let Z=$.toLowerCase().replace(/[^a-z0-9]/g,"");if(Z==="iso88591"||Z==="latin1")return"iso-8859-1";if(Z==="windows1252"||Z==="cp1252")return"windows-1252";if(Z==="utf8")return"utf-8";if(Z==="usascii"||Z==="ascii")return"utf-8";return $.trim().toLowerCase()}function OK($){let Q=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Q?Q[1]:null}var RK={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",aacute:"\xE1",Aacute:"\xC1",agrave:"\xE0",Agrave:"\xC0",atilde:"\xE3",Atilde:"\xC3",acirc:"\xE2",Acirc:"\xC2",eacute:"\xE9",Eacute:"\xC9",egrave:"\xE8",Egrave:"\xC8",ecirc:"\xEA",Ecirc:"\xCA",iacute:"\xED",Iacute:"\xCD",oacute:"\xF3",Oacute:"\xD3",otilde:"\xF5",Otilde:"\xD5",ocirc:"\xF4",Ocirc:"\xD4",uacute:"\xFA",Uacute:"\xDA",uuml:"\xFC",Uuml:"\xDC",ccedil:"\xE7",Ccedil:"\xC7",ntilde:"\xF1",Ntilde:"\xD1",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",bull:"\u2022",laquo:"\xAB",raquo:"\xBB",trade:"\u2122",copy:"\xA9",reg:"\xAE",euro:"\u20AC",pound:"\xA3",yen:"\xA5",cent:"\xA2",deg:"\xB0",middot:"\xB7",times:"\xD7",divide:"\xF7"};function w1($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Q)=>RK[Q]??Z).replace(/&#(\d+);/g,(Z,Q)=>String.fromCharCode(Number(Q))).replace(/&#x([0-9a-fA-F]+);/g,(Z,Q)=>String.fromCharCode(parseInt(Q,16))).trim()}async function B9($,Z=5){let Q=Math.max(1,Math.min(Z,U9));if($&&$.length===0)return{items:[],errors:[]};let Y=W9(),J=$?Y.filter((G)=>$.includes(G.category)):Y,X=await Promise.allSettled(J.map((G)=>LK(G,Q))),K=[],V=[];for(let G=0;G<X.length;G++){let H=X[G];if(H.status==="fulfilled")K.push(...H.value);else V.push(`${J[G].name}: ${EK(H.reason)}`)}return K.sort((G,H)=>{let z=G.pubDate?.getTime()||0;return(H.pubDate?.getTime()||0)-z}),{items:K,errors:V}}async function E4($,Z=5){if($&&$.length===0)return DK();let{items:Q,errors:Y}=await B9($,Z);if(Q.length===0)return Y.length>0?`Nenhuma noticia encontrada.
|
|
99
|
-
Falhas: ${Y.join(", ")}`:"Nenhuma noticia encontrada.";return jK(Q,Y)}function EK($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function LK($,Z){let Q=new AbortController,Y=setTimeout(()=>Q.abort(),WK);try{let J=await fetch($.url,{signal:Q.signal,headers:{"User-Agent":"smolerclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(Y),!J.ok)return[];let X=J.headers.get("content-length");if(X&&Number(X)>E6)return[];let K=J.body?.getReader();if(!K)return[];let V=[],G=0;while(!0){let{done:W,value:N}=await K.read();if(W)break;if(G+=N.byteLength,G>E6)return K.cancel(),[];V.push(N)}let H=Buffer.concat(V),z=MK(H,J.headers.get("content-type"));return BK(z,$.name,$.category).slice(0,Z)}catch(J){throw clearTimeout(Y),J}}function jK($,Z){let Q={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Y=new Map;for(let V of $){let G=Y.get(V.category)||[];Y.set(V.category,[...G,V])}let J=[],X=["finance","business","tech","security","brazil","world"];for(let V of X){let G=Y.get(V);if(!G||G.length===0)continue;let H=Q[V],z=G.slice(0,8).map((B)=>{let W=B.pubDate?B.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${W?`[${W}]`:""} ${B.title} (${B.source})`});J.push(`--- ${H} ---
|
|
100
|
-
${z.join(`
|
|
90
|
+
`);this.baseURL=J.baseURL,this.timeout=J.timeout??I2.DEFAULT_TIMEOUT,this.logger=J.logger??console;let z="warn";this.logLevel=z,this.logLevel=z2(J.logLevel,"ClientOptions.logLevel",this)??z2(L8("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??z,this.fetchOptions=J.fetchOptions,this.maxRetries=J.maxRetries??2,this.fetch=J.fetch??z6(),F(this,o4,X6,"f"),this._options=J,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Y}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return T([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return T([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return T([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return V6($)}getUserAgent(){return`${this.constructor.name}/JS ${G0}`}defaultIdempotencyKey(){return`stainless-node-retry-${e5()}`}makeStatusError($,Z,Y,Q){return d.generate($,Z,Y,Q)}buildURL($,Z,Y){let Q=!C(this,A2,"m",m6).call(this)&&Y||this.baseURL,J=rZ($)?new URL($):new URL(Q+(Q.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),z=this.defaultQuery(),K=Object.fromEntries(J.searchParams);if(!Y2(z)||!Y2(K))Z={...K,...z,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))J.search=this.stringifyQuery(Z);return J.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new E("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:Y}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,Y){return this.request(Promise.resolve(Y).then((Q)=>{return{method:$,path:Z,...Q}}))}request($,Z=null){return new w0(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Y){let Q=await $,J=Q.maxRetries??this.maxRetries;if(Z==null)Z=J;await this.prepareOptions(Q);let{req:z,url:K,timeout:X}=await this.buildRequest(Q,{retryCount:J-Z});await this.prepareRequest(z,{url:K,options:Q});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),G=Y===void 0?"":`, retryOf: ${Y}`,q=Date.now();if(o(this).debug(`[${V}] sending request`,u$({retryOfRequestLogID:Y,method:Q.method,url:K,options:Q,headers:z.headers})),Q.signal?.aborted)throw new e;let U=new AbortController,W=await this.fetchWithTimeout(K,z,X,U).catch(x1),B=Date.now();if(W instanceof globalThis.Error){let R=`retrying, ${Z} attempts remaining`;if(Q.signal?.aborted)throw new e;let P=m$(W)||/timed? ?out/i.test(String(W)+("cause"in W?String(W.cause):""));if(Z)return o(this).info(`[${V}] connection ${P?"timed out":"failed"} - ${R}`),o(this).debug(`[${V}] connection ${P?"timed out":"failed"} (${R})`,u$({retryOfRequestLogID:Y,url:K,durationMs:B-q,message:W.message})),this.retryRequest(Q,Z,Y??V);if(o(this).info(`[${V}] connection ${P?"timed out":"failed"} - error; no more retries left`),o(this).debug(`[${V}] connection ${P?"timed out":"failed"} (error; no more retries left)`,u$({retryOfRequestLogID:Y,url:K,durationMs:B-q,message:W.message})),P)throw new f1;throw new S0({cause:W})}let M=[...W.headers.entries()].filter(([R])=>R==="request-id").map(([R,P])=>", "+R+": "+JSON.stringify(P)).join(""),O=`[${V}${G}${M}] ${z.method} ${K} ${W.ok?"succeeded":"failed"} with status ${W.status} in ${B-q}ms`;if(!W.ok){let R=await this.shouldRetry(W);if(Z&&R){let n=`retrying, ${Z} attempts remaining`;return await K6(W.body),o(this).info(`${O} - ${n}`),o(this).debug(`[${V}] response error (${n})`,u$({retryOfRequestLogID:Y,url:W.url,status:W.status,headers:W.headers,durationMs:B-q})),this.retryRequest(Q,Z,Y??V,W.headers)}let P=R?"error; no more retries left":"error; not retryable";o(this).info(`${O} - ${P}`);let Q$=await W.text().catch((n)=>x1(n).message),l=E4(Q$),A=l?void 0:Q$;throw o(this).debug(`[${V}] response error (${P})`,u$({retryOfRequestLogID:Y,url:W.url,status:W.status,headers:W.headers,message:A,durationMs:Date.now()-q})),this.makeStatusError(W.status,l,A,W.headers)}return o(this).info(O),o(this).debug(`[${V}] response start`,u$({retryOfRequestLogID:Y,url:W.url,status:W.status,headers:W.headers,durationMs:B-q})),{response:W,options:Q,controller:U,requestLogID:V,retryOfRequestLogID:Y,startTime:q}}getAPIList($,Z,Y){return this.requestAPIList(Z,Y&&"then"in Y?Y.then((Q)=>({method:"get",path:$,...Q})):{method:"get",path:$,...Y})}requestAPIList($,Z){let Y=this.makeRequest(Z,null,void 0);return new A4(this,Y,$)}async fetchWithTimeout($,Z,Y,Q){let{signal:J,method:z,...K}=Z||{},X=this._makeAbort(Q);if(J)J.addEventListener("abort",X,{once:!0});let V=setTimeout(X,Y),G=globalThis.ReadableStream&&K.body instanceof globalThis.ReadableStream||typeof K.body==="object"&&K.body!==null&&Symbol.asyncIterator in K.body,q={signal:Q.signal,...G?{duplex:"half"}:{},method:"GET",...K};if(z)q.method=z.toUpperCase();try{return await this.fetch.call(void 0,$,q)}finally{clearTimeout(V)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Y,Q){let J,z=Q?.get("retry-after-ms");if(z){let X=parseFloat(z);if(!Number.isNaN(X))J=X}let K=Q?.get("retry-after");if(K&&!J){let X=parseFloat(K);if(!Number.isNaN(X))J=X*1000;else J=Date.parse(K)-Date.now()}if(J===void 0){let X=$.maxRetries??this.maxRetries;J=this.calculateDefaultRetryTimeoutMillis(Z,X)}return await eZ(J),this.makeRequest($,Z-1,Y)}calculateDefaultRetryTimeoutMillis($,Z){let J=Z-$,z=Math.min(0.5*Math.pow(2,J),8),K=1-Math.random()*0.25;return z*K*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new E("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let Y={...$},{method:Q,path:J,query:z,defaultBaseURL:K}=Y,X=this.buildURL(J,z,K);if("timeout"in Y)tZ("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:V,body:G}=this.buildBody({options:Y}),q=await this.buildHeaders({options:$,method:Q,bodyHeaders:V,retryCount:Z});return{req:{method:Q,headers:q,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&G instanceof globalThis.ReadableStream&&{duplex:"half"},...G&&{body:G},...this.fetchOptions??{},...Y.fetchOptions??{}},url:X,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:Q}){let J={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=$.idempotencyKey}let z=T([J,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Q),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...J6(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Y,$.headers]);return this.validateHeaders(z),z.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Y=T([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&Y.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:L4($)};else if(typeof $==="object"&&Y.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return C(this,o4,"f").call(this,{body:$,headers:Y})}}I2=g,o4=new WeakMap,A2=new WeakSet,m6=function(){return this.baseURL!=="https://api.anthropic.com"};g.Anthropic=I2;g.HUMAN_PROMPT=u6;g.AI_PROMPT=p6;g.DEFAULT_TIMEOUT=600000;g.AnthropicError=E;g.APIError=d;g.APIConnectionError=S0;g.APIConnectionTimeoutError=f1;g.APIUserAbortError=e;g.NotFoundError=m1;g.ConflictError=u1;g.RateLimitError=d1;g.BadRequestError=v1;g.AuthenticationError=h1;g.InternalServerError=c1;g.PermissionDeniedError=g1;g.UnprocessableEntityError=p1;g.toFile=I4;class S$ extends g{constructor(){super(...arguments);this.completions=new V1(this),this.messages=new x0(this),this.models=new q1(this),this.beta=new I$(this)}}S$.Completions=V1;S$.Messages=x0;S$.Models=q1;S$.Beta=I$;import{existsSync as sK,readFileSync as tK,writeFileSync as eK}from"fs";import{basename as S2}from"path";var d6=50;class w2{entries=[];saveState($){let Z=sK($),Y=Z?tK($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>d6)this.entries=this.entries.slice(-d6)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${S2($.path)} was a new file. Remove it manually if needed.`;eK($.path,$.content);let Z=$.content.split(`
|
|
91
|
+
`).length;return`Undo: restored ${S2($.path)} (${Z} lines, from ${c6($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${S2($.path)} (${c6($.timestamp)})`}}function c6($){let Z=Math.floor((Date.now()-$)/1000);if(Z<60)return`${Z}s ago`;let Y=Math.floor(Z/60);if(Y<60)return`${Y}m ago`;return`${Math.floor(Y/60)}h ago`}p();var k=[{name:"read_file",description:"Read file contents. For large files, use offset/limit to read specific line ranges.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},offset:{type:"number",description:"Start reading from this line number (1-based). Optional."},limit:{type:"number",description:"Max lines to read. Optional, defaults to 500."}},required:["path"]}},{name:"write_file",description:"Create a new file or completely overwrite an existing file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write"},content:{type:"string",description:"Full file content"}},required:["path","content"]}},{name:"edit_file",description:"Make a precise edit to a file. Finds old_text and replaces it with new_text. The old_text must match exactly (including whitespace). "+"Use this instead of write_file when modifying existing files \u2014 it preserves the rest of the file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to edit"},old_text:{type:"string",description:"Exact text to find (must be unique in the file)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}},{name:"search_files",description:"Search file contents using a regex pattern (like grep). Returns matching lines with file paths and line numbers.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in. Defaults to cwd."},include:{type:"string",description:'Glob pattern to filter files, e.g. "*.ts" or "*.py"'}},required:["pattern"]}},{name:"find_files",description:"Find files by name pattern (glob). Returns matching file paths.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.ts", "src/**/test*"'},path:{type:"string",description:"Base directory. Defaults to cwd."}},required:["pattern"]}},{name:"list_directory",description:"List files and directories with type indicators and sizes.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory to list. Defaults to cwd."}},required:[]}},{name:"run_command",description:"Run a shell command. Use for: git operations, running tests, installing packages, building projects, or any CLI task. Commands run in the current working directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"number",description:"Timeout in seconds. Default 30, max 120."}},required:["command"]}},{name:"fetch_url",description:"Fetch the content of a URL. Use for: reading documentation, checking APIs, downloading config files, or verifying endpoints. Returns the response body as text. For HTML pages, returns a text-only extraction (no tags).",input_schema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"},method:{type:"string",description:"HTTP method. Default GET.",enum:["GET","POST","PUT","DELETE","PATCH","HEAD"]},headers:{type:"object",description:"Optional request headers as key-value pairs."},body:{type:"string",description:"Optional request body (for POST/PUT/PATCH)."}},required:["url"]}}];var j8=[{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:[]}}],i4=[{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:[]}}],n4=[{name:"send_notification",description:'Send a Windows toast notification to the user. Displays a system notification with title and message. Use when you need to alert the user about: task completions, reminders, important events, or when the user asks "me avisa quando terminar", "notifica quando...", etc.',input_schema:{type:"object",properties:{title:{type:"string",description:"Notification title (short, max ~50 chars)."},message:{type:"string",description:"Notification message/body."}},required:["title","message"]}}],a4=j8.find(($)=>$.name==="get_news");import{resolve as $5,sep as UQ}from"path";import{writeFileSync as Uq}from"fs";f();import{existsSync as $X,readFileSync as ZX}from"fs";import{join as YX}from"path";var U1=[{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}],r4="",K$=[],C$=new Set,n6=()=>YX(r4,"news-feeds.json");function s4(){if(!r4)return;let $={custom:K$,disabled:[...C$]};D(n6(),JSON.stringify($,null,2))}function QX(){if(!r4)return;let $=n6();if(!$X($)){K$=[],C$=new Set;return}try{let Z=JSON.parse(ZX($,"utf-8"));K$=Z.custom||[],C$=new Set(Z.disabled||[])}catch{K$=[],C$=new Set}}function a6($){r4=$,QX()}function y2(){return[...U1.filter((Z)=>!C$.has(Z.url)),...K$]}function t4($,Z,Y){let Q=$.trim();if(!Q||Q.length>100)return"Error: nome invalido (1-100 caracteres).";let J=Y.trim().toLowerCase();if(!J||J.length>30)return"Error: categoria invalida (1-30 caracteres).";let z=Z.trim();if(!z.startsWith("http://")&&!z.startsWith("https://"))return"Error: URL deve comecar com http:// ou https://";if(z.length>500)return"Error: URL muito longa (max 500 caracteres).";if([...U1,...K$].some((V)=>V.url===z))return"Error: essa URL ja esta cadastrada.";let X={name:Q,url:z,category:J};return K$=[...K$,X],s4(),X}function e4($){let Z=$.toLowerCase().trim(),Y=K$.findIndex((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(Y===-1)return!1;return K$=[...K$.slice(0,Y),...K$.slice(Y+1)],s4(),!0}function $7($){let Z=$.toLowerCase().trim(),Y=U1.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(C$.has(Y.url))return!1;return C$=new Set([...C$,Y.url]),s4(),!0}function Z7($){let Z=$.toLowerCase().trim(),Y=U1.find((Q)=>Q.name.toLowerCase()===Z||Q.url===$.trim());if(!Y)return!1;if(!C$.has(Y.url))return!1;return C$=new Set([...C$].filter((Q)=>Q!==Y.url)),s4(),!0}function Y7(){let $=["Fontes de noticias:"];$.push(`
|
|
92
|
+
--- Built-in ---`);for(let Z of U1){let Y=C$.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(K$.length>0){$.push(`
|
|
93
|
+
--- Custom ---`);for(let Z of K$)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
|
|
94
|
+
Total: ${y2().length} ativas (${U1.length} built-in, ${K$.length} custom, ${C$.size} desativadas)`),$.join(`
|
|
95
|
+
`)}var l6=2097152,k2=10,JX=1e4;function zX($,Z,Y){let Q=[],J=/<item[\s>]([\s\S]*?)<\/item>/gi,z;while((z=J.exec($))!==null){let K=z[1],X=o6(K,Z,Y);if(X)Q.push(X);if(Q.length>=k2)break}if(Q.length===0){let K=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((z=K.exec($))!==null){let X=z[1],V=o6(X,Z,Y);if(V)Q.push(V);if(Q.length>=k2)break}}return Q}function o6($,Z,Y){let Q=D8($,"title");if(!Q)return null;let J=D8($,"link")||qX($),z=KX(J),K=D8($,"pubDate")||D8($,"published")||D8($,"updated"),X;if(K){let V=new Date(K);X=isNaN(V.getTime())?void 0:V}return{title:T8(Q),link:z,source:Z,category:Y,pubDate:X}}function KX($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function XX($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function D8($,Z){let Y=XX(Z),J=new RegExp(`<${Y}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Y}>`,"i").exec($);if(J)return J[1].trim();let K=new RegExp(`<${Y}[^>]*>([\\s\\S]*?)</${Y}>`,"i").exec($);return K?K[1].trim():null}function VX($,Z){let Y=GX($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function GX($,Z){if(Z){let J=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(J)return P8(J[1])}let Q=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Q)return P8(Q[1]);return"utf-8"}function P8($){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 qX($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}var UX={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 T8($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,Y)=>UX[Y]??Z).replace(/&#(\d+);/g,(Z,Y)=>String.fromCharCode(Number(Y))).replace(/&#x([0-9a-fA-F]+);/g,(Z,Y)=>String.fromCharCode(parseInt(Y,16))).trim()}async function b2($,Z=5){let Y=Math.max(1,Math.min(Z,k2));if($&&$.length===0)return{items:[],errors:[]};let Q=y2(),J=$?Q.filter((V)=>$.includes(V.category)):Q,z=await Promise.allSettled(J.map((V)=>WX(V,Y))),K=[],X=[];for(let V=0;V<z.length;V++){let G=z[V];if(G.status==="fulfilled")K.push(...G.value);else X.push(`${J[V].name}: ${HX(G.reason)}`)}return K.sort((V,G)=>{let q=V.pubDate?.getTime()||0;return(G.pubDate?.getTime()||0)-q}),{items:K,errors:X}}async function M0($,Z=5){if($&&$.length===0)return MX();let{items:Y,errors:Q}=await b2($,Z);if(Y.length===0)return Q.length>0?`Nenhuma noticia encontrada.
|
|
96
|
+
Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return BX(Y,Q)}function HX($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function WX($,Z){let Y=new AbortController,Q=setTimeout(()=>Y.abort(),JX);try{let J=await fetch($.url,{signal:Y.signal,headers:{"User-Agent":"smolerclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(Q),!J.ok)return[];let z=J.headers.get("content-length");if(z&&Number(z)>l6)return[];let K=J.body?.getReader();if(!K)return[];let X=[],V=0;while(!0){let{done:W,value:B}=await K.read();if(W)break;if(V+=B.byteLength,V>l6)return K.cancel(),[];X.push(B)}let G=Buffer.concat(X),q=VX(G,J.headers.get("content-type"));return zX(q,$.name,$.category).slice(0,Z)}catch(J){throw clearTimeout(Q),J}}function BX($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Q=new Map;for(let X of $){let V=Q.get(X.category)||[];Q.set(X.category,[...V,X])}let J=[],z=["finance","business","tech","security","brazil","world"];for(let X of z){let V=Q.get(X);if(!V||V.length===0)continue;let G=Y[X],q=V.slice(0,8).map((U)=>{let W=U.pubDate?U.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${W?`[${W}]`:""} ${U.title} (${U.source})`});J.push(`--- ${G} ---
|
|
97
|
+
${q.join(`
|
|
101
98
|
`)}`)}let K=J.join(`
|
|
102
99
|
|
|
103
100
|
`);if(Z.length>0)K+=`
|
|
104
101
|
|
|
105
|
-
(Fontes indisponiveis: ${Z.join(", ")})`;return K}function
|
|
106
|
-
Uso: /news [categoria]`}var
|
|
102
|
+
(Fontes indisponiveis: ${Z.join(", ")})`;return K}function MX(){let $=y2();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
|
|
103
|
+
Uso: /news [categoria]`}var CX=15000,i6=5242880;async function r6($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL invalida";let Z=new AbortController,Y=setTimeout(()=>Z.abort(),CX);try{let Q=await fetch($,{signal:Z.signal,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language":"pt-BR,pt;q=0.9,en;q=0.8"}});if(clearTimeout(Y),!Q.ok)return`Error: HTTP ${Q.status}`;let J=Q.headers.get("content-length");if(J&&Number(J)>i6)return"Error: pagina muito grande";let z=Q.body?.getReader();if(!z)return"Error: sem corpo de resposta";let K=[],X=0;while(!0){let{done:W,value:B}=await z.read();if(W)break;if(X+=B.byteLength,X>i6)return z.cancel(),"Error: pagina muito grande";K.push(B)}let V=Buffer.concat(K),G=Q.headers.get("content-type"),q=NX(V,G);return FX(q)}catch(Q){if(clearTimeout(Y),Q instanceof Error){if(Q.name==="AbortError")return"Error: timeout ao buscar pagina";return`Error: ${Q.message.slice(0,100)}`}return"Error: falha ao buscar pagina"}}function NX($,Z){let Y=OX($,Z);try{return new TextDecoder(Y).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function OX($,Z){if(Z){let z=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(z)return P8(z[1])}let Y=$.subarray(0,2048).toString("ascii"),Q=Y.match(/<meta[^>]+charset\s*=\s*["']?([^"'\s>]+)/i);if(Q)return P8(Q[1]);let J=Y.match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(J)return P8(J[1]);return"utf-8"}function FX($){let Z=$.match(/<title[^>]*>([^<]+)<\/title>/i)||$.match(/<h1[^>]*>([^<]+)<\/h1>/i)||$.match(/<meta[^>]+property="og:title"[^>]+content="([^"]+)"/i),Y=Z?T8(Z[1]):"Sem titulo",Q="",J=$.match(/<article[^>]*>([\s\S]*?)<\/article>/i);if(J)Q=J[1];if(!Q){let K=[/<div[^>]+class="[^"]*(?:article-body|post-content|entry-content|story-body|content-body|article-content|news-content|materia-corpo)[^"]*"[^>]*>([\s\S]*?)<\/div>/i,/<div[^>]+itemprop="articleBody"[^>]*>([\s\S]*?)<\/div>/i,/<main[^>]*>([\s\S]*?)<\/main>/i];for(let X of K){let V=$.match(X);if(V){Q=V[1];break}}}if(!Q){let K=[],X=/<p[^>]*>([\s\S]*?)<\/p>/gi,V;while((V=X.exec($))!==null){let G=T8(V[1]).trim();if(G.length>50)K.push(G)}Q=K.join(`
|
|
107
104
|
|
|
108
|
-
`)}else
|
|
105
|
+
`)}else Q=RX(Q);let z=Q.trim()||"Nao foi possivel extrair o conteudo do artigo.";return{title:Y,content:z}}function RX($){let Z=[],Y=/<p[^>]*>([\s\S]*?)<\/p>/gi,Q;while((Q=Y.exec($))!==null){let J=T8(Q[1]).trim();if(J.length>20)Z.push(J)}if(Z.length===0){let J=T8($).trim();if(J.length>50)return J}return Z.join(`
|
|
109
106
|
|
|
110
|
-
`)}
|
|
107
|
+
`)}p();f();f$();import{existsSync as s6,mkdirSync as EX,readFileSync as LX}from"fs";import{join as jX}from"path";import{randomUUID as DX}from"crypto";var t6="",m=[],H1=null,e6=null,$3=()=>jX(t6,"tasks.json");function Q7(){D($3(),JSON.stringify(m,null,2))}function PX(){let $=$3();if(!s6($)){m=[];return}try{m=JSON.parse(LX($,"utf-8"))}catch{m=[]}}function Z3($,Z){if(t6=$,e6=Z,!s6($))EX($,{recursive:!0});if(PX(),H1)clearInterval(H1);H1=setInterval(TX,30000),SX().catch(()=>{})}function Y3(){if(H1)clearInterval(H1),H1=null}function J7($,Z){let Y={id:wX(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(m=[...m,Y],Q7(),Z&&L)_2(Y).catch(()=>{});return Y}function z7($){let Z=$.toLowerCase(),Y=m.find((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(m=m.map((Q)=>Q.id===Y.id?{...Q,done:!0}:Q),Q7(),Y.dueAt&&L)J3(Y.id).catch(()=>{});return m.find((Q)=>Q.id===Y.id)||null}function Q3($){let Z=$.toLowerCase(),Y=m.findIndex((J)=>J.id===$||J.title.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=m[Y];if(m=[...m.slice(0,Y),...m.slice(Y+1)],Q7(),Q.dueAt&&L)J3(Q.id).catch(()=>{});return!0}function l$($=!1){return $?[...m]:m.filter((Z)=>!Z.done)}function f0($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let Q=Y.done?"[x]":"[ ]",J=Y.dueAt?` (${kX(Y.dueAt)})`:"";return` ${Q} ${Y.title}${J} [${Y.id}]`});return`Tarefas (${$.length}):
|
|
111
108
|
${Z.join(`
|
|
112
|
-
`)}`}function
|
|
109
|
+
`)}`}function W1($){let Z=new Date,Y=$.toLowerCase().trim(),Q=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(Q){let K=parseInt(Q[1]),X=Q[2].startsWith("h")?"hours":"minutes",V=new Date(Z);if(X==="hours")V.setHours(V.getHours()+K);else V.setMinutes(V.getMinutes()+K);return V}let J=new Date(Z);if(Y.includes("amanha")||Y.includes("amanh\xE3"))J.setDate(J.getDate()+1);let z=Y.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(z){let K=parseInt(z[1]),X=parseInt(z[2]||"0");if(K>=0&&K<=23&&X>=0&&X<=59){if(J.setHours(K,X,0,0),J<=Z&&!Y.includes("amanha")&&!Y.includes("amanh\xE3"))J.setDate(J.getDate()+1);return J}}return null}function TX(){let $=new Date,Z=!1;for(let Y of m){if(Y.done||Y.notified||!Y.dueAt)continue;let Q=new Date(Y.dueAt);if(isNaN(Q.getTime()))continue;let J=$.getTime()-Q.getTime();if(J>=0&&J<300000)m=m.map((z)=>z.id===Y.id?{...z,notified:!0}:z),Z=!0,IX(Y),e6?.(Y)}if(Z)Q7()}function AX($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}async function IX($){if(!L)return;try{await J0("smolerclaw - Lembrete",$.title,{timeout:1e4})}catch{}}var x2="smolerclaw-reminder-";async function _2($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${x2}${$.id}`,Q=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),J=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),K=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null;","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null;","$x = New-Object Windows.Data.Xml.Dom.XmlDocument;",`$x.LoadXml('<toast><visual><binding template=""ToastText02""><text id=""1"">smolerclaw</text><text id=""2"">${wZ(AX($.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 x$("Create",Y,["/SC","ONCE","/SD",Q,"/ST",J,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${K}"`,"/F"])}catch{}}async function J3($){let Z=`${x2}${$}`;try{await x$("Delete",Z,["/F"])}catch{}}async function SX(){if(!L)return;let $=Date.now();for(let Z of m){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if((await x$("Query",`${x2}${Z.id}`)).exitCode!==0)await _2(Z)}catch{await _2(Z)}}}function wX(){return DX().slice(0,8)}function kX($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),J=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),z=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(J.getTime()===Q.getTime())return`hoje ${z}`;let K=new Date(Q);if(K.setDate(K.getDate()+1),J.getTime()===K.getTime())return`amanha ${z}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${z}`}f();import{existsSync as z3,mkdirSync as yX,readFileSync as bX}from"fs";import{join as _X}from"path";import{randomUUID as xX}from"crypto";var K3="",G$=[],X3=()=>_X(K3,"memos.json");function V3(){D(X3(),JSON.stringify(G$,null,2))}function fX(){let $=X3();if(!z3($)){G$=[];return}try{G$=JSON.parse(bX($,"utf-8"))}catch{G$=[]}}function G3($){if(K3=$,!z3($))yX($,{recursive:!0});fX()}function K7($,Z=[]){let Y=new Date().toISOString(),Q=$.match(/#(\w+)/g)?.map((K)=>K.slice(1).toLowerCase())||[],J=[...new Set([...Z.map((K)=>K.toLowerCase()),...Q])],z={id:hX(),content:$.trim(),tags:J,createdAt:Y,updatedAt:Y};return G$=[...G$,z],V3(),z}function q3($){let Z=G$.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return G$=[...G$.slice(0,Z),...G$.slice(Z+1)],V3(),!0}function X7($){let Z=$.toLowerCase().trim();if(!Z)return[...G$];let Y=Z.startsWith("#"),Q=Y?Z.slice(1):Z;return G$.filter((J)=>{if(Y)return J.tags.some((z)=>z.includes(Q));return J.content.toLowerCase().includes(Q)||J.tags.some((z)=>z.includes(Q))}).sort((J,z)=>new Date(z.updatedAt).getTime()-new Date(J.updatedAt).getTime())}function A8($=20){return[...G$].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function vX(){let $=new Map;for(let Z of G$)for(let Y of Z.tags)$.set(Y,($.get(Y)||0)+1);return[...$.entries()].map(([Z,Y])=>({tag:Z,count:Y})).sort((Z,Y)=>Y.count-Z.count)}function v0($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((Y)=>{let Q=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.tags.length>0?` [${Y.tags.map((K)=>`#${K}`).join(" ")}]`:"",z=Y.content.length>80?Y.content.slice(0,80).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${Q}] ${z}${J} {${Y.id}}`});return`Memos (${$.length}):
|
|
113
110
|
${Z.join(`
|
|
114
|
-
`)}`}function
|
|
115
|
-
${$.map((
|
|
116
|
-
`)}`}function
|
|
117
|
-
`);try{let K=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",
|
|
118
|
-
`)}
|
|
111
|
+
`)}`}function U3(){let $=vX();if($.length===0)return"Nenhuma tag.";return`Tags:
|
|
112
|
+
${$.map((Y)=>` #${Y.tag} (${Y.count})`).join(`
|
|
113
|
+
`)}`}function hX(){return xX().slice(0,8)}p();async function V7($){if(L)return gX($);return f2($)}async function gX($){let Z=$.to.replace(/'/g,"''"),Y=$.subject.replace(/'/g,"''"),Q=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),J=$.cc?.replace(/'/g,"''")||"",z=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${Y}'`,` $mail.Body = '${Q}'`,J?` $mail.CC = '${J}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
|
|
114
|
+
`);try{let K=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",z],{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>K.kill(),15000),[V]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]);await K.exited,clearTimeout(X);let G=V.trim();if(G.includes("mailto"))return f2($);return G||"Email aberto no Outlook."}catch{return f2($)}}async function f2($){let Z=[];if($.subject)Z.push(`subject=${encodeURIComponent($.subject)}`);if($.body)Z.push(`body=${encodeURIComponent($.body)}`);if($.cc)Z.push(`cc=${encodeURIComponent($.cc)}`);let Y=`mailto:${encodeURIComponent($.to)}${Z.length?"?"+Z.join("&"):""}`;try{let Q=L?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${Y}'`]:["xdg-open",Y],J=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe"}),z=setTimeout(()=>J.kill(),1e4);return await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),await J.exited,clearTimeout(z),"Email aberto no cliente de email padrao."}catch(Q){return`Error: ${Q instanceof Error?Q.message:String(Q)}`}}function G7($){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(`
|
|
115
|
+
`)}p();f();f$();import{existsSync as U7,mkdirSync as M3,readFileSync as mX,writeFileSync as uX,unlinkSync as pX}from"fs";import{join as H7}from"path";import{randomUUID as dX}from"crypto";var v2="",x=[],cX=null,C3=()=>H7(v2,"scheduler.json"),lX="Smolerclaw_";function N3($,Z){if(v2=$,cX=Z??null,!U7($))M3($,{recursive:!0});if(aX(),L)nX().catch(()=>{})}async function W7($,Z,Y,Q,J,z){let K=rX(),X=`${lX}${K}`,V={id:K,name:$.trim(),scheduleType:Z,time:Y,dateOrDay:z,action:Q,target:J.trim(),enabled:!0,taskName:X,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};if(L)await q7(V);return x=[...x,V],B1(),V}async function B7($){let Z=$.toLowerCase(),Y=x.findIndex((J)=>J.id===$||J.name.toLowerCase().includes(Z));if(Y===-1)return!1;let Q=x[Y];if(L)await g2(Q.taskName,Q.id);return x=[...x.slice(0,Y),...x.slice(Y+1)],B1(),!0}async function M7($){let Z=E7($);if(!Z||Z.enabled)return null;if(L)await q7(Z);return x=x.map((Y)=>Y.id===Z.id?{...Y,enabled:!0,updatedAt:new Date().toISOString()}:Y),B1(),x.find((Y)=>Y.id===Z.id)??null}async function C7($){let Z=E7($);if(!Z||!Z.enabled)return null;if(L)await g2(Z.taskName,void 0);return x=x.map((Y)=>Y.id===Z.id?{...Y,enabled:!1,updatedAt:new Date().toISOString()}:Y),B1(),x.find((Y)=>Y.id===Z.id)??null}function I8($=!1){return $?[...x]:x.filter((Z)=>Z.enabled)}function O3($){return E7($)}async function N7($){let Z=E7($);if(!Z)return"Agendamento nao encontrado.";if(L){let Y=await x$("Run",Z.taskName);if(Y.exitCode!==0)return`Erro ao executar: ${Y.stderr}`}return x=x.map((Y)=>Y.id===Z.id?{...Y,lastRun:new Date().toISOString()}:Y),B1(),`Agendamento "${Z.name}" executado.`}function S8($){if($.length===0)return"Nenhum agendamento encontrado.";let Z=$.map((Y)=>{let Q=Y.enabled?"ativo":"desativado",J=sX(Y),z=Y.action==="toast"?"msg":Y.action==="command"?"cmd":"wf";return` [${Y.id}] ${Y.name} \u2014 ${J} [${z}] (${Q})`});return`Agendamentos (${$.length}):
|
|
119
116
|
${Z.join(`
|
|
120
|
-
`)}`}function
|
|
121
|
-
`)}function
|
|
117
|
+
`)}`}function h2($){let Z=[`=== ${$.name} ===`,`ID: ${$.id}`,`Tipo: ${$.scheduleType}`,`Horario: ${$.time}`];if($.dateOrDay)Z.push(`Data/Dia: ${$.dateOrDay}`);if(Z.push(`Acao: ${$.action}`,`Alvo: ${$.target}`,`Status: ${$.enabled?"ativo":"desativado"}`,`Tarefa Windows: ${$.taskName}`,`Criado: ${W3($.createdAt)}`),$.lastRun)Z.push(`Ultima execucao: ${W3($.lastRun)}`);return Z.join(`
|
|
118
|
+
`)}function O7($){let Z=$.toLowerCase().trim(),Y=Z.match(/^(\d{1,2}):(\d{2})$/);if(Y){let z=parseInt(Y[1]),K=parseInt(Y[2]);if(z>=0&&z<=23&&K>=0&&K<=59)return`${String(z).padStart(2,"0")}:${String(K).padStart(2,"0")}`}let Q=Z.match(/^(\d{1,2})h(\d{2})?$/);if(Q){let z=parseInt(Q[1]),K=parseInt(Q[2]||"0");if(z>=0&&z<=23&&K>=0&&K<=59)return`${String(z).padStart(2,"0")}:${String(K).padStart(2,"0")}`}let J=Z.match(/^(\d{1,2})(?::(\d{2}))?\s*(am|pm)$/);if(J){let z=parseInt(J[1]),K=parseInt(J[2]||"0"),X=J[3]==="pm";if(z===12)z=X?12:0;else if(X)z+=12;if(z>=0&&z<=23&&K>=0&&K<=59)return`${String(z).padStart(2,"0")}:${String(K).padStart(2,"0")}`}return null}function F7($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje"||Z==="today")return B3(Y);if(Z==="amanha"||Z==="amanh\xE3"||Z==="tomorrow"){let z=new Date(Y);return z.setDate(z.getDate()+1),B3(z)}let Q=Z.match(/^(\d{1,2})[/.-](\d{1,2})[/.-](\d{4})$/);if(Q){let z=parseInt(Q[1]),K=parseInt(Q[2]),X=parseInt(Q[3]);if(z>=1&&z<=31&&K>=1&&K<=12&&X>=2024)return`${String(K).padStart(2,"0")}/${String(z).padStart(2,"0")}/${X}`}let J=Z.match(/^(\d{1,2})[/.-](\d{1,2})$/);if(J){let z=parseInt(J[1]),K=parseInt(J[2]);if(z>=1&&z<=31&&K>=1&&K<=12)return`${String(K).padStart(2,"0")}/${String(z).padStart(2,"0")}/${Y.getFullYear()}`}return null}function R7($){let Z=$.toLowerCase().trim();return{dom:"SUN",domingo:"SUN",seg:"MON",segunda:"MON","segunda-feira":"MON",ter:"TUE",terca:"TUE","ter\xE7a":"TUE","terca-feira":"TUE","ter\xE7a-feira":"TUE",qua:"WED",quarta:"WED","quarta-feira":"WED",qui:"THU",quinta:"THU","quinta-feira":"THU",sex:"FRI",sexta:"FRI","sexta-feira":"FRI",sab:"SAT",sabado:"SAT","s\xE1bado":"SAT",sun:"SUN",sunday:"SUN",mon:"MON",monday:"MON",tue:"TUE",tuesday:"TUE",wed:"WED",wednesday:"WED",thu:"THU",thursday:"THU",fri:"FRI",friday:"FRI",sat:"SAT",saturday:"SAT"}[Z]??null}async function q7($){let Z=iX($),Y=[];switch($.scheduleType){case"once":if(Y.push("/SC","ONCE"),$.dateOrDay)Y.push("/SD",$.dateOrDay);break;case"daily":Y.push("/SC","DAILY");break;case"weekly":if(Y.push("/SC","WEEKLY"),$.dateOrDay)Y.push("/D",$.dateOrDay);break}Y.push("/ST",$.time),Y.push("/TR",Z),Y.push("/F");try{await x$("Create",$.taskName,Y)}catch{}}async function g2($,Z){try{await x$("Delete",$,["/F"])}catch{}if(Z)oX(Z)}function F3(){let $=H7(v2,"scripts");if(!U7($))M3($,{recursive:!0});return $}function H3($,Z,Y){let Q=F3(),J=H7(Q,`toast_${$}.ps1`),z=`# Toast notification script for smolerclaw
|
|
122
119
|
# Job ID: ${$}
|
|
123
120
|
# Generated: ${new Date().toISOString()}
|
|
124
121
|
|
|
@@ -126,7 +123,7 @@ ${Z.join(`
|
|
|
126
123
|
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
|
|
127
124
|
|
|
128
125
|
$title = '${Z.replace(/'/g,"''")}'
|
|
129
|
-
$body = '${
|
|
126
|
+
$body = '${Y.replace(/'/g,"''")}'
|
|
130
127
|
|
|
131
128
|
$template = @"
|
|
132
129
|
<toast>
|
|
@@ -144,55 +141,80 @@ $xml = New-Object Windows.Data.Xml.Dom.XmlDocument
|
|
|
144
141
|
$xml.LoadXml($template)
|
|
145
142
|
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
|
|
146
143
|
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('smolerclaw').Show($toast)
|
|
147
|
-
`,K=Buffer.from([239,187,191]),
|
|
148
|
-
`)}function
|
|
149
|
-
${Z.map((
|
|
150
|
-
`)}`}function
|
|
144
|
+
`,K=Buffer.from([239,187,191]),X=Buffer.concat([K,Buffer.from(z,"utf-8")]);return uX(J,X),J}function oX($){let Z=H7(F3(),`toast_${$}.ps1`);try{if(U7(Z))pX(Z)}catch{}}function iX($){if($.action==="toast")return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${H3($.id,"smolerclaw",$.target)}"`;else if($.action==="command")return $.target;else return`powershell -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File "${H3($.id,"smolerclaw",`Workflow: ${$.target}`)}"`}async function nX(){if(!L)return;for(let $ of x){if(!$.enabled)continue;try{if((await x$("Query",$.taskName)).exitCode!==0)await q7($)}catch{await q7($)}}}function R3(){}async function E3(){let $=0;for(let Z of x){if(L)await g2(Z.taskName,Z.id);$++}return x=[],B1(),`${$} agendamento(s) removido(s).`}function aX(){let $=C3();if(!U7($)){x=[];return}try{x=JSON.parse(mX($,"utf-8"))}catch{x=[]}}function B1(){D(C3(),JSON.stringify(x,null,2))}function rX(){return dX().slice(0,8)}function E7($){let Z=$.toLowerCase();return x.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))??null}function sX($){switch($.scheduleType){case"once":return $.dateOrDay?`${$.dateOrDay} ${$.time}`:`uma vez ${$.time}`;case"daily":return`diario ${$.time}`;case"weekly":return $.dateOrDay?`${tX($.dateOrDay)} ${$.time}`:`semanal ${$.time}`}}function tX($){return{SUN:"dom",MON:"seg",TUE:"ter",WED:"qua",THU:"qui",FRI:"sex",SAT:"sab"}[$]??$}function W3($){try{return new Date($).toLocaleString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}catch{return $}}function B3($){return[String($.getMonth()+1).padStart(2,"0"),String($.getDate()).padStart(2,"0"),String($.getFullYear())].join("/")}f();import{existsSync as j3,mkdirSync as eX,readFileSync as $V}from"fs";import{join as ZV}from"path";import{randomUUID as YV}from"crypto";var D3="",C0=[],P3=()=>ZV(D3,"finance.json");function QV(){D(P3(),JSON.stringify(C0,null,2))}function JV(){let $=P3();if(!j3($)){C0=[];return}try{C0=JSON.parse($V($,"utf-8"))}catch{C0=[]}}function T3($){if(D3=$,!j3($))eX($,{recursive:!0});JV()}function w8($,Z,Y,Q){let J={id:zV(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:Q.trim(),date:new Date().toISOString()};return C0=[...C0,J],QV(),J}function L7($,Z){let Y=new Date,Q=$||Y.getFullYear(),J=Z!==void 0?Z:Y.getMonth(),z=C0.filter((U)=>{let W=new Date(U.date);return W.getFullYear()===Q&&W.getMonth()===J});if(z.length===0)return`Nenhuma transacao em ${L3(J)}/${Q}.`;let K=z.filter((U)=>U.type==="entrada").reduce((U,W)=>U+W.amount,0),X=z.filter((U)=>U.type==="saida").reduce((U,W)=>U+W.amount,0),V=K-X,G=new Map;for(let U of z.filter((W)=>W.type==="saida"))G.set(U.category,(G.get(U.category)||0)+U.amount);let q=[`--- Resumo ${L3(J)}/${Q} ---`,`Entradas: R$ ${K.toFixed(2)}`,`Saidas: R$ ${X.toFixed(2)}`,`Saldo: R$ ${V.toFixed(2)} ${V>=0?"":"(NEGATIVO)"}`];if(G.size>0){q.push(""),q.push("Saidas por categoria:");let U=[...G.entries()].sort((W,B)=>B[1]-W[1]);for(let[W,B]of U){let M=X>0?Math.round(B/X*100):0;q.push(` ${W.padEnd(15)} R$ ${B.toFixed(2)} (${M}%)`)}}return q.join(`
|
|
145
|
+
`)}function m2($=10){let Z=[...C0].sort((Q,J)=>new Date(J.date).getTime()-new Date(Q.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
|
|
146
|
+
${Z.map((Q)=>{let J=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=Q.type==="entrada"?"+":"-";return` [${J}] ${z} R$ ${Q.amount.toFixed(2)} ${Q.category} \u2014 ${Q.description} [${Q.id}]`}).join(`
|
|
147
|
+
`)}`}function zV(){return YV().slice(0,8)}function L3($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}f();import{existsSync as A3,mkdirSync as KV,readFileSync as XV}from"fs";import{join as VV}from"path";import{randomUUID as GV}from"crypto";var I3="",N0=[],S3=()=>VV(I3,"decisions.json");function qV(){D(S3(),JSON.stringify(N0,null,2))}function UV(){let $=S3();if(!A3($)){N0=[];return}try{N0=JSON.parse(XV($,"utf-8"))}catch{N0=[]}}function w3($){if(I3=$,!A3($))KV($,{recursive:!0});UV()}function k3($,Z,Y,Q,J=[]){let z={id:HV(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:Q?.trim(),tags:J.map((K)=>K.toLowerCase()),date:new Date().toISOString()};return N0=[...N0,z],qV(),z}function h0($){let Z=$.toLowerCase();return N0.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.chosen.toLowerCase().includes(Z)||Y.context.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))).sort((Y,Q)=>new Date(Q.date).getTime()-new Date(Y.date).getTime())}function j7($=15){return[...N0].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function M1($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((Y)=>{let Q=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` [${Q}] ${Y.title}${J} {${Y.id}}`});return`Decisoes (${$.length}):
|
|
151
148
|
${Z.join(`
|
|
152
|
-
`)}`}function
|
|
149
|
+
`)}`}function HV(){return GV().slice(0,8)}y8();f();import{existsSync as h3,mkdirSync as FV,readFileSync as RV}from"fs";import{join as EV}from"path";import{randomUUID as LV}from"crypto";var g3="",S={people:[],interactions:[],delegations:[]},m3=()=>EV(g3,"people.json");function T7(){D(m3(),JSON.stringify(S,null,2))}function jV(){let $=m3();if(!h3($)){S={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(RV($,"utf-8"));S={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{S={people:[],interactions:[],delegations:[]}}}function u3($){if(g3=$,!h3($))FV($,{recursive:!0});jV()}function A7($,Z,Y,Q){let J={id:e2(),name:$.trim(),group:Z,role:Y?.trim(),contact:Q?.trim(),createdAt:new Date().toISOString()};return S={...S,people:[...S.people,J]},T7(),J}function o$($){let Z=$.toLowerCase();return S.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function I7($){if($)return S.people.filter((Z)=>Z.group===$);return[...S.people]}function p3($,Z,Y,Q){let J=o$($);if(!J)return null;let z={id:e2(),personId:J.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:Q?.toISOString(),followUpDone:!1};return S={...S,interactions:[...S.interactions,z]},T7(),z}function DV($,Z=10){let Y=o$($);if(!Y)return[];return[...S.interactions].filter((Q)=>Q.personId===Y.id).reverse().sort((Q,J)=>new Date(J.date).getTime()-new Date(Q.date).getTime()).slice(0,Z)}function C1(){let $=new Date,Z=[];for(let Y of S.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let Q=new Date(Y.followUpDate);if(isNaN(Q.getTime()))continue;if(Q<=$){let J=S.people.find((z)=>z.id===Y.personId);if(J)Z.push({person:J,interaction:Y})}}return Z.sort((Y,Q)=>new Date(Y.interaction.followUpDate).getTime()-new Date(Q.interaction.followUpDate).getTime())}function S7($,Z,Y){let Q=o$($);if(!Q)return null;let J={id:e2(),personId:Q.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return S={...S,delegations:[...S.delegations,J]},T7(),J}function d3($,Z,Y){if(!S.delegations.find((J)=>J.id===$))return null;return S={...S,delegations:S.delegations.map((J)=>J.id===$?{...J,status:Z,notes:Y||J.notes}:J)},T7(),S.delegations.find((J)=>J.id===$)||null}function g0($,Z=!0){let Y=[...S.delegations];if($){let J=o$($);if(!J)return[];Y=Y.filter((z)=>z.personId===J.id)}if(Z)Y=Y.filter((J)=>J.status!=="concluido");let Q=new Date;return Y=Y.map((J)=>{if(J.status==="pendente"&&J.dueDate){let z=new Date(J.dueDate);if(!isNaN(z.getTime())&&z<Q)return{...J,status:"atrasado"}}return J}),Y.sort((J,z)=>{if(J.status==="atrasado"&&z.status!=="atrasado")return-1;if(z.status==="atrasado"&&J.status!=="atrasado")return 1;let K=J.dueDate?new Date(J.dueDate).getTime():1/0,X=z.dueDate?new Date(z.dueDate).getTime():1/0;return K-X})}var c3={equipe:"Equipe",familia:"Familia",contato:"Contato"};function w7($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let J of $){let z=Z.get(J.group)||[];Z.set(J.group,[...z,J])}let Y=[],Q=["equipe","familia","contato"];for(let J of Q){let z=Z.get(J);if(!z?.length)continue;let K=z.map((X)=>{let V=X.role?` (${X.role})`:"",G=X.contact?` \u2014 ${X.contact}`:"";return` ${X.name}${V}${G} [${X.id}]`});Y.push(`--- ${c3[J]} ---
|
|
153
150
|
${K.join(`
|
|
154
|
-
`)}`)}return
|
|
151
|
+
`)}`)}return Y.join(`
|
|
155
152
|
|
|
156
|
-
`)}function
|
|
157
|
-
Interacoes recentes:`);for(let J of
|
|
158
|
-
Tarefas delegadas:`);for(let J of
|
|
159
|
-
`)}function
|
|
153
|
+
`)}function k7($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${c3[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=DV($.id,5);if(Y.length>0){Z.push(`
|
|
154
|
+
Interacoes recentes:`);for(let J of Y){let z=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${z}] ${J.type}: ${J.summary}`)}}let Q=g0($.id);if(Q.length>0){Z.push(`
|
|
155
|
+
Tarefas delegadas:`);for(let J of Q){let z=J.status==="atrasado"?"!!":J.status==="em_andamento"?">>":" ",K=J.dueDate?` (${$9(J.dueDate)})`:"";Z.push(` ${z} ${J.task}${K} [${J.status}]`)}}return Z.join(`
|
|
156
|
+
`)}function y7($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let J=S.people.find((X)=>X.id===Y.personId)?.name||"?",z=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",K=Y.dueDate?` (${$9(Y.dueDate)})`:"";return`${z}${J}: ${Y.task}${K} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
|
|
160
157
|
${Z.join(`
|
|
161
|
-
`)}`}function
|
|
158
|
+
`)}`}function b7($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:Q})=>{return` [${$9(Q.followUpDate)}] ${Y.name}: ${Q.summary} [${Q.id}]`});return`Follow-ups pendentes (${$.length}):
|
|
162
159
|
${Z.join(`
|
|
163
|
-
`)}`}function
|
|
164
|
-
`);let Z=
|
|
165
|
-
!! ${J.length} follow-up(s) pendente(s):`);for(let{person:
|
|
166
|
-
!! ${K.length} delegacao(oes) atrasada(s):`);for(let
|
|
167
|
-
${
|
|
168
|
-
Ultimas interacoes:`);for(let
|
|
160
|
+
`)}`}function l3(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
|
|
161
|
+
`);let Z=S.people.filter((G)=>G.group==="equipe").length,Y=S.people.filter((G)=>G.group==="familia").length,Q=S.people.filter((G)=>G.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${Q}`);let J=C1();if(J.length>0){$.push(`
|
|
162
|
+
!! ${J.length} follow-up(s) pendente(s):`);for(let{person:G,interaction:q}of J.slice(0,5))$.push(` ${G.name}: ${q.summary}`)}let z=g0(),K=z.filter((G)=>G.status==="atrasado"),X=z.filter((G)=>G.status==="pendente"||G.status==="em_andamento");if(K.length>0){$.push(`
|
|
163
|
+
!! ${K.length} delegacao(oes) atrasada(s):`);for(let G of K.slice(0,5)){let q=S.people.find((U)=>U.id===G.personId);$.push(` ${q?.name}: ${G.task}`)}}if(X.length>0)$.push(`
|
|
164
|
+
${X.length} delegacao(oes) em andamento`);let V=[...S.interactions].sort((G,q)=>new Date(q.date).getTime()-new Date(G.date).getTime()).slice(0,3);if(V.length>0){$.push(`
|
|
165
|
+
Ultimas interacoes:`);for(let G of V){let q=S.people.find((W)=>W.id===G.personId),U=new Date(G.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${U}] ${q?.name}: ${G.summary}`)}}return $.push(`
|
|
169
166
|
========================`),$.join(`
|
|
170
|
-
`)}function
|
|
171
|
-
[${
|
|
172
|
-
`)}function
|
|
167
|
+
`)}function e2(){return LV().slice(0,8)}function $9($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,Q=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),J=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(J.getTime()===Q.getTime())return"hoje";let z=new Date(Q);if(z.setDate(z.getDate()+1),J.getTime()===z.getTime())return"amanha";let K=Math.floor((J.getTime()-Q.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"})}f();import{existsSync as o3,mkdirSync as PV,readFileSync as TV}from"fs";import{join as AV}from"path";import{randomUUID as IV}from"crypto";var i3="",u=[],n3=()=>AV(i3,"materials.json");function Z9(){D(n3(),JSON.stringify(u,null,2))}function SV(){let $=n3();if(!o3($)){u=[];return}try{u=JSON.parse(TV($,"utf-8"))}catch{u=[]}}function a3($){if(i3=$,!o3($))PV($,{recursive:!0});SV()}function _7($,Z,Y="geral",Q=[]){let J=new Date().toISOString(),z=Z.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=$.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=[...new Set([...Q.map((G)=>G.toLowerCase()),...z,...K])],V={id:wV(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:X,createdAt:J,updatedAt:J};return u=[...u,V],Z9(),V}function r3($,Z){let Y=u.find((G)=>G.id===$);if(!Y)return null;let Q=Z.content??Y.content,J=Z.title??Y.title,z=Q.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],K=J.match(/#(\w+)/g)?.map((G)=>G.slice(1).toLowerCase())||[],X=Z.tags??Y.tags,V=[...new Set([...X.map((G)=>G.toLowerCase()),...z,...K])];return u=u.map((G)=>G.id===$?{...G,title:J.trim(),content:Q.trim(),category:(Z.category??G.category).toLowerCase().trim(),tags:V,updatedAt:new Date().toISOString()}:G),Z9(),u.find((G)=>G.id===$)||null}function x7($){let Z=u.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return u=[...u.slice(0,Z),...u.slice(Z+1)],Z9(),!0}function s3($){return u.find((Z)=>Z.id===$)||null}function N1($){let Z=$.toLowerCase().trim();if(!Z)return[...u];let Y=Z.startsWith("#"),Q=Z.startsWith("@"),J=Y||Q?Z.slice(1):Z;return u.filter((z)=>{if(Y)return z.tags.some((K)=>K.includes(J));if(Q)return z.category.includes(J);return z.title.toLowerCase().includes(J)||z.content.toLowerCase().includes(J)||z.category.toLowerCase().includes(J)||z.tags.some((K)=>K.includes(J))}).sort((z,K)=>new Date(K.updatedAt).getTime()-new Date(z.updatedAt).getTime())}function O1($=30,Z){let Y=[...u];if(Z){let Q=Z.toLowerCase().trim();Y=Y.filter((J)=>J.category===Q)}return Y.sort((Q,J)=>new Date(J.updatedAt).getTime()-new Date(Q.updatedAt).getTime()).slice(0,$)}function t3(){let $=new Map;for(let Z of u)$.set(Z.category,($.get(Z.category)||0)+1);return[...$.entries()].map(([Z,Y])=>({category:Z,count:Y})).sort((Z,Y)=>Y.count-Z.count)}function e3(){if(u.length===0)return"";let $=t3(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let Q=u.filter((J)=>J.category===Y).sort((J,z)=>new Date(z.updatedAt).getTime()-new Date(J.updatedAt).getTime());Z.push(`
|
|
168
|
+
[${Y}]`);for(let J of Q){let z=J.content.length>200?J.content.slice(0,200).replace(/\n/g," ")+"...":J.content.replace(/\n/g," "),K=J.tags.length>0?` [${J.tags.map((X)=>`#${X}`).join(" ")}]`:"";Z.push(` \u2022 ${J.title}: ${z}${K}`)}}return Z.join(`
|
|
169
|
+
`)}function O0($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((Y)=>{let Q=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.tags.length>0?` [${Y.tags.map((K)=>`#${K}`).join(" ")}]`:"",z=Y.content.length>60?Y.content.slice(0,60).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${Q}] (${Y.category}) ${Y.title} \u2014 ${z}${J} {${Y.id}}`});return`Materiais (${$.length}):
|
|
173
170
|
${Z.join(`
|
|
174
|
-
`)}`}function
|
|
171
|
+
`)}`}function $Y($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),Y=new Date($.updatedAt).toLocaleDateString("pt-BR"),Q=$.tags.length>0?`Tags: ${$.tags.map((z)=>`#${z}`).join(" ")}`:"",J=Z===Y?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${Y}`;return`--- Material {${$.id}} ---
|
|
175
172
|
Titulo: ${$.title}
|
|
176
173
|
Categoria: ${$.category}
|
|
177
174
|
|
|
178
175
|
${$.content}
|
|
179
176
|
|
|
180
|
-
${
|
|
181
|
-
${J}`}function
|
|
182
|
-
${$.map((
|
|
183
|
-
`)}`}function
|
|
184
|
-
${K}
|
|
177
|
+
${Q}
|
|
178
|
+
${J}`}function ZY(){let $=t3();if($.length===0)return"Nenhuma categoria.";return`Categorias:
|
|
179
|
+
${$.map((Y)=>` @${Y.category} (${Y.count})`).join(`
|
|
180
|
+
`)}`}function wV(){return IV().slice(0,8)}f();import{existsSync as L$,mkdirSync as kV,readFileSync as v7}from"fs";import{join as q$,basename as yV}from"path";import{randomUUID as bV}from"crypto";var F1="",D$=[],j$=[],w$=[],F0=null,YY=()=>q$(F1,"projects.json"),QY=()=>q$(F1,"work-sessions.json"),JY=()=>q$(F1,"opportunities.json"),zY=()=>q$(F1,"active-project.txt");function _V(){D(YY(),JSON.stringify(D$,null,2))}function Q9(){D(QY(),JSON.stringify(j$,null,2))}function KY(){D(JY(),JSON.stringify(w$,null,2))}function xV(){D(zY(),F0||"")}function fV(){D$=Y9(YY,[]),j$=Y9(QY,[]),w$=Y9(JY,[]);let $=zY();if(L$($))try{F0=v7($,"utf-8").trim()||null}catch{F0=null}}function Y9($,Z){let Y=$();if(!L$(Y))return Z;try{return JSON.parse(v7(Y,"utf-8"))}catch(Q){if(process.env.DEBUG)console.error(`[projects] Failed to load ${Y}: ${Q instanceof Error?Q.message:Q}`);return Z}}function XY($){if(F1=$,!L$($))kV($,{recursive:!0});fV()}function J9($,Z,Y="",Q=[],J=[]){let z={id:z9(),name:$.trim(),path:Z.trim(),description:Y.trim(),tags:Q.map((K)=>K.trim().toLowerCase()).filter(Boolean),techStack:J.map((K)=>K.trim().toLowerCase()).filter(Boolean),createdAt:new Date().toISOString(),active:!0};return D$=[...D$,z],_V(),z}function h7($){let Z=$.toLowerCase().trim();return D$.find((Y)=>Y.id===$)||D$.find((Y)=>Y.name.toLowerCase()===Z)||D$.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function R1($=!1){return($?D$.filter((Y)=>Y.active):[...D$]).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function E1($){let Z=h7($);if(!Z)return null;return F0=Z.id,xV(),Z}function R0(){if(!F0)return null;return D$.find(($)=>$.id===F0)||null}function g7($,Z=""){if(!D$.find((J)=>J.id===$))return null;vV($);let Q={id:z9(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return j$=[...j$,Q],Q9(),Q}function m7($,Z){let Y=j$.find((K)=>K.id===$);if(!Y||Y.endedAt)return null;let Q=new Date,J=new Date(Y.startedAt),z=Math.round((Q.getTime()-J.getTime())/60000);return j$=j$.map((K)=>K.id===$?{...K,endedAt:Q.toISOString(),durationMinutes:z,notes:Z?`${K.notes}
|
|
181
|
+
${Z}`.trim():K.notes}:K),Q9(),j$.find((K)=>K.id===$)||null}function vV($){let Z=new Date;j$=j$.map((Y)=>{if(Y.projectId===$&&!Y.endedAt){let Q=new Date(Y.startedAt),J=Math.round((Z.getTime()-Q.getTime())/60000);return{...Y,endedAt:Z.toISOString(),durationMinutes:J}}return Y}),Q9()}function E0($){return j$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function hV($,Z,Y){let Q=Y||new Date;return j$.filter((J)=>{if(J.projectId!==$)return!1;let z=new Date(J.startedAt);return z>=Z&&z<=Q})}async function gV($,Z="1 day ago"){if(!L$(q$($,".git")))return null;try{let Y=await f7(["git","log",`--since=${Z}`,"--format=%an|||%s","--no-merges"],$);if(!Y.ok||!Y.stdout.trim())return{commits:0,authors:[],filesChanged:0,insertions:0,deletions:0,topFiles:[],messages:[]};let Q=Y.stdout.trim().split(`
|
|
182
|
+
`).filter(Boolean),J=[...new Set(Q.map((M)=>M.split("|||")[0]))],z=Q.map((M)=>M.split("|||")[1]||"").filter(Boolean),K=await f7(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),X=await f7(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),V=0,G=0,q=0;if(X.ok&&X.stdout.trim())for(let M of X.stdout.trim().split(`
|
|
183
|
+
`)){let O=M.match(/(\d+)\s+files?\s+changed/),R=M.match(/(\d+)\s+insertions?/),P=M.match(/(\d+)\s+deletions?/);if(O)V+=parseInt(O[1]);if(R)G+=parseInt(R[1]);if(P)q+=parseInt(P[1])}let U=await f7(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),W=new Map;if(U.ok&&U.stdout.trim())for(let M of U.stdout.trim().split(`
|
|
184
|
+
`).filter(Boolean))W.set(M,(W.get(M)||0)+1);let B=[...W.entries()].sort((M,O)=>O[1]-M[1]).slice(0,10).map(([M])=>M);return{commits:Q.length,authors:J,filesChanged:V,insertions:G,deletions:q,topFiles:B,messages:z}}catch{return null}}async function f7($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Q,J]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),z=await Y.exited;return{stdout:Q.trim(),stderr:J.trim(),ok:z===0}}function VY($,Z,Y,Q=[],J="media",z=null){let K=new Date().toISOString(),X={id:z9(),title:$.trim(),description:Z.trim(),source:Y.trim(),techRequired:Q.map((V)=>V.toLowerCase()),priority:J,status:"nova",deadline:z,createdAt:K,updatedAt:K};return w$=[...w$,X],KY(),X}function GY($,Z){if(!w$.find((Q)=>Q.id===$))return null;return w$=w$.map((Q)=>Q.id===$?{...Q,status:Z,updatedAt:new Date().toISOString()}:Q),KY(),w$.find((Q)=>Q.id===$)||null}function u7($,Z){let Y=[...w$];if($)Y=Y.filter((Q)=>Q.status===$);if(Z&&Z.length>0){let Q=Z.map((J)=>J.toLowerCase());Y=Y.filter((J)=>J.techRequired.some((z)=>Q.includes(z)))}return Y.sort((Q,J)=>{let z={alta:3,media:2,baixa:1};return(z[J.priority]||0)-(z[Q.priority]||0)})}async function p7($,Z="today",Y="pt"){let Q=h7($);if(!Q)return null;let z=new Date(new Date);switch(Z){case"today":z.setHours(0,0,0,0);break;case"week":z.setDate(z.getDate()-7);break;case"month":z.setDate(z.getDate()-30);break}let K=Z==="today"?"1 day ago":Z==="week"?"7 days ago":"30 days ago",X=await gV(Q.path,K),V=hV(Q.id,z),G=V.reduce((W,B)=>W+B.durationMinutes,0),q=0;try{let W=q$(F1,"tasks.json");if(L$(W))q=JSON.parse(v7(W,"utf-8")).filter((M)=>{if(!M.done)return!1;return new Date(M.createdAt)>=z}).length}catch{}let U=mV(Q,Z,X,V,G,q,Y);return{project:Q,period:Z,gitSummary:X,sessions:V,totalMinutes:G,completedTasks:q,markdown:U}}function mV($,Z,Y,Q,J,z,K){let X=K==="pt",V=[],G=new Date,q=G.toLocaleDateString(X?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(V.push(`# ${X?"Relatorio de Progresso":"Work Progress Report"}`),V.push(`**${X?"Projeto":"Project"}:** ${$.name}`),V.push(`**${X?"Periodo":"Period"}:** ${Z} (${q})`),V.push(`**${X?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)V.push(`**Tech:** ${$.techStack.join(", ")}`);V.push("");let U=Math.floor(J/60),W=J%60;if(V.push(`## ${X?"Tempo Trabalhado":"Time Tracked"}`),V.push(`- **${X?"Total":"Total"}:** ${U}h ${W}m`),V.push(`- **${X?"Sessoes":"Sessions"}:** ${Q.length}`),z>0)V.push(`- **${X?"Tarefas concluidas":"Tasks completed"}:** ${z}`);if(V.push(""),Y&&Y.commits>0){if(V.push(`## ${X?"Atividade Git":"Git Activity"}`),V.push(`- **Commits:** ${Y.commits}`),Y.authors.length>0)V.push(`- **${X?"Autores":"Authors"}:** ${Y.authors.join(", ")}`);if(V.push(`- **${X?"Arquivos alterados":"Files changed"}:** ${Y.filesChanged}`),V.push(`- **${X?"Linhas":"Lines"}:** +${Y.insertions} / -${Y.deletions}`),Y.messages.length>0){V.push(""),V.push(`### ${X?"Commits recentes":"Recent commits"}`);for(let B of Y.messages.slice(0,15))V.push(`- ${B}`)}if(Y.topFiles.length>0){V.push(""),V.push(`### ${X?"Arquivos mais alterados":"Most changed files"}`);for(let B of Y.topFiles.slice(0,8))V.push(`- \`${B}\``)}V.push("")}else V.push(`## ${X?"Atividade Git":"Git Activity"}`),V.push(X?"_Nenhum commit no periodo._":"_No commits in this period._"),V.push("");if(Q.length>0){V.push(`## ${X?"Sessoes de Trabalho":"Work Sessions"}`);for(let B of Q){let M=new Date(B.startedAt).toLocaleTimeString(X?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),O=B.durationMinutes>0?`${B.durationMinutes}m`:X?"em andamento":"ongoing",R=B.notes?` \u2014 ${B.notes}`:"";V.push(`- ${M} (${O})${R}`)}V.push("")}return V.push("---"),V.push(X?`_Gerado por smolerclaw em ${G.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${G.toLocaleString("en-US")}_`),V.join(`
|
|
185
|
+
`)}function d7($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let Q=Y.id===F0?" [ATIVO]":"",J=Y.active?"":" (inativo)",z=Y.techStack.length>0?` [${Y.techStack.join(", ")}]`:"";return` ${Y.name}${Q}${J}${z} \u2014 ${Y.path} {${Y.id}}`});return`Projetos (${$.length}):
|
|
186
|
+
${Z.join(`
|
|
187
|
+
`)}`}function c7($){let Z=$.id===F0?" [ATIVO]":"",Y=[`--- Projeto {${$.id}}${Z} ---`,`Nome: ${$.name}`,`Caminho: ${$.path}`];if($.description)Y.push(`Descricao: ${$.description}`);if($.techStack.length>0)Y.push(`Tech: ${$.techStack.join(", ")}`);if($.tags.length>0)Y.push(`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`);Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(`Status: ${$.active?"ativo":"inativo"}`);let Q=E0($.id);if(Q){let J=new Date(Q.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Y.push(`Sessao aberta: desde ${J}`)}return Y.join(`
|
|
188
|
+
`)}function l7($){if($.length===0)return"Nenhuma oportunidade encontrada.";let Z=$.map((Y)=>{let Q={alta:"!!!",media:"!!",baixa:"!"}[Y.priority],J=Y.techRequired.length>0?` [${Y.techRequired.join(", ")}]`:"",z=Y.deadline?` \u2014 prazo: ${Y.deadline}`:"";return` ${Q} (${Y.status}) ${Y.title}${J}${z} \u2014 ${Y.source} {${Y.id}}`});return`Oportunidades (${$.length}):
|
|
189
|
+
${Z.join(`
|
|
190
|
+
`)}`}function o7(){let $=R0();if(!$)return"";let Z=E0($.id),Y=w$.filter((J)=>J.status==="nova").length,Q=["--- Projetos ---"];if(Q.push(`Projeto ativo: ${$.name} (${$.path})`),Z){let J=new Date(Z.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Q.push(`Sessao aberta desde ${J}`)}if(Y>0)Q.push(`${Y} oportunidade(s) nova(s) pendente(s)`);return Q.join(`
|
|
191
|
+
`)}function i7($){let Z=D$.find((J)=>J.path===$);if(Z)return Z;if(!L$(q$($,".git")))return null;let Y=[];if(L$(q$($,"package.json")))try{let J=JSON.parse(v7(q$($,"package.json"),"utf-8"));if(J.dependencies?.typescript||J.devDependencies?.typescript)Y.push("typescript");if(J.dependencies?.react)Y.push("react");if(J.dependencies?.next)Y.push("nextjs");if(J.dependencies?.vue)Y.push("vue");if(L$(q$($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(L$(q$($,"Cargo.toml")))Y.push("rust");if(L$(q$($,"go.mod")))Y.push("go");if(L$(q$($,"requirements.txt"))||L$(q$($,"pyproject.toml")))Y.push("python");let Q=yV($);return J9(Q,$,"",[],Y)}function z9(){return bV().slice(0,8)}f();p();import{existsSync as V9,mkdirSync as uV,readFileSync as HY}from"fs";import{join as WY,basename as pV}from"path";var BY=2,MY="pitwall-baselines.json",dV=0.1,cV=0.05,lV=5000000,oV=512000,qY=2048,iV=120000,r7="",i=[];function CY($){if(r7=$,!V9($))uV($,{recursive:!0});ZG()}async function UY($,Z){let Q=[...t0(),$],J=process.cpuUsage(),z=Bun.nanoseconds(),K=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe",cwd:Z}),X=setTimeout(()=>K.kill(),iV),V=K.pid,G=nV(V),[,q]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]),U=await K.exited;clearTimeout(X);let W=Bun.nanoseconds(),B=process.cpuUsage(J),M=await G,O=q.length>qY?`...${q.slice(-qY)}`:q;return{durationNs:W-z,peakMemoryBytes:M,cpuUserUs:B.user,cpuSystemUs:B.system,exitCode:U,stderr:O.trim()}}async function G9($,Z={}){let Y=Z.cwd||process.cwd(),Q=Math.min(Math.max(Z.iterations||1,1),10),J=Z.scriptKey||$G($);if(Z.warmup&&Q>1)await UY($,Y);let z=[];for(let q=0;q<Q;q++)z.push(await UY($,Y));let K=z[z.length-1],X=z.map((q)=>q.durationNs),V={durationNs:K9(X),peakMemoryBytes:Math.max(...z.map((q)=>q.peakMemoryBytes)),cpuUserUs:K9(z.map((q)=>q.cpuUserUs)),cpuSystemUs:K9(z.map((q)=>q.cpuSystemUs))},G=Q>1?{min:Math.min(...X),max:Math.max(...X),median:V.durationNs,stddev:eV(X)}:null;return{scriptKey:J,command:$,metrics:V,spread:G,exitCode:K.exitCode,stderr:K.stderr,timestamp:new Date().toISOString(),iterations:Q}}async function nV($){try{if(L){let Z=`(Get-Process -Id ${$} -ErrorAction SilentlyContinue).PeakWorkingSet64`,Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>Y.kill(),5000),J=await new Response(Y.stdout).text();await Y.exited,clearTimeout(Q);let z=parseInt(J.trim(),10);if(!isNaN(z)&&z>0)return z}else{let Z=`/proc/${$}/status`;if(V9(Z)){let Q=HY(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Q)return parseInt(Q[1],10)*1024}}}catch{}return process.memoryUsage().rss}function NY($,Z=[]){let Y=i.find((z)=>z.scriptKey===$.scriptKey),Q=new Date().toISOString();if(Y){let z=Y.runs+1,K={durationNs:Math.round((Y.metrics.durationNs*Y.runs+$.metrics.durationNs)/z),peakMemoryBytes:Math.round((Y.metrics.peakMemoryBytes*Y.runs+$.metrics.peakMemoryBytes)/z),cpuUserUs:Math.round((Y.metrics.cpuUserUs*Y.runs+$.metrics.cpuUserUs)/z),cpuSystemUs:Math.round((Y.metrics.cpuSystemUs*Y.runs+$.metrics.cpuSystemUs)/z)},X={...Y,metrics:K,spread:$.spread||Y.spread,updatedAt:Q,runs:z,tags:[...new Set([...Y.tags,...Z])]};return i=i.map((V)=>V.scriptKey===$.scriptKey?X:V),s7(),X}let J={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Q,updatedAt:Q,runs:1,tags:Z};return i=[...i,J],s7(),J}function aV($){return i.find((Z)=>Z.scriptKey===$)||null}function OY(){return[...i].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function q9($){let Z=i.findIndex((Y)=>Y.scriptKey===$);if(Z===-1)return!1;return i=[...i.slice(0,Z),...i.slice(Z+1)],s7(),!0}function FY($,Z=[]){q9($.scriptKey);let Y=new Date().toISOString(),Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return i=[...i,Q],s7(),Q}function U9($){let Z=aV($.scriptKey),Y=[];if(Z)Y.push(n7("duration",Z.metrics.durationNs,$.metrics.durationNs,lV),n7("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,oV),n7("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),n7("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Q=Y.some((z)=>z.severity==="regression"),J=tV($,Z,Y,Q);return{run:$,baseline:Z,alerts:Y,hasRegression:Q,markdown:J}}function n7($,Z,Y,Q){let J=Y-Z;if(Z===0||Math.abs(J)<Q)return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:0,absoluteDelta:J,severity:"ok"};let z=J/Z,K="ok";if(z>dV)K="regression";else if(z>cV)K="warning";return{metric:$,baselineValue:Z,currentValue:Y,deltaPercent:Math.round(z*1e4)/100,absoluteDelta:J,severity:K}}function i$($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function X9($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function a7($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function rV($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function sV($){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 tV($,Z,Y,Q){let J=[];if(Q)J.push("=== PIT WALL: REGRESSAO DETECTADA ===");else J.push("=== Pit Wall: Relatorio de Performance ===");if(J.push(`Script: ${$.scriptKey}`),J.push(`Comando: ${$.command}`),J.push(`Execucoes: ${$.iterations}`),$.exitCode!==0)J.push(`Exit code: ${$.exitCode} (FALHA)`);if(J.push(""),J.push("--- Metricas Atuais ---"),J.push(` Duracao: ${i$($.metrics.durationNs)}`),J.push(` Memoria: ${X9($.metrics.peakMemoryBytes)}`),J.push(` CPU (user): ${a7($.metrics.cpuUserUs)}`),J.push(` CPU (sys): ${a7($.metrics.cpuSystemUs)}`),$.spread){J.push(""),J.push("--- Dispersao ---"),J.push(` Min: ${i$($.spread.min)}`),J.push(` Max: ${i$($.spread.max)}`),J.push(` Mediana: ${i$($.spread.median)}`),J.push(` Stddev: ${i$($.spread.stddev)}`);let z=$.spread.median>0?($.spread.stddev/$.spread.median*100).toFixed(1):"0";if(J.push(` CV: ${z}%`),parseFloat(z)>15)J.push(" (!) Alta variancia \u2014 resultados podem ser inst\xE1veis")}if($.exitCode!==0&&$.stderr)J.push(""),J.push("--- Stderr ---"),J.push($.stderr.slice(0,500));if(J.push(""),!Z)return J.push("Nenhum baseline salvo para este script."),J.push("Use pitwall_save_baseline para definir o baseline atual."),J.join(`
|
|
192
|
+
`);J.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${RY(Z.updatedAt)}) ---`),J.push(` Duracao: ${i$(Z.metrics.durationNs)}`),J.push(` Memoria: ${X9(Z.metrics.peakMemoryBytes)}`),J.push(` CPU (user): ${a7(Z.metrics.cpuUserUs)}`),J.push(` CPU (sys): ${a7(Z.metrics.cpuSystemUs)}`),J.push(""),J.push("--- Comparacao ---");for(let z of Y){let K=z.deltaPercent>=0?"+":"",X=sV(z.metric);J.push(` ${rV(z.severity)} ${X}: ${K}${z.deltaPercent}%`)}if(J.push(""),Q)J.push("*** ALERTA: Regressao de performance > 10% detectada! ***"),J.push("Revise as mudancas recentes no codigo.");else if(Y.some((z)=>z.severity==="warning"))J.push("Atencao: algumas metricas estao proximas do limite (5-10%).");else J.push("Performance dentro do esperado.");return J.join(`
|
|
193
|
+
`)}function RY($){let Z=Date.now()-new Date($).getTime(),Y=Math.floor(Z/60000);if(Y<60)return`ha ${Y}min`;let Q=Math.floor(Y/60);if(Q<24)return`ha ${Q}h`;return`ha ${Math.floor(Q/24)}d`}function EY($){if($.length===0)return"Nenhum baseline salvo no Pit Wall.";let Z=["=== Pit Wall: Baselines ===",""];for(let Y of $){let Q=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"",J=RY(Y.updatedAt);if(Z.push(` ${Y.scriptKey}`),Z.push(` Duracao: ${i$(Y.metrics.durationNs)} | Memoria: ${X9(Y.metrics.peakMemoryBytes)} | ${Y.runs} runs | ${J}${Q}`),Y.spread){let z=Y.spread.median>0?(Y.spread.stddev/Y.spread.median*100).toFixed(1):"0";Z.push(` Spread: ${i$(Y.spread.min)} ~ ${i$(Y.spread.max)} (CV ${z}%)`)}Z.push("")}return Z.join(`
|
|
194
|
+
`)}function K9($){if($.length===0)return 0;let Z=[...$].sort((Q,J)=>Q-J),Y=Math.floor(Z.length/2);return Z.length%2!==0?Z[Y]:Math.round((Z[Y-1]+Z[Y])/2)}function eV($){if($.length<2)return 0;let Z=$.reduce((Q,J)=>Q+J,0)/$.length,Y=$.reduce((Q,J)=>Q+(J-Z)**2,0)/($.length-1);return Math.round(Math.sqrt(Y))}function $G($){let Z=$.trim().split(/\s+/);if(Z.length>=3&&["bun","npm","yarn","pnpm"].includes(Z[0])&&Z[1]==="run")return Z[2];if(Z.length>=2&&["bun","npm","yarn","pnpm"].includes(Z[0]))return Z[1];return pV(Z[0])}function ZG(){let $=WY(r7,MY);if(!V9($)){i=[];return}try{let Z=JSON.parse(HY($,"utf-8"));if(Z.version!==BY&&Z.version!==1){i=[];return}i=(Z.baselines||[]).map(YG)}catch{i=[]}}function YG($){let{durationMs:Z,...Y}=$.metrics;return{...$,metrics:Y,spread:$.spread||null}}function s7(){if(!r7)return;let $=WY(r7,MY);D($,JSON.stringify({baselines:i,version:BY},null,2))}p();import{readdirSync as QG,readFileSync as JG,lstatSync as zG}from"fs";import{join as KG,resolve as b8,relative as H9,dirname as XG,extname as VG}from"path";var GG=[".ts",".tsx",".mts",".cts"],qG=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],UG=new Set(S1),LY=5000,HG=5000,jY=new Map;function WG($){let Z=jY.get($);if(Z&&Date.now()-Z.ts<HG)return Z.graph;return null}function BG($,Z){jY.set($,{graph:Z,ts:Date.now()})}var MG=[/^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 CG($){let Z=new Set,Y=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Q of MG){Q.lastIndex=0;let J;while((J=Q.exec(Y))!==null){let z=J[1];if(z.startsWith("./")||z.startsWith("../"))Z.add(z)}}return[...Z]}function NG($){let Z=[];function Y(Q){if(Z.length>=LY)return;let J;try{J=QG(Q)}catch{return}for(let z of J){if(Z.length>=LY)return;if(UG.has(z))continue;let K=KG(Q,z),X;try{X=zG(K)}catch{continue}if(X.isSymbolicLink())continue;if(X.isDirectory())Y(K);else if(X.isFile()&&GG.includes(VG(z)))Z.push(K)}}return Y($),Z}function OG($,Z,Y){let Q=XG(Z),J=b8(Q,$);if(Y.has(J))return J;for(let z of qG){let K=J+z;if(Y.has(K))return K}return null}function W9($){let Z=b8($),Y=WG(Z);if(Y)return Y;let Q=NG(Z),J=new Set(Q),z=new Map,K=new Map;for(let V of Q)z.set(V,new Set),K.set(V,new Set);for(let V of Q){let G;try{G=JG(V,"utf-8")}catch{continue}let q=CG(G),U=z.get(V);for(let W of q){let B=OG(W,V,J);if(B){U.add(B);let M=K.get(B)||new Set;M.add(V),K.set(B,M)}}}let X={imports:z,importedBy:K,files:Q,root:Z};return BG(Z,X),X}function B9($,Z){let Y=b8(Z),Q=$.importedBy.get(Y)||new Set,J=[...Q],z=new Set([Y]),K=[],X=new Map,V=0;for(let M of Q)K.push({file:M,depth:1}),z.add(M),X.set(M,1);let G=[],q=0;while(q<K.length){let{file:M,depth:O}=K[q++];if(O>V)V=O;if(!Q.has(M))G.push(M);let R=$.importedBy.get(M)||new Set;for(let P of R)if(!z.has(P))z.add(P),X.set(P,O+1),K.push({file:P,depth:O+1})}let U=DY(Y,$.importedBy,new Set,0),W=(M)=>H9($.root,M).replace(/\\/g,"/"),B=new Map;for(let[M,O]of X)B.set(W(M),O);return{target:W(Y),directDependents:J.map(W),transitiveDependents:G.map(W),depthMap:B,totalAffected:J.length+G.length,depth:V,tree:PY(U,$.root)}}function DY($,Z,Y,Q){Y.add($);let J=Z.get($)||new Set,z=[];for(let K of J)if(!Y.has(K))z.push(DY(K,Z,Y,Q+1));return{file:$,depth:Q,children:z}}function PY($,Z){return{file:H9(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((Y)=>PY(Y,Z))}}function TY($,Z){let Y=b8(Z),Q=B9($,Z),J=(M)=>b8($.root,M),z=new Set([...Q.directDependents.map(J),...Q.transitiveDependents.map(J)]);z.add(Y);let K=new Map;for(let M of z)K.set(M,0);for(let M of z){let O=$.importedBy.get(M)||new Set;for(let R of O)if(z.has(R)&&R!==M)K.set(M,(K.get(M)||0)+1)}let X=[];for(let[M,O]of K)if(O===0&&M!==Y)X.push(M);let V=[],G=new Set,q=0;while(q<X.length){let M=X[q++];V.push(M),G.add(M);let O=$.imports.get(M)||new Set;for(let R of O)if(z.has(R)&&!G.has(R)&&R!==Y){let P=(K.get(R)||1)-1;if(K.set(R,P),P===0)X.push(R)}}for(let M of z)if(!G.has(M)&&M!==Y)V.push(M);let U=[Y,...V],W=(M)=>H9($.root,M).replace(/\\/g,"/"),B=U.map((M)=>{let R=[...$.imports.get(M)||new Set].filter((l)=>z.has(l)).map(W),P=W(M),Q$=M===Y?0:Q.depthMap.get(P)||1;return{file:P,depth:Q$,dependsOn:R}});return{target:W(Y),order:B,totalFiles:B.length}}function AY($){let Z=[];if(Z.push("=== Blast Radius Analysis ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Arquivos afetados: ${$.totalAffected}`),Z.push(`Profundidade maxima: ${$.depth}`),Z.push(""),$.directDependents.length>0){Z.push(`--- Dependentes diretos (${$.directDependents.length}) ---`);for(let Y of $.directDependents)Z.push(` ${Y}`);Z.push("")}if($.transitiveDependents.length>0){Z.push(`--- Dependentes transitivos (${$.transitiveDependents.length}) ---`);for(let Y of $.transitiveDependents){let Q=$.depthMap.get(Y)||0;Z.push(` ${Y} (depth ${Q})`)}Z.push("")}if($.totalAffected===0)Z.push("Nenhum arquivo depende deste modulo. Blast radius = 0."),Z.push("");return Z.push("--- Arvore de impacto ---"),IY($.tree,Z,"",!0),Z.join(`
|
|
195
|
+
`)}function IY($,Z,Y,Q){let J=Q?"\u2514\u2500 ":"\u251C\u2500 ",z=$.depth===0?`[ALVO] ${$.file}`:$.file;Z.push(`${Y}${J}${z}`);let K=Y+(Q?" ":"\u2502 ");for(let X=0;X<$.children.length;X++)IY($.children[X],Z,K,X===$.children.length-1)}function SY($){let Z=[];Z.push("=== Plano de Refatoracao ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Total de arquivos: ${$.totalFiles}`),Z.push(""),Z.push("Ordem segura de atualizacao:"),Z.push("");for(let Y=0;Y<$.order.length;Y++){let Q=$.order[Y],J=`${Y+1}`.padStart(3),z=Q.depth===0?"[ALVO]":`[depth ${Q.depth}]`;if(Z.push(` ${J}. ${Q.file} ${z}`),Q.dependsOn.length>0)Z.push(` depende de: ${Q.dependsOn.join(", ")}`)}return Z.push(""),Z.push("Estrategia: Altere o alvo primeiro, depois atualize"),Z.push("os dependentes de fora para dentro (folhas primeiro)."),Z.join(`
|
|
196
|
+
`)}f();import{existsSync as M9,mkdirSync as FG,readFileSync as kY}from"fs";import{join as yY}from"path";import{randomUUID as RG}from"crypto";var C9=[{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"}],N9="",n$=[],a$=[],bY=()=>yY(N9,"engine-tradeoffs.json"),_Y=()=>yY(N9,"engine-incidents.json");function EG(){D(bY(),JSON.stringify(n$,null,2))}function LG(){D(_Y(),JSON.stringify(a$,null,2))}function jG(){let $=bY();if(!M9($)){n$=[];return}try{n$=JSON.parse(kY($,"utf-8"))}catch{n$=[]}}function DG(){let $=_Y();if(!M9($)){a$=[];return}try{a$=JSON.parse(kY($,"utf-8"))}catch{a$=[]}}function xY($){if(N9=$,!M9($))FG($,{recursive:!0});jG(),DG()}function fY($,Z,Y=C9){let Q=Y.reduce((q,U)=>q+U.weight,0);if(Math.abs(Q-1)>0.01)Y=Y.map((U)=>({...U,weight:U.weight/Q}));let J={};for(let q of Z){let U=0;for(let W of Y){let B=q.scores[W.name]??3;U+=B*W.weight}J[q.name]=Math.round(U*100)/100}let K=Object.entries(J).sort(([,q],[,U])=>U-q)[0]?.[0]||Z[0]?.name||"N/A",X=Z.find((q)=>q.name===K),V=PG($,Z,Y,J,K,X),G={id:oY(),context:$,options:Z,criteria:Y,recommendation:K,weightedScores:J,adr:V,createdAt:new Date().toISOString()};return n$=[...n$,G],EG(),G}function PG($,Z,Y,Q,J,z){let X=new Date().toISOString().split("T")[0],V=[`# ADR: ${$.title}`,"",`**Date:** ${X}`,"**Status:** Proposed","","## Context","",$.background,""];if($.constraints.length>0){V.push("### Constraints"),V.push("");for(let U of $.constraints)V.push(`- ${U}`);V.push("")}if($.stakeholders.length>0){V.push("### Stakeholders"),V.push("");for(let U of $.stakeholders)V.push(`- ${U}`);V.push("")}V.push("## Options Considered"),V.push("");for(let U of Z){if(V.push(`### ${U.name}`),V.push(""),V.push(U.description),V.push(""),U.pros.length>0){V.push("**Pros:**");for(let W of U.pros)V.push(`- ${W}`);V.push("")}if(U.cons.length>0){V.push("**Cons:**");for(let W of U.cons)V.push(`- ${W}`);V.push("")}}V.push("## Evaluation Matrix"),V.push("");let G=["Criterion (Weight)",...Z.map((U)=>U.name)];V.push(`| ${G.join(" | ")} |`),V.push(`| ${G.map(()=>"---").join(" | ")} |`);for(let U of Y){let W=Math.round(U.weight*100),B=[`${U.name} (${W}%)`,...Z.map((M)=>{return`${M.scores[U.name]??3}/5`})];V.push(`| ${B.join(" | ")} |`)}let q=["**Weighted Total**",...Z.map((U)=>`**${Q[U.name]?.toFixed(2)??"0.00"}**`)];if(V.push(`| ${q.join(" | ")} |`),V.push(""),V.push("## Decision"),V.push(""),V.push(`**Recommended:** ${J}`),V.push(""),z){if(V.push(`Based on the weighted evaluation, **${J}** scores highest with a weighted total of ${Q[J]?.toFixed(2)}.`),V.push(""),z.pros.length>0){V.push("Key advantages:");for(let U of z.pros.slice(0,3))V.push(`- ${U}`);V.push("")}}if(V.push("## Consequences"),V.push(""),V.push("### Positive"),V.push(""),z&&z.pros.length>0)for(let U of z.pros)V.push(`- ${U}`);else V.push("- *To be determined based on implementation*");if(V.push(""),V.push("### Negative"),V.push(""),z&&z.cons.length>0)for(let U of z.cons)V.push(`- ${U}`);else V.push("- *To be determined based on implementation*");return V.push(""),V.push("---"),V.push(""),V.push("*Generated by Decision Engine*"),V.join(`
|
|
197
|
+
`)}function wY($){let Z=$.toLowerCase(),Y=[/error/gi,/exception/gi,/fail/gi,/crash/gi,/timeout/gi,/null/gi,/undefined/gi,/nan/gi,/overflow/gi,/underflow/gi,/memory/gi,/leak/gi,/deadlock/gi,/race/gi,/condition/gi,/connection/gi,/refused/gi,/denied/gi,/unauthorized/gi,/invalid/gi,/missing/gi,/corrupt/gi,/malformed/gi],Q=new Set;for(let V of Y){let G=Z.match(V);if(G)for(let q of G)Q.add(q.toLowerCase())}let J=/[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*/g,z=$.match(J)||[];for(let V of z)if(V.length>3&&!V.match(/^(the|and|for|with|from|this|that)$/i))Q.add(V.toLowerCase());let K=/[A-Z]{2,}_[A-Z0-9_]+|E[0-9]{3,}/g,X=$.match(K)||[];for(let V of X)Q.add(V.toLowerCase());return[...Q]}function TG($,Z){if($.length===0||Z.length===0)return 0;let Y=new Set($),Q=new Set(Z),J=0;for(let K of Y)if(Q.has(K))J++;let z=Y.size+Q.size-J;return z>0?J/z:0}function vY($,Z){let Y=Z?`${$}
|
|
198
|
+
${Z}`:$,Q=wY(Y),J=[];for(let V of a$){let G=`${V.title} ${V.description} ${V.stacktrace||""} ${V.rootCause} ${V.solution}`,q=wY(G),U=TG(Q,q);if(U>0.1){let W=Q.filter((O)=>q.includes(O)),B=[];for(let O of V.relatedDecisions){let R=h0(O);if(R.length>0)B.push(R[0])}let M=[];if(V.solution)M.push(`Apply solution: ${V.solution}`);if(V.rootCause)M.push(`Investigate root cause: ${V.rootCause}`);for(let O of B)M.push(`Review decision: ${O.title}`);J.push({incident:V,similarity:U,matchedKeywords:W,relatedDecisions:B,suggestedActions:M})}}J.sort((V,G)=>G.similarity-V.similarity);let z=h0($.slice(0,50)),K=N1($.slice(0,50)),X=AG($,J,z,K);return{query:$,matches:J.slice(0,5),materialsFound:K.slice(0,5),summary:X}}function AG($,Z,Y,Q){let J=["# Incident Correlation Report",""];if(J.push("## Query"),J.push(""),J.push("```"),J.push($.slice(0,500)),J.push("```"),J.push(""),Z.length>0){J.push("## Similar Past Incidents"),J.push("");for(let z of Z.slice(0,3)){let K=Math.round(z.similarity*100);if(J.push(`### ${z.incident.title} (${K}% match)`),J.push(""),J.push(`**Root Cause:** ${z.incident.rootCause}`),J.push(""),J.push(`**Solution:** ${z.incident.solution}`),J.push(""),z.matchedKeywords.length>0)J.push(`**Matched Keywords:** ${z.matchedKeywords.slice(0,5).join(", ")}`),J.push("");if(z.suggestedActions.length>0){J.push("**Suggested Actions:**");for(let X of z.suggestedActions.slice(0,3))J.push(`- ${X}`);J.push("")}}}else J.push("## Similar Past Incidents"),J.push(""),J.push("*No matching incidents found in the database.*"),J.push("");if(Y.length>0){J.push("## Related Decisions"),J.push("");for(let z of Y.slice(0,3))J.push(`- **${z.title}** (${z.date.split("T")[0]}): ${z.chosen}`);J.push("")}if(Q.length>0){J.push("## Relevant Materials"),J.push("");for(let z of Q.slice(0,3)){let K=z.content.length>100?z.content.slice(0,100).replace(/\n/g," ")+"...":z.content.replace(/\n/g," ");J.push(`- **${z.title}** (${z.category}): ${K}`)}J.push("")}return J.push("---"),J.push(""),J.push("*Generated by Decision Engine Post-Mortem Correlator*"),J.join(`
|
|
199
|
+
`)}function hY($,Z,Y,Q,J,z=[],K=[]){let X={id:oY(),title:$.trim(),description:Z.trim(),stacktrace:J?.trim(),rootCause:Y.trim(),solution:Q.trim(),relatedDecisions:z,tags:K.map((V)=>V.toLowerCase()),createdAt:new Date().toISOString()};return a$=[...a$,X],LG(),X}function gY($){let Z=$.toLowerCase();return a$.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.description.toLowerCase().includes(Z)||Y.rootCause.toLowerCase().includes(Z)||Y.solution.toLowerCase().includes(Z)||Y.tags.some((Q)=>Q.includes(Z))).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function mY($=10){return[...a$].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function uY($=10){return[...n$].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}function pY($){let Z=$.toLowerCase();return n$.filter((Y)=>Y.context.title.toLowerCase().includes(Z)||Y.context.background.toLowerCase().includes(Z)||Y.recommendation.toLowerCase().includes(Z)||Y.options.some((Q)=>Q.name.toLowerCase().includes(Z)||Q.description.toLowerCase().includes(Z))).sort((Y,Q)=>new Date(Q.createdAt).getTime()-new Date(Y.createdAt).getTime())}function dY($){return n$.find((Z)=>Z.id===$)||null}function cY($){if($.length===0)return"Nenhuma analise de trade-off registrada.";let Z=$.map((Y)=>{return` [${new Date(Y.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}] ${Y.context.title} \u2192 ${Y.recommendation} {${Y.id}}`});return`Trade-offs (${$.length}):
|
|
200
|
+
${Z.join(`
|
|
201
|
+
`)}`}function lY($){if($.length===0)return"Nenhum incidente registrado.";let Z=$.map((Y)=>{let Q=new Date(Y.createdAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),J=Y.resolvedAt?"\u2713":"\u25CB",z=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${J} [${Q}] ${Y.title}${z} {${Y.id}}`});return`Incidentes (${$.length}):
|
|
202
|
+
${Z.join(`
|
|
203
|
+
`)}`}function oY(){return RG().slice(0,8)}f();import{existsSync as x8,mkdirSync as iY,readFileSync as O9,readdirSync as IG,writeFileSync as nY}from"fs";import{join as u0}from"path";import{homedir as SG}from"os";import{createHash as wG}from"crypto";var kG=20,aY=3,yG=0.6,bG={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"]},_G={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."}},_8="",L0="",O$={events:[],sessionStart:Date.now()},m0=new Map,r$=[],N$=[],L1=!1,rY=null,sY=()=>u0(_8,"usage-patterns.json"),tY=()=>u0(_8,"insights.json");function eY($,Z){if(_8=u0($,"docs-engine"),L0=u0(SG(),".config","smolerclaw","materials","manual"),rY=Z||null,!x8(_8))iY(_8,{recursive:!0});if(!x8(L0))iY(L0,{recursive:!0});iG(),aG(),rG(),O$={events:[],sessionStart:Date.now()},L1=!0}function F9($){if(!L1)return;let Z={...$,timestamp:Date.now()},Y=[...O$.events,Z].slice(-kG);O$={...O$,events:Y},xG(Z),setImmediate(()=>fG(Z))}function xG($){let Z=`${$.type}:${$.name}`,Y=m0.get(Z);if(Y){let Q=Y.count+1,J=Y.avgDurationMs?(Y.avgDurationMs*Y.count+($.durationMs||0))/Q:$.durationMs||0;m0.set(Z,{action:Z,count:Q,avgDurationMs:J,lastUsed:$.timestamp})}else m0.set(Z,{action:Z,count:1,avgDurationMs:$.durationMs||0,lastUsed:$.timestamp})}function fG($){let Z=O$.events.slice(-5).map((Y)=>Y.name).join(" ");for(let[Y,{pattern:Q,suggestion:J}]of Object.entries(_G))if(Q.test(Z)){if(!r$.find((K)=>K.type==="inefficient_pattern"&&K.relatedActions.includes($.name)&&Date.now()-new Date(K.createdAt).getTime()<3600000)){let K={id:p0(),type:"inefficient_pattern",title:`Padrao detectado: ${Y.replace(/_/g," ")}`,description:"Detectamos um padrao de uso que pode ser otimizado.",recommendation:J,relatedActions:O$.events.slice(-5).map((X)=>X.name),confidence:0.8,createdAt:new Date().toISOString()};$Q(K)}}}async function j1(){if(!L1)return{insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:"Engine not initialized"};let $={insightsGenerated:0,patternsDetected:0,manualUpdates:0,summary:""},Z=vG();$.insightsGenerated+=Z.length,$.patternsDetected+=Z.length;let Y=hG();$.insightsGenerated+=Y.length;let Q=gG();$.insightsGenerated+=Q.length;for(let J of[...Z,...Y,...Q])if($Q(J),await uG(J))$.manualUpdates++;return oG(),nG(),O$={events:[],sessionStart:Date.now()},$.summary=["Reflexao concluida:",` ${$.patternsDetected} padroes detectados`,` ${$.insightsGenerated} insights gerados`,` ${$.manualUpdates} atualizacoes no manual`].join(`
|
|
204
|
+
`),$}function vG(){let $=[],Z=mG(O$.events);for(let Y of Z)if(Y.count>=aY){let Q={id:p0(),type:"repetitive_task",title:`Tarefa repetitiva: ${Y.actions.slice(0,3).join(" -> ")}`,description:`Este padrao de acoes foi executado ${Y.count} vezes nesta sessao.`,recommendation:"Considere criar um workflow para automatizar esta sequencia.",relatedActions:Y.actions,confidence:Math.min(0.5+Y.count*0.1,1),createdAt:new Date().toISOString()};$.push(Q)}return $}function hG(){let $=[],Z=new Set;for(let Y of O$.events)if(Y.type==="tool:executed")Z.add(Y.name);for(let[Y,Q]of Object.entries(bG)){let J=Q.filter((K)=>Z.has(K)),z=Q.filter((K)=>!Z.has(K));if(J.length>0&&z.length>0){let K=J.length/Q.length;if(K>=yG){let X={id:p0(),type:"underutilized_tool",title:`Ferramentas subutilizadas: ${Y}`,description:`Voce usa ${J.join(", ")} mas nao ${z.join(", ")}.`,recommendation:`Experimente as ferramentas ${z.slice(0,2).join(" e ")} para aumentar sua produtividade.`,relatedActions:z,confidence:K,createdAt:new Date().toISOString()};$.push(X)}}}return $}function gG(){let $=[];if(Date.now()-O$.sessionStart>1800000&&!O$.events.some((Q)=>Q.name==="save_memo"))$.push({id:p0(),type:"tip",title:"Dica: Capture insights em memos",description:"Sessao longa detectada sem uso de memos.",recommendation:"Use save_memo ou /memo para capturar ideias importantes durante o trabalho.",relatedActions:["save_memo"],confidence:0.6,createdAt:new Date().toISOString()});let Y=O$.events.filter((Q)=>Q.name==="run_command").length;if(Y>=5&&!O$.events.some((Q)=>Q.name.includes("workflow")))$.push({id:p0(),type:"tip",title:"Dica: Automatize com workflows",description:`${Y} comandos executados nesta sessao.`,recommendation:"Crie um workflow para automatizar sequencias de comandos frequentes.",relatedActions:["create_workflow","run_workflow"],confidence:0.7,createdAt:new Date().toISOString()});return $}function mG($){let Z=new Map,Y=$.map((Q)=>Q.name);for(let Q=2;Q<=4;Q++)for(let J=0;J<=Y.length-Q;J++){let z=Y.slice(J,J+Q),K=z.join("|"),X=Z.get(K);if(X)Z.set(K,{...X,count:X.count+1});else Z.set(K,{actions:z,count:1})}return[...Z.values()].filter((Q)=>Q.count>=aY)}function $Q($){if(!r$.some((Y)=>Y.type===$.type&&Y.title===$.title&&Date.now()-new Date(Y.createdAt).getTime()<86400000))r$=[...r$,$],rY?.($)}function ZQ($=5){return[...r$].sort((Z,Y)=>new Date(Y.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function uG($){try{let Z=cG($.type),Y=`${$.id}.md`,Q=u0(L0,Y),J=N$.find((V)=>V.id===$.id),z=J?J.version+1:1,K={id:$.id,title:$.title,category:Z,content:dG($),tags:lG($),source:"auto_generated",version:z,createdAt:J?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},X=zQ(K);return nY(Q,X,"utf-8"),N$=N$.filter((V)=>V.id!==K.id),N$=[...N$,K],!0}catch{return!1}}async function YQ($,Z,Y="best_practice",Q=[]){if(!L1)return{success:!1,path:""};try{let J=p0(),z=`${tG($)}-${J.slice(0,4)}.md`,K=u0(L0,z),X={id:J,title:$,category:Y,content:Z,tags:Q,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},V=zQ(X);return nY(K,V,"utf-8"),N$=[...N$,X],{success:!0,path:K,entry:X}}catch{return{success:!1,path:""}}}function pG($){let Y=$.toLowerCase().split(/\s+/).filter((Q)=>Q.length>2);return N$.map((Q)=>{let J=0,z=`${Q.title} ${Q.content} ${Q.tags.join(" ")}`.toLowerCase();for(let K of Y)if(z.includes(K))J++;return{entry:Q,score:J}}).filter((Q)=>Q.score>0).sort((Q,J)=>J.score-Q.score).map((Q)=>Q.entry)}function QQ($){let Z=$?pG($):N$;if(Z.length===0)return"Nenhum conteudo encontrado no manual. Execute /reflect para gerar insights baseados no seu uso.";let Y=Z.slice(0,5).map((Q)=>{let J=JQ[Q.category]||Q.category;return[`## ${Q.title}`,`*Categoria: ${J}*`,"",Q.content,"",Q.tags.length>0?`Tags: ${Q.tags.map((z)=>`#${z}`).join(" ")}`:""].filter(Boolean).join(`
|
|
205
|
+
`)});return["# Manual de Uso Otimizado","",`Baseado em ${N$.length} entradas do manual vivo.`,"",...Y].join(`
|
|
206
|
+
`)}var JQ={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function dG($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
|
|
207
|
+
`)}function zQ($){let Z=JQ[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
|
|
208
|
+
Tags: ${$.tags.map((Y)=>`#${Y}`).join(" ")}`:""].filter(Boolean).join(`
|
|
209
|
+
`)}function cG($){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 lG($){let Z=new Set;Z.add($.type.replace(/_/g,"-"));for(let Y of $.relatedActions)if(Y.includes("_"))Z.add(Y.split("_")[0]);return[...Z]}function KQ($){return $.summary}function XQ($){if($.length===0)return"Nenhum insight disponivel.";let Z=$.map((Y)=>{return[`[${{repetitive_task:"Tarefa Repetitiva",underutilized_tool:"Ferramenta Subutilizada",inefficient_pattern:"Padrao Ineficiente",tip:"Dica"}[Y.type]||Y.type}] ${Y.title}`,` ${Y.recommendation}`,` Confianca: ${Math.round(Y.confidence*100)}%`].join(`
|
|
210
|
+
`)});return`Insights (${$.length}):
|
|
185
211
|
|
|
186
212
|
${Z.join(`
|
|
187
213
|
|
|
188
|
-
`)}`}function
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
`)}}catch{}
|
|
192
|
-
---
|
|
193
|
-
`);if(H.length>0)$[`session:${G.id}`]=H}catch{}}}catch{}return $}function iz(){let $=X$.length;if($===0){Z4={},Q4=0;return}let Z=new Map,Q=0;for(let J of X$){let X=new Set;for(let K of J.tokens)if(!X.has(K))Z.set(K,(Z.get(K)??0)+1),X.add(K);Q+=J.tokens.length}Q4=Q/$;let Y={};for(let[J,X]of Z)Y[J]=Math.log(($-X+0.5)/(X+0.5)+1);Z4=Y}function sz(){if(!y7)return;let $={chunks:X$,idf:Z4,avgDocLength:Q4,sourceHashes:Y4,builtAt:new Date().toISOString(),version:b3};S(g9(),JSON.stringify($))}function tz(){let $=g9();if(!i4($)){X$=[],Z4={},Q4=0,Y4={};return}try{let Z=JSON.parse(L8($,"utf-8"));if(Z.version!==b3){X$=[],Z4={},Q4=0,Y4={};return}X$=Z.chunks,Z4=Z.idf,Q4=Z.avgDocLength,Y4=Z.sourceHashes}catch{X$=[],Z4={},Q4=0,Y4={}}}function ez(){let $=g9();if(!i4($))return null;try{return{builtAt:JSON.parse(L8($,"utf-8")).builtAt}}catch{return null}}function $V($){return cz("sha256").update($).digest("hex").slice(0,16)}function ZV($,Z,Q){switch($){case"material":{let Y=Q.split(`
|
|
194
|
-
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"memo":return Q.slice(0,60).replace(/\n/g," ")+(Q.length>60?"...":"");case"decision":{let Y=Q.split(`
|
|
195
|
-
`)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"session":return`Sessao ${Z}`;default:return Z}}function QV($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}Z$();b8();d$();import{writeFileSync as YV,unlinkSync as JV,existsSync as XV}from"fs";import{join as KV}from"path";import{tmpdir as zV}from"os";import{randomUUID as VV}from"crypto";var GV=30000,v3=50000;var HV=[{pattern:/Set-MpPreference\s.*-Disable/i,reason:"Tentativa de desativar Windows Defender"},{pattern:/Disable-WindowsOptionalFeature.*Defender/i,reason:"Tentativa de desativar Windows Defender"},{pattern:/Stop-Service\s.*WinDefend/i,reason:"Tentativa de parar Windows Defender"},{pattern:/sc\s+(stop|delete|disable)\s+WinDefend/i,reason:"Tentativa de desabilitar Windows Defender via sc"},{pattern:/New-ItemProperty.*DisableAntiSpyware/i,reason:"Tentativa de desativar prote\xE7\xE3o via registro"},{pattern:/Remove-Item\s.*\\Windows\\System32/i,reason:"Tentativa de deletar arquivos do System32"},{pattern:/Remove-Item\s.*\\Windows\\SysWOW64/i,reason:"Tentativa de deletar arquivos do SysWOW64"},{pattern:/Format-Volume/i,reason:"Tentativa de formatar volume"},{pattern:/Clear-Disk/i,reason:"Tentativa de limpar disco"},{pattern:/Stop-Computer/i,reason:"Tentativa de desligar computador"},{pattern:/Restart-Computer/i,reason:"Tentativa de reiniciar computador"},{pattern:/Set-ExecutionPolicy\s+Unrestricted/i,reason:"Tentativa de mudar politica de execu\xE7\xE3o permanentemente"},{pattern:/\bnet\s+user\s+.*\/add/i,reason:"Tentativa de criar usuario"},{pattern:/\bnet\s+localgroup\s+administrators/i,reason:"Tentativa de modificar grupo Administrators"},{pattern:/Invoke-Expression.*DownloadString/i,reason:"Tentativa de execu\xE7\xE3o remota (IEX + download)"},{pattern:/\biex\s*\(\s*\(?\s*New-Object/i,reason:"Tentativa de execu\xE7\xE3o remota (IEX + WebClient)"}],qV=[{pattern:/\\Windows\\System32/i,reason:"Acesso a System32"},{pattern:/\\Windows\\SysWOW64/i,reason:"Acesso a SysWOW64"},{pattern:/HKLM:|HKCU:/i,reason:"Acesso ao registro do Windows"},{pattern:/New-Service|Set-Service|Remove-Service/i,reason:"Manipula\xE7\xE3o de servi\xE7os"},{pattern:/New-NetFirewallRule|Remove-NetFirewallRule/i,reason:"Altera\xE7\xE3o de regras de firewall"},{pattern:/Start-Process\s.*-Verb\s+RunAs/i,reason:"Eleva\xE7\xE3o de privilegios (RunAs)"},{pattern:/Set-ItemProperty\s.*\\CurrentVersion\\Run/i,reason:"Modifica\xE7\xE3o de programas de inicializa\xE7\xE3o"}];function m9($){for(let{pattern:Z,reason:Q}of HV)if(Z.test($))return{safe:!1,blocked:!0,reason:Q};for(let{pattern:Z,reason:Q}of qV)if(Z.test($))return{safe:!1,blocked:!1,reason:Q};return{safe:!0,blocked:!1}}async function m1($){if(!A)return{stdout:"",stderr:"Error: PowerShell scripts only available on Windows.",exitCode:1,duration:0};if(!$.trim())return{stdout:"",stderr:"Error: script is empty.",exitCode:1,duration:0};if($.length>v3)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${v3}).`,exitCode:1,duration:0};let Z=m9($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};let Q=VV().slice(0,8),Y=KV(zV(),`smolerclaw-${Q}.ps1`);try{YV(Y,$,"utf-8");let J=await sZ(Y,{timeout:GV});return{stdout:J.stdout,stderr:J.timedOut?"Script timeout exceeded":J.stderr,exitCode:J.exitCode,duration:J.duration}}finally{try{if(XV(Y))JV(Y)}catch{}}}async function g7(){if(!A)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await UV();if($.type==="text")return $;return await WV()}async function UV(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await F5($,{timeout:1e4});if(Z.timedOut)return{type:"error",text:"Clipboard read timeout."};let Q=Z.stdout.trim();if(Q==="___EMPTY___"||!Q)return{type:"empty",text:""};return{type:"text",text:Q}}catch{return{type:"error",text:"Failed to read clipboard text."}}}async function WV(){try{let Z=await F5(`
|
|
214
|
+
`)}`}function oG(){if(!L1)return;let $=Object.fromEntries(m0);D(sY(),JSON.stringify($,null,2))}function iG(){let $=sY();if(!x8($)){m0=new Map;return}try{let Z=JSON.parse(O9($,"utf-8"));m0=new Map(Object.entries(Z))}catch{m0=new Map}}function nG(){if(!L1)return;D(tY(),JSON.stringify(r$,null,2))}function aG(){let $=tY();if(!x8($)){r$=[];return}try{let Z=JSON.parse(O9($,"utf-8"));r$=Array.isArray(Z)?Z:[]}catch{r$=[]}}function rG(){if(!x8(L0)){N$=[];return}try{let $=IG(L0,{withFileTypes:!0}).filter((Y)=>Y.isFile()&&Y.name.endsWith(".md")),Z=[];for(let Y of $){let Q=u0(L0,Y.name),J=O9(Q,"utf-8"),z=sG(Y.name,J);if(z)Z.push(z)}N$=Z}catch{N$=[]}}function sG($,Z){try{let Y=Z.split(`
|
|
215
|
+
`),Q=Y[0]?.replace(/^#\s*/,"")||$.replace(".md",""),J="best_practice",z=1,K=[];for(let U of Y.slice(1,6)){if(U.startsWith("> Categoria:")){let W=U.replace("> Categoria:","").trim().toLowerCase();if(W==="workflow"||W==="tool"||W==="shortcut"||W==="best_practice")J=W}if(U.startsWith("> Versao:"))z=parseInt(U.replace("> Versao:","").trim())||1}let V=Y.slice(-3).join(`
|
|
216
|
+
`).match(/Tags:\s*(.+)/);if(V){let W=V[1].match(/#[\w-]+/g);if(W)K.push(...W.map((B)=>B.slice(1)))}let G=$.match(/-([a-z0-9]{4,8})\.md$/);return{id:G?G[1]:p0(),title:Q,category:J,content:Y.slice(5).join(`
|
|
217
|
+
`).trim(),tags:K,source:"auto_generated",version:z,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()}}catch{return null}}function p0(){return wG("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function tG($){return $.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50)}i0();p();w1();f$();import{writeFileSync as $q,unlinkSync as Zq,existsSync as Yq}from"fs";import{join as Qq}from"path";import{tmpdir as Jq}from"os";import{randomUUID as zq}from"crypto";var Kq=30000,GQ=50000;var Xq=[{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)"}],Vq=[{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 j9($){for(let{pattern:Z,reason:Y}of Xq)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of Vq)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function h8($){if(!L)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>GQ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${GQ}).`,exitCode:1,duration:0};let Z=j9($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};let Y=zq().slice(0,8),Q=Qq(Jq(),`smolerclaw-${Y}.ps1`);try{$q(Q,$,"utf-8");let J=await AZ(Q,{timeout:Kq});return{stdout:J.stdout,stderr:J.timedOut?"Script timeout exceeded":J.stderr,exitCode:J.exitCode,duration:J.duration}}finally{try{if(Yq(Q))Zq(Q)}catch{}}}async function t7(){if(!L)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await Gq();if($.type==="text")return $;return await qq()}async function Gq(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=await d5($,{timeout:1e4});if(Z.timedOut)return{type:"error",text:"Clipboard read timeout."};let Y=Z.stdout.trim();if(Y==="___EMPTY___"||!Y)return{type:"empty",text:""};return{type:"text",text:Y}}catch{return{type:"error",text:"Failed to read clipboard text."}}}async function qq(){try{let Z=await d5(`
|
|
196
218
|
Add-Type -AssemblyName System.Windows.Forms
|
|
197
219
|
$img = [System.Windows.Forms.Clipboard]::GetImage()
|
|
198
220
|
if (-not $img) {
|
|
@@ -242,8 +264,8 @@ try {
|
|
|
242
264
|
} finally {
|
|
243
265
|
if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
|
|
244
266
|
}
|
|
245
|
-
`,{timeout:20000});if(Z.timedOut)return{type:"error",text:"OCR timeout."};let
|
|
246
|
-
${
|
|
267
|
+
`,{timeout:20000});if(Z.timedOut)return{type:"error",text:"OCR timeout."};let Y=Z.stdout.trim();if(Y==="___NO_IMAGE___")return{type:"empty",text:""};if(Y==="___NO_TEXT___")return{type:"image",text:"(Imagem detectada no clipboard, mas sem texto reconhecivel)"};if(Y.startsWith("___OCR_ERROR___"))return{type:"error",text:`OCR falhou: ${Y.replace("___OCR_ERROR___: ","")}`};if(Y)return{type:"image",text:`[OCR do clipboard]
|
|
268
|
+
${Y}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function e7(){if(!L)return"Error: screen context analysis only available on Windows.";let $=`
|
|
247
269
|
$sig = @'
|
|
248
270
|
[DllImport("user32.dll")]
|
|
249
271
|
public static extern IntPtr GetForegroundWindow();
|
|
@@ -276,9 +298,9 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
|
|
|
276
298
|
$marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
|
|
277
299
|
Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
|
|
278
300
|
}
|
|
279
|
-
`;try{let Z=await
|
|
280
|
-
$notificationTitle = '${
|
|
281
|
-
$notificationText = '${
|
|
301
|
+
`;try{let Z=await J$($,{timeout:15000});if(Z.timedOut)return"Error: screen context analysis timeout";let Y=Z.stdout.trim();if(!Y&&Z.stderr.trim())return`Error: ${Z.stderr.trim()}`;return Y||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function qQ($,Z){if(!L)return{success:!1,error:"Notifications only available on Windows."};if(!$?.trim())return{success:!1,error:"Title is required."};if(!Z?.trim())return{success:!1,error:"Message is required."};let Y=$.replace(/'/g,"''"),Q=Z.replace(/'/g,"''"),J=`
|
|
302
|
+
$notificationTitle = '${Y}'
|
|
303
|
+
$notificationText = '${Q}'
|
|
282
304
|
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
|
|
283
305
|
$template = [Windows.UI.Notifications.ToastNotificationManager]::GetTemplateContent([Windows.UI.Notifications.ToastTemplateType]::ToastText02)
|
|
284
306
|
$toastXml = [xml]$template.GetXml()
|
|
@@ -289,48 +311,48 @@ $xml.LoadXml($toastXml.OuterXml)
|
|
|
289
311
|
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
|
|
290
312
|
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Smolerclaw').Show($toast)
|
|
291
313
|
Write-Output 'OK'
|
|
292
|
-
`;try{let
|
|
293
|
-
${Z}`.trim():K.notes}:K),c9(),x$.find((K)=>K.id===$)||null}function RV($){let Z=new Date;x$=x$.map((Q)=>{if(Q.projectId===$&&!Q.endedAt){let Y=new Date(Q.startedAt),J=Math.round((Z.getTime()-Y.getTime())/60000);return{...Q,endedAt:Z.toISOString(),durationMinutes:J}}return Q}),c9()}function A4($){return x$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function EV($,Z,Q){let Y=Q||new Date;return x$.filter((J)=>{if(J.projectId!==$)return!1;let X=new Date(J.startedAt);return X>=Z&&X<=Y})}async function LV($,Z="1 day ago"){if(!I$(N$($,".git")))return null;try{let Q=await p7(["git","log",`--since=${Z}`,"--format=%an|||%s","--no-merges"],$);if(!Q.ok||!Q.stdout.trim())return{commits:0,authors:[],filesChanged:0,insertions:0,deletions:0,topFiles:[],messages:[]};let Y=Q.stdout.trim().split(`
|
|
294
|
-
|
|
295
|
-
`
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
${
|
|
299
|
-
|
|
300
|
-
`)}
|
|
301
|
-
${Z.
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
`
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
${
|
|
311
|
-
`)}
|
|
312
|
-
${
|
|
313
|
-
|
|
314
|
-
${Z.join(`
|
|
315
|
-
|
|
316
|
-
`),$}function RG(){let $=[],Z=jG(D$.events);for(let Q of Z)if(Q.count>=wQ){let Y={id:e4(),type:"repetitive_task",title:`Tarefa repetitiva: ${Q.actions.slice(0,3).join(" -> ")}`,description:`Este padrao de acoes foi executado ${Q.count} vezes nesta sessao.`,recommendation:"Considere criar um workflow para automatizar esta sequencia.",relatedActions:Q.actions,confidence:Math.min(0.5+Q.count*0.1,1),createdAt:new Date().toISOString()};$.push(Y)}return $}function EG(){let $=[],Z=new Set;for(let Q of D$.events)if(Q.type==="tool:executed")Z.add(Q.name);for(let[Q,Y]of Object.entries(NG)){let J=Y.filter((K)=>Z.has(K)),X=Y.filter((K)=>!Z.has(K));if(J.length>0&&X.length>0){let K=J.length/Y.length;if(K>=CG){let V={id:e4(),type:"underutilized_tool",title:`Ferramentas subutilizadas: ${Q}`,description:`Voce usa ${J.join(", ")} mas nao ${X.join(", ")}.`,recommendation:`Experimente as ferramentas ${X.slice(0,2).join(" e ")} para aumentar sua produtividade.`,relatedActions:X,confidence:K,createdAt:new Date().toISOString()};$.push(V)}}}return $}function LG(){let $=[];if(Date.now()-D$.sessionStart>1800000&&!D$.events.some((Y)=>Y.name==="save_memo"))$.push({id:e4(),type:"tip",title:"Dica: Capture insights em memos",description:"Sessao longa detectada sem uso de memos.",recommendation:"Use save_memo ou /memo para capturar ideias importantes durante o trabalho.",relatedActions:["save_memo"],confidence:0.6,createdAt:new Date().toISOString()});let Q=D$.events.filter((Y)=>Y.name==="run_command").length;if(Q>=5&&!D$.events.some((Y)=>Y.name.includes("workflow")))$.push({id:e4(),type:"tip",title:"Dica: Automatize com workflows",description:`${Q} comandos executados nesta sessao.`,recommendation:"Crie um workflow para automatizar sequencias de comandos frequentes.",relatedActions:["create_workflow","run_workflow"],confidence:0.7,createdAt:new Date().toISOString()});return $}function jG($){let Z=new Map,Q=$.map((Y)=>Y.name);for(let Y=2;Y<=4;Y++)for(let J=0;J<=Q.length-Y;J++){let X=Q.slice(J,J+Y),K=X.join("|"),V=Z.get(K);if(V)Z.set(K,{...V,count:V.count+1});else Z.set(K,{actions:X,count:1})}return[...Z.values()].filter((Y)=>Y.count>=wQ)}function vQ($){if(!z4.some((Q)=>Q.type===$.type&&Q.title===$.title&&Date.now()-new Date(Q.createdAt).getTime()<86400000))z4=[...z4,$],kQ?.($)}function fQ($=5){return[...z4].sort((Z,Q)=>new Date(Q.createdAt).getTime()-new Date(Z.createdAt).getTime()).slice(0,$)}async function DG($){try{let Z=AG($.type),Q=`${$.id}.md`,Y=t4(I4,Q),J=j$.find((G)=>G.id===$.id),X=J?J.version+1:1,K={id:$.id,title:$.title,category:Z,content:TG($),tags:IG($),source:"auto_generated",version:X,createdAt:J?.createdAt||$.createdAt,updatedAt:new Date().toISOString()},V=pQ(K);return SQ(Y,V,"utf-8"),j$=j$.filter((G)=>G.id!==K.id),j$=[...j$,K],!0}catch{return!1}}async function hQ($,Z,Q="best_practice",Y=[]){if(!T8)return{success:!1,path:""};try{let J=e4(),X=`${_G($)}-${J.slice(0,4)}.md`,K=t4(I4,X),V={id:J,title:$,category:Q,content:Z,tags:Y,source:"auto_generated",version:1,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()},G=pQ(V);return SQ(K,G,"utf-8"),j$=[...j$,V],{success:!0,path:K,entry:V}}catch{return{success:!1,path:""}}}function PG($){let Q=$.toLowerCase().split(/\s+/).filter((Y)=>Y.length>2);return j$.map((Y)=>{let J=0,X=`${Y.title} ${Y.content} ${Y.tags.join(" ")}`.toLowerCase();for(let K of Q)if(X.includes(K))J++;return{entry:Y,score:J}}).filter((Y)=>Y.score>0).sort((Y,J)=>J.score-Y.score).map((Y)=>Y.entry)}function gQ($){let Z=$?PG($):j$;if(Z.length===0)return"Nenhum conteudo encontrado no manual. Execute /reflect para gerar insights baseados no seu uso.";let Q=Z.slice(0,5).map((Y)=>{let J=mQ[Y.category]||Y.category;return[`## ${Y.title}`,`*Categoria: ${J}*`,"",Y.content,"",Y.tags.length>0?`Tags: ${Y.tags.map((X)=>`#${X}`).join(" ")}`:""].filter(Boolean).join(`
|
|
317
|
-
`)});return["# Manual de Uso Otimizado","",`Baseado em ${j$.length} entradas do manual vivo.`,"",...Q].join(`
|
|
318
|
-
`)}var mQ={workflow:"Workflow",tool:"Ferramenta",shortcut:"Atalho",best_practice:"Boa Pratica"};function TG($){return[$.description,"","### Recomendacao",$.recommendation,"",`**Confianca:** ${Math.round($.confidence*100)}%`,`**Acoes relacionadas:** ${$.relatedActions.join(", ")}`].join(`
|
|
319
|
-
`)}function pQ($){let Z=mQ[$.category]||$.category;return[`# ${$.title}`,"",`> Categoria: ${Z}`,`> Atualizado: ${new Date($.updatedAt).toLocaleDateString("pt-BR")}`,`> Versao: ${$.version}`,"",$.content,"",$.tags.length>0?`---
|
|
320
|
-
Tags: ${$.tags.map((Q)=>`#${Q}`).join(" ")}`:""].filter(Boolean).join(`
|
|
321
|
-
`)}function AG($){switch($){case"repetitive_task":return"workflow";case"underutilized_tool":return"tool";case"inefficient_pattern":return"best_practice";case"tip":return"shortcut";default:return"best_practice"}}function IG($){let Z=new Set;Z.add($.type.replace(/_/g,"-"));for(let Q of $.relatedActions)if(Q.includes("_"))Z.add(Q.split("_")[0]);return[...Z]}function cQ($){return $.summary}function uQ($){if($.length===0)return"Nenhum insight disponivel.";let Z=$.map((Q)=>{return[`[${{repetitive_task:"Tarefa Repetitiva",underutilized_tool:"Ferramenta Subutilizada",inefficient_pattern:"Padrao Ineficiente",tip:"Dica"}[Q.type]||Q.type}] ${Q.title}`,` ${Q.recommendation}`,` Confianca: ${Math.round(Q.confidence*100)}%`].join(`
|
|
322
|
-
`)});return`Insights (${$.length}):
|
|
314
|
+
`;try{let z=await h8(J);if(z.exitCode===0&&z.stdout.includes("OK"))return{success:!0};return{success:!1,error:z.stderr||"Unknown error sending notification."}}catch(z){return{success:!1,error:z instanceof Error?z.message:String(z)}}}var g8=50000;function y$($){if($.length<=g8)return $;return $.slice(0,g8)+`
|
|
315
|
+
... (output truncated)`}function m8($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function D9($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje")return Y;if(Z==="amanha"||Z==="amanh\xE3"){let X=new Date(Y);return X.setDate(X.getDate()+1),X}let Q=Z.match(/em\s+(\d+)\s*dias?/);if(Q){let X=new Date(Y);return X.setDate(X.getDate()+parseInt(Q[1])),X}let J=Z.match(/em\s+(\d+)\s*semanas?/);if(J){let X=new Date(Y);return X.setDate(X.getDate()+parseInt(J[1])*7),X}let z={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[X,V]of Object.entries(z))if(Z.includes(X)){let G=new Date(Y),q=(V-G.getDay()+7)%7||7;return G.setDate(G.getDate()+q),G}let K=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(K){let X=parseInt(K[1]),V=parseInt(K[2])-1,G=K[3]?parseInt(K[3])+(K[3].length===2?2000:0):Y.getFullYear(),q=new Date(G,V,X);if(!isNaN(q.getTime()))return q}return W1(Z)}var Z5=[{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:[]}}],Y5=[{name:"schedule_job",description:"Create a persistent scheduled job using Windows Task Scheduler. Jobs fire even when smolerclaw is not running. Supports one-time, daily, and weekly schedules.",input_schema:{type:"object",properties:{name:{type:"string",description:"Human-readable name for the job"},time:{type:"string",description:'Time in HH:MM format (e.g., "14:00", "09:30")'},message:{type:"string",description:"Message to display in the notification"},schedule_type:{type:"string",enum:["once","daily","weekly"],description:"Schedule type: once (single execution), daily, or weekly. Default: once"},date_or_day:{type:"string",description:'For "once": date in DD/MM/YYYY format or "hoje"/"amanha". For "weekly": day name (e.g., "segunda", "friday"). Optional.'}},required:["name","time","message"]}},{name:"remove_scheduled_job",description:"Remove a scheduled job by its ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"list_scheduled_jobs",description:"List all scheduled jobs. Shows name, schedule, and status.",input_schema:{type:"object",properties:{include_disabled:{type:"boolean",description:"Include disabled jobs. Default false."}},required:[]}},{name:"enable_scheduled_job",description:"Enable a previously disabled scheduled job.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"disable_scheduled_job",description:"Disable a scheduled job without removing it.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"run_scheduled_job_now",description:"Execute a scheduled job immediately (for testing).",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}}],Q5=[{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:[]}}],J5=[{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"]}}],z5={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"]}},K5=[{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"]}}],X5=[{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:[]}}],V5=[{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"]}}],G5=[{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"]}}],q5=[{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"]}}],U5=[{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"]}}],H5=[{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"]}}],W5=[{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"]}}],B5=[{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:[]}}],M5=[{name:"update_living_manual",description:"Silently update the living manual with a structured insight or best practice. The manual is stored at ~/.config/smolerclaw/materials/manual/ and persists across sessions. Use when you observe a pattern that could help the user work more efficiently, or when they ask to document a workflow. Categories: workflow, tool, shortcut, best_practice.",input_schema:{type:"object",properties:{title:{type:"string",description:'Title of the manual entry (e.g. "Atalho para commits rapidos")'},content:{type:"string",description:"Full content in markdown format. Include steps, examples, and tips."},category:{type:"string",enum:["workflow","tool","shortcut","best_practice"],description:"Category. Default: best_practice."},tags:{type:"array",items:{type:"string"},description:'Tags for categorization (e.g. "git", "automacao", "produtividade"). Optional.'}},required:["title","content"]}},{name:"explain_optimal_usage",description:'Generate an interactive tutorial explaining how to use smolerclaw more efficiently. Consults the living manual (via RAG or direct read) and recent insights to build a contextual guide. Use when the user asks "como usar melhor?", "dicas de uso", "tutorial", or seems to be using tools inefficiently.',input_schema:{type:"object",properties:{topic:{type:"string",description:'Optional topic to focus on (e.g. "workflows", "git", "tarefas"). If omitted, shows general tips.'}},required:[]}},{name:"trigger_self_reflection",description:"Manually trigger the self-reflection analysis. Analyzes recent actions to detect patterns, generate insights about repetitive tasks, underutilized tools, and inefficient patterns. Updates the living manual with findings. Use at end of session or when user asks for usage analysis.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_usage_insights",description:'Get recent insights generated by the meta-learning engine. Shows detected patterns, tips, and recommendations based on observed usage. Use when the user asks "o que aprendi?", "insights de uso", or wants to see optimization suggestions.',input_schema:{type:"object",properties:{count:{type:"number",description:"Number of recent insights to show. Default 5."}},required:[]}}];async function HQ($,Z,Y){switch($){case"open_application":return await d0(Z.name,Z.argument);case"open_file_default":return await f8(Z.path);case"open_url_browser":return await c0(Z.url);case"get_running_apps":return await v8();case"get_system_info":return await l0();case"get_calendar_events":return await k$();case"get_news":{let Q=Z.category;return await M0(Q?[Q]:void 0)}case"create_task":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.time,z=J?W1(J):void 0,K=J7(Q,z||void 0),X=z?` \u2014 lembrete: ${z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${K.title}"${X} [${K.id}]`}case"complete_task":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let J=z7(Q);return J?`Concluida: "${J.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,J=l$(Q);return f0(J)}case"schedule_job":{let{name:Q,time:J,message:z}=Z;if(!Q?.trim()||!J?.trim()||!z?.trim())return"Error: name, time, and message are required.";let K=O7(J);if(!K)return`Error: invalid time format "${J}". Use HH:MM.`;let X=Z.schedule_type||"once",V;if(Z.date_or_day){let q=Z.date_or_day;if(X==="weekly")V=R7(q)??void 0;else V=F7(q)??void 0}if(X==="once"&&!V){let q=new Date,[U,W]=K.split(":").map(Number),B=new Date(q);if(B.setHours(U,W,0,0),B<=q)B.setDate(B.getDate()+1);V=[String(B.getMonth()+1).padStart(2,"0"),String(B.getDate()).padStart(2,"0"),String(B.getFullYear())].join("/")}let G=await W7(Q,X,K,"toast",z,V);return`Agendamento criado: "${G.name}" [${G.id}] \u2014 ${G.scheduleType} \xE0s ${G.time}`}case"remove_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await B7(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,J=I8(Q);return S8(J)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let J=await M7(Q);return J?`Agendamento "${J.name}" ativado.`:`Agendamento nao encontrado: "${Q}"`}case"disable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let J=await C7(Q);return J?`Agendamento "${J.name}" desativado.`:`Agendamento nao encontrado: "${Q}"`}case"run_scheduled_job_now":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await N7(Q)}case"add_person":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let J=Z.group;if(!["equipe","familia","contato"].includes(J))return"Error: group must be equipe, familia, or contato.";let K=A7(Q,J,Z.role,Z.contact);return`Pessoa adicionada: ${K.name} (${J}) [${K.id}]`}case"find_person_info":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";let J=o$(Q);if(!J)return`Pessoa nao encontrada: "${Q}"`;return k7(J)}case"list_people":{let Q=Z.group,J=I7(Q);return w7(J)}case"log_interaction":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let{type:J,summary:z}=Z;if(!z?.trim())return"Error: summary is required.";let K=Z.follow_up,X=K?D9(K):void 0;if(!p3(Q,J,z,X||void 0))return`Pessoa nao encontrada: "${Q}"`;let G=X?` \u2014 follow-up: ${X.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${J} com ${Q}${G}`}case"delegate_to_person":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let J=Z.task;if(!J?.trim())return"Error: task is required.";let z=Z.due_date,K=z?D9(z):void 0,X=S7(Q,J,K||void 0);if(!X)return`Pessoa nao encontrada: "${Q}"`;let V=K?` \u2014 prazo: ${K.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Q}: "${J}"${V} [${X.id}]`}case"update_delegation_status":{let Q=Z.delegation_id;if(!Q?.trim())return"Error: delegation_id is required.";let J=Z.status,z=d3(Q,J,Z.notes);if(!z)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${z.task}" -> ${J}`}case"get_people_dashboard":return l3();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let J=Z.tags||[],z=K7(Q,J);return`Memo salvo${z.tags.length>0?` [${z.tags.map((X)=>"#"+X).join(" ")}]`:""} {${z.id}}`}case"search_memos":{let Q=Z.query;if(!Q?.trim())return v0(A8());let J=X7(Q);return v0(J)}case"record_transaction":{let{type:Q,amount:J,category:z,description:K}=Z;if(!Q||!J||!z||!K)return"Error: all fields required.";let X=w8(Q,J,z,K);return`${X.type==="entrada"?"+":"-"} R$ ${X.amount.toFixed(2)} (${X.category}) \u2014 ${X.description} [${X.id}]`}case"financial_summary":return L7();case"log_decision":{let{title:Q,context:J,chosen:z}=Z;if(!Q||!J||!z)return"Error: title, context, and chosen are required.";let K=k3(Q,J,z,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${K.title}" {${K.id}}`}case"search_decisions":{let Q=Z.query;if(!Q?.trim())return M1(j7());return M1(h0(Q))}case"open_investigation":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.type;if(!["bug","feature","test","audit","incident"].includes(J))return"Error: type must be bug, feature, test, audit, or incident.";let K=p2(Q,J,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${K.title}" (${K.type}) {${K.id}}`}case"collect_evidence":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{source:J,label:z,content:K}=Z;if(!z?.trim()||!K?.trim())return"Error: label and content are required.";let X=d2(Q,J,z,K,Z.path);if(!X)return`Investigacao nao encontrada: "${Q}"`;return`Evidencia coletada: [${X.id}] ${X.source}: ${X.label}`}case"add_finding":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{severity:J,title:z,description:K}=Z;if(!z?.trim()||!K?.trim())return"Error: title and description are required.";let X=Z.evidence_ids||[],V=c2(Q,J,z,K,X);if(!V)return`Investigacao nao encontrada: "${Q}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let J=Z.summary;if(!J?.trim())return"Error: summary is required.";let z=l2(Q,J,Z.recommendations);if(!z)return`Investigacao nao encontrada: "${Q}"`;return`Investigacao concluida: "${z.title}" \u2014 ${z.evidence.length} evidencias, ${z.findings.length} conclusoes`}case"investigation_status":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let J=o2(Q);if(!J)return`Investigacao nao encontrada: "${Q}"`;return r2(J)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let J=a2(Q);if(!J)return`Investigacao nao encontrada: "${Q}"`;return J}case"list_investigations":{let Q=Z.query;if(Q?.trim())return P7(n2(Q));let{status:J,type:z}=Z;return P7(i2(J,z))}case"draft_email":{let{to:Q,subject:J,body:z}=Z;if(!Q?.trim()||!J?.trim()||!z?.trim())return"Error: to, subject, and body are required.";let K={to:Q,subject:J,body:z,cc:Z.cc},X=G7(K),V=await V7(K);return`${X}
|
|
316
|
+
|
|
317
|
+
${V}`}case"save_material":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.content;if(!J?.trim())return"Error: content is required.";let z=Z.category||"geral",K=Z.tags||[],X=_7(Q,J,z,K),V=X.tags.length>0?` [${X.tags.map((G)=>"#"+G).join(" ")}]`:"";return`Material salvo: "${X.title}" (${X.category})${V} {${X.id}}`}case"search_materials":{let Q=Z.query;if(!Q?.trim())return O0(O1());let J=N1(Q);return O0(J)}case"list_materials":{let Q=Z.category,J=Z.limit||30,z=O1(J,Q);return O0(z)}case"update_material":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let J={};if(Z.title)J.title=Z.title;if(Z.content)J.content=Z.content;if(Z.category)J.category=Z.category;if(Z.tags)J.tags=Z.tags;let z=r3(Q,J);if(!z)return`Material nao encontrado: "${Q}"`;return`Material atualizado: "${z.title}" (${z.category}) {${z.id}}`}case"delete_material":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";return x7(Q)?"Material removido.":`Material nao encontrado: "${Q}"`}case"execute_powershell_script":{let Q=Z.script;if(!Q?.trim())return"Error: script is required.";let J=j9(Q);if(J.blocked)return`BLOCKED: ${J.reason}
|
|
318
|
+
Esse tipo de operacao nao e permitido.`;if(!J.safe&&J.reason);let z=await h8(Q),K=[];if(z.stdout.trim())K.push(`stdout:
|
|
319
|
+
${z.stdout.trim()}`);if(z.stderr.trim())K.push(`stderr:
|
|
320
|
+
${z.stderr.trim()}`);return K.push(`exit: ${z.exitCode} (${z.duration}ms)`),K.join(`
|
|
321
|
+
|
|
322
|
+
`)}case"analyze_screen_context":return await e7();case"read_clipboard_content":{let Q=await t7();switch(Q.type){case"text":return`Clipboard (texto):
|
|
323
|
+
${Q.text}`;case"image":return Q.text;case"empty":return"Clipboard vazio.";case"error":return`Erro ao ler clipboard: ${Q.text}`}}case"send_notification":{let{title:Q,message:J}=Z,z=await qQ(Q,J);if(z.success)return`Notifica\xE7\xE3o enviada: "${Q}"`;return`Erro ao enviar notifica\xE7\xE3o: ${z.error}`}case"manage_news_feeds":switch(Z.action){case"list":return Y7();case"add":{let{name:J,url:z,category:K}=Z;if(!J?.trim())return"Error: name is required for add.";if(!z?.trim())return"Error: url is required for add.";if(!K?.trim())return"Error: category is required for add.";let X=t4(J,z,K);if(typeof X==="string")return X;return`Fonte adicionada: ${X.name} (${X.category}) \u2014 ${X.url}`}case"remove":{let J=Z.name;if(!J?.trim())return"Error: name or URL is required.";return e4(J)?`Fonte removida: ${J}`:`Fonte custom nao encontrada: "${J}"`}case"disable":{let J=Z.name;if(!J?.trim())return"Error: name or URL is required.";return $7(J)?`Fonte desativada: ${J}`:`Fonte built-in nao encontrada ou ja desativada: "${J}"`}case"enable":{let J=Z.name;if(!J?.trim())return"Error: name or URL is required.";return Z7(J)?`Fonte reativada: ${J}`:`Fonte nao encontrada ou nao esta desativada: "${J}"`}default:return"Error: action must be add, remove, disable, enable, or list."}case"set_active_project":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";if(Q==="auto"){let z=i7(process.cwd());if(!z)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return E1(z.id),`Projeto ativo: "${z.name}" (${z.path}) \u2014 auto-detectado [${z.id}]`}let J=E1(Q);if(!J)return`Projeto nao encontrado: "${Q}". Use /projetos para listar ou add_project para criar.`;return`Projeto ativo: "${J.name}" (${J.path}) [${J.id}]`}case"report_work_progress":{let Q=Z.project||"",J=Z.period||"today",z=Z.lang||"pt",K=Z.save_to_file,X=Q;if(!X){let G=R0();if(!G)return"Nenhum projeto ativo. Use set_active_project primeiro.";X=G.id}let V=await p7(X,J,z);if(!V)return`Projeto nao encontrado: "${X}"`;if(K)return Uq(K,V.markdown,"utf-8"),`Relatorio salvo em: ${K}
|
|
324
|
+
|
|
325
|
+
${V.markdown}`;return V.markdown}case"manage_work_session":{let Q=Z.action,J=Z.notes||"",z=R0();if(!z)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Q){case"start":{let K=g7(z.id,J);if(!K)return"Erro ao iniciar sessao.";return`Sessao iniciada para "${z.name}" as ${new Date().toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}. [${K.id}]`}case"stop":{let K=E0(z.id);if(!K)return"Nenhuma sessao aberta para este projeto.";let X=m7(K.id,J);if(!X)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${X.durationMinutes} minutos trabalhados em "${z.name}".`}case"status":{let K=E0(z.id);if(!K)return`Nenhuma sessao aberta para "${z.name}".`;let X=new Date(K.startedAt),V=Math.round((Date.now()-X.getTime())/60000);return`Sessao aberta: "${z.name}" \u2014 ${V} minutos (desde ${X.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})`}default:return"Error: action must be start, stop, or status."}}case"add_project":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let J=Z.path;if(!J?.trim())return"Error: path is required.";let z=Z.description||"",K=Z.tech_stack||[],X=Z.tags||[],V=J9(Q,J,z,X,K);return`Projeto registrado: "${V.name}" (${V.path}) [${V.id}]`}case"list_projects":{let Q=Z.active_only||!1;return d7(R1(Q))}case"fetch_opportunities":{let{status:Q,tech:J}=Z,z=u7(Q,J);return l7(z)}case"add_opportunity":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.description;if(!J?.trim())return"Error: description is required.";let z=Z.source;if(!z?.trim())return"Error: source is required.";let K=Z.tech_required||[],X=Z.priority||"media",V=Z.deadline||null,G=VY(Q,J,z,K,X,V);return`Oportunidade registrada: "${G.title}" (${G.priority}) [${G.id}]`}case"update_opportunity_status":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let J=Z.status,z=GY(Q,J);if(!z)return`Oportunidade nao encontrada: "${Q}"`;return`Oportunidade atualizada: "${z.title}" -> ${J}`}case"pitwall_benchmark":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let J=Z.key,z=Math.min(Math.max(Z.iterations||1,1),10),K=Z.warmup||!1,X=Z.cwd,V=await G9(Q,{scriptKey:J,cwd:X,iterations:z,warmup:K});if(V.exitCode!==0){let G=U9(V);return`AVISO: Comando terminou com exit code ${V.exitCode}. Metricas podem nao ser confiaveis.
|
|
326
|
+
|
|
327
|
+
${G.markdown}`}return U9(V).markdown}case"pitwall_save_baseline":{let Q=Z.command;if(!Q?.trim())return"Error: command is required.";let J=Z.key,z=Math.min(Math.max(Z.iterations||3,1),10),K=Z.tags||[],X=Z.reset||!1,V=Z.cwd,G=await G9(Q,{scriptKey:J,cwd:V,iterations:z,warmup:!0});if(G.exitCode!==0)return`Error: Comando falhou (exit code ${G.exitCode}). Corrija o comando antes de salvar baseline.
|
|
328
|
+
`+(G.stderr?`Stderr: ${G.stderr.slice(0,300)}`:"");let q=X?FY(G,K):NY(G,K),U=q.metrics.durationNs/1e6;return`Baseline salvo: "${q.scriptKey}" (${q.runs} run${q.runs>1?"s":""})
|
|
329
|
+
Duracao: ${U.toFixed(2)}ms
|
|
330
|
+
Memoria: ${(q.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
|
|
331
|
+
CPU (user): ${(q.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return EY(OY());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return q9(Q)?`Baseline removido: "${Q}"`:`Baseline nao encontrado: "${Q}"`}case"analyze_blast_radius":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let J=$5(Z.project_dir||process.cwd()),z=$5(J,Q);if(!z.startsWith(J+UQ))return"Error: file must be inside project_dir.";try{let K=W9(J),X=B9(K,z);return AY(X)}catch(K){return`Error: ${K instanceof Error?K.message:String(K)}`}}case"plan_refactor":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let J=$5(Z.project_dir||process.cwd()),z=$5(J,Q);if(!z.startsWith(J+UQ))return"Error: file must be inside project_dir.";try{let K=W9(J),X=TY(K,z);return SY(X)}catch(K){return`Error: ${K instanceof Error?K.message:String(K)}`}}case"archive_session":{if(!Y)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";if(Q==="all"){let J=Y.archiveAll();return J.length>0?`Arquivadas ${J.length} sessoes: ${J.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return Y.archive(Q)?`Sessao arquivada: "${Q}"`:`Falha ao arquivar "${Q}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!Y)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";return Y.unarchive(Q)?`Sessao restaurada: "${Q}"`:`Sessao arquivada nao encontrada: "${Q}"`}case"list_archived_sessions":{if(!Y)return"Error: session manager not initialized.";let Q=Y.listArchived();if(Q.length===0)return"Nenhuma sessao arquivada.";let J=Q.map((z)=>{let K=Y.getArchivedInfo(z),X=K?new Date(K.updated).toLocaleDateString("pt-BR"):"",V=K?`${K.messageCount} msgs`:"";return` ${z.padEnd(20)} ${V.padEnd(10)} ${X}`});return`Sessoes arquivadas (${Q.length}):
|
|
332
|
+
${J.join(`
|
|
333
|
+
`)}`}case"evaluate_architecture_tradeoffs":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.background;if(!J?.trim())return"Error: background is required.";let z=Z.options;if(!z||z.length<2)return"Error: at least 2 options are required.";let K={title:Q.trim(),background:J.trim(),constraints:Z.constraints||[],stakeholders:Z.stakeholders||[]},X=z.map((U)=>({name:U.name.trim(),description:U.description.trim(),scores:U.scores,pros:U.pros||[],cons:U.cons||[]})),V=Z.custom_criteria,G=V&&V.length>0?V:C9;return fY(K,X,G).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let J=Z.stacktrace;return vY(Q,J).summary}case"log_incident":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.description;if(!J?.trim())return"Error: description is required.";let z=Z.root_cause;if(!z?.trim())return"Error: root_cause is required.";let K=Z.solution;if(!K?.trim())return"Error: solution is required.";let X=hY(Q,J,z,K,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${X.title}" {${X.id}}
|
|
334
|
+
Causa: ${X.rootCause.slice(0,80)}${X.rootCause.length>80?"...":""}
|
|
335
|
+
Solucao: ${X.solution.slice(0,80)}${X.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,J=Z.query,z=J?pY(J).slice(0,Q):uY(Q);return cY(z)}case"list_incidents":{let Q=Z.limit||10,J=Z.query,z=J?gY(J).slice(0,Q):mY(Q);return lY(z)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let J=dY(Q);if(!J)return`Trade-off nao encontrado: "${Q}"`;return J.adr}case"update_living_manual":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let J=Z.content;if(!J?.trim())return"Error: content is required.";let z=Z.category||"best_practice",K=Z.tags||[],X=await YQ(Q,J,z,K);if(!X.success)return"Falha ao atualizar o manual. Verifique se o docs-engine foi inicializado.";return`Manual atualizado: "${Q}" (${z})
|
|
336
|
+
Arquivo: ${X.path}`}case"explain_optimal_usage":{let Q=Z.topic;return QQ(Q)}case"trigger_self_reflection":{let Q=await j1();return KQ(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),J=ZQ(Q);return XQ(J)}default:return null}}f();var C5=[{name:"vault_status",description:'Show the integrity status of all data files: checksum verification, sizes, last backup time. Use when the user asks about data health, backup status, or says "esta tudo salvo?", "meus dados estao seguros?".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_backup",description:'Perform a manual backup of all data to the shadow backup repository. Use when the user says "faz backup", "salva tudo", "sync".',input_schema:{type:"object",properties:{message:{type:"string",description:"Optional commit message for the backup."}},required:[]}},{name:"sync_cloud_context",description:'Push the backup to a configured remote repository (if set up). Use when the user says "manda pro cloud", "sync remoto", "push backup".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_init_backup",description:"Initialize the shadow backup system (creates a local git repo for data versioning). Run once to enable automatic backups.",input_schema:{type:"object",properties:{},required:[]}}];async function WQ($,Z){switch($){case"vault_status":{if(!y1())return"Vault nao inicializado.";return q4(G4())}case"vault_backup":{if(!y1())return"Vault nao inicializado.";let Y=Z.message||void 0;return await e0(Y)}case"sync_cloud_context":{if(!y1())return"Vault nao inicializado.";return await H4()}case"vault_init_backup":{if(!y1())return"Vault nao inicializado.";return await U4()}default:return null}}f();import{existsSync as a0,mkdirSync as Hq,readFileSync as D1,readdirSync as Wq}from"fs";import{join as n0}from"path";import{createHash as Bq}from"crypto";var CQ=1,P9=400,Mq=80,BQ=1.5,MQ=0.75,Cq=10,Nq=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"]),u8="",N5="",r=[],s$={},t$=0,e$={},O5=!1,A9=()=>n0(N5,"rag-index.json");function NQ($){if(u8=$,N5=n0($,"rag"),!a0(N5))Hq(N5,{recursive:!0});Dq(),O5=!0}function F5(){return O5}function R5(){return{chunks:r.length,sources:Object.keys(e$).length,builtAt:r.length>0?Pq()?.builtAt??null:null}}function E5(){if(!O5)throw Error("Memory not initialized. Call initMemory() first.");let $=Eq(),Z=0,Y=0,Q={},J=new Set;for(let[K,X]of Object.entries($)){let V=Tq(X);if(Q[K]=V,e$[K]!==V)J.add(K)}let z=Object.keys(e$).filter((K)=>!(K in $));if(J.size===0&&z.length===0)return{indexed:0,skipped:Object.keys($).length,total:r.length};r=r.filter((K)=>{let X=`${K.source}:${K.sourceId}`;return!J.has(X)&&!z.includes(X)});for(let K of J){let X=$[K],V=K.indexOf(":");if(V===-1)continue;let G=K.slice(0,V),q=K.slice(V+1);if(!["memo","material","session","decision"].includes(G))continue;let W=Aq(G,q,X),B=Rq(X,G,q,W);r=[...r,...B],Z++}return Y=Object.keys($).length-Z,Lq(),e$=Q,jq(),{indexed:Z,skipped:Y,total:r.length}}function L5($,Z=3){if(r.length===0)return[];let Y=T9($);if(Y.length===0)return[];return r.map((J)=>{let z=Oq(Y,J),K=Fq(Y,J),X=0.6*z+0.4*K;return{chunk:J,score:X}}).filter((J)=>J.score>0).sort((J,z)=>z.score-J.score).slice(0,Math.min(Z,Cq))}function j5($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,Q)=>{let J=Iq(Y.chunk.source),z=(Y.score*100).toFixed(1),K=Y.chunk.content.length>300?Y.chunk.content.slice(0,300).replace(/\n/g," ")+"...":Y.chunk.content.replace(/\n/g," ");return`[${Q+1}] ${J}: ${Y.chunk.title} (relevancia: ${z}%)
|
|
337
|
+
${K}`});return`Resultados da memoria (${$.length}):
|
|
323
338
|
|
|
324
339
|
${Z.join(`
|
|
325
340
|
|
|
326
|
-
`)}`}function
|
|
327
|
-
|
|
328
|
-
`).
|
|
329
|
-
`)
|
|
330
|
-
|
|
331
|
-
`)
|
|
332
|
-
`)
|
|
333
|
-
`)}function
|
|
341
|
+
`)}`}function Oq($,Z){let Y=Z.tokens.length;if(Y===0||t$===0)return 0;let Q=new Map;for(let z of Z.tokens)Q.set(z,(Q.get(z)??0)+1);let J=0;for(let z of $){let K=Q.get(z)??0;if(K===0)continue;let X=s$[z]??0;if(X===0)continue;let V=K*(BQ+1),G=K+BQ*(1-MQ+MQ*(Y/t$));J+=X*(V/G)}return J}function Fq($,Z){let Y=new Map;for(let G of $)Y.set(G,(Y.get(G)??0)+1);let Q=new Map;for(let G of Z.tokens)Q.set(G,(Q.get(G)??0)+1);let J=new Set([...$,...Z.tokens]),z=0,K=0,X=0;for(let G of J){let q=s$[G]??0,U=(Y.get(G)??0)*q,W=(Q.get(G)??0)*q;z+=U*W,K+=U*U,X+=W*W}let V=Math.sqrt(K)*Math.sqrt(X);return V>0?z/V:0}function T9($){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&&!Nq.has(Z))}function Rq($,Z,Y,Q){let J=$.trim();if(J.length===0)return[];if(J.length<=P9)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:Q,content:J,tokens:T9(J)}];let z=[],K=0,X=0;while(K<J.length){let V=Math.min(K+P9,J.length),G=J.slice(K,V);z.push({id:`${Z}:${Y}:${X}`,source:Z,sourceId:Y,title:Q,content:G,tokens:T9(G)}),K+=P9-Mq,X++}return z}function Eq(){let $={},Z=n0(u8,"memos.json");if(a0(Z))try{let z=JSON.parse(D1(Z,"utf-8"));if(!Array.isArray(z))throw Error("not an array");for(let K of z){if(!K||typeof K!=="object")continue;let X=K;if(typeof X.id!=="string"||typeof X.content!=="string")continue;let V=Array.isArray(X.tags)&&X.tags.length>0?` [${X.tags.join(", ")}]`:"";$[`memo:${X.id}`]=`${X.content}${V}`}}catch{}let Y=n0(u8,"materials.json");if(a0(Y))try{let z=JSON.parse(D1(Y,"utf-8"));if(!Array.isArray(z))throw Error("not an array");for(let K of z){if(!K||typeof K!=="object")continue;let X=K;if(typeof X.id!=="string"||typeof X.title!=="string"||typeof X.content!=="string")continue;let V=typeof X.category==="string"?X.category:"geral",G=Array.isArray(X.tags)&&X.tags.length>0?` [${X.tags.join(", ")}]`:"";$[`material:${X.id}`]=`${X.title}
|
|
342
|
+
${V}
|
|
343
|
+
${X.content}${G}`}}catch{}let Q=n0(u8,"decisions.json");if(a0(Q))try{let z=JSON.parse(D1(Q,"utf-8"));if(!Array.isArray(z))throw Error("not an array");for(let K of z){if(!K||typeof K!=="object")continue;let X=K;if(typeof X.id!=="string"||typeof X.title!=="string"||typeof X.context!=="string"||typeof X.chosen!=="string")continue;let V=[X.title,X.context,`Escolha: ${X.chosen}`];if(typeof X.alternatives==="string")V.push(`Alternativas: ${X.alternatives}`);if(Array.isArray(X.tags)&&X.tags.length>0)V.push(`[${X.tags.join(", ")}]`);$[`decision:${X.id}`]=V.join(`
|
|
344
|
+
`)}}catch{}let J=n0(u8,"sessions");if(a0(J))try{let z=Wq(J,{withFileTypes:!0}).filter((K)=>K.isFile()&&K.name.endsWith(".json")&&!K.name.startsWith(".")).map((K)=>K.name);for(let K of z){let X=n0(J,K);try{let V=JSON.parse(D1(X,"utf-8"));if(!V||typeof V!=="object"||!Array.isArray(V.messages))continue;let G=V.messages.filter((q)=>{if(!q||typeof q!=="object")return!1;let U=q;return U.role==="assistant"&&typeof U.content==="string"&&U.content.length>50}).map((q)=>q.content).join(`
|
|
345
|
+
---
|
|
346
|
+
`);if(G.length>0)$[`session:${V.id}`]=G}catch{}}}catch{}return $}function Lq(){let $=r.length;if($===0){s$={},t$=0;return}let Z=new Map,Y=0;for(let J of r){let z=new Set;for(let K of J.tokens)if(!z.has(K))Z.set(K,(Z.get(K)??0)+1),z.add(K);Y+=J.tokens.length}t$=Y/$;let Q={};for(let[J,z]of Z)Q[J]=Math.log(($-z+0.5)/(z+0.5)+1);s$=Q}function jq(){if(!O5)return;let $={chunks:r,idf:s$,avgDocLength:t$,sourceHashes:e$,builtAt:new Date().toISOString(),version:CQ};D(A9(),JSON.stringify($))}function Dq(){let $=A9();if(!a0($)){r=[],s$={},t$=0,e$={};return}try{let Z=JSON.parse(D1($,"utf-8"));if(Z.version!==CQ){r=[],s$={},t$=0,e$={};return}r=Z.chunks,s$=Z.idf,t$=Z.avgDocLength,e$=Z.sourceHashes}catch{r=[],s$={},t$=0,e$={}}}function Pq(){let $=A9();if(!a0($))return null;try{return{builtAt:JSON.parse(D1($,"utf-8")).builtAt}}catch{return null}}function Tq($){return Bq("sha256").update($).digest("hex").slice(0,16)}function Aq($,Z,Y){switch($){case"material":{let Q=Y.split(`
|
|
347
|
+
`)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"memo":return Y.slice(0,60).replace(/\n/g," ")+(Y.length>60?"...":"");case"decision":{let Q=Y.split(`
|
|
348
|
+
`)[0];return Q.length>60?Q.slice(0,60)+"...":Q}case"session":return`Sessao ${Z}`;default:return Z}}function Iq($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}var D5=[{name:"recall_memory",description:'Search the local RAG memory index for relevant information from memos, materials, decisions, and past sessions. Use when the user asks "o que eu sei sobre...", "lembra de...", "busca na memoria...", or needs context from past interactions. Returns the top 3 most relevant text fragments.',input_schema:{type:"object",properties:{query:{type:"string",description:"Natural language query to search the memory index"},top_k:{type:"number",description:"Number of results to return. Default 3, max 10."}},required:["query"]}},{name:"index_memory",description:"Build or update the local RAG memory index. Indexes memos, materials, decisions, and sessions. "+'Incremental \u2014 only re-indexes changed data. Use when the user says "atualiza a memoria", "reindexa", or after adding many new items.',input_schema:{type:"object",properties:{},required:[]}},{name:"memory_status",description:"Show stats about the local RAG memory index: number of indexed chunks, sources, and last build time.",input_schema:{type:"object",properties:{},required:[]}}];function OQ($,Z){switch($){case"recall_memory":{if(!F5())return"Error: memory not initialized. Run /indexar first.";let Y=Z.query;if(!Y?.trim())return"Error: query is required.";let Q=Math.min(Math.max(Z.top_k||3,1),10),J=L5(Y,Q);return j5(J)}case"index_memory":{if(!F5())return"Error: memory not initialized.";let Y=E5();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!F5())return"Memory: nao inicializada.";let Y=R5(),Q=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
|
|
349
|
+
Chunks: ${Y.chunks}
|
|
350
|
+
Fontes: ${Y.sources}
|
|
351
|
+
Ultima indexacao: ${Q}`}default:return null}}f();w1();import{join as Sq}from"path";import{createHash as wq}from"crypto";var kq={requireApprovalFor:["moderate","complex","architectural"],autoApproveComplexity:["trivial","simple"],maxStepsWithoutCheckpoint:5,enableSelfCorrection:!0},p8={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"]},yq=[/config\.(ts|js|json)$/,/package\.json$/,/\.env/,/migration/,/schema\.(ts|prisma|sql)$/,/auth/i,/security/i],bq="",j=null,I9=[],LQ={...kq},jQ=!1,FQ=null,_q=()=>Sq(bq,"plan-history.json");function $0(){return jQ}function S9($,Z){let Y=$.toLowerCase(),Q=xq(Y),J=Z?.files||[],z=Z?.modules||[],K=[],X=[];for(let q of J)for(let U of yq)if(U.test(q))K.push(`Modifying sensitive file: ${q}`);if(J.length>3)K.push(`Affects ${J.length} files \u2014 higher coordination risk`);if(z.length>1)K.push(`Spans ${z.length} modules \u2014 may have cascading effects`);if(Y.includes("api"))X.push("API contract may need versioning consideration");if(Y.includes("database")||Y.includes("schema"))X.push("Database changes may require migration");if(Y.includes("auth")||Y.includes("security"))X.push("Security changes require thorough review");let V=LQ.requireApprovalFor.includes(Q),G=V?`Task classified as "${Q}" \u2014 requires explicit approval`:`Task classified as "${Q}" \u2014 can proceed with auto-approval`;return{complexity:Q,filesAffected:J,modulesAffected:z,risks:K,assumptions:X,requiresApproval:V,reason:G}}function xq($){for(let Z of p8.architectural)if($.includes(Z))return"architectural";for(let Z of p8.complex)if($.includes(Z))return"complex";for(let Z of p8.moderate)if($.includes(Z))return"moderate";for(let Z of p8.simple)if($.includes(Z))return"simple";for(let Z of p8.trivial)if($.includes(Z))return"trivial";return"moderate"}function DQ($,Z,Y){let Q=S9($),J={id:EQ(),objective:$,strategy:Z.map((z,K)=>({...z,id:EQ(),order:K+1,status:"pending"})),assumptions:[...Y?.assumptions||[],...Q.assumptions],risks:[...Y?.risks||[],...Q.risks],status:"draft",complexity:Q.complexity,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return j=J,z0().emit("planning:started",{planId:J.id,objective:$}),J}async function PQ(){if(!j)return{success:!1,plan:null,message:"No active plan to submit"};if(j.status!=="draft")return{success:!1,plan:j,message:`Plan already in status: ${j.status}`};if(j={...j,status:"pending_approval",updatedAt:new Date().toISOString()},LQ.autoApproveComplexity.includes(j.complexity))return RQ("Auto-approved based on complexity classification");if(FQ)if(await FQ(j))return RQ("Approved by user");else return fq("Rejected by user");return{success:!0,plan:j,message:"Plan submitted for approval \u2014 awaiting user confirmation"}}function RQ($){if(!j)return{success:!1,plan:null,message:"No active plan to approve"};if(j.status!=="pending_approval"&&j.status!=="draft")return{success:!1,plan:j,message:`Cannot approve plan in status: ${j.status}`};return j={...j,status:"approved",approvedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),userFeedback:$},z0().emit("planning:approved",{planId:j.id,feedback:$}),{success:!0,plan:j,message:"Plan approved \u2014 execution may proceed"}}function fq($){if(!j)return{success:!1,plan:null,message:"No active plan to reject"};return j={...j,status:"rejected",updatedAt:new Date().toISOString(),userFeedback:$},z0().emit("planning:rejected",{planId:j.id,feedback:$}),wQ(j),j=null,{success:!0,plan:null,message:"Plan rejected \u2014 create a new plan with adjustments"}}function TQ(){if(!j)return{allowed:!0,reason:"No plan required \u2014 trivial operation"};if(j.status==="approved"||j.status==="executing")return{allowed:!0,reason:"Plan approved \u2014 execution permitted"};if(j.status==="draft"||j.status==="pending_approval")return{allowed:!1,reason:`Execution blocked \u2014 plan awaiting approval (status: ${j.status})`};return{allowed:!1,reason:`Execution blocked \u2014 plan status: ${j.status}`}}function AQ($,Z){if(!j)return{success:!1,message:"No active plan"};let Y=j.strategy.findIndex((X)=>X.id===$);if(Y===-1)return{success:!1,message:`Step not found: ${$}`};let Q=j.strategy.map((X,V)=>V===Y?{...X,status:"completed",result:Z}:X);j={...j,strategy:Q,updatedAt:new Date().toISOString()},z0().emit("planning:step_completed",{planId:j.id,stepId:$,result:Z});let J=j.strategy.find((X)=>X.status==="pending"),z=j.strategy[Y].action;if(j.strategy.every((X)=>X.status==="completed"||X.status==="skipped"))vq();return{success:!0,message:`Step completed: ${z}`,nextStep:J}}function IQ($,Z,Y){if(!j)return{success:!1,message:"No active plan"};let Q=j.strategy.findIndex((z)=>z.id===$);if(Q===-1)return{success:!1,message:`Step not found: ${$}`};let J=j.strategy.map((z,K)=>K===Q?{...z,status:"blocked",blockedReason:Z}:z);return j={...j,strategy:J,status:"blocked",blockedAt:new Date().toISOString(),blockedReason:Z,updatedAt:new Date().toISOString()},z0().emit("planning:blocked",{planId:j.id,stepId:$,reason:Z,proposedAlternative:Y}),{success:!0,message:Y?`Step blocked: ${Z}. Proposed alternative: ${Y}`:`Step blocked: ${Z}. Awaiting user guidance.`}}function vq(){if(!j)return;j={...j,status:"completed",completedAt:new Date().toISOString(),updatedAt:new Date().toISOString()},z0().emit("planning:completed",{planId:j.id,stepsCompleted:j.strategy.filter(($)=>$.status==="completed").length}),wQ(j),j=null}function d8(){return j?{...j}:null}function w9($){let Z=$.strategy.map((J)=>{return`${J.status==="completed"?"\u2713":J.status==="in_progress"?"\u2192":J.status==="blocked"?"\u2717":"\u25CB"} Passo ${J.order}: ${J.action} \u2192 ${J.target}`}),Y=$.assumptions.length>0?$.assumptions.map((J)=>` - ${J}`).join(`
|
|
352
|
+
`):" (nenhuma)",Q=$.risks.length>0?$.risks.map((J)=>` - ${J}`).join(`
|
|
353
|
+
`):" (nenhum identificado)";return[`**Objetivo:** ${$.objective}`,"",`**Complexidade:** ${$.complexity}`,"","**Estrat\xE9gia T\xE9cnica:**",...Z,"","**Premissas/Riscos:**",Y,Q,"","**Bloqueio:** Posso prosseguir com este plano ou deseja ajustar algum detalhe?"].join(`
|
|
354
|
+
`)}function SQ($){let Z=$.strategy.filter((J)=>J.status==="completed").length,Y=$.strategy.length,Q=$.strategy.find((J)=>J.status==="in_progress"||J.status==="pending");return[`Plano: ${$.objective}`,`Status: ${$.status}`,`Progresso: ${Z}/${Y} passos`,Q?`Pr\xF3ximo: ${Q.action}`:""].filter(Boolean).join(`
|
|
355
|
+
`)}function wQ($){let Z={planId:$.id,objective:$.objective,status:$.status,complexity:$.complexity,stepsCompleted:$.strategy.filter((Y)=>Y.status==="completed").length,totalSteps:$.strategy.length,createdAt:$.createdAt,completedAt:$.completedAt};I9=[...I9,Z],hq()}function hq(){if(!jQ)return;D(_q(),JSON.stringify(I9,null,2))}function EQ(){return wq("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").slice(0,8)}function kQ(){return`
|
|
334
356
|
## Protocolo de Alta Ag\xEAncia
|
|
335
357
|
|
|
336
358
|
Voc\xEA opera sob o protocolo "Draft-then-Commit" que requer planejamento expl\xEDcito antes de execu\xE7\xE3o.
|
|
@@ -372,73 +394,52 @@ Ao usar \`propose_plan\`, estruture assim:
|
|
|
372
394
|
- **Estrat\xE9gia T\xE9cnica**: Lista ordenada de passos com arquivos-alvo
|
|
373
395
|
- **Premissas/Riscos**: Depend\xEAncias assumidas e potenciais quebras
|
|
374
396
|
- **Bloqueio**: Sempre termine com "Posso prosseguir com este plano?"
|
|
375
|
-
`.trim()}var x8=new z9,GY=[];function HY($){GY=$}var p=[{name:"read_file",description:"Read file contents. For large files, use offset/limit to read specific line ranges.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},offset:{type:"number",description:"Start reading from this line number (1-based). Optional."},limit:{type:"number",description:"Max lines to read. Optional, defaults to 500."}},required:["path"]}},{name:"write_file",description:"Create a new file or completely overwrite an existing file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to write"},content:{type:"string",description:"Full file content"}},required:["path","content"]}},{name:"edit_file",description:"Make a precise edit to a file. Finds old_text and replaces it with new_text. The old_text must match exactly (including whitespace). "+"Use this instead of write_file when modifying existing files \u2014 it preserves the rest of the file.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to edit"},old_text:{type:"string",description:"Exact text to find (must be unique in the file)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}},{name:"search_files",description:"Search file contents using a regex pattern (like grep). Returns matching lines with file paths and line numbers.",input_schema:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in. Defaults to cwd."},include:{type:"string",description:'Glob pattern to filter files, e.g. "*.ts" or "*.py"'}},required:["pattern"]}},{name:"find_files",description:"Find files by name pattern (glob). Returns matching file paths.",input_schema:{type:"object",properties:{pattern:{type:"string",description:'Glob pattern, e.g. "**/*.ts", "src/**/test*"'},path:{type:"string",description:"Base directory. Defaults to cwd."}},required:["pattern"]}},{name:"list_directory",description:"List files and directories with type indicators and sizes.",input_schema:{type:"object",properties:{path:{type:"string",description:"Directory to list. Defaults to cwd."}},required:[]}},{name:"run_command",description:"Run a shell command. Use for: git operations, running tests, installing packages, building projects, or any CLI task. Commands run in the current working directory.",input_schema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},timeout:{type:"number",description:"Timeout in seconds. Default 30, max 120."}},required:["command"]}},{name:"fetch_url",description:"Fetch the content of a URL. Use for: reading documentation, checking APIs, downloading config files, or verifying endpoints. Returns the response body as text. For HTML pages, returns a text-only extraction (no tags).",input_schema:{type:"object",properties:{url:{type:"string",description:"The URL to fetch"},method:{type:"string",description:"HTTP method. Default GET.",enum:["GET","POST","PUT","DELETE","PATCH","HEAD"]},headers:{type:"object",description:"Optional request headers as key-value pairs."},body:{type:"string",description:"Optional request body (for POST/PUT/PATCH)."}},required:["url"]}}],qY=[{name:"open_application",description:"Open a Windows application by name. Available apps: excel, word, powerpoint, outlook, onenote, teams, edge, chrome, firefox, calculator, notepad, terminal, explorer, vscode, cursor, paint, snip, settings, taskmanager.",input_schema:{type:"object",properties:{name:{type:"string",description:'App name (e.g. "excel", "outlook", "teams")'},argument:{type:"string",description:"Optional argument (e.g. file path to open in the app)"}},required:["name"]}},{name:"open_file_default",description:"Open a file with its default Windows application. E.g. .xlsx opens in Excel, .pdf in the PDF reader.",input_schema:{type:"object",properties:{path:{type:"string",description:"File path to open"}},required:["path"]}},{name:"open_url_browser",description:"Open a URL in the default web browser.",input_schema:{type:"object",properties:{url:{type:"string",description:"URL to open"}},required:["url"]}},{name:"get_running_apps",description:"List currently running Windows applications with memory usage. Read-only, non-destructive.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_system_info",description:"Get Windows system resource summary: CPU, RAM, disk, uptime, battery. Read-only.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_calendar_events",description:"Get today's Outlook calendar events. Read-only. Returns event times and subjects.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_news",description:"Fetch current news headlines. Categories: business, tech, finance, brazil, world, security. Returns headlines grouped by category with source attribution.",input_schema:{type:"object",properties:{category:{type:"string",description:"News category to filter. Omit for all categories.",enum:["business","tech","finance","brazil","world","security"]}},required:[]}}],rG=[{name:"create_task",description:'Create a task or reminder for the user. If a time is provided, a notification will fire at that time. Supports natural-language times like "18h", "em 30 minutos", "amanha 9h".',input_schema:{type:"object",properties:{title:{type:"string",description:'Task description (e.g. "buscar pao")'},time:{type:"string",description:'When to remind. E.g. "18h", "18:30", "em 30 minutos", "amanha 9h". Optional.'}},required:["title"]}},{name:"complete_task",description:"Mark a task as done by its ID or partial title match.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Task ID or partial title to match"}},required:["reference"]}},{name:"list_tasks",description:"List all pending tasks and reminders. Shows title, due time, and ID.",input_schema:{type:"object",properties:{show_done:{type:"boolean",description:"Include completed tasks. Default false."}},required:[]}}],iG=[{name:"schedule_job",description:"Create a persistent scheduled job using Windows Task Scheduler. Jobs fire even when smolerclaw is not running. Supports one-time, daily, and weekly schedules.",input_schema:{type:"object",properties:{name:{type:"string",description:"Human-readable name for the job"},time:{type:"string",description:'Time in HH:MM format (e.g., "14:00", "09:30")'},message:{type:"string",description:"Message to display in the notification"},schedule_type:{type:"string",enum:["once","daily","weekly"],description:"Schedule type: once (single execution), daily, or weekly. Default: once"},date_or_day:{type:"string",description:'For "once": date in DD/MM/YYYY format or "hoje"/"amanha". For "weekly": day name (e.g., "segunda", "friday"). Optional.'}},required:["name","time","message"]}},{name:"remove_scheduled_job",description:"Remove a scheduled job by its ID or name.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"list_scheduled_jobs",description:"List all scheduled jobs. Shows name, schedule, and status.",input_schema:{type:"object",properties:{include_disabled:{type:"boolean",description:"Include disabled jobs. Default false."}},required:[]}},{name:"enable_scheduled_job",description:"Enable a previously disabled scheduled job.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"disable_scheduled_job",description:"Disable a scheduled job without removing it.",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}},{name:"run_scheduled_job_now",description:"Execute a scheduled job immediately (for testing).",input_schema:{type:"object",properties:{reference:{type:"string",description:"Job ID or partial name to match"}},required:["reference"]}}],sG=[{name:"add_person",description:"Register a person (team member, family, or contact). Groups: equipe (work team), familia (family/home), contato (other contacts).",input_schema:{type:"object",properties:{name:{type:"string",description:"Person name"},group:{type:"string",enum:["equipe","familia","contato"],description:"Group: equipe, familia, or contato"},role:{type:"string",description:'Role or relationship (e.g. "dev frontend", "esposa", "fornecedor"). Optional.'},contact:{type:"string",description:"Phone, email, or other contact info. Optional."}},required:["name","group"]}},{name:"find_person_info",description:"Look up a person by name or ID. Returns their profile, recent interactions, and pending delegated tasks.",input_schema:{type:"object",properties:{name_or_id:{type:"string",description:"Person name (partial match) or ID"}},required:["name_or_id"]}},{name:"list_people",description:"List all registered people, optionally filtered by group.",input_schema:{type:"object",properties:{group:{type:"string",enum:["equipe","familia","contato"],description:"Filter by group. Optional."}},required:[]}},{name:"log_interaction",description:"Log an interaction with a person. Types: conversa, email, reuniao, ligacao, mensagem, delegacao, entrega, outro. Optionally set a follow-up date for a reminder.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},type:{type:"string",enum:["conversa","email","reuniao","ligacao","mensagem","delegacao","entrega","outro"],description:"Interaction type"},summary:{type:"string",description:"What was discussed or happened"},follow_up:{type:"string",description:'When to follow up (e.g. "em 3 dias", "amanha", "25/03"). Optional.'}},required:["person","type","summary"]}},{name:"delegate_to_person",description:"Delegate/assign a task to a person with optional due date. Use to track what you asked someone to do.",input_schema:{type:"object",properties:{person:{type:"string",description:"Person name or ID"},task:{type:"string",description:"What they need to do"},due_date:{type:"string",description:'Due date (e.g. "sexta", "em 3 dias", "28/03"). Optional.'}},required:["person","task"]}},{name:"update_delegation_status",description:"Update the status of a delegated task. Statuses: pendente, em_andamento, concluido.",input_schema:{type:"object",properties:{delegation_id:{type:"string",description:"Delegation ID"},status:{type:"string",enum:["pendente","em_andamento","concluido"],description:"New status"},notes:{type:"string",description:"Optional notes about the update"}},required:["delegation_id","status"]}},{name:"get_people_dashboard",description:"Show the people management dashboard: summary of team/family/contacts, overdue follow-ups, overdue delegations, and recent interactions.",input_schema:{type:"object",properties:{},required:[]}}],tG=[{name:"save_memo",description:`Save a note/memo to the user's personal knowledge base. Use #hashtags in the content to auto-tag. Use when the user says "anota", "lembra disso", "salva isso", or shares important information.`,input_schema:{type:"object",properties:{content:{type:"string",description:"The memo content. Use #tags for categorization."},tags:{type:"array",items:{type:"string"},description:"Optional additional tags (without #). Auto-extracted #tags from content are always included."}},required:["content"]}},{name:"search_memos",description:`Search the user's memos by keyword or tag. Use #tag to search by tag only. Use plain text for content search. Use when the user asks "o que eu anotei sobre...", "qual era aquela nota...", etc.`,input_schema:{type:"object",properties:{query:{type:"string",description:"Search query. Use #tag for tag search, or plain text for content search."}},required:["query"]}}],eG={name:"draft_email",description:'Create an email draft and open it in Outlook (Windows) or the default mail client. The user can review and send manually. Use when the user says "escreve um email", "manda um email", "rascunho de email", etc.',input_schema:{type:"object",properties:{to:{type:"string",description:"Recipient email address"},subject:{type:"string",description:"Email subject line"},body:{type:"string",description:"Email body text"},cc:{type:"string",description:"CC recipients (optional)"}},required:["to","subject","body"]}},$H=[{name:"record_transaction",description:"Record a financial transaction (income or expense). Use when user mentions spending, receiving money, or financial tracking.",input_schema:{type:"object",properties:{type:{type:"string",enum:["entrada","saida"],description:"Transaction type: entrada (income) or saida (expense)"},amount:{type:"number",description:"Amount in BRL (always positive)"},category:{type:"string",description:"Category (e.g. alimentacao, transporte, salario, freelance)"},description:{type:"string",description:"Description of the transaction"}},required:["type","amount","category","description"]}},{name:"financial_summary",description:"Show monthly financial summary with income, expenses, and balance by category.",input_schema:{type:"object",properties:{},required:[]}},{name:"log_decision",description:'Record an important decision with context and rationale. Use when the user says "decidi", "optei por", "escolhi", or discusses a major choice.',input_schema:{type:"object",properties:{title:{type:"string",description:"Decision title (short)"},context:{type:"string",description:"Why this decision was needed"},chosen:{type:"string",description:"What was decided"},alternatives:{type:"string",description:"What was considered but rejected. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["title","context","chosen"]}},{name:"search_decisions",description:"Search past decisions by keyword or tag.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query"}},required:["query"]}}],ZH=[{name:"open_investigation",description:'Start a new investigation to systematically collect evidence. Types: bug (malfunction), feature (material for building), test (test scenarios), audit (code review), incident (runtime issue). Use when the user says "investiga", "analisa", "diagnostica", "verifica", or needs structured evidence collection.',input_schema:{type:"object",properties:{title:{type:"string",description:"Investigation title (short, descriptive)"},type:{type:"string",enum:["bug","feature","test","audit","incident"],description:"Investigation type"},hypothesis:{type:"string",description:"Initial theory or goal to investigate. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["title","type"]}},{name:"collect_evidence",description:"Add a piece of evidence to an active investigation. Sources: file (file content), command (command output), log (log entries), diff (code changes), url (web content), observation (manual note). Use after reading files, running commands, or observing behavior to build the investigation record.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title (partial match)"},source:{type:"string",enum:["file","command","log","diff","url","observation"],description:"Evidence source type"},label:{type:"string",description:"Short description of this evidence"},content:{type:"string",description:"The evidence data (file content, command output, observation text, etc.)"},path:{type:"string",description:"File path or URL associated with this evidence. Optional."}},required:["investigation","source","label","content"]}},{name:"add_finding",description:"Record a conclusion or insight derived from collected evidence. Severity: critical, high, medium, low, info. Link to evidence IDs that support this finding.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"},severity:{type:"string",enum:["critical","high","medium","low","info"],description:"Finding severity"},title:{type:"string",description:"Finding title (short)"},description:{type:"string",description:"Detailed description of the finding"},evidence_ids:{type:"array",items:{type:"string"},description:"IDs of evidence supporting this finding. Optional."}},required:["investigation","severity","title","description"]}},{name:"close_investigation",description:"Close an investigation with a summary and recommendations. Use after all evidence is collected and findings are recorded.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"},summary:{type:"string",description:"Final summary of the investigation"},recommendations:{type:"string",description:"Action items and next steps. Optional."}},required:["investigation","summary"]}},{name:"investigation_status",description:"View the current state of an investigation: evidence collected, findings, and progress. Use to check progress or review before closing.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"}},required:["investigation"]}},{name:"investigation_report",description:"Generate a full structured report (markdown) for an investigation. Includes all evidence, findings, summary, and recommendations.",input_schema:{type:"object",properties:{investigation:{type:"string",description:"Investigation ID or title"}},required:["investigation"]}},{name:"list_investigations",description:"List all investigations, optionally filtered by status or type.",input_schema:{type:"object",properties:{status:{type:"string",enum:["aberta","em_andamento","concluida","arquivada"],description:"Filter by status. Optional."},type:{type:"string",enum:["bug","feature","test","audit","incident"],description:"Filter by type. Optional."},query:{type:"string",description:"Search by keyword. Optional."}},required:[]}}],QH=[{name:"save_material",description:`Save reference material to the assistant's persistent knowledge base. Materials are categorized documents, guides, procedures, or reference info that persists across sessions. Use when the user says "salva esse material", "guarda essa referencia", "adiciona ao conhecimento", etc. Categories: procedimento, referencia, guia, template, contato, projeto, tecnico, geral.`,input_schema:{type:"object",properties:{title:{type:"string",description:"Title of the material"},content:{type:"string",description:"Full content. Use #tags for categorization."},category:{type:"string",description:"Category (e.g. procedimento, referencia, guia, template, contato, projeto, tecnico, geral). Default: geral."},tags:{type:"array",items:{type:"string"},description:"Optional additional tags (without #)."}},required:["title","content"]}},{name:"search_materials",description:"Search the assistant's material knowledge base by keyword, tag (#tag), or category (@category). Use when answering questions that may be covered by saved materials, or when user asks about reference docs.",input_schema:{type:"object",properties:{query:{type:"string",description:"Search query. Use #tag for tag search, @category for category search, or plain text."}},required:["query"]}},{name:"list_materials",description:"List all saved materials, optionally filtered by category.",input_schema:{type:"object",properties:{category:{type:"string",description:"Filter by category. Optional."},limit:{type:"number",description:"Max results. Default 30."}},required:[]}},{name:"update_material",description:"Update an existing material by ID. Can change title, content, category, or tags.",input_schema:{type:"object",properties:{id:{type:"string",description:"Material ID"},title:{type:"string",description:"New title. Optional."},content:{type:"string",description:"New content. Optional."},category:{type:"string",description:"New category. Optional."},tags:{type:"array",items:{type:"string"},description:"New tags. Optional."}},required:["id"]}},{name:"delete_material",description:"Delete a material by ID.",input_schema:{type:"object",properties:{id:{type:"string",description:"Material ID"}},required:["id"]}}],YH=[{name:"vault_status",description:'Show the integrity status of all data files: checksum verification, sizes, last backup time. Use when the user asks about data health, backup status, or says "esta tudo salvo?", "meus dados estao seguros?".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_backup",description:'Perform a manual backup of all data to the shadow backup repository. Use when the user says "faz backup", "salva tudo", "sync".',input_schema:{type:"object",properties:{message:{type:"string",description:"Optional commit message for the backup."}},required:[]}},{name:"sync_cloud_context",description:'Push the backup to a configured remote repository (if set up). Use when the user says "manda pro cloud", "sync remoto", "push backup".',input_schema:{type:"object",properties:{},required:[]}},{name:"vault_init_backup",description:"Initialize the shadow backup system (creates a local git repo for data versioning). Run once to enable automatic backups.",input_schema:{type:"object",properties:{},required:[]}}],JH=[{name:"set_active_project",description:'Set which project the assistant should focus on. Auto-detects from the current directory if not registered. Use when the user says "estou trabalhando no projeto X", "muda pro projeto Y", or starts work.',input_schema:{type:"object",properties:{name_or_id:{type:"string",description:'Project name, ID, or "auto" to detect from current directory.'}},required:["name_or_id"]}},{name:"report_work_progress",description:'Generate a work progress report with git commits, time tracked, and tasks completed. Outputs a structured Markdown document. Use when the user says "relatorio", "como estou no projeto", "resumo do trabalho", "progress report".',input_schema:{type:"object",properties:{project:{type:"string",description:"Project name/ID. Defaults to active project."},period:{type:"string",enum:["today","week","month"],description:"Report period. Default: today."},lang:{type:"string",enum:["pt","en"],description:"Report language. Default: pt."},save_to_file:{type:"string",description:"Optional file path to save the report. If omitted, returns as text."}},required:[]}},{name:"manage_work_session",description:'Start or stop a work session timer for time tracking. Use when the user says "comecei a trabalhar", "parei de trabalhar", "timer", etc.',input_schema:{type:"object",properties:{action:{type:"string",enum:["start","stop","status"],description:"Start, stop, or check session status."},notes:{type:"string",description:"Optional notes for the session."}},required:["action"]}},{name:"add_project",description:"Register a new project for tracking. Use when the user mentions a new project or wants to track a directory.",input_schema:{type:"object",properties:{name:{type:"string",description:"Project name"},path:{type:"string",description:"Filesystem path to the project root"},description:{type:"string",description:"Brief project description. Optional."},tech_stack:{type:"array",items:{type:"string"},description:"Technologies used. Optional."},tags:{type:"array",items:{type:"string"},description:"Tags for categorization. Optional."}},required:["name","path"]}},{name:"list_projects",description:"List all registered projects with their status and tech stack.",input_schema:{type:"object",properties:{active_only:{type:"boolean",description:"Show only active projects. Default false."}},required:[]}},{name:"fetch_opportunities",description:'List pending opportunities/tasks filtered by tech stack or priority. Use when the user asks "tem alguma demanda nova?", "oportunidades", "o que tem pra fazer?".',input_schema:{type:"object",properties:{status:{type:"string",enum:["nova","em_analise","aceita","recusada","concluida"],description:"Filter by status. Optional."},tech:{type:"array",items:{type:"string"},description:"Filter by required tech. Optional."}},required:[]}},{name:"add_opportunity",description:"Register a new task/opportunity/demand for tracking. Use when the user mentions a potential project, job lead, or new demand.",input_schema:{type:"object",properties:{title:{type:"string",description:"Opportunity title"},description:{type:"string",description:"Details about the opportunity"},source:{type:"string",description:'Where this came from (e.g. "LinkedIn", "email", "contato direto")'},tech_required:{type:"array",items:{type:"string"},description:"Technologies required. Optional."},priority:{type:"string",enum:["alta","media","baixa"],description:"Priority level. Default: media."},deadline:{type:"string",description:'Deadline if any (e.g. "30/04", "em 2 semanas"). Optional.'}},required:["title","description","source"]}},{name:"update_opportunity_status",description:"Update the status of an opportunity.",input_schema:{type:"object",properties:{id:{type:"string",description:"Opportunity ID"},status:{type:"string",enum:["nova","em_analise","aceita","recusada","concluida"],description:"New status"}},required:["id","status"]}}],XH=[{name:"pitwall_benchmark",description:"Benchmark a local script or command \u2014 captures wall-clock time, child process peak memory, and CPU overhead. "+'Compares against saved baseline and alerts on regressions > 10%. Use when the user says "benchmark", "mede a performance", "testa a velocidade", "pit wall".',input_schema:{type:"object",properties:{command:{type:"string",description:'Shell command to benchmark (e.g. "bun run build", "bun test").'},key:{type:"string",description:"Unique label for this benchmark. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs (uses median). Default 1, max 10."},warmup:{type:"boolean",description:"Run one warmup iteration before measuring (discarded). Default false."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_save_baseline",description:'Benchmark a command and save results as the performance baseline for future comparisons. Default: 3 runs with warmup. Use "reset" to replace (not blend) an existing baseline.',input_schema:{type:"object",properties:{command:{type:"string",description:"Command to benchmark and save as baseline."},key:{type:"string",description:"Benchmark label. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs to measure. Default 3."},tags:{type:"array",items:{type:"string"},description:'Tags for this baseline (e.g. "build", "test").'},reset:{type:"boolean",description:"If true, replaces existing baseline entirely. Default false (blends)."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_status",description:'List all saved performance baselines with their metrics, spread, and age. Use when the user asks "quais baselines tenho?", "pit wall status", "mostra as metricas".',input_schema:{type:"object",properties:{},required:[]}},{name:"pitwall_remove_baseline",description:"Remove a saved performance baseline by its key.",input_schema:{type:"object",properties:{key:{type:"string",description:"The script key of the baseline to remove."}},required:["key"]}}],KH=[{name:"analyze_blast_radius",description:"Analyze the blast radius of changing a TypeScript file \u2014 shows all modules that import it (directly and transitively). "+'Use when the user says "blast radius", "impacto da mudanca", "quem depende de", "o que quebra se mudar".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file to analyze (relative or absolute)."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}},{name:"plan_refactor",description:'Generate a safe refactor order for updating dependents of a TypeScript file. Returns a numbered sequence: change the target first, then update dependents bottom-up. Use when the user says "plano de refatoracao", "ordem de atualizacao", "como refatorar seguro".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file being refactored."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}}],zH=[{name:"evaluate_architecture_tradeoffs",description:"Analyze trade-offs between architectural options using a weighted evaluation matrix. Returns an ADR (Architecture Decision Record) with recommendation. Default criteria: Maintainability (30%), Performance (25%), Learning Curve (20%), Infrastructure Cost (25%). Use when comparing technologies, frameworks, patterns, or infrastructure choices.",input_schema:{type:"object",properties:{title:{type:"string",description:'Title of the decision, e.g., "Redis vs SQLite for session storage".'},background:{type:"string",description:"Context and background of the decision \u2014 why is this decision needed?"},constraints:{type:"array",items:{type:"string"},description:'Project constraints, e.g., "Must run on Kubernetes", "Budget < $100/mo".'},stakeholders:{type:"array",items:{type:"string"},description:'People/teams affected, e.g., "Backend Team", "DevOps".'},options:{type:"array",items:{type:"object",properties:{name:{type:"string",description:'Option name, e.g., "Redis".'},description:{type:"string",description:"Brief description of this option."},scores:{type:"object",description:"Scores for each criterion (1-5). Keys: maintainability, performance, learning_curve, infrastructure_cost."},pros:{type:"array",items:{type:"string"},description:"Advantages of this option."},cons:{type:"array",items:{type:"string"},description:"Disadvantages of this option."}},required:["name","description","scores","pros","cons"]},description:"List of options to compare (minimum 2)."},custom_criteria:{type:"array",items:{type:"object",properties:{name:{type:"string",description:"Criterion name."},weight:{type:"number",description:"Weight (0.0-1.0). Must sum to 1.0 across all criteria."},description:{type:"string",description:"What this criterion measures."}},required:["name","weight","description"]},description:"Optional custom criteria. If not provided, uses default criteria."}},required:["title","background","options"]}},{name:"correlate_incident",description:"Analyze an error or bug and search for similar past incidents, related decisions, and relevant materials. Returns correlation matches with suggested solutions and actions based on historical data. Use when debugging, troubleshooting, or investigating an error.",input_schema:{type:"object",properties:{description:{type:"string",description:"Description of the current error or bug."},stacktrace:{type:"string",description:"Optional stacktrace or error output for better matching."}},required:["description"]}},{name:"log_incident",description:"Log a resolved incident for future correlation. This feeds the Post-Mortem database. Use after resolving a bug to help accelerate future debugging.",input_schema:{type:"object",properties:{title:{type:"string",description:"Short title of the incident."},description:{type:"string",description:"Detailed description of what happened."},root_cause:{type:"string",description:"Root cause analysis."},solution:{type:"string",description:"How the incident was resolved."},stacktrace:{type:"string",description:"Optional stacktrace for better correlation."},related_decisions:{type:"array",items:{type:"string"},description:"IDs of related decisions from the Decision Log."},tags:{type:"array",items:{type:"string"},description:'Tags for categorization, e.g., "memory-leak", "timeout", "auth".'}},required:["title","description","root_cause","solution"]}},{name:"list_tradeoff_analyses",description:"List past architecture trade-off analyses. Use to review previous decisions and their rationale.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Maximum number of results (default 10)."},query:{type:"string",description:"Optional search query to filter results."}},required:[]}},{name:"list_incidents",description:"List logged incidents from the Post-Mortem database. Use to review past issues and solutions.",input_schema:{type:"object",properties:{limit:{type:"number",description:"Maximum number of results (default 10)."},query:{type:"string",description:"Optional search query to filter results."}},required:[]}},{name:"get_tradeoff_adr",description:"Get the full ADR (Architecture Decision Record) for a past trade-off analysis by ID. Returns the complete Markdown document.",input_schema:{type:"object",properties:{id:{type:"string",description:"ID of the trade-off analysis."}},required:["id"]}}],VH=[{name:"execute_powershell_script",description:"Execute a PowerShell script on the local machine. The script runs in a temp .ps1 file with -ExecutionPolicy Bypass (scoped). Safety guards block dangerous operations (Defender, System32, formatting). Returns stdout, stderr, exit code, and duration. Use for: automation, system queries, batch operations, registry reads, scheduled tasks.",input_schema:{type:"object",properties:{script:{type:"string",description:"The PowerShell script to execute. Multi-line supported."}},required:["script"]}},{name:"analyze_screen_context",description:"Get detailed information about the user's current screen: foreground window (what they are looking at), all visible windows with PIDs, memory usage, and titles. Use to understand the user's current context. Read-only.",input_schema:{type:"object",properties:{},required:[]}},{name:"read_clipboard_content",description:'Read the current clipboard content. Auto-detects text or image. For images, performs OCR using Windows.Media.Ocr to extract text. Use when the user says "le o que copiei", "o que tem no clipboard", "cola isso", etc. Read-only.',input_schema:{type:"object",properties:{},required:[]}}],GH=[{name:"send_notification",description:'Send a Windows toast notification to the user. Displays a system notification with title and message. Use when you need to alert the user about: task completions, reminders, important events, or when the user asks "me avisa quando terminar", "notifica quando...", etc.',input_schema:{type:"object",properties:{title:{type:"string",description:"Notification title (short, max ~50 chars)."},message:{type:"string",description:"Notification message/body."}},required:["title","message"]}}],HH=[{name:"manage_news_feeds",description:'Manage RSS/Atom news feed sources. Actions: add (add custom feed), remove (remove custom feed), disable (disable a built-in feed), enable (re-enable a disabled built-in), list (show all feeds). Use when the user says "adiciona essa fonte", "remove o feed", "desativa o TechCrunch", "mostra as fontes".',input_schema:{type:"object",properties:{action:{type:"string",enum:["add","remove","disable","enable","list"],description:"Action to perform."},name:{type:"string",description:"Feed name (for add) or name/URL reference (for remove/disable/enable)."},url:{type:"string",description:"RSS/Atom feed URL (required for add)."},category:{type:"string",description:"Category for the feed (required for add). E.g. tech, finance, ai, devops."}},required:["action"]}}],qH=[{name:"recall_memory",description:'Search the local RAG memory index for relevant information from memos, materials, decisions, and past sessions. Use when the user asks "o que eu sei sobre...", "lembra de...", "busca na memoria...", or needs context from past interactions. Returns the top 3 most relevant text fragments.',input_schema:{type:"object",properties:{query:{type:"string",description:"Natural language query to search the memory index"},top_k:{type:"number",description:"Number of results to return. Default 3, max 10."}},required:["query"]}},{name:"index_memory",description:"Build or update the local RAG memory index. Indexes memos, materials, decisions, and sessions. "+'Incremental \u2014 only re-indexes changed data. Use when the user says "atualiza a memoria", "reindexa", or after adding many new items.',input_schema:{type:"object",properties:{},required:[]}},{name:"memory_status",description:"Show stats about the local RAG memory index: number of indexed chunks, sources, and last build time.",input_schema:{type:"object",properties:{},required:[]}}],UH=[{name:"archive_session",description:'Archive a conversation session. Archived sessions are preserved but removed from the active list. Use "all" as name to archive all sessions except the current one.',input_schema:{type:"object",properties:{name:{type:"string",description:'Session name to archive, or "all" to archive all except current.'}},required:["name"]}},{name:"unarchive_session",description:"Restore an archived session back to the active sessions list.",input_schema:{type:"object",properties:{name:{type:"string",description:"Archived session name to restore."}},required:["name"]}},{name:"list_archived_sessions",description:"List all archived conversation sessions with message count and last update.",input_schema:{type:"object",properties:{},required:[]}}],WH=[{name:"update_living_manual",description:"Silently update the living manual with a structured insight or best practice. The manual is stored at ~/.config/smolerclaw/materials/manual/ and persists across sessions. Use when you observe a pattern that could help the user work more efficiently, or when they ask to document a workflow. Categories: workflow, tool, shortcut, best_practice.",input_schema:{type:"object",properties:{title:{type:"string",description:'Title of the manual entry (e.g. "Atalho para commits rapidos")'},content:{type:"string",description:"Full content in markdown format. Include steps, examples, and tips."},category:{type:"string",enum:["workflow","tool","shortcut","best_practice"],description:"Category. Default: best_practice."},tags:{type:"array",items:{type:"string"},description:'Tags for categorization (e.g. "git", "automacao", "produtividade"). Optional.'}},required:["title","content"]}},{name:"explain_optimal_usage",description:'Generate an interactive tutorial explaining how to use smolerclaw more efficiently. Consults the living manual (via RAG or direct read) and recent insights to build a contextual guide. Use when the user asks "como usar melhor?", "dicas de uso", "tutorial", or seems to be using tools inefficiently.',input_schema:{type:"object",properties:{topic:{type:"string",description:'Optional topic to focus on (e.g. "workflows", "git", "tarefas"). If omitted, shows general tips.'}},required:[]}},{name:"trigger_self_reflection",description:"Manually trigger the self-reflection analysis. Analyzes recent actions to detect patterns, generate insights about repetitive tasks, underutilized tools, and inefficient patterns. Updates the living manual with findings. Use at end of session or when user asks for usage analysis.",input_schema:{type:"object",properties:{},required:[]}},{name:"get_usage_insights",description:'Get recent insights generated by the meta-learning engine. Shows detected patterns, tips, and recommendations based on observed usage. Use when the user asks "o que aprendi?", "insights de uso", or wants to see optimization suggestions.',input_schema:{type:"object",properties:{count:{type:"number",description:"Number of recent insights to show. Default 5."}},required:[]}}],BH=[{name:"propose_plan",description:"Submit a structured implementation plan for user approval. Use this BEFORE executing any non-trivial task that involves: - Multiple file modifications - Architectural decisions - Business logic changes - API integrations The plan must include objective, steps with targets, and risks/assumptions. Execution is BLOCKED until the user approves the plan.",input_schema:{type:"object",properties:{objective:{type:"string",description:'Concise description of the end goal (e.g., "Implement JWT authentication for /api/users")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",description:'What to do (e.g., "Create middleware")'},target:{type:"string",description:'Target file or module (e.g., "src/middleware/auth.ts")'},description:{type:"string",description:"Brief explanation of this step"},estimatedImpact:{type:"string",enum:["none","low","medium","high","critical"],description:"Risk level of this step. Default: low."},dependencies:{type:"array",items:{type:"string"},description:"IDs of steps that must complete first. Optional."}},required:["action","target","description"]},description:"Ordered list of implementation steps"},assumptions:{type:"array",items:{type:"string"},description:'Key assumptions being made (e.g., "JWT secret exists in .env")'},risks:{type:"array",items:{type:"string"},description:"Potential risks or breaking changes"}},required:["objective","steps"]}},{name:"check_plan_status",description:"Check if execution is allowed based on the current plan status. Returns whether you can proceed with modifications or need to wait for approval. Use this before any write operation if unsure about plan state.",input_schema:{type:"object",properties:{},required:[]}},{name:"report_plan_deviation",description:"Report that the current execution plan has encountered an obstacle. Use this when you discover something that invalidates the original plan. This STOPS execution and requires proposing an alternative approach. MANDATORY: Always explain what was found and propose a concrete alternative.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the step that encountered the obstacle. Optional if not in specific step."},obstacle:{type:"string",description:'What obstacle was encountered (e.g., "API does not support pagination")'},impact:{type:"string",description:'How this affects the plan (e.g., "Cannot proceed with step 3")'},alternative:{type:"string",description:"Proposed alternative approach"}},required:["obstacle","impact","alternative"]}},{name:"complete_plan_step",description:"Mark a plan step as completed and optionally provide the result. Use this after successfully completing each step in the approved plan. This helps track progress and enables checkpoint validation.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the completed step"},result:{type:"string",description:"Brief description of what was accomplished. Optional."}},required:["step_id"]}},{name:"get_current_plan",description:"Get the current active plan with its status and progress. Use to review the plan before continuing execution or to show status to user.",input_schema:{type:"object",properties:{},required:[]}},{name:"analyze_task_complexity",description:"Analyze a task description to determine its complexity and whether it requires planning. Returns complexity classification (trivial/simple/moderate/complex/architectural) and whether explicit approval is needed. Use this when unsure if planning is required.",input_schema:{type:"object",properties:{task:{type:"string",description:"Description of the task to analyze"},files:{type:"array",items:{type:"string"},description:"List of files that would be affected. Optional."},modules:{type:"array",items:{type:"string"},description:"List of modules/systems that would be affected. Optional."}},required:["task"]}}],CH=qY.find(($)=>$.name==="get_news"),YY=!1,G4=null;function UY($){G4=$}function WY(){if(YY)return;if(YY=!0,A)p.push(...qY),p.push(...VH),p.push(...GH);else p.push(CH);p.push(...rG),p.push(...iG),p.push(...sG),p.push(...tG),p.push(eG),p.push(...$H),p.push(...ZH),p.push(...QH),p.push(...qH),p.push(...HH),p.push(...YH),p.push(...JH),p.push(...XH),p.push(...KH),p.push(...UH),p.push(...zH),p.push(...WH),p.push(...BH)}var Y5=50000;async function HZ($,Z){let Q=performance.now();try{let Y=await NH($,Z);return setImmediate(()=>{JZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-Q),success:!Y.startsWith("Error:")})}),Y}catch(Y){return setImmediate(()=>{JZ({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-Q),success:!1})}),`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function NH($,Z){switch($){case"read_file":return MH(Z);case"write_file":return FH(Z);case"edit_file":return OH(Z);case"search_files":return await RH(Z);case"find_files":return await jH(Z);case"list_directory":return DH(Z);case"run_command":return await PH(Z);case"fetch_url":return await TH(Z);case"open_application":return await m4(Z.name,Z.argument);case"open_file_default":return await A1(Z.path);case"open_url_browser":return await p4(Z.url);case"get_running_apps":return await I1();case"get_system_info":return await c4();case"get_calendar_events":return await h$();case"get_news":{let Q=Z.category;return await E4(Q?[Q]:void 0)}case"create_task":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.time,J=Y?k1(Y):void 0,X=$7(Q,J||void 0),K=J?` \u2014 lembrete: ${J.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${X.title}"${K} [${X.id}]`}case"complete_task":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let Y=Z7(Q);return Y?`Concluida: "${Y.title}"`:`Tarefa nao encontrada: "${Q}"`}case"list_tasks":{let Q=Z.show_done||!1,Y=e$(Q);return l4(Y)}case"schedule_job":{let{name:Q,time:Y,message:J}=Z;if(!Q?.trim()||!Y?.trim()||!J?.trim())return"Error: name, time, and message are required.";let X=B7(Y);if(!X)return`Error: invalid time format "${Y}". Use HH:MM.`;let K=Z.schedule_type||"once",V;if(Z.date_or_day){let H=Z.date_or_day;if(K==="weekly")V=N7(H)??void 0;else V=C7(H)??void 0}if(K==="once"&&!V){let H=new Date,[z,B]=X.split(":").map(Number),W=new Date(H);if(W.setHours(z,B,0,0),W<=H)W.setDate(W.getDate()+1);V=[String(W.getMonth()+1).padStart(2,"0"),String(W.getDate()).padStart(2,"0"),String(W.getFullYear())].join("/")}let G=await G7(Q,K,X,"toast",J,V);return`Agendamento criado: "${G.name}" [${G.id}] \u2014 ${G.scheduleType} \xE0s ${G.time}`}case"remove_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await H7(Q)?"Agendamento removido.":`Agendamento nao encontrado: "${Q}"`}case"list_scheduled_jobs":{let Q=Z.include_disabled||!1,Y=b1(Q);return _1(Y)}case"enable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let Y=await q7(Q);return Y?`Agendamento "${Y.name}" ativado.`:`Agendamento nao encontrado: "${Q}"`}case"disable_scheduled_job":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";let Y=await U7(Q);return Y?`Agendamento "${Y.name}" desativado.`:`Agendamento nao encontrado: "${Q}"`}case"run_scheduled_job_now":{let Q=Z.reference;if(!Q?.trim())return"Error: reference is required.";return await W7(Q)}case"add_person":{let Q=Z.name;if(!Q?.trim())return"Error: name is required.";let Y=Z.group;if(!["equipe","familia","contato"].includes(Y))return"Error: group must be equipe, familia, or contato.";let X=j7(Q,Y,Z.role,Z.contact);return`Pessoa adicionada: ${X.name} (${Y}) [${X.id}]`}case"find_person_info":{let Q=Z.name_or_id;if(!Q?.trim())return"Error: name_or_id is required.";let Y=$4(Q);if(!Y)return`Pessoa nao encontrada: "${Q}"`;return A7(Y)}case"list_people":{let Q=Z.group,Y=D7(Q);return T7(Y)}case"log_interaction":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let{type:Y,summary:J}=Z;if(!J?.trim())return"Error: summary is required.";let X=Z.follow_up,K=X?KY(X):void 0;if(!F3(Q,Y,J,K||void 0))return`Pessoa nao encontrada: "${Q}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${Y} com ${Q}${G}`}case"delegate_to_person":{let Q=Z.person;if(!Q?.trim())return"Error: person is required.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let J=Z.due_date,X=J?KY(J):void 0,K=P7(Q,Y,X||void 0);if(!K)return`Pessoa nao encontrada: "${Q}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Q}: "${Y}"${V} [${K.id}]`}case"update_delegation_status":{let Q=Z.delegation_id;if(!Q?.trim())return"Error: delegation_id is required.";let Y=Z.status,J=O3(Q,Y,Z.notes);if(!J)return`Delegacao nao encontrada: "${Q}"`;return`Delegacao atualizada: "${J.task}" -> ${Y}`}case"get_people_dashboard":return E3();case"save_memo":{let Q=Z.content;if(!Q?.trim())return"Error: content is required.";let Y=Z.tags||[],J=Q7(Q,Y);return`Memo salvo${J.tags.length>0?` [${J.tags.map((K)=>"#"+K).join(" ")}]`:""} {${J.id}}`}case"search_memos":{let Q=Z.query;if(!Q?.trim())return o4(y1());let Y=Y7(Q);return o4(Y)}case"record_transaction":{let{type:Q,amount:Y,category:J,description:X}=Z;if(!Q||!Y||!J||!X)return"Error: all fields required.";let K=v1(Q,Y,J,X);return`${K.type==="entrada"?"+":"-"} R$ ${K.amount.toFixed(2)} (${K.category}) \u2014 ${K.description} [${K.id}]`}case"financial_summary":return F7();case"log_decision":{let{title:Q,context:Y,chosen:J}=Z;if(!Q||!Y||!J)return"Error: title, context, and chosen are required.";let X=z3(Q,Y,J,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${X.title}" {${X.id}}`}case"search_decisions":{let Q=Z.query;if(!Q?.trim())return F8(O7());return F8(a4(Q))}case"open_investigation":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.type;if(!["bug","feature","test","audit","incident"].includes(Y))return"Error: type must be bug, feature, test, audit, or incident.";let X=j9(Q,Y,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${X.title}" (${X.type}) {${X.id}}`}case"collect_evidence":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{source:Y,label:J,content:X}=Z;if(!J?.trim()||!X?.trim())return"Error: label and content are required.";let K=D9(Q,Y,J,X,Z.path);if(!K)return`Investigacao nao encontrada: "${Q}"`;return`Evidencia coletada: [${K.id}] ${K.source}: ${K.label}`}case"add_finding":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let{severity:Y,title:J,description:X}=Z;if(!J?.trim()||!X?.trim())return"Error: title and description are required.";let K=Z.evidence_ids||[],V=P9(Q,Y,J,X,K);if(!V)return`Investigacao nao encontrada: "${Q}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let Y=Z.summary;if(!Y?.trim())return"Error: summary is required.";let J=T9(Q,Y,Z.recommendations);if(!J)return`Investigacao nao encontrada: "${Q}"`;return`Investigacao concluida: "${J.title}" \u2014 ${J.evidence.length} evidencias, ${J.findings.length} conclusoes`}case"investigation_status":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let Y=A9(Q);if(!Y)return`Investigacao nao encontrada: "${Q}"`;return w9(Y)}case"investigation_report":{let Q=Z.investigation;if(!Q?.trim())return"Error: investigation is required.";let Y=S9(Q);if(!Y)return`Investigacao nao encontrada: "${Q}"`;return Y}case"list_investigations":{let Q=Z.query;if(Q?.trim())return E7(x9(Q));let{status:Y,type:J}=Z;return E7(I9(Y,J))}case"draft_email":{let{to:Q,subject:Y,body:J}=Z;if(!Q?.trim()||!Y?.trim()||!J?.trim())return"Error: to, subject, and body are required.";let X={to:Q,subject:Y,body:J,cc:Z.cc},K=X7(X),V=await J7(X);return`${K}
|
|
376
|
-
|
|
377
|
-
${
|
|
378
|
-
|
|
379
|
-
${
|
|
380
|
-
${J.
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
Duracao: ${z.toFixed(2)}ms
|
|
393
|
-
Memoria: ${(H.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
|
|
394
|
-
CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return YQ($Q());case"pitwall_remove_baseline":{let Q=Z.key;if(!Q?.trim())return"Error: key is required.";return r9(Q)?`Baseline removido: "${Q}"`:`Baseline nao encontrado: "${Q}"`}case"analyze_blast_radius":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let Y=b$(Z.project_dir||process.cwd()),J=b$(Y,Q);if(!J.startsWith(Y+A8))return"Error: file must be inside project_dir.";try{let X=t9(Y),K=e9(X,J);return GQ(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"plan_refactor":{let Q=Z.file;if(!Q?.trim())return"Error: file is required.";let Y=b$(Z.project_dir||process.cwd()),J=b$(Y,Q);if(!J.startsWith(Y+A8))return"Error: file must be inside project_dir.";try{let X=t9(Y),K=VQ(X,J);return qQ(K)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"archive_session":{if(!G4)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";if(Q==="all"){let Y=G4.archiveAll();return Y.length>0?`Arquivadas ${Y.length} sessoes: ${Y.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return G4.archive(Q)?`Sessao arquivada: "${Q}"`:`Falha ao arquivar "${Q}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!G4)return"Error: session manager not initialized.";let Q=Z.name;if(!Q?.trim())return"Error: name is required.";return G4.unarchive(Q)?`Sessao restaurada: "${Q}"`:`Sessao arquivada nao encontrada: "${Q}"`}case"list_archived_sessions":{if(!G4)return"Error: session manager not initialized.";let Q=G4.listArchived();if(Q.length===0)return"Nenhuma sessao arquivada.";let Y=Q.map((J)=>{let X=G4.getArchivedInfo(J),K=X?new Date(X.updated).toLocaleDateString("pt-BR"):"",V=X?`${X.messageCount} msgs`:"";return` ${J.padEnd(20)} ${V.padEnd(10)} ${K}`});return`Sessoes arquivadas (${Q.length}):
|
|
395
|
-
${Y.join(`
|
|
396
|
-
`)}`}case"evaluate_architecture_tradeoffs":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.background;if(!Y?.trim())return"Error: background is required.";let J=Z.options;if(!J||J.length<2)return"Error: at least 2 options are required.";let X={title:Q.trim(),background:Y.trim(),constraints:Z.constraints||[],stakeholders:Z.stakeholders||[]},K=J.map((z)=>({name:z.name.trim(),description:z.description.trim(),scores:z.scores,pros:z.pros||[],cons:z.cons||[]})),V=Z.custom_criteria,G=V&&V.length>0?V:ZZ;return FQ(X,K,G).adr}case"correlate_incident":{let Q=Z.description;if(!Q?.trim())return"Error: description is required.";let Y=Z.stacktrace;return OQ(Q,Y).summary}case"log_incident":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.description;if(!Y?.trim())return"Error: description is required.";let J=Z.root_cause;if(!J?.trim())return"Error: root_cause is required.";let X=Z.solution;if(!X?.trim())return"Error: solution is required.";let K=RQ(Q,Y,J,X,Z.stacktrace,Z.related_decisions||[],Z.tags||[]);return`Incidente registrado: "${K.title}" {${K.id}}
|
|
397
|
-
Causa: ${K.rootCause.slice(0,80)}${K.rootCause.length>80?"...":""}
|
|
398
|
-
Solucao: ${K.solution.slice(0,80)}${K.solution.length>80?"...":""}`}case"list_tradeoff_analyses":{let Q=Z.limit||10,Y=Z.query,J=Y?DQ(Y).slice(0,Q):jQ(Q);return TQ(J)}case"list_incidents":{let Q=Z.limit||10,Y=Z.query,J=Y?EQ(Y).slice(0,Q):LQ(Q);return AQ(J)}case"get_tradeoff_adr":{let Q=Z.id;if(!Q?.trim())return"Error: id is required.";let Y=PQ(Q);if(!Y)return`Trade-off nao encontrado: "${Q}"`;return Y.adr}case"update_living_manual":{let Q=Z.title;if(!Q?.trim())return"Error: title is required.";let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let J=Z.category||"best_practice",X=Z.tags||[],K=await hQ(Q,Y,J,X);if(!K.success)return"Falha ao atualizar o manual. Verifique se o docs-engine foi inicializado.";return`Manual atualizado: "${Q}" (${J})
|
|
399
|
-
Arquivo: ${K.path}`}case"explain_optimal_usage":{let Q=Z.topic;return gQ(Q)}case"trigger_self_reflection":{let Q=await d1();return cQ(Q)}case"get_usage_insights":{let Q=Math.min(Math.max(Z.count||5,1),20),Y=fQ(Q);return uQ(Y)}case"propose_plan":{if(!V4())return"Error: Agency engine not initialized. Planning features unavailable.";let Q=Z.objective;if(!Q?.trim())return"Error: objective is required.";let Y=Z.steps;if(!Y?.length)return"Error: at least one step is required.";let J=Y.map((G)=>({action:G.action,target:G.target,description:G.description,estimatedImpact:G.estimatedImpact||"low",dependencies:G.dependencies||[]})),X=rQ(Q,J,{assumptions:Z.assumptions,risks:Z.risks}),K=await iQ();if(!K.success)return`Error creating plan: ${K.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
|
|
400
|
-
|
|
401
|
-
${zZ(X)}`}case"check_plan_status":{if(!V4())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Q=sQ(),Y=o1();if(!Y)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${$Y(Y)}
|
|
402
|
-
|
|
403
|
-
Execu\xE7\xE3o: ${Q.allowed?"PERMITIDA":"BLOQUEADA"}
|
|
404
|
-
Motivo: ${Q.reason}`}case"report_plan_deviation":{if(!V4())return"Error: Agency engine not initialized.";let{obstacle:Q,impact:Y,alternative:J}=Z;if(!Q?.trim())return"Error: obstacle is required.";if(!Y?.trim())return"Error: impact is required.";if(!J?.trim())return"Error: alternative is required.";let X=o1();if(!X)return"Nenhum plano ativo. N\xE3o h\xE1 desvio a reportar.";let K=Z.step_id,V=K?X.strategy.find((G)=>G.id===K):X.strategy.find((G)=>G.status==="in_progress"||G.status==="pending");if(V)eQ(V.id,Q,J);return["**Desvio Detectado**","",`**Obst\xE1culo:** ${Q}`,`**Impacto no Plano:** ${Y}`,"","**Alternativa Proposta:**",J,"","**Status:** Execu\xE7\xE3o BLOQUEADA. Aguardando aprova\xE7\xE3o da alternativa.","","**Bloqueio:** Posso prosseguir com esta alternativa?"].join(`
|
|
405
|
-
`)}case"complete_plan_step":{if(!V4())return"Error: Agency engine not initialized.";let Q=Z.step_id;if(!Q?.trim())return"Error: step_id is required.";let Y=tQ(Q,Z.result);if(!Y.success)return`Error: ${Y.message}`;let J=o1(),X=J?`Progresso: ${J.strategy.filter((V)=>V.status==="completed").length}/${J.strategy.length}`:"",K=Y.nextStep?`
|
|
406
|
-
Pr\xF3ximo passo: ${Y.nextStep.action} \u2192 ${Y.nextStep.target}`:`
|
|
407
|
-
Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${Y.message}
|
|
408
|
-
${X}${K}`}case"get_current_plan":{if(!V4())return"Agency engine not initialized. No planning features available.";let Q=o1();if(!Q)return"Nenhum plano ativo no momento.";return zZ(Q)}case"analyze_task_complexity":{if(!V4())return"Agency engine not initialized. Cannot analyze complexity.";let Q=Z.task;if(!Q?.trim())return"Error: task is required.";let Y=KZ(Q,{files:Z.files,modules:Z.modules}),J=["**An\xE1lise de Complexidade**","",`**Tarefa:** ${Q}`,`**Classifica\xE7\xE3o:** ${Y.complexity}`,`**Requer Aprova\xE7\xE3o:** ${Y.requiresApproval?"SIM":"N\xC3O"}`,"",`**Motivo:** ${Y.reason}`];if(Y.risks.length>0){J.push("","**Riscos Identificados:**");for(let X of Y.risks)J.push(` - ${X}`)}if(Y.assumptions.length>0){J.push("","**Premissas:**");for(let X of Y.assumptions)J.push(` - ${X}`)}if(Y.requiresApproval)J.push("","**Recomenda\xE7\xE3o:** Use `propose_plan` antes de executar esta tarefa.");return J.join(`
|
|
409
|
-
`)}default:{let Q=GY.find((Y)=>Y.name===$);if(Q)return await M6(Q,Z);return`Error: unknown tool "${$}"`}}}var JY=10485760;function S8($){let Z=b$($),Q=process.cwd();if(Z!==Q&&!Z.startsWith(Q+A8))return`Error: path outside working directory is not permitted: ${Z}`;try{if(a1(Z)){let Y=nG(Z);if(Y!==Q&&!Y.startsWith(Q+A8))return`Error: symlink target is outside working directory: ${Y}`}}catch{}return null}function w8($,Z){let Q=$[Z];if(typeof Q!=="string"||Q.trim().length===0)return`Error: '${Z}' is required and must be a non-empty string.`;return null}function MH($){let Z=w8($,"path");if(Z)return Z;let Q=b$($.path),Y=S8(Q);if(Y)return Y;if(!a1(Q))return`Error: file not found: ${Q}`;let J=zY(Q).size;if(J>JY)return`Error: file too large (${VZ(J)}). Max is ${VZ(JY)}.`;let K=GZ(Q,"utf-8").split(`
|
|
410
|
-
`),V=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),B=K.slice(V-1,V-1+G).map((N,O)=>`${String(V+O).padStart(4)} ${N}`).join(`
|
|
411
|
-
`),W=K.length-(V-1+G);if(W>0)B+=`
|
|
412
|
-
... (${W} more lines, total ${K.length})`;return I8(B)}function FH($){let Z=w8($,"path");if(Z)return Z;let Q=b$($.path),Y=S8(Q);if(Y)return Y;let J=$.content,X=a1(Q);x8.saveState(Q),S(Q,J);let K=J.split(`
|
|
413
|
-
`).length;return`${X?"Updated":"Created"}: ${Q} (${K} lines)`}function OH($){let Z=w8($,"path");if(Z)return Z;let Q=b$($.path),Y=S8(Q);if(Y)return Y;if(!a1(Q))return`Error: file not found: ${Q}`;let J=GZ(Q,"utf-8"),X=$.old_text,K=$.new_text,V=J.split(X).length-1;if(V===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(V>1)return`Error: old_text found ${V} times. It must be unique. Include more surrounding context.`;x8.saveState(Q);let G=J.split(X).join(K);S(Q,G);let H=X.split(`
|
|
414
|
-
`).length,z=K.split(`
|
|
415
|
-
`).length;return`Edited: ${Q} (replaced ${H} lines with ${z} lines)`}async function RH($){let Z=w8($,"pattern");if(Z)return Z;let Q=$.pattern,Y=b$($.path||"."),J=S8(Y);if(J)return J;let X=$.include;if(await Y2())return EH(Q,Y,X);return LH(Q,Y,X)}async function EH($,Z,Q){let Y=["rg","--no-heading","--line-number","--color=never"];if(Q)Y.push("--glob",Q);for(let V of y8)Y.push("--glob",`!${V}`);Y.push("-e",$,Z);let J=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe"}),X=await new Response(J.stdout).text(),K=await new Response(J.stderr).text();if(await J.exited,!X.trim()&&!K.trim())return"No matches found.";if(K.trim()&&!X.trim())return`Error: ${K.trim()}`;return IH(X,Z)}async function LH($,Z,Q){let Y;try{Y=new RegExp($)}catch(z){return`Error: invalid regex pattern: ${z instanceof Error?z.message:$}`}let J=Q||"**/*",X=new Bun.Glob(J),K=[],V=0,G=5000;for await(let z of X.scan({cwd:Z,onlyFiles:!0})){if(R5(z))continue;if(++V>G){K.push(`... (stopped after scanning ${G} files)`);break}let B=VY(Z,z);try{let N=GZ(B,"utf-8").split(`
|
|
416
|
-
`);for(let O=0;O<N.length;O++)if(Y.test(N[O])){if(K.push(`${z}:${O+1}:${N[O]}`),K.length>=100)break}}catch{}if(K.length>=100)break}if(K.length===0)return"No matches found.";let H=K.slice(0,100).join(`
|
|
417
|
-
`);if(K.length>100)H+=`
|
|
418
|
-
... (showing first 100 matches)`;return I8(H)}async function jH($){let Z=w8($,"pattern");if(Z)return Z;let Q=$.pattern,Y=b$($.path||"."),J=S8(Y);if(J)return J;let X=new Bun.Glob(Q),K=[];for await(let G of X.scan({cwd:Y,onlyFiles:!0})){if(R5(G))continue;if(K.push(G),K.length>=200)break}if(K.length===0)return"No files found.";let V=K.join(`
|
|
419
|
-
`);if(K.length>=200)V+=`
|
|
420
|
-
... (showing first 200 files)`;return V}function DH($){let Z=b$($.path||"."),Q=S8(Z);if(Q)return Q;if(!a1(Z))return`Error: not found: ${Z}`;return oG(Z,{withFileTypes:!0}).sort((X,K)=>{if(X.isDirectory()!==K.isDirectory())return X.isDirectory()?-1:1;return X.name.localeCompare(K.name)}).map((X)=>{if(X.isDirectory())return`d ${X.name}/`;try{let K=zY(VY(Z,X.name)),V=VZ(K.size);return`f ${X.name} ${V}`}catch{return`f ${X.name}`}}).join(`
|
|
421
|
-
`)}async function PH($){let Z=w8($,"command");if(Z)return Z;let Q=$.command,Y=Math.min(120,Math.max(5,$.timeout||30)),J=Q8(),X=Bun.spawn([...J,Q],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),K=setTimeout(()=>X.kill(),Y*1000),[V,G]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),H=await X.exited;clearTimeout(K);let z="";if(V.trim())z+=V.trim();if(G.trim())z+=(z?`
|
|
422
|
-
`:"")+`STDERR:
|
|
423
|
-
`+G.trim();if(H!==0)z+=(z?`
|
|
424
|
-
`:"")+`Exit code: ${H}`;return I8(z||"(no output)")}async function TH($){let Z=$.url,Q=$.method||"GET",Y=$.headers||{},J=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let X=XY(Z);if(X)return X;try{let K=new AbortController,V=setTimeout(()=>K.abort(),30000),G=await fetch(Z,{method:Q,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Y},body:J&&Q!=="GET"&&Q!=="HEAD"?J:void 0,signal:K.signal});if(clearTimeout(V),G.status>=300&&G.status<400){let N=G.headers.get("location");if(!N)return`Status: ${G.status} (redirect with no location header)`;let O=XY(N);if(O)return`Redirect blocked: ${O}`;return`Status: ${G.status} -> Redirect to: ${N}
|
|
425
|
-
(Use fetch_url on the redirect target if needed)`}let H=`${G.status} ${G.statusText}`,z=G.headers.get("content-type")||"";if(Q==="HEAD"){let N=[...G.headers.entries()].map(([O,j])=>`${O}: ${j}`).join(`
|
|
426
|
-
`);return`Status: ${H}
|
|
427
|
-
${N}`}let B=G.headers.get("content-length");if(B&&Number(B)>Y5*2)return`Status: ${H}
|
|
397
|
+
`.trim()}var P5=[{name:"propose_plan",description:"Submit a structured implementation plan for user approval. Use this BEFORE executing any non-trivial task that involves: - Multiple file modifications - Architectural decisions - Business logic changes - API integrations The plan must include objective, steps with targets, and risks/assumptions. Execution is BLOCKED until the user approves the plan.",input_schema:{type:"object",properties:{objective:{type:"string",description:'Concise description of the end goal (e.g., "Implement JWT authentication for /api/users")'},steps:{type:"array",items:{type:"object",properties:{action:{type:"string",description:'What to do (e.g., "Create middleware")'},target:{type:"string",description:'Target file or module (e.g., "src/middleware/auth.ts")'},description:{type:"string",description:"Brief explanation of this step"},estimatedImpact:{type:"string",enum:["none","low","medium","high","critical"],description:"Risk level of this step. Default: low."},dependencies:{type:"array",items:{type:"string"},description:"IDs of steps that must complete first. Optional."}},required:["action","target","description"]},description:"Ordered list of implementation steps"},assumptions:{type:"array",items:{type:"string"},description:'Key assumptions being made (e.g., "JWT secret exists in .env")'},risks:{type:"array",items:{type:"string"},description:"Potential risks or breaking changes"}},required:["objective","steps"]}},{name:"check_plan_status",description:"Check if execution is allowed based on the current plan status. Returns whether you can proceed with modifications or need to wait for approval. Use this before any write operation if unsure about plan state.",input_schema:{type:"object",properties:{},required:[]}},{name:"report_plan_deviation",description:"Report that the current execution plan has encountered an obstacle. Use this when you discover something that invalidates the original plan. This STOPS execution and requires proposing an alternative approach. MANDATORY: Always explain what was found and propose a concrete alternative.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the step that encountered the obstacle. Optional if not in specific step."},obstacle:{type:"string",description:'What obstacle was encountered (e.g., "API does not support pagination")'},impact:{type:"string",description:'How this affects the plan (e.g., "Cannot proceed with step 3")'},alternative:{type:"string",description:"Proposed alternative approach"}},required:["obstacle","impact","alternative"]}},{name:"complete_plan_step",description:"Mark a plan step as completed and optionally provide the result. Use this after successfully completing each step in the approved plan. This helps track progress and enables checkpoint validation.",input_schema:{type:"object",properties:{step_id:{type:"string",description:"ID of the completed step"},result:{type:"string",description:"Brief description of what was accomplished. Optional."}},required:["step_id"]}},{name:"get_current_plan",description:"Get the current active plan with its status and progress. Use to review the plan before continuing execution or to show status to user.",input_schema:{type:"object",properties:{},required:[]}},{name:"analyze_task_complexity",description:"Analyze a task description to determine its complexity and whether it requires planning. Returns complexity classification (trivial/simple/moderate/complex/architectural) and whether explicit approval is needed. Use this when unsure if planning is required.",input_schema:{type:"object",properties:{task:{type:"string",description:"Description of the task to analyze"},files:{type:"array",items:{type:"string"},description:"List of files that would be affected. Optional."},modules:{type:"array",items:{type:"string"},description:"List of modules/systems that would be affected. Optional."}},required:["task"]}}];async function yQ($,Z){switch($){case"propose_plan":{if(!$0())return"Error: Agency engine not initialized. Planning features unavailable.";let Y=Z.objective;if(!Y?.trim())return"Error: objective is required.";let Q=Z.steps;if(!Q?.length)return"Error: at least one step is required.";let J=Q.map((V)=>({action:V.action,target:V.target,description:V.description,estimatedImpact:V.estimatedImpact||"low",dependencies:V.dependencies||[]})),z=DQ(Y,J,{assumptions:Z.assumptions,risks:Z.risks}),K=await PQ();if(!K.success)return`Error creating plan: ${K.message}`;return`Plano criado e aguardando aprova\xE7\xE3o.
|
|
398
|
+
|
|
399
|
+
${w9(z)}`}case"check_plan_status":{if(!$0())return"Agency engine not initialized. All operations allowed (no planning enforcement).";let Y=TQ(),Q=d8();if(!Q)return"Nenhum plano ativo. Opera\xE7\xF5es triviais permitidas sem planejamento.";return`${SQ(Q)}
|
|
400
|
+
|
|
401
|
+
Execu\xE7\xE3o: ${Y.allowed?"PERMITIDA":"BLOQUEADA"}
|
|
402
|
+
Motivo: ${Y.reason}`}case"report_plan_deviation":{if(!$0())return"Error: Agency engine not initialized.";let{obstacle:Y,impact:Q,alternative:J}=Z;if(!Y?.trim())return"Error: obstacle is required.";if(!Q?.trim())return"Error: impact is required.";if(!J?.trim())return"Error: alternative is required.";let z=d8();if(!z)return"Nenhum plano ativo. N\xE3o h\xE1 desvio a reportar.";let K=Z.step_id,X=K?z.strategy.find((V)=>V.id===K):z.strategy.find((V)=>V.status==="in_progress"||V.status==="pending");if(X)IQ(X.id,Y,J);return["**Desvio Detectado**","",`**Obst\xE1culo:** ${Y}`,`**Impacto no Plano:** ${Q}`,"","**Alternativa Proposta:**",J,"","**Status:** Execu\xE7\xE3o BLOQUEADA. Aguardando aprova\xE7\xE3o da alternativa.","","**Bloqueio:** Posso prosseguir com esta alternativa?"].join(`
|
|
403
|
+
`)}case"complete_plan_step":{if(!$0())return"Error: Agency engine not initialized.";let Y=Z.step_id;if(!Y?.trim())return"Error: step_id is required.";let Q=AQ(Y,Z.result);if(!Q.success)return`Error: ${Q.message}`;let J=d8(),z=J?`Progresso: ${J.strategy.filter((X)=>X.status==="completed").length}/${J.strategy.length}`:"",K=Q.nextStep?`
|
|
404
|
+
Pr\xF3ximo passo: ${Q.nextStep.action} \u2192 ${Q.nextStep.target}`:`
|
|
405
|
+
Todos os passos conclu\xEDdos!`;return`Passo conclu\xEDdo: ${Q.message}
|
|
406
|
+
${z}${K}`}case"get_current_plan":{if(!$0())return"Agency engine not initialized. No planning features available.";let Y=d8();if(!Y)return"Nenhum plano ativo no momento.";return w9(Y)}case"analyze_task_complexity":{if(!$0())return"Agency engine not initialized. Cannot analyze complexity.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=S9(Y,{files:Z.files,modules:Z.modules}),J=["**An\xE1lise de Complexidade**","",`**Tarefa:** ${Y}`,`**Classifica\xE7\xE3o:** ${Q.complexity}`,`**Requer Aprova\xE7\xE3o:** ${Q.requiresApproval?"SIM":"N\xC3O"}`,"",`**Motivo:** ${Q.reason}`];if(Q.risks.length>0){J.push("","**Riscos Identificados:**");for(let z of Q.risks)J.push(` - ${z}`)}if(Q.assumptions.length>0){J.push("","**Premissas:**");for(let z of Q.assumptions)J.push(` - ${z}`)}if(Q.requiresApproval)J.push("","**Recomenda\xE7\xE3o:** Use `propose_plan` antes de executar esta tarefa.");return J.join(`
|
|
407
|
+
`)}default:return null}}p();import{existsSync as bQ,readdirSync as gq,readFileSync as mq,mkdirSync as uq}from"fs";import{join as k9}from"path";function _Q($){if(!bQ($))return[];let Z=[],Y=gq($).filter((Q)=>Q.endsWith(".json"));for(let Q of Y)try{let J=JSON.parse(mq(k9($,Q),"utf-8"));if(!J.name||!J.description||!J.command)continue;if(typeof J.name!=="string"||typeof J.command!=="string")continue;if(J.command.includes("$(")||J.command.includes("`"))continue;Z.push({name:J.name,description:J.description,inputSchema:J.input_schema||{type:"object",properties:{},required:[]},command:J.command,source:k9($,Q)})}catch{}return Z}function xQ($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function fQ($,Z){let Y=$.command;for(let[q,U]of Object.entries(Z)){let W=String(U).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${q}\\}\\}`,"g"),W)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let Q=t0(),J=Bun.spawn([...Q,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),z=setTimeout(()=>J.kill(),30000),[K,X]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),V=await J.exited;clearTimeout(z);let G=K.trim();if(X.trim())G+=(G?`
|
|
408
|
+
`:"")+X.trim();if(V!==0)G+=(G?`
|
|
409
|
+
`:"")+`Exit code: ${V}`;return G||"(no output)"}function vQ($){if($.length===0)return"No plugins loaded. Add .json files to ~/.config/smolerclaw/plugins/";return`Plugins:
|
|
410
|
+
`+$.map((Z)=>` ${Z.name} \u2014 ${Z.description}`).join(`
|
|
411
|
+
`)}function hQ($){let Z=k9($,"plugins");if(!bQ(Z))uq(Z,{recursive:!0});return Z}f();import{existsSync as _9,readFileSync as uQ,statSync as lq}from"fs";import{resolve as x9}from"path";import{existsSync as pq,realpathSync as dq}from"fs";import{resolve as cq,sep as gQ}from"path";var y9=10485760;function j0($){let Z=cq($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+gQ))return`Error: path outside working directory is not permitted: ${Z}`;try{if(pq(Z)){let Q=dq(Z);if(Q!==Y&&!Q.startsWith(Y+gQ))return`Error: symlink target is outside working directory: ${Q}`}}catch{}return null}function Z0($,Z){let Y=$[Z];if(typeof Y!=="string"||Y.trim().length===0)return`Error: '${Z}' is required and must be a non-empty string.`;return null}function b9($){try{let Z=new URL($),Y=Z.hostname.toLowerCase();if(Z.protocol!=="http:"&&Z.protocol!=="https:")return`Error: protocol ${Z.protocol} is not allowed.`;if(["localhost","127.0.0.1","::1","0.0.0.0","::ffff:127.0.0.1","::ffff:0.0.0.0"].includes(Y))return"Error: requests to localhost are blocked for security.";if(Y.endsWith(".local")||Y.endsWith(".internal"))return"Error: requests to internal hostnames are blocked.";if(Y==="metadata.google.internal"||Y==="metadata.gcp.internal")return"Error: requests to cloud metadata endpoints are blocked.";let J=Y.split(".").map(Number);if(J.length===4&&J.every((z)=>!isNaN(z)&&z>=0&&z<=255)){if(J[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(J[0]===172&&J[1]>=16&&J[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(J[0]===192&&J[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(J[0]===169&&J[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(J[0]===0)return"Error: requests to 0.x IPs are blocked."}if(Y.startsWith("::ffff:")||Y.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function mQ($){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,`
|
|
412
|
+
`).replace(/<(br|hr)[^>]*\/?>/gi,`
|
|
413
|
+
`).replace(/<[^>]+>/g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
428
414
|
|
|
429
|
-
Error:
|
|
415
|
+
`).trim()}function pQ($){let Z=Z0($,"path");if(Z)return Z;let Y=x9($.path),Q=j0(Y);if(Q)return Q;if(!_9(Y))return`Error: file not found: ${Y}`;let J=lq(Y).size;if(J>y9)return`Error: file too large (${m8(J)}). Max is ${m8(y9)}.`;let K=uQ(Y,"utf-8").split(`
|
|
416
|
+
`),X=Math.max(1,$.offset||1),V=Math.min(2000,$.limit||500),U=K.slice(X-1,X-1+V).map((B,M)=>`${String(X+M).padStart(4)} ${B}`).join(`
|
|
417
|
+
`),W=K.length-(X-1+V);if(W>0)U+=`
|
|
418
|
+
... (${W} more lines, total ${K.length})`;return y$(U)}function dQ($,Z){let Y=Z0($,"path");if(Y)return Y;let Q=x9($.path),J=j0(Q);if(J)return J;let z=$.content,K=_9(Q);Z.saveState(Q),D(Q,z);let X=z.split(`
|
|
419
|
+
`).length;return`${K?"Updated":"Created"}: ${Q} (${X} lines)`}function cQ($,Z){let Y=Z0($,"path");if(Y)return Y;let Q=x9($.path),J=j0(Q);if(J)return J;if(!_9(Q))return`Error: file not found: ${Q}`;let z=uQ(Q,"utf-8"),K=$.old_text,X=$.new_text,V=z.split(K).length-1;if(V===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(V>1)return`Error: old_text found ${V} times. It must be unique. Include more surrounding context.`;Z.saveState(Q);let G=z.split(K).join(X);D(Q,G);let q=K.split(`
|
|
420
|
+
`).length,U=X.split(`
|
|
421
|
+
`).length;return`Edited: ${Q} (replaced ${q} lines with ${U} lines)`}p();import{existsSync as oq,readdirSync as iq,readFileSync as nq,statSync as aq}from"fs";import{resolve as f9,join as oQ,sep as lQ}from"path";async function iQ($){let Z=Z0($,"pattern");if(Z)return Z;let Y=$.pattern,Q=f9($.path||"."),J=j0(Q);if(J)return J;let z=$.include;if(await bZ())return rq(Y,Q,z);return sq(Y,Q,z)}async function rq($,Z,Y){let Q=["rg","--no-heading","--line-number","--color=never"];if(Y)Q.push("--glob",Y);for(let X of S1)Q.push("--glob",`!${X}`);Q.push("-e",$,Z);let J=Bun.spawn(Q,{stdout:"pipe",stderr:"pipe"}),z=await new Response(J.stdout).text(),K=await new Response(J.stderr).text();if(await J.exited,!z.trim()&&!K.trim())return"No matches found.";if(K.trim()&&!z.trim())return`Error: ${K.trim()}`;return tq(z,Z)}async function sq($,Z,Y){let Q;try{Q=new RegExp($)}catch(q){return`Error: invalid regex pattern: ${q instanceof Error?q.message:$}`}let J=Y||"**/*",z=new Bun.Glob(J),K=[],X=0,V=5000;for await(let q of z.scan({cwd:Z,onlyFiles:!0})){if(l5(q))continue;if(++X>V){K.push(`... (stopped after scanning ${V} files)`);break}let U=oQ(Z,q);try{let B=nq(U,"utf-8").split(`
|
|
422
|
+
`);for(let M=0;M<B.length;M++)if(Q.test(B[M])){if(K.push(`${q}:${M+1}:${B[M]}`),K.length>=100)break}}catch{}if(K.length>=100)break}if(K.length===0)return"No matches found.";let G=K.slice(0,100).join(`
|
|
423
|
+
`);if(K.length>100)G+=`
|
|
424
|
+
... (showing first 100 matches)`;return y$(G)}async function nQ($){let Z=Z0($,"pattern");if(Z)return Z;let Y=$.pattern,Q=f9($.path||"."),J=j0(Q);if(J)return J;let z=new Bun.Glob(Y),K=[];for await(let V of z.scan({cwd:Q,onlyFiles:!0})){if(l5(V))continue;if(K.push(V),K.length>=200)break}if(K.length===0)return"No files found.";let X=K.join(`
|
|
425
|
+
`);if(K.length>=200)X+=`
|
|
426
|
+
... (showing first 200 files)`;return X}function aQ($){let Z=f9($.path||"."),Y=j0(Z);if(Y)return Y;if(!oq(Z))return`Error: not found: ${Z}`;return iq(Z,{withFileTypes:!0}).sort((z,K)=>{if(z.isDirectory()!==K.isDirectory())return z.isDirectory()?-1:1;return z.name.localeCompare(K.name)}).map((z)=>{if(z.isDirectory())return`d ${z.name}/`;try{let K=aq(oQ(Z,z.name)),X=m8(K.size);return`f ${z.name} ${X}`}catch{return`f ${z.name}`}}).join(`
|
|
427
|
+
`)}function tq($,Z){let Y=process.cwd(),Q=Y+lQ,J=Z+lQ,K=$.trim().split(`
|
|
428
|
+
`).map((G)=>{if(G.startsWith(Q))return"."+G.slice(Y.length).replace(/\\/g,"/");if(G.startsWith(J))return"."+G.slice(Z.length).replace(/\\/g,"/");return G}),X=K.length,V=K.slice(0,100).join(`
|
|
429
|
+
`);if(X>100)V+=`
|
|
430
|
+
... (${X-100} more matches)`;return y$(V)}p();async function rQ($){let Z=Z0($,"command");if(Z)return Z;let Y=$.command,Q=Math.min(120,Math.max(5,$.timeout||30)),J=t0(),z=Bun.spawn([...J,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),K=setTimeout(()=>z.kill(),Q*1000),[X,V]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),G=await z.exited;clearTimeout(K);let q="";if(X.trim())q+=X.trim();if(V.trim())q+=(q?`
|
|
431
|
+
`:"")+`STDERR:
|
|
432
|
+
`+V.trim();if(G!==0)q+=(q?`
|
|
433
|
+
`:"")+`Exit code: ${G}`;return y$(q||"(no output)")}async function sQ($){let Z=$.url,Y=$.method||"GET",Q=$.headers||{},J=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let z=b9(Z);if(z)return z;try{let K=new AbortController,X=setTimeout(()=>K.abort(),30000),V=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Q},body:J&&Y!=="GET"&&Y!=="HEAD"?J:void 0,signal:K.signal});if(clearTimeout(X),V.status>=300&&V.status<400){let B=V.headers.get("location");if(!B)return`Status: ${V.status} (redirect with no location header)`;let M=b9(B);if(M)return`Redirect blocked: ${M}`;return`Status: ${V.status} -> Redirect to: ${B}
|
|
434
|
+
(Use fetch_url on the redirect target if needed)`}let G=`${V.status} ${V.statusText}`,q=V.headers.get("content-type")||"";if(Y==="HEAD"){let B=[...V.headers.entries()].map(([M,O])=>`${M}: ${O}`).join(`
|
|
435
|
+
`);return`Status: ${G}
|
|
436
|
+
${B}`}let U=V.headers.get("content-length");if(U&&Number(U)>g8*2)return`Status: ${G}
|
|
430
437
|
|
|
431
|
-
${
|
|
438
|
+
Error: response body too large (${U} bytes). Max is ${g8*2} bytes.`;let W=await V.text();if(q.includes("text/html")){let B=mQ(W);return y$(`Status: ${G}
|
|
432
439
|
|
|
433
|
-
${
|
|
434
|
-
`).replace(/<(br|hr)[^>]*\/?>/gi,`
|
|
435
|
-
`).replace(/<[^>]+>/g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
440
|
+
${B}`)}return y$(`Status: ${G}
|
|
436
441
|
|
|
437
|
-
`).
|
|
438
|
-
`).map((H)=>{if(H.startsWith(Y))return"."+H.slice(Q.length).replace(/\\/g,"/");if(H.startsWith(J))return"."+H.slice(Z.length).replace(/\\/g,"/");return H}),V=K.length,G=K.slice(0,100).join(`
|
|
439
|
-
`);if(V>100)G+=`
|
|
440
|
-
... (${V-100} more matches)`;return I8(G)}function I8($){if($.length<=Y5)return $;return $.slice(0,Y5)+`
|
|
441
|
-
... (output truncated)`}function VZ($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function KY($){let Z=$.toLowerCase().trim(),Q=new Date;if(Z==="hoje")return Q;if(Z==="amanha"||Z==="amanh\xE3"){let V=new Date(Q);return V.setDate(V.getDate()+1),V}let Y=Z.match(/em\s+(\d+)\s*dias?/);if(Y){let V=new Date(Q);return V.setDate(V.getDate()+parseInt(Y[1])),V}let J=Z.match(/em\s+(\d+)\s*semanas?/);if(J){let V=new Date(Q);return V.setDate(V.getDate()+parseInt(J[1])*7),V}let X={domingo:0,segunda:1,terca:2,ter\u{e7}a:2,quarta:3,quinta:4,sexta:5,sabado:6,s\u{e1}bado:6};for(let[V,G]of Object.entries(X))if(Z.includes(V)){let H=new Date(Q),z=(G-H.getDay()+7)%7||7;return H.setDate(H.getDate()+z),H}let K=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(K){let V=parseInt(K[1]),G=parseInt(K[2])-1,H=K[3]?parseInt(K[3])+(K[3].length===2?2000:0):Q.getFullYear(),z=new Date(H,G,V);if(!isNaN(z.getTime()))return z}return k1(Z)}var xH=new Set([429,500,502,503,529]);async function CY($,Z={}){let Q=Z.maxRetries??3,Y=Z.baseDelayMs??1000,J;for(let X=0;X<=Q;X++)try{return await $()}catch(K){if(J=K,Z.signal?.aborted)throw K;if(X>=Q)throw K;if(SH(K)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(X+1,500,"Auth refreshed, retrying..."),await BY(500,Z.signal);continue}}if(!wH(K))throw K;let G=kH(K)??Y*Math.pow(2,X),H=K instanceof Error?K.message:String(K);Z.onRetry?.(X+1,G,H),await BY(G,Z.signal)}throw J}function SH($){if(!($ instanceof Error))return!1;return $.status===401}function wH($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&xH.has(Z))return!0;let Q=$.message.toLowerCase();if(Q.includes("econnreset")||Q.includes("econnrefused"))return!0;if(Q.includes("etimedout")||Q.includes("socket hang up"))return!0;if(Q.includes("overloaded"))return!0;return!1}function kH($){let Z=$.headers;if(!Z)return null;let Q=Z["retry-after"];if(!Q)return null;let Y=Number(Q);if(!isNaN(Y)&&Y>0)return Math.min(Y,60)*1000;return null}function BY($,Z){return new Promise((Q,Y)=>{let J=setTimeout(Q,$);Z?.addEventListener("abort",()=>{clearTimeout(J),Y(Error("Aborted"))},{once:!0})})}var yH={haiku:200000,sonnet:200000,opus:200000};function x4($){return Math.ceil($.length/3.5)}function qZ($){let Z=0;for(let Q of $){if(Z+=x4(Q.content),Q.toolCalls)for(let Y of Q.toolCalls)Z+=x4(JSON.stringify(Y.input)),Z+=x4(Y.result);Z+=10}return Z}function UZ($){let Z=$.toLowerCase();for(let[Q,Y]of Object.entries(yH))if(Z.includes(Q))return Y;return 200000}function NY($,Z,Q){let Y=UZ(Z)-20000-Q;if(qZ($)<=Y)return $;let X=[],K=Y,V=[...$].reverse(),G=[];for(let z of V){let B=x4(z.content)+(z.toolCalls?.reduce((W,N)=>W+x4(JSON.stringify(N.input))+x4(N.result),0)??0)+10;if(K-B<0)break;K-=B,G.unshift(z)}let H=$.length-G.length;if(H>0)X.push({role:"user",content:`[Note: ${H} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return X.push(...G),X}function MY($,Z,Q){let Y=UZ(Z)-20000-Q;return qZ($)>Y*0.7}function FY($,Z,Q){let Y=UZ(Z)-20000-Q;if(qZ($)<=Y*0.7)return null;let X=Math.max(4,Math.floor($.length*0.3)),K=$.slice(0,$.length-X),V=$.slice($.length-X);if(K.length<2)return null;return{toSummarize:K,toKeep:V}}function OY($){return`Summarize this conversation concisely. Focus on:
|
|
442
|
+
${W}`)}catch(K){if(K instanceof Error&&K.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${K instanceof Error?K.message:String(K)}`}}async function tQ($,Z,Y,Q,J){let z=performance.now();try{let K=await eq($,Z,Y,Q,J);return setImmediate(()=>{F9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-z),success:!K.startsWith("Error:")})}),K}catch(K){return setImmediate(()=>{F9({type:"tool:executed",name:$,input:Z,durationMs:Math.round(performance.now()-z),success:!1})}),`Error: ${K instanceof Error?K.message:String(K)}`}}async function eq($,Z,Y,Q,J){switch($){case"read_file":return pQ(Z);case"write_file":return dQ(Z,Y);case"edit_file":return cQ(Z,Y);case"search_files":return await iQ(Z);case"find_files":return await nQ(Z);case"list_directory":return aQ(Z);case"run_command":return await rQ(Z);case"fetch_url":return await sQ(Z)}let z=await WQ($,Z);if(z!==null)return z;let K=OQ($,Z);if(K!==null)return K;let X=await yQ($,Z);if(X!==null)return X;let V=await HQ($,Z,J);if(V!==null)return V;let G=Q.find((q)=>q.name===$);if(G)return await fQ(G,Z);return`Error: unknown tool "${$}"`}var P1=new w2,$J=[];function v9($){$J=$}var ZJ=null;function h9($){ZJ=$}var eQ=!1;function g9(){if(eQ)return;if(eQ=!0,L)k.push(...j8),k.push(...i4),k.push(...n4);else k.push(a4);k.push(...Z5),k.push(...Y5),k.push(...Q5),k.push(...J5),k.push(z5),k.push(...K5),k.push(...X5),k.push(...V5),k.push(...D5),k.push(...W5),k.push(...C5),k.push(...G5),k.push(...q5),k.push(...U5),k.push(...B5),k.push(...H5),k.push(...M5),k.push(...P5)}async function T5($,Z){return tQ($,Z,P1,$J,ZJ)}var $U=new Set([429,500,502,503,529]);async function QJ($,Z={}){let Y=Z.maxRetries??3,Q=Z.baseDelayMs??1000,J;for(let z=0;z<=Y;z++)try{return await $()}catch(K){if(J=K,Z.signal?.aborted)throw K;if(z>=Y)throw K;if(ZU(K)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(z+1,500,"Auth refreshed, retrying..."),await YJ(500,Z.signal);continue}}if(!YU(K))throw K;let V=QU(K)??Q*Math.pow(2,z),G=K instanceof Error?K.message:String(K);Z.onRetry?.(z+1,V,G),await YJ(V,Z.signal)}throw J}function ZU($){if(!($ instanceof Error))return!1;return $.status===401}function YU($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&$U.has(Z))return!0;let Y=$.message.toLowerCase();if(Y.includes("econnreset")||Y.includes("econnrefused"))return!0;if(Y.includes("etimedout")||Y.includes("socket hang up"))return!0;if(Y.includes("overloaded"))return!0;return!1}function QU($){let Z=$.headers;if(!Z)return null;let Y=Z["retry-after"];if(!Y)return null;let Q=Number(Y);if(!isNaN(Q)&&Q>0)return Math.min(Q,60)*1000;return null}function YJ($,Z){return new Promise((Y,Q)=>{let J=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(J),Q(Error("Aborted"))},{once:!0})})}var JU={haiku:200000,sonnet:200000,opus:200000};function D0($){return Math.ceil($.length/3.5)}function m9($){let Z=0;for(let Y of $){if(Z+=D0(Y.content),Y.toolCalls)for(let Q of Y.toolCalls)Z+=D0(JSON.stringify(Q.input)),Z+=D0(Q.result);Z+=10}return Z}function u9($){let Z=$.toLowerCase();for(let[Y,Q]of Object.entries(JU))if(Z.includes(Y))return Q;return 200000}function JJ($,Z,Y){let Q=u9(Z)-20000-Y;if(m9($)<=Q)return $;let z=[],K=Q,X=[...$].reverse(),V=[];for(let q of X){let U=D0(q.content)+(q.toolCalls?.reduce((W,B)=>W+D0(JSON.stringify(B.input))+D0(B.result),0)??0)+10;if(K-U<0)break;K-=U,V.unshift(q)}let G=$.length-V.length;if(G>0)z.push({role:"user",content:`[Note: ${G} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return z.push(...V),z}function zJ($,Z,Y){let Q=u9(Z)-20000-Y;return m9($)>Q*0.7}function KJ($,Z,Y){let Q=u9(Z)-20000-Y;if(m9($)<=Q*0.7)return null;let z=Math.max(4,Math.floor($.length*0.3)),K=$.slice(0,$.length-z),X=$.slice($.length-z);if(K.length<2)return null;return{toSummarize:K,toKeep:X}}function XJ($){return`Summarize this conversation concisely. Focus on:
|
|
442
443
|
1. Key decisions made
|
|
443
444
|
2. Files created or modified
|
|
444
445
|
3. Important context the user shared
|
|
@@ -447,33 +448,36 @@ ${W}`)}catch(K){if(K instanceof Error&&K.name==="AbortError")return"Error: Reque
|
|
|
447
448
|
Be brief but preserve actionable information. Output ONLY the summary.
|
|
448
449
|
|
|
449
450
|
---
|
|
450
|
-
${$.map((
|
|
451
|
-
Tools used: ${
|
|
451
|
+
${$.map((Y)=>{let Q=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)Q+=`
|
|
452
|
+
Tools used: ${Y.toolCalls.map((J)=>J.name).join(", ")}`;return Q}).join(`
|
|
452
453
|
|
|
453
|
-
`)}`}function
|
|
454
|
-
`),K=Math.min(10,
|
|
455
|
-
`);return{...J,result:
|
|
456
|
-
Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${
|
|
454
|
+
`)}`}function VJ($,Z=2000){return $.map((Y)=>{if(!Y.toolCalls?.length)return Y;let Q=Y.toolCalls.map((J)=>{if(J.result.length<=Z)return J;let z=J.result.split(`
|
|
455
|
+
`),K=Math.min(10,z.length),X=Math.min(5,Math.max(0,z.length-K)),V=z.length-K-X,G=[...z.slice(0,K)];if(V>0)G.push(`... (${V} lines omitted)`);if(X>0)G.push(...z.slice(-X));let q=G.join(`
|
|
456
|
+
`);return{...J,result:q}});return{...Y,toolCalls:Q}})}var zU=[/OPENAI_API_KEY\s*=/i,/AWS_SECRET_ACCESS_KEY\s*=/i,/AWS_SESSION_TOKEN\s*=/i,/GITHUB_TOKEN\s*=/i,/GH_TOKEN\s*=/i,/SLACK_TOKEN\s*=/i,/SLACK_BOT_TOKEN\s*=/i,/DATABASE_URL\s*=.*:\/\/.+:.+@/i,/REDIS_URL\s*=.*:\/\/.+:.+@/i,/password\s*=\s*["'][^"']{4,}["']/i,/secret\s*=\s*["'][^"']{4,}["']/i,/Bearer\s+[A-Za-z0-9\-._~+\/]{20,}/i,/sk-[A-Za-z0-9]{20,}/,/ghp_[A-Za-z0-9]{36,}/,/xoxb-[0-9]{10,}/];function p9($){for(let Z of zU)if(Z.test($))return Z.source.split(/[\\(]/)[0].replace(/\s\*/g,"").slice(0,30);return null}var KU=[/^[A-Z]:\\Windows\\System32/i,/^[A-Z]:\\Windows\\SysWOW64/i,/^[A-Z]:\\Program Files/i,/^[A-Z]:\\ProgramData/i,/\\\.ssh\\/i,/\\\.gnupg\\/i],XU=[/^\/etc\//,/^\/usr\/bin\//,/^\/usr\/sbin\//,/^\/var\/log\//,/^\/root\//,/\/\.ssh\//,/\/\.gnupg\//];function GJ($){return(process.platform==="win32"?KU:XU).some((Y)=>Y.test($))}var VU=[/\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],GU=[/\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 qJ($,Z){switch($){case"read_file":case"list_directory":case"find_files":case"search_files":case"fetch_url":case"read_clipboard_content":case"analyze_screen_context":case"memory_status":case"recall_memory":return{level:"safe"};case"write_file":{let Y=String(Z.path||"");if(GJ(Y))return{level:"dangerous",reason:`write to protected path: ${Y}`};let Q=String(Z.content||""),J=p9(Q);if(J)return{level:"dangerous",reason:`content contains potential secret: ${J}`};return{level:"moderate",reason:`write ${Y}`}}case"edit_file":{let Y=String(Z.path||"");if(GJ(Y))return{level:"dangerous",reason:`edit protected path: ${Y}`};let Q=String(Z.new_text||""),J=p9(Q);if(J)return{level:"dangerous",reason:`new_text contains potential secret: ${J}`};return{level:"moderate",reason:`edit ${Y}`}}case"run_command":{let Y=String(Z.command||""),Q=p9(Y);if(Q)return{level:"dangerous",reason:`command contains potential secret: ${Q}`};for(let J of VU)if(J.test(Y))return{level:"dangerous",reason:Y};for(let J of GU)if(J.test(Y))return{level:"moderate",reason:Y};return{level:"moderate",reason:Y}}case"execute_powershell_script":return{level:"dangerous",reason:"PowerShell script execution"};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function d9($){if(!($ instanceof Error))return String($);let{status:Z,message:Y}=$;if(Z)switch(Z){case 400:if(Y.includes("context_length")||Y.includes("too many tokens"))return"Message too long for the model's context window. Try /clear to start fresh or use a shorter prompt.";return`Bad request: ${qU(Y)}`;case 401:return"Authentication failed. Your subscription token may be expired.\nTry: Run `claude` to refresh subscription credentials.";case 403:return`Access denied. Your subscription may not have permission for this model.
|
|
457
|
+
Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${UU(Y)}" may not exist or be unavailable.
|
|
457
458
|
Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
|
|
458
|
-
The request will be retried automatically. If this persists, wait a minute.`;case 500:case 502:case 503:return"Anthropic API is temporarily unavailable. Retrying automatically...";case 529:return"Anthropic API is overloaded. Retrying with backoff..."}let Y
|
|
459
|
-
`)[0]||"",J=
|
|
460
|
-
`).length;return`PowerShell (${J} line${J>1?"s":""}): ${
|
|
459
|
+
The request will be retried automatically. If this persists, wait a minute.`;case 500:case 502:case 503:return"Anthropic API is temporarily unavailable. Retrying automatically...";case 529:return"Anthropic API is overloaded. Retrying with backoff..."}let Q=Y.toLowerCase();if(Q.includes("econnrefused")||Q.includes("enotfound"))return"Cannot connect to Anthropic API. Check your internet connection.";if(Q.includes("etimedout")||Q.includes("socket hang up"))return"Connection to Anthropic API timed out. Retrying...";if(Q.includes("econnreset"))return"Connection was reset. This usually recovers automatically.";if(Q.includes("expired")||Q.includes("invalid_api_key"))return"Your subscription token has expired. Run `claude` to refresh.";return Y}function qU($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function UU($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function UJ($,Z,Y){if($==="auto")return!1;if(Y==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command","execute_powershell_script"].includes(Z);if($==="confirm-all")return Y!=="safe";return!1}function HJ($,Z){switch($){case"write_file":return`Write file: ${Z.path}`;case"edit_file":return`Edit file: ${Z.path}`;case"run_command":{let Y=String(Z.command||"");return`Run: ${Y.length>60?Y.slice(0,57)+"...":Y}`}case"execute_powershell_script":{let Y=String(Z.script||""),Q=Y.split(`
|
|
460
|
+
`)[0]||"",J=Y.split(`
|
|
461
|
+
`).length;return`PowerShell (${J} line${J>1?"s":""}): ${Q.length>50?Q.slice(0,47)+"...":Q}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function WJ($,Z,Y=20){let Q=$.split(`
|
|
461
462
|
`),J=Z.split(`
|
|
462
|
-
`),
|
|
463
|
-
${await this.generateSummary(
|
|
464
|
-
`)
|
|
465
|
-
`)}
|
|
466
|
-
`)
|
|
467
|
-
|
|
468
|
-
`))}}}catch{}try{let
|
|
463
|
+
`),z=[],K=Q.slice(0,Y);for(let V of K)z.push(` \x1B[31m- ${V}\x1B[0m`);if(Q.length>Y)z.push(` \x1B[2m ... (${Q.length-Y} more removed)\x1B[0m`);let X=J.slice(0,Y);for(let V of X)z.push(` \x1B[32m+ ${V}\x1B[0m`);if(J.length>Y)z.push(` \x1B[2m ... (${J.length-Y} more added)\x1B[0m`);return z}class c9{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,Q="auto"){this.model=Z;this.maxTokens=Y;this.client=new S$({apiKey:$}),this.approvalMode=Q}updateToken($){this.client=new S$({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let Q=VJ($),J=D0(Z);if(zJ(Q,this.model,J)){let V=KJ(Q,this.model,J);if(V)try{let q={role:"assistant",content:`[Conversation summary]
|
|
464
|
+
${await this.generateSummary(V.toSummarize)}`,timestamp:Date.now()};Q=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},q,...V.toKeep]}catch{}}let z=JJ(Q,this.model,J),K=HU(z),X=Y?k:void 0;try{yield*this.streamLoop(K,Z,X)}catch(V){yield{type:"error",error:d9(V)}}}async generateSummary($){let Z=XJ($),Q=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((J)=>J.type==="text");return Q?.type==="text"?Q.text:"Summary unavailable."}async*streamLoop($,Z,Y){let J=[...$],z=0;while(z++<25){let K;try{K=await QJ(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:J,...Y?.length?{tools:Y}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(q){yield{type:"error",error:d9(q)};return}for await(let q of K)if(q.type==="content_block_delta"&&q.delta.type==="text_delta")yield{type:"text",text:q.delta.text};let X=await K.finalMessage();if(X.usage)yield{type:"usage",inputTokens:X.usage.input_tokens,outputTokens:X.usage.output_tokens};if(X.stop_reason!=="tool_use"){yield{type:"done"};return}let V=X.content.filter((q)=>q.type==="tool_use");J.push({role:"assistant",content:X.content});let G=[];for(let q of V){let U=q.input,W=qJ(q.name,U);if(W.level==="dangerous"){yield{type:"tool_blocked",id:q.id,name:q.name,reason:`Blocked dangerous operation: ${W.reason}`},G.push({type:"tool_result",tool_use_id:q.id,content:`Error: Operation blocked for safety. Reason: ${W.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&UJ(this.approvalMode,q.name,W.level)&&this.approvalCallback){if(yield{type:"tool_call",id:q.id,name:q.name,input:q.input},!await this.approvalCallback(q.name,U,W.level)){yield{type:"tool_blocked",id:q.id,name:q.name,reason:"Rejected by user"},G.push({type:"tool_result",tool_use_id:q.id,content:"Error: User rejected this operation."});continue}let O=await T5(q.name,U);yield{type:"tool_result",id:q.id,name:q.name,result:O},G.push({type:"tool_result",tool_use_id:q.id,content:O});continue}yield{type:"tool_call",id:q.id,name:q.name,input:q.input};let B=await T5(q.name,U);yield{type:"tool_result",id:q.id,name:q.name,result:B},G.push({type:"tool_result",tool_use_id:q.id,content:B})}J.push({role:"user",content:G})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function HU($){let Z=[];for(let Y of $)if(Y.role==="user")if(Y.images?.length){let Q=Y.images.map((J)=>({type:"image",source:{type:"base64",media_type:J.mediaType,data:J.base64}}));Q.push({type:"text",text:Y.content}),Z.push({role:"user",content:Q})}else Z.push({role:"user",content:Y.content});else if(Y.role==="assistant")if(Y.toolCalls?.length){let Q=[];if(Y.content)Q.push({type:"text",text:Y.content});for(let J of Y.toolCalls)Q.push({type:"tool_use",id:J.id,name:J.name,input:J.input});Z.push({role:"assistant",content:Q}),Z.push({role:"user",content:Y.toolCalls.map((J)=>({type:"tool_result",tool_use_id:J.id,content:J.result}))})}else Z.push({role:"assistant",content:Y.content});return Z}class l9{name;apiKey;baseUrl;model;maxTokens;approvalMode="auto";approvalCallback=null;autoApproveAll=!1;constructor($,Z,Y){if(this.name=$,this.model=Z,this.maxTokens=Y,$==="ollama")this.apiKey="ollama",this.baseUrl=process.env.OLLAMA_BASE_URL||"http://localhost:11434/v1";else this.apiKey=process.env.OPENAI_API_KEY||"",this.baseUrl=process.env.OPENAI_BASE_URL||"https://api.openai.com/v1"}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){if(!this.apiKey&&this.name!=="ollama"){yield{type:"error",error:"No API key found. Set OPENAI_API_KEY env var."};return}let Q=[{role:"system",content:Z},...$.map((J)=>({role:J.role,content:J.content}))];try{let J=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:Q,max_tokens:this.maxTokens,stream:!0})});if(!J.ok){let q=await J.text();yield{type:"error",error:`${this.name} API error ${J.status}: ${q.slice(0,200)}`};return}if(!J.body){yield{type:"error",error:"No response body"};return}let z=J.body.getReader(),K=new TextDecoder,X="",V=Z.length+$.reduce((q,U)=>q+U.content.length,0),G=0;while(!0){let{done:q,value:U}=await z.read();if(q)break;X+=K.decode(U,{stream:!0});let W=X.split(`
|
|
465
|
+
`);X=W.pop()||"";for(let B of W){if(!B.startsWith("data: "))continue;let M=B.slice(6).trim();if(M==="[DONE]")continue;try{let R=JSON.parse(M).choices?.[0]?.delta;if(R?.content)yield{type:"text",text:R.content},G+=R.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(V/3.5),outputTokens:Math.ceil(G/3.5)},yield{type:"done"}}catch(J){yield{type:"error",error:J instanceof Error?J.message:String(J)}}}}function A5($){if($.includes(":")){let[Y,...Q]=$.split(":");return{provider:Y.toLowerCase(),model:Q.join(":")}}let Z=$.toLowerCase();if(Z.startsWith("gpt-")||Z.startsWith("o1")||Z.startsWith("o3"))return{provider:"openai",model:$};if(Z.startsWith("llama")||Z.startsWith("mistral")||Z.startsWith("codellama")||Z.startsWith("deepseek"))return{provider:"ollama",model:$};return{provider:"anthropic",model:$}}var WU={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 BJ(){let $=["Providers:"];for(let[Z,Y]of Object.entries(WU)){let Q=Y.envKey?` (${Y.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${Y.description}${Q}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
|
|
466
|
+
`)}function MJ($,Z,Y,Q){let{provider:J,model:z}=A5(Z);if(J==="openai"||J==="ollama")return new l9(J,z,Y);let K=new c9($.auth.token,Z,Y,Q);return K.setAuthRefresh(()=>{let X=N4();if(X&&X.token!==$.auth.token)return $.auth=X,K.updateToken(X.token),!0;return!1}),K}f();import{existsSync as F$,mkdirSync as CJ,readdirSync as NJ,readFileSync as I5,unlinkSync as OJ,renameSync as o9}from"fs";import{join as s}from"path";class i9{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=s($,"sessions"),this.archiveDir=s($,"sessions","archive"),!F$(this.sessionsDir))CJ(this.sessionsDir,{recursive:!0});if(!F$(this.archiveDir))CJ(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(!F$(this.sessionsDir))return[];return NJ(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=s(this.sessionsDir,`${$}.json`);if(!F$(Z))return null;try{let Y=JSON.parse(I5(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=s(this.sessionsDir,`${$}.json`);if(F$(Z))return OJ(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=s(this.sessionsDir,`${$}.json`);return D(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=s(this.sessionsDir,`${$}.json`);if(!F$(Z))return!1;let Y=s(this.archiveDir,`${$}.json`);return o9(Z,Y),!0}archiveAll(){let $=[],Z=this.list().filter((Y)=>Y!==this.current.name);for(let Y of Z)if(this.archive(Y))$.push(Y);return $}unarchive($){let Z=s(this.archiveDir,`${$}.json`);if(!F$(Z))return!1;let Y=s(this.sessionsDir,`${$}.json`);return o9(Z,Y),!0}listArchived(){if(!F$(this.archiveDir))return[];return NJ(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=s(this.archiveDir,`${$}.json`);if(!F$(Z))return null;try{let Y=JSON.parse(I5(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=s(this.archiveDir,`${$}.json`);if(F$(Z))return OJ(Z),!0;return!1}loadOrCreate($){let Z=s(this.sessionsDir,`${$}.json`);if(F$(Z))try{return JSON.parse(I5(Z,"utf-8"))}catch{let Q=s(this.sessionsDir,`${$}.corrupt.json`);try{o9(Z,Q)}catch{}}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return D(Z,JSON.stringify(Y,null,2)),Y}saveLastSession(){let $=s(this.sessionsDir,"..","last-session.txt");D($,this.current.name)}getLastSession(){let $=s(this.sessionsDir,"..","last-session.txt");if(!F$($))return null;try{let Z=I5($,"utf-8").trim();if(!Z||!F$(s(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}save(){let $=s(this.sessionsDir,`${this.current.name}.json`);D($,JSON.stringify(this.current,null,2))}}import{existsSync as EJ,readdirSync as RU,readFileSync as LJ}from"fs";import{join as r9}from"path";p();import{existsSync as a9,readFileSync as FJ}from"fs";import{basename as NU,join as w5}from"path";var n9={debug:0,info:1,warn:2,error:3};function BU(){let $=process.env.LOG_LEVEL?.toLowerCase();if($&&$ in n9)return $;if(process.env.DEBUG)return"debug";return"warn"}function MU($){return n9[$]>=n9[BU()]}function CU($,Z,Y){let J=`[${new Date().toISOString()}] ${$.toUpperCase()} ${Z}`;if(Y&&Object.keys(Y).length>0){let z=Object.entries(Y).map(([K,X])=>`${K}=${X instanceof Error?X.message:JSON.stringify(X)}`).join(" ");return`${J} | ${z}`}return J}function S5($,Z,Y){if(!MU($))return;let Q=CU($,Z,Y);process.stderr.write(Q+`
|
|
467
|
+
`)}var X$={debug:($,Z)=>S5("debug",$,Z),info:($,Z)=>S5("info",$,Z),warn:($,Z)=>S5("warn",$,Z),error:($,Z)=>S5("error",$,Z)};function RJ(){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]}`),L)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=OU($);if(Y)Z.push(`Project: ${Y}`);let Q=FU($);if(Q)Z.push(Q);return Z.join(`
|
|
468
|
+
`)}function OU($){let Z=[["package.json","Node.js/JavaScript"],["Cargo.toml","Rust"],["go.mod","Go"],["pyproject.toml","Python"],["requirements.txt","Python"],["pom.xml","Java (Maven)"],["build.gradle","Java (Gradle)"],["Gemfile","Ruby"],["composer.json","PHP"],["Makefile","Make"],["CMakeLists.txt","C/C++ (CMake)"],["Dockerfile","Docker"]],Y=[];for(let[J,z]of Z)if(a9(w5($,J)))Y.push(z);if(Y.length===0)return null;let Q=NU($);try{let J=w5($,"package.json");if(a9(J)){let z=JSON.parse(FJ(J,"utf-8"));if(z.name)Q=z.name}}catch(J){X$.debug("Failed to parse package.json for project name",{error:J})}return`Project: ${Q} (${Y.join(", ")})`}function FU($){if(!a9(w5($,".git")))return null;let Z=[];try{let Y=FJ(w5($,".git","HEAD"),"utf-8").trim(),Q=Y.startsWith("ref: refs/heads/")?Y.slice(16):Y.slice(0,8);Z.push(`Git branch: ${Q}`)}catch{return Z.push("Git: initialized"),Z.join(`
|
|
469
|
+
`)}try{let Y=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q)Z.push(`Last commit: ${Q}`)}}catch(Y){X$.debug("git log failed",{error:Y})}try{let Y=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q){let J=Q.split(`
|
|
470
|
+
`),z=J.slice(0,15);if(J.length>15)z.push(`... and ${J.length-15} more files`);Z.push(`Uncommitted changes:
|
|
471
|
+
`+z.join(`
|
|
472
|
+
`))}}}catch(Y){X$.debug("git diff --stat failed",{error:Y})}try{let Y=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let Q=new TextDecoder().decode(Y.stdout).trim();if(Q){let J=Q.split(`
|
|
469
473
|
`).slice(0,10);Z.push(`Staged:
|
|
470
474
|
`+J.join(`
|
|
471
|
-
`))}}}catch{}return Z.length>0?Z.join(`
|
|
472
|
-
`):null}function
|
|
475
|
+
`))}}}catch(Y){X$.debug("git diff --cached failed",{error:Y})}return Z.length>0?Z.join(`
|
|
476
|
+
`):null}function jJ($,Z){if(!EJ($))return[];let Y=[],Q=RU($,{withFileTypes:!0});for(let J of Q)if(J.isFile()&&J.name.endsWith(".md")){let z=LJ(r9($,J.name),"utf-8");Y.push({name:J.name.replace(".md",""),content:z.trim(),source:Z})}else if(J.isDirectory()){let z=r9($,J.name,"SKILL.md");if(EJ(z)){let K=LJ(z,"utf-8");Y.push({name:J.name,content:K.trim(),source:Z})}}return Y}function DJ($){let Z=jJ($,"global"),Y=r9(process.cwd(),".smolerclaw","skills"),Q=jJ(Y,"local"),J=new Map;for(let z of Z)J.set(z.name,z);for(let z of Q)J.set(z.name,z);return[...J.values()]}function PJ($){if($.length===0)return"No skills loaded.";return`Skills:
|
|
473
477
|
`+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
|
|
474
|
-
`)}function
|
|
475
|
-
ALWAYS respond in ${
|
|
476
|
-
`+
|
|
478
|
+
`)}function k5($,Z,Y="auto"){let Q=[];for(let J of Z)Q.push(J.content);if(Y&&Y!=="auto"){let z={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[Y]||Y;Q.push(`## Language Override
|
|
479
|
+
ALWAYS respond in ${z}. This is a hard requirement.`)}if($0())Q.push(`---
|
|
480
|
+
`+kQ());if(Q.push(`---
|
|
477
481
|
## Meta-Learning & Self-Awareness
|
|
478
482
|
You are aware of your own updates and capabilities. Your usage patterns are being observed to improve your helpfulness.
|
|
479
483
|
|
|
@@ -489,39 +493,100 @@ You are aware of your own updates and capabilities. Your usage patterns are bein
|
|
|
489
493
|
|
|
490
494
|
**Self-Reflection:**
|
|
491
495
|
- At session end or when explicitly asked, run self-reflection to generate insights.
|
|
492
|
-
- Share relevant insights proactively when they might help the current task.`),
|
|
496
|
+
- Share relevant insights proactively when they might help the current task.`),Q.push(`---
|
|
493
497
|
## Environment
|
|
494
498
|
The user's current working directory and project info. Use this context when they ask about code or files.
|
|
495
499
|
|
|
496
|
-
`+
|
|
497
|
-
`+$);return
|
|
500
|
+
`+RJ()),$)Q.push(`## User Instructions
|
|
501
|
+
`+$);return Q.join(`
|
|
502
|
+
|
|
503
|
+
`)}import{join as EU}from"path";function TJ($,Z,Y){let Q=new i9($.dataDir),J=Z||Q.getLastSession()||"default";if(J!=="default")Q.switchTo(J);let z=DJ($.skillsDir),K=k5($.systemPrompt,z,$.language),X=!Y;g9();let V=hQ(EU($.dataDir,"..")),G=_Q(V);if(G.length>0)v9(G),k.push(...xQ(G));let q=e3(),U=q?`${K}
|
|
498
504
|
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
505
|
+
${q}`:K;return{sessions:Q,sessionName:J,skills:z,systemPrompt:K,activeSystemPrompt:U,enableTools:X,plugins:G}}async function AJ($,Z,Y,Q,J,z){let K=J||"";if(z){let q=await LU();K=K?`${K}
|
|
506
|
+
|
|
507
|
+
${q}`:q}if(!K.trim())console.error("smolerclaw: no input provided"),process.exit(1);let X={role:"user",content:K.trim(),timestamp:Date.now()};Z.addMessage(X);let V="";for await(let q of $.chat(Z.messages,Y,Q))if(q.type==="text")process.stdout.write(q.text),V+=q.text;else if(q.type==="error")console.error(`
|
|
508
|
+
smolerclaw error: ${q.error}`);if(V&&!V.endsWith(`
|
|
509
|
+
`))process.stdout.write(`
|
|
510
|
+
`);let G={role:"assistant",content:V,timestamp:Date.now()};Z.addMessage(G)}async function LU(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}var jU=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function b$($){return jU?"":$}var H={altOn:b$("\x1B[?1049h"),altOff:b$("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:b$("\x1B[1m"),dim:b$("\x1B[2m"),italic:b$("\x1B[3m"),underline:b$("\x1B[4m"),reset:b$("\x1B[0m"),inv:b$("\x1B[7m"),fg:($)=>b$(`\x1B[38;5;${$}m`),bg:($)=>b$(`\x1B[48;5;${$}m`)};var I={user:H.fg(75),ai:H.fg(114),tool:H.fg(215),err:H.fg(196),sys:H.fg(245),prompt:H.fg(220),code:H.fg(180),heading:H.fg(75),link:H.fg(39),quote:H.fg(245)},DU={primary:H.fg(75),secondary:H.fg(39),accent:H.fg(220),muted:H.fg(245),header:H.fg(81)},PU={primary:H.fg(215),secondary:H.fg(220),accent:H.fg(196),muted:H.fg(245),header:H.fg(214)},TU={primary:H.fg(183),secondary:H.fg(157),accent:H.fg(147),muted:H.fg(242),header:H.fg(183)};function s9($){switch($){case"productivity":return DU;case"spillover_alert":return PU;case"sharpen_or_relax":return TU}}function N($){process.stdout.write($)}var AU=/\x1b\[[0-9;]*[a-zA-Z]/g;function P0($){return $.replace(AU,"")}function IU($){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 Z$($){let Z=P0($),Y=0;for(let Q of Z)Y+=IU(Q);return Y}function T0($,Z){if(Z<10)Z=10;let Y=[];for(let Q of $.split(`
|
|
511
|
+
`)){if(Z$(Q)<=Z){Y.push(Q);continue}let K=P0(Q).split(" "),X=[],V="";for(let q of K)if(V.length+(V?1:0)+q.length>Z&&V)X.push(V),V=" "+q;else V+=(V?" ":"")+q;if(V)X.push(V);let G=SU(Q);for(let q=0;q<X.length;q++)if(G&&q===0)X[q]=G+X[q]+H.reset;else if(G)X[q]=G+X[q]+H.reset;Y.push(...X)}return Y}function SU($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function y5($,Z){let Y=Z??(process.stdout.columns||80),Q=$.split(`
|
|
512
|
+
`),J=[],z=!1,K="";for(let X=0;X<Q.length;X++){let V=Q[X];if(V.trimStart().startsWith("```")){if(!z){z=!0,K=V.trimStart().slice(3).trim();let B=K?` ${K}`:"";J.push(` ${H.dim}\u250C\u2500\u2500${B}${"\u2500".repeat(Math.max(1,40-B.length))}${H.reset}`)}else z=!1,K="",J.push(` ${H.dim}\u2514${"\u2500".repeat(42)}${H.reset}`);continue}if(z){J.push(` ${H.dim}\u2502${H.reset} ${I.code}${V}${H.reset}`);continue}if(!V.trim()){J.push("");continue}let G=V.match(/^(#{1,3})\s+(.+)/);if(G){let B=G[1].length,M=G[2],O=B===1?"\u2501":B===2?"\u2500":"\xB7";J.push(` ${I.heading}${H.bold}${O} ${c8(M)}${H.reset}`);continue}if(V.trimStart().startsWith(">")){let B=V.replace(/^\s*>\s?/,"");t9(J,` ${I.quote}\u2502 ${c8(B)}${H.reset}`,Y);continue}let q=V.match(/^(\s*)([-*+])\s+(.+)/);if(q){let B=Math.floor(q[1].length/2),M=q[3],O=" ".repeat(B);t9(J,` ${O}${H.dim}\u2022${H.reset} ${c8(M)}`,Y);continue}let U=V.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(U){let B=Math.floor(U[1].length/2),M=U[2],O=U[3],R=" ".repeat(B);t9(J,` ${R}${H.dim}${M}.${H.reset} ${c8(O)}`,Y);continue}if(/^[-*_]{3,}\s*$/.test(V.trim())){J.push(` ${H.dim}${"\u2500".repeat(40)}${H.reset}`);continue}let W=` ${c8(V)}`;if(Z$(W)>Y)for(let B of T0(W,Y))J.push(B);else J.push(W)}if(z)J.push(` ${H.dim}\u2514${"\u2500".repeat(42)}${H.reset}`);return J}function t9($,Z,Y){if(Z$(Z)>Y)for(let Q of T0(Z,Y))$.push(Q);else $.push(Z)}function c8($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${H.inv} $1 ${H.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${H.bold}${H.italic}$1${H.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${H.bold}$1${H.reset}`),Z=Z.replace(/__(.+?)__/g,`${H.bold}$1${H.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${H.italic}$1${H.reset}`),Z=Z.replace(/_(.+?)_/g,`${H.italic}$1${H.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${H.underline}$1${H.reset} ${I.link}($2)${H.reset}`),Z}import{existsSync as wU,readFileSync as kU,writeFileSync as yU}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(wU(this.filePath)){let $=kU(this.filePath,"utf-8");this.entries=$.split(`
|
|
513
|
+
`).filter(Boolean).slice(-e9)}}catch{}}save(){try{yU(this.filePath,this.entries.join(`
|
|
503
514
|
`)+`
|
|
504
|
-
`)}catch{}}}import{join as Bq}from"path";var eH=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],$q=" ";function DZ($,Z={}){let{width:Q=$.length,min:Y=Math.min(...$),max:J=Math.max(...$),color:X="",showBounds:K=!1}=Z;if($.length===0)return"";let V=qq($,Q),G=J-Y||1,z=V.map((W)=>{if(W===0&&Y===0)return $q;let N=(W-Y)/G,O=Math.min(7,Math.floor(N*8));return eH[O]}).join(""),B=X?`${X}${z}${U.reset}`:z;if(K)return`${U.dim}${Y.toFixed(0)}${U.reset}${B}${U.dim}${J.toFixed(0)}${U.reset}`;return B}var Zq="\u2588",Qq="\u2589",Yq="\u258A",Jq="\u258B",Xq="\u258C",Kq="\u258D",zq="\u258E",Vq="\u258F",Gq="\u2591",Hq=[" ",Vq,zq,Kq,Xq,Jq,Yq,Qq];function PZ($,Z={}){let{width:Q=20,maxValue:Y=100,showValue:J=!0,color:X=U.fg(75),label:K=""}=Z,V=Math.min(1,Math.max(0,$/Y)),G=Math.floor(V*Q),H=V*Q-G,z=Math.floor(H*8),B=Zq.repeat(G);if(z>0&&G<Q)B+=Hq[z];let W=Q-G$(B);B+=Gq.repeat(Math.max(0,W));let N=X?`${X}${B}${U.reset}`:B,O=[];if(K)O.push(`${U.dim}${K.padEnd(12)}${U.reset}`);if(O.push(N),J)O.push(` ${U.dim}${$.toFixed(1)}%${U.reset}`);return O.join("")}function r1($,Z){let Q=[];if(Q.push(`${b.ai}${$.model}${U.reset}`),$.project)Q.push(`${b.heading}${$.project}${U.reset}`);if($.tokens){let{input:K,output:V}=$.tokens;Q.push(`${U.dim}${_Y(K)}/${_Y(V)} tok${U.reset}`)}if($.sessionCost)Q.push(`${U.dim}${$.sessionCost}${U.reset}`);if($.vaultStatus){let K=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",V=$.vaultStatus==="ok"?U.fg(114):$.vaultStatus==="warn"?U.fg(220):U.fg(196);Q.push(`${V}${K}${U.reset}`)}if($.customItems)for(let K of $.customItems){let V=K.color||"";Q.push(`${U.dim}${K.label}:${U.reset}${V}${K.value}${U.reset}`)}let Y=Q.join(` ${U.dim}\u2502${U.reset} `),J=G$(Y),X=Math.max(0,Z-J-2);return`${U.inv} ${Y}${" ".repeat(X)} ${U.reset}`}function TZ($,Z=40){let Q=[];Q.push(`${U.dim}${"\u2500".repeat(Z)}${U.reset}`),Q.push(`${b.heading}${U.bold} System${U.reset}`);let Y=DZ($.cpu,{width:15,color:U.fg(75)}),J=PZ($.currentCpu,{width:10,showValue:!1,color:U.fg(75)});Q.push(` ${U.dim}CPU:${U.reset} ${Y} ${J} ${$.currentCpu.toFixed(0)}%`);let X=DZ($.memory,{width:15,color:U.fg(114)}),K=PZ($.currentMem,{width:10,showValue:!1,color:U.fg(114)});return Q.push(` ${U.dim}MEM:${U.reset} ${X} ${K} ${$.currentMem.toFixed(0)}%`),Q.push(`${U.dim}${"\u2500".repeat(Z)}${U.reset}`),Q}function qq($,Z){if($.length<=Z){let J=[...$];while(J.length<Z)J.unshift(0);return J}let Q=$.length/Z,Y=[];for(let J=0;J<Z;J++){let X=Math.floor(J*Q),K=Math.floor((J+1)*Q),V=$.slice(X,K),G=V.reduce((H,z)=>H+z,0)/V.length;Y.push(G)}return Y}function _Y($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function i1($,Z,Q={}){let{title:Y="",padding:J=1,borderColor:X=U.dim,titleColor:K=b.heading}=Q,V=Z-2-J*2,G=[];if(Y){let z=G$(Y),B=2,W=Math.max(1,Z-z-2-4);G.push(`${X}\u250C${"\u2500".repeat(2)}${U.reset}${K}${U.bold} ${Y} ${U.reset}${X}${"\u2500".repeat(W)}\u2510${U.reset}`)}else G.push(`${X}\u250C${"\u2500".repeat(Z-2)}\u2510${U.reset}`);let H=" ".repeat(J);for(let z of $){let B=G$(z)>V?w4(z,V):[z];for(let W of B){let N=G$(W),O=Math.max(0,V-N);G.push(`${X}\u2502${U.reset}${H}${W}${" ".repeat(O)}${H}${X}\u2502${U.reset}`)}}return G.push(`${X}\u2514${"\u2500".repeat(Z-2)}\u2518${U.reset}`),G}function AZ($,Z,Q,Y,J={}){let X=i1($,Y,J);for(let K=0;K<X.length;K++)E(U.to(Z+K,Q)),E(X[K])}var z5={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},Uq={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function IZ($,Z={}){let{width:Q=60,showActions:Y=!0,compact:J=!1}=Z,X=[],K=Uq[$.category]||"\uD83D\uDCA1",V=z5.dimYellow+z5.italic;if(J){let z=$.title.length>Q-10?$.title.slice(0,Q-13)+"...":$.title;return X.push(` ${V}${K} ${z}${U.reset}`),X}X.push(` ${V}${K} ${$.title}${U.reset}`);let G=Q-6,H=w4($.explanation,G);for(let z of H)X.push(` ${V} ${S4(z)}${U.reset}`);if($.suggestedAction)X.push(` ${z5.dimCyan} \u2192 ${$.suggestedAction.label}${U.reset}`);if(Y)X.push(` ${U.dim} [Y] Aceitar [N] Ignorar${U.reset}`);return X}function vY($,Z=40){let Q=[],Y=[...$].sort((J,X)=>X.frequency-J.frequency).slice(0,3);if(Y.length===0)return Q.push(`${U.dim} Nenhuma dica disponivel ainda.${U.reset}`),Q.push(`${U.dim} Continue usando para gerar insights.${U.reset}`),Q;for(let J=0;J<Y.length;J++){let X=Y[J],K=J+1,V=K===1?"\uD83E\uDD47":K===2?"\uD83E\uDD48":"\uD83E\uDD49",G=Z-8,H=X.title.length>G?X.title.slice(0,G-3)+"...":X.title;Q.push(`${V} ${z5.dimYellow}${H}${U.reset}`);let z=Z-4,B=X.description.length>z?X.description.slice(0,z-3)+"...":X.description;Q.push(` ${U.dim}${B}${U.reset}`);let W=X.frequency===1?"vez":"vezes";if(Q.push(` ${U.dim}Detectado ${X.frequency}x${U.reset}`),J<Y.length-1)Q.push("")}return Q}function V5($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:vY($,Z)}}class s1{mode="chat";width;height;statusBarEnabled=!0;statusConfig=null;dashboardLayout=null;savedChatLines=[];resizeCallbacks=[];constructor(){this.width=process.stdout.columns||80,this.height=process.stdout.rows||24}getMode(){return this.mode}getViewState(){let Z=this.statusBarEnabled&&this.statusConfig?this.height:0;return{mode:this.mode,width:this.width,height:this.height,statusBarRow:Z,contentStartRow:3,contentEndRow:this.height-2,inputRow:this.height}}enterChatMode(){if(this.mode==="chat")return;this.mode="chat",this.clearScreen()}enterDashboardMode($){this.mode="dashboard",this.dashboardLayout=$,this.clearScreen(),this.renderDashboard()}toggleMode(){if(this.mode==="chat")return;this.enterChatMode()}setStatusBar($){this.statusConfig=$}enableStatusBar($){this.statusBarEnabled=$}renderStatusBar(){if(!this.statusBarEnabled||!this.statusConfig)return;let $=this.height-1;E(U.to($,1)),E(r1(this.statusConfig,this.width))}clearScreen(){E(U.clear),E(U.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)E(U.to(Z,1)),E(U.clearLine)}updateDimensions($,Z){this.width=$,this.height=Z;for(let Q of this.resizeCallbacks)Q()}onResize($){this.resizeCallbacks.push($)}removeResizeCallback($){this.resizeCallbacks=this.resizeCallbacks.filter((Z)=>Z!==$)}renderDashboard(){if(this.mode!=="dashboard"||!this.dashboardLayout)return;this.clearContentArea();let{panels:$,columns:Z=2,gap:Q=1}=this.dashboardLayout,Y=this.getViewState(),J=Y.contentEndRow-Y.contentStartRow,X=Math.floor((this.width-Q*(Z+1))/Z),K=Y.contentStartRow,V=1+Q;for(let G=0;G<$.length;G++){let H=$[G],z=H.row??K,B=H.col??V,W=H.width??X,N=H.height??Math.floor(J/Math.ceil($.length/Z));if(this.drawDashboardPanel(H,z,B,W,N),(G+1)%Z===0)K+=N+Q,V=1+Q;else V+=W+Q}this.renderStatusBar()}drawDashboardPanel($,Z,Q,Y,J){let X=J-2,K=$.content.slice(0,X);AZ(K,Z,Q,Y,{title:$.title})}createMorningBriefingLayout($){let Z=[{id:"tasks",title:"Tarefas do Dia",content:$.tasks.length>0?$.tasks:["Nenhuma tarefa para hoje"]},{id:"followups",title:"Follow-ups",content:$.followUps.length>0?$.followUps:["Nenhum follow-up pendente"]},{id:"calendar",title:"Agenda",content:$.calendar.length>0?$.calendar:["Sem eventos hoje"]},{id:"news",title:"Noticias",content:$.news.length>0?$.news:["Sem noticias recentes"]}];if($.projectSummary)Z.push({id:"project",title:"Projetos",content:$.projectSummary});return{panels:Z,columns:2,gap:1}}createMonitoringLayout($){return{panels:[{id:"telemetry",title:"Sistema",content:TZ($,35)}],columns:1,gap:1}}}function G5($,Z){E(`\x1B[${$};${Z}r`)}function H5(){E("\x1B[r")}var Wq=new s1;b8();class xZ{model;sessionName;authInfo;dataDir;width=80;height=24;lines=[];streamBuf="";streamLines=[];inputBuf="";inputPos=0;isStreaming=!1;scrollOffset=0;history=null;renderTimer=null;spinnerFrame=0;spinnerTimer=null;streamStartTime=0;sessionCost="";viewMode="chat";viewManager;dashboardContent=[];statusBarEnabled=!0;inputTokens=0;outputTokens=0;activeProject="";vaultStatus="ok";stickyStatusRow=0;personaMode="productivity";palette=RZ("productivity");timeContext=null;commands=["/help","/clear","/commit","/persona","/copy","/fork","/new","/load","/sessions","/delete","/model","/export","/cost","/retry","/undo","/search","/lang","/config","/exit","/briefing","/news","/open","/openfile","/openurl","/apps","/sysinfo","/calendar","/ask","/budget","/plugins","/task","/tasks","/done","/rmtask","/people","/team","/family","/person","/addperson","/delegate","/delegations","/followups","/dashboard","/contacts","/investigar","/investigate","/investigacoes","/monitor","/vigiar","/workflow","/fluxo","/pomodoro","/foco","/entrada","/saida","/income","/expense","/finance","/financas","/balanco","/decisions","/decisoes","/email","/rascunho","/memo","/memos","/note","/notas","/tags","/memotags","/rmmemo","/rmnota","/index","/indexar","/reindex","/memory","/memoria","/clipboard","/area","/tela","/screen","/ps1","/refresh","/renovar","/vault","/backup","/feeds","/fontes","/addfeed","/novafonte","/rmfeed","/rmfonte","/disablefeed","/desativarfonte","/enablefeed","/ativarfonte","/projeto","/project","/projetos","/projects","/sessao","/session","/relatorio","/report","/oportunidades","/opportunities","/anotar","/ajuda","/limpar","/commitar","/modo","/copiar","/novo","/carregar","/sessoes","/deletar","/modelo","/exportar","/custo","/repetir","/desfazer","/buscar","/idioma","/sair","/resumo","/noticias","/abrir","/programas","/sistema","/agenda","/calendario","/perguntar","/orcamento","/tarefa","/tarefas","/feito","/concluido","/rmtarefa","/pessoas","/equipe","/familia","/pessoa","/novapessoa","/addpessoa","/delegar","/delegacoes","/delegados","/painel","/contatos"];subcommands={"/model":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/modelo":["haiku","sonnet","sonnet-4.6","opus","opus-4.6"],"/news":["business","tech","finance","brazil","world","security"],"/noticias":["business","tech","finance","brazil","world","security"],"/open":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/abrir":["excel","word","powerpoint","outlook","onenote","teams","edge","chrome","firefox","calculator","notepad","terminal","explorer","vscode","cursor","paint","snip","settings","taskmanager"],"/sessao":["start","stop","status"],"/session":["start","stop","status"],"/relatorio":["today","week","month"],"/report":["today","week","month"],"/projeto":["auto"],"/project":["auto"],"/oportunidades":["nova","em_analise","aceita","recusada","concluida"],"/opportunities":["nova","em_analise","aceita","recusada","concluida"],"/persona":["default","business"],"/modo":["default","business"],"/people":["equipe","familia","contato"],"/pessoas":["equipe","familia","contato"],"/investigar":["bug","feature","test","audit","incident"],"/investigate":["bug","feature","test","audit","incident"],"/entrada":[],"/saida":[],"/lang":["pt","en","auto"],"/idioma":["pt","en","auto"],"/pomodoro":["start","stop","status"],"/foco":["start","stop","status"],"/monitor":["start","stop","list"],"/vigiar":["start","stop","list"],"/vault":["status","backup","sync","init"],"/workflow":["list","run","info","create","delete","enable","disable"],"/fluxo":["list","run","info","create","delete","ativar","desativar"]};onSubmit=null;onCancel=null;onExit=null;pickerActive=!1;lastCtrlCTime=0;eventUnsubscribers=[];statusBarContext="";activeInsight=null;insightSnippetLines=0;insightDisplayed=!1;metaLearningEntries=[];constructor($,Z,Q="",Y){this.model=$;this.sessionName=Z;this.authInfo=Q;this.dataDir=Y;this.viewManager=new s1}start($){if(this.onSubmit=$.onSubmit,this.onCancel=$.onCancel,this.onExit=$.onExit,this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.dataDir)this.history=new jZ(Bq(this.dataDir,"history"));this.setupEventListeners(),E(U.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}setupEventListeners(){this.eventUnsubscribers.push(W$.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(W$.on("status:update",($)=>{let Z=$.level==="error"?b.err:$.level==="warning"?b.prompt:$.level==="success"?b.sys:U.dim;if(this.lines.push({text:` ${Z}[${$.source}]${U.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(W$.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${b.prompt}\u26A0 ${$.message}${U.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${b.err}\u26A0 Rate limit: ${$.message}${U.reset}`});else this.lines.push({text:` ${U.dim}[telemetry] ${$.message}${U.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(W$.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${U.dim}[backup] ${$.message||"Backup concluido"}${U.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${b.sys}[pomodoro] ${$.message}${U.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${b.err}[${$.taskType}] ${$.message}${U.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(W$.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(W$.on("insight:available",($)=>{if(this.isStreaming||this.pickerActive)return;this.showInsight($.insight)}))}cleanupEventListeners(){for(let $ of this.eventUnsubscribers)$();this.eventUnsubscribers=[]}stop(){if(this.stopSpinner(),this.cleanupEventListeners(),this.renderTimer)clearTimeout(this.renderTimer);process.stdin.setRawMode?.(!1),process.stdin.pause(),E(U.show),E(U.altOff)}addUserMessage($){this.addLabel("user"),this.addWrapped($),this.lines.push({text:""})}addAssistantMessage($){this.addLabel("assistant"),this.addMarkdown($),this.lines.push({text:""})}startStream(){this.isStreaming=!0,this.streamBuf="",this.streamLines=[],this.streamStartTime=Date.now(),this.addLabel("assistant"),this.startSpinner(),this.renderAll()}appendStream($){if(this.streamBuf+=$,!this.renderTimer)this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.streamLines=K5(this.streamBuf,this.width).map((Z)=>({text:Z})),this.renderMessages(),this.renderInput()},50)}flushStream(){if(this.streamLines.length>0)this.lines.push(...this.streamLines),this.streamLines=[],this.streamBuf=""}resetStreamBuffer(){this.streamBuf="",this.streamLines=[]}endStream(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer),this.renderTimer=null,this.streamLines=K5(this.streamBuf,this.width).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let Q=Z,Y;switch($){case"read_file":if(Y=String(Q.path||""),Q.offset)Y+=`:${Q.offset}`;break;case"write_file":case"edit_file":Y=String(Q.path||"");break;case"search_files":if(Y=`/${Q.pattern||""}/`,Q.include)Y+=` (${Q.include})`;break;case"find_files":Y=String(Q.pattern||"");break;case"list_directory":Y=String(Q.path||".");break;case"run_command":if(Y=String(Q.command||""),Y.length>80)Y=Y.slice(0,77)+"...";break;default:{let J=JSON.stringify(Q);Y=J.length>80?J.slice(0,77)+"...":J}}this.lines.push({text:` ${b.tool}\u2699 ${$}${U.reset} ${U.dim}${Y}${U.reset}`}),this.renderMessages()}showToolResult($,Z){let Q=Z.split(`
|
|
505
|
-
`),
|
|
506
|
-
`)process.stdin.removeListener("data",
|
|
507
|
-
`){if(
|
|
508
|
-
`||
|
|
509
|
-
`){if(
|
|
510
|
-
`))this.lines.push({text:` ${
|
|
515
|
+
`)}catch{}}}import{join as nU}from"path";var bU=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],_U=" ";function ZZ($,Z={}){let{width:Y=$.length,min:Q=Math.min(...$),max:J=Math.max(...$),color:z="",showBounds:K=!1}=Z;if($.length===0)return"";let X=lU($,Y),V=J-Q||1,q=X.map((W)=>{if(W===0&&Q===0)return _U;let B=(W-Q)/V,M=Math.min(7,Math.floor(B*8));return bU[M]}).join(""),U=z?`${z}${q}${H.reset}`:q;if(K)return`${H.dim}${Q.toFixed(0)}${H.reset}${U}${H.dim}${J.toFixed(0)}${H.reset}`;return U}var xU="\u2588",fU="\u2589",vU="\u258A",hU="\u258B",gU="\u258C",mU="\u258D",uU="\u258E",pU="\u258F",dU="\u2591",cU=[" ",pU,uU,mU,gU,hU,vU,fU];function YZ($,Z={}){let{width:Y=20,maxValue:Q=100,showValue:J=!0,color:z=H.fg(75),label:K=""}=Z,X=Math.min(1,Math.max(0,$/Q)),V=Math.floor(X*Y),G=X*Y-V,q=Math.floor(G*8),U=xU.repeat(V);if(q>0&&V<Y)U+=cU[q];let W=Y-Z$(U);U+=dU.repeat(Math.max(0,W));let B=z?`${z}${U}${H.reset}`:U,M=[];if(K)M.push(`${H.dim}${K.padEnd(12)}${H.reset}`);if(M.push(B),J)M.push(` ${H.dim}${$.toFixed(1)}%${H.reset}`);return M.join("")}function l8($,Z){let Y=[];if(Y.push(`${I.ai}${$.model}${H.reset}`),$.project)Y.push(`${I.heading}${$.project}${H.reset}`);if($.tokens){let{input:K,output:X}=$.tokens;Y.push(`${H.dim}${IJ(K)}/${IJ(X)} tok${H.reset}`)}if($.sessionCost)Y.push(`${H.dim}${$.sessionCost}${H.reset}`);if($.vaultStatus){let K=$.vaultStatus==="ok"?"\u25CF":$.vaultStatus==="warn"?"\u25D0":"\u25CB",X=$.vaultStatus==="ok"?H.fg(114):$.vaultStatus==="warn"?H.fg(220):H.fg(196);Y.push(`${X}${K}${H.reset}`)}if($.customItems)for(let K of $.customItems){let X=K.color||"";Y.push(`${H.dim}${K.label}:${H.reset}${X}${K.value}${H.reset}`)}let Q=Y.join(` ${H.dim}\u2502${H.reset} `),J=Z$(Q),z=Math.max(0,Z-J-2);return`${H.inv} ${Q}${" ".repeat(z)} ${H.reset}`}function QZ($,Z=40){let Y=[];Y.push(`${H.dim}${"\u2500".repeat(Z)}${H.reset}`),Y.push(`${I.heading}${H.bold} System${H.reset}`);let Q=ZZ($.cpu,{width:15,color:H.fg(75)}),J=YZ($.currentCpu,{width:10,showValue:!1,color:H.fg(75)});Y.push(` ${H.dim}CPU:${H.reset} ${Q} ${J} ${$.currentCpu.toFixed(0)}%`);let z=ZZ($.memory,{width:15,color:H.fg(114)}),K=YZ($.currentMem,{width:10,showValue:!1,color:H.fg(114)});return Y.push(` ${H.dim}MEM:${H.reset} ${z} ${K} ${$.currentMem.toFixed(0)}%`),Y.push(`${H.dim}${"\u2500".repeat(Z)}${H.reset}`),Y}function lU($,Z){if($.length<=Z){let J=[...$];while(J.length<Z)J.unshift(0);return J}let Y=$.length/Z,Q=[];for(let J=0;J<Z;J++){let z=Math.floor(J*Y),K=Math.floor((J+1)*Y),X=$.slice(z,K),V=X.reduce((G,q)=>G+q,0)/X.length;Q.push(V)}return Q}function IJ($){if($>=1e6)return`${($/1e6).toFixed(1)}M`;if($>=1000)return`${($/1000).toFixed(1)}K`;return String($)}function o8($,Z,Y={}){let{title:Q="",padding:J=1,borderColor:z=H.dim,titleColor:K=I.heading}=Y,X=Z-2-J*2,V=[];if(Q){let q=Z$(Q),U=2,W=Math.max(1,Z-q-2-4);V.push(`${z}\u250C${"\u2500".repeat(2)}${H.reset}${K}${H.bold} ${Q} ${H.reset}${z}${"\u2500".repeat(W)}\u2510${H.reset}`)}else V.push(`${z}\u250C${"\u2500".repeat(Z-2)}\u2510${H.reset}`);let G=" ".repeat(J);for(let q of $){let U=Z$(q)>X?T0(q,X):[q];for(let W of U){let B=Z$(W),M=Math.max(0,X-B);V.push(`${z}\u2502${H.reset}${G}${W}${" ".repeat(M)}${G}${z}\u2502${H.reset}`)}}return V.push(`${z}\u2514${"\u2500".repeat(Z-2)}\u2518${H.reset}`),V}function JZ($,Z,Y,Q,J={}){let z=o8($,Q,J);for(let K=0;K<z.length;K++)N(H.to(Z+K,Y)),N(z[K])}var b5={dimYellow:"\x1B[2;33m",italic:"\x1B[3m",boldItalic:"\x1B[1;3m",dimCyan:"\x1B[2;36m"},oU={efficiency:"\uD83D\uDCA1",pattern:"\uD83D\uDD04",shortcut:"\u26A1",warning:"\u26A0\uFE0F",learning:"\uD83D\uDCDA"};function zZ($,Z={}){let{width:Y=60,showActions:Q=!0,compact:J=!1}=Z,z=[],K=oU[$.category]||"\uD83D\uDCA1",X=b5.dimYellow+b5.italic;if(J){let q=$.title.length>Y-10?$.title.slice(0,Y-13)+"...":$.title;return z.push(` ${X}${K} ${q}${H.reset}`),z}z.push(` ${X}${K} ${$.title}${H.reset}`);let V=Y-6,G=T0($.explanation,V);for(let q of G)z.push(` ${X} ${P0(q)}${H.reset}`);if($.suggestedAction)z.push(` ${b5.dimCyan} \u2192 ${$.suggestedAction.label}${H.reset}`);if(Q)z.push(` ${H.dim} [Y] Aceitar [N] Ignorar${H.reset}`);return z}function SJ($,Z=40){let Y=[],Q=[...$].sort((J,z)=>z.frequency-J.frequency).slice(0,3);if(Q.length===0)return Y.push(`${H.dim} Nenhuma dica disponivel ainda.${H.reset}`),Y.push(`${H.dim} Continue usando para gerar insights.${H.reset}`),Y;for(let J=0;J<Q.length;J++){let z=Q[J],K=J+1,X=K===1?"\uD83E\uDD47":K===2?"\uD83E\uDD48":"\uD83E\uDD49",V=Z-8,G=z.title.length>V?z.title.slice(0,V-3)+"...":z.title;Y.push(`${X} ${b5.dimYellow}${G}${H.reset}`);let q=Z-4,U=z.description.length>q?z.description.slice(0,q-3)+"...":z.description;Y.push(` ${H.dim}${U}${H.reset}`);let W=z.frequency===1?"vez":"vezes";if(Y.push(` ${H.dim}Detectado ${z.frequency}x${H.reset}`),J<Q.length-1)Y.push("")}return Y}function _5($,Z=40){return{id:"meta-learning",title:"Meta-Aprendizado",content:SJ($,Z)}}class i8{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;N(H.to($,1)),N(l8(this.statusConfig,this.width))}clearScreen(){N(H.clear),N(H.to(1,1))}clearContentArea(){let $=this.getViewState();for(let Z=$.contentStartRow;Z<=$.contentEndRow;Z++)N(H.to(Z,1)),N(H.clearLine)}updateDimensions($,Z){this.width=$,this.height=Z;for(let Y of this.resizeCallbacks)Y()}onResize($){this.resizeCallbacks.push($)}removeResizeCallback($){this.resizeCallbacks=this.resizeCallbacks.filter((Z)=>Z!==$)}renderDashboard(){if(this.mode!=="dashboard"||!this.dashboardLayout)return;this.clearContentArea();let{panels:$,columns:Z=2,gap:Y=1}=this.dashboardLayout,Q=this.getViewState(),J=Q.contentEndRow-Q.contentStartRow,z=Math.floor((this.width-Y*(Z+1))/Z),K=Q.contentStartRow,X=1+Y;for(let V=0;V<$.length;V++){let G=$[V],q=G.row??K,U=G.col??X,W=G.width??z,B=G.height??Math.floor(J/Math.ceil($.length/Z));if(this.drawDashboardPanel(G,q,U,W,B),(V+1)%Z===0)K+=B+Y,X=1+Y;else X+=W+Y}this.renderStatusBar()}drawDashboardPanel($,Z,Y,Q,J){let z=J-2,K=$.content.slice(0,z);JZ(K,Z,Y,Q,{title:$.title})}createMorningBriefingLayout($){let Z=[{id:"tasks",title:"Tarefas do Dia",content:$.tasks.length>0?$.tasks:["Nenhuma tarefa para hoje"]},{id:"followups",title:"Follow-ups",content:$.followUps.length>0?$.followUps:["Nenhum follow-up pendente"]},{id:"calendar",title:"Agenda",content:$.calendar.length>0?$.calendar:["Sem eventos hoje"]},{id:"news",title:"Noticias",content:$.news.length>0?$.news:["Sem noticias recentes"]}];if($.projectSummary)Z.push({id:"project",title:"Projetos",content:$.projectSummary});return{panels:Z,columns:2,gap:1}}createMonitoringLayout($){return{panels:[{id:"telemetry",title:"Sistema",content:QZ($,35)}],columns:1,gap:1}}}function x5($,Z){N(`\x1B[${$};${Z}r`)}function f5(){N("\x1B[r")}var iU=new i8;w1();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,Y="",Q){this.model=$;this.sessionName=Z;this.authInfo=Y;this.dataDir=Q;this.viewManager=new i8}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(nU(this.dataDir,"history"));this.setupEventListeners(),N(H.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(z$.on("context:changed",($)=>{this.statusBarContext=$.foregroundWindow||"",this.renderHeader()})),this.eventUnsubscribers.push(z$.on("status:update",($)=>{let Z=$.level==="error"?I.err:$.level==="warning"?I.prompt:$.level==="success"?I.sys:H.dim;if(this.lines.push({text:` ${Z}[${$.source}]${H.reset} ${$.message}`}),!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z$.on("telemetry:alert",($)=>{if($.alertType==="cost_warning")this.lines.push({text:` ${I.prompt}\u26A0 ${$.message}${H.reset}`});else if($.alertType==="rate_limit")this.lines.push({text:` ${I.err}\u26A0 Rate limit: ${$.message}${H.reset}`});else this.lines.push({text:` ${H.dim}[telemetry] ${$.message}${H.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z$.on("task:completed",($)=>{if($.taskType==="backup"&&$.success)this.lines.push({text:` ${H.dim}[backup] ${$.message||"Backup concluido"}${H.reset}`});else if($.taskType==="pomodoro")this.lines.push({text:` ${I.sys}[pomodoro] ${$.message}${H.reset}`});else if(!$.success&&$.message)this.lines.push({text:` ${I.err}[${$.taskType}] ${$.message}${H.reset}`});if(!this.isStreaming)this.renderMessages()})),this.eventUnsubscribers.push(z$.on("session:changed",($)=>{this.sessionName=$.currentSession,this.renderHeader()})),this.eventUnsubscribers.push(z$.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(),N(H.show),N(H.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=y5(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=y5(this.streamBuf,this.width).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let Y=Z,Q;switch($){case"read_file":if(Q=String(Y.path||""),Y.offset)Q+=`:${Y.offset}`;break;case"write_file":case"edit_file":Q=String(Y.path||"");break;case"search_files":if(Q=`/${Y.pattern||""}/`,Y.include)Q+=` (${Y.include})`;break;case"find_files":Q=String(Y.pattern||"");break;case"list_directory":Q=String(Y.path||".");break;case"run_command":if(Q=String(Y.command||""),Q.length>80)Q=Q.slice(0,77)+"...";break;default:{let J=JSON.stringify(Y);Q=J.length>80?J.slice(0,77)+"...":J}}this.lines.push({text:` ${I.tool}\u2699 ${$}${H.reset} ${H.dim}${Q}${H.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
|
|
516
|
+
`),Q=8,J=Y.slice(0,8);for(let z of J){let K=z.length>this.width-6?z.slice(0,this.width-9)+"...":z;this.lines.push({text:` ${H.dim}${K}${H.reset}`})}if(Y.length>8)this.lines.push({text:` ${H.dim}... (${Y.length-8} more lines)${H.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${I.prompt}? ${$}${H.reset} ${H.dim}[y]es / [n]o / [a]ll${H.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(Q)=>{let J=Q.toString().toLowerCase();if(J==="y"||J==="\r"||J===`
|
|
517
|
+
`)process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.sys}approved${H.reset}`}),this.renderAll(),Z(!0);else if(J==="n"||J==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.err}rejected${H.reset}`}),this.renderAll(),Z(!1);else if(J==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${I.sys}approved all for this session${H.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${H.dim}timeout \u2014 auto-rejected${H.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=$.findIndex((G)=>G.isCurrent);if(Y<0)Y=0;let Q="",J=!1,z=()=>{if(!Q)return $;let G=Q.toLowerCase();return $.filter((q)=>q.name.toLowerCase().includes(G))},K=()=>{let U=this.height-2-2,W=z();if(Y>=W.length)Y=Math.max(0,W.length-1);let B=2,M=2,O=U-B-M,R=Math.max(1,O),P=0;if(W.length>R)P=Math.max(0,Y-Math.floor(R/2)),P=Math.min(P,W.length-R);let Q$=W.slice(P,P+R);if(N(H.hide),N(H.to(3,1)),N(H.clearLine),J)N(` ${I.heading}${H.bold}Sessions${H.reset} ${H.dim}filter: ${Q}\u2588${H.reset}`);else N(` ${I.heading}${H.bold}Sessions${H.reset} ${H.dim}(${W.length})${H.reset}`);N(H.to(4,1)),N(H.clearLine);for(let w=0;w<R;w++){let n=2+B+w+1;if(N(H.to(n,1)),N(H.clearLine),w>=Q$.length)continue;let t=Q$[w],A$=P+w===Y,V$=t.isCurrent?"*":" ",_$=t.isArchived?`${H.dim}[arch] ${H.reset}`:" ",A0=`${t.messageCount} msgs`.padEnd(10),Y0=rU(t.updated);if(A$)N(` ${I.prompt}${H.bold}\u203A ${V$} ${_$}${I.prompt}${H.bold}${t.name.padEnd(20)}${H.reset} ${H.dim}${A0} ${Y0}${H.reset}`);else{let Q0=t.isArchived?H.dim:I.sys;N(` ${V$} ${_$}${Q0}${t.name.padEnd(20)}${H.reset} ${H.dim}${A0} ${Y0}${H.reset}`)}}for(let w=Q$.length;w<R;w++){let n=2+B+w+1;N(H.to(n,1)),N(H.clearLine)}let l=2+B+R+1;if(N(H.to(l,1)),N(H.clearLine),W.length>R){let w=Math.round((Y+1)/W.length*100);N(` ${H.dim}${P>0?"\u2191":" "} ${w}% ${P+R<W.length?"\u2193":" "}${H.reset}`)}let A=this.height-2;N(H.to(A,1)),N(H.clearLine),N(` ${H.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${H.reset}`)},X=(G)=>{this.pickerActive=!1,process.stdin.removeListener("data",V),this.renderAll(),Z(G)},V=(G)=>{let q=G.toString("utf-8"),U=z();if(q==="\x1B"&&G.length===1){if(J)J=!1,Q="",K();else X(null);return}if(q==="\x03"){X(null);return}if(q==="\r"||q===`
|
|
518
|
+
`){if(U.length>0&&Y<U.length)X({action:"load",name:U[Y].name});return}if(q==="\x1B[A"||q==="w"&&!J){if(Y>0)Y--,K();return}if(q==="\x1B[B"||q==="s"&&!J){if(Y<U.length-1)Y++,K();return}if(q==="d"&&J===!1){if(U.length>0&&Y<U.length){let W=U[Y];if(!W.isCurrent)X({action:"delete",name:W.name,isArchived:W.isArchived})}return}if(q==="a"&&J===!1){if(U.length>0&&Y<U.length){let W=U[Y];if(!W.isCurrent){let B=W.isArchived?"unarchive":"archive";X({action:B,name:W.name})}}return}if(q==="/"&&J===!1){J=!0,Q="",K();return}if(J){if(q==="\x7F"||q==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,K();else J=!1,K();return}if(q.length===1&&q>=" "){Q+=q,Y=0,K();return}}};process.stdin.on("data",V),K()})}promptNewsPicker($){if($.length===0)return this.showSystem("Nenhuma noticia encontrada."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let Y=0,Q="",J=!1,z="",K=[...new Set($.map((W)=>W.category))].sort(),X=()=>{let W=z?$.filter((B)=>B.category===z):$;if(Q){let B=Q.toLowerCase();W=W.filter((M)=>M.title.toLowerCase().includes(B)||M.source.toLowerCase().includes(B))}return W},V=(W)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[W]||W},G=()=>{let M=this.height-2-2,O=X();if(Y>=O.length)Y=Math.max(0,O.length-1);let R=2,P=2,Q$=M-R-P,l=Math.max(1,Q$),A=0;if(O.length>l)A=Math.max(0,Y-Math.floor(l/2)),A=Math.min(A,O.length-l);let w=O.slice(A,A+l);if(N(H.hide),N(H.to(3,1)),N(H.clearLine),J)N(` ${I.heading}${H.bold}Noticias${H.reset} ${H.dim}filtro: ${Q}\u2588${H.reset}`);else{let _=z?V(z):"Todas";N(` ${I.heading}${H.bold}Noticias${H.reset} ${H.dim}(${O.length}) ${_}${H.reset}`)}N(H.to(4,1)),N(H.clearLine);for(let _=0;_<l;_++){let A$=2+R+_+1;if(N(H.to(A$,1)),N(H.clearLine),_>=w.length)continue;let V$=w[_],_$=A+_===Y,A0=V$.time?`[${V$.time}]`:" ",Y0=this.width-30,Q0=V$.title.length>Y0?V$.title.slice(0,Y0-1)+"\u2026":V$.title;if(_$)N(` ${I.prompt}${H.bold}\u203A ${A0} ${Q0}${H.reset} ${H.dim}(${V$.source})${H.reset}`);else N(` ${H.dim}${A0}${H.reset} ${I.sys}${Q0}${H.reset} ${H.dim}(${V$.source})${H.reset}`)}for(let _=w.length;_<l;_++){let A$=2+R+_+1;N(H.to(A$,1)),N(H.clearLine)}let n=2+R+l+1;if(N(H.to(n,1)),N(H.clearLine),O.length>l){let _=Math.round((Y+1)/O.length*100);N(` ${H.dim}${A>0?"\u2191":" "} ${_}% ${A+l<O.length?"\u2193":" "}${H.reset}`)}let t=this.height-2;N(H.to(t,1)),N(H.clearLine),N(` ${H.dim}\u2191\u2193 navegar Enter abrir Ctrl+Enter ler aqui Esc cancelar / filtrar Tab categoria${H.reset}`)},q=(W)=>{this.pickerActive=!1,process.stdin.removeListener("data",U),this.renderAll(),Z(W)},U=(W)=>{let B=W.toString("utf-8"),M=X();if(B==="\x1B"&&W.length===1){if(J)J=!1,Q="",G();else q(null);return}if(B==="\x03"){q(null);return}if(B===`
|
|
519
|
+
`||B==="\x1B\r"||B==="\x1BOM"){if(M.length>0&&Y<M.length)q({action:"read",link:M[Y].link});return}if(B==="\r"||B===`
|
|
520
|
+
`){if(M.length>0&&Y<M.length)q({action:"open",link:M[Y].link});return}if(B==="\x1B[A"||B==="w"&&!J){if(Y>0)Y--,G();return}if(B==="\x1B[B"||B==="s"&&!J){if(Y<M.length-1)Y++,G();return}if(B==="\t"){if(!z)z=K[0]||"";else{let O=K.indexOf(z);z=O<K.length-1?K[O+1]:""}Y=0,G();return}if(B==="/"&&!J){J=!0,Q="",G();return}if(J){if(B==="\x7F"||B==="\b"){if(Q.length>0)Q=Q.slice(0,-1),Y=0,G();else J=!1,G();return}if(B.length===1&&B>=" "){Q+=B,Y=0,G();return}}};process.stdin.on("data",U),G()})}showUsage($){this.lines.push({text:` ${H.dim}tokens: ${$}${H.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${I.err}\u2717 ${$}${H.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
|
|
521
|
+
`))this.lines.push({text:` ${I.sys}${Z}${H.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(){N(H.hide)}getViewMode(){return this.viewMode}enterChatMode(){if(this.viewMode==="chat")return;this.viewMode="chat",this.viewManager.enterChatMode(),f5(),this.render()}enterDashboardMode($){this.viewMode="dashboard";let Z=[...$.panels];if(!Z.some((Q)=>Q.id==="meta-learning")&&this.metaLearningEntries.length>0){let Q=Math.floor(this.width/2)-4,J=_5(this.metaLearningEntries,Q);Z=[...Z,J]}this.dashboardContent=Z,this.viewManager.enterDashboardMode({...$,panels:Z}),x5(3,this.height-2),this.renderDashboard()}updateDashboardPanel($,Z){let Y=this.dashboardContent.find((Q)=>Q.id===$);if(Y){if(Y.content=Z,this.viewMode==="dashboard")this.renderDashboard()}}updateStatusBar($){if($.project!==void 0)this.activeProject=$.project;if($.inputTokens!==void 0)this.inputTokens=$.inputTokens;if($.outputTokens!==void 0)this.outputTokens=$.outputTokens;if($.vaultStatus!==void 0)this.vaultStatus=$.vaultStatus;this.renderStickyStatusBar()}setStatusBarEnabled($){this.statusBarEnabled=$,this.render()}showInsight($){if(this.activeInsight)this.dismissInsight();this.activeInsight=$;let Z=zZ($,{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;N(H.hide);for(let Y=0;Y<$.length;Y++)N(H.to(Z+Y,1)),N(H.clearLine),N($[Y]);N(H.show)}dismissInsight(){if(!this.activeInsight||!this.insightDisplayed)return;let $=this.height-1-this.insightSnippetLines-1;N(H.hide);for(let Z=0;Z<this.insightSnippetLines;Z++)N(H.to($+Z,1)),N(H.clearLine);N(H.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(z$.emit("insight:accepted",Z),this.lines.push({text:` ${I.sys}\u2713 Dica aceita: ${$.title}${H.reset}`}),$.suggestedAction)this.lines.push({text:` ${H.dim}Executando: ${$.suggestedAction.command}${H.reset}`});this.dismissInsight()}hasActiveInsight(){return this.activeInsight!==null&&this.insightDisplayed}updateMetaLearningEntries($){if(this.metaLearningEntries=$,this.viewMode==="dashboard"){let Z=_5($,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((Y)=>Y.title===$.title))this.metaLearningEntries=this.metaLearningEntries.map((Y)=>Y.title===$.title?{...Y,frequency:Y.frequency+1,lastSeen:Date.now()}:Y);else this.metaLearningEntries=[...this.metaLearningEntries,{...$,frequency:1,lastSeen:Date.now()}]}renderDashboard(){N(H.hide),N(H.clear),this.renderHeader();let $=2,Z=2+(this.statusBarEnabled?1:0),Y=this.height-$-Z,Q=this.dashboardContent,J=Math.min(2,Q.length),z=Math.ceil(Q.length/J),K=1,X=Math.floor((this.width-K*(J+1))/J),V=Math.floor((Y-K*(z+1))/z),G=0;for(let q=0;q<z;q++)for(let U=0;U<J&&G<Q.length;U++){let W=Q[G],B=$+K+q*(V+K)+1,M=K+U*(X+K)+1;this.drawDashboardPanel(W,B,M,X,V),G++}if(this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),N(H.show)}drawDashboardPanel($,Z,Y,Q,J){let z=this.personaMode==="sharpen_or_relax"?this.palette.muted:H.dim,K=this.palette.primary,X=o8($.content.slice(0,J-2),Q,{title:$.title,borderColor:z,titleColor:K});for(let V=0;V<X.length&&V<J;V++)N(H.to(Z+V,Y)),N(X[V])}renderStickyStatusBar(){if(!this.statusBarEnabled)return;let $=this.height-2;this.stickyStatusRow=$;let Z=[];if(this.personaMode!=="productivity"){let Q=this.personaMode==="spillover_alert"?this.palette.accent:this.palette.primary;Z.push({label:"MODE",value:this.getPersonaLabel(),color:Q})}if(this.timeContext&&this.personaMode==="spillover_alert"){let Q=this.timeContext.urgentTasks.length+this.timeContext.overdueTasks.length+this.timeContext.pendingCommits.length;if(Q>0)Z.push({label:"PEND",value:String(Q),color:this.palette.accent})}let Y={model:this.model,project:this.activeProject||void 0,tokens:{input:this.inputTokens,output:this.outputTokens},sessionCost:this.sessionCost||void 0,vaultStatus:this.vaultStatus,customItems:Z.length>0?Z:void 0};N(H.to($,1)),N(this.renderPersonaAwareStatusBar(Y))}renderPersonaAwareStatusBar($){let Z=l8($,this.width);if(this.personaMode==="sharpen_or_relax")return`${this.palette.muted}${P0(Z)}${H.reset}`;return Z}render(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(N(H.hide),N(H.clear),this.renderHeader(),this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput(),N(H.show)}renderAll(){if(this.viewMode==="dashboard"){this.renderDashboard();return}if(this.renderMessages(),this.statusBarEnabled)this.renderStickyStatusBar();this.renderInput()}renderHeader(){N(H.to(1,1));let $=this.palette.header,Z=this.getHeaderBgColor();N(Z),N(H.inv);let Q=` smolerclaw${this.personaMode!=="productivity"?` [${this.getPersonaLabel()}]`:""}`,J=[this.model,this.sessionName];if(this.sessionCost)J.push(this.sessionCost);if(this.authInfo)J.push(this.authInfo);let z=J.join(" | ")+" ",K=Math.max(1,this.width-Z$(Q)-z.length);N(Q+" ".repeat(K)+z),N(H.reset),N(H.to(2,1));let X=this.personaMode==="sharpen_or_relax"?this.palette.muted:H.dim;N(`${X}${"\u2500".repeat(this.width)}${H.reset}`)}getHeaderBgColor(){switch(this.personaMode){case"productivity":return"";case"spillover_alert":return H.bg(52);case"sharpen_or_relax":return H.bg(53)}}renderMessages(){let Y=2+(this.statusBarEnabled?1:0),Q=this.height-2-Y,J=[...this.lines,...this.streamLines],z=J.length,K=Math.max(0,z-Q-this.scrollOffset),X=Math.min(z,K+Q),V=J.slice(K,X);N(H.hide);for(let G=0;G<Q;G++)if(N(H.to(2+G+1,1)),N(H.clearLine),G<V.length)N(V[G].text)}completeInput($){let Z=$.split(" "),Y=Z[0];if(Z.length===1){let K=this.commands.filter((X)=>X.startsWith(Y));if(K.length===1){let X=this.subcommands[K[0]];if(X&&X.length>0)return{value:K[0]+" ",options:`Opcoes: ${X.join(" ")}`};return{value:K[0]+" "}}if(K.length>1){let X=K[0];for(let V of K)while(!V.startsWith(X))X=X.slice(0,-1);return{value:X.length>$.length?X:$,options:K.join(" ")}}return null}let Q=this.subcommands[Y];if(!Q||Q.length===0)return null;let J=Z[Z.length-1].toLowerCase(),z=Q.filter((K)=>K.toLowerCase().startsWith(J));if(z.length===1)return Z[Z.length-1]=z[0],{value:Z.join(" ")+" "};if(z.length>1){let K=z[0];for(let X of z)while(!X.toLowerCase().startsWith(K.toLowerCase()))K=K.slice(0,-1);if(K.length>J.length)return Z[Z.length-1]=K,{value:Z.join(" "),options:z.join(" ")};return{value:$,options:z.join(" ")}}if(!J&&Q.length>0)return{value:$,options:Q.join(" ")};return null}renderInput(){let $=this.height-1,Z=this.height;if(N(H.to($,1)),N(H.clearLine),N(`${H.dim}${"\u2500".repeat(this.width)}${H.reset}`),N(H.to(Z,1)),N(H.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);N(` ${I.ai}${this.getSpinnerChar()}${H.reset} ${H.dim}streaming... ${Y}s${H.reset}`),N(H.hide)}else{let Y=Z$(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;N(`${I.prompt}\u276F${H.reset} ${Y}`);let Q=this.inputBuf.slice(0,this.inputPos),J=Z$(Q)+3;N(H.to(Z,Math.min(J,this.width))),N(H.show)}}onKey($){if(this.pickerActive)return;let Z=$.toString("utf-8");if(this.hasActiveInsight()){let Y=Z.toLowerCase();if(Y==="y"){this.acceptInsight();return}if(Y==="n"||Z==="\x1B"){this.dismissInsight();return}this.dismissInsight()}if(Z==="\x03"){if(this.isStreaming){this.onCancel?.();return}let Y=Date.now(),Q=1500;if(this.inputBuf.length>0){this.inputBuf="",this.inputPos=0,this.lastCtrlCTime=Y,this.renderInput();return}if(Y-this.lastCtrlCTime<Q){this.onExit?.();return}this.lastCtrlCTime=Y,this.showSystem("Pressione Ctrl+C novamente para sair.");return}if(Z==="\x04"){this.onExit?.();return}if(Z==="\f"){this.render();return}if(this.isStreaming)return;if(Z==="\t"){if(this.inputBuf.startsWith("/")){let Y=this.completeInput(this.inputBuf);if(Y){if(this.inputBuf=Y.value,this.inputPos=this.inputBuf.length,this.renderInput(),Y.options)this.showSystem(Y.options)}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!yJ(Z)){let Y=Z.replace(/\r?\n/g," ").trim();if(Y.length>0)this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Y+this.inputBuf.slice(this.inputPos),this.inputPos+=Y.length,this.renderInput();return}if(Z==="\r"||Z===`
|
|
511
522
|
`){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
|
|
512
|
-
`,this.inputPos=this.inputBuf.length,this.renderInput();return}let
|
|
523
|
+
`,this.inputPos=this.inputBuf.length,this.renderInput();return}let Y=this.inputBuf.trim();if(Y)this.history?.add(Y),this.inputBuf="",this.inputPos=0,this.scrollOffset=0,this.onSubmit?.(Y);return}if(Z==="\x7F"||Z==="\b"){if(this.inputPos>0){let Y=wJ(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-Y)+this.inputBuf.slice(this.inputPos),this.inputPos-=Y,this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=wJ(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=kJ(this.inputBuf,this.inputPos),this.renderInput();break;case"A":{let Q=this.history?.prev(this.inputBuf);if(Q!==null&&Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.renderInput();break}case"B":{let Q=this.history?.next();if(Q!==void 0)this.inputBuf=Q,this.inputPos=this.inputBuf.length,this.renderInput();break}case"5~":if(this.scrollOffset<this.lines.length)this.scrollOffset=Math.min(this.scrollOffset+5,this.lines.length),this.renderMessages();break;case"6~":if(this.scrollOffset>0)this.scrollOffset=Math.max(0,this.scrollOffset-5),this.renderMessages();break;case"H":this.inputPos=0,this.renderInput();break;case"F":this.inputPos=this.inputBuf.length,this.renderInput();break;case"3~":{if(this.inputPos<this.inputBuf.length){let Q=kJ(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Q),this.renderInput()}break}}return}if(aU(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")x5(3,this.height-2);else f5();this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${I.user}${H.bold} You${H.reset} ${H.dim}${Z}${H.reset}`});else this.lines.push({text:`${I.ai}${H.bold} Claude${H.reset} ${H.dim}${Z}${H.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=T0(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=y5($,this.width);for(let Y of Z)this.lines.push({text:Y})}}function yJ($){return[...$].length===1}function aU($){if(!yJ($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function wJ($,Z){if(Z<=0)return 0;if(Z>=2){let Y=$.charCodeAt(Z-1),Q=$.charCodeAt(Z-2);if(Y>=56320&&Y<=57343&&Q>=55296&&Q<=56319)return 2}return 1}function kJ($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}function rU($){let Z=Date.now()-$,Y=Math.floor(Z/1000);if(Y<60)return"just now";let Q=Math.floor(Y/60);if(Q<60)return`${Q}m ago`;let J=Math.floor(Q/60);if(J<24)return`${J}h ago`;let z=Math.floor(J/24);if(z<30)return`${z}d ago`;return`${Math.floor(z/30)}mo ago`}var n8={"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}},sU={input:3,output:15};function bJ($,Z){let Y=tU(Z),Q=$.inputTokens/1e6*Y.input*100,J=$.outputTokens/1e6*Y.output*100;return{inputCostCents:Q,outputCostCents:J,totalCostCents:Q+J}}function tU($){if(n8[$])return n8[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return n8["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return n8["claude-opus-4-20250514"];if(Z.includes("sonnet"))return n8["claude-sonnet-4-20250514"];return sU}class XZ{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=bJ($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=bJ($,this.model);return`${v5($.inputTokens)} in / ${v5($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${v5(this.totalInput)} in / ${v5(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function v5($){return $.toLocaleString("en-US")}import{existsSync as _J,readFileSync as xJ,statSync as fJ}from"fs";import{basename as eU,extname as vJ,resolve as hJ}from"path";var gJ=new Set([".png",".jpg",".jpeg",".gif",".webp"]),$H=20971520,ZH=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"]),YH=1048576;function mJ($){let Z=[],Y=$.split(/\s+/),Q=[];for(let J of Y){let z=J.replace(/^["']|["']$/g,""),K=vJ(z).toLowerCase();if(gJ.has(K)){let X=hJ(z);if(_J(X))try{if(fJ(X).size>$H){Q.push(`[image too large: ${z}]`);continue}let q=xJ(X).toString("base64"),U=QH(K);Z.push({path:X,mediaType:U,base64:q}),Q.push(`[image: ${z}]`)}catch{Q.push(J)}else Q.push(J)}else Q.push(J)}return{text:Q.join(" "),images:Z}}function QH($){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 uJ($){let Z=[],Y=$.split(/\s+/),Q=[];for(let J of Y){let z=J.replace(/^["']|["']$/g,""),K=vJ(z).toLowerCase();if(gJ.has(K)){Q.push(J);continue}if(!(ZH.has(K)||(z.includes("/")||z.includes("\\"))&&K.length>0)){Q.push(J);continue}let V=hJ(z);if(!_J(V)){Q.push(J);continue}try{let G=fJ(V);if(!G.isFile()){Q.push(J);continue}if(G.size>YH){Q.push(`[file too large: ${z} (${(G.size/1024).toFixed(0)}KB)]`);continue}if(G.size===0){Q.push(`[empty file: ${z}]`);continue}let q=xJ(V,"utf-8"),U=eU(V);Z.push({path:V,name:U,content:q,size:G.size}),Q.push(`[file: ${U}]`)}catch{Q.push(J)}}return{text:Q.join(" "),files:Z}}i0();import{existsSync as pJ,readFileSync as JH}from"fs";import{join as dJ}from"path";p();function zH(){let $=new Date().getDay();return $===0||$===6}function KH(){return zH()?"weekend":"weekday"}async function XH($){let Z=[],Y=[],Q=[],J=new Date,z=new Date(J);z.setHours(23,59,59,999);let K=dJ($,"tasks.json");if(pJ(K))try{let G=JSON.parse(JH(K,"utf-8"));for(let q of G){if(q.done)continue;if(q.dueAt){let U=new Date(q.dueAt),W=U<J,B=!W&&U<=z;if(W)Y.push({id:q.id,title:q.title,dueAt:q.dueAt,isOverdue:!0});else if(B)Z.push({id:q.id,title:q.title,dueAt:q.dueAt,isOverdue:!1})}}}catch(G){X$.debug("Failed to parse task for spillover check",{error:G})}let X=R1(!0);for(let G of X.slice(0,5)){let q=await VH(G);if(q)Q.push(q)}return{hasSpillover:Z.length>0||Y.length>0||Q.length>0,urgentTasks:Z,overdueTasks:Y,pendingCommits:Q}}async function VH($){if(!pJ(dJ($.path,".git")))return null;try{let Z=Bun.spawn(["git","status","--porcelain"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),Y=await new Response(Z.stdout).text();await Z.exited;let Q=Y.trim().length>0,J=Bun.spawn(["git","rev-list","--count","@{u}..HEAD"],{cwd:$.path,stdout:"pipe",stderr:"pipe"}),z=await new Response(J.stdout).text(),X=await J.exited===0?parseInt(z.trim())||0:0;if(Q||X>0)return{projectName:$.name,projectPath:$.path,uncommittedChanges:Q,unpushedCommits:X}}catch(Z){X$.debug("Git status check failed for project",{error:Z})}return null}function GH($,Z){if($==="weekday")return"productivity";if(Z)return"spillover_alert";return"sharpen_or_relax"}async function a8($){let Z=KH(),Y=await XH($),Q=GH(Z,Y.hasSpillover);return{dayType:Z,workloadState:Y.hasSpillover?"spillover":"clear",persona:Q,urgentTasks:Y.urgentTasks,overdueTasks:Y.overdueTasks,pendingCommits:Y.pendingCommits}}function qH($){let Y=["Domingo","Segunda","Terca","Quarta","Quinta","Sexta","Sabado"][new Date().getDay()];switch($.persona){case"productivity":return`=== BRIEFING DIARIO === ${Y}
|
|
524
|
+
Modo: Produtividade Total`;case"spillover_alert":return`=== BRIEFING DIARIO === ${Y}
|
|
525
|
+
\u26A0 Trabalho escorrido detectado.`;case"sharpen_or_relax":return`=== BRIEFING DIARIO === ${Y}
|
|
526
|
+
Modo: Sharpen or Relax`}}function UH($){let Z=[];if($.overdueTasks.length>0){Z.push(`
|
|
527
|
+
--- Tarefas Atrasadas ---`);for(let Y of $.overdueTasks.slice(0,5)){let Q=Y.dueAt?new Date(Y.dueAt).toLocaleDateString("pt-BR"):"";Z.push(` \u26A0 ${Y.title} (venceu ${Q})`)}}if($.urgentTasks.length>0){Z.push(`
|
|
528
|
+
--- Tarefas Urgentes (Hoje) ---`);for(let Y of $.urgentTasks.slice(0,5)){let Q=Y.dueAt?new Date(Y.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";Z.push(` ! ${Y.title} (${Q})`)}}if($.pendingCommits.length>0){Z.push(`
|
|
529
|
+
--- Git Pendente ---`);for(let Y of $.pendingCommits){let Q=[];if(Y.uncommittedChanges)Q.push("uncommitted");if(Y.unpushedCommits>0)Q.push(`${Y.unpushedCommits} unpushed`);Z.push(` ${Y.projectName}: ${Q.join(", ")}`)}}return Z.join(`
|
|
530
|
+
`)}function HH($){if($.persona!=="sharpen_or_relax")return"";return`
|
|
531
|
+
--- Fim de Semana Livre ---
|
|
532
|
+
|
|
533
|
+
[A] Amolar o Machado
|
|
534
|
+
Estudo de arquitetura, refatoracao, melhoria do CLI
|
|
535
|
+
|
|
536
|
+
[B] Descompressao Criativa
|
|
537
|
+
Projetos paralelos sem prazo, foco pessoal/familia`}function WH($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
|
|
538
|
+
--- Sugestao: Timebox ---
|
|
539
|
+
Liquidar pendencias em ${Math.min(90,Z*15)} minutos.
|
|
540
|
+
Depois: descanso merecido.`}async function cJ($){let Z=[],Y=null;if($)Y=await a8($),Z.push(qH(Y));else Z.push("=== BRIEFING DIARIO ===");let Q=await o0();if(Z.push(Q),Y&&Y.workloadState==="spillover"){let z=UH(Y);if(z)Z.push(z);let K=WH(Y);if(K)Z.push(K)}if(Y){let z=HH(Y);if(z)Z.push(z)}if(L)try{let z=await k$();Z.push(`
|
|
541
|
+
--- Agenda ---
|
|
542
|
+
${z}`)}catch{Z.push(`
|
|
543
|
+
--- Agenda ---
|
|
544
|
+
Outlook nao disponivel.`)}if(L)try{let z=await l0();Z.push(`
|
|
545
|
+
--- Sistema ---
|
|
546
|
+
${z}`)}catch(z){X$.debug("System info unavailable for briefing",{error:z})}let J=Y?.persona==="sharpen_or_relax"?2:3;try{let z=await M0(["finance","business","tech"],J);Z.push(`
|
|
547
|
+
${z}`)}catch{Z.push(`
|
|
548
|
+
--- Noticias ---
|
|
549
|
+
Falha ao carregar noticias.`)}return Z.push(`
|
|
550
|
+
======================`),Z.join(`
|
|
551
|
+
`)}p();f$();var b=null,h5=null,VZ=null,GZ=0;function iJ($){VZ=$}function nJ($="foco",Z=25,Y=5){if(b)return`Pomodoro ja ativo: "${b.label}" (${sJ()}). Use /pomodoro stop para parar.`;return b={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},GZ++,rJ(),`Pomodoro #${GZ} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function aJ(){if(!b)return"Nenhum pomodoro ativo.";let $=b.label,Z=Math.floor((Date.now()-b.startedAt)/60000);return g5(),b=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function qZ(){if(!b)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=sJ();return`${b.type==="work"?"Trabalhando":"Pausa"}: "${b.label}" \u2014 ${$} restante(s) (ciclo #${GZ})`}function rJ(){if(!b)return;g5();let $=b.startedAt+b.durationMs-Date.now();if($<=0){lJ();return}h5=setTimeout(lJ,$)}function lJ(){if(!b)return;if(b.type==="work"){let $=`Pomodoro: "${b.label}" concluido! Hora da pausa (${b.breakMs/60000}min).`;oJ("Pausa!",`"${b.label}" concluido. Descanse ${b.breakMs/60000} minutos.`),VZ?.($),b={...b,type:"break",startedAt:Date.now(),durationMs:b.breakMs},rJ()}else oJ("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),VZ?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),g5(),b=null}function g5(){if(h5)clearTimeout(h5),h5=null}function sJ(){if(!b)return"0min";let $=Math.max(0,b.startedAt+b.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function oJ($,Z){if(!L)return;try{await J0($,Z,{timeout:1e4})}catch{}}function tJ(){g5(),b=null}p();f$();var T$=new Map,UZ=null;function $z($){UZ=$}function Zz($,Z=60){if(!L)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(T$.has(Y))return`"${$}" ja esta sendo monitorado.`;let Q=setInterval(()=>eJ(Y),Z*1000);return T$.set(Y,{name:$,interval:Q,lastSeen:!0}),eJ(Y),`Monitorando "${$}" a cada ${Z}s.`}function Yz($){let Z=$.toLowerCase(),Y=T$.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),T$.delete(Z),`Monitor parado: "${$}"`}function Qz(){if(T$.size===0)return"Nenhum processo monitorado.";let $=[...T$.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${T$.size}):
|
|
552
|
+
${$.join(`
|
|
553
|
+
`)}`}function Jz(){for(let $ of T$.values())clearInterval($.interval);T$.clear()}async function eJ($){let Z=T$.get($);if(!Z)return;let Y=await J4(Z.name,{timeout:1e4});if(Z.lastSeen&&!Y){let Q=`ALERTA: "${Z.name}" parou de rodar!`;J0("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),UZ?.(Q)}else if(!Z.lastSeen&&Y){let Q=`"${Z.name}" voltou a rodar.`;UZ?.(Q)}T$.set($,{...Z,lastSeen:Y})}f();i0();import{existsSync as BH,readFileSync as MH,writeFileSync as CH}from"fs";import{join as NH}from"path";p();var zz="",Kz=()=>NH(zz,"last-morning.txt");function Xz($){zz=$;let Z=Kz(),Y=new Date().toISOString().split("T")[0];if(!BH(Z))return!0;try{return MH(Z,"utf-8").trim()!==Y}catch{return!0}}function Vz(){let $=new Date().toISOString().split("T")[0];CH(Kz(),$)}async function Gz(){let $=[],Z=new Date().getHours(),Y=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Y}! Briefing do dia`),$.push(`==============================
|
|
554
|
+
`);let Q=await o0();$.push(Q);let z=l$().filter((U)=>{if(!U.dueAt)return!1;let W=new Date(U.dueAt),B=new Date;return W.toDateString()===B.toDateString()});if(z.length>0)$.push(`
|
|
555
|
+
--- Tarefas do dia ---`),$.push(f0(z));let K=C1();if(K.length>0)$.push(`
|
|
556
|
+
--- Follow-ups pendentes ---`),$.push(b7(K));let V=g0().filter((U)=>U.status==="atrasado");if(V.length>0)$.push(`
|
|
557
|
+
--- Delegacoes atrasadas ---`),$.push(y7(V));let G=o7();if(G)$.push(`
|
|
558
|
+
${G}`);if(L)try{let U=await k$();$.push(`
|
|
559
|
+
--- Agenda ---`),$.push(U)}catch{}try{let U=await M0(["finance","business","tech"],2);$.push(`
|
|
560
|
+
`+U)}catch{}let q=l$();if(q.length>0&&z.length!==q.length)$.push(`
|
|
561
|
+
${q.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
|
|
562
|
+
==============================`),$.join(`
|
|
563
|
+
`)}f();f();i0();p();f$();import{existsSync as qz,mkdirSync as OH,readFileSync as FH}from"fs";import{join as RH}from"path";import{randomUUID as EH}from"crypto";var Uz="",Y$=[],Hz=()=>RH(Uz,"workflows.json");function r8(){D(Hz(),JSON.stringify(Y$,null,2))}function LH(){let $=Hz();if(!qz($)){Y$=HZ(),r8();return}try{let Z=JSON.parse(FH($,"utf-8"));if(!Array.isArray(Z)){Y$=HZ(),r8();return}Y$=Z.map((Y)=>({id:Y.id||WZ(),name:Y.name||"unnamed",description:Y.description||"",steps:Array.isArray(Y.steps)?Y.steps:[],tags:Array.isArray(Y.tags)?Y.tags:[],enabled:Y.enabled!==!1,createdAt:Y.createdAt||new Date().toISOString(),updatedAt:Y.updatedAt||new Date().toISOString()}))}catch{Y$=HZ(),r8()}}function HZ(){let $=new Date().toISOString();return[{id:WZ(),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:WZ(),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 Wz($){if(Uz=$,!qz($))OH($,{recursive:!0});LH()}function s8($){let Z=$.toLowerCase().trim();return Y$.find((Y)=>Y.id===$)||Y$.find((Y)=>Y.name.toLowerCase()===Z)||Y$.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function Bz($){let Z=[...Y$];if($){let Y=$.toLowerCase();Z=Z.filter((Q)=>Q.tags.some((J)=>J.toLowerCase()===Y))}return Z}function BZ($,Z){let Y=s8($);if(!Y)return null;return Y$=Y$.map((Q)=>Q.id===Y.id?{...Q,...Z,updatedAt:new Date().toISOString()}:Q),r8(),Y$.find((Q)=>Q.id===Y.id)||null}function Mz($){let Z=s8($);if(!Z)return!1;return Y$=Y$.filter((Y)=>Y.id!==Z.id),r8(),!0}async function MZ($,Z){let Y=s8($);if(!Y){let J=Y$.map((z)=>z.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${J}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let Q=await Cz(Y.name,Y.steps,Z);return DH(Q)}async function Cz($,Z,Y){let Q=performance.now(),J=[`Executando workflow: "${$}"`],z=0,K=0,X=0,V=!0;for(let G=0;G<Z.length;G++){let q=Z[G],U=q.label||`${q.action}:${q.target}`,W=`[${G+1}/${Z.length}]`,B=q.on_error||"continue";Y?.(`${W} ${U}...`);try{let M=await jH(q,Y);J.push(` ${W} ${M}`),z++}catch(M){let O=M instanceof Error?M.message:String(M);switch(X++,B){case"stop":return J.push(` ${W} ERRO (parando): ${O}`),V=!1,{workflow:$,success:V,stepsRun:z,stepsSkipped:K,stepsFailed:X,log:J,duration:Math.round(performance.now()-Q)};case"skip":J.push(` ${W} ERRO (pulado): ${O}`),K++;break;case"continue":default:J.push(` ${W} ERRO (continuando): ${O}`);break}}}return{workflow:$,success:V,stepsRun:z,stepsSkipped:K,stepsFailed:X,log:J,duration:Math.round(performance.now()-Q)}}async function jH($,Z){switch($.action){case"open_app":{if(!L)return`skip: ${$.target} (not Windows)`;return await d0($.target)}case"open_url":{if(!L)return`skip: ${$.target} (not Windows)`;let Y=$.target.trim();if(!Y.startsWith("http://")&&!Y.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${Y}`);return await c0(Y)}case"run_command":{if(!L)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let Q=await J$(Y,{timeout:30000});if(Q.timedOut)throw Error("Command timeout (30s)");if(Q.exitCode!==0&&Q.stderr.trim())throw Error(`exit ${Q.exitCode}: ${Q.stderr.trim().slice(0,200)}`);let J=Q.stdout.trim().slice(0,200);return`Command: ${Y.slice(0,60)}${J?" -> "+J:""}`}case"wait":{let Y=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((Q)=>setTimeout(Q,Y*1000)),`Wait: ${Y}s`}case"notify":{if(L)try{J0("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!L)return"skip: condition (not Windows)";let Y=$.target.toLowerCase(),Q=await J4(Y,{timeout:5000});if(Q&&$.condition_steps&&$.condition_steps.length>0){let J=await Cz(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${Y} running=true, ran ${J.stepsRun} sub-steps`}return`Condition: ${Y} running=${Q}${!Q?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function Nz($){let Z=$||Y$;if(Z.length===0)return"Nenhum workflow configurado.";let Y=Z.map((Q)=>{let J=Q.enabled?"":" [DESATIVADO]",z=Q.tags.length>0?` [${Q.tags.join(", ")}]`:"",K=Q.steps.map((X)=>{let V=X.label||X.target;return X.action==="wait"?`${X.target}s`:V}).join(" -> ");return` ${Q.name}${J}${z} \u2014 ${Q.description}
|
|
564
|
+
${" ".repeat(4)}${K} {${Q.id}}`});return`Workflows (${Z.length}):
|
|
565
|
+
${Y.join(`
|
|
566
|
+
|
|
567
|
+
`)}`}function Oz($){let Z=$.enabled?"ativo":"desativado",Y=$.tags.length>0?`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`:"",Q=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(Y)Q.push(Y);return Q.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Q.push(""),Q.push("Steps:"),$.steps.forEach((J,z)=>{let K=J.label?` (${J.label})`:"",X=J.on_error&&J.on_error!=="continue"?` [on_error: ${J.on_error}]`:"";if(Q.push(` ${z+1}. ${J.action}: ${J.target}${K}${X}`),J.action==="if_app_running"&&J.condition_steps)for(let V of J.condition_steps)Q.push(` \u21B3 ${V.action}: ${V.target}`)}),Q.join(`
|
|
568
|
+
`)}function DH($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
|
|
569
|
+
`)}function WZ(){return EH().slice(0,8)}y8();function Fz($,Z,Y){pZ($,C4().replace(/[/\\]config\.json$/,"")),u3($),G3($),a3($),a6($),h9(Y),T3($),w3($),iJ((Q)=>Z.showSystem(`
|
|
570
|
+
*** ${Q} ***
|
|
571
|
+
`)),Wz($),u2($),NQ($),XY($),CY($),xY($),eY($,(Q)=>{Z.showSystem(`
|
|
572
|
+
*** Meta-Insight: ${Q.title} ***
|
|
573
|
+
${Q.recommendation}
|
|
574
|
+
`)}),$z((Q)=>Z.showSystem(`
|
|
575
|
+
*** ${Q} ***
|
|
576
|
+
`)),N3($,(Q)=>Z.showSystem(`
|
|
577
|
+
*** ${Q} ***
|
|
578
|
+
`)),Z3($,(Q)=>{Z.showSystem(`
|
|
579
|
+
*** LEMBRETE: ${Q.title} ***
|
|
580
|
+
`)})}function Rz($,Z={}){let{includeToolCalls:Y=!0,includeTimestamps:Q=!0}=Z,J=[];J.push(`# smolerclaw session: ${$.name}`),J.push(`Created: ${new Date($.created).toLocaleString()}`),J.push(""),J.push("---"),J.push("");for(let z of $.messages){let K=Q?` (${new Date(z.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(z.role==="user")J.push(`## You${K}`),J.push(""),J.push(z.content),J.push("");else{if(J.push(`## Claude${K}`),J.push(""),J.push(z.content),Y&&z.toolCalls?.length){J.push("");for(let X of z.toolCalls){let V=PH(X.name,X.input);J.push(`> **Tool:** \`${X.name}\`${V}`);let G=X.result.split(`
|
|
513
581
|
`).slice(0,5).join(`
|
|
514
|
-
`);if(
|
|
515
|
-
`))J.push(`> ${
|
|
516
|
-
`)}function
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
`+Q.stdout);return Y.join(`
|
|
523
|
-
|
|
524
|
-
`)||"(no changes)"}async function lY(){let $=await $8("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function oY(){return(await $8("git","add","-A")).ok}async function aY($){let Z=await $8("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function nY(){let $=await $8("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var rY={default:{name:"default",description:"Versatile assistant (general + coding)",systemPrompt:""},coder:{name:"coder",description:"Focused software engineer",systemPrompt:`You are a senior software engineer. Focus exclusively on code quality, architecture, and implementation.
|
|
582
|
+
`);if(G.trim()){J.push("> ```");for(let q of G.split(`
|
|
583
|
+
`))J.push(`> ${q}`);J.push("> ```")}}}if(z.usage)J.push(""),J.push(`*Tokens: ${z.usage.inputTokens} in / ${z.usage.outputTokens} out (~$${(z.usage.costCents/100).toFixed(4)})*`);J.push("")}J.push("---"),J.push("")}return J.join(`
|
|
584
|
+
`)}function PH($,Z){switch($){case"read_file":case"write_file":case"edit_file":return Z.path?` \`${Z.path}\``:"";case"search_files":return Z.pattern?` \`/${Z.pattern}/\``:"";case"find_files":return Z.pattern?` \`${Z.pattern}\``:"";case"run_command":return Z.command?` \`${Z.command}\``:"";default:return""}}async function r0(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[Y,Q]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),J=await Z.exited;return{stdout:Y.trim(),stderr:Q.trim(),ok:J===0}}async function Ez(){let $=await r0("git","diff","--cached"),Z=await r0("git","diff"),Y=await r0("git","ls-files","--others","--exclude-standard"),Q=[];if($.stdout)Q.push(`=== STAGED ===
|
|
585
|
+
`+$.stdout);if(Z.stdout)Q.push(`=== UNSTAGED ===
|
|
586
|
+
`+Z.stdout);if(Y.stdout)Q.push(`=== UNTRACKED ===
|
|
587
|
+
`+Y.stdout);return Q.join(`
|
|
588
|
+
|
|
589
|
+
`)||"(no changes)"}async function Lz(){let $=await r0("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function jz(){return(await r0("git","add","-A")).ok}async function Dz($){let Z=await r0("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function Pz(){let $=await r0("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var Tz={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.
|
|
525
590
|
|
|
526
591
|
Behavior:
|
|
527
592
|
- Write clean, production-grade code. No shortcuts.
|
|
@@ -552,122 +617,58 @@ Behavior:
|
|
|
552
617
|
- Be specific. Show the line, explain the problem, suggest the fix.
|
|
553
618
|
- Check for: error handling, input validation, edge cases, naming, complexity.
|
|
554
619
|
- Don't nitpick formatting unless it affects readability.
|
|
555
|
-
- Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function
|
|
556
|
-
`)}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
Modo: Sharpen or Relax`}}function yq($){let Z=[];if($.overdueTasks.length>0){Z.push(`
|
|
560
|
-
--- Tarefas Atrasadas ---`);for(let Q of $.overdueTasks.slice(0,5)){let Y=Q.dueAt?new Date(Q.dueAt).toLocaleDateString("pt-BR"):"";Z.push(` \u26A0 ${Q.title} (venceu ${Y})`)}}if($.urgentTasks.length>0){Z.push(`
|
|
561
|
-
--- Tarefas Urgentes (Hoje) ---`);for(let Q of $.urgentTasks.slice(0,5)){let Y=Q.dueAt?new Date(Q.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";Z.push(` ! ${Q.title} (${Y})`)}}if($.pendingCommits.length>0){Z.push(`
|
|
562
|
-
--- Git Pendente ---`);for(let Q of $.pendingCommits){let Y=[];if(Q.uncommittedChanges)Y.push("uncommitted");if(Q.unpushedCommits>0)Y.push(`${Q.unpushedCommits} unpushed`);Z.push(` ${Q.projectName}: ${Y.join(", ")}`)}}return Z.join(`
|
|
563
|
-
`)}function bq($){if($.persona!=="sharpen_or_relax")return"";return`
|
|
564
|
-
--- Fim de Semana Livre ---
|
|
565
|
-
|
|
566
|
-
[A] Amolar o Machado
|
|
567
|
-
Estudo de arquitetura, refatoracao, melhoria do CLI
|
|
568
|
-
|
|
569
|
-
[B] Descompressao Criativa
|
|
570
|
-
Projetos paralelos sem prazo, foco pessoal/familia`}function _q($){if($.persona!=="spillover_alert")return"";let Z=$.overdueTasks.length+$.urgentTasks.length+$.pendingCommits.length;return`
|
|
571
|
-
--- Sugestao: Timebox ---
|
|
572
|
-
Liquidar pendencias em ${Math.min(90,Z*15)} minutos.
|
|
573
|
-
Depois: descanso merecido.`}async function GJ($){let Z=[],Q=null;if($)Q=await W5($),Z.push(kq(Q));else Z.push("=== BRIEFING DIARIO ===");let Y=await u4();if(Z.push(Y),Q&&Q.workloadState==="spillover"){let X=yq(Q);if(X)Z.push(X);let K=_q(Q);if(K)Z.push(K)}if(Q){let X=bq(Q);if(X)Z.push(X)}if(A)try{let X=await h$();Z.push(`
|
|
574
|
-
--- Agenda ---
|
|
575
|
-
${X}`)}catch{Z.push(`
|
|
576
|
-
--- Agenda ---
|
|
577
|
-
Outlook nao disponivel.`)}if(A)try{let X=await c4();Z.push(`
|
|
578
|
-
--- Sistema ---
|
|
579
|
-
${X}`)}catch{}let J=Q?.persona==="sharpen_or_relax"?2:3;try{let X=await E4(["finance","business","tech"],J);Z.push(`
|
|
580
|
-
${X}`)}catch{Z.push(`
|
|
581
|
-
--- Noticias ---
|
|
582
|
-
Falha ao carregar noticias.`)}return Z.push(`
|
|
583
|
-
======================`),Z.join(`
|
|
584
|
-
`)}d4();import{existsSync as vq,readFileSync as fq,writeFileSync as hq}from"fs";import{join as gq}from"path";Z$();var HJ="",qJ=()=>gq(HJ,"last-morning.txt");function UJ($){HJ=$;let Z=qJ(),Q=new Date().toISOString().split("T")[0];if(!vq(Z))return!0;try{return fq(Z,"utf-8").trim()!==Q}catch{return!0}}function WJ(){let $=new Date().toISOString().split("T")[0];hq(qJ(),$)}async function BJ(){let $=[],Z=new Date().getHours(),Q=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${Q}! Briefing do dia`),$.push(`==============================
|
|
585
|
-
`);let Y=await u4();$.push(Y);let X=e$().filter((B)=>{if(!B.dueAt)return!1;let W=new Date(B.dueAt),N=new Date;return W.toDateString()===N.toDateString()});if(X.length>0)$.push(`
|
|
586
|
-
--- Tarefas do dia ---`),$.push(l4(X));let K=O8();if(K.length>0)$.push(`
|
|
587
|
-
--- Follow-ups pendentes ---`),$.push(x7(K));let G=n4().filter((B)=>B.status==="atrasado");if(G.length>0)$.push(`
|
|
588
|
-
--- Delegacoes atrasadas ---`),$.push(I7(G));let H=s7();if(H)$.push(`
|
|
589
|
-
${H}`);if(A)try{let B=await h$();$.push(`
|
|
590
|
-
--- Agenda ---`),$.push(B)}catch{}try{let B=await E4(["finance","business","tech"],2);$.push(`
|
|
591
|
-
`+B)}catch{}let z=e$();if(z.length>0&&X.length!==z.length)$.push(`
|
|
592
|
-
${z.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
|
|
593
|
-
==============================`),$.join(`
|
|
594
|
-
`)}Z$();d$();var m=null,B5=null,bZ=null,_Z=0;function MJ($){bZ=$}function FJ($="foco",Z=25,Q=5){if(m)return`Pomodoro ja ativo: "${m.label}" (${EJ()}). Use /pomodoro stop para parar.`;return m={startedAt:Date.now(),durationMs:Z*60000,breakMs:Q*60000,label:$,type:"work"},_Z++,RJ(),`Pomodoro #${_Z} iniciado: "${$}" (${Z}min trabalho / ${Q}min pausa)`}function OJ(){if(!m)return"Nenhum pomodoro ativo.";let $=m.label,Z=Math.floor((Date.now()-m.startedAt)/60000);return C5(),m=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function vZ(){if(!m)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=EJ();return`${m.type==="work"?"Trabalhando":"Pausa"}: "${m.label}" \u2014 ${$} restante(s) (ciclo #${_Z})`}function RJ(){if(!m)return;C5();let $=m.startedAt+m.durationMs-Date.now();if($<=0){CJ();return}B5=setTimeout(CJ,$)}function CJ(){if(!m)return;if(m.type==="work"){let $=`Pomodoro: "${m.label}" concluido! Hora da pausa (${m.breakMs/60000}min).`;NJ("Pausa!",`"${m.label}" concluido. Descanse ${m.breakMs/60000} minutos.`),bZ?.($),m={...m,type:"break",startedAt:Date.now(),durationMs:m.breakMs},RJ()}else NJ("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),bZ?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),C5(),m=null}function C5(){if(B5)clearTimeout(B5),B5=null}function EJ(){if(!m)return"0min";let $=Math.max(0,m.startedAt+m.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function NJ($,Z){if(!A)return;try{await H4($,Z,{timeout:1e4})}catch{}}function LJ(){C5(),m=null}n();d4();Z$();d$();import{existsSync as jJ,mkdirSync as mq,readFileSync as pq}from"fs";import{join as cq}from"path";import{randomUUID as uq}from"crypto";var DJ="",H$=[],PJ=()=>cq(DJ,"workflows.json");function e1(){S(PJ(),JSON.stringify(H$,null,2))}function dq(){let $=PJ();if(!jJ($)){H$=fZ(),e1();return}try{let Z=JSON.parse(pq($,"utf-8"));if(!Array.isArray(Z)){H$=fZ(),e1();return}H$=Z.map((Q)=>({id:Q.id||hZ(),name:Q.name||"unnamed",description:Q.description||"",steps:Array.isArray(Q.steps)?Q.steps:[],tags:Array.isArray(Q.tags)?Q.tags:[],enabled:Q.enabled!==!1,createdAt:Q.createdAt||new Date().toISOString(),updatedAt:Q.updatedAt||new Date().toISOString()}))}catch{H$=fZ(),e1()}}function fZ(){let $=new Date().toISOString();return[{id:hZ(),name:"iniciar-dia",description:"Abrir apps de trabalho: terminal e ferramentas",steps:[{action:"notify",target:"Iniciando ambiente de trabalho..."},{action:"open_app",target:"terminal",label:"Terminal"},{action:"wait",target:"2"},{action:"open_app",target:"vscode",label:"VS Code",on_error:"skip"},{action:"notify",target:"Ambiente pronto!"}],tags:["trabalho","diario"],enabled:!0,createdAt:$,updatedAt:$},{id:hZ(),name:"dev",description:"Ambiente de desenvolvimento: VSCode + Terminal",steps:[{action:"open_app",target:"vscode",label:"VS Code"},{action:"wait",target:"1"},{action:"open_app",target:"terminal",label:"Terminal"}],tags:["dev"],enabled:!0,createdAt:$,updatedAt:$}]}function TJ($){if(DJ=$,!jJ($))mq($,{recursive:!0});dq()}function $0($){let Z=$.toLowerCase().trim();return H$.find((Q)=>Q.id===$)||H$.find((Q)=>Q.name.toLowerCase()===Z)||H$.find((Q)=>Q.name.toLowerCase().includes(Z))||null}function AJ($){let Z=[...H$];if($){let Q=$.toLowerCase();Z=Z.filter((Y)=>Y.tags.some((J)=>J.toLowerCase()===Q))}return Z}function gZ($,Z){let Q=$0($);if(!Q)return null;return H$=H$.map((Y)=>Y.id===Q.id?{...Y,...Z,updatedAt:new Date().toISOString()}:Y),e1(),H$.find((Y)=>Y.id===Q.id)||null}function IJ($){let Z=$0($);if(!Z)return!1;return H$=H$.filter((Q)=>Q.id!==Z.id),e1(),!0}async function mZ($,Z){let Q=$0($);if(!Q){let J=H$.map((X)=>X.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${J}`}if(!Q.enabled)return`Workflow "${Q.name}" esta desativado.`;let Y=await xJ(Q.name,Q.steps,Z);return oq(Y)}async function xJ($,Z,Q){let Y=performance.now(),J=[`Executando workflow: "${$}"`],X=0,K=0,V=0,G=!0;for(let H=0;H<Z.length;H++){let z=Z[H],B=z.label||`${z.action}:${z.target}`,W=`[${H+1}/${Z.length}]`,N=z.on_error||"continue";Q?.(`${W} ${B}...`);try{let O=await lq(z,Q);J.push(` ${W} ${O}`),X++}catch(O){let j=O instanceof Error?O.message:String(O);switch(V++,N){case"stop":return J.push(` ${W} ERRO (parando): ${j}`),G=!1,{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:J,duration:Math.round(performance.now()-Y)};case"skip":J.push(` ${W} ERRO (pulado): ${j}`),K++;break;case"continue":default:J.push(` ${W} ERRO (continuando): ${j}`);break}}}return{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:J,duration:Math.round(performance.now()-Y)}}async function lq($,Z){switch($.action){case"open_app":{if(!A)return`skip: ${$.target} (not Windows)`;return await m4($.target)}case"open_url":{if(!A)return`skip: ${$.target} (not Windows)`;let Q=$.target.trim();if(!Q.startsWith("http://")&&!Q.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${Q}`);return await p4(Q)}case"run_command":{if(!A)return"skip: command (not Windows)";let Q=$.target;if(!Q.trim())throw Error("Comando vazio");let Y=await U$(Q,{timeout:30000});if(Y.timedOut)throw Error("Command timeout (30s)");if(Y.exitCode!==0&&Y.stderr.trim())throw Error(`exit ${Y.exitCode}: ${Y.stderr.trim().slice(0,200)}`);let J=Y.stdout.trim().slice(0,200);return`Command: ${Q.slice(0,60)}${J?" -> "+J:""}`}case"wait":{let Q=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((Y)=>setTimeout(Y,Q*1000)),`Wait: ${Q}s`}case"notify":{if(A)try{H4("smolerclaw",$.target,{timeout:1e4}).catch(()=>{})}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!A)return"skip: condition (not Windows)";let Q=$.target.toLowerCase(),Y=await z0(Q,{timeout:5000});if(Y&&$.condition_steps&&$.condition_steps.length>0){let J=await xJ(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${Q} running=true, ran ${J.stepsRun} sub-steps`}return`Condition: ${Q} running=${Y}${!Y?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function SJ($){let Z=$||H$;if(Z.length===0)return"Nenhum workflow configurado.";let Q=Z.map((Y)=>{let J=Y.enabled?"":" [DESATIVADO]",X=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"",K=Y.steps.map((V)=>{let G=V.label||V.target;return V.action==="wait"?`${V.target}s`:G}).join(" -> ");return` ${Y.name}${J}${X} \u2014 ${Y.description}
|
|
595
|
-
${" ".repeat(4)}${K} {${Y.id}}`});return`Workflows (${Z.length}):
|
|
596
|
-
${Q.join(`
|
|
597
|
-
|
|
598
|
-
`)}`}function wJ($){let Z=$.enabled?"ativo":"desativado",Q=$.tags.length>0?`Tags: ${$.tags.map((J)=>`#${J}`).join(" ")}`:"",Y=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(Q)Y.push(Q);return Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(""),Y.push("Steps:"),$.steps.forEach((J,X)=>{let K=J.label?` (${J.label})`:"",V=J.on_error&&J.on_error!=="continue"?` [on_error: ${J.on_error}]`:"";if(Y.push(` ${X+1}. ${J.action}: ${J.target}${K}${V}`),J.action==="if_app_running"&&J.condition_steps)for(let G of J.condition_steps)Y.push(` \u21B3 ${G.action}: ${G.target}`)}),Y.join(`
|
|
599
|
-
`)}function oq($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
|
|
600
|
-
`)}function hZ(){return uq().slice(0,8)}Z$();d$();var _$=new Map,pZ=null;function yJ($){pZ=$}function bJ($,Z=60){if(!A)return"Error: monitor is only available on Windows.";let Q=$.toLowerCase();if(_$.has(Q))return`"${$}" ja esta sendo monitorado.`;let Y=setInterval(()=>kJ(Q),Z*1000);return _$.set(Q,{name:$,interval:Y,lastSeen:!0}),kJ(Q),`Monitorando "${$}" a cada ${Z}s.`}function _J($){let Z=$.toLowerCase(),Q=_$.get(Z);if(!Q)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Q.interval),_$.delete(Z),`Monitor parado: "${$}"`}function vJ(){if(_$.size===0)return"Nenhum processo monitorado.";let $=[..._$.values()].map((Z)=>{let Q=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Q}]`});return`Processos monitorados (${_$.size}):
|
|
601
|
-
${$.join(`
|
|
602
|
-
`)}`}function fJ(){for(let $ of _$.values())clearInterval($.interval);_$.clear()}async function kJ($){let Z=_$.get($);if(!Z)return;let Q=await z0(Z.name,{timeout:1e4});if(Z.lastSeen&&!Q){let Y=`ALERTA: "${Z.name}" parou de rodar!`;H4("Processo parou!",`"${Z.name}" nao esta mais rodando.`,{timeout:1e4}).catch(()=>{}),pZ?.(Y)}else if(!Z.lastSeen&&Q){let Y=`"${Z.name}" voltou a rodar.`;pZ?.(Y)}_$.set($,{...Z,lastSeen:Q})}h1();n();import{writeFileSync as aq}from"fs";import{join as nq}from"path";async function rq(){let $=uZ(process.argv.slice(2));if($.help)dZ(),process.exit(0);if($.version)console.log(`smolerclaw v${Y0()}`),process.exit(0);let Z=N2();if($.model)Z.model=wZ($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Q;try{Q=I5()}catch(O){console.error("smolerclaw:",O instanceof Error?O.message:O),process.exit(1)}let{provider:Y,model:J}=kZ(Z.model),X;if(Y==="openai"||Y==="ollama")X=new yZ(Y,J,Z.maxTokens);else{let O=new BZ(Q.token,Z.model,Z.maxTokens,Z.toolApproval);O.setAuthRefresh(()=>{let j=x5();if(j&&j.token!==Q.token)return Q=j,O.updateApiKey(j.token),!0;return!1}),X=O}let K=new NZ(Z.dataDir),V=$.session||K.getLastSession()||"default";if(V!=="default")K.switchTo(V);let G=yY(Z.skillsDir),H=OZ(Z.systemPrompt,G,Z.language),z=!$.noTools;WY();let B=O6(nq(Z.dataDir,"..")),W=C6(B);if(W.length>0)HY(W),p.push(...N6(W));let N=!process.stdin.isTTY;if($.print||N)await iq(X,K,H,z,$.prompt,N),process.exit(0);await tq(X,K,Z,Q,G,H,z,W,$.prompt)}async function iq($,Z,Q,Y,J,X){let K=J||"";if(X){let z=await sq();K=K?`${K}
|
|
603
|
-
|
|
604
|
-
${z}`:z}if(!K.trim())console.error("smolerclaw: no input provided"),process.exit(1);let V={role:"user",content:K.trim(),timestamp:Date.now()};Z.addMessage(V);let G="";for await(let z of $.chat(Z.messages,Q,Y))if(z.type==="text")process.stdout.write(z.text),G+=z.text;else if(z.type==="error")console.error(`
|
|
605
|
-
smolerclaw error: ${z.error}`);if(G&&!G.endsWith(`
|
|
606
|
-
`))process.stdout.write(`
|
|
607
|
-
`);let H={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(H)}async function sq(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}async function tq($,Z,Q,Y,J,X,K,V,G){let H=new SZ(Q.model),z=new xZ(Q.model,Z.session.name,F2(Y),Q.dataDir),B="default",W=x3(),N=W?`${X}
|
|
608
|
-
|
|
609
|
-
${W}`:X;U2(Q.dataDir,A5().replace(/[/\\]config\.json$/,"")),M3(Q.dataDir),g6(Q.dataDir),P3(Q.dataDir),P6(Q.dataDir),UY(Z),Q3(Q.dataDir),K3(Q.dataDir),MJ((y)=>z.showSystem(`
|
|
610
|
-
*** ${y} ***
|
|
611
|
-
`)),TJ(Q.dataDir),L9(Q.dataDir),_3(Q.dataDir),u3(Q.dataDir),t3(Q.dataDir),MQ(Q.dataDir),_Q(Q.dataDir,(y)=>{z.showSystem(`
|
|
612
|
-
*** Meta-Insight: ${y.title} ***
|
|
613
|
-
${y.recommendation}
|
|
614
|
-
`)}),yJ((y)=>z.showSystem(`
|
|
615
|
-
*** ${y} ***
|
|
616
|
-
`)),a6(Q.dataDir,(y)=>z.showSystem(`
|
|
617
|
-
*** ${y} ***
|
|
618
|
-
`)),w6(Q.dataDir,(y)=>{z.showSystem(`
|
|
619
|
-
*** LEMBRETE: ${y.title} ***
|
|
620
|
-
`)});let O=null;try{O=await W5(Q.dataDir),z.setTimeContext(O)}catch{z.setPersonaMode("productivity")}if(Q.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(y,v,a)=>{if(y==="edit_file"&&v.old_text&&v.new_text){let C=DY(String(v.old_text),String(v.new_text));for(let F of C)z.showSystem(F)}let R=jY(y,v),q=await z.promptApproval(R);if(z._approveAllRequested)$.setAutoApproveAll?.(!0),z._approveAllRequested=!1;return q});for(let y of Z.messages)if(y.role==="user")z.addUserMessage(y.content);else z.addAssistantMessage(y.content);let j=null;async function P(y){if(y.startsWith("/")){await _(y);return}if(Q.maxSessionCost>0){let g=H.totals.costCents;if(g>=Q.maxSessionCost){z.showError(`Budget exceeded (~$${(g/100).toFixed(4)} / $${(Q.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(g>=Q.maxSessionCost*0.8)z.showSystem(`Budget: ${Math.round(g/Q.maxSessionCost*100)}% used`)}let{text:v,images:a}=XJ(y),{text:R,files:q}=KJ(v),C=R;if(q.length>0)C=`${q.map((Z0)=>`<file name="${Z0.name}" path="${Z0.path}" size="${Z0.size}">
|
|
621
|
-
${Z0.content}
|
|
622
|
-
</file>`).join(`
|
|
623
|
-
|
|
624
|
-
`)}
|
|
625
|
-
|
|
626
|
-
${R}`;let F={role:"user",content:C,images:a.length>0?a.map((g)=>({mediaType:g.mediaType,base64:g.base64})):void 0,files:q.length>0?q:void 0,timestamp:Date.now()};Z.addMessage(F);let L=[];if(a.length>0)L.push(`${a.length} image${a.length>1?"s":""}`);if(q.length>0)L.push(`${q.length} file${q.length>1?"s":""}`);let x=L.length>0?`${R} (${L.join(", ")})`:R;z.addUserMessage(x),z.disableInput(),z.startStream();let w="",u=[],s={},w$=0,h=0;j=new AbortController;try{for await(let g of $.chat(Z.messages,N,K)){if(j.signal.aborted)break;switch(g.type){case"text":z.appendStream(g.text),w+=g.text;break;case"tool_call":z.flushStream(),z.showToolCall(g.name,g.input),s=g.input;break;case"tool_result":z.showToolResult(g.name,g.result),u.push({id:g.id,name:g.name,input:s,result:g.result}),s={},z.resetStreamBuffer();break;case"tool_blocked":z.showError(g.reason);break;case"usage":w$+=g.inputTokens,h+=g.outputTokens;break;case"error":z.showError(g.error);break;case"done":break}}}catch(g){if(!j.signal.aborted)z.showError(g instanceof Error?g.message:String(g))}j=null,z.endStream();let k$={inputTokens:w$,outputTokens:h},p$=H.add(k$);if(w$>0||h>0)z.showUsage(H.formatUsage(k$)),z.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let c$={role:"assistant",content:w,toolCalls:u.length>0?u:void 0,usage:w$>0?{inputTokens:w$,outputTokens:h,costCents:p$.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(c$),Z.trimHistory(Q.maxHistory),z.enableInput()}async function _(y){let v=y.slice(1).split(" "),a=v[0].toLowerCase(),R=v.slice(1);switch(a){case"exit":case"quit":case"sair":case"q":q$();break;case"clear":case"limpar":Z.clear(),z.clearMessages(),z.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let q=R[0]||`s-${Date.now()}`;Z.switchTo(q),z.clearMessages(),z.updateSession(q),z.showSystem(`New session: ${q}`);break}case"load":case"carregar":{let q=R[0];if(!q){z.showError("Usage: /load <name>");break}Z.switchTo(q),z.clearMessages();for(let C of Z.messages)if(C.role==="user")z.addUserMessage(C.content);else z.addAssistantMessage(C.content);z.updateSession(q),z.showSystem(`Loaded: ${q}`);break}case"sessions":case"sessoes":case"ls":{let q=Z.list().map((L)=>{let x=Z.getInfo(L);return{name:L,messageCount:x?.messageCount??0,updated:x?.updated??0,isCurrent:L===Z.session.name,isArchived:!1}}),C=Z.listArchived().map((L)=>{let x=Z.getArchivedInfo(L);return{name:L,messageCount:x?.messageCount??0,updated:x?.updated??0,isCurrent:!1,isArchived:!0}}),F=await z.promptSessionPicker([...q,...C]);if(F)switch(F.action){case"load":{let L=F.name;if(C.some((w)=>w.name===L))Z.unarchive(L);Z.switchTo(L),z.clearMessages();for(let w of Z.messages)if(w.role==="user")z.addUserMessage(w.content);else z.addAssistantMessage(w.content);z.updateSession(L),z.showSystem(`Loaded: ${L}`);break}case"delete":{let L=F.name;if(F.isArchived?Z.deleteArchived(L):Z.delete(L))z.showSystem(`Deleted: ${L}`);else z.showError(`Not found: ${L}`);break}case"archive":if(Z.archive(F.name))z.showSystem(`Archived: ${F.name}`);else z.showError(`Failed to archive: ${F.name}`);break;case"unarchive":if(Z.unarchive(F.name))z.showSystem(`Restored: ${F.name}`);else z.showError(`Not found in archive: ${F.name}`);break}break}case"delete":case"deletar":case"rm":{let q=R[0];if(!q){z.showError("Usage: /delete <name>");break}if(Z.delete(q))z.showSystem(`Deleted: ${q}`);else z.showError(`Session not found: ${q}`);break}case"archive":case"arquivar":{let q=R[0];if(!q){z.showError("Uso: /archive <nome> ou /archive all");break}if(q==="all"||q==="todas"){let C=Z.archiveAll();if(C.length>0)z.showSystem(`Arquivadas ${C.length} sessoes: ${C.join(", ")}`);else z.showSystem("Nenhuma sessao para arquivar (apenas a sessao atual esta ativa).")}else if(Z.archive(q))z.showSystem(`Sessao arquivada: "${q}"`);else z.showError(`Falha ao arquivar "${q}" (nao encontrada ou e a sessao atual).`);break}case"unarchive":case"desarquivar":case"restore":case"restaurar":{let q=R[0];if(!q){z.showError("Uso: /unarchive <nome>");break}if(Z.unarchive(q))z.showSystem(`Sessao restaurada: "${q}"`);else z.showError(`Sessao arquivada nao encontrada: "${q}"`);break}case"archived":case"arquivadas":{let q=Z.listArchived();if(q.length===0){z.showSystem("Nenhuma sessao arquivada.");break}let C=q.map((F)=>{let L=Z.getArchivedInfo(F),x=L?eq(L.updated):"",w=L?`${L.messageCount} msgs`:"";return` ${F.padEnd(20)} ${w.padEnd(10)} ${x}`});z.showSystem(`Sessoes arquivadas (${q.length}):
|
|
627
|
-
${C.join(`
|
|
628
|
-
`)}`);break}case"model":case"modelo":{let q=R[0];if(!q){z.showSystem(cY(Q.model)+`
|
|
620
|
+
- Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function Az($){return Tz[$.toLowerCase()]||null}function Iz($){let Z=["Personas:"];for(let[Y,Q]of Object.entries(Tz)){let J=Y===$?" *":" ";Z.push(`${J} ${Y.padEnd(12)} ${Q.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
|
|
621
|
+
`)}p();async function Sz($){try{let Z=L?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:kZ?["pbcopy"]:["xclip","-selection","clipboard"],Y=Bun.spawn(Z,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});return Y.stdin.write($),Y.stdin.end(),await Y.exited===0}catch{return!1}}f();i0();import{writeFileSync as TH}from"fs";async function wz($,Z){let Y=$.slice(1).split(" "),Q=Y[0].toLowerCase(),J=Y.slice(1);switch(Q){case"exit":case"quit":case"sair":case"q":Z.cleanup();break;case"clear":case"limpar":Z.sessions.clear(),Z.tui.clearMessages(),Z.tui.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let z=J[0]||`s-${Date.now()}`;Z.sessions.switchTo(z),Z.tui.clearMessages(),Z.tui.updateSession(z),Z.tui.showSystem(`New session: ${z}`);break}case"load":case"carregar":{let z=J[0];if(!z){Z.tui.showError("Usage: /load <name>");break}Z.sessions.switchTo(z),Z.tui.clearMessages();for(let K of Z.sessions.messages)if(K.role==="user")Z.tui.addUserMessage(K.content);else Z.tui.addAssistantMessage(K.content);Z.tui.updateSession(z),Z.tui.showSystem(`Loaded: ${z}`);break}case"sessions":case"sessoes":case"ls":{let z=Z.sessions.list().map((V)=>{let G=Z.sessions.getInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:V===Z.sessions.session.name,isArchived:!1}}),K=Z.sessions.listArchived().map((V)=>{let G=Z.sessions.getArchivedInfo(V);return{name:V,messageCount:G?.messageCount??0,updated:G?.updated??0,isCurrent:!1,isArchived:!0}}),X=await Z.tui.promptSessionPicker([...z,...K]);if(X)switch(X.action){case"load":{let V=X.name;if(K.some((q)=>q.name===V))Z.sessions.unarchive(V);Z.sessions.switchTo(V),Z.tui.clearMessages();for(let q of Z.sessions.messages)if(q.role==="user")Z.tui.addUserMessage(q.content);else Z.tui.addAssistantMessage(q.content);Z.tui.updateSession(V),Z.tui.showSystem(`Loaded: ${V}`);break}case"delete":{let V=X.name;if(X.isArchived?Z.sessions.deleteArchived(V):Z.sessions.delete(V))Z.tui.showSystem(`Deleted: ${V}`);else Z.tui.showError(`Not found: ${V}`);break}case"archive":if(Z.sessions.archive(X.name))Z.tui.showSystem(`Archived: ${X.name}`);else Z.tui.showError(`Failed to archive: ${X.name}`);break;case"unarchive":if(Z.sessions.unarchive(X.name))Z.tui.showSystem(`Restored: ${X.name}`);else Z.tui.showError(`Not found in archive: ${X.name}`);break}break}case"delete":case"deletar":case"rm":{let z=J[0];if(!z){Z.tui.showError("Usage: /delete <name>");break}if(Z.sessions.delete(z))Z.tui.showSystem(`Deleted: ${z}`);else Z.tui.showError(`Session not found: ${z}`);break}case"archive":case"arquivar":{let z=J[0];if(!z){Z.tui.showError("Uso: /archive <nome> ou /archive all");break}if(z==="all"||z==="todas"){let K=Z.sessions.archiveAll();if(K.length>0)Z.tui.showSystem(`Arquivadas ${K.length} sessoes: ${K.join(", ")}`);else Z.tui.showSystem("Nenhuma sessao para arquivar (apenas a sessao atual esta ativa).")}else if(Z.sessions.archive(z))Z.tui.showSystem(`Sessao arquivada: "${z}"`);else Z.tui.showError(`Falha ao arquivar "${z}" (nao encontrada ou e a sessao atual).`);break}case"unarchive":case"desarquivar":case"restore":case"restaurar":{let z=J[0];if(!z){Z.tui.showError("Uso: /unarchive <nome>");break}if(Z.sessions.unarchive(z))Z.tui.showSystem(`Sessao restaurada: "${z}"`);else Z.tui.showError(`Sessao arquivada nao encontrada: "${z}"`);break}case"archived":case"arquivadas":{let z=Z.sessions.listArchived();if(z.length===0){Z.tui.showSystem("Nenhuma sessao arquivada.");break}let K=z.map((X)=>{let V=Z.sessions.getArchivedInfo(X),G=V?AH(V.updated):"",q=V?`${V.messageCount} msgs`:"";return` ${X.padEnd(20)} ${q.padEnd(10)} ${G}`});Z.tui.showSystem(`Sessoes arquivadas (${z.length}):
|
|
622
|
+
${K.join(`
|
|
623
|
+
`)}`);break}case"model":case"modelo":{let z=J[0];if(!z){Z.tui.showSystem(aZ(Z.config.model)+`
|
|
629
624
|
|
|
630
|
-
`+
|
|
631
|
-
Expires: ${new Date(
|
|
632
|
-
`));break;case"commit":case"commitar":{if(!await
|
|
633
|
-
`+
|
|
625
|
+
`+BJ());break}let{provider:K,model:X}=A5(z),V=K==="anthropic"?F4(X):X;if(Z.config.model=K==="anthropic"?V:`${K}:${V}`,M4(Z.config),K==="anthropic")Z.claude.setModel(V);else Z.tui.showSystem(`Note: ${K} provider selected. Restart smolerclaw for full provider switch.`);Z.tracker.setModel(V),Z.tui.updateModel(Z.config.model),Z.tui.showSystem(`Model -> ${Z.config.model}`);break}case"skills":case"habilidades":{Z.tui.showSystem(PJ(Z.skills));break}case"auth":Z.tui.showSystem(`Auth: subscription (${Z.auth.auth.subscriptionType})
|
|
626
|
+
Expires: ${new Date(Z.auth.auth.expiresAt).toLocaleString()}`);break;case"refresh":case"renovar":{Z.tui.showSystem("Renovando sessao Claude...");try{let z=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>z.kill(),15000);await z.exited,clearTimeout(K);let X=N4();if(X){if(Z.auth.auth=X,"updateToken"in Z.claude)Z.claude.updateToken(X.token);Z.tui.showSystem(`Sessao renovada. Expira: ${new Date(X.expiresAt).toLocaleString()}`)}else Z.tui.showSystem("claude executado, mas credenciais nao atualizaram. Tente novamente.")}catch(z){Z.tui.showError(`Falha ao renovar: ${z instanceof Error?z.message:String(z)}`)}break}case"config":Z.tui.showSystem(`Config: ${C4()}`);break;case"export":case"exportar":{let z=new Date().toISOString().split("T")[0],K=J[0]||`smolerclaw-${Z.sessions.session.name}-${z}.md`;try{let X=Rz(Z.sessions.session);TH(K,X),Z.tui.showSystem(`Exported to: ${K}`)}catch(X){Z.tui.showError(`Export failed: ${X instanceof Error?X.message:X}`)}break}case"cost":case"custo":Z.tui.showSystem(`Session: ${Z.tracker.formatSession()}`);break;case"retry":case"repetir":{let z=[...Z.sessions.messages].reverse().find((G)=>G.role==="user");if(!z){Z.tui.showError("No previous message to retry.");break}let K=Z.sessions.messages,X=0;if(K.length>0&&K[K.length-1].role==="assistant")X++;if(K.length>X&&K[K.length-1-X].role==="user")X++;if(X>0)Z.sessions.popMessages(X);Z.tui.showSystem("Retrying...");let V=z.images?.length?z.content:z.content;await Z.handleSubmit(V);break}case"help":case"ajuda":case"?":Z.tui.showSystem(["Comandos / Commands (en | pt):"," /help /ajuda Mostrar ajuda"," /clear /limpar Limpar conversa"," /new /novo Nova sessao"," /load /carregar Carregar sessao"," /sessions /sessoes Listar sessoes"," /delete /deletar Deletar sessao"," /model /modelo Ver/trocar modelo"," /persona /modo Trocar modo (business, coder...)"," /export /exportar Exportar para markdown"," /copy /copiar Copiar ultima resposta"," /cost /custo Ver uso de tokens"," /retry /repetir Repetir ultima msg"," /undo /desfazer Desfazer alteracao"," /search /buscar Buscar na conversa"," /lang /idioma Definir idioma"," /commit /commitar Git commit com IA"," /exit /sair Sair","","Negocios / Business:"," /briefing /resumo Briefing diario"," /news /noticias Radar de noticias"," /open /abrir Abrir app Windows"," /apps /programas Apps em execucao"," /sysinfo /sistema Recursos do sistema"," /calendar /agenda Calendario Outlook","","Pessoas / People:"," /addperson /novapessoa Cadastrar pessoa"," /people /pessoas Listar todas"," /team /equipe Listar equipe"," /family /familia Listar familia"," /person /pessoa Detalhes de alguem"," /delegate /delegar Delegar tarefa"," /delegations /delegacoes Listar delegacoes"," /followups Follow-ups pendentes"," /dashboard /painel Painel geral","","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(`
|
|
627
|
+
`));break;case"commit":case"commitar":{if(!await Pz()){Z.tui.showError("Not a git repository.");break}let z=await Lz();if(z==="(clean)"){Z.tui.showSystem("Nothing to commit \u2014 working tree clean.");break}Z.tui.showSystem(`Changes:
|
|
628
|
+
`+z),Z.tui.disableInput();try{let X=`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.
|
|
634
629
|
|
|
635
630
|
Diff:
|
|
636
|
-
${(await
|
|
637
|
-
${
|
|
638
|
-
`)}`:`No matches for "${
|
|
639
|
-
Falhas: ${
|
|
631
|
+
${(await Ez()).slice(0,8000)}`;Z.tui.startStream();let V="";for await(let q of Z.claude.chat([{role:"user",content:X,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(q.type==="text")V+=q.text,Z.tui.appendStream(q.text);else if(q.type==="error")Z.tui.showError(q.error);if(Z.tui.endStream(),V=V.trim().replace(/^["']|["']$/g,""),!V){Z.tui.showError("Failed to generate commit message. Aborting.");break}await jz();let G=await Dz(V);if(G.ok)Z.tui.showSystem(`Committed: ${V}`);else Z.tui.showError(`Commit failed: ${G.output}`)}catch(K){Z.tui.showError(`Commit error: ${K instanceof Error?K.message:String(K)}`)}Z.tui.enableInput();break}case"persona":case"modo":{let z=J[0];if(!z){Z.tui.showSystem(Iz(Z.currentPersona));break}let K=Az(z);if(!K){Z.tui.showError(`Unknown persona: ${z}. Try /persona to see options.`);break}if(Z.setCurrentPersona(K.name),K.systemPrompt)Z.setActiveSystemPrompt(k5(K.systemPrompt,Z.skills,Z.config.language));else Z.setActiveSystemPrompt(Z.systemPrompt);Z.tui.showSystem(`Persona -> ${K.name}: ${K.description}`);break}case"copy":case"copiar":{let z=[...Z.sessions.messages].reverse().find((X)=>X.role==="assistant");if(!z){Z.tui.showError("No assistant message to copy.");break}if(await Sz(z.content))Z.tui.showSystem("Copied last response to clipboard.");else Z.tui.showError("Failed to copy. Is xclip/pbcopy available?");break}case"ask":case"perguntar":{let z=J.join(" ");if(!z){Z.tui.showError("Usage: /ask <question>");break}Z.tui.addUserMessage(`(ephemeral) ${z}`),Z.tui.disableInput(),Z.tui.startStream();let K="";for await(let X of Z.claude.chat([{role:"user",content:z,timestamp:Date.now()}],Z.activeSystemPrompt,!1))if(X.type==="text")K+=X.text,Z.tui.appendStream(X.text);else if(X.type==="error")Z.tui.showError(X.error);else if(X.type==="usage")Z.tui.showUsage(`${X.inputTokens} in / ${X.outputTokens} out (ephemeral)`);Z.tui.endStream(),Z.tui.enableInput();break}case"fork":{let z=J[0]||`fork-${Date.now()}`;Z.sessions.fork(z),Z.tui.updateSession(z),Z.tui.showSystem(`Forked session -> ${z} (${Z.sessions.messages.length} messages copied)`);break}case"plugins":{Z.tui.showSystem(vQ(Z.plugins));break}case"budget":case"orcamento":{let z=J[0];if(!z){let X=Z.config.maxSessionCost,V=Z.tracker.totals.costCents;if(X===0)Z.tui.showSystem(`Budget: unlimited (spent ~$${(V/100).toFixed(4)})`);else{let G=Math.round(V/X*100);Z.tui.showSystem(`Budget: ~$${(V/100).toFixed(4)} / $${(X/100).toFixed(4)} (${G}%)`)}break}let K=Number(z);if(isNaN(K)||K<0){Z.tui.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Z.config.maxSessionCost=K,M4(Z.config),Z.tui.showSystem(K===0?"Budget: unlimited":`Budget set: $${(K/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!P1.peek()){Z.tui.showError("Nothing to undo.");break}let K=P1.undo();if(K)Z.tui.showSystem(K);break}case"search":case"buscar":{let z=J.join(" ").toLowerCase();if(!z){Z.tui.showError("Usage: /search <text>");break}let K=[];for(let X of Z.sessions.messages)if(X.content.toLowerCase().includes(z)){let V=X.content.slice(0,100).replace(/\n/g," "),G=new Date(X.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});K.push(` [${X.role} ${G}] ${V}${X.content.length>100?"...":""}`)}Z.tui.showSystem(K.length>0?`Found ${K.length} match${K.length>1?"es":""}:
|
|
632
|
+
${K.join(`
|
|
633
|
+
`)}`:`No matches for "${z}".`);break}case"lang":case"language":case"idioma":{let z=J[0];if(!z){Z.tui.showSystem(`Language: ${Z.config.language} (auto = match user's language)`);break}Z.config.language=z,M4(Z.config),Z.tui.showSystem(`Language -> ${z}`);break}case"briefing":case"resumo":{Z.tui.showSystem("Carregando briefing..."),Z.tui.disableInput();try{let z=await cJ(Z.config.dataDir);Z.tui.showSystem(z);let K=await a8(Z.config.dataDir);Z.tui.setTimeContext(K),Z.setTimeContext(K)}catch(z){Z.tui.showError(`Briefing falhou: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"news":case"noticias":{let z=J[0];if(z)Z.tui.showSystem(`Buscando noticias (${z})...`);else Z.tui.showSystem("Buscando noticias...");Z.tui.disableInput();try{let{items:K,errors:X}=await b2(z?[z]:void 0);if(K.length===0){Z.tui.showSystem(X.length>0?`Nenhuma noticia encontrada.
|
|
634
|
+
Falhas: ${X.join(", ")}`:"Nenhuma noticia encontrada."),Z.tui.enableInput();break}let V=K.map((q)=>({title:q.title,link:q.link,source:q.source,category:q.category,time:q.pubDate?q.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),G=await Z.tui.promptNewsPicker(V);if(G){if(G.action==="open"){let{openUrl:q}=await Promise.resolve().then(() => (i0(),VQ));q(G.link),Z.tui.showSystem(`Abrindo: ${G.link}`)}else if(G.action==="read"){Z.tui.showSystem("Buscando conteudo...");let q=await r6(G.link);if(typeof q==="string")Z.tui.showError(q);else{let W=`Por favor, resuma esta noticia de forma objetiva e destaque os pontos principais:
|
|
640
635
|
|
|
641
|
-
${`Noticia: ${
|
|
642
|
-
Fonte: ${
|
|
636
|
+
${`Noticia: ${q.title}
|
|
637
|
+
Fonte: ${G.link}
|
|
643
638
|
|
|
644
|
-
${
|
|
645
|
-
Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let
|
|
646
|
-
Uso: /open <app> ou /open <app> <arquivo>`);break}let
|
|
639
|
+
${q.content}`}`;Z.tui.enableInput(),Z.handleSubmit(W);return}}}}catch(K){Z.tui.showError(`Falha ao buscar noticias: ${K instanceof Error?K.message:String(K)}`)}Z.tui.enableInput();break}case"feeds":case"fontes":{Z.tui.showSystem(Y7());break}case"addfeed":case"novafonte":{if(J.length<3){Z.tui.showError(`Uso: /addfeed <nome> <url> <categoria>
|
|
640
|
+
Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let z=J[0],K=J[1],X=J[2],V=t4(z,K,X);if(typeof V==="string")Z.tui.showError(V);else Z.tui.showSystem(`Fonte adicionada: ${V.name} (${V.category}) \u2014 ${V.url}`);break}case"rmfeed":case"rmfonte":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /rmfeed <nome ou url>");break}if(e4(z))Z.tui.showSystem(`Fonte removida: ${z}`);else Z.tui.showError(`Fonte custom nao encontrada: "${z}". Para desativar uma built-in, use /disablefeed.`);break}case"disablefeed":case"desativarfonte":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /disablefeed <nome ou url>");break}if($7(z))Z.tui.showSystem(`Fonte desativada: ${z}`);else Z.tui.showError(`Fonte built-in nao encontrada ou ja desativada: "${z}"`);break}case"enablefeed":case"ativarfonte":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /enablefeed <nome ou url>");break}if(Z7(z))Z.tui.showSystem(`Fonte reativada: ${z}`);else Z.tui.showError(`Fonte built-in nao encontrada ou nao esta desativada: "${z}"`);break}case"open":case"abrir":{if(!J.join(" ")){Z.tui.showSystem(`Apps disponiveis: ${L9().join(", ")}
|
|
641
|
+
Uso: /open <app> ou /open <app> <arquivo>`);break}let K=J.length>1?J.slice(1).join(" "):void 0,X=await d0(J[0],K);Z.tui.showSystem(X);break}case"openfile":case"abrirarquivo":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /openfile <caminho>");break}let K=await f8(z);Z.tui.showSystem(K);break}case"openurl":{let z=J[0];if(!z){Z.tui.showError("Uso: /openurl <url>");break}let K=await c0(z);Z.tui.showSystem(K);break}case"apps":case"programas":{Z.tui.disableInput();try{let z=await v8();Z.tui.showSystem(z)}catch(z){Z.tui.showError(`Apps: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"sysinfo":case"sistema":{Z.tui.disableInput();try{let z=await l0();Z.tui.showSystem(z)}catch(z){Z.tui.showError(`Sysinfo: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"calendar":case"calendario":case"agenda":case"cal":{Z.tui.disableInput();try{let z=await o0(),K=await k$();Z.tui.showSystem(`${z}
|
|
647
642
|
|
|
648
643
|
--- Agenda ---
|
|
649
|
-
${
|
|
644
|
+
${K}`)}catch(z){Z.tui.showError(`Calendar: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"monitor":case"vigiar":{let z=J[0]?.toLowerCase();if(!z||z==="list"||z==="listar")Z.tui.showSystem(Qz());else if(z==="stop"||z==="parar"){let K=J[1];if(!K){Z.tui.showError("Uso: /monitor stop <processo>");break}Z.tui.showSystem(Yz(K))}else{let K=parseInt(J[1])||60;Z.tui.showSystem(Zz(z,K))}break}case"workflow":case"fluxo":{let z=J[0]?.toLowerCase();if(!z||z==="list"||z==="listar"){let K=J[1];Z.tui.showSystem(Nz(Bz(K)))}else if(z==="run"||z==="rodar"){let K=J[1];if(!K){Z.tui.showError("Uso: /workflow run <nome>");break}Z.tui.disableInput();try{let X=await MZ(K,(V)=>Z.tui.showSystem(V));Z.tui.showSystem(X)}catch(X){Z.tui.showError(`Workflow: ${X instanceof Error?X.message:String(X)}`)}Z.tui.enableInput()}else if(z==="info"||z==="detalhe"){let K=J[1];if(!K){Z.tui.showError("Uso: /workflow info <nome>");break}let X=s8(K);if(X)Z.tui.showSystem(Oz(X));else Z.tui.showError(`Workflow nao encontrado: ${K}`)}else if(z==="delete"||z==="deletar"){let K=J[1];if(!K){Z.tui.showError("Uso: /workflow delete <nome>");break}if(Mz(K))Z.tui.showSystem(`Workflow removido: ${K}`);else Z.tui.showError(`Workflow nao encontrado: ${K}`)}else if(z==="enable"||z==="ativar"){let K=J[1];if(!K){Z.tui.showError("Uso: /workflow enable <nome>");break}let X=BZ(K,{enabled:!0});if(X)Z.tui.showSystem(`Workflow ativado: ${X.name}`);else Z.tui.showError(`Workflow nao encontrado: ${K}`)}else if(z==="disable"||z==="desativar"){let K=J[1];if(!K){Z.tui.showError("Uso: /workflow disable <nome>");break}let X=BZ(K,{enabled:!1});if(X)Z.tui.showSystem(`Workflow desativado: ${X.name}`);else Z.tui.showError(`Workflow nao encontrado: ${K}`)}else{Z.tui.disableInput();try{let K=await MZ(z,(X)=>Z.tui.showSystem(X));Z.tui.showSystem(K)}catch(K){Z.tui.showError(`Workflow: ${K instanceof Error?K.message:String(K)}`)}Z.tui.enableInput()}break}case"pomodoro":case"foco":{let z=J[0]?.toLowerCase();if(z==="stop"||z==="parar")Z.tui.showSystem(aJ());else if(z==="status")Z.tui.showSystem(qZ());else if(!z)Z.tui.showSystem(qZ());else{let K=J.join(" "),X=25,V=5;Z.tui.showSystem(nJ(K,25,5))}break}case"agendar":case"schedule":{let z=J[0]?.toLowerCase();if(!z||z==="list"||z==="listar"){let M=I8(J[1]==="all"||J[1]==="todos");Z.tui.showSystem(S8(M));break}if(z==="remove"||z==="remover"||z==="delete"){if(!J[1]){Z.tui.showSystem("Uso: /agendar remove <id ou nome>");break}let M=await B7(J[1]);Z.tui.showSystem(M?"Agendamento removido.":"Agendamento nao encontrado.");break}if(z==="enable"||z==="ativar"){if(!J[1]){Z.tui.showSystem("Uso: /agendar ativar <id ou nome>");break}let M=await M7(J[1]);Z.tui.showSystem(M?`Agendamento "${M.name}" ativado.`:"Agendamento nao encontrado.");break}if(z==="disable"||z==="desativar"){if(!J[1]){Z.tui.showSystem("Uso: /agendar desativar <id ou nome>");break}let M=await C7(J[1]);Z.tui.showSystem(M?`Agendamento "${M.name}" desativado.`:"Agendamento nao encontrado.");break}if(z==="run"||z==="executar"){if(!J[1]){Z.tui.showSystem("Uso: /agendar executar <id ou nome>");break}Z.tui.showSystem(await N7(J[1]));break}if(z==="clear"||z==="limpar"){Z.tui.showSystem(await E3());break}if(z==="detail"||z==="detalhe"||z==="info"){if(!J[1]){Z.tui.showSystem("Uso: /agendar info <id ou nome>");break}let M=O3(J[1]);Z.tui.showSystem(M?h2(M):"Agendamento nao encontrado.");break}let K=J.join(" "),X=K.match(/"([^"]+)"/g);if(!X||X.length<2){Z.tui.showSystem(`Uso: /agendar "<mensagem>" "<horario>" [once|daily|weekly] [data/dia]
|
|
650
645
|
Exemplos:
|
|
651
646
|
/agendar "Reuniao" "14:00"
|
|
652
647
|
/agendar "Standup" "09:00" daily
|
|
653
648
|
/agendar "Review" "15:00" weekly sexta
|
|
654
|
-
/agendar "Dentista" "10:00" once 15/04/2026`);break}let
|
|
655
|
-
`).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(
|
|
656
|
-
|
|
657
|
-
`+
|
|
658
|
-
Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let
|
|
659
|
-
Use | para separar assunto do corpo.`);break}let
|
|
660
|
-
Ou peca a IA: "salva esse material sobre..."`);break}let
|
|
661
|
-
Chunks: ${
|
|
662
|
-
Fontes: ${
|
|
663
|
-
Ultima indexacao: ${
|
|
664
|
-
${
|
|
665
|
-
`));break}case"projeto":case"project":{let
|
|
666
|
-
Ex: /addperson equipe Joao dev frontend`);break}let
|
|
667
|
-
Ex: /delegate Joao revisar relatorio`);break}let
|
|
649
|
+
/agendar "Dentista" "10:00" once 15/04/2026`);break}let V=X[0].slice(1,-1),G=X[1].slice(1,-1),q=O7(G);if(!q){Z.tui.showSystem(`Horario invalido: "${G}". Use formato HH:MM ou HHh.`);break}let U=K.replace(/"[^"]+"/g,"").trim().split(/\s+/).filter(Boolean),W="once",B;for(let M of U){let O=M.toLowerCase();if(O==="daily"||O==="diario")W="daily";else if(O==="weekly"||O==="semanal")W="weekly";else if(O==="once"||O==="uma-vez")W="once";else if(W==="weekly"){let R=R7(M);if(R)B=R}else if(W==="once"){let R=F7(M);if(R)B=R}}if(W==="once"&&!B){let M=new Date,[O,R]=q.split(":").map(Number),P=new Date(M);if(P.setHours(O,R,0,0),P<=M)P.setDate(P.getDate()+1);B=[String(P.getMonth()+1).padStart(2,"0"),String(P.getDate()).padStart(2,"0"),String(P.getFullYear())].join("/")}try{let M=await W7(V,W,q,"toast",V,B);Z.tui.showSystem(`Tarefa "${M.name}" agendada para ${h2(M).split(`
|
|
650
|
+
`).slice(2,5).join(", ").replace(/\n/g,"")}`)}catch(M){Z.tui.showError(`Erro ao agendar: ${M instanceof Error?M.message:String(M)}`)}break}case"agendamentos":case"schedules":{let z=I8(J[0]==="all"||J[0]==="todos");Z.tui.showSystem(S8(z));break}case"entrada":case"income":{let z=parseFloat(J[0]);if(isNaN(z)||J.length<3){Z.tui.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let K=w8("entrada",z,J[1],J.slice(2).join(" "));Z.tui.showSystem(`+ R$ ${K.amount.toFixed(2)} (${K.category}) \u2014 ${K.description}`);break}case"saida":case"expense":{let z=parseFloat(J[0]);if(isNaN(z)||J.length<3){Z.tui.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let K=w8("saida",z,J[1],J.slice(2).join(" "));Z.tui.showSystem(`- R$ ${K.amount.toFixed(2)} (${K.category}) \u2014 ${K.description}`);break}case"finance":case"financas":case"balanco":{let z=J[0];if(z==="recent"||z==="recentes")Z.tui.showSystem(m2());else Z.tui.showSystem(L7()+`
|
|
651
|
+
|
|
652
|
+
`+m2(5));break}case"decisions":case"decisoes":{let z=J.join(" ");if(z){let K=h0(z);Z.tui.showSystem(M1(K))}else Z.tui.showSystem(M1(j7()));break}case"investigar":case"investigate":case"investigacoes":{let z=J.join(" ");if(z){let{searchInvestigations:K,formatInvestigationList:X}=await Promise.resolve().then(() => (y8(),t2));Z.tui.showSystem(X(K(z)))}else{let{listInvestigations:K,formatInvestigationList:X}=await Promise.resolve().then(() => (y8(),t2));Z.tui.showSystem(X(K()))}break}case"email":case"rascunho":{if(!J.join(" ")){Z.tui.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
|
|
653
|
+
Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let K=J[0],X=J.slice(1).join(" "),V=X.indexOf("|");if(V===-1){Z.tui.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
|
|
654
|
+
Use | para separar assunto do corpo.`);break}let G=X.slice(0,V).trim(),q=X.slice(V+1).trim();if(!G||!q){Z.tui.showError("Assunto e corpo sao obrigatorios.");break}let U={to:K,subject:G,body:q};Z.tui.showSystem(G7(U)),Z.tui.disableInput();try{let W=await V7(U);Z.tui.showSystem(W)}catch(W){Z.tui.showError(`Email: ${W instanceof Error?W.message:String(W)}`)}Z.tui.enableInput();break}case"memo":case"anotar":case"note":{let z=J.join(" ");if(!z){let V=A8();Z.tui.showSystem(v0(V));break}let K=K7(z),X=K.tags.length>0?` [${K.tags.map((V)=>"#"+V).join(" ")}]`:"";Z.tui.showSystem(`Memo salvo${X} {${K.id}}`);break}case"memos":case"notas":{let z=J.join(" ");if(z){let K=X7(z);Z.tui.showSystem(v0(K))}else{let K=A8();Z.tui.showSystem(v0(K))}break}case"memotags":case"tags":{Z.tui.showSystem(U3());break}case"rmmemo":case"rmnota":{let z=J[0];if(!z){Z.tui.showError("Uso: /rmmemo <id>");break}if(q3(z))Z.tui.showSystem("Memo removido.");else Z.tui.showError(`Memo nao encontrado: ${z}`);break}case"material":case"mat":{let z=J.join(" ");if(!z){let U=O1(10);Z.tui.showSystem(O0(U));break}if(/^[a-z0-9]{6}$/.test(z)){let U=s3(z);if(U)Z.tui.showSystem($Y(U));else Z.tui.showError(`Material nao encontrado: ${z}`);break}let K=z.indexOf("|");if(K===-1){Z.tui.showSystem(`Uso: /material <titulo> | <conteudo>
|
|
655
|
+
Ou peca a IA: "salva esse material sobre..."`);break}let X=z.slice(0,K).trim(),V=z.slice(K+1).trim();if(!X||!V){Z.tui.showError("Titulo e conteudo sao obrigatorios.");break}let G=_7(X,V),q=G.tags.length>0?` [${G.tags.map((U)=>"#"+U).join(" ")}]`:"";Z.tui.showSystem(`Material salvo: "${G.title}" (${G.category})${q} {${G.id}}`);break}case"materials":case"materiais":{let z=J.join(" ");if(z){let K=N1(z);Z.tui.showSystem(O0(K))}else{let K=O1();Z.tui.showSystem(O0(K))}break}case"matcats":case"categorias":{Z.tui.showSystem(ZY());break}case"rmmat":case"rmmaterial":{let z=J[0];if(!z){Z.tui.showError("Uso: /rmmat <id>");break}if(x7(z))Z.tui.showSystem("Material removido.");else Z.tui.showError(`Material nao encontrado: ${z}`);break}case"reflect":case"reflexao":case"aprender":{Z.tui.showSystem("Executando reflexao de uso..."),Z.tui.disableInput();try{let z=await j1();Z.tui.showSystem(z.summary)}catch(z){Z.tui.showError(`Reflexao falhou: ${z instanceof Error?z.message:String(z)}`)}Z.tui.enableInput();break}case"indexar":case"index":case"reindex":{Z.tui.showSystem("Indexando memoria local...");let z=E5();Z.tui.showSystem(`Indexacao concluida: ${z.indexed} fonte(s) indexada(s), ${z.skipped} sem alteracao. Total: ${z.total} chunks.`);break}case"memoria":case"memory":{let z=J.join(" ");if(z){let K=L5(z);Z.tui.showSystem(j5(K))}else{let K=R5(),X=K.builtAt?new Date(K.builtAt).toLocaleString("pt-BR"):"nunca";Z.tui.showSystem(`Memory RAG Index:
|
|
656
|
+
Chunks: ${K.chunks}
|
|
657
|
+
Fontes: ${K.sources}
|
|
658
|
+
Ultima indexacao: ${X}`)}break}case"vault":{let z=J[0]?.toLowerCase();if(!z||z==="status")Z.tui.showSystem(q4(G4()));else if(z==="backup"){Z.tui.showSystem("Realizando backup...");let K=J.slice(1).join(" ")||void 0,X=await e0(K);Z.tui.showSystem(X)}else if(z==="sync"||z==="push"){Z.tui.showSystem("Sincronizando com remote...");let K=await H4();Z.tui.showSystem(K)}else if(z==="init"){let K=await U4();Z.tui.showSystem(K),cZ(30),Z.tui.showSystem("Auto-backup ativado (a cada 30 minutos).")}else Z.tui.showError("Uso: /vault [status|backup|sync|init]");break}case"backup":{Z.tui.showSystem("Realizando backup...");let z=await e0();Z.tui.showSystem(z);break}case"clipboard":case"area":{Z.tui.showSystem("Lendo clipboard...");let z=await t7();switch(z.type){case"text":Z.tui.showSystem(`Clipboard (texto):
|
|
659
|
+
${z.text}`);break;case"image":Z.tui.showSystem(z.text);break;case"empty":Z.tui.showSystem("Clipboard vazio.");break;case"error":Z.tui.showError(z.text);break}break}case"tela":case"screen":{Z.tui.showSystem("Analisando tela...");let z=await e7();Z.tui.showSystem(z);break}case"ps1":{let z=J.join(" ");if(!z.trim()){Z.tui.showError("Uso: /ps1 <script powershell>");break}Z.tui.showSystem("Executando script...");let K=await h8(z),X=[];if(K.stdout.trim())X.push(K.stdout.trim());if(K.stderr.trim())X.push(`stderr: ${K.stderr.trim()}`);X.push(`(exit: ${K.exitCode}, ${K.duration}ms)`),Z.tui.showSystem(X.join(`
|
|
660
|
+
`));break}case"projeto":case"project":{let z=J.join(" ");if(z){let K=h7(z);if(K)E1(K.id),Z.tui.showSystem(c7(K));else if(z==="auto"){let X=i7(process.cwd());if(X)E1(X.id),Z.tui.showSystem(`Projeto detectado: ${c7(X)}`);else Z.tui.showError("Nenhum projeto detectado no diretorio atual.")}else Z.tui.showError(`Projeto nao encontrado: "${z}"`)}else{let K=R0();if(K)Z.tui.showSystem(c7(K));else Z.tui.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{Z.tui.showSystem(d7(R1()));break}case"sessao":case"session":{let z=J[0],K=R0();if(!K){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(z==="start"||z==="iniciar"){let X=J.slice(1).join(" "),V=g7(K.id,X);if(V)Z.tui.showSystem(`Sessao iniciada para "${K.name}" [${V.id}]`)}else if(z==="stop"||z==="parar"){let X=E0(K.id);if(X){let V=m7(X.id,J.slice(1).join(" "));if(V)Z.tui.showSystem(`Sessao encerrada: ${V.durationMinutes} minutos em "${K.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta.")}else{let X=E0(K.id);if(X){let V=Math.round((Date.now()-new Date(X.startedAt).getTime())/60000);Z.tui.showSystem(`Sessao aberta: ${V} minutos em "${K.name}"`)}else Z.tui.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let z=R0();if(!z){Z.tui.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let K=J[0]||"today";Z.tui.showSystem("Gerando relatorio...");let X=await p7(z.id,K,"pt");if(X)Z.tui.showSystem(X.markdown);else Z.tui.showError("Falha ao gerar relatorio.");break}case"oportunidades":case"opportunities":{let z=J[0]||void 0,K=u7(z);Z.tui.showSystem(l7(K));break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let K={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[Q]||J[0],X=I7(K);Z.tui.showSystem(w7(X));break}case"person":case"pessoa":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /person <nome>");break}let K=o$(z);if(!K){Z.tui.showError(`Pessoa nao encontrada: "${z}"`);break}Z.tui.showSystem(k7(K));break}case"addperson":case"addpessoa":case"novapessoa":{let z=J[0];if(!z||!["equipe","familia","contato"].includes(z)){Z.tui.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
|
|
661
|
+
Ex: /addperson equipe Joao dev frontend`);break}let X=J.slice(1).join(" ");if(!X){Z.tui.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[V,...G]=X.split(","),q=G.join(",").trim()||void 0,U=A7(V.trim(),z,q);Z.tui.showSystem(`Adicionado: ${U.name} (${z}) [${U.id}]`);break}case"delegate":case"delegar":{let z=J[0];if(!z||J.length<2){Z.tui.showSystem(`Uso: /delegate <pessoa> <tarefa>
|
|
662
|
+
Ex: /delegate Joao revisar relatorio`);break}let K=J.slice(1).join(" "),X=S7(z,K);if(!X){Z.tui.showError(`Pessoa nao encontrada: "${z}"`);break}Z.tui.showSystem(`Delegado para ${z}: "${K}" [${X.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let z=J[0],K=g0(z);Z.tui.showSystem(y7(K));break}case"followups":{let z=C1();Z.tui.showSystem(b7(z));break}case"dashboard":case"painel":{let z=await CZ(Z.config.dataDir);Z.tui.enterDashboardMode(z),process.stdin.once("data",()=>{if(Z.tui.getViewMode()==="dashboard")Z.tui.enterChatMode()});break}case"chat":{Z.tui.enterChatMode();break}case"task":case"tarefa":{let z=J.join(" ");if(!z){let q=l$();Z.tui.showSystem(f0(q));break}let K=W1(z),X=z.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(!X)X=z;let V=J7(X,K||void 0),G=K?` \u2014 lembrete: ${K.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";Z.tui.showSystem(`Tarefa criada: "${V.title}"${G} [${V.id}]`);break}case"tasks":case"tarefas":{let z=J[0]==="all"||J[0]==="todas",K=l$(z);Z.tui.showSystem(f0(K));break}case"done":case"feito":case"concluido":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /done <id ou parte do titulo>");break}let K=z7(z);if(K)Z.tui.showSystem(`Concluida: "${K.title}"`);else Z.tui.showError(`Tarefa nao encontrada: "${z}"`);break}case"rmtask":case"rmtarefa":{let z=J.join(" ");if(!z){Z.tui.showError("Uso: /rmtask <id ou parte do titulo>");break}if(Q3(z))Z.tui.showSystem("Tarefa removida.");else Z.tui.showError(`Tarefa nao encontrada: "${z}"`);break}default:Z.tui.showError(`Unknown command: /${Q}. Try /help`)}}async function CZ($){let Z=[],Y=new Date().getHours(),Q=Y<12?"BOM DIA":Y<18?"BOA TARDE":"BOA NOITE",J=new Date().toLocaleDateString("pt-BR",{weekday:"long",year:"numeric",month:"long",day:"numeric"}),z=l$(),K=z.filter((U)=>{if(!U.dueAt)return!0;let W=new Date(U.dueAt),B=new Date;return W.toDateString()===B.toDateString()});if(K.length>0||z.length>0){let U=K.slice(0,8).map((W)=>{let B=W.dueAt?new Date(W.dueAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"}):"";return`${B?`[${B}] `:""}${W.title}`});if(z.length>K.length)U.push(`... +${z.length-K.length} outras`);Z.push({id:"tasks",title:`${Q}! Tarefas (${K.length})`,content:U.length>0?U:["Nenhuma tarefa para hoje"]})}let X=C1();if(X.length>0){let U=X.slice(0,6).map((W)=>{let B=W.person.name||"Alguem",M=W.interaction.summary||"Follow-up pendente";return`${B}: ${M.slice(0,30)}...`});Z.push({id:"followups",title:`Follow-ups (${X.length})`,content:U})}let G=g0().filter((U)=>U.status==="atrasado");if(G.length>0){let U=G.slice(0,5).map((W)=>{return`${o$(W.personId)?.name||"Alguem"}: ${W.task.slice(0,25)}...`});Z.push({id:"delegations",title:`Atrasados (${G.length})`,content:U})}try{let W=(await k$()).split(`
|
|
663
|
+
`).filter((B)=>B.trim()).slice(0,6);if(W.length>0)Z.push({id:"calendar",title:"Agenda",content:W})}catch(U){X$.debug("Calendar unavailable for dashboard",{error:U})}let q=o7();if(q){let U=q.split(`
|
|
664
|
+
`).filter((W)=>W.trim()).slice(0,5);Z.push({id:"project",title:"Projetos",content:U})}try{let W=(await M0(["finance","business","tech"],2)).split(`
|
|
665
|
+
`).filter((B)=>B.trim()).slice(0,6);if(W.length>0)Z.push({id:"news",title:"Noticias",content:W})}catch(U){X$.debug("News fetch failed for dashboard",{error:U})}if(Z.length===0)Z.push({id:"greeting",title:Q,content:[J,"","Nenhuma tarefa ou evento pendente.","Use /ajuda para ver comandos dispon\xEDveis."]});return{panels:Z,columns:Math.min(2,Z.length),gap:1}}function AH($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let Y=Math.floor(Z/60000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;let Q=Math.floor(Y/60);if(Q<24)return`${Q}h ago`;let J=Math.floor(Q/24);if(J>365)return`${Math.floor(J/365)}y ago`;return`${J}d ago`}async function kz($,Z,Y,Q,J,z,K,X,V,G){let q=new XZ(Y.model),U=new KZ(Y.model,Z.session.name,nZ(Q.auth),Y.dataDir),W="default",B=K;Fz(Y.dataDir,U,Z);let M=null;try{M=await a8(Y.dataDir),U.setTimeContext(M)}catch(A){X$.debug("Time context init failed, using productivity mode",{error:A}),U.setPersonaMode("productivity")}if(Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(A,w,n)=>{if(A==="edit_file"&&w.old_text&&w.new_text){let A$=WJ(String(w.old_text),String(w.new_text));for(let V$ of A$)U.showSystem(V$)}let t=HJ(A,w),_=await U.promptApproval(t);if(U._approveAllRequested)$.setAutoApproveAll?.(!0),U._approveAllRequested=!1;return _});for(let A of Z.messages)if(A.role==="user")U.addUserMessage(A.content);else U.addAssistantMessage(A.content);let O=null;async function R(A){if(A.startsWith("/")){await wz(A,Q$);return}if(Y.maxSessionCost>0){let y=q.totals.costCents;if(y>=Y.maxSessionCost){U.showError(`Budget exceeded (~$${(y/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(y>=Y.maxSessionCost*0.8)U.showSystem(`Budget: ${Math.round(y/Y.maxSessionCost*100)}% used`)}let{text:w,images:n}=mJ(A),{text:t,files:_}=uJ(w),A$=t;if(_.length>0)A$=`${_.map((e8)=>`<file name="${e8.name}" path="${e8.path}" size="${e8.size}">
|
|
666
|
+
${e8.content}
|
|
667
|
+
</file>`).join(`
|
|
668
|
+
|
|
669
|
+
`)}
|
|
670
|
+
|
|
671
|
+
${t}`;let V$={role:"user",content:A$,images:n.length>0?n.map((y)=>({mediaType:y.mediaType,base64:y.base64})):void 0,files:_.length>0?_:void 0,timestamp:Date.now()};Z.addMessage(V$);let _$=[];if(n.length>0)_$.push(`${n.length} image${n.length>1?"s":""}`);if(_.length>0)_$.push(`${_.length} file${_.length>1?"s":""}`);let A0=_$.length>0?`${t} (${_$.join(", ")})`:t;U.addUserMessage(A0),U.disableInput(),U.startStream();let Y0="",Q0=[],m5={},T1=0,t8=0;O=new AbortController;try{for await(let y of $.chat(Z.messages,B,X)){if(O.signal.aborted)break;switch(y.type){case"text":U.appendStream(y.text),Y0+=y.text;break;case"tool_call":U.flushStream(),U.showToolCall(y.name,y.input),m5=y.input;break;case"tool_result":U.showToolResult(y.name,y.result),Q0.push({id:y.id,name:y.name,input:m5,result:y.result}),m5={},U.resetStreamBuffer();break;case"tool_blocked":U.showError(y.reason);break;case"usage":T1+=y.inputTokens,t8+=y.outputTokens;break;case"error":U.showError(y.error);break;case"done":break}}}catch(y){if(!O.signal.aborted)U.showError(y instanceof Error?y.message:String(y))}O=null,U.endStream();let NZ={inputTokens:T1,outputTokens:t8},yz=q.add(NZ);if(T1>0||t8>0)U.showUsage(q.formatUsage(NZ)),U.updateSessionCost(`~$${(q.totals.costCents/100).toFixed(4)}`);let bz={role:"assistant",content:Y0,toolCalls:Q0.length>0?Q0:void 0,usage:T1>0?{inputTokens:T1,outputTokens:t8,costCents:yz.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(bz),Z.trimHistory(Y.maxHistory),U.enableInput()}function P(){Z.saveLastSession(),Y3(),tJ(),Jz(),R3(),r5(),j1().catch(()=>{}),U.stop(),process.exit(0)}let Q$={tui:U,sessions:Z,claude:$,config:Y,auth:Q,skills:J,tracker:q,plugins:V,systemPrompt:z,activeSystemPrompt:B,setActiveSystemPrompt:(A)=>{B=A,Q$.activeSystemPrompt=A},currentPersona:W,setCurrentPersona:(A)=>{W=A,Q$.currentPersona=A},timeContext:M,setTimeContext:(A)=>{M=A,Q$.timeContext=A},handleSubmit:R,cleanup:P};process.on("SIGINT",P),process.on("SIGTERM",P),U.start({onSubmit:R,onCancel:()=>{O?.abort(),U.endStream(),U.showSystem("Cancelled."),U.enableInput()},onExit:P});let l=`Authenticated via Claude ${Q.auth.subscriptionType} subscription.`;if(U.showSystem(`smolerclaw v${A1()} \u2014 the micro AI assistant.
|
|
668
672
|
Criado por Aldeia Viva - Impactando Vida (aldeia-viva.com.br)
|
|
669
|
-
${
|
|
670
|
-
Type /ajuda for commands.`),
|
|
671
|
-
`).filter((W)=>W.trim()).slice(0,6);if(B.length>0)$.push({id:"calendar",title:"Agenda",content:B})}catch{}let H=s7();if(H){let z=H.split(`
|
|
672
|
-
`).filter((B)=>B.trim()).slice(0,5);$.push({id:"project",title:"Projetos",content:z})}try{let B=(await E4(["finance","business","tech"],2)).split(`
|
|
673
|
-
`).filter((W)=>W.trim()).slice(0,6);if(B.length>0)$.push({id:"news",title:"Noticias",content:B})}catch{}if($.length===0)$.push({id:"greeting",title:Q,content:[Y,"","Nenhuma tarefa ou evento pendente.","Use /ajuda para ver comandos dispon\xEDveis."]});return{panels:$,columns:Math.min(2,$.length),gap:1}}function eq($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let Q=Math.floor(Z/60000);if(Q<1)return"just now";if(Q<60)return`${Q}m ago`;let Y=Math.floor(Q/60);if(Y<24)return`${Y}h ago`;let J=Math.floor(Y/24);if(J>365)return`${Math.floor(J/365)}y ago`;return`${J}d ago`}rq().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
|
|
673
|
+
${l}
|
|
674
|
+
Type /ajuda for commands.`),Xz(Y.dataDir))try{let A=await CZ(Y.dataDir);if(A.panels.length>0){U.enterDashboardMode(A);let w=()=>{U.enterChatMode(),U.showSystem("Briefing exibido. Pressione qualquer tecla para continuar."),process.stdin.removeListener("data",w)};setTimeout(()=>{if(U.getViewMode()==="dashboard")U.enterChatMode()},30000),process.stdin.once("data",()=>{if(U.getViewMode()==="dashboard")U.enterChatMode()})}else{let w=await Gz();U.showSystem(w)}Vz()}catch(A){X$.debug("Morning briefing failed at startup",{error:A})}if(G)await R(G)}async function IH(){let $=FZ(process.argv.slice(2));if($.help)RZ(),process.exit(0);if($.version)console.log(`smolerclaw v${A1()}`),process.exit(0);let Z=oZ();if($.model)Z.model=F4($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=t5()}catch(W){console.error("smolerclaw:",W instanceof Error?W.message:W),process.exit(1)}let Q={auth:Y},J=MJ(Q,Z.model,Z.maxTokens,Z.toolApproval),{sessions:z,skills:K,systemPrompt:X,activeSystemPrompt:V,enableTools:G,plugins:q}=TJ(Z,$.session,$.noTools),U=!process.stdin.isTTY;if($.print||U)await AJ(J,z,X,G,$.prompt,U),process.exit(0);await kz(J,z,Z,Q,K,X,V,G,q,$.prompt)}IH().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
|