smolerclaw 0.1.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 (73) hide show
  1. package/.github/workflows/ci.yml +30 -0
  2. package/.github/workflows/release.yml +67 -0
  3. package/bun.lock +33 -0
  4. package/dist/index.js +321 -0
  5. package/dist/tinyclaw.exe +0 -0
  6. package/install.ps1 +119 -0
  7. package/package.json +25 -0
  8. package/skills/business.md +77 -0
  9. package/skills/default.md +77 -0
  10. package/src/ansi.ts +164 -0
  11. package/src/approval.ts +74 -0
  12. package/src/auth.ts +125 -0
  13. package/src/briefing.ts +52 -0
  14. package/src/claude.ts +267 -0
  15. package/src/cli.ts +137 -0
  16. package/src/clipboard.ts +27 -0
  17. package/src/config.ts +87 -0
  18. package/src/context-window.ts +190 -0
  19. package/src/context.ts +125 -0
  20. package/src/decisions.ts +122 -0
  21. package/src/email.ts +123 -0
  22. package/src/errors.ts +78 -0
  23. package/src/export.ts +82 -0
  24. package/src/finance.ts +148 -0
  25. package/src/git.ts +62 -0
  26. package/src/history.ts +100 -0
  27. package/src/images.ts +68 -0
  28. package/src/index.ts +1431 -0
  29. package/src/investigate.ts +415 -0
  30. package/src/markdown.ts +125 -0
  31. package/src/memos.ts +191 -0
  32. package/src/models.ts +94 -0
  33. package/src/monitor.ts +169 -0
  34. package/src/morning.ts +108 -0
  35. package/src/news.ts +329 -0
  36. package/src/openai-provider.ts +127 -0
  37. package/src/people.ts +472 -0
  38. package/src/personas.ts +99 -0
  39. package/src/platform.ts +84 -0
  40. package/src/plugins.ts +125 -0
  41. package/src/pomodoro.ts +169 -0
  42. package/src/providers.ts +70 -0
  43. package/src/retry.ts +108 -0
  44. package/src/session.ts +128 -0
  45. package/src/skills.ts +102 -0
  46. package/src/tasks.ts +418 -0
  47. package/src/tokens.ts +102 -0
  48. package/src/tool-safety.ts +100 -0
  49. package/src/tools.ts +1479 -0
  50. package/src/tui.ts +693 -0
  51. package/src/types.ts +55 -0
  52. package/src/undo.ts +83 -0
  53. package/src/windows.ts +299 -0
  54. package/src/workflows.ts +197 -0
  55. package/tests/ansi.test.ts +58 -0
  56. package/tests/approval.test.ts +43 -0
  57. package/tests/briefing.test.ts +10 -0
  58. package/tests/cli.test.ts +53 -0
  59. package/tests/context-window.test.ts +83 -0
  60. package/tests/images.test.ts +28 -0
  61. package/tests/memos.test.ts +116 -0
  62. package/tests/models.test.ts +34 -0
  63. package/tests/news.test.ts +13 -0
  64. package/tests/path-guard.test.ts +37 -0
  65. package/tests/people.test.ts +204 -0
  66. package/tests/skills.test.ts +35 -0
  67. package/tests/ssrf.test.ts +80 -0
  68. package/tests/tasks.test.ts +152 -0
  69. package/tests/tokens.test.ts +44 -0
  70. package/tests/tool-safety.test.ts +55 -0
  71. package/tests/windows-security.test.ts +59 -0
  72. package/tests/windows.test.ts +20 -0
  73. package/tsconfig.json +19 -0
