smolerclaw 1.0.5 → 1.2.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.
Files changed (3) hide show
  1. package/README.md +28 -10
  2. package/dist/index.js +311 -175
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,16 +1,20 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var lZ=Object.defineProperty;var iZ=($)=>$;function nZ($,Z){this[$]=iZ.bind(null,Z)}var oZ=($,Z)=>{for(var Y in Z)lZ($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:nZ.bind(Z,Y)})};var aZ=($,Z)=>()=>($&&(Z=$($=0)),Z);var _6={};oZ(_6,{searchInvestigations:()=>S6,openInvestigation:()=>D6,listInvestigations:()=>I6,initInvestigations:()=>x6,getInvestigation:()=>T6,generateReport:()=>k6,formatInvestigationList:()=>q4,formatInvestigationDetail:()=>b6,formatEvidenceDetail:()=>i5,collectEvidence:()=>A6,closeInvestigation:()=>P6,addFinding:()=>w6});import{existsSync as t8,mkdirSync as d5,readFileSync as m5,writeFileSync as u5}from"fs";import{join as p5}from"path";function W4(){u5($0(),JSON.stringify(l,null,2))}function l5(){let $=$0();if(!t8($)){l=[];return}try{l=JSON.parse(m5($,"utf-8"))}catch{l=[]}}function x6($){if(e8=$,!t8($))d5($,{recursive:!0});l5()}function D6($,Z,Y,J=[]){let X=new Date().toISOString(),z={id:y6(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:J.map((Q)=>Q.toLowerCase()),evidence:[],findings:[],created:X,updated:X};return l=[...l,z],W4(),z}function A6($,Z,Y,J,X){let z=G1($);if(!z)return null;let Q={id:y6(),source:Z,label:Y.trim(),content:J.trim(),path:X?.trim(),timestamp:new Date().toISOString()},V={...z,evidence:[...z.evidence,Q],status:z.status==="aberta"?"em_andamento":z.status,updated:new Date().toISOString()};return l=l.map((G)=>G.id===z.id?V:G),W4(),Q}function w6($,Z,Y,J,X=[]){let z=G1($);if(!z)return null;let Q=X.filter((q)=>z.evidence.some((K)=>K.id===q)),V={id:y6(),severity:Z,title:Y.trim(),description:J.trim(),evidence_ids:Q,timestamp:new Date().toISOString()},G={...z,findings:[...z.findings,V],updated:new Date().toISOString()};return l=l.map((q)=>q.id===z.id?G:q),W4(),V}function P6($,Z,Y){let J=G1($);if(!J)return null;let X={...J,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return l=l.map((z)=>z.id===J.id?X:z),W4(),X}function T6($){return G1($)}function I6($,Z,Y=20){let J=[...l];if($)J=J.filter((X)=>X.status===$);if(Z)J=J.filter((X)=>X.type===Z);return J.sort((X,z)=>new Date(z.updated).getTime()-new Date(X.updated).getTime()).slice(0,Y)}function S6($){let Z=$.toLowerCase();return l.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.hypothesis?.toLowerCase().includes(Z)||Y.tags.some((J)=>J.includes(Z))||Y.findings.some((J)=>J.title.toLowerCase().includes(Z))||Y.summary?.toLowerCase().includes(Z)).sort((Y,J)=>new Date(J.updated).getTime()-new Date(Y.updated).getTime())}function k6($){let Z=G1($);if(!Z)return null;let Y=[],J=(Q)=>new Date(Q).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),X={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:** ${X[Z.type]}`),Y.push(`**Status:** ${Z.status}`),Y.push(`**Abertura:** ${J(Z.created)}`),Y.push(`**Ultima atualizacao:** ${J(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 Q of Z.evidence){let V=J(Q.timestamp);Y.push(""),Y.push(`### [${Q.id}] ${Q.label}`),Y.push(`- Fonte: ${Q.source}${Q.path?` (${Q.path})`:""}`),Y.push(`- Coletada: ${V}`);let G=Q.content.length>2000?Q.content.slice(0,2000)+`
4
- ... (truncado)`:Q.content;Y.push("```"),Y.push(G),Y.push("```")}}if(Z.findings.length>0){let Q=[...Z.findings].sort((V,G)=>(z[V.severity]??4)-(z[G.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let V of Q){let G=Y0(V.severity);if(Y.push(""),Y.push(`### ${G} ${V.title}`),Y.push(V.description),V.evidence_ids.length>0)Y.push(`- Evidencias: ${V.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(`
5
- `)}function q4($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Y)=>{let J=new Date(Y.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Z0(Y.status),z=Y.evidence.length,Q=Y.findings.length,V=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${X} [${J}] ${Y.title} (${Y.type}) \u2014 ${z} ev, ${Q} concl${V} {${Y.id}}`});return`Investigacoes (${$.length}):
3
+ var e6=Object.defineProperty;var $3=($)=>$;function Z3($,Z){this[$]=$3.bind(null,Z)}var Y3=($,Z)=>{for(var Y in Z)e6($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:Z3.bind(Z,Y)})};var l7=($,Z)=>()=>($&&(Z=$($=0)),Z);import{existsSync as A$,mkdirSync as e0,readFileSync as Q8,writeFileSync as i1,renameSync as s7,statSync as V3}from"fs";import{join as X$,dirname as t7,relative as G3}from"path";import{createHash as W3,randomUUID as e7}from"crypto";function Q5($,Z){if(x$=$,J5=Z,n=X$($,".backup"),q3(),Z2=!0,J1=A$(X$(n,".git")),J1)$2=N3()}function o1(){return Z2}function D($,Z){let Y=t7($);if(!A$(Y))e0(Y,{recursive:!0});let J=X$(Y,`.smolerclaw-${e7().slice(0,8)}.tmp`);if(i1(J,Z),s7(J,$),Z2){let Q=B3($);if(Q&&X8.includes(Q))H3(Q,Z)}}function X5($){return W3("sha256").update($).digest("hex")}function H3($,Z){let Y=X5(Z),J=new Date().toISOString(),Q=Buffer.byteLength(Z,"utf-8");h$=[...h$.filter((X)=>X.file!==$),{file:$,sha256:Y,size:Q,updatedAt:J}],U3()}function q3(){let $=X$(x$,Z5);if(!A$($)){h$=[];return}try{let Z=JSON.parse(Q8($,"utf-8"));if(Z.version!==$5){h$=[];return}h$=Z.checksums||[]}catch{h$=[]}}function U3(){if(!x$)return;let $=X$(x$,Z5),Z={checksums:h$,version:$5},Y=X$(x$,`.vault-${e7().slice(0,8)}.tmp`);i1(Y,JSON.stringify(Z,null,2)),s7(Y,$)}function B3($){try{let Z=G3(x$,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function K8(){let $=[],Z=0;for(let Y of X8){let J=X$(x$,Y),Q=A$(J);if(!Q){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let X=0,K="";try{let H=V3(J);X=H.size,K=H.mtime.toISOString()}catch{}let V=h$.find((H)=>H.file===Y),G=null;if(V)try{let H=Q8(J,"utf-8");if(G=X5(H)===V.sha256,!G)Z++}catch{G=!1,Z++}$.push({file:Y,exists:Q,checksumValid:G,size:X,lastModified:K})}return{files:$,lastBackup:$2,backupEnabled:J1,totalFiles:$.filter((Y)=>Y.exists).length,corruptFiles:Z}}function z8($){let Z=["=== Vault Status ==="],Y=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${Y}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${X8.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
4
+ --- Arquivos ---`);for(let J of $.files){if(!J.exists){Z.push(` ${J.file.padEnd(30)} (nao existe)`);continue}let Q=(J.size/1024).toFixed(1),X=J.checksumValid===null?"?":J.checksumValid?"OK":"CORROMPIDO",K=J.lastModified?new Date(J.lastModified).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${J.file.padEnd(30)} ${Q.padStart(8)} KB [${X}] ${K}`)}return Z.join(`
5
+ `)}async function V8(){if(!x$)return"Error: vault not initialized.";if(!A$(n))e0(n,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
6
+ `);if(i1(X$(n,".gitignore"),$),!A$(X$(n,".git"))){let Z=await f$(["git","init","-b",Y5],n);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await f$(["git","config","user.email","vault@smolerclaw.local"],n),await f$(["git","config","user.name","smolerclaw-vault"],n)}return J1=!0,"Shadow backup inicializado."}async function M1($){if(!J1)return"Backup nao ativado. Use vault_init_backup primeiro.";try{for(let X of X8){let K=X$(x$,X);if(!A$(K))continue;let V=X$(n,X),G=t7(V);if(!A$(G))e0(G,{recursive:!0});i1(V,Q8(K,"utf-8"))}let Z=X$(J5,"config.json");if(A$(Z))i1(X$(n,"config.json"),Q8(Z,"utf-8"));if(await f$(["git","add","-A"],n),!(await f$(["git","status","--porcelain"],n)).stdout.trim())return"Nenhuma mudanca para backup.";let J=$||`backup ${new Date().toISOString().slice(0,19)}`,Q=await f$(["git","commit","-m",J],n);if(!Q.ok)return`Backup commit falhou: ${Q.stderr}`;return $2=new Date().toISOString(),`Backup concluido: ${J}`}catch(Z){return`Backup falhou: ${Z instanceof Error?Z.message:String(Z)}`}}async function G8(){if(!J1)return"Backup nao ativado.";if(!(await f$(["git","remote","-v"],n)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await f$(["git","push","-u","origin",Y5],n);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function N3(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:n,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function f$($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[J,Q]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),X=await Y.exited;return{stdout:J.trim(),stderr:Q.trim(),ok:X===0}}function K5($=30){if(Y2(),!J1)return;J8=setInterval(()=>{M1("auto-backup").catch(()=>{})},$*60*1000)}function Y2(){if(J8)clearInterval(J8),J8=null}var $5=1,Z5="vault-checksums.json",Y5="smolerclaw-backup",X8,x$="",J5="",h$,n="",J1=!1,$2=null,Z2=!1,J8=null;var r=l7(()=>{X8=["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","rag/rag-index.json"],h$=[]});var X7={};Y3(X7,{searchInvestigations:()=>Z7,openInvestigation:()=>a2,listInvestigations:()=>$7,initInvestigations:()=>o2,getInvestigation:()=>e2,generateReport:()=>Y7,formatInvestigationList:()=>K0,formatInvestigationDetail:()=>J7,formatEvidenceDetail:()=>BJ,collectEvidence:()=>r2,closeInvestigation:()=>t2,addFinding:()=>s2});import{existsSync as p9,mkdirSync as GJ,readFileSync as WJ}from"fs";import{join as HJ}from"path";import{randomUUID as qJ}from"crypto";function X0(){D(n9(),JSON.stringify(t,null,2))}function UJ(){let $=n9();if(!p9($)){t=[];return}try{t=JSON.parse(WJ($,"utf-8"))}catch{t=[]}}function o2($){if(l9=$,!p9($))GJ($,{recursive:!0});UJ()}function a2($,Z,Y,J=[]){let Q=new Date().toISOString(),X={id:Q7(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:J.map((K)=>K.toLowerCase()),evidence:[],findings:[],created:Q,updated:Q};return t=[...t,X],X0(),X}function r2($,Z,Y,J,Q){let X=u4($);if(!X)return null;let K=J.trim();if(K.length>u9)K=K.slice(0,u9)+`
7
+ ...(truncated, ${J.length} total chars)`;let V={id:Q7(),source:Z,label:Y.trim(),content:K,path:Q?.trim(),timestamp:new Date().toISOString()},G={...X,evidence:[...X.evidence,V],status:X.status==="aberta"?"em_andamento":X.status,updated:new Date().toISOString()};return t=t.map((H)=>H.id===X.id?G:H),X0(),V}function s2($,Z,Y,J,Q=[]){let X=u4($);if(!X)return null;let K=Q.filter((H)=>X.evidence.some((z)=>z.id===H)),V={id:Q7(),severity:Z,title:Y.trim(),description:J.trim(),evidence_ids:K,timestamp:new Date().toISOString()},G={...X,findings:[...X.findings,V],updated:new Date().toISOString()};return t=t.map((H)=>H.id===X.id?G:H),X0(),V}function t2($,Z,Y){let J=u4($);if(!J)return null;let Q={...J,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return t=t.map((X)=>X.id===J.id?Q:X),X0(),Q}function e2($){return u4($)}function $7($,Z,Y=20){let J=[...t];if($)J=J.filter((Q)=>Q.status===$);if(Z)J=J.filter((Q)=>Q.type===Z);return J.sort((Q,X)=>new Date(X.updated).getTime()-new Date(Q.updated).getTime()).slice(0,Y)}function Z7($){let Z=$.toLowerCase();return t.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.hypothesis?.toLowerCase().includes(Z)||Y.tags.some((J)=>J.includes(Z))||Y.findings.some((J)=>J.title.toLowerCase().includes(Z))||Y.summary?.toLowerCase().includes(Z)).sort((Y,J)=>new Date(J.updated).getTime()-new Date(Y.updated).getTime())}function Y7($){let Z=u4($);if(!Z)return null;let Y=[],J=(K)=>new Date(K).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),Q={bug:"Bug / Mal funcionamento",feature:"Construcao de funcionalidade",test:"Material para testes",audit:"Auditoria",incident:"Incidente"},X={critical:0,high:1,medium:2,low:3,info:4};if(Y.push(`# Investigacao: ${Z.title}`),Y.push(""),Y.push(`**Tipo:** ${Q[Z.type]}`),Y.push(`**Status:** ${Z.status}`),Y.push(`**Abertura:** ${J(Z.created)}`),Y.push(`**Ultima atualizacao:** ${J(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 V=J(K.timestamp);Y.push(""),Y.push(`### [${K.id}] ${K.label}`),Y.push(`- Fonte: ${K.source}${K.path?` (${K.path})`:""}`),Y.push(`- Coletada: ${V}`);let G=K.content.length>2000?K.content.slice(0,2000)+`
8
+ ... (truncado)`:K.content;Y.push("```"),Y.push(G),Y.push("```")}}if(Z.findings.length>0){let K=[...Z.findings].sort((V,G)=>(X[V.severity]??4)-(X[G.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let V of K){let G=o9(V.severity);if(Y.push(""),Y.push(`### ${G} ${V.title}`),Y.push(V.description),V.evidence_ids.length>0)Y.push(`- Evidencias: ${V.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(`
9
+ `)}function K0($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Y)=>{let J=new Date(Y.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=i9(Y.status),X=Y.evidence.length,K=Y.findings.length,V=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${Q} [${J}] ${Y.title} (${Y.type}) \u2014 ${X} ev, ${K} concl${V} {${Y.id}}`});return`Investigacoes (${$.length}):
6
10
  ${Z.join(`
7
- `)}`}function b6($){let Z=(X)=>new Date(X).toLocaleDateString("pt-BR"),Y=Z0($.status),J=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${Y}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)J.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)J.push(`Tags: ${$.tags.join(", ")}`);J.push(`
8
- Evidencias: ${$.evidence.length}`);for(let X of $.evidence.slice(-5)){let z=X.content.slice(0,80).replace(/\n/g," ");J.push(` [${X.id}] ${X.source}: ${X.label} \u2014 "${z}..."`)}if($.evidence.length>5)J.push(` ... (${$.evidence.length-5} mais)`);J.push(`
9
- Conclusoes: ${$.findings.length}`);for(let X of $.findings)J.push(` ${Y0(X.severity)} ${X.title}`);if($.summary)J.push(`
11
+ `)}`}function J7($){let Z=(Q)=>new Date(Q).toLocaleDateString("pt-BR"),Y=i9($.status),J=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${Y}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)J.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)J.push(`Tags: ${$.tags.join(", ")}`);J.push(`
12
+ Evidencias: ${$.evidence.length}`);for(let Q of $.evidence.slice(-5)){let X=Q.content.slice(0,80).replace(/\n/g," ");J.push(` [${Q.id}] ${Q.source}: ${Q.label} \u2014 "${X}..."`)}if($.evidence.length>5)J.push(` ... (${$.evidence.length-5} mais)`);J.push(`
13
+ Conclusoes: ${$.findings.length}`);for(let Q of $.findings)J.push(` ${o9(Q.severity)} ${Q.title}`);if($.summary)J.push(`
10
14
  Resumo: ${$.summary}`);if($.recommendations)J.push(`Recomendacoes: ${$.recommendations}`);return J.join(`
11
- `)}function i5($){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)+`
15
+ `)}function BJ($){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)+`
12
16
  ... (truncado)`:$.content].join(`
13
- `)}function G1($){let Z=$.toLowerCase().trim(),Y=l.find((X)=>X.id===Z);if(Y)return Y;return l.filter((X)=>X.title.toLowerCase().includes(Z)).sort((X,z)=>new Date(z.updated).getTime()-new Date(X.updated).getTime())[0]||null}function Z0($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function Y0($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function y6(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}var e8="",l,$0=()=>p5(e8,"investigations.json");var W1=aZ(()=>{l=[]});import{readFileSync as rZ}from"fs";import{join as sZ,dirname as tZ}from"path";function H7($){let Z={help:!1,version:!1,noTools:!1,print:!1},Y=[],J=0;while(J<$.length){let X=$[J];switch(X){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++J],!Z.model)C1("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++J],!Z.session)C1("--session requires a value");break;case"--max-tokens":let z=Number($[++J]);if(!z||z<=0)C1("--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(X.startsWith("-"))C1(`Unknown option: ${X}. Try --help`);Y.push(X)}J++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function j1(){return"1.0.0"}function U7(){let $=j1();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
17
+ `)}function u4($){let Z=$.toLowerCase().trim(),Y=t.find((Q)=>Q.id===Z);if(Y)return Y;return t.filter((Q)=>Q.title.toLowerCase().includes(Z)).sort((Q,X)=>new Date(X.updated).getTime()-new Date(Q.updated).getTime())[0]||null}function i9($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function o9($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function Q7(){return qJ().slice(0,8)}var l9="",t,n9=()=>HJ(l9,"investigations.json"),u9=50000;var p4=l7(()=>{r();t=[]});import{readFileSync as J3}from"fs";import{join as Q3,dirname as X3}from"path";function n7($){let Z={help:!1,version:!1,noTools:!1,print:!1},Y=[],J=0;while(J<$.length){let Q=$[J];switch(Q){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++J],!Z.model)e4("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++J],!Z.session)e4("--session requires a value");break;case"--max-tokens":let X=Number($[++J]);if(!X||X<=0)e4("--max-tokens requires a positive number");Z.maxTokens=X;break;case"--no-tools":Z.noTools=!0;break;case"-p":case"--print":Z.print=!0;break;default:if(Q.startsWith("-"))e4(`Unknown option: ${Q}. Try --help`);Y.push(Q)}J++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function $8(){return"1.0.0"}function i7(){let $=$8();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
14
18
 
15
19
  Usage:
16
20
  smolerclaw [options] [prompt]
@@ -38,15 +42,15 @@ Commands (inside TUI):
38
42
  /briefing Daily briefing /news News radar
39
43
  /task Create task /tasks List tasks
40
44
  /open Open Windows app /calendar Outlook calendar
41
- /export Export markdown /exit Quit`)}function C1($){console.error(`smolerclaw: ${$}`),process.exit(2)}import{existsSync as E1,mkdirSync as Z3,readFileSync as j7,writeFileSync as M1}from"fs";import{homedir as Y3}from"os";import{join as H2}from"path";import{existsSync as eZ}from"fs";var x=process.platform==="win32",B7=process.platform==="darwin",fY=process.platform==="linux";function F1(){if(x)return["powershell","-NoProfile","-NonInteractive","-Command"];let $=process.env.SHELL;if($&&eZ($))return[$,"-c"];return["bash","-c"]}function N7(){if(x)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function $3($){try{let Z=x?["powershell","-NoProfile","-Command",`Get-Command ${$} -ErrorAction SilentlyContinue`]:["which",$],Y=Bun.spawn(Z,{stdout:"pipe",stderr:"pipe"});return await Y.exited,Y.exitCode===0}catch{return!1}}var O1=null;async function C7(){if(O1!==null)return O1;return O1=await $3("rg"),O1}var y4=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"];function _4($){let Z=$.replace(/\\/g,"/");return y4.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var C$=Y3(),L1=x?H2(process.env.APPDATA||H2(C$,"AppData","Roaming"),"smolerclaw"):H2(C$,".config","smolerclaw"),f4=x?H2(process.env.LOCALAPPDATA||H2(C$,"AppData","Local"),"smolerclaw"):H2(C$,".local","share","smolerclaw"),F2=H2(L1,"config.json"),B$={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:f4,toolApproval:"auto",language:"auto",maxSessionCost:0};function N$($){if(!E1($))Z3($,{recursive:!0})}function O7(){if(N$(L1),N$(f4),N$(H2(f4,"sessions")),x)J3();if(!E1(F2))return M1(F2,JSON.stringify(B$,null,2)),{...B$};let $;try{$=JSON.parse(j7(F2,"utf-8"))}catch{return M1(F2,JSON.stringify(B$,null,2)),{...B$}}return{...B$,...$}}function R1($){N$(L1),M1(F2,JSON.stringify($,null,2))}function F7(){return F2}function J3(){let $=H2(C$,".config","smolerclaw","config.json");if(E1($)&&!E1(F2))try{let Z=j7($,"utf-8");N$(L1),M1(F2,Z)}catch{}}import{existsSync as X3,readFileSync as z3}from"fs";import{homedir as Q3}from"os";import{join as K3}from"path";var E7=K3(Q3(),".claude",".credentials.json");function h4(){let $=V3();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 V3(){if(!X3(E7))return null;try{let Z=JSON.parse(z3(E7,"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 M7(){try{return h4()}catch{return null}}function L7($){return`sub:${$.subscriptionType||"pro"}`}function j($,Z,Y,J,X){if(J==="m")throw TypeError("Private method is not writable");if(J==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!X:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?X.call($,Y):X?X.value=Y:Z.set($,Y),Y}function H($,Z,Y,J){if(Y==="a"&&!J)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!J:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?J:Y==="a"?J.call($):J?J.value:Z.get($)}var v4=function(){let{crypto:$}=globalThis;if($?.randomUUID)return v4=$.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,(J)=>(+J^Y()&15>>+J/4).toString(16))};function U2($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var j$=($)=>{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 g extends E{constructor($,Z,Y,J){super(`${g.makeMessage($,Z,Y)}`);this.status=$,this.headers=J,this.requestID=J?.get("request-id"),this.error=Z}static makeMessage($,Z,Y){let J=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Y;if($&&J)return`${$} ${J}`;if($)return`${$} status code (no body)`;if(J)return J;return"(no status code or body)"}static generate($,Z,Y,J){if(!$||!J)return new _2({message:Y,cause:j$(Z)});let X=Z;if($===400)return new F$($,X,Y,J);if($===401)return new E$($,X,Y,J);if($===403)return new M$($,X,Y,J);if($===404)return new L$($,X,Y,J);if($===409)return new R$($,X,Y,J);if($===422)return new x$($,X,Y,J);if($===429)return new D$($,X,Y,J);if($>=500)return new A$($,X,Y,J);return new g($,X,Y,J)}}class p extends g{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class _2 extends g{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class O$ extends _2{constructor({message:$}={}){super({message:$??"Request timed out."})}}class F$ extends g{}class E$ extends g{}class M$ extends g{}class L$ extends g{}class R$ extends g{}class x$ extends g{}class D$ extends g{}class A$ extends g{}var W3=/^[a-z][a-z0-9+.-]*:/i,R7=($)=>{return W3.test($)},g4=($)=>(g4=Array.isArray,g4($)),c4=g4;function x1($){if(typeof $!=="object")return{};return $??{}}function d4($){if(!$)return!0;for(let Z in $)return!1;return!0}function x7($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var D7=($,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 D1=($)=>{try{return JSON.parse($)}catch(Z){return}};var A7=($)=>new Promise((Z)=>setTimeout(Z,$));var E2="0.80.0";var I7=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function q3(){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 H3=()=>{let $=q3();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E2,"X-Stainless-OS":P7(Deno.build.os),"X-Stainless-Arch":w7(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":E2,"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":E2,"X-Stainless-OS":P7(globalThis.process.platform??"unknown"),"X-Stainless-Arch":w7(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=U3();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E2,"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":E2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function U3(){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 J=Y.exec(navigator.userAgent);if(J){let X=J[1]||0,z=J[2]||0,Q=J[3]||0;return{browser:Z,version:`${X}.${z}.${Q}`}}}return null}var w7=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},P7=($)=>{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"},T7,S7=()=>{return T7??(T7=H3())};function k7(){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 m4(...$){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 A1($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return m4({start(){},async pull(Y){let{done:J,value:X}=await Z.next();if(J)Y.close();else Y.enqueue(X)},async cancel(){await Z.return?.()}})}function w$($){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 b7($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var y7=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function _7($){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 v7($){let Z=0;for(let X of $)Z+=X.length;let Y=new Uint8Array(Z),J=0;for(let X of $)Y.set(X,J),J+=X.length;return Y}var f7;function P$($){let Z;return(f7??(Z=new globalThis.TextEncoder,f7=Z.encode.bind(Z)))($)}var h7;function u4($){let Z;return(h7??(Z=new globalThis.TextDecoder,h7=Z.decode.bind(Z)))($)}var s,t;class M2{constructor(){s.set(this,void 0),t.set(this,void 0),j(this,s,new Uint8Array,"f"),j(this,t,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?P$($):$;j(this,s,v7([H(this,s,"f"),Z]),"f");let Y=[],J;while((J=C3(H(this,s,"f"),H(this,t,"f")))!=null){if(J.carriage&&H(this,t,"f")==null){j(this,t,J.index,"f");continue}if(H(this,t,"f")!=null&&(J.index!==H(this,t,"f")+1||J.carriage)){Y.push(u4(H(this,s,"f").subarray(0,H(this,t,"f")-1))),j(this,s,H(this,s,"f").subarray(H(this,t,"f")),"f"),j(this,t,null,"f");continue}let X=H(this,t,"f")!==null?J.preceding-1:J.preceding,z=u4(H(this,s,"f").subarray(0,X));Y.push(z),j(this,s,H(this,s,"f").subarray(J.index),"f"),j(this,t,null,"f")}return Y}flush(){if(!H(this,s,"f").length)return[];return this.decode(`
42
- `)}}s=new WeakMap,t=new WeakMap;M2.NEWLINE_CHARS=new Set([`
43
- `,"\r"]);M2.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function C3($,Z){for(let X=Z??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function g7($){for(let J=0;J<$.length-1;J++){if($[J]===10&&$[J+1]===10)return J+2;if($[J]===13&&$[J+1]===13)return J+2;if($[J]===13&&$[J+1]===10&&J+3<$.length&&$[J+2]===13&&$[J+3]===10)return J+4}return-1}var P1={off:0,error:200,warn:300,info:400,debug:500},p4=($,Z,Y)=>{if(!$)return;if(x7(P1,$))return $;d(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(P1))}`);return};function T$(){}function w1($,Z,Y){if(!Z||P1[$]>P1[Y])return T$;else return Z[$].bind(Z)}var j3={error:T$,warn:T$,info:T$,debug:T$},c7=new WeakMap;function d($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return j3;let J=c7.get(Z);if(J&&J[0]===Y)return J[1];let X={error:w1("error",Z,Y),warn:w1("warn",Z,Y),info:w1("info",Z,Y),debug:w1("debug",Z,Y)};return c7.set(Z,[Y,X]),X}var B2=($)=>{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 I$;class e{constructor($,Z,Y){this.iterator=$,I$.set(this,void 0),this.controller=Z,j(this,I$,Y,"f")}static fromSSEResponse($,Z,Y){let J=!1,X=Y?d(Y):console;async function*z(){if(J)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let Q=!1;try{for await(let V of O3($,Z)){if(V.event==="completion")try{yield JSON.parse(V.data)}catch(G){throw X.error("Could not parse message into JSON:",V.data),X.error("From chunk:",V.raw),G}if(V.event==="message_start"||V.event==="message_delta"||V.event==="message_stop"||V.event==="content_block_start"||V.event==="content_block_delta"||V.event==="content_block_stop")try{yield JSON.parse(V.data)}catch(G){throw X.error("Could not parse message into JSON:",V.data),X.error("From chunk:",V.raw),G}if(V.event==="ping")continue;if(V.event==="error")throw new g(void 0,D1(V.data)??V.data,void 0,$.headers)}Q=!0}catch(V){if(U2(V))return;throw V}finally{if(!Q)Z.abort()}}return new e(z,Z,Y)}static fromReadableStream($,Z,Y){let J=!1;async function*X(){let Q=new M2,V=w$($);for await(let G of V)for(let q of Q.decode(G))yield q;for(let G of Q.flush())yield G}async function*z(){if(J)throw new E("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let Q=!1;try{for await(let V of X()){if(Q)continue;if(V)yield JSON.parse(V)}Q=!0}catch(V){if(U2(V))return;throw V}finally{if(!Q)Z.abort()}}return new e(z,Z,Y)}[(I$=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Y=this.iterator(),J=(X)=>{return{next:()=>{if(X.length===0){let z=Y.next();$.push(z),Z.push(z)}return X.shift()}}};return[new e(()=>J($),this.controller,H(this,I$,"f")),new e(()=>J(Z),this.controller,H(this,I$,"f"))]}toReadableStream(){let $=this,Z;return m4({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:J,done:X}=await Z.next();if(X)return Y.close();let z=P$(JSON.stringify(J)+`
44
- `);Y.enqueue(z)}catch(J){Y.error(J)}},async cancel(){await Z.return?.()}})}}async function*O3($,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 d7,J=new M2,X=w$($.body);for await(let z of F3(X))for(let Q of J.decode(z)){let V=Y.decode(Q);if(V)yield V}for(let z of J.flush()){let Q=Y.decode(z);if(Q)yield Q}}async function*F3($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let J=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?P$(Y):Y,X=new Uint8Array(Z.length+J.length);X.set(Z),X.set(J,Z.length),Z=X;let z;while((z=g7(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class d7{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 X={event:this.event,data:this.data.join(`
45
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,J]=E3($,":");if(J.startsWith(" "))J=J.substring(1);if(Z==="event")this.event=J;else if(Z==="data")this.data.push(J);return null}}function E3($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function T1($,Z){let{response:Y,requestLogID:J,retryOfRequestLogID:X,startTime:z}=Z,Q=await(async()=>{if(Z.options.stream){if(d($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return e.fromSSEResponse(Y,Z.controller)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let G=Y.headers.get("content-type")?.split(";")[0]?.trim();if(G?.includes("application/json")||G?.endsWith("+json")){if(Y.headers.get("content-length")==="0")return;let N=await Y.json();return l4(N,Y)}return await Y.text()})();return d($).debug(`[${J}] response parsed`,B2({retryOfRequestLogID:X,url:Y.url,status:Y.status,body:Q,durationMs:Date.now()-z})),Q}function l4($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var S$;class f2 extends Promise{constructor($,Z,Y=T1){super((J)=>{J(null)});this.responsePromise=Z,this.parseResponse=Y,S$.set(this,void 0),j(this,S$,$,"f")}_thenUnwrap($){return new f2(H(this,S$,"f"),this.responsePromise,async(Z,Y)=>l4($(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(H(this,S$,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}S$=new WeakMap;var I1;class i4{constructor($,Z,Y,J){I1.set(this,void 0),j(this,I1,$,"f"),this.options=J,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 H(this,I1,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(I1=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class S1 extends f2{constructor($,Z,Y){super($,Z,async(J,X)=>new Y(J,X.response,await T1(J,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class Q2 extends i4{constructor($,Z,Y,J){super($,Z,Y,J);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:{...x1(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...x1(this.options.query),after_id:$}}}}class k$ extends i4{constructor($,Z,Y,J){super($,Z,Y,J);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:{...x1(this.options.query),page:$}}}}var o4=()=>{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 h2($,Z,Y){return o4(),new File($,Z??"unknown_file",Y)}function b$($,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 a4=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var i2=async($,Z,Y=!0)=>{return{...$,body:await R3($.body,Z,Y)}},m7=new WeakMap;function L3($){let Z=typeof $==="function"?$:$.fetch,Y=m7.get(Z);if(Y)return Y;let J=(async()=>{try{let X="Response"in Z?Z.Response:(await Z("data:,")).constructor,z=new FormData;if(z.toString()===await new X(z).text())return!1;return!0}catch{return!0}})();return m7.set(Z,J),J}var R3=async($,Z,Y=!0)=>{if(!await L3(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let J=new FormData;return await Promise.all(Object.entries($||{}).map(([X,z])=>n4(J,X,z,Y))),J},x3=($)=>$ instanceof Blob&&("name"in $);var n4=async($,Z,Y,J)=>{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 X={},z=Y.headers.get("Content-Type");if(z)X={type:z};$.append(Z,h2([await Y.blob()],b$(Y,J),X))}else if(a4(Y))$.append(Z,h2([await new Response(A1(Y)).blob()],b$(Y,J)));else if(x3(Y))$.append(Z,h2([Y],b$(Y,J),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((X)=>n4($,Z+"[]",X,J)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([X,z])=>n4($,`${Z}[${X}]`,z,J)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var u7=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",D3=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&u7($),A3=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function k1($,Z,Y){if(o4(),$=await $,Z||(Z=b$($,!0)),D3($)){if($ instanceof File&&Z==null&&Y==null)return $;return h2([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(A3($)){let X=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),h2(await r4(X),Z,Y)}let J=await r4($);if(!Y?.type){let X=J.find((z)=>typeof z==="object"&&("type"in z)&&z.type);if(typeof X==="string")Y={...Y,type:X}}return h2(J,Z,Y)}async function r4($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(u7($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(a4($))for await(let Y of $)Z.push(...await r4(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${w3($)}`)}return Z}function w3($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class b{constructor($){this._client=$}}var p7=Symbol.for("brand.privateNullableHeaders");function*T3($){if(!$)return;if(p7 in $){let{values:J,nulls:X}=$;yield*J.entries();for(let z of X)yield[z,null];return}let Z=!1,Y;if($ instanceof Headers)Y=$.entries();else if(c4($))Y=$;else Z=!0,Y=Object.entries($??{});for(let J of Y){let X=J[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let z=c4(J[1])?J[1]:[J[1]],Q=!1;for(let V of z){if(V===void 0)continue;if(Z&&!Q)Q=!0,yield[X,null];yield[X,V]}}}var R=($)=>{let Z=new Headers,Y=new Set;for(let J of $){let X=new Set;for(let[z,Q]of T3(J)){let V=z.toLowerCase();if(!X.has(V))Z.delete(z),X.add(V);if(Q===null)Z.delete(z),Y.add(V);else Z.append(z,Q),Y.delete(V)}}return{[p7]:!0,values:Z,nulls:Y}};var y$=Symbol("anthropic.sdk.stainlessHelper");function b1($){return typeof $==="object"&&$!==null&&y$ in $}function s4($,Z){let Y=new Set;if($){for(let J of $)if(b1(J))Y.add(J[y$])}if(Z)for(let J of Z){if(b1(J))Y.add(J[y$]);if(Array.isArray(J.content)){for(let X of J.content)if(b1(X))Y.add(X[y$])}}return Array.from(Y)}function y1($,Z){let Y=s4($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function l7($){if(b1($))return{"x-stainless-helper":$[y$]};return{}}function n7($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var i7=Object.freeze(Object.create(null)),I3=($=n7)=>function(Y,...J){if(Y.length===1)return Y[0];let X=!1,z=[],Q=Y.reduce((K,O,N)=>{if(/[?#]/.test(O))X=!0;let M=J[N],D=(X?encodeURIComponent:$)(""+M);if(N!==J.length&&(M==null||typeof M==="object"&&M.toString===Object.getPrototypeOf(Object.getPrototypeOf(M.hasOwnProperty??i7)??i7)?.toString))D=M+"",z.push({start:K.length+O.length,length:D.length,error:`Value of type ${Object.prototype.toString.call(M).slice(8,-1)} is not a valid path parameter`});return K+O+(N===J.length?"":D)},""),V=Q.split(/[?#]/,1)[0],G=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,q;while((q=G.exec(V))!==null)z.push({start:q.index,length:q[0].length,error:`Value "${q[0]}" can't be safely passed as a path parameter`});if(z.sort((K,O)=>K.start-O.start),z.length>0){let K=0,O=z.reduce((N,M)=>{let D=" ".repeat(M.start-K),v="^".repeat(M.length);return K=M.start+M.length,N+D+v},"");throw new E(`Path parameters result in path with invalid segments:
46
- ${z.map((N)=>N.error).join(`
45
+ /export Export markdown /exit Quit`)}function e4($){console.error(`smolerclaw: ${$}`),process.exit(2)}import{existsSync as W8,mkdirSync as C3,readFileSync as z5}from"fs";import{homedir as M3}from"os";import{join as D$}from"path";import{existsSync as K3}from"fs";var A=process.platform==="win32",o7=process.platform==="darwin",nX=process.platform==="linux";function Y8(){if(A)return["powershell","-NoProfile","-NonInteractive","-Command"];let $=process.env.SHELL;if($&&K3($))return[$,"-c"];return["bash","-c"]}function a7(){if(A)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function z3($){try{let Z=A?["powershell","-NoProfile","-Command",`Get-Command ${$} -ErrorAction SilentlyContinue`]:["which",$],Y=Bun.spawn(Z,{stdout:"pipe",stderr:"pipe"});return await Y.exited,Y.exitCode===0}catch{return!1}}var Z8=null;async function r7(){if(Z8!==null)return Z8;return Z8=await z3("rg"),Z8}var s0=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"];function t0($){let Z=$.replace(/\\/g,"/");return s0.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}r();var r1=M3(),H8=A?D$(process.env.APPDATA||D$(r1,"AppData","Roaming"),"smolerclaw"):D$(r1,".config","smolerclaw"),J2=A?D$(process.env.LOCALAPPDATA||D$(r1,"AppData","Local"),"smolerclaw"):D$(r1,".local","share","smolerclaw"),v$=D$(H8,"config.json"),O1={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:J2,toolApproval:"auto",language:"auto",maxSessionCost:0};function a1($){if(!W8($))C3($,{recursive:!0})}function V5(){if(a1(H8),a1(J2),a1(D$(J2,"sessions")),A)E3();if(!W8(v$))return D(v$,JSON.stringify(O1,null,2)),{...O1};let $;try{$=JSON.parse(z5(v$,"utf-8"))}catch{return D(v$,JSON.stringify(O1,null,2)),{...O1}}return O3({...O1,...$})}function O3($){let Z={...O1};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 q8($){a1(H8),D(v$,JSON.stringify($,null,2))}function Q2(){return v$}function E3(){let $=D$(r1,".config","smolerclaw","config.json");if(W8($)&&!W8(v$))try{let Z=z5($,"utf-8");a1(H8),D(v$,Z)}catch{}}import{existsSync as L3,readFileSync as j3}from"fs";import{homedir as F3}from"os";import{join as R3}from"path";var G5=R3(F3(),".claude",".credentials.json");function X2(){let $=A3();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 A3(){if(!L3(G5))return null;try{let Z=JSON.parse(j3(G5,"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 K2(){try{return X2()}catch{return null}}function W5($){return`sub:${$.subscriptionType||"pro"}`}function L($,Z,Y,J,Q){if(J==="m")throw TypeError("Private method is not writable");if(J==="a"&&!Q)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!Q:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?Q.call($,Y):Q?Q.value=Y:Z.set($,Y),Y}function U($,Z,Y,J){if(Y==="a"&&!J)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!J:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return Y==="m"?J:Y==="a"?J.call($):J?J.value:Z.get($)}var z2=function(){let{crypto:$}=globalThis;if($?.randomUUID)return z2=$.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,(J)=>(+J^Y()&15>>+J/4).toString(16))};function T$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var s1=($)=>{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 R extends Error{}class c extends R{constructor($,Z,Y,J){super(`${c.makeMessage($,Z,Y)}`);this.status=$,this.headers=J,this.requestID=J?.get("request-id"),this.error=Z}static makeMessage($,Z,Y){let J=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):Y;if($&&J)return`${$} ${J}`;if($)return`${$} status code (no body)`;if(J)return J;return"(no status code or body)"}static generate($,Z,Y,J){if(!$||!J)return new Q1({message:Y,cause:s1(Z)});let Q=Z;if($===400)return new e1($,Q,Y,J);if($===401)return new $4($,Q,Y,J);if($===403)return new Z4($,Q,Y,J);if($===404)return new Y4($,Q,Y,J);if($===409)return new J4($,Q,Y,J);if($===422)return new Q4($,Q,Y,J);if($===429)return new X4($,Q,Y,J);if($>=500)return new K4($,Q,Y,J);return new c($,Q,Y,J)}}class s extends c{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class Q1 extends c{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class t1 extends Q1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class e1 extends c{}class $4 extends c{}class Z4 extends c{}class Y4 extends c{}class J4 extends c{}class Q4 extends c{}class X4 extends c{}class K4 extends c{}var D3=/^[a-z][a-z0-9+.-]*:/i,H5=($)=>{return D3.test($)},V2=($)=>(V2=Array.isArray,V2($)),G2=V2;function U8($){if(typeof $!=="object")return{};return $??{}}function W2($){if(!$)return!0;for(let Z in $)return!1;return!0}function q5($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var U5=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new R(`${$} must be an integer`);if(Z<0)throw new R(`${$} must be a positive integer`);return Z};var B8=($)=>{try{return JSON.parse($)}catch(Z){return}};var B5=($)=>new Promise((Z)=>setTimeout(Z,$));var g$="0.80.0";var O5=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function T3(){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 P3=()=>{let $=T3();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":g$,"X-Stainless-OS":C5(Deno.build.os),"X-Stainless-Arch":N5(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":g$,"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":g$,"X-Stainless-OS":C5(globalThis.process.platform??"unknown"),"X-Stainless-Arch":N5(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=w3();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":g$,"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":g$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function w3(){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 J=Y.exec(navigator.userAgent);if(J){let Q=J[1]||0,X=J[2]||0,K=J[3]||0;return{browser:Z,version:`${Q}.${X}.${K}`}}}return null}var N5=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},C5=($)=>{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"},M5,E5=()=>{return M5??(M5=P3())};function L5(){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 H2(...$){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 N8($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return H2({start(){},async pull(Y){let{done:J,value:Q}=await Z.next();if(J)Y.close();else Y.enqueue(Q)},async cancel(){await Z.return?.()}})}function z4($){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 j5($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var F5=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function R5($){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 R(`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 D5($){let Z=0;for(let Q of $)Z+=Q.length;let Y=new Uint8Array(Z),J=0;for(let Q of $)Y.set(Q,J),J+=Q.length;return Y}var A5;function V4($){let Z;return(A5??(Z=new globalThis.TextEncoder,A5=Z.encode.bind(Z)))($)}var x5;function q2($){let Z;return(x5??(Z=new globalThis.TextDecoder,x5=Z.decode.bind(Z)))($)}var K$,z$;class m${constructor(){K$.set(this,void 0),z$.set(this,void 0),L(this,K$,new Uint8Array,"f"),L(this,z$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?V4($):$;L(this,K$,D5([U(this,K$,"f"),Z]),"f");let Y=[],J;while((J=b3(U(this,K$,"f"),U(this,z$,"f")))!=null){if(J.carriage&&U(this,z$,"f")==null){L(this,z$,J.index,"f");continue}if(U(this,z$,"f")!=null&&(J.index!==U(this,z$,"f")+1||J.carriage)){Y.push(q2(U(this,K$,"f").subarray(0,U(this,z$,"f")-1))),L(this,K$,U(this,K$,"f").subarray(U(this,z$,"f")),"f"),L(this,z$,null,"f");continue}let Q=U(this,z$,"f")!==null?J.preceding-1:J.preceding,X=q2(U(this,K$,"f").subarray(0,Q));Y.push(X),L(this,K$,U(this,K$,"f").subarray(J.index),"f"),L(this,z$,null,"f")}return Y}flush(){if(!U(this,K$,"f").length)return[];return this.decode(`
46
+ `)}}K$=new WeakMap,z$=new WeakMap;m$.NEWLINE_CHARS=new Set([`
47
+ `,"\r"]);m$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function b3($,Z){for(let Q=Z??0;Q<$.length;Q++){if($[Q]===10)return{preceding:Q,index:Q+1,carriage:!1};if($[Q]===13)return{preceding:Q,index:Q+1,carriage:!0}}return null}function T5($){for(let J=0;J<$.length-1;J++){if($[J]===10&&$[J+1]===10)return J+2;if($[J]===13&&$[J+1]===13)return J+2;if($[J]===13&&$[J+1]===10&&J+3<$.length&&$[J+2]===13&&$[J+3]===10)return J+4}return-1}var M8={off:0,error:200,warn:300,info:400,debug:500},U2=($,Z,Y)=>{if(!$)return;if(q5(M8,$))return $;l(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(M8))}`);return};function G4(){}function C8($,Z,Y){if(!Z||M8[$]>M8[Y])return G4;else return Z[$].bind(Z)}var k3={error:G4,warn:G4,info:G4,debug:G4},P5=new WeakMap;function l($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return k3;let J=P5.get(Z);if(J&&J[0]===Y)return J[1];let Q={error:C8("error",Z,Y),warn:C8("warn",Z,Y),info:C8("info",Z,Y),debug:C8("debug",Z,Y)};return P5.set(Z,[Y,Q]),Q}var P$=($)=>{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 W4;class V${constructor($,Z,Y){this.iterator=$,W4.set(this,void 0),this.controller=Z,L(this,W4,Y,"f")}static fromSSEResponse($,Z,Y){let J=!1,Q=Y?l(Y):console;async function*X(){if(J)throw new R("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let K=!1;try{for await(let V of y3($,Z)){if(V.event==="completion")try{yield JSON.parse(V.data)}catch(G){throw Q.error("Could not parse message into JSON:",V.data),Q.error("From chunk:",V.raw),G}if(V.event==="message_start"||V.event==="message_delta"||V.event==="message_stop"||V.event==="content_block_start"||V.event==="content_block_delta"||V.event==="content_block_stop")try{yield JSON.parse(V.data)}catch(G){throw Q.error("Could not parse message into JSON:",V.data),Q.error("From chunk:",V.raw),G}if(V.event==="ping")continue;if(V.event==="error")throw new c(void 0,B8(V.data)??V.data,void 0,$.headers)}K=!0}catch(V){if(T$(V))return;throw V}finally{if(!K)Z.abort()}}return new V$(X,Z,Y)}static fromReadableStream($,Z,Y){let J=!1;async function*Q(){let K=new m$,V=z4($);for await(let G of V)for(let H of K.decode(G))yield H;for(let G of K.flush())yield G}async function*X(){if(J)throw new R("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let K=!1;try{for await(let V of Q()){if(K)continue;if(V)yield JSON.parse(V)}K=!0}catch(V){if(T$(V))return;throw V}finally{if(!K)Z.abort()}}return new V$(X,Z,Y)}[(W4=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Y=this.iterator(),J=(Q)=>{return{next:()=>{if(Q.length===0){let X=Y.next();$.push(X),Z.push(X)}return Q.shift()}}};return[new V$(()=>J($),this.controller,U(this,W4,"f")),new V$(()=>J(Z),this.controller,U(this,W4,"f"))]}toReadableStream(){let $=this,Z;return H2({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:J,done:Q}=await Z.next();if(Q)return Y.close();let X=V4(JSON.stringify(J)+`
48
+ `);Y.enqueue(X)}catch(J){Y.error(J)}},async cancel(){await Z.return?.()}})}}async function*y3($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new R("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 R("Attempted to iterate over a response with no body")}let Y=new w5,J=new m$,Q=z4($.body);for await(let X of _3(Q))for(let K of J.decode(X)){let V=Y.decode(K);if(V)yield V}for(let X of J.flush()){let K=Y.decode(X);if(K)yield K}}async function*_3($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let J=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?V4(Y):Y,Q=new Uint8Array(Z.length+J.length);Q.set(Z),Q.set(J,Z.length),Z=Q;let X;while((X=T5(Z))!==-1)yield Z.slice(0,X),Z=Z.slice(X)}if(Z.length>0)yield Z}class w5{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let Q={event:this.event,data:this.data.join(`
49
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Q}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,J]=h3($,":");if(J.startsWith(" "))J=J.substring(1);if(Z==="event")this.event=J;else if(Z==="data")this.data.push(J);return null}}function h3($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function O8($,Z){let{response:Y,requestLogID:J,retryOfRequestLogID:Q,startTime:X}=Z,K=await(async()=>{if(Z.options.stream){if(l($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return V$.fromSSEResponse(Y,Z.controller)}if(Y.status===204)return null;if(Z.options.__binaryResponse)return Y;let G=Y.headers.get("content-type")?.split(";")[0]?.trim();if(G?.includes("application/json")||G?.endsWith("+json")){if(Y.headers.get("content-length")==="0")return;let N=await Y.json();return B2(N,Y)}return await Y.text()})();return l($).debug(`[${J}] response parsed`,P$({retryOfRequestLogID:Q,url:Y.url,status:Y.status,body:K,durationMs:Date.now()-X})),K}function B2($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var H4;class X1 extends Promise{constructor($,Z,Y=O8){super((J)=>{J(null)});this.responsePromise=Z,this.parseResponse=Y,H4.set(this,void 0),L(this,H4,$,"f")}_thenUnwrap($){return new X1(U(this,H4,"f"),this.responsePromise,async(Z,Y)=>B2($(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(U(this,H4,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}H4=new WeakMap;var E8;class N2{constructor($,Z,Y,J){E8.set(this,void 0),L(this,E8,$,"f"),this.options=J,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 R("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await U(this,E8,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(E8=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class L8 extends X1{constructor($,Z,Y){super($,Z,async(J,Q)=>new Y(J,Q.response,await O8(J,Q),Q.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class M$ extends N2{constructor($,Z,Y,J){super($,Z,Y,J);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:{...U8(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...U8(this.options.query),after_id:$}}}}class q4 extends N2{constructor($,Z,Y,J){super($,Z,Y,J);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:{...U8(this.options.query),page:$}}}}var M2=()=>{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 K1($,Z,Y){return M2(),new File($,Z??"unknown_file",Y)}function U4($,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 O2=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var E1=async($,Z,Y=!0)=>{return{...$,body:await g3($.body,Z,Y)}},I5=new WeakMap;function v3($){let Z=typeof $==="function"?$:$.fetch,Y=I5.get(Z);if(Y)return Y;let J=(async()=>{try{let Q="Response"in Z?Z.Response:(await Z("data:,")).constructor,X=new FormData;if(X.toString()===await new Q(X).text())return!1;return!0}catch{return!0}})();return I5.set(Z,J),J}var g3=async($,Z,Y=!0)=>{if(!await v3(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let J=new FormData;return await Promise.all(Object.entries($||{}).map(([Q,X])=>C2(J,Q,X,Y))),J},m3=($)=>$ instanceof Blob&&("name"in $);var C2=async($,Z,Y,J)=>{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 Q={},X=Y.headers.get("Content-Type");if(X)Q={type:X};$.append(Z,K1([await Y.blob()],U4(Y,J),Q))}else if(O2(Y))$.append(Z,K1([await new Response(N8(Y)).blob()],U4(Y,J)));else if(m3(Y))$.append(Z,K1([Y],U4(Y,J),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((Q)=>C2($,Z+"[]",Q,J)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([Q,X])=>C2($,`${Z}[${Q}]`,X,J)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var S5=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",c3=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&S5($),d3=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function j8($,Z,Y){if(M2(),$=await $,Z||(Z=U4($,!0)),c3($)){if($ instanceof File&&Z==null&&Y==null)return $;return K1([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(d3($)){let Q=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),K1(await E2(Q),Z,Y)}let J=await E2($);if(!Y?.type){let Q=J.find((X)=>typeof X==="object"&&("type"in X)&&X.type);if(typeof Q==="string")Y={...Y,type:Q}}return K1(J,Z,Y)}async function E2($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(S5($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(O2($))for await(let Y of $)Z.push(...await E2(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${u3($)}`)}return Z}function u3($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class _{constructor($){this._client=$}}var b5=Symbol.for("brand.privateNullableHeaders");function*l3($){if(!$)return;if(b5 in $){let{values:J,nulls:Q}=$;yield*J.entries();for(let X of Q)yield[X,null];return}let Z=!1,Y;if($ instanceof Headers)Y=$.entries();else if(G2($))Y=$;else Z=!0,Y=Object.entries($??{});for(let J of Y){let Q=J[0];if(typeof Q!=="string")throw TypeError("expected header name to be a string");let X=G2(J[1])?J[1]:[J[1]],K=!1;for(let V of X){if(V===void 0)continue;if(Z&&!K)K=!0,yield[Q,null];yield[Q,V]}}}var x=($)=>{let Z=new Headers,Y=new Set;for(let J of $){let Q=new Set;for(let[X,K]of l3(J)){let V=X.toLowerCase();if(!Q.has(V))Z.delete(X),Q.add(V);if(K===null)Z.delete(X),Y.add(V);else Z.append(X,K),Y.delete(V)}}return{[b5]:!0,values:Z,nulls:Y}};var B4=Symbol("anthropic.sdk.stainlessHelper");function F8($){return typeof $==="object"&&$!==null&&B4 in $}function L2($,Z){let Y=new Set;if($){for(let J of $)if(F8(J))Y.add(J[B4])}if(Z)for(let J of Z){if(F8(J))Y.add(J[B4]);if(Array.isArray(J.content)){for(let Q of J.content)if(F8(Q))Y.add(Q[B4])}}return Array.from(Y)}function R8($,Z){let Y=L2($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function k5($){if(F8($))return{"x-stainless-helper":$[B4]};return{}}function _5($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var y5=Object.freeze(Object.create(null)),n3=($=_5)=>function(Y,...J){if(Y.length===1)return Y[0];let Q=!1,X=[],K=Y.reduce((z,M,N)=>{if(/[?#]/.test(M))Q=!0;let E=J[N],j=(Q?encodeURIComponent:$)(""+E);if(N!==J.length&&(E==null||typeof E==="object"&&E.toString===Object.getPrototypeOf(Object.getPrototypeOf(E.hasOwnProperty??y5)??y5)?.toString))j=E+"",X.push({start:z.length+M.length,length:j.length,error:`Value of type ${Object.prototype.toString.call(E).slice(8,-1)} is not a valid path parameter`});return z+M+(N===J.length?"":j)},""),V=K.split(/[?#]/,1)[0],G=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,H;while((H=G.exec(V))!==null)X.push({start:H.index,length:H[0].length,error:`Value "${H[0]}" can't be safely passed as a path parameter`});if(X.sort((z,M)=>z.start-M.start),X.length>0){let z=0,M=X.reduce((N,E)=>{let j=" ".repeat(E.start-z),T="^".repeat(E.length);return z=E.start+E.length,N+j+T},"");throw new R(`Path parameters result in path with invalid segments:
50
+ ${X.map((N)=>N.error).join(`
47
51
  `)}
48
- ${Q}
49
- ${O}`)}return Q},S=I3(n7);class _$ extends b{list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/files",Q2,{query:J,...Z,headers:R([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(S`/v1/files/${$}`,{...Y,headers:R([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:J}=Z??{};return this._client.get(S`/v1/files/${$}/content`,{...Y,headers:R([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},Y){let{betas:J}=Z??{};return this._client.get(S`/v1/files/${$}`,{...Y,headers:R([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/files",i2({body:J,...Z,headers:R([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},l7(J.file),Z?.headers])},this._client))}}class f$ extends b{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(S`/v1/models/${$}?beta=true`,{...Y,headers:R([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/models?beta=true",Q2,{query:J,...Z,headers:R([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var _1={"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 o7($){return $?.output_format??$?.output_config?.format}function t4($,Z,Y){let J=o7(Z);if(!Z||!("parse"in(J??{})))return{...$,content:$.content.map((X)=>{if(X.type==="text"){let z=Object.defineProperty({...X},"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 X}),parsed_output:null};return e4($,Z,Y)}function e4($,Z,Y){let J=null,X=$.content.map((z)=>{if(z.type==="text"){let Q=b3(Z,z.text);if(J===null)J=Q;let V=Object.defineProperty({...z},"parsed_output",{value:Q,enumerable:!1});return Object.defineProperty(V,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),Q},enumerable:!1})}return z});return{...$,content:X,parsed_output:J}}function b3($,Z){let Y=o7($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(J){throw new E(`Failed to parse structured output: ${J}`)}}var y3=($)=>{let Z=0,Y=[];while(Z<$.length){let J=$[Z];if(J==="\\"){Z++;continue}if(J==="{"){Y.push({type:"brace",value:"{"}),Z++;continue}if(J==="}"){Y.push({type:"brace",value:"}"}),Z++;continue}if(J==="["){Y.push({type:"paren",value:"["}),Z++;continue}if(J==="]"){Y.push({type:"paren",value:"]"}),Z++;continue}if(J===":"){Y.push({type:"separator",value:":"}),Z++;continue}if(J===","){Y.push({type:"delimiter",value:","}),Z++;continue}if(J==='"'){let V="",G=!1;J=$[++Z];while(J!=='"'){if(Z===$.length){G=!0;break}if(J==="\\"){if(Z++,Z===$.length){G=!0;break}V+=J+$[Z],J=$[++Z]}else V+=J,J=$[++Z]}if(J=$[++Z],!G)Y.push({type:"string",value:V});continue}if(J&&/\s/.test(J)){Z++;continue}let z=/[0-9]/;if(J&&z.test(J)||J==="-"||J==="."){let V="";if(J==="-")V+=J,J=$[++Z];while(J&&z.test(J)||J===".")V+=J,J=$[++Z];Y.push({type:"number",value:V});continue}let Q=/[a-z]/i;if(J&&Q.test(J)){let V="";while(J&&Q.test(J)){if(Z===$.length)break;V+=J,J=$[++Z]}if(V=="true"||V=="false"||V==="null")Y.push({type:"name",value:V});else{Z++;continue}continue}Z++}return Y},n2=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),n2($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),n2($);case"string":let J=$[$.length-2];if(J?.type==="delimiter")return $=$.slice(0,$.length-1),n2($);else if(J?.type==="brace"&&J.value==="{")return $=$.slice(0,$.length-1),n2($);break;case"delimiter":return $=$.slice(0,$.length-1),n2($);break}return $},_3=($)=>{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 $},f3=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},f1=($)=>JSON.parse(f3(_3(n2(y3($)))));var J2,L2,o2,h$,h1,v$,g$,v1,c$,N2,d$,g1,c1,v2,d1,m1,m$,$6,a7,u1,Z6,Y6,J6,r7,s7="__json_buf";function t7($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class u${constructor($,Z){J2.add(this),this.messages=[],this.receivedMessages=[],L2.set(this,void 0),o2.set(this,null),this.controller=new AbortController,h$.set(this,void 0),h1.set(this,()=>{}),v$.set(this,()=>{}),g$.set(this,void 0),v1.set(this,()=>{}),c$.set(this,()=>{}),N2.set(this,{}),d$.set(this,!1),g1.set(this,!1),c1.set(this,!1),v2.set(this,!1),d1.set(this,void 0),m1.set(this,void 0),m$.set(this,void 0),u1.set(this,(Y)=>{if(j(this,g1,!0,"f"),U2(Y))Y=new p;if(Y instanceof p)return j(this,c1,!0,"f"),this._emit("abort",Y);if(Y instanceof E)return this._emit("error",Y);if(Y instanceof Error){let J=new E(Y.message);return J.cause=Y,this._emit("error",J)}return this._emit("error",new E(String(Y)))}),j(this,h$,new Promise((Y,J)=>{j(this,h1,Y,"f"),j(this,v$,J,"f")}),"f"),j(this,g$,new Promise((Y,J)=>{j(this,v1,Y,"f"),j(this,c$,J,"f")}),"f"),H(this,h$,"f").catch(()=>{}),H(this,g$,"f").catch(()=>{}),j(this,o2,$,"f"),j(this,m$,Z?.logger??console,"f")}get response(){return H(this,d1,"f")}get request_id(){return H(this,m1,"f")}async withResponse(){j(this,v2,!0,"f");let $=await H(this,h$,"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 u$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let X=new u$(Z,{logger:J});for(let z of Z.messages)X._addMessageParam(z);return j(X,o2,{...Z,stream:!0},"f"),X._run(()=>X._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),X}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},H(this,u1,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let J=Y?.signal,X;if(J){if(J.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),J.addEventListener("abort",X)}try{H(this,J2,"m",Z6).call(this);let{response:z,data:Q}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let V of Q)H(this,J2,"m",Y6).call(this,V);if(Q.controller.signal?.aborted)throw new p;H(this,J2,"m",J6).call(this)}finally{if(J&&X)J.removeEventListener("abort",X)}}_connected($){if(this.ended)return;j(this,d1,$,"f"),j(this,m1,$?.headers.get("request-id"),"f"),H(this,h1,"f").call(this,$),this._emit("connect")}get ended(){return H(this,d$,"f")}get errored(){return H(this,g1,"f")}get aborted(){return H(this,c1,"f")}abort(){this.controller.abort()}on($,Z){return(H(this,N2,"f")[$]||(H(this,N2,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=H(this,N2,"f")[$];if(!Y)return this;let J=Y.findIndex((X)=>X.listener===Z);if(J>=0)Y.splice(J,1);return this}once($,Z){return(H(this,N2,"f")[$]||(H(this,N2,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(j(this,v2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){j(this,v2,!0,"f"),await H(this,g$,"f")}get currentMessage(){return H(this,L2,"f")}async finalMessage(){return await this.done(),H(this,J2,"m",$6).call(this)}async finalText(){return await this.done(),H(this,J2,"m",a7).call(this)}_emit($,...Z){if(H(this,d$,"f"))return;if($==="end")j(this,d$,!0,"f"),H(this,v1,"f").call(this);let Y=H(this,N2,"f")[$];if(Y)H(this,N2,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!H(this,v2,"f")&&!Y?.length)Promise.reject(J);H(this,v$,"f").call(this,J),H(this,c$,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!H(this,v2,"f")&&!Y?.length)Promise.reject(J);H(this,v$,"f").call(this,J),H(this,c$,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",H(this,J2,"m",$6).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{H(this,J2,"m",Z6).call(this),this._connected(null);let X=e.fromReadableStream($,this.controller);for await(let z of X)H(this,J2,"m",Y6).call(this,z);if(X.controller.signal?.aborted)throw new p;H(this,J2,"m",J6).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(L2=new WeakMap,o2=new WeakMap,h$=new WeakMap,h1=new WeakMap,v$=new WeakMap,g$=new WeakMap,v1=new WeakMap,c$=new WeakMap,N2=new WeakMap,d$=new WeakMap,g1=new WeakMap,c1=new WeakMap,v2=new WeakMap,d1=new WeakMap,m1=new WeakMap,m$=new WeakMap,u1=new WeakMap,J2=new WeakSet,$6=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},a7=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(" ")},Z6=function(){if(this.ended)return;j(this,L2,void 0,"f")},Y6=function(Z){if(this.ended)return;let Y=H(this,J2,"m",r7).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let J=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(J.type==="text")this._emit("text",Z.delta.text,J.text||"");break}case"citations_delta":{if(J.type==="text")this._emit("citation",Z.delta.citation,J.citations??[]);break}case"input_json_delta":{if(t7(J)&&J.input)this._emit("inputJson",Z.delta.partial_json,J.input);break}case"thinking_delta":{if(J.type==="thinking")this._emit("thinking",Z.delta.thinking,J.thinking);break}case"signature_delta":{if(J.type==="thinking")this._emit("signature",J.signature);break}case"compaction_delta":{if(J.type==="compaction"&&J.content)this._emit("compaction",J.content);break}default:e7(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(t4(Y,H(this,o2,"f"),{logger:H(this,m$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{j(this,L2,Y,"f");break}case"content_block_start":case"message_delta":break}},J6=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let Z=H(this,L2,"f");if(!Z)throw new E("request ended without sending any chunks");return j(this,L2,void 0,"f"),t4(Z,H(this,o2,"f"),{logger:H(this,m$,"f")})},r7=function(Z){let Y=H(this,L2,"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 J=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(J?.type==="text")Y.content[Z.index]={...J,text:(J.text||"")+Z.delta.text};break}case"citations_delta":{if(J?.type==="text")Y.content[Z.index]={...J,citations:[...J.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(J&&t7(J)){let X=J[s7]||"";X+=Z.delta.partial_json;let z={...J};if(Object.defineProperty(z,s7,{value:X,enumerable:!1,writable:!0}),X)try{z.input=f1(X)}catch(Q){let V=new E(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${Q}. JSON: ${X}`);H(this,u1,"f").call(this,V)}Y.content[Z.index]=z}break}case"thinking_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,thinking:J.thinking+Z.delta.thinking};break}case"signature_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,signature:Z.delta.signature};break}case"compaction_delta":{if(J?.type==="compaction")Y.content[Z.index]={...J,content:(J.content||"")+Z.delta.content};break}default:e7(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(J)=>{let X=Z.shift();if(X)X.resolve(J);else $.push(J)}),this.on("end",()=>{Y=!0;for(let J of Z)J.resolve(void 0);Z.length=0}),this.on("abort",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),this.on("error",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((X,z)=>Z.push({resolve:X,reject:z})).then((X)=>X?{value:X,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 e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function e7($){}class a2 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 $8=1e5,Z8=`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:
52
+ ${K}
53
+ ${M}`)}return K},k=n3(_5);class N4 extends _{list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/files",M$,{query:J,...Z,headers:x([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(k`/v1/files/${$}`,{...Y,headers:x([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:J}=Z??{};return this._client.get(k`/v1/files/${$}/content`,{...Y,headers:x([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},Y?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},Y){let{betas:J}=Z??{};return this._client.get(k`/v1/files/${$}`,{...Y,headers:x([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/files",E1({body:J,...Z,headers:x([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},k5(J.file),Z?.headers])},this._client))}}class C4 extends _{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(k`/v1/models/${$}?beta=true`,{...Y,headers:x([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/models?beta=true",M$,{query:J,...Z,headers:x([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var A8={"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 h5($){return $?.output_format??$?.output_config?.format}function j2($,Z,Y){let J=h5(Z);if(!Z||!("parse"in(J??{})))return{...$,content:$.content.map((Q)=>{if(Q.type==="text"){let X=Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(X,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return Q}),parsed_output:null};return F2($,Z,Y)}function F2($,Z,Y){let J=null,Q=$.content.map((X)=>{if(X.type==="text"){let K=a3(Z,X.text);if(J===null)J=K;let V=Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1});return Object.defineProperty(V,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),K},enumerable:!1})}return X});return{...$,content:Q,parsed_output:J}}function a3($,Z){let Y=h5($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(J){throw new R(`Failed to parse structured output: ${J}`)}}var r3=($)=>{let Z=0,Y=[];while(Z<$.length){let J=$[Z];if(J==="\\"){Z++;continue}if(J==="{"){Y.push({type:"brace",value:"{"}),Z++;continue}if(J==="}"){Y.push({type:"brace",value:"}"}),Z++;continue}if(J==="["){Y.push({type:"paren",value:"["}),Z++;continue}if(J==="]"){Y.push({type:"paren",value:"]"}),Z++;continue}if(J===":"){Y.push({type:"separator",value:":"}),Z++;continue}if(J===","){Y.push({type:"delimiter",value:","}),Z++;continue}if(J==='"'){let V="",G=!1;J=$[++Z];while(J!=='"'){if(Z===$.length){G=!0;break}if(J==="\\"){if(Z++,Z===$.length){G=!0;break}V+=J+$[Z],J=$[++Z]}else V+=J,J=$[++Z]}if(J=$[++Z],!G)Y.push({type:"string",value:V});continue}if(J&&/\s/.test(J)){Z++;continue}let X=/[0-9]/;if(J&&X.test(J)||J==="-"||J==="."){let V="";if(J==="-")V+=J,J=$[++Z];while(J&&X.test(J)||J===".")V+=J,J=$[++Z];Y.push({type:"number",value:V});continue}let K=/[a-z]/i;if(J&&K.test(J)){let V="";while(J&&K.test(J)){if(Z===$.length)break;V+=J,J=$[++Z]}if(V=="true"||V=="false"||V==="null")Y.push({type:"name",value:V});else{Z++;continue}continue}Z++}return Y},L1=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),L1($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),L1($);case"string":let J=$[$.length-2];if(J?.type==="delimiter")return $=$.slice(0,$.length-1),L1($);else if(J?.type==="brace"&&J.value==="{")return $=$.slice(0,$.length-1),L1($);break;case"delimiter":return $=$.slice(0,$.length-1),L1($);break}return $},s3=($)=>{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 $},t3=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},x8=($)=>JSON.parse(t3(s3(L1(r3($)))));var H$,c$,j1,M4,D8,O4,E4,T8,L4,w$,j4,P8,w8,z1,I8,S8,F4,R2,f5,b8,A2,x2,D2,v5,g5="__json_buf";function m5($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class R4{constructor($,Z){H$.add(this),this.messages=[],this.receivedMessages=[],c$.set(this,void 0),j1.set(this,null),this.controller=new AbortController,M4.set(this,void 0),D8.set(this,()=>{}),O4.set(this,()=>{}),E4.set(this,void 0),T8.set(this,()=>{}),L4.set(this,()=>{}),w$.set(this,{}),j4.set(this,!1),P8.set(this,!1),w8.set(this,!1),z1.set(this,!1),I8.set(this,void 0),S8.set(this,void 0),F4.set(this,void 0),b8.set(this,(Y)=>{if(L(this,P8,!0,"f"),T$(Y))Y=new s;if(Y instanceof s)return L(this,w8,!0,"f"),this._emit("abort",Y);if(Y instanceof R)return this._emit("error",Y);if(Y instanceof Error){let J=new R(Y.message);return J.cause=Y,this._emit("error",J)}return this._emit("error",new R(String(Y)))}),L(this,M4,new Promise((Y,J)=>{L(this,D8,Y,"f"),L(this,O4,J,"f")}),"f"),L(this,E4,new Promise((Y,J)=>{L(this,T8,Y,"f"),L(this,L4,J,"f")}),"f"),U(this,M4,"f").catch(()=>{}),U(this,E4,"f").catch(()=>{}),L(this,j1,$,"f"),L(this,F4,Z?.logger??console,"f")}get response(){return U(this,I8,"f")}get request_id(){return U(this,S8,"f")}async withResponse(){L(this,z1,!0,"f");let $=await U(this,M4,"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 R4(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let Q=new R4(Z,{logger:J});for(let X of Z.messages)Q._addMessageParam(X);return L(Q,j1,{...Z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},U(this,b8,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let J=Y?.signal,Q;if(J){if(J.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),J.addEventListener("abort",Q)}try{U(this,H$,"m",A2).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)U(this,H$,"m",x2).call(this,V);if(K.controller.signal?.aborted)throw new s;U(this,H$,"m",D2).call(this)}finally{if(J&&Q)J.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,I8,$,"f"),L(this,S8,$?.headers.get("request-id"),"f"),U(this,D8,"f").call(this,$),this._emit("connect")}get ended(){return U(this,j4,"f")}get errored(){return U(this,P8,"f")}get aborted(){return U(this,w8,"f")}abort(){this.controller.abort()}on($,Z){return(U(this,w$,"f")[$]||(U(this,w$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=U(this,w$,"f")[$];if(!Y)return this;let J=Y.findIndex((Q)=>Q.listener===Z);if(J>=0)Y.splice(J,1);return this}once($,Z){return(U(this,w$,"f")[$]||(U(this,w$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(L(this,z1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){L(this,z1,!0,"f"),await U(this,E4,"f")}get currentMessage(){return U(this,c$,"f")}async finalMessage(){return await this.done(),U(this,H$,"m",R2).call(this)}async finalText(){return await this.done(),U(this,H$,"m",f5).call(this)}_emit($,...Z){if(U(this,j4,"f"))return;if($==="end")L(this,j4,!0,"f"),U(this,T8,"f").call(this);let Y=U(this,w$,"f")[$];if(Y)U(this,w$,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!U(this,z1,"f")&&!Y?.length)Promise.reject(J);U(this,O4,"f").call(this,J),U(this,L4,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!U(this,z1,"f")&&!Y?.length)Promise.reject(J);U(this,O4,"f").call(this,J),U(this,L4,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",U(this,H$,"m",R2).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{U(this,H$,"m",A2).call(this),this._connected(null);let Q=V$.fromReadableStream($,this.controller);for await(let X of Q)U(this,H$,"m",x2).call(this,X);if(Q.controller.signal?.aborted)throw new s;U(this,H$,"m",D2).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(c$=new WeakMap,j1=new WeakMap,M4=new WeakMap,D8=new WeakMap,O4=new WeakMap,E4=new WeakMap,T8=new WeakMap,L4=new WeakMap,w$=new WeakMap,j4=new WeakMap,P8=new WeakMap,w8=new WeakMap,z1=new WeakMap,I8=new WeakMap,S8=new WeakMap,F4=new WeakMap,b8=new WeakMap,H$=new WeakSet,R2=function(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},f5=function(){if(this.receivedMessages.length===0)throw new R("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 R("stream ended without producing a content block with type=text");return Z.join(" ")},A2=function(){if(this.ended)return;L(this,c$,void 0,"f")},x2=function(Z){if(this.ended)return;let Y=U(this,H$,"m",v5).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let J=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(J.type==="text")this._emit("text",Z.delta.text,J.text||"");break}case"citations_delta":{if(J.type==="text")this._emit("citation",Z.delta.citation,J.citations??[]);break}case"input_json_delta":{if(m5(J)&&J.input)this._emit("inputJson",Z.delta.partial_json,J.input);break}case"thinking_delta":{if(J.type==="thinking")this._emit("thinking",Z.delta.thinking,J.thinking);break}case"signature_delta":{if(J.type==="thinking")this._emit("signature",J.signature);break}case"compaction_delta":{if(J.type==="compaction"&&J.content)this._emit("compaction",J.content);break}default:c5(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(j2(Y,U(this,j1,"f"),{logger:U(this,F4,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{L(this,c$,Y,"f");break}case"content_block_start":case"message_delta":break}},D2=function(){if(this.ended)throw new R("stream has ended, this shouldn't happen");let Z=U(this,c$,"f");if(!Z)throw new R("request ended without sending any chunks");return L(this,c$,void 0,"f"),j2(Z,U(this,j1,"f"),{logger:U(this,F4,"f")})},v5=function(Z){let Y=U(this,c$,"f");if(Z.type==="message_start"){if(Y)throw new R(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new R(`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 J=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(J?.type==="text")Y.content[Z.index]={...J,text:(J.text||"")+Z.delta.text};break}case"citations_delta":{if(J?.type==="text")Y.content[Z.index]={...J,citations:[...J.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(J&&m5(J)){let Q=J[g5]||"";Q+=Z.delta.partial_json;let X={...J};if(Object.defineProperty(X,g5,{value:Q,enumerable:!1,writable:!0}),Q)try{X.input=x8(Q)}catch(K){let V=new R(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${K}. JSON: ${Q}`);U(this,b8,"f").call(this,V)}Y.content[Z.index]=X}break}case"thinking_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,thinking:J.thinking+Z.delta.thinking};break}case"signature_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,signature:Z.delta.signature};break}case"compaction_delta":{if(J?.type==="compaction")Y.content[Z.index]={...J,content:(J.content||"")+Z.delta.content};break}default:c5(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(J)=>{let Q=Z.shift();if(Q)Q.resolve(J);else $.push(J)}),this.on("end",()=>{Y=!0;for(let J of Z)J.resolve(void 0);Z.length=0}),this.on("abort",(J)=>{Y=!0;for(let Q of Z)Q.reject(J);Z.length=0}),this.on("error",(J)=>{Y=!0;for(let Q of Z)Q.reject(J);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((Q,X)=>Z.push({resolve:Q,reject:X})).then((Q)=>Q?{value:Q,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new V$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function c5($){}class F1 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 d5=1e5,u5=`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:
50
54
  1. Task Overview
51
55
  The user's core request and success criteria
52
56
  Any clarifications or constraints they specified
@@ -68,111 +72,234 @@ User preferences or style requirements
68
72
  Domain-specific details that aren't obvious
69
73
  Any promises made to the user
70
74
  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.
71
- Wrap your summary in <summary></summary> tags.`;var p$,r2,g2,c,l$,$2,C2,R2,i$,Y8,X6;function J8(){let $,Z;return{promise:new Promise((J,X)=>{$=J,Z=X}),resolve:$,reject:Z}}class n${constructor($,Z,Y){p$.add(this),this.client=$,r2.set(this,!1),g2.set(this,!1),c.set(this,void 0),l$.set(this,void 0),$2.set(this,void 0),C2.set(this,void 0),R2.set(this,void 0),i$.set(this,0),j(this,c,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let X=["BetaToolRunner",...s4(Z.tools,Z.messages)].join(", ");j(this,l$,{...Y,headers:R([{"x-stainless-helper":X},Y?.headers])},"f"),j(this,R2,J8(),"f")}async*[(r2=new WeakMap,g2=new WeakMap,c=new WeakMap,l$=new WeakMap,$2=new WeakMap,C2=new WeakMap,R2=new WeakMap,i$=new WeakMap,p$=new WeakSet,Y8=async function(){let Z=H(this,c,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(H(this,$2,"f")!==void 0)try{let G=await H(this,$2,"f");Y=G.usage.input_tokens+(G.usage.cache_creation_input_tokens??0)+(G.usage.cache_read_input_tokens??0)+G.usage.output_tokens}catch{return!1}let J=Z.contextTokenThreshold??$8;if(Y<J)return!1;let X=Z.model??H(this,c,"f").params.model,z=Z.summaryPrompt??Z8,Q=H(this,c,"f").params.messages;if(Q[Q.length-1].role==="assistant"){let G=Q[Q.length-1];if(Array.isArray(G.content)){let q=G.content.filter((K)=>K.type!=="tool_use");if(q.length===0)Q.pop();else G.content=q}}let V=await this.client.beta.messages.create({model:X,messages:[...Q,{role:"user",content:[{type:"text",text:z}]}],max_tokens:H(this,c,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(V.content[0]?.type!=="text")throw new E("Expected text response for compaction");return H(this,c,"f").params.messages=[{role:"user",content:V.content}],!0},Symbol.asyncIterator)](){var $;if(H(this,r2,"f"))throw new E("Cannot iterate over a consumed stream");j(this,r2,!0,"f"),j(this,g2,!0,"f"),j(this,C2,void 0,"f");try{while(!0){let Z;try{if(H(this,c,"f").params.max_iterations&&H(this,i$,"f")>=H(this,c,"f").params.max_iterations)break;j(this,g2,!1,"f"),j(this,C2,void 0,"f"),j(this,i$,($=H(this,i$,"f"),$++,$),"f"),j(this,$2,void 0,"f");let{max_iterations:Y,compactionControl:J,...X}=H(this,c,"f").params;if(X.stream)Z=this.client.beta.messages.stream({...X},H(this,l$,"f")),j(this,$2,Z.finalMessage(),"f"),H(this,$2,"f").catch(()=>{}),yield Z;else j(this,$2,this.client.beta.messages.create({...X,stream:!1},H(this,l$,"f")),"f"),yield H(this,$2,"f");if(!await H(this,p$,"m",Y8).call(this)){if(!H(this,g2,"f")){let{role:V,content:G}=await H(this,$2,"f");H(this,c,"f").params.messages.push({role:V,content:G})}let Q=await H(this,p$,"m",X6).call(this,H(this,c,"f").params.messages.at(-1));if(Q)H(this,c,"f").params.messages.push(Q);else if(!H(this,g2,"f"))break}}finally{if(Z)Z.abort()}}if(!H(this,$2,"f"))throw new E("ToolRunner concluded without a message from the server");H(this,R2,"f").resolve(await H(this,$2,"f"))}catch(Z){throw j(this,r2,!1,"f"),H(this,R2,"f").promise.catch(()=>{}),H(this,R2,"f").reject(Z),j(this,R2,J8(),"f"),Z}}setMessagesParams($){if(typeof $==="function")H(this,c,"f").params=$(H(this,c,"f").params);else H(this,c,"f").params=$;j(this,g2,!0,"f"),j(this,C2,void 0,"f")}async generateToolResponse(){let $=await H(this,$2,"f")??this.params.messages.at(-1);if(!$)return null;return H(this,p$,"m",X6).call(this,$)}done(){return H(this,R2,"f").promise}async runUntilDone(){if(!H(this,r2,"f"))for await(let $ of this);return this.done()}get params(){return H(this,c,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}X6=async function(Z){if(H(this,C2,"f")!==void 0)return H(this,C2,"f");return j(this,C2,h3(H(this,c,"f").params,Z),"f"),H(this,C2,"f")};async function h3($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let Y=Z.content.filter((X)=>X.type==="tool_use");if(Y.length===0)return null;return{role:"user",content:await Promise.all(Y.map(async(X)=>{let z=$.tools.find((Q)=>("name"in Q?Q.name:Q.mcp_server_name)===X.name);if(!z||!("run"in z))return{type:"tool_result",tool_use_id:X.id,content:`Error: Tool '${X.name}' not found`,is_error:!0};try{let Q=X.input;if("parse"in z&&z.parse)Q=z.parse(Q);let V=await z.run(Q);return{type:"tool_result",tool_use_id:X.id,content:V}}catch(Q){return{type:"tool_result",tool_use_id:X.id,content:Q instanceof a2?Q.content:`Error: ${Q instanceof Error?Q.message:String(Q)}`,is_error:!0}}}))}}class s2{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new M2;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 s2(w$($.body),Z)}}class o$ extends b{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/messages/batches?beta=true",{body:J,...Z,headers:R([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(S`/v1/messages/batches/${$}?beta=true`,{...Y,headers:R([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",Q2,{query:J,...Z,headers:R([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(S`/v1/messages/batches/${$}?beta=true`,{...Y,headers:R([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:J}=Z??{};return this._client.post(S`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:R([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}async results($,Z={},Y){let J=await this.retrieve($);if(!J.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${J.processing_status} - ${J.id}`);let{betas:X}=Z??{};return this._client.get(J.results_url,{...Y,headers:R([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((z,Q)=>s2.fromResponse(Q.response,Q.controller))}}var X8={"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"},g3=["claude-opus-4-6"];class x2 extends b{constructor(){super(...arguments);this.batches=new o$(this._client)}create($,Z){let Y=z8($),{betas:J,...X}=Y;if(X.model in X8)console.warn(`The model '${X.model}' is deprecated and will reach end-of-life on ${X8[X.model]}
72
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(X.model in g3&&X.thinking&&X.thinking.type==="enabled")console.warn(`Using Claude with ${X.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(!X.stream&&z==null){let V=_1[X.model]??void 0;z=this._client.calculateNonstreamingTimeout(X.max_tokens,V)}let Q=y1(X.tools,X.messages);return this._client.post("/v1/messages?beta=true",{body:X,timeout:z??600000,...Z,headers:R([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Q,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:R([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>e4(Y,$,{logger:this._client.logger??console}))}stream($,Z){return u$.createMessage(this,$,Z)}countTokens($,Z){let Y=z8($),{betas:J,...X}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:X,...Z,headers:R([{"anthropic-beta":[...J??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new n$(this._client,$,Z)}}function z8($){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}}}x2.Batches=o$;x2.BetaToolRunner=n$;x2.ToolError=a2;class a$ extends b{create($,Z={},Y){let{betas:J,...X}=Z??{};return this._client.post(S`/v1/skills/${$}/versions?beta=true`,i2({body:X,...Y,headers:R([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve($,Z,Y){let{skill_id:J,betas:X}=Z;return this._client.get(S`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:R([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:J,...X}=Z??{};return this._client.getAPIList(S`/v1/skills/${$}/versions?beta=true`,k$,{query:X,...Y,headers:R([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:J,betas:X}=Z;return this._client.delete(S`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:R([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class t2 extends b{constructor(){super(...arguments);this.versions=new a$(this._client)}create($={},Z){let{betas:Y,...J}=$??{};return this._client.post("/v1/skills?beta=true",i2({body:J,...Z,headers:R([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(S`/v1/skills/${$}?beta=true`,{...Y,headers:R([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/skills?beta=true",k$,{query:J,...Z,headers:R([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(S`/v1/skills/${$}?beta=true`,{...Y,headers:R([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}}t2.Versions=a$;class G2 extends b{constructor(){super(...arguments);this.models=new f$(this._client),this.messages=new x2(this._client),this.files=new _$(this._client),this.skills=new t2(this._client)}}G2.Models=f$;G2.Messages=x2;G2.Files=_$;G2.Skills=t2;class e2 extends b{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/complete",{body:J,timeout:this._client._options.timeout??600000,...Z,headers:R([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function Q8($){return $?.output_config?.format}function z6($,Z,Y){let J=Q8(Z);if(!Z||!("parse"in(J??{})))return{...$,content:$.content.map((X)=>{if(X.type==="text")return Object.defineProperty({...X},"parsed_output",{value:null,enumerable:!1});return X}),parsed_output:null};return Q6($,Z,Y)}function Q6($,Z,Y){let J=null,X=$.content.map((z)=>{if(z.type==="text"){let Q=u3(Z,z.text);if(J===null)J=Q;return Object.defineProperty({...z},"parsed_output",{value:Q,enumerable:!1})}return z});return{...$,content:X,parsed_output:J}}function u3($,Z){let Y=Q8($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(J){throw new E(`Failed to parse structured output: ${J}`)}}var X2,D2,$$,r$,p1,s$,t$,l1,e$,j2,$1,i1,n1,c2,o1,a1,Z1,K6,K8,V6,G6,W6,q6,V8,G8="__json_buf";function W8($){return $.type==="tool_use"||$.type==="server_tool_use"}class Y1{constructor($,Z){X2.add(this),this.messages=[],this.receivedMessages=[],D2.set(this,void 0),$$.set(this,null),this.controller=new AbortController,r$.set(this,void 0),p1.set(this,()=>{}),s$.set(this,()=>{}),t$.set(this,void 0),l1.set(this,()=>{}),e$.set(this,()=>{}),j2.set(this,{}),$1.set(this,!1),i1.set(this,!1),n1.set(this,!1),c2.set(this,!1),o1.set(this,void 0),a1.set(this,void 0),Z1.set(this,void 0),V6.set(this,(Y)=>{if(j(this,i1,!0,"f"),U2(Y))Y=new p;if(Y instanceof p)return j(this,n1,!0,"f"),this._emit("abort",Y);if(Y instanceof E)return this._emit("error",Y);if(Y instanceof Error){let J=new E(Y.message);return J.cause=Y,this._emit("error",J)}return this._emit("error",new E(String(Y)))}),j(this,r$,new Promise((Y,J)=>{j(this,p1,Y,"f"),j(this,s$,J,"f")}),"f"),j(this,t$,new Promise((Y,J)=>{j(this,l1,Y,"f"),j(this,e$,J,"f")}),"f"),H(this,r$,"f").catch(()=>{}),H(this,t$,"f").catch(()=>{}),j(this,$$,$,"f"),j(this,Z1,Z?.logger??console,"f")}get response(){return H(this,o1,"f")}get request_id(){return H(this,a1,"f")}async withResponse(){j(this,c2,!0,"f");let $=await H(this,r$,"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 Y1(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let X=new Y1(Z,{logger:J});for(let z of Z.messages)X._addMessageParam(z);return j(X,$$,{...Z,stream:!0},"f"),X._run(()=>X._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),X}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},H(this,V6,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let J=Y?.signal,X;if(J){if(J.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),J.addEventListener("abort",X)}try{H(this,X2,"m",G6).call(this);let{response:z,data:Q}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let V of Q)H(this,X2,"m",W6).call(this,V);if(Q.controller.signal?.aborted)throw new p;H(this,X2,"m",q6).call(this)}finally{if(J&&X)J.removeEventListener("abort",X)}}_connected($){if(this.ended)return;j(this,o1,$,"f"),j(this,a1,$?.headers.get("request-id"),"f"),H(this,p1,"f").call(this,$),this._emit("connect")}get ended(){return H(this,$1,"f")}get errored(){return H(this,i1,"f")}get aborted(){return H(this,n1,"f")}abort(){this.controller.abort()}on($,Z){return(H(this,j2,"f")[$]||(H(this,j2,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=H(this,j2,"f")[$];if(!Y)return this;let J=Y.findIndex((X)=>X.listener===Z);if(J>=0)Y.splice(J,1);return this}once($,Z){return(H(this,j2,"f")[$]||(H(this,j2,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(j(this,c2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){j(this,c2,!0,"f"),await H(this,t$,"f")}get currentMessage(){return H(this,D2,"f")}async finalMessage(){return await this.done(),H(this,X2,"m",K6).call(this)}async finalText(){return await this.done(),H(this,X2,"m",K8).call(this)}_emit($,...Z){if(H(this,$1,"f"))return;if($==="end")j(this,$1,!0,"f"),H(this,l1,"f").call(this);let Y=H(this,j2,"f")[$];if(Y)H(this,j2,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!H(this,c2,"f")&&!Y?.length)Promise.reject(J);H(this,s$,"f").call(this,J),H(this,e$,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!H(this,c2,"f")&&!Y?.length)Promise.reject(J);H(this,s$,"f").call(this,J),H(this,e$,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",H(this,X2,"m",K6).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{H(this,X2,"m",G6).call(this),this._connected(null);let X=e.fromReadableStream($,this.controller);for await(let z of X)H(this,X2,"m",W6).call(this,z);if(X.controller.signal?.aborted)throw new p;H(this,X2,"m",q6).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(D2=new WeakMap,$$=new WeakMap,r$=new WeakMap,p1=new WeakMap,s$=new WeakMap,t$=new WeakMap,l1=new WeakMap,e$=new WeakMap,j2=new WeakMap,$1=new WeakMap,i1=new WeakMap,n1=new WeakMap,c2=new WeakMap,o1=new WeakMap,a1=new WeakMap,Z1=new WeakMap,V6=new WeakMap,X2=new WeakSet,K6=function(){if(this.receivedMessages.length===0)throw new E("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},K8=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(" ")},G6=function(){if(this.ended)return;j(this,D2,void 0,"f")},W6=function(Z){if(this.ended)return;let Y=H(this,X2,"m",V8).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let J=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(J.type==="text")this._emit("text",Z.delta.text,J.text||"");break}case"citations_delta":{if(J.type==="text")this._emit("citation",Z.delta.citation,J.citations??[]);break}case"input_json_delta":{if(W8(J)&&J.input)this._emit("inputJson",Z.delta.partial_json,J.input);break}case"thinking_delta":{if(J.type==="thinking")this._emit("thinking",Z.delta.thinking,J.thinking);break}case"signature_delta":{if(J.type==="thinking")this._emit("signature",J.signature);break}default:q8(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(z6(Y,H(this,$$,"f"),{logger:H(this,Z1,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{j(this,D2,Y,"f");break}case"content_block_start":case"message_delta":break}},q6=function(){if(this.ended)throw new E("stream has ended, this shouldn't happen");let Z=H(this,D2,"f");if(!Z)throw new E("request ended without sending any chunks");return j(this,D2,void 0,"f"),z6(Z,H(this,$$,"f"),{logger:H(this,Z1,"f")})},V8=function(Z){let Y=H(this,D2,"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 J=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(J?.type==="text")Y.content[Z.index]={...J,text:(J.text||"")+Z.delta.text};break}case"citations_delta":{if(J?.type==="text")Y.content[Z.index]={...J,citations:[...J.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(J&&W8(J)){let X=J[G8]||"";X+=Z.delta.partial_json;let z={...J};if(Object.defineProperty(z,G8,{value:X,enumerable:!1,writable:!0}),X)z.input=f1(X);Y.content[Z.index]=z}break}case"thinking_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,thinking:J.thinking+Z.delta.thinking};break}case"signature_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,signature:Z.delta.signature};break}default:q8(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(J)=>{let X=Z.shift();if(X)X.resolve(J);else $.push(J)}),this.on("end",()=>{Y=!0;for(let J of Z)J.resolve(void 0);Z.length=0}),this.on("abort",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),this.on("error",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((X,z)=>Z.push({resolve:X,reject:z})).then((X)=>X?{value:X,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 e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function q8($){}class J1 extends b{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(S`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",Q2,{query:$,...Z})}delete($,Z){return this._client.delete(S`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(S`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new E(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:R([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,X)=>s2.fromResponse(X.response,X.controller))}}class d2 extends b{constructor(){super(...arguments);this.batches=new J1(this._client)}create($,Z){if($.model in H8)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${H8[$.model]}
73
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in l3&&$.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 X=_1[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,X)}let J=y1($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:R([J,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>Q6(Y,$,{logger:this._client.logger??console}))}stream($,Z){return Y1.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var H8={"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"},l3=["claude-opus-4-6"];d2.Batches=J1;class Z$ extends b{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(S`/v1/models/${$}`,{...Y,headers:R([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/models",Q2,{query:J,...Z,headers:R([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var X1=($)=>{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 H6,U6,r1,U8,B8="\\n\\nHuman:",N8="\\n\\nAssistant:";class y{constructor({baseURL:$=X1("ANTHROPIC_BASE_URL"),apiKey:Z=X1("ANTHROPIC_API_KEY")??null,authToken:Y=X1("ANTHROPIC_AUTH_TOKEN")??null,...J}={}){H6.add(this),r1.set(this,void 0);let X={apiKey:Z,authToken:Y,...J,baseURL:$||"https://api.anthropic.com"};if(!X.dangerouslyAllowBrowser&&I7())throw new E(`It looks like you're running in a browser-like environment.
75
+ Wrap your summary in <summary></summary> tags.`;var A4,R1,V1,d,x4,G$,I$,d$,D4,p5,T2;function l5(){let $,Z;return{promise:new Promise((J,Q)=>{$=J,Z=Q}),resolve:$,reject:Z}}class T4{constructor($,Z,Y){A4.add(this),this.client=$,R1.set(this,!1),V1.set(this,!1),d.set(this,void 0),x4.set(this,void 0),G$.set(this,void 0),I$.set(this,void 0),d$.set(this,void 0),D4.set(this,0),L(this,d,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let Q=["BetaToolRunner",...L2(Z.tools,Z.messages)].join(", ");L(this,x4,{...Y,headers:x([{"x-stainless-helper":Q},Y?.headers])},"f"),L(this,d$,l5(),"f")}async*[(R1=new WeakMap,V1=new WeakMap,d=new WeakMap,x4=new WeakMap,G$=new WeakMap,I$=new WeakMap,d$=new WeakMap,D4=new WeakMap,A4=new WeakSet,p5=async function(){let Z=U(this,d,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(U(this,G$,"f")!==void 0)try{let G=await U(this,G$,"f");Y=G.usage.input_tokens+(G.usage.cache_creation_input_tokens??0)+(G.usage.cache_read_input_tokens??0)+G.usage.output_tokens}catch{return!1}let J=Z.contextTokenThreshold??d5;if(Y<J)return!1;let Q=Z.model??U(this,d,"f").params.model,X=Z.summaryPrompt??u5,K=U(this,d,"f").params.messages;if(K[K.length-1].role==="assistant"){let G=K[K.length-1];if(Array.isArray(G.content)){let H=G.content.filter((z)=>z.type!=="tool_use");if(H.length===0)K.pop();else G.content=H}}let V=await this.client.beta.messages.create({model:Q,messages:[...K,{role:"user",content:[{type:"text",text:X}]}],max_tokens:U(this,d,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(V.content[0]?.type!=="text")throw new R("Expected text response for compaction");return U(this,d,"f").params.messages=[{role:"user",content:V.content}],!0},Symbol.asyncIterator)](){var $;if(U(this,R1,"f"))throw new R("Cannot iterate over a consumed stream");L(this,R1,!0,"f"),L(this,V1,!0,"f"),L(this,I$,void 0,"f");try{while(!0){let Z;try{if(U(this,d,"f").params.max_iterations&&U(this,D4,"f")>=U(this,d,"f").params.max_iterations)break;L(this,V1,!1,"f"),L(this,I$,void 0,"f"),L(this,D4,($=U(this,D4,"f"),$++,$),"f"),L(this,G$,void 0,"f");let{max_iterations:Y,compactionControl:J,...Q}=U(this,d,"f").params;if(Q.stream)Z=this.client.beta.messages.stream({...Q},U(this,x4,"f")),L(this,G$,Z.finalMessage(),"f"),U(this,G$,"f").catch(()=>{}),yield Z;else L(this,G$,this.client.beta.messages.create({...Q,stream:!1},U(this,x4,"f")),"f"),yield U(this,G$,"f");if(!await U(this,A4,"m",p5).call(this)){if(!U(this,V1,"f")){let{role:V,content:G}=await U(this,G$,"f");U(this,d,"f").params.messages.push({role:V,content:G})}let K=await U(this,A4,"m",T2).call(this,U(this,d,"f").params.messages.at(-1));if(K)U(this,d,"f").params.messages.push(K);else if(!U(this,V1,"f"))break}}finally{if(Z)Z.abort()}}if(!U(this,G$,"f"))throw new R("ToolRunner concluded without a message from the server");U(this,d$,"f").resolve(await U(this,G$,"f"))}catch(Z){throw L(this,R1,!1,"f"),U(this,d$,"f").promise.catch(()=>{}),U(this,d$,"f").reject(Z),L(this,d$,l5(),"f"),Z}}setMessagesParams($){if(typeof $==="function")U(this,d,"f").params=$(U(this,d,"f").params);else U(this,d,"f").params=$;L(this,V1,!0,"f"),L(this,I$,void 0,"f")}async generateToolResponse(){let $=await U(this,G$,"f")??this.params.messages.at(-1);if(!$)return null;return U(this,A4,"m",T2).call(this,$)}done(){return U(this,d$,"f").promise}async runUntilDone(){if(!U(this,R1,"f"))for await(let $ of this);return this.done()}get params(){return U(this,d,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}T2=async function(Z){if(U(this,I$,"f")!==void 0)return U(this,I$,"f");return L(this,I$,e3(U(this,d,"f").params,Z),"f"),U(this,I$,"f")};async function e3($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let Y=Z.content.filter((Q)=>Q.type==="tool_use");if(Y.length===0)return null;return{role:"user",content:await Promise.all(Y.map(async(Q)=>{let X=$.tools.find((K)=>("name"in K?K.name:K.mcp_server_name)===Q.name);if(!X||!("run"in X))return{type:"tool_result",tool_use_id:Q.id,content:`Error: Tool '${Q.name}' not found`,is_error:!0};try{let K=Q.input;if("parse"in X&&X.parse)K=X.parse(K);let V=await X.run(K);return{type:"tool_result",tool_use_id:Q.id,content:V}}catch(K){return{type:"tool_result",tool_use_id:Q.id,content:K instanceof F1?K.content:`Error: ${K instanceof Error?K.message:String(K)}`,is_error:!0}}}))}}class A1{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new m$;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 R("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 R("Attempted to iterate over a response with no body")}return new A1(z4($.body),Z)}}class P4 extends _{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/messages/batches?beta=true",{body:J,...Z,headers:x([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(k`/v1/messages/batches/${$}?beta=true`,{...Y,headers:x([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",M$,{query:J,...Z,headers:x([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(k`/v1/messages/batches/${$}?beta=true`,{...Y,headers:x([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:J}=Z??{};return this._client.post(k`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:x([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}async results($,Z={},Y){let J=await this.retrieve($);if(!J.results_url)throw new R(`No batch \`results_url\`; Has it finished processing? ${J.processing_status} - ${J.id}`);let{betas:Q}=Z??{};return this._client.get(J.results_url,{...Y,headers:x([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((X,K)=>A1.fromResponse(K.response,K.controller))}}var n5={"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"},ZY=["claude-opus-4-6"];class u$ extends _{constructor(){super(...arguments);this.batches=new P4(this._client)}create($,Z){let Y=i5($),{betas:J,...Q}=Y;if(Q.model in n5)console.warn(`The model '${Q.model}' is deprecated and will reach end-of-life on ${n5[Q.model]}
76
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Q.model in ZY&&Q.thinking&&Q.thinking.type==="enabled")console.warn(`Using Claude with ${Q.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let X=this._client._options.timeout;if(!Q.stream&&X==null){let V=A8[Q.model]??void 0;X=this._client.calculateNonstreamingTimeout(Q.max_tokens,V)}let K=R8(Q.tools,Q.messages);return this._client.post("/v1/messages?beta=true",{body:Q,timeout:X??600000,...Z,headers:x([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},K,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:x([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>F2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return R4.createMessage(this,$,Z)}countTokens($,Z){let Y=i5($),{betas:J,...Q}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...Z,headers:x([{"anthropic-beta":[...J??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new T4(this._client,$,Z)}}function i5($){if(!$.output_format)return $;if($.output_config?.format)throw new R("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}}}u$.Batches=P4;u$.BetaToolRunner=T4;u$.ToolError=F1;class w4 extends _{create($,Z={},Y){let{betas:J,...Q}=Z??{};return this._client.post(k`/v1/skills/${$}/versions?beta=true`,E1({body:Q,...Y,headers:x([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve($,Z,Y){let{skill_id:J,betas:Q}=Z;return this._client.get(k`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:x([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:J,...Q}=Z??{};return this._client.getAPIList(k`/v1/skills/${$}/versions?beta=true`,q4,{query:Q,...Y,headers:x([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:J,betas:Q}=Z;return this._client.delete(k`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:x([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class x1 extends _{constructor(){super(...arguments);this.versions=new w4(this._client)}create($={},Z){let{betas:Y,...J}=$??{};return this._client.post("/v1/skills?beta=true",E1({body:J,...Z,headers:x([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(k`/v1/skills/${$}?beta=true`,{...Y,headers:x([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/skills?beta=true",q4,{query:J,...Z,headers:x([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(k`/v1/skills/${$}?beta=true`,{...Y,headers:x([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}}x1.Versions=w4;class L$ extends _{constructor(){super(...arguments);this.models=new C4(this._client),this.messages=new u$(this._client),this.files=new N4(this._client),this.skills=new x1(this._client)}}L$.Models=C4;L$.Messages=u$;L$.Files=N4;L$.Skills=x1;class D1 extends _{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/complete",{body:J,timeout:this._client._options.timeout??600000,...Z,headers:x([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function o5($){return $?.output_config?.format}function P2($,Z,Y){let J=o5(Z);if(!Z||!("parse"in(J??{})))return{...$,content:$.content.map((Q)=>{if(Q.type==="text")return Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Q}),parsed_output:null};return w2($,Z,Y)}function w2($,Z,Y){let J=null,Q=$.content.map((X)=>{if(X.type==="text"){let K=XY(Z,X.text);if(J===null)J=K;return Object.defineProperty({...X},"parsed_output",{value:K,enumerable:!1})}return X});return{...$,content:Q,parsed_output:J}}function XY($,Z){let Y=o5($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(J){throw new R(`Failed to parse structured output: ${J}`)}}var q$,p$,T1,I4,k8,S4,b4,y8,k4,S$,y4,_8,h8,G1,f8,v8,_4,I2,a5,S2,b2,k2,y2,r5,s5="__json_buf";function t5($){return $.type==="tool_use"||$.type==="server_tool_use"}class h4{constructor($,Z){q$.add(this),this.messages=[],this.receivedMessages=[],p$.set(this,void 0),T1.set(this,null),this.controller=new AbortController,I4.set(this,void 0),k8.set(this,()=>{}),S4.set(this,()=>{}),b4.set(this,void 0),y8.set(this,()=>{}),k4.set(this,()=>{}),S$.set(this,{}),y4.set(this,!1),_8.set(this,!1),h8.set(this,!1),G1.set(this,!1),f8.set(this,void 0),v8.set(this,void 0),_4.set(this,void 0),S2.set(this,(Y)=>{if(L(this,_8,!0,"f"),T$(Y))Y=new s;if(Y instanceof s)return L(this,h8,!0,"f"),this._emit("abort",Y);if(Y instanceof R)return this._emit("error",Y);if(Y instanceof Error){let J=new R(Y.message);return J.cause=Y,this._emit("error",J)}return this._emit("error",new R(String(Y)))}),L(this,I4,new Promise((Y,J)=>{L(this,k8,Y,"f"),L(this,S4,J,"f")}),"f"),L(this,b4,new Promise((Y,J)=>{L(this,y8,Y,"f"),L(this,k4,J,"f")}),"f"),U(this,I4,"f").catch(()=>{}),U(this,b4,"f").catch(()=>{}),L(this,T1,$,"f"),L(this,_4,Z?.logger??console,"f")}get response(){return U(this,f8,"f")}get request_id(){return U(this,v8,"f")}async withResponse(){L(this,G1,!0,"f");let $=await U(this,I4,"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 h4(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let Q=new h4(Z,{logger:J});for(let X of Z.messages)Q._addMessageParam(X);return L(Q,T1,{...Z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},U(this,S2,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let J=Y?.signal,Q;if(J){if(J.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),J.addEventListener("abort",Q)}try{U(this,q$,"m",b2).call(this);let{response:X,data:K}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(X);for await(let V of K)U(this,q$,"m",k2).call(this,V);if(K.controller.signal?.aborted)throw new s;U(this,q$,"m",y2).call(this)}finally{if(J&&Q)J.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,f8,$,"f"),L(this,v8,$?.headers.get("request-id"),"f"),U(this,k8,"f").call(this,$),this._emit("connect")}get ended(){return U(this,y4,"f")}get errored(){return U(this,_8,"f")}get aborted(){return U(this,h8,"f")}abort(){this.controller.abort()}on($,Z){return(U(this,S$,"f")[$]||(U(this,S$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=U(this,S$,"f")[$];if(!Y)return this;let J=Y.findIndex((Q)=>Q.listener===Z);if(J>=0)Y.splice(J,1);return this}once($,Z){return(U(this,S$,"f")[$]||(U(this,S$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(L(this,G1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){L(this,G1,!0,"f"),await U(this,b4,"f")}get currentMessage(){return U(this,p$,"f")}async finalMessage(){return await this.done(),U(this,q$,"m",I2).call(this)}async finalText(){return await this.done(),U(this,q$,"m",a5).call(this)}_emit($,...Z){if(U(this,y4,"f"))return;if($==="end")L(this,y4,!0,"f"),U(this,y8,"f").call(this);let Y=U(this,S$,"f")[$];if(Y)U(this,S$,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!U(this,G1,"f")&&!Y?.length)Promise.reject(J);U(this,S4,"f").call(this,J),U(this,k4,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!U(this,G1,"f")&&!Y?.length)Promise.reject(J);U(this,S4,"f").call(this,J),U(this,k4,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",U(this,q$,"m",I2).call(this))}async _fromReadableStream($,Z){let Y=Z?.signal,J;if(Y){if(Y.aborted)this.controller.abort();J=this.controller.abort.bind(this.controller),Y.addEventListener("abort",J)}try{U(this,q$,"m",b2).call(this),this._connected(null);let Q=V$.fromReadableStream($,this.controller);for await(let X of Q)U(this,q$,"m",k2).call(this,X);if(Q.controller.signal?.aborted)throw new s;U(this,q$,"m",y2).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(p$=new WeakMap,T1=new WeakMap,I4=new WeakMap,k8=new WeakMap,S4=new WeakMap,b4=new WeakMap,y8=new WeakMap,k4=new WeakMap,S$=new WeakMap,y4=new WeakMap,_8=new WeakMap,h8=new WeakMap,G1=new WeakMap,f8=new WeakMap,v8=new WeakMap,_4=new WeakMap,S2=new WeakMap,q$=new WeakSet,I2=function(){if(this.receivedMessages.length===0)throw new R("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},a5=function(){if(this.receivedMessages.length===0)throw new R("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 R("stream ended without producing a content block with type=text");return Z.join(" ")},b2=function(){if(this.ended)return;L(this,p$,void 0,"f")},k2=function(Z){if(this.ended)return;let Y=U(this,q$,"m",r5).call(this,Z);switch(this._emit("streamEvent",Z,Y),Z.type){case"content_block_delta":{let J=Y.content.at(-1);switch(Z.delta.type){case"text_delta":{if(J.type==="text")this._emit("text",Z.delta.text,J.text||"");break}case"citations_delta":{if(J.type==="text")this._emit("citation",Z.delta.citation,J.citations??[]);break}case"input_json_delta":{if(t5(J)&&J.input)this._emit("inputJson",Z.delta.partial_json,J.input);break}case"thinking_delta":{if(J.type==="thinking")this._emit("thinking",Z.delta.thinking,J.thinking);break}case"signature_delta":{if(J.type==="thinking")this._emit("signature",J.signature);break}default:e5(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(P2(Y,U(this,T1,"f"),{logger:U(this,_4,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{L(this,p$,Y,"f");break}case"content_block_start":case"message_delta":break}},y2=function(){if(this.ended)throw new R("stream has ended, this shouldn't happen");let Z=U(this,p$,"f");if(!Z)throw new R("request ended without sending any chunks");return L(this,p$,void 0,"f"),P2(Z,U(this,T1,"f"),{logger:U(this,_4,"f")})},r5=function(Z){let Y=U(this,p$,"f");if(Z.type==="message_start"){if(Y)throw new R(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new R(`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 J=Y.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(J?.type==="text")Y.content[Z.index]={...J,text:(J.text||"")+Z.delta.text};break}case"citations_delta":{if(J?.type==="text")Y.content[Z.index]={...J,citations:[...J.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(J&&t5(J)){let Q=J[s5]||"";Q+=Z.delta.partial_json;let X={...J};if(Object.defineProperty(X,s5,{value:Q,enumerable:!1,writable:!0}),Q)X.input=x8(Q);Y.content[Z.index]=X}break}case"thinking_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,thinking:J.thinking+Z.delta.thinking};break}case"signature_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,signature:Z.delta.signature};break}default:e5(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(J)=>{let Q=Z.shift();if(Q)Q.resolve(J);else $.push(J)}),this.on("end",()=>{Y=!0;for(let J of Z)J.resolve(void 0);Z.length=0}),this.on("abort",(J)=>{Y=!0;for(let Q of Z)Q.reject(J);Z.length=0}),this.on("error",(J)=>{Y=!0;for(let Q of Z)Q.reject(J);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((Q,X)=>Z.push({resolve:Q,reject:X})).then((Q)=>Q?{value:Q,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new V$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function e5($){}class f4 extends _{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(k`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",M$,{query:$,...Z})}delete($,Z){return this._client.delete(k`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(k`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new R(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:x([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,Q)=>A1.fromResponse(Q.response,Q.controller))}}class W1 extends _{constructor(){super(...arguments);this.batches=new f4(this._client)}create($,Z){if($.model in $9)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${$9[$.model]}
77
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in zY&&$.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 Q=A8[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,Q)}let J=R8($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:x([J,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>w2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return h4.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var $9={"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"},zY=["claude-opus-4-6"];W1.Batches=f4;class P1 extends _{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(k`/v1/models/${$}`,{...Y,headers:x([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/models",M$,{query:J,...Z,headers:x([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var v4=($)=>{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 _2,h2,g8,Z9,Y9="\\n\\nHuman:",J9="\\n\\nAssistant:";class h{constructor({baseURL:$=v4("ANTHROPIC_BASE_URL"),apiKey:Z=v4("ANTHROPIC_API_KEY")??null,authToken:Y=v4("ANTHROPIC_AUTH_TOKEN")??null,...J}={}){_2.add(this),g8.set(this,void 0);let Q={apiKey:Z,authToken:Y,...J,baseURL:$||"https://api.anthropic.com"};if(!Q.dangerouslyAllowBrowser&&O5())throw new R(`It looks like you're running in a browser-like environment.
74
78
 
75
79
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
76
80
  If you understand the risks and have appropriate mitigations in place,
77
81
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
78
82
 
79
83
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
80
- `);this.baseURL=X.baseURL,this.timeout=X.timeout??U6.DEFAULT_TIMEOUT,this.logger=X.logger??console;let z="warn";this.logLevel=z,this.logLevel=p4(X.logLevel,"ClientOptions.logLevel",this)??p4(X1("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??z,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??k7(),j(this,r1,y7,"f"),this._options=X,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 R([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return R([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return R([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return _7($)}getUserAgent(){return`${this.constructor.name}/JS ${E2}`}defaultIdempotencyKey(){return`stainless-node-retry-${v4()}`}makeStatusError($,Z,Y,J){return g.generate($,Z,Y,J)}buildURL($,Z,Y){let J=!H(this,H6,"m",U8).call(this)&&Y||this.baseURL,X=R7($)?new URL($):new URL(J+(J.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),z=this.defaultQuery(),Q=Object.fromEntries(X.searchParams);if(!d4(z)||!d4(Q))Z={...Q,...z,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))X.search=this.stringifyQuery(Z);return X.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((J)=>{return{method:$,path:Z,...J}}))}request($,Z=null){return new f2(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Y){let J=await $,X=J.maxRetries??this.maxRetries;if(Z==null)Z=X;await this.prepareOptions(J);let{req:z,url:Q,timeout:V}=await this.buildRequest(J,{retryCount:X-Z});await this.prepareRequest(z,{url:Q,options:J});let G="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),q=Y===void 0?"":`, retryOf: ${Y}`,K=Date.now();if(d(this).debug(`[${G}] sending request`,B2({retryOfRequestLogID:Y,method:J.method,url:Q,options:J,headers:z.headers})),J.signal?.aborted)throw new p;let O=new AbortController,N=await this.fetchWithTimeout(Q,z,V,O).catch(j$),M=Date.now();if(N instanceof globalThis.Error){let i=`retrying, ${Z} attempts remaining`;if(J.signal?.aborted)throw new p;let n=U2(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(Z)return d(this).info(`[${G}] connection ${n?"timed out":"failed"} - ${i}`),d(this).debug(`[${G}] connection ${n?"timed out":"failed"} (${i})`,B2({retryOfRequestLogID:Y,url:Q,durationMs:M-K,message:N.message})),this.retryRequest(J,Z,Y??G);if(d(this).info(`[${G}] connection ${n?"timed out":"failed"} - error; no more retries left`),d(this).debug(`[${G}] connection ${n?"timed out":"failed"} (error; no more retries left)`,B2({retryOfRequestLogID:Y,url:Q,durationMs:M-K,message:N.message})),n)throw new O$;throw new _2({cause:N})}let D=[...N.headers.entries()].filter(([i])=>i==="request-id").map(([i,n])=>", "+i+": "+JSON.stringify(n)).join(""),v=`[${G}${q}${D}] ${z.method} ${Q} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${M-K}ms`;if(!N.ok){let i=await this.shouldRetry(N);if(Z&&i){let F=`retrying, ${Z} attempts remaining`;return await b7(N.body),d(this).info(`${v} - ${F}`),d(this).debug(`[${G}] response error (${F})`,B2({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,durationMs:M-K})),this.retryRequest(J,Z,Y??G,N.headers)}let n=i?"error; no more retries left":"error; not retryable";d(this).info(`${v} - ${n}`);let N1=await N.text().catch((F)=>j$(F).message),k=D1(N1),o=k?void 0:N1;throw d(this).debug(`[${G}] response error (${n})`,B2({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,message:o,durationMs:Date.now()-K})),this.makeStatusError(N.status,k,o,N.headers)}return d(this).info(v),d(this).debug(`[${G}] response start`,B2({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,durationMs:M-K})),{response:N,options:J,controller:O,requestLogID:G,retryOfRequestLogID:Y,startTime:K}}getAPIList($,Z,Y){return this.requestAPIList(Z,Y&&"then"in Y?Y.then((J)=>({method:"get",path:$,...J})):{method:"get",path:$,...Y})}requestAPIList($,Z){let Y=this.makeRequest(Z,null,void 0);return new S1(this,Y,$)}async fetchWithTimeout($,Z,Y,J){let{signal:X,method:z,...Q}=Z||{},V=this._makeAbort(J);if(X)X.addEventListener("abort",V,{once:!0});let G=setTimeout(V,Y),q=globalThis.ReadableStream&&Q.body instanceof globalThis.ReadableStream||typeof Q.body==="object"&&Q.body!==null&&Symbol.asyncIterator in Q.body,K={signal:J.signal,...q?{duplex:"half"}:{},method:"GET",...Q};if(z)K.method=z.toUpperCase();try{return await this.fetch.call(void 0,$,K)}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,Y,J){let X,z=J?.get("retry-after-ms");if(z){let V=parseFloat(z);if(!Number.isNaN(V))X=V}let Q=J?.get("retry-after");if(Q&&!X){let V=parseFloat(Q);if(!Number.isNaN(V))X=V*1000;else X=Date.parse(Q)-Date.now()}if(X===void 0){let V=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(Z,V)}return await A7(X),this.makeRequest($,Z-1,Y)}calculateDefaultRetryTimeoutMillis($,Z){let X=Z-$,z=Math.min(0.5*Math.pow(2,X),8),Q=1-Math.random()*0.25;return z*Q*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:J,path:X,query:z,defaultBaseURL:Q}=Y,V=this.buildURL(X,z,Q);if("timeout"in Y)D7("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:G,body:q}=this.buildBody({options:Y}),K=await this.buildHeaders({options:$,method:J,bodyHeaders:G,retryCount:Z});return{req:{method:J,headers:K,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&q instanceof globalThis.ReadableStream&&{duplex:"half"},...q&&{body:q},...this.fetchOptions??{},...Y.fetchOptions??{}},url:V,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:J}){let X={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let z=R([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(J),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...S7(),...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=R([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:A1($)};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 H(this,r1,"f").call(this,{body:$,headers:Y})}}U6=y,r1=new WeakMap,H6=new WeakSet,U8=function(){return this.baseURL!=="https://api.anthropic.com"};y.Anthropic=U6;y.HUMAN_PROMPT=B8;y.AI_PROMPT=N8;y.DEFAULT_TIMEOUT=600000;y.AnthropicError=E;y.APIError=g;y.APIConnectionError=_2;y.APIConnectionTimeoutError=O$;y.APIUserAbortError=p;y.NotFoundError=L$;y.ConflictError=R$;y.RateLimitError=D$;y.BadRequestError=F$;y.AuthenticationError=E$;y.InternalServerError=A$;y.PermissionDeniedError=M$;y.UnprocessableEntityError=x$;y.toFile=k1;class W2 extends y{constructor(){super(...arguments);this.completions=new e2(this),this.messages=new d2(this),this.models=new Z$(this),this.beta=new G2(this)}}W2.Completions=e2;W2.Messages=d2;W2.Models=Z$;W2.Beta=G2;import{existsSync as H1,readdirSync as z9,readFileSync as c6,writeFileSync as Q9,renameSync as K9,statSync as x0,realpathSync as V9}from"fs";import{resolve as p2,join as d6,sep as x4,dirname as G9}from"path";import{randomUUID as W9}from"crypto";import{existsSync as n3,readFileSync as o3,writeFileSync as a3}from"fs";import{basename as B6}from"path";var C8=50;class N6{entries=[];saveState($){let Z=n3($),Y=Z?o3($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>C8)this.entries=this.entries.slice(-C8)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${B6($.path)} was a new file. Remove it manually if needed.`;a3($.path,$.content);let Z=$.content.split(`
81
- `).length;return`Undo: restored ${B6($.path)} (${Z} lines, from ${j8($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${B6($.path)} (${j8($.timestamp)})`}}function j8($){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`}import{existsSync as O8,readdirSync as r3,readFileSync as s3,mkdirSync as t3}from"fs";import{join as C6}from"path";function F8($){if(!O8($))return[];let Z=[],Y=r3($).filter((J)=>J.endsWith(".json"));for(let J of Y)try{let X=JSON.parse(s3(C6($,J),"utf-8"));if(!X.name||!X.description||!X.command)continue;if(typeof X.name!=="string"||typeof X.command!=="string")continue;if(X.command.includes("$(")||X.command.includes("`"))continue;Z.push({name:X.name,description:X.description,inputSchema:X.input_schema||{type:"object",properties:{},required:[]},command:X.command,source:C6($,J)})}catch{}return Z}function E8($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function M8($,Z){let Y=$.command;for(let[K,O]of Object.entries(Z)){let N=String(O).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${K}\\}\\}`,"g"),N)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let J=F1(),X=Bun.spawn([...J,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),z=setTimeout(()=>X.kill(),30000),[Q,V]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),G=await X.exited;clearTimeout(z);let q=Q.trim();if(V.trim())q+=(q?`
82
- `:"")+V.trim();if(G!==0)q+=(q?`
83
- `:"")+`Exit code: ${G}`;return q||"(no output)"}function L8($){if($.length===0)return"No plugins loaded. Add .json files to ~/.config/smolerclaw/plugins/";return`Plugins:
84
+ `);this.baseURL=Q.baseURL,this.timeout=Q.timeout??h2.DEFAULT_TIMEOUT,this.logger=Q.logger??console;let X="warn";this.logLevel=X,this.logLevel=U2(Q.logLevel,"ClientOptions.logLevel",this)??U2(v4("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??X,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??L5(),L(this,g8,F5,"f"),this._options=Q,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 x([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return x([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return x([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return R5($)}getUserAgent(){return`${this.constructor.name}/JS ${g$}`}defaultIdempotencyKey(){return`stainless-node-retry-${z2()}`}makeStatusError($,Z,Y,J){return c.generate($,Z,Y,J)}buildURL($,Z,Y){let J=!U(this,_2,"m",Z9).call(this)&&Y||this.baseURL,Q=H5($)?new URL($):new URL(J+(J.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery(),K=Object.fromEntries(Q.searchParams);if(!W2(X)||!W2(K))Z={...K,...X,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))Q.search=this.stringifyQuery(Z);return Q.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new R("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((J)=>{return{method:$,path:Z,...J}}))}request($,Z=null){return new X1(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Y){let J=await $,Q=J.maxRetries??this.maxRetries;if(Z==null)Z=Q;await this.prepareOptions(J);let{req:X,url:K,timeout:V}=await this.buildRequest(J,{retryCount:Q-Z});await this.prepareRequest(X,{url:K,options:J});let G="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Y===void 0?"":`, retryOf: ${Y}`,z=Date.now();if(l(this).debug(`[${G}] sending request`,P$({retryOfRequestLogID:Y,method:J.method,url:K,options:J,headers:X.headers})),J.signal?.aborted)throw new s;let M=new AbortController,N=await this.fetchWithTimeout(K,X,V,M).catch(s1),E=Date.now();if(N instanceof globalThis.Error){let m=`retrying, ${Z} attempts remaining`;if(J.signal?.aborted)throw new s;let p=T$(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(Z)return l(this).info(`[${G}] connection ${p?"timed out":"failed"} - ${m}`),l(this).debug(`[${G}] connection ${p?"timed out":"failed"} (${m})`,P$({retryOfRequestLogID:Y,url:K,durationMs:E-z,message:N.message})),this.retryRequest(J,Z,Y??G);if(l(this).info(`[${G}] connection ${p?"timed out":"failed"} - error; no more retries left`),l(this).debug(`[${G}] connection ${p?"timed out":"failed"} (error; no more retries left)`,P$({retryOfRequestLogID:Y,url:K,durationMs:E-z,message:N.message})),p)throw new t1;throw new Q1({cause:N})}let j=[...N.headers.entries()].filter(([m])=>m==="request-id").map(([m,p])=>", "+m+": "+JSON.stringify(p)).join(""),T=`[${G}${H}${j}] ${X.method} ${K} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${E-z}ms`;if(!N.ok){let m=await this.shouldRetry(N);if(Z&&m){let O=`retrying, ${Z} attempts remaining`;return await j5(N.body),l(this).info(`${T} - ${O}`),l(this).debug(`[${G}] response error (${O})`,P$({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,durationMs:E-z})),this.retryRequest(J,Z,Y??G,N.headers)}let p=m?"error; no more retries left":"error; not retryable";l(this).info(`${T} - ${p}`);let t4=await N.text().catch((O)=>s1(O).message),y=B8(t4),$$=y?void 0:t4;throw l(this).debug(`[${G}] response error (${p})`,P$({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,message:$$,durationMs:Date.now()-z})),this.makeStatusError(N.status,y,$$,N.headers)}return l(this).info(T),l(this).debug(`[${G}] response start`,P$({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,durationMs:E-z})),{response:N,options:J,controller:M,requestLogID:G,retryOfRequestLogID:Y,startTime:z}}getAPIList($,Z,Y){return this.requestAPIList(Z,Y&&"then"in Y?Y.then((J)=>({method:"get",path:$,...J})):{method:"get",path:$,...Y})}requestAPIList($,Z){let Y=this.makeRequest(Z,null,void 0);return new L8(this,Y,$)}async fetchWithTimeout($,Z,Y,J){let{signal:Q,method:X,...K}=Z||{},V=this._makeAbort(J);if(Q)Q.addEventListener("abort",V,{once:!0});let G=setTimeout(V,Y),H=globalThis.ReadableStream&&K.body instanceof globalThis.ReadableStream||typeof K.body==="object"&&K.body!==null&&Symbol.asyncIterator in K.body,z={signal:J.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,Y,J){let Q,X=J?.get("retry-after-ms");if(X){let V=parseFloat(X);if(!Number.isNaN(V))Q=V}let K=J?.get("retry-after");if(K&&!Q){let V=parseFloat(K);if(!Number.isNaN(V))Q=V*1000;else Q=Date.parse(K)-Date.now()}if(Q===void 0){let V=$.maxRetries??this.maxRetries;Q=this.calculateDefaultRetryTimeoutMillis(Z,V)}return await B5(Q),this.makeRequest($,Z-1,Y)}calculateDefaultRetryTimeoutMillis($,Z){let Q=Z-$,X=Math.min(0.5*Math.pow(2,Q),8),K=1-Math.random()*0.25;return X*K*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new R("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:J,path:Q,query:X,defaultBaseURL:K}=Y,V=this.buildURL(Q,X,K);if("timeout"in Y)U5("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:G,body:H}=this.buildBody({options:Y}),z=await this.buildHeaders({options:$,method:J,bodyHeaders:G,retryCount:Z});return{req:{method:J,headers:z,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Y.fetchOptions??{}},url:V,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:J}){let Q={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Q[this.idempotencyHeader]=$.idempotencyKey}let X=x([Q,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(J),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...E5(),...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(X),X.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Y=x([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:N8($)};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 U(this,g8,"f").call(this,{body:$,headers:Y})}}h2=h,g8=new WeakMap,_2=new WeakSet,Z9=function(){return this.baseURL!=="https://api.anthropic.com"};h.Anthropic=h2;h.HUMAN_PROMPT=Y9;h.AI_PROMPT=J9;h.DEFAULT_TIMEOUT=600000;h.AnthropicError=R;h.APIError=c;h.APIConnectionError=Q1;h.APIConnectionTimeoutError=t1;h.APIUserAbortError=s;h.NotFoundError=Y4;h.ConflictError=J4;h.RateLimitError=X4;h.BadRequestError=e1;h.AuthenticationError=$4;h.InternalServerError=K4;h.PermissionDeniedError=Z4;h.UnprocessableEntityError=Q4;h.toFile=j8;class j$ extends h{constructor(){super(...arguments);this.completions=new D1(this),this.messages=new W1(this),this.models=new P1(this),this.beta=new L$(this)}}j$.Completions=D1;j$.Messages=W1;j$.Models=P1;j$.Beta=L$;r();import{existsSync as i4,readdirSync as qQ,readFileSync as O7,writeFileSync as UQ,statSync as SZ,realpathSync as BQ}from"fs";import{resolve as N1,join as bZ,sep as c0}from"path";import{existsSync as GY,readFileSync as WY,writeFileSync as HY}from"fs";import{basename as f2}from"path";var Q9=50;class v2{entries=[];saveState($){let Z=GY($),Y=Z?WY($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>Q9)this.entries=this.entries.slice(-Q9)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${f2($.path)} was a new file. Remove it manually if needed.`;HY($.path,$.content);let Z=$.content.split(`
85
+ `).length;return`Undo: restored ${f2($.path)} (${Z} lines, from ${X9($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${f2($.path)} (${X9($.timestamp)})`}}function X9($){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`}import{existsSync as K9,readdirSync as qY,readFileSync as UY,mkdirSync as BY}from"fs";import{join as g2}from"path";function z9($){if(!K9($))return[];let Z=[],Y=qY($).filter((J)=>J.endsWith(".json"));for(let J of Y)try{let Q=JSON.parse(UY(g2($,J),"utf-8"));if(!Q.name||!Q.description||!Q.command)continue;if(typeof Q.name!=="string"||typeof Q.command!=="string")continue;if(Q.command.includes("$(")||Q.command.includes("`"))continue;Z.push({name:Q.name,description:Q.description,inputSchema:Q.input_schema||{type:"object",properties:{},required:[]},command:Q.command,source:g2($,J)})}catch{}return Z}function V9($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function G9($,Z){let Y=$.command;for(let[z,M]of Object.entries(Z)){let N=String(M).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${z}\\}\\}`,"g"),N)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let J=Y8(),Q=Bun.spawn([...J,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>Q.kill(),30000),[K,V]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),G=await Q.exited;clearTimeout(X);let H=K.trim();if(V.trim())H+=(H?`
86
+ `:"")+V.trim();if(G!==0)H+=(H?`
87
+ `:"")+`Exit code: ${G}`;return H||"(no output)"}function W9($){if($.length===0)return"No plugins loaded. Add .json files to ~/.config/smolerclaw/plugins/";return`Plugins:
84
88
  `+$.map((Z)=>` ${Z.name} \u2014 ${Z.description}`).join(`
85
- `)}function R8($){let Z=C6($,"plugins");if(!O8(Z))t3(Z,{recursive:!0});return Z}var e3=/[";`$\n\r|&<>{}()]/;function O6($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(e3.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}var $5=15000;async function Y$($){let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",$],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>Z.kill(),$5),[J,X]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),z=await Z.exited;return clearTimeout(Y),{stdout:J,stderr:X,exitCode:z}}var j6={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"};async function J$($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),J=j6[Y];if(!J){let z=Object.keys(j6).join(", ");return`Unknown app: "${$}". Available: ${z}`}if(Z){let z=O6(Z,"argument");if(z)return z}if(!x)return"Error: this command is only available on Windows.";let X=Z?`Start-Process '${J}' -ArgumentList '${Z}'`:`Start-Process '${J}'`;try{let{exitCode:z,stderr:Q}=await Y$(X);if(z!==0&&Q.trim())return`Error opening ${$}: ${Q.trim()}`;return`Opened: ${$}`}catch(z){return`Error opening ${$}: ${z instanceof Error?z.message:String(z)}`}}async function s1($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=O6($,"URL");if(Z)return Z;if(!x)return"Error: this command is only available on Windows.";try{let{exitCode:Y,stderr:J}=await Y$(`Start-Process '${$}'`);if(Y!==0&&J.trim())return`Error: ${J.trim()}`;return`Opened in browser: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function t1($){let Z=O6($,"file path");if(Z)return Z;if(!x)return"Error: this command is only available on Windows.";try{let{exitCode:Y,stderr:J}=await Y$(`Invoke-Item '${$}'`);if(Y!==0&&J.trim())return`Error: ${J.trim()}`;return`Opened: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function e1(){if(!x)return"Error: this command is only available on Windows.";try{let{stdout:Z,stderr:Y}=await Y$("Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First 15 Name, @{N='Memory(MB)';E={[math]::Round($_.WorkingSet64/1MB,1)}}, MainWindowTitle | Format-Table -AutoSize | Out-String -Width 200");if(Y.trim())return`Error: ${Y.trim()}`;return Z.trim()||"No windowed applications running."}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}async function X$(){if(!x)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{stdout:Z,stderr:Y}=await Y$($.join("; "));if(!Z.trim()&&Y.trim())return`Error: ${Y.trim()}`;return Z.trim()||"System info unavailable."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function z$(){let $=new Date,Z=[],Y=$.toLocaleDateString("pt-BR",{weekday:"long"}),J=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),X=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${Y}, ${J} \u2014 ${X}`);let z=new Date($.valueOf());z.setDate(z.getDate()+3-(z.getDay()+6)%7);let Q=new Date(z.getFullYear(),0,4),V=1+Math.round(((z.getTime()-Q.getTime())/86400000-3+(Q.getDay()+6)%7)/7);Z.push(`Semana ${V} do ano`);let G=$.getHours();if(G>=8&&G<18)Z.push("Status: horario comercial");else if(G>=18&&G<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
86
- `)}async function A2(){if(!x)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(`
87
- `);try{let{stdout:Z}=await Y$($);return Z.trim()||"Outlook nao disponivel."}catch{return"Outlook nao disponivel."}}function x8(){return Object.keys(j6)}var D8=[{name:"InfoMoney",url:"https://www.infomoney.com.br/feed/",category:"finance"},{name:"Valor Economico",url:"https://pox.globo.com/rss/valor/",category:"business"},{name:"Bloomberg Linea BR",url:"https://www.bloomberglinea.com.br/feed/",category:"finance"},{name:"TechCrunch",url:"https://techcrunch.com/feed/",category:"tech"},{name:"Hacker News (best)",url:"https://hnrss.org/best",category:"tech"},{name:"The Verge",url:"https://www.theverge.com/rss/index.xml",category:"tech"},{name:"G1",url:"https://g1.globo.com/rss/g1/",category:"brazil"},{name:"Folha",url:"https://feeds.folha.uol.com.br/folha/cotidiano/rss091.xml",category:"brazil"},{name:"BBC World",url:"https://feeds.bbci.co.uk/news/world/rss.xml",category:"world"},{name:"Reuters",url:"https://www.reutersagency.com/feed/",category:"world"},{name:"The Hacker News",url:"https://feeds.feedburner.com/TheHackersNews",category:"security"},{name:"BleepingComputer",url:"https://www.bleepingcomputer.com/feed/",category:"security"},{name:"Krebs on Security",url:"https://krebsonsecurity.com/feed/",category:"security"}];function Z5($,Z,Y){let J=[],X=/<item[\s>]([\s\S]*?)<\/item>/gi,z;while((z=X.exec($))!==null){let Q=z[1],V=A8(Q,Z,Y);if(V)J.push(V);if(J.length>=10)break}if(J.length===0){let Q=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((z=Q.exec($))!==null){let V=z[1],G=A8(V,Z,Y);if(G)J.push(G);if(J.length>=10)break}}return J}function A8($,Z,Y){let J=z1($,"title");if(!J)return null;let X=z1($,"link")||X5($),z=Y5(X),Q=z1($,"pubDate")||z1($,"published")||z1($,"updated"),V;if(Q){let G=new Date(Q);V=isNaN(G.getTime())?void 0:G}return{title:z5(J),link:z,source:Z,category:Y,pubDate:V}}function Y5($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function J5($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function z1($,Z){let Y=J5(Z),X=new RegExp(`<${Y}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Y}>`,"i").exec($);if(X)return X[1].trim();let Q=new RegExp(`<${Y}[^>]*>([\\s\\S]*?)</${Y}>`,"i").exec($);return Q?Q[1].trim():null}function X5($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}function z5($){return $.replace(/<[^>]+>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").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 w2($,Z=5){let Y=Math.max(1,Math.min(Z,10));if($&&$.length===0)return F6();let J=$?D8.filter((V)=>$.includes(V.category)):D8,X=await Promise.allSettled(J.map((V)=>K5(V,Y))),z=[],Q=[];for(let V=0;V<X.length;V++){let G=X[V];if(G.status==="fulfilled")z.push(...G.value);else Q.push(`${J[V].name}: ${Q5(G.reason)}`)}if(z.length===0)return Q.length>0?`Nenhuma noticia encontrada.
88
- Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return z.sort((V,G)=>{let q=V.pubDate?.getTime()||0;return(G.pubDate?.getTime()||0)-q}),V5(z,Q)}function Q5($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function K5($,Z){let Y=new AbortController,J=setTimeout(()=>Y.abort(),1e4);try{let X=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(J),!X.ok)return[];let z=X.headers.get("content-length");if(z&&Number(z)>2097152)return[];let Q=X.body?.getReader();if(!Q)return[];let V=[],G=0;while(!0){let{done:O,value:N}=await Q.read();if(O)break;if(G+=N.byteLength,G>2097152)return Q.cancel(),[];V.push(N)}let q=new TextDecoder().decode(Buffer.concat(V));return Z5(q,$.name,$.category).slice(0,Z)}catch(X){if(clearTimeout(J),process.env.DEBUG)console.error(`[news] ${$.name}: ${X instanceof Error?X.message:X}`);return[]}}function V5($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},J=new Map;for(let V of $){let G=J.get(V.category)||[];J.set(V.category,[...G,V])}let X=[],z=["finance","business","tech","security","brazil","world"];for(let V of z){let G=J.get(V);if(!G||G.length===0)continue;let q=Y[V],K=G.slice(0,8).map((O)=>{let N=O.pubDate?O.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${N?`[${N}]`:""} ${O.title} (${O.source})`});X.push(`--- ${q} ---
89
- ${K.join(`
90
- `)}`)}let Q=X.join(`
91
-
92
- `);if(Z.length>0)Q+=`
93
-
94
- (Fontes indisponiveis: ${Z.join(", ")})`;return Q}function F6(){return`Categorias: business, tech, finance, brazil, world, security
95
- Uso: /news [categoria]`}import{existsSync as w8,mkdirSync as G5,readFileSync as W5,writeFileSync as q5}from"fs";import{join as H5}from"path";var P8="",f=[],Q$=null,T8=null,I8=()=>H5(P8,"tasks.json");function $4(){q5(I8(),JSON.stringify(f,null,2))}function U5(){let $=I8();if(!w8($)){f=[];return}try{f=JSON.parse(W5($,"utf-8"))}catch{f=[]}}function S8($,Z){if(P8=$,T8=Z,!w8($))G5($,{recursive:!0});if(U5(),Q$)clearInterval(Q$);Q$=setInterval(B5,30000),C5().catch(()=>{})}function k8(){if(Q$)clearInterval(Q$),Q$=null}function Z4($,Z){let Y={id:j5(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(f=[...f,Y],$4(),Z&&x)E6(Y).catch(()=>{});return Y}function Y4($){let Z=$.toLowerCase(),Y=f.find((J)=>J.id===$||J.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(f=f.map((J)=>J.id===Y.id?{...J,done:!0}:J),$4(),Y.dueAt&&x)y8(Y.id).catch(()=>{});return f.find((J)=>J.id===Y.id)||null}function b8($){let Z=$.toLowerCase(),Y=f.findIndex((X)=>X.id===$||X.title.toLowerCase().includes(Z));if(Y===-1)return!1;let J=f[Y];if(f=[...f.slice(0,Y),...f.slice(Y+1)],$4(),J.dueAt&&x)y8(J.id).catch(()=>{});return!0}function P2($=!1){return $?[...f]:f.filter((Z)=>!Z.done)}function m2($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let J=Y.done?"[x]":"[ ]",X=Y.dueAt?` (${O5(Y.dueAt)})`:"";return` ${J} ${Y.title}${X} [${Y.id}]`});return`Tarefas (${$.length}):
89
+ `)}function H9($){let Z=g2($,"plugins");if(!K9(Z))BY(Z,{recursive:!0});return Z}var NY=/[";`$\n\r|&<>{}()]/;function c2($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(NY.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}var CY=15000;async function w1($){let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",$],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>Z.kill(),CY),[J,Q]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),X=await Z.exited;return clearTimeout(Y),{stdout:J,stderr:Q,exitCode:X}}var m2={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"};async function I1($,Z){let Y=$.toLowerCase().replace(/\s+/g,""),J=m2[Y];if(!J){let X=Object.keys(m2).join(", ");return`Unknown app: "${$}". Available: ${X}`}if(Z){let X=c2(Z,"argument");if(X)return X}if(!A)return"Error: this command is only available on Windows.";let Q=Z?`Start-Process '${J}' -ArgumentList '${Z}'`:`Start-Process '${J}'`;try{let{exitCode:X,stderr:K}=await w1(Q);if(X!==0&&K.trim())return`Error opening ${$}: ${K.trim()}`;return`Opened: ${$}`}catch(X){return`Error opening ${$}: ${X instanceof Error?X.message:String(X)}`}}async function S1($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=c2($,"URL");if(Z)return Z;if(!A)return"Error: this command is only available on Windows.";try{let{exitCode:Y,stderr:J}=await w1(`Start-Process '${$}'`);if(Y!==0&&J.trim())return`Error: ${J.trim()}`;return`Opened in browser: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function m8($){let Z=c2($,"file path");if(Z)return Z;if(!A)return"Error: this command is only available on Windows.";try{let{exitCode:Y,stderr:J}=await w1(`Invoke-Item '${$}'`);if(Y!==0&&J.trim())return`Error: ${J.trim()}`;return`Opened: ${$}`}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}async function c8(){if(!A)return"Error: this command is only available on Windows.";try{let{stdout:Z,stderr:Y}=await w1("Get-Process | Where-Object {$_.MainWindowTitle -ne ''} | Sort-Object -Property WorkingSet64 -Descending | Select-Object -First 15 Name, @{N='Memory(MB)';E={[math]::Round($_.WorkingSet64/1MB,1)}}, MainWindowTitle | Format-Table -AutoSize | Out-String -Width 200");if(Y.trim())return`Error: ${Y.trim()}`;return Z.trim()||"No windowed applications running."}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}async function b1(){if(!A)return"Error: this command is only available on Windows.";let $=['$cpu = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average; "CPU: $cpu%"','$os = Get-CimInstance Win32_OperatingSystem; $total = [math]::Round($os.TotalVisibleMemorySize/1MB,1); $free = [math]::Round($os.FreePhysicalMemory/1MB,1); $used = $total - $free; "RAM: $used GB / $total GB (Free: $free GB)"','Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object { $free = [math]::Round($_.FreeSpace/1GB,1); $total = [math]::Round($_.Size/1GB,1); "$($_.DeviceID) $free GB free / $total GB" }','$uptime = (Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime; "Uptime: $($uptime.Days)d $($uptime.Hours)h $($uptime.Minutes)m"','$b = Get-CimInstance Win32_Battery -ErrorAction SilentlyContinue; if ($b) { "Battery: $($b.EstimatedChargeRemaining)%" } else { "Battery: N/A (desktop)" }'];try{let{stdout:Z,stderr:Y}=await w1($.join("; "));if(!Z.trim()&&Y.trim())return`Error: ${Y.trim()}`;return Z.trim()||"System info unavailable."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function k1(){let $=new Date,Z=[],Y=$.toLocaleDateString("pt-BR",{weekday:"long"}),J=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),Q=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${Y}, ${J} \u2014 ${Q}`);let X=new Date($.valueOf());X.setDate(X.getDate()+3-(X.getDay()+6)%7);let K=new Date(X.getFullYear(),0,4),V=1+Math.round(((X.getTime()-K.getTime())/86400000-3+(K.getDay()+6)%7)/7);Z.push(`Semana ${V} do ano`);let G=$.getHours();if(G>=8&&G<18)Z.push("Status: horario comercial");else if(G>=18&&G<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
90
+ `)}async function l$(){if(!A)return"Outlook integration only available on Windows.";let $=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop",' $ns = $outlook.GetNamespace("MAPI")'," $cal = $ns.GetDefaultFolder(9)"," $today = (Get-Date).Date"," $tomorrow = $today.AddDays(1)"," $items = $cal.Items",' $items.Sort("[Start]")'," $items.IncludeRecurrences = $true",` $filter = "[Start] >= '$($today.ToString('g'))' AND [Start] < '$($tomorrow.ToString('g'))'"`," $events = $items.Restrict($filter)"," $results = @()"," foreach ($e in $events) {",' $start = ([DateTime]$e.Start).ToString("HH:mm")',' $end = ([DateTime]$e.End).ToString("HH:mm")',' $results += "$start-$end $($e.Subject)"'," }",' if ($results.Count -eq 0) { "Nenhum evento hoje." }'," else { $results -join [char]10 }","} catch {",' "Outlook nao disponivel ou sem eventos."',"}"].join(`
91
+ `);try{let{stdout:Z}=await w1($);return Z.trim()||"Outlook nao disponivel."}catch{return"Outlook nao disponivel."}}function q9(){return Object.keys(m2)}r();import{existsSync as MY,readFileSync as OY}from"fs";import{join as EY}from"path";var y1=[{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}],d8="",Z$=[],W$=new Set,N9=()=>EY(d8,"news-feeds.json");function u8(){if(!d8)return;let $={custom:Z$,disabled:[...W$]};D(N9(),JSON.stringify($,null,2))}function LY(){if(!d8)return;let $=N9();if(!MY($)){Z$=[],W$=new Set;return}try{let Z=JSON.parse(OY($,"utf-8"));Z$=Z.custom||[],W$=new Set(Z.disabled||[])}catch{Z$=[],W$=new Set}}function C9($){d8=$,LY()}function u2(){return[...y1.filter((Z)=>!W$.has(Z.url)),...Z$]}function p8($,Z,Y){let J=$.trim();if(!J||J.length>100)return"Error: nome invalido (1-100 caracteres).";let Q=Y.trim().toLowerCase();if(!Q||Q.length>30)return"Error: categoria invalida (1-30 caracteres).";let X=Z.trim();if(!X.startsWith("http://")&&!X.startsWith("https://"))return"Error: URL deve comecar com http:// ou https://";if(X.length>500)return"Error: URL muito longa (max 500 caracteres).";if([...y1,...Z$].some((G)=>G.url===X))return"Error: essa URL ja esta cadastrada.";let V={name:J,url:X,category:Q};return Z$=[...Z$,V],u8(),V}function l8($){let Z=$.toLowerCase().trim(),Y=Z$.findIndex((J)=>J.name.toLowerCase()===Z||J.url===$.trim());if(Y===-1)return!1;return Z$=[...Z$.slice(0,Y),...Z$.slice(Y+1)],u8(),!0}function n8($){let Z=$.toLowerCase().trim(),Y=y1.find((J)=>J.name.toLowerCase()===Z||J.url===$.trim());if(!Y)return!1;if(W$.has(Y.url))return!1;return W$=new Set([...W$,Y.url]),u8(),!0}function i8($){let Z=$.toLowerCase().trim(),Y=y1.find((J)=>J.name.toLowerCase()===Z||J.url===$.trim());if(!Y)return!1;if(!W$.has(Y.url))return!1;return W$=new Set([...W$].filter((J)=>J!==Y.url)),u8(),!0}function o8(){let $=["Fontes de noticias:"];$.push(`
92
+ --- Built-in ---`);for(let Z of y1){let Y=W$.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(Z$.length>0){$.push(`
93
+ --- Custom ---`);for(let Z of Z$)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
94
+ Total: ${u2().length} ativas (${y1.length} built-in, ${Z$.length} custom, ${W$.size} desativadas)`),$.join(`
95
+ `)}var U9=2097152,d2=10,jY=1e4;function FY($,Z,Y){let J=[],Q=/<item[\s>]([\s\S]*?)<\/item>/gi,X;while((X=Q.exec($))!==null){let K=X[1],V=B9(K,Z,Y);if(V)J.push(V);if(J.length>=d2)break}if(J.length===0){let K=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((X=K.exec($))!==null){let V=X[1],G=B9(V,Z,Y);if(G)J.push(G);if(J.length>=d2)break}}return J}function B9($,Z,Y){let J=g4($,"title");if(!J)return null;let Q=g4($,"link")||xY($),X=RY(Q),K=g4($,"pubDate")||g4($,"published")||g4($,"updated"),V;if(K){let G=new Date(K);V=isNaN(G.getTime())?void 0:G}return{title:DY(J),link:X,source:Z,category:Y,pubDate:V}}function RY($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function AY($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g4($,Z){let Y=AY(Z),Q=new RegExp(`<${Y}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Y}>`,"i").exec($);if(Q)return Q[1].trim();let K=new RegExp(`<${Y}[^>]*>([\\s\\S]*?)</${Y}>`,"i").exec($);return K?K[1].trim():null}function xY($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}function DY($){return $.replace(/<[^>]+>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").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 n$($,Z=5){let Y=Math.max(1,Math.min(Z,d2));if($&&$.length===0)return IY();let J=u2(),Q=$?J.filter((G)=>$.includes(G.category)):J,X=await Promise.allSettled(Q.map((G)=>PY(G,Y))),K=[],V=[];for(let G=0;G<X.length;G++){let H=X[G];if(H.status==="fulfilled")K.push(...H.value);else V.push(`${Q[G].name}: ${TY(H.reason)}`)}if(K.length===0)return V.length>0?`Nenhuma noticia encontrada.
96
+ Falhas: ${V.join(", ")}`:"Nenhuma noticia encontrada.";return K.sort((G,H)=>{let z=G.pubDate?.getTime()||0;return(H.pubDate?.getTime()||0)-z}),wY(K,V)}function TY($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function PY($,Z){let Y=new AbortController,J=setTimeout(()=>Y.abort(),jY);try{let Q=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(J),!Q.ok)return[];let X=Q.headers.get("content-length");if(X&&Number(X)>U9)return[];let K=Q.body?.getReader();if(!K)return[];let V=[],G=0;while(!0){let{done:M,value:N}=await K.read();if(M)break;if(G+=N.byteLength,G>U9)return K.cancel(),[];V.push(N)}let H=new TextDecoder().decode(Buffer.concat(V));return FY(H,$.name,$.category).slice(0,Z)}catch(Q){throw clearTimeout(J),Q}}function wY($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},J=new Map;for(let V of $){let G=J.get(V.category)||[];J.set(V.category,[...G,V])}let Q=[],X=["finance","business","tech","security","brazil","world"];for(let V of X){let G=J.get(V);if(!G||G.length===0)continue;let H=Y[V],z=G.slice(0,8).map((M)=>{let N=M.pubDate?M.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${N?`[${N}]`:""} ${M.title} (${M.source})`});Q.push(`--- ${H} ---
97
+ ${z.join(`
98
+ `)}`)}let K=Q.join(`
99
+
100
+ `);if(Z.length>0)K+=`
101
+
102
+ (Fontes indisponiveis: ${Z.join(", ")})`;return K}function IY(){let $=u2();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
103
+ Uso: /news [categoria]`}import{existsSync as M9,mkdirSync as SY,readFileSync as bY}from"fs";import{join as kY}from"path";import{randomUUID as yY}from"crypto";r();var O9="",v=[],_1=null,E9=null,L9=()=>kY(O9,"tasks.json");function a8(){D(L9(),JSON.stringify(v,null,2))}function _Y(){let $=L9();if(!M9($)){v=[];return}try{v=JSON.parse(bY($,"utf-8"))}catch{v=[]}}function j9($,Z){if(O9=$,E9=Z,!M9($))SY($,{recursive:!0});if(_Y(),_1)clearInterval(_1);_1=setInterval(hY,30000),vY().catch(()=>{})}function F9(){if(_1)clearInterval(_1),_1=null}function r8($,Z){let Y={id:gY(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(v=[...v,Y],a8(),Z&&A)p2(Y).catch(()=>{});return Y}function s8($){let Z=$.toLowerCase(),Y=v.find((J)=>J.id===$||J.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(v=v.map((J)=>J.id===Y.id?{...J,done:!0}:J),a8(),Y.dueAt&&A)x9(Y.id).catch(()=>{});return v.find((J)=>J.id===Y.id)||null}function R9($){let Z=$.toLowerCase(),Y=v.findIndex((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(Y===-1)return!1;let J=v[Y];if(v=[...v.slice(0,Y),...v.slice(Y+1)],a8(),J.dueAt&&A)x9(J.id).catch(()=>{});return!0}function i$($=!1){return $?[...v]:v.filter((Z)=>!Z.done)}function H1($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let J=Y.done?"[x]":"[ ]",Q=Y.dueAt?` (${mY(Y.dueAt)})`:"";return` ${J} ${Y.title}${Q} [${Y.id}]`});return`Tarefas (${$.length}):
96
104
  ${Z.join(`
97
- `)}`}function Q1($){let Z=new Date,Y=$.toLowerCase().trim(),J=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(J){let Q=parseInt(J[1]),V=J[2].startsWith("h")?"hours":"minutes",G=new Date(Z);if(V==="hours")G.setHours(G.getHours()+Q);else G.setMinutes(G.getMinutes()+Q);return G}let X=new Date(Z);if(Y.includes("amanha")||Y.includes("amanh\xE3"))X.setDate(X.getDate()+1);let z=Y.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(z){let Q=parseInt(z[1]),V=parseInt(z[2]||"0");if(Q>=0&&Q<=23&&V>=0&&V<=59){if(X.setHours(Q,V,0,0),X<=Z&&!Y.includes("amanha")&&!Y.includes("amanh\xE3"))X.setDate(X.getDate()+1);return X}}return null}function B5(){let $=new Date,Z=!1;for(let Y of f){if(Y.done||Y.notified||!Y.dueAt)continue;let J=new Date(Y.dueAt);if(isNaN(J.getTime()))continue;let X=$.getTime()-J.getTime();if(X>=0&&X<300000)f=f.map((z)=>z.id===Y.id?{...z,notified:!0}:z),Z=!0,N5(Y),T8?.(Y)}if(Z)$4()}async function N5($){if(!x)return;let Y=["[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">smolerclaw - Lembrete</text><text id="2">${$.title.replace(/'/g,"''")}</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("; ");try{let J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Y],{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>J.kill(),1e4);await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),await J.exited,clearTimeout(X)}catch{}}var M6="smolerclaw-reminder-";async function E6($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${M6}${$.id}`,J=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),X=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),Q=["[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"">${$.title.replace(/'/g,"''").replace(/"/g,"\\\"")}</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 Bun.spawn(["schtasks","/Create","/TN",Y,"/SC","ONCE","/SD",J,"/ST",X,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${Q}"`,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function y8($){let Z=`${M6}${$}`;try{await Bun.spawn(["schtasks","/Delete","/TN",Z,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function C5(){if(!x)return;let $=Date.now();for(let Z of f){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if(await Bun.spawn(["schtasks","/Query","/TN",`${M6}${Z.id}`],{stdout:"pipe",stderr:"pipe"}).exited!==0)await E6(Z)}catch{await E6(Z)}}}function j5(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}function O5($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,J=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),X=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),z=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(X.getTime()===J.getTime())return`hoje ${z}`;let Q=new Date(J);if(Q.setDate(Q.getDate()+1),X.getTime()===Q.getTime())return`amanha ${z}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${z}`}import{existsSync as _8,mkdirSync as F5,readFileSync as E5,writeFileSync as M5}from"fs";import{join as L5}from"path";var f8="",a=[],h8=()=>L5(f8,"memos.json");function v8(){M5(h8(),JSON.stringify(a,null,2))}function R5(){let $=h8();if(!_8($)){a=[];return}try{a=JSON.parse(E5($,"utf-8"))}catch{a=[]}}function g8($){if(f8=$,!_8($))F5($,{recursive:!0});R5()}function J4($,Z=[]){let Y=new Date().toISOString(),J=$.match(/#(\w+)/g)?.map((Q)=>Q.slice(1).toLowerCase())||[],X=[...new Set([...Z.map((Q)=>Q.toLowerCase()),...J])],z={id:D5(),content:$.trim(),tags:X,createdAt:Y,updatedAt:Y};return a=[...a,z],v8(),z}function c8($){let Z=a.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return a=[...a.slice(0,Z),...a.slice(Z+1)],v8(),!0}function X4($){let Z=$.toLowerCase().trim();if(!Z)return[...a];let Y=Z.startsWith("#"),J=Y?Z.slice(1):Z;return a.filter((X)=>{if(Y)return X.tags.some((z)=>z.includes(J));return X.content.toLowerCase().includes(J)||X.tags.some((z)=>z.includes(J))}).sort((X,z)=>new Date(z.updatedAt).getTime()-new Date(X.updatedAt).getTime())}function K1($=20){return[...a].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function x5(){let $=new Map;for(let Z of a)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 u2($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((Y)=>{let J=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.tags.length>0?` [${Y.tags.map((Q)=>`#${Q}`).join(" ")}]`:"",z=Y.content.length>80?Y.content.slice(0,80).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${J}] ${z}${X} {${Y.id}}`});return`Memos (${$.length}):
105
+ `)}`}function m4($){let Z=new Date,Y=$.toLowerCase().trim(),J=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(J){let K=parseInt(J[1]),V=J[2].startsWith("h")?"hours":"minutes",G=new Date(Z);if(V==="hours")G.setHours(G.getHours()+K);else G.setMinutes(G.getMinutes()+K);return G}let Q=new Date(Z);if(Y.includes("amanha")||Y.includes("amanh\xE3"))Q.setDate(Q.getDate()+1);let X=Y.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(X){let K=parseInt(X[1]),V=parseInt(X[2]||"0");if(K>=0&&K<=23&&V>=0&&V<=59){if(Q.setHours(K,V,0,0),Q<=Z&&!Y.includes("amanha")&&!Y.includes("amanh\xE3"))Q.setDate(Q.getDate()+1);return Q}}return null}function hY(){let $=new Date,Z=!1;for(let Y of v){if(Y.done||Y.notified||!Y.dueAt)continue;let J=new Date(Y.dueAt);if(isNaN(J.getTime()))continue;let Q=$.getTime()-J.getTime();if(Q>=0&&Q<300000)v=v.map((X)=>X.id===Y.id?{...X,notified:!0}:X),Z=!0,fY(Y),E9?.(Y)}if(Z)a8()}function A9($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function fY($){if(!A)return;let Y=["[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">smolerclaw - Lembrete</text><text id="2">${A9($.title)}</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("; ");try{let J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Y],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>J.kill(),1e4);await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),await J.exited,clearTimeout(Q)}catch{}}var l2="smolerclaw-reminder-";async function p2($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${l2}${$.id}`,J=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),Q=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),K=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null;","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null;","$x = New-Object Windows.Data.Xml.Dom.XmlDocument;",`$x.LoadXml('<toast><visual><binding template=""ToastText02""><text id=""1"">smolerclaw</text><text id=""2"">${A9($.title).replace(/"/g,'""')}</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 Bun.spawn(["schtasks","/Create","/TN",Y,"/SC","ONCE","/SD",J,"/ST",Q,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${K}"`,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function x9($){let Z=`${l2}${$}`;try{await Bun.spawn(["schtasks","/Delete","/TN",Z,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function vY(){if(!A)return;let $=Date.now();for(let Z of v){if(Z.done||Z.notified||!Z.dueAt)continue;let Y=new Date(Z.dueAt);if(isNaN(Y.getTime())||Y.getTime()<=$)continue;try{if(await Bun.spawn(["schtasks","/Query","/TN",`${l2}${Z.id}`],{stdout:"pipe",stderr:"pipe"}).exited!==0)await p2(Z)}catch{await p2(Z)}}}function gY(){return yY().slice(0,8)}function mY($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,J=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),Q=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),X=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(Q.getTime()===J.getTime())return`hoje ${X}`;let K=new Date(J);if(K.setDate(K.getDate()+1),Q.getTime()===K.getTime())return`amanha ${X}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${X}`}r();import{existsSync as D9,mkdirSync as cY,readFileSync as dY}from"fs";import{join as uY}from"path";import{randomUUID as pY}from"crypto";var T9="",Y$=[],P9=()=>uY(T9,"memos.json");function w9(){D(P9(),JSON.stringify(Y$,null,2))}function lY(){let $=P9();if(!D9($)){Y$=[];return}try{Y$=JSON.parse(dY($,"utf-8"))}catch{Y$=[]}}function I9($){if(T9=$,!D9($))cY($,{recursive:!0});lY()}function t8($,Z=[]){let Y=new Date().toISOString(),J=$.match(/#(\w+)/g)?.map((K)=>K.slice(1).toLowerCase())||[],Q=[...new Set([...Z.map((K)=>K.toLowerCase()),...J])],X={id:iY(),content:$.trim(),tags:Q,createdAt:Y,updatedAt:Y};return Y$=[...Y$,X],w9(),X}function S9($){let Z=Y$.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return Y$=[...Y$.slice(0,Z),...Y$.slice(Z+1)],w9(),!0}function e8($){let Z=$.toLowerCase().trim();if(!Z)return[...Y$];let Y=Z.startsWith("#"),J=Y?Z.slice(1):Z;return Y$.filter((Q)=>{if(Y)return Q.tags.some((X)=>X.includes(J));return Q.content.toLowerCase().includes(J)||Q.tags.some((X)=>X.includes(J))}).sort((Q,X)=>new Date(X.updatedAt).getTime()-new Date(Q.updatedAt).getTime())}function c4($=20){return[...Y$].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function nY(){let $=new Map;for(let Z of Y$)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 q1($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((Y)=>{let J=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=Y.tags.length>0?` [${Y.tags.map((K)=>`#${K}`).join(" ")}]`:"",X=Y.content.length>80?Y.content.slice(0,80).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${J}] ${X}${Q} {${Y.id}}`});return`Memos (${$.length}):
98
106
  ${Z.join(`
99
- `)}`}function d8(){let $=x5();if($.length===0)return"Nenhuma tag.";return`Tags:
107
+ `)}`}function b9(){let $=nY();if($.length===0)return"Nenhuma tag.";return`Tags:
100
108
  ${$.map((Y)=>` #${Y.tag} (${Y.count})`).join(`
101
- `)}`}function D5(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}async function z4($){if(x)return A5($);return L6($)}async function A5($){let Z=$.to.replace(/'/g,"''"),Y=$.subject.replace(/'/g,"''"),J=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),X=$.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 = '${J}'`,X?` $mail.CC = '${X}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
102
- `);try{let Q=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",z],{stdout:"pipe",stderr:"pipe"}),V=setTimeout(()=>Q.kill(),15000),[G]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]);await Q.exited,clearTimeout(V);let q=G.trim();if(q.includes("mailto"))return L6($);return q||"Email aberto no Outlook."}catch{return L6($)}}async function L6($){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 J=x?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${Y}'`]:["xdg-open",Y],X=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),z=setTimeout(()=>X.kill(),1e4);return await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),await X.exited,clearTimeout(z),"Email aberto no cliente de email padrao."}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}function Q4($){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(`
103
- `)}import{existsSync as u8,mkdirSync as w5,readFileSync as P5,writeFileSync as T5}from"fs";import{join as I5}from"path";var p8="",T2=[],l8=()=>I5(p8,"finance.json");function S5(){T5(l8(),JSON.stringify(T2,null,2))}function k5(){let $=l8();if(!u8($)){T2=[];return}try{T2=JSON.parse(P5($,"utf-8"))}catch{T2=[]}}function i8($){if(p8=$,!u8($))w5($,{recursive:!0});k5()}function V1($,Z,Y,J){let X={id:b5(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:J.trim(),date:new Date().toISOString()};return T2=[...T2,X],S5(),X}function K4($,Z){let Y=new Date,J=$||Y.getFullYear(),X=Z!==void 0?Z:Y.getMonth(),z=T2.filter((O)=>{let N=new Date(O.date);return N.getFullYear()===J&&N.getMonth()===X});if(z.length===0)return`Nenhuma transacao em ${m8(X)}/${J}.`;let Q=z.filter((O)=>O.type==="entrada").reduce((O,N)=>O+N.amount,0),V=z.filter((O)=>O.type==="saida").reduce((O,N)=>O+N.amount,0),G=Q-V,q=new Map;for(let O of z.filter((N)=>N.type==="saida"))q.set(O.category,(q.get(O.category)||0)+O.amount);let K=[`--- Resumo ${m8(X)}/${J} ---`,`Entradas: R$ ${Q.toFixed(2)}`,`Saidas: R$ ${V.toFixed(2)}`,`Saldo: R$ ${G.toFixed(2)} ${G>=0?"":"(NEGATIVO)"}`];if(q.size>0){K.push(""),K.push("Saidas por categoria:");let O=[...q.entries()].sort((N,M)=>M[1]-N[1]);for(let[N,M]of O){let D=V>0?Math.round(M/V*100):0;K.push(` ${N.padEnd(15)} R$ ${M.toFixed(2)} (${D}%)`)}}return K.join(`
104
- `)}function R6($=10){let Z=[...T2].sort((J,X)=>new Date(X.date).getTime()-new Date(J.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
105
- ${Z.map((J)=>{let X=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=J.type==="entrada"?"+":"-";return` [${X}] ${z} R$ ${J.amount.toFixed(2)} ${J.category} \u2014 ${J.description} [${J.id}]`}).join(`
106
- `)}`}function b5(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}function m8($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}import{existsSync as n8,mkdirSync as y5,readFileSync as _5,writeFileSync as f5}from"fs";import{join as h5}from"path";var o8="",I2=[],a8=()=>h5(o8,"decisions.json");function v5(){f5(a8(),JSON.stringify(I2,null,2))}function g5(){let $=a8();if(!n8($)){I2=[];return}try{I2=JSON.parse(_5($,"utf-8"))}catch{I2=[]}}function r8($){if(o8=$,!n8($))y5($,{recursive:!0});g5()}function s8($,Z,Y,J,X=[]){let z={id:c5(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:J?.trim(),tags:X.map((Q)=>Q.toLowerCase()),date:new Date().toISOString()};return I2=[...I2,z],v5(),z}function V4($){let Z=$.toLowerCase();return I2.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.chosen.toLowerCase().includes(Z)||Y.context.toLowerCase().includes(Z)||Y.tags.some((J)=>J.includes(Z))).sort((Y,J)=>new Date(J.date).getTime()-new Date(Y.date).getTime())}function G4($=15){return[...I2].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function K$($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((Y)=>{let J=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` [${J}] ${Y.title}${X} {${Y.id}}`});return`Decisoes (${$.length}):
109
+ `)}`}function iY(){return pY().slice(0,8)}async function $0($){if(A)return oY($);return n2($)}async function oY($){let Z=$.to.replace(/'/g,"''"),Y=$.subject.replace(/'/g,"''"),J=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),Q=$.cc?.replace(/'/g,"''")||"",X=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${Y}'`,` $mail.Body = '${J}'`,Q?` $mail.CC = '${Q}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
110
+ `);try{let K=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",X],{stdout:"pipe",stderr:"pipe"}),V=setTimeout(()=>K.kill(),15000),[G]=await Promise.all([new Response(K.stdout).text(),new Response(K.stderr).text()]);await K.exited,clearTimeout(V);let H=G.trim();if(H.includes("mailto"))return n2($);return H||"Email aberto no Outlook."}catch{return n2($)}}async function n2($){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 J=A?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${Y}'`]:["xdg-open",Y],Q=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>Q.kill(),1e4);return await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),await Q.exited,clearTimeout(X),"Email aberto no cliente de email padrao."}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}function Z0($){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(`
111
+ `)}r();import{existsSync as y9,mkdirSync as aY,readFileSync as rY}from"fs";import{join as sY}from"path";import{randomUUID as tY}from"crypto";var _9="",o$=[],h9=()=>sY(_9,"finance.json");function eY(){D(h9(),JSON.stringify(o$,null,2))}function $J(){let $=h9();if(!y9($)){o$=[];return}try{o$=JSON.parse(rY($,"utf-8"))}catch{o$=[]}}function f9($){if(_9=$,!y9($))aY($,{recursive:!0});$J()}function d4($,Z,Y,J){let Q={id:ZJ(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:J.trim(),date:new Date().toISOString()};return o$=[...o$,Q],eY(),Q}function Y0($,Z){let Y=new Date,J=$||Y.getFullYear(),Q=Z!==void 0?Z:Y.getMonth(),X=o$.filter((M)=>{let N=new Date(M.date);return N.getFullYear()===J&&N.getMonth()===Q});if(X.length===0)return`Nenhuma transacao em ${k9(Q)}/${J}.`;let K=X.filter((M)=>M.type==="entrada").reduce((M,N)=>M+N.amount,0),V=X.filter((M)=>M.type==="saida").reduce((M,N)=>M+N.amount,0),G=K-V,H=new Map;for(let M of X.filter((N)=>N.type==="saida"))H.set(M.category,(H.get(M.category)||0)+M.amount);let z=[`--- Resumo ${k9(Q)}/${J} ---`,`Entradas: R$ ${K.toFixed(2)}`,`Saidas: R$ ${V.toFixed(2)}`,`Saldo: R$ ${G.toFixed(2)} ${G>=0?"":"(NEGATIVO)"}`];if(H.size>0){z.push(""),z.push("Saidas por categoria:");let M=[...H.entries()].sort((N,E)=>E[1]-N[1]);for(let[N,E]of M){let j=V>0?Math.round(E/V*100):0;z.push(` ${N.padEnd(15)} R$ ${E.toFixed(2)} (${j}%)`)}}return z.join(`
112
+ `)}function i2($=10){let Z=[...o$].sort((J,Q)=>new Date(Q.date).getTime()-new Date(J.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
113
+ ${Z.map((J)=>{let Q=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=J.type==="entrada"?"+":"-";return` [${Q}] ${X} R$ ${J.amount.toFixed(2)} ${J.category} \u2014 ${J.description} [${J.id}]`}).join(`
114
+ `)}`}function ZJ(){return tY().slice(0,8)}function k9($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}r();import{existsSync as v9,mkdirSync as YJ,readFileSync as JJ}from"fs";import{join as QJ}from"path";import{randomUUID as XJ}from"crypto";var g9="",a$=[],m9=()=>QJ(g9,"decisions.json");function KJ(){D(m9(),JSON.stringify(a$,null,2))}function zJ(){let $=m9();if(!v9($)){a$=[];return}try{a$=JSON.parse(JJ($,"utf-8"))}catch{a$=[]}}function c9($){if(g9=$,!v9($))YJ($,{recursive:!0});zJ()}function d9($,Z,Y,J,Q=[]){let X={id:VJ(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:J?.trim(),tags:Q.map((K)=>K.toLowerCase()),date:new Date().toISOString()};return a$=[...a$,X],KJ(),X}function J0($){let Z=$.toLowerCase();return a$.filter((Y)=>Y.title.toLowerCase().includes(Z)||Y.chosen.toLowerCase().includes(Z)||Y.context.toLowerCase().includes(Z)||Y.tags.some((J)=>J.includes(Z))).sort((Y,J)=>new Date(J.date).getTime()-new Date(Y.date).getTime())}function Q0($=15){return[...a$].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function h1($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((Y)=>{let J=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` [${J}] ${Y.title}${Q} {${Y.id}}`});return`Decisoes (${$.length}):
107
115
  ${Z.join(`
108
- `)}`}function c5(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}W1();import{existsSync as J0,mkdirSync as n5,readFileSync as o5,writeFileSync as a5}from"fs";import{join as r5}from"path";var X0="",A={people:[],interactions:[],delegations:[]},z0=()=>r5(X0,"people.json");function H4(){a5(z0(),JSON.stringify(A,null,2))}function s5(){let $=z0();if(!J0($)){A={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(o5($,"utf-8"));A={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{A={people:[],interactions:[],delegations:[]}}}function Q0($){if(X0=$,!J0($))n5($,{recursive:!0});s5()}function U4($,Z,Y,J){let X={id:f6(),name:$.trim(),group:Z,role:Y?.trim(),contact:J?.trim(),createdAt:new Date().toISOString()};return A={...A,people:[...A.people,X]},H4(),X}function S2($){let Z=$.toLowerCase();return A.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function B4($){if($)return A.people.filter((Z)=>Z.group===$);return[...A.people]}function K0($,Z,Y,J){let X=S2($);if(!X)return null;let z={id:f6(),personId:X.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:J?.toISOString(),followUpDone:!1};return A={...A,interactions:[...A.interactions,z]},H4(),z}function t5($,Z=10){let Y=S2($);if(!Y)return[];return[...A.interactions].filter((J)=>J.personId===Y.id).reverse().sort((J,X)=>new Date(X.date).getTime()-new Date(J.date).getTime()).slice(0,Z)}function q1(){let $=new Date,Z=[];for(let Y of A.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let J=new Date(Y.followUpDate);if(isNaN(J.getTime()))continue;if(J<=$){let X=A.people.find((z)=>z.id===Y.personId);if(X)Z.push({person:X,interaction:Y})}}return Z.sort((Y,J)=>new Date(Y.interaction.followUpDate).getTime()-new Date(J.interaction.followUpDate).getTime())}function N4($,Z,Y){let J=S2($);if(!J)return null;let X={id:f6(),personId:J.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return A={...A,delegations:[...A.delegations,X]},H4(),X}function V0($,Z,Y){if(!A.delegations.find((X)=>X.id===$))return null;return A={...A,delegations:A.delegations.map((X)=>X.id===$?{...X,status:Z,notes:Y||X.notes}:X)},H4(),A.delegations.find((X)=>X.id===$)||null}function V$($,Z=!0){let Y=[...A.delegations];if($){let X=S2($);if(!X)return[];Y=Y.filter((z)=>z.personId===X.id)}if(Z)Y=Y.filter((X)=>X.status!=="concluido");let J=new Date;return Y=Y.map((X)=>{if(X.status==="pendente"&&X.dueDate){let z=new Date(X.dueDate);if(!isNaN(z.getTime())&&z<J)return{...X,status:"atrasado"}}return X}),Y.sort((X,z)=>{if(X.status==="atrasado"&&z.status!=="atrasado")return-1;if(z.status==="atrasado"&&X.status!=="atrasado")return 1;let Q=X.dueDate?new Date(X.dueDate).getTime():1/0,V=z.dueDate?new Date(z.dueDate).getTime():1/0;return Q-V})}var G0={equipe:"Equipe",familia:"Familia",contato:"Contato"};function C4($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let X of $){let z=Z.get(X.group)||[];Z.set(X.group,[...z,X])}let Y=[],J=["equipe","familia","contato"];for(let X of J){let z=Z.get(X);if(!z?.length)continue;let Q=z.map((V)=>{let G=V.role?` (${V.role})`:"",q=V.contact?` \u2014 ${V.contact}`:"";return` ${V.name}${G}${q} [${V.id}]`});Y.push(`--- ${G0[X]} ---
109
- ${Q.join(`
116
+ `)}`}function VJ(){return XJ().slice(0,8)}p4();r();import{existsSync as a9,mkdirSync as NJ,readFileSync as CJ}from"fs";import{join as MJ}from"path";import{randomUUID as OJ}from"crypto";var r9="",P={people:[],interactions:[],delegations:[]},s9=()=>MJ(r9,"people.json");function z0(){D(s9(),JSON.stringify(P,null,2))}function EJ(){let $=s9();if(!a9($)){P={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(CJ($,"utf-8"));P={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{P={people:[],interactions:[],delegations:[]}}}function t9($){if(r9=$,!a9($))NJ($,{recursive:!0});EJ()}function V0($,Z,Y,J){let Q={id:K7(),name:$.trim(),group:Z,role:Y?.trim(),contact:J?.trim(),createdAt:new Date().toISOString()};return P={...P,people:[...P.people,Q]},z0(),Q}function r$($){let Z=$.toLowerCase();return P.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function G0($){if($)return P.people.filter((Z)=>Z.group===$);return[...P.people]}function e9($,Z,Y,J){let Q=r$($);if(!Q)return null;let X={id:K7(),personId:Q.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:J?.toISOString(),followUpDone:!1};return P={...P,interactions:[...P.interactions,X]},z0(),X}function LJ($,Z=10){let Y=r$($);if(!Y)return[];return[...P.interactions].filter((J)=>J.personId===Y.id).reverse().sort((J,Q)=>new Date(Q.date).getTime()-new Date(J.date).getTime()).slice(0,Z)}function l4(){let $=new Date,Z=[];for(let Y of P.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let J=new Date(Y.followUpDate);if(isNaN(J.getTime()))continue;if(J<=$){let Q=P.people.find((X)=>X.id===Y.personId);if(Q)Z.push({person:Q,interaction:Y})}}return Z.sort((Y,J)=>new Date(Y.interaction.followUpDate).getTime()-new Date(J.interaction.followUpDate).getTime())}function W0($,Z,Y){let J=r$($);if(!J)return null;let Q={id:K7(),personId:J.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return P={...P,delegations:[...P.delegations,Q]},z0(),Q}function $Z($,Z,Y){if(!P.delegations.find((Q)=>Q.id===$))return null;return P={...P,delegations:P.delegations.map((Q)=>Q.id===$?{...Q,status:Z,notes:Y||Q.notes}:Q)},z0(),P.delegations.find((Q)=>Q.id===$)||null}function f1($,Z=!0){let Y=[...P.delegations];if($){let Q=r$($);if(!Q)return[];Y=Y.filter((X)=>X.personId===Q.id)}if(Z)Y=Y.filter((Q)=>Q.status!=="concluido");let J=new Date;return Y=Y.map((Q)=>{if(Q.status==="pendente"&&Q.dueDate){let X=new Date(Q.dueDate);if(!isNaN(X.getTime())&&X<J)return{...Q,status:"atrasado"}}return Q}),Y.sort((Q,X)=>{if(Q.status==="atrasado"&&X.status!=="atrasado")return-1;if(X.status==="atrasado"&&Q.status!=="atrasado")return 1;let K=Q.dueDate?new Date(Q.dueDate).getTime():1/0,V=X.dueDate?new Date(X.dueDate).getTime():1/0;return K-V})}var ZZ={equipe:"Equipe",familia:"Familia",contato:"Contato"};function H0($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let Q of $){let X=Z.get(Q.group)||[];Z.set(Q.group,[...X,Q])}let Y=[],J=["equipe","familia","contato"];for(let Q of J){let X=Z.get(Q);if(!X?.length)continue;let K=X.map((V)=>{let G=V.role?` (${V.role})`:"",H=V.contact?` \u2014 ${V.contact}`:"";return` ${V.name}${G}${H} [${V.id}]`});Y.push(`--- ${ZZ[Q]} ---
117
+ ${K.join(`
110
118
  `)}`)}return Y.join(`
111
119
 
112
- `)}function j4($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${G0[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=t5($.id,5);if(Y.length>0){Z.push(`
113
- Interacoes recentes:`);for(let X of Y){let z=new Date(X.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${z}] ${X.type}: ${X.summary}`)}}let J=V$($.id);if(J.length>0){Z.push(`
114
- Tarefas delegadas:`);for(let X of J){let z=X.status==="atrasado"?"!!":X.status==="em_andamento"?">>":" ",Q=X.dueDate?` (${h6(X.dueDate)})`:"";Z.push(` ${z} ${X.task}${Q} [${X.status}]`)}}return Z.join(`
115
- `)}function O4($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let X=A.people.find((V)=>V.id===Y.personId)?.name||"?",z=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",Q=Y.dueDate?` (${h6(Y.dueDate)})`:"";return`${z}${X}: ${Y.task}${Q} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
120
+ `)}function q0($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${ZZ[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=LJ($.id,5);if(Y.length>0){Z.push(`
121
+ Interacoes recentes:`);for(let Q of Y){let X=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${X}] ${Q.type}: ${Q.summary}`)}}let J=f1($.id);if(J.length>0){Z.push(`
122
+ Tarefas delegadas:`);for(let Q of J){let X=Q.status==="atrasado"?"!!":Q.status==="em_andamento"?">>":" ",K=Q.dueDate?` (${z7(Q.dueDate)})`:"";Z.push(` ${X} ${Q.task}${K} [${Q.status}]`)}}return Z.join(`
123
+ `)}function U0($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let Q=P.people.find((V)=>V.id===Y.personId)?.name||"?",X=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",K=Y.dueDate?` (${z7(Y.dueDate)})`:"";return`${X}${Q}: ${Y.task}${K} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
116
124
  ${Z.join(`
117
- `)}`}function F4($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:J})=>{return` [${h6(J.followUpDate)}] ${Y.name}: ${J.summary} [${J.id}]`});return`Follow-ups pendentes (${$.length}):
125
+ `)}`}function B0($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:J})=>{return` [${z7(J.followUpDate)}] ${Y.name}: ${J.summary} [${J.id}]`});return`Follow-ups pendentes (${$.length}):
118
126
  ${Z.join(`
119
- `)}`}function E4(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
120
- `);let Z=A.people.filter((q)=>q.group==="equipe").length,Y=A.people.filter((q)=>q.group==="familia").length,J=A.people.filter((q)=>q.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${J}`);let X=q1();if(X.length>0){$.push(`
121
- !! ${X.length} follow-up(s) pendente(s):`);for(let{person:q,interaction:K}of X.slice(0,5))$.push(` ${q.name}: ${K.summary}`)}let z=V$(),Q=z.filter((q)=>q.status==="atrasado"),V=z.filter((q)=>q.status==="pendente"||q.status==="em_andamento");if(Q.length>0){$.push(`
122
- !! ${Q.length} delegacao(oes) atrasada(s):`);for(let q of Q.slice(0,5)){let K=A.people.find((O)=>O.id===q.personId);$.push(` ${K?.name}: ${q.task}`)}}if(V.length>0)$.push(`
123
- ${V.length} delegacao(oes) em andamento`);let G=[...A.interactions].sort((q,K)=>new Date(K.date).getTime()-new Date(q.date).getTime()).slice(0,3);if(G.length>0){$.push(`
124
- Ultimas interacoes:`);for(let q of G){let K=A.people.find((N)=>N.id===q.personId),O=new Date(q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${O}] ${K?.name}: ${q.summary}`)}}return $.push(`
127
+ `)}`}function N0(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
128
+ `);let Z=P.people.filter((H)=>H.group==="equipe").length,Y=P.people.filter((H)=>H.group==="familia").length,J=P.people.filter((H)=>H.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${J}`);let Q=l4();if(Q.length>0){$.push(`
129
+ !! ${Q.length} follow-up(s) pendente(s):`);for(let{person:H,interaction:z}of Q.slice(0,5))$.push(` ${H.name}: ${z.summary}`)}let X=f1(),K=X.filter((H)=>H.status==="atrasado"),V=X.filter((H)=>H.status==="pendente"||H.status==="em_andamento");if(K.length>0){$.push(`
130
+ !! ${K.length} delegacao(oes) atrasada(s):`);for(let H of K.slice(0,5)){let z=P.people.find((M)=>M.id===H.personId);$.push(` ${z?.name}: ${H.task}`)}}if(V.length>0)$.push(`
131
+ ${V.length} delegacao(oes) em andamento`);let G=[...P.interactions].sort((H,z)=>new Date(z.date).getTime()-new Date(H.date).getTime()).slice(0,3);if(G.length>0){$.push(`
132
+ Ultimas interacoes:`);for(let H of G){let z=P.people.find((N)=>N.id===H.personId),M=new Date(H.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${M}] ${z?.name}: ${H.summary}`)}}return $.push(`
125
133
  ========================`),$.join(`
126
- `)}function f6(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}function h6($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,J=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),X=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(X.getTime()===J.getTime())return"hoje";let z=new Date(J);if(z.setDate(z.getDate()+1),X.getTime()===z.getTime())return"amanha";let Q=Math.floor((X.getTime()-J.getTime())/86400000);if(Q<0)return`${Math.abs(Q)}d atras`;if(Q<=7)return`em ${Q}d`;return Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}import{existsSync as W0,mkdirSync as e5,readFileSync as $9,writeFileSync as Z9}from"fs";import{join as Y9}from"path";var q0="",h=[],H0=()=>Y9(q0,"materials.json");function v6(){Z9(H0(),JSON.stringify(h,null,2))}function J9(){let $=H0();if(!W0($)){h=[];return}try{h=JSON.parse($9($,"utf-8"))}catch{h=[]}}function U0($){if(q0=$,!W0($))e5($,{recursive:!0});J9()}function M4($,Z,Y="geral",J=[]){let X=new Date().toISOString(),z=Z.match(/#(\w+)/g)?.map((q)=>q.slice(1).toLowerCase())||[],Q=$.match(/#(\w+)/g)?.map((q)=>q.slice(1).toLowerCase())||[],V=[...new Set([...J.map((q)=>q.toLowerCase()),...z,...Q])],G={id:X9(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:V,createdAt:X,updatedAt:X};return h=[...h,G],v6(),G}function B0($,Z){let Y=h.find((q)=>q.id===$);if(!Y)return null;let J=Z.content??Y.content,X=Z.title??Y.title,z=J.match(/#(\w+)/g)?.map((q)=>q.slice(1).toLowerCase())||[],Q=X.match(/#(\w+)/g)?.map((q)=>q.slice(1).toLowerCase())||[],V=Z.tags??Y.tags,G=[...new Set([...V.map((q)=>q.toLowerCase()),...z,...Q])];return h=h.map((q)=>q.id===$?{...q,title:X.trim(),content:J.trim(),category:(Z.category??q.category).toLowerCase().trim(),tags:G,updatedAt:new Date().toISOString()}:q),v6(),h.find((q)=>q.id===$)||null}function L4($){let Z=h.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return h=[...h.slice(0,Z),...h.slice(Z+1)],v6(),!0}function N0($){return h.find((Z)=>Z.id===$)||null}function R4($){let Z=$.toLowerCase().trim();if(!Z)return[...h];let Y=Z.startsWith("#"),J=Z.startsWith("@"),X=Y||J?Z.slice(1):Z;return h.filter((z)=>{if(Y)return z.tags.some((Q)=>Q.includes(X));if(J)return z.category.includes(X);return z.title.toLowerCase().includes(X)||z.content.toLowerCase().includes(X)||z.category.toLowerCase().includes(X)||z.tags.some((Q)=>Q.includes(X))}).sort((z,Q)=>new Date(Q.updatedAt).getTime()-new Date(z.updatedAt).getTime())}function G$($=30,Z){let Y=[...h];if(Z){let J=Z.toLowerCase().trim();Y=Y.filter((X)=>X.category===J)}return Y.sort((J,X)=>new Date(X.updatedAt).getTime()-new Date(J.updatedAt).getTime()).slice(0,$)}function C0(){let $=new Map;for(let Z of h)$.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 j0(){if(h.length===0)return"";let $=C0(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let J=h.filter((X)=>X.category===Y).sort((X,z)=>new Date(z.updatedAt).getTime()-new Date(X.updatedAt).getTime());Z.push(`
127
- [${Y}]`);for(let X of J){let z=X.content.length>200?X.content.slice(0,200).replace(/\n/g," ")+"...":X.content.replace(/\n/g," "),Q=X.tags.length>0?` [${X.tags.map((V)=>`#${V}`).join(" ")}]`:"";Z.push(` \u2022 ${X.title}: ${z}${Q}`)}}return Z.join(`
128
- `)}function k2($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((Y)=>{let J=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.tags.length>0?` [${Y.tags.map((Q)=>`#${Q}`).join(" ")}]`:"",z=Y.content.length>60?Y.content.slice(0,60).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${J}] (${Y.category}) ${Y.title} \u2014 ${z}${X} {${Y.id}}`});return`Materiais (${$.length}):
134
+ `)}function K7(){return OJ().slice(0,8)}function z7($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,J=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),Q=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(Q.getTime()===J.getTime())return"hoje";let X=new Date(J);if(X.setDate(X.getDate()+1),Q.getTime()===X.getTime())return"amanha";let K=Math.floor((Q.getTime()-J.getTime())/86400000);if(K<0)return`${Math.abs(K)}d atras`;if(K<=7)return`em ${K}d`;return Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}r();import{existsSync as YZ,mkdirSync as jJ,readFileSync as FJ}from"fs";import{join as RJ}from"path";import{randomUUID as AJ}from"crypto";var JZ="",g=[],QZ=()=>RJ(JZ,"materials.json");function V7(){D(QZ(),JSON.stringify(g,null,2))}function xJ(){let $=QZ();if(!YZ($)){g=[];return}try{g=JSON.parse(FJ($,"utf-8"))}catch{g=[]}}function XZ($){if(JZ=$,!YZ($))jJ($,{recursive:!0});xJ()}function C0($,Z,Y="geral",J=[]){let Q=new Date().toISOString(),X=Z.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],K=$.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],V=[...new Set([...J.map((H)=>H.toLowerCase()),...X,...K])],G={id:DJ(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:V,createdAt:Q,updatedAt:Q};return g=[...g,G],V7(),G}function KZ($,Z){let Y=g.find((H)=>H.id===$);if(!Y)return null;let J=Z.content??Y.content,Q=Z.title??Y.title,X=J.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],K=Q.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],V=Z.tags??Y.tags,G=[...new Set([...V.map((H)=>H.toLowerCase()),...X,...K])];return g=g.map((H)=>H.id===$?{...H,title:Q.trim(),content:J.trim(),category:(Z.category??H.category).toLowerCase().trim(),tags:G,updatedAt:new Date().toISOString()}:H),V7(),g.find((H)=>H.id===$)||null}function M0($){let Z=g.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return g=[...g.slice(0,Z),...g.slice(Z+1)],V7(),!0}function zZ($){return g.find((Z)=>Z.id===$)||null}function O0($){let Z=$.toLowerCase().trim();if(!Z)return[...g];let Y=Z.startsWith("#"),J=Z.startsWith("@"),Q=Y||J?Z.slice(1):Z;return g.filter((X)=>{if(Y)return X.tags.some((K)=>K.includes(Q));if(J)return X.category.includes(Q);return X.title.toLowerCase().includes(Q)||X.content.toLowerCase().includes(Q)||X.category.toLowerCase().includes(Q)||X.tags.some((K)=>K.includes(Q))}).sort((X,K)=>new Date(K.updatedAt).getTime()-new Date(X.updatedAt).getTime())}function v1($=30,Z){let Y=[...g];if(Z){let J=Z.toLowerCase().trim();Y=Y.filter((Q)=>Q.category===J)}return Y.sort((J,Q)=>new Date(Q.updatedAt).getTime()-new Date(J.updatedAt).getTime()).slice(0,$)}function VZ(){let $=new Map;for(let Z of g)$.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 GZ(){if(g.length===0)return"";let $=VZ(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let J=g.filter((Q)=>Q.category===Y).sort((Q,X)=>new Date(X.updatedAt).getTime()-new Date(Q.updatedAt).getTime());Z.push(`
135
+ [${Y}]`);for(let Q of J){let X=Q.content.length>200?Q.content.slice(0,200).replace(/\n/g," ")+"...":Q.content.replace(/\n/g," "),K=Q.tags.length>0?` [${Q.tags.map((V)=>`#${V}`).join(" ")}]`:"";Z.push(` \u2022 ${Q.title}: ${X}${K}`)}}return Z.join(`
136
+ `)}function s$($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((Y)=>{let J=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=Y.tags.length>0?` [${Y.tags.map((K)=>`#${K}`).join(" ")}]`:"",X=Y.content.length>60?Y.content.slice(0,60).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${J}] (${Y.category}) ${Y.title} \u2014 ${X}${Q} {${Y.id}}`});return`Materiais (${$.length}):
129
137
  ${Z.join(`
130
- `)}`}function O0($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),Y=new Date($.updatedAt).toLocaleDateString("pt-BR"),J=$.tags.length>0?`Tags: ${$.tags.map((z)=>`#${z}`).join(" ")}`:"",X=Z===Y?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${Y}`;return`--- Material {${$.id}} ---
138
+ `)}`}function WZ($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),Y=new Date($.updatedAt).toLocaleDateString("pt-BR"),J=$.tags.length>0?`Tags: ${$.tags.map((X)=>`#${X}`).join(" ")}`:"",Q=Z===Y?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${Y}`;return`--- Material {${$.id}} ---
131
139
  Titulo: ${$.title}
132
140
  Categoria: ${$.category}
133
141
 
134
142
  ${$.content}
135
143
 
136
144
  ${J}
137
- ${X}`}function F0(){let $=C0();if($.length===0)return"Nenhuma categoria.";return`Categorias:
145
+ ${Q}`}function HZ(){let $=VZ();if($.length===0)return"Nenhuma categoria.";return`Categorias:
138
146
  ${$.map((Y)=>` @${Y.category} (${Y.count})`).join(`
139
- `)}`}function X9(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}var q$=new N6,D0=[];function A0($){D0=$}var r=[{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"]}}],w0=[{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:[]}}],q9=[{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:[]}}],H9=[{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:[]}}],U9=[{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"]}}],B9={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"]}},N9=[{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"]}}],C9=[{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:[]}}],j9=[{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"]}}],O9=[{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:[]}}],F9=w0.find(($)=>$.name==="get_news"),E0=!1,O2=null;function P0($){O2=$}function T0(){if(E0)return;if(E0=!0,x)r.push(...w0);else r.push(F9);r.push(...q9),r.push(...H9),r.push(...U9),r.push(B9),r.push(...N9),r.push(...C9),r.push(...j9),r.push(...O9)}var D4=50000;async function m6($,Z){try{switch($){case"read_file":return E9(Z);case"write_file":return M9(Z);case"edit_file":return L9(Z);case"search_files":return await R9(Z);case"find_files":return await A9(Z);case"list_directory":return w9(Z);case"run_command":return await P9(Z);case"fetch_url":return await T9(Z);case"open_application":return await J$(Z.name,Z.argument);case"open_file_default":return await t1(Z.path);case"open_url_browser":return await s1(Z.url);case"get_running_apps":return await e1();case"get_system_info":return await X$();case"get_calendar_events":return await A2();case"get_news":{let Y=Z.category;return await w2(Y?[Y]:void 0)}case"create_task":{let Y=Z.title;if(!Y?.trim())return"Error: title is required.";let J=Z.time,X=J?Q1(J):void 0,z=Z4(Y,X||void 0),Q=X?` \u2014 lembrete: ${X.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${z.title}"${Q} [${z.id}]`}case"complete_task":{let Y=Z.reference;if(!Y?.trim())return"Error: reference is required.";let J=Y4(Y);return J?`Concluida: "${J.title}"`:`Tarefa nao encontrada: "${Y}"`}case"list_tasks":{let Y=Z.show_done||!1,J=P2(Y);return m2(J)}case"add_person":{let Y=Z.name;if(!Y?.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 z=U4(Y,J,Z.role,Z.contact);return`Pessoa adicionada: ${z.name} (${J}) [${z.id}]`}case"find_person_info":{let Y=Z.name_or_id;if(!Y?.trim())return"Error: name_or_id is required.";let J=S2(Y);if(!J)return`Pessoa nao encontrada: "${Y}"`;return j4(J)}case"list_people":{let Y=Z.group,J=B4(Y);return C4(J)}case"log_interaction":{let Y=Z.person;if(!Y?.trim())return"Error: person is required.";let{type:J,summary:X}=Z;if(!X?.trim())return"Error: summary is required.";let z=Z.follow_up,Q=z?R0(z):void 0;if(!K0(Y,J,X,Q||void 0))return`Pessoa nao encontrada: "${Y}"`;let G=Q?` \u2014 follow-up: ${Q.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${J} com ${Y}${G}`}case"delegate_to_person":{let Y=Z.person;if(!Y?.trim())return"Error: person is required.";let J=Z.task;if(!J?.trim())return"Error: task is required.";let X=Z.due_date,z=X?R0(X):void 0,Q=N4(Y,J,z||void 0);if(!Q)return`Pessoa nao encontrada: "${Y}"`;let V=z?` \u2014 prazo: ${z.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Y}: "${J}"${V} [${Q.id}]`}case"update_delegation_status":{let Y=Z.delegation_id;if(!Y?.trim())return"Error: delegation_id is required.";let J=Z.status,X=V0(Y,J,Z.notes);if(!X)return`Delegacao nao encontrada: "${Y}"`;return`Delegacao atualizada: "${X.task}" -> ${J}`}case"get_people_dashboard":return E4();case"save_memo":{let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let J=Z.tags||[],X=J4(Y,J);return`Memo salvo${X.tags.length>0?` [${X.tags.map((Q)=>"#"+Q).join(" ")}]`:""} {${X.id}}`}case"search_memos":{let Y=Z.query;if(!Y?.trim())return u2(K1());let J=X4(Y);return u2(J)}case"record_transaction":{let{type:Y,amount:J,category:X,description:z}=Z;if(!Y||!J||!X||!z)return"Error: all fields required.";let Q=V1(Y,J,X,z);return`${Q.type==="entrada"?"+":"-"} R$ ${Q.amount.toFixed(2)} (${Q.category}) \u2014 ${Q.description} [${Q.id}]`}case"financial_summary":return K4();case"log_decision":{let{title:Y,context:J,chosen:X}=Z;if(!Y||!J||!X)return"Error: title, context, and chosen are required.";let z=s8(Y,J,X,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${z.title}" {${z.id}}`}case"search_decisions":{let Y=Z.query;if(!Y?.trim())return K$(G4());return K$(V4(Y))}case"open_investigation":{let Y=Z.title;if(!Y?.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 z=D6(Y,J,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${z.title}" (${z.type}) {${z.id}}`}case"collect_evidence":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let{source:J,label:X,content:z}=Z;if(!X?.trim()||!z?.trim())return"Error: label and content are required.";let Q=A6(Y,J,X,z,Z.path);if(!Q)return`Investigacao nao encontrada: "${Y}"`;return`Evidencia coletada: [${Q.id}] ${Q.source}: ${Q.label}`}case"add_finding":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let{severity:J,title:X,description:z}=Z;if(!X?.trim()||!z?.trim())return"Error: title and description are required.";let Q=Z.evidence_ids||[],V=w6(Y,J,X,z,Q);if(!V)return`Investigacao nao encontrada: "${Y}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=Z.summary;if(!J?.trim())return"Error: summary is required.";let X=P6(Y,J,Z.recommendations);if(!X)return`Investigacao nao encontrada: "${Y}"`;return`Investigacao concluida: "${X.title}" \u2014 ${X.evidence.length} evidencias, ${X.findings.length} conclusoes`}case"investigation_status":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=T6(Y);if(!J)return`Investigacao nao encontrada: "${Y}"`;return b6(J)}case"investigation_report":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=k6(Y);if(!J)return`Investigacao nao encontrada: "${Y}"`;return J}case"list_investigations":{let Y=Z.query;if(Y?.trim())return q4(S6(Y));let{status:J,type:X}=Z;return q4(I6(J,X))}case"draft_email":{let{to:Y,subject:J,body:X}=Z;if(!Y?.trim()||!J?.trim()||!X?.trim())return"Error: to, subject, and body are required.";let z={to:Y,subject:J,body:X,cc:Z.cc},Q=Q4(z),V=await z4(z);return`${Q}
147
+ `)}`}function DJ(){return AJ().slice(0,8)}r();import{existsSync as B1,mkdirSync as TJ,readFileSync as g1,readdirSync as PJ}from"fs";import{join as U1}from"path";import{createHash as wJ}from"crypto";var BZ=1,G7=400,IJ=80,qZ=1.5,UZ=0.75,SJ=10,bJ=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"]),n4="",E0="",i=[],b$={},k$=0,y$={},L0=!1,H7=()=>U1(E0,"rag-index.json");function NZ($){if(n4=$,E0=U1($,"rag"),!B1(E0))TJ(E0,{recursive:!0});gJ(),L0=!0}function j0(){return L0}function F0(){return{chunks:i.length,sources:Object.keys(y$).length,builtAt:i.length>0?mJ()?.builtAt??null:null}}function R0(){if(!L0)throw Error("Memory not initialized. Call initMemory() first.");let $=hJ(),Z=0,Y=0,J={},Q=new Set;for(let[K,V]of Object.entries($)){let G=cJ(V);if(J[K]=G,y$[K]!==G)Q.add(K)}let X=Object.keys(y$).filter((K)=>!(K in $));if(Q.size===0&&X.length===0)return{indexed:0,skipped:Object.keys($).length,total:i.length};i=i.filter((K)=>{let V=`${K.source}:${K.sourceId}`;return!Q.has(V)&&!X.includes(V)});for(let K of Q){let V=$[K],G=K.indexOf(":");if(G===-1)continue;let H=K.slice(0,G),z=K.slice(G+1);if(!["memo","material","session","decision"].includes(H))continue;let N=dJ(H,z,V),E=_J(V,H,z,N);i=[...i,...E],Z++}return Y=Object.keys($).length-Z,fJ(),y$=J,vJ(),{indexed:Z,skipped:Y,total:i.length}}function A0($,Z=3){if(i.length===0)return[];let Y=W7($);if(Y.length===0)return[];return i.map((Q)=>{let X=kJ(Y,Q),K=yJ(Y,Q),V=0.6*X+0.4*K;return{chunk:Q,score:V}}).filter((Q)=>Q.score>0).sort((Q,X)=>X.score-Q.score).slice(0,Math.min(Z,SJ))}function x0($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,J)=>{let Q=uJ(Y.chunk.source),X=(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`[${J+1}] ${Q}: ${Y.chunk.title} (relevancia: ${X}%)
148
+ ${K}`});return`Resultados da memoria (${$.length}):
140
149
 
141
- ${V}`}case"save_material":{let Y=Z.title;if(!Y?.trim())return"Error: title is required.";let J=Z.content;if(!J?.trim())return"Error: content is required.";let X=Z.category||"geral",z=Z.tags||[],Q=M4(Y,J,X,z),V=Q.tags.length>0?` [${Q.tags.map((G)=>"#"+G).join(" ")}]`:"";return`Material salvo: "${Q.title}" (${Q.category})${V} {${Q.id}}`}case"search_materials":{let Y=Z.query;if(!Y?.trim())return k2(G$());let J=R4(Y);return k2(J)}case"list_materials":{let Y=Z.category,J=Z.limit||30,X=G$(J,Y);return k2(X)}case"update_material":{let Y=Z.id;if(!Y?.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 X=B0(Y,J);if(!X)return`Material nao encontrado: "${Y}"`;return`Material atualizado: "${X.title}" (${X.category}) {${X.id}}`}case"delete_material":{let Y=Z.id;if(!Y?.trim())return"Error: id is required.";return L4(Y)?"Material removido.":`Material nao encontrado: "${Y}"`}case"archive_session":{if(!O2)return"Error: session manager not initialized.";let Y=Z.name;if(!Y?.trim())return"Error: name is required.";if(Y==="all"){let J=O2.archiveAll();return J.length>0?`Arquivadas ${J.length} sessoes: ${J.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return O2.archive(Y)?`Sessao arquivada: "${Y}"`:`Falha ao arquivar "${Y}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!O2)return"Error: session manager not initialized.";let Y=Z.name;if(!Y?.trim())return"Error: name is required.";return O2.unarchive(Y)?`Sessao restaurada: "${Y}"`:`Sessao arquivada nao encontrada: "${Y}"`}case"list_archived_sessions":{if(!O2)return"Error: session manager not initialized.";let Y=O2.listArchived();if(Y.length===0)return"Nenhuma sessao arquivada.";let J=Y.map((X)=>{let z=O2.getArchivedInfo(X),Q=z?new Date(z.updated).toLocaleDateString("pt-BR"):"",V=z?`${z.messageCount} msgs`:"";return` ${X.padEnd(20)} ${V.padEnd(10)} ${Q}`});return`Sessoes arquivadas (${Y.length}):
150
+ ${Z.join(`
151
+
152
+ `)}`}function kJ($,Z){let Y=Z.tokens.length;if(Y===0||k$===0)return 0;let J=new Map;for(let X of Z.tokens)J.set(X,(J.get(X)??0)+1);let Q=0;for(let X of $){let K=J.get(X)??0;if(K===0)continue;let V=b$[X]??0;if(V===0)continue;let G=K*(qZ+1),H=K+qZ*(1-UZ+UZ*(Y/k$));Q+=V*(G/H)}return Q}function yJ($,Z){let Y=new Map;for(let H of $)Y.set(H,(Y.get(H)??0)+1);let J=new Map;for(let H of Z.tokens)J.set(H,(J.get(H)??0)+1);let Q=new Set([...$,...Z.tokens]),X=0,K=0,V=0;for(let H of Q){let z=b$[H]??0,M=(Y.get(H)??0)*z,N=(J.get(H)??0)*z;X+=M*N,K+=M*M,V+=N*N}let G=Math.sqrt(K)*Math.sqrt(V);return G>0?X/G:0}function W7($){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&&!bJ.has(Z))}function _J($,Z,Y,J){let Q=$.trim();if(Q.length===0)return[];if(Q.length<=G7)return[{id:`${Z}:${Y}:0`,source:Z,sourceId:Y,title:J,content:Q,tokens:W7(Q)}];let X=[],K=0,V=0;while(K<Q.length){let G=Math.min(K+G7,Q.length),H=Q.slice(K,G);X.push({id:`${Z}:${Y}:${V}`,source:Z,sourceId:Y,title:J,content:H,tokens:W7(H)}),K+=G7-IJ,V++}return X}function hJ(){let $={},Z=U1(n4,"memos.json");if(B1(Z))try{let X=JSON.parse(g1(Z,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let K of X){if(!K||typeof K!=="object")continue;let V=K;if(typeof V.id!=="string"||typeof V.content!=="string")continue;let G=Array.isArray(V.tags)&&V.tags.length>0?` [${V.tags.join(", ")}]`:"";$[`memo:${V.id}`]=`${V.content}${G}`}}catch{}let Y=U1(n4,"materials.json");if(B1(Y))try{let X=JSON.parse(g1(Y,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let K of X){if(!K||typeof K!=="object")continue;let V=K;if(typeof V.id!=="string"||typeof V.title!=="string"||typeof V.content!=="string")continue;let G=typeof V.category==="string"?V.category:"geral",H=Array.isArray(V.tags)&&V.tags.length>0?` [${V.tags.join(", ")}]`:"";$[`material:${V.id}`]=`${V.title}
153
+ ${G}
154
+ ${V.content}${H}`}}catch{}let J=U1(n4,"decisions.json");if(B1(J))try{let X=JSON.parse(g1(J,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let K of X){if(!K||typeof K!=="object")continue;let V=K;if(typeof V.id!=="string"||typeof V.title!=="string"||typeof V.context!=="string"||typeof V.chosen!=="string")continue;let G=[V.title,V.context,`Escolha: ${V.chosen}`];if(typeof V.alternatives==="string")G.push(`Alternativas: ${V.alternatives}`);if(Array.isArray(V.tags)&&V.tags.length>0)G.push(`[${V.tags.join(", ")}]`);$[`decision:${V.id}`]=G.join(`
155
+ `)}}catch{}let Q=U1(n4,"sessions");if(B1(Q))try{let X=PJ(Q,{withFileTypes:!0}).filter((K)=>K.isFile()&&K.name.endsWith(".json")&&!K.name.startsWith(".")).map((K)=>K.name);for(let K of X){let V=U1(Q,K);try{let G=JSON.parse(g1(V,"utf-8"));if(!G||typeof G!=="object"||!Array.isArray(G.messages))continue;let H=G.messages.filter((z)=>{if(!z||typeof z!=="object")return!1;let M=z;return M.role==="assistant"&&typeof M.content==="string"&&M.content.length>50}).map((z)=>z.content).join(`
156
+ ---
157
+ `);if(H.length>0)$[`session:${G.id}`]=H}catch{}}}catch{}return $}function fJ(){let $=i.length;if($===0){b$={},k$=0;return}let Z=new Map,Y=0;for(let Q of i){let X=new Set;for(let K of Q.tokens)if(!X.has(K))Z.set(K,(Z.get(K)??0)+1),X.add(K);Y+=Q.tokens.length}k$=Y/$;let J={};for(let[Q,X]of Z)J[Q]=Math.log(($-X+0.5)/(X+0.5)+1);b$=J}function vJ(){if(!L0)return;let $={chunks:i,idf:b$,avgDocLength:k$,sourceHashes:y$,builtAt:new Date().toISOString(),version:BZ};D(H7(),JSON.stringify($))}function gJ(){let $=H7();if(!B1($)){i=[],b$={},k$=0,y$={};return}try{let Z=JSON.parse(g1($,"utf-8"));if(Z.version!==BZ){i=[],b$={},k$=0,y$={};return}i=Z.chunks,b$=Z.idf,k$=Z.avgDocLength,y$=Z.sourceHashes}catch{i=[],b$={},k$=0,y$={}}}function mJ(){let $=H7();if(!B1($))return null;try{return{builtAt:JSON.parse(g1($,"utf-8")).builtAt}}catch{return null}}function cJ($){return wJ("sha256").update($).digest("hex").slice(0,16)}function dJ($,Z,Y){switch($){case"material":{let J=Y.split(`
158
+ `)[0];return J.length>60?J.slice(0,60)+"...":J}case"memo":return Y.slice(0,60).replace(/\n/g," ")+(Y.length>60?"...":"");case"decision":{let J=Y.split(`
159
+ `)[0];return J.length>60?J.slice(0,60)+"...":J}case"session":return`Sessao ${Z}`;default:return Z}}function uJ($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}import{writeFileSync as pJ,unlinkSync as lJ,existsSync as nJ}from"fs";import{join as iJ}from"path";import{tmpdir as oJ}from"os";import{randomUUID as aJ}from"crypto";var rJ=30000,CZ=50000,MZ=1e5,sJ=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,tJ=[{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)"}],eJ=[{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 q7($){for(let{pattern:Z,reason:Y}of tJ)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of eJ)if(Z.test($))return{safe:!1,blocked:!1,reason:Y};return{safe:!0,blocked:!1}}async function D0($){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>CZ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${CZ}).`,exitCode:1,duration:0};let Z=q7($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};let Y=aJ().slice(0,8),J=iJ(oJ(),`smolerclaw-${Y}.ps1`);try{pJ(J,$,"utf-8");let Q=performance.now(),X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",J],{stdout:"pipe",stderr:"pipe"}),K=new Promise((N,E)=>{setTimeout(()=>{X.kill(),E(Error("Script timeout exceeded"))},rJ)}),V=(async()=>{let[N,E]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),j=await X.exited;return{stdout:N,stderr:E,exitCode:j}})(),{stdout:G,stderr:H,exitCode:z}=await Promise.race([V,K]),M=Math.round(performance.now()-Q);return{stdout:m1(G),stderr:m1(H),exitCode:z,duration:M}}finally{try{if(nJ(J))lJ(J)}catch{}}}async function T0(){if(!A)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await $Q();if($.type==="text")return $;return await ZQ()}async function $Q(){let $=["Add-Type -AssemblyName System.Windows.Forms","$clip = [System.Windows.Forms.Clipboard]::GetText()",'if ($clip) { $clip } else { "___EMPTY___" }'].join("; ");try{let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-STA","-Command",$],{stdout:"pipe",stderr:"pipe"}),Y=new Promise((K,V)=>{setTimeout(()=>{Z.kill(),V(Error("clipboard timeout"))},1e4)}),J=(async()=>{let[K]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return await Z.exited,K})(),Q=await Promise.race([J,Y]),X=m1(Q).trim();if(X==="___EMPTY___"||!X)return{type:"empty",text:""};return{type:"text",text:X}}catch{return{type:"error",text:"Failed to read clipboard text."}}}async function ZQ(){try{let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-STA","-Command",`
160
+ Add-Type -AssemblyName System.Windows.Forms
161
+ $img = [System.Windows.Forms.Clipboard]::GetImage()
162
+ if (-not $img) {
163
+ Write-Output "___NO_IMAGE___"
164
+ exit
165
+ }
166
+ $tmpFile = [System.IO.Path]::Combine($env:TEMP, "smolerclaw-ocr-$(Get-Random).png")
167
+ try {
168
+ $img.Save($tmpFile, [System.Drawing.Imaging.ImageFormat]::Png)
169
+ $null = [Windows.Media.Ocr.OcrEngine, Windows.Foundation, ContentType = WindowsRuntime]
170
+ $null = [Windows.Graphics.Imaging.BitmapDecoder, Windows.Foundation, ContentType = WindowsRuntime]
171
+ $null = [Windows.Storage.StorageFile, Windows.Foundation, ContentType = WindowsRuntime]
172
+
173
+ $asyncOp = [Windows.Storage.StorageFile]::GetFileFromPathAsync($tmpFile)
174
+ $taskFile = [System.WindowsRuntimeSystemExtensions]::AsTask($asyncOp)
175
+ $taskFile.Wait()
176
+ $storageFile = $taskFile.Result
177
+
178
+ $asyncStream = $storageFile.OpenAsync([Windows.Storage.FileAccessMode]::Read)
179
+ $taskStream = [System.WindowsRuntimeSystemExtensions]::AsTask($asyncStream)
180
+ $taskStream.Wait()
181
+ $stream = $taskStream.Result
182
+
183
+ $asyncDecoder = [Windows.Graphics.Imaging.BitmapDecoder]::CreateAsync($stream)
184
+ $taskDecoder = [System.WindowsRuntimeSystemExtensions]::AsTask($asyncDecoder)
185
+ $taskDecoder.Wait()
186
+ $decoder = $taskDecoder.Result
187
+
188
+ $asyncBitmap = $decoder.GetSoftwareBitmapAsync()
189
+ $taskBitmap = [System.WindowsRuntimeSystemExtensions]::AsTask($asyncBitmap)
190
+ $taskBitmap.Wait()
191
+ $bitmap = $taskBitmap.Result
192
+
193
+ $ocrEngine = [Windows.Media.Ocr.OcrEngine]::TryCreateFromUserProfileLanguages()
194
+ $asyncResult = $ocrEngine.RecognizeAsync($bitmap)
195
+ $taskResult = [System.WindowsRuntimeSystemExtensions]::AsTask($asyncResult)
196
+ $taskResult.Wait()
197
+ $result = $taskResult.Result
198
+
199
+ if ($result.Text) {
200
+ Write-Output $result.Text
201
+ } else {
202
+ Write-Output "___NO_TEXT___"
203
+ }
204
+ } catch {
205
+ Write-Output "___OCR_ERROR___: $($_.Exception.Message)"
206
+ } finally {
207
+ if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
208
+ }
209
+ `],{stdout:"pipe",stderr:"pipe"}),Y=new Promise((K,V)=>{setTimeout(()=>{Z.kill(),V(Error("OCR timeout"))},20000)}),J=(async()=>{let[K]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return await Z.exited,K})(),Q=await Promise.race([J,Y]),X=m1(Q).trim();if(X==="___NO_IMAGE___")return{type:"empty",text:""};if(X==="___NO_TEXT___")return{type:"image",text:"(Imagem detectada no clipboard, mas sem texto reconhecivel)"};if(X.startsWith("___OCR_ERROR___"))return{type:"error",text:`OCR falhou: ${X.replace("___OCR_ERROR___: ","")}`};if(X)return{type:"image",text:`[OCR do clipboard]
210
+ ${X}`};return{type:"empty",text:""}}catch{return{type:"error",text:"Failed to perform OCR on clipboard image."}}}async function P0(){if(!A)return"Error: screen context analysis only available on Windows.";let $=`
211
+ $sig = @'
212
+ [DllImport("user32.dll")]
213
+ public static extern IntPtr GetForegroundWindow();
214
+ [DllImport("user32.dll")]
215
+ public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
216
+ '@
217
+ $User32 = Add-Type -MemberDefinition $sig -Name User32 -Namespace Win32 -PassThru
218
+
219
+ $fgHwnd = $User32::GetForegroundWindow()
220
+ $fgPid = 0
221
+ $null = $User32::GetWindowThreadProcessId($fgHwnd, [ref]$fgPid)
222
+
223
+ $fgProc = if ($fgPid -gt 0) { Get-Process -Id $fgPid -ErrorAction SilentlyContinue } else { $null }
224
+ $fgName = if ($fgProc) { $fgProc.ProcessName } else { "unknown" }
225
+ $fgTitle = if ($fgProc) { $fgProc.MainWindowTitle } else { "" }
226
+
227
+ Write-Output "=== FOREGROUND ==="
228
+ Write-Output "PID: $fgPid"
229
+ Write-Output "Process: $fgName"
230
+ Write-Output "Title: $fgTitle"
231
+ Write-Output ""
232
+ Write-Output "=== ALL VISIBLE WINDOWS ==="
233
+
234
+ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
235
+ Sort-Object -Property WorkingSet64 -Descending |
236
+ Select-Object -First 20 Id, ProcessName,
237
+ @{N='MemMB';E={[math]::Round($_.WorkingSet64/1MB,1)}},
238
+ MainWindowTitle |
239
+ ForEach-Object {
240
+ $marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
241
+ Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
242
+ }
243
+ `;try{let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",$],{stdout:"pipe",stderr:"pipe"}),Y=new Promise((V,G)=>{setTimeout(()=>{Z.kill(),G(Error("screen context timeout"))},15000)}),J=(async()=>{let[V,G]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return await Z.exited,{stdout:V,stderr:G}})(),{stdout:Q,stderr:X}=await Promise.race([J,Y]),K=m1(Q).trim();if(!K&&X.trim())return`Error: ${m1(X).trim()}`;return K||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}function m1($){let Z=$.replace(sJ,"");if(Z.length>MZ)return Z.slice(0,MZ)+`
244
+ ... (truncated, ${Z.length} total chars)`;return Z}r();import{existsSync as U$,mkdirSync as YQ,readFileSync as I0}from"fs";import{join as J$,basename as JQ}from"path";import{randomUUID as QQ}from"crypto";var c1="",N$=[],B$=[],F$=[],t$=null,OZ=()=>J$(c1,"projects.json"),EZ=()=>J$(c1,"work-sessions.json"),LZ=()=>J$(c1,"opportunities.json"),jZ=()=>J$(c1,"active-project.txt");function XQ(){D(OZ(),JSON.stringify(N$,null,2))}function B7(){D(EZ(),JSON.stringify(B$,null,2))}function FZ(){D(LZ(),JSON.stringify(F$,null,2))}function KQ(){D(jZ(),t$||"")}function zQ(){N$=U7(OZ,[]),B$=U7(EZ,[]),F$=U7(LZ,[]);let $=jZ();if(U$($))try{t$=I0($,"utf-8").trim()||null}catch{t$=null}}function U7($,Z){let Y=$();if(!U$(Y))return Z;try{return JSON.parse(I0(Y,"utf-8"))}catch(J){if(process.env.DEBUG)console.error(`[projects] Failed to load ${Y}: ${J instanceof Error?J.message:J}`);return Z}}function RZ($){if(c1=$,!U$($))YQ($,{recursive:!0});zQ()}function N7($,Z,Y="",J=[],Q=[]){let X={id:C7(),name:$.trim(),path:Z.trim(),description:Y.trim(),tags:J.map((K)=>K.trim().toLowerCase()).filter(Boolean),techStack:Q.map((K)=>K.trim().toLowerCase()).filter(Boolean),createdAt:new Date().toISOString(),active:!0};return N$=[...N$,X],XQ(),X}function S0($){let Z=$.toLowerCase().trim();return N$.find((Y)=>Y.id===$)||N$.find((Y)=>Y.name.toLowerCase()===Z)||N$.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function b0($=!1){return($?N$.filter((Y)=>Y.active):[...N$]).sort((Y,J)=>new Date(J.createdAt).getTime()-new Date(Y.createdAt).getTime())}function d1($){let Z=S0($);if(!Z)return null;return t$=Z.id,KQ(),Z}function e$(){if(!t$)return null;return N$.find(($)=>$.id===t$)||null}function k0($,Z=""){if(!N$.find((Q)=>Q.id===$))return null;VQ($);let J={id:C7(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return B$=[...B$,J],B7(),J}function y0($,Z){let Y=B$.find((K)=>K.id===$);if(!Y||Y.endedAt)return null;let J=new Date,Q=new Date(Y.startedAt),X=Math.round((J.getTime()-Q.getTime())/60000);return B$=B$.map((K)=>K.id===$?{...K,endedAt:J.toISOString(),durationMinutes:X,notes:Z?`${K.notes}
245
+ ${Z}`.trim():K.notes}:K),B7(),B$.find((K)=>K.id===$)||null}function VQ($){let Z=new Date;B$=B$.map((Y)=>{if(Y.projectId===$&&!Y.endedAt){let J=new Date(Y.startedAt),Q=Math.round((Z.getTime()-J.getTime())/60000);return{...Y,endedAt:Z.toISOString(),durationMinutes:Q}}return Y}),B7()}function $1($){return B$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function GQ($,Z,Y){let J=Y||new Date;return B$.filter((Q)=>{if(Q.projectId!==$)return!1;let X=new Date(Q.startedAt);return X>=Z&&X<=J})}async function WQ($,Z="1 day ago"){if(!U$(J$($,".git")))return null;try{let Y=await w0(["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 J=Y.stdout.trim().split(`
246
+ `).filter(Boolean),Q=[...new Set(J.map((j)=>j.split("|||")[0]))],X=J.map((j)=>j.split("|||")[1]||"").filter(Boolean),K=await w0(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),V=await w0(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),G=0,H=0,z=0;if(V.ok&&V.stdout.trim())for(let j of V.stdout.trim().split(`
247
+ `)){let T=j.match(/(\d+)\s+files?\s+changed/),m=j.match(/(\d+)\s+insertions?/),p=j.match(/(\d+)\s+deletions?/);if(T)G+=parseInt(T[1]);if(m)H+=parseInt(m[1]);if(p)z+=parseInt(p[1])}let M=await w0(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),N=new Map;if(M.ok&&M.stdout.trim())for(let j of M.stdout.trim().split(`
248
+ `).filter(Boolean))N.set(j,(N.get(j)||0)+1);let E=[...N.entries()].sort((j,T)=>T[1]-j[1]).slice(0,10).map(([j])=>j);return{commits:J.length,authors:Q,filesChanged:G,insertions:H,deletions:z,topFiles:E,messages:X}}catch{return null}}async function w0($,Z){let Y=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[J,Q]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),X=await Y.exited;return{stdout:J.trim(),stderr:Q.trim(),ok:X===0}}function AZ($,Z,Y,J=[],Q="media",X=null){let K=new Date().toISOString(),V={id:C7(),title:$.trim(),description:Z.trim(),source:Y.trim(),techRequired:J.map((G)=>G.toLowerCase()),priority:Q,status:"nova",deadline:X,createdAt:K,updatedAt:K};return F$=[...F$,V],FZ(),V}function xZ($,Z){if(!F$.find((J)=>J.id===$))return null;return F$=F$.map((J)=>J.id===$?{...J,status:Z,updatedAt:new Date().toISOString()}:J),FZ(),F$.find((J)=>J.id===$)||null}function _0($,Z){let Y=[...F$];if($)Y=Y.filter((J)=>J.status===$);if(Z&&Z.length>0){let J=Z.map((Q)=>Q.toLowerCase());Y=Y.filter((Q)=>Q.techRequired.some((X)=>J.includes(X)))}return Y.sort((J,Q)=>{let X={alta:3,media:2,baixa:1};return(X[Q.priority]||0)-(X[J.priority]||0)})}async function h0($,Z="today",Y="pt"){let J=S0($);if(!J)return null;let X=new Date(new Date);switch(Z){case"today":X.setHours(0,0,0,0);break;case"week":X.setDate(X.getDate()-7);break;case"month":X.setDate(X.getDate()-30);break}let K=Z==="today"?"1 day ago":Z==="week"?"7 days ago":"30 days ago",V=await WQ(J.path,K),G=GQ(J.id,X),H=G.reduce((N,E)=>N+E.durationMinutes,0),z=0;try{let N=J$(c1,"tasks.json");if(U$(N))z=JSON.parse(I0(N,"utf-8")).filter((j)=>{if(!j.done)return!1;return new Date(j.createdAt)>=X}).length}catch{}let M=HQ(J,Z,V,G,H,z,Y);return{project:J,period:Z,gitSummary:V,sessions:G,totalMinutes:H,completedTasks:z,markdown:M}}function HQ($,Z,Y,J,Q,X,K){let V=K==="pt",G=[],H=new Date,z=H.toLocaleDateString(V?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(G.push(`# ${V?"Relatorio de Progresso":"Work Progress Report"}`),G.push(`**${V?"Projeto":"Project"}:** ${$.name}`),G.push(`**${V?"Periodo":"Period"}:** ${Z} (${z})`),G.push(`**${V?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)G.push(`**Tech:** ${$.techStack.join(", ")}`);G.push("");let M=Math.floor(Q/60),N=Q%60;if(G.push(`## ${V?"Tempo Trabalhado":"Time Tracked"}`),G.push(`- **${V?"Total":"Total"}:** ${M}h ${N}m`),G.push(`- **${V?"Sessoes":"Sessions"}:** ${J.length}`),X>0)G.push(`- **${V?"Tarefas concluidas":"Tasks completed"}:** ${X}`);if(G.push(""),Y&&Y.commits>0){if(G.push(`## ${V?"Atividade Git":"Git Activity"}`),G.push(`- **Commits:** ${Y.commits}`),Y.authors.length>0)G.push(`- **${V?"Autores":"Authors"}:** ${Y.authors.join(", ")}`);if(G.push(`- **${V?"Arquivos alterados":"Files changed"}:** ${Y.filesChanged}`),G.push(`- **${V?"Linhas":"Lines"}:** +${Y.insertions} / -${Y.deletions}`),Y.messages.length>0){G.push(""),G.push(`### ${V?"Commits recentes":"Recent commits"}`);for(let E of Y.messages.slice(0,15))G.push(`- ${E}`)}if(Y.topFiles.length>0){G.push(""),G.push(`### ${V?"Arquivos mais alterados":"Most changed files"}`);for(let E of Y.topFiles.slice(0,8))G.push(`- \`${E}\``)}G.push("")}else G.push(`## ${V?"Atividade Git":"Git Activity"}`),G.push(V?"_Nenhum commit no periodo._":"_No commits in this period._"),G.push("");if(J.length>0){G.push(`## ${V?"Sessoes de Trabalho":"Work Sessions"}`);for(let E of J){let j=new Date(E.startedAt).toLocaleTimeString(V?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),T=E.durationMinutes>0?`${E.durationMinutes}m`:V?"em andamento":"ongoing",m=E.notes?` \u2014 ${E.notes}`:"";G.push(`- ${j} (${T})${m}`)}G.push("")}return G.push("---"),G.push(V?`_Gerado por smolerclaw em ${H.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${H.toLocaleString("en-US")}_`),G.join(`
249
+ `)}function f0($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((Y)=>{let J=Y.id===t$?" [ATIVO]":"",Q=Y.active?"":" (inativo)",X=Y.techStack.length>0?` [${Y.techStack.join(", ")}]`:"";return` ${Y.name}${J}${Q}${X} \u2014 ${Y.path} {${Y.id}}`});return`Projetos (${$.length}):
250
+ ${Z.join(`
251
+ `)}`}function v0($){let Z=$.id===t$?" [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((Q)=>`#${Q}`).join(" ")}`);Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(`Status: ${$.active?"ativo":"inativo"}`);let J=$1($.id);if(J){let Q=new Date(J.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Y.push(`Sessao aberta: desde ${Q}`)}return Y.join(`
252
+ `)}function g0($){if($.length===0)return"Nenhuma oportunidade encontrada.";let Z=$.map((Y)=>{let J={alta:"!!!",media:"!!",baixa:"!"}[Y.priority],Q=Y.techRequired.length>0?` [${Y.techRequired.join(", ")}]`:"",X=Y.deadline?` \u2014 prazo: ${Y.deadline}`:"";return` ${J} (${Y.status}) ${Y.title}${Q}${X} \u2014 ${Y.source} {${Y.id}}`});return`Oportunidades (${$.length}):
253
+ ${Z.join(`
254
+ `)}`}function DZ(){let $=e$();if(!$)return"";let Z=$1($.id),Y=F$.filter((Q)=>Q.status==="nova").length,J=["--- Projetos ---"];if(J.push(`Projeto ativo: ${$.name} (${$.path})`),Z){let Q=new Date(Z.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});J.push(`Sessao aberta desde ${Q}`)}if(Y>0)J.push(`${Y} oportunidade(s) nova(s) pendente(s)`);return J.join(`
255
+ `)}function m0($){let Z=N$.find((Q)=>Q.path===$);if(Z)return Z;if(!U$(J$($,".git")))return null;let Y=[];if(U$(J$($,"package.json")))try{let Q=JSON.parse(I0(J$($,"package.json"),"utf-8"));if(Q.dependencies?.typescript||Q.devDependencies?.typescript)Y.push("typescript");if(Q.dependencies?.react)Y.push("react");if(Q.dependencies?.next)Y.push("nextjs");if(Q.dependencies?.vue)Y.push("vue");if(U$(J$($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(U$(J$($,"Cargo.toml")))Y.push("rust");if(U$(J$($,"go.mod")))Y.push("go");if(U$(J$($,"requirements.txt"))||U$(J$($,"pyproject.toml")))Y.push("python");let J=JQ($);return N7(J,$,"",[],Y)}function C7(){return QQ().slice(0,8)}var p1=new v2,kZ=[];function yZ($){kZ=$}var u=[{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"]}}],_Z=[{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:[]}}],NQ=[{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:[]}}],CQ=[{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:[]}}],MQ=[{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"]}}],OQ={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"]}},EQ=[{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"]}}],LQ=[{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:[]}}],jQ=[{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"]}}],FQ=[{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:[]}}],RQ=[{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"]}}],AQ=[{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:[]}}],xQ=[{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"]}}],DQ=[{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:[]}}],TQ=[{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:[]}}],PQ=_Z.find(($)=>$.name==="get_news"),TZ=!1,_$=null;function hZ($){_$=$}function fZ(){if(TZ)return;if(TZ=!0,A)u.push(..._Z),u.push(...AQ);else u.push(PQ);u.push(...NQ),u.push(...CQ),u.push(...MQ),u.push(OQ),u.push(...EQ),u.push(...LQ),u.push(...jQ),u.push(...DQ),u.push(...xQ),u.push(...FQ),u.push(...RQ),u.push(...TQ)}var d0=50000;async function E7($,Z){try{switch($){case"read_file":return wQ(Z);case"write_file":return IQ(Z);case"edit_file":return SQ(Z);case"search_files":return await bQ(Z);case"find_files":return await _Q(Z);case"list_directory":return hQ(Z);case"run_command":return await fQ(Z);case"fetch_url":return await vQ(Z);case"open_application":return await I1(Z.name,Z.argument);case"open_file_default":return await m8(Z.path);case"open_url_browser":return await S1(Z.url);case"get_running_apps":return await c8();case"get_system_info":return await b1();case"get_calendar_events":return await l$();case"get_news":{let Y=Z.category;return await n$(Y?[Y]:void 0)}case"create_task":{let Y=Z.title;if(!Y?.trim())return"Error: title is required.";let J=Z.time,Q=J?m4(J):void 0,X=r8(Y,Q||void 0),K=Q?` \u2014 lembrete: ${Q.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${X.title}"${K} [${X.id}]`}case"complete_task":{let Y=Z.reference;if(!Y?.trim())return"Error: reference is required.";let J=s8(Y);return J?`Concluida: "${J.title}"`:`Tarefa nao encontrada: "${Y}"`}case"list_tasks":{let Y=Z.show_done||!1,J=i$(Y);return H1(J)}case"add_person":{let Y=Z.name;if(!Y?.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 X=V0(Y,J,Z.role,Z.contact);return`Pessoa adicionada: ${X.name} (${J}) [${X.id}]`}case"find_person_info":{let Y=Z.name_or_id;if(!Y?.trim())return"Error: name_or_id is required.";let J=r$(Y);if(!J)return`Pessoa nao encontrada: "${Y}"`;return q0(J)}case"list_people":{let Y=Z.group,J=G0(Y);return H0(J)}case"log_interaction":{let Y=Z.person;if(!Y?.trim())return"Error: person is required.";let{type:J,summary:Q}=Z;if(!Q?.trim())return"Error: summary is required.";let X=Z.follow_up,K=X?IZ(X):void 0;if(!e9(Y,J,Q,K||void 0))return`Pessoa nao encontrada: "${Y}"`;let G=K?` \u2014 follow-up: ${K.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${J} com ${Y}${G}`}case"delegate_to_person":{let Y=Z.person;if(!Y?.trim())return"Error: person is required.";let J=Z.task;if(!J?.trim())return"Error: task is required.";let Q=Z.due_date,X=Q?IZ(Q):void 0,K=W0(Y,J,X||void 0);if(!K)return`Pessoa nao encontrada: "${Y}"`;let V=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Y}: "${J}"${V} [${K.id}]`}case"update_delegation_status":{let Y=Z.delegation_id;if(!Y?.trim())return"Error: delegation_id is required.";let J=Z.status,Q=$Z(Y,J,Z.notes);if(!Q)return`Delegacao nao encontrada: "${Y}"`;return`Delegacao atualizada: "${Q.task}" -> ${J}`}case"get_people_dashboard":return N0();case"save_memo":{let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let J=Z.tags||[],Q=t8(Y,J);return`Memo salvo${Q.tags.length>0?` [${Q.tags.map((K)=>"#"+K).join(" ")}]`:""} {${Q.id}}`}case"search_memos":{let Y=Z.query;if(!Y?.trim())return q1(c4());let J=e8(Y);return q1(J)}case"record_transaction":{let{type:Y,amount:J,category:Q,description:X}=Z;if(!Y||!J||!Q||!X)return"Error: all fields required.";let K=d4(Y,J,Q,X);return`${K.type==="entrada"?"+":"-"} R$ ${K.amount.toFixed(2)} (${K.category}) \u2014 ${K.description} [${K.id}]`}case"financial_summary":return Y0();case"log_decision":{let{title:Y,context:J,chosen:Q}=Z;if(!Y||!J||!Q)return"Error: title, context, and chosen are required.";let X=d9(Y,J,Q,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${X.title}" {${X.id}}`}case"search_decisions":{let Y=Z.query;if(!Y?.trim())return h1(Q0());return h1(J0(Y))}case"open_investigation":{let Y=Z.title;if(!Y?.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 X=a2(Y,J,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${X.title}" (${X.type}) {${X.id}}`}case"collect_evidence":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let{source:J,label:Q,content:X}=Z;if(!Q?.trim()||!X?.trim())return"Error: label and content are required.";let K=r2(Y,J,Q,X,Z.path);if(!K)return`Investigacao nao encontrada: "${Y}"`;return`Evidencia coletada: [${K.id}] ${K.source}: ${K.label}`}case"add_finding":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let{severity:J,title:Q,description:X}=Z;if(!Q?.trim()||!X?.trim())return"Error: title and description are required.";let K=Z.evidence_ids||[],V=s2(Y,J,Q,X,K);if(!V)return`Investigacao nao encontrada: "${Y}"`;return`Conclusao registrada: [${V.severity.toUpperCase()}] ${V.title} {${V.id}}`}case"close_investigation":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=Z.summary;if(!J?.trim())return"Error: summary is required.";let Q=t2(Y,J,Z.recommendations);if(!Q)return`Investigacao nao encontrada: "${Y}"`;return`Investigacao concluida: "${Q.title}" \u2014 ${Q.evidence.length} evidencias, ${Q.findings.length} conclusoes`}case"investigation_status":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=e2(Y);if(!J)return`Investigacao nao encontrada: "${Y}"`;return J7(J)}case"investigation_report":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=Y7(Y);if(!J)return`Investigacao nao encontrada: "${Y}"`;return J}case"list_investigations":{let Y=Z.query;if(Y?.trim())return K0(Z7(Y));let{status:J,type:Q}=Z;return K0($7(J,Q))}case"draft_email":{let{to:Y,subject:J,body:Q}=Z;if(!Y?.trim()||!J?.trim()||!Q?.trim())return"Error: to, subject, and body are required.";let X={to:Y,subject:J,body:Q,cc:Z.cc},K=Z0(X),V=await $0(X);return`${K}
256
+
257
+ ${V}`}case"save_material":{let Y=Z.title;if(!Y?.trim())return"Error: title is required.";let J=Z.content;if(!J?.trim())return"Error: content is required.";let Q=Z.category||"geral",X=Z.tags||[],K=C0(Y,J,Q,X),V=K.tags.length>0?` [${K.tags.map((G)=>"#"+G).join(" ")}]`:"";return`Material salvo: "${K.title}" (${K.category})${V} {${K.id}}`}case"search_materials":{let Y=Z.query;if(!Y?.trim())return s$(v1());let J=O0(Y);return s$(J)}case"list_materials":{let Y=Z.category,J=Z.limit||30,Q=v1(J,Y);return s$(Q)}case"update_material":{let Y=Z.id;if(!Y?.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 Q=KZ(Y,J);if(!Q)return`Material nao encontrado: "${Y}"`;return`Material atualizado: "${Q.title}" (${Q.category}) {${Q.id}}`}case"delete_material":{let Y=Z.id;if(!Y?.trim())return"Error: id is required.";return M0(Y)?"Material removido.":`Material nao encontrado: "${Y}"`}case"execute_powershell_script":{let Y=Z.script;if(!Y?.trim())return"Error: script is required.";let J=q7(Y);if(J.blocked)return`BLOCKED: ${J.reason}
258
+ Esse tipo de operacao nao e permitido.`;if(!J.safe&&J.reason);let Q=await D0(Y),X=[];if(Q.stdout.trim())X.push(`stdout:
259
+ ${Q.stdout.trim()}`);if(Q.stderr.trim())X.push(`stderr:
260
+ ${Q.stderr.trim()}`);return X.push(`exit: ${Q.exitCode} (${Q.duration}ms)`),X.join(`
261
+
262
+ `)}case"analyze_screen_context":return await P0();case"read_clipboard_content":{let Y=await T0();switch(Y.type){case"text":return`Clipboard (texto):
263
+ ${Y.text}`;case"image":return Y.text;case"empty":return"Clipboard vazio.";case"error":return`Erro ao ler clipboard: ${Y.text}`}}case"manage_news_feeds":switch(Z.action){case"list":return o8();case"add":{let{name:J,url:Q,category:X}=Z;if(!J?.trim())return"Error: name is required for add.";if(!Q?.trim())return"Error: url is required for add.";if(!X?.trim())return"Error: category is required for add.";let K=p8(J,Q,X);if(typeof K==="string")return K;return`Fonte adicionada: ${K.name} (${K.category}) \u2014 ${K.url}`}case"remove":{let J=Z.name;if(!J?.trim())return"Error: name or URL is required.";return l8(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 n8(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 i8(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"recall_memory":{if(!j0())return"Error: memory not initialized. Run /indexar first.";let Y=Z.query;if(!Y?.trim())return"Error: query is required.";let J=Math.min(Math.max(Z.top_k||3,1),10),Q=A0(Y,J);return x0(Q)}case"index_memory":{if(!j0())return"Error: memory not initialized.";let Y=R0();return`Indexacao concluida: ${Y.indexed} fonte(s) indexada(s), ${Y.skipped} sem alteracao. Total: ${Y.total} chunks.`}case"memory_status":{if(!j0())return"Memory: nao inicializada.";let Y=F0(),J=Y.builtAt?new Date(Y.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
264
+ Chunks: ${Y.chunks}
265
+ Fontes: ${Y.sources}
266
+ Ultima indexacao: ${J}`}case"vault_status":{if(!o1())return"Vault nao inicializado.";return z8(K8())}case"vault_backup":{if(!o1())return"Vault nao inicializado.";let Y=Z.message||void 0;return await M1(Y)}case"sync_cloud_context":{if(!o1())return"Vault nao inicializado.";return await G8()}case"vault_init_backup":{if(!o1())return"Vault nao inicializado.";return await V8()}case"set_active_project":{let Y=Z.name_or_id;if(!Y?.trim())return"Error: name_or_id is required.";if(Y==="auto"){let Q=m0(process.cwd());if(!Q)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return d1(Q.id),`Projeto ativo: "${Q.name}" (${Q.path}) \u2014 auto-detectado [${Q.id}]`}let J=d1(Y);if(!J)return`Projeto nao encontrado: "${Y}". Use /projetos para listar ou add_project para criar.`;return`Projeto ativo: "${J.name}" (${J.path}) [${J.id}]`}case"report_work_progress":{let Y=Z.project||"",J=Z.period||"today",Q=Z.lang||"pt",X=Z.save_to_file,K=Y;if(!K){let G=e$();if(!G)return"Nenhum projeto ativo. Use set_active_project primeiro.";K=G.id}let V=await h0(K,J,Q);if(!V)return`Projeto nao encontrado: "${K}"`;if(X)return UQ(X,V.markdown,"utf-8"),`Relatorio salvo em: ${X}
267
+
268
+ ${V.markdown}`;return V.markdown}case"manage_work_session":{let Y=Z.action,J=Z.notes||"",Q=e$();if(!Q)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(Y){case"start":{let X=k0(Q.id,J);if(!X)return"Erro ao iniciar sessao.";return`Sessao iniciada para "${Q.name}" as ${new Date().toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}. [${X.id}]`}case"stop":{let X=$1(Q.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let K=y0(X.id,J);if(!K)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${K.durationMinutes} minutos trabalhados em "${Q.name}".`}case"status":{let X=$1(Q.id);if(!X)return`Nenhuma sessao aberta para "${Q.name}".`;let K=new Date(X.startedAt),V=Math.round((Date.now()-K.getTime())/60000);return`Sessao aberta: "${Q.name}" \u2014 ${V} minutos (desde ${K.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})`}default:return"Error: action must be start, stop, or status."}}case"add_project":{let Y=Z.name;if(!Y?.trim())return"Error: name is required.";let J=Z.path;if(!J?.trim())return"Error: path is required.";let Q=Z.description||"",X=Z.tech_stack||[],K=Z.tags||[],V=N7(Y,J,Q,K,X);return`Projeto registrado: "${V.name}" (${V.path}) [${V.id}]`}case"list_projects":{let Y=Z.active_only||!1;return f0(b0(Y))}case"fetch_opportunities":{let{status:Y,tech:J}=Z,Q=_0(Y,J);return g0(Q)}case"add_opportunity":{let Y=Z.title;if(!Y?.trim())return"Error: title is required.";let J=Z.description;if(!J?.trim())return"Error: description is required.";let Q=Z.source;if(!Q?.trim())return"Error: source is required.";let X=Z.tech_required||[],K=Z.priority||"media",V=Z.deadline||null,G=AZ(Y,J,Q,X,K,V);return`Oportunidade registrada: "${G.title}" (${G.priority}) [${G.id}]`}case"update_opportunity_status":{let Y=Z.id;if(!Y?.trim())return"Error: id is required.";let J=Z.status,Q=xZ(Y,J);if(!Q)return`Oportunidade nao encontrada: "${Y}"`;return`Oportunidade atualizada: "${Q.title}" -> ${J}`}case"archive_session":{if(!_$)return"Error: session manager not initialized.";let Y=Z.name;if(!Y?.trim())return"Error: name is required.";if(Y==="all"){let J=_$.archiveAll();return J.length>0?`Arquivadas ${J.length} sessoes: ${J.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return _$.archive(Y)?`Sessao arquivada: "${Y}"`:`Falha ao arquivar "${Y}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!_$)return"Error: session manager not initialized.";let Y=Z.name;if(!Y?.trim())return"Error: name is required.";return _$.unarchive(Y)?`Sessao restaurada: "${Y}"`:`Sessao arquivada nao encontrada: "${Y}"`}case"list_archived_sessions":{if(!_$)return"Error: session manager not initialized.";let Y=_$.listArchived();if(Y.length===0)return"Nenhuma sessao arquivada.";let J=Y.map((Q)=>{let X=_$.getArchivedInfo(Q),K=X?new Date(X.updated).toLocaleDateString("pt-BR"):"",V=X?`${X.messageCount} msgs`:"";return` ${Q.padEnd(20)} ${V.padEnd(10)} ${K}`});return`Sessoes arquivadas (${Y.length}):
142
269
  ${J.join(`
143
- `)}`}default:{let Y=D0.find((J)=>J.name===$);if(Y)return await M8(Y,Z);return`Error: unknown tool "${$}"`}}}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}var M0=10485760;function I0($,Z){let Y=d6(G9($),`.smolerclaw-${W9().slice(0,8)}.tmp`);Q9(Y,Z),K9(Y,$)}function H$($){let Z=p2($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+x4))return`Error: path outside working directory is not permitted: ${Z}`;try{if(H1(Z)){let J=V9(Z);if(J!==Y&&!J.startsWith(Y+x4))return`Error: symlink target is outside working directory: ${J}`}}catch{}return null}function U$($,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 E9($){let Z=U$($,"path");if(Z)return Z;let Y=p2($.path),J=H$(Y);if(J)return J;if(!H1(Y))return`Error: file not found: ${Y}`;let X=x0(Y).size;if(X>M0)return`Error: file too large (${g6(X)}). Max is ${g6(M0)}.`;let Q=c6(Y,"utf-8").split(`
144
- `),V=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),O=Q.slice(V-1,V-1+G).map((M,D)=>`${String(V+D).padStart(4)} ${M}`).join(`
145
- `),N=Q.length-(V-1+G);if(N>0)O+=`
146
- ... (${N} more lines, total ${Q.length})`;return W$(O)}function M9($){let Z=U$($,"path");if(Z)return Z;let Y=p2($.path),J=H$(Y);if(J)return J;let X=$.content,z=H1(Y);q$.saveState(Y),I0(Y,X);let Q=X.split(`
147
- `).length;return`${z?"Updated":"Created"}: ${Y} (${Q} lines)`}function L9($){let Z=U$($,"path");if(Z)return Z;let Y=p2($.path),J=H$(Y);if(J)return J;if(!H1(Y))return`Error: file not found: ${Y}`;let X=c6(Y,"utf-8"),z=$.old_text,Q=$.new_text,V=X.split(z).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.`;q$.saveState(Y);let G=X.split(z).join(Q);I0(Y,G);let q=z.split(`
148
- `).length,K=Q.split(`
149
- `).length;return`Edited: ${Y} (replaced ${q} lines with ${K} lines)`}async function R9($){let Z=U$($,"pattern");if(Z)return Z;let Y=$.pattern,J=p2($.path||"."),X=H$(J);if(X)return X;let z=$.include;if(await C7())return x9(Y,J,z);return D9(Y,J,z)}async function x9($,Z,Y){let J=["rg","--no-heading","--line-number","--color=never"];if(Y)J.push("--glob",Y);for(let V of y4)J.push("--glob",`!${V}`);J.push("-e",$,Z);let X=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),z=await new Response(X.stdout).text(),Q=await new Response(X.stderr).text();if(await X.exited,!z.trim()&&!Q.trim())return"No matches found.";if(Q.trim()&&!z.trim())return`Error: ${Q.trim()}`;return S9(z,Z)}async function D9($,Z,Y){let J;try{J=new RegExp($)}catch(K){return`Error: invalid regex pattern: ${K instanceof Error?K.message:$}`}let X=Y||"**/*",z=new Bun.Glob(X),Q=[],V=0,G=5000;for await(let K of z.scan({cwd:Z,onlyFiles:!0})){if(_4(K))continue;if(++V>G){Q.push(`... (stopped after scanning ${G} files)`);break}let O=d6(Z,K);try{let M=c6(O,"utf-8").split(`
150
- `);for(let D=0;D<M.length;D++)if(J.test(M[D])){if(Q.push(`${K}:${D+1}:${M[D]}`),Q.length>=100)break}}catch{}if(Q.length>=100)break}if(Q.length===0)return"No matches found.";let q=Q.slice(0,100).join(`
151
- `);if(Q.length>100)q+=`
152
- ... (showing first 100 matches)`;return W$(q)}async function A9($){let Z=U$($,"pattern");if(Z)return Z;let Y=$.pattern,J=p2($.path||"."),X=H$(J);if(X)return X;let z=new Bun.Glob(Y),Q=[];for await(let G of z.scan({cwd:J,onlyFiles:!0})){if(_4(G))continue;if(Q.push(G),Q.length>=200)break}if(Q.length===0)return"No files found.";let V=Q.join(`
153
- `);if(Q.length>=200)V+=`
154
- ... (showing first 200 files)`;return V}function w9($){let Z=p2($.path||"."),Y=H$(Z);if(Y)return Y;if(!H1(Z))return`Error: not found: ${Z}`;return z9(Z,{withFileTypes:!0}).sort((z,Q)=>{if(z.isDirectory()!==Q.isDirectory())return z.isDirectory()?-1:1;return z.name.localeCompare(Q.name)}).map((z)=>{if(z.isDirectory())return`d ${z.name}/`;try{let Q=x0(d6(Z,z.name)),V=g6(Q.size);return`f ${z.name} ${V}`}catch{return`f ${z.name}`}}).join(`
155
- `)}async function P9($){let Z=U$($,"command");if(Z)return Z;let Y=$.command,J=Math.min(120,Math.max(5,$.timeout||30)),X=F1(),z=Bun.spawn([...X,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),Q=setTimeout(()=>z.kill(),J*1000),[V,G]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),q=await z.exited;clearTimeout(Q);let K="";if(V.trim())K+=V.trim();if(G.trim())K+=(K?`
270
+ `)}`}default:{let Y=kZ.find((J)=>J.name===$);if(Y)return await G9(Y,Z);return`Error: unknown tool "${$}"`}}}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}var PZ=10485760;function l1($){let Z=N1($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+c0))return`Error: path outside working directory is not permitted: ${Z}`;try{if(i4(Z)){let J=BQ(Z);if(J!==Y&&!J.startsWith(Y+c0))return`Error: symlink target is outside working directory: ${J}`}}catch{}return null}function n1($,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 wQ($){let Z=n1($,"path");if(Z)return Z;let Y=N1($.path),J=l1(Y);if(J)return J;if(!i4(Y))return`Error: file not found: ${Y}`;let Q=SZ(Y).size;if(Q>PZ)return`Error: file too large (${M7(Q)}). Max is ${M7(PZ)}.`;let K=O7(Y,"utf-8").split(`
271
+ `),V=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),M=K.slice(V-1,V-1+G).map((E,j)=>`${String(V+j).padStart(4)} ${E}`).join(`
272
+ `),N=K.length-(V-1+G);if(N>0)M+=`
273
+ ... (${N} more lines, total ${K.length})`;return u1(M)}function IQ($){let Z=n1($,"path");if(Z)return Z;let Y=N1($.path),J=l1(Y);if(J)return J;let Q=$.content,X=i4(Y);p1.saveState(Y),D(Y,Q);let K=Q.split(`
274
+ `).length;return`${X?"Updated":"Created"}: ${Y} (${K} lines)`}function SQ($){let Z=n1($,"path");if(Z)return Z;let Y=N1($.path),J=l1(Y);if(J)return J;if(!i4(Y))return`Error: file not found: ${Y}`;let Q=O7(Y,"utf-8"),X=$.old_text,K=$.new_text,V=Q.split(X).length-1;if(V===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(V>1)return`Error: old_text found ${V} times. It must be unique. Include more surrounding context.`;p1.saveState(Y);let G=Q.split(X).join(K);D(Y,G);let H=X.split(`
275
+ `).length,z=K.split(`
276
+ `).length;return`Edited: ${Y} (replaced ${H} lines with ${z} lines)`}async function bQ($){let Z=n1($,"pattern");if(Z)return Z;let Y=$.pattern,J=N1($.path||"."),Q=l1(J);if(Q)return Q;let X=$.include;if(await r7())return kQ(Y,J,X);return yQ(Y,J,X)}async function kQ($,Z,Y){let J=["rg","--no-heading","--line-number","--color=never"];if(Y)J.push("--glob",Y);for(let V of s0)J.push("--glob",`!${V}`);J.push("-e",$,Z);let Q=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),X=await new Response(Q.stdout).text(),K=await new Response(Q.stderr).text();if(await Q.exited,!X.trim()&&!K.trim())return"No matches found.";if(K.trim()&&!X.trim())return`Error: ${K.trim()}`;return mQ(X,Z)}async function yQ($,Z,Y){let J;try{J=new RegExp($)}catch(z){return`Error: invalid regex pattern: ${z instanceof Error?z.message:$}`}let Q=Y||"**/*",X=new Bun.Glob(Q),K=[],V=0,G=5000;for await(let z of X.scan({cwd:Z,onlyFiles:!0})){if(t0(z))continue;if(++V>G){K.push(`... (stopped after scanning ${G} files)`);break}let M=bZ(Z,z);try{let E=O7(M,"utf-8").split(`
277
+ `);for(let j=0;j<E.length;j++)if(J.test(E[j])){if(K.push(`${z}:${j+1}:${E[j]}`),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(`
278
+ `);if(K.length>100)H+=`
279
+ ... (showing first 100 matches)`;return u1(H)}async function _Q($){let Z=n1($,"pattern");if(Z)return Z;let Y=$.pattern,J=N1($.path||"."),Q=l1(J);if(Q)return Q;let X=new Bun.Glob(Y),K=[];for await(let G of X.scan({cwd:J,onlyFiles:!0})){if(t0(G))continue;if(K.push(G),K.length>=200)break}if(K.length===0)return"No files found.";let V=K.join(`
280
+ `);if(K.length>=200)V+=`
281
+ ... (showing first 200 files)`;return V}function hQ($){let Z=N1($.path||"."),Y=l1(Z);if(Y)return Y;if(!i4(Z))return`Error: not found: ${Z}`;return qQ(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=SZ(bZ(Z,X.name)),V=M7(K.size);return`f ${X.name} ${V}`}catch{return`f ${X.name}`}}).join(`
282
+ `)}async function fQ($){let Z=n1($,"command");if(Z)return Z;let Y=$.command,J=Math.min(120,Math.max(5,$.timeout||30)),Q=Y8(),X=Bun.spawn([...Q,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),K=setTimeout(()=>X.kill(),J*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?`
156
283
  `:"")+`STDERR:
157
- `+G.trim();if(q!==0)K+=(K?`
158
- `:"")+`Exit code: ${q}`;return W$(K||"(no output)")}async function T9($){let Z=$.url,Y=$.method||"GET",J=$.headers||{},X=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let z=L0(Z);if(z)return z;try{let Q=new AbortController,V=setTimeout(()=>Q.abort(),30000),G=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...J},body:X&&Y!=="GET"&&Y!=="HEAD"?X:void 0,signal:Q.signal});if(clearTimeout(V),G.status>=300&&G.status<400){let M=G.headers.get("location");if(!M)return`Status: ${G.status} (redirect with no location header)`;let D=L0(M);if(D)return`Redirect blocked: ${D}`;return`Status: ${G.status} -> Redirect to: ${M}
159
- (Use fetch_url on the redirect target if needed)`}let q=`${G.status} ${G.statusText}`,K=G.headers.get("content-type")||"";if(Y==="HEAD"){let M=[...G.headers.entries()].map(([D,v])=>`${D}: ${v}`).join(`
160
- `);return`Status: ${q}
161
- ${M}`}let O=G.headers.get("content-length");if(O&&Number(O)>D4*2)return`Status: ${q}
284
+ `+G.trim();if(H!==0)z+=(z?`
285
+ `:"")+`Exit code: ${H}`;return u1(z||"(no output)")}async function vQ($){let Z=$.url,Y=$.method||"GET",J=$.headers||{},Q=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let X=wZ(Z);if(X)return X;try{let K=new AbortController,V=setTimeout(()=>K.abort(),30000),G=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...J},body:Q&&Y!=="GET"&&Y!=="HEAD"?Q:void 0,signal:K.signal});if(clearTimeout(V),G.status>=300&&G.status<400){let E=G.headers.get("location");if(!E)return`Status: ${G.status} (redirect with no location header)`;let j=wZ(E);if(j)return`Redirect blocked: ${j}`;return`Status: ${G.status} -> Redirect to: ${E}
286
+ (Use fetch_url on the redirect target if needed)`}let H=`${G.status} ${G.statusText}`,z=G.headers.get("content-type")||"";if(Y==="HEAD"){let E=[...G.headers.entries()].map(([j,T])=>`${j}: ${T}`).join(`
287
+ `);return`Status: ${H}
288
+ ${E}`}let M=G.headers.get("content-length");if(M&&Number(M)>d0*2)return`Status: ${H}
162
289
 
163
- Error: response body too large (${O} bytes). Max is ${D4*2} bytes.`;let N=await G.text();if(K.includes("text/html")){let M=I9(N);return W$(`Status: ${q}
290
+ Error: response body too large (${M} bytes). Max is ${d0*2} bytes.`;let N=await G.text();if(z.includes("text/html")){let E=gQ(N);return u1(`Status: ${H}
164
291
 
165
- ${M}`)}return W$(`Status: ${q}
292
+ ${E}`)}return u1(`Status: ${H}
166
293
 
167
- ${N}`)}catch(Q){if(Q instanceof Error&&Q.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${Q instanceof Error?Q.message:String(Q)}`}}function L0($){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 X=Y.split(".").map(Number);if(X.length===4&&X.every((z)=>!isNaN(z)&&z>=0&&z<=255)){if(X[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(X[0]===172&&X[1]>=16&&X[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(X[0]===192&&X[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(X[0]===169&&X[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(X[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 I9($){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,`
294
+ ${N}`)}catch(K){if(K instanceof Error&&K.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${K instanceof Error?K.message:String(K)}`}}function wZ($){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 Q=Y.split(".").map(Number);if(Q.length===4&&Q.every((X)=>!isNaN(X)&&X>=0&&X<=255)){if(Q[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(Q[0]===172&&Q[1]>=16&&Q[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(Q[0]===192&&Q[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(Q[0]===169&&Q[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(Q[0]===0)return"Error: requests to 0.x IPs are blocked."}if(Y.startsWith("::ffff:")||Y.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function gQ($){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,`
168
295
  `).replace(/<(br|hr)[^>]*\/?>/gi,`
169
296
  `).replace(/<[^>]+>/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
170
297
 
171
- `).trim()}function S9($,Z){let Y=process.cwd(),J=Y+x4,X=Z+x4,Q=$.trim().split(`
172
- `).map((q)=>{if(q.startsWith(J))return"."+q.slice(Y.length).replace(/\\/g,"/");if(q.startsWith(X))return"."+q.slice(Z.length).replace(/\\/g,"/");return q}),V=Q.length,G=Q.slice(0,100).join(`
298
+ `).trim()}function mQ($,Z){let Y=process.cwd(),J=Y+c0,Q=Z+c0,K=$.trim().split(`
299
+ `).map((H)=>{if(H.startsWith(J))return"."+H.slice(Y.length).replace(/\\/g,"/");if(H.startsWith(Q))return"."+H.slice(Z.length).replace(/\\/g,"/");return H}),V=K.length,G=K.slice(0,100).join(`
173
300
  `);if(V>100)G+=`
174
- ... (${V-100} more matches)`;return W$(G)}function W$($){if($.length<=D4)return $;return $.slice(0,D4)+`
175
- ... (output truncated)`}function g6($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function R0($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje")return Y;if(Z==="amanha"||Z==="amanh\xE3"){let V=new Date(Y);return V.setDate(V.getDate()+1),V}let J=Z.match(/em\s+(\d+)\s*dias?/);if(J){let V=new Date(Y);return V.setDate(V.getDate()+parseInt(J[1])),V}let X=Z.match(/em\s+(\d+)\s*semanas?/);if(X){let V=new Date(Y);return V.setDate(V.getDate()+parseInt(X[1])*7),V}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[V,G]of Object.entries(z))if(Z.includes(V)){let q=new Date(Y),K=(G-q.getDay()+7)%7||7;return q.setDate(q.getDate()+K),q}let Q=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(Q){let V=parseInt(Q[1]),G=parseInt(Q[2])-1,q=Q[3]?parseInt(Q[3])+(Q[3].length===2?2000:0):Y.getFullYear(),K=new Date(q,G,V);if(!isNaN(K.getTime()))return K}return Q1(Z)}var k9=new Set([429,500,502,503,529]);async function k0($,Z={}){let Y=Z.maxRetries??3,J=Z.baseDelayMs??1000,X;for(let z=0;z<=Y;z++)try{return await $()}catch(Q){if(X=Q,Z.signal?.aborted)throw Q;if(z>=Y)throw Q;if(b9(Q)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(z+1,500,"Auth refreshed, retrying..."),await S0(500,Z.signal);continue}}if(!y9(Q))throw Q;let G=_9(Q)??J*Math.pow(2,z),q=Q instanceof Error?Q.message:String(Q);Z.onRetry?.(z+1,G,q),await S0(G,Z.signal)}throw X}function b9($){if(!($ instanceof Error))return!1;return $.status===401}function y9($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&k9.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 _9($){let Z=$.headers;if(!Z)return null;let Y=Z["retry-after"];if(!Y)return null;let J=Number(Y);if(!isNaN(J)&&J>0)return Math.min(J,60)*1000;return null}function S0($,Z){return new Promise((Y,J)=>{let X=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(X),J(Error("Aborted"))},{once:!0})})}var f9={haiku:200000,sonnet:200000,opus:200000};function b2($){return Math.ceil($.length/3.5)}function u6($){let Z=0;for(let Y of $){if(Z+=b2(Y.content),Y.toolCalls)for(let J of Y.toolCalls)Z+=b2(JSON.stringify(J.input)),Z+=b2(J.result);Z+=10}return Z}function p6($){let Z=$.toLowerCase();for(let[Y,J]of Object.entries(f9))if(Z.includes(Y))return J;return 200000}function b0($,Z,Y){let J=p6(Z)-20000-Y;if(u6($)<=J)return $;let z=[],Q=J,V=[...$].reverse(),G=[];for(let K of V){let O=b2(K.content)+(K.toolCalls?.reduce((N,M)=>N+b2(JSON.stringify(M.input))+b2(M.result),0)??0)+10;if(Q-O<0)break;Q-=O,G.unshift(K)}let q=$.length-G.length;if(q>0)z.push({role:"user",content:`[Note: ${q} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return z.push(...G),z}function y0($,Z,Y){let J=p6(Z)-20000-Y;return u6($)>J*0.7}function _0($,Z,Y){let J=p6(Z)-20000-Y;if(u6($)<=J*0.7)return null;let z=Math.max(4,Math.floor($.length*0.3)),Q=$.slice(0,$.length-z),V=$.slice($.length-z);if(Q.length<2)return null;return{toSummarize:Q,toKeep:V}}function f0($){return`Summarize this conversation concisely. Focus on:
301
+ ... (${V-100} more matches)`;return u1(G)}function u1($){if($.length<=d0)return $;return $.slice(0,d0)+`
302
+ ... (output truncated)`}function M7($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function IZ($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje")return Y;if(Z==="amanha"||Z==="amanh\xE3"){let V=new Date(Y);return V.setDate(V.getDate()+1),V}let J=Z.match(/em\s+(\d+)\s*dias?/);if(J){let V=new Date(Y);return V.setDate(V.getDate()+parseInt(J[1])),V}let Q=Z.match(/em\s+(\d+)\s*semanas?/);if(Q){let V=new Date(Y);return V.setDate(V.getDate()+parseInt(Q[1])*7),V}let X={domingo:0,segunda:1,terca:2,ter\u{e7}a:2,quarta:3,quinta:4,sexta:5,sabado:6,s\u{e1}bado:6};for(let[V,G]of Object.entries(X))if(Z.includes(V)){let H=new Date(Y),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):Y.getFullYear(),z=new Date(H,G,V);if(!isNaN(z.getTime()))return z}return m4(Z)}var cQ=new Set([429,500,502,503,529]);async function gZ($,Z={}){let Y=Z.maxRetries??3,J=Z.baseDelayMs??1000,Q;for(let X=0;X<=Y;X++)try{return await $()}catch(K){if(Q=K,Z.signal?.aborted)throw K;if(X>=Y)throw K;if(dQ(K)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(X+1,500,"Auth refreshed, retrying..."),await vZ(500,Z.signal);continue}}if(!uQ(K))throw K;let G=pQ(K)??J*Math.pow(2,X),H=K instanceof Error?K.message:String(K);Z.onRetry?.(X+1,G,H),await vZ(G,Z.signal)}throw Q}function dQ($){if(!($ instanceof Error))return!1;return $.status===401}function uQ($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&cQ.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 pQ($){let Z=$.headers;if(!Z)return null;let Y=Z["retry-after"];if(!Y)return null;let J=Number(Y);if(!isNaN(J)&&J>0)return Math.min(J,60)*1000;return null}function vZ($,Z){return new Promise((Y,J)=>{let Q=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(Q),J(Error("Aborted"))},{once:!0})})}var lQ={haiku:200000,sonnet:200000,opus:200000};function Z1($){return Math.ceil($.length/3.5)}function L7($){let Z=0;for(let Y of $){if(Z+=Z1(Y.content),Y.toolCalls)for(let J of Y.toolCalls)Z+=Z1(JSON.stringify(J.input)),Z+=Z1(J.result);Z+=10}return Z}function j7($){let Z=$.toLowerCase();for(let[Y,J]of Object.entries(lQ))if(Z.includes(Y))return J;return 200000}function mZ($,Z,Y){let J=j7(Z)-20000-Y;if(L7($)<=J)return $;let X=[],K=J,V=[...$].reverse(),G=[];for(let z of V){let M=Z1(z.content)+(z.toolCalls?.reduce((N,E)=>N+Z1(JSON.stringify(E.input))+Z1(E.result),0)??0)+10;if(K-M<0)break;K-=M,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 cZ($,Z,Y){let J=j7(Z)-20000-Y;return L7($)>J*0.7}function dZ($,Z,Y){let J=j7(Z)-20000-Y;if(L7($)<=J*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 uZ($){return`Summarize this conversation concisely. Focus on:
176
303
  1. Key decisions made
177
304
  2. Files created or modified
178
305
  3. Important context the user shared
@@ -182,58 +309,60 @@ Be brief but preserve actionable information. Output ONLY the summary.
182
309
 
183
310
  ---
184
311
  ${$.map((Y)=>{let J=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)J+=`
185
- Tools used: ${Y.toolCalls.map((X)=>X.name).join(", ")}`;return J}).join(`
312
+ Tools used: ${Y.toolCalls.map((Q)=>Q.name).join(", ")}`;return J}).join(`
186
313
 
187
- `)}`}function h0($,Z=2000){return $.map((Y)=>{if(!Y.toolCalls?.length)return Y;let J=Y.toolCalls.map((X)=>{if(X.result.length<=Z)return X;let z=X.result.split(`
188
- `),Q=Math.min(10,z.length),V=Math.min(5,Math.max(0,z.length-Q)),G=z.length-Q-V,q=[...z.slice(0,Q)];if(G>0)q.push(`... (${G} lines omitted)`);if(V>0)q.push(...z.slice(-V));let K=q.join(`
189
- `);return{...X,result:K}});return{...Y,toolCalls:J}})}var h9=[/\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],v9=[/\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 v0($,Z){switch($){case"read_file":case"list_directory":case"find_files":case"search_files":case"fetch_url":return{level:"safe"};case"write_file":return{level:"moderate",reason:`write ${Z.path}`};case"edit_file":return{level:"moderate",reason:`edit ${Z.path}`};case"run_command":{let Y=String(Z.command||"");for(let J of h9)if(J.test(Y))return{level:"dangerous",reason:Y};for(let J of v9)if(J.test(Y))return{level:"moderate",reason:Y};return{level:"moderate",reason:Y}}default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function l6($){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: ${g9(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.
190
- Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${c9(Y)}" may not exist or be unavailable.
314
+ `)}`}function pZ($,Z=2000){return $.map((Y)=>{if(!Y.toolCalls?.length)return Y;let J=Y.toolCalls.map((Q)=>{if(Q.result.length<=Z)return Q;let X=Q.result.split(`
315
+ `),K=Math.min(10,X.length),V=Math.min(5,Math.max(0,X.length-K)),G=X.length-K-V,H=[...X.slice(0,K)];if(G>0)H.push(`... (${G} lines omitted)`);if(V>0)H.push(...X.slice(-V));let z=H.join(`
316
+ `);return{...Q,result:z}});return{...Y,toolCalls:J}})}var nQ=[/\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],iQ=[/\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 lZ($,Z){switch($){case"read_file":case"list_directory":case"find_files":case"search_files":case"fetch_url":case"read_clipboard_content":case"analyze_screen_context":case"memory_status":case"recall_memory":return{level:"safe"};case"write_file":return{level:"moderate",reason:`write ${Z.path}`};case"edit_file":return{level:"moderate",reason:`edit ${Z.path}`};case"run_command":{let Y=String(Z.command||"");for(let J of nQ)if(J.test(Y))return{level:"dangerous",reason:Y};for(let J of iQ)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 F7($){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: ${oQ(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.
317
+ Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${aQ(Y)}" may not exist or be unavailable.
191
318
  Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
192
- 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 J=Y.toLowerCase();if(J.includes("econnrefused")||J.includes("enotfound"))return"Cannot connect to Anthropic API. Check your internet connection.";if(J.includes("etimedout")||J.includes("socket hang up"))return"Connection to Anthropic API timed out. Retrying...";if(J.includes("econnreset"))return"Connection was reset. This usually recovers automatically.";if(J.includes("expired")||J.includes("invalid_api_key"))return"Your subscription token has expired. Run `claude` to refresh.";return Y}function g9($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function c9($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function g0($,Z,Y){if($==="auto")return!1;if(Y==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command"].includes(Z);if($==="confirm-all")return Y!=="safe";return!1}function c0($,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}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function d0($,Z,Y=20){let J=$.split(`
193
- `),X=Z.split(`
194
- `),z=[],Q=J.slice(0,Y);for(let G of Q)z.push(` \x1B[31m- ${G}\x1B[0m`);if(J.length>Y)z.push(` \x1B[2m ... (${J.length-Y} more removed)\x1B[0m`);let V=X.slice(0,Y);for(let G of V)z.push(` \x1B[32m+ ${G}\x1B[0m`);if(X.length>Y)z.push(` \x1B[2m ... (${X.length-Y} more added)\x1B[0m`);return z}class i6{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,J="auto"){this.model=Z;this.maxTokens=Y;this.client=new W2({apiKey:$}),this.approvalMode=J}updateApiKey($){this.client=new W2({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let J=h0($),X=b2(Z);if(y0(J,this.model,X)){let G=_0(J,this.model,X);if(G)try{let K={role:"assistant",content:`[Conversation summary]
195
- ${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};J=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},K,...G.toKeep]}catch{}}let z=b0(J,this.model,X),Q=d9(z),V=Y?r:void 0;try{yield*this.streamLoop(Q,Z,V)}catch(G){yield{type:"error",error:l6(G)}}}async generateSummary($){let Z=f0($),J=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((X)=>X.type==="text");return J?.type==="text"?J.text:"Summary unavailable."}async*streamLoop($,Z,Y){let X=[...$],z=0;while(z++<25){let Q;try{Q=await k0(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:X,...Y?.length?{tools:Y}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(K){yield{type:"error",error:l6(K)};return}for await(let K of Q)if(K.type==="content_block_delta"&&K.delta.type==="text_delta")yield{type:"text",text:K.delta.text};let V=await Q.finalMessage();if(V.usage)yield{type:"usage",inputTokens:V.usage.input_tokens,outputTokens:V.usage.output_tokens};if(V.stop_reason!=="tool_use"){yield{type:"done"};return}let G=V.content.filter((K)=>K.type==="tool_use");X.push({role:"assistant",content:V.content});let q=[];for(let K of G){let O=K.input,N=v0(K.name,O);if(N.level==="dangerous"){yield{type:"tool_blocked",id:K.id,name:K.name,reason:`Blocked dangerous operation: ${N.reason}`},q.push({type:"tool_result",tool_use_id:K.id,content:`Error: Operation blocked for safety. Reason: ${N.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&g0(this.approvalMode,K.name,N.level)&&this.approvalCallback){if(yield{type:"tool_call",id:K.id,name:K.name,input:K.input},!await this.approvalCallback(K.name,O,N.level)){yield{type:"tool_blocked",id:K.id,name:K.name,reason:"Rejected by user"},q.push({type:"tool_result",tool_use_id:K.id,content:"Error: User rejected this operation."});continue}let v=await m6(K.name,O);yield{type:"tool_result",id:K.id,name:K.name,result:v},q.push({type:"tool_result",tool_use_id:K.id,content:v});continue}yield{type:"tool_call",id:K.id,name:K.name,input:K.input};let M=await m6(K.name,O);yield{type:"tool_result",id:K.id,name:K.name,result:M},q.push({type:"tool_result",tool_use_id:K.id,content:M})}X.push({role:"user",content:q})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function d9($){let Z=[];for(let Y of $)if(Y.role==="user")if(Y.images?.length){let J=Y.images.map((X)=>({type:"image",source:{type:"base64",media_type:X.mediaType,data:X.base64}}));J.push({type:"text",text:Y.content}),Z.push({role:"user",content:J})}else Z.push({role:"user",content:Y.content});else if(Y.role==="assistant")if(Y.toolCalls?.length){let J=[];if(Y.content)J.push({type:"text",text:Y.content});for(let X of Y.toolCalls)J.push({type:"tool_use",id:X.id,name:X.name,input:X.input});Z.push({role:"assistant",content:J}),Z.push({role:"user",content:Y.toolCalls.map((X)=>({type:"tool_result",tool_use_id:X.id,content:X.result}))})}else Z.push({role:"assistant",content:Y.content});return Z}import{existsSync as K2,mkdirSync as m0,readdirSync as u0,readFileSync as n6,writeFileSync as o6,unlinkSync as p0,renameSync as l0}from"fs";import{join as Z2}from"path";class a6{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=Z2($,"sessions"),this.archiveDir=Z2($,"sessions","archive"),!K2(this.sessionsDir))m0(this.sessionsDir,{recursive:!0});if(!K2(this.archiveDir))m0(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.current}list(){if(!K2(this.sessionsDir))return[];return u0(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=Z2(this.sessionsDir,`${$}.json`);if(!K2(Z))return null;try{let Y=JSON.parse(n6(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=Z2(this.sessionsDir,`${$}.json`);if(K2(Z))return p0(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=Z2(this.sessionsDir,`${$}.json`);return o6(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=Z2(this.sessionsDir,`${$}.json`);if(!K2(Z))return!1;let Y=Z2(this.archiveDir,`${$}.json`);return l0(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=Z2(this.archiveDir,`${$}.json`);if(!K2(Z))return!1;let Y=Z2(this.sessionsDir,`${$}.json`);return l0(Z,Y),!0}listArchived(){if(!K2(this.archiveDir))return[];return u0(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=Z2(this.archiveDir,`${$}.json`);if(!K2(Z))return null;try{let Y=JSON.parse(n6(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=Z2(this.archiveDir,`${$}.json`);if(K2(Z))return p0(Z),!0;return!1}loadOrCreate($){let Z=Z2(this.sessionsDir,`${$}.json`);if(K2(Z))try{return JSON.parse(n6(Z,"utf-8"))}catch{}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return o6(Z,JSON.stringify(Y,null,2)),Y}save(){let $=Z2(this.sessionsDir,`${this.current.name}.json`);o6($,JSON.stringify(this.current,null,2))}}import{existsSync as o0,readdirSync as l9,readFileSync as a0}from"fs";import{join as s6}from"path";import{existsSync as r6,readFileSync as i0}from"fs";import{basename as m9,join as A4}from"path";function n0(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${N7()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),x)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=u9($);if(Y)Z.push(`Project: ${Y}`);let J=p9($);if(J)Z.push(J);return Z.join(`
196
- `)}function u9($){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[X,z]of Z)if(r6(A4($,X)))Y.push(z);if(Y.length===0)return null;let J=m9($);try{let X=A4($,"package.json");if(r6(X)){let z=JSON.parse(i0(X,"utf-8"));if(z.name)J=z.name}}catch{}return`Project: ${J} (${Y.join(", ")})`}function p9($){if(!r6(A4($,".git")))return null;let Z=[];try{let Y=i0(A4($,".git","HEAD"),"utf-8").trim(),J=Y.startsWith("ref: refs/heads/")?Y.slice(16):Y.slice(0,8);Z.push(`Git branch: ${J}`)}catch{return Z.push("Git: initialized"),Z.join(`
197
- `)}try{let Y=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J)Z.push(`Last commit: ${J}`)}}catch{}try{let Y=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J){let X=J.split(`
198
- `),z=X.slice(0,15);if(X.length>15)z.push(`... and ${X.length-15} more files`);Z.push(`Uncommitted changes:
199
- `+z.join(`
200
- `))}}}catch{}try{let Y=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J){let X=J.split(`
201
- `).slice(0,10);Z.push(`Staged:
319
+ 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 J=Y.toLowerCase();if(J.includes("econnrefused")||J.includes("enotfound"))return"Cannot connect to Anthropic API. Check your internet connection.";if(J.includes("etimedout")||J.includes("socket hang up"))return"Connection to Anthropic API timed out. Retrying...";if(J.includes("econnreset"))return"Connection was reset. This usually recovers automatically.";if(J.includes("expired")||J.includes("invalid_api_key"))return"Your subscription token has expired. Run `claude` to refresh.";return Y}function oQ($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function aQ($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function nZ($,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 iZ($,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||""),J=Y.split(`
320
+ `)[0]||"",Q=Y.split(`
321
+ `).length;return`PowerShell (${Q} line${Q>1?"s":""}): ${J.length>50?J.slice(0,47)+"...":J}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function oZ($,Z,Y=20){let J=$.split(`
322
+ `),Q=Z.split(`
323
+ `),X=[],K=J.slice(0,Y);for(let G of K)X.push(` \x1B[31m- ${G}\x1B[0m`);if(J.length>Y)X.push(` \x1B[2m ... (${J.length-Y} more removed)\x1B[0m`);let V=Q.slice(0,Y);for(let G of V)X.push(` \x1B[32m+ ${G}\x1B[0m`);if(Q.length>Y)X.push(` \x1B[2m ... (${Q.length-Y} more added)\x1B[0m`);return X}class R7{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,J="auto"){this.model=Z;this.maxTokens=Y;this.client=new j$({apiKey:$}),this.approvalMode=J}updateApiKey($){this.client=new j$({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let J=pZ($),Q=Z1(Z);if(cZ(J,this.model,Q)){let G=dZ(J,this.model,Q);if(G)try{let z={role:"assistant",content:`[Conversation summary]
324
+ ${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};J=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},z,...G.toKeep]}catch{}}let X=mZ(J,this.model,Q),K=rQ(X),V=Y?u:void 0;try{yield*this.streamLoop(K,Z,V)}catch(G){yield{type:"error",error:F7(G)}}}async generateSummary($){let Z=uZ($),J=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((Q)=>Q.type==="text");return J?.type==="text"?J.text:"Summary unavailable."}async*streamLoop($,Z,Y){let Q=[...$],X=0;while(X++<25){let K;try{K=await gZ(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:Q,...Y?.length?{tools:Y}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(z){yield{type:"error",error:F7(z)};return}for await(let z of K)if(z.type==="content_block_delta"&&z.delta.type==="text_delta")yield{type:"text",text:z.delta.text};let V=await K.finalMessage();if(V.usage)yield{type:"usage",inputTokens:V.usage.input_tokens,outputTokens:V.usage.output_tokens};if(V.stop_reason!=="tool_use"){yield{type:"done"};return}let G=V.content.filter((z)=>z.type==="tool_use");Q.push({role:"assistant",content:V.content});let H=[];for(let z of G){let M=z.input,N=lZ(z.name,M);if(N.level==="dangerous"){yield{type:"tool_blocked",id:z.id,name:z.name,reason:`Blocked dangerous operation: ${N.reason}`},H.push({type:"tool_result",tool_use_id:z.id,content:`Error: Operation blocked for safety. Reason: ${N.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&nZ(this.approvalMode,z.name,N.level)&&this.approvalCallback){if(yield{type:"tool_call",id:z.id,name:z.name,input:z.input},!await this.approvalCallback(z.name,M,N.level)){yield{type:"tool_blocked",id:z.id,name:z.name,reason:"Rejected by user"},H.push({type:"tool_result",tool_use_id:z.id,content:"Error: User rejected this operation."});continue}let T=await E7(z.name,M);yield{type:"tool_result",id:z.id,name:z.name,result:T},H.push({type:"tool_result",tool_use_id:z.id,content:T});continue}yield{type:"tool_call",id:z.id,name:z.name,input:z.input};let E=await E7(z.name,M);yield{type:"tool_result",id:z.id,name:z.name,result:E},H.push({type:"tool_result",tool_use_id:z.id,content:E})}Q.push({role:"user",content:H})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function rQ($){let Z=[];for(let Y of $)if(Y.role==="user")if(Y.images?.length){let J=Y.images.map((Q)=>({type:"image",source:{type:"base64",media_type:Q.mediaType,data:Q.base64}}));J.push({type:"text",text:Y.content}),Z.push({role:"user",content:J})}else Z.push({role:"user",content:Y.content});else if(Y.role==="assistant")if(Y.toolCalls?.length){let J=[];if(Y.content)J.push({type:"text",text:Y.content});for(let Q of Y.toolCalls)J.push({type:"tool_use",id:Q.id,name:Q.name,input:Q.input});Z.push({role:"assistant",content:J}),Z.push({role:"user",content:Y.toolCalls.map((Q)=>({type:"tool_result",tool_use_id:Q.id,content:Q.result}))})}else Z.push({role:"assistant",content:Y.content});return Z}r();import{existsSync as O$,mkdirSync as aZ,readdirSync as rZ,readFileSync as A7,unlinkSync as sZ,renameSync as x7}from"fs";import{join as Q$}from"path";class D7{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=Q$($,"sessions"),this.archiveDir=Q$($,"sessions","archive"),!O$(this.sessionsDir))aZ(this.sessionsDir,{recursive:!0});if(!O$(this.archiveDir))aZ(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.current}list(){if(!O$(this.sessionsDir))return[];return rZ(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=Q$(this.sessionsDir,`${$}.json`);if(!O$(Z))return null;try{let Y=JSON.parse(A7(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=Q$(this.sessionsDir,`${$}.json`);if(O$(Z))return sZ(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=Q$(this.sessionsDir,`${$}.json`);return D(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=Q$(this.sessionsDir,`${$}.json`);if(!O$(Z))return!1;let Y=Q$(this.archiveDir,`${$}.json`);return x7(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=Q$(this.archiveDir,`${$}.json`);if(!O$(Z))return!1;let Y=Q$(this.sessionsDir,`${$}.json`);return x7(Z,Y),!0}listArchived(){if(!O$(this.archiveDir))return[];return rZ(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=Q$(this.archiveDir,`${$}.json`);if(!O$(Z))return null;try{let Y=JSON.parse(A7(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}deleteArchived($){let Z=Q$(this.archiveDir,`${$}.json`);if(O$(Z))return sZ(Z),!0;return!1}loadOrCreate($){let Z=Q$(this.sessionsDir,`${$}.json`);if(O$(Z))try{return JSON.parse(A7(Z,"utf-8"))}catch{let J=Q$(this.sessionsDir,`${$}.corrupt.json`);try{x7(Z,J)}catch{}}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return D(Z,JSON.stringify(Y,null,2)),Y}save(){let $=Q$(this.sessionsDir,`${this.current.name}.json`);D($,JSON.stringify(this.current,null,2))}}import{existsSync as $6,readdirSync as $X,readFileSync as Z6}from"fs";import{join as P7}from"path";import{existsSync as T7,readFileSync as tZ}from"fs";import{basename as sQ,join as u0}from"path";function eZ(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${a7()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),A)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=tQ($);if(Y)Z.push(`Project: ${Y}`);let J=eQ($);if(J)Z.push(J);return Z.join(`
325
+ `)}function tQ($){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[Q,X]of Z)if(T7(u0($,Q)))Y.push(X);if(Y.length===0)return null;let J=sQ($);try{let Q=u0($,"package.json");if(T7(Q)){let X=JSON.parse(tZ(Q,"utf-8"));if(X.name)J=X.name}}catch{}return`Project: ${J} (${Y.join(", ")})`}function eQ($){if(!T7(u0($,".git")))return null;let Z=[];try{let Y=tZ(u0($,".git","HEAD"),"utf-8").trim(),J=Y.startsWith("ref: refs/heads/")?Y.slice(16):Y.slice(0,8);Z.push(`Git branch: ${J}`)}catch{return Z.push("Git: initialized"),Z.join(`
326
+ `)}try{let Y=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J)Z.push(`Last commit: ${J}`)}}catch{}try{let Y=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J){let Q=J.split(`
327
+ `),X=Q.slice(0,15);if(Q.length>15)X.push(`... and ${Q.length-15} more files`);Z.push(`Uncommitted changes:
202
328
  `+X.join(`
329
+ `))}}}catch{}try{let Y=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J){let Q=J.split(`
330
+ `).slice(0,10);Z.push(`Staged:
331
+ `+Q.join(`
203
332
  `))}}}catch{}return Z.length>0?Z.join(`
204
- `):null}function r0($,Z){if(!o0($))return[];let Y=[],J=l9($,{withFileTypes:!0});for(let X of J)if(X.isFile()&&X.name.endsWith(".md")){let z=a0(s6($,X.name),"utf-8");Y.push({name:X.name.replace(".md",""),content:z.trim(),source:Z})}else if(X.isDirectory()){let z=s6($,X.name,"SKILL.md");if(o0(z)){let Q=a0(z,"utf-8");Y.push({name:X.name,content:Q.trim(),source:Z})}}return Y}function s0($){let Z=r0($,"global"),Y=s6(process.cwd(),".smolerclaw","skills"),J=r0(Y,"local"),X=new Map;for(let z of Z)X.set(z.name,z);for(let z of J)X.set(z.name,z);return[...X.values()]}function t0($){if($.length===0)return"No skills loaded.";return`Skills:
333
+ `):null}function Y6($,Z){if(!$6($))return[];let Y=[],J=$X($,{withFileTypes:!0});for(let Q of J)if(Q.isFile()&&Q.name.endsWith(".md")){let X=Z6(P7($,Q.name),"utf-8");Y.push({name:Q.name.replace(".md",""),content:X.trim(),source:Z})}else if(Q.isDirectory()){let X=P7($,Q.name,"SKILL.md");if($6(X)){let K=Z6(X,"utf-8");Y.push({name:Q.name,content:K.trim(),source:Z})}}return Y}function J6($){let Z=Y6($,"global"),Y=P7(process.cwd(),".smolerclaw","skills"),J=Y6(Y,"local"),Q=new Map;for(let X of Z)Q.set(X.name,X);for(let X of J)Q.set(X.name,X);return[...Q.values()]}function Q6($){if($.length===0)return"No skills loaded.";return`Skills:
205
334
  `+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
206
- `)}function t6($,Z,Y="auto"){let J=[];for(let X of Z)J.push(X.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;J.push(`## Language Override
207
- ALWAYS respond in ${z}. This is a hard requirement.`)}if(J.push(`---
335
+ `)}function w7($,Z,Y="auto"){let J=[];for(let Q of Z)J.push(Q.content);if(Y&&Y!=="auto"){let X={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[Y]||Y;J.push(`## Language Override
336
+ ALWAYS respond in ${X}. This is a hard requirement.`)}if(J.push(`---
208
337
  ## Environment
209
338
  The user's current working directory and project info. Use this context when they ask about code or files.
210
339
 
211
- `+n0()),$)J.push(`## User Instructions
340
+ `+eZ()),$)J.push(`## User Instructions
212
341
  `+$);return J.join(`
213
342
 
214
- `)}var i9=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function q2($){return i9?"":$}var B={altOn:q2("\x1B[?1049h"),altOff:q2("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:q2("\x1B[1m"),dim:q2("\x1B[2m"),italic:q2("\x1B[3m"),underline:q2("\x1B[4m"),reset:q2("\x1B[0m"),inv:q2("\x1B[7m"),fg:($)=>q2(`\x1B[38;5;${$}m`),bg:($)=>q2(`\x1B[48;5;${$}m`)};var m={user:B.fg(75),ai:B.fg(114),tool:B.fg(215),err:B.fg(196),sys:B.fg(245),prompt:B.fg(220),code:B.fg(180),heading:B.fg(75),link:B.fg(39),quote:B.fg(245)};function P($){process.stdout.write($)}var n9=/\x1b\[[0-9;]*[a-zA-Z]/g;function w4($){return $.replace(n9,"")}function o9($){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 P4($){let Z=w4($),Y=0;for(let J of Z)Y+=o9(J);return Y}function e0($,Z){if(Z<10)Z=10;let Y=[];for(let J of $.split(`
215
- `)){if(P4(J)<=Z){Y.push(J);continue}let Q=w4(J).split(" "),V=[],G="";for(let K of Q)if(G.length+(G?1:0)+K.length>Z&&G)V.push(G),G=" "+K;else G+=(G?" ":"")+K;if(G)V.push(G);let q=a9(J);for(let K=0;K<V.length;K++)if(q&&K===0)V[K]=q+V[K]+B.reset;else if(q)V[K]=q+V[K]+B.reset;Y.push(...V)}return Y}function a9($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function T4($){let Z=$.split(`
216
- `),Y=[],J=!1,X="";for(let z=0;z<Z.length;z++){let Q=Z[z];if(Q.trimStart().startsWith("```")){if(!J){J=!0,X=Q.trimStart().slice(3).trim();let K=X?` ${X}`:"";Y.push(` ${B.dim}\u250C\u2500\u2500${K}${"\u2500".repeat(Math.max(1,40-K.length))}${B.reset}`)}else J=!1,X="",Y.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);continue}if(J){Y.push(` ${B.dim}\u2502${B.reset} ${m.code}${Q}${B.reset}`);continue}if(!Q.trim()){Y.push("");continue}let V=Q.match(/^(#{1,3})\s+(.+)/);if(V){let K=V[1].length,O=V[2],N=K===1?"\u2501":K===2?"\u2500":"\xB7";Y.push(` ${m.heading}${B.bold}${N} ${U1(O)}${B.reset}`);continue}if(Q.trimStart().startsWith(">")){let K=Q.replace(/^\s*>\s?/,"");Y.push(` ${m.quote}\u2502 ${U1(K)}${B.reset}`);continue}let G=Q.match(/^(\s*)([-*+])\s+(.+)/);if(G){let K=Math.floor(G[1].length/2),O=G[3],N=" ".repeat(K);Y.push(` ${N}${B.dim}\u2022${B.reset} ${U1(O)}`);continue}let q=Q.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(q){let K=Math.floor(q[1].length/2),O=q[2],N=q[3],M=" ".repeat(K);Y.push(` ${M}${B.dim}${O}.${B.reset} ${U1(N)}`);continue}if(/^[-*_]{3,}\s*$/.test(Q.trim())){Y.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`);continue}Y.push(` ${U1(Q)}`)}if(J)Y.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);return Y}function U1($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${B.inv} $1 ${B.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${B.bold}${B.italic}$1${B.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${B.bold}$1${B.reset}`),Z=Z.replace(/__(.+?)__/g,`${B.bold}$1${B.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${B.italic}$1${B.reset}`),Z=Z.replace(/_(.+?)_/g,`${B.italic}$1${B.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${B.underline}$1${B.reset} ${m.link}($2)${B.reset}`),Z}import{existsSync as r9,readFileSync as s9,writeFileSync as t9}from"fs";var e6=500;class $7{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>e6)this.entries=this.entries.slice(-e6);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(r9(this.filePath)){let $=s9(this.filePath,"utf-8");this.entries=$.split(`
217
- `).filter(Boolean).slice(-e6)}}catch{}}save(){try{t9(this.filePath,this.entries.join(`
343
+ `)}var ZX=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function R$($){return ZX?"":$}var C={altOn:R$("\x1B[?1049h"),altOff:R$("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:R$("\x1B[1m"),dim:R$("\x1B[2m"),italic:R$("\x1B[3m"),underline:R$("\x1B[4m"),reset:R$("\x1B[0m"),inv:R$("\x1B[7m"),fg:($)=>R$(`\x1B[38;5;${$}m`),bg:($)=>R$(`\x1B[48;5;${$}m`)};var o={user:C.fg(75),ai:C.fg(114),tool:C.fg(215),err:C.fg(196),sys:C.fg(245),prompt:C.fg(220),code:C.fg(180),heading:C.fg(75),link:C.fg(39),quote:C.fg(245)};function I($){process.stdout.write($)}var YX=/\x1b\[[0-9;]*[a-zA-Z]/g;function p0($){return $.replace(YX,"")}function JX($){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 l0($){let Z=p0($),Y=0;for(let J of Z)Y+=JX(J);return Y}function X6($,Z){if(Z<10)Z=10;let Y=[];for(let J of $.split(`
344
+ `)){if(l0(J)<=Z){Y.push(J);continue}let K=p0(J).split(" "),V=[],G="";for(let z of K)if(G.length+(G?1:0)+z.length>Z&&G)V.push(G),G=" "+z;else G+=(G?" ":"")+z;if(G)V.push(G);let H=QX(J);for(let z=0;z<V.length;z++)if(H&&z===0)V[z]=H+V[z]+C.reset;else if(H)V[z]=H+V[z]+C.reset;Y.push(...V)}return Y}function QX($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function n0($){let Z=$.split(`
345
+ `),Y=[],J=!1,Q="";for(let X=0;X<Z.length;X++){let K=Z[X];if(K.trimStart().startsWith("```")){if(!J){J=!0,Q=K.trimStart().slice(3).trim();let z=Q?` ${Q}`:"";Y.push(` ${C.dim}\u250C\u2500\u2500${z}${"\u2500".repeat(Math.max(1,40-z.length))}${C.reset}`)}else J=!1,Q="",Y.push(` ${C.dim}\u2514${"\u2500".repeat(42)}${C.reset}`);continue}if(J){Y.push(` ${C.dim}\u2502${C.reset} ${o.code}${K}${C.reset}`);continue}if(!K.trim()){Y.push("");continue}let V=K.match(/^(#{1,3})\s+(.+)/);if(V){let z=V[1].length,M=V[2],N=z===1?"\u2501":z===2?"\u2500":"\xB7";Y.push(` ${o.heading}${C.bold}${N} ${o4(M)}${C.reset}`);continue}if(K.trimStart().startsWith(">")){let z=K.replace(/^\s*>\s?/,"");Y.push(` ${o.quote}\u2502 ${o4(z)}${C.reset}`);continue}let G=K.match(/^(\s*)([-*+])\s+(.+)/);if(G){let z=Math.floor(G[1].length/2),M=G[3],N=" ".repeat(z);Y.push(` ${N}${C.dim}\u2022${C.reset} ${o4(M)}`);continue}let H=K.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(H){let z=Math.floor(H[1].length/2),M=H[2],N=H[3],E=" ".repeat(z);Y.push(` ${E}${C.dim}${M}.${C.reset} ${o4(N)}`);continue}if(/^[-*_]{3,}\s*$/.test(K.trim())){Y.push(` ${C.dim}${"\u2500".repeat(40)}${C.reset}`);continue}Y.push(` ${o4(K)}`)}if(J)Y.push(` ${C.dim}\u2514${"\u2500".repeat(42)}${C.reset}`);return Y}function o4($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${C.inv} $1 ${C.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${C.bold}${C.italic}$1${C.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${C.bold}$1${C.reset}`),Z=Z.replace(/__(.+?)__/g,`${C.bold}$1${C.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${C.italic}$1${C.reset}`),Z=Z.replace(/_(.+?)_/g,`${C.italic}$1${C.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${C.underline}$1${C.reset} ${o.link}($2)${C.reset}`),Z}import{existsSync as XX,readFileSync as KX,writeFileSync as zX}from"fs";var I7=500;class S7{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>I7)this.entries=this.entries.slice(-I7);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(XX(this.filePath)){let $=KX(this.filePath,"utf-8");this.entries=$.split(`
346
+ `).filter(Boolean).slice(-I7)}}catch{}}save(){try{zX(this.filePath,this.entries.join(`
218
347
  `)+`
219
- `)}catch{}}}import{join as e9}from"path";class Z7{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="";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","/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"];onSubmit=null;onCancel=null;onExit=null;constructor($,Z,Y="",J){this.model=$;this.sessionName=Z;this.authInfo=Y;this.dataDir=J}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 $7(e9(this.dataDir,"history"));P(B.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}stop(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer);process.stdin.setRawMode?.(!1),process.stdin.pause(),P(B.show),P(B.altOff)}addUserMessage($){this.addLabel("user"),this.addWrapped($),this.lines.push({text:""})}addAssistantMessage($){this.addLabel("assistant"),this.addMarkdown($),this.lines.push({text:""})}startStream(){this.isStreaming=!0,this.streamBuf="",this.streamLines=[],this.streamStartTime=Date.now(),this.addLabel("assistant"),this.startSpinner(),this.renderAll()}appendStream($){if(this.streamBuf+=$,!this.renderTimer)this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.streamLines=T4(this.streamBuf).map((Z)=>({text:Z})),this.renderMessages(),this.renderInput()},50)}flushStream(){if(this.streamLines.length>0)this.lines.push(...this.streamLines),this.streamLines=[],this.streamBuf=""}resetStreamBuffer(){this.streamBuf="",this.streamLines=[]}endStream(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer),this.renderTimer=null,this.streamLines=T4(this.streamBuf).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let Y=Z,J;switch($){case"read_file":if(J=String(Y.path||""),Y.offset)J+=`:${Y.offset}`;break;case"write_file":case"edit_file":J=String(Y.path||"");break;case"search_files":if(J=`/${Y.pattern||""}/`,Y.include)J+=` (${Y.include})`;break;case"find_files":J=String(Y.pattern||"");break;case"list_directory":J=String(Y.path||".");break;case"run_command":if(J=String(Y.command||""),J.length>80)J=J.slice(0,77)+"...";break;default:{let X=JSON.stringify(Y);J=X.length>80?X.slice(0,77)+"...":X}}this.lines.push({text:` ${m.tool}\u2699 ${$}${B.reset} ${B.dim}${J}${B.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
220
- `),J=8,X=Y.slice(0,8);for(let z of X){let Q=z.length>this.width-6?z.slice(0,this.width-9)+"...":z;this.lines.push({text:` ${B.dim}${Q}${B.reset}`})}if(Y.length>8)this.lines.push({text:` ${B.dim}... (${Y.length-8} more lines)${B.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${m.prompt}? ${$}${B.reset} ${B.dim}[y]es / [n]o / [a]ll${B.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(J)=>{let X=J.toString().toLowerCase();if(X==="y"||X==="\r"||X===`
221
- `)process.stdin.removeListener("data",Y),this.lines.push({text:` ${m.sys}approved${B.reset}`}),this.renderAll(),Z(!0);else if(X==="n"||X==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${m.err}rejected${B.reset}`}),this.renderAll(),Z(!1);else if(X==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${m.sys}approved all for this session${B.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${B.dim}timeout \u2014 auto-rejected${B.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;showUsage($){this.lines.push({text:` ${B.dim}tokens: ${$}${B.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${m.err}\u2717 ${$}${B.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
222
- `))this.lines.push({text:` ${m.sys}${Z}${B.reset}`});this.lines.push({text:""}),this.renderAll()}clearMessages(){this.lines=[],this.renderAll()}updateModel($){this.model=$,this.renderHeader()}updateSession($){this.sessionName=$,this.renderHeader()}enableInput(){this.inputBuf="",this.inputPos=0,this.isStreaming=!1,this.history?.reset(),this.renderInput()}disableInput(){P(B.hide)}render(){P(B.hide),P(B.clear),this.renderHeader(),this.renderMessages(),this.renderInput(),P(B.show)}renderAll(){this.renderMessages(),this.renderInput()}renderHeader(){P(B.to(1,1)),P(B.inv);let $=" smolerclaw",Z=[this.model,this.sessionName];if(this.sessionCost)Z.push(this.sessionCost);if(this.authInfo)Z.push(this.authInfo);let Y=Z.join(" | ")+" ",J=Math.max(1,this.width-$.length-Y.length);P($+" ".repeat(J)+Y),P(B.reset),P(B.to(2,1)),P(`${B.dim}${"\u2500".repeat(this.width)}${B.reset}`)}renderMessages(){let Y=this.height-2-2,J=[...this.lines,...this.streamLines],X=J.length,z=Math.max(0,X-Y-this.scrollOffset),Q=Math.min(X,z+Y),V=J.slice(z,Q);P(B.hide);for(let G=0;G<Y;G++)if(P(B.to(2+G+1,1)),P(B.clearLine),G<V.length){let q=w4(V[G].text);if(q.length>this.width)P(V[G].text.slice(0,this.width+(V[G].text.length-q.length))),P(B.reset);else P(V[G].text)}}renderInput(){let $=this.height-1,Z=this.height;if(P(B.to($,1)),P(B.clearLine),P(`${B.dim}${"\u2500".repeat(this.width)}${B.reset}`),P(B.to(Z,1)),P(B.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);P(` ${m.ai}${this.getSpinnerChar()}${B.reset} ${B.dim}streaming... ${Y}s${B.reset}`),P(B.hide)}else{let Y=P4(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;P(`${m.prompt}\u276F${B.reset} ${Y}`);let J=this.inputBuf.slice(0,this.inputPos),X=P4(J)+3;P(B.to(Z,Math.min(X,this.width))),P(B.show)}}onKey($){let Z=$.toString("utf-8");if(Z==="\x03"){if(this.isStreaming)this.onCancel?.();else this.onExit?.();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.commands.filter((J)=>J.startsWith(this.inputBuf));if(Y.length===1)this.inputBuf=Y[0]+" ",this.inputPos=this.inputBuf.length,this.renderInput();else if(Y.length>1){let J=Y[0];for(let X of Y)while(!X.startsWith(J))J=J.slice(0,-1);if(J.length>this.inputBuf.length)this.inputBuf=J,this.inputPos=this.inputBuf.length;this.showSystem(Y.join(" "))}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!YZ(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===`
348
+ `)}catch{}}}import{join as VX}from"path";class b7{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="";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;constructor($,Z,Y="",J){this.model=$;this.sessionName=Z;this.authInfo=Y;this.dataDir=J}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 S7(VX(this.dataDir,"history"));I(C.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}stop(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer);process.stdin.setRawMode?.(!1),process.stdin.pause(),I(C.show),I(C.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=n0(this.streamBuf).map((Z)=>({text:Z})),this.renderMessages(),this.renderInput()},50)}flushStream(){if(this.streamLines.length>0)this.lines.push(...this.streamLines),this.streamLines=[],this.streamBuf=""}resetStreamBuffer(){this.streamBuf="",this.streamLines=[]}endStream(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer),this.renderTimer=null,this.streamLines=n0(this.streamBuf).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let Y=Z,J;switch($){case"read_file":if(J=String(Y.path||""),Y.offset)J+=`:${Y.offset}`;break;case"write_file":case"edit_file":J=String(Y.path||"");break;case"search_files":if(J=`/${Y.pattern||""}/`,Y.include)J+=` (${Y.include})`;break;case"find_files":J=String(Y.pattern||"");break;case"list_directory":J=String(Y.path||".");break;case"run_command":if(J=String(Y.command||""),J.length>80)J=J.slice(0,77)+"...";break;default:{let Q=JSON.stringify(Y);J=Q.length>80?Q.slice(0,77)+"...":Q}}this.lines.push({text:` ${o.tool}\u2699 ${$}${C.reset} ${C.dim}${J}${C.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
349
+ `),J=8,Q=Y.slice(0,8);for(let X of Q){let K=X.length>this.width-6?X.slice(0,this.width-9)+"...":X;this.lines.push({text:` ${C.dim}${K}${C.reset}`})}if(Y.length>8)this.lines.push({text:` ${C.dim}... (${Y.length-8} more lines)${C.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${o.prompt}? ${$}${C.reset} ${C.dim}[y]es / [n]o / [a]ll${C.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(J)=>{let Q=J.toString().toLowerCase();if(Q==="y"||Q==="\r"||Q===`
350
+ `)process.stdin.removeListener("data",Y),this.lines.push({text:` ${o.sys}approved${C.reset}`}),this.renderAll(),Z(!0);else if(Q==="n"||Q==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${o.err}rejected${C.reset}`}),this.renderAll(),Z(!1);else if(Q==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${o.sys}approved all for this session${C.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${C.dim}timeout \u2014 auto-rejected${C.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;showUsage($){this.lines.push({text:` ${C.dim}tokens: ${$}${C.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${o.err}\u2717 ${$}${C.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
351
+ `))this.lines.push({text:` ${o.sys}${Z}${C.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(){I(C.hide)}render(){I(C.hide),I(C.clear),this.renderHeader(),this.renderMessages(),this.renderInput(),I(C.show)}renderAll(){this.renderMessages(),this.renderInput()}renderHeader(){I(C.to(1,1)),I(C.inv);let $=" smolerclaw",Z=[this.model,this.sessionName];if(this.sessionCost)Z.push(this.sessionCost);if(this.authInfo)Z.push(this.authInfo);let Y=Z.join(" | ")+" ",J=Math.max(1,this.width-$.length-Y.length);I($+" ".repeat(J)+Y),I(C.reset),I(C.to(2,1)),I(`${C.dim}${"\u2500".repeat(this.width)}${C.reset}`)}renderMessages(){let Y=this.height-2-2,J=[...this.lines,...this.streamLines],Q=J.length,X=Math.max(0,Q-Y-this.scrollOffset),K=Math.min(Q,X+Y),V=J.slice(X,K);I(C.hide);for(let G=0;G<Y;G++)if(I(C.to(2+G+1,1)),I(C.clearLine),G<V.length){let H=p0(V[G].text);if(H.length>this.width)I(V[G].text.slice(0,this.width+(V[G].text.length-H.length))),I(C.reset);else I(V[G].text)}}completeInput($){let Z=$.split(" "),Y=Z[0];if(Z.length===1){let K=this.commands.filter((V)=>V.startsWith(Y));if(K.length===1){let V=this.subcommands[K[0]];if(V&&V.length>0)return{value:K[0]+" ",options:`Opcoes: ${V.join(" ")}`};return{value:K[0]+" "}}if(K.length>1){let V=K[0];for(let G of K)while(!G.startsWith(V))V=V.slice(0,-1);return{value:V.length>$.length?V:$,options:K.join(" ")}}return null}let J=this.subcommands[Y];if(!J||J.length===0)return null;let Q=Z[Z.length-1].toLowerCase(),X=J.filter((K)=>K.toLowerCase().startsWith(Q));if(X.length===1)return Z[Z.length-1]=X[0],{value:Z.join(" ")+" "};if(X.length>1){let K=X[0];for(let V of X)while(!V.toLowerCase().startsWith(K.toLowerCase()))K=K.slice(0,-1);if(K.length>Q.length)return Z[Z.length-1]=K,{value:Z.join(" "),options:X.join(" ")};return{value:$,options:X.join(" ")}}if(!Q&&J.length>0)return{value:$,options:J.join(" ")};return null}renderInput(){let $=this.height-1,Z=this.height;if(I(C.to($,1)),I(C.clearLine),I(`${C.dim}${"\u2500".repeat(this.width)}${C.reset}`),I(C.to(Z,1)),I(C.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);I(` ${o.ai}${this.getSpinnerChar()}${C.reset} ${C.dim}streaming... ${Y}s${C.reset}`),I(C.hide)}else{let Y=l0(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;I(`${o.prompt}\u276F${C.reset} ${Y}`);let J=this.inputBuf.slice(0,this.inputPos),Q=l0(J)+3;I(C.to(Z,Math.min(Q,this.width))),I(C.show)}}onKey($){let Z=$.toString("utf-8");if(Z==="\x03"){if(this.isStreaming)this.onCancel?.();else this.onExit?.();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")&&!V6(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===`
223
352
  `){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
224
- `,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=$Z(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-=$Z(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=ZZ(this.inputBuf,this.inputPos),this.renderInput();break;case"A":{let J=this.history?.prev(this.inputBuf);if(J!==null&&J!==void 0)this.inputBuf=J,this.inputPos=this.inputBuf.length,this.renderInput();break}case"B":{let J=this.history?.next();if(J!==void 0)this.inputBuf=J,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 J=ZZ(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+J),this.renderInput()}break}}return}if($Y(Z))this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.renderInput()}onResize(){this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${m.user}${B.bold} You${B.reset} ${B.dim}${Z}${B.reset}`});else this.lines.push({text:`${m.ai}${B.bold} Claude${B.reset} ${B.dim}${Z}${B.reset}`})}startSpinner(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];this.spinnerFrame=0,this.spinnerTimer=setInterval(()=>{this.spinnerFrame=(this.spinnerFrame+1)%$.length,this.renderInput()},80)}stopSpinner(){if(this.spinnerTimer)clearInterval(this.spinnerTimer),this.spinnerTimer=null}getSpinnerChar(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];return $[this.spinnerFrame%$.length]}addWrapped($){let Z=e0(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=T4($);for(let Y of Z)this.lines.push({text:Y})}}function YZ($){return[...$].length===1}function $Y($){if(!YZ($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function $Z($,Z){if(Z<=0)return 0;if(Z>=2){let Y=$.charCodeAt(Z-1),J=$.charCodeAt(Z-2);if(Y>=56320&&Y<=57343&&J>=55296&&J<=56319)return 2}return 1}function ZZ($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}var B1={"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}},ZY={input:3,output:15};function JZ($,Z){let Y=YY(Z),J=$.inputTokens/1e6*Y.input*100,X=$.outputTokens/1e6*Y.output*100;return{inputCostCents:J,outputCostCents:X,totalCostCents:J+X}}function YY($){if(B1[$])return B1[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return B1["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return B1["claude-opus-4-20250514"];if(Z.includes("sonnet"))return B1["claude-sonnet-4-20250514"];return ZY}class Y7{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=JZ($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=JZ($,this.model);return`${I4($.inputTokens)} in / ${I4($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${I4(this.totalInput)} in / ${I4(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function I4($){return $.toLocaleString("en-US")}function XZ($,Z={}){let{includeToolCalls:Y=!0,includeTimestamps:J=!0}=Z,X=[];X.push(`# smolerclaw session: ${$.name}`),X.push(`Created: ${new Date($.created).toLocaleString()}`),X.push(""),X.push("---"),X.push("");for(let z of $.messages){let Q=J?` (${new Date(z.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(z.role==="user")X.push(`## You${Q}`),X.push(""),X.push(z.content),X.push("");else{if(X.push(`## Claude${Q}`),X.push(""),X.push(z.content),Y&&z.toolCalls?.length){X.push("");for(let V of z.toolCalls){let G=JY(V.name,V.input);X.push(`> **Tool:** \`${V.name}\`${G}`);let q=V.result.split(`
353
+ `,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=K6(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-=K6(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=z6(this.inputBuf,this.inputPos),this.renderInput();break;case"A":{let J=this.history?.prev(this.inputBuf);if(J!==null&&J!==void 0)this.inputBuf=J,this.inputPos=this.inputBuf.length,this.renderInput();break}case"B":{let J=this.history?.next();if(J!==void 0)this.inputBuf=J,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 J=z6(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+J),this.renderInput()}break}}return}if(GX(Z))this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.renderInput()}onResize(){this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${o.user}${C.bold} You${C.reset} ${C.dim}${Z}${C.reset}`});else this.lines.push({text:`${o.ai}${C.bold} Claude${C.reset} ${C.dim}${Z}${C.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=X6(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=n0($);for(let Y of Z)this.lines.push({text:Y})}}function V6($){return[...$].length===1}function GX($){if(!V6($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function K6($,Z){if(Z<=0)return 0;if(Z>=2){let Y=$.charCodeAt(Z-1),J=$.charCodeAt(Z-2);if(Y>=56320&&Y<=57343&&J>=55296&&J<=56319)return 2}return 1}function z6($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}var a4={"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}},WX={input:3,output:15};function G6($,Z){let Y=HX(Z),J=$.inputTokens/1e6*Y.input*100,Q=$.outputTokens/1e6*Y.output*100;return{inputCostCents:J,outputCostCents:Q,totalCostCents:J+Q}}function HX($){if(a4[$])return a4[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return a4["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return a4["claude-opus-4-20250514"];if(Z.includes("sonnet"))return a4["claude-sonnet-4-20250514"];return WX}class k7{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=G6($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=G6($,this.model);return`${i0($.inputTokens)} in / ${i0($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${i0(this.totalInput)} in / ${i0(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function i0($){return $.toLocaleString("en-US")}function W6($,Z={}){let{includeToolCalls:Y=!0,includeTimestamps:J=!0}=Z,Q=[];Q.push(`# smolerclaw session: ${$.name}`),Q.push(`Created: ${new Date($.created).toLocaleString()}`),Q.push(""),Q.push("---"),Q.push("");for(let X of $.messages){let K=J?` (${new Date(X.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(X.role==="user")Q.push(`## You${K}`),Q.push(""),Q.push(X.content),Q.push("");else{if(Q.push(`## Claude${K}`),Q.push(""),Q.push(X.content),Y&&X.toolCalls?.length){Q.push("");for(let V of X.toolCalls){let G=qX(V.name,V.input);Q.push(`> **Tool:** \`${V.name}\`${G}`);let H=V.result.split(`
225
354
  `).slice(0,5).join(`
226
- `);if(q.trim()){X.push("> ```");for(let K of q.split(`
227
- `))X.push(`> ${K}`);X.push("> ```")}}}if(z.usage)X.push(""),X.push(`*Tokens: ${z.usage.inputTokens} in / ${z.usage.outputTokens} out (~$${(z.usage.costCents/100).toFixed(4)})*`);X.push("")}X.push("---"),X.push("")}return X.join(`
228
- `)}function JY($,Z){switch($){case"read_file":case"write_file":case"edit_file":return Z.path?` \`${Z.path}\``:"";case"search_files":return Z.pattern?` \`/${Z.pattern}/\``:"";case"find_files":return Z.pattern?` \`${Z.pattern}\``:"";case"run_command":return Z.command?` \`${Z.command}\``:"";default:return""}}var S4=[{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 J7($){let Z=S4.find((z)=>z.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),J=S4.find((z)=>z.alias===Y);if(J)return J.id;let X=S4.find((z)=>z.id.includes(Y)||z.name.toLowerCase().includes(Y));if(X)return X.id;return $}function zZ($){let Z=["Available models:"];for(let Y of S4){let J=Y.id===$?" *":" ",X=Y.tier==="fast"?"\u26A1":Y.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${J} ${Y.alias.padEnd(12)} ${X} ${Y.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
229
- `)}function X7($){if($.includes(":")){let[Y,...J]=$.split(":");return{provider:Y.toLowerCase(),model:J.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 XY={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 QZ(){let $=["Providers:"];for(let[Z,Y]of Object.entries(XY)){let J=Y.envKey?` (${Y.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${Y.description}${J}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
230
- `)}class z7{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 J=[{role:"system",content:Z},...$.map((X)=>({role:X.role,content:X.content}))];try{let X=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:J,max_tokens:this.maxTokens,stream:!0})});if(!X.ok){let K=await X.text();yield{type:"error",error:`${this.name} API error ${X.status}: ${K.slice(0,200)}`};return}if(!X.body){yield{type:"error",error:"No response body"};return}let z=X.body.getReader(),Q=new TextDecoder,V="",G=Z.length+$.reduce((K,O)=>K+O.content.length,0),q=0;while(!0){let{done:K,value:O}=await z.read();if(K)break;V+=Q.decode(O,{stream:!0});let N=V.split(`
231
- `);V=N.pop()||"";for(let M of N){if(!M.startsWith("data: "))continue;let D=M.slice(6).trim();if(D==="[DONE]")continue;try{let i=JSON.parse(D).choices?.[0]?.delta;if(i?.content)yield{type:"text",text:i.content},q+=i.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(G/3.5),outputTokens:Math.ceil(q/3.5)},yield{type:"done"}}catch(X){yield{type:"error",error:X instanceof Error?X.message:String(X)}}}}async function l2(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[Y,J]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),X=await Z.exited;return{stdout:Y.trim(),stderr:J.trim(),ok:X===0}}async function KZ(){let $=await l2("git","diff","--cached"),Z=await l2("git","diff"),Y=await l2("git","ls-files","--others","--exclude-standard"),J=[];if($.stdout)J.push(`=== STAGED ===
355
+ `);if(H.trim()){Q.push("> ```");for(let z of H.split(`
356
+ `))Q.push(`> ${z}`);Q.push("> ```")}}}if(X.usage)Q.push(""),Q.push(`*Tokens: ${X.usage.inputTokens} in / ${X.usage.outputTokens} out (~$${(X.usage.costCents/100).toFixed(4)})*`);Q.push("")}Q.push("---"),Q.push("")}return Q.join(`
357
+ `)}function qX($,Z){switch($){case"read_file":case"write_file":case"edit_file":return Z.path?` \`${Z.path}\``:"";case"search_files":return Z.pattern?` \`/${Z.pattern}/\``:"";case"find_files":return Z.pattern?` \`${Z.pattern}\``:"";case"run_command":return Z.command?` \`${Z.command}\``:"";default:return""}}var o0=[{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 y7($){let Z=o0.find((X)=>X.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),J=o0.find((X)=>X.alias===Y);if(J)return J.id;let Q=o0.find((X)=>X.id.includes(Y)||X.name.toLowerCase().includes(Y));if(Q)return Q.id;return $}function H6($){let Z=["Available models:"];for(let Y of o0){let J=Y.id===$?" *":" ",Q=Y.tier==="fast"?"\u26A1":Y.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${J} ${Y.alias.padEnd(12)} ${Q} ${Y.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
358
+ `)}function _7($){if($.includes(":")){let[Y,...J]=$.split(":");return{provider:Y.toLowerCase(),model:J.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 UX={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 q6(){let $=["Providers:"];for(let[Z,Y]of Object.entries(UX)){let J=Y.envKey?` (${Y.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${Y.description}${J}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
359
+ `)}class h7{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 J=[{role:"system",content:Z},...$.map((Q)=>({role:Q.role,content:Q.content}))];try{let Q=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:J,max_tokens:this.maxTokens,stream:!0})});if(!Q.ok){let z=await Q.text();yield{type:"error",error:`${this.name} API error ${Q.status}: ${z.slice(0,200)}`};return}if(!Q.body){yield{type:"error",error:"No response body"};return}let X=Q.body.getReader(),K=new TextDecoder,V="",G=Z.length+$.reduce((z,M)=>z+M.content.length,0),H=0;while(!0){let{done:z,value:M}=await X.read();if(z)break;V+=K.decode(M,{stream:!0});let N=V.split(`
360
+ `);V=N.pop()||"";for(let E of N){if(!E.startsWith("data: "))continue;let j=E.slice(6).trim();if(j==="[DONE]")continue;try{let m=JSON.parse(j).choices?.[0]?.delta;if(m?.content)yield{type:"text",text:m.content},H+=m.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(G/3.5),outputTokens:Math.ceil(H/3.5)},yield{type:"done"}}catch(Q){yield{type:"error",error:Q instanceof Error?Q.message:String(Q)}}}}async function C1(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[Y,J]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),Q=await Z.exited;return{stdout:Y.trim(),stderr:J.trim(),ok:Q===0}}async function U6(){let $=await C1("git","diff","--cached"),Z=await C1("git","diff"),Y=await C1("git","ls-files","--others","--exclude-standard"),J=[];if($.stdout)J.push(`=== STAGED ===
232
361
  `+$.stdout);if(Z.stdout)J.push(`=== UNSTAGED ===
233
362
  `+Z.stdout);if(Y.stdout)J.push(`=== UNTRACKED ===
234
363
  `+Y.stdout);return J.join(`
235
364
 
236
- `)||"(no changes)"}async function VZ(){let $=await l2("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function GZ(){return(await l2("git","add","-A")).ok}async function WZ($){let Z=await l2("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function qZ(){let $=await l2("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var HZ={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.
365
+ `)||"(no changes)"}async function B6(){let $=await C1("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function N6(){return(await C1("git","add","-A")).ok}async function C6($){let Z=await C1("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function M6(){let $=await C1("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var O6={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.
237
366
 
238
367
  Behavior:
239
368
  - Write clean, production-grade code. No shortcuts.
@@ -264,73 +393,80 @@ Behavior:
264
393
  - Be specific. Show the line, explain the problem, suggest the fix.
265
394
  - Check for: error handling, input validation, edge cases, naming, complexity.
266
395
  - Don't nitpick formatting unless it affects readability.
267
- - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function UZ($){return HZ[$.toLowerCase()]||null}function BZ($){let Z=["Personas:"];for(let[Y,J]of Object.entries(HZ)){let X=Y===$?" *":" ";Z.push(`${X} ${Y.padEnd(12)} ${J.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
268
- `)}async function NZ($){try{let Z=x?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:B7?["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}}import{existsSync as zY,readFileSync as QY,statSync as KY}from"fs";import{extname as VY,resolve as GY}from"path";var WY=new Set([".png",".jpg",".jpeg",".gif",".webp"]),qY=20971520;function CZ($){let Z=[],Y=$.split(/\s+/),J=[];for(let X of Y){let z=X.replace(/^["']|["']$/g,""),Q=VY(z).toLowerCase();if(WY.has(Q)){let V=GY(z);if(zY(V))try{if(KY(V).size>qY){J.push(`[image too large: ${z}]`);continue}let K=QY(V).toString("base64"),O=HY(Q);Z.push({path:V,mediaType:O,base64:K}),J.push(`[image: ${z}]`)}catch{J.push(X)}else J.push(X)}else J.push(X)}return{text:J.join(" "),images:Z}}function HY($){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"}}async function jZ(){let $=[];$.push("=== BRIEFING DIARIO ===");let Z=await z$();if($.push(Z),x)try{let Y=await A2();$.push(`
396
+ - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function E6($){return O6[$.toLowerCase()]||null}function L6($){let Z=["Personas:"];for(let[Y,J]of Object.entries(O6)){let Q=Y===$?" *":" ";Z.push(`${Q} ${Y.padEnd(12)} ${J.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
397
+ `)}async function j6($){try{let Z=A?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:o7?["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}}import{existsSync as BX,readFileSync as NX,statSync as CX}from"fs";import{extname as MX,resolve as OX}from"path";var EX=new Set([".png",".jpg",".jpeg",".gif",".webp"]),LX=20971520;function F6($){let Z=[],Y=$.split(/\s+/),J=[];for(let Q of Y){let X=Q.replace(/^["']|["']$/g,""),K=MX(X).toLowerCase();if(EX.has(K)){let V=OX(X);if(BX(V))try{if(CX(V).size>LX){J.push(`[image too large: ${X}]`);continue}let z=NX(V).toString("base64"),M=jX(K);Z.push({path:V,mediaType:M,base64:z}),J.push(`[image: ${X}]`)}catch{J.push(Q)}else J.push(Q)}else J.push(Q)}return{text:J.join(" "),images:Z}}function jX($){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"}}async function R6(){let $=[];$.push("=== BRIEFING DIARIO ===");let Z=await k1();if($.push(Z),A)try{let Y=await l$();$.push(`
269
398
  --- Agenda ---
270
399
  ${Y}`)}catch{$.push(`
271
400
  --- Agenda ---
272
- Outlook nao disponivel.`)}if(x)try{let Y=await X$();$.push(`
401
+ Outlook nao disponivel.`)}if(A)try{let Y=await b1();$.push(`
273
402
  --- Sistema ---
274
- ${Y}`)}catch{}try{let Y=await w2(["finance","business","tech"],3);$.push(`
403
+ ${Y}`)}catch{}try{let Y=await n$(["finance","business","tech"],3);$.push(`
275
404
  ${Y}`)}catch{$.push(`
276
405
  --- Noticias ---
277
406
  Falha ao carregar noticias.`)}return $.push(`
278
407
  ======================`),$.join(`
279
- `)}import{existsSync as UY,readFileSync as BY,writeFileSync as NY}from"fs";import{join as CY}from"path";var OZ="",FZ=()=>CY(OZ,"last-morning.txt");function EZ($){OZ=$;let Z=FZ(),Y=new Date().toISOString().split("T")[0];if(!UY(Z))return!0;try{return BY(Z,"utf-8").trim()!==Y}catch{return!0}}function MZ(){let $=new Date().toISOString().split("T")[0];NY(FZ(),$)}async function LZ(){let $=[];$.push("=============================="),$.push(" BOM DIA! Briefing do dia"),$.push(`==============================
280
- `);let Z=await z$();$.push(Z);let J=P2().filter((G)=>{if(!G.dueAt)return!1;let q=new Date(G.dueAt),K=new Date;return q.toDateString()===K.toDateString()});if(J.length>0)$.push(`
281
- --- Tarefas do dia ---`),$.push(m2(J));let X=q1();if(X.length>0)$.push(`
282
- --- Follow-ups pendentes ---`),$.push(F4(X));let Q=V$().filter((G)=>G.status==="atrasado");if(Q.length>0)$.push(`
283
- --- Delegacoes atrasadas ---`),$.push(O4(Q));if(x)try{let G=await A2();$.push(`
284
- --- Agenda ---`),$.push(G)}catch{}try{let G=await w2(["finance","business","tech"],2);$.push(`
285
- `+G)}catch{}let V=P2();if(V.length>0&&J.length!==V.length)$.push(`
286
- ${V.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
408
+ `)}import{existsSync as FX,readFileSync as RX,writeFileSync as AX}from"fs";import{join as xX}from"path";var A6="",x6=()=>xX(A6,"last-morning.txt");function D6($){A6=$;let Z=x6(),Y=new Date().toISOString().split("T")[0];if(!FX(Z))return!0;try{return RX(Z,"utf-8").trim()!==Y}catch{return!0}}function T6(){let $=new Date().toISOString().split("T")[0];AX(x6(),$)}async function P6(){let $=[];$.push("=============================="),$.push(" BOM DIA! Briefing do dia"),$.push(`==============================
409
+ `);let Z=await k1();$.push(Z);let J=i$().filter((H)=>{if(!H.dueAt)return!1;let z=new Date(H.dueAt),M=new Date;return z.toDateString()===M.toDateString()});if(J.length>0)$.push(`
410
+ --- Tarefas do dia ---`),$.push(H1(J));let Q=l4();if(Q.length>0)$.push(`
411
+ --- Follow-ups pendentes ---`),$.push(B0(Q));let K=f1().filter((H)=>H.status==="atrasado");if(K.length>0)$.push(`
412
+ --- Delegacoes atrasadas ---`),$.push(U0(K));let V=DZ();if(V)$.push(`
413
+ ${V}`);if(A)try{let H=await l$();$.push(`
414
+ --- Agenda ---`),$.push(H)}catch{}try{let H=await n$(["finance","business","tech"],2);$.push(`
415
+ `+H)}catch{}let G=i$();if(G.length>0&&J.length!==G.length)$.push(`
416
+ ${G.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
287
417
  ==============================`),$.join(`
288
- `)}var I=null,k4=null,Q7=null,K7=0;function DZ($){Q7=$}function AZ($="foco",Z=25,Y=5){if(I)return`Pomodoro ja ativo: "${I.label}" (${TZ()}). Use /pomodoro stop para parar.`;return I={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},K7++,PZ(),`Pomodoro #${K7} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function wZ(){if(!I)return"Nenhum pomodoro ativo.";let $=I.label,Z=Math.floor((Date.now()-I.startedAt)/60000);return b4(),I=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function V7(){if(!I)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=TZ();return`${I.type==="work"?"Trabalhando":"Pausa"}: "${I.label}" \u2014 ${$} restante(s) (ciclo #${K7})`}function PZ(){if(!I)return;b4();let $=I.startedAt+I.durationMs-Date.now();if($<=0){RZ();return}k4=setTimeout(RZ,$)}function RZ(){if(!I)return;if(I.type==="work"){let $=`Pomodoro: "${I.label}" concluido! Hora da pausa (${I.breakMs/60000}min).`;xZ("Pausa!",`"${I.label}" concluido. Descanse ${I.breakMs/60000} minutos.`),Q7?.($),I={...I,type:"break",startedAt:Date.now(),durationMs:I.breakMs},PZ()}else xZ("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),Q7?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),b4(),I=null}function b4(){if(k4)clearTimeout(k4),k4=null}function TZ(){if(!I)return"0min";let $=Math.max(0,I.startedAt+I.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function xZ($,Z){if(!x)return;let Y=$.replace(/'/g,"''"),J=Z.replace(/'/g,"''"),X=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Y}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Reminder"/></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("; ");try{let z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",X],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>z.kill(),1e4);await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),await z.exited,clearTimeout(Q)}catch{}}function IZ(){b4(),I=null}import{existsSync as kZ,mkdirSync as jY,readFileSync as OY,writeFileSync as FY}from"fs";import{join as EY}from"path";var bZ="",Y2=[],yZ=()=>EY(bZ,"workflows.json");function G7(){FY(yZ(),JSON.stringify(Y2,null,2))}function MY(){let $=yZ();if(!kZ($)){Y2=SZ,G7();return}try{Y2=JSON.parse(OY($,"utf-8"))}catch{Y2=SZ,G7()}}var SZ=[{name:"iniciar-dia",description:"Abrir terminal e Postman",steps:[{action:"open_app",target:"terminal"},{action:"wait",target:"2"},{action:"open_app",target:"postman"}]},{name:"dev",description:"Abrir ambiente de desenvolvimento: VSCode e Terminal",steps:[{action:"open_app",target:"vscode"},{action:"wait",target:"1"},{action:"open_app",target:"terminal"}]}];function _Z($){if(bZ=$,!kZ($))jY($,{recursive:!0});MY()}function LY($){return Y2.find((Z)=>Z.name.toLowerCase()===$.toLowerCase())||null}function fZ($){let Z=Y2.length;if(Y2=Y2.filter((Y)=>Y.name.toLowerCase()!==$.toLowerCase()),Y2.length===Z)return!1;return G7(),!0}async function W7($,Z){let Y=LY($);if(!Y){let X=Y2.map((z)=>z.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${X}`}if(!x)return"Error: workflows are only available on Windows.";let J=[`Executando workflow: "${Y.name}" \u2014 ${Y.description}`];for(let X=0;X<Y.steps.length;X++){let z=Y.steps[X];switch(z.action){case"open_app":{Z?.(`[${X+1}/${Y.steps.length}] Abrindo ${z.target}...`);let Q=await J$(z.target);J.push(` ${X+1}. ${Q}`);break}case"open_url":{Z?.(`[${X+1}/${Y.steps.length}] Abrindo ${z.target}...`);let Q=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${z.target}'`],{stdout:"pipe",stderr:"pipe"}),V=setTimeout(()=>Q.kill(),1e4);await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),await Q.exited,clearTimeout(V),J.push(` ${X+1}. Opened: ${z.target}`);break}case"run_command":{Z?.(`[${X+1}/${Y.steps.length}] Executando: ${z.target}...`);let Q=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",z.target],{stdout:"pipe",stderr:"pipe"}),V=setTimeout(()=>Q.kill(),30000),[G]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]);await Q.exited,clearTimeout(V);let q=G.trim().slice(0,100);J.push(` ${X+1}. Command: ${z.target}${q?" -> "+q:""}`);break}case"wait":{let Q=parseInt(z.target)||1;Z?.(`[${X+1}/${Y.steps.length}] Aguardando ${Q}s...`),await new Promise((V)=>setTimeout(V,Q*1000)),J.push(` ${X+1}. Wait: ${Q}s`);break}}}return J.push(`
289
- Workflow "${Y.name}" concluido.`),J.join(`
290
- `)}function hZ(){if(Y2.length===0)return"Nenhum workflow configurado.";let $=Y2.map((Z)=>{let Y=Z.steps.map((J)=>`${J.action}:${J.target}`).join(" -> ");return` ${Z.name.padEnd(15)} ${Z.description}
291
- ${" ".repeat(17)}${Y}`});return`Workflows (${Y2.length}):
292
- ${$.join(`
418
+ `)}var b=null,a0=null,f7=null,v7=0;function S6($){f7=$}function b6($="foco",Z=25,Y=5){if(b)return`Pomodoro ja ativo: "${b.label}" (${_6()}). Use /pomodoro stop para parar.`;return b={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},v7++,y6(),`Pomodoro #${v7} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function k6(){if(!b)return"Nenhum pomodoro ativo.";let $=b.label,Z=Math.floor((Date.now()-b.startedAt)/60000);return r0(),b=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function g7(){if(!b)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=_6();return`${b.type==="work"?"Trabalhando":"Pausa"}: "${b.label}" \u2014 ${$} restante(s) (ciclo #${v7})`}function y6(){if(!b)return;r0();let $=b.startedAt+b.durationMs-Date.now();if($<=0){w6();return}a0=setTimeout(w6,$)}function w6(){if(!b)return;if(b.type==="work"){let $=`Pomodoro: "${b.label}" concluido! Hora da pausa (${b.breakMs/60000}min).`;I6("Pausa!",`"${b.label}" concluido. Descanse ${b.breakMs/60000} minutos.`),f7?.($),b={...b,type:"break",startedAt:Date.now(),durationMs:b.breakMs},y6()}else I6("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),f7?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),r0(),b=null}function r0(){if(a0)clearTimeout(a0),a0=null}function _6(){if(!b)return"0min";let $=Math.max(0,b.startedAt+b.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function I6($,Z){if(!A)return;let Y=$.replace(/'/g,"''"),J=Z.replace(/'/g,"''"),Q=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Y}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Reminder"/></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("; ");try{let X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Q],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),1e4);await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),await X.exited,clearTimeout(K)}catch{}}function h6(){r0(),b=null}r();import{existsSync as f6,mkdirSync as DX,readFileSync as TX}from"fs";import{join as PX}from"path";import{randomUUID as wX}from"crypto";var v6="",e=[],g6=()=>PX(v6,"workflows.json");function r4(){D(g6(),JSON.stringify(e,null,2))}function IX(){let $=g6();if(!f6($)){e=m7(),r4();return}try{let Z=JSON.parse(TX($,"utf-8"));if(!Array.isArray(Z)){e=m7(),r4();return}e=Z.map((Y)=>({id:Y.id||c7(),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{e=m7(),r4()}}function m7(){let $=new Date().toISOString();return[{id:c7(),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:c7(),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 m6($){if(v6=$,!f6($))DX($,{recursive:!0});IX()}function s4($){let Z=$.toLowerCase().trim();return e.find((Y)=>Y.id===$)||e.find((Y)=>Y.name.toLowerCase()===Z)||e.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function c6($){let Z=[...e];if($){let Y=$.toLowerCase();Z=Z.filter((J)=>J.tags.some((Q)=>Q.toLowerCase()===Y))}return Z}function d7($,Z){let Y=s4($);if(!Y)return null;return e=e.map((J)=>J.id===Y.id?{...J,...Z,updatedAt:new Date().toISOString()}:J),r4(),e.find((J)=>J.id===Y.id)||null}function d6($){let Z=s4($);if(!Z)return!1;return e=e.filter((Y)=>Y.id!==Z.id),r4(),!0}async function u7($,Z){let Y=s4($);if(!Y){let Q=e.map((X)=>X.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${Q}`}if(!Y.enabled)return`Workflow "${Y.name}" esta desativado.`;let J=await u6(Y.name,Y.steps,Z);return bX(J)}async function u6($,Z,Y){let J=performance.now(),Q=[`Executando workflow: "${$}"`],X=0,K=0,V=0,G=!0;for(let H=0;H<Z.length;H++){let z=Z[H],M=z.label||`${z.action}:${z.target}`,N=`[${H+1}/${Z.length}]`,E=z.on_error||"continue";Y?.(`${N} ${M}...`);try{let j=await SX(z,Y);Q.push(` ${N} ${j}`),X++}catch(j){let T=j instanceof Error?j.message:String(j);switch(V++,E){case"stop":return Q.push(` ${N} ERRO (parando): ${T}`),G=!1,{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:Q,duration:Math.round(performance.now()-J)};case"skip":Q.push(` ${N} ERRO (pulado): ${T}`),K++;break;case"continue":default:Q.push(` ${N} ERRO (continuando): ${T}`);break}}}return{workflow:$,success:G,stepsRun:X,stepsSkipped:K,stepsFailed:V,log:Q,duration:Math.round(performance.now()-J)}}async function SX($,Z){switch($.action){case"open_app":{if(!A)return`skip: ${$.target} (not Windows)`;return await I1($.target)}case"open_url":{if(!A)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 S1(Y)}case"run_command":{if(!A)return"skip: command (not Windows)";let Y=$.target;if(!Y.trim())throw Error("Comando vazio");let J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Y],{stdout:"pipe",stderr:"pipe"}),Q=new Promise((V,G)=>{setTimeout(()=>{J.kill(),G(Error("Command timeout (30s)"))},30000)}),X=(async()=>{let[V,G]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),H=await J.exited;if(H!==0&&G.trim())throw Error(`exit ${H}: ${G.trim().slice(0,200)}`);return V.trim().slice(0,200)})(),K=await Promise.race([X,Q]);return`Command: ${Y.slice(0,60)}${K?" -> "+K:""}`}case"wait":{let Y=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((J)=>setTimeout(J,Y*1000)),`Wait: ${Y}s`}case"notify":{if(A)try{let Y=$.target.replace(/'/g,"''"),J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",`[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null; [System.Windows.Forms.MessageBox]::Show('${Y}', 'smolerclaw', 'OK', 'Information') | Out-Null`],{stdout:"pipe",stderr:"pipe"});setTimeout(()=>J.kill(),1e4)}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!A)return"skip: condition (not Windows)";let Y=$.target.toLowerCase(),J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",`(Get-Process -Name '${Y}' -ErrorAction SilentlyContinue) -ne $null`],{stdout:"pipe",stderr:"pipe"}),Q=new Promise((V,G)=>{setTimeout(()=>{J.kill(),G(Error("condition timeout"))},5000)}),X=(async()=>{let[V]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]);return await J.exited,V.trim().toLowerCase()==="true"})(),K=await Promise.race([X,Q]);if(K&&$.condition_steps&&$.condition_steps.length>0){let V=await u6(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${Y} running=true, ran ${V.stepsRun} sub-steps`}return`Condition: ${Y} running=${K}${!K?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function p6($){let Z=$||e;if(Z.length===0)return"Nenhum workflow configurado.";let Y=Z.map((J)=>{let Q=J.enabled?"":" [DESATIVADO]",X=J.tags.length>0?` [${J.tags.join(", ")}]`:"",K=J.steps.map((V)=>{let G=V.label||V.target;return V.action==="wait"?`${V.target}s`:G}).join(" -> ");return` ${J.name}${Q}${X} \u2014 ${J.description}
419
+ ${" ".repeat(4)}${K} {${J.id}}`});return`Workflows (${Z.length}):
420
+ ${Y.join(`
293
421
 
294
- `)}`}var V2=new Map,q7=null;function gZ($){q7=$}function cZ($,Z=60){if(!x)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(V2.has(Y))return`"${$}" ja esta sendo monitorado.`;let J=setInterval(()=>vZ(Y),Z*1000);return V2.set(Y,{name:$,interval:J,lastSeen:!0}),vZ(Y),`Monitorando "${$}" a cada ${Z}s.`}function dZ($){let Z=$.toLowerCase(),Y=V2.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),V2.delete(Z),`Monitor parado: "${$}"`}function mZ(){if(V2.size===0)return"Nenhum processo monitorado.";let $=[...V2.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${V2.size}):
422
+ `)}`}function l6($){let Z=$.enabled?"ativo":"desativado",Y=$.tags.length>0?`Tags: ${$.tags.map((Q)=>`#${Q}`).join(" ")}`:"",J=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(Y)J.push(Y);return J.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),J.push(""),J.push("Steps:"),$.steps.forEach((Q,X)=>{let K=Q.label?` (${Q.label})`:"",V=Q.on_error&&Q.on_error!=="continue"?` [on_error: ${Q.on_error}]`:"";if(J.push(` ${X+1}. ${Q.action}: ${Q.target}${K}${V}`),Q.action==="if_app_running"&&Q.condition_steps)for(let G of Q.condition_steps)J.push(` \u21B3 ${G.action}: ${G.target}`)}),J.join(`
423
+ `)}function bX($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
424
+ `)}function c7(){return wX().slice(0,8)}var E$=new Map,p7=null;function i6($){p7=$}function o6($,Z=60){if(!A)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(E$.has(Y))return`"${$}" ja esta sendo monitorado.`;let J=setInterval(()=>n6(Y),Z*1000);return E$.set(Y,{name:$,interval:J,lastSeen:!0}),n6(Y),`Monitorando "${$}" a cada ${Z}s.`}function a6($){let Z=$.toLowerCase(),Y=E$.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),E$.delete(Z),`Monitor parado: "${$}"`}function r6(){if(E$.size===0)return"Nenhum processo monitorado.";let $=[...E$.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${E$.size}):
295
425
  ${$.join(`
296
- `)}`}function uZ(){for(let $ of V2.values())clearInterval($.interval);V2.clear()}async function vZ($){let Z=V2.get($);if(!Z)return;let Y=await RY(Z.name);if(Z.lastSeen&&!Y){let J=`ALERTA: "${Z.name}" parou de rodar!`;xY("Processo parou!",`"${Z.name}" nao esta mais rodando.`),q7?.(J)}else if(!Z.lastSeen&&Y){let J=`"${Z.name}" voltou a rodar.`;q7?.(J)}V2.set($,{...Z,lastSeen:Y})}async function RY($){if(!x)return!1;try{let Z=`(Get-Process -Name '${$}' -ErrorAction SilentlyContinue) -ne $null`,Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),J=setTimeout(()=>Y.kill(),1e4),[X]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]);return await Y.exited,clearTimeout(J),X.trim().toLowerCase()==="true"}catch{return!1}}async function xY($,Z){if(!x)return;let Y=$.replace(/'/g,"''"),J=Z.replace(/'/g,"''"),X=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Y}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("smolerclaw").Show($toast)'].join("; ");try{let z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",X],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>z.kill(),1e4);await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),await z.exited,clearTimeout(Q)}catch{}}W1();import{writeFileSync as DY}from"fs";import{join as AY}from"path";async function wY(){let $=H7(process.argv.slice(2));if($.help)U7(),process.exit(0);if($.version)console.log(`smolerclaw v${j1()}`),process.exit(0);let Z=O7();if($.model)Z.model=J7($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=h4()}catch(D){console.error("smolerclaw:",D instanceof Error?D.message:D),process.exit(1)}let{provider:J,model:X}=X7(Z.model),z;if(J==="openai"||J==="ollama")z=new z7(J,X,Z.maxTokens);else{let D=new i6(Y.token,Z.model,Z.maxTokens,Z.toolApproval);D.setAuthRefresh(()=>{let v=M7();if(v&&v.token!==Y.token)return Y=v,D.updateApiKey(v.token),!0;return!1}),z=D}let Q=$.session||"default",V=new a6(Z.dataDir);if($.session)V.switchTo($.session);let G=s0(Z.skillsDir),q=t6(Z.systemPrompt,G,Z.language),K=!$.noTools;T0();let O=R8(AY(Z.dataDir,"..")),N=F8(O);if(N.length>0)A0(N),r.push(...E8(N));let M=!process.stdin.isTTY;if($.print||M)await PY(z,V,q,K,$.prompt,M),process.exit(0);await IY(z,V,Z,Y,G,q,K,N,$.prompt)}async function PY($,Z,Y,J,X,z){let Q=X||"";if(z){let K=await TY();Q=Q?`${Q}
426
+ `)}`}function s6(){for(let $ of E$.values())clearInterval($.interval);E$.clear()}async function n6($){let Z=E$.get($);if(!Z)return;let Y=await kX(Z.name);if(Z.lastSeen&&!Y){let J=`ALERTA: "${Z.name}" parou de rodar!`;yX("Processo parou!",`"${Z.name}" nao esta mais rodando.`),p7?.(J)}else if(!Z.lastSeen&&Y){let J=`"${Z.name}" voltou a rodar.`;p7?.(J)}E$.set($,{...Z,lastSeen:Y})}async function kX($){if(!A)return!1;try{let Z=`(Get-Process -Name '${$}' -ErrorAction SilentlyContinue) -ne $null`,Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),J=setTimeout(()=>Y.kill(),1e4),[Q]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]);return await Y.exited,clearTimeout(J),Q.trim().toLowerCase()==="true"}catch{return!1}}async function yX($,Z){if(!A)return;let Y=$.replace(/'/g,"''"),J=Z.replace(/'/g,"''"),Q=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Y}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("smolerclaw").Show($toast)'].join("; ");try{let X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Q],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>X.kill(),1e4);await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),await X.exited,clearTimeout(K)}catch{}}p4();r();import{writeFileSync as _X}from"fs";import{join as hX}from"path";async function fX(){let $=n7(process.argv.slice(2));if($.help)i7(),process.exit(0);if($.version)console.log(`smolerclaw v${$8()}`),process.exit(0);let Z=V5();if($.model)Z.model=y7($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=X2()}catch(j){console.error("smolerclaw:",j instanceof Error?j.message:j),process.exit(1)}let{provider:J,model:Q}=_7(Z.model),X;if(J==="openai"||J==="ollama")X=new h7(J,Q,Z.maxTokens);else{let j=new R7(Y.token,Z.model,Z.maxTokens,Z.toolApproval);j.setAuthRefresh(()=>{let T=K2();if(T&&T.token!==Y.token)return Y=T,j.updateApiKey(T.token),!0;return!1}),X=j}let K=$.session||"default",V=new D7(Z.dataDir);if($.session)V.switchTo($.session);let G=J6(Z.skillsDir),H=w7(Z.systemPrompt,G,Z.language),z=!$.noTools;fZ();let M=H9(hX(Z.dataDir,"..")),N=z9(M);if(N.length>0)yZ(N),u.push(...V9(N));let E=!process.stdin.isTTY;if($.print||E)await vX(X,V,H,z,$.prompt,E),process.exit(0);await mX(X,V,Z,Y,G,H,z,N,$.prompt)}async function vX($,Z,Y,J,Q,X){let K=Q||"";if(X){let z=await gX();K=K?`${K}
297
427
 
298
- ${K}`:K}if(!Q.trim())console.error("smolerclaw: no input provided"),process.exit(1);let V={role:"user",content:Q.trim(),timestamp:Date.now()};Z.addMessage(V);let G="";for await(let K of $.chat(Z.messages,Y,J))if(K.type==="text")process.stdout.write(K.text),G+=K.text;else if(K.type==="error")console.error(`
299
- smolerclaw error: ${K.error}`);if(G&&!G.endsWith(`
428
+ ${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,Y,J))if(z.type==="text")process.stdout.write(z.text),G+=z.text;else if(z.type==="error")console.error(`
429
+ smolerclaw error: ${z.error}`);if(G&&!G.endsWith(`
300
430
  `))process.stdout.write(`
301
- `);let q={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(q)}async function TY(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}async function IY($,Z,Y,J,X,z,Q,V,G){let q=new Y7(Y.model),K=new Z7(Y.model,Z.session.name,L7(J),Y.dataDir),O="default",N=j0(),M=N?`${z}
302
-
303
- ${N}`:z;if(Q0(Y.dataDir),g8(Y.dataDir),U0(Y.dataDir),P0(Z),i8(Y.dataDir),r8(Y.dataDir),DZ((k)=>K.showSystem(`
304
- *** ${k} ***
305
- `)),_Z(Y.dataDir),x6(Y.dataDir),gZ((k)=>K.showSystem(`
306
- *** ${k} ***
307
- `)),S8(Y.dataDir,(k)=>{K.showSystem(`
308
- *** LEMBRETE: ${k.title} ***
309
- `)}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(k,o,z2)=>{if(k==="edit_file"&&o.old_text&&o.new_text){let U=d0(String(o.old_text),String(o.new_text));for(let C of U)K.showSystem(C)}let F=c0(k,o),W=await K.promptApproval(F);if(K._approveAllRequested)$.setAutoApproveAll?.(!0),K._approveAllRequested=!1;return W});for(let k of Z.messages)if(k.role==="user")K.addUserMessage(k.content);else K.addAssistantMessage(k.content);let D=null;async function v(k){if(k.startsWith("/")){await i(k);return}if(Y.maxSessionCost>0){let T=q.totals.costCents;if(T>=Y.maxSessionCost){K.showError(`Budget exceeded (~$${(T/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(T>=Y.maxSessionCost*0.8)K.showSystem(`Budget: ${Math.round(T/Y.maxSessionCost*100)}% used`)}let{text:o,images:z2}=CZ(k),F={role:"user",content:o,images:z2.length>0?z2.map((T)=>({mediaType:T.mediaType,base64:T.base64})):void 0,timestamp:Date.now()};Z.addMessage(F),K.addUserMessage(z2.length>0?`${o} (${z2.length} image${z2.length>1?"s":""})`:o),K.disableInput(),K.startStream();let W="",U=[],C={},L=0,w=0;D=new AbortController;try{for await(let T of $.chat(Z.messages,M,Q)){if(D.signal.aborted)break;switch(T.type){case"text":K.appendStream(T.text),W+=T.text;break;case"tool_call":K.flushStream(),K.showToolCall(T.name,T.input),C=T.input;break;case"tool_result":K.showToolResult(T.name,T.result),U.push({id:T.id,name:T.name,input:C,result:T.result}),C={},K.resetStreamBuffer();break;case"tool_blocked":K.showError(T.reason);break;case"usage":L+=T.inputTokens,w+=T.outputTokens;break;case"error":K.showError(T.error);break;case"done":break}}}catch(T){if(!D.signal.aborted)K.showError(T instanceof Error?T.message:String(T))}D=null,K.endStream();let _={inputTokens:L,outputTokens:w},u=q.add(_);if(L>0||w>0)K.showUsage(q.formatUsage(_)),K.updateSessionCost(`~$${(q.totals.costCents/100).toFixed(4)}`);let y2={role:"assistant",content:W,toolCalls:U.length>0?U:void 0,usage:L>0?{inputTokens:L,outputTokens:w,costCents:u.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(y2),Z.trimHistory(Y.maxHistory),K.enableInput()}async function i(k){let o=k.slice(1).split(" "),z2=o[0].toLowerCase(),F=o.slice(1);switch(z2){case"exit":case"quit":case"sair":case"q":n();break;case"clear":case"limpar":Z.clear(),K.clearMessages(),K.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let W=F[0]||`s-${Date.now()}`;Z.switchTo(W),K.clearMessages(),K.updateSession(W),K.showSystem(`New session: ${W}`);break}case"load":case"carregar":{let W=F[0];if(!W){K.showError("Usage: /load <name>");break}Z.switchTo(W),K.clearMessages();for(let U of Z.messages)if(U.role==="user")K.addUserMessage(U.content);else K.addAssistantMessage(U.content);K.updateSession(W),K.showSystem(`Loaded: ${W}`);break}case"sessions":case"sessoes":case"ls":{let W=Z.list();if(W.length===0){K.showSystem("No saved sessions.");break}let U=W.map((C)=>{let L=Z.getInfo(C),w=C===Z.session.name?" *":" ",_=L?pZ(L.updated):"",u=L?`${L.messageCount} msgs`:"";return`${w} ${C.padEnd(20)} ${u.padEnd(10)} ${_}`});K.showSystem(`Sessions:
310
- `+U.join(`
311
- `));break}case"delete":case"deletar":case"rm":{let W=F[0];if(!W){K.showError("Usage: /delete <name>");break}if(Z.delete(W))K.showSystem(`Deleted: ${W}`);else K.showError(`Session not found: ${W}`);break}case"archive":case"arquivar":{let W=F[0];if(!W){K.showError("Uso: /archive <nome> ou /archive all");break}if(W==="all"||W==="todas"){let U=Z.archiveAll();if(U.length>0)K.showSystem(`Arquivadas ${U.length} sessoes: ${U.join(", ")}`);else K.showSystem("Nenhuma sessao para arquivar (apenas a sessao atual esta ativa).")}else if(Z.archive(W))K.showSystem(`Sessao arquivada: "${W}"`);else K.showError(`Falha ao arquivar "${W}" (nao encontrada ou e a sessao atual).`);break}case"unarchive":case"desarquivar":case"restore":case"restaurar":{let W=F[0];if(!W){K.showError("Uso: /unarchive <nome>");break}if(Z.unarchive(W))K.showSystem(`Sessao restaurada: "${W}"`);else K.showError(`Sessao arquivada nao encontrada: "${W}"`);break}case"archived":case"arquivadas":{let W=Z.listArchived();if(W.length===0){K.showSystem("Nenhuma sessao arquivada.");break}let U=W.map((C)=>{let L=Z.getArchivedInfo(C),w=L?pZ(L.updated):"",_=L?`${L.messageCount} msgs`:"";return` ${C.padEnd(20)} ${_.padEnd(10)} ${w}`});K.showSystem(`Sessoes arquivadas (${W.length}):
312
- ${U.join(`
313
- `)}`);break}case"model":case"modelo":{let W=F[0];if(!W){K.showSystem(zZ(Y.model)+`
314
-
315
- `+QZ());break}let{provider:U,model:C}=X7(W),L=U==="anthropic"?J7(C):C;if(Y.model=U==="anthropic"?L:`${U}:${L}`,R1(Y),U==="anthropic")$.setModel(L);else K.showSystem(`Note: ${U} provider selected. Restart smolerclaw for full provider switch.`);q.setModel(L),K.updateModel(Y.model),K.showSystem(`Model -> ${Y.model}`);break}case"skills":case"habilidades":{K.showSystem(t0(X));break}case"auth":K.showSystem(`Auth: subscription (${J.subscriptionType})
316
- Expires: ${new Date(J.expiresAt).toLocaleString()}`);break;case"config":K.showSystem(`Config: ${F7()}`);break;case"export":case"exportar":{let W=new Date().toISOString().split("T")[0],U=F[0]||`smolerclaw-${Z.session.name}-${W}.md`;try{let C=XZ(Z.session);DY(U,C),K.showSystem(`Exported to: ${U}`)}catch(C){K.showError(`Export failed: ${C instanceof Error?C.message:C}`)}break}case"cost":case"custo":K.showSystem(`Session: ${q.formatSession()}`);break;case"retry":case"repetir":{let W=[...Z.messages].reverse().find((w)=>w.role==="user");if(!W){K.showError("No previous message to retry.");break}let U=Z.messages,C=0;if(U.length>0&&U[U.length-1].role==="assistant")C++;if(U.length>C&&U[U.length-1-C].role==="user")C++;if(C>0)Z.popMessages(C);K.showSystem("Retrying...");let L=W.images?.length?W.content:W.content;await v(L);break}case"help":case"ajuda":case"?":K.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","","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(`
317
- `));break;case"commit":case"commitar":{if(!await qZ()){K.showError("Not a git repository.");break}let W=await VZ();if(W==="(clean)"){K.showSystem("Nothing to commit \u2014 working tree clean.");break}K.showSystem(`Changes:
318
- `+W),K.disableInput();try{let C=`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.
431
+ `);let H={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(H)}async function gX(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}async function mX($,Z,Y,J,Q,X,K,V,G){let H=new k7(Y.model),z=new b7(Y.model,Z.session.name,W5(J),Y.dataDir),M="default",N=GZ(),E=N?`${X}
432
+
433
+ ${N}`:X;if(Q5(Y.dataDir,Q2().replace(/[/\\]config\.json$/,"")),t9(Y.dataDir),I9(Y.dataDir),XZ(Y.dataDir),C9(Y.dataDir),hZ(Z),f9(Y.dataDir),c9(Y.dataDir),S6((y)=>z.showSystem(`
434
+ *** ${y} ***
435
+ `)),m6(Y.dataDir),o2(Y.dataDir),NZ(Y.dataDir),RZ(Y.dataDir),i6((y)=>z.showSystem(`
436
+ *** ${y} ***
437
+ `)),j9(Y.dataDir,(y)=>{z.showSystem(`
438
+ *** LEMBRETE: ${y.title} ***
439
+ `)}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(y,$$,C$)=>{if(y==="edit_file"&&$$.old_text&&$$.new_text){let q=oZ(String($$.old_text),String($$.new_text));for(let B of q)z.showSystem(B)}let O=iZ(y,$$),W=await z.promptApproval(O);if(z._approveAllRequested)$.setAutoApproveAll?.(!0),z._approveAllRequested=!1;return W});for(let y of Z.messages)if(y.role==="user")z.addUserMessage(y.content);else z.addAssistantMessage(y.content);let j=null;async function T(y){if(y.startsWith("/")){await m(y);return}if(Y.maxSessionCost>0){let S=H.totals.costCents;if(S>=Y.maxSessionCost){z.showError(`Budget exceeded (~$${(S/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(S>=Y.maxSessionCost*0.8)z.showSystem(`Budget: ${Math.round(S/Y.maxSessionCost*100)}% used`)}let{text:$$,images:C$}=F6(y),O={role:"user",content:$$,images:C$.length>0?C$.map((S)=>({mediaType:S.mediaType,base64:S.base64})):void 0,timestamp:Date.now()};Z.addMessage(O),z.addUserMessage(C$.length>0?`${$$} (${C$.length} image${C$.length>1?"s":""})`:$$),z.disableInput(),z.startStream();let W="",q=[],B={},F=0,w=0;j=new AbortController;try{for await(let S of $.chat(Z.messages,E,K)){if(j.signal.aborted)break;switch(S.type){case"text":z.appendStream(S.text),W+=S.text;break;case"tool_call":z.flushStream(),z.showToolCall(S.name,S.input),B=S.input;break;case"tool_result":z.showToolResult(S.name,S.result),q.push({id:S.id,name:S.name,input:B,result:S.result}),B={},z.resetStreamBuffer();break;case"tool_blocked":z.showError(S.reason);break;case"usage":F+=S.inputTokens,w+=S.outputTokens;break;case"error":z.showError(S.error);break;case"done":break}}}catch(S){if(!j.signal.aborted)z.showError(S instanceof Error?S.message:String(S))}j=null,z.endStream();let f={inputTokens:F,outputTokens:w},a=H.add(f);if(F>0||w>0)z.showUsage(H.formatUsage(f)),z.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let Y1={role:"assistant",content:W,toolCalls:q.length>0?q:void 0,usage:F>0?{inputTokens:F,outputTokens:w,costCents:a.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(Y1),Z.trimHistory(Y.maxHistory),z.enableInput()}async function m(y){let $$=y.slice(1).split(" "),C$=$$[0].toLowerCase(),O=$$.slice(1);switch(C$){case"exit":case"quit":case"sair":case"q":p();break;case"clear":case"limpar":Z.clear(),z.clearMessages(),z.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let W=O[0]||`s-${Date.now()}`;Z.switchTo(W),z.clearMessages(),z.updateSession(W),z.showSystem(`New session: ${W}`);break}case"load":case"carregar":{let W=O[0];if(!W){z.showError("Usage: /load <name>");break}Z.switchTo(W),z.clearMessages();for(let q of Z.messages)if(q.role==="user")z.addUserMessage(q.content);else z.addAssistantMessage(q.content);z.updateSession(W),z.showSystem(`Loaded: ${W}`);break}case"sessions":case"sessoes":case"ls":{let W=Z.list();if(W.length===0){z.showSystem("No saved sessions.");break}let q=W.map((B)=>{let F=Z.getInfo(B),w=B===Z.session.name?" *":" ",f=F?t6(F.updated):"",a=F?`${F.messageCount} msgs`:"";return`${w} ${B.padEnd(20)} ${a.padEnd(10)} ${f}`});z.showSystem(`Sessions:
440
+ `+q.join(`
441
+ `));break}case"delete":case"deletar":case"rm":{let W=O[0];if(!W){z.showError("Usage: /delete <name>");break}if(Z.delete(W))z.showSystem(`Deleted: ${W}`);else z.showError(`Session not found: ${W}`);break}case"archive":case"arquivar":{let W=O[0];if(!W){z.showError("Uso: /archive <nome> ou /archive all");break}if(W==="all"||W==="todas"){let q=Z.archiveAll();if(q.length>0)z.showSystem(`Arquivadas ${q.length} sessoes: ${q.join(", ")}`);else z.showSystem("Nenhuma sessao para arquivar (apenas a sessao atual esta ativa).")}else if(Z.archive(W))z.showSystem(`Sessao arquivada: "${W}"`);else z.showError(`Falha ao arquivar "${W}" (nao encontrada ou e a sessao atual).`);break}case"unarchive":case"desarquivar":case"restore":case"restaurar":{let W=O[0];if(!W){z.showError("Uso: /unarchive <nome>");break}if(Z.unarchive(W))z.showSystem(`Sessao restaurada: "${W}"`);else z.showError(`Sessao arquivada nao encontrada: "${W}"`);break}case"archived":case"arquivadas":{let W=Z.listArchived();if(W.length===0){z.showSystem("Nenhuma sessao arquivada.");break}let q=W.map((B)=>{let F=Z.getArchivedInfo(B),w=F?t6(F.updated):"",f=F?`${F.messageCount} msgs`:"";return` ${B.padEnd(20)} ${f.padEnd(10)} ${w}`});z.showSystem(`Sessoes arquivadas (${W.length}):
442
+ ${q.join(`
443
+ `)}`);break}case"model":case"modelo":{let W=O[0];if(!W){z.showSystem(H6(Y.model)+`
444
+
445
+ `+q6());break}let{provider:q,model:B}=_7(W),F=q==="anthropic"?y7(B):B;if(Y.model=q==="anthropic"?F:`${q}:${F}`,q8(Y),q==="anthropic")$.setModel(F);else z.showSystem(`Note: ${q} provider selected. Restart smolerclaw for full provider switch.`);H.setModel(F),z.updateModel(Y.model),z.showSystem(`Model -> ${Y.model}`);break}case"skills":case"habilidades":{z.showSystem(Q6(Q));break}case"auth":z.showSystem(`Auth: subscription (${J.subscriptionType})
446
+ Expires: ${new Date(J.expiresAt).toLocaleString()}`);break;case"refresh":case"renovar":{z.showSystem("Renovando sessao Claude...");try{let W=Bun.spawn(["claude","-p","Fresh!"],{stdout:"pipe",stderr:"pipe"}),q=setTimeout(()=>W.kill(),15000);await W.exited,clearTimeout(q);let B=K2();if(B){if(J=B,"updateApiKey"in $)$.updateApiKey(B.token);z.showSystem(`Sessao renovada. Expira: ${new Date(B.expiresAt).toLocaleString()}`)}else z.showSystem("claude executado, mas credenciais nao atualizaram. Tente novamente.")}catch(W){z.showError(`Falha ao renovar: ${W instanceof Error?W.message:String(W)}`)}break}case"config":z.showSystem(`Config: ${Q2()}`);break;case"export":case"exportar":{let W=new Date().toISOString().split("T")[0],q=O[0]||`smolerclaw-${Z.session.name}-${W}.md`;try{let B=W6(Z.session);_X(q,B),z.showSystem(`Exported to: ${q}`)}catch(B){z.showError(`Export failed: ${B instanceof Error?B.message:B}`)}break}case"cost":case"custo":z.showSystem(`Session: ${H.formatSession()}`);break;case"retry":case"repetir":{let W=[...Z.messages].reverse().find((w)=>w.role==="user");if(!W){z.showError("No previous message to retry.");break}let q=Z.messages,B=0;if(q.length>0&&q[q.length-1].role==="assistant")B++;if(q.length>B&&q[q.length-1-B].role==="user")B++;if(B>0)Z.popMessages(B);z.showSystem("Retrying...");let F=W.images?.length?W.content:W.content;await T(F);break}case"help":case"ajuda":case"?":z.showSystem(["Comandos / Commands (en | pt):"," /help /ajuda Mostrar ajuda"," /clear /limpar Limpar conversa"," /new /novo Nova sessao"," /load /carregar Carregar sessao"," /sessions /sessoes Listar sessoes"," /delete /deletar Deletar sessao"," /model /modelo Ver/trocar modelo"," /persona /modo Trocar modo (business, coder...)"," /export /exportar Exportar para markdown"," /copy /copiar Copiar ultima resposta"," /cost /custo Ver uso de tokens"," /retry /repetir Repetir ultima msg"," /undo /desfazer Desfazer alteracao"," /search /buscar Buscar na conversa"," /lang /idioma Definir idioma"," /commit /commitar Git commit com IA"," /exit /sair Sair","","Negocios / Business:"," /briefing /resumo Briefing diario"," /news /noticias Radar de noticias"," /open /abrir Abrir app Windows"," /apps /programas Apps em execucao"," /sysinfo /sistema Recursos do sistema"," /calendar /agenda Calendario Outlook","","Pessoas / People:"," /addperson /novapessoa Cadastrar pessoa"," /people /pessoas Listar todas"," /team /equipe Listar equipe"," /family /familia Listar familia"," /person /pessoa Detalhes de alguem"," /delegate /delegar Delegar tarefa"," /delegations /delegacoes Listar delegacoes"," /followups Follow-ups pendentes"," /dashboard /painel Painel geral","","Monitor:"," /monitor /vigiar Monitorar processo (ex: /monitor nginx)"," /monitor stop <nome> Parar monitoramento","","Workflows:"," /workflow /fluxo Listar workflows"," /workflow run <nome> Executar (ex: /workflow iniciar-dia)","","Pomodoro:"," /pomodoro /foco Iniciar (ex: /foco revisar codigo)"," /pomodoro status Ver tempo restante"," /pomodoro stop Parar","","Financas / Finance:"," /entrada <$> <cat> Registrar entrada"," /saida <$> <cat> Registrar saida"," /finance /balanco Resumo mensal","","Decisoes / Decisions:"," /decisoes [busca] Listar/buscar decisoes","","Email:"," /email /rascunho Rascunho (ex: /email joao@x.com oi | texto)","","Memos / Notes:"," /memo /anotar Salvar memo (ex: /memo senha wifi #casa)"," /memos /notas Buscar memos (ex: /memos docker)"," /tags /memotags Listar tags"," /rmmemo /rmnota Remover memo","","Materiais / Materials:"," /material /mat Salvar material (ex: /mat titulo | conteudo)"," /materials /materiais Listar/buscar materiais"," /matcats /categorias Listar categorias"," /rmmat /rmmaterial Remover material","","Arquivo / Archive:"," /archive /arquivar Arquivar sessao (ex: /archive minha-sessao)"," /archive all Arquivar todas exceto a atual"," /archived /arquivadas Listar sessoes arquivadas"," /unarchive /restaurar Restaurar sessao arquivada","","Investigacao / Investigation:"," /investigar /investigate Listar investigacoes"," /investigar <busca> Buscar por palavra-chave","","Tarefas / Tasks:"," /task /tarefa Criar tarefa (ex: /tarefa 18h buscar pao)"," /tasks /tarefas Listar pendentes"," /done /feito Marcar como concluida"," /rmtask /rmtarefa Remover tarefa","","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(`
447
+ `));break;case"commit":case"commitar":{if(!await M6()){z.showError("Not a git repository.");break}let W=await B6();if(W==="(clean)"){z.showSystem("Nothing to commit \u2014 working tree clean.");break}z.showSystem(`Changes:
448
+ `+W),z.disableInput();try{let B=`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.
319
449
 
320
450
  Diff:
321
- ${(await KZ()).slice(0,8000)}`;K.startStream();let L="";for await(let _ of $.chat([{role:"user",content:C,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(_.type==="text")L+=_.text,K.appendStream(_.text);else if(_.type==="error")K.showError(_.error);if(K.endStream(),L=L.trim().replace(/^["']|["']$/g,""),!L){K.showError("Failed to generate commit message. Aborting.");break}await GZ();let w=await WZ(L);if(w.ok)K.showSystem(`Committed: ${L}`);else K.showError(`Commit failed: ${w.output}`)}catch(U){K.showError(`Commit error: ${U instanceof Error?U.message:String(U)}`)}K.enableInput();break}case"persona":case"modo":{let W=F[0];if(!W){K.showSystem(BZ(O));break}let U=UZ(W);if(!U){K.showError(`Unknown persona: ${W}. Try /persona to see options.`);break}if(O=U.name,U.systemPrompt)M=t6(U.systemPrompt,X,Y.language);else M=z;K.showSystem(`Persona -> ${U.name}: ${U.description}`);break}case"copy":case"copiar":{let W=[...Z.messages].reverse().find((C)=>C.role==="assistant");if(!W){K.showError("No assistant message to copy.");break}if(await NZ(W.content))K.showSystem("Copied last response to clipboard.");else K.showError("Failed to copy. Is xclip/pbcopy available?");break}case"ask":case"perguntar":{let W=F.join(" ");if(!W){K.showError("Usage: /ask <question>");break}K.addUserMessage(`(ephemeral) ${W}`),K.disableInput(),K.startStream();let U="";for await(let C of $.chat([{role:"user",content:W,timestamp:Date.now()}],M,!1))if(C.type==="text")U+=C.text,K.appendStream(C.text);else if(C.type==="error")K.showError(C.error);else if(C.type==="usage")K.showUsage(`${C.inputTokens} in / ${C.outputTokens} out (ephemeral)`);K.endStream(),K.enableInput();break}case"fork":{let W=F[0]||`fork-${Date.now()}`;Z.fork(W),K.updateSession(W),K.showSystem(`Forked session -> ${W} (${Z.messages.length} messages copied)`);break}case"plugins":{K.showSystem(L8(V));break}case"budget":case"orcamento":{let W=F[0];if(!W){let C=Y.maxSessionCost,L=q.totals.costCents;if(C===0)K.showSystem(`Budget: unlimited (spent ~$${(L/100).toFixed(4)})`);else{let w=Math.round(L/C*100);K.showSystem(`Budget: ~$${(L/100).toFixed(4)} / $${(C/100).toFixed(4)} (${w}%)`)}break}let U=Number(W);if(isNaN(U)||U<0){K.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Y.maxSessionCost=U,R1(Y),K.showSystem(U===0?"Budget: unlimited":`Budget set: $${(U/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!q$.peek()){K.showError("Nothing to undo.");break}let U=q$.undo();if(U)K.showSystem(U);break}case"search":case"buscar":{let W=F.join(" ").toLowerCase();if(!W){K.showError("Usage: /search <text>");break}let U=[];for(let C of Z.messages)if(C.content.toLowerCase().includes(W)){let L=C.content.slice(0,100).replace(/\n/g," "),w=new Date(C.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});U.push(` [${C.role} ${w}] ${L}${C.content.length>100?"...":""}`)}K.showSystem(U.length>0?`Found ${U.length} match${U.length>1?"es":""}:
322
- ${U.join(`
323
- `)}`:`No matches for "${W}".`);break}case"lang":case"language":case"idioma":{let W=F[0];if(!W){K.showSystem(`Language: ${Y.language} (auto = match user's language)`);break}Y.language=W,R1(Y),K.showSystem(`Language -> ${W}`);break}case"briefing":case"resumo":{K.showSystem("Carregando briefing..."),K.disableInput();try{let W=await jZ();K.showSystem(W)}catch(W){K.showError(`Briefing falhou: ${W instanceof Error?W.message:String(W)}`)}K.enableInput();break}case"news":case"noticias":{let W=F[0];if(W&&!["business","tech","finance","brazil","world","security"].includes(W)){K.showSystem(F6());break}K.showSystem("Buscando noticias..."),K.disableInput();try{let C=await w2(W?[W]:void 0);K.showSystem(C)}catch(C){K.showError(`Falha ao buscar noticias: ${C instanceof Error?C.message:String(C)}`)}K.enableInput();break}case"open":case"abrir":{if(!F.join(" ")){K.showSystem(`Apps disponiveis: ${x8().join(", ")}
324
- Uso: /open <app> ou /open <app> <arquivo>`);break}let U=F.length>1?F.slice(1).join(" "):void 0,C=await J$(F[0],U);K.showSystem(C);break}case"openfile":case"abrirarquivo":{let W=F.join(" ");if(!W){K.showError("Uso: /openfile <caminho>");break}let U=await t1(W);K.showSystem(U);break}case"openurl":{let W=F[0];if(!W){K.showError("Uso: /openurl <url>");break}let U=await s1(W);K.showSystem(U);break}case"apps":case"programas":{K.disableInput();try{let W=await e1();K.showSystem(W)}catch(W){K.showError(`Apps: ${W instanceof Error?W.message:String(W)}`)}K.enableInput();break}case"sysinfo":case"sistema":{K.disableInput();try{let W=await X$();K.showSystem(W)}catch(W){K.showError(`Sysinfo: ${W instanceof Error?W.message:String(W)}`)}K.enableInput();break}case"calendar":case"calendario":case"agenda":case"cal":{K.disableInput();try{let W=await z$(),U=await A2();K.showSystem(`${W}
451
+ ${(await U6()).slice(0,8000)}`;z.startStream();let F="";for await(let f of $.chat([{role:"user",content:B,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(f.type==="text")F+=f.text,z.appendStream(f.text);else if(f.type==="error")z.showError(f.error);if(z.endStream(),F=F.trim().replace(/^["']|["']$/g,""),!F){z.showError("Failed to generate commit message. Aborting.");break}await N6();let w=await C6(F);if(w.ok)z.showSystem(`Committed: ${F}`);else z.showError(`Commit failed: ${w.output}`)}catch(q){z.showError(`Commit error: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"persona":case"modo":{let W=O[0];if(!W){z.showSystem(L6(M));break}let q=E6(W);if(!q){z.showError(`Unknown persona: ${W}. Try /persona to see options.`);break}if(M=q.name,q.systemPrompt)E=w7(q.systemPrompt,Q,Y.language);else E=X;z.showSystem(`Persona -> ${q.name}: ${q.description}`);break}case"copy":case"copiar":{let W=[...Z.messages].reverse().find((B)=>B.role==="assistant");if(!W){z.showError("No assistant message to copy.");break}if(await j6(W.content))z.showSystem("Copied last response to clipboard.");else z.showError("Failed to copy. Is xclip/pbcopy available?");break}case"ask":case"perguntar":{let W=O.join(" ");if(!W){z.showError("Usage: /ask <question>");break}z.addUserMessage(`(ephemeral) ${W}`),z.disableInput(),z.startStream();let q="";for await(let B of $.chat([{role:"user",content:W,timestamp:Date.now()}],E,!1))if(B.type==="text")q+=B.text,z.appendStream(B.text);else if(B.type==="error")z.showError(B.error);else if(B.type==="usage")z.showUsage(`${B.inputTokens} in / ${B.outputTokens} out (ephemeral)`);z.endStream(),z.enableInput();break}case"fork":{let W=O[0]||`fork-${Date.now()}`;Z.fork(W),z.updateSession(W),z.showSystem(`Forked session -> ${W} (${Z.messages.length} messages copied)`);break}case"plugins":{z.showSystem(W9(V));break}case"budget":case"orcamento":{let W=O[0];if(!W){let B=Y.maxSessionCost,F=H.totals.costCents;if(B===0)z.showSystem(`Budget: unlimited (spent ~$${(F/100).toFixed(4)})`);else{let w=Math.round(F/B*100);z.showSystem(`Budget: ~$${(F/100).toFixed(4)} / $${(B/100).toFixed(4)} (${w}%)`)}break}let q=Number(W);if(isNaN(q)||q<0){z.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Y.maxSessionCost=q,q8(Y),z.showSystem(q===0?"Budget: unlimited":`Budget set: $${(q/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!p1.peek()){z.showError("Nothing to undo.");break}let q=p1.undo();if(q)z.showSystem(q);break}case"search":case"buscar":{let W=O.join(" ").toLowerCase();if(!W){z.showError("Usage: /search <text>");break}let q=[];for(let B of Z.messages)if(B.content.toLowerCase().includes(W)){let F=B.content.slice(0,100).replace(/\n/g," "),w=new Date(B.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});q.push(` [${B.role} ${w}] ${F}${B.content.length>100?"...":""}`)}z.showSystem(q.length>0?`Found ${q.length} match${q.length>1?"es":""}:
452
+ ${q.join(`
453
+ `)}`:`No matches for "${W}".`);break}case"lang":case"language":case"idioma":{let W=O[0];if(!W){z.showSystem(`Language: ${Y.language} (auto = match user's language)`);break}Y.language=W,q8(Y),z.showSystem(`Language -> ${W}`);break}case"briefing":case"resumo":{z.showSystem("Carregando briefing..."),z.disableInput();try{let W=await R6();z.showSystem(W)}catch(W){z.showError(`Briefing falhou: ${W instanceof Error?W.message:String(W)}`)}z.enableInput();break}case"news":case"noticias":{let W=O[0];if(W)z.showSystem(`Buscando noticias (${W})...`);else z.showSystem("Buscando noticias...");z.disableInput();try{let q=await n$(W?[W]:void 0);z.showSystem(q)}catch(q){z.showError(`Falha ao buscar noticias: ${q instanceof Error?q.message:String(q)}`)}z.enableInput();break}case"feeds":case"fontes":{z.showSystem(o8());break}case"addfeed":case"novafonte":{if(O.length<3){z.showError(`Uso: /addfeed <nome> <url> <categoria>
454
+ Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let W=O[0],q=O[1],B=O[2],F=p8(W,q,B);if(typeof F==="string")z.showError(F);else z.showSystem(`Fonte adicionada: ${F.name} (${F.category}) \u2014 ${F.url}`);break}case"rmfeed":case"rmfonte":{let W=O.join(" ");if(!W){z.showError("Uso: /rmfeed <nome ou url>");break}if(l8(W))z.showSystem(`Fonte removida: ${W}`);else z.showError(`Fonte custom nao encontrada: "${W}". Para desativar uma built-in, use /disablefeed.`);break}case"disablefeed":case"desativarfonte":{let W=O.join(" ");if(!W){z.showError("Uso: /disablefeed <nome ou url>");break}if(n8(W))z.showSystem(`Fonte desativada: ${W}`);else z.showError(`Fonte built-in nao encontrada ou ja desativada: "${W}"`);break}case"enablefeed":case"ativarfonte":{let W=O.join(" ");if(!W){z.showError("Uso: /enablefeed <nome ou url>");break}if(i8(W))z.showSystem(`Fonte reativada: ${W}`);else z.showError(`Fonte built-in nao encontrada ou nao esta desativada: "${W}"`);break}case"open":case"abrir":{if(!O.join(" ")){z.showSystem(`Apps disponiveis: ${q9().join(", ")}
455
+ Uso: /open <app> ou /open <app> <arquivo>`);break}let q=O.length>1?O.slice(1).join(" "):void 0,B=await I1(O[0],q);z.showSystem(B);break}case"openfile":case"abrirarquivo":{let W=O.join(" ");if(!W){z.showError("Uso: /openfile <caminho>");break}let q=await m8(W);z.showSystem(q);break}case"openurl":{let W=O[0];if(!W){z.showError("Uso: /openurl <url>");break}let q=await S1(W);z.showSystem(q);break}case"apps":case"programas":{z.disableInput();try{let W=await c8();z.showSystem(W)}catch(W){z.showError(`Apps: ${W instanceof Error?W.message:String(W)}`)}z.enableInput();break}case"sysinfo":case"sistema":{z.disableInput();try{let W=await b1();z.showSystem(W)}catch(W){z.showError(`Sysinfo: ${W instanceof Error?W.message:String(W)}`)}z.enableInput();break}case"calendar":case"calendario":case"agenda":case"cal":{z.disableInput();try{let W=await k1(),q=await l$();z.showSystem(`${W}
325
456
 
326
457
  --- Agenda ---
327
- ${U}`)}catch(W){K.showError(`Calendar: ${W instanceof Error?W.message:String(W)}`)}K.enableInput();break}case"monitor":case"vigiar":{let W=F[0]?.toLowerCase();if(!W||W==="list"||W==="listar")K.showSystem(mZ());else if(W==="stop"||W==="parar"){let U=F[1];if(!U){K.showError("Uso: /monitor stop <processo>");break}K.showSystem(dZ(U))}else{let U=parseInt(F[1])||60;K.showSystem(cZ(W,U))}break}case"workflow":case"fluxo":{let W=F[0]?.toLowerCase();if(!W||W==="list"||W==="listar")K.showSystem(hZ());else if(W==="run"||W==="rodar"){let U=F[1];if(!U){K.showError("Uso: /workflow run <nome>");break}K.disableInput();try{let C=await W7(U,(L)=>K.showSystem(L));K.showSystem(C)}catch(C){K.showError(`Workflow: ${C instanceof Error?C.message:String(C)}`)}K.enableInput()}else if(W==="delete"||W==="deletar"){let U=F[1];if(!U){K.showError("Uso: /workflow delete <nome>");break}if(fZ(U))K.showSystem(`Workflow removido: ${U}`);else K.showError(`Workflow nao encontrado: ${U}`)}else{K.disableInput();try{let U=await W7(W,(C)=>K.showSystem(C));K.showSystem(U)}catch(U){K.showError(`Workflow: ${U instanceof Error?U.message:String(U)}`)}K.enableInput()}break}case"pomodoro":case"foco":{let W=F[0]?.toLowerCase();if(W==="stop"||W==="parar")K.showSystem(wZ());else if(W==="status")K.showSystem(V7());else if(!W)K.showSystem(V7());else{let U=F.join(" "),C=25,L=5;K.showSystem(AZ(U,25,5))}break}case"entrada":case"income":{let W=parseFloat(F[0]);if(isNaN(W)||F.length<3){K.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let U=V1("entrada",W,F[1],F.slice(2).join(" "));K.showSystem(`+ R$ ${U.amount.toFixed(2)} (${U.category}) \u2014 ${U.description}`);break}case"saida":case"expense":{let W=parseFloat(F[0]);if(isNaN(W)||F.length<3){K.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let U=V1("saida",W,F[1],F.slice(2).join(" "));K.showSystem(`- R$ ${U.amount.toFixed(2)} (${U.category}) \u2014 ${U.description}`);break}case"finance":case"financas":case"balanco":{let W=F[0];if(W==="recent"||W==="recentes")K.showSystem(R6());else K.showSystem(K4()+`
328
-
329
- `+R6(5));break}case"decisions":case"decisoes":{let W=F.join(" ");if(W){let U=V4(W);K.showSystem(K$(U))}else K.showSystem(K$(G4()));break}case"investigar":case"investigate":case"investigacoes":{let W=F.join(" ");if(W){let{searchInvestigations:U,formatInvestigationList:C}=await Promise.resolve().then(() => (W1(),_6));K.showSystem(C(U(W)))}else{let{listInvestigations:U,formatInvestigationList:C}=await Promise.resolve().then(() => (W1(),_6));K.showSystem(C(U()))}break}case"email":case"rascunho":{if(!F.join(" ")){K.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
330
- Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let U=F[0],C=F.slice(1).join(" "),L=C.indexOf("|");if(L===-1){K.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
331
- Use | para separar assunto do corpo.`);break}let w=C.slice(0,L).trim(),_=C.slice(L+1).trim();if(!w||!_){K.showError("Assunto e corpo sao obrigatorios.");break}let u={to:U,subject:w,body:_};K.showSystem(Q4(u)),K.disableInput();try{let y2=await z4(u);K.showSystem(y2)}catch(y2){K.showError(`Email: ${y2 instanceof Error?y2.message:String(y2)}`)}K.enableInput();break}case"memo":case"anotar":case"note":{let W=F.join(" ");if(!W){let L=K1();K.showSystem(u2(L));break}let U=J4(W),C=U.tags.length>0?` [${U.tags.map((L)=>"#"+L).join(" ")}]`:"";K.showSystem(`Memo salvo${C} {${U.id}}`);break}case"memos":case"notas":{let W=F.join(" ");if(W){let U=X4(W);K.showSystem(u2(U))}else{let U=K1();K.showSystem(u2(U))}break}case"memotags":case"tags":{K.showSystem(d8());break}case"rmmemo":case"rmnota":{let W=F[0];if(!W){K.showError("Uso: /rmmemo <id>");break}if(c8(W))K.showSystem("Memo removido.");else K.showError(`Memo nao encontrado: ${W}`);break}case"material":case"mat":{let W=F.join(" ");if(!W){let u=G$(10);K.showSystem(k2(u));break}if(/^[a-z0-9]{6}$/.test(W)){let u=N0(W);if(u)K.showSystem(O0(u));else K.showError(`Material nao encontrado: ${W}`);break}let U=W.indexOf("|");if(U===-1){K.showSystem(`Uso: /material <titulo> | <conteudo>
332
- Ou peca a IA: "salva esse material sobre..."`);break}let C=W.slice(0,U).trim(),L=W.slice(U+1).trim();if(!C||!L){K.showError("Titulo e conteudo sao obrigatorios.");break}let w=M4(C,L),_=w.tags.length>0?` [${w.tags.map((u)=>"#"+u).join(" ")}]`:"";K.showSystem(`Material salvo: "${w.title}" (${w.category})${_} {${w.id}}`);break}case"materials":case"materiais":{let W=F.join(" ");if(W){let U=R4(W);K.showSystem(k2(U))}else{let U=G$();K.showSystem(k2(U))}break}case"matcats":case"categorias":{K.showSystem(F0());break}case"rmmat":case"rmmaterial":{let W=F[0];if(!W){K.showError("Uso: /rmmat <id>");break}if(L4(W))K.showSystem("Material removido.");else K.showError(`Material nao encontrado: ${W}`);break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let U={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[z2]||F[0],C=B4(U);K.showSystem(C4(C));break}case"person":case"pessoa":{let W=F.join(" ");if(!W){K.showError("Uso: /person <nome>");break}let U=S2(W);if(!U){K.showError(`Pessoa nao encontrada: "${W}"`);break}K.showSystem(j4(U));break}case"addperson":case"addpessoa":case"novapessoa":{let W=F[0];if(!W||!["equipe","familia","contato"].includes(W)){K.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
333
- Ex: /addperson equipe Joao dev frontend`);break}let C=F.slice(1).join(" ");if(!C){K.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[L,...w]=C.split(","),_=w.join(",").trim()||void 0,u=U4(L.trim(),W,_);K.showSystem(`Adicionado: ${u.name} (${W}) [${u.id}]`);break}case"delegate":case"delegar":{let W=F[0];if(!W||F.length<2){K.showSystem(`Uso: /delegate <pessoa> <tarefa>
334
- Ex: /delegate Joao revisar relatorio`);break}let U=F.slice(1).join(" "),C=N4(W,U);if(!C){K.showError(`Pessoa nao encontrada: "${W}"`);break}K.showSystem(`Delegado para ${W}: "${U}" [${C.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let W=F[0],U=V$(W);K.showSystem(O4(U));break}case"followups":{let W=q1();K.showSystem(F4(W));break}case"dashboard":case"painel":{K.showSystem(E4());break}case"task":case"tarefa":{let W=F.join(" ");if(!W){let _=P2();K.showSystem(m2(_));break}let U=Q1(W),C=W.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(!C)C=W;let L=Z4(C,U||void 0),w=U?` \u2014 lembrete: ${U.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";K.showSystem(`Tarefa criada: "${L.title}"${w} [${L.id}]`);break}case"tasks":case"tarefas":{let W=F[0]==="all"||F[0]==="todas",U=P2(W);K.showSystem(m2(U));break}case"done":case"feito":case"concluido":{let W=F.join(" ");if(!W){K.showError("Uso: /done <id ou parte do titulo>");break}let U=Y4(W);if(U)K.showSystem(`Concluida: "${U.title}"`);else K.showError(`Tarefa nao encontrada: "${W}"`);break}case"rmtask":case"rmtarefa":{let W=F.join(" ");if(!W){K.showError("Uso: /rmtask <id ou parte do titulo>");break}if(b8(W))K.showSystem("Tarefa removida.");else K.showError(`Tarefa nao encontrada: "${W}"`);break}default:K.showError(`Unknown command: /${z2}. Try /help`)}}function n(){k8(),IZ(),uZ(),K.stop(),process.exit(0)}process.on("SIGINT",n),process.on("SIGTERM",n),K.start({onSubmit:v,onCancel:()=>{D?.abort(),K.endStream(),K.showSystem("Cancelled."),K.enableInput()},onExit:n});let N1=`Authenticated via Claude ${J.subscriptionType} subscription.`;if(K.showSystem(`smolerclaw v${j1()} \u2014 the micro AI assistant.
335
- ${N1}
336
- Type /ajuda for commands.`),EZ(Y.dataDir))try{let k=await LZ();K.showSystem(k),MZ()}catch{}if(G)await v(G)}function pZ($){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 J=Math.floor(Y/60);if(J<24)return`${J}h ago`;let X=Math.floor(J/24);if(X>365)return`${Math.floor(X/365)}y ago`;return`${X}d ago`}wY().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});
458
+ ${q}`)}catch(W){z.showError(`Calendar: ${W instanceof Error?W.message:String(W)}`)}z.enableInput();break}case"monitor":case"vigiar":{let W=O[0]?.toLowerCase();if(!W||W==="list"||W==="listar")z.showSystem(r6());else if(W==="stop"||W==="parar"){let q=O[1];if(!q){z.showError("Uso: /monitor stop <processo>");break}z.showSystem(a6(q))}else{let q=parseInt(O[1])||60;z.showSystem(o6(W,q))}break}case"workflow":case"fluxo":{let W=O[0]?.toLowerCase();if(!W||W==="list"||W==="listar"){let q=O[1];z.showSystem(p6(c6(q)))}else if(W==="run"||W==="rodar"){let q=O[1];if(!q){z.showError("Uso: /workflow run <nome>");break}z.disableInput();try{let B=await u7(q,(F)=>z.showSystem(F));z.showSystem(B)}catch(B){z.showError(`Workflow: ${B instanceof Error?B.message:String(B)}`)}z.enableInput()}else if(W==="info"||W==="detalhe"){let q=O[1];if(!q){z.showError("Uso: /workflow info <nome>");break}let B=s4(q);if(B)z.showSystem(l6(B));else z.showError(`Workflow nao encontrado: ${q}`)}else if(W==="delete"||W==="deletar"){let q=O[1];if(!q){z.showError("Uso: /workflow delete <nome>");break}if(d6(q))z.showSystem(`Workflow removido: ${q}`);else z.showError(`Workflow nao encontrado: ${q}`)}else if(W==="enable"||W==="ativar"){let q=O[1];if(!q){z.showError("Uso: /workflow enable <nome>");break}let B=d7(q,{enabled:!0});if(B)z.showSystem(`Workflow ativado: ${B.name}`);else z.showError(`Workflow nao encontrado: ${q}`)}else if(W==="disable"||W==="desativar"){let q=O[1];if(!q){z.showError("Uso: /workflow disable <nome>");break}let B=d7(q,{enabled:!1});if(B)z.showSystem(`Workflow desativado: ${B.name}`);else z.showError(`Workflow nao encontrado: ${q}`)}else{z.disableInput();try{let q=await u7(W,(B)=>z.showSystem(B));z.showSystem(q)}catch(q){z.showError(`Workflow: ${q instanceof Error?q.message:String(q)}`)}z.enableInput()}break}case"pomodoro":case"foco":{let W=O[0]?.toLowerCase();if(W==="stop"||W==="parar")z.showSystem(k6());else if(W==="status")z.showSystem(g7());else if(!W)z.showSystem(g7());else{let q=O.join(" "),B=25,F=5;z.showSystem(b6(q,25,5))}break}case"entrada":case"income":{let W=parseFloat(O[0]);if(isNaN(W)||O.length<3){z.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let q=d4("entrada",W,O[1],O.slice(2).join(" "));z.showSystem(`+ R$ ${q.amount.toFixed(2)} (${q.category}) \u2014 ${q.description}`);break}case"saida":case"expense":{let W=parseFloat(O[0]);if(isNaN(W)||O.length<3){z.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let q=d4("saida",W,O[1],O.slice(2).join(" "));z.showSystem(`- R$ ${q.amount.toFixed(2)} (${q.category}) \u2014 ${q.description}`);break}case"finance":case"financas":case"balanco":{let W=O[0];if(W==="recent"||W==="recentes")z.showSystem(i2());else z.showSystem(Y0()+`
459
+
460
+ `+i2(5));break}case"decisions":case"decisoes":{let W=O.join(" ");if(W){let q=J0(W);z.showSystem(h1(q))}else z.showSystem(h1(Q0()));break}case"investigar":case"investigate":case"investigacoes":{let W=O.join(" ");if(W){let{searchInvestigations:q,formatInvestigationList:B}=await Promise.resolve().then(() => (p4(),X7));z.showSystem(B(q(W)))}else{let{listInvestigations:q,formatInvestigationList:B}=await Promise.resolve().then(() => (p4(),X7));z.showSystem(B(q()))}break}case"email":case"rascunho":{if(!O.join(" ")){z.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
461
+ Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let q=O[0],B=O.slice(1).join(" "),F=B.indexOf("|");if(F===-1){z.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
462
+ Use | para separar assunto do corpo.`);break}let w=B.slice(0,F).trim(),f=B.slice(F+1).trim();if(!w||!f){z.showError("Assunto e corpo sao obrigatorios.");break}let a={to:q,subject:w,body:f};z.showSystem(Z0(a)),z.disableInput();try{let Y1=await $0(a);z.showSystem(Y1)}catch(Y1){z.showError(`Email: ${Y1 instanceof Error?Y1.message:String(Y1)}`)}z.enableInput();break}case"memo":case"anotar":case"note":{let W=O.join(" ");if(!W){let F=c4();z.showSystem(q1(F));break}let q=t8(W),B=q.tags.length>0?` [${q.tags.map((F)=>"#"+F).join(" ")}]`:"";z.showSystem(`Memo salvo${B} {${q.id}}`);break}case"memos":case"notas":{let W=O.join(" ");if(W){let q=e8(W);z.showSystem(q1(q))}else{let q=c4();z.showSystem(q1(q))}break}case"memotags":case"tags":{z.showSystem(b9());break}case"rmmemo":case"rmnota":{let W=O[0];if(!W){z.showError("Uso: /rmmemo <id>");break}if(S9(W))z.showSystem("Memo removido.");else z.showError(`Memo nao encontrado: ${W}`);break}case"material":case"mat":{let W=O.join(" ");if(!W){let a=v1(10);z.showSystem(s$(a));break}if(/^[a-z0-9]{6}$/.test(W)){let a=zZ(W);if(a)z.showSystem(WZ(a));else z.showError(`Material nao encontrado: ${W}`);break}let q=W.indexOf("|");if(q===-1){z.showSystem(`Uso: /material <titulo> | <conteudo>
463
+ Ou peca a IA: "salva esse material sobre..."`);break}let B=W.slice(0,q).trim(),F=W.slice(q+1).trim();if(!B||!F){z.showError("Titulo e conteudo sao obrigatorios.");break}let w=C0(B,F),f=w.tags.length>0?` [${w.tags.map((a)=>"#"+a).join(" ")}]`:"";z.showSystem(`Material salvo: "${w.title}" (${w.category})${f} {${w.id}}`);break}case"materials":case"materiais":{let W=O.join(" ");if(W){let q=O0(W);z.showSystem(s$(q))}else{let q=v1();z.showSystem(s$(q))}break}case"matcats":case"categorias":{z.showSystem(HZ());break}case"rmmat":case"rmmaterial":{let W=O[0];if(!W){z.showError("Uso: /rmmat <id>");break}if(M0(W))z.showSystem("Material removido.");else z.showError(`Material nao encontrado: ${W}`);break}case"indexar":case"index":case"reindex":{z.showSystem("Indexando memoria local...");let W=R0();z.showSystem(`Indexacao concluida: ${W.indexed} fonte(s) indexada(s), ${W.skipped} sem alteracao. Total: ${W.total} chunks.`);break}case"memoria":case"memory":{let W=O.join(" ");if(W){let q=A0(W);z.showSystem(x0(q))}else{let q=F0(),B=q.builtAt?new Date(q.builtAt).toLocaleString("pt-BR"):"nunca";z.showSystem(`Memory RAG Index:
464
+ Chunks: ${q.chunks}
465
+ Fontes: ${q.sources}
466
+ Ultima indexacao: ${B}`)}break}case"vault":{let W=O[0]?.toLowerCase();if(!W||W==="status")z.showSystem(z8(K8()));else if(W==="backup"){z.showSystem("Realizando backup...");let q=O.slice(1).join(" ")||void 0,B=await M1(q);z.showSystem(B)}else if(W==="sync"||W==="push"){z.showSystem("Sincronizando com remote...");let q=await G8();z.showSystem(q)}else if(W==="init"){let q=await V8();z.showSystem(q),K5(30),z.showSystem("Auto-backup ativado (a cada 30 minutos).")}else z.showError("Uso: /vault [status|backup|sync|init]");break}case"backup":{z.showSystem("Realizando backup...");let W=await M1();z.showSystem(W);break}case"clipboard":case"area":{z.showSystem("Lendo clipboard...");let W=await T0();switch(W.type){case"text":z.showSystem(`Clipboard (texto):
467
+ ${W.text}`);break;case"image":z.showSystem(W.text);break;case"empty":z.showSystem("Clipboard vazio.");break;case"error":z.showError(W.text);break}break}case"tela":case"screen":{z.showSystem("Analisando tela...");let W=await P0();z.showSystem(W);break}case"ps1":{let W=O.join(" ");if(!W.trim()){z.showError("Uso: /ps1 <script powershell>");break}z.showSystem("Executando script...");let q=await D0(W),B=[];if(q.stdout.trim())B.push(q.stdout.trim());if(q.stderr.trim())B.push(`stderr: ${q.stderr.trim()}`);B.push(`(exit: ${q.exitCode}, ${q.duration}ms)`),z.showSystem(B.join(`
468
+ `));break}case"projeto":case"project":{let W=O.join(" ");if(W){let q=S0(W);if(q)d1(q.id),z.showSystem(v0(q));else if(W==="auto"){let B=m0(process.cwd());if(B)d1(B.id),z.showSystem(`Projeto detectado: ${v0(B)}`);else z.showError("Nenhum projeto detectado no diretorio atual.")}else z.showError(`Projeto nao encontrado: "${W}"`)}else{let q=e$();if(q)z.showSystem(v0(q));else z.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{z.showSystem(f0(b0()));break}case"sessao":case"session":{let W=O[0],q=e$();if(!q){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(W==="start"||W==="iniciar"){let B=O.slice(1).join(" "),F=k0(q.id,B);if(F)z.showSystem(`Sessao iniciada para "${q.name}" [${F.id}]`)}else if(W==="stop"||W==="parar"){let B=$1(q.id);if(B){let F=y0(B.id,O.slice(1).join(" "));if(F)z.showSystem(`Sessao encerrada: ${F.durationMinutes} minutos em "${q.name}"`)}else z.showSystem("Nenhuma sessao aberta.")}else{let B=$1(q.id);if(B){let F=Math.round((Date.now()-new Date(B.startedAt).getTime())/60000);z.showSystem(`Sessao aberta: ${F} minutos em "${q.name}"`)}else z.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let W=e$();if(!W){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let q=O[0]||"today";z.showSystem("Gerando relatorio...");let B=await h0(W.id,q,"pt");if(B)z.showSystem(B.markdown);else z.showError("Falha ao gerar relatorio.");break}case"oportunidades":case"opportunities":{let W=O[0]||void 0,q=_0(W);z.showSystem(g0(q));break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let q={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[C$]||O[0],B=G0(q);z.showSystem(H0(B));break}case"person":case"pessoa":{let W=O.join(" ");if(!W){z.showError("Uso: /person <nome>");break}let q=r$(W);if(!q){z.showError(`Pessoa nao encontrada: "${W}"`);break}z.showSystem(q0(q));break}case"addperson":case"addpessoa":case"novapessoa":{let W=O[0];if(!W||!["equipe","familia","contato"].includes(W)){z.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
469
+ Ex: /addperson equipe Joao dev frontend`);break}let B=O.slice(1).join(" ");if(!B){z.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[F,...w]=B.split(","),f=w.join(",").trim()||void 0,a=V0(F.trim(),W,f);z.showSystem(`Adicionado: ${a.name} (${W}) [${a.id}]`);break}case"delegate":case"delegar":{let W=O[0];if(!W||O.length<2){z.showSystem(`Uso: /delegate <pessoa> <tarefa>
470
+ Ex: /delegate Joao revisar relatorio`);break}let q=O.slice(1).join(" "),B=W0(W,q);if(!B){z.showError(`Pessoa nao encontrada: "${W}"`);break}z.showSystem(`Delegado para ${W}: "${q}" [${B.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let W=O[0],q=f1(W);z.showSystem(U0(q));break}case"followups":{let W=l4();z.showSystem(B0(W));break}case"dashboard":case"painel":{z.showSystem(N0());break}case"task":case"tarefa":{let W=O.join(" ");if(!W){let f=i$();z.showSystem(H1(f));break}let q=m4(W),B=W.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(!B)B=W;let F=r8(B,q||void 0),w=q?` \u2014 lembrete: ${q.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";z.showSystem(`Tarefa criada: "${F.title}"${w} [${F.id}]`);break}case"tasks":case"tarefas":{let W=O[0]==="all"||O[0]==="todas",q=i$(W);z.showSystem(H1(q));break}case"done":case"feito":case"concluido":{let W=O.join(" ");if(!W){z.showError("Uso: /done <id ou parte do titulo>");break}let q=s8(W);if(q)z.showSystem(`Concluida: "${q.title}"`);else z.showError(`Tarefa nao encontrada: "${W}"`);break}case"rmtask":case"rmtarefa":{let W=O.join(" ");if(!W){z.showError("Uso: /rmtask <id ou parte do titulo>");break}if(R9(W))z.showSystem("Tarefa removida.");else z.showError(`Tarefa nao encontrada: "${W}"`);break}default:z.showError(`Unknown command: /${C$}. Try /help`)}}function p(){F9(),h6(),s6(),Y2(),z.stop(),process.exit(0)}process.on("SIGINT",p),process.on("SIGTERM",p),z.start({onSubmit:T,onCancel:()=>{j?.abort(),z.endStream(),z.showSystem("Cancelled."),z.enableInput()},onExit:p});let t4=`Authenticated via Claude ${J.subscriptionType} subscription.`;if(z.showSystem(`smolerclaw v${$8()} \u2014 the micro AI assistant.
471
+ ${t4}
472
+ Type /ajuda for commands.`),D6(Y.dataDir))try{let y=await P6();z.showSystem(y),T6()}catch{}if(G)await T(G)}function t6($){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 J=Math.floor(Y/60);if(J<24)return`${J}h ago`;let Q=Math.floor(J/24);if(Q>365)return`${Math.floor(Q/365)}y ago`;return`${Q}d ago`}fX().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});