smolerclaw 1.2.3 → 1.3.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 (2) hide show
  1. package/dist/index.js +235 -222
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,20 +1,22 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
- var t6=Object.defineProperty;var e6=($)=>$;function $3($,Z){this[$]=e6.bind(null,Z)}var Z3=($,Z)=>{for(var Y in Z)t6($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:$3.bind(Z,Y)})};var l7=($,Z)=>()=>($&&(Z=$($=0)),Z);import{existsSync as x$,mkdirSync as e0,readFileSync as Q8,writeFileSync as o1,renameSync as s7,statSync as z3}from"fs";import{join as K$,dirname as t7,relative as V3}from"path";import{createHash as G3,randomUUID as e7}from"crypto";function Q5($,Z){if(D$=$,J5=Z,r=K$($,".backup"),H3(),Z2=!0,Q1=x$(K$(r,".git")),Q1)$2=B3()}function a1(){return Z2}function P($,Z){let Y=t7($);if(!x$(Y))e0(Y,{recursive:!0});let J=K$(Y,`.smolerclaw-${e7().slice(0,8)}.tmp`);if(o1(J,Z),s7(J,$),Z2){let Q=U3($);if(Q&&X8.includes(Q))W3(Q,Z)}}function X5($){return G3("sha256").update($).digest("hex")}function W3($,Z){let Y=X5(Z),J=new Date().toISOString(),Q=Buffer.byteLength(Z,"utf-8");v$=[...v$.filter((X)=>X.file!==$),{file:$,sha256:Y,size:Q,updatedAt:J}],q3()}function H3(){let $=K$(D$,Z5);if(!x$($)){v$=[];return}try{let Z=JSON.parse(Q8($,"utf-8"));if(Z.version!==$5){v$=[];return}v$=Z.checksums||[]}catch{v$=[]}}function q3(){if(!D$)return;let $=K$(D$,Z5),Z={checksums:v$,version:$5},Y=K$(D$,`.vault-${e7().slice(0,8)}.tmp`);o1(Y,JSON.stringify(Z,null,2)),s7(Y,$)}function U3($){try{let Z=V3(D$,$).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=K$(D$,Y),Q=x$(J);if(!Q){$.push({file:Y,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let X=0,K="";try{let H=z3(J);X=H.size,K=H.mtime.toISOString()}catch{}let V=v$.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:Q1,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(!D$)return"Error: vault not initialized.";if(!x$(r))e0(r,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
6
- `);if(o1(K$(r,".gitignore"),$),!x$(K$(r,".git"))){let Z=await g$(["git","init","-b",Y5],r);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await g$(["git","config","user.email","vault@smolerclaw.local"],r),await g$(["git","config","user.name","smolerclaw-vault"],r)}return Q1=!0,"Shadow backup inicializado."}async function O1($){if(!Q1)return"Backup nao ativado. Use vault_init_backup primeiro.";try{for(let X of X8){let K=K$(D$,X);if(!x$(K))continue;let V=K$(r,X),G=t7(V);if(!x$(G))e0(G,{recursive:!0});o1(V,Q8(K,"utf-8"))}let Z=K$(J5,"config.json");if(x$(Z))o1(K$(r,"config.json"),Q8(Z,"utf-8"));if(await g$(["git","add","-A"],r),!(await g$(["git","status","--porcelain"],r)).stdout.trim())return"Nenhuma mudanca para backup.";let J=$||`backup ${new Date().toISOString().slice(0,19)}`,Q=await g$(["git","commit","-m",J],r);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(!Q1)return"Backup nao ativado.";if(!(await g$(["git","remote","-v"],r)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await g$(["git","push","-u","origin",Y5],r);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function B3(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:r,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function g$($,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(),!Q1)return;J8=setInterval(()=>{O1("auto-backup").catch(()=>{})},$*60*1000)}function Y2(){if(J8)clearInterval(J8),J8=null}var $5=1,Z5="vault-checksums.json",Y5="smolerclaw-backup",X8,D$="",J5="",v$,r="",Q1=!1,$2=null,Z2=!1,J8=null;var t=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"],v$=[]});var X7={};Z3(X7,{searchInvestigations:()=>Z7,openInvestigation:()=>a2,listInvestigations:()=>$7,initInvestigations:()=>o2,getInvestigation:()=>e2,generateReport:()=>Y7,formatInvestigationList:()=>K0,formatInvestigationDetail:()=>J7,formatEvidenceDetail:()=>UJ,collectEvidence:()=>r2,closeInvestigation:()=>t2,addFinding:()=>s2});import{existsSync as p9,mkdirSync as VJ,readFileSync as GJ}from"fs";import{join as WJ}from"path";import{randomUUID as HJ}from"crypto";function X0(){P(n9(),JSON.stringify($$,null,2))}function qJ(){let $=n9();if(!p9($)){$$=[];return}try{$$=JSON.parse(GJ($,"utf-8"))}catch{$$=[]}}function o2($){if(l9=$,!p9($))VJ($,{recursive:!0});qJ()}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 $$=[...$$,X],X0(),X}function r2($,Z,Y,J,Q){let X=p4($);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 $$=$$.map((H)=>H.id===X.id?G:H),X0(),V}function s2($,Z,Y,J,Q=[]){let X=p4($);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 $$=$$.map((H)=>H.id===X.id?G:H),X0(),V}function t2($,Z,Y){let J=p4($);if(!J)return null;let Q={...J,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return $$=$$.map((X)=>X.id===J.id?Q:X),X0(),Q}function e2($){return p4($)}function $7($,Z,Y=20){let J=[...$$];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 $$.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=p4($);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}):
3
+ var m3=Object.defineProperty;var c3=($)=>$;function d3($,Z){this[$]=c3.bind(null,Z)}var q5=($,Z)=>{for(var J in Z)m3($,J,{get:Z[J],enumerable:!0,configurable:!0,set:d3.bind(Z,J)})};var V0=($,Z)=>()=>($&&(Z=$($=0)),Z);import{existsSync as o3}from"fs";function D4(){if(x)return["powershell","-NoProfile","-NonInteractive","-Command"];let $=process.env.SHELL;if($&&o3($))return[$,"-c"];return["bash","-c"]}function C5(){if(x)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function n3($){try{let Z=x?["powershell","-NoProfile","-Command",`Get-Command ${$} -ErrorAction SilentlyContinue`]:["which",$],J=Bun.spawn(Z,{stdout:"pipe",stderr:"pipe"});return await J.exited,J.exitCode===0}catch{return!1}}async function M5(){if(q0!==null)return q0;return q0=await n3("rg"),q0}function V2($){let Z=$.replace(/\\/g,"/");return $8.some((J)=>Z.includes(`/${J}/`)||Z.startsWith(`${J}/`))}var x,N5,MK,q0=null,$8;var s=V0(()=>{x=process.platform==="win32",N5=process.platform==="darwin",MK=process.platform==="linux";$8=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"]});import{existsSync as I$,mkdirSync as W2,readFileSync as B0,writeFileSync as Z8,renameSync as O5,statSync as i3}from"fs";import{join as G$,dirname as j5,relative as a3}from"path";import{createHash as r3,randomUUID as E5}from"crypto";function D5($,Z){if(w$=$,A5=Z,t=G$($,".backup"),t3(),q2=!0,K4=I$(G$(t,".git")),K4)H2=ZJ()}function J8(){return q2}function k($,Z){let J=j5($);if(!I$(J))W2(J,{recursive:!0});let Y=G$(J,`.smolerclaw-${E5().slice(0,8)}.tmp`);if(Z8(Y,Z),O5(Y,$),q2){let Q=$J($);if(Q&&N0.includes(Q))s3(Q,Z)}}function x5($){return r3("sha256").update($).digest("hex")}function s3($,Z){let J=x5(Z),Y=new Date().toISOString(),Q=Buffer.byteLength(Z,"utf-8");u$=[...u$.filter((X)=>X.file!==$),{file:$,sha256:J,size:Q,updatedAt:Y}],e3()}function t3(){let $=G$(w$,L5);if(!I$($)){u$=[];return}try{let Z=JSON.parse(B0($,"utf-8"));if(Z.version!==F5){u$=[];return}u$=Z.checksums||[]}catch{u$=[]}}function e3(){if(!w$)return;let $=G$(w$,L5),Z={checksums:u$,version:F5},J=G$(w$,`.vault-${E5().slice(0,8)}.tmp`);Z8(J,JSON.stringify(Z,null,2)),O5(J,$)}function $J($){try{let Z=a3(w$,$).replace(/\\/g,"/");if(Z.startsWith("..")||Z.startsWith("/"))return null;return Z}catch{return null}}function C0(){let $=[],Z=0;for(let J of N0){let Y=G$(w$,J),Q=I$(Y);if(!Q){$.push({file:J,exists:!1,checksumValid:null,size:0,lastModified:""});continue}let X=0,z="";try{let H=i3(Y);X=H.size,z=H.mtime.toISOString()}catch{}let G=u$.find((H)=>H.file===J),V=null;if(G)try{let H=B0(Y,"utf-8");if(V=x5(H)===G.sha256,!V)Z++}catch{V=!1,Z++}$.push({file:J,exists:Q,checksumValid:V,size:X,lastModified:z})}return{files:$,lastBackup:H2,backupEnabled:K4,totalFiles:$.filter((J)=>J.exists).length,corruptFiles:Z}}function M0($){let Z=["=== Vault Status ==="],J=$.corruptFiles===0?"OK":`ATENCAO (${$.corruptFiles} corrompido(s))`;if(Z.push(`Integridade: ${J}`),Z.push(`Arquivos rastreados: ${$.totalFiles}/${N0.length}`),Z.push(`Backup: ${$.backupEnabled?"ativado":"desativado"}`),$.lastBackup)Z.push(`Ultimo backup: ${new Date($.lastBackup).toLocaleString("pt-BR")}`);Z.push(`
4
+ --- Arquivos ---`);for(let Y of $.files){if(!Y.exists){Z.push(` ${Y.file.padEnd(30)} (nao existe)`);continue}let Q=(Y.size/1024).toFixed(1),X=Y.checksumValid===null?"?":Y.checksumValid?"OK":"CORROMPIDO",z=Y.lastModified?new Date(Y.lastModified).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"}):"";Z.push(` ${Y.file.padEnd(30)} ${Q.padStart(8)} KB [${X}] ${z}`)}return Z.join(`
5
+ `)}async function O0(){if(!w$)return"Error: vault not initialized.";if(!I$(t))W2(t,{recursive:!0});let $=["# Sensitive \u2014 never backup","*.credentials.json","*.tmp",".vault-*.tmp",".smolerclaw-*.tmp","","# Large/transient","rag/","sessions/archive/",""].join(`
6
+ `);if(Z8(G$(t,".gitignore"),$),!I$(G$(t,".git"))){let Z=await p$(["git","init","-b",R5],t);if(!Z.ok)return`Error: git init failed: ${Z.stderr}`;await p$(["git","config","user.email","vault@smolerclaw.local"],t),await p$(["git","config","user.name","smolerclaw-vault"],t)}return K4=!0,"Shadow backup inicializado."}async function x4($){if(!K4)return"Backup nao ativado. Use vault_init_backup primeiro.";try{for(let X of N0){let z=G$(w$,X);if(!I$(z))continue;let G=G$(t,X),V=j5(G);if(!I$(V))W2(V,{recursive:!0});Z8(G,B0(z,"utf-8"))}let Z=G$(A5,"config.json");if(I$(Z))Z8(G$(t,"config.json"),B0(Z,"utf-8"));if(await p$(["git","add","-A"],t),!(await p$(["git","status","--porcelain"],t)).stdout.trim())return"Nenhuma mudanca para backup.";let Y=$||`backup ${new Date().toISOString().slice(0,19)}`,Q=await p$(["git","commit","-m",Y],t);if(!Q.ok)return`Backup commit falhou: ${Q.stderr}`;return H2=new Date().toISOString(),`Backup concluido: ${Y}`}catch(Z){return`Backup falhou: ${Z instanceof Error?Z.message:String(Z)}`}}async function j0(){if(!K4)return"Backup nao ativado.";if(!(await p$(["git","remote","-v"],t)).stdout.trim())return"Nenhum remote configurado. Use: git -C <backup-dir> remote add origin <url>";let Z=await p$(["git","push","-u","origin",R5],t);if(!Z.ok)return`Push falhou: ${Z.stderr}`;return"Sync concluido \u2014 dados enviados para o remote."}function ZJ(){try{let $=Bun.spawnSync(["git","log","-1","--format=%aI"],{cwd:t,stdout:"pipe",stderr:"pipe"});return new TextDecoder().decode($.stdout).trim()||null}catch{return null}}async function p$($,Z){let J=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Y,Q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),X=await J.exited;return{stdout:Y.trim(),stderr:Q.trim(),ok:X===0}}function T5($=30){if(U2(),!K4)return;U0=setInterval(()=>{x4("auto-backup").catch(()=>{})},$*60*1000)}function U2(){if(U0)clearInterval(U0),U0=null}var F5=1,L5="vault-checksums.json",R5="smolerclaw-backup",N0,w$="",A5="",u$,t="",K4=!1,H2=null,q2=!1,U0=null;var e=V0(()=>{N0=["config.json","memos.json","materials.json","decisions.json","tasks.json","finance.json","people.json","projects.json","work-sessions.json","opportunities.json","workflows.json","news-feeds.json","pitwall-baselines.json","rag/rag-index.json"],u$=[]});var b9={};q5(b9,{openUrl:()=>C4,openFile:()=>n8,openApp:()=>N4,getSystemInfo:()=>M4,getRunningApps:()=>i8,getOutlookEvents:()=>v$,getKnownApps:()=>e2,getDateTimeInfo:()=>O4});function t2($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(ZY.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}async function f4($){let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",$],{stdout:"pipe",stderr:"pipe"}),J=setTimeout(()=>Z.kill(),JY),[Y,Q]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),X=await Z.exited;return clearTimeout(J),{stdout:Y,stderr:Q,exitCode:X}}async function N4($,Z){let J=$.toLowerCase().replace(/\s+/g,""),Y=s2[J];if(!Y){let X=Object.keys(s2).join(", ");return`Unknown app: "${$}". Available: ${X}`}if(Z){let X=t2(Z,"argument");if(X)return X}if(!x)return"Error: this command is only available on Windows.";let Q=Z?`Start-Process '${Y}' -ArgumentList '${Z}'`:`Start-Process '${Y}'`;try{let{exitCode:X,stderr:z}=await f4(Q);if(X!==0&&z.trim())return`Error opening ${$}: ${z.trim()}`;return`Opened: ${$}`}catch(X){return`Error opening ${$}: ${X instanceof Error?X.message:String(X)}`}}async function C4($){if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=t2($,"URL");if(Z)return Z;if(!x)return"Error: this command is only available on Windows.";try{let{exitCode:J,stderr:Y}=await f4(`Start-Process '${$}'`);if(J!==0&&Y.trim())return`Error: ${Y.trim()}`;return`Opened in browser: ${$}`}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}async function n8($){let Z=t2($,"file path");if(Z)return Z;if(!x)return"Error: this command is only available on Windows.";try{let{exitCode:J,stderr:Y}=await f4(`Invoke-Item '${$}'`);if(J!==0&&Y.trim())return`Error: ${Y.trim()}`;return`Opened: ${$}`}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}async function i8(){if(!x)return"Error: this command is only available on Windows.";try{let{stdout:Z,stderr:J}=await f4("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(J.trim())return`Error: ${J.trim()}`;return Z.trim()||"No windowed applications running."}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}async function M4(){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:J}=await f4($.join("; "));if(!Z.trim()&&J.trim())return`Error: ${J.trim()}`;return Z.trim()||"System info unavailable."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}async function O4(){let $=new Date,Z=[],J=$.toLocaleDateString("pt-BR",{weekday:"long"}),Y=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),Q=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${J}, ${Y} \u2014 ${Q}`);let X=new Date($.valueOf());X.setDate(X.getDate()+3-(X.getDay()+6)%7);let z=new Date(X.getFullYear(),0,4),G=1+Math.round(((X.getTime()-z.getTime())/86400000-3+(z.getDay()+6)%7)/7);Z.push(`Semana ${G} do ano`);let V=$.getHours();if(V>=8&&V<18)Z.push("Status: horario comercial");else if(V>=18&&V<22)Z.push("Status: pos-expediente");else Z.push("Status: fora do horario comercial");return Z.join(`
7
+ `)}async function v$(){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(`
8
+ `);try{let{stdout:Z}=await f4($);return Z.trim()||"Outlook nao disponivel."}catch{return"Outlook nao disponivel."}}function e2(){return Object.keys(s2)}var ZY,JY=15000,s2;var j4=V0(()=>{s();ZY=/[";`$\n\r|&<>{}()]/;s2={excel:"excel",word:"winword",powerpoint:"powerpnt",outlook:"ms-outlook:",onenote:"onenote",teams:"msteams:",edge:"msedge",chrome:"chrome",firefox:"firefox",calculator:"calc",notepad:"notepad",terminal:"wt",explorer:"explorer",taskmanager:"taskmgr",settings:"ms-settings:",paint:"mspaint",snip:"snippingtool",vscode:"code",cursor:"cursor",postman:"Postman"}});var O7={};q5(O7,{searchInvestigations:()=>B7,openInvestigation:()=>G7,listInvestigations:()=>U7,initInvestigations:()=>K7,getInvestigation:()=>q7,generateReport:()=>N7,formatInvestigationList:()=>B1,formatInvestigationDetail:()=>C7,formatEvidenceDetail:()=>YQ,collectEvidence:()=>V7,closeInvestigation:()=>H7,addFinding:()=>W7});import{existsSync as qZ,mkdirSync as tY,readFileSync as eY}from"fs";import{join as $Q}from"path";import{randomUUID as ZQ}from"crypto";function U1(){k(BZ(),JSON.stringify(Y$,null,2))}function JQ(){let $=BZ();if(!qZ($)){Y$=[];return}try{Y$=JSON.parse(eY($,"utf-8"))}catch{Y$=[]}}function K7($){if(UZ=$,!qZ($))tY($,{recursive:!0});JQ()}function G7($,Z,J,Y=[]){let Q=new Date().toISOString(),X={id:M7(),title:$.trim(),type:Z,status:"aberta",hypothesis:J?.trim(),tags:Y.map((z)=>z.toLowerCase()),evidence:[],findings:[],created:Q,updated:Q};return Y$=[...Y$,X],U1(),X}function V7($,Z,J,Y,Q){let X=e8($);if(!X)return null;let z=Y.trim();if(z.length>HZ)z=z.slice(0,HZ)+`
9
+ ...(truncated, ${Y.length} total chars)`;let G={id:M7(),source:Z,label:J.trim(),content:z,path:Q?.trim(),timestamp:new Date().toISOString()},V={...X,evidence:[...X.evidence,G],status:X.status==="aberta"?"em_andamento":X.status,updated:new Date().toISOString()};return Y$=Y$.map((H)=>H.id===X.id?V:H),U1(),G}function W7($,Z,J,Y,Q=[]){let X=e8($);if(!X)return null;let z=Q.filter((H)=>X.evidence.some((K)=>K.id===H)),G={id:M7(),severity:Z,title:J.trim(),description:Y.trim(),evidence_ids:z,timestamp:new Date().toISOString()},V={...X,findings:[...X.findings,G],updated:new Date().toISOString()};return Y$=Y$.map((H)=>H.id===X.id?V:H),U1(),G}function H7($,Z,J){let Y=e8($);if(!Y)return null;let Q={...Y,status:"concluida",summary:Z.trim(),recommendations:J?.trim(),updated:new Date().toISOString()};return Y$=Y$.map((X)=>X.id===Y.id?Q:X),U1(),Q}function q7($){return e8($)}function U7($,Z,J=20){let Y=[...Y$];if($)Y=Y.filter((Q)=>Q.status===$);if(Z)Y=Y.filter((Q)=>Q.type===Z);return Y.sort((Q,X)=>new Date(X.updated).getTime()-new Date(Q.updated).getTime()).slice(0,J)}function B7($){let Z=$.toLowerCase();return Y$.filter((J)=>J.title.toLowerCase().includes(Z)||J.hypothesis?.toLowerCase().includes(Z)||J.tags.some((Y)=>Y.includes(Z))||J.findings.some((Y)=>Y.title.toLowerCase().includes(Z))||J.summary?.toLowerCase().includes(Z)).sort((J,Y)=>new Date(Y.updated).getTime()-new Date(J.updated).getTime())}function N7($){let Z=e8($);if(!Z)return null;let J=[],Y=(z)=>new Date(z).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),Q={bug:"Bug / Mal funcionamento",feature:"Construcao de funcionalidade",test:"Material para testes",audit:"Auditoria",incident:"Incidente"},X={critical:0,high:1,medium:2,low:3,info:4};if(J.push(`# Investigacao: ${Z.title}`),J.push(""),J.push(`**Tipo:** ${Q[Z.type]}`),J.push(`**Status:** ${Z.status}`),J.push(`**Abertura:** ${Y(Z.created)}`),J.push(`**Ultima atualizacao:** ${Y(Z.updated)}`),Z.tags.length)J.push(`**Tags:** ${Z.tags.join(", ")}`);if(J.push(`**ID:** ${Z.id}`),Z.hypothesis)J.push(""),J.push("## Hipotese"),J.push(Z.hypothesis);if(Z.evidence.length>0){J.push(""),J.push(`## Evidencias (${Z.evidence.length})`);for(let z of Z.evidence){let G=Y(z.timestamp);J.push(""),J.push(`### [${z.id}] ${z.label}`),J.push(`- Fonte: ${z.source}${z.path?` (${z.path})`:""}`),J.push(`- Coletada: ${G}`);let V=z.content.length>2000?z.content.slice(0,2000)+`
10
+ ... (truncado)`:z.content;J.push("```"),J.push(V),J.push("```")}}if(Z.findings.length>0){let z=[...Z.findings].sort((G,V)=>(X[G.severity]??4)-(X[V.severity]??4));J.push(""),J.push(`## Conclusoes (${Z.findings.length})`);for(let G of z){let V=CZ(G.severity);if(J.push(""),J.push(`### ${V} ${G.title}`),J.push(G.description),G.evidence_ids.length>0)J.push(`- Evidencias: ${G.evidence_ids.join(", ")}`)}}if(Z.summary)J.push(""),J.push("## Resumo"),J.push(Z.summary);if(Z.recommendations)J.push(""),J.push("## Recomendacoes"),J.push(Z.recommendations);return J.join(`
11
+ `)}function B1($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((J)=>{let Y=new Date(J.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=NZ(J.status),X=J.evidence.length,z=J.findings.length,G=J.tags.length>0?` [${J.tags.join(", ")}]`:"";return` ${Q} [${Y}] ${J.title} (${J.type}) \u2014 ${X} ev, ${z} concl${G} {${J.id}}`});return`Investigacoes (${$.length}):
10
12
  ${Z.join(`
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(`
14
- Resumo: ${$.summary}`);if($.recommendations)J.push(`Recomendacoes: ${$.recommendations}`);return J.join(`
15
- `)}function UJ($){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)+`
13
+ `)}`}function C7($){let Z=(Q)=>new Date(Q).toLocaleDateString("pt-BR"),J=NZ($.status),Y=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${J}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)Y.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)Y.push(`Tags: ${$.tags.join(", ")}`);Y.push(`
14
+ Evidencias: ${$.evidence.length}`);for(let Q of $.evidence.slice(-5)){let X=Q.content.slice(0,80).replace(/\n/g," ");Y.push(` [${Q.id}] ${Q.source}: ${Q.label} \u2014 "${X}..."`)}if($.evidence.length>5)Y.push(` ... (${$.evidence.length-5} mais)`);Y.push(`
15
+ Conclusoes: ${$.findings.length}`);for(let Q of $.findings)Y.push(` ${CZ(Q.severity)} ${Q.title}`);if($.summary)Y.push(`
16
+ Resumo: ${$.summary}`);if($.recommendations)Y.push(`Recomendacoes: ${$.recommendations}`);return Y.join(`
17
+ `)}function YQ($){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)+`
16
18
  ... (truncado)`:$.content].join(`
17
- `)}function p4($){let Z=$.toLowerCase().trim(),Y=$$.find((Q)=>Q.id===Z);if(Y)return Y;return $$.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 HJ().slice(0,8)}var l9="",$$,n9=()=>WJ(l9,"investigations.json"),u9=50000;var l4=l7(()=>{t();$$=[]});import{readFileSync as Y3}from"fs";import{join as J3,dirname as Q3}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.2.3"}function i7(){let $=$8();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
19
+ `)}function e8($){let Z=$.toLowerCase().trim(),J=Y$.find((Q)=>Q.id===Z);if(J)return J;return Y$.filter((Q)=>Q.title.toLowerCase().includes(Z)).sort((Q,X)=>new Date(X.updated).getTime()-new Date(Q.updated).getTime())[0]||null}function NZ($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function CZ($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function M7(){return ZQ().slice(0,8)}var UZ="",Y$,BZ=()=>$Q(UZ,"investigations.json"),HZ=50000;var $0=V0(()=>{e();Y$=[]});import{readFileSync as u3}from"fs";import{join as p3,dirname as l3}from"path";function U5($){let Z={help:!1,version:!1,noTools:!1,print:!1},J=[],Y=0;while(Y<$.length){let Q=$[Y];switch(Q){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++Y],!Z.model)W0("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++Y],!Z.session)W0("--session requires a value");break;case"--max-tokens":let X=Number($[++Y]);if(!X||X<=0)W0("--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("-"))W0(`Unknown option: ${Q}. Try --help`);J.push(Q)}Y++}if(J.length>0)Z.prompt=J.join(" ");return Z}function H0(){return"1.3.0"}function B5(){let $=H0();console.log(`smolerclaw v${$} \u2014 the micro AI assistant
18
20
 
19
21
  Usage:
20
22
  smolerclaw [options] [prompt]
@@ -42,15 +44,15 @@ Commands (inside TUI):
42
44
  /briefing Daily briefing /news News radar
43
45
  /task Create task /tasks List tasks
44
46
  /open Open Windows app /calendar Outlook calendar
45
- /export Export markdown /exit Quit`)}function e4($){console.error(`smolerclaw: ${$}`),process.exit(2)}import{existsSync as W8,mkdirSync as N3,readFileSync as z5}from"fs";import{homedir as C3}from"os";import{join as T$}from"path";import{existsSync as X3}from"fs";var A=process.platform==="win32",o7=process.platform==="darwin",iX=process.platform==="linux";function Y8(){if(A)return["powershell","-NoProfile","-NonInteractive","-Command"];let $=process.env.SHELL;if($&&X3($))return[$,"-c"];return["bash","-c"]}function a7(){if(A)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function K3($){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 K3("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}/`))}t();var s1=C3(),H8=A?T$(process.env.APPDATA||T$(s1,"AppData","Roaming"),"smolerclaw"):T$(s1,".config","smolerclaw"),J2=A?T$(process.env.LOCALAPPDATA||T$(s1,"AppData","Local"),"smolerclaw"):T$(s1,".local","share","smolerclaw"),m$=T$(H8,"config.json"),E1={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:J2,toolApproval:"auto",language:"auto",maxSessionCost:0};function r1($){if(!W8($))N3($,{recursive:!0})}function V5(){if(r1(H8),r1(J2),r1(T$(J2,"sessions")),A)O3();if(!W8(m$))return P(m$,JSON.stringify(E1,null,2)),{...E1};let $;try{$=JSON.parse(z5(m$,"utf-8"))}catch{return P(m$,JSON.stringify(E1,null,2)),{...E1}}return M3({...E1,...$})}function M3($){let Z={...E1};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($){r1(H8),P(m$,JSON.stringify($,null,2))}function Q2(){return m$}function O3(){let $=T$(s1,".config","smolerclaw","config.json");if(W8($)&&!W8(m$))try{let Z=z5($,"utf-8");r1(H8),P(m$,Z)}catch{}}import{existsSync as E3,readFileSync as j3}from"fs";import{homedir as F3}from"os";import{join as L3}from"path";var G5=L3(F3(),".claude",".credentials.json");function X2(){let $=R3();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 R3(){if(!E3(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 F($,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 P$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var t1=($)=>{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 p extends R{constructor($,Z,Y,J){super(`${p.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 X1({message:Y,cause:t1(Z)});let Q=Z;if($===400)return new $4($,Q,Y,J);if($===401)return new Z4($,Q,Y,J);if($===403)return new Y4($,Q,Y,J);if($===404)return new J4($,Q,Y,J);if($===409)return new Q4($,Q,Y,J);if($===422)return new X4($,Q,Y,J);if($===429)return new K4($,Q,Y,J);if($>=500)return new z4($,Q,Y,J);return new p($,Q,Y,J)}}class e extends p{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class X1 extends p{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class e1 extends X1{constructor({message:$}={}){super({message:$??"Request timed out."})}}class $4 extends p{}class Z4 extends p{}class Y4 extends p{}class J4 extends p{}class Q4 extends p{}class X4 extends p{}class K4 extends p{}class z4 extends p{}var x3=/^[a-z][a-z0-9+.-]*:/i,H5=($)=>{return x3.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 c$="0.80.0";var O5=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function D3(){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 T3=()=>{let $=D3();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":c$,"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":c$,"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":c$,"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=P3();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":c$,"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":c$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function P3(){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=T3())};function j5(){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 V4($){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 F5($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var L5=({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 G4($){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 z$,V$;class d${constructor(){z$.set(this,void 0),V$.set(this,void 0),F(this,z$,new Uint8Array,"f"),F(this,V$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?G4($):$;F(this,z$,D5([U(this,z$,"f"),Z]),"f");let Y=[],J;while((J=S3(U(this,z$,"f"),U(this,V$,"f")))!=null){if(J.carriage&&U(this,V$,"f")==null){F(this,V$,J.index,"f");continue}if(U(this,V$,"f")!=null&&(J.index!==U(this,V$,"f")+1||J.carriage)){Y.push(q2(U(this,z$,"f").subarray(0,U(this,V$,"f")-1))),F(this,z$,U(this,z$,"f").subarray(U(this,V$,"f")),"f"),F(this,V$,null,"f");continue}let Q=U(this,V$,"f")!==null?J.preceding-1:J.preceding,X=q2(U(this,z$,"f").subarray(0,Q));Y.push(X),F(this,z$,U(this,z$,"f").subarray(J.index),"f"),F(this,V$,null,"f")}return Y}flush(){if(!U(this,z$,"f").length)return[];return this.decode(`
46
- `)}}z$=new WeakMap,V$=new WeakMap;d$.NEWLINE_CHARS=new Set([`
47
- `,"\r"]);d$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function S3($,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 $;i(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(M8))}`);return};function W4(){}function C8($,Z,Y){if(!Z||M8[$]>M8[Y])return W4;else return Z[$].bind(Z)}var b3={error:W4,warn:W4,info:W4,debug:W4},P5=new WeakMap;function i($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return b3;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 w$=($)=>{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 H4;class G${constructor($,Z,Y){this.iterator=$,H4.set(this,void 0),this.controller=Z,F(this,H4,Y,"f")}static fromSSEResponse($,Z,Y){let J=!1,Q=Y?i(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 k3($,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 p(void 0,B8(V.data)??V.data,void 0,$.headers)}K=!0}catch(V){if(P$(V))return;throw V}finally{if(!K)Z.abort()}}return new G$(X,Z,Y)}static fromReadableStream($,Z,Y){let J=!1;async function*Q(){let K=new d$,V=V4($);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(P$(V))return;throw V}finally{if(!K)Z.abort()}}return new G$(X,Z,Y)}[(H4=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 G$(()=>J($),this.controller,U(this,H4,"f")),new G$(()=>J(Z),this.controller,U(this,H4,"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=G4(JSON.stringify(J)+`
48
- `);Y.enqueue(X)}catch(J){Y.error(J)}},async cancel(){await Z.return?.()}})}}async function*k3($,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 d$,Q=V4($.body);for await(let X of y3(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*y3($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let J=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?G4(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]=_3($,":");if(J.startsWith(" "))J=J.substring(1);if(Z==="event")this.event=J;else if(Z==="data")this.data.push(J);return null}}function _3($,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(i($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return G$.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 i($).debug(`[${J}] response parsed`,w$({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 q4;class K1 extends Promise{constructor($,Z,Y=O8){super((J)=>{J(null)});this.responsePromise=Z,this.parseResponse=Y,q4.set(this,void 0),F(this,q4,$,"f")}_thenUnwrap($){return new K1(U(this,q4,"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,q4,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}q4=new WeakMap;var E8;class N2{constructor($,Z,Y,J){E8.set(this,void 0),F(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 j8 extends K1{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 U4 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 z1($,Z,Y){return M2(),new File($,Z??"unknown_file",Y)}function B4($,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 j1=async($,Z,Y=!0)=>{return{...$,body:await v3($.body,Z,Y)}},I5=new WeakMap;function f3($){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 v3=async($,Z,Y=!0)=>{if(!await f3(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},g3=($)=>$ 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,z1([await Y.blob()],B4(Y,J),Q))}else if(O2(Y))$.append(Z,z1([await new Response(N8(Y)).blob()],B4(Y,J)));else if(g3(Y))$.append(Z,z1([Y],B4(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",m3=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&S5($),c3=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function F8($,Z,Y){if(M2(),$=await $,Z||(Z=B4($,!0)),m3($)){if($ instanceof File&&Z==null&&Y==null)return $;return z1([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(c3($)){let Q=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),z1(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 z1(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}`:""}${d3($)}`)}return Z}function d3($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class g{constructor($){this._client=$}}var b5=Symbol.for("brand.privateNullableHeaders");function*p3($){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 D=($)=>{let Z=new Headers,Y=new Set;for(let J of $){let Q=new Set;for(let[X,K]of p3(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 N4=Symbol("anthropic.sdk.stainlessHelper");function L8($){return typeof $==="object"&&$!==null&&N4 in $}function j2($,Z){let Y=new Set;if($){for(let J of $)if(L8(J))Y.add(J[N4])}if(Z)for(let J of Z){if(L8(J))Y.add(J[N4]);if(Array.isArray(J.content)){for(let Q of J.content)if(L8(Q))Y.add(Q[N4])}}return Array.from(Y)}function R8($,Z){let Y=j2($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function k5($){if(L8($))return{"x-stainless-helper":$[N4]};return{}}function _5($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var y5=Object.freeze(Object.create(null)),l3=($=_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],L=(Q?encodeURIComponent:$)(""+E);if(N!==J.length&&(E==null||typeof E==="object"&&E.toString===Object.getPrototypeOf(Object.getPrototypeOf(E.hasOwnProperty??y5)??y5)?.toString))L=E+"",X.push({start:z.length+M.length,length:L.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?"":L)},""),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 L=" ".repeat(E.start-z),w="^".repeat(E.length);return z=E.start+E.length,N+L+w},"");throw new R(`Path parameters result in path with invalid segments:
50
- ${X.map((N)=>N.error).join(`
47
+ /export Export markdown /exit Quit`)}function W0($){console.error(`smolerclaw: ${$}`),process.exit(2)}s();e();import{existsSync as E0,mkdirSync as JJ,readFileSync as P5}from"fs";import{homedir as YJ}from"os";import{join as S$}from"path";var Q8=YJ(),F0=x?S$(process.env.APPDATA||S$(Q8,"AppData","Roaming"),"smolerclaw"):S$(Q8,".config","smolerclaw"),B2=x?S$(process.env.LOCALAPPDATA||S$(Q8,"AppData","Local"),"smolerclaw"):S$(Q8,".local","share","smolerclaw"),l$=S$(F0,"config.json"),T4={model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:B2,toolApproval:"auto",language:"auto",maxSessionCost:0};function Y8($){if(!E0($))JJ($,{recursive:!0})}function I5(){if(Y8(F0),Y8(B2),Y8(S$(B2,"sessions")),x)XJ();if(!E0(l$))return k(l$,JSON.stringify(T4,null,2)),{...T4};let $;try{$=JSON.parse(P5(l$,"utf-8"))}catch{return k(l$,JSON.stringify(T4,null,2)),{...T4}}return QJ({...T4,...$})}function QJ($){let Z={...T4};if(typeof $.model==="string"&&$.model.trim())Z.model=$.model;if(typeof $.maxTokens==="number"&&$.maxTokens>0&&$.maxTokens<=1e5)Z.maxTokens=$.maxTokens;if(typeof $.maxHistory==="number"&&$.maxHistory>0&&$.maxHistory<=1000)Z.maxHistory=$.maxHistory;if(typeof $.systemPrompt==="string")Z.systemPrompt=$.systemPrompt;if(typeof $.skillsDir==="string"&&$.skillsDir.trim())Z.skillsDir=$.skillsDir;if(typeof $.dataDir==="string"&&$.dataDir.trim())Z.dataDir=$.dataDir;let J=["auto","confirm-writes","confirm-all"];if(typeof $.toolApproval==="string"&&J.includes($.toolApproval))Z.toolApproval=$.toolApproval;if(typeof $.language==="string")Z.language=$.language;if(typeof $.maxSessionCost==="number"&&$.maxSessionCost>=0)Z.maxSessionCost=$.maxSessionCost;return Z}function L0($){Y8(F0),k(l$,JSON.stringify($,null,2))}function N2(){return l$}function XJ(){let $=S$(Q8,".config","smolerclaw","config.json");if(E0($)&&!E0(l$))try{let Z=P5($,"utf-8");Y8(F0),k(l$,Z)}catch{}}import{existsSync as zJ,readFileSync as KJ}from"fs";import{homedir as GJ}from"os";import{join as VJ}from"path";var w5=VJ(GJ(),".claude",".credentials.json");function C2(){let $=WJ();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 WJ(){if(!zJ(w5))return null;try{let Z=JSON.parse(KJ(w5,"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 M2(){try{return C2()}catch{return null}}function S5($){return`sub:${$.subscriptionType||"pro"}`}function L($,Z,J,Y,Q){if(Y==="m")throw TypeError("Private method is not writable");if(Y==="a"&&!Q)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!Q:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return Y==="a"?Q.call($,J):Q?Q.value=J:Z.set($,J),J}function N($,Z,J,Y){if(J==="a"&&!Y)throw TypeError("Private accessor was defined without a getter");if(typeof Z==="function"?$!==Z||!Y:!Z.has($))throw TypeError("Cannot read private member from an object whose class did not declare it");return J==="m"?Y:J==="a"?Y.call($):Y?Y.value:Z.get($)}var O2=function(){let{crypto:$}=globalThis;if($?.randomUUID)return O2=$.randomUUID.bind($),$.randomUUID();let Z=new Uint8Array(1),J=$?()=>$.getRandomValues(Z)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(Y)=>(+Y^J()&15>>+Y/4).toString(16))};function k$($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var X8=($)=>{if($ instanceof Error)return $;if(typeof $==="object"&&$!==null){try{if(Object.prototype.toString.call($)==="[object Error]"){let Z=Error($.message,$.cause?{cause:$.cause}:{});if($.stack)Z.stack=$.stack;if($.cause&&!Z.cause)Z.cause=$.cause;if($.name)Z.name=$.name;return Z}}catch{}try{return Error(JSON.stringify($))}catch{}}return Error($)};class D extends Error{}class n extends D{constructor($,Z,J,Y){super(`${n.makeMessage($,Z,J)}`);this.status=$,this.headers=Y,this.requestID=Y?.get("request-id"),this.error=Z}static makeMessage($,Z,J){let Y=Z?.message?typeof Z.message==="string"?Z.message:JSON.stringify(Z.message):Z?JSON.stringify(Z):J;if($&&Y)return`${$} ${Y}`;if($)return`${$} status code (no body)`;if(Y)return Y;return"(no status code or body)"}static generate($,Z,J,Y){if(!$||!Y)return new G4({message:J,cause:X8(Z)});let Q=Z;if($===400)return new K8($,Q,J,Y);if($===401)return new G8($,Q,J,Y);if($===403)return new V8($,Q,J,Y);if($===404)return new W8($,Q,J,Y);if($===409)return new H8($,Q,J,Y);if($===422)return new q8($,Q,J,Y);if($===429)return new U8($,Q,J,Y);if($>=500)return new B8($,Q,J,Y);return new n($,Q,J,Y)}}class J$ extends n{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class G4 extends n{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class z8 extends G4{constructor({message:$}={}){super({message:$??"Request timed out."})}}class K8 extends n{}class G8 extends n{}class V8 extends n{}class W8 extends n{}class H8 extends n{}class q8 extends n{}class U8 extends n{}class B8 extends n{}var qJ=/^[a-z][a-z0-9+.-]*:/i,k5=($)=>{return qJ.test($)},j2=($)=>(j2=Array.isArray,j2($)),E2=j2;function R0($){if(typeof $!=="object")return{};return $??{}}function F2($){if(!$)return!0;for(let Z in $)return!1;return!0}function b5($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var y5=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new D(`${$} must be an integer`);if(Z<0)throw new D(`${$} must be a positive integer`);return Z};var A0=($)=>{try{return JSON.parse($)}catch(Z){return}};var _5=($)=>new Promise((Z)=>setTimeout(Z,$));var o$="0.80.0";var g5=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function UJ(){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 BJ=()=>{let $=UJ();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o$,"X-Stainless-OS":v5(Deno.build.os),"X-Stainless-Arch":h5(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":o$,"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":o$,"X-Stainless-OS":v5(globalThis.process.platform??"unknown"),"X-Stainless-Arch":h5(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=NJ();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":o$,"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":o$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function NJ(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:J}of $){let Y=J.exec(navigator.userAgent);if(Y){let Q=Y[1]||0,X=Y[2]||0,z=Y[3]||0;return{browser:Z,version:`${Q}.${X}.${z}`}}}return null}var h5=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},v5=($)=>{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"},f5,m5=()=>{return f5??(f5=BJ())};function c5(){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 L2(...$){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 D0($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return L2({start(){},async pull(J){let{done:Y,value:Q}=await Z.next();if(Y)J.close();else J.enqueue(Q)},async cancel(){await Z.return?.()}})}function N8($){if($[Symbol.asyncIterator])return $;let Z=$.getReader();return{async next(){try{let J=await Z.read();if(J?.done)Z.releaseLock();return J}catch(J){throw Z.releaseLock(),J}},async return(){let J=Z.cancel();return Z.releaseLock(),await J,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function d5($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),J=Z.cancel();Z.releaseLock(),await J}var u5=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function p5($){return Object.entries($).filter(([Z,J])=>typeof J<"u").map(([Z,J])=>{if(typeof J==="string"||typeof J==="number"||typeof J==="boolean")return`${encodeURIComponent(Z)}=${encodeURIComponent(J)}`;if(J===null)return`${encodeURIComponent(Z)}=`;throw new D(`Cannot stringify type ${typeof J}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}function n5($){let Z=0;for(let Q of $)Z+=Q.length;let J=new Uint8Array(Z),Y=0;for(let Q of $)J.set(Q,Y),Y+=Q.length;return J}var l5;function C8($){let Z;return(l5??(Z=new globalThis.TextEncoder,l5=Z.encode.bind(Z)))($)}var o5;function R2($){let Z;return(o5??(Z=new globalThis.TextDecoder,o5=Z.decode.bind(Z)))($)}var V$,W$;class n${constructor(){V$.set(this,void 0),W$.set(this,void 0),L(this,V$,new Uint8Array,"f"),L(this,W$,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?C8($):$;L(this,V$,n5([N(this,V$,"f"),Z]),"f");let J=[],Y;while((Y=OJ(N(this,V$,"f"),N(this,W$,"f")))!=null){if(Y.carriage&&N(this,W$,"f")==null){L(this,W$,Y.index,"f");continue}if(N(this,W$,"f")!=null&&(Y.index!==N(this,W$,"f")+1||Y.carriage)){J.push(R2(N(this,V$,"f").subarray(0,N(this,W$,"f")-1))),L(this,V$,N(this,V$,"f").subarray(N(this,W$,"f")),"f"),L(this,W$,null,"f");continue}let Q=N(this,W$,"f")!==null?Y.preceding-1:Y.preceding,X=R2(N(this,V$,"f").subarray(0,Q));J.push(X),L(this,V$,N(this,V$,"f").subarray(Y.index),"f"),L(this,W$,null,"f")}return J}flush(){if(!N(this,V$,"f").length)return[];return this.decode(`
48
+ `)}}V$=new WeakMap,W$=new WeakMap;n$.NEWLINE_CHARS=new Set([`
49
+ `,"\r"]);n$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function OJ($,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 i5($){for(let Y=0;Y<$.length-1;Y++){if($[Y]===10&&$[Y+1]===10)return Y+2;if($[Y]===13&&$[Y+1]===13)return Y+2;if($[Y]===13&&$[Y+1]===10&&Y+3<$.length&&$[Y+2]===13&&$[Y+3]===10)return Y+4}return-1}var T0={off:0,error:200,warn:300,info:400,debug:500},A2=($,Z,J)=>{if(!$)return;if(b5(T0,$))return $;a(J).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(T0))}`);return};function M8(){}function x0($,Z,J){if(!Z||T0[$]>T0[J])return M8;else return Z[$].bind(Z)}var jJ={error:M8,warn:M8,info:M8,debug:M8},a5=new WeakMap;function a($){let Z=$.logger,J=$.logLevel??"off";if(!Z)return jJ;let Y=a5.get(Z);if(Y&&Y[0]===J)return Y[1];let Q={error:x0("error",Z,J),warn:x0("warn",Z,J),info:x0("info",Z,J),debug:x0("debug",Z,J)};return a5.set(Z,[J,Q]),Q}var b$=($)=>{if($.options)$.options={...$.options},delete $.options.headers;if($.headers)$.headers=Object.fromEntries(($.headers instanceof Headers?[...$.headers]:Object.entries($.headers)).map(([Z,J])=>[Z,Z.toLowerCase()==="x-api-key"||Z.toLowerCase()==="authorization"||Z.toLowerCase()==="cookie"||Z.toLowerCase()==="set-cookie"?"***":J]));if("retryOfRequestLogID"in $){if($.retryOfRequestLogID)$.retryOf=$.retryOfRequestLogID;delete $.retryOfRequestLogID}return $};var O8;class H${constructor($,Z,J){this.iterator=$,O8.set(this,void 0),this.controller=Z,L(this,O8,J,"f")}static fromSSEResponse($,Z,J){let Y=!1,Q=J?a(J):console;async function*X(){if(Y)throw new D("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let z=!1;try{for await(let G of EJ($,Z)){if(G.event==="completion")try{yield JSON.parse(G.data)}catch(V){throw Q.error("Could not parse message into JSON:",G.data),Q.error("From chunk:",G.raw),V}if(G.event==="message_start"||G.event==="message_delta"||G.event==="message_stop"||G.event==="content_block_start"||G.event==="content_block_delta"||G.event==="content_block_stop")try{yield JSON.parse(G.data)}catch(V){throw Q.error("Could not parse message into JSON:",G.data),Q.error("From chunk:",G.raw),V}if(G.event==="ping")continue;if(G.event==="error")throw new n(void 0,A0(G.data)??G.data,void 0,$.headers)}z=!0}catch(G){if(k$(G))return;throw G}finally{if(!z)Z.abort()}}return new H$(X,Z,J)}static fromReadableStream($,Z,J){let Y=!1;async function*Q(){let z=new n$,G=N8($);for await(let V of G)for(let H of z.decode(V))yield H;for(let V of z.flush())yield V}async function*X(){if(Y)throw new D("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");Y=!0;let z=!1;try{for await(let G of Q()){if(z)continue;if(G)yield JSON.parse(G)}z=!0}catch(G){if(k$(G))return;throw G}finally{if(!z)Z.abort()}}return new H$(X,Z,J)}[(O8=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],J=this.iterator(),Y=(Q)=>{return{next:()=>{if(Q.length===0){let X=J.next();$.push(X),Z.push(X)}return Q.shift()}}};return[new H$(()=>Y($),this.controller,N(this,O8,"f")),new H$(()=>Y(Z),this.controller,N(this,O8,"f"))]}toReadableStream(){let $=this,Z;return L2({async start(){Z=$[Symbol.asyncIterator]()},async pull(J){try{let{value:Y,done:Q}=await Z.next();if(Q)return J.close();let X=C8(JSON.stringify(Y)+`
50
+ `);J.enqueue(X)}catch(Y){J.error(Y)}},async cancel(){await Z.return?.()}})}}async function*EJ($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new D("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 D("Attempted to iterate over a response with no body")}let J=new r5,Y=new n$,Q=N8($.body);for await(let X of FJ(Q))for(let z of Y.decode(X)){let G=J.decode(z);if(G)yield G}for(let X of Y.flush()){let z=J.decode(X);if(z)yield z}}async function*FJ($){let Z=new Uint8Array;for await(let J of $){if(J==null)continue;let Y=J instanceof ArrayBuffer?new Uint8Array(J):typeof J==="string"?C8(J):J,Q=new Uint8Array(Z.length+Y.length);Q.set(Z),Q.set(Y,Z.length),Z=Q;let X;while((X=i5(Z))!==-1)yield Z.slice(0,X),Z=Z.slice(X)}if(Z.length>0)yield Z}class r5{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(`
51
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],Q}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,J,Y]=LJ($,":");if(Y.startsWith(" "))Y=Y.substring(1);if(Z==="event")this.event=Y;else if(Z==="data")this.data.push(Y);return null}}function LJ($,Z){let J=$.indexOf(Z);if(J!==-1)return[$.substring(0,J),Z,$.substring(J+Z.length)];return[$,"",""]}async function P0($,Z){let{response:J,requestLogID:Y,retryOfRequestLogID:Q,startTime:X}=Z,z=await(async()=>{if(Z.options.stream){if(a($).debug("response",J.status,J.url,J.headers,J.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(J,Z.controller);return H$.fromSSEResponse(J,Z.controller)}if(J.status===204)return null;if(Z.options.__binaryResponse)return J;let V=J.headers.get("content-type")?.split(";")[0]?.trim();if(V?.includes("application/json")||V?.endsWith("+json")){if(J.headers.get("content-length")==="0")return;let B=await J.json();return D2(B,J)}return await J.text()})();return a($).debug(`[${Y}] response parsed`,b$({retryOfRequestLogID:Q,url:J.url,status:J.status,body:z,durationMs:Date.now()-X})),z}function D2($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var j8;class V4 extends Promise{constructor($,Z,J=P0){super((Y)=>{Y(null)});this.responsePromise=Z,this.parseResponse=J,j8.set(this,void 0),L(this,j8,$,"f")}_thenUnwrap($){return new V4(N(this,j8,"f"),this.responsePromise,async(Z,J)=>D2($(await this.parseResponse(Z,J),J),J.response))}asResponse(){return this.responsePromise.then(($)=>$.response)}async withResponse(){let[$,Z]=await Promise.all([this.parse(),this.asResponse()]);return{data:$,response:Z,request_id:Z.headers.get("request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(($)=>this.parseResponse(N(this,j8,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}j8=new WeakMap;var I0;class x2{constructor($,Z,J,Y){I0.set(this,void 0),L(this,I0,$,"f"),this.options=Y,this.response=Z,this.body=J}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let $=this.nextPageRequestOptions();if(!$)throw new D("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await N(this,I0,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(I0=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class w0 extends V4{constructor($,Z,J){super($,Z,async(Y,Q)=>new J(Y,Q.response,await P0(Y,Q),Q.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class L$ extends x2{constructor($,Z,J,Y){super($,Z,J,Y);this.data=J.data||[],this.has_more=J.has_more||!1,this.first_id=J.first_id||null,this.last_id=J.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){let Z=this.first_id;if(!Z)return null;return{...this.options,query:{...R0(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...R0(this.options.query),after_id:$}}}}class E8 extends x2{constructor($,Z,J,Y){super($,Z,J,Y);this.data=J.data||[],this.has_more=J.has_more||!1,this.next_page=J.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let $=this.next_page;if(!$)return null;return{...this.options,query:{...R0(this.options.query),page:$}}}}var P2=()=>{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 W4($,Z,J){return P2(),new File($,Z??"unknown_file",J)}function F8($,Z){let J=typeof $==="object"&&$!==null&&(("name"in $)&&$.name&&String($.name)||("url"in $)&&$.url&&String($.url)||("filename"in $)&&$.filename&&String($.filename)||("path"in $)&&$.path&&String($.path))||"";return Z?J.split(/[\\/]/).pop()||void 0:J}var I2=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var P4=async($,Z,J=!0)=>{return{...$,body:await DJ($.body,Z,J)}},s5=new WeakMap;function AJ($){let Z=typeof $==="function"?$:$.fetch,J=s5.get(Z);if(J)return J;let Y=(async()=>{try{let Q="Response"in Z?Z.Response:(await Z("data:,")).constructor,X=new FormData;if(X.toString()===await new Q(X).text())return!1;return!0}catch{return!0}})();return s5.set(Z,Y),Y}var DJ=async($,Z,J=!0)=>{if(!await AJ(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let Y=new FormData;return await Promise.all(Object.entries($||{}).map(([Q,X])=>T2(Y,Q,X,J))),Y},xJ=($)=>$ instanceof Blob&&("name"in $);var T2=async($,Z,J,Y)=>{if(J===void 0)return;if(J==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof J==="string"||typeof J==="number"||typeof J==="boolean")$.append(Z,String(J));else if(J instanceof Response){let Q={},X=J.headers.get("Content-Type");if(X)Q={type:X};$.append(Z,W4([await J.blob()],F8(J,Y),Q))}else if(I2(J))$.append(Z,W4([await new Response(D0(J)).blob()],F8(J,Y)));else if(xJ(J))$.append(Z,W4([J],F8(J,Y),{type:J.type}));else if(Array.isArray(J))await Promise.all(J.map((Q)=>T2($,Z+"[]",Q,Y)));else if(typeof J==="object")await Promise.all(Object.entries(J).map(([Q,X])=>T2($,`${Z}[${Q}]`,X,Y)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${J} instead`)};var t5=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",TJ=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&t5($),PJ=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function S0($,Z,J){if(P2(),$=await $,Z||(Z=F8($,!0)),TJ($)){if($ instanceof File&&Z==null&&J==null)return $;return W4([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...J})}if(PJ($)){let Q=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),W4(await w2(Q),Z,J)}let Y=await w2($);if(!J?.type){let Q=Y.find((X)=>typeof X==="object"&&("type"in X)&&X.type);if(typeof Q==="string")J={...J,type:Q}}return W4(Y,Z,J)}async function w2($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(t5($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(I2($))for await(let J of $)Z.push(...await w2(J));else{let J=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${J?`; constructor: ${J}`:""}${IJ($)}`)}return Z}function IJ($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((J)=>`"${J}"`).join(", ")}]`}class c{constructor($){this._client=$}}var e5=Symbol.for("brand.privateNullableHeaders");function*SJ($){if(!$)return;if(e5 in $){let{values:Y,nulls:Q}=$;yield*Y.entries();for(let X of Q)yield[X,null];return}let Z=!1,J;if($ instanceof Headers)J=$.entries();else if(E2($))J=$;else Z=!0,J=Object.entries($??{});for(let Y of J){let Q=Y[0];if(typeof Q!=="string")throw TypeError("expected header name to be a string");let X=E2(Y[1])?Y[1]:[Y[1]],z=!1;for(let G of X){if(G===void 0)continue;if(Z&&!z)z=!0,yield[Q,null];yield[Q,G]}}}var P=($)=>{let Z=new Headers,J=new Set;for(let Y of $){let Q=new Set;for(let[X,z]of SJ(Y)){let G=X.toLowerCase();if(!Q.has(G))Z.delete(X),Q.add(G);if(z===null)Z.delete(X),J.add(G);else Z.append(X,z),J.delete(G)}}return{[e5]:!0,values:Z,nulls:J}};var L8=Symbol("anthropic.sdk.stainlessHelper");function k0($){return typeof $==="object"&&$!==null&&L8 in $}function S2($,Z){let J=new Set;if($){for(let Y of $)if(k0(Y))J.add(Y[L8])}if(Z)for(let Y of Z){if(k0(Y))J.add(Y[L8]);if(Array.isArray(Y.content)){for(let Q of Y.content)if(k0(Q))J.add(Q[L8])}}return Array.from(J)}function b0($,Z){let J=S2($,Z);if(J.length===0)return{};return{"x-stainless-helper":J.join(", ")}}function $9($){if(k0($))return{"x-stainless-helper":$[L8]};return{}}function J9($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Z9=Object.freeze(Object.create(null)),kJ=($=J9)=>function(J,...Y){if(J.length===1)return J[0];let Q=!1,X=[],z=J.reduce((K,M,B)=>{if(/[?#]/.test(M))Q=!0;let O=Y[B],j=(Q?encodeURIComponent:$)(""+O);if(B!==Y.length&&(O==null||typeof O==="object"&&O.toString===Object.getPrototypeOf(Object.getPrototypeOf(O.hasOwnProperty??Z9)??Z9)?.toString))j=O+"",X.push({start:K.length+M.length,length:j.length,error:`Value of type ${Object.prototype.toString.call(O).slice(8,-1)} is not a valid path parameter`});return K+M+(B===Y.length?"":j)},""),G=z.split(/[?#]/,1)[0],V=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,H;while((H=V.exec(G))!==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((K,M)=>K.start-M.start),X.length>0){let K=0,M=X.reduce((B,O)=>{let j=" ".repeat(O.start-K),A="^".repeat(O.length);return K=O.start+O.length,B+j+A},"");throw new D(`Path parameters result in path with invalid segments:
52
+ ${X.map((B)=>B.error).join(`
51
53
  `)}
52
- ${K}
53
- ${M}`)}return K},v=l3(_5);class C4 extends g{list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/files",M$,{query:J,...Z,headers:D([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(v`/v1/files/${$}`,{...Y,headers:D([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:J}=Z??{};return this._client.get(v`/v1/files/${$}/content`,{...Y,headers:D([{"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(v`/v1/files/${$}`,{...Y,headers:D([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/files",j1({body:J,...Z,headers:D([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},k5(J.file),Z?.headers])},this._client))}}class M4 extends g{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(v`/v1/models/${$}?beta=true`,{...Y,headers:D([{...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:D([{...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 F2($,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 L2($,Z,Y)}function L2($,Z,Y){let J=null,Q=$.content.map((X)=>{if(X.type==="text"){let K=o3(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 o3($,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 a3=($)=>{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},F1=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),F1($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),F1($);case"string":let J=$[$.length-2];if(J?.type==="delimiter")return $=$.slice(0,$.length-1),F1($);else if(J?.type==="brace"&&J.value==="{")return $=$.slice(0,$.length-1),F1($);break;case"delimiter":return $=$.slice(0,$.length-1),F1($);break}return $},r3=($)=>{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 $},s3=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},x8=($)=>JSON.parse(s3(r3(F1(a3($)))));var q$,u$,L1,O4,D8,E4,j4,T8,F4,I$,L4,P8,w8,V1,I8,S8,R4,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 A4{constructor($,Z){q$.add(this),this.messages=[],this.receivedMessages=[],u$.set(this,void 0),L1.set(this,null),this.controller=new AbortController,O4.set(this,void 0),D8.set(this,()=>{}),E4.set(this,()=>{}),j4.set(this,void 0),T8.set(this,()=>{}),F4.set(this,()=>{}),I$.set(this,{}),L4.set(this,!1),P8.set(this,!1),w8.set(this,!1),V1.set(this,!1),I8.set(this,void 0),S8.set(this,void 0),R4.set(this,void 0),b8.set(this,(Y)=>{if(F(this,P8,!0,"f"),P$(Y))Y=new e;if(Y instanceof e)return F(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)))}),F(this,O4,new Promise((Y,J)=>{F(this,D8,Y,"f"),F(this,E4,J,"f")}),"f"),F(this,j4,new Promise((Y,J)=>{F(this,T8,Y,"f"),F(this,F4,J,"f")}),"f"),U(this,O4,"f").catch(()=>{}),U(this,j4,"f").catch(()=>{}),F(this,L1,$,"f"),F(this,R4,Z?.logger??console,"f")}get response(){return U(this,I8,"f")}get request_id(){return U(this,S8,"f")}async withResponse(){F(this,V1,!0,"f");let $=await U(this,O4,"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 A4(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let Q=new A4(Z,{logger:J});for(let X of Z.messages)Q._addMessageParam(X);return F(Q,L1,{...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,q$,"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,q$,"m",x2).call(this,V);if(K.controller.signal?.aborted)throw new e;U(this,q$,"m",D2).call(this)}finally{if(J&&Q)J.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;F(this,I8,$,"f"),F(this,S8,$?.headers.get("request-id"),"f"),U(this,D8,"f").call(this,$),this._emit("connect")}get ended(){return U(this,L4,"f")}get errored(){return U(this,P8,"f")}get aborted(){return U(this,w8,"f")}abort(){this.controller.abort()}on($,Z){return(U(this,I$,"f")[$]||(U(this,I$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=U(this,I$,"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,I$,"f")[$]||(U(this,I$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(F(this,V1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){F(this,V1,!0,"f"),await U(this,j4,"f")}get currentMessage(){return U(this,u$,"f")}async finalMessage(){return await this.done(),U(this,q$,"m",R2).call(this)}async finalText(){return await this.done(),U(this,q$,"m",f5).call(this)}_emit($,...Z){if(U(this,L4,"f"))return;if($==="end")F(this,L4,!0,"f"),U(this,T8,"f").call(this);let Y=U(this,I$,"f")[$];if(Y)U(this,I$,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!U(this,V1,"f")&&!Y?.length)Promise.reject(J);U(this,E4,"f").call(this,J),U(this,F4,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!U(this,V1,"f")&&!Y?.length)Promise.reject(J);U(this,E4,"f").call(this,J),U(this,F4,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",U(this,q$,"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,q$,"m",A2).call(this),this._connected(null);let Q=G$.fromReadableStream($,this.controller);for await(let X of Q)U(this,q$,"m",x2).call(this,X);if(Q.controller.signal?.aborted)throw new e;U(this,q$,"m",D2).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(u$=new WeakMap,L1=new WeakMap,O4=new WeakMap,D8=new WeakMap,E4=new WeakMap,j4=new WeakMap,T8=new WeakMap,F4=new WeakMap,I$=new WeakMap,L4=new WeakMap,P8=new WeakMap,w8=new WeakMap,V1=new WeakMap,I8=new WeakMap,S8=new WeakMap,R4=new WeakMap,b8=new WeakMap,q$=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;F(this,u$,void 0,"f")},x2=function(Z){if(this.ended)return;let Y=U(this,q$,"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(F2(Y,U(this,L1,"f"),{logger:U(this,R4,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{F(this,u$,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,u$,"f");if(!Z)throw new R("request ended without sending any chunks");return F(this,u$,void 0,"f"),F2(Z,U(this,L1,"f"),{logger:U(this,R4,"f")})},v5=function(Z){let Y=U(this,u$,"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 G$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function c5($){}class R1 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:
54
+ ${z}
55
+ ${M}`)}return z},m=kJ(J9);class R8 extends c{list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/files",L$,{query:Y,...Z,headers:P([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(m`/v1/files/${$}`,{...J,headers:P([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},J?.headers])})}download($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/files/${$}/content`,{...J,headers:P([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},J?.headers]),__binaryResponse:!0})}retrieveMetadata($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/files/${$}`,{...J,headers:P([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},J?.headers])})}upload($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/files",P4({body:Y,...Z,headers:P([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},$9(Y.file),Z?.headers])},this._client))}}class A8 extends c{retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/models/${$}?beta=true`,{...J,headers:P([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/models?beta=true",L$,{query:Y,...Z,headers:P([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers])})}}var y0={"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 Y9($){return $?.output_format??$?.output_config?.format}function k2($,Z,J){let Y=Y9(Z);if(!Z||!("parse"in(Y??{})))return{...$,content:$.content.map((Q)=>{if(Q.type==="text"){let X=Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(X,"parsed",{get(){return J.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return Q}),parsed_output:null};return b2($,Z,J)}function b2($,Z,J){let Y=null,Q=$.content.map((X)=>{if(X.type==="text"){let z=_J(Z,X.text);if(Y===null)Y=z;let G=Object.defineProperty({...X},"parsed_output",{value:z,enumerable:!1});return Object.defineProperty(G,"parsed",{get(){return J.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),z},enumerable:!1})}return X});return{...$,content:Q,parsed_output:Y}}function _J($,Z){let J=Y9($);if(J?.type!=="json_schema")return null;try{if("parse"in J)return J.parse(Z);return JSON.parse(Z)}catch(Y){throw new D(`Failed to parse structured output: ${Y}`)}}var hJ=($)=>{let Z=0,J=[];while(Z<$.length){let Y=$[Z];if(Y==="\\"){Z++;continue}if(Y==="{"){J.push({type:"brace",value:"{"}),Z++;continue}if(Y==="}"){J.push({type:"brace",value:"}"}),Z++;continue}if(Y==="["){J.push({type:"paren",value:"["}),Z++;continue}if(Y==="]"){J.push({type:"paren",value:"]"}),Z++;continue}if(Y===":"){J.push({type:"separator",value:":"}),Z++;continue}if(Y===","){J.push({type:"delimiter",value:","}),Z++;continue}if(Y==='"'){let G="",V=!1;Y=$[++Z];while(Y!=='"'){if(Z===$.length){V=!0;break}if(Y==="\\"){if(Z++,Z===$.length){V=!0;break}G+=Y+$[Z],Y=$[++Z]}else G+=Y,Y=$[++Z]}if(Y=$[++Z],!V)J.push({type:"string",value:G});continue}if(Y&&/\s/.test(Y)){Z++;continue}let X=/[0-9]/;if(Y&&X.test(Y)||Y==="-"||Y==="."){let G="";if(Y==="-")G+=Y,Y=$[++Z];while(Y&&X.test(Y)||Y===".")G+=Y,Y=$[++Z];J.push({type:"number",value:G});continue}let z=/[a-z]/i;if(Y&&z.test(Y)){let G="";while(Y&&z.test(Y)){if(Z===$.length)break;G+=Y,Y=$[++Z]}if(G=="true"||G=="false"||G==="null")J.push({type:"name",value:G});else{Z++;continue}continue}Z++}return J},I4=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),I4($);break;case"number":let J=Z.value[Z.value.length-1];if(J==="."||J==="-")return $=$.slice(0,$.length-1),I4($);case"string":let Y=$[$.length-2];if(Y?.type==="delimiter")return $=$.slice(0,$.length-1),I4($);else if(Y?.type==="brace"&&Y.value==="{")return $=$.slice(0,$.length-1),I4($);break;case"delimiter":return $=$.slice(0,$.length-1),I4($);break}return $},vJ=($)=>{let Z=[];if($.map((J)=>{if(J.type==="brace")if(J.value==="{")Z.push("}");else Z.splice(Z.lastIndexOf("}"),1);if(J.type==="paren")if(J.value==="[")Z.push("]");else Z.splice(Z.lastIndexOf("]"),1)}),Z.length>0)Z.reverse().map((J)=>{if(J==="}")$.push({type:"brace",value:"}"});else if(J==="]")$.push({type:"paren",value:"]"})});return $},fJ=($)=>{let Z="";return $.map((J)=>{switch(J.type){case"string":Z+='"'+J.value+'"';break;default:Z+=J.value;break}}),Z},_0=($)=>JSON.parse(fJ(vJ(I4(hJ($)))));var M$,i$,w4,D8,h0,x8,T8,v0,P8,y$,I8,f0,g0,H4,m0,c0,w8,y2,Q9,d0,_2,h2,v2,X9,z9="__json_buf";function K9($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class S8{constructor($,Z){M$.add(this),this.messages=[],this.receivedMessages=[],i$.set(this,void 0),w4.set(this,null),this.controller=new AbortController,D8.set(this,void 0),h0.set(this,()=>{}),x8.set(this,()=>{}),T8.set(this,void 0),v0.set(this,()=>{}),P8.set(this,()=>{}),y$.set(this,{}),I8.set(this,!1),f0.set(this,!1),g0.set(this,!1),H4.set(this,!1),m0.set(this,void 0),c0.set(this,void 0),w8.set(this,void 0),d0.set(this,(J)=>{if(L(this,f0,!0,"f"),k$(J))J=new J$;if(J instanceof J$)return L(this,g0,!0,"f"),this._emit("abort",J);if(J instanceof D)return this._emit("error",J);if(J instanceof Error){let Y=new D(J.message);return Y.cause=J,this._emit("error",Y)}return this._emit("error",new D(String(J)))}),L(this,D8,new Promise((J,Y)=>{L(this,h0,J,"f"),L(this,x8,Y,"f")}),"f"),L(this,T8,new Promise((J,Y)=>{L(this,v0,J,"f"),L(this,P8,Y,"f")}),"f"),N(this,D8,"f").catch(()=>{}),N(this,T8,"f").catch(()=>{}),L(this,w4,$,"f"),L(this,w8,Z?.logger??console,"f")}get response(){return N(this,m0,"f")}get request_id(){return N(this,c0,"f")}async withResponse(){L(this,H4,!0,"f");let $=await N(this,D8,"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 S8(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,J,{logger:Y}={}){let Q=new S8(Z,{logger:Y});for(let X of Z.messages)Q._addMessageParam(X);return L(Q,w4,{...Z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...Z,stream:!0},{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},N(this,d0,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,J){let Y=J?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{N(this,M$,"m",_2).call(this);let{response:X,data:z}=await $.create({...Z,stream:!0},{...J,signal:this.controller.signal}).withResponse();this._connected(X);for await(let G of z)N(this,M$,"m",h2).call(this,G);if(z.controller.signal?.aborted)throw new J$;N(this,M$,"m",v2).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,m0,$,"f"),L(this,c0,$?.headers.get("request-id"),"f"),N(this,h0,"f").call(this,$),this._emit("connect")}get ended(){return N(this,I8,"f")}get errored(){return N(this,f0,"f")}get aborted(){return N(this,g0,"f")}abort(){this.controller.abort()}on($,Z){return(N(this,y$,"f")[$]||(N(this,y$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let J=N(this,y$,"f")[$];if(!J)return this;let Y=J.findIndex((Q)=>Q.listener===Z);if(Y>=0)J.splice(Y,1);return this}once($,Z){return(N(this,y$,"f")[$]||(N(this,y$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,J)=>{if(L(this,H4,!0,"f"),$!=="error")this.once("error",J);this.once($,Z)})}async done(){L(this,H4,!0,"f"),await N(this,T8,"f")}get currentMessage(){return N(this,i$,"f")}async finalMessage(){return await this.done(),N(this,M$,"m",y2).call(this)}async finalText(){return await this.done(),N(this,M$,"m",Q9).call(this)}_emit($,...Z){if(N(this,I8,"f"))return;if($==="end")L(this,I8,!0,"f"),N(this,v0,"f").call(this);let J=N(this,y$,"f")[$];if(J)N(this,y$,"f")[$]=J.filter((Y)=>!Y.once),J.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!N(this,H4,"f")&&!J?.length)Promise.reject(Y);N(this,x8,"f").call(this,Y),N(this,P8,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!N(this,H4,"f")&&!J?.length)Promise.reject(Y);N(this,x8,"f").call(this,Y),N(this,P8,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",N(this,M$,"m",y2).call(this))}async _fromReadableStream($,Z){let J=Z?.signal,Y;if(J){if(J.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),J.addEventListener("abort",Y)}try{N(this,M$,"m",_2).call(this),this._connected(null);let Q=H$.fromReadableStream($,this.controller);for await(let X of Q)N(this,M$,"m",h2).call(this,X);if(Q.controller.signal?.aborted)throw new J$;N(this,M$,"m",v2).call(this)}finally{if(J&&Y)J.removeEventListener("abort",Y)}}[(i$=new WeakMap,w4=new WeakMap,D8=new WeakMap,h0=new WeakMap,x8=new WeakMap,T8=new WeakMap,v0=new WeakMap,P8=new WeakMap,y$=new WeakMap,I8=new WeakMap,f0=new WeakMap,g0=new WeakMap,H4=new WeakMap,m0=new WeakMap,c0=new WeakMap,w8=new WeakMap,d0=new WeakMap,M$=new WeakSet,y2=function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Q9=function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((J)=>J.type==="text").map((J)=>J.text);if(Z.length===0)throw new D("stream ended without producing a content block with type=text");return Z.join(" ")},_2=function(){if(this.ended)return;L(this,i$,void 0,"f")},h2=function(Z){if(this.ended)return;let J=N(this,M$,"m",X9).call(this,Z);switch(this._emit("streamEvent",Z,J),Z.type){case"content_block_delta":{let Y=J.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(K9(Y)&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}case"compaction_delta":{if(Y.type==="compaction"&&Y.content)this._emit("compaction",Y.content);break}default:G9(Z.delta)}break}case"message_stop":{this._addMessageParam(J),this._addMessage(k2(J,N(this,w4,"f"),{logger:N(this,w8,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",J.content.at(-1));break}case"message_start":{L(this,i$,J,"f");break}case"content_block_start":case"message_delta":break}},v2=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");let Z=N(this,i$,"f");if(!Z)throw new D("request ended without sending any chunks");return L(this,i$,void 0,"f"),k2(Z,N(this,w4,"f"),{logger:N(this,w8,"f")})},X9=function(Z){let J=N(this,i$,"f");if(Z.type==="message_start"){if(J)throw new D(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!J)throw new D(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return J;case"message_delta":if(J.container=Z.delta.container,J.stop_reason=Z.delta.stop_reason,J.stop_sequence=Z.delta.stop_sequence,J.usage.output_tokens=Z.usage.output_tokens,J.context_management=Z.context_management,Z.usage.input_tokens!=null)J.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)J.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)J.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)J.usage.server_tool_use=Z.usage.server_tool_use;if(Z.usage.iterations!=null)J.usage.iterations=Z.usage.iterations;return J;case"content_block_start":return J.content.push(Z.content_block),J;case"content_block_delta":{let Y=J.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&K9(Y)){let Q=Y[z9]||"";Q+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,z9,{value:Q,enumerable:!1,writable:!0}),Q)try{X.input=_0(Q)}catch(z){let G=new D(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${z}. JSON: ${Q}`);N(this,d0,"f").call(this,G)}J.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,signature:Z.delta.signature};break}case"compaction_delta":{if(Y?.type==="compaction")J.content[Z.index]={...Y,content:(Y.content||"")+Z.delta.content};break}default:G9(Z.delta)}return J}case"content_block_stop":return J}},Symbol.asyncIterator)](){let $=[],Z=[],J=!1;return this.on("streamEvent",(Y)=>{let Q=Z.shift();if(Q)Q.resolve(Y);else $.push(Y)}),this.on("end",()=>{J=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),this.on("error",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(J)return{value:void 0,done:!0};return new Promise((Q,X)=>Z.push({resolve:Q,reject:X})).then((Q)=>Q?{value:Q,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new H$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function G9($){}class S4 extends Error{constructor($){let Z=typeof $==="string"?$:$.map((J)=>{if(J.type==="text")return J.text;return`[${J.type}]`}).join(" ");super(Z);this.name="ToolError",this.content=$}}var V9=1e5,W9=`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:
54
56
  1. Task Overview
55
57
  The user's core request and success criteria
56
58
  Any clarifications or constraints they specified
@@ -72,91 +74,89 @@ User preferences or style requirements
72
74
  Domain-specific details that aren't obvious
73
75
  Any promises made to the user
74
76
  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.
75
- Wrap your summary in <summary></summary> tags.`;var x4,A1,G1,l,D4,W$,S$,p$,T4,p5,T2;function l5(){let $,Z;return{promise:new Promise((J,Q)=>{$=J,Z=Q}),resolve:$,reject:Z}}class P4{constructor($,Z,Y){x4.add(this),this.client=$,A1.set(this,!1),G1.set(this,!1),l.set(this,void 0),D4.set(this,void 0),W$.set(this,void 0),S$.set(this,void 0),p$.set(this,void 0),T4.set(this,0),F(this,l,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let Q=["BetaToolRunner",...j2(Z.tools,Z.messages)].join(", ");F(this,D4,{...Y,headers:D([{"x-stainless-helper":Q},Y?.headers])},"f"),F(this,p$,l5(),"f")}async*[(A1=new WeakMap,G1=new WeakMap,l=new WeakMap,D4=new WeakMap,W$=new WeakMap,S$=new WeakMap,p$=new WeakMap,T4=new WeakMap,x4=new WeakSet,p5=async function(){let Z=U(this,l,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(U(this,W$,"f")!==void 0)try{let G=await U(this,W$,"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,l,"f").params.model,X=Z.summaryPrompt??u5,K=U(this,l,"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,l,"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,l,"f").params.messages=[{role:"user",content:V.content}],!0},Symbol.asyncIterator)](){var $;if(U(this,A1,"f"))throw new R("Cannot iterate over a consumed stream");F(this,A1,!0,"f"),F(this,G1,!0,"f"),F(this,S$,void 0,"f");try{while(!0){let Z;try{if(U(this,l,"f").params.max_iterations&&U(this,T4,"f")>=U(this,l,"f").params.max_iterations)break;F(this,G1,!1,"f"),F(this,S$,void 0,"f"),F(this,T4,($=U(this,T4,"f"),$++,$),"f"),F(this,W$,void 0,"f");let{max_iterations:Y,compactionControl:J,...Q}=U(this,l,"f").params;if(Q.stream)Z=this.client.beta.messages.stream({...Q},U(this,D4,"f")),F(this,W$,Z.finalMessage(),"f"),U(this,W$,"f").catch(()=>{}),yield Z;else F(this,W$,this.client.beta.messages.create({...Q,stream:!1},U(this,D4,"f")),"f"),yield U(this,W$,"f");if(!await U(this,x4,"m",p5).call(this)){if(!U(this,G1,"f")){let{role:V,content:G}=await U(this,W$,"f");U(this,l,"f").params.messages.push({role:V,content:G})}let K=await U(this,x4,"m",T2).call(this,U(this,l,"f").params.messages.at(-1));if(K)U(this,l,"f").params.messages.push(K);else if(!U(this,G1,"f"))break}}finally{if(Z)Z.abort()}}if(!U(this,W$,"f"))throw new R("ToolRunner concluded without a message from the server");U(this,p$,"f").resolve(await U(this,W$,"f"))}catch(Z){throw F(this,A1,!1,"f"),U(this,p$,"f").promise.catch(()=>{}),U(this,p$,"f").reject(Z),F(this,p$,l5(),"f"),Z}}setMessagesParams($){if(typeof $==="function")U(this,l,"f").params=$(U(this,l,"f").params);else U(this,l,"f").params=$;F(this,G1,!0,"f"),F(this,S$,void 0,"f")}async generateToolResponse(){let $=await U(this,W$,"f")??this.params.messages.at(-1);if(!$)return null;return U(this,x4,"m",T2).call(this,$)}done(){return U(this,p$,"f").promise}async runUntilDone(){if(!U(this,A1,"f"))for await(let $ of this);return this.done()}get params(){return U(this,l,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}T2=async function(Z){if(U(this,S$,"f")!==void 0)return U(this,S$,"f");return F(this,S$,t3(U(this,l,"f").params,Z),"f"),U(this,S$,"f")};async function t3($,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 R1?K.content:`Error: ${K instanceof Error?K.message:String(K)}`,is_error:!0}}}))}}class x1{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new d$;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 x1(V4($.body),Z)}}class w4 extends g{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/messages/batches?beta=true",{body:J,...Z,headers:D([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(v`/v1/messages/batches/${$}?beta=true`,{...Y,headers:D([{"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:D([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(v`/v1/messages/batches/${$}?beta=true`,{...Y,headers:D([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:J}=Z??{};return this._client.post(v`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:D([{"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:D([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((X,K)=>x1.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"},$Y=["claude-opus-4-6"];class l$ extends g{constructor(){super(...arguments);this.batches=new w4(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 $Y&&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:D([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},K,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:D([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>L2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return A4.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:D([{"anthropic-beta":[...J??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new P4(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}}}l$.Batches=w4;l$.BetaToolRunner=P4;l$.ToolError=R1;class I4 extends g{create($,Z={},Y){let{betas:J,...Q}=Z??{};return this._client.post(v`/v1/skills/${$}/versions?beta=true`,j1({body:Q,...Y,headers:D([{"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(v`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:D([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:J,...Q}=Z??{};return this._client.getAPIList(v`/v1/skills/${$}/versions?beta=true`,U4,{query:Q,...Y,headers:D([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:J,betas:Q}=Z;return this._client.delete(v`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:D([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class D1 extends g{constructor(){super(...arguments);this.versions=new I4(this._client)}create($={},Z){let{betas:Y,...J}=$??{};return this._client.post("/v1/skills?beta=true",j1({body:J,...Z,headers:D([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(v`/v1/skills/${$}?beta=true`,{...Y,headers:D([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/skills?beta=true",U4,{query:J,...Z,headers:D([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(v`/v1/skills/${$}?beta=true`,{...Y,headers:D([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}}D1.Versions=I4;class j$ extends g{constructor(){super(...arguments);this.models=new M4(this._client),this.messages=new l$(this._client),this.files=new C4(this._client),this.skills=new D1(this._client)}}j$.Models=M4;j$.Messages=l$;j$.Files=C4;j$.Skills=D1;class T1 extends g{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/complete",{body:J,timeout:this._client._options.timeout??600000,...Z,headers:D([{...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=QY(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 QY($,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 U$,n$,P1,S4,k8,b4,k4,y8,y4,b$,_4,_8,h8,W1,f8,v8,h4,I2,a5,S2,b2,k2,y2,r5,s5="__json_buf";function t5($){return $.type==="tool_use"||$.type==="server_tool_use"}class f4{constructor($,Z){U$.add(this),this.messages=[],this.receivedMessages=[],n$.set(this,void 0),P1.set(this,null),this.controller=new AbortController,S4.set(this,void 0),k8.set(this,()=>{}),b4.set(this,()=>{}),k4.set(this,void 0),y8.set(this,()=>{}),y4.set(this,()=>{}),b$.set(this,{}),_4.set(this,!1),_8.set(this,!1),h8.set(this,!1),W1.set(this,!1),f8.set(this,void 0),v8.set(this,void 0),h4.set(this,void 0),S2.set(this,(Y)=>{if(F(this,_8,!0,"f"),P$(Y))Y=new e;if(Y instanceof e)return F(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)))}),F(this,S4,new Promise((Y,J)=>{F(this,k8,Y,"f"),F(this,b4,J,"f")}),"f"),F(this,k4,new Promise((Y,J)=>{F(this,y8,Y,"f"),F(this,y4,J,"f")}),"f"),U(this,S4,"f").catch(()=>{}),U(this,k4,"f").catch(()=>{}),F(this,P1,$,"f"),F(this,h4,Z?.logger??console,"f")}get response(){return U(this,f8,"f")}get request_id(){return U(this,v8,"f")}async withResponse(){F(this,W1,!0,"f");let $=await U(this,S4,"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 f4(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let Q=new f4(Z,{logger:J});for(let X of Z.messages)Q._addMessageParam(X);return F(Q,P1,{...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,U$,"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,U$,"m",k2).call(this,V);if(K.controller.signal?.aborted)throw new e;U(this,U$,"m",y2).call(this)}finally{if(J&&Q)J.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;F(this,f8,$,"f"),F(this,v8,$?.headers.get("request-id"),"f"),U(this,k8,"f").call(this,$),this._emit("connect")}get ended(){return U(this,_4,"f")}get errored(){return U(this,_8,"f")}get aborted(){return U(this,h8,"f")}abort(){this.controller.abort()}on($,Z){return(U(this,b$,"f")[$]||(U(this,b$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=U(this,b$,"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,b$,"f")[$]||(U(this,b$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(F(this,W1,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){F(this,W1,!0,"f"),await U(this,k4,"f")}get currentMessage(){return U(this,n$,"f")}async finalMessage(){return await this.done(),U(this,U$,"m",I2).call(this)}async finalText(){return await this.done(),U(this,U$,"m",a5).call(this)}_emit($,...Z){if(U(this,_4,"f"))return;if($==="end")F(this,_4,!0,"f"),U(this,y8,"f").call(this);let Y=U(this,b$,"f")[$];if(Y)U(this,b$,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!U(this,W1,"f")&&!Y?.length)Promise.reject(J);U(this,b4,"f").call(this,J),U(this,y4,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!U(this,W1,"f")&&!Y?.length)Promise.reject(J);U(this,b4,"f").call(this,J),U(this,y4,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",U(this,U$,"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,U$,"m",b2).call(this),this._connected(null);let Q=G$.fromReadableStream($,this.controller);for await(let X of Q)U(this,U$,"m",k2).call(this,X);if(Q.controller.signal?.aborted)throw new e;U(this,U$,"m",y2).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(n$=new WeakMap,P1=new WeakMap,S4=new WeakMap,k8=new WeakMap,b4=new WeakMap,k4=new WeakMap,y8=new WeakMap,y4=new WeakMap,b$=new WeakMap,_4=new WeakMap,_8=new WeakMap,h8=new WeakMap,W1=new WeakMap,f8=new WeakMap,v8=new WeakMap,h4=new WeakMap,S2=new WeakMap,U$=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;F(this,n$,void 0,"f")},k2=function(Z){if(this.ended)return;let Y=U(this,U$,"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,P1,"f"),{logger:U(this,h4,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{F(this,n$,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,n$,"f");if(!Z)throw new R("request ended without sending any chunks");return F(this,n$,void 0,"f"),P2(Z,U(this,P1,"f"),{logger:U(this,h4,"f")})},r5=function(Z){let Y=U(this,n$,"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 G$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function e5($){}class v4 extends g{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(v`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",M$,{query:$,...Z})}delete($,Z){return this._client.delete(v`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(v`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new R(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:D([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,Q)=>x1.fromResponse(Q.response,Q.controller))}}class H1 extends g{constructor(){super(...arguments);this.batches=new v4(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 KY&&$.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:D([J,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>w2(Y,$,{logger:this._client.logger??console}))}stream($,Z){return f4.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"},KY=["claude-opus-4-6"];H1.Batches=v4;class w1 extends g{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(v`/v1/models/${$}`,{...Y,headers:D([{...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:D([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var g4=($)=>{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 m{constructor({baseURL:$=g4("ANTHROPIC_BASE_URL"),apiKey:Z=g4("ANTHROPIC_API_KEY")??null,authToken:Y=g4("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.
77
+ Wrap your summary in <summary></summary> tags.`;var k8,k4,q4,i,b8,q$,_$,a$,y8,H9,f2;function q9(){let $,Z;return{promise:new Promise((Y,Q)=>{$=Y,Z=Q}),resolve:$,reject:Z}}class _8{constructor($,Z,J){k8.add(this),this.client=$,k4.set(this,!1),q4.set(this,!1),i.set(this,void 0),b8.set(this,void 0),q$.set(this,void 0),_$.set(this,void 0),a$.set(this,void 0),y8.set(this,0),L(this,i,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let Q=["BetaToolRunner",...S2(Z.tools,Z.messages)].join(", ");L(this,b8,{...J,headers:P([{"x-stainless-helper":Q},J?.headers])},"f"),L(this,a$,q9(),"f")}async*[(k4=new WeakMap,q4=new WeakMap,i=new WeakMap,b8=new WeakMap,q$=new WeakMap,_$=new WeakMap,a$=new WeakMap,y8=new WeakMap,k8=new WeakSet,H9=async function(){let Z=N(this,i,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let J=0;if(N(this,q$,"f")!==void 0)try{let V=await N(this,q$,"f");J=V.usage.input_tokens+(V.usage.cache_creation_input_tokens??0)+(V.usage.cache_read_input_tokens??0)+V.usage.output_tokens}catch{return!1}let Y=Z.contextTokenThreshold??V9;if(J<Y)return!1;let Q=Z.model??N(this,i,"f").params.model,X=Z.summaryPrompt??W9,z=N(this,i,"f").params.messages;if(z[z.length-1].role==="assistant"){let V=z[z.length-1];if(Array.isArray(V.content)){let H=V.content.filter((K)=>K.type!=="tool_use");if(H.length===0)z.pop();else V.content=H}}let G=await this.client.beta.messages.create({model:Q,messages:[...z,{role:"user",content:[{type:"text",text:X}]}],max_tokens:N(this,i,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(G.content[0]?.type!=="text")throw new D("Expected text response for compaction");return N(this,i,"f").params.messages=[{role:"user",content:G.content}],!0},Symbol.asyncIterator)](){var $;if(N(this,k4,"f"))throw new D("Cannot iterate over a consumed stream");L(this,k4,!0,"f"),L(this,q4,!0,"f"),L(this,_$,void 0,"f");try{while(!0){let Z;try{if(N(this,i,"f").params.max_iterations&&N(this,y8,"f")>=N(this,i,"f").params.max_iterations)break;L(this,q4,!1,"f"),L(this,_$,void 0,"f"),L(this,y8,($=N(this,y8,"f"),$++,$),"f"),L(this,q$,void 0,"f");let{max_iterations:J,compactionControl:Y,...Q}=N(this,i,"f").params;if(Q.stream)Z=this.client.beta.messages.stream({...Q},N(this,b8,"f")),L(this,q$,Z.finalMessage(),"f"),N(this,q$,"f").catch(()=>{}),yield Z;else L(this,q$,this.client.beta.messages.create({...Q,stream:!1},N(this,b8,"f")),"f"),yield N(this,q$,"f");if(!await N(this,k8,"m",H9).call(this)){if(!N(this,q4,"f")){let{role:G,content:V}=await N(this,q$,"f");N(this,i,"f").params.messages.push({role:G,content:V})}let z=await N(this,k8,"m",f2).call(this,N(this,i,"f").params.messages.at(-1));if(z)N(this,i,"f").params.messages.push(z);else if(!N(this,q4,"f"))break}}finally{if(Z)Z.abort()}}if(!N(this,q$,"f"))throw new D("ToolRunner concluded without a message from the server");N(this,a$,"f").resolve(await N(this,q$,"f"))}catch(Z){throw L(this,k4,!1,"f"),N(this,a$,"f").promise.catch(()=>{}),N(this,a$,"f").reject(Z),L(this,a$,q9(),"f"),Z}}setMessagesParams($){if(typeof $==="function")N(this,i,"f").params=$(N(this,i,"f").params);else N(this,i,"f").params=$;L(this,q4,!0,"f"),L(this,_$,void 0,"f")}async generateToolResponse(){let $=await N(this,q$,"f")??this.params.messages.at(-1);if(!$)return null;return N(this,k8,"m",f2).call(this,$)}done(){return N(this,a$,"f").promise}async runUntilDone(){if(!N(this,k4,"f"))for await(let $ of this);return this.done()}get params(){return N(this,i,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}f2=async function(Z){if(N(this,_$,"f")!==void 0)return N(this,_$,"f");return L(this,_$,gJ(N(this,i,"f").params,Z),"f"),N(this,_$,"f")};async function gJ($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let J=Z.content.filter((Q)=>Q.type==="tool_use");if(J.length===0)return null;return{role:"user",content:await Promise.all(J.map(async(Q)=>{let X=$.tools.find((z)=>("name"in z?z.name:z.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 z=Q.input;if("parse"in X&&X.parse)z=X.parse(z);let G=await X.run(z);return{type:"tool_result",tool_use_id:Q.id,content:G}}catch(z){return{type:"tool_result",tool_use_id:Q.id,content:z instanceof S4?z.content:`Error: ${z instanceof Error?z.message:String(z)}`,is_error:!0}}}))}}class b4{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new n$;for await(let Z of this.iterator)for(let J of $.decode(Z))yield JSON.parse(J);for(let Z of $.flush())yield JSON.parse(Z)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new D("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 D("Attempted to iterate over a response with no body")}return new b4(N8($.body),Z)}}class h8 extends c{create($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/messages/batches?beta=true",{body:Y,...Z,headers:P([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/messages/batches/${$}?beta=true`,{...J,headers:P([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/messages/batches?beta=true",L$,{query:Y,...Z,headers:P([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(m`/v1/messages/batches/${$}?beta=true`,{...J,headers:P([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},J?.headers])})}cancel($,Z={},J){let{betas:Y}=Z??{};return this._client.post(m`/v1/messages/batches/${$}/cancel?beta=true`,{...J,headers:P([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},J?.headers])})}async results($,Z={},J){let Y=await this.retrieve($);if(!Y.results_url)throw new D(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);let{betas:Q}=Z??{};return this._client.get(Y.results_url,{...J,headers:P([{"anthropic-beta":[...Q??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},J?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((X,z)=>b4.fromResponse(z.response,z.controller))}}var U9={"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"},cJ=["claude-opus-4-6"];class r$ extends c{constructor(){super(...arguments);this.batches=new h8(this._client)}create($,Z){let J=B9($),{betas:Y,...Q}=J;if(Q.model in U9)console.warn(`The model '${Q.model}' is deprecated and will reach end-of-life on ${U9[Q.model]}
78
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(Q.model in cJ&&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 G=y0[Q.model]??void 0;X=this._client.calculateNonstreamingTimeout(Q.max_tokens,G)}let z=b0(Q.tools,Q.messages);return this._client.post("/v1/messages?beta=true",{body:Q,timeout:X??600000,...Z,headers:P([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},z,Z?.headers]),stream:J.stream??!1})}parse($,Z){return Z={...Z,headers:P([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((J)=>b2(J,$,{logger:this._client.logger??console}))}stream($,Z){return S8.createMessage(this,$,Z)}countTokens($,Z){let J=B9($),{betas:Y,...Q}=J;return this._client.post("/v1/messages/count_tokens?beta=true",{body:Q,...Z,headers:P([{"anthropic-beta":[...Y??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new _8(this._client,$,Z)}}function B9($){if(!$.output_format)return $;if($.output_config?.format)throw new D("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");let{output_format:Z,...J}=$;return{...J,output_config:{...$.output_config,format:Z}}}r$.Batches=h8;r$.BetaToolRunner=_8;r$.ToolError=S4;class v8 extends c{create($,Z={},J){let{betas:Y,...Q}=Z??{};return this._client.post(m`/v1/skills/${$}/versions?beta=true`,P4({body:Q,...J,headers:P([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])},this._client))}retrieve($,Z,J){let{skill_id:Y,betas:Q}=Z;return this._client.get(m`/v1/skills/${Y}/versions/${$}?beta=true`,{...J,headers:P([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},J?.headers])})}list($,Z={},J){let{betas:Y,...Q}=Z??{};return this._client.getAPIList(m`/v1/skills/${$}/versions?beta=true`,E8,{query:Q,...J,headers:P([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}delete($,Z,J){let{skill_id:Y,betas:Q}=Z;return this._client.delete(m`/v1/skills/${Y}/versions/${$}?beta=true`,{...J,headers:P([{"anthropic-beta":[...Q??[],"skills-2025-10-02"].toString()},J?.headers])})}}class y4 extends c{constructor(){super(...arguments);this.versions=new v8(this._client)}create($={},Z){let{betas:J,...Y}=$??{};return this._client.post("/v1/skills?beta=true",P4({body:Y,...Z,headers:P([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/skills/${$}?beta=true`,{...J,headers:P([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/skills?beta=true",E8,{query:Y,...Z,headers:P([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},J){let{betas:Y}=Z??{};return this._client.delete(m`/v1/skills/${$}?beta=true`,{...J,headers:P([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},J?.headers])})}}y4.Versions=v8;class D$ extends c{constructor(){super(...arguments);this.models=new A8(this._client),this.messages=new r$(this._client),this.files=new R8(this._client),this.skills=new y4(this._client)}}D$.Models=A8;D$.Messages=r$;D$.Files=R8;D$.Skills=y4;class _4 extends c{create($,Z){let{betas:J,...Y}=$;return this._client.post("/v1/complete",{body:Y,timeout:this._client._options.timeout??600000,...Z,headers:P([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function N9($){return $?.output_config?.format}function g2($,Z,J){let Y=N9(Z);if(!Z||!("parse"in(Y??{})))return{...$,content:$.content.map((Q)=>{if(Q.type==="text")return Object.defineProperty({...Q},"parsed_output",{value:null,enumerable:!1});return Q}),parsed_output:null};return m2($,Z,J)}function m2($,Z,J){let Y=null,Q=$.content.map((X)=>{if(X.type==="text"){let z=lJ(Z,X.text);if(Y===null)Y=z;return Object.defineProperty({...X},"parsed_output",{value:z,enumerable:!1})}return X});return{...$,content:Q,parsed_output:Y}}function lJ($,Z){let J=N9($);if(J?.type!=="json_schema")return null;try{if("parse"in J)return J.parse(Z);return JSON.parse(Z)}catch(Y){throw new D(`Failed to parse structured output: ${Y}`)}}var O$,s$,h4,f8,u0,g8,m8,p0,c8,h$,d8,l0,o0,U4,n0,i0,u8,c2,C9,d2,u2,p2,l2,M9,O9="__json_buf";function j9($){return $.type==="tool_use"||$.type==="server_tool_use"}class p8{constructor($,Z){O$.add(this),this.messages=[],this.receivedMessages=[],s$.set(this,void 0),h4.set(this,null),this.controller=new AbortController,f8.set(this,void 0),u0.set(this,()=>{}),g8.set(this,()=>{}),m8.set(this,void 0),p0.set(this,()=>{}),c8.set(this,()=>{}),h$.set(this,{}),d8.set(this,!1),l0.set(this,!1),o0.set(this,!1),U4.set(this,!1),n0.set(this,void 0),i0.set(this,void 0),u8.set(this,void 0),d2.set(this,(J)=>{if(L(this,l0,!0,"f"),k$(J))J=new J$;if(J instanceof J$)return L(this,o0,!0,"f"),this._emit("abort",J);if(J instanceof D)return this._emit("error",J);if(J instanceof Error){let Y=new D(J.message);return Y.cause=J,this._emit("error",Y)}return this._emit("error",new D(String(J)))}),L(this,f8,new Promise((J,Y)=>{L(this,u0,J,"f"),L(this,g8,Y,"f")}),"f"),L(this,m8,new Promise((J,Y)=>{L(this,p0,J,"f"),L(this,c8,Y,"f")}),"f"),N(this,f8,"f").catch(()=>{}),N(this,m8,"f").catch(()=>{}),L(this,h4,$,"f"),L(this,u8,Z?.logger??console,"f")}get response(){return N(this,n0,"f")}get request_id(){return N(this,i0,"f")}async withResponse(){L(this,U4,!0,"f");let $=await N(this,f8,"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 p8(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,J,{logger:Y}={}){let Q=new p8(Z,{logger:Y});for(let X of Z.messages)Q._addMessageParam(X);return L(Q,h4,{...Z,stream:!0},"f"),Q._run(()=>Q._createMessage($,{...Z,stream:!0},{...J,headers:{...J?.headers,"X-Stainless-Helper-Method":"stream"}})),Q}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},N(this,d2,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,J){let Y=J?.signal,Q;if(Y){if(Y.aborted)this.controller.abort();Q=this.controller.abort.bind(this.controller),Y.addEventListener("abort",Q)}try{N(this,O$,"m",u2).call(this);let{response:X,data:z}=await $.create({...Z,stream:!0},{...J,signal:this.controller.signal}).withResponse();this._connected(X);for await(let G of z)N(this,O$,"m",p2).call(this,G);if(z.controller.signal?.aborted)throw new J$;N(this,O$,"m",l2).call(this)}finally{if(Y&&Q)Y.removeEventListener("abort",Q)}}_connected($){if(this.ended)return;L(this,n0,$,"f"),L(this,i0,$?.headers.get("request-id"),"f"),N(this,u0,"f").call(this,$),this._emit("connect")}get ended(){return N(this,d8,"f")}get errored(){return N(this,l0,"f")}get aborted(){return N(this,o0,"f")}abort(){this.controller.abort()}on($,Z){return(N(this,h$,"f")[$]||(N(this,h$,"f")[$]=[])).push({listener:Z}),this}off($,Z){let J=N(this,h$,"f")[$];if(!J)return this;let Y=J.findIndex((Q)=>Q.listener===Z);if(Y>=0)J.splice(Y,1);return this}once($,Z){return(N(this,h$,"f")[$]||(N(this,h$,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,J)=>{if(L(this,U4,!0,"f"),$!=="error")this.once("error",J);this.once($,Z)})}async done(){L(this,U4,!0,"f"),await N(this,m8,"f")}get currentMessage(){return N(this,s$,"f")}async finalMessage(){return await this.done(),N(this,O$,"m",c2).call(this)}async finalText(){return await this.done(),N(this,O$,"m",C9).call(this)}_emit($,...Z){if(N(this,d8,"f"))return;if($==="end")L(this,d8,!0,"f"),N(this,p0,"f").call(this);let J=N(this,h$,"f")[$];if(J)N(this,h$,"f")[$]=J.filter((Y)=>!Y.once),J.forEach(({listener:Y})=>Y(...Z));if($==="abort"){let Y=Z[0];if(!N(this,U4,"f")&&!J?.length)Promise.reject(Y);N(this,g8,"f").call(this,Y),N(this,c8,"f").call(this,Y),this._emit("end");return}if($==="error"){let Y=Z[0];if(!N(this,U4,"f")&&!J?.length)Promise.reject(Y);N(this,g8,"f").call(this,Y),N(this,c8,"f").call(this,Y),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",N(this,O$,"m",c2).call(this))}async _fromReadableStream($,Z){let J=Z?.signal,Y;if(J){if(J.aborted)this.controller.abort();Y=this.controller.abort.bind(this.controller),J.addEventListener("abort",Y)}try{N(this,O$,"m",u2).call(this),this._connected(null);let Q=H$.fromReadableStream($,this.controller);for await(let X of Q)N(this,O$,"m",p2).call(this,X);if(Q.controller.signal?.aborted)throw new J$;N(this,O$,"m",l2).call(this)}finally{if(J&&Y)J.removeEventListener("abort",Y)}}[(s$=new WeakMap,h4=new WeakMap,f8=new WeakMap,u0=new WeakMap,g8=new WeakMap,m8=new WeakMap,p0=new WeakMap,c8=new WeakMap,h$=new WeakMap,d8=new WeakMap,l0=new WeakMap,o0=new WeakMap,U4=new WeakMap,n0=new WeakMap,i0=new WeakMap,u8=new WeakMap,d2=new WeakMap,O$=new WeakSet,c2=function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},C9=function(){if(this.receivedMessages.length===0)throw new D("stream ended without producing a Message with role=assistant");let Z=this.receivedMessages.at(-1).content.filter((J)=>J.type==="text").map((J)=>J.text);if(Z.length===0)throw new D("stream ended without producing a content block with type=text");return Z.join(" ")},u2=function(){if(this.ended)return;L(this,s$,void 0,"f")},p2=function(Z){if(this.ended)return;let J=N(this,O$,"m",M9).call(this,Z);switch(this._emit("streamEvent",Z,J),Z.type){case"content_block_delta":{let Y=J.content.at(-1);switch(Z.delta.type){case"text_delta":{if(Y.type==="text")this._emit("text",Z.delta.text,Y.text||"");break}case"citations_delta":{if(Y.type==="text")this._emit("citation",Z.delta.citation,Y.citations??[]);break}case"input_json_delta":{if(j9(Y)&&Y.input)this._emit("inputJson",Z.delta.partial_json,Y.input);break}case"thinking_delta":{if(Y.type==="thinking")this._emit("thinking",Z.delta.thinking,Y.thinking);break}case"signature_delta":{if(Y.type==="thinking")this._emit("signature",Y.signature);break}default:E9(Z.delta)}break}case"message_stop":{this._addMessageParam(J),this._addMessage(g2(J,N(this,h4,"f"),{logger:N(this,u8,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",J.content.at(-1));break}case"message_start":{L(this,s$,J,"f");break}case"content_block_start":case"message_delta":break}},l2=function(){if(this.ended)throw new D("stream has ended, this shouldn't happen");let Z=N(this,s$,"f");if(!Z)throw new D("request ended without sending any chunks");return L(this,s$,void 0,"f"),g2(Z,N(this,h4,"f"),{logger:N(this,u8,"f")})},M9=function(Z){let J=N(this,s$,"f");if(Z.type==="message_start"){if(J)throw new D(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!J)throw new D(`Unexpected event order, got ${Z.type} before "message_start"`);switch(Z.type){case"message_stop":return J;case"message_delta":if(J.stop_reason=Z.delta.stop_reason,J.stop_sequence=Z.delta.stop_sequence,J.usage.output_tokens=Z.usage.output_tokens,Z.usage.input_tokens!=null)J.usage.input_tokens=Z.usage.input_tokens;if(Z.usage.cache_creation_input_tokens!=null)J.usage.cache_creation_input_tokens=Z.usage.cache_creation_input_tokens;if(Z.usage.cache_read_input_tokens!=null)J.usage.cache_read_input_tokens=Z.usage.cache_read_input_tokens;if(Z.usage.server_tool_use!=null)J.usage.server_tool_use=Z.usage.server_tool_use;return J;case"content_block_start":return J.content.push({...Z.content_block}),J;case"content_block_delta":{let Y=J.content.at(Z.index);switch(Z.delta.type){case"text_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,text:(Y.text||"")+Z.delta.text};break}case"citations_delta":{if(Y?.type==="text")J.content[Z.index]={...Y,citations:[...Y.citations??[],Z.delta.citation]};break}case"input_json_delta":{if(Y&&j9(Y)){let Q=Y[O9]||"";Q+=Z.delta.partial_json;let X={...Y};if(Object.defineProperty(X,O9,{value:Q,enumerable:!1,writable:!0}),Q)X.input=_0(Q);J.content[Z.index]=X}break}case"thinking_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,thinking:Y.thinking+Z.delta.thinking};break}case"signature_delta":{if(Y?.type==="thinking")J.content[Z.index]={...Y,signature:Z.delta.signature};break}default:E9(Z.delta)}return J}case"content_block_stop":return J}},Symbol.asyncIterator)](){let $=[],Z=[],J=!1;return this.on("streamEvent",(Y)=>{let Q=Z.shift();if(Q)Q.resolve(Y);else $.push(Y)}),this.on("end",()=>{J=!0;for(let Y of Z)Y.resolve(void 0);Z.length=0}),this.on("abort",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),this.on("error",(Y)=>{J=!0;for(let Q of Z)Q.reject(Y);Z.length=0}),{next:async()=>{if(!$.length){if(J)return{value:void 0,done:!0};return new Promise((Q,X)=>Z.push({resolve:Q,reject:X})).then((Q)=>Q?{value:Q,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new H$(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function E9($){}class l8 extends c{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(m`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",L$,{query:$,...Z})}delete($,Z){return this._client.delete(m`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(m`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let J=await this.retrieve($);if(!J.results_url)throw new D(`No batch \`results_url\`; Has it finished processing? ${J.processing_status} - ${J.id}`);return this._client.get(J.results_url,{...Z,headers:P([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((Y,Q)=>b4.fromResponse(Q.response,Q.controller))}}class B4 extends c{constructor(){super(...arguments);this.batches=new l8(this._client)}create($,Z){if($.model in F9)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${F9[$.model]}
79
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in nJ&&$.thinking&&$.thinking.type==="enabled")console.warn(`Using Claude with ${$.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let J=this._client._options.timeout;if(!$.stream&&J==null){let Q=y0[$.model]??void 0;J=this._client.calculateNonstreamingTimeout($.max_tokens,Q)}let Y=b0($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:J??600000,...Z,headers:P([Y,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((J)=>m2(J,$,{logger:this._client.logger??console}))}stream($,Z){return p8.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var F9={"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"},nJ=["claude-opus-4-6"];B4.Batches=l8;class v4 extends c{retrieve($,Z={},J){let{betas:Y}=Z??{};return this._client.get(m`/v1/models/${$}`,{...J,headers:P([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},J?.headers])})}list($={},Z){let{betas:J,...Y}=$??{};return this._client.getAPIList("/v1/models",L$,{query:Y,...Z,headers:P([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Z?.headers])})}}var o8=($)=>{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 o2,n2,a0,L9,R9="\\n\\nHuman:",A9="\\n\\nAssistant:";class d{constructor({baseURL:$=o8("ANTHROPIC_BASE_URL"),apiKey:Z=o8("ANTHROPIC_API_KEY")??null,authToken:J=o8("ANTHROPIC_AUTH_TOKEN")??null,...Y}={}){o2.add(this),a0.set(this,void 0);let Q={apiKey:Z,authToken:J,...Y,baseURL:$||"https://api.anthropic.com"};if(!Q.dangerouslyAllowBrowser&&g5())throw new D(`It looks like you're running in a browser-like environment.
78
80
 
79
81
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
80
82
  If you understand the risks and have appropriate mitigations in place,
81
83
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
82
84
 
83
85
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
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(g4("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??X,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??j5(),F(this,g8,L5,"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 D([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return D([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return D([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return R5($)}getUserAgent(){return`${this.constructor.name}/JS ${c$}`}defaultIdempotencyKey(){return`stainless-node-retry-${z2()}`}makeStatusError($,Z,Y,J){return p.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 K1(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(i(this).debug(`[${G}] sending request`,w$({retryOfRequestLogID:Y,method:J.method,url:K,options:J,headers:X.headers})),J.signal?.aborted)throw new e;let M=new AbortController,N=await this.fetchWithTimeout(K,X,V,M).catch(t1),E=Date.now();if(N instanceof globalThis.Error){let S=`retrying, ${Z} attempts remaining`;if(J.signal?.aborted)throw new e;let k=P$(N)||/timed? ?out/i.test(String(N)+("cause"in N?String(N.cause):""));if(Z)return i(this).info(`[${G}] connection ${k?"timed out":"failed"} - ${S}`),i(this).debug(`[${G}] connection ${k?"timed out":"failed"} (${S})`,w$({retryOfRequestLogID:Y,url:K,durationMs:E-z,message:N.message})),this.retryRequest(J,Z,Y??G);if(i(this).info(`[${G}] connection ${k?"timed out":"failed"} - error; no more retries left`),i(this).debug(`[${G}] connection ${k?"timed out":"failed"} (error; no more retries left)`,w$({retryOfRequestLogID:Y,url:K,durationMs:E-z,message:N.message})),k)throw new e1;throw new X1({cause:N})}let L=[...N.headers.entries()].filter(([S])=>S==="request-id").map(([S,k])=>", "+S+": "+JSON.stringify(k)).join(""),w=`[${G}${H}${L}] ${X.method} ${K} ${N.ok?"succeeded":"failed"} with status ${N.status} in ${E-z}ms`;if(!N.ok){let S=await this.shouldRetry(N);if(Z&&S){let O=`retrying, ${Z} attempts remaining`;return await F5(N.body),i(this).info(`${w} - ${O}`),i(this).debug(`[${G}] response error (${O})`,w$({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,durationMs:E-z})),this.retryRequest(J,Z,Y??G,N.headers)}let k=S?"error; no more retries left":"error; not retryable";i(this).info(`${w} - ${k}`);let f$=await N.text().catch((O)=>t1(O).message),h=B8(f$),o=h?void 0:f$;throw i(this).debug(`[${G}] response error (${k})`,w$({retryOfRequestLogID:Y,url:N.url,status:N.status,headers:N.headers,message:o,durationMs:Date.now()-z})),this.makeStatusError(N.status,h,o,N.headers)}return i(this).info(w),i(this).debug(`[${G}] response start`,w$({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 j8(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=D([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=D([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=m,g8=new WeakMap,_2=new WeakSet,Z9=function(){return this.baseURL!=="https://api.anthropic.com"};m.Anthropic=h2;m.HUMAN_PROMPT=Y9;m.AI_PROMPT=J9;m.DEFAULT_TIMEOUT=600000;m.AnthropicError=R;m.APIError=p;m.APIConnectionError=X1;m.APIConnectionTimeoutError=e1;m.APIUserAbortError=e;m.NotFoundError=J4;m.ConflictError=Q4;m.RateLimitError=K4;m.BadRequestError=$4;m.AuthenticationError=Z4;m.InternalServerError=z4;m.PermissionDeniedError=Y4;m.UnprocessableEntityError=X4;m.toFile=F8;class F$ extends m{constructor(){super(...arguments);this.completions=new T1(this),this.messages=new H1(this),this.models=new w1(this),this.beta=new j$(this)}}F$.Completions=T1;F$.Messages=H1;F$.Models=w1;F$.Beta=j$;t();import{existsSync as o4,readdirSync as HQ,readFileSync as O7,writeFileSync as qQ,statSync as SZ,realpathSync as UQ}from"fs";import{resolve as C1,join as bZ,sep as c0}from"path";import{existsSync as VY,readFileSync as GY,writeFileSync as WY}from"fs";import{basename as f2}from"path";var Q9=50;class v2{entries=[];saveState($){let Z=VY($),Y=Z?GY($,"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.`;WY($.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 HY,readFileSync as qY,mkdirSync as UY}from"fs";import{join as g2}from"path";function z9($){if(!K9($))return[];let Z=[],Y=HY($).filter((J)=>J.endsWith(".json"));for(let J of Y)try{let Q=JSON.parse(qY(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:
86
+ `);this.baseURL=Q.baseURL,this.timeout=Q.timeout??n2.DEFAULT_TIMEOUT,this.logger=Q.logger??console;let X="warn";this.logLevel=X,this.logLevel=A2(Q.logLevel,"ClientOptions.logLevel",this)??A2(o8("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??X,this.fetchOptions=Q.fetchOptions,this.maxRetries=Q.maxRetries??2,this.fetch=Q.fetch??c5(),L(this,a0,u5,"f"),this._options=Q,this.apiKey=typeof Z==="string"?Z:null,this.authToken=J}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return P([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return P([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return P([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return p5($)}getUserAgent(){return`${this.constructor.name}/JS ${o$}`}defaultIdempotencyKey(){return`stainless-node-retry-${O2()}`}makeStatusError($,Z,J,Y){return n.generate($,Z,J,Y)}buildURL($,Z,J){let Y=!N(this,o2,"m",L9).call(this)&&J||this.baseURL,Q=k5($)?new URL($):new URL(Y+(Y.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),X=this.defaultQuery(),z=Object.fromEntries(Q.searchParams);if(!F2(X)||!F2(z))Z={...z,...X,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))Q.search=this.stringifyQuery(Z);return Q.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new D("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600000}async prepareOptions($){}async prepareRequest($,{url:Z,options:J}){}get($,Z){return this.methodRequest("get",$,Z)}post($,Z){return this.methodRequest("post",$,Z)}patch($,Z){return this.methodRequest("patch",$,Z)}put($,Z){return this.methodRequest("put",$,Z)}delete($,Z){return this.methodRequest("delete",$,Z)}methodRequest($,Z,J){return this.request(Promise.resolve(J).then((Y)=>{return{method:$,path:Z,...Y}}))}request($,Z=null){return new V4(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,J){let Y=await $,Q=Y.maxRetries??this.maxRetries;if(Z==null)Z=Q;await this.prepareOptions(Y);let{req:X,url:z,timeout:G}=await this.buildRequest(Y,{retryCount:Q-Z});await this.prepareRequest(X,{url:z,options:Y});let V="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=J===void 0?"":`, retryOf: ${J}`,K=Date.now();if(a(this).debug(`[${V}] sending request`,b$({retryOfRequestLogID:J,method:Y.method,url:z,options:Y,headers:X.headers})),Y.signal?.aborted)throw new J$;let M=new AbortController,B=await this.fetchWithTimeout(z,X,G,M).catch(X8),O=Date.now();if(B instanceof globalThis.Error){let T=`retrying, ${Z} attempts remaining`;if(Y.signal?.aborted)throw new J$;let w=k$(B)||/timed? ?out/i.test(String(B)+("cause"in B?String(B.cause):""));if(Z)return a(this).info(`[${V}] connection ${w?"timed out":"failed"} - ${T}`),a(this).debug(`[${V}] connection ${w?"timed out":"failed"} (${T})`,b$({retryOfRequestLogID:J,url:z,durationMs:O-K,message:B.message})),this.retryRequest(Y,Z,J??V);if(a(this).info(`[${V}] connection ${w?"timed out":"failed"} - error; no more retries left`),a(this).debug(`[${V}] connection ${w?"timed out":"failed"} (error; no more retries left)`,b$({retryOfRequestLogID:J,url:z,durationMs:O-K,message:B.message})),w)throw new z8;throw new G4({cause:B})}let j=[...B.headers.entries()].filter(([T])=>T==="request-id").map(([T,w])=>", "+T+": "+JSON.stringify(w)).join(""),A=`[${V}${H}${j}] ${X.method} ${z} ${B.ok?"succeeded":"failed"} with status ${B.status} in ${O-K}ms`;if(!B.ok){let T=await this.shouldRetry(B);if(Z&&T){let E=`retrying, ${Z} attempts remaining`;return await d5(B.body),a(this).info(`${A} - ${E}`),a(this).debug(`[${V}] response error (${E})`,b$({retryOfRequestLogID:J,url:B.url,status:B.status,headers:B.headers,durationMs:O-K})),this.retryRequest(Y,Z,J??V,B.headers)}let w=T?"error; no more retries left":"error; not retryable";a(this).info(`${A} - ${w}`);let N$=await B.text().catch((E)=>X8(E).message),b=A0(N$),f=b?void 0:N$;throw a(this).debug(`[${V}] response error (${w})`,b$({retryOfRequestLogID:J,url:B.url,status:B.status,headers:B.headers,message:f,durationMs:Date.now()-K})),this.makeStatusError(B.status,b,f,B.headers)}return a(this).info(A),a(this).debug(`[${V}] response start`,b$({retryOfRequestLogID:J,url:B.url,status:B.status,headers:B.headers,durationMs:O-K})),{response:B,options:Y,controller:M,requestLogID:V,retryOfRequestLogID:J,startTime:K}}getAPIList($,Z,J){return this.requestAPIList(Z,J&&"then"in J?J.then((Y)=>({method:"get",path:$,...Y})):{method:"get",path:$,...J})}requestAPIList($,Z){let J=this.makeRequest(Z,null,void 0);return new w0(this,J,$)}async fetchWithTimeout($,Z,J,Y){let{signal:Q,method:X,...z}=Z||{},G=this._makeAbort(Y);if(Q)Q.addEventListener("abort",G,{once:!0});let V=setTimeout(G,J),H=globalThis.ReadableStream&&z.body instanceof globalThis.ReadableStream||typeof z.body==="object"&&z.body!==null&&Symbol.asyncIterator in z.body,K={signal:Y.signal,...H?{duplex:"half"}:{},method:"GET",...z};if(X)K.method=X.toUpperCase();try{return await this.fetch.call(void 0,$,K)}finally{clearTimeout(V)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,J,Y){let Q,X=Y?.get("retry-after-ms");if(X){let G=parseFloat(X);if(!Number.isNaN(G))Q=G}let z=Y?.get("retry-after");if(z&&!Q){let G=parseFloat(z);if(!Number.isNaN(G))Q=G*1000;else Q=Date.parse(z)-Date.now()}if(Q===void 0){let G=$.maxRetries??this.maxRetries;Q=this.calculateDefaultRetryTimeoutMillis(Z,G)}return await _5(Q),this.makeRequest($,Z-1,J)}calculateDefaultRetryTimeoutMillis($,Z){let Q=Z-$,X=Math.min(0.5*Math.pow(2,Q),8),z=1-Math.random()*0.25;return X*z*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new D("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let J={...$},{method:Y,path:Q,query:X,defaultBaseURL:z}=J,G=this.buildURL(Q,X,z);if("timeout"in J)y5("timeout",J.timeout);J.timeout=J.timeout??this.timeout;let{bodyHeaders:V,body:H}=this.buildBody({options:J}),K=await this.buildHeaders({options:$,method:Y,bodyHeaders:V,retryCount:Z});return{req:{method:Y,headers:K,...J.signal&&{signal:J.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...J.fetchOptions??{}},url:G,timeout:J.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:J,retryCount:Y}){let Q={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();Q[this.idempotencyHeader]=$.idempotencyKey}let X=P([Q,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(Y),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...m5(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,J,$.headers]);return this.validateHeaders(X),X.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let J=P([Z]);if(ArrayBuffer.isView($)||$ instanceof ArrayBuffer||$ instanceof DataView||typeof $==="string"&&J.values.has("content-type")||globalThis.Blob&&$ instanceof globalThis.Blob||$ instanceof FormData||$ instanceof URLSearchParams||globalThis.ReadableStream&&$ instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:$};else if(typeof $==="object"&&((Symbol.asyncIterator in $)||(Symbol.iterator in $)&&("next"in $)&&typeof $.next==="function"))return{bodyHeaders:void 0,body:D0($)};else if(typeof $==="object"&&J.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery($)};else return N(this,a0,"f").call(this,{body:$,headers:J})}}n2=d,a0=new WeakMap,o2=new WeakSet,L9=function(){return this.baseURL!=="https://api.anthropic.com"};d.Anthropic=n2;d.HUMAN_PROMPT=R9;d.AI_PROMPT=A9;d.DEFAULT_TIMEOUT=600000;d.AnthropicError=D;d.APIError=n;d.APIConnectionError=G4;d.APIConnectionTimeoutError=z8;d.APIUserAbortError=J$;d.NotFoundError=W8;d.ConflictError=H8;d.RateLimitError=U8;d.BadRequestError=K8;d.AuthenticationError=G8;d.InternalServerError=B8;d.PermissionDeniedError=V8;d.UnprocessableEntityError=q8;d.toFile=S0;class x$ extends d{constructor(){super(...arguments);this.completions=new _4(this),this.messages=new B4(this),this.models=new v4(this),this.beta=new D$(this)}}x$.Completions=_4;x$.Messages=B4;x$.Models=v4;x$.Beta=D$;e();s();import{existsSync as Q0,readdirSync as bX,readFileSync as m7,writeFileSync as yX,statSync as j6,realpathSync as _X}from"fs";import{resolve as R$,join as E6,sep as a4}from"path";import{existsSync as aJ,readFileSync as rJ,writeFileSync as sJ}from"fs";import{basename as i2}from"path";var D9=50;class a2{entries=[];saveState($){let Z=aJ($),J=Z?rJ($,"utf-8"):"";if(this.entries.push({path:$,content:J,timestamp:Date.now(),existed:Z}),this.entries.length>D9)this.entries=this.entries.slice(-D9)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${i2($.path)} was a new file. Remove it manually if needed.`;sJ($.path,$.content);let Z=$.content.split(`
87
+ `).length;return`Undo: restored ${i2($.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`${i2($.path)} (${x9($.timestamp)})`}}function x9($){let Z=Math.floor((Date.now()-$)/1000);if(Z<60)return`${Z}s ago`;let J=Math.floor(Z/60);if(J<60)return`${J}m ago`;return`${Math.floor(J/60)}h ago`}s();import{existsSync as T9,readdirSync as tJ,readFileSync as eJ,mkdirSync as $Y}from"fs";import{join as r2}from"path";function P9($){if(!T9($))return[];let Z=[],J=tJ($).filter((Y)=>Y.endsWith(".json"));for(let Y of J)try{let Q=JSON.parse(eJ(r2($,Y),"utf-8"));if(!Q.name||!Q.description||!Q.command)continue;if(typeof Q.name!=="string"||typeof Q.command!=="string")continue;if(Q.command.includes("$(")||Q.command.includes("`"))continue;Z.push({name:Q.name,description:Q.description,inputSchema:Q.input_schema||{type:"object",properties:{},required:[]},command:Q.command,source:r2($,Y)})}catch{}return Z}function I9($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function w9($,Z){let J=$.command;for(let[K,M]of Object.entries(Z)){let B=String(M).replace(/[;&|`$()]/g,"");J=J.replace(new RegExp(`\\{\\{input\\.${K}\\}\\}`,"g"),B)}J=J.replace(/\{\{input\.\w+\}\}/g,"");let Y=D4(),Q=Bun.spawn([...Y,J],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),X=setTimeout(()=>Q.kill(),30000),[z,G]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),V=await Q.exited;clearTimeout(X);let H=z.trim();if(G.trim())H+=(H?`
88
+ `:"")+G.trim();if(V!==0)H+=(H?`
89
+ `:"")+`Exit code: ${V}`;return H||"(no output)"}function S9($){if($.length===0)return"No plugins loaded. Add .json files to ~/.config/smolerclaw/plugins/";return`Plugins:
88
90
  `+$.map((Z)=>` ${Z.name} \u2014 ${Z.description}`).join(`
89
- `)}function H9($){let Z=g2($,"plugins");if(!K9(Z))UY(Z,{recursive:!0});return Z}var BY=/[";`$\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(BY.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}var NY=15000;async function I1($){let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",$],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>Z.kill(),NY),[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 S1($,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 I1(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 b1($){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 I1(`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 I1(`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 I1("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 k1(){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 I1($.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 y1(){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 i$(){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 I1($);return Z.trim()||"Outlook nao disponivel."}catch{return"Outlook nao disponivel."}}function q9(){return Object.keys(m2)}t();import{existsSync as CY,readFileSync as MY}from"fs";import{join as OY}from"path";var _1=[{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="",Y$=[],H$=new Set,N9=()=>OY(d8,"news-feeds.json");function u8(){if(!d8)return;let $={custom:Y$,disabled:[...H$]};P(N9(),JSON.stringify($,null,2))}function EY(){if(!d8)return;let $=N9();if(!CY($)){Y$=[],H$=new Set;return}try{let Z=JSON.parse(MY($,"utf-8"));Y$=Z.custom||[],H$=new Set(Z.disabled||[])}catch{Y$=[],H$=new Set}}function C9($){d8=$,EY()}function u2(){return[..._1.filter((Z)=>!H$.has(Z.url)),...Y$]}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([..._1,...Y$].some((G)=>G.url===X))return"Error: essa URL ja esta cadastrada.";let V={name:J,url:X,category:Q};return Y$=[...Y$,V],u8(),V}function l8($){let Z=$.toLowerCase().trim(),Y=Y$.findIndex((J)=>J.name.toLowerCase()===Z||J.url===$.trim());if(Y===-1)return!1;return Y$=[...Y$.slice(0,Y),...Y$.slice(Y+1)],u8(),!0}function n8($){let Z=$.toLowerCase().trim(),Y=_1.find((J)=>J.name.toLowerCase()===Z||J.url===$.trim());if(!Y)return!1;if(H$.has(Y.url))return!1;return H$=new Set([...H$,Y.url]),u8(),!0}function i8($){let Z=$.toLowerCase().trim(),Y=_1.find((J)=>J.name.toLowerCase()===Z||J.url===$.trim());if(!Y)return!1;if(!H$.has(Y.url))return!1;return H$=new Set([...H$].filter((J)=>J!==Y.url)),u8(),!0}function o8(){let $=["Fontes de noticias:"];$.push(`
92
- --- Built-in ---`);for(let Z of _1){let Y=H$.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${Y} \u2014 ${Z.url}`)}if(Y$.length>0){$.push(`
93
- --- Custom ---`);for(let Z of Y$)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
94
- Total: ${u2().length} ativas (${_1.length} built-in, ${Y$.length} custom, ${H$.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=m4($,"title");if(!J)return null;let Q=m4($,"link")||AY($),X=LY(Q),K=m4($,"pubDate")||m4($,"published")||m4($,"updated"),V;if(K){let G=new Date(K);V=isNaN(G.getTime())?void 0:G}return{title:xY(J),link:X,source:Z,category:Y,pubDate:V}}function LY($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function RY($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function m4($,Z){let Y=RY(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 AY($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}function xY($){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 o$($,Z=5){let Y=Math.max(1,Math.min(Z,d2));if($&&$.length===0)return wY();let J=u2(),Q=$?J.filter((G)=>$.includes(G.category)):J,X=await Promise.allSettled(Q.map((G)=>TY(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}: ${DY(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}),PY(K,V)}function DY($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function TY($,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 PY($,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(`
91
+ `)}function k9($){let Z=r2($,"plugins");if(!T9(Z))$Y(Z,{recursive:!0});return Z}j4();e();import{existsSync as YY,readFileSync as QY}from"fs";import{join as XY}from"path";var g4=[{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}],r0="",X$=[],U$=new Set,v9=()=>XY(r0,"news-feeds.json");function s0(){if(!r0)return;let $={custom:X$,disabled:[...U$]};k(v9(),JSON.stringify($,null,2))}function zY(){if(!r0)return;let $=v9();if(!YY($)){X$=[],U$=new Set;return}try{let Z=JSON.parse(QY($,"utf-8"));X$=Z.custom||[],U$=new Set(Z.disabled||[])}catch{X$=[],U$=new Set}}function f9($){r0=$,zY()}function Z7(){return[...g4.filter((Z)=>!U$.has(Z.url)),...X$]}function t0($,Z,J){let Y=$.trim();if(!Y||Y.length>100)return"Error: nome invalido (1-100 caracteres).";let Q=J.trim().toLowerCase();if(!Q||Q.length>30)return"Error: categoria invalida (1-30 caracteres).";let X=Z.trim();if(!X.startsWith("http://")&&!X.startsWith("https://"))return"Error: URL deve comecar com http:// ou https://";if(X.length>500)return"Error: URL muito longa (max 500 caracteres).";if([...g4,...X$].some((V)=>V.url===X))return"Error: essa URL ja esta cadastrada.";let G={name:Y,url:X,category:Q};return X$=[...X$,G],s0(),G}function e0($){let Z=$.toLowerCase().trim(),J=X$.findIndex((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(J===-1)return!1;return X$=[...X$.slice(0,J),...X$.slice(J+1)],s0(),!0}function $1($){let Z=$.toLowerCase().trim(),J=g4.find((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(!J)return!1;if(U$.has(J.url))return!1;return U$=new Set([...U$,J.url]),s0(),!0}function Z1($){let Z=$.toLowerCase().trim(),J=g4.find((Y)=>Y.name.toLowerCase()===Z||Y.url===$.trim());if(!J)return!1;if(!U$.has(J.url))return!1;return U$=new Set([...U$].filter((Y)=>Y!==J.url)),s0(),!0}function J1(){let $=["Fontes de noticias:"];$.push(`
92
+ --- Built-in ---`);for(let Z of g4){let J=U$.has(Z.url)?" [DESATIVADO]":"";$.push(` (${Z.category}) ${Z.name}${J} \u2014 ${Z.url}`)}if(X$.length>0){$.push(`
93
+ --- Custom ---`);for(let Z of X$)$.push(` (${Z.category}) ${Z.name} \u2014 ${Z.url}`)}return $.push(`
94
+ Total: ${Z7().length} ativas (${g4.length} built-in, ${X$.length} custom, ${U$.size} desativadas)`),$.join(`
95
+ `)}var y9=2097152,$7=10,KY=1e4;function GY($,Z,J){let Y=[],Q=/<item[\s>]([\s\S]*?)<\/item>/gi,X;while((X=Q.exec($))!==null){let z=X[1],G=_9(z,Z,J);if(G)Y.push(G);if(Y.length>=$7)break}if(Y.length===0){let z=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((X=z.exec($))!==null){let G=X[1],V=_9(G,Z,J);if(V)Y.push(V);if(Y.length>=$7)break}}return Y}function _9($,Z,J){let Y=a8($,"title");if(!Y)return null;let Q=a8($,"link")||UY($),X=VY(Q),z=a8($,"pubDate")||a8($,"published")||a8($,"updated"),G;if(z){let V=new Date(z);G=isNaN(V.getTime())?void 0:V}return{title:NY(Y),link:X,source:Z,category:J,pubDate:G}}function VY($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function WY($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function a8($,Z){let J=WY(Z),Q=new RegExp(`<${J}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${J}>`,"i").exec($);if(Q)return Q[1].trim();let z=new RegExp(`<${J}[^>]*>([\\s\\S]*?)</${J}>`,"i").exec($);return z?z[1].trim():null}function HY($,Z){let J=qY($,Z);try{return new TextDecoder(J).decode($)}catch{try{return new TextDecoder("latin1").decode($)}catch{return new TextDecoder("utf-8",{fatal:!1}).decode($)}}}function qY($,Z){if(Z){let Q=Z.match(/charset\s*=\s*["']?([^\s;"']+)/i);if(Q)return h9(Q[1])}let Y=$.subarray(0,200).toString("ascii").match(/<\?xml[^?]+encoding\s*=\s*["']([^"']+)["']/i);if(Y)return h9(Y[1]);return"utf-8"}function h9($){let Z=$.toLowerCase().replace(/[^a-z0-9]/g,"");if(Z==="iso88591"||Z==="latin1")return"iso-8859-1";if(Z==="windows1252"||Z==="cp1252")return"windows-1252";if(Z==="utf8")return"utf-8";if(Z==="usascii"||Z==="ascii")return"utf-8";return $.trim().toLowerCase()}function UY($){let J=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return J?J[1]:null}var BY={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",aacute:"\xE1",Aacute:"\xC1",agrave:"\xE0",Agrave:"\xC0",atilde:"\xE3",Atilde:"\xC3",acirc:"\xE2",Acirc:"\xC2",eacute:"\xE9",Eacute:"\xC9",egrave:"\xE8",Egrave:"\xC8",ecirc:"\xEA",Ecirc:"\xCA",iacute:"\xED",Iacute:"\xCD",oacute:"\xF3",Oacute:"\xD3",otilde:"\xF5",Otilde:"\xD5",ocirc:"\xF4",Ocirc:"\xD4",uacute:"\xFA",Uacute:"\xDA",uuml:"\xFC",Uuml:"\xDC",ccedil:"\xE7",Ccedil:"\xC7",ntilde:"\xF1",Ntilde:"\xD1",rsquo:"\u2019",lsquo:"\u2018",rdquo:"\u201D",ldquo:"\u201C",mdash:"\u2014",ndash:"\u2013",hellip:"\u2026",bull:"\u2022",laquo:"\xAB",raquo:"\xBB",trade:"\u2122",copy:"\xA9",reg:"\xAE",euro:"\u20AC",pound:"\xA3",yen:"\xA5",cent:"\xA2",deg:"\xB0",middot:"\xB7",times:"\xD7",divide:"\xF7"};function NY($){return $.replace(/<[^>]+>/g,"").replace(/&([a-zA-Z]+);/g,(Z,J)=>BY[J]??Z).replace(/&#(\d+);/g,(Z,J)=>String.fromCharCode(Number(J))).replace(/&#x([0-9a-fA-F]+);/g,(Z,J)=>String.fromCharCode(parseInt(J,16))).trim()}async function J7($,Z=5){let J=Math.max(1,Math.min(Z,$7));if($&&$.length===0)return{items:[],errors:[]};let Y=Z7(),Q=$?Y.filter((V)=>$.includes(V.category)):Y,X=await Promise.allSettled(Q.map((V)=>MY(V,J))),z=[],G=[];for(let V=0;V<X.length;V++){let H=X[V];if(H.status==="fulfilled")z.push(...H.value);else G.push(`${Q[V].name}: ${CY(H.reason)}`)}return z.sort((V,H)=>{let K=V.pubDate?.getTime()||0;return(H.pubDate?.getTime()||0)-K}),{items:z,errors:G}}async function m4($,Z=5){if($&&$.length===0)return jY();let{items:J,errors:Y}=await J7($,Z);if(J.length===0)return Y.length>0?`Nenhuma noticia encontrada.
96
+ Falhas: ${Y.join(", ")}`:"Nenhuma noticia encontrada.";return OY(J,Y)}function CY($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function MY($,Z){let J=new AbortController,Y=setTimeout(()=>J.abort(),KY);try{let Q=await fetch($.url,{signal:J.signal,headers:{"User-Agent":"smolerclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(Y),!Q.ok)return[];let X=Q.headers.get("content-length");if(X&&Number(X)>y9)return[];let z=Q.body?.getReader();if(!z)return[];let G=[],V=0;while(!0){let{done:B,value:O}=await z.read();if(B)break;if(V+=O.byteLength,V>y9)return z.cancel(),[];G.push(O)}let H=Buffer.concat(G),K=HY(H,Q.headers.get("content-type"));return GY(K,$.name,$.category).slice(0,Z)}catch(Q){throw clearTimeout(Y),Q}}function OY($,Z){let J={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"},Y=new Map;for(let G of $){let V=Y.get(G.category)||[];Y.set(G.category,[...V,G])}let Q=[],X=["finance","business","tech","security","brazil","world"];for(let G of X){let V=Y.get(G);if(!V||V.length===0)continue;let H=J[G],K=V.slice(0,8).map((M)=>{let B=M.pubDate?M.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${B?`[${B}]`:""} ${M.title} (${M.source})`});Q.push(`--- ${H} ---
97
+ ${K.join(`
98
+ `)}`)}let z=Q.join(`
99
99
 
100
- `);if(Z.length>0)K+=`
100
+ `);if(Z.length>0)z+=`
101
101
 
102
- (Fontes indisponiveis: ${Z.join(", ")})`;return K}function wY(){let $=u2();return`Categorias: ${[...new Set($.map((Y)=>Y.category))].sort().join(", ")}
103
- Uso: /news [categoria]`}import{existsSync as M9,mkdirSync as IY,readFileSync as SY}from"fs";import{join as bY}from"path";import{randomUUID as kY}from"crypto";t();var O9="",d=[],h1=null,E9=null,j9=()=>bY(O9,"tasks.json");function a8(){P(j9(),JSON.stringify(d,null,2))}function yY(){let $=j9();if(!M9($)){d=[];return}try{d=JSON.parse(SY($,"utf-8"))}catch{d=[]}}function F9($,Z){if(O9=$,E9=Z,!M9($))IY($,{recursive:!0});if(yY(),h1)clearInterval(h1);h1=setInterval(_Y,30000),fY().catch(()=>{})}function L9(){if(h1)clearInterval(h1),h1=null}function r8($,Z){let Y={id:vY(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(d=[...d,Y],a8(),Z&&A)p2(Y).catch(()=>{});return Y}function s8($){let Z=$.toLowerCase(),Y=d.find((J)=>J.id===$||J.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(d=d.map((J)=>J.id===Y.id?{...J,done:!0}:J),a8(),Y.dueAt&&A)x9(Y.id).catch(()=>{});return d.find((J)=>J.id===Y.id)||null}function R9($){let Z=$.toLowerCase(),Y=d.findIndex((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(Y===-1)return!1;let J=d[Y];if(d=[...d.slice(0,Y),...d.slice(Y+1)],a8(),J.dueAt&&A)x9(J.id).catch(()=>{});return!0}function a$($=!1){return $?[...d]:d.filter((Z)=>!Z.done)}function q1($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let J=Y.done?"[x]":"[ ]",Q=Y.dueAt?` (${gY(Y.dueAt)})`:"";return` ${J} ${Y.title}${Q} [${Y.id}]`});return`Tarefas (${$.length}):
102
+ (Fontes indisponiveis: ${Z.join(", ")})`;return z}function jY(){let $=Z7();return`Categorias: ${[...new Set($.map((J)=>J.category))].sort().join(", ")}
103
+ Uso: /news [categoria]`}s();e();import{existsSync as g9,mkdirSync as EY,readFileSync as FY}from"fs";import{join as LY}from"path";import{randomUUID as RY}from"crypto";var m9="",u=[],c4=null,c9=null,d9=()=>LY(m9,"tasks.json");function Y1(){k(d9(),JSON.stringify(u,null,2))}function AY(){let $=d9();if(!g9($)){u=[];return}try{u=JSON.parse(FY($,"utf-8"))}catch{u=[]}}function u9($,Z){if(m9=$,c9=Z,!g9($))EY($,{recursive:!0});if(AY(),c4)clearInterval(c4);c4=setInterval(DY,30000),TY().catch(()=>{})}function p9(){if(c4)clearInterval(c4),c4=null}function Q1($,Z){let J={id:PY(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(u=[...u,J],Y1(),Z&&x)Y7(J).catch(()=>{});return J}function X1($){let Z=$.toLowerCase(),J=u.find((Y)=>Y.id===$||Y.title.toLowerCase().includes(Z));if(!J||J.done)return null;if(u=u.map((Y)=>Y.id===J.id?{...Y,done:!0}:Y),Y1(),J.dueAt&&x)n9(J.id).catch(()=>{});return u.find((Y)=>Y.id===J.id)||null}function l9($){let Z=$.toLowerCase(),J=u.findIndex((Q)=>Q.id===$||Q.title.toLowerCase().includes(Z));if(J===-1)return!1;let Y=u[J];if(u=[...u.slice(0,J),...u.slice(J+1)],Y1(),Y.dueAt&&x)n9(Y.id).catch(()=>{});return!0}function t$($=!1){return $?[...u]:u.filter((Z)=>!Z.done)}function E4($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((J)=>{let Y=J.done?"[x]":"[ ]",Q=J.dueAt?` (${IY(J.dueAt)})`:"";return` ${Y} ${J.title}${Q} [${J.id}]`});return`Tarefas (${$.length}):
104
104
  ${Z.join(`
105
- `)}`}function c4($){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 _Y(){let $=new Date,Z=!1;for(let Y of d){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)d=d.map((X)=>X.id===Y.id?{...X,notified:!0}:X),Z=!0,hY(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 hY($){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 fY(){if(!A)return;let $=Date.now();for(let Z of d){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 vY(){return kY().slice(0,8)}function gY($){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}`}t();import{existsSync as D9,mkdirSync as mY,readFileSync as cY}from"fs";import{join as dY}from"path";import{randomUUID as uY}from"crypto";var T9="",J$=[],P9=()=>dY(T9,"memos.json");function w9(){P(P9(),JSON.stringify(J$,null,2))}function pY(){let $=P9();if(!D9($)){J$=[];return}try{J$=JSON.parse(cY($,"utf-8"))}catch{J$=[]}}function I9($){if(T9=$,!D9($))mY($,{recursive:!0});pY()}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:nY(),content:$.trim(),tags:Q,createdAt:Y,updatedAt:Y};return J$=[...J$,X],w9(),X}function S9($){let Z=J$.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return J$=[...J$.slice(0,Z),...J$.slice(Z+1)],w9(),!0}function e8($){let Z=$.toLowerCase().trim();if(!Z)return[...J$];let Y=Z.startsWith("#"),J=Y?Z.slice(1):Z;return J$.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 d4($=20){return[...J$].reverse().sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function lY(){let $=new Map;for(let Z of J$)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 U1($){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}):
105
+ `)}`}function r8($){let Z=new Date,J=$.toLowerCase().trim(),Y=J.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(Y){let z=parseInt(Y[1]),G=Y[2].startsWith("h")?"hours":"minutes",V=new Date(Z);if(G==="hours")V.setHours(V.getHours()+z);else V.setMinutes(V.getMinutes()+z);return V}let Q=new Date(Z);if(J.includes("amanha")||J.includes("amanh\xE3"))Q.setDate(Q.getDate()+1);let X=J.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(X){let z=parseInt(X[1]),G=parseInt(X[2]||"0");if(z>=0&&z<=23&&G>=0&&G<=59){if(Q.setHours(z,G,0,0),Q<=Z&&!J.includes("amanha")&&!J.includes("amanh\xE3"))Q.setDate(Q.getDate()+1);return Q}}return null}function DY(){let $=new Date,Z=!1;for(let J of u){if(J.done||J.notified||!J.dueAt)continue;let Y=new Date(J.dueAt);if(isNaN(Y.getTime()))continue;let Q=$.getTime()-Y.getTime();if(Q>=0&&Q<300000)u=u.map((X)=>X.id===J.id?{...X,notified:!0}:X),Z=!0,xY(J),c9?.(J)}if(Z)Y1()}function o9($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}async function xY($){if(!x)return;let J=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">smolerclaw - Lembrete</text><text id="2">${o9($.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 Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",J],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>Y.kill(),1e4);await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),await Y.exited,clearTimeout(Q)}catch{}}var Q7="smolerclaw-reminder-";async function Y7($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let J=`${Q7}${$.id}`,Y=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),Q=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),z=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null;","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null;","$x = New-Object Windows.Data.Xml.Dom.XmlDocument;",`$x.LoadXml('<toast><visual><binding template=""ToastText02""><text id=""1"">smolerclaw</text><text id=""2"">${o9($.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",J,"/SC","ONCE","/SD",Y,"/ST",Q,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${z}"`,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function n9($){let Z=`${Q7}${$}`;try{await Bun.spawn(["schtasks","/Delete","/TN",Z,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function TY(){if(!x)return;let $=Date.now();for(let Z of u){if(Z.done||Z.notified||!Z.dueAt)continue;let J=new Date(Z.dueAt);if(isNaN(J.getTime())||J.getTime()<=$)continue;try{if(await Bun.spawn(["schtasks","/Query","/TN",`${Q7}${Z.id}`],{stdout:"pipe",stderr:"pipe"}).exited!==0)await Y7(Z)}catch{await Y7(Z)}}}function PY(){return RY().slice(0,8)}function IY($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let J=new Date,Y=new Date(J.getFullYear(),J.getMonth(),J.getDate()),Q=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),X=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(Q.getTime()===Y.getTime())return`hoje ${X}`;let z=new Date(Y);if(z.setDate(z.getDate()+1),Q.getTime()===z.getTime())return`amanha ${X}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${X}`}e();import{existsSync as i9,mkdirSync as wY,readFileSync as SY}from"fs";import{join as kY}from"path";import{randomUUID as bY}from"crypto";var a9="",z$=[],r9=()=>kY(a9,"memos.json");function s9(){k(r9(),JSON.stringify(z$,null,2))}function yY(){let $=r9();if(!i9($)){z$=[];return}try{z$=JSON.parse(SY($,"utf-8"))}catch{z$=[]}}function t9($){if(a9=$,!i9($))wY($,{recursive:!0});yY()}function z1($,Z=[]){let J=new Date().toISOString(),Y=$.match(/#(\w+)/g)?.map((z)=>z.slice(1).toLowerCase())||[],Q=[...new Set([...Z.map((z)=>z.toLowerCase()),...Y])],X={id:hY(),content:$.trim(),tags:Q,createdAt:J,updatedAt:J};return z$=[...z$,X],s9(),X}function e9($){let Z=z$.findIndex((J)=>J.id===$);if(Z===-1)return!1;return z$=[...z$.slice(0,Z),...z$.slice(Z+1)],s9(),!0}function K1($){let Z=$.toLowerCase().trim();if(!Z)return[...z$];let J=Z.startsWith("#"),Y=J?Z.slice(1):Z;return z$.filter((Q)=>{if(J)return Q.tags.some((X)=>X.includes(Y));return Q.content.toLowerCase().includes(Y)||Q.tags.some((X)=>X.includes(Y))}).sort((Q,X)=>new Date(X.updatedAt).getTime()-new Date(Q.updatedAt).getTime())}function s8($=20){return[...z$].reverse().sort((Z,J)=>new Date(J.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function _Y(){let $=new Map;for(let Z of z$)for(let J of Z.tags)$.set(J,($.get(J)||0)+1);return[...$.entries()].map(([Z,J])=>({tag:Z,count:J})).sort((Z,J)=>J.count-Z.count)}function F4($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((J)=>{let Y=new Date(J.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=J.tags.length>0?` [${J.tags.map((z)=>`#${z}`).join(" ")}]`:"",X=J.content.length>80?J.content.slice(0,80).replace(/\n/g," ")+"...":J.content.replace(/\n/g," ");return` [${Y}] ${X}${Q} {${J.id}}`});return`Memos (${$.length}):
106
106
  ${Z.join(`
107
- `)}`}function b9(){let $=lY();if($.length===0)return"Nenhuma tag.";return`Tags:
108
- ${$.map((Y)=>` #${Y.tag} (${Y.count})`).join(`
109
- `)}`}function nY(){return uY().slice(0,8)}async function $0($){if(A)return iY($);return n2($)}async function iY($){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
- `)}t();import{existsSync as y9,mkdirSync as oY,readFileSync as aY}from"fs";import{join as rY}from"path";import{randomUUID as sY}from"crypto";var _9="",r$=[],h9=()=>rY(_9,"finance.json");function tY(){P(h9(),JSON.stringify(r$,null,2))}function eY(){let $=h9();if(!y9($)){r$=[];return}try{r$=JSON.parse(aY($,"utf-8"))}catch{r$=[]}}function f9($){if(_9=$,!y9($))oY($,{recursive:!0});eY()}function u4($,Z,Y,J){let Q={id:$J(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:J.trim(),date:new Date().toISOString()};return r$=[...r$,Q],tY(),Q}function Y0($,Z){let Y=new Date,J=$||Y.getFullYear(),Q=Z!==void 0?Z:Y.getMonth(),X=r$.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 L=V>0?Math.round(E/V*100):0;z.push(` ${N.padEnd(15)} R$ ${E.toFixed(2)} (${L}%)`)}}return z.join(`
112
- `)}function i2($=10){let Z=[...r$].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 $J(){return sY().slice(0,8)}function k9($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}t();import{existsSync as v9,mkdirSync as ZJ,readFileSync as YJ}from"fs";import{join as JJ}from"path";import{randomUUID as QJ}from"crypto";var g9="",s$=[],m9=()=>JJ(g9,"decisions.json");function XJ(){P(m9(),JSON.stringify(s$,null,2))}function KJ(){let $=m9();if(!v9($)){s$=[];return}try{s$=JSON.parse(YJ($,"utf-8"))}catch{s$=[]}}function c9($){if(g9=$,!v9($))ZJ($,{recursive:!0});KJ()}function d9($,Z,Y,J,Q=[]){let X={id:zJ(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:J?.trim(),tags:Q.map((K)=>K.toLowerCase()),date:new Date().toISOString()};return s$=[...s$,X],XJ(),X}function J0($){let Z=$.toLowerCase();return s$.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[...s$].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function f1($){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
+ `)}`}function $Z(){let $=_Y();if($.length===0)return"Nenhuma tag.";return`Tags:
108
+ ${$.map((J)=>` #${J.tag} (${J.count})`).join(`
109
+ `)}`}function hY(){return bY().slice(0,8)}s();async function G1($){if(x)return vY($);return X7($)}async function vY($){let Z=$.to.replace(/'/g,"''"),J=$.subject.replace(/'/g,"''"),Y=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),Q=$.cc?.replace(/'/g,"''")||"",X=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${J}'`,` $mail.Body = '${Y}'`,Q?` $mail.CC = '${Q}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
110
+ `);try{let z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",X],{stdout:"pipe",stderr:"pipe"}),G=setTimeout(()=>z.kill(),15000),[V]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]);await z.exited,clearTimeout(G);let H=V.trim();if(H.includes("mailto"))return X7($);return H||"Email aberto no Outlook."}catch{return X7($)}}async function X7($){let Z=[];if($.subject)Z.push(`subject=${encodeURIComponent($.subject)}`);if($.body)Z.push(`body=${encodeURIComponent($.body)}`);if($.cc)Z.push(`cc=${encodeURIComponent($.cc)}`);let J=`mailto:${encodeURIComponent($.to)}${Z.length?"?"+Z.join("&"):""}`;try{let Y=x?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${J}'`]:["xdg-open",J],Q=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>Q.kill(),1e4);return await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),await Q.exited,clearTimeout(X),"Email aberto no cliente de email padrao."}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}function V1($){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
+ `)}e();import{existsSync as JZ,mkdirSync as fY,readFileSync as gY}from"fs";import{join as mY}from"path";import{randomUUID as cY}from"crypto";var YZ="",e$=[],QZ=()=>mY(YZ,"finance.json");function dY(){k(QZ(),JSON.stringify(e$,null,2))}function uY(){let $=QZ();if(!JZ($)){e$=[];return}try{e$=JSON.parse(gY($,"utf-8"))}catch{e$=[]}}function XZ($){if(YZ=$,!JZ($))fY($,{recursive:!0});uY()}function t8($,Z,J,Y){let Q={id:pY(),type:$,amount:Math.abs(Z),category:J.toLowerCase().trim(),description:Y.trim(),date:new Date().toISOString()};return e$=[...e$,Q],dY(),Q}function W1($,Z){let J=new Date,Y=$||J.getFullYear(),Q=Z!==void 0?Z:J.getMonth(),X=e$.filter((M)=>{let B=new Date(M.date);return B.getFullYear()===Y&&B.getMonth()===Q});if(X.length===0)return`Nenhuma transacao em ${ZZ(Q)}/${Y}.`;let z=X.filter((M)=>M.type==="entrada").reduce((M,B)=>M+B.amount,0),G=X.filter((M)=>M.type==="saida").reduce((M,B)=>M+B.amount,0),V=z-G,H=new Map;for(let M of X.filter((B)=>B.type==="saida"))H.set(M.category,(H.get(M.category)||0)+M.amount);let K=[`--- Resumo ${ZZ(Q)}/${Y} ---`,`Entradas: R$ ${z.toFixed(2)}`,`Saidas: R$ ${G.toFixed(2)}`,`Saldo: R$ ${V.toFixed(2)} ${V>=0?"":"(NEGATIVO)"}`];if(H.size>0){K.push(""),K.push("Saidas por categoria:");let M=[...H.entries()].sort((B,O)=>O[1]-B[1]);for(let[B,O]of M){let j=G>0?Math.round(O/G*100):0;K.push(` ${B.padEnd(15)} R$ ${O.toFixed(2)} (${j}%)`)}}return K.join(`
112
+ `)}function z7($=10){let Z=[...e$].sort((Y,Q)=>new Date(Q.date).getTime()-new Date(Y.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
113
+ ${Z.map((Y)=>{let Q=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.type==="entrada"?"+":"-";return` [${Q}] ${X} R$ ${Y.amount.toFixed(2)} ${Y.category} \u2014 ${Y.description} [${Y.id}]`}).join(`
114
+ `)}`}function pY(){return cY().slice(0,8)}function ZZ($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}e();import{existsSync as zZ,mkdirSync as lY,readFileSync as oY}from"fs";import{join as nY}from"path";import{randomUUID as iY}from"crypto";var KZ="",$4=[],GZ=()=>nY(KZ,"decisions.json");function aY(){k(GZ(),JSON.stringify($4,null,2))}function rY(){let $=GZ();if(!zZ($)){$4=[];return}try{$4=JSON.parse(oY($,"utf-8"))}catch{$4=[]}}function VZ($){if(KZ=$,!zZ($))lY($,{recursive:!0});rY()}function WZ($,Z,J,Y,Q=[]){let X={id:sY(),title:$.trim(),context:Z.trim(),chosen:J.trim(),alternatives:Y?.trim(),tags:Q.map((z)=>z.toLowerCase()),date:new Date().toISOString()};return $4=[...$4,X],aY(),X}function H1($){let Z=$.toLowerCase();return $4.filter((J)=>J.title.toLowerCase().includes(Z)||J.chosen.toLowerCase().includes(Z)||J.context.toLowerCase().includes(Z)||J.tags.some((Y)=>Y.includes(Z))).sort((J,Y)=>new Date(Y.date).getTime()-new Date(J.date).getTime())}function q1($=15){return[...$4].sort((Z,J)=>new Date(J.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function d4($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((J)=>{let Y=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=J.tags.length>0?` [${J.tags.join(", ")}]`:"";return` [${Y}] ${J.title}${Q} {${J.id}}`});return`Decisoes (${$.length}):
115
115
  ${Z.join(`
116
- `)}`}function zJ(){return QJ().slice(0,8)}l4();t();import{existsSync as a9,mkdirSync as BJ,readFileSync as NJ}from"fs";import{join as CJ}from"path";import{randomUUID as MJ}from"crypto";var r9="",I={people:[],interactions:[],delegations:[]},s9=()=>CJ(r9,"people.json");function z0(){P(s9(),JSON.stringify(I,null,2))}function OJ(){let $=s9();if(!a9($)){I={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(NJ($,"utf-8"));I={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{I={people:[],interactions:[],delegations:[]}}}function t9($){if(r9=$,!a9($))BJ($,{recursive:!0});OJ()}function V0($,Z,Y,J){let Q={id:K7(),name:$.trim(),group:Z,role:Y?.trim(),contact:J?.trim(),createdAt:new Date().toISOString()};return I={...I,people:[...I.people,Q]},z0(),Q}function t$($){let Z=$.toLowerCase();return I.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function G0($){if($)return I.people.filter((Z)=>Z.group===$);return[...I.people]}function e9($,Z,Y,J){let Q=t$($);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 I={...I,interactions:[...I.interactions,X]},z0(),X}function EJ($,Z=10){let Y=t$($);if(!Y)return[];return[...I.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 n4(){let $=new Date,Z=[];for(let Y of I.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let J=new Date(Y.followUpDate);if(isNaN(J.getTime()))continue;if(J<=$){let Q=I.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=t$($);if(!J)return null;let Q={id:K7(),personId:J.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return I={...I,delegations:[...I.delegations,Q]},z0(),Q}function $Z($,Z,Y){if(!I.delegations.find((Q)=>Q.id===$))return null;return I={...I,delegations:I.delegations.map((Q)=>Q.id===$?{...Q,status:Z,notes:Y||Q.notes}:Q)},z0(),I.delegations.find((Q)=>Q.id===$)||null}function v1($,Z=!0){let Y=[...I.delegations];if($){let Q=t$($);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(`
118
- `)}`)}return Y.join(`
116
+ `)}`}function sY(){return iY().slice(0,8)}$0();e();import{existsSync as MZ,mkdirSync as QQ,readFileSync as XQ}from"fs";import{join as zQ}from"path";import{randomUUID as KQ}from"crypto";var OZ="",y={people:[],interactions:[],delegations:[]},jZ=()=>zQ(OZ,"people.json");function N1(){k(jZ(),JSON.stringify(y,null,2))}function GQ(){let $=jZ();if(!MZ($)){y={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(XQ($,"utf-8"));y={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{y={people:[],interactions:[],delegations:[]}}}function EZ($){if(OZ=$,!MZ($))QQ($,{recursive:!0});GQ()}function C1($,Z,J,Y){let Q={id:j7(),name:$.trim(),group:Z,role:J?.trim(),contact:Y?.trim(),createdAt:new Date().toISOString()};return y={...y,people:[...y.people,Q]},N1(),Q}function Z4($){let Z=$.toLowerCase();return y.people.find((J)=>J.id===$||J.name.toLowerCase().includes(Z))||null}function M1($){if($)return y.people.filter((Z)=>Z.group===$);return[...y.people]}function FZ($,Z,J,Y){let Q=Z4($);if(!Q)return null;let X={id:j7(),personId:Q.id,date:new Date().toISOString(),type:Z,summary:J.trim(),followUpDate:Y?.toISOString(),followUpDone:!1};return y={...y,interactions:[...y.interactions,X]},N1(),X}function VQ($,Z=10){let J=Z4($);if(!J)return[];return[...y.interactions].filter((Y)=>Y.personId===J.id).reverse().sort((Y,Q)=>new Date(Q.date).getTime()-new Date(Y.date).getTime()).slice(0,Z)}function Z0(){let $=new Date,Z=[];for(let J of y.interactions){if(J.followUpDone||!J.followUpDate)continue;let Y=new Date(J.followUpDate);if(isNaN(Y.getTime()))continue;if(Y<=$){let Q=y.people.find((X)=>X.id===J.personId);if(Q)Z.push({person:Q,interaction:J})}}return Z.sort((J,Y)=>new Date(J.interaction.followUpDate).getTime()-new Date(Y.interaction.followUpDate).getTime())}function O1($,Z,J){let Y=Z4($);if(!Y)return null;let Q={id:j7(),personId:Y.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:J?.toISOString(),status:"pendente"};return y={...y,delegations:[...y.delegations,Q]},N1(),Q}function LZ($,Z,J){if(!y.delegations.find((Q)=>Q.id===$))return null;return y={...y,delegations:y.delegations.map((Q)=>Q.id===$?{...Q,status:Z,notes:J||Q.notes}:Q)},N1(),y.delegations.find((Q)=>Q.id===$)||null}function u4($,Z=!0){let J=[...y.delegations];if($){let Q=Z4($);if(!Q)return[];J=J.filter((X)=>X.personId===Q.id)}if(Z)J=J.filter((Q)=>Q.status!=="concluido");let Y=new Date;return J=J.map((Q)=>{if(Q.status==="pendente"&&Q.dueDate){let X=new Date(Q.dueDate);if(!isNaN(X.getTime())&&X<Y)return{...Q,status:"atrasado"}}return Q}),J.sort((Q,X)=>{if(Q.status==="atrasado"&&X.status!=="atrasado")return-1;if(X.status==="atrasado"&&Q.status!=="atrasado")return 1;let z=Q.dueDate?new Date(Q.dueDate).getTime():1/0,G=X.dueDate?new Date(X.dueDate).getTime():1/0;return z-G})}var RZ={equipe:"Equipe",familia:"Familia",contato:"Contato"};function j1($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let Q of $){let X=Z.get(Q.group)||[];Z.set(Q.group,[...X,Q])}let J=[],Y=["equipe","familia","contato"];for(let Q of Y){let X=Z.get(Q);if(!X?.length)continue;let z=X.map((G)=>{let V=G.role?` (${G.role})`:"",H=G.contact?` \u2014 ${G.contact}`:"";return` ${G.name}${V}${H} [${G.id}]`});J.push(`--- ${RZ[Q]} ---
117
+ ${z.join(`
118
+ `)}`)}return J.join(`
119
119
 
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=EJ($.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=v1($.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=I.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}):
120
+ `)}function E1($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${RZ[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let J=VQ($.id,5);if(J.length>0){Z.push(`
121
+ Interacoes recentes:`);for(let Q of J){let X=new Date(Q.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${X}] ${Q.type}: ${Q.summary}`)}}let Y=u4($.id);if(Y.length>0){Z.push(`
122
+ Tarefas delegadas:`);for(let Q of Y){let X=Q.status==="atrasado"?"!!":Q.status==="em_andamento"?">>":" ",z=Q.dueDate?` (${E7(Q.dueDate)})`:"";Z.push(` ${X} ${Q.task}${z} [${Q.status}]`)}}return Z.join(`
123
+ `)}function F1($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((J)=>{let Q=y.people.find((G)=>G.id===J.personId)?.name||"?",X=J.status==="atrasado"?"!! ":J.status==="em_andamento"?">> ":" ",z=J.dueDate?` (${E7(J.dueDate)})`:"";return`${X}${Q}: ${J.task}${z} [${J.status}] [${J.id}]`});return`Delegacoes (${$.length}):
124
124
  ${Z.join(`
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}):
125
+ `)}`}function L1($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:J,interaction:Y})=>{return` [${E7(Y.followUpDate)}] ${J.name}: ${Y.summary} [${Y.id}]`});return`Follow-ups pendentes (${$.length}):
126
126
  ${Z.join(`
127
- `)}`}function N0(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
128
- `);let Z=I.people.filter((H)=>H.group==="equipe").length,Y=I.people.filter((H)=>H.group==="familia").length,J=I.people.filter((H)=>H.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${J}`);let Q=n4();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=v1(),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=I.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=[...I.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=I.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(`
127
+ `)}`}function R1(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
128
+ `);let Z=y.people.filter((H)=>H.group==="equipe").length,J=y.people.filter((H)=>H.group==="familia").length,Y=y.people.filter((H)=>H.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${J} | Contatos: ${Y}`);let Q=Z0();if(Q.length>0){$.push(`
129
+ !! ${Q.length} follow-up(s) pendente(s):`);for(let{person:H,interaction:K}of Q.slice(0,5))$.push(` ${H.name}: ${K.summary}`)}let X=u4(),z=X.filter((H)=>H.status==="atrasado"),G=X.filter((H)=>H.status==="pendente"||H.status==="em_andamento");if(z.length>0){$.push(`
130
+ !! ${z.length} delegacao(oes) atrasada(s):`);for(let H of z.slice(0,5)){let K=y.people.find((M)=>M.id===H.personId);$.push(` ${K?.name}: ${H.task}`)}}if(G.length>0)$.push(`
131
+ ${G.length} delegacao(oes) em andamento`);let V=[...y.interactions].sort((H,K)=>new Date(K.date).getTime()-new Date(H.date).getTime()).slice(0,3);if(V.length>0){$.push(`
132
+ Ultimas interacoes:`);for(let H of V){let K=y.people.find((B)=>B.id===H.personId),M=new Date(H.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${M}] ${K?.name}: ${H.summary}`)}}return $.push(`
133
133
  ========================`),$.join(`
134
- `)}function K7(){return MJ().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"})}t();import{existsSync as YZ,mkdirSync as jJ,readFileSync as FJ}from"fs";import{join as LJ}from"path";import{randomUUID as RJ}from"crypto";var JZ="",u=[],QZ=()=>LJ(JZ,"materials.json");function V7(){P(QZ(),JSON.stringify(u,null,2))}function AJ(){let $=QZ();if(!YZ($)){u=[];return}try{u=JSON.parse(FJ($,"utf-8"))}catch{u=[]}}function XZ($){if(JZ=$,!YZ($))jJ($,{recursive:!0});AJ()}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:xJ(),title:$.trim(),content:Z.trim(),category:Y.toLowerCase().trim(),tags:V,createdAt:Q,updatedAt:Q};return u=[...u,G],V7(),G}function KZ($,Z){let Y=u.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 u=u.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(),u.find((H)=>H.id===$)||null}function M0($){let Z=u.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return u=[...u.slice(0,Z),...u.slice(Z+1)],V7(),!0}function zZ($){return u.find((Z)=>Z.id===$)||null}function O0($){let Z=$.toLowerCase().trim();if(!Z)return[...u];let Y=Z.startsWith("#"),J=Z.startsWith("@"),Q=Y||J?Z.slice(1):Z;return u.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 g1($=30,Z){let Y=[...u];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 u)$.set(Z.category,($.get(Z.category)||0)+1);return[...$.entries()].map(([Z,Y])=>({category:Z,count:Y})).sort((Z,Y)=>Y.count-Z.count)}function GZ(){if(u.length===0)return"";let $=VZ(),Z=["--- Materiais do Assistente ---"];for(let{category:Y}of $){let J=u.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 e$($){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}):
134
+ `)}function j7(){return KQ().slice(0,8)}function E7($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let J=new Date,Y=new Date(J.getFullYear(),J.getMonth(),J.getDate()),Q=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(Q.getTime()===Y.getTime())return"hoje";let X=new Date(Y);if(X.setDate(X.getDate()+1),Q.getTime()===X.getTime())return"amanha";let z=Math.floor((Q.getTime()-Y.getTime())/86400000);if(z<0)return`${Math.abs(z)}d atras`;if(z<=7)return`em ${z}d`;return Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}e();import{existsSync as AZ,mkdirSync as WQ,readFileSync as HQ}from"fs";import{join as qQ}from"path";import{randomUUID as UQ}from"crypto";var DZ="",p=[],xZ=()=>qQ(DZ,"materials.json");function F7(){k(xZ(),JSON.stringify(p,null,2))}function BQ(){let $=xZ();if(!AZ($)){p=[];return}try{p=JSON.parse(HQ($,"utf-8"))}catch{p=[]}}function TZ($){if(DZ=$,!AZ($))WQ($,{recursive:!0});BQ()}function A1($,Z,J="geral",Y=[]){let Q=new Date().toISOString(),X=Z.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],z=$.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],G=[...new Set([...Y.map((H)=>H.toLowerCase()),...X,...z])],V={id:NQ(),title:$.trim(),content:Z.trim(),category:J.toLowerCase().trim(),tags:G,createdAt:Q,updatedAt:Q};return p=[...p,V],F7(),V}function PZ($,Z){let J=p.find((H)=>H.id===$);if(!J)return null;let Y=Z.content??J.content,Q=Z.title??J.title,X=Y.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],z=Q.match(/#(\w+)/g)?.map((H)=>H.slice(1).toLowerCase())||[],G=Z.tags??J.tags,V=[...new Set([...G.map((H)=>H.toLowerCase()),...X,...z])];return p=p.map((H)=>H.id===$?{...H,title:Q.trim(),content:Y.trim(),category:(Z.category??H.category).toLowerCase().trim(),tags:V,updatedAt:new Date().toISOString()}:H),F7(),p.find((H)=>H.id===$)||null}function D1($){let Z=p.findIndex((J)=>J.id===$);if(Z===-1)return!1;return p=[...p.slice(0,Z),...p.slice(Z+1)],F7(),!0}function IZ($){return p.find((Z)=>Z.id===$)||null}function x1($){let Z=$.toLowerCase().trim();if(!Z)return[...p];let J=Z.startsWith("#"),Y=Z.startsWith("@"),Q=J||Y?Z.slice(1):Z;return p.filter((X)=>{if(J)return X.tags.some((z)=>z.includes(Q));if(Y)return X.category.includes(Q);return X.title.toLowerCase().includes(Q)||X.content.toLowerCase().includes(Q)||X.category.toLowerCase().includes(Q)||X.tags.some((z)=>z.includes(Q))}).sort((X,z)=>new Date(z.updatedAt).getTime()-new Date(X.updatedAt).getTime())}function p4($=30,Z){let J=[...p];if(Z){let Y=Z.toLowerCase().trim();J=J.filter((Q)=>Q.category===Y)}return J.sort((Y,Q)=>new Date(Q.updatedAt).getTime()-new Date(Y.updatedAt).getTime()).slice(0,$)}function wZ(){let $=new Map;for(let Z of p)$.set(Z.category,($.get(Z.category)||0)+1);return[...$.entries()].map(([Z,J])=>({category:Z,count:J})).sort((Z,J)=>J.count-Z.count)}function SZ(){if(p.length===0)return"";let $=wZ(),Z=["--- Materiais do Assistente ---"];for(let{category:J}of $){let Y=p.filter((Q)=>Q.category===J).sort((Q,X)=>new Date(X.updatedAt).getTime()-new Date(Q.updatedAt).getTime());Z.push(`
135
+ [${J}]`);for(let Q of Y){let X=Q.content.length>200?Q.content.slice(0,200).replace(/\n/g," ")+"...":Q.content.replace(/\n/g," "),z=Q.tags.length>0?` [${Q.tags.map((G)=>`#${G}`).join(" ")}]`:"";Z.push(` \u2022 ${Q.title}: ${X}${z}`)}}return Z.join(`
136
+ `)}function J4($){if($.length===0)return"Nenhum material encontrado.";let Z=$.map((J)=>{let Y=new Date(J.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),Q=J.tags.length>0?` [${J.tags.map((z)=>`#${z}`).join(" ")}]`:"",X=J.content.length>60?J.content.slice(0,60).replace(/\n/g," ")+"...":J.content.replace(/\n/g," ");return` [${Y}] (${J.category}) ${J.title} \u2014 ${X}${Q} {${J.id}}`});return`Materiais (${$.length}):
137
137
  ${Z.join(`
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}} ---
138
+ `)}`}function kZ($){let Z=new Date($.createdAt).toLocaleDateString("pt-BR"),J=new Date($.updatedAt).toLocaleDateString("pt-BR"),Y=$.tags.length>0?`Tags: ${$.tags.map((X)=>`#${X}`).join(" ")}`:"",Q=Z===J?`Criado: ${Z}`:`Criado: ${Z} | Atualizado: ${J}`;return`--- Material {${$.id}} ---
139
139
  Titulo: ${$.title}
140
140
  Categoria: ${$.category}
141
141
 
142
142
  ${$.content}
143
143
 
144
- ${J}
145
- ${Q}`}function HZ(){let $=VZ();if($.length===0)return"Nenhuma categoria.";return`Categorias:
146
- ${$.map((Y)=>` @${Y.category} (${Y.count})`).join(`
147
- `)}`}function xJ(){return RJ().slice(0,8)}t();import{existsSync as N1,mkdirSync as DJ,readFileSync as m1,readdirSync as TJ}from"fs";import{join as B1}from"path";import{createHash as PJ}from"crypto";var BZ=1,G7=400,wJ=80,qZ=1.5,UZ=0.75,IJ=10,SJ=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"]),i4="",E0="",s=[],k$={},y$=0,_$={},j0=!1,H7=()=>B1(E0,"rag-index.json");function NZ($){if(i4=$,E0=B1($,"rag"),!N1(E0))DJ(E0,{recursive:!0});vJ(),j0=!0}function F0(){return j0}function L0(){return{chunks:s.length,sources:Object.keys(_$).length,builtAt:s.length>0?gJ()?.builtAt??null:null}}function R0(){if(!j0)throw Error("Memory not initialized. Call initMemory() first.");let $=_J(),Z=0,Y=0,J={},Q=new Set;for(let[K,V]of Object.entries($)){let G=mJ(V);if(J[K]=G,_$[K]!==G)Q.add(K)}let X=Object.keys(_$).filter((K)=>!(K in $));if(Q.size===0&&X.length===0)return{indexed:0,skipped:Object.keys($).length,total:s.length};s=s.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=cJ(H,z,V),E=yJ(V,H,z,N);s=[...s,...E],Z++}return Y=Object.keys($).length-Z,hJ(),_$=J,fJ(),{indexed:Z,skipped:Y,total:s.length}}function A0($,Z=3){if(s.length===0)return[];let Y=W7($);if(Y.length===0)return[];return s.map((Q)=>{let X=bJ(Y,Q),K=kJ(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,IJ))}function x0($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((Y,J)=>{let Q=dJ(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}):
144
+ ${Y}
145
+ ${Q}`}function bZ(){let $=wZ();if($.length===0)return"Nenhuma categoria.";return`Categorias:
146
+ ${$.map((J)=>` @${J.category} (${J.count})`).join(`
147
+ `)}`}function NQ(){return UQ().slice(0,8)}e();import{existsSync as R4,mkdirSync as CQ,readFileSync as l4,readdirSync as MQ}from"fs";import{join as L4}from"path";import{createHash as OQ}from"crypto";var hZ=1,L7=400,jQ=80,yZ=1.5,_Z=0.75,EQ=10,FQ=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"]),J0="",T1="",$$=[],f$={},g$=0,m$={},P1=!1,A7=()=>L4(T1,"rag-index.json");function vZ($){if(J0=$,T1=L4($,"rag"),!R4(T1))CQ(T1,{recursive:!0});PQ(),P1=!0}function I1(){return P1}function w1(){return{chunks:$$.length,sources:Object.keys(m$).length,builtAt:$$.length>0?IQ()?.builtAt??null:null}}function S1(){if(!P1)throw Error("Memory not initialized. Call initMemory() first.");let $=DQ(),Z=0,J=0,Y={},Q=new Set;for(let[z,G]of Object.entries($)){let V=wQ(G);if(Y[z]=V,m$[z]!==V)Q.add(z)}let X=Object.keys(m$).filter((z)=>!(z in $));if(Q.size===0&&X.length===0)return{indexed:0,skipped:Object.keys($).length,total:$$.length};$$=$$.filter((z)=>{let G=`${z.source}:${z.sourceId}`;return!Q.has(G)&&!X.includes(G)});for(let z of Q){let G=$[z],V=z.indexOf(":");if(V===-1)continue;let H=z.slice(0,V),K=z.slice(V+1);if(!["memo","material","session","decision"].includes(H))continue;let B=SQ(H,K,G),O=AQ(G,H,K,B);$$=[...$$,...O],Z++}return J=Object.keys($).length-Z,xQ(),m$=Y,TQ(),{indexed:Z,skipped:J,total:$$.length}}function k1($,Z=3){if($$.length===0)return[];let J=R7($);if(J.length===0)return[];return $$.map((Q)=>{let X=LQ(J,Q),z=RQ(J,Q),G=0.6*X+0.4*z;return{chunk:Q,score:G}}).filter((Q)=>Q.score>0).sort((Q,X)=>X.score-Q.score).slice(0,Math.min(Z,EQ))}function b1($){if($.length===0)return"Nenhum resultado encontrado na memoria local.";let Z=$.map((J,Y)=>{let Q=kQ(J.chunk.source),X=(J.score*100).toFixed(1),z=J.chunk.content.length>300?J.chunk.content.slice(0,300).replace(/\n/g," ")+"...":J.chunk.content.replace(/\n/g," ");return`[${Y+1}] ${Q}: ${J.chunk.title} (relevancia: ${X}%)
148
+ ${z}`});return`Resultados da memoria (${$.length}):
149
149
 
150
150
  ${Z.join(`
151
151
 
152
- `)}`}function bJ($,Z){let Y=Z.tokens.length;if(Y===0||y$===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=k$[X]??0;if(V===0)continue;let G=K*(qZ+1),H=K+qZ*(1-UZ+UZ*(Y/y$));Q+=V*(G/H)}return Q}function kJ($,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=k$[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&&!SJ.has(Z))}function yJ($,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-wJ,V++}return X}function _J(){let $={},Z=B1(i4,"memos.json");if(N1(Z))try{let X=JSON.parse(m1(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=B1(i4,"materials.json");if(N1(Y))try{let X=JSON.parse(m1(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=B1(i4,"decisions.json");if(N1(J))try{let X=JSON.parse(m1(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=B1(i4,"sessions");if(N1(Q))try{let X=TJ(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=B1(Q,K);try{let G=JSON.parse(m1(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(`
152
+ `)}`}function LQ($,Z){let J=Z.tokens.length;if(J===0||g$===0)return 0;let Y=new Map;for(let X of Z.tokens)Y.set(X,(Y.get(X)??0)+1);let Q=0;for(let X of $){let z=Y.get(X)??0;if(z===0)continue;let G=f$[X]??0;if(G===0)continue;let V=z*(yZ+1),H=z+yZ*(1-_Z+_Z*(J/g$));Q+=G*(V/H)}return Q}function RQ($,Z){let J=new Map;for(let H of $)J.set(H,(J.get(H)??0)+1);let Y=new Map;for(let H of Z.tokens)Y.set(H,(Y.get(H)??0)+1);let Q=new Set([...$,...Z.tokens]),X=0,z=0,G=0;for(let H of Q){let K=f$[H]??0,M=(J.get(H)??0)*K,B=(Y.get(H)??0)*K;X+=M*B,z+=M*M,G+=B*B}let V=Math.sqrt(z)*Math.sqrt(G);return V>0?X/V:0}function R7($){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&&!FQ.has(Z))}function AQ($,Z,J,Y){let Q=$.trim();if(Q.length===0)return[];if(Q.length<=L7)return[{id:`${Z}:${J}:0`,source:Z,sourceId:J,title:Y,content:Q,tokens:R7(Q)}];let X=[],z=0,G=0;while(z<Q.length){let V=Math.min(z+L7,Q.length),H=Q.slice(z,V);X.push({id:`${Z}:${J}:${G}`,source:Z,sourceId:J,title:Y,content:H,tokens:R7(H)}),z+=L7-jQ,G++}return X}function DQ(){let $={},Z=L4(J0,"memos.json");if(R4(Z))try{let X=JSON.parse(l4(Z,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let z of X){if(!z||typeof z!=="object")continue;let G=z;if(typeof G.id!=="string"||typeof G.content!=="string")continue;let V=Array.isArray(G.tags)&&G.tags.length>0?` [${G.tags.join(", ")}]`:"";$[`memo:${G.id}`]=`${G.content}${V}`}}catch{}let J=L4(J0,"materials.json");if(R4(J))try{let X=JSON.parse(l4(J,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let z of X){if(!z||typeof z!=="object")continue;let G=z;if(typeof G.id!=="string"||typeof G.title!=="string"||typeof G.content!=="string")continue;let V=typeof G.category==="string"?G.category:"geral",H=Array.isArray(G.tags)&&G.tags.length>0?` [${G.tags.join(", ")}]`:"";$[`material:${G.id}`]=`${G.title}
153
+ ${V}
154
+ ${G.content}${H}`}}catch{}let Y=L4(J0,"decisions.json");if(R4(Y))try{let X=JSON.parse(l4(Y,"utf-8"));if(!Array.isArray(X))throw Error("not an array");for(let z of X){if(!z||typeof z!=="object")continue;let G=z;if(typeof G.id!=="string"||typeof G.title!=="string"||typeof G.context!=="string"||typeof G.chosen!=="string")continue;let V=[G.title,G.context,`Escolha: ${G.chosen}`];if(typeof G.alternatives==="string")V.push(`Alternativas: ${G.alternatives}`);if(Array.isArray(G.tags)&&G.tags.length>0)V.push(`[${G.tags.join(", ")}]`);$[`decision:${G.id}`]=V.join(`
155
+ `)}}catch{}let Q=L4(J0,"sessions");if(R4(Q))try{let X=MQ(Q,{withFileTypes:!0}).filter((z)=>z.isFile()&&z.name.endsWith(".json")&&!z.name.startsWith(".")).map((z)=>z.name);for(let z of X){let G=L4(Q,z);try{let V=JSON.parse(l4(G,"utf-8"));if(!V||typeof V!=="object"||!Array.isArray(V.messages))continue;let H=V.messages.filter((K)=>{if(!K||typeof K!=="object")return!1;let M=K;return M.role==="assistant"&&typeof M.content==="string"&&M.content.length>50}).map((K)=>K.content).join(`
156
156
  ---
157
- `);if(H.length>0)$[`session:${G.id}`]=H}catch{}}}catch{}return $}function hJ(){let $=s.length;if($===0){k$={},y$=0;return}let Z=new Map,Y=0;for(let Q of s){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}y$=Y/$;let J={};for(let[Q,X]of Z)J[Q]=Math.log(($-X+0.5)/(X+0.5)+1);k$=J}function fJ(){if(!j0)return;let $={chunks:s,idf:k$,avgDocLength:y$,sourceHashes:_$,builtAt:new Date().toISOString(),version:BZ};P(H7(),JSON.stringify($))}function vJ(){let $=H7();if(!N1($)){s=[],k$={},y$=0,_$={};return}try{let Z=JSON.parse(m1($,"utf-8"));if(Z.version!==BZ){s=[],k$={},y$=0,_$={};return}s=Z.chunks,k$=Z.idf,y$=Z.avgDocLength,_$=Z.sourceHashes}catch{s=[],k$={},y$=0,_$={}}}function gJ(){let $=H7();if(!N1($))return null;try{return{builtAt:JSON.parse(m1($,"utf-8")).builtAt}}catch{return null}}function mJ($){return PJ("sha256").update($).digest("hex").slice(0,16)}function cJ($,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 dJ($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}import{writeFileSync as uJ,unlinkSync as pJ,existsSync as lJ}from"fs";import{join as nJ}from"path";import{tmpdir as iJ}from"os";import{randomUUID as oJ}from"crypto";var aJ=30000,CZ=50000,MZ=1e5,rJ=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,sJ=[{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)"}],tJ=[{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 sJ)if(Z.test($))return{safe:!1,blocked:!0,reason:Y};for(let{pattern:Z,reason:Y}of tJ)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=oJ().slice(0,8),J=nJ(iJ(),`smolerclaw-${Y}.ps1`);try{uJ(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"))},aJ)}),V=(async()=>{let[N,E]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),L=await X.exited;return{stdout:N,stderr:E,exitCode:L}})(),{stdout:G,stderr:H,exitCode:z}=await Promise.race([V,K]),M=Math.round(performance.now()-Q);return{stdout:c1(G),stderr:c1(H),exitCode:z,duration:M}}finally{try{if(lJ(J))pJ(J)}catch{}}}async function T0(){if(!A)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await eJ();if($.type==="text")return $;return await $Q()}async function eJ(){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=c1(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 $Q(){try{let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-STA","-Command",`
157
+ `);if(H.length>0)$[`session:${V.id}`]=H}catch{}}}catch{}return $}function xQ(){let $=$$.length;if($===0){f$={},g$=0;return}let Z=new Map,J=0;for(let Q of $$){let X=new Set;for(let z of Q.tokens)if(!X.has(z))Z.set(z,(Z.get(z)??0)+1),X.add(z);J+=Q.tokens.length}g$=J/$;let Y={};for(let[Q,X]of Z)Y[Q]=Math.log(($-X+0.5)/(X+0.5)+1);f$=Y}function TQ(){if(!P1)return;let $={chunks:$$,idf:f$,avgDocLength:g$,sourceHashes:m$,builtAt:new Date().toISOString(),version:hZ};k(A7(),JSON.stringify($))}function PQ(){let $=A7();if(!R4($)){$$=[],f$={},g$=0,m$={};return}try{let Z=JSON.parse(l4($,"utf-8"));if(Z.version!==hZ){$$=[],f$={},g$=0,m$={};return}$$=Z.chunks,f$=Z.idf,g$=Z.avgDocLength,m$=Z.sourceHashes}catch{$$=[],f$={},g$=0,m$={}}}function IQ(){let $=A7();if(!R4($))return null;try{return{builtAt:JSON.parse(l4($,"utf-8")).builtAt}}catch{return null}}function wQ($){return OQ("sha256").update($).digest("hex").slice(0,16)}function SQ($,Z,J){switch($){case"material":{let Y=J.split(`
158
+ `)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"memo":return J.slice(0,60).replace(/\n/g," ")+(J.length>60?"...":"");case"decision":{let Y=J.split(`
159
+ `)[0];return Y.length>60?Y.slice(0,60)+"...":Y}case"session":return`Sessao ${Z}`;default:return Z}}function kQ($){switch($){case"memo":return"Memo";case"material":return"Material";case"session":return"Sessao";case"decision":return"Decisao";default:return $}}s();import{writeFileSync as bQ,unlinkSync as yQ,existsSync as _Q}from"fs";import{join as hQ}from"path";import{tmpdir as vQ}from"os";import{randomUUID as fQ}from"crypto";var gQ=30000,fZ=50000,gZ=1e5,mQ=/[\x1b\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nq-uy=><~]/g,cQ=[{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)"}],dQ=[{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 D7($){for(let{pattern:Z,reason:J}of cQ)if(Z.test($))return{safe:!1,blocked:!0,reason:J};for(let{pattern:Z,reason:J}of dQ)if(Z.test($))return{safe:!1,blocked:!1,reason:J};return{safe:!0,blocked:!1}}async function y1($){if(!x)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>fZ)return{stdout:"",stderr:`Error: script too long (${$.length} chars, max ${fZ}).`,exitCode:1,duration:0};let Z=D7($);if(Z.blocked)return{stdout:"",stderr:`BLOCKED: ${Z.reason}`,exitCode:1,duration:0};let J=fQ().slice(0,8),Y=hQ(vQ(),`smolerclaw-${J}.ps1`);try{bQ(Y,$,"utf-8");let Q=performance.now(),X=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-File",Y],{stdout:"pipe",stderr:"pipe"}),z=new Promise((B,O)=>{setTimeout(()=>{X.kill(),O(Error("Script timeout exceeded"))},gQ)}),G=(async()=>{let[B,O]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),j=await X.exited;return{stdout:B,stderr:O,exitCode:j}})(),{stdout:V,stderr:H,exitCode:K}=await Promise.race([G,z]),M=Math.round(performance.now()-Q);return{stdout:o4(V),stderr:o4(H),exitCode:K,duration:M}}finally{try{if(_Q(Y))yQ(Y)}catch{}}}async function _1(){if(!x)return{type:"error",text:"Clipboard reading only available on Windows."};let $=await uQ();if($.type==="text")return $;return await pQ()}async function uQ(){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"}),J=new Promise((z,G)=>{setTimeout(()=>{Z.kill(),G(Error("clipboard timeout"))},1e4)}),Y=(async()=>{let[z]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return await Z.exited,z})(),Q=await Promise.race([Y,J]),X=o4(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 pQ(){try{let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-STA","-Command",`
160
160
  Add-Type -AssemblyName System.Windows.Forms
161
161
  $img = [System.Windows.Forms.Clipboard]::GetImage()
162
162
  if (-not $img) {
@@ -206,8 +206,8 @@ try {
206
206
  } finally {
207
207
  if (Test-Path $tmpFile) { Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue }
208
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=c1(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 $=`
209
+ `],{stdout:"pipe",stderr:"pipe"}),J=new Promise((z,G)=>{setTimeout(()=>{Z.kill(),G(Error("OCR timeout"))},20000)}),Y=(async()=>{let[z]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return await Z.exited,z})(),Q=await Promise.race([Y,J]),X=o4(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 h1(){if(!x)return"Error: screen context analysis only available on Windows.";let $=`
211
211
  $sig = @'
212
212
  [DllImport("user32.dll")]
213
213
  public static extern IntPtr GetForegroundWindow();
@@ -240,66 +240,77 @@ Get-Process | Where-Object { $_.MainWindowTitle -ne '' } |
240
240
  $marker = if ($_.Id -eq $fgPid) { " [ACTIVE]" } else { "" }
241
241
  Write-Output " PID:$($_.Id) | $($_.ProcessName) | $($_.MemMB)MB | $($_.MainWindowTitle)$marker"
242
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=c1(Q).trim();if(!K&&X.trim())return`Error: ${c1(X).trim()}`;return K||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}function c1($){let Z=$.replace(rJ,"");if(Z.length>MZ)return Z.slice(0,MZ)+`
244
- ... (truncated, ${Z.length} total chars)`;return Z}t();import{existsSync as B$,mkdirSync as ZQ,readFileSync as I0}from"fs";import{join as Q$,basename as YQ}from"path";import{randomUUID as JQ}from"crypto";var d1="",C$=[],N$=[],L$=[],$1=null,OZ=()=>Q$(d1,"projects.json"),EZ=()=>Q$(d1,"work-sessions.json"),jZ=()=>Q$(d1,"opportunities.json"),FZ=()=>Q$(d1,"active-project.txt");function QQ(){P(OZ(),JSON.stringify(C$,null,2))}function B7(){P(EZ(),JSON.stringify(N$,null,2))}function LZ(){P(jZ(),JSON.stringify(L$,null,2))}function XQ(){P(FZ(),$1||"")}function KQ(){C$=U7(OZ,[]),N$=U7(EZ,[]),L$=U7(jZ,[]);let $=FZ();if(B$($))try{$1=I0($,"utf-8").trim()||null}catch{$1=null}}function U7($,Z){let Y=$();if(!B$(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(d1=$,!B$($))ZQ($,{recursive:!0});KQ()}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 C$=[...C$,X],QQ(),X}function S0($){let Z=$.toLowerCase().trim();return C$.find((Y)=>Y.id===$)||C$.find((Y)=>Y.name.toLowerCase()===Z)||C$.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function b0($=!1){return($?C$.filter((Y)=>Y.active):[...C$]).sort((Y,J)=>new Date(J.createdAt).getTime()-new Date(Y.createdAt).getTime())}function u1($){let Z=S0($);if(!Z)return null;return $1=Z.id,XQ(),Z}function Z1(){if(!$1)return null;return C$.find(($)=>$.id===$1)||null}function k0($,Z=""){if(!C$.find((Q)=>Q.id===$))return null;zQ($);let J={id:C7(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return N$=[...N$,J],B7(),J}function y0($,Z){let Y=N$.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 N$=N$.map((K)=>K.id===$?{...K,endedAt:J.toISOString(),durationMinutes:X,notes:Z?`${K.notes}
245
- ${Z}`.trim():K.notes}:K),B7(),N$.find((K)=>K.id===$)||null}function zQ($){let Z=new Date;N$=N$.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 Y1($){return N$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function VQ($,Z,Y){let J=Y||new Date;return N$.filter((Q)=>{if(Q.projectId!==$)return!1;let X=new Date(Q.startedAt);return X>=Z&&X<=J})}async function GQ($,Z="1 day ago"){if(!B$(Q$($,".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((L)=>L.split("|||")[0]))],X=J.map((L)=>L.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 L of V.stdout.trim().split(`
247
- `)){let w=L.match(/(\d+)\s+files?\s+changed/),S=L.match(/(\d+)\s+insertions?/),k=L.match(/(\d+)\s+deletions?/);if(w)G+=parseInt(w[1]);if(S)H+=parseInt(S[1]);if(k)z+=parseInt(k[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 L of M.stdout.trim().split(`
248
- `).filter(Boolean))N.set(L,(N.get(L)||0)+1);let E=[...N.entries()].sort((L,w)=>w[1]-L[1]).slice(0,10).map(([L])=>L);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 L$=[...L$,V],LZ(),V}function xZ($,Z){if(!L$.find((J)=>J.id===$))return null;return L$=L$.map((J)=>J.id===$?{...J,status:Z,updatedAt:new Date().toISOString()}:J),LZ(),L$.find((J)=>J.id===$)||null}function _0($,Z){let Y=[...L$];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 GQ(J.path,K),G=VQ(J.id,X),H=G.reduce((N,E)=>N+E.durationMinutes,0),z=0;try{let N=Q$(d1,"tasks.json");if(B$(N))z=JSON.parse(I0(N,"utf-8")).filter((L)=>{if(!L.done)return!1;return new Date(L.createdAt)>=X}).length}catch{}let M=WQ(J,Z,V,G,H,z,Y);return{project:J,period:Z,gitSummary:V,sessions:G,totalMinutes:H,completedTasks:z,markdown:M}}function WQ($,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 L=new Date(E.startedAt).toLocaleTimeString(V?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),w=E.durationMinutes>0?`${E.durationMinutes}m`:V?"em andamento":"ongoing",S=E.notes?` \u2014 ${E.notes}`:"";G.push(`- ${L} (${w})${S}`)}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===$1?" [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}):
243
+ `;try{let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",$],{stdout:"pipe",stderr:"pipe"}),J=new Promise((G,V)=>{setTimeout(()=>{Z.kill(),V(Error("screen context timeout"))},15000)}),Y=(async()=>{let[G,V]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]);return await Z.exited,{stdout:G,stderr:V}})(),{stdout:Q,stderr:X}=await Promise.race([Y,J]),z=o4(Q).trim();if(!z&&X.trim())return`Error: ${o4(X).trim()}`;return z||"Nenhuma janela visivel encontrada."}catch(Z){return`Error: ${Z instanceof Error?Z.message:String(Z)}`}}function o4($){let Z=$.replace(mQ,"");if(Z.length>gZ)return Z.slice(0,gZ)+`
244
+ ... (truncated, ${Z.length} total chars)`;return Z}e();import{existsSync as j$,mkdirSync as lQ,readFileSync as f1}from"fs";import{join as K$,basename as oQ}from"path";import{randomUUID as nQ}from"crypto";var n4="",F$=[],E$=[],T$=[],Y4=null,mZ=()=>K$(n4,"projects.json"),cZ=()=>K$(n4,"work-sessions.json"),dZ=()=>K$(n4,"opportunities.json"),uZ=()=>K$(n4,"active-project.txt");function iQ(){k(mZ(),JSON.stringify(F$,null,2))}function T7(){k(cZ(),JSON.stringify(E$,null,2))}function pZ(){k(dZ(),JSON.stringify(T$,null,2))}function aQ(){k(uZ(),Y4||"")}function rQ(){F$=x7(mZ,[]),E$=x7(cZ,[]),T$=x7(dZ,[]);let $=uZ();if(j$($))try{Y4=f1($,"utf-8").trim()||null}catch{Y4=null}}function x7($,Z){let J=$();if(!j$(J))return Z;try{return JSON.parse(f1(J,"utf-8"))}catch(Y){if(process.env.DEBUG)console.error(`[projects] Failed to load ${J}: ${Y instanceof Error?Y.message:Y}`);return Z}}function lZ($){if(n4=$,!j$($))lQ($,{recursive:!0});rQ()}function P7($,Z,J="",Y=[],Q=[]){let X={id:I7(),name:$.trim(),path:Z.trim(),description:J.trim(),tags:Y.map((z)=>z.trim().toLowerCase()).filter(Boolean),techStack:Q.map((z)=>z.trim().toLowerCase()).filter(Boolean),createdAt:new Date().toISOString(),active:!0};return F$=[...F$,X],iQ(),X}function g1($){let Z=$.toLowerCase().trim();return F$.find((J)=>J.id===$)||F$.find((J)=>J.name.toLowerCase()===Z)||F$.find((J)=>J.name.toLowerCase().includes(Z))||null}function m1($=!1){return($?F$.filter((J)=>J.active):[...F$]).sort((J,Y)=>new Date(Y.createdAt).getTime()-new Date(J.createdAt).getTime())}function i4($){let Z=g1($);if(!Z)return null;return Y4=Z.id,aQ(),Z}function Q4(){if(!Y4)return null;return F$.find(($)=>$.id===Y4)||null}function c1($,Z=""){if(!F$.find((Q)=>Q.id===$))return null;sQ($);let Y={id:I7(),projectId:$,startedAt:new Date().toISOString(),endedAt:null,durationMinutes:0,notes:Z.trim()};return E$=[...E$,Y],T7(),Y}function d1($,Z){let J=E$.find((z)=>z.id===$);if(!J||J.endedAt)return null;let Y=new Date,Q=new Date(J.startedAt),X=Math.round((Y.getTime()-Q.getTime())/60000);return E$=E$.map((z)=>z.id===$?{...z,endedAt:Y.toISOString(),durationMinutes:X,notes:Z?`${z.notes}
245
+ ${Z}`.trim():z.notes}:z),T7(),E$.find((z)=>z.id===$)||null}function sQ($){let Z=new Date;E$=E$.map((J)=>{if(J.projectId===$&&!J.endedAt){let Y=new Date(J.startedAt),Q=Math.round((Z.getTime()-Y.getTime())/60000);return{...J,endedAt:Z.toISOString(),durationMinutes:Q}}return J}),T7()}function X4($){return E$.find((Z)=>!Z.endedAt&&($?Z.projectId===$:!0))||null}function tQ($,Z,J){let Y=J||new Date;return E$.filter((Q)=>{if(Q.projectId!==$)return!1;let X=new Date(Q.startedAt);return X>=Z&&X<=Y})}async function eQ($,Z="1 day ago"){if(!j$(K$($,".git")))return null;try{let J=await v1(["git","log",`--since=${Z}`,"--format=%an|||%s","--no-merges"],$);if(!J.ok||!J.stdout.trim())return{commits:0,authors:[],filesChanged:0,insertions:0,deletions:0,topFiles:[],messages:[]};let Y=J.stdout.trim().split(`
246
+ `).filter(Boolean),Q=[...new Set(Y.map((j)=>j.split("|||")[0]))],X=Y.map((j)=>j.split("|||")[1]||"").filter(Boolean),z=await v1(["git","diff","--stat",`--since=${Z}`,"HEAD"],$),G=await v1(["git","log",`--since=${Z}`,"--shortstat","--format=","--no-merges"],$),V=0,H=0,K=0;if(G.ok&&G.stdout.trim())for(let j of G.stdout.trim().split(`
247
+ `)){let A=j.match(/(\d+)\s+files?\s+changed/),T=j.match(/(\d+)\s+insertions?/),w=j.match(/(\d+)\s+deletions?/);if(A)V+=parseInt(A[1]);if(T)H+=parseInt(T[1]);if(w)K+=parseInt(w[1])}let M=await v1(["git","log",`--since=${Z}`,"--name-only","--format=","--no-merges"],$),B=new Map;if(M.ok&&M.stdout.trim())for(let j of M.stdout.trim().split(`
248
+ `).filter(Boolean))B.set(j,(B.get(j)||0)+1);let O=[...B.entries()].sort((j,A)=>A[1]-j[1]).slice(0,10).map(([j])=>j);return{commits:Y.length,authors:Q,filesChanged:V,insertions:H,deletions:K,topFiles:O,messages:X}}catch{return null}}async function v1($,Z){let J=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:Z}),[Y,Q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),X=await J.exited;return{stdout:Y.trim(),stderr:Q.trim(),ok:X===0}}function oZ($,Z,J,Y=[],Q="media",X=null){let z=new Date().toISOString(),G={id:I7(),title:$.trim(),description:Z.trim(),source:J.trim(),techRequired:Y.map((V)=>V.toLowerCase()),priority:Q,status:"nova",deadline:X,createdAt:z,updatedAt:z};return T$=[...T$,G],pZ(),G}function nZ($,Z){if(!T$.find((Y)=>Y.id===$))return null;return T$=T$.map((Y)=>Y.id===$?{...Y,status:Z,updatedAt:new Date().toISOString()}:Y),pZ(),T$.find((Y)=>Y.id===$)||null}function u1($,Z){let J=[...T$];if($)J=J.filter((Y)=>Y.status===$);if(Z&&Z.length>0){let Y=Z.map((Q)=>Q.toLowerCase());J=J.filter((Q)=>Q.techRequired.some((X)=>Y.includes(X)))}return J.sort((Y,Q)=>{let X={alta:3,media:2,baixa:1};return(X[Q.priority]||0)-(X[Y.priority]||0)})}async function p1($,Z="today",J="pt"){let Y=g1($);if(!Y)return null;let X=new Date(new Date);switch(Z){case"today":X.setHours(0,0,0,0);break;case"week":X.setDate(X.getDate()-7);break;case"month":X.setDate(X.getDate()-30);break}let z=Z==="today"?"1 day ago":Z==="week"?"7 days ago":"30 days ago",G=await eQ(Y.path,z),V=tQ(Y.id,X),H=V.reduce((B,O)=>B+O.durationMinutes,0),K=0;try{let B=K$(n4,"tasks.json");if(j$(B))K=JSON.parse(f1(B,"utf-8")).filter((j)=>{if(!j.done)return!1;return new Date(j.createdAt)>=X}).length}catch{}let M=$X(Y,Z,G,V,H,K,J);return{project:Y,period:Z,gitSummary:G,sessions:V,totalMinutes:H,completedTasks:K,markdown:M}}function $X($,Z,J,Y,Q,X,z){let G=z==="pt",V=[],H=new Date,K=H.toLocaleDateString(G?"pt-BR":"en-US",{day:"2-digit",month:"2-digit",year:"numeric"});if(V.push(`# ${G?"Relatorio de Progresso":"Work Progress Report"}`),V.push(`**${G?"Projeto":"Project"}:** ${$.name}`),V.push(`**${G?"Periodo":"Period"}:** ${Z} (${K})`),V.push(`**${G?"Caminho":"Path"}:** \`${$.path}\``),$.techStack.length>0)V.push(`**Tech:** ${$.techStack.join(", ")}`);V.push("");let M=Math.floor(Q/60),B=Q%60;if(V.push(`## ${G?"Tempo Trabalhado":"Time Tracked"}`),V.push(`- **${G?"Total":"Total"}:** ${M}h ${B}m`),V.push(`- **${G?"Sessoes":"Sessions"}:** ${Y.length}`),X>0)V.push(`- **${G?"Tarefas concluidas":"Tasks completed"}:** ${X}`);if(V.push(""),J&&J.commits>0){if(V.push(`## ${G?"Atividade Git":"Git Activity"}`),V.push(`- **Commits:** ${J.commits}`),J.authors.length>0)V.push(`- **${G?"Autores":"Authors"}:** ${J.authors.join(", ")}`);if(V.push(`- **${G?"Arquivos alterados":"Files changed"}:** ${J.filesChanged}`),V.push(`- **${G?"Linhas":"Lines"}:** +${J.insertions} / -${J.deletions}`),J.messages.length>0){V.push(""),V.push(`### ${G?"Commits recentes":"Recent commits"}`);for(let O of J.messages.slice(0,15))V.push(`- ${O}`)}if(J.topFiles.length>0){V.push(""),V.push(`### ${G?"Arquivos mais alterados":"Most changed files"}`);for(let O of J.topFiles.slice(0,8))V.push(`- \`${O}\``)}V.push("")}else V.push(`## ${G?"Atividade Git":"Git Activity"}`),V.push(G?"_Nenhum commit no periodo._":"_No commits in this period._"),V.push("");if(Y.length>0){V.push(`## ${G?"Sessoes de Trabalho":"Work Sessions"}`);for(let O of Y){let j=new Date(O.startedAt).toLocaleTimeString(G?"pt-BR":"en-US",{hour:"2-digit",minute:"2-digit"}),A=O.durationMinutes>0?`${O.durationMinutes}m`:G?"em andamento":"ongoing",T=O.notes?` \u2014 ${O.notes}`:"";V.push(`- ${j} (${A})${T}`)}V.push("")}return V.push("---"),V.push(G?`_Gerado por smolerclaw em ${H.toLocaleString("pt-BR")}_`:`_Generated by smolerclaw at ${H.toLocaleString("en-US")}_`),V.join(`
249
+ `)}function l1($){if($.length===0)return"Nenhum projeto cadastrado.";let Z=$.map((J)=>{let Y=J.id===Y4?" [ATIVO]":"",Q=J.active?"":" (inativo)",X=J.techStack.length>0?` [${J.techStack.join(", ")}]`:"";return` ${J.name}${Y}${Q}${X} \u2014 ${J.path} {${J.id}}`});return`Projetos (${$.length}):
250
250
  ${Z.join(`
251
- `)}`}function v0($){let Z=$.id===$1?" [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=Y1($.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}):
251
+ `)}`}function o1($){let Z=$.id===Y4?" [ATIVO]":"",J=[`--- Projeto {${$.id}}${Z} ---`,`Nome: ${$.name}`,`Caminho: ${$.path}`];if($.description)J.push(`Descricao: ${$.description}`);if($.techStack.length>0)J.push(`Tech: ${$.techStack.join(", ")}`);if($.tags.length>0)J.push(`Tags: ${$.tags.map((Q)=>`#${Q}`).join(" ")}`);J.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),J.push(`Status: ${$.active?"ativo":"inativo"}`);let Y=X4($.id);if(Y){let Q=new Date(Y.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});J.push(`Sessao aberta: desde ${Q}`)}return J.join(`
252
+ `)}function n1($){if($.length===0)return"Nenhuma oportunidade encontrada.";let Z=$.map((J)=>{let Y={alta:"!!!",media:"!!",baixa:"!"}[J.priority],Q=J.techRequired.length>0?` [${J.techRequired.join(", ")}]`:"",X=J.deadline?` \u2014 prazo: ${J.deadline}`:"";return` ${Y} (${J.status}) ${J.title}${Q}${X} \u2014 ${J.source} {${J.id}}`});return`Oportunidades (${$.length}):
253
253
  ${Z.join(`
254
- `)}`}function DZ(){let $=Z1();if(!$)return"";let Z=Y1($.id),Y=L$.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=C$.find((Q)=>Q.path===$);if(Z)return Z;if(!B$(Q$($,".git")))return null;let Y=[];if(B$(Q$($,"package.json")))try{let Q=JSON.parse(I0(Q$($,"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(B$(Q$($,"bun.lock")))Y.push("bun");else Y.push("node")}catch{}if(B$(Q$($,"Cargo.toml")))Y.push("rust");if(B$(Q$($,"go.mod")))Y.push("go");if(B$(Q$($,"requirements.txt"))||B$(Q$($,"pyproject.toml")))Y.push("python");let J=YQ($);return N7(J,$,"",[],Y)}function C7(){return JQ().slice(0,8)}var l1=new v2,kZ=[];function yZ($){kZ=$}var n=[{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:[]}}],BQ=[{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:[]}}],NQ=[{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:[]}}],CQ=[{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"]}}],MQ={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"]}},OQ=[{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"]}}],EQ=[{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:[]}}],LQ=[{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"]}}],RQ=[{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:[]}}],AQ=[{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"]}}],xQ=[{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:[]}}],DQ=[{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:[]}}],TQ=_Z.find(($)=>$.name==="get_news"),TZ=!1,h$=null;function hZ($){h$=$}function fZ(){if(TZ)return;if(TZ=!0,A)n.push(..._Z),n.push(...RQ);else n.push(TQ);n.push(...BQ),n.push(...NQ),n.push(...CQ),n.push(MQ),n.push(...OQ),n.push(...EQ),n.push(...jQ),n.push(...xQ),n.push(...AQ),n.push(...FQ),n.push(...LQ),n.push(...DQ)}var d0=50000;async function E7($,Z){try{switch($){case"read_file":return PQ(Z);case"write_file":return wQ(Z);case"edit_file":return IQ(Z);case"search_files":return await SQ(Z);case"find_files":return await yQ(Z);case"list_directory":return _Q(Z);case"run_command":return await hQ(Z);case"fetch_url":return await fQ(Z);case"open_application":return await S1(Z.name,Z.argument);case"open_file_default":return await m8(Z.path);case"open_url_browser":return await b1(Z.url);case"get_running_apps":return await c8();case"get_system_info":return await k1();case"get_calendar_events":return await i$();case"get_news":{let Y=Z.category;return await o$(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?c4(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=a$(Y);return q1(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=t$(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 U1(d4());let J=e8(Y);return U1(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=u4(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 f1(Q0());return f1(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 e$(g1());let J=O0(Y);return e$(J)}case"list_materials":{let Y=Z.category,J=Z.limit||30,Q=g1(J,Y);return e$(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:
254
+ `)}`}function iZ(){let $=Q4();if(!$)return"";let Z=X4($.id),J=T$.filter((Q)=>Q.status==="nova").length,Y=["--- Projetos ---"];if(Y.push(`Projeto ativo: ${$.name} (${$.path})`),Z){let Q=new Date(Z.startedAt).toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Y.push(`Sessao aberta desde ${Q}`)}if(J>0)Y.push(`${J} oportunidade(s) nova(s) pendente(s)`);return Y.join(`
255
+ `)}function i1($){let Z=F$.find((Q)=>Q.path===$);if(Z)return Z;if(!j$(K$($,".git")))return null;let J=[];if(j$(K$($,"package.json")))try{let Q=JSON.parse(f1(K$($,"package.json"),"utf-8"));if(Q.dependencies?.typescript||Q.devDependencies?.typescript)J.push("typescript");if(Q.dependencies?.react)J.push("react");if(Q.dependencies?.next)J.push("nextjs");if(Q.dependencies?.vue)J.push("vue");if(j$(K$($,"bun.lock")))J.push("bun");else J.push("node")}catch{}if(j$(K$($,"Cargo.toml")))J.push("rust");if(j$(K$($,"go.mod")))J.push("go");if(j$(K$($,"requirements.txt"))||j$(K$($,"pyproject.toml")))J.push("python");let Y=oQ($);return P7(Y,$,"",[],J)}function I7(){return nQ().slice(0,8)}e();s();import{existsSync as k7,mkdirSync as ZX,readFileSync as sZ}from"fs";import{join as tZ,basename as JX}from"path";var eZ=2,$6="pitwall-baselines.json",YX=0.1,QX=0.05,XX=5000000,zX=512000,aZ=2048,KX=120000,s1="",r=[];function Z6($){if(s1=$,!k7($))ZX($,{recursive:!0});NX()}async function rZ($,Z){let Y=[...D4(),$],Q=process.cpuUsage(),X=Bun.nanoseconds(),z=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe",cwd:Z}),G=setTimeout(()=>z.kill(),KX),V=z.pid,H=GX(V),[,K]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),M=await z.exited;clearTimeout(G);let B=Bun.nanoseconds(),O=process.cpuUsage(Q),j=await H,A=K.length>aZ?`...${K.slice(-aZ)}`:K;return{durationNs:B-X,peakMemoryBytes:j,cpuUserUs:O.user,cpuSystemUs:O.system,exitCode:M,stderr:A.trim()}}async function b7($,Z={}){let J=Z.cwd||process.cwd(),Y=Math.min(Math.max(Z.iterations||1,1),10),Q=Z.scriptKey||BX($);if(Z.warmup&&Y>1)await rZ($,J);let X=[];for(let K=0;K<Y;K++)X.push(await rZ($,J));let z=X[X.length-1],G=X.map((K)=>K.durationNs),V={durationNs:w7(G),peakMemoryBytes:Math.max(...X.map((K)=>K.peakMemoryBytes)),cpuUserUs:w7(X.map((K)=>K.cpuUserUs)),cpuSystemUs:w7(X.map((K)=>K.cpuSystemUs))},H=Y>1?{min:Math.min(...G),max:Math.max(...G),median:V.durationNs,stddev:UX(G)}:null;return{scriptKey:Q,command:$,metrics:V,spread:H,exitCode:z.exitCode,stderr:z.stderr,timestamp:new Date().toISOString(),iterations:Y}}async function GX($){try{if(x){let Z=`(Get-Process -Id ${$} -ErrorAction SilentlyContinue).PeakWorkingSet64`,J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>J.kill(),5000),Q=await new Response(J.stdout).text();await J.exited,clearTimeout(Y);let X=parseInt(Q.trim(),10);if(!isNaN(X)&&X>0)return X}else{let Z=`/proc/${$}/status`;if(k7(Z)){let Y=sZ(Z,"utf-8").match(/VmPeak:\s+(\d+)\s+kB/);if(Y)return parseInt(Y[1],10)*1024}}}catch{}return process.memoryUsage().rss}function J6($,Z=[]){let J=r.find((X)=>X.scriptKey===$.scriptKey),Y=new Date().toISOString();if(J){let X=J.runs+1,z={durationNs:Math.round((J.metrics.durationNs*J.runs+$.metrics.durationNs)/X),peakMemoryBytes:Math.round((J.metrics.peakMemoryBytes*J.runs+$.metrics.peakMemoryBytes)/X),cpuUserUs:Math.round((J.metrics.cpuUserUs*J.runs+$.metrics.cpuUserUs)/X),cpuSystemUs:Math.round((J.metrics.cpuSystemUs*J.runs+$.metrics.cpuSystemUs)/X)},G={...J,metrics:z,spread:$.spread||J.spread,updatedAt:Y,runs:X,tags:[...new Set([...J.tags,...Z])]};return r=r.map((V)=>V.scriptKey===$.scriptKey?G:V),t1(),G}let Q={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:Y,updatedAt:Y,runs:1,tags:Z};return r=[...r,Q],t1(),Q}function VX($){return r.find((Z)=>Z.scriptKey===$)||null}function Y6(){return[...r].sort(($,Z)=>$.scriptKey.localeCompare(Z.scriptKey))}function y7($){let Z=r.findIndex((J)=>J.scriptKey===$);if(Z===-1)return!1;return r=[...r.slice(0,Z),...r.slice(Z+1)],t1(),!0}function Q6($,Z=[]){y7($.scriptKey);let J=new Date().toISOString(),Y={scriptKey:$.scriptKey,metrics:{...$.metrics},spread:$.spread,createdAt:J,updatedAt:J,runs:1,tags:Z};return r=[...r,Y],t1(),Y}function _7($){let Z=VX($.scriptKey),J=[];if(Z)J.push(a1("duration",Z.metrics.durationNs,$.metrics.durationNs,XX),a1("memory",Z.metrics.peakMemoryBytes,$.metrics.peakMemoryBytes,zX),a1("cpu_user",Z.metrics.cpuUserUs,$.metrics.cpuUserUs,0),a1("cpu_system",Z.metrics.cpuSystemUs,$.metrics.cpuSystemUs,0));let Y=J.some((X)=>X.severity==="regression"),Q=qX($,Z,J,Y);return{run:$,baseline:Z,alerts:J,hasRegression:Y,markdown:Q}}function a1($,Z,J,Y){let Q=J-Z;if(Z===0||Math.abs(Q)<Y)return{metric:$,baselineValue:Z,currentValue:J,deltaPercent:0,absoluteDelta:Q,severity:"ok"};let X=Q/Z,z="ok";if(X>YX)z="regression";else if(X>QX)z="warning";return{metric:$,baselineValue:Z,currentValue:J,deltaPercent:Math.round(X*1e4)/100,absoluteDelta:Q,severity:z}}function c$($){if($<1000)return`${$}ns`;if($<1e6)return`${($/1000).toFixed(1)}us`;if($<1e9)return`${($/1e6).toFixed(2)}ms`;return`${($/1e9).toFixed(3)}s`}function S7($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}KB`;if($<1073741824)return`${($/1048576).toFixed(1)}MB`;return`${($/1073741824).toFixed(2)}GB`}function r1($){if($<1000)return`${$}us`;if($<1e6)return`${($/1000).toFixed(2)}ms`;return`${($/1e6).toFixed(2)}s`}function WX($){switch($){case"ok":return"[OK]";case"warning":return"[!]";case"regression":return"[REGRESSAO]"}}function HX($){switch($){case"duration":return"Duracao";case"memory":return"Memoria (peak)";case"cpu_user":return"CPU (user)";case"cpu_system":return"CPU (sys)";default:return $}}function qX($,Z,J,Y){let Q=[];if(Y)Q.push("=== PIT WALL: REGRESSAO DETECTADA ===");else Q.push("=== Pit Wall: Relatorio de Performance ===");if(Q.push(`Script: ${$.scriptKey}`),Q.push(`Comando: ${$.command}`),Q.push(`Execucoes: ${$.iterations}`),$.exitCode!==0)Q.push(`Exit code: ${$.exitCode} (FALHA)`);if(Q.push(""),Q.push("--- Metricas Atuais ---"),Q.push(` Duracao: ${c$($.metrics.durationNs)}`),Q.push(` Memoria: ${S7($.metrics.peakMemoryBytes)}`),Q.push(` CPU (user): ${r1($.metrics.cpuUserUs)}`),Q.push(` CPU (sys): ${r1($.metrics.cpuSystemUs)}`),$.spread){Q.push(""),Q.push("--- Dispersao ---"),Q.push(` Min: ${c$($.spread.min)}`),Q.push(` Max: ${c$($.spread.max)}`),Q.push(` Mediana: ${c$($.spread.median)}`),Q.push(` Stddev: ${c$($.spread.stddev)}`);let X=$.spread.median>0?($.spread.stddev/$.spread.median*100).toFixed(1):"0";if(Q.push(` CV: ${X}%`),parseFloat(X)>15)Q.push(" (!) Alta variancia \u2014 resultados podem ser inst\xE1veis")}if($.exitCode!==0&&$.stderr)Q.push(""),Q.push("--- Stderr ---"),Q.push($.stderr.slice(0,500));if(Q.push(""),!Z)return Q.push("Nenhum baseline salvo para este script."),Q.push("Use pitwall_save_baseline para definir o baseline atual."),Q.join(`
256
+ `);Q.push(`--- Baseline (${Z.runs} run${Z.runs>1?"s":""}, atualizado ${X6(Z.updatedAt)}) ---`),Q.push(` Duracao: ${c$(Z.metrics.durationNs)}`),Q.push(` Memoria: ${S7(Z.metrics.peakMemoryBytes)}`),Q.push(` CPU (user): ${r1(Z.metrics.cpuUserUs)}`),Q.push(` CPU (sys): ${r1(Z.metrics.cpuSystemUs)}`),Q.push(""),Q.push("--- Comparacao ---");for(let X of J){let z=X.deltaPercent>=0?"+":"",G=HX(X.metric);Q.push(` ${WX(X.severity)} ${G}: ${z}${X.deltaPercent}%`)}if(Q.push(""),Y)Q.push("*** ALERTA: Regressao de performance > 10% detectada! ***"),Q.push("Revise as mudancas recentes no codigo.");else if(J.some((X)=>X.severity==="warning"))Q.push("Atencao: algumas metricas estao proximas do limite (5-10%).");else Q.push("Performance dentro do esperado.");return Q.join(`
257
+ `)}function X6($){let Z=Date.now()-new Date($).getTime(),J=Math.floor(Z/60000);if(J<60)return`ha ${J}min`;let Y=Math.floor(J/60);if(Y<24)return`ha ${Y}h`;return`ha ${Math.floor(Y/24)}d`}function z6($){if($.length===0)return"Nenhum baseline salvo no Pit Wall.";let Z=["=== Pit Wall: Baselines ===",""];for(let J of $){let Y=J.tags.length>0?` [${J.tags.join(", ")}]`:"",Q=X6(J.updatedAt);if(Z.push(` ${J.scriptKey}`),Z.push(` Duracao: ${c$(J.metrics.durationNs)} | Memoria: ${S7(J.metrics.peakMemoryBytes)} | ${J.runs} runs | ${Q}${Y}`),J.spread){let X=J.spread.median>0?(J.spread.stddev/J.spread.median*100).toFixed(1):"0";Z.push(` Spread: ${c$(J.spread.min)} ~ ${c$(J.spread.max)} (CV ${X}%)`)}Z.push("")}return Z.join(`
258
+ `)}function w7($){if($.length===0)return 0;let Z=[...$].sort((Y,Q)=>Y-Q),J=Math.floor(Z.length/2);return Z.length%2!==0?Z[J]:Math.round((Z[J-1]+Z[J])/2)}function UX($){if($.length<2)return 0;let Z=$.reduce((Y,Q)=>Y+Q,0)/$.length,J=$.reduce((Y,Q)=>Y+(Q-Z)**2,0)/($.length-1);return Math.round(Math.sqrt(J))}function BX($){let Z=$.trim().split(/\s+/);if(Z.length>=3&&["bun","npm","yarn","pnpm"].includes(Z[0])&&Z[1]==="run")return Z[2];if(Z.length>=2&&["bun","npm","yarn","pnpm"].includes(Z[0]))return Z[1];return JX(Z[0])}function NX(){let $=tZ(s1,$6);if(!k7($)){r=[];return}try{let Z=JSON.parse(sZ($,"utf-8"));if(Z.version!==eZ&&Z.version!==1){r=[];return}r=(Z.baselines||[]).map(CX)}catch{r=[]}}function CX($){let{durationMs:Z,...J}=$.metrics;return{...$,metrics:J,spread:$.spread||null}}function t1(){if(!s1)return;let $=tZ(s1,$6);k($,JSON.stringify({baselines:r,version:eZ},null,2))}s();import{readdirSync as MX,readFileSync as OX,lstatSync as jX}from"fs";import{join as EX,resolve as Y0,relative as h7,dirname as FX,extname as LX}from"path";var RX=[".ts",".tsx",".mts",".cts"],AX=[".ts",".tsx",".mts",".cts","/index.ts","/index.tsx"],DX=new Set($8),K6=5000,xX=5000,G6=new Map;function TX($){let Z=G6.get($);if(Z&&Date.now()-Z.ts<xX)return Z.graph;return null}function PX($,Z){G6.set($,{graph:Z,ts:Date.now()})}var IX=[/^import\s+(?:type\s+)?[^'"]*?\s+from\s+['"]([^'"]+)['"]/gm,/^import\s+['"]([^'"]+)['"]/gm,/^export\s+(?:type\s+)?(?:\*|{[^}]*})\s+from\s+['"]([^'"]+)['"]/gm,/import\(\s*['"]([^'"]+)['"]\s*\)/g,/require\(\s*['"]([^'"]+)['"]\s*\)/g];function wX($){let Z=new Set,J=$.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/.*$/gm,"");for(let Y of IX){Y.lastIndex=0;let Q;while((Q=Y.exec(J))!==null){let X=Q[1];if(X.startsWith("./")||X.startsWith("../"))Z.add(X)}}return[...Z]}function SX($){let Z=[];function J(Y){if(Z.length>=K6)return;let Q;try{Q=MX(Y)}catch{return}for(let X of Q){if(Z.length>=K6)return;if(DX.has(X))continue;let z=EX(Y,X),G;try{G=jX(z)}catch{continue}if(G.isSymbolicLink())continue;if(G.isDirectory())J(z);else if(G.isFile()&&RX.includes(LX(X)))Z.push(z)}}return J($),Z}function kX($,Z,J){let Y=FX(Z),Q=Y0(Y,$);if(J.has(Q))return Q;for(let X of AX){let z=Q+X;if(J.has(z))return z}return null}function v7($){let Z=Y0($),J=TX(Z);if(J)return J;let Y=SX(Z),Q=new Set(Y),X=new Map,z=new Map;for(let V of Y)X.set(V,new Set),z.set(V,new Set);for(let V of Y){let H;try{H=OX(V,"utf-8")}catch{continue}let K=wX(H),M=X.get(V);for(let B of K){let O=kX(B,V,Q);if(O){M.add(O);let j=z.get(O)||new Set;j.add(V),z.set(O,j)}}}let G={imports:X,importedBy:z,files:Y,root:Z};return PX(Z,G),G}function f7($,Z){let J=Y0(Z),Y=$.importedBy.get(J)||new Set,Q=[...Y],X=new Set([J]),z=[],G=new Map,V=0;for(let j of Y)z.push({file:j,depth:1}),X.add(j),G.set(j,1);let H=[],K=0;while(K<z.length){let{file:j,depth:A}=z[K++];if(A>V)V=A;if(!Y.has(j))H.push(j);let T=$.importedBy.get(j)||new Set;for(let w of T)if(!X.has(w))X.add(w),G.set(w,A+1),z.push({file:w,depth:A+1})}let M=V6(J,$.importedBy,new Set,0),B=(j)=>h7($.root,j).replace(/\\/g,"/"),O=new Map;for(let[j,A]of G)O.set(B(j),A);return{target:B(J),directDependents:Q.map(B),transitiveDependents:H.map(B),depthMap:O,totalAffected:Q.length+H.length,depth:V,tree:W6(M,$.root)}}function V6($,Z,J,Y){J.add($);let Q=Z.get($)||new Set,X=[];for(let z of Q)if(!J.has(z))X.push(V6(z,Z,J,Y+1));return{file:$,depth:Y,children:X}}function W6($,Z){return{file:h7(Z,$.file).replace(/\\/g,"/"),depth:$.depth,children:$.children.map((J)=>W6(J,Z))}}function H6($,Z){let J=Y0(Z),Y=f7($,Z),Q=(j)=>Y0($.root,j),X=new Set([...Y.directDependents.map(Q),...Y.transitiveDependents.map(Q)]);X.add(J);let z=new Map;for(let j of X)z.set(j,0);for(let j of X){let A=$.importedBy.get(j)||new Set;for(let T of A)if(X.has(T)&&T!==j)z.set(j,(z.get(j)||0)+1)}let G=[];for(let[j,A]of z)if(A===0&&j!==J)G.push(j);let V=[],H=new Set,K=0;while(K<G.length){let j=G[K++];V.push(j),H.add(j);let A=$.imports.get(j)||new Set;for(let T of A)if(X.has(T)&&!H.has(T)&&T!==J){let w=(z.get(T)||1)-1;if(z.set(T,w),w===0)G.push(T)}}for(let j of X)if(!H.has(j)&&j!==J)V.push(j);let M=[J,...V],B=(j)=>h7($.root,j).replace(/\\/g,"/"),O=M.map((j)=>{let T=[...$.imports.get(j)||new Set].filter((b)=>X.has(b)).map(B),w=B(j),N$=j===J?0:Y.depthMap.get(w)||1;return{file:w,depth:N$,dependsOn:T}});return{target:B(J),order:O,totalFiles:O.length}}function q6($){let Z=[];if(Z.push("=== Blast Radius Analysis ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Arquivos afetados: ${$.totalAffected}`),Z.push(`Profundidade maxima: ${$.depth}`),Z.push(""),$.directDependents.length>0){Z.push(`--- Dependentes diretos (${$.directDependents.length}) ---`);for(let J of $.directDependents)Z.push(` ${J}`);Z.push("")}if($.transitiveDependents.length>0){Z.push(`--- Dependentes transitivos (${$.transitiveDependents.length}) ---`);for(let J of $.transitiveDependents){let Y=$.depthMap.get(J)||0;Z.push(` ${J} (depth ${Y})`)}Z.push("")}if($.totalAffected===0)Z.push("Nenhum arquivo depende deste modulo. Blast radius = 0."),Z.push("");return Z.push("--- Arvore de impacto ---"),U6($.tree,Z,"",!0),Z.join(`
259
+ `)}function U6($,Z,J,Y){let Q=Y?"\u2514\u2500 ":"\u251C\u2500 ",X=$.depth===0?`[ALVO] ${$.file}`:$.file;Z.push(`${J}${Q}${X}`);let z=J+(Y?" ":"\u2502 ");for(let G=0;G<$.children.length;G++)U6($.children[G],Z,z,G===$.children.length-1)}function B6($){let Z=[];Z.push("=== Plano de Refatoracao ==="),Z.push(`Alvo: ${$.target}`),Z.push(`Total de arquivos: ${$.totalFiles}`),Z.push(""),Z.push("Ordem segura de atualizacao:"),Z.push("");for(let J=0;J<$.order.length;J++){let Y=$.order[J],Q=`${J+1}`.padStart(3),X=Y.depth===0?"[ALVO]":`[depth ${Y.depth}]`;if(Z.push(` ${Q}. ${Y.file} ${X}`),Y.dependsOn.length>0)Z.push(` depende de: ${Y.dependsOn.join(", ")}`)}return Z.push(""),Z.push("Estrategia: Altere o alvo primeiro, depois atualize"),Z.push("os dependentes de fora para dentro (folhas primeiro)."),Z.join(`
260
+ `)}var s4=new a2,F6=[];function L6($){F6=$}var l=[{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"]}}],R6=[{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:[]}}],hX=[{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:[]}}],vX=[{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:[]}}],fX=[{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"]}}],gX={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"]}},mX=[{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"]}}],cX=[{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:[]}}],dX=[{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"]}}],uX=[{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:[]}}],pX=[{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"]}}],lX=[{name:"pitwall_benchmark",description:"Benchmark a local script or command \u2014 captures wall-clock time, child process peak memory, and CPU overhead. "+'Compares against saved baseline and alerts on regressions > 10%. Use when the user says "benchmark", "mede a performance", "testa a velocidade", "pit wall".',input_schema:{type:"object",properties:{command:{type:"string",description:'Shell command to benchmark (e.g. "bun run build", "bun test").'},key:{type:"string",description:"Unique label for this benchmark. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs (uses median). Default 1, max 10."},warmup:{type:"boolean",description:"Run one warmup iteration before measuring (discarded). Default false."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_save_baseline",description:'Benchmark a command and save results as the performance baseline for future comparisons. Default: 3 runs with warmup. Use "reset" to replace (not blend) an existing baseline.',input_schema:{type:"object",properties:{command:{type:"string",description:"Command to benchmark and save as baseline."},key:{type:"string",description:"Benchmark label. Auto-derived from command if omitted."},iterations:{type:"number",description:"Number of runs to measure. Default 3."},tags:{type:"array",items:{type:"string"},description:'Tags for this baseline (e.g. "build", "test").'},reset:{type:"boolean",description:"If true, replaces existing baseline entirely. Default false (blends)."},cwd:{type:"string",description:"Working directory. Defaults to cwd."}},required:["command"]}},{name:"pitwall_status",description:'List all saved performance baselines with their metrics, spread, and age. Use when the user asks "quais baselines tenho?", "pit wall status", "mostra as metricas".',input_schema:{type:"object",properties:{},required:[]}},{name:"pitwall_remove_baseline",description:"Remove a saved performance baseline by its key.",input_schema:{type:"object",properties:{key:{type:"string",description:"The script key of the baseline to remove."}},required:["key"]}}],oX=[{name:"analyze_blast_radius",description:"Analyze the blast radius of changing a TypeScript file \u2014 shows all modules that import it (directly and transitively). "+'Use when the user says "blast radius", "impacto da mudanca", "quem depende de", "o que quebra se mudar".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file to analyze (relative or absolute)."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}},{name:"plan_refactor",description:'Generate a safe refactor order for updating dependents of a TypeScript file. Returns a numbered sequence: change the target first, then update dependents bottom-up. Use when the user says "plano de refatoracao", "ordem de atualizacao", "como refatorar seguro".',input_schema:{type:"object",properties:{file:{type:"string",description:"Path to the target file being refactored."},project_dir:{type:"string",description:"Root directory of the TypeScript project. Defaults to cwd."}},required:["file"]}}],nX=[{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:[]}}],iX=[{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"]}}],aX=[{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:[]}}],rX=[{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:[]}}],sX=R6.find(($)=>$.name==="get_news"),N6=!1,d$=null;function A6($){d$=$}function D6(){if(N6)return;if(N6=!0,x)l.push(...R6),l.push(...nX);else l.push(sX);l.push(...hX),l.push(...vX),l.push(...fX),l.push(gX),l.push(...mX),l.push(...cX),l.push(...dX),l.push(...aX),l.push(...iX),l.push(...uX),l.push(...pX),l.push(...lX),l.push(...oX),l.push(...rX)}var e1=50000;async function c7($,Z){try{switch($){case"read_file":return tX(Z);case"write_file":return eX(Z);case"edit_file":return $z(Z);case"search_files":return await Zz(Z);case"find_files":return await Qz(Z);case"list_directory":return Xz(Z);case"run_command":return await zz(Z);case"fetch_url":return await Kz(Z);case"open_application":return await N4(Z.name,Z.argument);case"open_file_default":return await n8(Z.path);case"open_url_browser":return await C4(Z.url);case"get_running_apps":return await i8();case"get_system_info":return await M4();case"get_calendar_events":return await v$();case"get_news":{let J=Z.category;return await m4(J?[J]:void 0)}case"create_task":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.time,Q=Y?r8(Y):void 0,X=Q1(J,Q||void 0),z=Q?` \u2014 lembrete: ${Q.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${X.title}"${z} [${X.id}]`}case"complete_task":{let J=Z.reference;if(!J?.trim())return"Error: reference is required.";let Y=X1(J);return Y?`Concluida: "${Y.title}"`:`Tarefa nao encontrada: "${J}"`}case"list_tasks":{let J=Z.show_done||!1,Y=t$(J);return E4(Y)}case"add_person":{let J=Z.name;if(!J?.trim())return"Error: name is required.";let Y=Z.group;if(!["equipe","familia","contato"].includes(Y))return"Error: group must be equipe, familia, or contato.";let X=C1(J,Y,Z.role,Z.contact);return`Pessoa adicionada: ${X.name} (${Y}) [${X.id}]`}case"find_person_info":{let J=Z.name_or_id;if(!J?.trim())return"Error: name_or_id is required.";let Y=Z4(J);if(!Y)return`Pessoa nao encontrada: "${J}"`;return E1(Y)}case"list_people":{let J=Z.group,Y=M1(J);return j1(Y)}case"log_interaction":{let J=Z.person;if(!J?.trim())return"Error: person is required.";let{type:Y,summary:Q}=Z;if(!Q?.trim())return"Error: summary is required.";let X=Z.follow_up,z=X?O6(X):void 0;if(!FZ(J,Y,Q,z||void 0))return`Pessoa nao encontrada: "${J}"`;let V=z?` \u2014 follow-up: ${z.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${Y} com ${J}${V}`}case"delegate_to_person":{let J=Z.person;if(!J?.trim())return"Error: person is required.";let Y=Z.task;if(!Y?.trim())return"Error: task is required.";let Q=Z.due_date,X=Q?O6(Q):void 0,z=O1(J,Y,X||void 0);if(!z)return`Pessoa nao encontrada: "${J}"`;let G=X?` \u2014 prazo: ${X.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${J}: "${Y}"${G} [${z.id}]`}case"update_delegation_status":{let J=Z.delegation_id;if(!J?.trim())return"Error: delegation_id is required.";let Y=Z.status,Q=LZ(J,Y,Z.notes);if(!Q)return`Delegacao nao encontrada: "${J}"`;return`Delegacao atualizada: "${Q.task}" -> ${Y}`}case"get_people_dashboard":return R1();case"save_memo":{let J=Z.content;if(!J?.trim())return"Error: content is required.";let Y=Z.tags||[],Q=z1(J,Y);return`Memo salvo${Q.tags.length>0?` [${Q.tags.map((z)=>"#"+z).join(" ")}]`:""} {${Q.id}}`}case"search_memos":{let J=Z.query;if(!J?.trim())return F4(s8());let Y=K1(J);return F4(Y)}case"record_transaction":{let{type:J,amount:Y,category:Q,description:X}=Z;if(!J||!Y||!Q||!X)return"Error: all fields required.";let z=t8(J,Y,Q,X);return`${z.type==="entrada"?"+":"-"} R$ ${z.amount.toFixed(2)} (${z.category}) \u2014 ${z.description} [${z.id}]`}case"financial_summary":return W1();case"log_decision":{let{title:J,context:Y,chosen:Q}=Z;if(!J||!Y||!Q)return"Error: title, context, and chosen are required.";let X=WZ(J,Y,Q,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${X.title}" {${X.id}}`}case"search_decisions":{let J=Z.query;if(!J?.trim())return d4(q1());return d4(H1(J))}case"open_investigation":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.type;if(!["bug","feature","test","audit","incident"].includes(Y))return"Error: type must be bug, feature, test, audit, or incident.";let X=G7(J,Y,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${X.title}" (${X.type}) {${X.id}}`}case"collect_evidence":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let{source:Y,label:Q,content:X}=Z;if(!Q?.trim()||!X?.trim())return"Error: label and content are required.";let z=V7(J,Y,Q,X,Z.path);if(!z)return`Investigacao nao encontrada: "${J}"`;return`Evidencia coletada: [${z.id}] ${z.source}: ${z.label}`}case"add_finding":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let{severity:Y,title:Q,description:X}=Z;if(!Q?.trim()||!X?.trim())return"Error: title and description are required.";let z=Z.evidence_ids||[],G=W7(J,Y,Q,X,z);if(!G)return`Investigacao nao encontrada: "${J}"`;return`Conclusao registrada: [${G.severity.toUpperCase()}] ${G.title} {${G.id}}`}case"close_investigation":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let Y=Z.summary;if(!Y?.trim())return"Error: summary is required.";let Q=H7(J,Y,Z.recommendations);if(!Q)return`Investigacao nao encontrada: "${J}"`;return`Investigacao concluida: "${Q.title}" \u2014 ${Q.evidence.length} evidencias, ${Q.findings.length} conclusoes`}case"investigation_status":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let Y=q7(J);if(!Y)return`Investigacao nao encontrada: "${J}"`;return C7(Y)}case"investigation_report":{let J=Z.investigation;if(!J?.trim())return"Error: investigation is required.";let Y=N7(J);if(!Y)return`Investigacao nao encontrada: "${J}"`;return Y}case"list_investigations":{let J=Z.query;if(J?.trim())return B1(B7(J));let{status:Y,type:Q}=Z;return B1(U7(Y,Q))}case"draft_email":{let{to:J,subject:Y,body:Q}=Z;if(!J?.trim()||!Y?.trim()||!Q?.trim())return"Error: to, subject, and body are required.";let X={to:J,subject:Y,body:Q,cc:Z.cc},z=V1(X),G=await G1(X);return`${z}
261
+
262
+ ${G}`}case"save_material":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let Q=Z.category||"geral",X=Z.tags||[],z=A1(J,Y,Q,X),G=z.tags.length>0?` [${z.tags.map((V)=>"#"+V).join(" ")}]`:"";return`Material salvo: "${z.title}" (${z.category})${G} {${z.id}}`}case"search_materials":{let J=Z.query;if(!J?.trim())return J4(p4());let Y=x1(J);return J4(Y)}case"list_materials":{let J=Z.category,Y=Z.limit||30,Q=p4(Y,J);return J4(Q)}case"update_material":{let J=Z.id;if(!J?.trim())return"Error: id is required.";let Y={};if(Z.title)Y.title=Z.title;if(Z.content)Y.content=Z.content;if(Z.category)Y.category=Z.category;if(Z.tags)Y.tags=Z.tags;let Q=PZ(J,Y);if(!Q)return`Material nao encontrado: "${J}"`;return`Material atualizado: "${Q.title}" (${Q.category}) {${Q.id}}`}case"delete_material":{let J=Z.id;if(!J?.trim())return"Error: id is required.";return D1(J)?"Material removido.":`Material nao encontrado: "${J}"`}case"execute_powershell_script":{let J=Z.script;if(!J?.trim())return"Error: script is required.";let Y=D7(J);if(Y.blocked)return`BLOCKED: ${Y.reason}
263
+ Esse tipo de operacao nao e permitido.`;if(!Y.safe&&Y.reason);let Q=await y1(J),X=[];if(Q.stdout.trim())X.push(`stdout:
259
264
  ${Q.stdout.trim()}`);if(Q.stderr.trim())X.push(`stderr:
260
265
  ${Q.stderr.trim()}`);return X.push(`exit: ${Q.exitCode} (${Q.duration}ms)`),X.join(`
261
266
 
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(!F0())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(!F0())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(!F0())return"Memory: nao inicializada.";let Y=L0(),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(!a1())return"Vault nao inicializado.";return z8(K8())}case"vault_backup":{if(!a1())return"Vault nao inicializado.";let Y=Z.message||void 0;return await O1(Y)}case"sync_cloud_context":{if(!a1())return"Vault nao inicializado.";return await G8()}case"vault_init_backup":{if(!a1())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 u1(Q.id),`Projeto ativo: "${Q.name}" (${Q.path}) \u2014 auto-detectado [${Q.id}]`}let J=u1(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=Z1();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 qQ(X,V.markdown,"utf-8"),`Relatorio salvo em: ${X}
267
+ `)}case"analyze_screen_context":return await h1();case"read_clipboard_content":{let J=await _1();switch(J.type){case"text":return`Clipboard (texto):
268
+ ${J.text}`;case"image":return J.text;case"empty":return"Clipboard vazio.";case"error":return`Erro ao ler clipboard: ${J.text}`}}case"manage_news_feeds":switch(Z.action){case"list":return J1();case"add":{let{name:Y,url:Q,category:X}=Z;if(!Y?.trim())return"Error: name is required for add.";if(!Q?.trim())return"Error: url is required for add.";if(!X?.trim())return"Error: category is required for add.";let z=t0(Y,Q,X);if(typeof z==="string")return z;return`Fonte adicionada: ${z.name} (${z.category}) \u2014 ${z.url}`}case"remove":{let Y=Z.name;if(!Y?.trim())return"Error: name or URL is required.";return e0(Y)?`Fonte removida: ${Y}`:`Fonte custom nao encontrada: "${Y}"`}case"disable":{let Y=Z.name;if(!Y?.trim())return"Error: name or URL is required.";return $1(Y)?`Fonte desativada: ${Y}`:`Fonte built-in nao encontrada ou ja desativada: "${Y}"`}case"enable":{let Y=Z.name;if(!Y?.trim())return"Error: name or URL is required.";return Z1(Y)?`Fonte reativada: ${Y}`:`Fonte nao encontrada ou nao esta desativada: "${Y}"`}default:return"Error: action must be add, remove, disable, enable, or list."}case"recall_memory":{if(!I1())return"Error: memory not initialized. Run /indexar first.";let J=Z.query;if(!J?.trim())return"Error: query is required.";let Y=Math.min(Math.max(Z.top_k||3,1),10),Q=k1(J,Y);return b1(Q)}case"index_memory":{if(!I1())return"Error: memory not initialized.";let J=S1();return`Indexacao concluida: ${J.indexed} fonte(s) indexada(s), ${J.skipped} sem alteracao. Total: ${J.total} chunks.`}case"memory_status":{if(!I1())return"Memory: nao inicializada.";let J=w1(),Y=J.builtAt?new Date(J.builtAt).toLocaleString("pt-BR"):"nunca";return`Memory RAG Index:
269
+ Chunks: ${J.chunks}
270
+ Fontes: ${J.sources}
271
+ Ultima indexacao: ${Y}`}case"vault_status":{if(!J8())return"Vault nao inicializado.";return M0(C0())}case"vault_backup":{if(!J8())return"Vault nao inicializado.";let J=Z.message||void 0;return await x4(J)}case"sync_cloud_context":{if(!J8())return"Vault nao inicializado.";return await j0()}case"vault_init_backup":{if(!J8())return"Vault nao inicializado.";return await O0()}case"set_active_project":{let J=Z.name_or_id;if(!J?.trim())return"Error: name_or_id is required.";if(J==="auto"){let Q=i1(process.cwd());if(!Q)return"Nenhum projeto detectado no diretorio atual (nao e um repositorio git).";return i4(Q.id),`Projeto ativo: "${Q.name}" (${Q.path}) \u2014 auto-detectado [${Q.id}]`}let Y=i4(J);if(!Y)return`Projeto nao encontrado: "${J}". Use /projetos para listar ou add_project para criar.`;return`Projeto ativo: "${Y.name}" (${Y.path}) [${Y.id}]`}case"report_work_progress":{let J=Z.project||"",Y=Z.period||"today",Q=Z.lang||"pt",X=Z.save_to_file,z=J;if(!z){let V=Q4();if(!V)return"Nenhum projeto ativo. Use set_active_project primeiro.";z=V.id}let G=await p1(z,Y,Q);if(!G)return`Projeto nao encontrado: "${z}"`;if(X)return yX(X,G.markdown,"utf-8"),`Relatorio salvo em: ${X}
267
272
 
268
- ${V.markdown}`;return V.markdown}case"manage_work_session":{let Y=Z.action,J=Z.notes||"",Q=Z1();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=Y1(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=Y1(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(!h$)return"Error: session manager not initialized.";let Y=Z.name;if(!Y?.trim())return"Error: name is required.";if(Y==="all"){let J=h$.archiveAll();return J.length>0?`Arquivadas ${J.length} sessoes: ${J.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return h$.archive(Y)?`Sessao arquivada: "${Y}"`:`Falha ao arquivar "${Y}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!h$)return"Error: session manager not initialized.";let Y=Z.name;if(!Y?.trim())return"Error: name is required.";return h$.unarchive(Y)?`Sessao restaurada: "${Y}"`:`Sessao arquivada nao encontrada: "${Y}"`}case"list_archived_sessions":{if(!h$)return"Error: session manager not initialized.";let Y=h$.listArchived();if(Y.length===0)return"Nenhuma sessao arquivada.";let J=Y.map((Q)=>{let X=h$.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}):
269
- ${J.join(`
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 n1($){let Z=C1($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+c0))return`Error: path outside working directory is not permitted: ${Z}`;try{if(o4(Z)){let J=UQ(Z);if(J!==Y&&!J.startsWith(Y+c0))return`Error: symlink target is outside working directory: ${J}`}}catch{}return null}function i1($,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 PQ($){let Z=i1($,"path");if(Z)return Z;let Y=C1($.path),J=n1(Y);if(J)return J;if(!o4(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,L)=>`${String(V+L).padStart(4)} ${E}`).join(`
272
- `),N=K.length-(V-1+G);if(N>0)M+=`
273
- ... (${N} more lines, total ${K.length})`;return p1(M)}function wQ($){let Z=i1($,"path");if(Z)return Z;let Y=C1($.path),J=n1(Y);if(J)return J;let Q=$.content,X=o4(Y);l1.saveState(Y),P(Y,Q);let K=Q.split(`
274
- `).length;return`${X?"Updated":"Created"}: ${Y} (${K} lines)`}function IQ($){let Z=i1($,"path");if(Z)return Z;let Y=C1($.path),J=n1(Y);if(J)return J;if(!o4(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.`;l1.saveState(Y);let G=Q.split(X).join(K);P(Y,G);let H=X.split(`
275
- `).length,z=K.split(`
276
- `).length;return`Edited: ${Y} (replaced ${H} lines with ${z} lines)`}async function SQ($){let Z=i1($,"pattern");if(Z)return Z;let Y=$.pattern,J=C1($.path||"."),Q=n1(J);if(Q)return Q;let X=$.include;if(await r7())return bQ(Y,J,X);return kQ(Y,J,X)}async function bQ($,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 gQ(X,Z)}async function kQ($,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 L=0;L<E.length;L++)if(J.test(E[L])){if(K.push(`${z}:${L+1}:${E[L]}`),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 p1(H)}async function yQ($){let Z=i1($,"pattern");if(Z)return Z;let Y=$.pattern,J=C1($.path||"."),Q=n1(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 _Q($){let Z=C1($.path||"."),Y=n1(Z);if(Y)return Y;if(!o4(Z))return`Error: not found: ${Z}`;return HQ(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 hQ($){let Z=i1($,"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?`
273
+ ${G.markdown}`;return G.markdown}case"manage_work_session":{let J=Z.action,Y=Z.notes||"",Q=Q4();if(!Q)return"Nenhum projeto ativo. Use set_active_project primeiro.";switch(J){case"start":{let X=c1(Q.id,Y);if(!X)return"Erro ao iniciar sessao.";return`Sessao iniciada para "${Q.name}" as ${new Date().toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}. [${X.id}]`}case"stop":{let X=X4(Q.id);if(!X)return"Nenhuma sessao aberta para este projeto.";let z=d1(X.id,Y);if(!z)return"Erro ao encerrar sessao.";return`Sessao encerrada: ${z.durationMinutes} minutos trabalhados em "${Q.name}".`}case"status":{let X=X4(Q.id);if(!X)return`Nenhuma sessao aberta para "${Q.name}".`;let z=new Date(X.startedAt),G=Math.round((Date.now()-z.getTime())/60000);return`Sessao aberta: "${Q.name}" \u2014 ${G} minutos (desde ${z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})})`}default:return"Error: action must be start, stop, or status."}}case"add_project":{let J=Z.name;if(!J?.trim())return"Error: name is required.";let Y=Z.path;if(!Y?.trim())return"Error: path is required.";let Q=Z.description||"",X=Z.tech_stack||[],z=Z.tags||[],G=P7(J,Y,Q,z,X);return`Projeto registrado: "${G.name}" (${G.path}) [${G.id}]`}case"list_projects":{let J=Z.active_only||!1;return l1(m1(J))}case"fetch_opportunities":{let{status:J,tech:Y}=Z,Q=u1(J,Y);return n1(Q)}case"add_opportunity":{let J=Z.title;if(!J?.trim())return"Error: title is required.";let Y=Z.description;if(!Y?.trim())return"Error: description is required.";let Q=Z.source;if(!Q?.trim())return"Error: source is required.";let X=Z.tech_required||[],z=Z.priority||"media",G=Z.deadline||null,V=oZ(J,Y,Q,X,z,G);return`Oportunidade registrada: "${V.title}" (${V.priority}) [${V.id}]`}case"update_opportunity_status":{let J=Z.id;if(!J?.trim())return"Error: id is required.";let Y=Z.status,Q=nZ(J,Y);if(!Q)return`Oportunidade nao encontrada: "${J}"`;return`Oportunidade atualizada: "${Q.title}" -> ${Y}`}case"pitwall_benchmark":{let J=Z.command;if(!J?.trim())return"Error: command is required.";let Y=Z.key,Q=Math.min(Math.max(Z.iterations||1,1),10),X=Z.warmup||!1,z=Z.cwd,G=await b7(J,{scriptKey:Y,cwd:z,iterations:Q,warmup:X});if(G.exitCode!==0){let V=_7(G);return`AVISO: Comando terminou com exit code ${G.exitCode}. Metricas podem nao ser confiaveis.
274
+
275
+ ${V.markdown}`}return _7(G).markdown}case"pitwall_save_baseline":{let J=Z.command;if(!J?.trim())return"Error: command is required.";let Y=Z.key,Q=Math.min(Math.max(Z.iterations||3,1),10),X=Z.tags||[],z=Z.reset||!1,G=Z.cwd,V=await b7(J,{scriptKey:Y,cwd:G,iterations:Q,warmup:!0});if(V.exitCode!==0)return`Error: Comando falhou (exit code ${V.exitCode}). Corrija o comando antes de salvar baseline.
276
+ `+(V.stderr?`Stderr: ${V.stderr.slice(0,300)}`:"");let H=z?Q6(V,X):J6(V,X),K=H.metrics.durationNs/1e6;return`Baseline salvo: "${H.scriptKey}" (${H.runs} run${H.runs>1?"s":""})
277
+ Duracao: ${K.toFixed(2)}ms
278
+ Memoria: ${(H.metrics.peakMemoryBytes/1024/1024).toFixed(1)}MB
279
+ CPU (user): ${(H.metrics.cpuUserUs/1000).toFixed(2)}ms`}case"pitwall_status":return z6(Y6());case"pitwall_remove_baseline":{let J=Z.key;if(!J?.trim())return"Error: key is required.";return y7(J)?`Baseline removido: "${J}"`:`Baseline nao encontrado: "${J}"`}case"analyze_blast_radius":{let J=Z.file;if(!J?.trim())return"Error: file is required.";let Y=R$(Z.project_dir||process.cwd()),Q=R$(Y,J);if(!Q.startsWith(Y+a4))return"Error: file must be inside project_dir.";try{let X=v7(Y),z=f7(X,Q);return q6(z)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"plan_refactor":{let J=Z.file;if(!J?.trim())return"Error: file is required.";let Y=R$(Z.project_dir||process.cwd()),Q=R$(Y,J);if(!Q.startsWith(Y+a4))return"Error: file must be inside project_dir.";try{let X=v7(Y),z=H6(X,Q);return B6(z)}catch(X){return`Error: ${X instanceof Error?X.message:String(X)}`}}case"archive_session":{if(!d$)return"Error: session manager not initialized.";let J=Z.name;if(!J?.trim())return"Error: name is required.";if(J==="all"){let Y=d$.archiveAll();return Y.length>0?`Arquivadas ${Y.length} sessoes: ${Y.join(", ")}`:"Nenhuma sessao para arquivar (apenas a sessao atual esta ativa)."}return d$.archive(J)?`Sessao arquivada: "${J}"`:`Falha ao arquivar "${J}" (nao encontrada ou e a sessao atual).`}case"unarchive_session":{if(!d$)return"Error: session manager not initialized.";let J=Z.name;if(!J?.trim())return"Error: name is required.";return d$.unarchive(J)?`Sessao restaurada: "${J}"`:`Sessao arquivada nao encontrada: "${J}"`}case"list_archived_sessions":{if(!d$)return"Error: session manager not initialized.";let J=d$.listArchived();if(J.length===0)return"Nenhuma sessao arquivada.";let Y=J.map((Q)=>{let X=d$.getArchivedInfo(Q),z=X?new Date(X.updated).toLocaleDateString("pt-BR"):"",G=X?`${X.messageCount} msgs`:"";return` ${Q.padEnd(20)} ${G.padEnd(10)} ${z}`});return`Sessoes arquivadas (${J.length}):
280
+ ${Y.join(`
281
+ `)}`}default:{let J=F6.find((Y)=>Y.name===$);if(J)return await w9(J,Z);return`Error: unknown tool "${$}"`}}}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}var C6=10485760;function t4($){let Z=R$($),J=process.cwd();if(Z!==J&&!Z.startsWith(J+a4))return`Error: path outside working directory is not permitted: ${Z}`;try{if(Q0(Z)){let Y=_X(Z);if(Y!==J&&!Y.startsWith(J+a4))return`Error: symlink target is outside working directory: ${Y}`}}catch{}return null}function e4($,Z){let J=$[Z];if(typeof J!=="string"||J.trim().length===0)return`Error: '${Z}' is required and must be a non-empty string.`;return null}function tX($){let Z=e4($,"path");if(Z)return Z;let J=R$($.path),Y=t4(J);if(Y)return Y;if(!Q0(J))return`Error: file not found: ${J}`;let Q=j6(J).size;if(Q>C6)return`Error: file too large (${g7(Q)}). Max is ${g7(C6)}.`;let z=m7(J,"utf-8").split(`
282
+ `),G=Math.max(1,$.offset||1),V=Math.min(2000,$.limit||500),M=z.slice(G-1,G-1+V).map((O,j)=>`${String(G+j).padStart(4)} ${O}`).join(`
283
+ `),B=z.length-(G-1+V);if(B>0)M+=`
284
+ ... (${B} more lines, total ${z.length})`;return r4(M)}function eX($){let Z=e4($,"path");if(Z)return Z;let J=R$($.path),Y=t4(J);if(Y)return Y;let Q=$.content,X=Q0(J);s4.saveState(J),k(J,Q);let z=Q.split(`
285
+ `).length;return`${X?"Updated":"Created"}: ${J} (${z} lines)`}function $z($){let Z=e4($,"path");if(Z)return Z;let J=R$($.path),Y=t4(J);if(Y)return Y;if(!Q0(J))return`Error: file not found: ${J}`;let Q=m7(J,"utf-8"),X=$.old_text,z=$.new_text,G=Q.split(X).length-1;if(G===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(G>1)return`Error: old_text found ${G} times. It must be unique. Include more surrounding context.`;s4.saveState(J);let V=Q.split(X).join(z);k(J,V);let H=X.split(`
286
+ `).length,K=z.split(`
287
+ `).length;return`Edited: ${J} (replaced ${H} lines with ${K} lines)`}async function Zz($){let Z=e4($,"pattern");if(Z)return Z;let J=$.pattern,Y=R$($.path||"."),Q=t4(Y);if(Q)return Q;let X=$.include;if(await M5())return Jz(J,Y,X);return Yz(J,Y,X)}async function Jz($,Z,J){let Y=["rg","--no-heading","--line-number","--color=never"];if(J)Y.push("--glob",J);for(let G of $8)Y.push("--glob",`!${G}`);Y.push("-e",$,Z);let Q=Bun.spawn(Y,{stdout:"pipe",stderr:"pipe"}),X=await new Response(Q.stdout).text(),z=await new Response(Q.stderr).text();if(await Q.exited,!X.trim()&&!z.trim())return"No matches found.";if(z.trim()&&!X.trim())return`Error: ${z.trim()}`;return Vz(X,Z)}async function Yz($,Z,J){let Y;try{Y=new RegExp($)}catch(K){return`Error: invalid regex pattern: ${K instanceof Error?K.message:$}`}let Q=J||"**/*",X=new Bun.Glob(Q),z=[],G=0,V=5000;for await(let K of X.scan({cwd:Z,onlyFiles:!0})){if(V2(K))continue;if(++G>V){z.push(`... (stopped after scanning ${V} files)`);break}let M=E6(Z,K);try{let O=m7(M,"utf-8").split(`
288
+ `);for(let j=0;j<O.length;j++)if(Y.test(O[j])){if(z.push(`${K}:${j+1}:${O[j]}`),z.length>=100)break}}catch{}if(z.length>=100)break}if(z.length===0)return"No matches found.";let H=z.slice(0,100).join(`
289
+ `);if(z.length>100)H+=`
290
+ ... (showing first 100 matches)`;return r4(H)}async function Qz($){let Z=e4($,"pattern");if(Z)return Z;let J=$.pattern,Y=R$($.path||"."),Q=t4(Y);if(Q)return Q;let X=new Bun.Glob(J),z=[];for await(let V of X.scan({cwd:Y,onlyFiles:!0})){if(V2(V))continue;if(z.push(V),z.length>=200)break}if(z.length===0)return"No files found.";let G=z.join(`
291
+ `);if(z.length>=200)G+=`
292
+ ... (showing first 200 files)`;return G}function Xz($){let Z=R$($.path||"."),J=t4(Z);if(J)return J;if(!Q0(Z))return`Error: not found: ${Z}`;return bX(Z,{withFileTypes:!0}).sort((X,z)=>{if(X.isDirectory()!==z.isDirectory())return X.isDirectory()?-1:1;return X.name.localeCompare(z.name)}).map((X)=>{if(X.isDirectory())return`d ${X.name}/`;try{let z=j6(E6(Z,X.name)),G=g7(z.size);return`f ${X.name} ${G}`}catch{return`f ${X.name}`}}).join(`
293
+ `)}async function zz($){let Z=e4($,"command");if(Z)return Z;let J=$.command,Y=Math.min(120,Math.max(5,$.timeout||30)),Q=D4(),X=Bun.spawn([...Q,J],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),z=setTimeout(()=>X.kill(),Y*1000),[G,V]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),H=await X.exited;clearTimeout(z);let K="";if(G.trim())K+=G.trim();if(V.trim())K+=(K?`
283
294
  `:"")+`STDERR:
284
- `+G.trim();if(H!==0)z+=(z?`
285
- `:"")+`Exit code: ${H}`;return p1(z||"(no output)")}async function fQ($){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 L=wZ(E);if(L)return`Redirect blocked: ${L}`;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(([L,w])=>`${L}: ${w}`).join(`
295
+ `+V.trim();if(H!==0)K+=(K?`
296
+ `:"")+`Exit code: ${H}`;return r4(K||"(no output)")}async function Kz($){let Z=$.url,J=$.method||"GET",Y=$.headers||{},Q=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let X=M6(Z);if(X)return X;try{let z=new AbortController,G=setTimeout(()=>z.abort(),30000),V=await fetch(Z,{method:J,redirect:"manual",headers:{"User-Agent":"smolerclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...Y},body:Q&&J!=="GET"&&J!=="HEAD"?Q:void 0,signal:z.signal});if(clearTimeout(G),V.status>=300&&V.status<400){let O=V.headers.get("location");if(!O)return`Status: ${V.status} (redirect with no location header)`;let j=M6(O);if(j)return`Redirect blocked: ${j}`;return`Status: ${V.status} -> Redirect to: ${O}
297
+ (Use fetch_url on the redirect target if needed)`}let H=`${V.status} ${V.statusText}`,K=V.headers.get("content-type")||"";if(J==="HEAD"){let O=[...V.headers.entries()].map(([j,A])=>`${j}: ${A}`).join(`
287
298
  `);return`Status: ${H}
288
- ${E}`}let M=G.headers.get("content-length");if(M&&Number(M)>d0*2)return`Status: ${H}
299
+ ${O}`}let M=V.headers.get("content-length");if(M&&Number(M)>e1*2)return`Status: ${H}
289
300
 
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=vQ(N);return p1(`Status: ${H}
301
+ Error: response body too large (${M} bytes). Max is ${e1*2} bytes.`;let B=await V.text();if(K.includes("text/html")){let O=Gz(B);return r4(`Status: ${H}
291
302
 
292
- ${E}`)}return p1(`Status: ${H}
303
+ ${O}`)}return r4(`Status: ${H}
293
304
 
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 vQ($){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,`
305
+ ${B}`)}catch(z){if(z instanceof Error&&z.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${z instanceof Error?z.message:String(z)}`}}function M6($){try{let Z=new URL($),J=Z.hostname.toLowerCase();if(Z.protocol!=="http:"&&Z.protocol!=="https:")return`Error: protocol ${Z.protocol} is not allowed.`;if(["localhost","127.0.0.1","::1","0.0.0.0","::ffff:127.0.0.1","::ffff:0.0.0.0"].includes(J))return"Error: requests to localhost are blocked for security.";if(J.endsWith(".local")||J.endsWith(".internal"))return"Error: requests to internal hostnames are blocked.";if(J==="metadata.google.internal"||J==="metadata.gcp.internal")return"Error: requests to cloud metadata endpoints are blocked.";let Q=J.split(".").map(Number);if(Q.length===4&&Q.every((X)=>!isNaN(X)&&X>=0&&X<=255)){if(Q[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(Q[0]===172&&Q[1]>=16&&Q[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(Q[0]===192&&Q[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(Q[0]===169&&Q[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(Q[0]===0)return"Error: requests to 0.x IPs are blocked."}if(J.startsWith("::ffff:")||J.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function Gz($){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,`
295
306
  `).replace(/<(br|hr)[^>]*\/?>/gi,`
296
307
  `).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,`
297
308
 
298
- `).trim()}function gQ($,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(`
300
- `);if(V>100)G+=`
301
- ... (${V-100} more matches)`;return p1(G)}function p1($){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 c4(Z)}var mQ=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(cQ(K)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(X+1,500,"Auth refreshed, retrying..."),await vZ(500,Z.signal);continue}}if(!dQ(K))throw K;let G=uQ(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 cQ($){if(!($ instanceof Error))return!1;return $.status===401}function dQ($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&mQ.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 uQ($){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 pQ={haiku:200000,sonnet:200000,opus:200000};function J1($){return Math.ceil($.length/3.5)}function j7($){let Z=0;for(let Y of $){if(Z+=J1(Y.content),Y.toolCalls)for(let J of Y.toolCalls)Z+=J1(JSON.stringify(J.input)),Z+=J1(J.result);Z+=10}return Z}function F7($){let Z=$.toLowerCase();for(let[Y,J]of Object.entries(pQ))if(Z.includes(Y))return J;return 200000}function mZ($,Z,Y){let J=F7(Z)-20000-Y;if(j7($)<=J)return $;let X=[],K=J,V=[...$].reverse(),G=[];for(let z of V){let M=J1(z.content)+(z.toolCalls?.reduce((N,E)=>N+J1(JSON.stringify(E.input))+J1(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=F7(Z)-20000-Y;return j7($)>J*0.7}function dZ($,Z,Y){let J=F7(Z)-20000-Y;if(j7($)<=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:
309
+ `).trim()}function Vz($,Z){let J=process.cwd(),Y=J+a4,Q=Z+a4,z=$.trim().split(`
310
+ `).map((H)=>{if(H.startsWith(Y))return"."+H.slice(J.length).replace(/\\/g,"/");if(H.startsWith(Q))return"."+H.slice(Z.length).replace(/\\/g,"/");return H}),G=z.length,V=z.slice(0,100).join(`
311
+ `);if(G>100)V+=`
312
+ ... (${G-100} more matches)`;return r4(V)}function r4($){if($.length<=e1)return $;return $.slice(0,e1)+`
313
+ ... (output truncated)`}function g7($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function O6($){let Z=$.toLowerCase().trim(),J=new Date;if(Z==="hoje")return J;if(Z==="amanha"||Z==="amanh\xE3"){let G=new Date(J);return G.setDate(G.getDate()+1),G}let Y=Z.match(/em\s+(\d+)\s*dias?/);if(Y){let G=new Date(J);return G.setDate(G.getDate()+parseInt(Y[1])),G}let Q=Z.match(/em\s+(\d+)\s*semanas?/);if(Q){let G=new Date(J);return G.setDate(G.getDate()+parseInt(Q[1])*7),G}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[G,V]of Object.entries(X))if(Z.includes(G)){let H=new Date(J),K=(V-H.getDay()+7)%7||7;return H.setDate(H.getDate()+K),H}let z=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(z){let G=parseInt(z[1]),V=parseInt(z[2])-1,H=z[3]?parseInt(z[3])+(z[3].length===2?2000:0):J.getFullYear(),K=new Date(H,V,G);if(!isNaN(K.getTime()))return K}return r8(Z)}var Wz=new Set([429,500,502,503,529]);async function T6($,Z={}){let J=Z.maxRetries??3,Y=Z.baseDelayMs??1000,Q;for(let X=0;X<=J;X++)try{return await $()}catch(z){if(Q=z,Z.signal?.aborted)throw z;if(X>=J)throw z;if(Hz(z)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(X+1,500,"Auth refreshed, retrying..."),await x6(500,Z.signal);continue}}if(!qz(z))throw z;let V=Uz(z)??Y*Math.pow(2,X),H=z instanceof Error?z.message:String(z);Z.onRetry?.(X+1,V,H),await x6(V,Z.signal)}throw Q}function Hz($){if(!($ instanceof Error))return!1;return $.status===401}function qz($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&Wz.has(Z))return!0;let J=$.message.toLowerCase();if(J.includes("econnreset")||J.includes("econnrefused"))return!0;if(J.includes("etimedout")||J.includes("socket hang up"))return!0;if(J.includes("overloaded"))return!0;return!1}function Uz($){let Z=$.headers;if(!Z)return null;let J=Z["retry-after"];if(!J)return null;let Y=Number(J);if(!isNaN(Y)&&Y>0)return Math.min(Y,60)*1000;return null}function x6($,Z){return new Promise((J,Y)=>{let Q=setTimeout(J,$);Z?.addEventListener("abort",()=>{clearTimeout(Q),Y(Error("Aborted"))},{once:!0})})}var Bz={haiku:200000,sonnet:200000,opus:200000};function z4($){return Math.ceil($.length/3.5)}function d7($){let Z=0;for(let J of $){if(Z+=z4(J.content),J.toolCalls)for(let Y of J.toolCalls)Z+=z4(JSON.stringify(Y.input)),Z+=z4(Y.result);Z+=10}return Z}function u7($){let Z=$.toLowerCase();for(let[J,Y]of Object.entries(Bz))if(Z.includes(J))return Y;return 200000}function P6($,Z,J){let Y=u7(Z)-20000-J;if(d7($)<=Y)return $;let X=[],z=Y,G=[...$].reverse(),V=[];for(let K of G){let M=z4(K.content)+(K.toolCalls?.reduce((B,O)=>B+z4(JSON.stringify(O.input))+z4(O.result),0)??0)+10;if(z-M<0)break;z-=M,V.unshift(K)}let H=$.length-V.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(...V),X}function I6($,Z,J){let Y=u7(Z)-20000-J;return d7($)>Y*0.7}function w6($,Z,J){let Y=u7(Z)-20000-J;if(d7($)<=Y*0.7)return null;let X=Math.max(4,Math.floor($.length*0.3)),z=$.slice(0,$.length-X),G=$.slice($.length-X);if(z.length<2)return null;return{toSummarize:z,toKeep:G}}function S6($){return`Summarize this conversation concisely. Focus on:
303
314
  1. Key decisions made
304
315
  2. Files created or modified
305
316
  3. Important context the user shared
@@ -308,62 +319,63 @@ ${N}`)}catch(K){if(K instanceof Error&&K.name==="AbortError")return"Error: Reque
308
319
  Be brief but preserve actionable information. Output ONLY the summary.
309
320
 
310
321
  ---
311
- ${$.map((Y)=>{let J=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)J+=`
312
- Tools used: ${Y.toolCalls.map((Q)=>Q.name).join(", ")}`;return J}).join(`
322
+ ${$.map((J)=>{let Y=`[${J.role}]: ${J.content.slice(0,500)}`;if(J.toolCalls?.length)Y+=`
323
+ Tools used: ${J.toolCalls.map((Q)=>Q.name).join(", ")}`;return Y}).join(`
313
324
 
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 lQ=[/\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],nQ=[/\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 lQ)if(J.test(Y))return{level:"dangerous",reason:Y};for(let J of nQ)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 L7($){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: ${iQ(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 "${oQ(Y)}" may not exist or be unavailable.
325
+ `)}`}function k6($,Z=2000){return $.map((J)=>{if(!J.toolCalls?.length)return J;let Y=J.toolCalls.map((Q)=>{if(Q.result.length<=Z)return Q;let X=Q.result.split(`
326
+ `),z=Math.min(10,X.length),G=Math.min(5,Math.max(0,X.length-z)),V=X.length-z-G,H=[...X.slice(0,z)];if(V>0)H.push(`... (${V} lines omitted)`);if(G>0)H.push(...X.slice(-G));let K=H.join(`
327
+ `);return{...Q,result:K}});return{...J,toolCalls:Y}})}var Nz=[/\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],Cz=[/\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 b6($,Z){switch($){case"read_file":case"list_directory":case"find_files":case"search_files":case"fetch_url":case"read_clipboard_content":case"analyze_screen_context":case"memory_status":case"recall_memory":return{level:"safe"};case"write_file":return{level:"moderate",reason:`write ${Z.path}`};case"edit_file":return{level:"moderate",reason:`edit ${Z.path}`};case"run_command":{let J=String(Z.command||"");for(let Y of Nz)if(Y.test(J))return{level:"dangerous",reason:J};for(let Y of Cz)if(Y.test(J))return{level:"moderate",reason:J};return{level:"moderate",reason:J}}case"execute_powershell_script":return{level:"dangerous",reason:"PowerShell script execution"};default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function p7($){if(!($ instanceof Error))return String($);let{status:Z,message:J}=$;if(Z)switch(Z){case 400:if(J.includes("context_length")||J.includes("too many tokens"))return"Message too long for the model's context window. Try /clear to start fresh or use a shorter prompt.";return`Bad request: ${Mz(J)}`;case 401:return"Authentication failed. Your subscription token may be expired.\nTry: Run `claude` to refresh subscription credentials.";case 403:return`Access denied. Your subscription may not have permission for this model.
328
+ Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${Oz(J)}" may not exist or be unavailable.
318
329
  Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
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 iQ($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function oQ($){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(`
330
+ The request will be retried automatically. If this persists, wait a minute.`;case 500:case 502:case 503:return"Anthropic API is temporarily unavailable. Retrying automatically...";case 529:return"Anthropic API is overloaded. Retrying with backoff..."}let Y=J.toLowerCase();if(Y.includes("econnrefused")||Y.includes("enotfound"))return"Cannot connect to Anthropic API. Check your internet connection.";if(Y.includes("etimedout")||Y.includes("socket hang up"))return"Connection to Anthropic API timed out. Retrying...";if(Y.includes("econnreset"))return"Connection was reset. This usually recovers automatically.";if(Y.includes("expired")||Y.includes("invalid_api_key"))return"Your subscription token has expired. Run `claude` to refresh.";return J}function Mz($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function Oz($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function y6($,Z,J){if($==="auto")return!1;if(J==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command","execute_powershell_script"].includes(Z);if($==="confirm-all")return J!=="safe";return!1}function _6($,Z){switch($){case"write_file":return`Write file: ${Z.path}`;case"edit_file":return`Edit file: ${Z.path}`;case"run_command":{let J=String(Z.command||"");return`Run: ${J.length>60?J.slice(0,57)+"...":J}`}case"execute_powershell_script":{let J=String(Z.script||""),Y=J.split(`
331
+ `)[0]||"",Q=J.split(`
332
+ `).length;return`PowerShell (${Q} line${Q>1?"s":""}): ${Y.length>50?Y.slice(0,47)+"...":Y}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function h6($,Z,J=20){let Y=$.split(`
322
333
  `),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 F$({apiKey:$}),this.approvalMode=J}updateApiKey($){this.client=new F$({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=J1(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=aQ(X),V=Y?n:void 0;try{yield*this.streamLoop(K,Z,V)}catch(G){yield{type:"error",error:L7(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:L7(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 w=await E7(z.name,M);yield{type:"tool_result",id:z.id,name:z.name,result:w},H.push({type:"tool_result",tool_use_id:z.id,content:w});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 aQ($){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}t();import{existsSync as O$,mkdirSync as aZ,readdirSync as rZ,readFileSync as A7,unlinkSync as sZ,renameSync as x7}from"fs";import{join as X$}from"path";class D7{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=X$($,"sessions"),this.archiveDir=X$($,"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=X$(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=X$(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=X$(this.sessionsDir,`${$}.json`);return P(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=X$(this.sessionsDir,`${$}.json`);if(!O$(Z))return!1;let Y=X$(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=X$(this.archiveDir,`${$}.json`);if(!O$(Z))return!1;let Y=X$(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=X$(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=X$(this.archiveDir,`${$}.json`);if(O$(Z))return sZ(Z),!0;return!1}loadOrCreate($){let Z=X$(this.sessionsDir,`${$}.json`);if(O$(Z))try{return JSON.parse(A7(Z,"utf-8"))}catch{let J=X$(this.sessionsDir,`${$}.corrupt.json`);try{x7(Z,J)}catch{}}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return P(Z,JSON.stringify(Y,null,2)),Y}save(){let $=X$(this.sessionsDir,`${this.current.name}.json`);P($,JSON.stringify(this.current,null,2))}}import{existsSync as $6,readdirSync as eQ,readFileSync as Z6}from"fs";import{join as P7}from"path";import{existsSync as T7,readFileSync as tZ}from"fs";import{basename as rQ,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=sQ($);if(Y)Z.push(`Project: ${Y}`);let J=tQ($);if(J)Z.push(J);return Z.join(`
325
- `)}function sQ($){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=rQ($);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 tQ($){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(`
334
+ `),X=[],z=Y.slice(0,J);for(let V of z)X.push(` \x1B[31m- ${V}\x1B[0m`);if(Y.length>J)X.push(` \x1B[2m ... (${Y.length-J} more removed)\x1B[0m`);let G=Q.slice(0,J);for(let V of G)X.push(` \x1B[32m+ ${V}\x1B[0m`);if(Q.length>J)X.push(` \x1B[2m ... (${Q.length-J} more added)\x1B[0m`);return X}class l7{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,J,Y="auto"){this.model=Z;this.maxTokens=J;this.client=new x$({apiKey:$}),this.approvalMode=Y}updateApiKey($){this.client=new x$({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,J=!0){let Y=k6($),Q=z4(Z);if(I6(Y,this.model,Q)){let V=w6(Y,this.model,Q);if(V)try{let K={role:"assistant",content:`[Conversation summary]
335
+ ${await this.generateSummary(V.toSummarize)}`,timestamp:Date.now()};Y=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},K,...V.toKeep]}catch{}}let X=P6(Y,this.model,Q),z=jz(X),G=J?l:void 0;try{yield*this.streamLoop(z,Z,G)}catch(V){yield{type:"error",error:p7(V)}}}async generateSummary($){let Z=S6($),Y=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((Q)=>Q.type==="text");return Y?.type==="text"?Y.text:"Summary unavailable."}async*streamLoop($,Z,J){let Q=[...$],X=0;while(X++<25){let z;try{z=await T6(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:Q,...J?.length?{tools:J}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(K){yield{type:"error",error:p7(K)};return}for await(let K of z)if(K.type==="content_block_delta"&&K.delta.type==="text_delta")yield{type:"text",text:K.delta.text};let G=await z.finalMessage();if(G.usage)yield{type:"usage",inputTokens:G.usage.input_tokens,outputTokens:G.usage.output_tokens};if(G.stop_reason!=="tool_use"){yield{type:"done"};return}let V=G.content.filter((K)=>K.type==="tool_use");Q.push({role:"assistant",content:G.content});let H=[];for(let K of V){let M=K.input,B=b6(K.name,M);if(B.level==="dangerous"){yield{type:"tool_blocked",id:K.id,name:K.name,reason:`Blocked dangerous operation: ${B.reason}`},H.push({type:"tool_result",tool_use_id:K.id,content:`Error: Operation blocked for safety. Reason: ${B.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&y6(this.approvalMode,K.name,B.level)&&this.approvalCallback){if(yield{type:"tool_call",id:K.id,name:K.name,input:K.input},!await this.approvalCallback(K.name,M,B.level)){yield{type:"tool_blocked",id:K.id,name:K.name,reason:"Rejected by user"},H.push({type:"tool_result",tool_use_id:K.id,content:"Error: User rejected this operation."});continue}let A=await c7(K.name,M);yield{type:"tool_result",id:K.id,name:K.name,result:A},H.push({type:"tool_result",tool_use_id:K.id,content:A});continue}yield{type:"tool_call",id:K.id,name:K.name,input:K.input};let O=await c7(K.name,M);yield{type:"tool_result",id:K.id,name:K.name,result:O},H.push({type:"tool_result",tool_use_id:K.id,content:O})}Q.push({role:"user",content:H})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function jz($){let Z=[];for(let J of $)if(J.role==="user")if(J.images?.length){let Y=J.images.map((Q)=>({type:"image",source:{type:"base64",media_type:Q.mediaType,data:Q.base64}}));Y.push({type:"text",text:J.content}),Z.push({role:"user",content:Y})}else Z.push({role:"user",content:J.content});else if(J.role==="assistant")if(J.toolCalls?.length){let Y=[];if(J.content)Y.push({type:"text",text:J.content});for(let Q of J.toolCalls)Y.push({type:"tool_use",id:Q.id,name:Q.name,input:Q.input});Z.push({role:"assistant",content:Y}),Z.push({role:"user",content:J.toolCalls.map((Q)=>({type:"tool_result",tool_use_id:Q.id,content:Q.result}))})}else Z.push({role:"assistant",content:J.content});return Z}e();import{existsSync as B$,mkdirSync as v6,readdirSync as f6,readFileSync as $2,unlinkSync as g6,renameSync as o7}from"fs";import{join as Z$}from"path";class n7{sessionsDir;archiveDir;current;constructor($){if(this.sessionsDir=Z$($,"sessions"),this.archiveDir=Z$($,"sessions","archive"),!B$(this.sessionsDir))v6(this.sessionsDir,{recursive:!0});if(!B$(this.archiveDir))v6(this.archiveDir,{recursive:!0});this.current=this.loadOrCreate("default")}get session(){return this.current}get messages(){return this.current.messages}addMessage($){this.current.messages.push($),this.current.updated=Date.now(),this.save()}trimHistory($){if(this.current.messages.length>$)this.current.messages=this.current.messages.slice(-$),this.save()}clear(){this.current.messages=[],this.current.updated=Date.now(),this.save()}popMessages($){let Z=this.current.messages.splice(-$,$);return this.current.updated=Date.now(),this.save(),Z}switchTo($){return this.current=this.loadOrCreate($),this.saveLastSession(),this.current}list(){if(!B$(this.sessionsDir))return[];return f6(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=Z$(this.sessionsDir,`${$}.json`);if(!B$(Z))return null;try{let J=JSON.parse($2(Z,"utf-8"));return{messageCount:J.messages.length,updated:J.updated}}catch{return null}}delete($){let Z=Z$(this.sessionsDir,`${$}.json`);if(B$(Z))return g6(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},J=Z$(this.sessionsDir,`${$}.json`);return k(J,JSON.stringify(Z,null,2)),this.current=Z,Z}archive($){if($===this.current.name)return!1;let Z=Z$(this.sessionsDir,`${$}.json`);if(!B$(Z))return!1;let J=Z$(this.archiveDir,`${$}.json`);return o7(Z,J),!0}archiveAll(){let $=[],Z=this.list().filter((J)=>J!==this.current.name);for(let J of Z)if(this.archive(J))$.push(J);return $}unarchive($){let Z=Z$(this.archiveDir,`${$}.json`);if(!B$(Z))return!1;let J=Z$(this.sessionsDir,`${$}.json`);return o7(Z,J),!0}listArchived(){if(!B$(this.archiveDir))return[];return f6(this.archiveDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getArchivedInfo($){let Z=Z$(this.archiveDir,`${$}.json`);if(!B$(Z))return null;try{let J=JSON.parse($2(Z,"utf-8"));return{messageCount:J.messages.length,updated:J.updated}}catch{return null}}deleteArchived($){let Z=Z$(this.archiveDir,`${$}.json`);if(B$(Z))return g6(Z),!0;return!1}loadOrCreate($){let Z=Z$(this.sessionsDir,`${$}.json`);if(B$(Z))try{return JSON.parse($2(Z,"utf-8"))}catch{let Y=Z$(this.sessionsDir,`${$}.corrupt.json`);try{o7(Z,Y)}catch{}}let J={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return k(Z,JSON.stringify(J,null,2)),J}saveLastSession(){let $=Z$(this.sessionsDir,"..","last-session.txt");k($,this.current.name)}getLastSession(){let $=Z$(this.sessionsDir,"..","last-session.txt");if(!B$($))return null;try{let Z=$2($,"utf-8").trim();if(!Z||!B$(Z$(this.sessionsDir,`${Z}.json`)))return null;return Z}catch{return null}}save(){let $=Z$(this.sessionsDir,`${this.current.name}.json`);k($,JSON.stringify(this.current,null,2))}}import{existsSync as d6,readdirSync as Rz,readFileSync as u6}from"fs";import{join as a7}from"path";s();import{existsSync as i7,readFileSync as m6}from"fs";import{basename as Ez,join as Z2}from"path";function c6(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${C5()}`),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 J=Fz($);if(J)Z.push(`Project: ${J}`);let Y=Lz($);if(Y)Z.push(Y);return Z.join(`
336
+ `)}function Fz($){let Z=[["package.json","Node.js/JavaScript"],["Cargo.toml","Rust"],["go.mod","Go"],["pyproject.toml","Python"],["requirements.txt","Python"],["pom.xml","Java (Maven)"],["build.gradle","Java (Gradle)"],["Gemfile","Ruby"],["composer.json","PHP"],["Makefile","Make"],["CMakeLists.txt","C/C++ (CMake)"],["Dockerfile","Docker"]],J=[];for(let[Q,X]of Z)if(i7(Z2($,Q)))J.push(X);if(J.length===0)return null;let Y=Ez($);try{let Q=Z2($,"package.json");if(i7(Q)){let X=JSON.parse(m6(Q,"utf-8"));if(X.name)Y=X.name}}catch{}return`Project: ${Y} (${J.join(", ")})`}function Lz($){if(!i7(Z2($,".git")))return null;let Z=[];try{let J=m6(Z2($,".git","HEAD"),"utf-8").trim(),Y=J.startsWith("ref: refs/heads/")?J.slice(16):J.slice(0,8);Z.push(`Git branch: ${Y}`)}catch{return Z.push("Git: initialized"),Z.join(`
337
+ `)}try{let J=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(J.exitCode===0){let Y=new TextDecoder().decode(J.stdout).trim();if(Y)Z.push(`Last commit: ${Y}`)}}catch{}try{let J=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(J.exitCode===0){let Y=new TextDecoder().decode(J.stdout).trim();if(Y){let Q=Y.split(`
327
338
  `),X=Q.slice(0,15);if(Q.length>15)X.push(`... and ${Q.length-15} more files`);Z.push(`Uncommitted changes:
328
339
  `+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(`
340
+ `))}}}catch{}try{let J=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(J.exitCode===0){let Y=new TextDecoder().decode(J.stdout).trim();if(Y){let Q=Y.split(`
330
341
  `).slice(0,10);Z.push(`Staged:
331
342
  `+Q.join(`
332
343
  `))}}}catch{}return Z.length>0?Z.join(`
333
- `):null}function Y6($,Z){if(!$6($))return[];let Y=[],J=eQ($,{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:
344
+ `):null}function p6($,Z){if(!d6($))return[];let J=[],Y=Rz($,{withFileTypes:!0});for(let Q of Y)if(Q.isFile()&&Q.name.endsWith(".md")){let X=u6(a7($,Q.name),"utf-8");J.push({name:Q.name.replace(".md",""),content:X.trim(),source:Z})}else if(Q.isDirectory()){let X=a7($,Q.name,"SKILL.md");if(d6(X)){let z=u6(X,"utf-8");J.push({name:Q.name,content:z.trim(),source:Z})}}return J}function l6($){let Z=p6($,"global"),J=a7(process.cwd(),".smolerclaw","skills"),Y=p6(J,"local"),Q=new Map;for(let X of Z)Q.set(X.name,X);for(let X of Y)Q.set(X.name,X);return[...Q.values()]}function o6($){if($.length===0)return"No skills loaded.";return`Skills:
334
345
  `+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
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(`---
346
+ `)}function r7($,Z,J="auto"){let Y=[];for(let Q of Z)Y.push(Q.content);if(J&&J!=="auto"){let X={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[J]||J;Y.push(`## Language Override
347
+ ALWAYS respond in ${X}. This is a hard requirement.`)}if(Y.push(`---
337
348
  ## Environment
338
349
  The user's current working directory and project info. Use this context when they ask about code or files.
339
350
 
340
- `+eZ()),$)J.push(`## User Instructions
341
- `+$);return J.join(`
351
+ `+c6()),$)Y.push(`## User Instructions
352
+ `+$);return Y.join(`
342
353
 
343
- `)}var $X=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function R$($){return $X?"":$}var B={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 c={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 x($){process.stdout.write($)}var ZX=/\x1b\[[0-9;]*[a-zA-Z]/g;function p0($){return $.replace(ZX,"")}function YX($){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+=YX(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=JX(J);for(let z=0;z<V.length;z++)if(H&&z===0)V[z]=H+V[z]+B.reset;else if(H)V[z]=H+V[z]+B.reset;Y.push(...V)}return Y}function JX($){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(` ${B.dim}\u250C\u2500\u2500${z}${"\u2500".repeat(Math.max(1,40-z.length))}${B.reset}`)}else J=!1,Q="",Y.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);continue}if(J){Y.push(` ${B.dim}\u2502${B.reset} ${c.code}${K}${B.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(` ${c.heading}${B.bold}${N} ${a4(M)}${B.reset}`);continue}if(K.trimStart().startsWith(">")){let z=K.replace(/^\s*>\s?/,"");Y.push(` ${c.quote}\u2502 ${a4(z)}${B.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}${B.dim}\u2022${B.reset} ${a4(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}${B.dim}${M}.${B.reset} ${a4(N)}`);continue}if(/^[-*_]{3,}\s*$/.test(K.trim())){Y.push(` ${B.dim}${"\u2500".repeat(40)}${B.reset}`);continue}Y.push(` ${a4(K)}`)}if(J)Y.push(` ${B.dim}\u2514${"\u2500".repeat(42)}${B.reset}`);return Y}function a4($){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} ${c.link}($2)${B.reset}`),Z}import{existsSync as QX,readFileSync as XX,writeFileSync as KX}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(QX(this.filePath)){let $=XX(this.filePath,"utf-8");this.entries=$.split(`
346
- `).filter(Boolean).slice(-I7)}}catch{}}save(){try{KX(this.filePath,this.entries.join(`
354
+ `)}var Az=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function P$($){return Az?"":$}var U={altOn:P$("\x1B[?1049h"),altOff:P$("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:P$("\x1B[1m"),dim:P$("\x1B[2m"),italic:P$("\x1B[3m"),underline:P$("\x1B[4m"),reset:P$("\x1B[0m"),inv:P$("\x1B[7m"),fg:($)=>P$(`\x1B[38;5;${$}m`),bg:($)=>P$(`\x1B[48;5;${$}m`)};var g={user:U.fg(75),ai:U.fg(114),tool:U.fg(215),err:U.fg(196),sys:U.fg(245),prompt:U.fg(220),code:U.fg(180),heading:U.fg(75),link:U.fg(39),quote:U.fg(245)};function R($){process.stdout.write($)}var Dz=/\x1b\[[0-9;]*[a-zA-Z]/g;function J2($){return $.replace(Dz,"")}function xz($){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 Y2($){let Z=J2($),J=0;for(let Y of Z)J+=xz(Y);return J}function n6($,Z){if(Z<10)Z=10;let J=[];for(let Y of $.split(`
355
+ `)){if(Y2(Y)<=Z){J.push(Y);continue}let z=J2(Y).split(" "),G=[],V="";for(let K of z)if(V.length+(V?1:0)+K.length>Z&&V)G.push(V),V=" "+K;else V+=(V?" ":"")+K;if(V)G.push(V);let H=Tz(Y);for(let K=0;K<G.length;K++)if(H&&K===0)G[K]=H+G[K]+U.reset;else if(H)G[K]=H+G[K]+U.reset;J.push(...G)}return J}function Tz($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function Q2($){let Z=$.split(`
356
+ `),J=[],Y=!1,Q="";for(let X=0;X<Z.length;X++){let z=Z[X];if(z.trimStart().startsWith("```")){if(!Y){Y=!0,Q=z.trimStart().slice(3).trim();let K=Q?` ${Q}`:"";J.push(` ${U.dim}\u250C\u2500\u2500${K}${"\u2500".repeat(Math.max(1,40-K.length))}${U.reset}`)}else Y=!1,Q="",J.push(` ${U.dim}\u2514${"\u2500".repeat(42)}${U.reset}`);continue}if(Y){J.push(` ${U.dim}\u2502${U.reset} ${g.code}${z}${U.reset}`);continue}if(!z.trim()){J.push("");continue}let G=z.match(/^(#{1,3})\s+(.+)/);if(G){let K=G[1].length,M=G[2],B=K===1?"\u2501":K===2?"\u2500":"\xB7";J.push(` ${g.heading}${U.bold}${B} ${X0(M)}${U.reset}`);continue}if(z.trimStart().startsWith(">")){let K=z.replace(/^\s*>\s?/,"");J.push(` ${g.quote}\u2502 ${X0(K)}${U.reset}`);continue}let V=z.match(/^(\s*)([-*+])\s+(.+)/);if(V){let K=Math.floor(V[1].length/2),M=V[3],B=" ".repeat(K);J.push(` ${B}${U.dim}\u2022${U.reset} ${X0(M)}`);continue}let H=z.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(H){let K=Math.floor(H[1].length/2),M=H[2],B=H[3],O=" ".repeat(K);J.push(` ${O}${U.dim}${M}.${U.reset} ${X0(B)}`);continue}if(/^[-*_]{3,}\s*$/.test(z.trim())){J.push(` ${U.dim}${"\u2500".repeat(40)}${U.reset}`);continue}J.push(` ${X0(z)}`)}if(Y)J.push(` ${U.dim}\u2514${"\u2500".repeat(42)}${U.reset}`);return J}function X0($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${U.inv} $1 ${U.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${U.bold}${U.italic}$1${U.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${U.bold}$1${U.reset}`),Z=Z.replace(/__(.+?)__/g,`${U.bold}$1${U.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${U.italic}$1${U.reset}`),Z=Z.replace(/_(.+?)_/g,`${U.italic}$1${U.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${U.underline}$1${U.reset} ${g.link}($2)${U.reset}`),Z}import{existsSync as Pz,readFileSync as Iz,writeFileSync as wz}from"fs";var s7=500;class t7{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>s7)this.entries=this.entries.slice(-s7);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(Pz(this.filePath)){let $=Iz(this.filePath,"utf-8");this.entries=$.split(`
357
+ `).filter(Boolean).slice(-s7)}}catch{}}save(){try{wz(this.filePath,this.entries.join(`
347
358
  `)+`
348
- `)}catch{}}}import{join as zX}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(zX(this.dataDir,"history"));x(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(),x(B.show),x(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=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:` ${c.tool}\u2699 ${$}${B.reset} ${B.dim}${J}${B.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:` ${B.dim}${K}${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:` ${c.prompt}? ${$}${B.reset} ${B.dim}[y]es / [n]o / [a]ll${B.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:` ${c.sys}approved${B.reset}`}),this.renderAll(),Z(!0);else if(Q==="n"||Q==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${c.err}rejected${B.reset}`}),this.renderAll(),Z(!1);else if(Q==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${c.sys}approved all for this session${B.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${B.dim}timeout \u2014 auto-rejected${B.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{let Y=$.findIndex((H)=>H.isCurrent);if(Y<0)Y=0;let J="",Q=!1,X=()=>{if(!J)return $;let H=J.toLowerCase();return $.filter((z)=>z.name.toLowerCase().includes(H))},K=()=>{let M=this.height-2-2,N=X();if(Y>=N.length)Y=Math.max(0,N.length-1);let E=2,L=2,w=M-E-L,S=Math.max(1,w),k=0;if(N.length>S)k=Math.max(0,Y-Math.floor(S/2)),k=Math.min(k,N.length-S);let f$=N.slice(k,k+S);if(x(B.hide),x(B.to(3,1)),x(B.clearLine),Q)x(` ${c.heading}${B.bold}Sessions${B.reset} ${B.dim}filter: ${J}\u2588${B.reset}`);else x(` ${c.heading}${B.bold}Sessions${B.reset} ${B.dim}(${N.length})${B.reset}`);x(B.to(4,1)),x(B.clearLine);for(let f=0;f<S;f++){let O=2+E+f+1;if(x(B.to(O,1)),x(B.clearLine),f>=f$.length)continue;let W=f$[f],C=k+f===Y,j=W.isCurrent?"*":" ",T=W.isArchived?`${B.dim}[arch] ${B.reset}`:" ",b=`${W.messageCount} msgs`.padEnd(10),a=GX(W.updated);if(C)x(` ${c.prompt}${B.bold}\u203A ${j} ${T}${c.prompt}${B.bold}${W.name.padEnd(20)}${B.reset} ${B.dim}${b} ${a}${B.reset}`);else{let A$=W.isArchived?B.dim:c.sys;x(` ${j} ${T}${A$}${W.name.padEnd(20)}${B.reset} ${B.dim}${b} ${a}${B.reset}`)}}for(let f=f$.length;f<S;f++){let O=2+E+f+1;x(B.to(O,1)),x(B.clearLine)}let h=2+E+S+1;if(x(B.to(h,1)),x(B.clearLine),N.length>S){let f=Math.round((Y+1)/N.length*100);x(` ${B.dim}${k>0?"\u2191":" "} ${f}% ${k+S<N.length?"\u2193":" "}${B.reset}`)}let o=this.height-2;x(B.to(o,1)),x(B.clearLine),x(` ${B.dim}\u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${B.reset}`)},V=(H)=>{process.stdin.removeListener("data",G),this.renderAll(),Z(H)},G=(H)=>{let z=H.toString("utf-8"),M=X();if(z==="\x1B"&&H.length===1){if(Q)Q=!1,J="",K();else V(null);return}if(z==="\x03"){V(null);return}if(z==="\r"||z===`
351
- `){if(M.length>0&&Y<M.length)V({action:"load",name:M[Y].name});return}if(z==="\x1B[A"){if(Y>0)Y--,K();return}if(z==="\x1B[B"){if(Y<M.length-1)Y++,K();return}if(z==="d"&&Q===!1){if(M.length>0&&Y<M.length){let N=M[Y];if(!N.isCurrent)V({action:"delete",name:N.name,isArchived:N.isArchived})}return}if(z==="a"&&Q===!1){if(M.length>0&&Y<M.length){let N=M[Y];if(!N.isCurrent){let E=N.isArchived?"unarchive":"archive";V({action:E,name:N.name})}}return}if(z==="/"&&Q===!1){Q=!0,J="",K();return}if(Q){if(z==="\x7F"||z==="\b"){if(J.length>0)J=J.slice(0,-1),Y=0,K();else Q=!1,K();return}if(z.length===1&&z>=" "){J+=z,Y=0,K();return}}};process.stdin.on("data",G),K()})}showUsage($){this.lines.push({text:` ${B.dim}tokens: ${$}${B.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${c.err}\u2717 ${$}${B.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
352
- `))this.lines.push({text:` ${c.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(){x(B.hide)}render(){x(B.hide),x(B.clear),this.renderHeader(),this.renderMessages(),this.renderInput(),x(B.show)}renderAll(){this.renderMessages(),this.renderInput()}renderHeader(){x(B.to(1,1)),x(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);x($+" ".repeat(J)+Y),x(B.reset),x(B.to(2,1)),x(`${B.dim}${"\u2500".repeat(this.width)}${B.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);x(B.hide);for(let G=0;G<Y;G++)if(x(B.to(2+G+1,1)),x(B.clearLine),G<V.length){let H=p0(V[G].text);if(H.length>this.width)x(V[G].text.slice(0,this.width+(V[G].text.length-H.length))),x(B.reset);else x(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(x(B.to($,1)),x(B.clearLine),x(`${B.dim}${"\u2500".repeat(this.width)}${B.reset}`),x(B.to(Z,1)),x(B.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);x(` ${c.ai}${this.getSpinnerChar()}${B.reset} ${B.dim}streaming... ${Y}s${B.reset}`),x(B.hide)}else{let Y=l0(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;x(`${c.prompt}\u276F${B.reset} ${Y}`);let J=this.inputBuf.slice(0,this.inputPos),Q=l0(J)+3;x(B.to(Z,Math.min(Q,this.width))),x(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.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===`
359
+ `)}catch{}}}import{join as Sz}from"path";class e7{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;pickerActive=!1;lastCtrlCTime=0;constructor($,Z,J="",Y){this.model=$;this.sessionName=Z;this.authInfo=J;this.dataDir=Y}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 t7(Sz(this.dataDir,"history"));R(U.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}stop(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer);process.stdin.setRawMode?.(!1),process.stdin.pause(),R(U.show),R(U.altOff)}addUserMessage($){this.addLabel("user"),this.addWrapped($),this.lines.push({text:""})}addAssistantMessage($){this.addLabel("assistant"),this.addMarkdown($),this.lines.push({text:""})}startStream(){this.isStreaming=!0,this.streamBuf="",this.streamLines=[],this.streamStartTime=Date.now(),this.addLabel("assistant"),this.startSpinner(),this.renderAll()}appendStream($){if(this.streamBuf+=$,!this.renderTimer)this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.streamLines=Q2(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=Q2(this.streamBuf).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let J=Z,Y;switch($){case"read_file":if(Y=String(J.path||""),J.offset)Y+=`:${J.offset}`;break;case"write_file":case"edit_file":Y=String(J.path||"");break;case"search_files":if(Y=`/${J.pattern||""}/`,J.include)Y+=` (${J.include})`;break;case"find_files":Y=String(J.pattern||"");break;case"list_directory":Y=String(J.path||".");break;case"run_command":if(Y=String(J.command||""),Y.length>80)Y=Y.slice(0,77)+"...";break;default:{let Q=JSON.stringify(J);Y=Q.length>80?Q.slice(0,77)+"...":Q}}this.lines.push({text:` ${g.tool}\u2699 ${$}${U.reset} ${U.dim}${Y}${U.reset}`}),this.renderMessages()}showToolResult($,Z){let J=Z.split(`
360
+ `),Y=8,Q=J.slice(0,8);for(let X of Q){let z=X.length>this.width-6?X.slice(0,this.width-9)+"...":X;this.lines.push({text:` ${U.dim}${z}${U.reset}`})}if(J.length>8)this.lines.push({text:` ${U.dim}... (${J.length-8} more lines)${U.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${g.prompt}? ${$}${U.reset} ${U.dim}[y]es / [n]o / [a]ll${U.reset}`}),this.renderAll(),new Promise((Z)=>{let J=(Y)=>{let Q=Y.toString().toLowerCase();if(Q==="y"||Q==="\r"||Q===`
361
+ `)process.stdin.removeListener("data",J),this.lines.push({text:` ${g.sys}approved${U.reset}`}),this.renderAll(),Z(!0);else if(Q==="n"||Q==="\x1B")process.stdin.removeListener("data",J),this.lines.push({text:` ${g.err}rejected${U.reset}`}),this.renderAll(),Z(!1);else if(Q==="a")process.stdin.removeListener("data",J),this.lines.push({text:` ${g.sys}approved all for this session${U.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",J),setTimeout(()=>{process.stdin.removeListener("data",J),this.lines.push({text:` ${U.dim}timeout \u2014 auto-rejected${U.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;promptSessionPicker($){if($.length===0)return this.showSystem("No sessions found."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let J=$.findIndex((H)=>H.isCurrent);if(J<0)J=0;let Y="",Q=!1,X=()=>{if(!Y)return $;let H=Y.toLowerCase();return $.filter((K)=>K.name.toLowerCase().includes(H))},z=()=>{let M=this.height-2-2,B=X();if(J>=B.length)J=Math.max(0,B.length-1);let O=2,j=2,A=M-O-j,T=Math.max(1,A),w=0;if(B.length>T)w=Math.max(0,J-Math.floor(T/2)),w=Math.min(w,B.length-T);let N$=B.slice(w,w+T);if(R(U.hide),R(U.to(3,1)),R(U.clearLine),Q)R(` ${g.heading}${U.bold}Sessions${U.reset} ${U.dim}filter: ${Y}\u2588${U.reset}`);else R(` ${g.heading}${U.bold}Sessions${U.reset} ${U.dim}(${B.length})${U.reset}`);R(U.to(4,1)),R(U.clearLine);for(let _=0;_<T;_++){let E=2+O+_+1;if(R(U.to(E,1)),R(U.clearLine),_>=N$.length)continue;let W=N$[_],C=w+_===J,F=W.isCurrent?"*":" ",I=W.isArchived?`${U.dim}[arch] ${U.reset}`:" ",S=`${W.messageCount} msgs`.padEnd(10),o=bz(W.updated);if(C)R(` ${g.prompt}${U.bold}\u203A ${F} ${I}${g.prompt}${U.bold}${W.name.padEnd(20)}${U.reset} ${U.dim}${S} ${o}${U.reset}`);else{let C$=W.isArchived?U.dim:g.sys;R(` ${F} ${I}${C$}${W.name.padEnd(20)}${U.reset} ${U.dim}${S} ${o}${U.reset}`)}}for(let _=N$.length;_<T;_++){let E=2+O+_+1;R(U.to(E,1)),R(U.clearLine)}let b=2+O+T+1;if(R(U.to(b,1)),R(U.clearLine),B.length>T){let _=Math.round((J+1)/B.length*100);R(` ${U.dim}${w>0?"\u2191":" "} ${_}% ${w+T<B.length?"\u2193":" "}${U.reset}`)}let f=this.height-2;R(U.to(f,1)),R(U.clearLine),R(` ${U.dim}W/S or \u2191\u2193 navigate Enter select Esc cancel / filter d delete a archive${U.reset}`)},G=(H)=>{this.pickerActive=!1,process.stdin.removeListener("data",V),this.renderAll(),Z(H)},V=(H)=>{let K=H.toString("utf-8"),M=X();if(K==="\x1B"&&H.length===1){if(Q)Q=!1,Y="",z();else G(null);return}if(K==="\x03"){G(null);return}if(K==="\r"||K===`
362
+ `){if(M.length>0&&J<M.length)G({action:"load",name:M[J].name});return}if(K==="\x1B[A"||K==="w"&&!Q){if(J>0)J--,z();return}if(K==="\x1B[B"||K==="s"&&!Q){if(J<M.length-1)J++,z();return}if(K==="d"&&Q===!1){if(M.length>0&&J<M.length){let B=M[J];if(!B.isCurrent)G({action:"delete",name:B.name,isArchived:B.isArchived})}return}if(K==="a"&&Q===!1){if(M.length>0&&J<M.length){let B=M[J];if(!B.isCurrent){let O=B.isArchived?"unarchive":"archive";G({action:O,name:B.name})}}return}if(K==="/"&&Q===!1){Q=!0,Y="",z();return}if(Q){if(K==="\x7F"||K==="\b"){if(Y.length>0)Y=Y.slice(0,-1),J=0,z();else Q=!1,z();return}if(K.length===1&&K>=" "){Y+=K,J=0,z();return}}};process.stdin.on("data",V),z()})}promptNewsPicker($){if($.length===0)return this.showSystem("Nenhuma noticia encontrada."),Promise.resolve(null);return new Promise((Z)=>{this.pickerActive=!0;let J=0,Y="",Q=!1,X="",z=[...new Set($.map((B)=>B.category))].sort(),G=()=>{let B=X?$.filter((O)=>O.category===X):$;if(Y){let O=Y.toLowerCase();B=B.filter((j)=>j.title.toLowerCase().includes(O)||j.source.toLowerCase().includes(O))}return B},V=(B)=>{return{business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo",security:"Ciberseguranca"}[B]||B},H=()=>{let j=this.height-2-2,A=G();if(J>=A.length)J=Math.max(0,A.length-1);let T=2,w=2,N$=j-T-w,b=Math.max(1,N$),f=0;if(A.length>b)f=Math.max(0,J-Math.floor(b/2)),f=Math.min(f,A.length-b);let _=A.slice(f,f+b);if(R(U.hide),R(U.to(3,1)),R(U.clearLine),Q)R(` ${g.heading}${U.bold}Noticias${U.reset} ${U.dim}filtro: ${Y}\u2588${U.reset}`);else{let q=X?V(X):"Todas";R(` ${g.heading}${U.bold}Noticias${U.reset} ${U.dim}(${A.length}) ${q}${U.reset}`)}R(U.to(4,1)),R(U.clearLine);for(let q=0;q<b;q++){let C=2+T+q+1;if(R(U.to(C,1)),R(U.clearLine),q>=_.length)continue;let F=_[q],I=f+q===J,S=F.time?`[${F.time}]`:" ",o=this.width-30,C$=F.title.length>o?F.title.slice(0,o-1)+"\u2026":F.title;if(I)R(` ${g.prompt}${U.bold}\u203A ${S} ${C$}${U.reset} ${U.dim}(${F.source})${U.reset}`);else R(` ${U.dim}${S}${U.reset} ${g.sys}${C$}${U.reset} ${U.dim}(${F.source})${U.reset}`)}for(let q=_.length;q<b;q++){let C=2+T+q+1;R(U.to(C,1)),R(U.clearLine)}let E=2+T+b+1;if(R(U.to(E,1)),R(U.clearLine),A.length>b){let q=Math.round((J+1)/A.length*100);R(` ${U.dim}${f>0?"\u2191":" "} ${q}% ${f+b<A.length?"\u2193":" "}${U.reset}`)}let W=this.height-2;R(U.to(W,1)),R(U.clearLine),R(` ${U.dim}W/S or \u2191\u2193 navigate Enter open Esc cancel / filter Tab category${U.reset}`)},K=(B)=>{this.pickerActive=!1,process.stdin.removeListener("data",M),this.renderAll(),Z(B)},M=(B)=>{let O=B.toString("utf-8"),j=G();if(O==="\x1B"&&B.length===1){if(Q)Q=!1,Y="",H();else K(null);return}if(O==="\x03"){K(null);return}if(O==="\r"||O===`
363
+ `){if(j.length>0&&J<j.length)K(j[J].link);return}if(O==="\x1B[A"||O==="w"&&!Q){if(J>0)J--,H();return}if(O==="\x1B[B"||O==="s"&&!Q){if(J<j.length-1)J++,H();return}if(O==="\t"){if(!X)X=z[0]||"";else{let A=z.indexOf(X);X=A<z.length-1?z[A+1]:""}J=0,H();return}if(O==="/"&&!Q){Q=!0,Y="",H();return}if(Q){if(O==="\x7F"||O==="\b"){if(Y.length>0)Y=Y.slice(0,-1),J=0,H();else Q=!1,H();return}if(O.length===1&&O>=" "){Y+=O,J=0,H();return}}};process.stdin.on("data",M),H()})}showUsage($){this.lines.push({text:` ${U.dim}tokens: ${$}${U.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${g.err}\u2717 ${$}${U.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
364
+ `))this.lines.push({text:` ${g.sys}${Z}${U.reset}`});this.lines.push({text:""}),this.renderAll()}clearMessages(){this.lines=[],this.renderAll()}updateModel($){this.model=$,this.renderHeader()}updateSession($){this.sessionName=$,this.renderHeader()}enableInput(){this.inputBuf="",this.inputPos=0,this.isStreaming=!1,this.history?.reset(),this.renderInput()}disableInput(){R(U.hide)}render(){R(U.hide),R(U.clear),this.renderHeader(),this.renderMessages(),this.renderInput(),R(U.show)}renderAll(){this.renderMessages(),this.renderInput()}renderHeader(){R(U.to(1,1)),R(U.inv);let $=" smolerclaw",Z=[this.model,this.sessionName];if(this.sessionCost)Z.push(this.sessionCost);if(this.authInfo)Z.push(this.authInfo);let J=Z.join(" | ")+" ",Y=Math.max(1,this.width-$.length-J.length);R($+" ".repeat(Y)+J),R(U.reset),R(U.to(2,1)),R(`${U.dim}${"\u2500".repeat(this.width)}${U.reset}`)}renderMessages(){let J=this.height-2-2,Y=[...this.lines,...this.streamLines],Q=Y.length,X=Math.max(0,Q-J-this.scrollOffset),z=Math.min(Q,X+J),G=Y.slice(X,z);R(U.hide);for(let V=0;V<J;V++)if(R(U.to(2+V+1,1)),R(U.clearLine),V<G.length){let H=J2(G[V].text);if(H.length>this.width)R(G[V].text.slice(0,this.width+(G[V].text.length-H.length))),R(U.reset);else R(G[V].text)}}completeInput($){let Z=$.split(" "),J=Z[0];if(Z.length===1){let z=this.commands.filter((G)=>G.startsWith(J));if(z.length===1){let G=this.subcommands[z[0]];if(G&&G.length>0)return{value:z[0]+" ",options:`Opcoes: ${G.join(" ")}`};return{value:z[0]+" "}}if(z.length>1){let G=z[0];for(let V of z)while(!V.startsWith(G))G=G.slice(0,-1);return{value:G.length>$.length?G:$,options:z.join(" ")}}return null}let Y=this.subcommands[J];if(!Y||Y.length===0)return null;let Q=Z[Z.length-1].toLowerCase(),X=Y.filter((z)=>z.toLowerCase().startsWith(Q));if(X.length===1)return Z[Z.length-1]=X[0],{value:Z.join(" ")+" "};if(X.length>1){let z=X[0];for(let G of X)while(!G.toLowerCase().startsWith(z.toLowerCase()))z=z.slice(0,-1);if(z.length>Q.length)return Z[Z.length-1]=z,{value:Z.join(" "),options:X.join(" ")};return{value:$,options:X.join(" ")}}if(!Q&&Y.length>0)return{value:$,options:Y.join(" ")};return null}renderInput(){let $=this.height-1,Z=this.height;if(R(U.to($,1)),R(U.clearLine),R(`${U.dim}${"\u2500".repeat(this.width)}${U.reset}`),R(U.to(Z,1)),R(U.clearLine),this.isStreaming){let J=((Date.now()-this.streamStartTime)/1000).toFixed(1);R(` ${g.ai}${this.getSpinnerChar()}${U.reset} ${U.dim}streaming... ${J}s${U.reset}`),R(U.hide)}else{let J=Y2(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;R(`${g.prompt}\u276F${U.reset} ${J}`);let Y=this.inputBuf.slice(0,this.inputPos),Q=Y2(Y)+3;R(U.to(Z,Math.min(Q,this.width))),R(U.show)}}onKey($){if(this.pickerActive)return;let Z=$.toString("utf-8");if(Z==="\x03"){if(this.isStreaming){this.onCancel?.();return}let J=Date.now(),Y=1500;if(this.inputBuf.length>0){this.inputBuf="",this.inputPos=0,this.lastCtrlCTime=J,this.renderInput();return}if(J-this.lastCtrlCTime<Y){this.onExit?.();return}this.lastCtrlCTime=J,this.showSystem("Pressione Ctrl+C novamente para sair.");return}if(Z==="\x04"){this.onExit?.();return}if(Z==="\f"){this.render();return}if(this.isStreaming)return;if(Z==="\t"){if(this.inputBuf.startsWith("/")){let J=this.completeInput(this.inputBuf);if(J){if(this.inputBuf=J.value,this.inputPos=this.inputBuf.length,this.renderInput(),J.options)this.showSystem(J.options)}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!r6(Z)){let J=Z.replace(/\r?\n/g," ").trim();if(J.length>0)this.inputBuf=this.inputBuf.slice(0,this.inputPos)+J+this.inputBuf.slice(this.inputPos),this.inputPos+=J.length,this.renderInput();return}if(Z==="\r"||Z===`
353
365
  `){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
354
- `,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(VX(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:`${c.user}${B.bold} You${B.reset} ${B.dim}${Z}${B.reset}`});else this.lines.push({text:`${c.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=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 VX($){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}function GX($){let Z=Date.now()-$,Y=Math.floor(Z/1000);if(Y<60)return"just now";let J=Math.floor(Y/60);if(J<60)return`${J}m ago`;let Q=Math.floor(J/60);if(Q<24)return`${Q}h ago`;let X=Math.floor(Q/24);if(X<30)return`${X}d ago`;return`${Math.floor(X/30)}mo ago`}var r4={"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(r4[$])return r4[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return r4["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return r4["claude-opus-4-20250514"];if(Z.includes("sonnet"))return r4["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(`
366
+ `,this.inputPos=this.inputBuf.length,this.renderInput();return}let J=this.inputBuf.trim();if(J)this.history?.add(J),this.inputBuf="",this.inputPos=0,this.scrollOffset=0,this.onSubmit?.(J);return}if(Z==="\x7F"||Z==="\b"){if(this.inputPos>0){let J=i6(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos-J)+this.inputBuf.slice(this.inputPos),this.inputPos-=J,this.renderInput()}return}if(Z.startsWith("\x1B[")){switch(Z.slice(2)){case"D":if(this.inputPos>0)this.inputPos-=i6(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=a6(this.inputBuf,this.inputPos),this.renderInput();break;case"A":{let Y=this.history?.prev(this.inputBuf);if(Y!==null&&Y!==void 0)this.inputBuf=Y,this.inputPos=this.inputBuf.length,this.renderInput();break}case"B":{let Y=this.history?.next();if(Y!==void 0)this.inputBuf=Y,this.inputPos=this.inputBuf.length,this.renderInput();break}case"5~":if(this.scrollOffset<this.lines.length)this.scrollOffset=Math.min(this.scrollOffset+5,this.lines.length),this.renderMessages();break;case"6~":if(this.scrollOffset>0)this.scrollOffset=Math.max(0,this.scrollOffset-5),this.renderMessages();break;case"H":this.inputPos=0,this.renderInput();break;case"F":this.inputPos=this.inputBuf.length,this.renderInput();break;case"3~":{if(this.inputPos<this.inputBuf.length){let Y=a6(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+Y),this.renderInput()}break}}return}if(kz(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:`${g.user}${U.bold} You${U.reset} ${U.dim}${Z}${U.reset}`});else this.lines.push({text:`${g.ai}${U.bold} Claude${U.reset} ${U.dim}${Z}${U.reset}`})}startSpinner(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];this.spinnerFrame=0,this.spinnerTimer=setInterval(()=>{this.spinnerFrame=(this.spinnerFrame+1)%$.length,this.renderInput()},80)}stopSpinner(){if(this.spinnerTimer)clearInterval(this.spinnerTimer),this.spinnerTimer=null}getSpinnerChar(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];return $[this.spinnerFrame%$.length]}addWrapped($){let Z=n6(" "+$,this.width-2);for(let J of Z)this.lines.push({text:J})}addMarkdown($){let Z=Q2($);for(let J of Z)this.lines.push({text:J})}}function r6($){return[...$].length===1}function kz($){if(!r6($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function i6($,Z){if(Z<=0)return 0;if(Z>=2){let J=$.charCodeAt(Z-1),Y=$.charCodeAt(Z-2);if(J>=56320&&J<=57343&&Y>=55296&&Y<=56319)return 2}return 1}function a6($,Z){if(Z>=$.length)return 0;let J=$.charCodeAt(Z);if(J>=55296&&J<=56319&&Z+1<$.length)return 2;return 1}function bz($){let Z=Date.now()-$,J=Math.floor(Z/1000);if(J<60)return"just now";let Y=Math.floor(J/60);if(Y<60)return`${Y}m ago`;let Q=Math.floor(Y/60);if(Q<24)return`${Q}h ago`;let X=Math.floor(Q/24);if(X<30)return`${X}d ago`;return`${Math.floor(X/30)}mo ago`}var z0={"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}},yz={input:3,output:15};function s6($,Z){let J=_z(Z),Y=$.inputTokens/1e6*J.input*100,Q=$.outputTokens/1e6*J.output*100;return{inputCostCents:Y,outputCostCents:Q,totalCostCents:Y+Q}}function _z($){if(z0[$])return z0[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return z0["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return z0["claude-opus-4-20250514"];if(Z.includes("sonnet"))return z0["claude-sonnet-4-20250514"];return yz}class $5{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=s6($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=s6($,this.model);return`${X2($.inputTokens)} in / ${X2($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${X2(this.totalInput)} in / ${X2(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function X2($){return $.toLocaleString("en-US")}function t6($,Z={}){let{includeToolCalls:J=!0,includeTimestamps:Y=!0}=Z,Q=[];Q.push(`# smolerclaw session: ${$.name}`),Q.push(`Created: ${new Date($.created).toLocaleString()}`),Q.push(""),Q.push("---"),Q.push("");for(let X of $.messages){let z=Y?` (${new Date(X.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(X.role==="user")Q.push(`## You${z}`),Q.push(""),Q.push(X.content),Q.push("");else{if(Q.push(`## Claude${z}`),Q.push(""),Q.push(X.content),J&&X.toolCalls?.length){Q.push("");for(let G of X.toolCalls){let V=hz(G.name,G.input);Q.push(`> **Tool:** \`${G.name}\`${V}`);let H=G.result.split(`
355
367
  `).slice(0,5).join(`
356
- `);if(H.trim()){Q.push("> ```");for(let z of H.split(`
357
- `))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(`
358
- `)}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(`
359
- `)}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(`
360
- `)}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(`
361
- `);V=N.pop()||"";for(let E of N){if(!E.startsWith("data: "))continue;let L=E.slice(6).trim();if(L==="[DONE]")continue;try{let S=JSON.parse(L).choices?.[0]?.delta;if(S?.content)yield{type:"text",text:S.content},H+=S.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 M1(...$){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 M1("git","diff","--cached"),Z=await M1("git","diff"),Y=await M1("git","ls-files","--others","--exclude-standard"),J=[];if($.stdout)J.push(`=== STAGED ===
362
- `+$.stdout);if(Z.stdout)J.push(`=== UNSTAGED ===
363
- `+Z.stdout);if(Y.stdout)J.push(`=== UNTRACKED ===
364
- `+Y.stdout);return J.join(`
365
-
366
- `)||"(no changes)"}async function B6(){let $=await M1("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function N6(){return(await M1("git","add","-A")).ok}async function C6($){let Z=await M1("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function M6(){let $=await M1("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.
368
+ `);if(H.trim()){Q.push("> ```");for(let K of H.split(`
369
+ `))Q.push(`> ${K}`);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(`
370
+ `)}function hz($,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 z2=[{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 Z5($){let Z=z2.find((X)=>X.id===$);if(Z)return Z.id;let J=$.toLowerCase(),Y=z2.find((X)=>X.alias===J);if(Y)return Y.id;let Q=z2.find((X)=>X.id.includes(J)||X.name.toLowerCase().includes(J));if(Q)return Q.id;return $}function e6($){let Z=["Available models:"];for(let J of z2){let Y=J.id===$?" *":" ",Q=J.tier==="fast"?"\u26A1":J.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${Y} ${J.alias.padEnd(12)} ${Q} ${J.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
371
+ `)}function J5($){if($.includes(":")){let[J,...Y]=$.split(":");return{provider:J.toLowerCase(),model:Y.join(":")}}let Z=$.toLowerCase();if(Z.startsWith("gpt-")||Z.startsWith("o1")||Z.startsWith("o3"))return{provider:"openai",model:$};if(Z.startsWith("llama")||Z.startsWith("mistral")||Z.startsWith("codellama")||Z.startsWith("deepseek"))return{provider:"ollama",model:$};return{provider:"anthropic",model:$}}var vz={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 $3(){let $=["Providers:"];for(let[Z,J]of Object.entries(vz)){let Y=J.envKey?` (${J.envKey})`:" (local)";$.push(` ${Z.padEnd(12)} ${J.description}${Y}`)}return $.push(""),$.push("Use: /model provider:model (e.g., /model openai:gpt-4o)"),$.join(`
372
+ `)}class Y5{name;apiKey;baseUrl;model;maxTokens;approvalMode="auto";approvalCallback=null;autoApproveAll=!1;constructor($,Z,J){if(this.name=$,this.model=Z,this.maxTokens=J,$==="ollama")this.apiKey="ollama",this.baseUrl=process.env.OLLAMA_BASE_URL||"http://localhost:11434/v1";else this.apiKey=process.env.OPENAI_API_KEY||"",this.baseUrl=process.env.OPENAI_BASE_URL||"https://api.openai.com/v1"}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,J=!0){if(!this.apiKey&&this.name!=="ollama"){yield{type:"error",error:"No API key found. Set OPENAI_API_KEY env var."};return}let Y=[{role:"system",content:Z},...$.map((Q)=>({role:Q.role,content:Q.content}))];try{let Q=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:Y,max_tokens:this.maxTokens,stream:!0})});if(!Q.ok){let K=await Q.text();yield{type:"error",error:`${this.name} API error ${Q.status}: ${K.slice(0,200)}`};return}if(!Q.body){yield{type:"error",error:"No response body"};return}let X=Q.body.getReader(),z=new TextDecoder,G="",V=Z.length+$.reduce((K,M)=>K+M.content.length,0),H=0;while(!0){let{done:K,value:M}=await X.read();if(K)break;G+=z.decode(M,{stream:!0});let B=G.split(`
373
+ `);G=B.pop()||"";for(let O of B){if(!O.startsWith("data: "))continue;let j=O.slice(6).trim();if(j==="[DONE]")continue;try{let T=JSON.parse(j).choices?.[0]?.delta;if(T?.content)yield{type:"text",text:T.content},H+=T.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(V/3.5),outputTokens:Math.ceil(H/3.5)},yield{type:"done"}}catch(Q){yield{type:"error",error:Q instanceof Error?Q.message:String(Q)}}}}async function A4(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[J,Y]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),Q=await Z.exited;return{stdout:J.trim(),stderr:Y.trim(),ok:Q===0}}async function Z3(){let $=await A4("git","diff","--cached"),Z=await A4("git","diff"),J=await A4("git","ls-files","--others","--exclude-standard"),Y=[];if($.stdout)Y.push(`=== STAGED ===
374
+ `+$.stdout);if(Z.stdout)Y.push(`=== UNSTAGED ===
375
+ `+Z.stdout);if(J.stdout)Y.push(`=== UNTRACKED ===
376
+ `+J.stdout);return Y.join(`
377
+
378
+ `)||"(no changes)"}async function J3(){let $=await A4("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function Y3(){return(await A4("git","add","-A")).ok}async function Q3($){let Z=await A4("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function X3(){let $=await A4("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var z3={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.
367
379
 
368
380
  Behavior:
369
381
  - Write clean, production-grade code. No shortcuts.
@@ -394,78 +406,79 @@ Behavior:
394
406
  - Be specific. Show the line, explain the problem, suggest the fix.
395
407
  - Check for: error handling, input validation, edge cases, naming, complexity.
396
408
  - Don't nitpick formatting unless it affects readability.
397
- - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function E6($){return O6[$.toLowerCase()]||null}function j6($){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(`
398
- `)}async function F6($){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"]),jX=20971520;function L6($){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>jX){J.push(`[image too large: ${X}]`);continue}let z=NX(V).toString("base64"),M=FX(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 FX($){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 y1();if($.push(Z),A)try{let Y=await i$();$.push(`
409
+ - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function K3($){return z3[$.toLowerCase()]||null}function G3($){let Z=["Personas:"];for(let[J,Y]of Object.entries(z3)){let Q=J===$?" *":" ";Z.push(`${Q} ${J.padEnd(12)} ${Y.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
410
+ `)}s();async function V3($){try{let Z=x?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:N5?["pbcopy"]:["xclip","-selection","clipboard"],J=Bun.spawn(Z,{stdin:"pipe",stdout:"pipe",stderr:"pipe"});return J.stdin.write($),J.stdin.end(),await J.exited===0}catch{return!1}}import{existsSync as fz,readFileSync as gz,statSync as mz}from"fs";import{extname as cz,resolve as dz}from"path";var uz=new Set([".png",".jpg",".jpeg",".gif",".webp"]),pz=20971520;function W3($){let Z=[],J=$.split(/\s+/),Y=[];for(let Q of J){let X=Q.replace(/^["']|["']$/g,""),z=cz(X).toLowerCase();if(uz.has(z)){let G=dz(X);if(fz(G))try{if(mz(G).size>pz){Y.push(`[image too large: ${X}]`);continue}let K=gz(G).toString("base64"),M=lz(z);Z.push({path:G,mediaType:M,base64:K}),Y.push(`[image: ${X}]`)}catch{Y.push(Q)}else Y.push(Q)}else Y.push(Q)}return{text:Y.join(" "),images:Z}}function lz($){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"}}j4();j4();s();async function H3(){let $=[];$.push("=== BRIEFING DIARIO ===");let Z=await O4();if($.push(Z),x)try{let J=await v$();$.push(`
399
411
  --- Agenda ---
400
- ${Y}`)}catch{$.push(`
412
+ ${J}`)}catch{$.push(`
401
413
  --- Agenda ---
402
- Outlook nao disponivel.`)}if(A)try{let Y=await k1();$.push(`
414
+ Outlook nao disponivel.`)}if(x)try{let J=await M4();$.push(`
403
415
  --- Sistema ---
404
- ${Y}`)}catch{}try{let Y=await o$(["finance","business","tech"],3);$.push(`
405
- ${Y}`)}catch{$.push(`
416
+ ${J}`)}catch{}try{let J=await m4(["finance","business","tech"],3);$.push(`
417
+ ${J}`)}catch{$.push(`
406
418
  --- Noticias ---
407
419
  Falha ao carregar noticias.`)}return $.push(`
408
420
  ======================`),$.join(`
409
- `)}import{existsSync as LX,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(!LX(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(`==============================
410
- `);let Z=await y1();$.push(Z);let J=a$().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(`
411
- --- Tarefas do dia ---`),$.push(q1(J));let Q=n4();if(Q.length>0)$.push(`
412
- --- Follow-ups pendentes ---`),$.push(B0(Q));let K=v1().filter((H)=>H.status==="atrasado");if(K.length>0)$.push(`
413
- --- Delegacoes atrasadas ---`),$.push(U0(K));let V=DZ();if(V)$.push(`
414
- ${V}`);if(A)try{let H=await i$();$.push(`
415
- --- Agenda ---`),$.push(H)}catch{}try{let H=await o$(["finance","business","tech"],2);$.push(`
416
- `+H)}catch{}let G=a$();if(G.length>0&&J.length!==G.length)$.push(`
417
- ${G.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
421
+ `)}j4();import{existsSync as oz,readFileSync as nz,writeFileSync as iz}from"fs";import{join as az}from"path";s();var q3="",U3=()=>az(q3,"last-morning.txt");function B3($){q3=$;let Z=U3(),J=new Date().toISOString().split("T")[0];if(!oz(Z))return!0;try{return nz(Z,"utf-8").trim()!==J}catch{return!0}}function N3(){let $=new Date().toISOString().split("T")[0];iz(U3(),$)}async function C3(){let $=[],Z=new Date().getHours(),J=Z<12?"BOM DIA":Z<18?"BOA TARDE":"BOA NOITE";$.push("=============================="),$.push(` ${J}! Briefing do dia`),$.push(`==============================
422
+ `);let Y=await O4();$.push(Y);let X=t$().filter((M)=>{if(!M.dueAt)return!1;let B=new Date(M.dueAt),O=new Date;return B.toDateString()===O.toDateString()});if(X.length>0)$.push(`
423
+ --- Tarefas do dia ---`),$.push(E4(X));let z=Z0();if(z.length>0)$.push(`
424
+ --- Follow-ups pendentes ---`),$.push(L1(z));let V=u4().filter((M)=>M.status==="atrasado");if(V.length>0)$.push(`
425
+ --- Delegacoes atrasadas ---`),$.push(F1(V));let H=iZ();if(H)$.push(`
426
+ ${H}`);if(x)try{let M=await v$();$.push(`
427
+ --- Agenda ---`),$.push(M)}catch{}try{let M=await m4(["finance","business","tech"],2);$.push(`
428
+ `+M)}catch{}let K=t$();if(K.length>0&&X.length!==K.length)$.push(`
429
+ ${K.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
418
430
  ==============================`),$.join(`
419
- `)}var _=null,a0=null,f7=null,v7=0;function S6($){f7=$}function b6($="foco",Z=25,Y=5){if(_)return`Pomodoro ja ativo: "${_.label}" (${_6()}). Use /pomodoro stop para parar.`;return _={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(!_)return"Nenhum pomodoro ativo.";let $=_.label,Z=Math.floor((Date.now()-_.startedAt)/60000);return r0(),_=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function g7(){if(!_)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=_6();return`${_.type==="work"?"Trabalhando":"Pausa"}: "${_.label}" \u2014 ${$} restante(s) (ciclo #${v7})`}function y6(){if(!_)return;r0();let $=_.startedAt+_.durationMs-Date.now();if($<=0){w6();return}a0=setTimeout(w6,$)}function w6(){if(!_)return;if(_.type==="work"){let $=`Pomodoro: "${_.label}" concluido! Hora da pausa (${_.breakMs/60000}min).`;I6("Pausa!",`"${_.label}" concluido. Descanse ${_.breakMs/60000} minutos.`),f7?.($),_={..._,type:"break",startedAt:Date.now(),durationMs:_.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(),_=null}function r0(){if(a0)clearTimeout(a0),a0=null}function _6(){if(!_)return"0min";let $=Math.max(0,_.startedAt+_.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(),_=null}t();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="",Z$=[],g6=()=>PX(v6,"workflows.json");function s4(){P(g6(),JSON.stringify(Z$,null,2))}function IX(){let $=g6();if(!f6($)){Z$=m7(),s4();return}try{let Z=JSON.parse(TX($,"utf-8"));if(!Array.isArray(Z)){Z$=m7(),s4();return}Z$=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{Z$=m7(),s4()}}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 t4($){let Z=$.toLowerCase().trim();return Z$.find((Y)=>Y.id===$)||Z$.find((Y)=>Y.name.toLowerCase()===Z)||Z$.find((Y)=>Y.name.toLowerCase().includes(Z))||null}function c6($){let Z=[...Z$];if($){let Y=$.toLowerCase();Z=Z.filter((J)=>J.tags.some((Q)=>Q.toLowerCase()===Y))}return Z}function d7($,Z){let Y=t4($);if(!Y)return null;return Z$=Z$.map((J)=>J.id===Y.id?{...J,...Z,updatedAt:new Date().toISOString()}:J),s4(),Z$.find((J)=>J.id===Y.id)||null}function d6($){let Z=t4($);if(!Z)return!1;return Z$=Z$.filter((Y)=>Y.id!==Z.id),s4(),!0}async function u7($,Z){let Y=t4($);if(!Y){let Q=Z$.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 L=await SX(z,Y);Q.push(` ${N} ${L}`),X++}catch(L){let w=L instanceof Error?L.message:String(L);switch(V++,E){case"stop":return Q.push(` ${N} ERRO (parando): ${w}`),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): ${w}`),K++;break;case"continue":default:Q.push(` ${N} ERRO (continuando): ${w}`);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 S1($.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 b1(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=$||Z$;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}
420
- ${" ".repeat(4)}${K} {${J.id}}`});return`Workflows (${Z.length}):
421
- ${Y.join(`
431
+ `)}s();var v=null,K2=null,Q5=null,X5=0;function j3($){Q5=$}function E3($="foco",Z=25,J=5){if(v)return`Pomodoro ja ativo: "${v.label}" (${R3()}). Use /pomodoro stop para parar.`;return v={startedAt:Date.now(),durationMs:Z*60000,breakMs:J*60000,label:$,type:"work"},X5++,L3(),`Pomodoro #${X5} iniciado: "${$}" (${Z}min trabalho / ${J}min pausa)`}function F3(){if(!v)return"Nenhum pomodoro ativo.";let $=v.label,Z=Math.floor((Date.now()-v.startedAt)/60000);return G2(),v=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function z5(){if(!v)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=R3();return`${v.type==="work"?"Trabalhando":"Pausa"}: "${v.label}" \u2014 ${$} restante(s) (ciclo #${X5})`}function L3(){if(!v)return;G2();let $=v.startedAt+v.durationMs-Date.now();if($<=0){M3();return}K2=setTimeout(M3,$)}function M3(){if(!v)return;if(v.type==="work"){let $=`Pomodoro: "${v.label}" concluido! Hora da pausa (${v.breakMs/60000}min).`;O3("Pausa!",`"${v.label}" concluido. Descanse ${v.breakMs/60000} minutos.`),Q5?.($),v={...v,type:"break",startedAt:Date.now(),durationMs:v.breakMs},L3()}else O3("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),Q5?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),G2(),v=null}function G2(){if(K2)clearTimeout(K2),K2=null}function R3(){if(!v)return"0min";let $=Math.max(0,v.startedAt+v.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function O3($,Z){if(!x)return;let J=$.replace(/'/g,"''"),Y=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">${J}</text><text id="2">${Y}</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"}),z=setTimeout(()=>X.kill(),1e4);await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),await X.exited,clearTimeout(z)}catch{}}function A3(){G2(),v=null}e();j4();s();import{existsSync as D3,mkdirSync as rz,readFileSync as sz}from"fs";import{join as tz}from"path";import{randomUUID as ez}from"crypto";var x3="",Q$=[],T3=()=>tz(x3,"workflows.json");function K0(){k(T3(),JSON.stringify(Q$,null,2))}function $K(){let $=T3();if(!D3($)){Q$=K5(),K0();return}try{let Z=JSON.parse(sz($,"utf-8"));if(!Array.isArray(Z)){Q$=K5(),K0();return}Q$=Z.map((J)=>({id:J.id||G5(),name:J.name||"unnamed",description:J.description||"",steps:Array.isArray(J.steps)?J.steps:[],tags:Array.isArray(J.tags)?J.tags:[],enabled:J.enabled!==!1,createdAt:J.createdAt||new Date().toISOString(),updatedAt:J.updatedAt||new Date().toISOString()}))}catch{Q$=K5(),K0()}}function K5(){let $=new Date().toISOString();return[{id:G5(),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:G5(),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 P3($){if(x3=$,!D3($))rz($,{recursive:!0});$K()}function G0($){let Z=$.toLowerCase().trim();return Q$.find((J)=>J.id===$)||Q$.find((J)=>J.name.toLowerCase()===Z)||Q$.find((J)=>J.name.toLowerCase().includes(Z))||null}function I3($){let Z=[...Q$];if($){let J=$.toLowerCase();Z=Z.filter((Y)=>Y.tags.some((Q)=>Q.toLowerCase()===J))}return Z}function V5($,Z){let J=G0($);if(!J)return null;return Q$=Q$.map((Y)=>Y.id===J.id?{...Y,...Z,updatedAt:new Date().toISOString()}:Y),K0(),Q$.find((Y)=>Y.id===J.id)||null}function w3($){let Z=G0($);if(!Z)return!1;return Q$=Q$.filter((J)=>J.id!==Z.id),K0(),!0}async function W5($,Z){let J=G0($);if(!J){let Q=Q$.map((X)=>X.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${Q}`}if(!J.enabled)return`Workflow "${J.name}" esta desativado.`;let Y=await S3(J.name,J.steps,Z);return JK(Y)}async function S3($,Z,J){let Y=performance.now(),Q=[`Executando workflow: "${$}"`],X=0,z=0,G=0,V=!0;for(let H=0;H<Z.length;H++){let K=Z[H],M=K.label||`${K.action}:${K.target}`,B=`[${H+1}/${Z.length}]`,O=K.on_error||"continue";J?.(`${B} ${M}...`);try{let j=await ZK(K,J);Q.push(` ${B} ${j}`),X++}catch(j){let A=j instanceof Error?j.message:String(j);switch(G++,O){case"stop":return Q.push(` ${B} ERRO (parando): ${A}`),V=!1,{workflow:$,success:V,stepsRun:X,stepsSkipped:z,stepsFailed:G,log:Q,duration:Math.round(performance.now()-Y)};case"skip":Q.push(` ${B} ERRO (pulado): ${A}`),z++;break;case"continue":default:Q.push(` ${B} ERRO (continuando): ${A}`);break}}}return{workflow:$,success:V,stepsRun:X,stepsSkipped:z,stepsFailed:G,log:Q,duration:Math.round(performance.now()-Y)}}async function ZK($,Z){switch($.action){case"open_app":{if(!x)return`skip: ${$.target} (not Windows)`;return await N4($.target)}case"open_url":{if(!x)return`skip: ${$.target} (not Windows)`;let J=$.target.trim();if(!J.startsWith("http://")&&!J.startsWith("https://"))throw Error(`URL invalida (deve comecar com http/https): ${J}`);return await C4(J)}case"run_command":{if(!x)return"skip: command (not Windows)";let J=$.target;if(!J.trim())throw Error("Comando vazio");let Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",J],{stdout:"pipe",stderr:"pipe"}),Q=new Promise((G,V)=>{setTimeout(()=>{Y.kill(),V(Error("Command timeout (30s)"))},30000)}),X=(async()=>{let[G,V]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]),H=await Y.exited;if(H!==0&&V.trim())throw Error(`exit ${H}: ${V.trim().slice(0,200)}`);return G.trim().slice(0,200)})(),z=await Promise.race([X,Q]);return`Command: ${J.slice(0,60)}${z?" -> "+z:""}`}case"wait":{let J=Math.max(0,Math.min(parseInt($.target)||1,60));return await new Promise((Y)=>setTimeout(Y,J*1000)),`Wait: ${J}s`}case"notify":{if(x)try{let J=$.target.replace(/'/g,"''"),Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",`[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms') | Out-Null; [System.Windows.Forms.MessageBox]::Show('${J}', 'smolerclaw', 'OK', 'Information') | Out-Null`],{stdout:"pipe",stderr:"pipe"});setTimeout(()=>Y.kill(),1e4)}catch{}return`Notify: ${$.target}`}case"if_app_running":{if(!x)return"skip: condition (not Windows)";let J=$.target.toLowerCase(),Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",`(Get-Process -Name '${J}' -ErrorAction SilentlyContinue) -ne $null`],{stdout:"pipe",stderr:"pipe"}),Q=new Promise((G,V)=>{setTimeout(()=>{Y.kill(),V(Error("condition timeout"))},5000)}),X=(async()=>{let[G]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]);return await Y.exited,G.trim().toLowerCase()==="true"})(),z=await Promise.race([X,Q]);if(z&&$.condition_steps&&$.condition_steps.length>0){let G=await S3(`${$.target}-conditional`,$.condition_steps,Z);return`Condition: ${J} running=true, ran ${G.stepsRun} sub-steps`}return`Condition: ${J} running=${z}${!z?" (skipped sub-steps)":""}`}case"log":return`Log: ${$.target}`;default:throw Error(`Acao desconhecida: ${$.action}`)}}function k3($){let Z=$||Q$;if(Z.length===0)return"Nenhum workflow configurado.";let J=Z.map((Y)=>{let Q=Y.enabled?"":" [DESATIVADO]",X=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"",z=Y.steps.map((G)=>{let V=G.label||G.target;return G.action==="wait"?`${G.target}s`:V}).join(" -> ");return` ${Y.name}${Q}${X} \u2014 ${Y.description}
432
+ ${" ".repeat(4)}${z} {${Y.id}}`});return`Workflows (${Z.length}):
433
+ ${J.join(`
422
434
 
423
- `)}`}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(`
424
- `)}function bX($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
425
- `)}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}):
435
+ `)}`}function b3($){let Z=$.enabled?"ativo":"desativado",J=$.tags.length>0?`Tags: ${$.tags.map((Q)=>`#${Q}`).join(" ")}`:"",Y=[`--- Workflow {${$.id}} ---`,`Nome: ${$.name}`,`Descricao: ${$.description}`,`Status: ${Z}`];if(J)Y.push(J);return Y.push(`Criado: ${new Date($.createdAt).toLocaleDateString("pt-BR")}`),Y.push(""),Y.push("Steps:"),$.steps.forEach((Q,X)=>{let z=Q.label?` (${Q.label})`:"",G=Q.on_error&&Q.on_error!=="continue"?` [on_error: ${Q.on_error}]`:"";if(Y.push(` ${X+1}. ${Q.action}: ${Q.target}${z}${G}`),Q.action==="if_app_running"&&Q.condition_steps)for(let V of Q.condition_steps)Y.push(` \u21B3 ${V.action}: ${V.target}`)}),Y.join(`
436
+ `)}function JK($){let Z=[...$.log];return Z.push(""),Z.push(`Concluido em ${$.duration}ms \u2014 ${$.stepsRun} executados, ${$.stepsSkipped} pulados, ${$.stepsFailed} falhas`),Z.join(`
437
+ `)}function G5(){return ez().slice(0,8)}s();var A$=new Map,H5=null;function _3($){H5=$}function h3($,Z=60){if(!x)return"Error: monitor is only available on Windows.";let J=$.toLowerCase();if(A$.has(J))return`"${$}" ja esta sendo monitorado.`;let Y=setInterval(()=>y3(J),Z*1000);return A$.set(J,{name:$,interval:Y,lastSeen:!0}),y3(J),`Monitorando "${$}" a cada ${Z}s.`}function v3($){let Z=$.toLowerCase(),J=A$.get(Z);if(!J)return`"${$}" nao esta sendo monitorado.`;return clearInterval(J.interval),A$.delete(Z),`Monitor parado: "${$}"`}function f3(){if(A$.size===0)return"Nenhum processo monitorado.";let $=[...A$.values()].map((Z)=>{let J=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${J}]`});return`Processos monitorados (${A$.size}):
426
438
  ${$.join(`
427
- `)}`}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{}}l4();t();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(L){console.error("smolerclaw:",L instanceof Error?L.message:L),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 L=new R7(Y.token,Z.model,Z.maxTokens,Z.toolApproval);L.setAuthRefresh(()=>{let w=K2();if(w&&w.token!==Y.token)return Y=w,L.updateApiKey(w.token),!0;return!1}),X=L}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),n.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}
439
+ `)}`}function g3(){for(let $ of A$.values())clearInterval($.interval);A$.clear()}async function y3($){let Z=A$.get($);if(!Z)return;let J=await YK(Z.name);if(Z.lastSeen&&!J){let Y=`ALERTA: "${Z.name}" parou de rodar!`;QK("Processo parou!",`"${Z.name}" nao esta mais rodando.`),H5?.(Y)}else if(!Z.lastSeen&&J){let Y=`"${Z.name}" voltou a rodar.`;H5?.(Y)}A$.set($,{...Z,lastSeen:J})}async function YK($){if(!x)return!1;try{let Z=`(Get-Process -Name '${$}' -ErrorAction SilentlyContinue) -ne $null`,J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>J.kill(),1e4),[Q]=await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]);return await J.exited,clearTimeout(Y),Q.trim().toLowerCase()==="true"}catch{return!1}}async function QK($,Z){if(!x)return;let J=$.replace(/'/g,"''"),Y=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">${J}</text><text id="2">${Y}</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"}),z=setTimeout(()=>X.kill(),1e4);await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),await X.exited,clearTimeout(z)}catch{}}$0();e();import{writeFileSync as XK}from"fs";import{join as zK}from"path";async function KK(){let $=U5(process.argv.slice(2));if($.help)B5(),process.exit(0);if($.version)console.log(`smolerclaw v${H0()}`),process.exit(0);let Z=I5();if($.model)Z.model=Z5($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let J;try{J=C2()}catch(j){console.error("smolerclaw:",j instanceof Error?j.message:j),process.exit(1)}let{provider:Y,model:Q}=J5(Z.model),X;if(Y==="openai"||Y==="ollama")X=new Y5(Y,Q,Z.maxTokens);else{let j=new l7(J.token,Z.model,Z.maxTokens,Z.toolApproval);j.setAuthRefresh(()=>{let A=M2();if(A&&A.token!==J.token)return J=A,j.updateApiKey(A.token),!0;return!1}),X=j}let z=new n7(Z.dataDir),G=$.session||z.getLastSession()||"default";if(G!=="default")z.switchTo(G);let V=l6(Z.skillsDir),H=r7(Z.systemPrompt,V,Z.language),K=!$.noTools;D6();let M=k9(zK(Z.dataDir,"..")),B=P9(M);if(B.length>0)L6(B),l.push(...I9(B));let O=!process.stdin.isTTY;if($.print||O)await GK(X,z,H,K,$.prompt,O),process.exit(0);await WK(X,z,Z,J,V,H,K,B,$.prompt)}async function GK($,Z,J,Y,Q,X){let z=Q||"";if(X){let K=await VK();z=z?`${z}
428
440
 
429
- ${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(`
430
- smolerclaw error: ${z.error}`);if(G&&!G.endsWith(`
441
+ ${K}`:K}if(!z.trim())console.error("smolerclaw: no input provided"),process.exit(1);let G={role:"user",content:z.trim(),timestamp:Date.now()};Z.addMessage(G);let V="";for await(let K of $.chat(Z.messages,J,Y))if(K.type==="text")process.stdout.write(K.text),V+=K.text;else if(K.type==="error")console.error(`
442
+ smolerclaw error: ${K.error}`);if(V&&!V.endsWith(`
431
443
  `))process.stdout.write(`
432
- `);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}
433
-
434
- ${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((h)=>z.showSystem(`
435
- *** ${h} ***
436
- `)),m6(Y.dataDir),o2(Y.dataDir),NZ(Y.dataDir),RZ(Y.dataDir),i6((h)=>z.showSystem(`
437
- *** ${h} ***
438
- `)),F9(Y.dataDir,(h)=>{z.showSystem(`
439
- *** LEMBRETE: ${h.title} ***
440
- `)}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(h,o,f)=>{if(h==="edit_file"&&o.old_text&&o.new_text){let q=oZ(String(o.old_text),String(o.new_text));for(let C of q)z.showSystem(C)}let O=iZ(h,o),W=await z.promptApproval(O);if(z._approveAllRequested)$.setAutoApproveAll?.(!0),z._approveAllRequested=!1;return W});for(let h of Z.messages)if(h.role==="user")z.addUserMessage(h.content);else z.addAssistantMessage(h.content);let L=null;async function w(h){if(h.startsWith("/")){await S(h);return}if(Y.maxSessionCost>0){let y=H.totals.costCents;if(y>=Y.maxSessionCost){z.showError(`Budget exceeded (~$${(y/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(y>=Y.maxSessionCost*0.8)z.showSystem(`Budget: ${Math.round(y/Y.maxSessionCost*100)}% used`)}let{text:o,images:f}=L6(h),O={role:"user",content:o,images:f.length>0?f.map((y)=>({mediaType:y.mediaType,base64:y.base64})):void 0,timestamp:Date.now()};Z.addMessage(O),z.addUserMessage(f.length>0?`${o} (${f.length} image${f.length>1?"s":""})`:o),z.disableInput(),z.startStream();let W="",q=[],C={},j=0,T=0;L=new AbortController;try{for await(let y of $.chat(Z.messages,E,K)){if(L.signal.aborted)break;switch(y.type){case"text":z.appendStream(y.text),W+=y.text;break;case"tool_call":z.flushStream(),z.showToolCall(y.name,y.input),C=y.input;break;case"tool_result":z.showToolResult(y.name,y.result),q.push({id:y.id,name:y.name,input:C,result:y.result}),C={},z.resetStreamBuffer();break;case"tool_blocked":z.showError(y.reason);break;case"usage":j+=y.inputTokens,T+=y.outputTokens;break;case"error":z.showError(y.error);break;case"done":break}}}catch(y){if(!L.signal.aborted)z.showError(y instanceof Error?y.message:String(y))}L=null,z.endStream();let b={inputTokens:j,outputTokens:T},a=H.add(b);if(j>0||T>0)z.showUsage(H.formatUsage(b)),z.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let A$={role:"assistant",content:W,toolCalls:q.length>0?q:void 0,usage:j>0?{inputTokens:j,outputTokens:T,costCents:a.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(A$),Z.trimHistory(Y.maxHistory),z.enableInput()}async function S(h){let o=h.slice(1).split(" "),f=o[0].toLowerCase(),O=o.slice(1);switch(f){case"exit":case"quit":case"sair":case"q":k();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().map((j)=>{let T=Z.getInfo(j);return{name:j,messageCount:T?.messageCount??0,updated:T?.updated??0,isCurrent:j===Z.session.name,isArchived:!1}}),q=Z.listArchived().map((j)=>{let T=Z.getArchivedInfo(j);return{name:j,messageCount:T?.messageCount??0,updated:T?.updated??0,isCurrent:!1,isArchived:!0}}),C=await z.promptSessionPicker([...W,...q]);if(C)switch(C.action){case"load":{let j=C.name;if(q.some((b)=>b.name===j))Z.unarchive(j);Z.switchTo(j),z.clearMessages();for(let b of Z.messages)if(b.role==="user")z.addUserMessage(b.content);else z.addAssistantMessage(b.content);z.updateSession(j),z.showSystem(`Loaded: ${j}`);break}case"delete":{let j=C.name;if(C.isArchived?Z.deleteArchived(j):Z.delete(j))z.showSystem(`Deleted: ${j}`);else z.showError(`Not found: ${j}`);break}case"archive":if(Z.archive(C.name))z.showSystem(`Archived: ${C.name}`);else z.showError(`Failed to archive: ${C.name}`);break;case"unarchive":if(Z.unarchive(C.name))z.showSystem(`Restored: ${C.name}`);else z.showError(`Not found in archive: ${C.name}`);break}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((C)=>{let j=Z.getArchivedInfo(C),T=j?cX(j.updated):"",b=j?`${j.messageCount} msgs`:"";return` ${C.padEnd(20)} ${b.padEnd(10)} ${T}`});z.showSystem(`Sessoes arquivadas (${W.length}):
444
+ `);let H={role:"assistant",content:V,timestamp:Date.now()};Z.addMessage(H)}async function VK(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}async function WK($,Z,J,Y,Q,X,z,G,V){let H=new $5(J.model),K=new e7(J.model,Z.session.name,S5(Y),J.dataDir),M="default",B=SZ(),O=B?`${X}
445
+
446
+ ${B}`:X;if(D5(J.dataDir,N2().replace(/[/\\]config\.json$/,"")),EZ(J.dataDir),t9(J.dataDir),TZ(J.dataDir),f9(J.dataDir),A6(Z),XZ(J.dataDir),VZ(J.dataDir),j3((b)=>K.showSystem(`
447
+ *** ${b} ***
448
+ `)),P3(J.dataDir),K7(J.dataDir),vZ(J.dataDir),lZ(J.dataDir),Z6(J.dataDir),_3((b)=>K.showSystem(`
449
+ *** ${b} ***
450
+ `)),u9(J.dataDir,(b)=>{K.showSystem(`
451
+ *** LEMBRETE: ${b.title} ***
452
+ `)}),J.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(b,f,_)=>{if(b==="edit_file"&&f.old_text&&f.new_text){let q=h6(String(f.old_text),String(f.new_text));for(let C of q)K.showSystem(C)}let E=_6(b,f),W=await K.promptApproval(E);if(K._approveAllRequested)$.setAutoApproveAll?.(!0),K._approveAllRequested=!1;return W});for(let b of Z.messages)if(b.role==="user")K.addUserMessage(b.content);else K.addAssistantMessage(b.content);let j=null;async function A(b){if(b.startsWith("/")){await T(b);return}if(J.maxSessionCost>0){let h=H.totals.costCents;if(h>=J.maxSessionCost){K.showError(`Budget exceeded (~$${(h/100).toFixed(4)} / $${(J.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(h>=J.maxSessionCost*0.8)K.showSystem(`Budget: ${Math.round(h/J.maxSessionCost*100)}% used`)}let{text:f,images:_}=W3(b),E={role:"user",content:f,images:_.length>0?_.map((h)=>({mediaType:h.mediaType,base64:h.base64})):void 0,timestamp:Date.now()};Z.addMessage(E),K.addUserMessage(_.length>0?`${f} (${_.length} image${_.length>1?"s":""})`:f),K.disableInput(),K.startStream();let W="",q=[],C={},F=0,I=0;j=new AbortController;try{for await(let h of $.chat(Z.messages,O,z)){if(j.signal.aborted)break;switch(h.type){case"text":K.appendStream(h.text),W+=h.text;break;case"tool_call":K.flushStream(),K.showToolCall(h.name,h.input),C=h.input;break;case"tool_result":K.showToolResult(h.name,h.result),q.push({id:h.id,name:h.name,input:C,result:h.result}),C={},K.resetStreamBuffer();break;case"tool_blocked":K.showError(h.reason);break;case"usage":F+=h.inputTokens,I+=h.outputTokens;break;case"error":K.showError(h.error);break;case"done":break}}}catch(h){if(!j.signal.aborted)K.showError(h instanceof Error?h.message:String(h))}j=null,K.endStream();let S={inputTokens:F,outputTokens:I},o=H.add(S);if(F>0||I>0)K.showUsage(H.formatUsage(S)),K.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let C$={role:"assistant",content:W,toolCalls:q.length>0?q:void 0,usage:F>0?{inputTokens:F,outputTokens:I,costCents:o.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(C$),Z.trimHistory(J.maxHistory),K.enableInput()}async function T(b){let f=b.slice(1).split(" "),_=f[0].toLowerCase(),E=f.slice(1);switch(_){case"exit":case"quit":case"sair":case"q":w();break;case"clear":case"limpar":Z.clear(),K.clearMessages(),K.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let W=E[0]||`s-${Date.now()}`;Z.switchTo(W),K.clearMessages(),K.updateSession(W),K.showSystem(`New session: ${W}`);break}case"load":case"carregar":{let W=E[0];if(!W){K.showError("Usage: /load <name>");break}Z.switchTo(W),K.clearMessages();for(let q of Z.messages)if(q.role==="user")K.addUserMessage(q.content);else K.addAssistantMessage(q.content);K.updateSession(W),K.showSystem(`Loaded: ${W}`);break}case"sessions":case"sessoes":case"ls":{let W=Z.list().map((F)=>{let I=Z.getInfo(F);return{name:F,messageCount:I?.messageCount??0,updated:I?.updated??0,isCurrent:F===Z.session.name,isArchived:!1}}),q=Z.listArchived().map((F)=>{let I=Z.getArchivedInfo(F);return{name:F,messageCount:I?.messageCount??0,updated:I?.updated??0,isCurrent:!1,isArchived:!0}}),C=await K.promptSessionPicker([...W,...q]);if(C)switch(C.action){case"load":{let F=C.name;if(q.some((S)=>S.name===F))Z.unarchive(F);Z.switchTo(F),K.clearMessages();for(let S of Z.messages)if(S.role==="user")K.addUserMessage(S.content);else K.addAssistantMessage(S.content);K.updateSession(F),K.showSystem(`Loaded: ${F}`);break}case"delete":{let F=C.name;if(C.isArchived?Z.deleteArchived(F):Z.delete(F))K.showSystem(`Deleted: ${F}`);else K.showError(`Not found: ${F}`);break}case"archive":if(Z.archive(C.name))K.showSystem(`Archived: ${C.name}`);else K.showError(`Failed to archive: ${C.name}`);break;case"unarchive":if(Z.unarchive(C.name))K.showSystem(`Restored: ${C.name}`);else K.showError(`Not found in archive: ${C.name}`);break}break}case"delete":case"deletar":case"rm":{let W=E[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=E[0];if(!W){K.showError("Uso: /archive <nome> ou /archive all");break}if(W==="all"||W==="todas"){let q=Z.archiveAll();if(q.length>0)K.showSystem(`Arquivadas ${q.length} sessoes: ${q.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=E[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 q=W.map((C)=>{let F=Z.getArchivedInfo(C),I=F?HK(F.updated):"",S=F?`${F.messageCount} msgs`:"";return` ${C.padEnd(20)} ${S.padEnd(10)} ${I}`});K.showSystem(`Sessoes arquivadas (${W.length}):
441
453
  ${q.join(`
442
- `)}`);break}case"model":case"modelo":{let W=O[0];if(!W){z.showSystem(H6(Y.model)+`
454
+ `)}`);break}case"model":case"modelo":{let W=E[0];if(!W){K.showSystem(e6(J.model)+`
443
455
 
444
- `+q6());break}let{provider:q,model:C}=_7(W),j=q==="anthropic"?y7(C):C;if(Y.model=q==="anthropic"?j:`${q}:${j}`,q8(Y),q==="anthropic")$.setModel(j);else z.showSystem(`Note: ${q} provider selected. Restart smolerclaw for full provider switch.`);H.setModel(j),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})
445
- 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 C=K2();if(C){if(J=C,"updateApiKey"in $)$.updateApiKey(C.token);z.showSystem(`Sessao renovada. Expira: ${new Date(C.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 C=W6(Z.session);_X(q,C),z.showSystem(`Exported to: ${q}`)}catch(C){z.showError(`Export failed: ${C instanceof Error?C.message:C}`)}break}case"cost":case"custo":z.showSystem(`Session: ${H.formatSession()}`);break;case"retry":case"repetir":{let W=[...Z.messages].reverse().find((T)=>T.role==="user");if(!W){z.showError("No previous message to retry.");break}let q=Z.messages,C=0;if(q.length>0&&q[q.length-1].role==="assistant")C++;if(q.length>C&&q[q.length-1-C].role==="user")C++;if(C>0)Z.popMessages(C);z.showSystem("Retrying...");let j=W.images?.length?W.content:W.content;await w(j);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(`
446
- `));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:
447
- `+W),z.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.
456
+ `+$3());break}let{provider:q,model:C}=J5(W),F=q==="anthropic"?Z5(C):C;if(J.model=q==="anthropic"?F:`${q}:${F}`,L0(J),q==="anthropic")$.setModel(F);else K.showSystem(`Note: ${q} provider selected. Restart smolerclaw for full provider switch.`);H.setModel(F),K.updateModel(J.model),K.showSystem(`Model -> ${J.model}`);break}case"skills":case"habilidades":{K.showSystem(o6(Q));break}case"auth":K.showSystem(`Auth: subscription (${Y.subscriptionType})
457
+ Expires: ${new Date(Y.expiresAt).toLocaleString()}`);break;case"refresh":case"renovar":{K.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 C=M2();if(C){if(Y=C,"updateApiKey"in $)$.updateApiKey(C.token);K.showSystem(`Sessao renovada. Expira: ${new Date(C.expiresAt).toLocaleString()}`)}else K.showSystem("claude executado, mas credenciais nao atualizaram. Tente novamente.")}catch(W){K.showError(`Falha ao renovar: ${W instanceof Error?W.message:String(W)}`)}break}case"config":K.showSystem(`Config: ${N2()}`);break;case"export":case"exportar":{let W=new Date().toISOString().split("T")[0],q=E[0]||`smolerclaw-${Z.session.name}-${W}.md`;try{let C=t6(Z.session);XK(q,C),K.showSystem(`Exported to: ${q}`)}catch(C){K.showError(`Export failed: ${C instanceof Error?C.message:C}`)}break}case"cost":case"custo":K.showSystem(`Session: ${H.formatSession()}`);break;case"retry":case"repetir":{let W=[...Z.messages].reverse().find((I)=>I.role==="user");if(!W){K.showError("No previous message to retry.");break}let q=Z.messages,C=0;if(q.length>0&&q[q.length-1].role==="assistant")C++;if(q.length>C&&q[q.length-1-C].role==="user")C++;if(C>0)Z.popMessages(C);K.showSystem("Retrying...");let F=W.images?.length?W.content:W.content;await A(F);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(`
458
+ `));break;case"commit":case"commitar":{if(!await X3()){K.showError("Not a git repository.");break}let W=await J3();if(W==="(clean)"){K.showSystem("Nothing to commit \u2014 working tree clean.");break}K.showSystem(`Changes:
459
+ `+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.
448
460
 
449
461
  Diff:
450
- ${(await U6()).slice(0,8000)}`;z.startStream();let j="";for await(let b of $.chat([{role:"user",content:C,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(b.type==="text")j+=b.text,z.appendStream(b.text);else if(b.type==="error")z.showError(b.error);if(z.endStream(),j=j.trim().replace(/^["']|["']$/g,""),!j){z.showError("Failed to generate commit message. Aborting.");break}await N6();let T=await C6(j);if(T.ok)z.showSystem(`Committed: ${j}`);else z.showError(`Commit failed: ${T.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(j6(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((C)=>C.role==="assistant");if(!W){z.showError("No assistant message to copy.");break}if(await F6(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 C of $.chat([{role:"user",content:W,timestamp:Date.now()}],E,!1))if(C.type==="text")q+=C.text,z.appendStream(C.text);else if(C.type==="error")z.showError(C.error);else if(C.type==="usage")z.showUsage(`${C.inputTokens} in / ${C.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 C=Y.maxSessionCost,j=H.totals.costCents;if(C===0)z.showSystem(`Budget: unlimited (spent ~$${(j/100).toFixed(4)})`);else{let T=Math.round(j/C*100);z.showSystem(`Budget: ~$${(j/100).toFixed(4)} / $${(C/100).toFixed(4)} (${T}%)`)}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(!l1.peek()){z.showError("Nothing to undo.");break}let q=l1.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 C of Z.messages)if(C.content.toLowerCase().includes(W)){let j=C.content.slice(0,100).replace(/\n/g," "),T=new Date(C.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});q.push(` [${C.role} ${T}] ${j}${C.content.length>100?"...":""}`)}z.showSystem(q.length>0?`Found ${q.length} match${q.length>1?"es":""}:
462
+ ${(await Z3()).slice(0,8000)}`;K.startStream();let F="";for await(let S of $.chat([{role:"user",content:C,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(S.type==="text")F+=S.text,K.appendStream(S.text);else if(S.type==="error")K.showError(S.error);if(K.endStream(),F=F.trim().replace(/^["']|["']$/g,""),!F){K.showError("Failed to generate commit message. Aborting.");break}await Y3();let I=await Q3(F);if(I.ok)K.showSystem(`Committed: ${F}`);else K.showError(`Commit failed: ${I.output}`)}catch(q){K.showError(`Commit error: ${q instanceof Error?q.message:String(q)}`)}K.enableInput();break}case"persona":case"modo":{let W=E[0];if(!W){K.showSystem(G3(M));break}let q=K3(W);if(!q){K.showError(`Unknown persona: ${W}. Try /persona to see options.`);break}if(M=q.name,q.systemPrompt)O=r7(q.systemPrompt,Q,J.language);else O=X;K.showSystem(`Persona -> ${q.name}: ${q.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 V3(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=E.join(" ");if(!W){K.showError("Usage: /ask <question>");break}K.addUserMessage(`(ephemeral) ${W}`),K.disableInput(),K.startStream();let q="";for await(let C of $.chat([{role:"user",content:W,timestamp:Date.now()}],O,!1))if(C.type==="text")q+=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=E[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(S9(G));break}case"budget":case"orcamento":{let W=E[0];if(!W){let C=J.maxSessionCost,F=H.totals.costCents;if(C===0)K.showSystem(`Budget: unlimited (spent ~$${(F/100).toFixed(4)})`);else{let I=Math.round(F/C*100);K.showSystem(`Budget: ~$${(F/100).toFixed(4)} / $${(C/100).toFixed(4)} (${I}%)`)}break}let q=Number(W);if(isNaN(q)||q<0){K.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}J.maxSessionCost=q,L0(J),K.showSystem(q===0?"Budget: unlimited":`Budget set: $${(q/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!s4.peek()){K.showError("Nothing to undo.");break}let q=s4.undo();if(q)K.showSystem(q);break}case"search":case"buscar":{let W=E.join(" ").toLowerCase();if(!W){K.showError("Usage: /search <text>");break}let q=[];for(let C of Z.messages)if(C.content.toLowerCase().includes(W)){let F=C.content.slice(0,100).replace(/\n/g," "),I=new Date(C.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});q.push(` [${C.role} ${I}] ${F}${C.content.length>100?"...":""}`)}K.showSystem(q.length>0?`Found ${q.length} match${q.length>1?"es":""}:
451
463
  ${q.join(`
452
- `)}`:`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 o$(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>
453
- Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let W=O[0],q=O[1],C=O[2],j=p8(W,q,C);if(typeof j==="string")z.showError(j);else z.showSystem(`Fonte adicionada: ${j.name} (${j.category}) \u2014 ${j.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(", ")}
454
- Uso: /open <app> ou /open <app> <arquivo>`);break}let q=O.length>1?O.slice(1).join(" "):void 0,C=await S1(O[0],q);z.showSystem(C);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 b1(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 k1();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 y1(),q=await i$();z.showSystem(`${W}
464
+ `)}`:`No matches for "${W}".`);break}case"lang":case"language":case"idioma":{let W=E[0];if(!W){K.showSystem(`Language: ${J.language} (auto = match user's language)`);break}J.language=W,L0(J),K.showSystem(`Language -> ${W}`);break}case"briefing":case"resumo":{K.showSystem("Carregando briefing..."),K.disableInput();try{let W=await H3();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=E[0];if(W)K.showSystem(`Buscando noticias (${W})...`);else K.showSystem("Buscando noticias...");K.disableInput();try{let{items:q,errors:C}=await J7(W?[W]:void 0);if(q.length===0){K.showSystem(C.length>0?`Nenhuma noticia encontrada.
465
+ Falhas: ${C.join(", ")}`:"Nenhuma noticia encontrada."),K.enableInput();break}let F=q.map((S)=>({title:S.title,link:S.link,source:S.source,category:S.category,time:S.pubDate?S.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):""})),I=await K.promptNewsPicker(F);if(I){let{openUrl:S}=await Promise.resolve().then(() => (j4(),b9));S(I),K.showSystem(`Abrindo: ${I}`)}}catch(q){K.showError(`Falha ao buscar noticias: ${q instanceof Error?q.message:String(q)}`)}K.enableInput();break}case"feeds":case"fontes":{K.showSystem(J1());break}case"addfeed":case"novafonte":{if(E.length<3){K.showError(`Uso: /addfeed <nome> <url> <categoria>
466
+ Ex: /addfeed "Ars Technica" https://feeds.arstechnica.com/arstechnica/index tech`);break}let W=E[0],q=E[1],C=E[2],F=t0(W,q,C);if(typeof F==="string")K.showError(F);else K.showSystem(`Fonte adicionada: ${F.name} (${F.category}) \u2014 ${F.url}`);break}case"rmfeed":case"rmfonte":{let W=E.join(" ");if(!W){K.showError("Uso: /rmfeed <nome ou url>");break}if(e0(W))K.showSystem(`Fonte removida: ${W}`);else K.showError(`Fonte custom nao encontrada: "${W}". Para desativar uma built-in, use /disablefeed.`);break}case"disablefeed":case"desativarfonte":{let W=E.join(" ");if(!W){K.showError("Uso: /disablefeed <nome ou url>");break}if($1(W))K.showSystem(`Fonte desativada: ${W}`);else K.showError(`Fonte built-in nao encontrada ou ja desativada: "${W}"`);break}case"enablefeed":case"ativarfonte":{let W=E.join(" ");if(!W){K.showError("Uso: /enablefeed <nome ou url>");break}if(Z1(W))K.showSystem(`Fonte reativada: ${W}`);else K.showError(`Fonte built-in nao encontrada ou nao esta desativada: "${W}"`);break}case"open":case"abrir":{if(!E.join(" ")){K.showSystem(`Apps disponiveis: ${e2().join(", ")}
467
+ Uso: /open <app> ou /open <app> <arquivo>`);break}let q=E.length>1?E.slice(1).join(" "):void 0,C=await N4(E[0],q);K.showSystem(C);break}case"openfile":case"abrirarquivo":{let W=E.join(" ");if(!W){K.showError("Uso: /openfile <caminho>");break}let q=await n8(W);K.showSystem(q);break}case"openurl":{let W=E[0];if(!W){K.showError("Uso: /openurl <url>");break}let q=await C4(W);K.showSystem(q);break}case"apps":case"programas":{K.disableInput();try{let W=await i8();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 M4();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 O4(),q=await v$();K.showSystem(`${W}
455
468
 
456
469
  --- Agenda ---
457
- ${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 C=await u7(q,(j)=>z.showSystem(j));z.showSystem(C)}catch(C){z.showError(`Workflow: ${C instanceof Error?C.message:String(C)}`)}z.enableInput()}else if(W==="info"||W==="detalhe"){let q=O[1];if(!q){z.showError("Uso: /workflow info <nome>");break}let C=t4(q);if(C)z.showSystem(l6(C));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 C=d7(q,{enabled:!0});if(C)z.showSystem(`Workflow ativado: ${C.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 C=d7(q,{enabled:!1});if(C)z.showSystem(`Workflow desativado: ${C.name}`);else z.showError(`Workflow nao encontrado: ${q}`)}else{z.disableInput();try{let q=await u7(W,(C)=>z.showSystem(C));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(" "),C=25,j=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=u4("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=u4("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()+`
470
+ ${q}`)}catch(W){K.showError(`Calendar: ${W instanceof Error?W.message:String(W)}`)}K.enableInput();break}case"monitor":case"vigiar":{let W=E[0]?.toLowerCase();if(!W||W==="list"||W==="listar")K.showSystem(f3());else if(W==="stop"||W==="parar"){let q=E[1];if(!q){K.showError("Uso: /monitor stop <processo>");break}K.showSystem(v3(q))}else{let q=parseInt(E[1])||60;K.showSystem(h3(W,q))}break}case"workflow":case"fluxo":{let W=E[0]?.toLowerCase();if(!W||W==="list"||W==="listar"){let q=E[1];K.showSystem(k3(I3(q)))}else if(W==="run"||W==="rodar"){let q=E[1];if(!q){K.showError("Uso: /workflow run <nome>");break}K.disableInput();try{let C=await W5(q,(F)=>K.showSystem(F));K.showSystem(C)}catch(C){K.showError(`Workflow: ${C instanceof Error?C.message:String(C)}`)}K.enableInput()}else if(W==="info"||W==="detalhe"){let q=E[1];if(!q){K.showError("Uso: /workflow info <nome>");break}let C=G0(q);if(C)K.showSystem(b3(C));else K.showError(`Workflow nao encontrado: ${q}`)}else if(W==="delete"||W==="deletar"){let q=E[1];if(!q){K.showError("Uso: /workflow delete <nome>");break}if(w3(q))K.showSystem(`Workflow removido: ${q}`);else K.showError(`Workflow nao encontrado: ${q}`)}else if(W==="enable"||W==="ativar"){let q=E[1];if(!q){K.showError("Uso: /workflow enable <nome>");break}let C=V5(q,{enabled:!0});if(C)K.showSystem(`Workflow ativado: ${C.name}`);else K.showError(`Workflow nao encontrado: ${q}`)}else if(W==="disable"||W==="desativar"){let q=E[1];if(!q){K.showError("Uso: /workflow disable <nome>");break}let C=V5(q,{enabled:!1});if(C)K.showSystem(`Workflow desativado: ${C.name}`);else K.showError(`Workflow nao encontrado: ${q}`)}else{K.disableInput();try{let q=await W5(W,(C)=>K.showSystem(C));K.showSystem(q)}catch(q){K.showError(`Workflow: ${q instanceof Error?q.message:String(q)}`)}K.enableInput()}break}case"pomodoro":case"foco":{let W=E[0]?.toLowerCase();if(W==="stop"||W==="parar")K.showSystem(F3());else if(W==="status")K.showSystem(z5());else if(!W)K.showSystem(z5());else{let q=E.join(" "),C=25,F=5;K.showSystem(E3(q,25,5))}break}case"entrada":case"income":{let W=parseFloat(E[0]);if(isNaN(W)||E.length<3){K.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let q=t8("entrada",W,E[1],E.slice(2).join(" "));K.showSystem(`+ R$ ${q.amount.toFixed(2)} (${q.category}) \u2014 ${q.description}`);break}case"saida":case"expense":{let W=parseFloat(E[0]);if(isNaN(W)||E.length<3){K.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let q=t8("saida",W,E[1],E.slice(2).join(" "));K.showSystem(`- R$ ${q.amount.toFixed(2)} (${q.category}) \u2014 ${q.description}`);break}case"finance":case"financas":case"balanco":{let W=E[0];if(W==="recent"||W==="recentes")K.showSystem(z7());else K.showSystem(W1()+`
458
471
 
459
- `+i2(5));break}case"decisions":case"decisoes":{let W=O.join(" ");if(W){let q=J0(W);z.showSystem(f1(q))}else z.showSystem(f1(Q0()));break}case"investigar":case"investigate":case"investigacoes":{let W=O.join(" ");if(W){let{searchInvestigations:q,formatInvestigationList:C}=await Promise.resolve().then(() => (l4(),X7));z.showSystem(C(q(W)))}else{let{listInvestigations:q,formatInvestigationList:C}=await Promise.resolve().then(() => (l4(),X7));z.showSystem(C(q()))}break}case"email":case"rascunho":{if(!O.join(" ")){z.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
460
- Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let q=O[0],C=O.slice(1).join(" "),j=C.indexOf("|");if(j===-1){z.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
461
- Use | para separar assunto do corpo.`);break}let T=C.slice(0,j).trim(),b=C.slice(j+1).trim();if(!T||!b){z.showError("Assunto e corpo sao obrigatorios.");break}let a={to:q,subject:T,body:b};z.showSystem(Z0(a)),z.disableInput();try{let A$=await $0(a);z.showSystem(A$)}catch(A$){z.showError(`Email: ${A$ instanceof Error?A$.message:String(A$)}`)}z.enableInput();break}case"memo":case"anotar":case"note":{let W=O.join(" ");if(!W){let j=d4();z.showSystem(U1(j));break}let q=t8(W),C=q.tags.length>0?` [${q.tags.map((j)=>"#"+j).join(" ")}]`:"";z.showSystem(`Memo salvo${C} {${q.id}}`);break}case"memos":case"notas":{let W=O.join(" ");if(W){let q=e8(W);z.showSystem(U1(q))}else{let q=d4();z.showSystem(U1(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=g1(10);z.showSystem(e$(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>
462
- Ou peca a IA: "salva esse material sobre..."`);break}let C=W.slice(0,q).trim(),j=W.slice(q+1).trim();if(!C||!j){z.showError("Titulo e conteudo sao obrigatorios.");break}let T=C0(C,j),b=T.tags.length>0?` [${T.tags.map((a)=>"#"+a).join(" ")}]`:"";z.showSystem(`Material salvo: "${T.title}" (${T.category})${b} {${T.id}}`);break}case"materials":case"materiais":{let W=O.join(" ");if(W){let q=O0(W);z.showSystem(e$(q))}else{let q=g1();z.showSystem(e$(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=L0(),C=q.builtAt?new Date(q.builtAt).toLocaleString("pt-BR"):"nunca";z.showSystem(`Memory RAG Index:
472
+ `+z7(5));break}case"decisions":case"decisoes":{let W=E.join(" ");if(W){let q=H1(W);K.showSystem(d4(q))}else K.showSystem(d4(q1()));break}case"investigar":case"investigate":case"investigacoes":{let W=E.join(" ");if(W){let{searchInvestigations:q,formatInvestigationList:C}=await Promise.resolve().then(() => ($0(),O7));K.showSystem(C(q(W)))}else{let{listInvestigations:q,formatInvestigationList:C}=await Promise.resolve().then(() => ($0(),O7));K.showSystem(C(q()))}break}case"email":case"rascunho":{if(!E.join(" ")){K.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
473
+ Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let q=E[0],C=E.slice(1).join(" "),F=C.indexOf("|");if(F===-1){K.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
474
+ Use | para separar assunto do corpo.`);break}let I=C.slice(0,F).trim(),S=C.slice(F+1).trim();if(!I||!S){K.showError("Assunto e corpo sao obrigatorios.");break}let o={to:q,subject:I,body:S};K.showSystem(V1(o)),K.disableInput();try{let C$=await G1(o);K.showSystem(C$)}catch(C$){K.showError(`Email: ${C$ instanceof Error?C$.message:String(C$)}`)}K.enableInput();break}case"memo":case"anotar":case"note":{let W=E.join(" ");if(!W){let F=s8();K.showSystem(F4(F));break}let q=z1(W),C=q.tags.length>0?` [${q.tags.map((F)=>"#"+F).join(" ")}]`:"";K.showSystem(`Memo salvo${C} {${q.id}}`);break}case"memos":case"notas":{let W=E.join(" ");if(W){let q=K1(W);K.showSystem(F4(q))}else{let q=s8();K.showSystem(F4(q))}break}case"memotags":case"tags":{K.showSystem($Z());break}case"rmmemo":case"rmnota":{let W=E[0];if(!W){K.showError("Uso: /rmmemo <id>");break}if(e9(W))K.showSystem("Memo removido.");else K.showError(`Memo nao encontrado: ${W}`);break}case"material":case"mat":{let W=E.join(" ");if(!W){let o=p4(10);K.showSystem(J4(o));break}if(/^[a-z0-9]{6}$/.test(W)){let o=IZ(W);if(o)K.showSystem(kZ(o));else K.showError(`Material nao encontrado: ${W}`);break}let q=W.indexOf("|");if(q===-1){K.showSystem(`Uso: /material <titulo> | <conteudo>
475
+ Ou peca a IA: "salva esse material sobre..."`);break}let C=W.slice(0,q).trim(),F=W.slice(q+1).trim();if(!C||!F){K.showError("Titulo e conteudo sao obrigatorios.");break}let I=A1(C,F),S=I.tags.length>0?` [${I.tags.map((o)=>"#"+o).join(" ")}]`:"";K.showSystem(`Material salvo: "${I.title}" (${I.category})${S} {${I.id}}`);break}case"materials":case"materiais":{let W=E.join(" ");if(W){let q=x1(W);K.showSystem(J4(q))}else{let q=p4();K.showSystem(J4(q))}break}case"matcats":case"categorias":{K.showSystem(bZ());break}case"rmmat":case"rmmaterial":{let W=E[0];if(!W){K.showError("Uso: /rmmat <id>");break}if(D1(W))K.showSystem("Material removido.");else K.showError(`Material nao encontrado: ${W}`);break}case"indexar":case"index":case"reindex":{K.showSystem("Indexando memoria local...");let W=S1();K.showSystem(`Indexacao concluida: ${W.indexed} fonte(s) indexada(s), ${W.skipped} sem alteracao. Total: ${W.total} chunks.`);break}case"memoria":case"memory":{let W=E.join(" ");if(W){let q=k1(W);K.showSystem(b1(q))}else{let q=w1(),C=q.builtAt?new Date(q.builtAt).toLocaleString("pt-BR"):"nunca";K.showSystem(`Memory RAG Index:
463
476
  Chunks: ${q.chunks}
464
477
  Fontes: ${q.sources}
465
- Ultima indexacao: ${C}`)}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,C=await O1(q);z.showSystem(C)}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 O1();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):
466
- ${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),C=[];if(q.stdout.trim())C.push(q.stdout.trim());if(q.stderr.trim())C.push(`stderr: ${q.stderr.trim()}`);C.push(`(exit: ${q.exitCode}, ${q.duration}ms)`),z.showSystem(C.join(`
467
- `));break}case"projeto":case"project":{let W=O.join(" ");if(W){let q=S0(W);if(q)u1(q.id),z.showSystem(v0(q));else if(W==="auto"){let C=m0(process.cwd());if(C)u1(C.id),z.showSystem(`Projeto detectado: ${v0(C)}`);else z.showError("Nenhum projeto detectado no diretorio atual.")}else z.showError(`Projeto nao encontrado: "${W}"`)}else{let q=Z1();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=Z1();if(!q){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(W==="start"||W==="iniciar"){let C=O.slice(1).join(" "),j=k0(q.id,C);if(j)z.showSystem(`Sessao iniciada para "${q.name}" [${j.id}]`)}else if(W==="stop"||W==="parar"){let C=Y1(q.id);if(C){let j=y0(C.id,O.slice(1).join(" "));if(j)z.showSystem(`Sessao encerrada: ${j.durationMinutes} minutos em "${q.name}"`)}else z.showSystem("Nenhuma sessao aberta.")}else{let C=Y1(q.id);if(C){let j=Math.round((Date.now()-new Date(C.startedAt).getTime())/60000);z.showSystem(`Sessao aberta: ${j} minutos em "${q.name}"`)}else z.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let W=Z1();if(!W){z.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let q=O[0]||"today";z.showSystem("Gerando relatorio...");let C=await h0(W.id,q,"pt");if(C)z.showSystem(C.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"}[f]||O[0],C=G0(q);z.showSystem(H0(C));break}case"person":case"pessoa":{let W=O.join(" ");if(!W){z.showError("Uso: /person <nome>");break}let q=t$(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]
468
- Ex: /addperson equipe Joao dev frontend`);break}let C=O.slice(1).join(" ");if(!C){z.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[j,...T]=C.split(","),b=T.join(",").trim()||void 0,a=V0(j.trim(),W,b);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>
469
- Ex: /delegate Joao revisar relatorio`);break}let q=O.slice(1).join(" "),C=W0(W,q);if(!C){z.showError(`Pessoa nao encontrada: "${W}"`);break}z.showSystem(`Delegado para ${W}: "${q}" [${C.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let W=O[0],q=v1(W);z.showSystem(U0(q));break}case"followups":{let W=n4();z.showSystem(B0(W));break}case"dashboard":case"painel":{z.showSystem(N0());break}case"task":case"tarefa":{let W=O.join(" ");if(!W){let b=a$();z.showSystem(q1(b));break}let q=c4(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 j=r8(C,q||void 0),T=q?` \u2014 lembrete: ${q.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";z.showSystem(`Tarefa criada: "${j.title}"${T} [${j.id}]`);break}case"tasks":case"tarefas":{let W=O[0]==="all"||O[0]==="todas",q=a$(W);z.showSystem(q1(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: /${f}. Try /help`)}}function k(){L9(),h6(),s6(),Y2(),z.stop(),process.exit(0)}process.on("SIGINT",k),process.on("SIGTERM",k),z.start({onSubmit:w,onCancel:()=>{L?.abort(),z.endStream(),z.showSystem("Cancelled."),z.enableInput()},onExit:k});let f$=`Authenticated via Claude ${J.subscriptionType} subscription.`;if(z.showSystem(`smolerclaw v${$8()} \u2014 the micro AI assistant.
470
- ${f$}
471
- Type /ajuda for commands.`),D6(Y.dataDir))try{let h=await P6();z.showSystem(h),T6()}catch{}if(G)await w(G)}function cX($){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)});
478
+ Ultima indexacao: ${C}`)}break}case"vault":{let W=E[0]?.toLowerCase();if(!W||W==="status")K.showSystem(M0(C0()));else if(W==="backup"){K.showSystem("Realizando backup...");let q=E.slice(1).join(" ")||void 0,C=await x4(q);K.showSystem(C)}else if(W==="sync"||W==="push"){K.showSystem("Sincronizando com remote...");let q=await j0();K.showSystem(q)}else if(W==="init"){let q=await O0();K.showSystem(q),T5(30),K.showSystem("Auto-backup ativado (a cada 30 minutos).")}else K.showError("Uso: /vault [status|backup|sync|init]");break}case"backup":{K.showSystem("Realizando backup...");let W=await x4();K.showSystem(W);break}case"clipboard":case"area":{K.showSystem("Lendo clipboard...");let W=await _1();switch(W.type){case"text":K.showSystem(`Clipboard (texto):
479
+ ${W.text}`);break;case"image":K.showSystem(W.text);break;case"empty":K.showSystem("Clipboard vazio.");break;case"error":K.showError(W.text);break}break}case"tela":case"screen":{K.showSystem("Analisando tela...");let W=await h1();K.showSystem(W);break}case"ps1":{let W=E.join(" ");if(!W.trim()){K.showError("Uso: /ps1 <script powershell>");break}K.showSystem("Executando script...");let q=await y1(W),C=[];if(q.stdout.trim())C.push(q.stdout.trim());if(q.stderr.trim())C.push(`stderr: ${q.stderr.trim()}`);C.push(`(exit: ${q.exitCode}, ${q.duration}ms)`),K.showSystem(C.join(`
480
+ `));break}case"projeto":case"project":{let W=E.join(" ");if(W){let q=g1(W);if(q)i4(q.id),K.showSystem(o1(q));else if(W==="auto"){let C=i1(process.cwd());if(C)i4(C.id),K.showSystem(`Projeto detectado: ${o1(C)}`);else K.showError("Nenhum projeto detectado no diretorio atual.")}else K.showError(`Projeto nao encontrado: "${W}"`)}else{let q=Q4();if(q)K.showSystem(o1(q));else K.showSystem("Nenhum projeto ativo. Use /projeto <nome> ou /projeto auto")}break}case"projetos":case"projects":{K.showSystem(l1(m1()));break}case"sessao":case"session":{let W=E[0],q=Q4();if(!q){K.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}if(W==="start"||W==="iniciar"){let C=E.slice(1).join(" "),F=c1(q.id,C);if(F)K.showSystem(`Sessao iniciada para "${q.name}" [${F.id}]`)}else if(W==="stop"||W==="parar"){let C=X4(q.id);if(C){let F=d1(C.id,E.slice(1).join(" "));if(F)K.showSystem(`Sessao encerrada: ${F.durationMinutes} minutos em "${q.name}"`)}else K.showSystem("Nenhuma sessao aberta.")}else{let C=X4(q.id);if(C){let F=Math.round((Date.now()-new Date(C.startedAt).getTime())/60000);K.showSystem(`Sessao aberta: ${F} minutos em "${q.name}"`)}else K.showSystem("Nenhuma sessao aberta. Use /sessao start")}break}case"relatorio":case"report":{let W=Q4();if(!W){K.showError("Nenhum projeto ativo. Use /projeto primeiro.");break}let q=E[0]||"today";K.showSystem("Gerando relatorio...");let C=await p1(W.id,q,"pt");if(C)K.showSystem(C.markdown);else K.showError("Falha ao gerar relatorio.");break}case"oportunidades":case"opportunities":{let W=E[0]||void 0,q=u1(W);K.showSystem(n1(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"}[_]||E[0],C=M1(q);K.showSystem(j1(C));break}case"person":case"pessoa":{let W=E.join(" ");if(!W){K.showError("Uso: /person <nome>");break}let q=Z4(W);if(!q){K.showError(`Pessoa nao encontrada: "${W}"`);break}K.showSystem(E1(q));break}case"addperson":case"addpessoa":case"novapessoa":{let W=E[0];if(!W||!["equipe","familia","contato"].includes(W)){K.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
481
+ Ex: /addperson equipe Joao dev frontend`);break}let C=E.slice(1).join(" ");if(!C){K.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[F,...I]=C.split(","),S=I.join(",").trim()||void 0,o=C1(F.trim(),W,S);K.showSystem(`Adicionado: ${o.name} (${W}) [${o.id}]`);break}case"delegate":case"delegar":{let W=E[0];if(!W||E.length<2){K.showSystem(`Uso: /delegate <pessoa> <tarefa>
482
+ Ex: /delegate Joao revisar relatorio`);break}let q=E.slice(1).join(" "),C=O1(W,q);if(!C){K.showError(`Pessoa nao encontrada: "${W}"`);break}K.showSystem(`Delegado para ${W}: "${q}" [${C.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let W=E[0],q=u4(W);K.showSystem(F1(q));break}case"followups":{let W=Z0();K.showSystem(L1(W));break}case"dashboard":case"painel":{K.showSystem(R1());break}case"task":case"tarefa":{let W=E.join(" ");if(!W){let S=t$();K.showSystem(E4(S));break}let q=r8(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 F=Q1(C,q||void 0),I=q?` \u2014 lembrete: ${q.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";K.showSystem(`Tarefa criada: "${F.title}"${I} [${F.id}]`);break}case"tasks":case"tarefas":{let W=E[0]==="all"||E[0]==="todas",q=t$(W);K.showSystem(E4(q));break}case"done":case"feito":case"concluido":{let W=E.join(" ");if(!W){K.showError("Uso: /done <id ou parte do titulo>");break}let q=X1(W);if(q)K.showSystem(`Concluida: "${q.title}"`);else K.showError(`Tarefa nao encontrada: "${W}"`);break}case"rmtask":case"rmtarefa":{let W=E.join(" ");if(!W){K.showError("Uso: /rmtask <id ou parte do titulo>");break}if(l9(W))K.showSystem("Tarefa removida.");else K.showError(`Tarefa nao encontrada: "${W}"`);break}default:K.showError(`Unknown command: /${_}. Try /help`)}}function w(){Z.saveLastSession(),p9(),A3(),g3(),U2(),K.stop(),process.exit(0)}process.on("SIGINT",w),process.on("SIGTERM",w),K.start({onSubmit:A,onCancel:()=>{j?.abort(),K.endStream(),K.showSystem("Cancelled."),K.enableInput()},onExit:w});let N$=`Authenticated via Claude ${Y.subscriptionType} subscription.`;if(K.showSystem(`smolerclaw v${H0()} \u2014 the micro AI assistant.
483
+ ${N$}
484
+ Type /ajuda for commands.`),B3(J.dataDir))try{let b=await C3();K.showSystem(b),N3()}catch{}if(V)await A(V)}function HK($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let J=Math.floor(Z/60000);if(J<1)return"just now";if(J<60)return`${J}m ago`;let Y=Math.floor(J/60);if(Y<24)return`${Y}h ago`;let Q=Math.floor(Y/24);if(Q>365)return`${Math.floor(Q/365)}y ago`;return`${Q}d ago`}KK().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});