package/dist/index.js ADDED
@@ -0,0 +1,321 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+ var EZ=Object.defineProperty;var LZ=($)=>$;function xZ($,Z){this[$]=LZ.bind(null,Z)}var DZ=($,Z)=>{for(var Y in Z)EZ($,Y,{get:Z[Y],enumerable:!0,configurable:!0,set:xZ.bind(Z,Y)})};var RZ=($,Z)=>()=>($&&(Z=$($=0)),Z);var w6={};DZ(w6,{searchInvestigations:()=>x6,openInvestigation:()=>j6,listInvestigations:()=>L6,initInvestigations:()=>N6,getInvestigation:()=>E6,generateReport:()=>D6,formatInvestigationList:()=>Q4,formatInvestigationDetail:()=>R6,formatEvidenceDetail:()=>E5,collectEvidence:()=>O6,closeInvestigation:()=>F6,addFinding:()=>M6});import{existsSync as u8,mkdirSync as N5,readFileSync as j5,writeFileSync as O5}from"fs";import{join as M5}from"path";function z4(){O5(l8(),JSON.stringify(p,null,2))}function F5(){let $=l8();if(!u8($)){p=[];return}try{p=JSON.parse(j5($,"utf-8"))}catch{p=[]}}function N6($){if(p8=$,!u8($))N5($,{recursive:!0});F5()}function j6($,Z,Y,J=[]){let X=new Date().toISOString(),z={id:A6(),title:$.trim(),type:Z,status:"aberta",hypothesis:Y?.trim(),tags:J.map((Q)=>Q.toLowerCase()),evidence:[],findings:[],created:X,updated:X};return p=[...p,z],z4(),z}function O6($,Z,Y,J,X){let z=X1($);if(!z)return null;let Q={id:A6(),source:Z,label:Y.trim(),content:J.trim(),path:X?.trim(),timestamp:new Date().toISOString()},K={...z,evidence:[...z.evidence,Q],status:z.status==="aberta"?"em_andamento":z.status,updated:new Date().toISOString()};return p=p.map((G)=>G.id===z.id?K:G),z4(),Q}function M6($,Z,Y,J,X=[]){let z=X1($);if(!z)return null;let Q=X.filter((H)=>z.evidence.some((V)=>V.id===H)),K={id:A6(),severity:Z,title:Y.trim(),description:J.trim(),evidence_ids:Q,timestamp:new Date().toISOString()},G={...z,findings:[...z.findings,K],updated:new Date().toISOString()};return p=p.map((H)=>H.id===z.id?G:H),z4(),K}function F6($,Z,Y){let J=X1($);if(!J)return null;let X={...J,status:"concluida",summary:Z.trim(),recommendations:Y?.trim(),updated:new Date().toISOString()};return p=p.map((z)=>z.id===J.id?X:z),z4(),X}function E6($){return X1($)}function L6($,Z,Y=20){let J=[...p];if($)J=J.filter((X)=>X.status===$);if(Z)J=J.filter((X)=>X.type===Z);return J.sort((X,z)=>new Date(z.updated).getTime()-new Date(X.updated).getTime()).slice(0,Y)}function x6($){let Z=$.toLowerCase();return p.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 D6($){let Z=X1($);if(!Z)return null;let Y=[],J=(Q)=>new Date(Q).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}),X={bug:"Bug / Mal funcionamento",feature:"Construcao de funcionalidade",test:"Material para testes",audit:"Auditoria",incident:"Incidente"},z={critical:0,high:1,medium:2,low:3,info:4};if(Y.push(`# Investigacao: ${Z.title}`),Y.push(""),Y.push(`**Tipo:** ${X[Z.type]}`),Y.push(`**Status:** ${Z.status}`),Y.push(`**Abertura:** ${J(Z.created)}`),Y.push(`**Ultima atualizacao:** ${J(Z.updated)}`),Z.tags.length)Y.push(`**Tags:** ${Z.tags.join(", ")}`);if(Y.push(`**ID:** ${Z.id}`),Z.hypothesis)Y.push(""),Y.push("## Hipotese"),Y.push(Z.hypothesis);if(Z.evidence.length>0){Y.push(""),Y.push(`## Evidencias (${Z.evidence.length})`);for(let Q of Z.evidence){let K=J(Q.timestamp);Y.push(""),Y.push(`### [${Q.id}] ${Q.label}`),Y.push(`- Fonte: ${Q.source}${Q.path?` (${Q.path})`:""}`),Y.push(`- Coletada: ${K}`);let G=Q.content.length>2000?Q.content.slice(0,2000)+`
4
+ ... (truncado)`:Q.content;Y.push("```"),Y.push(G),Y.push("```")}}if(Z.findings.length>0){let Q=[...Z.findings].sort((K,G)=>(z[K.severity]??4)-(z[G.severity]??4));Y.push(""),Y.push(`## Conclusoes (${Z.findings.length})`);for(let K of Q){let G=n8(K.severity);if(Y.push(""),Y.push(`### ${G} ${K.title}`),Y.push(K.description),K.evidence_ids.length>0)Y.push(`- Evidencias: ${K.evidence_ids.join(", ")}`)}}if(Z.summary)Y.push(""),Y.push("## Resumo"),Y.push(Z.summary);if(Z.recommendations)Y.push(""),Y.push("## Recomendacoes"),Y.push(Z.recommendations);return Y.join(`
5
+ `)}function Q4($){if($.length===0)return"Nenhuma investigacao encontrada.";let Z=$.map((Y)=>{let J=new Date(Y.updated).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=i8(Y.status),z=Y.evidence.length,Q=Y.findings.length,K=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` ${X} [${J}] ${Y.title} (${Y.type}) \u2014 ${z} ev, ${Q} concl${K} {${Y.id}}`});return`Investigacoes (${$.length}):
6
+ ${Z.join(`
7
+ `)}`}function R6($){let Z=(X)=>new Date(X).toLocaleDateString("pt-BR"),Y=i8($.status),J=[`--- Investigacao {${$.id}} ---`,`Titulo: ${$.title}`,`Tipo: ${$.type} | Status: ${Y}`,`Criada: ${Z($.created)} | Atualizada: ${Z($.updated)}`];if($.hypothesis)J.push(`Hipotese: ${$.hypothesis}`);if($.tags.length)J.push(`Tags: ${$.tags.join(", ")}`);J.push(`
8
+ Evidencias: ${$.evidence.length}`);for(let X of $.evidence.slice(-5)){let z=X.content.slice(0,80).replace(/\n/g," ");J.push(` [${X.id}] ${X.source}: ${X.label} \u2014 "${z}..."`)}if($.evidence.length>5)J.push(` ... (${$.evidence.length-5} mais)`);J.push(`
9
+ Conclusoes: ${$.findings.length}`);for(let X of $.findings)J.push(` ${n8(X.severity)} ${X.title}`);if($.summary)J.push(`
10
+ Resumo: ${$.summary}`);if($.recommendations)J.push(`Recomendacoes: ${$.recommendations}`);return J.join(`
11
+ `)}function E5($){let Z=new Date($.timestamp).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",hour:"2-digit",minute:"2-digit"});return[`--- Evidencia {${$.id}} ---`,`Label: ${$.label}`,`Fonte: ${$.source}${$.path?` (${$.path})`:""}`,`Coletada: ${Z}`,"",$.content.length>3000?$.content.slice(0,3000)+`
12
+ ... (truncado)`:$.content].join(`
13
+ `)}function X1($){let Z=$.toLowerCase().trim(),Y=p.find((X)=>X.id===Z);if(Y)return Y;return p.filter((X)=>X.title.toLowerCase().includes(Z)).sort((X,z)=>new Date(z.updated).getTime()-new Date(X.updated).getTime())[0]||null}function i8($){switch($){case"aberta":return"\u25CB";case"em_andamento":return"\u25C9";case"concluida":return"\u25CF";case"arquivada":return"\u25CC"}}function n8($){switch($){case"critical":return"[CRITICO]";case"high":return"[ALTO]";case"medium":return"[MEDIO]";case"low":return"[BAIXO]";case"info":return"[INFO]"}}function A6(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}var p8="",p,l8=()=>M5(p8,"investigations.json");var z1=RZ(()=>{p=[]});import{readFileSync as AZ}from"fs";import{join as wZ,dirname as TZ}from"path";function Y7($){let Z={help:!1,version:!1,noTools:!1,print:!1},Y=[],J=0;while(J<$.length){let X=$[J];switch(X){case"-h":case"--help":Z.help=!0;break;case"-v":case"--version":Z.version=!0;break;case"-m":case"--model":if(Z.model=$[++J],!Z.model)q1("--model requires a value");break;case"-s":case"--session":if(Z.session=$[++J],!Z.session)q1("--session requires a value");break;case"--max-tokens":let z=Number($[++J]);if(!z||z<=0)q1("--max-tokens requires a positive number");Z.maxTokens=z;break;case"--no-tools":Z.noTools=!0;break;case"-p":case"--print":Z.print=!0;break;default:if(X.startsWith("-"))q1(`Unknown option: ${X}. Try --help`);Y.push(X)}J++}if(Y.length>0)Z.prompt=Y.join(" ");return Z}function H1(){return"0.1.0"}function J7(){let $=H1();console.log(`tinyclaw v${$} \u2014 the micro AI assistant
14
+
15
+ Usage:
16
+ tinyclaw [options] [prompt]
17
+
18
+ Options:
19
+ -h, --help Show this help
20
+ -v, --version Show version
21
+ -m, --model <name> Override model (e.g. claude-sonnet-4-20250514)
22
+ -s, --session <name> Start with a specific session
23
+ --max-tokens <n> Override max tokens per response
24
+ --no-tools Disable tool use for this session
25
+ -p, --print Print response and exit (no TUI)
26
+
27
+ Examples:
28
+ tinyclaw Interactive TUI mode
29
+ tinyclaw "explain this error" Launch TUI with initial prompt
30
+ tinyclaw -p "what is 2+2" Print answer and exit
31
+ echo "review" | tinyclaw -p Pipe input, print response
32
+ tinyclaw -m claude-sonnet-4-20250514 -s work
33
+
34
+ Commands (inside TUI):
35
+ /help Show commands /clear Clear conversation
36
+ /new New session /load Load session
37
+ /model Show/set model /persona Switch mode
38
+ /briefing Daily briefing /news News radar
39
+ /task Create task /tasks List tasks
40
+ /open Open Windows app /calendar Outlook calendar
41
+ /export Export markdown /exit Quit`)}function q1($){console.error(`tinyclaw: ${$}`),process.exit(2)}import{existsSync as B1,mkdirSync as SZ,readFileSync as V7,writeFileSync as N1}from"fs";import{homedir as kZ}from"os";import{join as G2}from"path";import{existsSync as PZ}from"fs";var D=process.platform==="win32",X7=process.platform==="darwin",VY=process.platform==="linux";function C1(){if(D)return["powershell","-NoProfile","-NonInteractive","-Command"];let $=process.env.SHELL;if($&&PZ($))return[$,"-c"];return["bash","-c"]}function z7(){if(D)return"powershell";return(process.env.SHELL||"/bin/bash").split("/").pop()||"bash"}async function IZ($){try{let Z=D?["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 U1=null;async function Q7(){if(U1!==null)return U1;return U1=await IZ("rg"),U1}var A4=["node_modules",".git","dist","build",".next","__pycache__",".venv","target",".cache"];function w4($){let Z=$.replace(/\\/g,"/");return A4.some((Y)=>Z.includes(`/${Y}/`)||Z.startsWith(`${Y}/`))}var q$=kZ(),j1=D?G2(process.env.APPDATA||G2(q$,"AppData","Roaming"),"tinyclaw"):G2(q$,".config","tinyclaw"),T4=D?G2(process.env.LOCALAPPDATA||G2(q$,"AppData","Local"),"tinyclaw"):G2(q$,".local","share","tinyclaw"),B2=G2(j1,"config.json"),G$={apiKey:"",authMode:"auto",model:"claude-haiku-4-5-20251001",maxTokens:4096,maxHistory:50,systemPrompt:"",skillsDir:"./skills",dataDir:T4,toolApproval:"auto",language:"auto",maxSessionCost:0};function W$($){if(!B1($))SZ($,{recursive:!0})}function K7(){if(W$(j1),W$(T4),W$(G2(T4,"sessions")),D)bZ();if(!B1(B2))return N1(B2,JSON.stringify(G$,null,2)),{...G$};let $;try{$=JSON.parse(V7(B2,"utf-8"))}catch{return N1(B2,JSON.stringify(G$,null,2)),{...G$}}return{...G$,...$}}function O1($){W$(j1),N1(B2,JSON.stringify($,null,2))}function G7(){return B2}function bZ(){let $=G2(q$,".config","tinyclaw","config.json");if(B1($)&&!B1(B2))try{let Z=V7($,"utf-8");W$(j1),N1(B2,Z)}catch{}}import{existsSync as yZ,readFileSync as _Z}from"fs";import{homedir as fZ}from"os";import{join as hZ}from"path";var W7=hZ(fZ(),".claude",".credentials.json");function P4($,Z="auto"){if(Z==="subscription"){let J=q7();if(J)return J;throw Error("Claude Code credentials not found or expired.\nRun `claude` to refresh, then restart tinyclaw.")}if(Z==="api-key"){let J=process.env.ANTHROPIC_API_KEY||$;if(J)return{apiKey:J,source:"api-key"};throw Error(`No API key found.
42
+ Set ANTHROPIC_API_KEY env var or add apiKey to config.`)}if(process.env.ANTHROPIC_API_KEY)return{apiKey:process.env.ANTHROPIC_API_KEY,source:"api-key"};let Y=q7();if(Y)return Y;if($)return{apiKey:$,source:"api-key"};throw Error(`No authentication found.
43
+ Options:
44
+ 1. Install Claude Code with a Pro/Max subscription (auto-detected)
45
+ 2. Set ANTHROPIC_API_KEY env var
46
+ 3. Add apiKey to ~/.config/tinyclaw/config.json`)}function q7(){if(!yZ(W7))return null;try{let Z=JSON.parse(_Z(W7,"utf-8")).claudeAiOauth;if(!Z?.accessToken)return null;if(Date.now()>Z.expiresAt-60000)return null;return{apiKey:Z.accessToken,source:"subscription",subscriptionType:Z.subscriptionType,expiresAt:Z.expiresAt}}catch{return null}}function H7($,Z="auto"){try{return P4($,Z)}catch{return null}}function U7($){if($.source==="subscription")return`sub:${$.subscriptionType||"pro"}`;return"api-key"}function j($,Z,Y,J,X){if(J==="m")throw TypeError("Private method is not writable");if(J==="a"&&!X)throw TypeError("Private accessor was defined without a setter");if(typeof Z==="function"?$!==Z||!X:!Z.has($))throw TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?X.call($,Y):X?X.value=Y:Z.set($,Y),Y}function q($,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 I4=function(){let{crypto:$}=globalThis;if($?.randomUUID)return I4=$.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 W2($){return typeof $==="object"&&$!==null&&(("name"in $)&&$.name==="AbortError"||("message"in $)&&String($.message).includes("FetchRequestCanceledException"))}var H$=($)=>{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 M extends Error{}class f extends M{constructor($,Z,Y,J){super(`${f.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 I2({message:Y,cause:H$(Z)});let X=Z;if($===400)return new C$($,X,Y,J);if($===401)return new B$($,X,Y,J);if($===403)return new N$($,X,Y,J);if($===404)return new j$($,X,Y,J);if($===409)return new O$($,X,Y,J);if($===422)return new M$($,X,Y,J);if($===429)return new F$($,X,Y,J);if($>=500)return new E$($,X,Y,J);return new f($,X,Y,J)}}class u extends f{constructor({message:$}={}){super(void 0,void 0,$||"Request was aborted.",void 0)}}class I2 extends f{constructor({message:$,cause:Z}){super(void 0,void 0,$||"Connection error.",void 0);if(Z)this.cause=Z}}class U$ extends I2{constructor({message:$}={}){super({message:$??"Request timed out."})}}class C$ extends f{}class B$ extends f{}class N$ extends f{}class j$ extends f{}class O$ extends f{}class M$ extends f{}class F$ extends f{}class E$ extends f{}var gZ=/^[a-z][a-z0-9+.-]*:/i,C7=($)=>{return gZ.test($)},S4=($)=>(S4=Array.isArray,S4($)),k4=S4;function M1($){if(typeof $!=="object")return{};return $??{}}function b4($){if(!$)return!0;for(let Z in $)return!1;return!0}function B7($,Z){return Object.prototype.hasOwnProperty.call($,Z)}var N7=($,Z)=>{if(typeof Z!=="number"||!Number.isInteger(Z))throw new M(`${$} must be an integer`);if(Z<0)throw new M(`${$} must be a positive integer`);return Z};var F1=($)=>{try{return JSON.parse($)}catch(Z){return}};var j7=($)=>new Promise((Z)=>setTimeout(Z,$));var N2="0.80.0";var E7=()=>{return typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u"};function cZ(){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 dZ=()=>{let $=cZ();if($==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N2,"X-Stainless-OS":M7(Deno.build.os),"X-Stainless-Arch":O7(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":N2,"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":N2,"X-Stainless-OS":M7(globalThis.process.platform??"unknown"),"X-Stainless-Arch":O7(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let Z=mZ();if(Z)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":N2,"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":N2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function mZ(){if(typeof navigator>"u"||!navigator)return null;let $=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:Z,pattern:Y}of $){let J=Y.exec(navigator.userAgent);if(J){let X=J[1]||0,z=J[2]||0,Q=J[3]||0;return{browser:Z,version:`${X}.${z}.${Q}`}}}return null}var O7=($)=>{if($==="x32")return"x32";if($==="x86_64"||$==="x64")return"x64";if($==="arm")return"arm";if($==="aarch64"||$==="arm64")return"arm64";if($)return`other:${$}`;return"unknown"},M7=($)=>{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"},F7,L7=()=>{return F7??(F7=dZ())};function x7(){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 y4(...$){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 E1($){let Z=Symbol.asyncIterator in $?$[Symbol.asyncIterator]():$[Symbol.iterator]();return y4({start(){},async pull(Y){let{done:J,value:X}=await Z.next();if(J)Y.close();else Y.enqueue(X)},async cancel(){await Z.return?.()}})}function L$($){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 D7($){if($===null||typeof $!=="object")return;if($[Symbol.asyncIterator]){await $[Symbol.asyncIterator]().return?.();return}let Z=$.getReader(),Y=Z.cancel();Z.releaseLock(),await Y}var R7=({headers:$,body:Z})=>{return{bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(Z)}};function A7($){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 M(`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 P7($){let Z=0;for(let X of $)Z+=X.length;let Y=new Uint8Array(Z),J=0;for(let X of $)Y.set(X,J),J+=X.length;return Y}var w7;function x$($){let Z;return(w7??(Z=new globalThis.TextEncoder,w7=Z.encode.bind(Z)))($)}var T7;function _4($){let Z;return(T7??(Z=new globalThis.TextDecoder,T7=Z.decode.bind(Z)))($)}var o,a;class j2{constructor(){o.set(this,void 0),a.set(this,void 0),j(this,o,new Uint8Array,"f"),j(this,a,null,"f")}decode($){if($==null)return[];let Z=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?x$($):$;j(this,o,P7([q(this,o,"f"),Z]),"f");let Y=[],J;while((J=lZ(q(this,o,"f"),q(this,a,"f")))!=null){if(J.carriage&&q(this,a,"f")==null){j(this,a,J.index,"f");continue}if(q(this,a,"f")!=null&&(J.index!==q(this,a,"f")+1||J.carriage)){Y.push(_4(q(this,o,"f").subarray(0,q(this,a,"f")-1))),j(this,o,q(this,o,"f").subarray(q(this,a,"f")),"f"),j(this,a,null,"f");continue}let X=q(this,a,"f")!==null?J.preceding-1:J.preceding,z=_4(q(this,o,"f").subarray(0,X));Y.push(z),j(this,o,q(this,o,"f").subarray(J.index),"f"),j(this,a,null,"f")}return Y}flush(){if(!q(this,o,"f").length)return[];return this.decode(`
47
+ `)}}o=new WeakMap,a=new WeakMap;j2.NEWLINE_CHARS=new Set([`
48
+ `,"\r"]);j2.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function lZ($,Z){for(let X=Z??0;X<$.length;X++){if($[X]===10)return{preceding:X,index:X+1,carriage:!1};if($[X]===13)return{preceding:X,index:X+1,carriage:!0}}return null}function I7($){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 x1={off:0,error:200,warn:300,info:400,debug:500},f4=($,Z,Y)=>{if(!$)return;if(B7(x1,$))return $;c(Y).warn(`${Z} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(x1))}`);return};function D$(){}function L1($,Z,Y){if(!Z||x1[$]>x1[Y])return D$;else return Z[$].bind(Z)}var iZ={error:D$,warn:D$,info:D$,debug:D$},S7=new WeakMap;function c($){let Z=$.logger,Y=$.logLevel??"off";if(!Z)return iZ;let J=S7.get(Z);if(J&&J[0]===Y)return J[1];let X={error:L1("error",Z,Y),warn:L1("warn",Z,Y),info:L1("info",Z,Y),debug:L1("debug",Z,Y)};return S7.set(Z,[Y,X]),X}var q2=($)=>{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 R$;class r{constructor($,Z,Y){this.iterator=$,R$.set(this,void 0),this.controller=Z,j(this,R$,Y,"f")}static fromSSEResponse($,Z,Y){let J=!1,X=Y?c(Y):console;async function*z(){if(J)throw new M("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let Q=!1;try{for await(let K of nZ($,Z)){if(K.event==="completion")try{yield JSON.parse(K.data)}catch(G){throw X.error("Could not parse message into JSON:",K.data),X.error("From chunk:",K.raw),G}if(K.event==="message_start"||K.event==="message_delta"||K.event==="message_stop"||K.event==="content_block_start"||K.event==="content_block_delta"||K.event==="content_block_stop")try{yield JSON.parse(K.data)}catch(G){throw X.error("Could not parse message into JSON:",K.data),X.error("From chunk:",K.raw),G}if(K.event==="ping")continue;if(K.event==="error")throw new f(void 0,F1(K.data)??K.data,void 0,$.headers)}Q=!0}catch(K){if(W2(K))return;throw K}finally{if(!Q)Z.abort()}}return new r(z,Z,Y)}static fromReadableStream($,Z,Y){let J=!1;async function*X(){let Q=new j2,K=L$($);for await(let G of K)for(let H of Q.decode(G))yield H;for(let G of Q.flush())yield G}async function*z(){if(J)throw new M("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");J=!0;let Q=!1;try{for await(let K of X()){if(Q)continue;if(K)yield JSON.parse(K)}Q=!0}catch(K){if(W2(K))return;throw K}finally{if(!Q)Z.abort()}}return new r(z,Z,Y)}[(R$=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let $=[],Z=[],Y=this.iterator(),J=(X)=>{return{next:()=>{if(X.length===0){let z=Y.next();$.push(z),Z.push(z)}return X.shift()}}};return[new r(()=>J($),this.controller,q(this,R$,"f")),new r(()=>J(Z),this.controller,q(this,R$,"f"))]}toReadableStream(){let $=this,Z;return y4({async start(){Z=$[Symbol.asyncIterator]()},async pull(Y){try{let{value:J,done:X}=await Z.next();if(X)return Y.close();let z=x$(JSON.stringify(J)+`
49
+ `);Y.enqueue(z)}catch(J){Y.error(J)}},async cancel(){await Z.return?.()}})}}async function*nZ($,Z){if(!$.body){if(Z.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new M("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 M("Attempted to iterate over a response with no body")}let Y=new k7,J=new j2,X=L$($.body);for await(let z of oZ(X))for(let Q of J.decode(z)){let K=Y.decode(Q);if(K)yield K}for(let z of J.flush()){let Q=Y.decode(z);if(Q)yield Q}}async function*oZ($){let Z=new Uint8Array;for await(let Y of $){if(Y==null)continue;let J=Y instanceof ArrayBuffer?new Uint8Array(Y):typeof Y==="string"?x$(Y):Y,X=new Uint8Array(Z.length+J.length);X.set(Z),X.set(J,Z.length),Z=X;let z;while((z=I7(Z))!==-1)yield Z.slice(0,z),Z=Z.slice(z)}if(Z.length>0)yield Z}class k7{constructor(){this.event=null,this.data=[],this.chunks=[]}decode($){if($.endsWith("\r"))$=$.substring(0,$.length-1);if(!$){if(!this.event&&!this.data.length)return null;let X={event:this.event,data:this.data.join(`
50
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],X}if(this.chunks.push($),$.startsWith(":"))return null;let[Z,Y,J]=aZ($,":");if(J.startsWith(" "))J=J.substring(1);if(Z==="event")this.event=J;else if(Z==="data")this.data.push(J);return null}}function aZ($,Z){let Y=$.indexOf(Z);if(Y!==-1)return[$.substring(0,Y),Z,$.substring(Y+Z.length)];return[$,"",""]}async function D1($,Z){let{response:Y,requestLogID:J,retryOfRequestLogID:X,startTime:z}=Z,Q=await(async()=>{if(Z.options.stream){if(c($).debug("response",Y.status,Y.url,Y.headers,Y.body),Z.options.__streamClass)return Z.options.__streamClass.fromSSEResponse(Y,Z.controller);return r.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 B=await Y.json();return h4(B,Y)}return await Y.text()})();return c($).debug(`[${J}] response parsed`,q2({retryOfRequestLogID:X,url:Y.url,status:Y.status,body:Q,durationMs:Date.now()-z})),Q}function h4($,Z){if(!$||typeof $!=="object"||Array.isArray($))return $;return Object.defineProperty($,"_request_id",{value:Z.headers.get("request-id"),enumerable:!1})}var A$;class S2 extends Promise{constructor($,Z,Y=D1){super((J)=>{J(null)});this.responsePromise=Z,this.parseResponse=Y,A$.set(this,void 0),j(this,A$,$,"f")}_thenUnwrap($){return new S2(q(this,A$,"f"),this.responsePromise,async(Z,Y)=>h4($(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(q(this,A$,"f"),$));return this.parsedPromise}then($,Z){return this.parse().then($,Z)}catch($){return this.parse().catch($)}finally($){return this.parse().finally($)}}A$=new WeakMap;var R1;class v4{constructor($,Z,Y,J){R1.set(this,void 0),j(this,R1,$,"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 M("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await q(this,R1,"f").requestAPIList(this.constructor,$)}async*iterPages(){let $=this;yield $;while($.hasNextPage())$=await $.getNextPage(),yield $}async*[(R1=new WeakMap,Symbol.asyncIterator)](){for await(let $ of this.iterPages())for(let Z of $.getPaginatedItems())yield Z}}class A1 extends S2{constructor($,Z,Y){super($,Z,async(J,X)=>new Y(J,X.response,await D1(J,X),X.options))}async*[Symbol.asyncIterator](){let $=await this;for await(let Z of $)yield Z}}class J2 extends v4{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:{...M1(this.options.query),before_id:Z}}}let $=this.last_id;if(!$)return null;return{...this.options,query:{...M1(this.options.query),after_id:$}}}}class w$ extends v4{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:{...M1(this.options.query),page:$}}}}var c4=()=>{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 k2($,Z,Y){return c4(),new File($,Z??"unknown_file",Y)}function T$($,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 d4=($)=>$!=null&&typeof $==="object"&&typeof $[Symbol.asyncIterator]==="function";var d2=async($,Z,Y=!0)=>{return{...$,body:await tZ($.body,Z,Y)}},b7=new WeakMap;function sZ($){let Z=typeof $==="function"?$:$.fetch,Y=b7.get(Z);if(Y)return Y;let J=(async()=>{try{let X="Response"in Z?Z.Response:(await Z("data:,")).constructor,z=new FormData;if(z.toString()===await new X(z).text())return!1;return!0}catch{return!0}})();return b7.set(Z,J),J}var tZ=async($,Z,Y=!0)=>{if(!await sZ(Z))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let J=new FormData;return await Promise.all(Object.entries($||{}).map(([X,z])=>g4(J,X,z,Y))),J},eZ=($)=>$ instanceof Blob&&("name"in $);var g4=async($,Z,Y,J)=>{if(Y===void 0)return;if(Y==null)throw TypeError(`Received null for "${Z}"; to pass null in FormData, you must use the string 'null'`);if(typeof Y==="string"||typeof Y==="number"||typeof Y==="boolean")$.append(Z,String(Y));else if(Y instanceof Response){let X={},z=Y.headers.get("Content-Type");if(z)X={type:z};$.append(Z,k2([await Y.blob()],T$(Y,J),X))}else if(d4(Y))$.append(Z,k2([await new Response(E1(Y)).blob()],T$(Y,J)));else if(eZ(Y))$.append(Z,k2([Y],T$(Y,J),{type:Y.type}));else if(Array.isArray(Y))await Promise.all(Y.map((X)=>g4($,Z+"[]",X,J)));else if(typeof Y==="object")await Promise.all(Object.entries(Y).map(([X,z])=>g4($,`${Z}[${X}]`,z,J)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${Y} instead`)};var y7=($)=>$!=null&&typeof $==="object"&&typeof $.size==="number"&&typeof $.type==="string"&&typeof $.text==="function"&&typeof $.slice==="function"&&typeof $.arrayBuffer==="function",$3=($)=>$!=null&&typeof $==="object"&&typeof $.name==="string"&&typeof $.lastModified==="number"&&y7($),Z3=($)=>$!=null&&typeof $==="object"&&typeof $.url==="string"&&typeof $.blob==="function";async function w1($,Z,Y){if(c4(),$=await $,Z||(Z=T$($,!0)),$3($)){if($ instanceof File&&Z==null&&Y==null)return $;return k2([await $.arrayBuffer()],Z??$.name,{type:$.type,lastModified:$.lastModified,...Y})}if(Z3($)){let X=await $.blob();return Z||(Z=new URL($.url).pathname.split(/[\\/]/).pop()),k2(await m4(X),Z,Y)}let J=await m4($);if(!Y?.type){let X=J.find((z)=>typeof z==="object"&&("type"in z)&&z.type);if(typeof X==="string")Y={...Y,type:X}}return k2(J,Z,Y)}async function m4($){let Z=[];if(typeof $==="string"||ArrayBuffer.isView($)||$ instanceof ArrayBuffer)Z.push($);else if(y7($))Z.push($ instanceof Blob?$:await $.arrayBuffer());else if(d4($))for await(let Y of $)Z.push(...await m4(Y));else{let Y=$?.constructor?.name;throw Error(`Unexpected data type: ${typeof $}${Y?`; constructor: ${Y}`:""}${Y3($)}`)}return Z}function Y3($){if(typeof $!=="object"||$===null)return"";return`; props: [${Object.getOwnPropertyNames($).map((Y)=>`"${Y}"`).join(", ")}]`}class k{constructor($){this._client=$}}var _7=Symbol.for("brand.privateNullableHeaders");function*X3($){if(!$)return;if(_7 in $){let{values:J,nulls:X}=$;yield*J.entries();for(let z of X)yield[z,null];return}let Z=!1,Y;if($ instanceof Headers)Y=$.entries();else if(k4($))Y=$;else Z=!0,Y=Object.entries($??{});for(let J of Y){let X=J[0];if(typeof X!=="string")throw TypeError("expected header name to be a string");let z=k4(J[1])?J[1]:[J[1]],Q=!1;for(let K of z){if(K===void 0)continue;if(Z&&!Q)Q=!0,yield[X,null];yield[X,K]}}}var L=($)=>{let Z=new Headers,Y=new Set;for(let J of $){let X=new Set;for(let[z,Q]of X3(J)){let K=z.toLowerCase();if(!X.has(K))Z.delete(z),X.add(K);if(Q===null)Z.delete(z),Y.add(K);else Z.append(z,Q),Y.delete(K)}}return{[_7]:!0,values:Z,nulls:Y}};var P$=Symbol("anthropic.sdk.stainlessHelper");function T1($){return typeof $==="object"&&$!==null&&P$ in $}function u4($,Z){let Y=new Set;if($){for(let J of $)if(T1(J))Y.add(J[P$])}if(Z)for(let J of Z){if(T1(J))Y.add(J[P$]);if(Array.isArray(J.content)){for(let X of J.content)if(T1(X))Y.add(X[P$])}}return Array.from(Y)}function P1($,Z){let Y=u4($,Z);if(Y.length===0)return{};return{"x-stainless-helper":Y.join(", ")}}function f7($){if(T1($))return{"x-stainless-helper":$[P$]};return{}}function v7($){return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var h7=Object.freeze(Object.create(null)),z3=($=v7)=>function(Y,...J){if(Y.length===1)return Y[0];let X=!1,z=[],Q=Y.reduce((V,O,B)=>{if(/[?#]/.test(O))X=!0;let E=J[B],R=(X?encodeURIComponent:$)(""+E);if(B!==J.length&&(E==null||typeof E==="object"&&E.toString===Object.getPrototypeOf(Object.getPrototypeOf(E.hasOwnProperty??h7)??h7)?.toString))R=E+"",z.push({start:V.length+O.length,length:R.length,error:`Value of type ${Object.prototype.toString.call(E).slice(8,-1)} is not a valid path parameter`});return V+O+(B===J.length?"":R)},""),K=Q.split(/[?#]/,1)[0],G=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,H;while((H=G.exec(K))!==null)z.push({start:H.index,length:H[0].length,error:`Value "${H[0]}" can't be safely passed as a path parameter`});if(z.sort((V,O)=>V.start-O.start),z.length>0){let V=0,O=z.reduce((B,E)=>{let R=" ".repeat(E.start-V),v="^".repeat(E.length);return V=E.start+E.length,B+R+v},"");throw new M(`Path parameters result in path with invalid segments:
51
+ ${z.map((B)=>B.error).join(`
52
+ `)}
53
+ ${Q}
54
+ ${O}`)}return Q},I=z3(v7);class I$ extends k{list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/files",J2,{query:J,...Z,headers:L([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(I`/v1/files/${$}`,{...Y,headers:L([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}download($,Z={},Y){let{betas:J}=Z??{};return this._client.get(I`/v1/files/${$}/content`,{...Y,headers:L([{"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(I`/v1/files/${$}`,{...Y,headers:L([{"anthropic-beta":[...J??[],"files-api-2025-04-14"].toString()},Y?.headers])})}upload($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/files",d2({body:J,...Z,headers:L([{"anthropic-beta":[...Y??[],"files-api-2025-04-14"].toString()},f7(J.file),Z?.headers])},this._client))}}class S$ extends k{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(I`/v1/models/${$}?beta=true`,{...Y,headers:L([{...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",J2,{query:J,...Z,headers:L([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var I1={"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 g7($){return $?.output_format??$?.output_config?.format}function p4($,Z,Y){let J=g7(Z);if(!Z||!("parse"in(J??{})))return{...$,content:$.content.map((X)=>{if(X.type==="text"){let z=Object.defineProperty({...X},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(z,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return X}),parsed_output:null};return l4($,Z,Y)}function l4($,Z,Y){let J=null,X=$.content.map((z)=>{if(z.type==="text"){let Q=K3(Z,z.text);if(J===null)J=Q;let K=Object.defineProperty({...z},"parsed_output",{value:Q,enumerable:!1});return Object.defineProperty(K,"parsed",{get(){return Y.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),Q},enumerable:!1})}return z});return{...$,content:X,parsed_output:J}}function K3($,Z){let Y=g7($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(J){throw new M(`Failed to parse structured output: ${J}`)}}var G3=($)=>{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 K="",G=!1;J=$[++Z];while(J!=='"'){if(Z===$.length){G=!0;break}if(J==="\\"){if(Z++,Z===$.length){G=!0;break}K+=J+$[Z],J=$[++Z]}else K+=J,J=$[++Z]}if(J=$[++Z],!G)Y.push({type:"string",value:K});continue}if(J&&/\s/.test(J)){Z++;continue}let z=/[0-9]/;if(J&&z.test(J)||J==="-"||J==="."){let K="";if(J==="-")K+=J,J=$[++Z];while(J&&z.test(J)||J===".")K+=J,J=$[++Z];Y.push({type:"number",value:K});continue}let Q=/[a-z]/i;if(J&&Q.test(J)){let K="";while(J&&Q.test(J)){if(Z===$.length)break;K+=J,J=$[++Z]}if(K=="true"||K=="false"||K==="null")Y.push({type:"name",value:K});else{Z++;continue}continue}Z++}return Y},m2=($)=>{if($.length===0)return $;let Z=$[$.length-1];switch(Z.type){case"separator":return $=$.slice(0,$.length-1),m2($);break;case"number":let Y=Z.value[Z.value.length-1];if(Y==="."||Y==="-")return $=$.slice(0,$.length-1),m2($);case"string":let J=$[$.length-2];if(J?.type==="delimiter")return $=$.slice(0,$.length-1),m2($);else if(J?.type==="brace"&&J.value==="{")return $=$.slice(0,$.length-1),m2($);break;case"delimiter":return $=$.slice(0,$.length-1),m2($);break}return $},W3=($)=>{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 $},q3=($)=>{let Z="";return $.map((Y)=>{switch(Y.type){case"string":Z+='"'+Y.value+'"';break;default:Z+=Y.value;break}}),Z},S1=($)=>JSON.parse(q3(W3(m2(G3($)))));var $2,O2,u2,k$,k1,b$,y$,b1,_$,H2,f$,y1,_1,b2,f1,h1,h$,i4,c7,v1,n4,o4,a4,d7,m7="__json_buf";function u7($){return $.type==="tool_use"||$.type==="server_tool_use"||$.type==="mcp_tool_use"}class v${constructor($,Z){$2.add(this),this.messages=[],this.receivedMessages=[],O2.set(this,void 0),u2.set(this,null),this.controller=new AbortController,k$.set(this,void 0),k1.set(this,()=>{}),b$.set(this,()=>{}),y$.set(this,void 0),b1.set(this,()=>{}),_$.set(this,()=>{}),H2.set(this,{}),f$.set(this,!1),y1.set(this,!1),_1.set(this,!1),b2.set(this,!1),f1.set(this,void 0),h1.set(this,void 0),h$.set(this,void 0),v1.set(this,(Y)=>{if(j(this,y1,!0,"f"),W2(Y))Y=new u;if(Y instanceof u)return j(this,_1,!0,"f"),this._emit("abort",Y);if(Y instanceof M)return this._emit("error",Y);if(Y instanceof Error){let J=new M(Y.message);return J.cause=Y,this._emit("error",J)}return this._emit("error",new M(String(Y)))}),j(this,k$,new Promise((Y,J)=>{j(this,k1,Y,"f"),j(this,b$,J,"f")}),"f"),j(this,y$,new Promise((Y,J)=>{j(this,b1,Y,"f"),j(this,_$,J,"f")}),"f"),q(this,k$,"f").catch(()=>{}),q(this,y$,"f").catch(()=>{}),j(this,u2,$,"f"),j(this,h$,Z?.logger??console,"f")}get response(){return q(this,f1,"f")}get request_id(){return q(this,h1,"f")}async withResponse(){j(this,b2,!0,"f");let $=await q(this,k$,"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 v$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let X=new v$(Z,{logger:J});for(let z of Z.messages)X._addMessageParam(z);return j(X,u2,{...Z,stream:!0},"f"),X._run(()=>X._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),X}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},q(this,v1,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let J=Y?.signal,X;if(J){if(J.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),J.addEventListener("abort",X)}try{q(this,$2,"m",n4).call(this);let{response:z,data:Q}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let K of Q)q(this,$2,"m",o4).call(this,K);if(Q.controller.signal?.aborted)throw new u;q(this,$2,"m",a4).call(this)}finally{if(J&&X)J.removeEventListener("abort",X)}}_connected($){if(this.ended)return;j(this,f1,$,"f"),j(this,h1,$?.headers.get("request-id"),"f"),q(this,k1,"f").call(this,$),this._emit("connect")}get ended(){return q(this,f$,"f")}get errored(){return q(this,y1,"f")}get aborted(){return q(this,_1,"f")}abort(){this.controller.abort()}on($,Z){return(q(this,H2,"f")[$]||(q(this,H2,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=q(this,H2,"f")[$];if(!Y)return this;let J=Y.findIndex((X)=>X.listener===Z);if(J>=0)Y.splice(J,1);return this}once($,Z){return(q(this,H2,"f")[$]||(q(this,H2,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(j(this,b2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){j(this,b2,!0,"f"),await q(this,y$,"f")}get currentMessage(){return q(this,O2,"f")}async finalMessage(){return await this.done(),q(this,$2,"m",i4).call(this)}async finalText(){return await this.done(),q(this,$2,"m",c7).call(this)}_emit($,...Z){if(q(this,f$,"f"))return;if($==="end")j(this,f$,!0,"f"),q(this,b1,"f").call(this);let Y=q(this,H2,"f")[$];if(Y)q(this,H2,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!q(this,b2,"f")&&!Y?.length)Promise.reject(J);q(this,b$,"f").call(this,J),q(this,_$,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!q(this,b2,"f")&&!Y?.length)Promise.reject(J);q(this,b$,"f").call(this,J),q(this,_$,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",q(this,$2,"m",i4).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{q(this,$2,"m",n4).call(this),this._connected(null);let X=r.fromReadableStream($,this.controller);for await(let z of X)q(this,$2,"m",o4).call(this,z);if(X.controller.signal?.aborted)throw new u;q(this,$2,"m",a4).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(O2=new WeakMap,u2=new WeakMap,k$=new WeakMap,k1=new WeakMap,b$=new WeakMap,y$=new WeakMap,b1=new WeakMap,_$=new WeakMap,H2=new WeakMap,f$=new WeakMap,y1=new WeakMap,_1=new WeakMap,b2=new WeakMap,f1=new WeakMap,h1=new WeakMap,h$=new WeakMap,v1=new WeakMap,$2=new WeakSet,i4=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},c7=function(){if(this.receivedMessages.length===0)throw new M("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 M("stream ended without producing a content block with type=text");return Z.join(" ")},n4=function(){if(this.ended)return;j(this,O2,void 0,"f")},o4=function(Z){if(this.ended)return;let Y=q(this,$2,"m",d7).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(u7(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:p7(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(p4(Y,q(this,u2,"f"),{logger:q(this,h$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{j(this,O2,Y,"f");break}case"content_block_start":case"message_delta":break}},a4=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");let Z=q(this,O2,"f");if(!Z)throw new M("request ended without sending any chunks");return j(this,O2,void 0,"f"),p4(Z,q(this,u2,"f"),{logger:q(this,h$,"f")})},d7=function(Z){let Y=q(this,O2,"f");if(Z.type==="message_start"){if(Y)throw new M(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new M(`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&&u7(J)){let X=J[m7]||"";X+=Z.delta.partial_json;let z={...J};if(Object.defineProperty(z,m7,{value:X,enumerable:!1,writable:!0}),X)try{z.input=S1(X)}catch(Q){let K=new M(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${Q}. JSON: ${X}`);q(this,v1,"f").call(this,K)}Y.content[Z.index]=z}break}case"thinking_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,thinking:J.thinking+Z.delta.thinking};break}case"signature_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,signature:Z.delta.signature};break}case"compaction_delta":{if(J?.type==="compaction")Y.content[Z.index]={...J,content:(J.content||"")+Z.delta.content};break}default:p7(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(J)=>{let X=Z.shift();if(X)X.resolve(J);else $.push(J)}),this.on("end",()=>{Y=!0;for(let J of Z)J.resolve(void 0);Z.length=0}),this.on("abort",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),this.on("error",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((X,z)=>Z.push({resolve:X,reject:z})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new r(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function p7($){}class p2 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 l7=1e5,i7=`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:
55
+ 1. Task Overview
56
+ The user's core request and success criteria
57
+ Any clarifications or constraints they specified
58
+ 2. Current State
59
+ What has been completed so far
60
+ Files created, modified, or analyzed (with paths if relevant)
61
+ Key outputs or artifacts produced
62
+ 3. Important Discoveries
63
+ Technical constraints or requirements uncovered
64
+ Decisions made and their rationale
65
+ Errors encountered and how they were resolved
66
+ What approaches were tried that didn't work (and why)
67
+ 4. Next Steps
68
+ Specific actions needed to complete the task
69
+ Any blockers or open questions to resolve
70
+ Priority order if multiple steps remain
71
+ 5. Context to Preserve
72
+ User preferences or style requirements
73
+ Domain-specific details that aren't obvious
74
+ Any promises made to the user
75
+ 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.
76
+ Wrap your summary in <summary></summary> tags.`;var g$,l2,y2,h,c$,s,U2,M2,d$,n7,r4;function o7(){let $,Z;return{promise:new Promise((J,X)=>{$=J,Z=X}),resolve:$,reject:Z}}class m${constructor($,Z,Y){g$.add(this),this.client=$,l2.set(this,!1),y2.set(this,!1),h.set(this,void 0),c$.set(this,void 0),s.set(this,void 0),U2.set(this,void 0),M2.set(this,void 0),d$.set(this,0),j(this,h,{params:{...Z,messages:structuredClone(Z.messages)}},"f");let X=["BetaToolRunner",...u4(Z.tools,Z.messages)].join(", ");j(this,c$,{...Y,headers:L([{"x-stainless-helper":X},Y?.headers])},"f"),j(this,M2,o7(),"f")}async*[(l2=new WeakMap,y2=new WeakMap,h=new WeakMap,c$=new WeakMap,s=new WeakMap,U2=new WeakMap,M2=new WeakMap,d$=new WeakMap,g$=new WeakSet,n7=async function(){let Z=q(this,h,"f").params.compactionControl;if(!Z||!Z.enabled)return!1;let Y=0;if(q(this,s,"f")!==void 0)try{let G=await q(this,s,"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??l7;if(Y<J)return!1;let X=Z.model??q(this,h,"f").params.model,z=Z.summaryPrompt??i7,Q=q(this,h,"f").params.messages;if(Q[Q.length-1].role==="assistant"){let G=Q[Q.length-1];if(Array.isArray(G.content)){let H=G.content.filter((V)=>V.type!=="tool_use");if(H.length===0)Q.pop();else G.content=H}}let K=await this.client.beta.messages.create({model:X,messages:[...Q,{role:"user",content:[{type:"text",text:z}]}],max_tokens:q(this,h,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(K.content[0]?.type!=="text")throw new M("Expected text response for compaction");return q(this,h,"f").params.messages=[{role:"user",content:K.content}],!0},Symbol.asyncIterator)](){var $;if(q(this,l2,"f"))throw new M("Cannot iterate over a consumed stream");j(this,l2,!0,"f"),j(this,y2,!0,"f"),j(this,U2,void 0,"f");try{while(!0){let Z;try{if(q(this,h,"f").params.max_iterations&&q(this,d$,"f")>=q(this,h,"f").params.max_iterations)break;j(this,y2,!1,"f"),j(this,U2,void 0,"f"),j(this,d$,($=q(this,d$,"f"),$++,$),"f"),j(this,s,void 0,"f");let{max_iterations:Y,compactionControl:J,...X}=q(this,h,"f").params;if(X.stream)Z=this.client.beta.messages.stream({...X},q(this,c$,"f")),j(this,s,Z.finalMessage(),"f"),q(this,s,"f").catch(()=>{}),yield Z;else j(this,s,this.client.beta.messages.create({...X,stream:!1},q(this,c$,"f")),"f"),yield q(this,s,"f");if(!await q(this,g$,"m",n7).call(this)){if(!q(this,y2,"f")){let{role:K,content:G}=await q(this,s,"f");q(this,h,"f").params.messages.push({role:K,content:G})}let Q=await q(this,g$,"m",r4).call(this,q(this,h,"f").params.messages.at(-1));if(Q)q(this,h,"f").params.messages.push(Q);else if(!q(this,y2,"f"))break}}finally{if(Z)Z.abort()}}if(!q(this,s,"f"))throw new M("ToolRunner concluded without a message from the server");q(this,M2,"f").resolve(await q(this,s,"f"))}catch(Z){throw j(this,l2,!1,"f"),q(this,M2,"f").promise.catch(()=>{}),q(this,M2,"f").reject(Z),j(this,M2,o7(),"f"),Z}}setMessagesParams($){if(typeof $==="function")q(this,h,"f").params=$(q(this,h,"f").params);else q(this,h,"f").params=$;j(this,y2,!0,"f"),j(this,U2,void 0,"f")}async generateToolResponse(){let $=await q(this,s,"f")??this.params.messages.at(-1);if(!$)return null;return q(this,g$,"m",r4).call(this,$)}done(){return q(this,M2,"f").promise}async runUntilDone(){if(!q(this,l2,"f"))for await(let $ of this);return this.done()}get params(){return q(this,h,"f").params}pushMessages(...$){this.setMessagesParams((Z)=>({...Z,messages:[...Z.messages,...$]}))}then($,Z){return this.runUntilDone().then($,Z)}}r4=async function(Z){if(q(this,U2,"f")!==void 0)return q(this,U2,"f");return j(this,U2,H3(q(this,h,"f").params,Z),"f"),q(this,U2,"f")};async function H3($,Z=$.messages.at(-1)){if(!Z||Z.role!=="assistant"||!Z.content||typeof Z.content==="string")return null;let Y=Z.content.filter((X)=>X.type==="tool_use");if(Y.length===0)return null;return{role:"user",content:await Promise.all(Y.map(async(X)=>{let z=$.tools.find((Q)=>("name"in Q?Q.name:Q.mcp_server_name)===X.name);if(!z||!("run"in z))return{type:"tool_result",tool_use_id:X.id,content:`Error: Tool '${X.name}' not found`,is_error:!0};try{let Q=X.input;if("parse"in z&&z.parse)Q=z.parse(Q);let K=await z.run(Q);return{type:"tool_result",tool_use_id:X.id,content:K}}catch(Q){return{type:"tool_result",tool_use_id:X.id,content:Q instanceof p2?Q.content:`Error: ${Q instanceof Error?Q.message:String(Q)}`,is_error:!0}}}))}}class i2{constructor($,Z){this.iterator=$,this.controller=Z}async*decoder(){let $=new j2;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 M("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 M("Attempted to iterate over a response with no body")}return new i2(L$($.body),Z)}}class u$ extends k{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/messages/batches?beta=true",{body:J,...Z,headers:L([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(I`/v1/messages/batches/${$}?beta=true`,{...Y,headers:L([{"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",J2,{query:J,...Z,headers:L([{"anthropic-beta":[...Y??[],"message-batches-2024-09-24"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(I`/v1/messages/batches/${$}?beta=true`,{...Y,headers:L([{"anthropic-beta":[...J??[],"message-batches-2024-09-24"].toString()},Y?.headers])})}cancel($,Z={},Y){let{betas:J}=Z??{};return this._client.post(I`/v1/messages/batches/${$}/cancel?beta=true`,{...Y,headers:L([{"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 M(`No batch \`results_url\`; Has it finished processing? ${J.processing_status} - ${J.id}`);let{betas:X}=Z??{};return this._client.get(J.results_url,{...Y,headers:L([{"anthropic-beta":[...X??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},Y?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((z,Q)=>i2.fromResponse(Q.response,Q.controller))}}var a7={"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"},C3=["claude-opus-4-6"];class F2 extends k{constructor(){super(...arguments);this.batches=new u$(this._client)}create($,Z){let Y=r7($),{betas:J,...X}=Y;if(X.model in a7)console.warn(`The model '${X.model}' is deprecated and will reach end-of-life on ${a7[X.model]}
77
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if(X.model in C3&&X.thinking&&X.thinking.type==="enabled")console.warn(`Using Claude with ${X.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let z=this._client._options.timeout;if(!X.stream&&z==null){let K=I1[X.model]??void 0;z=this._client.calculateNonstreamingTimeout(X.max_tokens,K)}let Q=P1(X.tools,X.messages);return this._client.post("/v1/messages?beta=true",{body:X,timeout:z??600000,...Z,headers:L([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Q,Z?.headers]),stream:Y.stream??!1})}parse($,Z){return Z={...Z,headers:L([{"anthropic-beta":[...$.betas??[],"structured-outputs-2025-12-15"].toString()},Z?.headers])},this.create($,Z).then((Y)=>l4(Y,$,{logger:this._client.logger??console}))}stream($,Z){return v$.createMessage(this,$,Z)}countTokens($,Z){let Y=r7($),{betas:J,...X}=Y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:X,...Z,headers:L([{"anthropic-beta":[...J??[],"token-counting-2024-11-01"].toString()},Z?.headers])})}toolRunner($,Z){return new m$(this._client,$,Z)}}function r7($){if(!$.output_format)return $;if($.output_config?.format)throw new M("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}}}F2.Batches=u$;F2.BetaToolRunner=m$;F2.ToolError=p2;class p$ extends k{create($,Z={},Y){let{betas:J,...X}=Z??{};return this._client.post(I`/v1/skills/${$}/versions?beta=true`,d2({body:X,...Y,headers:L([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])},this._client))}retrieve($,Z,Y){let{skill_id:J,betas:X}=Z;return this._client.get(I`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:L([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($,Z={},Y){let{betas:J,...X}=Z??{};return this._client.getAPIList(I`/v1/skills/${$}/versions?beta=true`,w$,{query:X,...Y,headers:L([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}delete($,Z,Y){let{skill_id:J,betas:X}=Z;return this._client.delete(I`/v1/skills/${J}/versions/${$}?beta=true`,{...Y,headers:L([{"anthropic-beta":[...X??[],"skills-2025-10-02"].toString()},Y?.headers])})}}class n2 extends k{constructor(){super(...arguments);this.versions=new p$(this._client)}create($={},Z){let{betas:Y,...J}=$??{};return this._client.post("/v1/skills?beta=true",d2({body:J,...Z,headers:L([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])},this._client,!1))}retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(I`/v1/skills/${$}?beta=true`,{...Y,headers:L([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/skills?beta=true",w$,{query:J,...Z,headers:L([{"anthropic-beta":[...Y??[],"skills-2025-10-02"].toString()},Z?.headers])})}delete($,Z={},Y){let{betas:J}=Z??{};return this._client.delete(I`/v1/skills/${$}?beta=true`,{...Y,headers:L([{"anthropic-beta":[...J??[],"skills-2025-10-02"].toString()},Y?.headers])})}}n2.Versions=p$;class z2 extends k{constructor(){super(...arguments);this.models=new S$(this._client),this.messages=new F2(this._client),this.files=new I$(this._client),this.skills=new n2(this._client)}}z2.Models=S$;z2.Messages=F2;z2.Files=I$;z2.Skills=n2;class o2 extends k{create($,Z){let{betas:Y,...J}=$;return this._client.post("/v1/complete",{body:J,timeout:this._client._options.timeout??600000,...Z,headers:L([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers]),stream:$.stream??!1})}}function s7($){return $?.output_config?.format}function s4($,Z,Y){let J=s7(Z);if(!Z||!("parse"in(J??{})))return{...$,content:$.content.map((X)=>{if(X.type==="text")return Object.defineProperty({...X},"parsed_output",{value:null,enumerable:!1});return X}),parsed_output:null};return t4($,Z,Y)}function t4($,Z,Y){let J=null,X=$.content.map((z)=>{if(z.type==="text"){let Q=O3(Z,z.text);if(J===null)J=Q;return Object.defineProperty({...z},"parsed_output",{value:Q,enumerable:!1})}return z});return{...$,content:X,parsed_output:J}}function O3($,Z){let Y=s7($);if(Y?.type!=="json_schema")return null;try{if("parse"in Y)return Y.parse(Z);return JSON.parse(Z)}catch(J){throw new M(`Failed to parse structured output: ${J}`)}}var Z2,E2,a2,l$,g1,i$,n$,c1,o$,C2,a$,d1,m1,_2,u1,p1,r$,e4,t7,$6,Z6,Y6,J6,e7,$8="__json_buf";function Z8($){return $.type==="tool_use"||$.type==="server_tool_use"}class s${constructor($,Z){Z2.add(this),this.messages=[],this.receivedMessages=[],E2.set(this,void 0),a2.set(this,null),this.controller=new AbortController,l$.set(this,void 0),g1.set(this,()=>{}),i$.set(this,()=>{}),n$.set(this,void 0),c1.set(this,()=>{}),o$.set(this,()=>{}),C2.set(this,{}),a$.set(this,!1),d1.set(this,!1),m1.set(this,!1),_2.set(this,!1),u1.set(this,void 0),p1.set(this,void 0),r$.set(this,void 0),$6.set(this,(Y)=>{if(j(this,d1,!0,"f"),W2(Y))Y=new u;if(Y instanceof u)return j(this,m1,!0,"f"),this._emit("abort",Y);if(Y instanceof M)return this._emit("error",Y);if(Y instanceof Error){let J=new M(Y.message);return J.cause=Y,this._emit("error",J)}return this._emit("error",new M(String(Y)))}),j(this,l$,new Promise((Y,J)=>{j(this,g1,Y,"f"),j(this,i$,J,"f")}),"f"),j(this,n$,new Promise((Y,J)=>{j(this,c1,Y,"f"),j(this,o$,J,"f")}),"f"),q(this,l$,"f").catch(()=>{}),q(this,n$,"f").catch(()=>{}),j(this,a2,$,"f"),j(this,r$,Z?.logger??console,"f")}get response(){return q(this,u1,"f")}get request_id(){return q(this,p1,"f")}async withResponse(){j(this,_2,!0,"f");let $=await q(this,l$,"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 s$(null);return Z._run(()=>Z._fromReadableStream($)),Z}static createMessage($,Z,Y,{logger:J}={}){let X=new s$(Z,{logger:J});for(let z of Z.messages)X._addMessageParam(z);return j(X,a2,{...Z,stream:!0},"f"),X._run(()=>X._createMessage($,{...Z,stream:!0},{...Y,headers:{...Y?.headers,"X-Stainless-Helper-Method":"stream"}})),X}_run($){$().then(()=>{this._emitFinal(),this._emit("end")},q(this,$6,"f"))}_addMessageParam($){this.messages.push($)}_addMessage($,Z=!0){if(this.receivedMessages.push($),Z)this._emit("message",$)}async _createMessage($,Z,Y){let J=Y?.signal,X;if(J){if(J.aborted)this.controller.abort();X=this.controller.abort.bind(this.controller),J.addEventListener("abort",X)}try{q(this,Z2,"m",Z6).call(this);let{response:z,data:Q}=await $.create({...Z,stream:!0},{...Y,signal:this.controller.signal}).withResponse();this._connected(z);for await(let K of Q)q(this,Z2,"m",Y6).call(this,K);if(Q.controller.signal?.aborted)throw new u;q(this,Z2,"m",J6).call(this)}finally{if(J&&X)J.removeEventListener("abort",X)}}_connected($){if(this.ended)return;j(this,u1,$,"f"),j(this,p1,$?.headers.get("request-id"),"f"),q(this,g1,"f").call(this,$),this._emit("connect")}get ended(){return q(this,a$,"f")}get errored(){return q(this,d1,"f")}get aborted(){return q(this,m1,"f")}abort(){this.controller.abort()}on($,Z){return(q(this,C2,"f")[$]||(q(this,C2,"f")[$]=[])).push({listener:Z}),this}off($,Z){let Y=q(this,C2,"f")[$];if(!Y)return this;let J=Y.findIndex((X)=>X.listener===Z);if(J>=0)Y.splice(J,1);return this}once($,Z){return(q(this,C2,"f")[$]||(q(this,C2,"f")[$]=[])).push({listener:Z,once:!0}),this}emitted($){return new Promise((Z,Y)=>{if(j(this,_2,!0,"f"),$!=="error")this.once("error",Y);this.once($,Z)})}async done(){j(this,_2,!0,"f"),await q(this,n$,"f")}get currentMessage(){return q(this,E2,"f")}async finalMessage(){return await this.done(),q(this,Z2,"m",e4).call(this)}async finalText(){return await this.done(),q(this,Z2,"m",t7).call(this)}_emit($,...Z){if(q(this,a$,"f"))return;if($==="end")j(this,a$,!0,"f"),q(this,c1,"f").call(this);let Y=q(this,C2,"f")[$];if(Y)q(this,C2,"f")[$]=Y.filter((J)=>!J.once),Y.forEach(({listener:J})=>J(...Z));if($==="abort"){let J=Z[0];if(!q(this,_2,"f")&&!Y?.length)Promise.reject(J);q(this,i$,"f").call(this,J),q(this,o$,"f").call(this,J),this._emit("end");return}if($==="error"){let J=Z[0];if(!q(this,_2,"f")&&!Y?.length)Promise.reject(J);q(this,i$,"f").call(this,J),q(this,o$,"f").call(this,J),this._emit("end")}}_emitFinal(){if(this.receivedMessages.at(-1))this._emit("finalMessage",q(this,Z2,"m",e4).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{q(this,Z2,"m",Z6).call(this),this._connected(null);let X=r.fromReadableStream($,this.controller);for await(let z of X)q(this,Z2,"m",Y6).call(this,z);if(X.controller.signal?.aborted)throw new u;q(this,Z2,"m",J6).call(this)}finally{if(Y&&J)Y.removeEventListener("abort",J)}}[(E2=new WeakMap,a2=new WeakMap,l$=new WeakMap,g1=new WeakMap,i$=new WeakMap,n$=new WeakMap,c1=new WeakMap,o$=new WeakMap,C2=new WeakMap,a$=new WeakMap,d1=new WeakMap,m1=new WeakMap,_2=new WeakMap,u1=new WeakMap,p1=new WeakMap,r$=new WeakMap,$6=new WeakMap,Z2=new WeakSet,e4=function(){if(this.receivedMessages.length===0)throw new M("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},t7=function(){if(this.receivedMessages.length===0)throw new M("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 M("stream ended without producing a content block with type=text");return Z.join(" ")},Z6=function(){if(this.ended)return;j(this,E2,void 0,"f")},Y6=function(Z){if(this.ended)return;let Y=q(this,Z2,"m",e7).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(Z8(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:Y8(Z.delta)}break}case"message_stop":{this._addMessageParam(Y),this._addMessage(s4(Y,q(this,a2,"f"),{logger:q(this,r$,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",Y.content.at(-1));break}case"message_start":{j(this,E2,Y,"f");break}case"content_block_start":case"message_delta":break}},J6=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");let Z=q(this,E2,"f");if(!Z)throw new M("request ended without sending any chunks");return j(this,E2,void 0,"f"),s4(Z,q(this,a2,"f"),{logger:q(this,r$,"f")})},e7=function(Z){let Y=q(this,E2,"f");if(Z.type==="message_start"){if(Y)throw new M(`Unexpected event order, got ${Z.type} before receiving "message_stop"`);return Z.message}if(!Y)throw new M(`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&&Z8(J)){let X=J[$8]||"";X+=Z.delta.partial_json;let z={...J};if(Object.defineProperty(z,$8,{value:X,enumerable:!1,writable:!0}),X)z.input=S1(X);Y.content[Z.index]=z}break}case"thinking_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,thinking:J.thinking+Z.delta.thinking};break}case"signature_delta":{if(J?.type==="thinking")Y.content[Z.index]={...J,signature:Z.delta.signature};break}default:Y8(Z.delta)}return Y}case"content_block_stop":return Y}},Symbol.asyncIterator)](){let $=[],Z=[],Y=!1;return this.on("streamEvent",(J)=>{let X=Z.shift();if(X)X.resolve(J);else $.push(J)}),this.on("end",()=>{Y=!0;for(let J of Z)J.resolve(void 0);Z.length=0}),this.on("abort",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),this.on("error",(J)=>{Y=!0;for(let X of Z)X.reject(J);Z.length=0}),{next:async()=>{if(!$.length){if(Y)return{value:void 0,done:!0};return new Promise((X,z)=>Z.push({resolve:X,reject:z})).then((X)=>X?{value:X,done:!1}:{value:void 0,done:!0})}return{value:$.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new r(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Y8($){}class t$ extends k{create($,Z){return this._client.post("/v1/messages/batches",{body:$,...Z})}retrieve($,Z){return this._client.get(I`/v1/messages/batches/${$}`,Z)}list($={},Z){return this._client.getAPIList("/v1/messages/batches",J2,{query:$,...Z})}delete($,Z){return this._client.delete(I`/v1/messages/batches/${$}`,Z)}cancel($,Z){return this._client.post(I`/v1/messages/batches/${$}/cancel`,Z)}async results($,Z){let Y=await this.retrieve($);if(!Y.results_url)throw new M(`No batch \`results_url\`; Has it finished processing? ${Y.processing_status} - ${Y.id}`);return this._client.get(Y.results_url,{...Z,headers:L([{Accept:"application/binary"},Z?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((J,X)=>i2.fromResponse(X.response,X.controller))}}class f2 extends k{constructor(){super(...arguments);this.batches=new t$(this._client)}create($,Z){if($.model in J8)console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${J8[$.model]}
78
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);if($.model in F3&&$.thinking&&$.thinking.type==="enabled")console.warn(`Using Claude with ${$.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);let Y=this._client._options.timeout;if(!$.stream&&Y==null){let X=I1[$.model]??void 0;Y=this._client.calculateNonstreamingTimeout($.max_tokens,X)}let J=P1($.tools,$.messages);return this._client.post("/v1/messages",{body:$,timeout:Y??600000,...Z,headers:L([J,Z?.headers]),stream:$.stream??!1})}parse($,Z){return this.create($,Z).then((Y)=>t4(Y,$,{logger:this._client.logger??console}))}stream($,Z){return s$.createMessage(this,$,Z,{logger:this._client.logger??console})}countTokens($,Z){return this._client.post("/v1/messages/count_tokens",{body:$,...Z})}}var J8={"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"},F3=["claude-opus-4-6"];f2.Batches=t$;class r2 extends k{retrieve($,Z={},Y){let{betas:J}=Z??{};return this._client.get(I`/v1/models/${$}`,{...Y,headers:L([{...J?.toString()!=null?{"anthropic-beta":J?.toString()}:void 0},Y?.headers])})}list($={},Z){let{betas:Y,...J}=$??{};return this._client.getAPIList("/v1/models",J2,{query:J,...Z,headers:L([{...Y?.toString()!=null?{"anthropic-beta":Y?.toString()}:void 0},Z?.headers])})}}var e$=($)=>{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 X6,z6,l1,X8,z8="\\n\\nHuman:",Q8="\\n\\nAssistant:";class y{constructor({baseURL:$=e$("ANTHROPIC_BASE_URL"),apiKey:Z=e$("ANTHROPIC_API_KEY")??null,authToken:Y=e$("ANTHROPIC_AUTH_TOKEN")??null,...J}={}){X6.add(this),l1.set(this,void 0);let X={apiKey:Z,authToken:Y,...J,baseURL:$||"https://api.anthropic.com"};if(!X.dangerouslyAllowBrowser&&E7())throw new M(`It looks like you're running in a browser-like environment.
79
+
80
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
81
+ If you understand the risks and have appropriate mitigations in place,
82
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
83
+
84
+ new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
85
+ `);this.baseURL=X.baseURL,this.timeout=X.timeout??z6.DEFAULT_TIMEOUT,this.logger=X.logger??console;let z="warn";this.logLevel=z,this.logLevel=f4(X.logLevel,"ClientOptions.logLevel",this)??f4(e$("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??z,this.fetchOptions=X.fetchOptions,this.maxRetries=X.maxRetries??2,this.fetch=X.fetch??x7(),j(this,l1,R7,"f"),this._options=X,this.apiKey=typeof Z==="string"?Z:null,this.authToken=Y}withOptions($){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...$})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:$,nulls:Z}){if($.get("x-api-key")||$.get("authorization"))return;if(this.apiKey&&$.get("x-api-key"))return;if(Z.has("x-api-key"))return;if(this.authToken&&$.get("authorization"))return;if(Z.has("authorization"))return;throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders($){return L([await this.apiKeyAuth($),await this.bearerAuth($)])}async apiKeyAuth($){if(this.apiKey==null)return;return L([{"X-Api-Key":this.apiKey}])}async bearerAuth($){if(this.authToken==null)return;return L([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery($){return A7($)}getUserAgent(){return`${this.constructor.name}/JS ${N2}`}defaultIdempotencyKey(){return`stainless-node-retry-${I4()}`}makeStatusError($,Z,Y,J){return f.generate($,Z,Y,J)}buildURL($,Z,Y){let J=!q(this,X6,"m",X8).call(this)&&Y||this.baseURL,X=C7($)?new URL($):new URL(J+(J.endsWith("/")&&$.startsWith("/")?$.slice(1):$)),z=this.defaultQuery(),Q=Object.fromEntries(X.searchParams);if(!b4(z)||!b4(Q))Z={...Q,...z,...Z};if(typeof Z==="object"&&Z&&!Array.isArray(Z))X.search=this.stringifyQuery(Z);return X.toString()}_calculateNonstreamingTimeout($){if(3600*$/128000>600)throw new M("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 S2(this,this.makeRequest($,Z,void 0))}async makeRequest($,Z,Y){let J=await $,X=J.maxRetries??this.maxRetries;if(Z==null)Z=X;await this.prepareOptions(J);let{req:z,url:Q,timeout:K}=await this.buildRequest(J,{retryCount:X-Z});await this.prepareRequest(z,{url:Q,options:J});let G="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),H=Y===void 0?"":`, retryOf: ${Y}`,V=Date.now();if(c(this).debug(`[${G}] sending request`,q2({retryOfRequestLogID:Y,method:J.method,url:Q,options:J,headers:z.headers})),J.signal?.aborted)throw new u;let O=new AbortController,B=await this.fetchWithTimeout(Q,z,K,O).catch(H$),E=Date.now();if(B instanceof globalThis.Error){let g=`retrying, ${Z} attempts remaining`;if(J.signal?.aborted)throw new u;let e=W2(B)||/timed? ?out/i.test(String(B)+("cause"in B?String(B.cause):""));if(Z)return c(this).info(`[${G}] connection ${e?"timed out":"failed"} - ${g}`),c(this).debug(`[${G}] connection ${e?"timed out":"failed"} (${g})`,q2({retryOfRequestLogID:Y,url:Q,durationMs:E-V,message:B.message})),this.retryRequest(J,Z,Y??G);if(c(this).info(`[${G}] connection ${e?"timed out":"failed"} - error; no more retries left`),c(this).debug(`[${G}] connection ${e?"timed out":"failed"} (error; no more retries left)`,q2({retryOfRequestLogID:Y,url:Q,durationMs:E-V,message:B.message})),e)throw new U$;throw new I2({cause:B})}let R=[...B.headers.entries()].filter(([g])=>g==="request-id").map(([g,e])=>", "+g+": "+JSON.stringify(e)).join(""),v=`[${G}${H}${R}] ${z.method} ${Q} ${B.ok?"succeeded":"failed"} with status ${B.status} in ${E-V}ms`;if(!B.ok){let g=await this.shouldRetry(B);if(Z&&g){let W=`retrying, ${Z} attempts remaining`;return await D7(B.body),c(this).info(`${v} - ${W}`),c(this).debug(`[${G}] response error (${W})`,q2({retryOfRequestLogID:Y,url:B.url,status:B.status,headers:B.headers,durationMs:E-V})),this.retryRequest(J,Z,Y??G,B.headers)}let e=g?"error; no more retries left":"error; not retryable";c(this).info(`${v} - ${e}`);let S=await B.text().catch((W)=>H$(W).message),l=F1(S),n=l?void 0:S;throw c(this).debug(`[${G}] response error (${e})`,q2({retryOfRequestLogID:Y,url:B.url,status:B.status,headers:B.headers,message:n,durationMs:Date.now()-V})),this.makeStatusError(B.status,l,n,B.headers)}return c(this).info(v),c(this).debug(`[${G}] response start`,q2({retryOfRequestLogID:Y,url:B.url,status:B.status,headers:B.headers,durationMs:E-V})),{response:B,options:J,controller:O,requestLogID:G,retryOfRequestLogID:Y,startTime:V}}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 A1(this,Y,$)}async fetchWithTimeout($,Z,Y,J){let{signal:X,method:z,...Q}=Z||{},K=this._makeAbort(J);if(X)X.addEventListener("abort",K,{once:!0});let G=setTimeout(K,Y),H=globalThis.ReadableStream&&Q.body instanceof globalThis.ReadableStream||typeof Q.body==="object"&&Q.body!==null&&Symbol.asyncIterator in Q.body,V={signal:J.signal,...H?{duplex:"half"}:{},method:"GET",...Q};if(z)V.method=z.toUpperCase();try{return await this.fetch.call(void 0,$,V)}finally{clearTimeout(G)}}async shouldRetry($){let Z=$.headers.get("x-should-retry");if(Z==="true")return!0;if(Z==="false")return!1;if($.status===408)return!0;if($.status===409)return!0;if($.status===429)return!0;if($.status>=500)return!0;return!1}async retryRequest($,Z,Y,J){let X,z=J?.get("retry-after-ms");if(z){let K=parseFloat(z);if(!Number.isNaN(K))X=K}let Q=J?.get("retry-after");if(Q&&!X){let K=parseFloat(Q);if(!Number.isNaN(K))X=K*1000;else X=Date.parse(Q)-Date.now()}if(X===void 0){let K=$.maxRetries??this.maxRetries;X=this.calculateDefaultRetryTimeoutMillis(Z,K)}return await j7(X),this.makeRequest($,Z-1,Y)}calculateDefaultRetryTimeoutMillis($,Z){let X=Z-$,z=Math.min(0.5*Math.pow(2,X),8),Q=1-Math.random()*0.25;return z*Q*1000}calculateNonstreamingTimeout($,Z){if(3600000*$/128000>600000||Z!=null&&$>Z)throw new M("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 600000}async buildRequest($,{retryCount:Z=0}={}){let Y={...$},{method:J,path:X,query:z,defaultBaseURL:Q}=Y,K=this.buildURL(X,z,Q);if("timeout"in Y)N7("timeout",Y.timeout);Y.timeout=Y.timeout??this.timeout;let{bodyHeaders:G,body:H}=this.buildBody({options:Y}),V=await this.buildHeaders({options:$,method:J,bodyHeaders:G,retryCount:Z});return{req:{method:J,headers:V,...Y.signal&&{signal:Y.signal},...globalThis.ReadableStream&&H instanceof globalThis.ReadableStream&&{duplex:"half"},...H&&{body:H},...this.fetchOptions??{},...Y.fetchOptions??{}},url:K,timeout:Y.timeout}}async buildHeaders({options:$,method:Z,bodyHeaders:Y,retryCount:J}){let X={};if(this.idempotencyHeader&&Z!=="get"){if(!$.idempotencyKey)$.idempotencyKey=this.defaultIdempotencyKey();X[this.idempotencyHeader]=$.idempotencyKey}let z=L([X,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(J),...$.timeout?{"X-Stainless-Timeout":String(Math.trunc($.timeout/1000))}:{},...L7(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders($),this._options.defaultHeaders,Y,$.headers]);return this.validateHeaders(z),z.values}_makeAbort($){return()=>$.abort()}buildBody({options:{body:$,headers:Z}}){if(!$)return{bodyHeaders:void 0,body:void 0};let Y=L([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:E1($)};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 q(this,l1,"f").call(this,{body:$,headers:Y})}}z6=y,l1=new WeakMap,X6=new WeakSet,X8=function(){return this.baseURL!=="https://api.anthropic.com"};y.Anthropic=z6;y.HUMAN_PROMPT=z8;y.AI_PROMPT=Q8;y.DEFAULT_TIMEOUT=600000;y.AnthropicError=M;y.APIError=f;y.APIConnectionError=I2;y.APIConnectionTimeoutError=U$;y.APIUserAbortError=u;y.NotFoundError=j$;y.ConflictError=O$;y.RateLimitError=F$;y.BadRequestError=C$;y.AuthenticationError=B$;y.InternalServerError=E$;y.PermissionDeniedError=N$;y.UnprocessableEntityError=M$;y.toFile=w1;class Q2 extends y{constructor(){super(...arguments);this.completions=new o2(this),this.messages=new f2(this),this.models=new r2(this),this.beta=new z2(this)}}Q2.Completions=o2;Q2.Messages=f2;Q2.Models=r2;Q2.Beta=z2;import{existsSync as V1,readdirSync as T5,readFileSync as S6,writeFileSync as P5,renameSync as I5,statSync as z0,realpathSync as S5}from"fs";import{resolve as g2,join as k6,sep as N4,dirname as k5}from"path";import{randomUUID as b5}from"crypto";import{existsSync as L3,readFileSync as x3,writeFileSync as D3}from"fs";import{basename as Q6}from"path";var V8=50;class V6{entries=[];saveState($){let Z=L3($),Y=Z?x3($,"utf-8"):"";if(this.entries.push({path:$,content:Y,timestamp:Date.now(),existed:Z}),this.entries.length>V8)this.entries=this.entries.slice(-V8)}undo(){let $=this.entries.pop();if(!$)return null;if(!$.existed)return`Undo: ${Q6($.path)} was a new file. Remove it manually if needed.`;D3($.path,$.content);let Z=$.content.split(`
86
+ `).length;return`Undo: restored ${Q6($.path)} (${Z} lines, from ${K8($.timestamp)})`}get size(){return this.entries.length}peek(){if(this.entries.length===0)return null;let $=this.entries[this.entries.length-1];return`${Q6($.path)} (${K8($.timestamp)})`}}function K8($){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 G8,readdirSync as R3,readFileSync as A3,mkdirSync as w3}from"fs";import{join as K6}from"path";function W8($){if(!G8($))return[];let Z=[],Y=R3($).filter((J)=>J.endsWith(".json"));for(let J of Y)try{let X=JSON.parse(A3(K6($,J),"utf-8"));if(!X.name||!X.description||!X.command)continue;if(typeof X.name!=="string"||typeof X.command!=="string")continue;if(X.command.includes("$(")||X.command.includes("`"))continue;Z.push({name:X.name,description:X.description,inputSchema:X.input_schema||{type:"object",properties:{},required:[]},command:X.command,source:K6($,J)})}catch{}return Z}function q8($){return $.map((Z)=>({name:Z.name,description:Z.description,input_schema:Z.inputSchema}))}async function H8($,Z){let Y=$.command;for(let[V,O]of Object.entries(Z)){let B=String(O).replace(/[;&|`$()]/g,"");Y=Y.replace(new RegExp(`\\{\\{input\\.${V}\\}\\}`,"g"),B)}Y=Y.replace(/\{\{input\.\w+\}\}/g,"");let J=C1(),X=Bun.spawn([...J,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),z=setTimeout(()=>X.kill(),30000),[Q,K]=await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),G=await X.exited;clearTimeout(z);let H=Q.trim();if(K.trim())H+=(H?`
87
+ `:"")+K.trim();if(G!==0)H+=(H?`
88
+ `:"")+`Exit code: ${G}`;return H||"(no output)"}function U8($){if($.length===0)return"No plugins loaded. Add .json files to ~/.config/tinyclaw/plugins/";return`Plugins:
89
+ `+$.map((Z)=>` ${Z.name} \u2014 ${Z.description}`).join(`
90
+ `)}function C8($){let Z=K6($,"plugins");if(!G8(Z))w3(Z,{recursive:!0});return Z}var T3=/[";`$\n\r|&<>{}()]/;function W6($,Z){if(!$||typeof $!=="string")return`Error: ${Z} is required.`;if($.length>500)return`Error: ${Z} too long (max 500 chars).`;if(T3.test($))return`Error: ${Z} contains invalid characters. Avoid: " ; \` $ | & < > { } ( ) and newlines.`;return null}var P3=15000;async function s2($){let Z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",$],{stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>Z.kill(),P3),[J,X]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),z=await Z.exited;return clearTimeout(Y),{stdout:J,stderr:X,exitCode:z}}var G6={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 t2($,Z){if(!D)return"Error: this command is only available on Windows.";let Y=$.toLowerCase().replace(/\s+/g,""),J=G6[Y];if(!J){let z=Object.keys(G6).join(", ");return`Unknown app: "${$}". Available: ${z}`}if(Z){let z=W6(Z,"argument");if(z)return z}let X=Z?`Start-Process '${J}' -ArgumentList '${Z}'`:`Start-Process '${J}'`;try{let{exitCode:z,stderr:Q}=await s2(X);if(z!==0&&Q.trim())return`Error opening ${$}: ${Q.trim()}`;return`Opened: ${$}`}catch(z){return`Error opening ${$}: ${z instanceof Error?z.message:String(z)}`}}async function i1($){if(!D)return"Error: this command is only available on Windows.";if(!$.startsWith("http://")&&!$.startsWith("https://"))return"Error: URL must start with http:// or https://";let Z=W6($,"URL");if(Z)return Z;try{let{exitCode:Y,stderr:J}=await s2(`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 n1($){if(!D)return"Error: this command is only available on Windows.";let Z=W6($,"file path");if(Z)return Z;try{let{exitCode:Y,stderr:J}=await s2(`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 o1(){if(!D)return"Error: this command is only available on Windows.";try{let{stdout:Z,stderr:Y}=await s2("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 e2(){if(!D)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 s2($.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 $$(){let $=new Date,Z=[],Y=$.toLocaleDateString("pt-BR",{weekday:"long"}),J=$.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit",year:"numeric"}),X=$.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});Z.push(`${Y}, ${J} \u2014 ${X}`);let z=new Date($.valueOf());z.setDate(z.getDate()+3-(z.getDay()+6)%7);let Q=new Date(z.getFullYear(),0,4),K=1+Math.round(((z.getTime()-Q.getTime())/86400000-3+(Q.getDay()+6)%7)/7);Z.push(`Semana ${K} 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(`
91
+ `)}async function L2(){if(!D)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(`
92
+ `);try{let{stdout:Z}=await s2($);return Z.trim()||"Outlook nao disponivel."}catch{return"Outlook nao disponivel."}}function B8(){return Object.keys(G6)}var N8=[{name:"InfoMoney",url:"https://www.infomoney.com.br/feed/",category:"finance"},{name:"Valor Economico",url:"https://pox.globo.com/rss/valor/",category:"business"},{name:"Bloomberg Linea BR",url:"https://www.bloomberglinea.com.br/feed/",category:"finance"},{name:"TechCrunch",url:"https://techcrunch.com/feed/",category:"tech"},{name:"Hacker News (best)",url:"https://hnrss.org/best",category:"tech"},{name:"The Verge",url:"https://www.theverge.com/rss/index.xml",category:"tech"},{name:"G1",url:"https://g1.globo.com/rss/g1/",category:"brazil"},{name:"Folha",url:"https://feeds.folha.uol.com.br/folha/cotidiano/rss091.xml",category:"brazil"},{name:"BBC World",url:"https://feeds.bbci.co.uk/news/world/rss.xml",category:"world"},{name:"Reuters",url:"https://www.reutersagency.com/feed/",category:"world"}];function I3($,Z,Y){let J=[],X=/<item[\s>]([\s\S]*?)<\/item>/gi,z;while((z=X.exec($))!==null){let Q=z[1],K=j8(Q,Z,Y);if(K)J.push(K);if(J.length>=10)break}if(J.length===0){let Q=/<entry[\s>]([\s\S]*?)<\/entry>/gi;while((z=Q.exec($))!==null){let K=z[1],G=j8(K,Z,Y);if(G)J.push(G);if(J.length>=10)break}}return J}function j8($,Z,Y){let J=$1($,"title");if(!J)return null;let X=$1($,"link")||b3($),z=S3(X),Q=$1($,"pubDate")||$1($,"published")||$1($,"updated"),K;if(Q){let G=new Date(Q);K=isNaN(G.getTime())?void 0:G}return{title:y3(J),link:z,source:Z,category:Y,pubDate:K}}function S3($){if(!$)return"";let Z=$.trim();if(Z.startsWith("https://")||Z.startsWith("http://"))return Z;return""}function k3($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $1($,Z){let Y=k3(Z),X=new RegExp(`<${Y}[^>]*>\\s*<!\\[CDATA\\[([\\s\\S]*?)\\]\\]>\\s*</${Y}>`,"i").exec($);if(X)return X[1].trim();let Q=new RegExp(`<${Y}[^>]*>([\\s\\S]*?)</${Y}>`,"i").exec($);return Q?Q[1].trim():null}function b3($){let Y=/<link[^>]+href="([^"]+)"[^>]*\/?>/i.exec($);return Y?Y[1]:null}function y3($){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 x2($,Z=5){let Y=Math.max(1,Math.min(Z,10));if($&&$.length===0)return q6();let J=$?N8.filter((K)=>$.includes(K.category)):N8,X=await Promise.allSettled(J.map((K)=>f3(K,Y))),z=[],Q=[];for(let K=0;K<X.length;K++){let G=X[K];if(G.status==="fulfilled")z.push(...G.value);else Q.push(`${J[K].name}: ${_3(G.reason)}`)}if(z.length===0)return Q.length>0?`Nenhuma noticia encontrada.
93
+ Falhas: ${Q.join(", ")}`:"Nenhuma noticia encontrada.";return z.sort((K,G)=>{let H=K.pubDate?.getTime()||0;return(G.pubDate?.getTime()||0)-H}),h3(z,Q)}function _3($){if($ instanceof Error){if($.name==="AbortError")return"timeout";return $.message.slice(0,80)}return"unreachable"}async function f3($,Z){let Y=new AbortController,J=setTimeout(()=>Y.abort(),1e4);try{let X=await fetch($.url,{signal:Y.signal,headers:{"User-Agent":"tinyclaw/1.0 (news-radar)",Accept:"application/rss+xml, application/atom+xml, application/xml, text/xml"}});if(clearTimeout(J),!X.ok)return[];let z=X.headers.get("content-length");if(z&&Number(z)>2097152)return[];let Q=X.body?.getReader();if(!Q)return[];let K=[],G=0;while(!0){let{done:O,value:B}=await Q.read();if(O)break;if(G+=B.byteLength,G>2097152)return Q.cancel(),[];K.push(B)}let H=new TextDecoder().decode(Buffer.concat(K));return I3(H,$.name,$.category).slice(0,Z)}catch(X){if(clearTimeout(J),process.env.DEBUG)console.error(`[news] ${$.name}: ${X instanceof Error?X.message:X}`);return[]}}function h3($,Z){let Y={business:"Negocios",tech:"Tecnologia",finance:"Financas",brazil:"Brasil",world:"Mundo"},J=new Map;for(let K of $){let G=J.get(K.category)||[];J.set(K.category,[...G,K])}let X=[],z=["finance","business","tech","brazil","world"];for(let K of z){let G=J.get(K);if(!G||G.length===0)continue;let H=Y[K],V=G.slice(0,8).map((O)=>{let B=O.pubDate?O.pubDate.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit",timeZone:"America/Sao_Paulo"}):"";return` ${B?`[${B}]`:""} ${O.title} (${O.source})`});X.push(`--- ${H} ---
94
+ ${V.join(`
95
+ `)}`)}let Q=X.join(`
96
+
97
+ `);if(Z.length>0)Q+=`
98
+
99
+ (Fontes indisponiveis: ${Z.join(", ")})`;return Q}function q6(){return`Categorias: business, tech, finance, brazil, world
100
+ Uso: /news [categoria]`}import{existsSync as O8,mkdirSync as v3,readFileSync as g3,writeFileSync as c3}from"fs";import{join as d3}from"path";var M8="",_=[],Z$=null,F8=null,E8=()=>d3(M8,"tasks.json");function a1(){c3(E8(),JSON.stringify(_,null,2))}function m3(){let $=E8();if(!O8($)){_=[];return}try{_=JSON.parse(g3($,"utf-8"))}catch{_=[]}}function L8($,Z){if(M8=$,F8=Z,!O8($))v3($,{recursive:!0});if(m3(),Z$)clearInterval(Z$);Z$=setInterval(u3,30000),l3().catch(()=>{})}function x8(){if(Z$)clearInterval(Z$),Z$=null}function r1($,Z){let Y={id:i3(),title:$.trim(),dueAt:Z?Z.toISOString():null,createdAt:new Date().toISOString(),done:!1,notified:!1};if(_=[..._,Y],a1(),Z&&D)H6(Y).catch(()=>{});return Y}function s1($){let Z=$.toLowerCase(),Y=_.find((J)=>J.id===$||J.title.toLowerCase().includes(Z));if(!Y||Y.done)return null;if(_=_.map((J)=>J.id===Y.id?{...J,done:!0}:J),a1(),Y.dueAt&&D)R8(Y.id).catch(()=>{});return _.find((J)=>J.id===Y.id)||null}function D8($){let Z=$.toLowerCase(),Y=_.findIndex((X)=>X.id===$||X.title.toLowerCase().includes(Z));if(Y===-1)return!1;let J=_[Y];if(_=[..._.slice(0,Y),..._.slice(Y+1)],a1(),J.dueAt&&D)R8(J.id).catch(()=>{});return!0}function D2($=!1){return $?[..._]:_.filter((Z)=>!Z.done)}function h2($){if($.length===0)return"Nenhuma tarefa pendente.";let Z=$.map((Y)=>{let J=Y.done?"[x]":"[ ]",X=Y.dueAt?` (${n3(Y.dueAt)})`:"";return` ${J} ${Y.title}${X} [${Y.id}]`});return`Tarefas (${$.length}):
101
+ ${Z.join(`
102
+ `)}`}function Z1($){let Z=new Date,Y=$.toLowerCase().trim(),J=Y.match(/em\s+(\d+)\s*(min|minutos?|h|horas?)/);if(J){let Q=parseInt(J[1]),K=J[2].startsWith("h")?"hours":"minutes",G=new Date(Z);if(K==="hours")G.setHours(G.getHours()+Q);else G.setMinutes(G.getMinutes()+Q);return G}let X=new Date(Z);if(Y.includes("amanha")||Y.includes("amanh\xE3"))X.setDate(X.getDate()+1);let z=Y.match(/(\d{1,2})\s*[h:]\s*(\d{2})?/);if(z){let Q=parseInt(z[1]),K=parseInt(z[2]||"0");if(Q>=0&&Q<=23&&K>=0&&K<=59){if(X.setHours(Q,K,0,0),X<=Z&&!Y.includes("amanha")&&!Y.includes("amanh\xE3"))X.setDate(X.getDate()+1);return X}}return null}function u3(){let $=new Date,Z=!1;for(let Y of _){if(Y.done||Y.notified||!Y.dueAt)continue;let J=new Date(Y.dueAt);if(isNaN(J.getTime()))continue;let X=$.getTime()-J.getTime();if(X>=0&&X<300000)_=_.map((z)=>z.id===Y.id?{...z,notified:!0}:z),Z=!0,p3(Y),F8?.(Y)}if(Z)a1()}async function p3($){if(!D)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">tinyclaw - Lembrete</text><text id="2">${$.title.replace(/'/g,"''")}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)","[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('tinyclaw').Show($toast)"].join("; ");try{let J=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Y],{stdout:"pipe",stderr:"pipe"}),X=setTimeout(()=>J.kill(),1e4);await Promise.all([new Response(J.stdout).text(),new Response(J.stderr).text()]),await J.exited,clearTimeout(X)}catch{}}var U6="tinyclaw-reminder-";async function H6($){if(!$.dueAt)return;let Z=new Date($.dueAt);if(isNaN(Z.getTime())||Z.getTime()<=Date.now())return;let Y=`${U6}${$.id}`,J=[String(Z.getMonth()+1).padStart(2,"0"),String(Z.getDate()).padStart(2,"0"),String(Z.getFullYear())].join("/"),X=[String(Z.getHours()).padStart(2,"0"),String(Z.getMinutes()).padStart(2,"0")].join(":"),Q=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null;","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null;","$x = New-Object Windows.Data.Xml.Dom.XmlDocument;",`$x.LoadXml('<toast><visual><binding template=""ToastText02""><text id=""1"">tinyclaw</text><text id=""2"">${$.title.replace(/'/g,"''").replace(/"/g,"\\\"")}</text></binding></visual><audio src=""ms-winsoundevent:Notification.Reminder""/></toast>');`,"[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('tinyclaw').Show([Windows.UI.Notifications.ToastNotification]::new($x))"].join(" ");try{await Bun.spawn(["schtasks","/Create","/TN",Y,"/SC","ONCE","/SD",J,"/ST",X,"/TR",`powershell -NoProfile -WindowStyle Hidden -Command "${Q}"`,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function R8($){let Z=`${U6}${$}`;try{await Bun.spawn(["schtasks","/Delete","/TN",Z,"/F"],{stdout:"pipe",stderr:"pipe"}).exited}catch{}}async function l3(){if(!D)return;let $=Date.now();for(let Z of _){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",`${U6}${Z.id}`],{stdout:"pipe",stderr:"pipe"}).exited!==0)await H6(Z)}catch{await H6(Z)}}}function i3(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}function n3($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,J=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),X=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate()),z=Z.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"});if(X.getTime()===J.getTime())return`hoje ${z}`;let Q=new Date(J);if(Q.setDate(Q.getDate()+1),X.getTime()===Q.getTime())return`amanha ${z}`;return`${Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})} ${z}`}import{existsSync as A8,mkdirSync as o3,readFileSync as a3,writeFileSync as r3}from"fs";import{join as s3}from"path";var w8="",i=[],T8=()=>s3(w8,"memos.json");function P8(){r3(T8(),JSON.stringify(i,null,2))}function t3(){let $=T8();if(!A8($)){i=[];return}try{i=JSON.parse(a3($,"utf-8"))}catch{i=[]}}function I8($){if(w8=$,!A8($))o3($,{recursive:!0});t3()}function t1($,Z=[]){let Y=new Date().toISOString(),J=$.match(/#(\w+)/g)?.map((Q)=>Q.slice(1).toLowerCase())||[],X=[...new Set([...Z.map((Q)=>Q.toLowerCase()),...J])],z={id:$5(),content:$.trim(),tags:X,createdAt:Y,updatedAt:Y};return i=[...i,z],P8(),z}function S8($){let Z=i.findIndex((Y)=>Y.id===$);if(Z===-1)return!1;return i=[...i.slice(0,Z),...i.slice(Z+1)],P8(),!0}function e1($){let Z=$.toLowerCase().trim();if(!Z)return[...i];let Y=Z.startsWith("#"),J=Y?Z.slice(1):Z;return i.filter((X)=>{if(Y)return X.tags.some((z)=>z.includes(J));return X.content.toLowerCase().includes(J)||X.tags.some((z)=>z.includes(J))}).sort((X,z)=>new Date(z.updatedAt).getTime()-new Date(X.updatedAt).getTime())}function Y1($=20){return[...i].sort((Z,Y)=>new Date(Y.updatedAt).getTime()-new Date(Z.updatedAt).getTime()).slice(0,$)}function e3(){let $=new Map;for(let Z of i)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 v2($){if($.length===0)return"Nenhum memo encontrado.";let Z=$.map((Y)=>{let J=new Date(Y.updatedAt).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.tags.length>0?` [${Y.tags.map((Q)=>`#${Q}`).join(" ")}]`:"",z=Y.content.length>80?Y.content.slice(0,80).replace(/\n/g," ")+"...":Y.content.replace(/\n/g," ");return` [${J}] ${z}${X} {${Y.id}}`});return`Memos (${$.length}):
103
+ ${Z.join(`
104
+ `)}`}function k8(){let $=e3();if($.length===0)return"Nenhuma tag.";return`Tags:
105
+ ${$.map((Y)=>` #${Y.tag} (${Y.count})`).join(`
106
+ `)}`}function $5(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}async function $4($){if(D)return Z5($);return C6($)}async function Z5($){let Z=$.to.replace(/'/g,"''"),Y=$.subject.replace(/'/g,"''"),J=$.body.replace(/'/g,"''").replace(/\n/g,"`n"),X=$.cc?.replace(/'/g,"''")||"",z=["try {"," $outlook = New-Object -ComObject Outlook.Application -ErrorAction Stop"," $mail = $outlook.CreateItem(0)",` $mail.To = '${Z}'`,` $mail.Subject = '${Y}'`,` $mail.Body = '${J}'`,X?` $mail.CC = '${X}'`:""," $mail.Display()",' "Email aberto no Outlook."',"} catch {",' "Outlook nao disponivel. Usando mailto..."',"}"].filter(Boolean).join(`
107
+ `);try{let Q=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",z],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>Q.kill(),15000),[G]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]);await Q.exited,clearTimeout(K);let H=G.trim();if(H.includes("mailto"))return C6($);return H||"Email aberto no Outlook."}catch{return C6($)}}async function C6($){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=D?["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${Y}'`]:["xdg-open",Y],X=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),z=setTimeout(()=>X.kill(),1e4);return await Promise.all([new Response(X.stdout).text(),new Response(X.stderr).text()]),await X.exited,clearTimeout(z),"Email aberto no cliente de email padrao."}catch(J){return`Error: ${J instanceof Error?J.message:String(J)}`}}function Z4($){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(`
108
+ `)}import{existsSync as y8,mkdirSync as Y5,readFileSync as J5,writeFileSync as X5}from"fs";import{join as z5}from"path";var _8="",R2=[],f8=()=>z5(_8,"finance.json");function Q5(){X5(f8(),JSON.stringify(R2,null,2))}function V5(){let $=f8();if(!y8($)){R2=[];return}try{R2=JSON.parse(J5($,"utf-8"))}catch{R2=[]}}function h8($){if(_8=$,!y8($))Y5($,{recursive:!0});V5()}function J1($,Z,Y,J){let X={id:K5(),type:$,amount:Math.abs(Z),category:Y.toLowerCase().trim(),description:J.trim(),date:new Date().toISOString()};return R2=[...R2,X],Q5(),X}function Y4($,Z){let Y=new Date,J=$||Y.getFullYear(),X=Z!==void 0?Z:Y.getMonth(),z=R2.filter((O)=>{let B=new Date(O.date);return B.getFullYear()===J&&B.getMonth()===X});if(z.length===0)return`Nenhuma transacao em ${b8(X)}/${J}.`;let Q=z.filter((O)=>O.type==="entrada").reduce((O,B)=>O+B.amount,0),K=z.filter((O)=>O.type==="saida").reduce((O,B)=>O+B.amount,0),G=Q-K,H=new Map;for(let O of z.filter((B)=>B.type==="saida"))H.set(O.category,(H.get(O.category)||0)+O.amount);let V=[`--- Resumo ${b8(X)}/${J} ---`,`Entradas: R$ ${Q.toFixed(2)}`,`Saidas: R$ ${K.toFixed(2)}`,`Saldo: R$ ${G.toFixed(2)} ${G>=0?"":"(NEGATIVO)"}`];if(H.size>0){V.push(""),V.push("Saidas por categoria:");let O=[...H.entries()].sort((B,E)=>E[1]-B[1]);for(let[B,E]of O){let R=K>0?Math.round(E/K*100):0;V.push(` ${B.padEnd(15)} R$ ${E.toFixed(2)} (${R}%)`)}}return V.join(`
109
+ `)}function B6($=10){let Z=[...R2].sort((J,X)=>new Date(X.date).getTime()-new Date(J.date).getTime()).slice(0,$);if(Z.length===0)return"Nenhuma transacao registrada.";return`Transacoes recentes:
110
+ ${Z.map((J)=>{let X=new Date(J.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),z=J.type==="entrada"?"+":"-";return` [${X}] ${z} R$ ${J.amount.toFixed(2)} ${J.category} \u2014 ${J.description} [${J.id}]`}).join(`
111
+ `)}`}function K5(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}function b8($){return["Jan","Fev","Mar","Abr","Mai","Jun","Jul","Ago","Set","Out","Nov","Dez"][$]||String($+1)}import{existsSync as v8,mkdirSync as G5,readFileSync as W5,writeFileSync as q5}from"fs";import{join as H5}from"path";var g8="",A2=[],c8=()=>H5(g8,"decisions.json");function U5(){q5(c8(),JSON.stringify(A2,null,2))}function C5(){let $=c8();if(!v8($)){A2=[];return}try{A2=JSON.parse(W5($,"utf-8"))}catch{A2=[]}}function d8($){if(g8=$,!v8($))G5($,{recursive:!0});C5()}function m8($,Z,Y,J,X=[]){let z={id:B5(),title:$.trim(),context:Z.trim(),chosen:Y.trim(),alternatives:J?.trim(),tags:X.map((Q)=>Q.toLowerCase()),date:new Date().toISOString()};return A2=[...A2,z],U5(),z}function J4($){let Z=$.toLowerCase();return A2.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 X4($=15){return[...A2].sort((Z,Y)=>new Date(Y.date).getTime()-new Date(Z.date).getTime()).slice(0,$)}function Y$($){if($.length===0)return"Nenhuma decisao registrada.";let Z=$.map((Y)=>{let J=new Date(Y.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"}),X=Y.tags.length>0?` [${Y.tags.join(", ")}]`:"";return` [${J}] ${Y.title}${X} {${Y.id}}`});return`Decisoes (${$.length}):
112
+ ${Z.join(`
113
+ `)}`}function B5(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}z1();import{existsSync as o8,mkdirSync as L5,readFileSync as x5,writeFileSync as D5}from"fs";import{join as R5}from"path";var a8="",A={people:[],interactions:[],delegations:[]},r8=()=>R5(a8,"people.json");function V4(){D5(r8(),JSON.stringify(A,null,2))}function A5(){let $=r8();if(!o8($)){A={people:[],interactions:[],delegations:[]};return}try{let Z=JSON.parse(x5($,"utf-8"));A={people:Z.people||[],interactions:Z.interactions||[],delegations:Z.delegations||[]}}catch{A={people:[],interactions:[],delegations:[]}}}function s8($){if(a8=$,!o8($))L5($,{recursive:!0});A5()}function K4($,Z,Y,J){let X={id:T6(),name:$.trim(),group:Z,role:Y?.trim(),contact:J?.trim(),createdAt:new Date().toISOString()};return A={...A,people:[...A.people,X]},V4(),X}function w2($){let Z=$.toLowerCase();return A.people.find((Y)=>Y.id===$||Y.name.toLowerCase().includes(Z))||null}function G4($){if($)return A.people.filter((Z)=>Z.group===$);return[...A.people]}function t8($,Z,Y,J){let X=w2($);if(!X)return null;let z={id:T6(),personId:X.id,date:new Date().toISOString(),type:Z,summary:Y.trim(),followUpDate:J?.toISOString(),followUpDone:!1};return A={...A,interactions:[...A.interactions,z]},V4(),z}function w5($,Z=10){let Y=w2($);if(!Y)return[];return A.interactions.filter((J)=>J.personId===Y.id).sort((J,X)=>new Date(X.date).getTime()-new Date(J.date).getTime()).slice(0,Z)}function Q1(){let $=new Date,Z=[];for(let Y of A.interactions){if(Y.followUpDone||!Y.followUpDate)continue;let J=new Date(Y.followUpDate);if(isNaN(J.getTime()))continue;if(J<=$){let X=A.people.find((z)=>z.id===Y.personId);if(X)Z.push({person:X,interaction:Y})}}return Z.sort((Y,J)=>new Date(Y.interaction.followUpDate).getTime()-new Date(J.interaction.followUpDate).getTime())}function W4($,Z,Y){let J=w2($);if(!J)return null;let X={id:T6(),personId:J.id,task:Z.trim(),assignedAt:new Date().toISOString(),dueDate:Y?.toISOString(),status:"pendente"};return A={...A,delegations:[...A.delegations,X]},V4(),X}function e8($,Z,Y){if(!A.delegations.find((X)=>X.id===$))return null;return A={...A,delegations:A.delegations.map((X)=>X.id===$?{...X,status:Z,notes:Y||X.notes}:X)},V4(),A.delegations.find((X)=>X.id===$)||null}function J$($,Z=!0){let Y=[...A.delegations];if($){let X=w2($);if(!X)return[];Y=Y.filter((z)=>z.personId===X.id)}if(Z)Y=Y.filter((X)=>X.status!=="concluido");let J=new Date;return Y=Y.map((X)=>{if(X.status==="pendente"&&X.dueDate){let z=new Date(X.dueDate);if(!isNaN(z.getTime())&&z<J)return{...X,status:"atrasado"}}return X}),Y.sort((X,z)=>{if(X.status==="atrasado"&&z.status!=="atrasado")return-1;if(z.status==="atrasado"&&X.status!=="atrasado")return 1;let Q=X.dueDate?new Date(X.dueDate).getTime():1/0,K=z.dueDate?new Date(z.dueDate).getTime():1/0;return Q-K})}var $0={equipe:"Equipe",familia:"Familia",contato:"Contato"};function q4($){if($.length===0)return"Nenhuma pessoa cadastrada.";let Z=new Map;for(let X of $){let z=Z.get(X.group)||[];Z.set(X.group,[...z,X])}let Y=[],J=["equipe","familia","contato"];for(let X of J){let z=Z.get(X);if(!z?.length)continue;let Q=z.map((K)=>{let G=K.role?` (${K.role})`:"",H=K.contact?` \u2014 ${K.contact}`:"";return` ${K.name}${G}${H} [${K.id}]`});Y.push(`--- ${$0[X]} ---
114
+ ${Q.join(`
115
+ `)}`)}return Y.join(`
116
+
117
+ `)}function H4($){let Z=[];if(Z.push(`${$.name} [${$.id}]`),Z.push(`Grupo: ${$0[$.group]}`),$.role)Z.push(`Papel: ${$.role}`);if($.contact)Z.push(`Contato: ${$.contact}`);if($.notes)Z.push(`Notas: ${$.notes}`);let Y=w5($.id,5);if(Y.length>0){Z.push(`
118
+ Interacoes recentes:`);for(let X of Y){let z=new Date(X.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});Z.push(` [${z}] ${X.type}: ${X.summary}`)}}let J=J$($.id);if(J.length>0){Z.push(`
119
+ Tarefas delegadas:`);for(let X of J){let z=X.status==="atrasado"?"!!":X.status==="em_andamento"?">>":" ",Q=X.dueDate?` (${P6(X.dueDate)})`:"";Z.push(` ${z} ${X.task}${Q} [${X.status}]`)}}return Z.join(`
120
+ `)}function U4($){if($.length===0)return"Nenhuma tarefa delegada pendente.";let Z=$.map((Y)=>{let X=A.people.find((K)=>K.id===Y.personId)?.name||"?",z=Y.status==="atrasado"?"!! ":Y.status==="em_andamento"?">> ":" ",Q=Y.dueDate?` (${P6(Y.dueDate)})`:"";return`${z}${X}: ${Y.task}${Q} [${Y.status}] [${Y.id}]`});return`Delegacoes (${$.length}):
121
+ ${Z.join(`
122
+ `)}`}function C4($){if($.length===0)return"Nenhum follow-up pendente.";let Z=$.map(({person:Y,interaction:J})=>{return` [${P6(J.followUpDate)}] ${Y.name}: ${J.summary} [${J.id}]`});return`Follow-ups pendentes (${$.length}):
123
+ ${Z.join(`
124
+ `)}`}function B4(){let $=[];$.push(`=== PAINEL DE PESSOAS ===
125
+ `);let Z=A.people.filter((H)=>H.group==="equipe").length,Y=A.people.filter((H)=>H.group==="familia").length,J=A.people.filter((H)=>H.group==="contato").length;$.push(`Equipe: ${Z} | Familia: ${Y} | Contatos: ${J}`);let X=Q1();if(X.length>0){$.push(`
126
+ !! ${X.length} follow-up(s) pendente(s):`);for(let{person:H,interaction:V}of X.slice(0,5))$.push(` ${H.name}: ${V.summary}`)}let z=J$(),Q=z.filter((H)=>H.status==="atrasado"),K=z.filter((H)=>H.status==="pendente"||H.status==="em_andamento");if(Q.length>0){$.push(`
127
+ !! ${Q.length} delegacao(oes) atrasada(s):`);for(let H of Q.slice(0,5)){let V=A.people.find((O)=>O.id===H.personId);$.push(` ${V?.name}: ${H.task}`)}}if(K.length>0)$.push(`
128
+ ${K.length} delegacao(oes) em andamento`);let G=[...A.interactions].sort((H,V)=>new Date(V.date).getTime()-new Date(H.date).getTime()).slice(0,3);if(G.length>0){$.push(`
129
+ Ultimas interacoes:`);for(let H of G){let V=A.people.find((B)=>B.id===H.personId),O=new Date(H.date).toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"});$.push(` [${O}] ${V?.name}: ${H.summary}`)}}return $.push(`
130
+ ========================`),$.join(`
131
+ `)}function T6(){let Z="";for(let Y=0;Y<6;Y++)Z+="abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(Math.random()*36)];return Z}function P6($){let Z=new Date($);if(isNaN(Z.getTime()))return"?";let Y=new Date,J=new Date(Y.getFullYear(),Y.getMonth(),Y.getDate()),X=new Date(Z.getFullYear(),Z.getMonth(),Z.getDate());if(X.getTime()===J.getTime())return"hoje";let z=new Date(J);if(z.setDate(z.getDate()+1),X.getTime()===z.getTime())return"amanha";let Q=Math.floor((X.getTime()-J.getTime())/86400000);if(Q<0)return`${Math.abs(Q)}d atras`;if(Q<=7)return`em ${Q}d`;return Z.toLocaleDateString("pt-BR",{day:"2-digit",month:"2-digit"})}var z$=new V6,Q0=[];function V0($){Q0=$}var Y2=[{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"]}}],K0=[{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. 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"]}},required:[]}}],y5=[{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:[]}}],_5=[{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:[]}}],f5=[{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"]}}],h5={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"]}},v5=[{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"]}}],g5=[{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:[]}}],c5=K0.find(($)=>$.name==="get_news"),Z0=!1;function G0(){if(Z0)return;if(Z0=!0,D)Y2.push(...K0);else Y2.push(c5);Y2.push(...y5),Y2.push(..._5),Y2.push(...f5),Y2.push(h5),Y2.push(...v5),Y2.push(...g5)}var j4=50000;async function b6($,Z){try{switch($){case"read_file":return d5(Z);case"write_file":return m5(Z);case"edit_file":return u5(Z);case"search_files":return await p5(Z);case"find_files":return await n5(Z);case"list_directory":return o5(Z);case"run_command":return await a5(Z);case"fetch_url":return await r5(Z);case"open_application":return await t2(Z.name,Z.argument);case"open_file_default":return await n1(Z.path);case"open_url_browser":return await i1(Z.url);case"get_running_apps":return await o1();case"get_system_info":return await e2();case"get_calendar_events":return await L2();case"get_news":{let Y=Z.category;return await x2(Y?[Y]:void 0)}case"create_task":{let Y=Z.title;if(!Y?.trim())return"Error: title is required.";let J=Z.time,X=J?Z1(J):void 0,z=r1(Y,X||void 0),Q=X?` \u2014 lembrete: ${X.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";return`Tarefa criada: "${z.title}"${Q} [${z.id}]`}case"complete_task":{let Y=Z.reference;if(!Y?.trim())return"Error: reference is required.";let J=s1(Y);return J?`Concluida: "${J.title}"`:`Tarefa nao encontrada: "${Y}"`}case"list_tasks":{let Y=Z.show_done||!1,J=D2(Y);return h2(J)}case"add_person":{let Y=Z.name;if(!Y?.trim())return"Error: name is required.";let J=Z.group;if(!["equipe","familia","contato"].includes(J))return"Error: group must be equipe, familia, or contato.";let z=K4(Y,J,Z.role,Z.contact);return`Pessoa adicionada: ${z.name} (${J}) [${z.id}]`}case"find_person_info":{let Y=Z.name_or_id;if(!Y?.trim())return"Error: name_or_id is required.";let J=w2(Y);if(!J)return`Pessoa nao encontrada: "${Y}"`;return H4(J)}case"list_people":{let Y=Z.group,J=G4(Y);return q4(J)}case"log_interaction":{let Y=Z.person;if(!Y?.trim())return"Error: person is required.";let{type:J,summary:X}=Z;if(!X?.trim())return"Error: summary is required.";let z=Z.follow_up,Q=z?X0(z):void 0;if(!t8(Y,J,X,Q||void 0))return`Pessoa nao encontrada: "${Y}"`;let G=Q?` \u2014 follow-up: ${Q.toLocaleDateString("pt-BR")}`:"";return`Interacao registrada: ${J} com ${Y}${G}`}case"delegate_to_person":{let Y=Z.person;if(!Y?.trim())return"Error: person is required.";let J=Z.task;if(!J?.trim())return"Error: task is required.";let X=Z.due_date,z=X?X0(X):void 0,Q=W4(Y,J,z||void 0);if(!Q)return`Pessoa nao encontrada: "${Y}"`;let K=z?` \u2014 prazo: ${z.toLocaleDateString("pt-BR")}`:"";return`Tarefa delegada para ${Y}: "${J}"${K} [${Q.id}]`}case"update_delegation_status":{let Y=Z.delegation_id;if(!Y?.trim())return"Error: delegation_id is required.";let J=Z.status,X=e8(Y,J,Z.notes);if(!X)return`Delegacao nao encontrada: "${Y}"`;return`Delegacao atualizada: "${X.task}" -> ${J}`}case"get_people_dashboard":return B4();case"save_memo":{let Y=Z.content;if(!Y?.trim())return"Error: content is required.";let J=Z.tags||[],X=t1(Y,J);return`Memo salvo${X.tags.length>0?` [${X.tags.map((Q)=>"#"+Q).join(" ")}]`:""} {${X.id}}`}case"search_memos":{let Y=Z.query;if(!Y?.trim())return v2(Y1());let J=e1(Y);return v2(J)}case"record_transaction":{let{type:Y,amount:J,category:X,description:z}=Z;if(!Y||!J||!X||!z)return"Error: all fields required.";let Q=J1(Y,J,X,z);return`${Q.type==="entrada"?"+":"-"} R$ ${Q.amount.toFixed(2)} (${Q.category}) \u2014 ${Q.description} [${Q.id}]`}case"financial_summary":return Y4();case"log_decision":{let{title:Y,context:J,chosen:X}=Z;if(!Y||!J||!X)return"Error: title, context, and chosen are required.";let z=m8(Y,J,X,Z.alternatives,Z.tags||[]);return`Decisao registrada: "${z.title}" {${z.id}}`}case"search_decisions":{let Y=Z.query;if(!Y?.trim())return Y$(X4());return Y$(J4(Y))}case"open_investigation":{let Y=Z.title;if(!Y?.trim())return"Error: title is required.";let J=Z.type;if(!["bug","feature","test","audit","incident"].includes(J))return"Error: type must be bug, feature, test, audit, or incident.";let z=j6(Y,J,Z.hypothesis,Z.tags||[]);return`Investigacao aberta: "${z.title}" (${z.type}) {${z.id}}`}case"collect_evidence":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let{source:J,label:X,content:z}=Z;if(!X?.trim()||!z?.trim())return"Error: label and content are required.";let Q=O6(Y,J,X,z,Z.path);if(!Q)return`Investigacao nao encontrada: "${Y}"`;return`Evidencia coletada: [${Q.id}] ${Q.source}: ${Q.label}`}case"add_finding":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let{severity:J,title:X,description:z}=Z;if(!X?.trim()||!z?.trim())return"Error: title and description are required.";let Q=Z.evidence_ids||[],K=M6(Y,J,X,z,Q);if(!K)return`Investigacao nao encontrada: "${Y}"`;return`Conclusao registrada: [${K.severity.toUpperCase()}] ${K.title} {${K.id}}`}case"close_investigation":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=Z.summary;if(!J?.trim())return"Error: summary is required.";let X=F6(Y,J,Z.recommendations);if(!X)return`Investigacao nao encontrada: "${Y}"`;return`Investigacao concluida: "${X.title}" \u2014 ${X.evidence.length} evidencias, ${X.findings.length} conclusoes`}case"investigation_status":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=E6(Y);if(!J)return`Investigacao nao encontrada: "${Y}"`;return R6(J)}case"investigation_report":{let Y=Z.investigation;if(!Y?.trim())return"Error: investigation is required.";let J=D6(Y);if(!J)return`Investigacao nao encontrada: "${Y}"`;return J}case"list_investigations":{let Y=Z.query;if(Y?.trim())return Q4(x6(Y));let{status:J,type:X}=Z;return Q4(L6(J,X))}case"draft_email":{let{to:Y,subject:J,body:X}=Z;if(!Y?.trim()||!J?.trim()||!X?.trim())return"Error: to, subject, and body are required.";let z={to:Y,subject:J,body:X,cc:Z.cc},Q=Z4(z),K=await $4(z);return`${Q}
132
+
133
+ ${K}`}default:{let Y=Q0.find((J)=>J.name===$);if(Y)return await H8(Y,Z);return`Error: unknown tool "${$}"`}}}catch(Y){return`Error: ${Y instanceof Error?Y.message:String(Y)}`}}var Y0=10485760;function W0($,Z){let Y=k6(k5($),`.tinyclaw-${b5().slice(0,8)}.tmp`);P5(Y,Z),I5(Y,$)}function Q$($){let Z=g2($),Y=process.cwd();if(Z!==Y&&!Z.startsWith(Y+N4))return`Error: path outside working directory is not permitted: ${Z}`;try{if(V1(Z)){let J=S5(Z);if(J!==Y&&!J.startsWith(Y+N4))return`Error: symlink target is outside working directory: ${J}`}}catch{}return null}function V$($,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 d5($){let Z=V$($,"path");if(Z)return Z;let Y=g2($.path),J=Q$(Y);if(J)return J;if(!V1(Y))return`Error: file not found: ${Y}`;let X=z0(Y).size;if(X>Y0)return`Error: file too large (${I6(X)}). Max is ${I6(Y0)}.`;let Q=S6(Y,"utf-8").split(`
134
+ `),K=Math.max(1,$.offset||1),G=Math.min(2000,$.limit||500),O=Q.slice(K-1,K-1+G).map((E,R)=>`${String(K+R).padStart(4)} ${E}`).join(`
135
+ `),B=Q.length-(K-1+G);if(B>0)O+=`
136
+ ... (${B} more lines, total ${Q.length})`;return X$(O)}function m5($){let Z=V$($,"path");if(Z)return Z;let Y=g2($.path),J=Q$(Y);if(J)return J;let X=$.content,z=V1(Y);z$.saveState(Y),W0(Y,X);let Q=X.split(`
137
+ `).length;return`${z?"Updated":"Created"}: ${Y} (${Q} lines)`}function u5($){let Z=V$($,"path");if(Z)return Z;let Y=g2($.path),J=Q$(Y);if(J)return J;if(!V1(Y))return`Error: file not found: ${Y}`;let X=S6(Y,"utf-8"),z=$.old_text,Q=$.new_text,K=X.split(z).length-1;if(K===0)return"Error: old_text not found in file. Make sure it matches exactly, including whitespace and indentation.";if(K>1)return`Error: old_text found ${K} times. It must be unique. Include more surrounding context.`;z$.saveState(Y);let G=X.split(z).join(Q);W0(Y,G);let H=z.split(`
138
+ `).length,V=Q.split(`
139
+ `).length;return`Edited: ${Y} (replaced ${H} lines with ${V} lines)`}async function p5($){let Z=V$($,"pattern");if(Z)return Z;let Y=$.pattern,J=g2($.path||"."),X=Q$(J);if(X)return X;let z=$.include;if(await Q7())return l5(Y,J,z);return i5(Y,J,z)}async function l5($,Z,Y){let J=["rg","--no-heading","--line-number","--color=never"];if(Y)J.push("--glob",Y);for(let K of A4)J.push("--glob",`!${K}`);J.push("-e",$,Z);let X=Bun.spawn(J,{stdout:"pipe",stderr:"pipe"}),z=await new Response(X.stdout).text(),Q=await new Response(X.stderr).text();if(await X.exited,!z.trim()&&!Q.trim())return"No matches found.";if(Q.trim()&&!z.trim())return`Error: ${Q.trim()}`;return t5(z,Z)}async function i5($,Z,Y){let J;try{J=new RegExp($)}catch(V){return`Error: invalid regex pattern: ${V instanceof Error?V.message:$}`}let X=Y||"**/*",z=new Bun.Glob(X),Q=[],K=0,G=5000;for await(let V of z.scan({cwd:Z,onlyFiles:!0})){if(w4(V))continue;if(++K>G){Q.push(`... (stopped after scanning ${G} files)`);break}let O=k6(Z,V);try{let E=S6(O,"utf-8").split(`
140
+ `);for(let R=0;R<E.length;R++)if(J.test(E[R])){if(Q.push(`${V}:${R+1}:${E[R]}`),Q.length>=100)break}}catch{}if(Q.length>=100)break}if(Q.length===0)return"No matches found.";let H=Q.slice(0,100).join(`
141
+ `);if(Q.length>100)H+=`
142
+ ... (showing first 100 matches)`;return X$(H)}async function n5($){let Z=V$($,"pattern");if(Z)return Z;let Y=$.pattern,J=g2($.path||"."),X=Q$(J);if(X)return X;let z=new Bun.Glob(Y),Q=[];for await(let G of z.scan({cwd:J,onlyFiles:!0})){if(w4(G))continue;if(Q.push(G),Q.length>=200)break}if(Q.length===0)return"No files found.";let K=Q.join(`
143
+ `);if(Q.length>=200)K+=`
144
+ ... (showing first 200 files)`;return K}function o5($){let Z=g2($.path||"."),Y=Q$(Z);if(Y)return Y;if(!V1(Z))return`Error: not found: ${Z}`;return T5(Z,{withFileTypes:!0}).sort((z,Q)=>{if(z.isDirectory()!==Q.isDirectory())return z.isDirectory()?-1:1;return z.name.localeCompare(Q.name)}).map((z)=>{if(z.isDirectory())return`d ${z.name}/`;try{let Q=z0(k6(Z,z.name)),K=I6(Q.size);return`f ${z.name} ${K}`}catch{return`f ${z.name}`}}).join(`
145
+ `)}async function a5($){let Z=V$($,"command");if(Z)return Z;let Y=$.command,J=Math.min(120,Math.max(5,$.timeout||30)),X=C1(),z=Bun.spawn([...X,Y],{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),Q=setTimeout(()=>z.kill(),J*1000),[K,G]=await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),H=await z.exited;clearTimeout(Q);let V="";if(K.trim())V+=K.trim();if(G.trim())V+=(V?`
146
+ `:"")+`STDERR:
147
+ `+G.trim();if(H!==0)V+=(V?`
148
+ `:"")+`Exit code: ${H}`;return X$(V||"(no output)")}async function r5($){let Z=$.url,Y=$.method||"GET",J=$.headers||{},X=$.body;if(!Z.startsWith("http://")&&!Z.startsWith("https://"))return"Error: URL must start with http:// or https://";let z=J0(Z);if(z)return z;try{let Q=new AbortController,K=setTimeout(()=>Q.abort(),30000),G=await fetch(Z,{method:Y,redirect:"manual",headers:{"User-Agent":"tinyclaw/1.0",Accept:"text/html, application/json, text/plain, */*",...J},body:X&&Y!=="GET"&&Y!=="HEAD"?X:void 0,signal:Q.signal});if(clearTimeout(K),G.status>=300&&G.status<400){let E=G.headers.get("location");if(!E)return`Status: ${G.status} (redirect with no location header)`;let R=J0(E);if(R)return`Redirect blocked: ${R}`;return`Status: ${G.status} -> Redirect to: ${E}
149
+ (Use fetch_url on the redirect target if needed)`}let H=`${G.status} ${G.statusText}`,V=G.headers.get("content-type")||"";if(Y==="HEAD"){let E=[...G.headers.entries()].map(([R,v])=>`${R}: ${v}`).join(`
150
+ `);return`Status: ${H}
151
+ ${E}`}let O=G.headers.get("content-length");if(O&&Number(O)>j4*2)return`Status: ${H}
152
+
153
+ Error: response body too large (${O} bytes). Max is ${j4*2} bytes.`;let B=await G.text();if(V.includes("text/html")){let E=s5(B);return X$(`Status: ${H}
154
+
155
+ ${E}`)}return X$(`Status: ${H}
156
+
157
+ ${B}`)}catch(Q){if(Q instanceof Error&&Q.name==="AbortError")return"Error: Request timed out after 30 seconds.";return`Error: ${Q instanceof Error?Q.message:String(Q)}`}}function J0($){try{let Z=new URL($),Y=Z.hostname.toLowerCase();if(Z.protocol!=="http:"&&Z.protocol!=="https:")return`Error: protocol ${Z.protocol} is not allowed.`;if(["localhost","127.0.0.1","::1","0.0.0.0","::ffff:127.0.0.1","::ffff:0.0.0.0"].includes(Y))return"Error: requests to localhost are blocked for security.";if(Y.endsWith(".local")||Y.endsWith(".internal"))return"Error: requests to internal hostnames are blocked.";if(Y==="metadata.google.internal"||Y==="metadata.gcp.internal")return"Error: requests to cloud metadata endpoints are blocked.";let X=Y.split(".").map(Number);if(X.length===4&&X.every((z)=>!isNaN(z)&&z>=0&&z<=255)){if(X[0]===10)return"Error: requests to private IPs (10.x) are blocked.";if(X[0]===172&&X[1]>=16&&X[1]<=31)return"Error: requests to private IPs (172.16-31.x) are blocked.";if(X[0]===192&&X[1]===168)return"Error: requests to private IPs (192.168.x) are blocked.";if(X[0]===169&&X[1]===254)return"Error: requests to link-local/metadata IPs are blocked.";if(X[0]===0)return"Error: requests to 0.x IPs are blocked."}if(Y.startsWith("::ffff:")||Y.startsWith("[::ffff:"))return"Error: requests to IPv6-mapped IPv4 addresses are blocked."}catch{return"Error: invalid URL."}return null}function s5($){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,`
158
+ `).replace(/<(br|hr)[^>]*\/?>/gi,`
159
+ `).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,`
160
+
161
+ `).trim()}function t5($,Z){let Y=process.cwd(),J=Y+N4,X=Z+N4,Q=$.trim().split(`
162
+ `).map((H)=>{if(H.startsWith(J))return"."+H.slice(Y.length).replace(/\\/g,"/");if(H.startsWith(X))return"."+H.slice(Z.length).replace(/\\/g,"/");return H}),K=Q.length,G=Q.slice(0,100).join(`
163
+ `);if(K>100)G+=`
164
+ ... (${K-100} more matches)`;return X$(G)}function X$($){if($.length<=j4)return $;return $.slice(0,j4)+`
165
+ ... (output truncated)`}function I6($){if($<1024)return`${$}B`;if($<1048576)return`${($/1024).toFixed(1)}K`;return`${($/1048576).toFixed(1)}M`}function X0($){let Z=$.toLowerCase().trim(),Y=new Date;if(Z==="hoje")return Y;if(Z==="amanha"||Z==="amanh\xE3"){let K=new Date(Y);return K.setDate(K.getDate()+1),K}let J=Z.match(/em\s+(\d+)\s*dias?/);if(J){let K=new Date(Y);return K.setDate(K.getDate()+parseInt(J[1])),K}let X=Z.match(/em\s+(\d+)\s*semanas?/);if(X){let K=new Date(Y);return K.setDate(K.getDate()+parseInt(X[1])*7),K}let z={domingo:0,segunda:1,terca:2,ter\u{e7}a:2,quarta:3,quinta:4,sexta:5,sabado:6,s\u{e1}bado:6};for(let[K,G]of Object.entries(z))if(Z.includes(K)){let H=new Date(Y),V=(G-H.getDay()+7)%7||7;return H.setDate(H.getDate()+V),H}let Q=Z.match(/(\d{1,2})\/(\d{1,2})(?:\/(\d{2,4}))?\s*/);if(Q){let K=parseInt(Q[1]),G=parseInt(Q[2])-1,H=Q[3]?parseInt(Q[3])+(Q[3].length===2?2000:0):Y.getFullYear(),V=new Date(H,G,K);if(!isNaN(V.getTime()))return V}return Z1(Z)}var e5=new Set([429,500,502,503,529]);async function H0($,Z={}){let Y=Z.maxRetries??3,J=Z.baseDelayMs??1000,X;for(let z=0;z<=Y;z++)try{return await $()}catch(Q){if(X=Q,Z.signal?.aborted)throw Q;if(z>=Y)throw Q;if($9(Q)&&Z.onAuthExpired){if(Z.onAuthExpired()){Z.onRetry?.(z+1,500,"Auth refreshed, retrying..."),await q0(500,Z.signal);continue}}if(!Z9(Q))throw Q;let G=Y9(Q)??J*Math.pow(2,z),H=Q instanceof Error?Q.message:String(Q);Z.onRetry?.(z+1,G,H),await q0(G,Z.signal)}throw X}function $9($){if(!($ instanceof Error))return!1;return $.status===401}function Z9($){if(!($ instanceof Error))return!1;let Z=$.status;if(Z&&e5.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 Y9($){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 q0($,Z){return new Promise((Y,J)=>{let X=setTimeout(Y,$);Z?.addEventListener("abort",()=>{clearTimeout(X),J(Error("Aborted"))},{once:!0})})}var J9={haiku:200000,sonnet:200000,opus:200000};function T2($){return Math.ceil($.length/3.5)}function y6($){let Z=0;for(let Y of $){if(Z+=T2(Y.content),Y.toolCalls)for(let J of Y.toolCalls)Z+=T2(JSON.stringify(J.input)),Z+=T2(J.result);Z+=10}return Z}function _6($){let Z=$.toLowerCase();for(let[Y,J]of Object.entries(J9))if(Z.includes(Y))return J;return 200000}function U0($,Z,Y){let J=_6(Z)-20000-Y;if(y6($)<=J)return $;let z=[],Q=J,K=[...$].reverse(),G=[];for(let V of K){let O=T2(V.content)+(V.toolCalls?.reduce((B,E)=>B+T2(JSON.stringify(E.input))+T2(E.result),0)??0)+10;if(Q-O<0)break;Q-=O,G.unshift(V)}let H=$.length-G.length;if(H>0)z.push({role:"user",content:`[Note: ${H} earlier messages were trimmed to fit context. The conversation continues below.]`,timestamp:Date.now()});return z.push(...G),z}function C0($,Z,Y){let J=_6(Z)-20000-Y;return y6($)>J*0.7}function B0($,Z,Y){let J=_6(Z)-20000-Y;if(y6($)<=J*0.7)return null;let z=Math.max(4,Math.floor($.length*0.3)),Q=$.slice(0,$.length-z),K=$.slice($.length-z);if(Q.length<2)return null;return{toSummarize:Q,toKeep:K}}function N0($){return`Summarize this conversation concisely. Focus on:
166
+ 1. Key decisions made
167
+ 2. Files created or modified
168
+ 3. Important context the user shared
169
+ 4. Current state of the task
170
+
171
+ Be brief but preserve actionable information. Output ONLY the summary.
172
+
173
+ ---
174
+ ${$.map((Y)=>{let J=`[${Y.role}]: ${Y.content.slice(0,500)}`;if(Y.toolCalls?.length)J+=`
175
+ Tools used: ${Y.toolCalls.map((X)=>X.name).join(", ")}`;return J}).join(`
176
+
177
+ `)}`}function j0($,Z=2000){return $.map((Y)=>{if(!Y.toolCalls?.length)return Y;let J=Y.toolCalls.map((X)=>{if(X.result.length<=Z)return X;let z=X.result.split(`
178
+ `),Q=Math.min(10,z.length),K=Math.min(5,Math.max(0,z.length-Q)),G=z.length-Q-K,H=[...z.slice(0,Q)];if(G>0)H.push(`... (${G} lines omitted)`);if(K>0)H.push(...z.slice(-K));let V=H.join(`
179
+ `);return{...X,result:V}});return{...Y,toolCalls:J}})}var X9=[/\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],z9=[/\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 O0($,Z){switch($){case"read_file":case"list_directory":case"find_files":case"search_files":case"fetch_url":return{level:"safe"};case"write_file":return{level:"moderate",reason:`write ${Z.path}`};case"edit_file":return{level:"moderate",reason:`edit ${Z.path}`};case"run_command":{let Y=String(Z.command||"");for(let J of X9)if(J.test(Y))return{level:"dangerous",reason:Y};for(let J of z9)if(J.test(Y))return{level:"moderate",reason:Y};return{level:"moderate",reason:Y}}default:return{level:"moderate",reason:`unknown tool: ${$}`}}}function f6($){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: ${Q9(Y)}`;case 401:return"Authentication failed. Your API key or subscription token may be expired.\nTry: Set ANTHROPIC_API_KEY env var, or run `claude` to refresh subscription credentials.";case 403:return`Access denied. Your API key may not have permission for this model.
180
+ Try: /model haiku (uses a more accessible model).`;case 404:return`Model not found. The model "${V9(Y)}" may not exist or be unavailable.
181
+ Try: /model to see available models.`;case 429:return`Rate limited. Too many requests in a short period.
182
+ 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 authentication has expired. Run `claude` to refresh, or set a new ANTHROPIC_API_KEY.";return Y}function Q9($){try{let Z=$.match(/"message"\s*:\s*"([^"]+)"/);if(Z)return Z[1]}catch{}return $.length>200?$.slice(0,200)+"...":$}function V9($){let Z=$.match(/model[:\s]+"?([a-z0-9-]+)"?/i);return Z?Z[1]:"unknown"}function M0($,Z,Y){if($==="auto")return!1;if(Y==="safe")return!1;if($==="confirm-writes")return["write_file","edit_file","run_command"].includes(Z);if($==="confirm-all")return Y!=="safe";return!1}function F0($,Z){switch($){case"write_file":return`Write file: ${Z.path}`;case"edit_file":return`Edit file: ${Z.path}`;case"run_command":{let Y=String(Z.command||"");return`Run: ${Y.length>60?Y.slice(0,57)+"...":Y}`}default:return`${$}: ${JSON.stringify(Z).slice(0,60)}`}}function E0($,Z,Y=20){let J=$.split(`
183
+ `),X=Z.split(`
184
+ `),z=[],Q=J.slice(0,Y);for(let G of Q)z.push(` \x1B[31m- ${G}\x1B[0m`);if(J.length>Y)z.push(` \x1B[2m ... (${J.length-Y} more removed)\x1B[0m`);let K=X.slice(0,Y);for(let G of K)z.push(` \x1B[32m+ ${G}\x1B[0m`);if(X.length>Y)z.push(` \x1B[2m ... (${X.length-Y} more added)\x1B[0m`);return z}class h6{model;maxTokens;client;approvalMode;approvalCallback=null;autoApproveAll=!1;onAuthExpired=null;constructor($,Z,Y,J="auto"){this.model=Z;this.maxTokens=Y;this.client=new Q2({apiKey:$}),this.approvalMode=J}updateApiKey($){this.client=new Q2({apiKey:$})}setAuthRefresh($){this.onAuthExpired=$}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){let J=j0($),X=T2(Z);if(C0(J,this.model,X)){let G=B0(J,this.model,X);if(G)try{let V={role:"assistant",content:`[Conversation summary]
185
+ ${await this.generateSummary(G.toSummarize)}`,timestamp:Date.now()};J=[{role:"user",content:"Continue from this summary of our earlier conversation.",timestamp:Date.now()},V,...G.toKeep]}catch{}}let z=U0(J,this.model,X),Q=K9(z),K=Y?Y2:void 0;try{yield*this.streamLoop(Q,Z,K)}catch(G){yield{type:"error",error:f6(G)}}}async generateSummary($){let Z=N0($),J=(await this.client.messages.create({model:this.model,max_tokens:1024,messages:[{role:"user",content:Z}]})).content.find((X)=>X.type==="text");return J?.type==="text"?J.text:"Summary unavailable."}async*streamLoop($,Z,Y){let X=[...$],z=0;while(z++<25){let Q;try{Q=await H0(async()=>{return this.client.messages.stream({model:this.model,max_tokens:this.maxTokens,system:Z,messages:X,...Y?.length?{tools:Y}:{}})},{onAuthExpired:this.onAuthExpired??void 0})}catch(V){yield{type:"error",error:f6(V)};return}for await(let V of Q)if(V.type==="content_block_delta"&&V.delta.type==="text_delta")yield{type:"text",text:V.delta.text};let K=await Q.finalMessage();if(K.usage)yield{type:"usage",inputTokens:K.usage.input_tokens,outputTokens:K.usage.output_tokens};if(K.stop_reason!=="tool_use"){yield{type:"done"};return}let G=K.content.filter((V)=>V.type==="tool_use");X.push({role:"assistant",content:K.content});let H=[];for(let V of G){let O=V.input,B=O0(V.name,O);if(B.level==="dangerous"){yield{type:"tool_blocked",id:V.id,name:V.name,reason:`Blocked dangerous operation: ${B.reason}`},H.push({type:"tool_result",tool_use_id:V.id,content:`Error: Operation blocked for safety. Reason: ${B.reason}. This command appears dangerous and was not executed.`});continue}if(!this.autoApproveAll&&M0(this.approvalMode,V.name,B.level)&&this.approvalCallback){if(yield{type:"tool_call",id:V.id,name:V.name,input:V.input},!await this.approvalCallback(V.name,O,B.level)){yield{type:"tool_blocked",id:V.id,name:V.name,reason:"Rejected by user"},H.push({type:"tool_result",tool_use_id:V.id,content:"Error: User rejected this operation."});continue}let v=await b6(V.name,O);yield{type:"tool_result",id:V.id,name:V.name,result:v},H.push({type:"tool_result",tool_use_id:V.id,content:v});continue}yield{type:"tool_call",id:V.id,name:V.name,input:V.input};let E=await b6(V.name,O);yield{type:"tool_result",id:V.id,name:V.name,result:E},H.push({type:"tool_result",tool_use_id:V.id,content:E})}X.push({role:"user",content:H})}yield{type:"error",error:"Stopped after 25 tool rounds to prevent runaway execution."}}}function K9($){let Z=[];for(let Y of $)if(Y.role==="user")if(Y.images?.length){let J=Y.images.map((X)=>({type:"image",source:{type:"base64",media_type:X.mediaType,data:X.base64}}));J.push({type:"text",text:Y.content}),Z.push({role:"user",content:J})}else Z.push({role:"user",content:Y.content});else if(Y.role==="assistant")if(Y.toolCalls?.length){let J=[];if(Y.content)J.push({type:"text",text:Y.content});for(let X of Y.toolCalls)J.push({type:"tool_use",id:X.id,name:X.name,input:X.input});Z.push({role:"assistant",content:J}),Z.push({role:"user",content:Y.toolCalls.map((X)=>({type:"tool_result",tool_use_id:X.id,content:X.result}))})}else Z.push({role:"assistant",content:Y.content});return Z}import{existsSync as K1,mkdirSync as G9,readdirSync as W9,readFileSync as L0,writeFileSync as v6,unlinkSync as q9}from"fs";import{join as K$}from"path";class g6{sessionsDir;current;constructor($){if(this.sessionsDir=K$($,"sessions"),!K1(this.sessionsDir))G9(this.sessionsDir,{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(!K1(this.sessionsDir))return[];return W9(this.sessionsDir).filter(($)=>$.endsWith(".json")).map(($)=>$.replace(".json",""))}getInfo($){let Z=K$(this.sessionsDir,`${$}.json`);if(!K1(Z))return null;try{let Y=JSON.parse(L0(Z,"utf-8"));return{messageCount:Y.messages.length,updated:Y.updated}}catch{return null}}delete($){let Z=K$(this.sessionsDir,`${$}.json`);if(K1(Z))return q9(Z),!0;return!1}fork($){let Z={id:crypto.randomUUID(),name:$,messages:[...this.current.messages],created:Date.now(),updated:Date.now()},Y=K$(this.sessionsDir,`${$}.json`);return v6(Y,JSON.stringify(Z,null,2)),this.current=Z,Z}loadOrCreate($){let Z=K$(this.sessionsDir,`${$}.json`);if(K1(Z))try{return JSON.parse(L0(Z,"utf-8"))}catch{}let Y={id:crypto.randomUUID(),name:$,messages:[],created:Date.now(),updated:Date.now()};return v6(Z,JSON.stringify(Y,null,2)),Y}save(){let $=K$(this.sessionsDir,`${this.current.name}.json`);v6($,JSON.stringify(this.current,null,2))}}import{existsSync as R0,readdirSync as B9,readFileSync as A0}from"fs";import{join as d6}from"path";import{existsSync as c6,readFileSync as x0}from"fs";import{basename as H9,join as O4}from"path";function D0(){let $=process.cwd(),Z=[];if(Z.push(`Working directory: ${$}`),Z.push(`Platform: ${process.platform} (${process.arch})`),Z.push(`Shell: ${z7()}`),Z.push(`Runtime: Bun ${Bun.version}`),Z.push(`Date: ${new Date().toISOString().split("T")[0]}`),D)Z.push("Note: Use PowerShell syntax for commands (e.g., Get-ChildItem instead of ls, Get-Content instead of cat).");let Y=U9($);if(Y)Z.push(`Project: ${Y}`);let J=C9($);if(J)Z.push(J);return Z.join(`
186
+ `)}function U9($){let Z=[["package.json","Node.js/JavaScript"],["Cargo.toml","Rust"],["go.mod","Go"],["pyproject.toml","Python"],["requirements.txt","Python"],["pom.xml","Java (Maven)"],["build.gradle","Java (Gradle)"],["Gemfile","Ruby"],["composer.json","PHP"],["Makefile","Make"],["CMakeLists.txt","C/C++ (CMake)"],["Dockerfile","Docker"]],Y=[];for(let[X,z]of Z)if(c6(O4($,X)))Y.push(z);if(Y.length===0)return null;let J=H9($);try{let X=O4($,"package.json");if(c6(X)){let z=JSON.parse(x0(X,"utf-8"));if(z.name)J=z.name}}catch{}return`Project: ${J} (${Y.join(", ")})`}function C9($){if(!c6(O4($,".git")))return null;let Z=[];try{let Y=x0(O4($,".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(`
187
+ `)}try{let Y=Bun.spawnSync(["git","log","--oneline","-1"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J)Z.push(`Last commit: ${J}`)}}catch{}try{let Y=Bun.spawnSync(["git","diff","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J){let X=J.split(`
188
+ `),z=X.slice(0,15);if(X.length>15)z.push(`... and ${X.length-15} more files`);Z.push(`Uncommitted changes:
189
+ `+z.join(`
190
+ `))}}}catch{}try{let Y=Bun.spawnSync(["git","diff","--cached","--stat","--stat-width=60"],{cwd:$,stdout:"pipe",stderr:"pipe"});if(Y.exitCode===0){let J=new TextDecoder().decode(Y.stdout).trim();if(J){let X=J.split(`
191
+ `).slice(0,10);Z.push(`Staged:
192
+ `+X.join(`
193
+ `))}}}catch{}return Z.length>0?Z.join(`
194
+ `):null}function w0($,Z){if(!R0($))return[];let Y=[],J=B9($,{withFileTypes:!0});for(let X of J)if(X.isFile()&&X.name.endsWith(".md")){let z=A0(d6($,X.name),"utf-8");Y.push({name:X.name.replace(".md",""),content:z.trim(),source:Z})}else if(X.isDirectory()){let z=d6($,X.name,"SKILL.md");if(R0(z)){let Q=A0(z,"utf-8");Y.push({name:X.name,content:Q.trim(),source:Z})}}return Y}function T0($){let Z=w0($,"global"),Y=d6(process.cwd(),".tinyclaw","skills"),J=w0(Y,"local"),X=new Map;for(let z of Z)X.set(z.name,z);for(let z of J)X.set(z.name,z);return[...X.values()]}function P0($){if($.length===0)return"No skills loaded.";return`Skills:
195
+ `+$.map((Z)=>` ${Z.name} [${Z.source}]`).join(`
196
+ `)}function m6($,Z,Y="auto"){let J=[];for(let X of Z)J.push(X.content);if(Y&&Y!=="auto"){let z={pt:"Portuguese (Brazilian)",en:"English",es:"Spanish",fr:"French",de:"German",it:"Italian",ja:"Japanese",ko:"Korean",zh:"Chinese"}[Y]||Y;J.push(`## Language Override
197
+ ALWAYS respond in ${z}. This is a hard requirement.`)}if(J.push(`---
198
+ ## Environment
199
+ The user's current working directory and project info. Use this context when they ask about code or files.
200
+
201
+ `+D0()),$)J.push(`## User Instructions
202
+ `+$);return J.join(`
203
+
204
+ `)}var N9=!!(process.env.NO_COLOR||process.env.TERM==="dumb");function V2($){return N9?"":$}var C={altOn:V2("\x1B[?1049h"),altOff:V2("\x1B[?1049l"),clear:"\x1B[2J",clearLine:"\x1B[2K",hide:"\x1B[?25l",show:"\x1B[?25h",to:($,Z)=>`\x1B[${$};${Z}H`,bold:V2("\x1B[1m"),dim:V2("\x1B[2m"),italic:V2("\x1B[3m"),underline:V2("\x1B[4m"),reset:V2("\x1B[0m"),inv:V2("\x1B[7m"),fg:($)=>V2(`\x1B[38;5;${$}m`),bg:($)=>V2(`\x1B[48;5;${$}m`)};var m={user:C.fg(75),ai:C.fg(114),tool:C.fg(215),err:C.fg(196),sys:C.fg(245),prompt:C.fg(220),code:C.fg(180),heading:C.fg(75),link:C.fg(39),quote:C.fg(245)};function w($){process.stdout.write($)}var j9=/\x1b\[[0-9;]*[a-zA-Z]/g;function M4($){return $.replace(j9,"")}function O9($){let Z=$.codePointAt(0)||0;if(Z>=4352&&Z<=4447||Z>=11904&&Z<=42191&&Z!==12351||Z>=44032&&Z<=55203||Z>=63744&&Z<=64255||Z>=65040&&Z<=65135||Z>=65281&&Z<=65376||Z>=65504&&Z<=65510||Z>=127744&&Z<=130047||Z>=131072&&Z<=196607)return 2;return 1}function F4($){let Z=M4($),Y=0;for(let J of Z)Y+=O9(J);return Y}function I0($,Z){if(Z<10)Z=10;let Y=[];for(let J of $.split(`
205
+ `)){if(F4(J)<=Z){Y.push(J);continue}let Q=M4(J).split(" "),K=[],G="";for(let V of Q)if(G.length+(G?1:0)+V.length>Z&&G)K.push(G),G=" "+V;else G+=(G?" ":"")+V;if(G)K.push(G);let H=M9(J);for(let V=0;V<K.length;V++)if(H&&V===0)K[V]=H+K[V]+C.reset;else if(H)K[V]=H+K[V]+C.reset;Y.push(...K)}return Y}function M9($){let Z=$.match(/^(\x1b\[[0-9;]*[a-zA-Z])+/);return Z?Z[0]:""}function E4($){let Z=$.split(`
206
+ `),Y=[],J=!1,X="";for(let z=0;z<Z.length;z++){let Q=Z[z];if(Q.trimStart().startsWith("```")){if(!J){J=!0,X=Q.trimStart().slice(3).trim();let V=X?` ${X}`:"";Y.push(` ${C.dim}\u250C\u2500\u2500${V}${"\u2500".repeat(Math.max(1,40-V.length))}${C.reset}`)}else J=!1,X="",Y.push(` ${C.dim}\u2514${"\u2500".repeat(42)}${C.reset}`);continue}if(J){Y.push(` ${C.dim}\u2502${C.reset} ${m.code}${Q}${C.reset}`);continue}if(!Q.trim()){Y.push("");continue}let K=Q.match(/^(#{1,3})\s+(.+)/);if(K){let V=K[1].length,O=K[2],B=V===1?"\u2501":V===2?"\u2500":"\xB7";Y.push(` ${m.heading}${C.bold}${B} ${G1(O)}${C.reset}`);continue}if(Q.trimStart().startsWith(">")){let V=Q.replace(/^\s*>\s?/,"");Y.push(` ${m.quote}\u2502 ${G1(V)}${C.reset}`);continue}let G=Q.match(/^(\s*)([-*+])\s+(.+)/);if(G){let V=Math.floor(G[1].length/2),O=G[3],B=" ".repeat(V);Y.push(` ${B}${C.dim}\u2022${C.reset} ${G1(O)}`);continue}let H=Q.match(/^(\s*)(\d+)[.)]\s+(.+)/);if(H){let V=Math.floor(H[1].length/2),O=H[2],B=H[3],E=" ".repeat(V);Y.push(` ${E}${C.dim}${O}.${C.reset} ${G1(B)}`);continue}if(/^[-*_]{3,}\s*$/.test(Q.trim())){Y.push(` ${C.dim}${"\u2500".repeat(40)}${C.reset}`);continue}Y.push(` ${G1(Q)}`)}if(J)Y.push(` ${C.dim}\u2514${"\u2500".repeat(42)}${C.reset}`);return Y}function G1($){let Z=$;return Z=Z.replace(/`([^`]+)`/g,`${C.inv} $1 ${C.reset}`),Z=Z.replace(/\*\*\*(.+?)\*\*\*/g,`${C.bold}${C.italic}$1${C.reset}`),Z=Z.replace(/\*\*(.+?)\*\*/g,`${C.bold}$1${C.reset}`),Z=Z.replace(/__(.+?)__/g,`${C.bold}$1${C.reset}`),Z=Z.replace(/\*(.+?)\*/g,`${C.italic}$1${C.reset}`),Z=Z.replace(/_(.+?)_/g,`${C.italic}$1${C.reset}`),Z=Z.replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${C.underline}$1${C.reset} ${m.link}($2)${C.reset}`),Z}import{existsSync as F9,readFileSync as E9,writeFileSync as L9}from"fs";var u6=500;class p6{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>u6)this.entries=this.entries.slice(-u6);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(F9(this.filePath)){let $=E9(this.filePath,"utf-8");this.entries=$.split(`
207
+ `).filter(Boolean).slice(-u6)}}catch{}}save(){try{L9(this.filePath,this.entries.join(`
208
+ `)+`
209
+ `)}catch{}}}import{join as x9}from"path";class l6{model;sessionName;authInfo;dataDir;width=80;height=24;lines=[];streamBuf="";streamLines=[];inputBuf="";inputPos=0;isStreaming=!1;scrollOffset=0;history=null;renderTimer=null;spinnerFrame=0;spinnerTimer=null;streamStartTime=0;sessionCost="";commands=["/help","/clear","/commit","/persona","/copy","/fork","/new","/load","/sessions","/delete","/model","/export","/cost","/retry","/undo","/search","/lang","/config","/exit","/briefing","/news","/open","/openfile","/openurl","/apps","/sysinfo","/calendar","/ask","/budget","/plugins","/task","/tasks","/done","/rmtask","/people","/team","/family","/person","/addperson","/delegate","/delegations","/followups","/dashboard","/contacts","/investigar","/investigate","/investigacoes","/monitor","/vigiar","/workflow","/fluxo","/pomodoro","/foco","/entrada","/saida","/income","/expense","/finance","/financas","/balanco","/decisions","/decisoes","/email","/rascunho","/memo","/memos","/note","/notas","/tags","/memotags","/rmmemo","/rmnota","/anotar","/ajuda","/limpar","/commitar","/modo","/copiar","/novo","/carregar","/sessoes","/deletar","/modelo","/exportar","/custo","/repetir","/desfazer","/buscar","/idioma","/sair","/resumo","/noticias","/abrir","/programas","/sistema","/agenda","/calendario","/perguntar","/orcamento","/tarefa","/tarefas","/feito","/concluido","/rmtarefa","/pessoas","/equipe","/familia","/pessoa","/novapessoa","/addpessoa","/delegar","/delegacoes","/delegados","/painel","/contatos"];onSubmit=null;onCancel=null;onExit=null;constructor($,Z,Y="",J){this.model=$;this.sessionName=Z;this.authInfo=Y;this.dataDir=J}start($){if(this.onSubmit=$.onSubmit,this.onCancel=$.onCancel,this.onExit=$.onExit,this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.dataDir)this.history=new p6(x9(this.dataDir,"history"));w(C.altOn),process.stdin.setRawMode?.(!0),process.stdin.resume(),process.stdin.on("data",(Z)=>this.onKey(Z)),process.stdout.on("resize",()=>this.onResize()),this.render()}stop(){if(this.stopSpinner(),this.renderTimer)clearTimeout(this.renderTimer);process.stdin.setRawMode?.(!1),process.stdin.pause(),w(C.show),w(C.altOff)}addUserMessage($){this.addLabel("user"),this.addWrapped($),this.lines.push({text:""})}addAssistantMessage($){this.addLabel("assistant"),this.addMarkdown($),this.lines.push({text:""})}startStream(){this.isStreaming=!0,this.streamBuf="",this.streamLines=[],this.streamStartTime=Date.now(),this.addLabel("assistant"),this.startSpinner(),this.renderAll()}appendStream($){if(this.streamBuf+=$,!this.renderTimer)this.renderTimer=setTimeout(()=>{this.renderTimer=null,this.streamLines=E4(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=E4(this.streamBuf).map(($)=>({text:$}));this.lines.push(...this.streamLines),this.lines.push({text:""}),this.streamBuf="",this.streamLines=[],this.isStreaming=!1,this.scrollOffset=0,this.renderAll()}showToolCall($,Z){let Y=Z,J;switch($){case"read_file":if(J=String(Y.path||""),Y.offset)J+=`:${Y.offset}`;break;case"write_file":case"edit_file":J=String(Y.path||"");break;case"search_files":if(J=`/${Y.pattern||""}/`,Y.include)J+=` (${Y.include})`;break;case"find_files":J=String(Y.pattern||"");break;case"list_directory":J=String(Y.path||".");break;case"run_command":if(J=String(Y.command||""),J.length>80)J=J.slice(0,77)+"...";break;default:{let X=JSON.stringify(Y);J=X.length>80?X.slice(0,77)+"...":X}}this.lines.push({text:` ${m.tool}\u2699 ${$}${C.reset} ${C.dim}${J}${C.reset}`}),this.renderMessages()}showToolResult($,Z){let Y=Z.split(`
210
+ `),J=8,X=Y.slice(0,8);for(let z of X){let Q=z.length>this.width-6?z.slice(0,this.width-9)+"...":z;this.lines.push({text:` ${C.dim}${Q}${C.reset}`})}if(Y.length>8)this.lines.push({text:` ${C.dim}... (${Y.length-8} more lines)${C.reset}`});this.renderMessages()}promptApproval($){return this.lines.push({text:` ${m.prompt}? ${$}${C.reset} ${C.dim}[y]es / [n]o / [a]ll${C.reset}`}),this.renderAll(),new Promise((Z)=>{let Y=(J)=>{let X=J.toString().toLowerCase();if(X==="y"||X==="\r"||X===`
211
+ `)process.stdin.removeListener("data",Y),this.lines.push({text:` ${m.sys}approved${C.reset}`}),this.renderAll(),Z(!0);else if(X==="n"||X==="\x1B")process.stdin.removeListener("data",Y),this.lines.push({text:` ${m.err}rejected${C.reset}`}),this.renderAll(),Z(!1);else if(X==="a")process.stdin.removeListener("data",Y),this.lines.push({text:` ${m.sys}approved all for this session${C.reset}`}),this.renderAll(),this._approveAllRequested=!0,Z(!0)};process.stdin.on("data",Y),setTimeout(()=>{process.stdin.removeListener("data",Y),this.lines.push({text:` ${C.dim}timeout \u2014 auto-rejected${C.reset}`}),this.renderAll(),Z(!1)},30000)})}_approveAllRequested=!1;showUsage($){this.lines.push({text:` ${C.dim}tokens: ${$}${C.reset}`}),this.renderAll()}updateSessionCost($){this.sessionCost=$,this.renderHeader()}showError($){this.lines.push({text:` ${m.err}\u2717 ${$}${C.reset}`}),this.lines.push({text:""}),this.renderAll()}showSystem($){for(let Z of $.split(`
212
+ `))this.lines.push({text:` ${m.sys}${Z}${C.reset}`});this.lines.push({text:""}),this.renderAll()}clearMessages(){this.lines=[],this.renderAll()}updateModel($){this.model=$,this.renderHeader()}updateSession($){this.sessionName=$,this.renderHeader()}enableInput(){this.inputBuf="",this.inputPos=0,this.isStreaming=!1,this.history?.reset(),this.renderInput()}disableInput(){w(C.hide)}render(){w(C.hide),w(C.clear),this.renderHeader(),this.renderMessages(),this.renderInput(),w(C.show)}renderAll(){this.renderMessages(),this.renderInput()}renderHeader(){w(C.to(1,1)),w(C.inv);let $=" tinyclaw",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);w($+" ".repeat(J)+Y),w(C.reset),w(C.to(2,1)),w(`${C.dim}${"\u2500".repeat(this.width)}${C.reset}`)}renderMessages(){let Y=this.height-2-2,J=[...this.lines,...this.streamLines],X=J.length,z=Math.max(0,X-Y-this.scrollOffset),Q=Math.min(X,z+Y),K=J.slice(z,Q);w(C.hide);for(let G=0;G<Y;G++)if(w(C.to(2+G+1,1)),w(C.clearLine),G<K.length){let H=M4(K[G].text);if(H.length>this.width)w(K[G].text.slice(0,this.width+(K[G].text.length-H.length))),w(C.reset);else w(K[G].text)}}renderInput(){let $=this.height-1,Z=this.height;if(w(C.to($,1)),w(C.clearLine),w(`${C.dim}${"\u2500".repeat(this.width)}${C.reset}`),w(C.to(Z,1)),w(C.clearLine),this.isStreaming){let Y=((Date.now()-this.streamStartTime)/1000).toFixed(1);w(` ${m.ai}${this.getSpinnerChar()}${C.reset} ${C.dim}streaming... ${Y}s${C.reset}`),w(C.hide)}else{let Y=F4(this.inputBuf)>this.width-3?this.inputBuf.slice(this.inputBuf.length-this.width+3):this.inputBuf;w(`${m.prompt}\u276F${C.reset} ${Y}`);let J=this.inputBuf.slice(0,this.inputPos),X=F4(J)+3;w(C.to(Z,Math.min(X,this.width))),w(C.show)}}onKey($){let Z=$.toString("utf-8");if(Z==="\x03"){if(this.isStreaming)this.onCancel?.();else this.onExit?.();return}if(Z==="\x04"){this.onExit?.();return}if(Z==="\f"){this.render();return}if(this.isStreaming)return;if(Z==="\t"){if(this.inputBuf.startsWith("/")){let Y=this.commands.filter((J)=>J.startsWith(this.inputBuf));if(Y.length===1)this.inputBuf=Y[0]+" ",this.inputPos=this.inputBuf.length,this.renderInput();else if(Y.length>1){let J=Y[0];for(let X of Y)while(!X.startsWith(J))J=J.slice(0,-1);if(J.length>this.inputBuf.length)this.inputBuf=J,this.inputPos=this.inputBuf.length;this.showSystem(Y.join(" "))}}return}if(Z.length>1&&!Z.startsWith("\x1B")&&!b0(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===`
213
+ `){if(this.inputBuf.endsWith("\\")){this.inputBuf=this.inputBuf.slice(0,-1)+`
214
+ `,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=S0(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-=S0(this.inputBuf,this.inputPos),this.renderInput();break;case"C":if(this.inputPos<this.inputBuf.length)this.inputPos+=k0(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=k0(this.inputBuf,this.inputPos);this.inputBuf=this.inputBuf.slice(0,this.inputPos)+this.inputBuf.slice(this.inputPos+J),this.renderInput()}break}}return}if(D9(Z))this.inputBuf=this.inputBuf.slice(0,this.inputPos)+Z+this.inputBuf.slice(this.inputPos),this.inputPos+=Z.length,this.renderInput()}onResize(){this.width=process.stdout.columns||80,this.height=process.stdout.rows||24,this.render()}addLabel($){let Z=new Date().toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});if($==="user")this.lines.push({text:`${m.user}${C.bold} You${C.reset} ${C.dim}${Z}${C.reset}`});else this.lines.push({text:`${m.ai}${C.bold} Claude${C.reset} ${C.dim}${Z}${C.reset}`})}startSpinner(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];this.spinnerFrame=0,this.spinnerTimer=setInterval(()=>{this.spinnerFrame=(this.spinnerFrame+1)%$.length,this.renderInput()},80)}stopSpinner(){if(this.spinnerTimer)clearInterval(this.spinnerTimer),this.spinnerTimer=null}getSpinnerChar(){let $=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];return $[this.spinnerFrame%$.length]}addWrapped($){let Z=I0(" "+$,this.width-2);for(let Y of Z)this.lines.push({text:Y})}addMarkdown($){let Z=E4($);for(let Y of Z)this.lines.push({text:Y})}}function b0($){return[...$].length===1}function D9($){if(!b0($))return!1;let Z=$.codePointAt(0)||0;return Z>=32&&Z!==127}function S0($,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 k0($,Z){if(Z>=$.length)return 0;let Y=$.charCodeAt(Z);if(Y>=55296&&Y<=56319&&Z+1<$.length)return 2;return 1}var W1={"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}},R9={input:3,output:15};function y0($,Z){let Y=A9(Z),J=$.inputTokens/1e6*Y.input*100,X=$.outputTokens/1e6*Y.output*100;return{inputCostCents:J,outputCostCents:X,totalCostCents:J+X}}function A9($){if(W1[$])return W1[$];let Z=$.toLowerCase();if(Z.includes("haiku"))return W1["claude-haiku-4-5-20251001"];if(Z.includes("opus"))return W1["claude-opus-4-20250514"];if(Z.includes("sonnet"))return W1["claude-sonnet-4-20250514"];return R9}class i6{totalInput=0;totalOutput=0;totalCostCents=0;model;constructor($){this.model=$}setModel($){this.model=$}add($){this.totalInput+=$.inputTokens,this.totalOutput+=$.outputTokens;let Z=y0($,this.model);return this.totalCostCents+=Z.totalCostCents,Z}get totals(){return{inputTokens:this.totalInput,outputTokens:this.totalOutput,costCents:this.totalCostCents}}formatUsage($){let Z=y0($,this.model);return`${L4($.inputTokens)} in / ${L4($.outputTokens)} out (~$${(Z.totalCostCents/100).toFixed(4)})`}formatSession(){return`${L4(this.totalInput)} in / ${L4(this.totalOutput)} out | session: ~$${(this.totalCostCents/100).toFixed(4)}`}}function L4($){return $.toLocaleString("en-US")}function _0($,Z={}){let{includeToolCalls:Y=!0,includeTimestamps:J=!0}=Z,X=[];X.push(`# tinyclaw session: ${$.name}`),X.push(`Created: ${new Date($.created).toLocaleString()}`),X.push(""),X.push("---"),X.push("");for(let z of $.messages){let Q=J?` (${new Date(z.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"})})`:"";if(z.role==="user")X.push(`## You${Q}`),X.push(""),X.push(z.content),X.push("");else{if(X.push(`## Claude${Q}`),X.push(""),X.push(z.content),Y&&z.toolCalls?.length){X.push("");for(let K of z.toolCalls){let G=w9(K.name,K.input);X.push(`> **Tool:** \`${K.name}\`${G}`);let H=K.result.split(`
215
+ `).slice(0,5).join(`
216
+ `);if(H.trim()){X.push("> ```");for(let V of H.split(`
217
+ `))X.push(`> ${V}`);X.push("> ```")}}}if(z.usage)X.push(""),X.push(`*Tokens: ${z.usage.inputTokens} in / ${z.usage.outputTokens} out (~$${(z.usage.costCents/100).toFixed(4)})*`);X.push("")}X.push("---"),X.push("")}return X.join(`
218
+ `)}function w9($,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 x4=[{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 n6($){let Z=x4.find((z)=>z.id===$);if(Z)return Z.id;let Y=$.toLowerCase(),J=x4.find((z)=>z.alias===Y);if(J)return J.id;let X=x4.find((z)=>z.id.includes(Y)||z.name.toLowerCase().includes(Y));if(X)return X.id;return $}function f0($){let Z=["Available models:"];for(let Y of x4){let J=Y.id===$?" *":" ",X=Y.tier==="fast"?"\u26A1":Y.tier==="balanced"?"\u2696\uFE0F":"\uD83E\uDDE0";Z.push(`${J} ${Y.alias.padEnd(12)} ${X} ${Y.name}`)}return Z.push(""),Z.push("Use: /model <alias> (e.g., /model sonnet)"),Z.join(`
219
+ `)}function o6($){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 T9={anthropic:{name:"Anthropic",envKey:"ANTHROPIC_API_KEY",description:"Claude models (default)"},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 h0(){let $=["Providers:"];for(let[Z,Y]of Object.entries(T9)){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(`
220
+ `)}class a6{name;apiKey;baseUrl;model;maxTokens;approvalMode="auto";approvalCallback=null;autoApproveAll=!1;constructor($,Z,Y){if(this.name=$,this.model=Z,this.maxTokens=Y,$==="ollama")this.apiKey="ollama",this.baseUrl=process.env.OLLAMA_BASE_URL||"http://localhost:11434/v1";else this.apiKey=process.env.OPENAI_API_KEY||"",this.baseUrl=process.env.OPENAI_BASE_URL||"https://api.openai.com/v1"}setModel($){this.model=$}setApprovalMode($){this.approvalMode=$}setApprovalCallback($){this.approvalCallback=$}setAutoApproveAll($){this.autoApproveAll=$}async*chat($,Z,Y=!0){if(!this.apiKey&&this.name!=="ollama"){yield{type:"error",error:"No API key found. Set OPENAI_API_KEY env var."};return}let J=[{role:"system",content:Z},...$.map((X)=>({role:X.role,content:X.content}))];try{let X=await fetch(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:J,max_tokens:this.maxTokens,stream:!0})});if(!X.ok){let V=await X.text();yield{type:"error",error:`${this.name} API error ${X.status}: ${V.slice(0,200)}`};return}if(!X.body){yield{type:"error",error:"No response body"};return}let z=X.body.getReader(),Q=new TextDecoder,K="",G=Z.length+$.reduce((V,O)=>V+O.content.length,0),H=0;while(!0){let{done:V,value:O}=await z.read();if(V)break;K+=Q.decode(O,{stream:!0});let B=K.split(`
221
+ `);K=B.pop()||"";for(let E of B){if(!E.startsWith("data: "))continue;let R=E.slice(6).trim();if(R==="[DONE]")continue;try{let g=JSON.parse(R).choices?.[0]?.delta;if(g?.content)yield{type:"text",text:g.content},H+=g.content.length}catch{}}}yield{type:"usage",inputTokens:Math.ceil(G/3.5),outputTokens:Math.ceil(H/3.5)},yield{type:"done"}}catch(X){yield{type:"error",error:X instanceof Error?X.message:String(X)}}}}async function c2(...$){let Z=Bun.spawn($,{stdout:"pipe",stderr:"pipe",cwd:process.cwd()}),[Y,J]=await Promise.all([new Response(Z.stdout).text(),new Response(Z.stderr).text()]),X=await Z.exited;return{stdout:Y.trim(),stderr:J.trim(),ok:X===0}}async function v0(){let $=await c2("git","diff","--cached"),Z=await c2("git","diff"),Y=await c2("git","ls-files","--others","--exclude-standard"),J=[];if($.stdout)J.push(`=== STAGED ===
222
+ `+$.stdout);if(Z.stdout)J.push(`=== UNSTAGED ===
223
+ `+Z.stdout);if(Y.stdout)J.push(`=== UNTRACKED ===
224
+ `+Y.stdout);return J.join(`
225
+
226
+ `)||"(no changes)"}async function g0(){let $=await c2("git","status","--short");return $.ok?$.stdout||"(clean)":$.stderr}async function c0(){return(await c2("git","add","-A")).ok}async function d0($){let Z=await c2("git","commit","-m",$);return{ok:Z.ok,output:Z.stdout||Z.stderr}}async function m0(){let $=await c2("git","rev-parse","--is-inside-work-tree");return $.ok&&$.stdout==="true"}var u0={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.
227
+
228
+ Behavior:
229
+ - Write clean, production-grade code. No shortcuts.
230
+ - Always read files before editing. Use edit_file for modifications.
231
+ - Run tests after changes. Check types. Verify builds.
232
+ - Match the project's existing patterns and conventions.
233
+ - Be terse. Code speaks louder than explanations.`},writer:{name:"writer",description:"Technical and creative writer",systemPrompt:`You are a skilled writer who adapts tone and style to the task.
234
+
235
+ Behavior:
236
+ - For technical writing: clear, structured, precise. Use headings, lists, examples.
237
+ - For creative writing: vivid, engaging, varied sentence structure.
238
+ - For emails/messages: concise, professional, direct.
239
+ - Always match the language the user writes in.
240
+ - Use fetch_url to research topics when needed.
241
+ - Never pad with filler. Every sentence should carry weight.`},researcher:{name:"researcher",description:"Deep research and analysis",systemPrompt:`You are a research analyst. Thorough, evidence-based, skeptical.
242
+
243
+ Behavior:
244
+ - Use fetch_url extensively to gather information from multiple sources.
245
+ - Cross-reference claims. Note when sources conflict.
246
+ - Structure findings with clear sections: Summary, Key Findings, Sources, Caveats.
247
+ - Distinguish between facts, opinions, and speculation.
248
+ - Always cite where you found information.
249
+ - If you can't verify something, say so explicitly.`},reviewer:{name:"reviewer",description:"Code review specialist",systemPrompt:`You are a meticulous code reviewer focused on quality, security, and maintainability.
250
+
251
+ Behavior:
252
+ - Read the entire file/diff before commenting.
253
+ - Categorize issues: CRITICAL (bugs, security), WARNING (code smell, performance), SUGGESTION (style, readability).
254
+ - Be specific. Show the line, explain the problem, suggest the fix.
255
+ - Check for: error handling, input validation, edge cases, naming, complexity.
256
+ - Don't nitpick formatting unless it affects readability.
257
+ - Praise good patterns when you see them.`},business:{name:"business",description:"Personal business assistant (Windows-focused)",systemPrompt:""}};function p0($){return u0[$.toLowerCase()]||null}function l0($){let Z=["Personas:"];for(let[Y,J]of Object.entries(u0)){let X=Y===$?" *":" ";Z.push(`${X} ${Y.padEnd(12)} ${J.description}`)}return Z.push(""),Z.push("Use: /persona <name>"),Z.join(`
258
+ `)}async function i0($){try{let Z=D?["powershell","-NoProfile","-Command","Set-Clipboard -Value $input"]:X7?["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 P9,readFileSync as I9,statSync as S9}from"fs";import{extname as k9,resolve as b9}from"path";var y9=new Set([".png",".jpg",".jpeg",".gif",".webp"]),_9=20971520;function n0($){let Z=[],Y=$.split(/\s+/),J=[];for(let X of Y){let z=X.replace(/^["']|["']$/g,""),Q=k9(z).toLowerCase();if(y9.has(Q)){let K=b9(z);if(P9(K))try{if(S9(K).size>_9){J.push(`[image too large: ${z}]`);continue}let V=I9(K).toString("base64"),O=f9(Q);Z.push({path:K,mediaType:O,base64:V}),J.push(`[image: ${z}]`)}catch{J.push(X)}else J.push(X)}else J.push(X)}return{text:J.join(" "),images:Z}}function f9($){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 o0(){let $=[];$.push("=== BRIEFING DIARIO ===");let Z=await $$();if($.push(Z),D)try{let Y=await L2();$.push(`
259
+ --- Agenda ---
260
+ ${Y}`)}catch{$.push(`
261
+ --- Agenda ---
262
+ Outlook nao disponivel.`)}if(D)try{let Y=await e2();$.push(`
263
+ --- Sistema ---
264
+ ${Y}`)}catch{}try{let Y=await x2(["finance","business","tech"],3);$.push(`
265
+ ${Y}`)}catch{$.push(`
266
+ --- Noticias ---
267
+ Falha ao carregar noticias.`)}return $.push(`
268
+ ======================`),$.join(`
269
+ `)}import{existsSync as h9,readFileSync as v9,writeFileSync as g9}from"fs";import{join as c9}from"path";var a0="",r0=()=>c9(a0,"last-morning.txt");function s0($){a0=$;let Z=r0(),Y=new Date().toISOString().split("T")[0];if(!h9(Z))return!0;try{return v9(Z,"utf-8").trim()!==Y}catch{return!0}}function t0(){let $=new Date().toISOString().split("T")[0];g9(r0(),$)}async function e0(){let $=[];$.push("=============================="),$.push(" BOM DIA! Briefing do dia"),$.push(`==============================
270
+ `);let Z=await $$();$.push(Z);let J=D2().filter((G)=>{if(!G.dueAt)return!1;let H=new Date(G.dueAt),V=new Date;return H.toDateString()===V.toDateString()});if(J.length>0)$.push(`
271
+ --- Tarefas do dia ---`),$.push(h2(J));let X=Q1();if(X.length>0)$.push(`
272
+ --- Follow-ups pendentes ---`),$.push(C4(X));let Q=J$().filter((G)=>G.status==="atrasado");if(Q.length>0)$.push(`
273
+ --- Delegacoes atrasadas ---`),$.push(U4(Q));if(D)try{let G=await L2();$.push(`
274
+ --- Agenda ---`),$.push(G)}catch{}try{let G=await x2(["finance","business","tech"],2);$.push(`
275
+ `+G)}catch{}let K=D2();if(K.length>0&&J.length!==K.length)$.push(`
276
+ ${K.length} tarefa(s) pendente(s) no total. Use /tarefas para ver todas.`);return $.push(`
277
+ ==============================`),$.join(`
278
+ `)}var P=null,D4=null,r6=null,s6=0;function YZ($){r6=$}function JZ($="foco",Z=25,Y=5){if(P)return`Pomodoro ja ativo: "${P.label}" (${QZ()}). Use /pomodoro stop para parar.`;return P={startedAt:Date.now(),durationMs:Z*60000,breakMs:Y*60000,label:$,type:"work"},s6++,zZ(),`Pomodoro #${s6} iniciado: "${$}" (${Z}min trabalho / ${Y}min pausa)`}function XZ(){if(!P)return"Nenhum pomodoro ativo.";let $=P.label,Z=Math.floor((Date.now()-P.startedAt)/60000);return R4(),P=null,`Pomodoro parado: "${$}" (${Z}min decorridos)`}function t6(){if(!P)return"Nenhum pomodoro ativo. Use /pomodoro <descricao> para iniciar.";let $=QZ();return`${P.type==="work"?"Trabalhando":"Pausa"}: "${P.label}" \u2014 ${$} restante(s) (ciclo #${s6})`}function zZ(){if(!P)return;R4();let $=P.startedAt+P.durationMs-Date.now();if($<=0){$Z();return}D4=setTimeout($Z,$)}function $Z(){if(!P)return;if(P.type==="work"){let $=`Pomodoro: "${P.label}" concluido! Hora da pausa (${P.breakMs/60000}min).`;ZZ("Pausa!",`"${P.label}" concluido. Descanse ${P.breakMs/60000} minutos.`),r6?.($),P={...P,type:"break",startedAt:Date.now(),durationMs:P.breakMs},zZ()}else ZZ("Volta ao trabalho!","Pausa concluida. Pronto para o proximo ciclo."),r6?.("Pausa concluida! Pronto para o proximo ciclo. Use /pomodoro para iniciar."),R4(),P=null}function R4(){if(D4)clearTimeout(D4),D4=null}function QZ(){if(!P)return"0min";let $=Math.max(0,P.startedAt+P.durationMs-Date.now());return`${Math.ceil($/60000)}min`}async function ZZ($,Z){if(!D)return;let Y=$.replace(/'/g,"''"),J=Z.replace(/'/g,"''"),X=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Y}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Reminder"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("tinyclaw").Show($toast)'].join("; ");try{let z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",X],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>z.kill(),1e4);await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),await z.exited,clearTimeout(Q)}catch{}}function VZ(){R4(),P=null}import{existsSync as GZ,mkdirSync as d9,readFileSync as m9,writeFileSync as u9}from"fs";import{join as p9}from"path";var WZ="",t=[],qZ=()=>p9(WZ,"workflows.json");function e6(){u9(qZ(),JSON.stringify(t,null,2))}function l9(){let $=qZ();if(!GZ($)){t=KZ,e6();return}try{t=JSON.parse(m9($,"utf-8"))}catch{t=KZ,e6()}}var KZ=[{name:"iniciar-dia",description:"Abrir terminal e Postman",steps:[{action:"open_app",target:"terminal"},{action:"wait",target:"2"},{action:"open_app",target:"postman"}]},{name:"dev",description:"Abrir ambiente de desenvolvimento: VSCode e Terminal",steps:[{action:"open_app",target:"vscode"},{action:"wait",target:"1"},{action:"open_app",target:"terminal"}]}];function HZ($){if(WZ=$,!GZ($))d9($,{recursive:!0});l9()}function i9($){return t.find((Z)=>Z.name.toLowerCase()===$.toLowerCase())||null}function UZ($){let Z=t.length;if(t=t.filter((Y)=>Y.name.toLowerCase()!==$.toLowerCase()),t.length===Z)return!1;return e6(),!0}async function $7($,Z){let Y=i9($);if(!Y){let X=t.map((z)=>z.name).join(", ");return`Workflow nao encontrado: "${$}". Disponiveis: ${X}`}if(!D)return"Error: workflows are only available on Windows.";let J=[`Executando workflow: "${Y.name}" \u2014 ${Y.description}`];for(let X=0;X<Y.steps.length;X++){let z=Y.steps[X];switch(z.action){case"open_app":{Z?.(`[${X+1}/${Y.steps.length}] Abrindo ${z.target}...`);let Q=await t2(z.target);J.push(` ${X+1}. ${Q}`);break}case"open_url":{Z?.(`[${X+1}/${Y.steps.length}] Abrindo ${z.target}...`);let Q=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",`Start-Process '${z.target}'`],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>Q.kill(),1e4);await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]),await Q.exited,clearTimeout(K),J.push(` ${X+1}. Opened: ${z.target}`);break}case"run_command":{Z?.(`[${X+1}/${Y.steps.length}] Executando: ${z.target}...`);let Q=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",z.target],{stdout:"pipe",stderr:"pipe"}),K=setTimeout(()=>Q.kill(),30000),[G]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text()]);await Q.exited,clearTimeout(K);let H=G.trim().slice(0,100);J.push(` ${X+1}. Command: ${z.target}${H?" -> "+H:""}`);break}case"wait":{let Q=parseInt(z.target)||1;Z?.(`[${X+1}/${Y.steps.length}] Aguardando ${Q}s...`),await new Promise((K)=>setTimeout(K,Q*1000)),J.push(` ${X+1}. Wait: ${Q}s`);break}}}return J.push(`
279
+ Workflow "${Y.name}" concluido.`),J.join(`
280
+ `)}function CZ(){if(t.length===0)return"Nenhum workflow configurado.";let $=t.map((Z)=>{let Y=Z.steps.map((J)=>`${J.action}:${J.target}`).join(" -> ");return` ${Z.name.padEnd(15)} ${Z.description}
281
+ ${" ".repeat(17)}${Y}`});return`Workflows (${t.length}):
282
+ ${$.join(`
283
+
284
+ `)}`}var X2=new Map,Z7=null;function NZ($){Z7=$}function jZ($,Z=60){if(!D)return"Error: monitor is only available on Windows.";let Y=$.toLowerCase();if(X2.has(Y))return`"${$}" ja esta sendo monitorado.`;let J=setInterval(()=>BZ(Y),Z*1000);return X2.set(Y,{name:$,interval:J,lastSeen:!0}),BZ(Y),`Monitorando "${$}" a cada ${Z}s.`}function OZ($){let Z=$.toLowerCase(),Y=X2.get(Z);if(!Y)return`"${$}" nao esta sendo monitorado.`;return clearInterval(Y.interval),X2.delete(Z),`Monitor parado: "${$}"`}function MZ(){if(X2.size===0)return"Nenhum processo monitorado.";let $=[...X2.values()].map((Z)=>{let Y=Z.lastSeen?"rodando":"PARADO";return` ${Z.name.padEnd(20)} [${Y}]`});return`Processos monitorados (${X2.size}):
285
+ ${$.join(`
286
+ `)}`}function FZ(){for(let $ of X2.values())clearInterval($.interval);X2.clear()}async function BZ($){let Z=X2.get($);if(!Z)return;let Y=await n9(Z.name);if(Z.lastSeen&&!Y){let J=`ALERTA: "${Z.name}" parou de rodar!`;o9("Processo parou!",`"${Z.name}" nao esta mais rodando.`),Z7?.(J)}else if(!Z.lastSeen&&Y){let J=`"${Z.name}" voltou a rodar.`;Z7?.(J)}X2.set($,{...Z,lastSeen:Y})}async function n9($){if(!D)return!1;try{let Z=`(Get-Process -Name '${$}' -ErrorAction SilentlyContinue) -ne $null`,Y=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",Z],{stdout:"pipe",stderr:"pipe"}),J=setTimeout(()=>Y.kill(),1e4),[X]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text()]);return await Y.exited,clearTimeout(J),X.trim().toLowerCase()==="true"}catch{return!1}}async function o9($,Z){if(!D)return;let Y=$.replace(/'/g,"''"),J=Z.replace(/'/g,"''"),X=["[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null","[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",`$template = '<toast><visual><binding template="ToastText02"><text id="1">${Y}</text><text id="2">${J}</text></binding></visual><audio src="ms-winsoundevent:Notification.Default"/></toast>'`,"$xml = New-Object Windows.Data.Xml.Dom.XmlDocument","$xml.LoadXml($template)","$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)",'[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("tinyclaw").Show($toast)'].join("; ");try{let z=Bun.spawn(["powershell","-NoProfile","-NonInteractive","-Command",X],{stdout:"pipe",stderr:"pipe"}),Q=setTimeout(()=>z.kill(),1e4);await Promise.all([new Response(z.stdout).text(),new Response(z.stderr).text()]),await z.exited,clearTimeout(Q)}catch{}}z1();import{writeFileSync as a9}from"fs";import{join as r9}from"path";async function s9(){let $=Y7(process.argv.slice(2));if($.help)J7(),process.exit(0);if($.version)console.log(`tinyclaw v${H1()}`),process.exit(0);let Z=K7();if($.model)Z.model=n6($.model);if($.maxTokens)Z.maxTokens=$.maxTokens;let Y;try{Y=P4(Z.apiKey,Z.authMode)}catch(R){console.error("tinyclaw:",R instanceof Error?R.message:R),process.exit(1)}let{provider:J,model:X}=o6(Z.model),z;if(J==="openai"||J==="ollama")z=new a6(J,X,Z.maxTokens);else{let R=new h6(Y.apiKey,Z.model,Z.maxTokens,Z.toolApproval);R.setAuthRefresh(()=>{let v=H7(Z.apiKey,Z.authMode);if(v&&v.apiKey!==Y.apiKey)return Y=v,R.updateApiKey(v.apiKey),!0;return!1}),z=R}let Q=$.session||"default",K=new g6(Z.dataDir);if($.session)K.switchTo($.session);let G=T0(Z.skillsDir),H=m6(Z.systemPrompt,G,Z.language),V=!$.noTools;G0();let O=C8(r9(Z.dataDir,"..")),B=W8(O);if(B.length>0)V0(B),Y2.push(...q8(B));let E=!process.stdin.isTTY;if($.print||E)await t9(z,K,H,V,$.prompt,E),process.exit(0);await $Y(z,K,Z,Y,G,H,V,B,$.prompt)}async function t9($,Z,Y,J,X,z){let Q=X||"";if(z){let V=await e9();Q=Q?`${Q}
287
+
288
+ ${V}`:V}if(!Q.trim())console.error("tinyclaw: no input provided"),process.exit(1);let K={role:"user",content:Q.trim(),timestamp:Date.now()};Z.addMessage(K);let G="";for await(let V of $.chat(Z.messages,Y,J))if(V.type==="text")process.stdout.write(V.text),G+=V.text;else if(V.type==="error")console.error(`
289
+ tinyclaw error: ${V.error}`);if(G&&!G.endsWith(`
290
+ `))process.stdout.write(`
291
+ `);let H={role:"assistant",content:G,timestamp:Date.now()};Z.addMessage(H)}async function e9(){let $=[];for await(let Z of process.stdin)$.push(Z);return Buffer.concat($).toString("utf-8")}async function $Y($,Z,Y,J,X,z,Q,K,G){let H=new i6(Y.model),V=new l6(Y.model,Z.session.name,U7(J),Y.dataDir),O="default",B=z;if(s8(Y.dataDir),I8(Y.dataDir),h8(Y.dataDir),d8(Y.dataDir),YZ((S)=>V.showSystem(`
292
+ *** ${S} ***
293
+ `)),HZ(Y.dataDir),N6(Y.dataDir),NZ((S)=>V.showSystem(`
294
+ *** ${S} ***
295
+ `)),L8(Y.dataDir,(S)=>{V.showSystem(`
296
+ *** LEMBRETE: ${S.title} ***
297
+ `)}),Y.toolApproval!=="auto"&&$.setApprovalCallback)$.setApprovalCallback(async(S,l,n)=>{if(S==="edit_file"&&l.old_text&&l.new_text){let U=E0(String(l.old_text),String(l.new_text));for(let N of U)V.showSystem(N)}let F=F0(S,l),W=await V.promptApproval(F);if(V._approveAllRequested)$.setAutoApproveAll?.(!0),V._approveAllRequested=!1;return W});for(let S of Z.messages)if(S.role==="user")V.addUserMessage(S.content);else V.addAssistantMessage(S.content);let E=null;async function R(S){if(S.startsWith("/")){await v(S);return}if(Y.maxSessionCost>0){let T=H.totals.costCents;if(T>=Y.maxSessionCost){V.showError(`Budget exceeded (~$${(T/100).toFixed(4)} / $${(Y.maxSessionCost/100).toFixed(4)}). Use /budget <cents> to increase or /clear to reset.`);return}if(T>=Y.maxSessionCost*0.8)V.showSystem(`Budget: ${Math.round(T/Y.maxSessionCost*100)}% used`)}let{text:l,images:n}=n0(S),F={role:"user",content:l,images:n.length>0?n.map((T)=>({mediaType:T.mediaType,base64:T.base64})):void 0,timestamp:Date.now()};Z.addMessage(F),V.addUserMessage(n.length>0?`${l} (${n.length} image${n.length>1?"s":""})`:l),V.disableInput(),V.startStream();let W="",U=[],N={},x=0,b=0;E=new AbortController;try{for await(let T of $.chat(Z.messages,B,Q)){if(E.signal.aborted)break;switch(T.type){case"text":V.appendStream(T.text),W+=T.text;break;case"tool_call":V.flushStream(),V.showToolCall(T.name,T.input),N=T.input;break;case"tool_result":V.showToolResult(T.name,T.result),U.push({id:T.id,name:T.name,input:N,result:T.result}),N={},V.resetStreamBuffer();break;case"tool_blocked":V.showError(T.reason);break;case"usage":x+=T.inputTokens,b+=T.outputTokens;break;case"error":V.showError(T.error);break;case"done":break}}}catch(T){if(!E.signal.aborted)V.showError(T instanceof Error?T.message:String(T))}E=null,V.endStream();let d={inputTokens:x,outputTokens:b},K2=H.add(d);if(x>0||b>0)V.showUsage(H.formatUsage(d)),V.updateSessionCost(`~$${(H.totals.costCents/100).toFixed(4)}`);let P2={role:"assistant",content:W,toolCalls:U.length>0?U:void 0,usage:x>0?{inputTokens:x,outputTokens:b,costCents:K2.totalCostCents}:void 0,timestamp:Date.now()};Z.addMessage(P2),Z.trimHistory(Y.maxHistory),V.enableInput()}async function v(S){let l=S.slice(1).split(" "),n=l[0].toLowerCase(),F=l.slice(1);switch(n){case"exit":case"quit":case"sair":case"q":g();break;case"clear":case"limpar":Z.clear(),V.clearMessages(),V.showSystem("Conversation cleared.");break;case"new":case"novo":case"nova":{let W=F[0]||`s-${Date.now()}`;Z.switchTo(W),V.clearMessages(),V.updateSession(W),V.showSystem(`New session: ${W}`);break}case"load":case"carregar":{let W=F[0];if(!W){V.showError("Usage: /load <name>");break}Z.switchTo(W),V.clearMessages();for(let U of Z.messages)if(U.role==="user")V.addUserMessage(U.content);else V.addAssistantMessage(U.content);V.updateSession(W),V.showSystem(`Loaded: ${W}`);break}case"sessions":case"sessoes":case"ls":{let W=Z.list();if(W.length===0){V.showSystem("No saved sessions.");break}let U=W.map((N)=>{let x=Z.getInfo(N),b=N===Z.session.name?" *":" ",d=x?ZY(x.updated):"",K2=x?`${x.messageCount} msgs`:"";return`${b} ${N.padEnd(20)} ${K2.padEnd(10)} ${d}`});V.showSystem(`Sessions:
298
+ `+U.join(`
299
+ `));break}case"delete":case"deletar":case"rm":{let W=F[0];if(!W){V.showError("Usage: /delete <name>");break}if(Z.delete(W))V.showSystem(`Deleted: ${W}`);else V.showError(`Session not found: ${W}`);break}case"model":case"modelo":{let W=F[0];if(!W){V.showSystem(f0(Y.model)+`
300
+
301
+ `+h0());break}let{provider:U,model:N}=o6(W),x=U==="anthropic"?n6(N):N;if(Y.model=U==="anthropic"?x:`${U}:${x}`,O1(Y),U==="anthropic")$.setModel(x);else V.showSystem(`Note: ${U} provider selected. Restart tinyclaw for full provider switch.`);H.setModel(x),V.updateModel(Y.model),V.showSystem(`Model -> ${Y.model}`);break}case"skills":case"habilidades":{V.showSystem(P0(X));break}case"auth":V.showSystem(`Auth: ${J.source}`+(J.subscriptionType?` (${J.subscriptionType})`:"")+(J.expiresAt?`
302
+ Expires: ${new Date(J.expiresAt).toLocaleString()}`:""));break;case"config":V.showSystem(`Config: ${G7()}`);break;case"export":case"exportar":{let W=new Date().toISOString().split("T")[0],U=F[0]||`tinyclaw-${Z.session.name}-${W}.md`;try{let N=_0(Z.session);a9(U,N),V.showSystem(`Exported to: ${U}`)}catch(N){V.showError(`Export failed: ${N instanceof Error?N.message:N}`)}break}case"cost":case"custo":V.showSystem(`Session: ${H.formatSession()}`);break;case"retry":case"repetir":{let W=[...Z.messages].reverse().find((b)=>b.role==="user");if(!W){V.showError("No previous message to retry.");break}let U=Z.messages,N=0;if(U.length>0&&U[U.length-1].role==="assistant")N++;if(U.length>N&&U[U.length-1-N].role==="user")N++;if(N>0)Z.popMessages(N);V.showSystem("Retrying...");let x=W.images?.length?W.content:W.content;await R(x);break}case"help":case"ajuda":case"?":V.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","","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(`
303
+ `));break;case"commit":case"commitar":{if(!await m0()){V.showError("Not a git repository.");break}let W=await g0();if(W==="(clean)"){V.showSystem("Nothing to commit \u2014 working tree clean.");break}V.showSystem(`Changes:
304
+ `+W),V.disableInput();try{let N=`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.
305
+
306
+ Diff:
307
+ ${(await v0()).slice(0,8000)}`;V.startStream();let x="";for await(let d of $.chat([{role:"user",content:N,timestamp:Date.now()}],"You generate git commit messages. Output ONLY the commit message, nothing else.",!1))if(d.type==="text")x+=d.text,V.appendStream(d.text);else if(d.type==="error")V.showError(d.error);if(V.endStream(),x=x.trim().replace(/^["']|["']$/g,""),!x){V.showError("Failed to generate commit message. Aborting.");break}await c0();let b=await d0(x);if(b.ok)V.showSystem(`Committed: ${x}`);else V.showError(`Commit failed: ${b.output}`)}catch(U){V.showError(`Commit error: ${U instanceof Error?U.message:String(U)}`)}V.enableInput();break}case"persona":case"modo":{let W=F[0];if(!W){V.showSystem(l0(O));break}let U=p0(W);if(!U){V.showError(`Unknown persona: ${W}. Try /persona to see options.`);break}if(O=U.name,U.systemPrompt)B=m6(U.systemPrompt,X,Y.language);else B=z;V.showSystem(`Persona -> ${U.name}: ${U.description}`);break}case"copy":case"copiar":{let W=[...Z.messages].reverse().find((N)=>N.role==="assistant");if(!W){V.showError("No assistant message to copy.");break}if(await i0(W.content))V.showSystem("Copied last response to clipboard.");else V.showError("Failed to copy. Is xclip/pbcopy available?");break}case"ask":case"perguntar":{let W=F.join(" ");if(!W){V.showError("Usage: /ask <question>");break}V.addUserMessage(`(ephemeral) ${W}`),V.disableInput(),V.startStream();let U="";for await(let N of $.chat([{role:"user",content:W,timestamp:Date.now()}],B,!1))if(N.type==="text")U+=N.text,V.appendStream(N.text);else if(N.type==="error")V.showError(N.error);else if(N.type==="usage")V.showUsage(`${N.inputTokens} in / ${N.outputTokens} out (ephemeral)`);V.endStream(),V.enableInput();break}case"fork":{let W=F[0]||`fork-${Date.now()}`;Z.fork(W),V.updateSession(W),V.showSystem(`Forked session -> ${W} (${Z.messages.length} messages copied)`);break}case"plugins":{V.showSystem(U8(K));break}case"budget":case"orcamento":{let W=F[0];if(!W){let N=Y.maxSessionCost,x=H.totals.costCents;if(N===0)V.showSystem(`Budget: unlimited (spent ~$${(x/100).toFixed(4)})`);else{let b=Math.round(x/N*100);V.showSystem(`Budget: ~$${(x/100).toFixed(4)} / $${(N/100).toFixed(4)} (${b}%)`)}break}let U=Number(W);if(isNaN(U)||U<0){V.showError("Usage: /budget <cents> (e.g., /budget 50 for $0.50)");break}Y.maxSessionCost=U,O1(Y),V.showSystem(U===0?"Budget: unlimited":`Budget set: $${(U/100).toFixed(2)}`);break}case"undo":case"desfazer":{if(!z$.peek()){V.showError("Nothing to undo.");break}let U=z$.undo();if(U)V.showSystem(U);break}case"search":case"buscar":{let W=F.join(" ").toLowerCase();if(!W){V.showError("Usage: /search <text>");break}let U=[];for(let N of Z.messages)if(N.content.toLowerCase().includes(W)){let x=N.content.slice(0,100).replace(/\n/g," "),b=new Date(N.timestamp).toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit"});U.push(` [${N.role} ${b}] ${x}${N.content.length>100?"...":""}`)}V.showSystem(U.length>0?`Found ${U.length} match${U.length>1?"es":""}:
308
+ ${U.join(`
309
+ `)}`:`No matches for "${W}".`);break}case"lang":case"language":case"idioma":{let W=F[0];if(!W){V.showSystem(`Language: ${Y.language} (auto = match user's language)`);break}Y.language=W,O1(Y),V.showSystem(`Language -> ${W}`);break}case"briefing":case"resumo":{V.showSystem("Carregando briefing..."),V.disableInput();try{let W=await o0();V.showSystem(W)}catch(W){V.showError(`Briefing falhou: ${W instanceof Error?W.message:String(W)}`)}V.enableInput();break}case"news":case"noticias":{let W=F[0];if(W&&!["business","tech","finance","brazil","world"].includes(W)){V.showSystem(q6());break}V.showSystem("Buscando noticias..."),V.disableInput();try{let N=await x2(W?[W]:void 0);V.showSystem(N)}catch(N){V.showError(`Falha ao buscar noticias: ${N instanceof Error?N.message:String(N)}`)}V.enableInput();break}case"open":case"abrir":{if(!F.join(" ")){V.showSystem(`Apps disponiveis: ${B8().join(", ")}
310
+ Uso: /open <app> ou /open <app> <arquivo>`);break}let U=F.length>1?F.slice(1).join(" "):void 0,N=await t2(F[0],U);V.showSystem(N);break}case"openfile":case"abrirarquivo":{let W=F.join(" ");if(!W){V.showError("Uso: /openfile <caminho>");break}let U=await n1(W);V.showSystem(U);break}case"openurl":{let W=F[0];if(!W){V.showError("Uso: /openurl <url>");break}let U=await i1(W);V.showSystem(U);break}case"apps":case"programas":{V.disableInput();try{let W=await o1();V.showSystem(W)}catch(W){V.showError(`Apps: ${W instanceof Error?W.message:String(W)}`)}V.enableInput();break}case"sysinfo":case"sistema":{V.disableInput();try{let W=await e2();V.showSystem(W)}catch(W){V.showError(`Sysinfo: ${W instanceof Error?W.message:String(W)}`)}V.enableInput();break}case"calendar":case"calendario":case"agenda":case"cal":{V.disableInput();try{let W=await $$(),U=await L2();V.showSystem(`${W}
311
+
312
+ --- Agenda ---
313
+ ${U}`)}catch(W){V.showError(`Calendar: ${W instanceof Error?W.message:String(W)}`)}V.enableInput();break}case"monitor":case"vigiar":{let W=F[0]?.toLowerCase();if(!W||W==="list"||W==="listar")V.showSystem(MZ());else if(W==="stop"||W==="parar"){let U=F[1];if(!U){V.showError("Uso: /monitor stop <processo>");break}V.showSystem(OZ(U))}else{let U=parseInt(F[1])||60;V.showSystem(jZ(W,U))}break}case"workflow":case"fluxo":{let W=F[0]?.toLowerCase();if(!W||W==="list"||W==="listar")V.showSystem(CZ());else if(W==="run"||W==="rodar"){let U=F[1];if(!U){V.showError("Uso: /workflow run <nome>");break}V.disableInput();try{let N=await $7(U,(x)=>V.showSystem(x));V.showSystem(N)}catch(N){V.showError(`Workflow: ${N instanceof Error?N.message:String(N)}`)}V.enableInput()}else if(W==="delete"||W==="deletar"){let U=F[1];if(!U){V.showError("Uso: /workflow delete <nome>");break}if(UZ(U))V.showSystem(`Workflow removido: ${U}`);else V.showError(`Workflow nao encontrado: ${U}`)}else{V.disableInput();try{let U=await $7(W,(N)=>V.showSystem(N));V.showSystem(U)}catch(U){V.showError(`Workflow: ${U instanceof Error?U.message:String(U)}`)}V.enableInput()}break}case"pomodoro":case"foco":{let W=F[0]?.toLowerCase();if(W==="stop"||W==="parar")V.showSystem(XZ());else if(W==="status")V.showSystem(t6());else if(!W)V.showSystem(t6());else{let U=F.join(" "),N=25,x=5;V.showSystem(JZ(U,25,5))}break}case"entrada":case"income":{let W=parseFloat(F[0]);if(isNaN(W)||F.length<3){V.showSystem("Uso: /entrada <valor> <categoria> <descricao>");break}let U=J1("entrada",W,F[1],F.slice(2).join(" "));V.showSystem(`+ R$ ${U.amount.toFixed(2)} (${U.category}) \u2014 ${U.description}`);break}case"saida":case"expense":{let W=parseFloat(F[0]);if(isNaN(W)||F.length<3){V.showSystem("Uso: /saida <valor> <categoria> <descricao>");break}let U=J1("saida",W,F[1],F.slice(2).join(" "));V.showSystem(`- R$ ${U.amount.toFixed(2)} (${U.category}) \u2014 ${U.description}`);break}case"finance":case"financas":case"balanco":{let W=F[0];if(W==="recent"||W==="recentes")V.showSystem(B6());else V.showSystem(Y4()+`
314
+
315
+ `+B6(5));break}case"decisions":case"decisoes":{let W=F.join(" ");if(W){let U=J4(W);V.showSystem(Y$(U))}else V.showSystem(Y$(X4()));break}case"investigar":case"investigate":case"investigacoes":{let W=F.join(" ");if(W){let{searchInvestigations:U,formatInvestigationList:N}=await Promise.resolve().then(() => (z1(),w6));V.showSystem(N(U(W)))}else{let{listInvestigations:U,formatInvestigationList:N}=await Promise.resolve().then(() => (z1(),w6));V.showSystem(N(U()))}break}case"email":case"rascunho":{if(!F.join(" ")){V.showSystem(`Uso: /email <destinatario> <assunto> | <corpo>
316
+ Ou peca a IA: "escreve um email para joao@email.com cobrando o relatorio"`);break}let U=F[0],N=F.slice(1).join(" "),x=N.indexOf("|");if(x===-1){V.showSystem(`Formato: /email <destinatario> <assunto> | <corpo>
317
+ Use | para separar assunto do corpo.`);break}let b=N.slice(0,x).trim(),d=N.slice(x+1).trim();if(!b||!d){V.showError("Assunto e corpo sao obrigatorios.");break}let K2={to:U,subject:b,body:d};V.showSystem(Z4(K2)),V.disableInput();try{let P2=await $4(K2);V.showSystem(P2)}catch(P2){V.showError(`Email: ${P2 instanceof Error?P2.message:String(P2)}`)}V.enableInput();break}case"memo":case"anotar":case"note":{let W=F.join(" ");if(!W){let x=Y1();V.showSystem(v2(x));break}let U=t1(W),N=U.tags.length>0?` [${U.tags.map((x)=>"#"+x).join(" ")}]`:"";V.showSystem(`Memo salvo${N} {${U.id}}`);break}case"memos":case"notas":{let W=F.join(" ");if(W){let U=e1(W);V.showSystem(v2(U))}else{let U=Y1();V.showSystem(v2(U))}break}case"memotags":case"tags":{V.showSystem(k8());break}case"rmmemo":case"rmnota":{let W=F[0];if(!W){V.showError("Uso: /rmmemo <id>");break}if(S8(W))V.showSystem("Memo removido.");else V.showError(`Memo nao encontrado: ${W}`);break}case"people":case"pessoas":case"equipe":case"team":case"familia":case"family":case"contato":case"contatos":case"contacts":{let U={equipe:"equipe",team:"equipe",familia:"familia",family:"familia",contato:"contato",contatos:"contato",contacts:"contato"}[n]||F[0],N=G4(U);V.showSystem(q4(N));break}case"person":case"pessoa":{let W=F.join(" ");if(!W){V.showError("Uso: /person <nome>");break}let U=w2(W);if(!U){V.showError(`Pessoa nao encontrada: "${W}"`);break}V.showSystem(H4(U));break}case"addperson":case"addpessoa":case"novapessoa":{let W=F[0];if(!W||!["equipe","familia","contato"].includes(W)){V.showSystem(`Uso: /addperson <equipe|familia|contato> <nome> [papel]
318
+ Ex: /addperson equipe Joao dev frontend`);break}let N=F.slice(1).join(" ");if(!N){V.showError("Nome obrigatorio. Ex: /addperson equipe Joao dev frontend");break}let[x,...b]=N.split(","),d=b.join(",").trim()||void 0,K2=K4(x.trim(),W,d);V.showSystem(`Adicionado: ${K2.name} (${W}) [${K2.id}]`);break}case"delegate":case"delegar":{let W=F[0];if(!W||F.length<2){V.showSystem(`Uso: /delegate <pessoa> <tarefa>
319
+ Ex: /delegate Joao revisar relatorio`);break}let U=F.slice(1).join(" "),N=W4(W,U);if(!N){V.showError(`Pessoa nao encontrada: "${W}"`);break}V.showSystem(`Delegado para ${W}: "${U}" [${N.id}]`);break}case"delegations":case"delegacoes":case"delegados":{let W=F[0],U=J$(W);V.showSystem(U4(U));break}case"followups":{let W=Q1();V.showSystem(C4(W));break}case"dashboard":case"painel":{V.showSystem(B4());break}case"task":case"tarefa":{let W=F.join(" ");if(!W){let d=D2();V.showSystem(h2(d));break}let U=Z1(W),N=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(!N)N=W;let x=r1(N,U||void 0),b=U?` \u2014 lembrete: ${U.toLocaleTimeString("pt-BR",{hour:"2-digit",minute:"2-digit"})}`:"";V.showSystem(`Tarefa criada: "${x.title}"${b} [${x.id}]`);break}case"tasks":case"tarefas":{let W=F[0]==="all"||F[0]==="todas",U=D2(W);V.showSystem(h2(U));break}case"done":case"feito":case"concluido":{let W=F.join(" ");if(!W){V.showError("Uso: /done <id ou parte do titulo>");break}let U=s1(W);if(U)V.showSystem(`Concluida: "${U.title}"`);else V.showError(`Tarefa nao encontrada: "${W}"`);break}case"rmtask":case"rmtarefa":{let W=F.join(" ");if(!W){V.showError("Uso: /rmtask <id ou parte do titulo>");break}if(D8(W))V.showSystem("Tarefa removida.");else V.showError(`Tarefa nao encontrada: "${W}"`);break}default:V.showError(`Unknown command: /${n}. Try /help`)}}function g(){x8(),VZ(),FZ(),V.stop(),process.exit(0)}process.on("SIGINT",g),process.on("SIGTERM",g),V.start({onSubmit:R,onCancel:()=>{E?.abort(),V.endStream(),V.showSystem("Cancelled."),V.enableInput()},onExit:g});let e=J.source==="subscription"?`Authenticated via Claude ${J.subscriptionType} subscription.`:"Authenticated via API key.";if(V.showSystem(`tinyclaw v${H1()} \u2014 the micro AI assistant.
320
+ ${e}
321
+ Type /ajuda for commands.`),s0(Y.dataDir))try{let S=await e0();V.showSystem(S),t0()}catch{}if(G)await R(G)}function ZY($){if(!$||$<=0)return"";let Z=Date.now()-$;if(Z<0)return"";let Y=Math.floor(Z/60000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;let J=Math.floor(Y/60);if(J<24)return`${J}h ago`;let X=Math.floor(J/24);if(X>365)return`${Math.floor(X/365)}y ago`;return`${X}d ago`}s9().catch(($)=>{try{process.stdin.setRawMode?.(!1),process.stdout.write("\x1B[?1049l"),process.stdout.write("\x1B[?25h")}catch{}console.error("Fatal:",$),process.exit(1)});