@maincode-ai/matilda-code 0.21.11 → 0.21.12

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 (123) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +16 -5
  2. package/bundled/mainy/docs/configuration/trusted-folders.md +12 -6
  3. package/chunks/agent-WM63A6NK.js +3 -0
  4. package/chunks/agent-headless-QIUBDKPW.js +3 -0
  5. package/chunks/{anthropicContentGenerator-IYZILRDW.js → anthropicContentGenerator-VKFTAIU3.js} +1 -1
  6. package/chunks/{askUserQuestion-XWHJY3DM.js → askUserQuestion-2QI4NSFJ.js} +1 -1
  7. package/chunks/{ca-EUJBUYX5.js → ca-I2HEEIL7.js} +1 -1
  8. package/chunks/{chunk-MH2P4YXC.js → chunk-27Q5KW3A.js} +2 -2
  9. package/chunks/{chunk-NYEWHSBL.js → chunk-2HTPVSGT.js} +1 -1
  10. package/chunks/{chunk-2HQMJ2IU.js → chunk-2MOGYHWM.js} +1 -1
  11. package/chunks/{chunk-WRQLIPXW.js → chunk-3IRGBRSP.js} +10 -10
  12. package/chunks/{chunk-NIQK6NX3.js → chunk-5C2RJ5RR.js} +1 -1
  13. package/chunks/{chunk-T4P4KEDW.js → chunk-6E766NPX.js} +1 -1
  14. package/chunks/{chunk-QH7736R5.js → chunk-6EQMZNIY.js} +1 -1
  15. package/chunks/{chunk-4FVBPNTZ.js → chunk-6T2GIM76.js} +1 -1
  16. package/chunks/{chunk-25NCTG5H.js → chunk-6Z2MV7ZY.js} +55 -53
  17. package/chunks/chunk-BVOCFLC4.js +56 -0
  18. package/chunks/chunk-CSJTA7NE.js +101 -0
  19. package/chunks/{chunk-SNLH42QJ.js → chunk-CZGZ3KK7.js} +1 -1
  20. package/chunks/{chunk-JXUDKX6D.js → chunk-DE3HKC2W.js} +1 -1
  21. package/chunks/{chunk-4CSSDBOS.js → chunk-DOOFGSRV.js} +10 -10
  22. package/chunks/{chunk-RK2AKQAX.js → chunk-FPO57O66.js} +6 -6
  23. package/chunks/{chunk-ODZOYHIC.js → chunk-GOJCMVJJ.js} +1 -1
  24. package/chunks/{chunk-FFFZ2QMG.js → chunk-GTVCJCHR.js} +1 -1
  25. package/chunks/{chunk-SUH3UUWZ.js → chunk-JCE3JAVC.js} +1 -1
  26. package/chunks/chunk-JRECUFB3.js +2630 -0
  27. package/chunks/chunk-KHHJYBR5.js +9 -0
  28. package/chunks/{chunk-GO2GA2GY.js → chunk-LUNDTQ3G.js} +1 -1
  29. package/chunks/{chunk-5427BPR2.js → chunk-MCQUPLRE.js} +1 -1
  30. package/chunks/{chunk-QN6WSWMM.js → chunk-MO2HXJG5.js} +1 -1
  31. package/chunks/{chunk-ELH4YHJR.js → chunk-PGXQZVLX.js} +1 -1
  32. package/chunks/{chunk-Q55AVE2N.js → chunk-QVCGLQCI.js} +11 -11
  33. package/chunks/{chunk-W5CGKUM4.js → chunk-S3CWEVTS.js} +1 -1
  34. package/chunks/{chunk-YMIF2DMT.js → chunk-VTGICC67.js} +1 -1
  35. package/chunks/chunk-WC2VTVCE.js +27 -0
  36. package/chunks/{chunk-SPW5DXX4.js → chunk-WV3IUPZS.js} +1 -1
  37. package/chunks/{chunk-4YVN5HXG.js → chunk-YJAKOETP.js} +2 -2
  38. package/chunks/{chunk-WHG6N5X2.js → chunk-YRQP3SLC.js} +1 -1
  39. package/chunks/{chunk-GUFIMKF5.js → chunk-YV3PUOBU.js} +1 -1
  40. package/chunks/{computer-use-SXP25RZQ.js → computer-use-WKDNUTLD.js} +1 -1
  41. package/chunks/contextCommand-DAB3HOHY.js +3 -0
  42. package/chunks/{cron-create-2UI4AT4Q.js → cron-create-F2LXM2OA.js} +1 -1
  43. package/chunks/{cron-delete-ZB6BOTFF.js → cron-delete-DE6Q2S2L.js} +1 -1
  44. package/chunks/{cron-list-YYAXNHB6.js → cron-list-IAQEJVV7.js} +1 -1
  45. package/chunks/{de-DNEPG7S7.js → de-AQXFJYZI.js} +1 -1
  46. package/chunks/edit-QQNJZ55P.js +43 -0
  47. package/chunks/{en-NOD6KQNM.js → en-EJLDYIBM.js} +1 -1
  48. package/chunks/{enter-worktree-X47BSJLE.js → enter-worktree-5X5SAMBJ.js} +1 -1
  49. package/chunks/{enterPlanMode-F22ZNTYJ.js → enterPlanMode-HP35SPLN.js} +1 -1
  50. package/chunks/{exit-worktree-XY5UMDHX.js → exit-worktree-SRKZBEYF.js} +1 -1
  51. package/chunks/exitPlanMode-WSPTGGVN.js +120 -0
  52. package/chunks/{fr-2OE5WLJ4.js → fr-6TDHK7F2.js} +1 -1
  53. package/chunks/{geminiContentGenerator-EQEGOXOV.js → geminiContentGenerator-RJ73DQAP.js} +1 -1
  54. package/chunks/{glob-KSBEWI3E.js → glob-QQ6LGKDX.js} +1 -1
  55. package/chunks/{goal-tools-6QTC3UI7.js → goal-tools-C6BSBHCF.js} +1 -1
  56. package/chunks/{grep-6TTPZ524.js → grep-MVCOBUYW.js} +1 -1
  57. package/chunks/{ja-3B6V5KS7.js → ja-GGNJR7AR.js} +1 -1
  58. package/chunks/{keychain-token-storage-54BNK6VH.js → keychain-token-storage-KQK6MNOJ.js} +1 -1
  59. package/chunks/{ls-YWZU3FYL.js → ls-JYJXFSXN.js} +1 -1
  60. package/chunks/{lsp-4CJDKEEC.js → lsp-DYDK6XCS.js} +1 -1
  61. package/chunks/{matildaAgentContentGenerator-OV4U6DJD.js → matildaAgentContentGenerator-YUYS4336.js} +1 -1
  62. package/chunks/{matildaContentGenerator-ETIAWE22.js → matildaContentGenerator-O4Z2QPCP.js} +1 -1
  63. package/chunks/{matildaOAuth2-WOY7ZS43.js → matildaOAuth2-7COTQQR2.js} +1 -1
  64. package/chunks/mcp-client-RXVQU5VI.js +3 -0
  65. package/chunks/monitor-77KXDXPR.js +32 -0
  66. package/chunks/{notebook-edit-TL7CI5EA.js → notebook-edit-TKJD2EQZ.js} +1 -1
  67. package/chunks/{openaiContentGenerator-MGASUFQL.js → openaiContentGenerator-2EALAM3U.js} +1 -1
  68. package/chunks/{pt-KP2JCPUY.js → pt-D6L2QTDM.js} +1 -1
  69. package/chunks/read-file-3KUAH6ND.js +3 -0
  70. package/chunks/ripGrep-U2PLKXMY.js +3 -0
  71. package/chunks/{ru-K7IQQKHC.js → ru-BNJCHDYO.js} +1 -1
  72. package/chunks/{scheduler-TKWPD4LP.js → scheduler-J7VU2V5Y.js} +1 -1
  73. package/chunks/{send-message-OO2HAKCC.js → send-message-P3SMWNEE.js} +1 -1
  74. package/chunks/{serve-ZQX2WBLF.js → serve-FXH6EBQ6.js} +36 -36
  75. package/chunks/shell-PXR2AXDD.js +3 -0
  76. package/chunks/{skill-KDM3UUML.js → skill-HZPFEAPF.js} +1 -1
  77. package/chunks/src-RFAEPLY7.js +3 -0
  78. package/chunks/{symbol-search-ALYOX5JN.js → symbol-search-EAIZPWN7.js} +1 -1
  79. package/chunks/{syntheticOutput-UASKABJH.js → syntheticOutput-432LXITX.js} +1 -1
  80. package/chunks/task-create-Z3QRCMX4.js +3 -0
  81. package/chunks/{task-detach-I67ZE5MX.js → task-detach-XMSJ3HBM.js} +1 -1
  82. package/chunks/{task-list-5BGX4G5N.js → task-list-GXAJW3JP.js} +1 -1
  83. package/chunks/{task-stop-ERI5X4AO.js → task-stop-NTS62FLG.js} +1 -1
  84. package/chunks/{task-update-CD3W556L.js → task-update-AR26UFYZ.js} +1 -1
  85. package/chunks/{team-create-F4KQRGMB.js → team-create-PYXFVIR5.js} +1 -1
  86. package/chunks/{team-delete-5U3GBFKJ.js → team-delete-OMYVUAQU.js} +1 -1
  87. package/chunks/todoWrite-5NZ7CHTC.js +3 -0
  88. package/chunks/{tool-search-JFCD5W5M.js → tool-search-RKZDSRYS.js} +1 -1
  89. package/chunks/tree-sitter-bash-2SWKO5B7.js +3 -0
  90. package/chunks/{web-fetch-REWGIRWQ.js → web-fetch-VW3SVDQ6.js} +13 -13
  91. package/chunks/{web-search-OX2DPEVN.js → web-search-XQUIZARL.js} +1 -1
  92. package/chunks/{workflow-SEFYGBED.js → workflow-YXNXDRWZ.js} +2 -2
  93. package/chunks/{write-file-UAGVBZMC.js → write-file-XDDLTGSG.js} +1 -1
  94. package/cli.js +459 -449
  95. package/locales/ca.js +1 -0
  96. package/locales/de.js +1 -0
  97. package/locales/en.js +1 -0
  98. package/locales/fr.js +1 -0
  99. package/locales/ja.js +1 -0
  100. package/locales/pt.js +1 -0
  101. package/locales/ru.js +1 -0
  102. package/package.json +2 -2
  103. package/sandbox-macos-restrictive-closed.sb +3 -0
  104. package/sandbox-macos-restrictive-open.sb +3 -0
  105. package/sandbox-macos-restrictive-proxied.sb +3 -0
  106. package/chunks/agent-ZFZ4HJQC.js +0 -3
  107. package/chunks/agent-headless-KH2BKLP7.js +0 -3
  108. package/chunks/chunk-GHBKFIHC.js +0 -35
  109. package/chunks/chunk-HWOQNYAO.js +0 -27
  110. package/chunks/chunk-NVM7W7TG.js +0 -101
  111. package/chunks/chunk-QFNFLE2I.js +0 -2625
  112. package/chunks/chunk-XCFLI3OC.js +0 -9
  113. package/chunks/contextCommand-3GN5CAOK.js +0 -3
  114. package/chunks/edit-KX6V4PH3.js +0 -39
  115. package/chunks/exitPlanMode-G3QLIWJ4.js +0 -90
  116. package/chunks/monitor-F4K5HOZX.js +0 -32
  117. package/chunks/read-file-6EAPS2KG.js +0 -3
  118. package/chunks/ripGrep-K6SFFUIE.js +0 -3
  119. package/chunks/shell-AZRK5GIO.js +0 -3
  120. package/chunks/src-SGI6VLOS.js +0 -3
  121. package/chunks/task-create-EBJD55TB.js +0 -3
  122. package/chunks/todoWrite-YGG6AZ3A.js +0 -3
  123. package/chunks/tree-sitter-bash-XNCMPQBK.js +0 -3
@@ -0,0 +1,9 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{d as m}from"./chunk-27Q5KW3A.js";import{b as w}from"./chunk-GZPNIYVZ.js";w();import{URL as E}from"node:url";var p=[/^10\./,/^127\./,/^172\.(1[6-9]|2[0-9]|3[0-1])\./,/^192\.168\./,/^::1$/,/^fc00:/,/^fe80:/],T=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID"]),S=new Set([...T,"ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]),o=class extends Error{constructor(n,s){super(n);this.code=s;this.name="FetchError"}};function N(e){try{let t=new E(e).hostname;return p.some(n=>n.test(t))}catch{return!1}}var b=new Set([301,302,303,307,308]);function _(e,t){try{let n=new E(e),s=new E(t),f=n.protocol==="http:"&&s.protocol==="https:";return s.protocol!==n.protocol&&!f||s.port!==n.port||s.username||s.password?!1:s.hostname===n.hostname}catch{return!1}}async function U(e,t){let n=AbortSignal.timeout(t.timeoutMs),s=t.signal?AbortSignal.any([t.signal,n]):n,f=a=>t.signal?.aborted?new o("Request aborted","ABORT_ERR"):n.aborted?new o(`Request timed out after ${t.timeoutMs}ms`,"ETIMEDOUT"):a instanceof o?a:new o(m(a),d(a)),i=e;for(let a=0;a<=t.maxRedirects;a++){let r;try{r=await fetch(i,{signal:s,headers:t.headers,redirect:"manual"})}catch(c){throw f(c)}if(b.has(r.status)){let c=r.headers.get("location");if(await r.body?.cancel().catch(()=>{}),!c)throw new o("Redirect response missing Location header");let u;try{u=new E(c,i).toString()}catch{throw new o(`Redirect response has a malformed Location header: ${c}`)}if(!_(i,u))return{kind:"cross-host-redirect",originalUrl:i,redirectUrl:u,status:r.status};i=u;continue}let l=r.headers.get("content-type")??"";if(r.status<200||r.status>=300)return await r.body?.cancel().catch(()=>{}),{kind:"response",status:r.status,statusText:r.statusText,contentType:l,body:Buffer.alloc(0),finalUrl:i};let h=Number(r.headers.get("content-length"));if(Number.isFinite(h)&&h>t.maxBytes)throw await r.body?.cancel().catch(()=>{}),new o(`Response too large: ${h} bytes exceeds the ${t.maxBytes}-byte limit`,"EMSGSIZE");let R=[],g=0;if(r.body){let c=r.body.getReader();try{for(;;){let{done:u,value:y}=await c.read();if(u)break;if(g+=y.byteLength,g>t.maxBytes)throw new o(`Response too large: exceeded the ${t.maxBytes}-byte limit while reading`,"EMSGSIZE");R.push(y)}}catch(u){throw await c.cancel().catch(()=>{}),f(u)}finally{c.releaseLock()}}return{kind:"response",status:r.status,statusText:r.statusText,contentType:l,body:Buffer.concat(R,g),finalUrl:i}}throw new o(`Too many redirects (more than ${t.maxRedirects})`,"EMAXREDIRECTS")}function d(e){if(!(!e||typeof e!="object")&&"code"in e&&typeof e.code=="string")return e.code}function A(e){if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(e instanceof Error)return e.message;if(!e||typeof e!="object")return;let t=e.message;if(typeof t=="string")return t}function x(e){if(!(e instanceof Error))return;let t=e.cause;if(!t)return;let n=d(t),s=A(t);if(!(!n&&!s))return n&&s&&!s.includes(n)?`${n}: ${s}`:s??n}function L(e,t={}){let n=m(e),s=e instanceof Error?d(e.cause)??d(e):d(e),f=x(e),i=[n,f?`(cause: ${f})`:void 0].filter(Boolean).join(" "),a=n.toLowerCase().includes("fetch failed")||s!=null&&S.has(s),r=s!=null&&T.has(s);if(!a)return i;let l=["","Troubleshooting:",...t.url?[`- Confirm you can reach ${t.url} from this machine.`]:[],"- If you are behind a proxy, pass `--proxy <url>` (or set `proxy` in settings).",...r?["- If your network uses a corporate TLS inspection CA, set `NODE_EXTRA_CA_CERTS` to your CA bundle."]:[]];return`${i}${l.join(`
4
+ `)}`}export{N as a,U as b,L as c};
5
+ /**
6
+ * @license
7
+ * Copyright 2025 Google LLC
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as u,ba as M}from"./chunk-MH2P4YXC.js";import{b as I}from"./chunk-GZPNIYVZ.js";I();import*as P from"node:crypto";import*as n from"node:fs";import*as f from"node:fs/promises";import*as O from"node:path";var C=M("ATOMIC_WRITE");async function L(t,o,e,i,w=f.rename){for(let a=0;a<=e;a++)try{await w(t,o);return}catch(c){if(!(u(c)&&(c.code==="EPERM"||c.code==="EACCES"))||a===e)throw c;await new Promise(v=>setTimeout(v,i*2**a))}}async function $(t){let e=t;for(let w=0;w<40;w++){let a;try{a=await f.lstat(e)}catch(l){if(u(l)&&l.code==="ENOENT")return e;throw l}if(!a.isSymbolicLink())return e;let c=await f.readlink(e);if(O.isAbsolute(c))e=c;else{let l=await f.realpath(O.dirname(e));e=O.resolve(l,c)}}let i=new Error(`ELOOP: too many levels of symbolic links, resolve '${t}'`);throw i.code="ELOOP",i}async function B(t,o,e,i){let w=e?.retries??3,a=e?.delayMs??50,c=e?.flush??!0,l=e?.encoding??"utf-8",v=i?.rename??f.rename,F=i?.writeFile??f.writeFile,x=i?.open??f.open,T=i?.chmod??f.chmod,A=i?.fchmod??((d,s)=>d.chmod(s)),b=i?.unlink??f.unlink,r=e?.noFollow?t:await $(t).catch(d=>{throw N(d,t)}),S;try{S=await f.stat(r)}catch(d){if(!u(d)||d.code!=="ENOENT")throw d}let W;(!e?.forceMode||e?.mode===void 0)&&(W=S!==void 0?S.mode&4095:void 0);let y=W??e?.mode,p={};typeof o=="string"&&(p.encoding=l),c&&(p.flush=!0),y!==void 0&&(p.mode=y);let k=async d=>{if(y!==void 0)try{await T(d,y)}catch(s){if(!u(s)||s.code!=="ENOSYS"&&s.code!=="ENOTSUP")throw s}},h=()=>{if(S===void 0||process.platform==="win32")return!1;let d=process.geteuid?.();return d===void 0?!1:S.uid!==d};if(S!==void 0&&S.isFile()&&h()){await f.writeFile(r,o,p),await k(r);return}let m=`${r}.${P.randomBytes(6).toString("hex")}.tmp`;try{await F(m,o,p),await k(m),await L(m,r,w,a,v)}catch(d){try{await b(m)}catch{}if(u(d)&&d.code==="EXDEV")try{if(e?.noFollow){try{await b(r)}catch(g){if(!u(g)||g.code!=="ENOENT")throw g}let s=await x(r,n.constants.O_WRONLY|n.constants.O_CREAT|n.constants.O_EXCL,y??438),E=!1;try{try{if(await s.writeFile(typeof o=="string"?Buffer.from(o,l):o),c&&await s.sync(),y!==void 0)try{await A(s,y)}catch(g){if(!u(g)||g.code!=="ENOSYS"&&g.code!=="ENOTSUP")throw g}E=!0}finally{await s.close()}}catch(g){if(!E)try{await b(r)}catch(R){C.debug(`orphan unlink failed for ${r}:`,R)}throw g}}else await F(r,o,p),await k(r);return}catch(s){throw N(s,r)}throw N(d,r)}}function N(t,o,e="atomicWriteFile"){return t instanceof Error&&!t.message.startsWith(`${e}(`)&&(t.message=`${e}(${JSON.stringify(o)}): ${t.message}`),t}async function X(t,o,e){await B(t,JSON.stringify(o,null,2),{encoding:"utf-8",...e})}function H(t){if(t<=0)return;let o=new SharedArrayBuffer(4),e=new Int32Array(o);Atomics.wait(e,0,0,t)}function Y(t,o,e,i,w=n.renameSync){for(let a=0;a<=e;a++)try{w(t,o);return}catch(c){if(!(u(c)&&(c.code==="EPERM"||c.code==="EACCES"))||a===e)throw c;H(i*2**a)}}function D(t){let e=t;for(let w=0;w<40;w++){let a;try{a=n.lstatSync(e)}catch(l){if(u(l)&&l.code==="ENOENT")return e;throw l}if(!a.isSymbolicLink())return e;let c=n.readlinkSync(e);if(O.isAbsolute(c))e=c;else{let l=n.realpathSync(O.dirname(e));e=O.resolve(l,c)}}let i=new Error(`ELOOP: too many levels of symbolic links, resolve '${t}'`);throw i.code="ELOOP",i}function V(t,o,e,i){let w=e?.retries??3,a=e?.delayMs??50,c=e?.flush??!0,l=e?.encoding??"utf-8",v=i?.rename??n.renameSync,F=i?.writeFile??n.writeFileSync,x=i?.open??n.openSync,T=i?.chmod??n.chmodSync,A=i?.fchmod??n.fchmodSync,b=i?.unlink??n.unlinkSync,r;if(e?.noFollow)r=t;else try{r=D(t)}catch(h){throw N(h,t,"atomicWriteFileSync")}let S=`${r}.${P.randomBytes(6).toString("hex")}.tmp`,W;if(!e?.forceMode||e?.mode===void 0)try{W=n.statSync(r).mode&4095}catch(h){if(!u(h)||h.code!=="ENOENT")throw h}let y=W??e?.mode,p={};typeof o=="string"&&(p.encoding=l),c&&(p.flush=!0),y!==void 0&&(p.mode=y);let k=h=>{if(y!==void 0)try{T(h,y)}catch(m){if(!u(m)||m.code!=="ENOSYS"&&m.code!=="ENOTSUP")throw m}};try{F(S,o,p),k(S),Y(S,r,w,a,v)}catch(h){try{b(S)}catch{}if(u(h)&&h.code==="EXDEV")try{if(e?.noFollow){try{b(r)}catch(s){if(!u(s)||s.code!=="ENOENT")throw s}let m=x(r,n.constants.O_WRONLY|n.constants.O_CREAT|n.constants.O_EXCL,y??438),d=!1;try{try{let s=typeof o=="string"?Buffer.from(o,l):o;if(n.writeFileSync(m,s),c&&n.fsyncSync(m),y!==void 0)try{A(m,y)}catch(E){if(!u(E)||E.code!=="ENOSYS"&&E.code!=="ENOTSUP")throw E}d=!0}finally{n.closeSync(m)}}catch(s){if(!d)try{b(r)}catch(E){C.debug(`orphan unlink failed for ${r}:`,E)}throw s}}else F(r,o,p),k(r);return}catch(m){throw N(m,r,"atomicWriteFileSync")}throw N(h,r,"atomicWriteFileSync")}}export{L as a,B as b,X as c,Y as d,V as e};
3
+ import{b as u,ba as M}from"./chunk-27Q5KW3A.js";import{b as I}from"./chunk-GZPNIYVZ.js";I();import*as P from"node:crypto";import*as n from"node:fs";import*as f from"node:fs/promises";import*as O from"node:path";var C=M("ATOMIC_WRITE");async function L(t,o,e,i,w=f.rename){for(let a=0;a<=e;a++)try{await w(t,o);return}catch(c){if(!(u(c)&&(c.code==="EPERM"||c.code==="EACCES"))||a===e)throw c;await new Promise(v=>setTimeout(v,i*2**a))}}async function $(t){let e=t;for(let w=0;w<40;w++){let a;try{a=await f.lstat(e)}catch(l){if(u(l)&&l.code==="ENOENT")return e;throw l}if(!a.isSymbolicLink())return e;let c=await f.readlink(e);if(O.isAbsolute(c))e=c;else{let l=await f.realpath(O.dirname(e));e=O.resolve(l,c)}}let i=new Error(`ELOOP: too many levels of symbolic links, resolve '${t}'`);throw i.code="ELOOP",i}async function B(t,o,e,i){let w=e?.retries??3,a=e?.delayMs??50,c=e?.flush??!0,l=e?.encoding??"utf-8",v=i?.rename??f.rename,F=i?.writeFile??f.writeFile,x=i?.open??f.open,T=i?.chmod??f.chmod,A=i?.fchmod??((d,s)=>d.chmod(s)),b=i?.unlink??f.unlink,r=e?.noFollow?t:await $(t).catch(d=>{throw N(d,t)}),S;try{S=await f.stat(r)}catch(d){if(!u(d)||d.code!=="ENOENT")throw d}let W;(!e?.forceMode||e?.mode===void 0)&&(W=S!==void 0?S.mode&4095:void 0);let y=W??e?.mode,p={};typeof o=="string"&&(p.encoding=l),c&&(p.flush=!0),y!==void 0&&(p.mode=y);let k=async d=>{if(y!==void 0)try{await T(d,y)}catch(s){if(!u(s)||s.code!=="ENOSYS"&&s.code!=="ENOTSUP")throw s}},h=()=>{if(S===void 0||process.platform==="win32")return!1;let d=process.geteuid?.();return d===void 0?!1:S.uid!==d};if(S!==void 0&&S.isFile()&&h()){await f.writeFile(r,o,p),await k(r);return}let m=`${r}.${P.randomBytes(6).toString("hex")}.tmp`;try{await F(m,o,p),await k(m),await L(m,r,w,a,v)}catch(d){try{await b(m)}catch{}if(u(d)&&d.code==="EXDEV")try{if(e?.noFollow){try{await b(r)}catch(g){if(!u(g)||g.code!=="ENOENT")throw g}let s=await x(r,n.constants.O_WRONLY|n.constants.O_CREAT|n.constants.O_EXCL,y??438),E=!1;try{try{if(await s.writeFile(typeof o=="string"?Buffer.from(o,l):o),c&&await s.sync(),y!==void 0)try{await A(s,y)}catch(g){if(!u(g)||g.code!=="ENOSYS"&&g.code!=="ENOTSUP")throw g}E=!0}finally{await s.close()}}catch(g){if(!E)try{await b(r)}catch(R){C.debug(`orphan unlink failed for ${r}:`,R)}throw g}}else await F(r,o,p),await k(r);return}catch(s){throw N(s,r)}throw N(d,r)}}function N(t,o,e="atomicWriteFile"){return t instanceof Error&&!t.message.startsWith(`${e}(`)&&(t.message=`${e}(${JSON.stringify(o)}): ${t.message}`),t}async function X(t,o,e){await B(t,JSON.stringify(o,null,2),{encoding:"utf-8",...e})}function H(t){if(t<=0)return;let o=new SharedArrayBuffer(4),e=new Int32Array(o);Atomics.wait(e,0,0,t)}function Y(t,o,e,i,w=n.renameSync){for(let a=0;a<=e;a++)try{w(t,o);return}catch(c){if(!(u(c)&&(c.code==="EPERM"||c.code==="EACCES"))||a===e)throw c;H(i*2**a)}}function D(t){let e=t;for(let w=0;w<40;w++){let a;try{a=n.lstatSync(e)}catch(l){if(u(l)&&l.code==="ENOENT")return e;throw l}if(!a.isSymbolicLink())return e;let c=n.readlinkSync(e);if(O.isAbsolute(c))e=c;else{let l=n.realpathSync(O.dirname(e));e=O.resolve(l,c)}}let i=new Error(`ELOOP: too many levels of symbolic links, resolve '${t}'`);throw i.code="ELOOP",i}function V(t,o,e,i){let w=e?.retries??3,a=e?.delayMs??50,c=e?.flush??!0,l=e?.encoding??"utf-8",v=i?.rename??n.renameSync,F=i?.writeFile??n.writeFileSync,x=i?.open??n.openSync,T=i?.chmod??n.chmodSync,A=i?.fchmod??n.fchmodSync,b=i?.unlink??n.unlinkSync,r;if(e?.noFollow)r=t;else try{r=D(t)}catch(h){throw N(h,t,"atomicWriteFileSync")}let S=`${r}.${P.randomBytes(6).toString("hex")}.tmp`,W;if(!e?.forceMode||e?.mode===void 0)try{W=n.statSync(r).mode&4095}catch(h){if(!u(h)||h.code!=="ENOENT")throw h}let y=W??e?.mode,p={};typeof o=="string"&&(p.encoding=l),c&&(p.flush=!0),y!==void 0&&(p.mode=y);let k=h=>{if(y!==void 0)try{T(h,y)}catch(m){if(!u(m)||m.code!=="ENOSYS"&&m.code!=="ENOTSUP")throw m}};try{F(S,o,p),k(S),Y(S,r,w,a,v)}catch(h){try{b(S)}catch{}if(u(h)&&h.code==="EXDEV")try{if(e?.noFollow){try{b(r)}catch(s){if(!u(s)||s.code!=="ENOENT")throw s}let m=x(r,n.constants.O_WRONLY|n.constants.O_CREAT|n.constants.O_EXCL,y??438),d=!1;try{try{let s=typeof o=="string"?Buffer.from(o,l):o;if(n.writeFileSync(m,s),c&&n.fsyncSync(m),y!==void 0)try{A(m,y)}catch(E){if(!u(E)||E.code!=="ENOSYS"&&E.code!=="ENOTSUP")throw E}d=!0}finally{n.closeSync(m)}}catch(s){if(!d)try{b(r)}catch(E){C.debug(`orphan unlink failed for ${r}:`,E)}throw s}}else F(r,o,p),k(r);return}catch(m){throw N(m,r,"atomicWriteFileSync")}throw N(h,r,"atomicWriteFileSync")}}export{L as a,B as b,X as c,Y as d,V as e};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as c}from"./chunk-4F4DA5UI.js";import{k as i}from"./chunk-SDTWBD62.js";import{e as l}from"./chunk-T4P4KEDW.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function h(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
3
+ import{a as c}from"./chunk-4F4DA5UI.js";import{k as i}from"./chunk-SDTWBD62.js";import{e as l}from"./chunk-6E766NPX.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function h(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
4
4
 
5
5
  `):void 0}catch{return}}function C(t,e){return e?t===void 0?e:typeof t=="string"?`${t}
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as h,g}from"./chunk-W5CGKUM4.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-GO2GA2GY.js";import{b as c,ba as b}from"./chunk-MH2P4YXC.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new M,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
3
+ import{b as h,g}from"./chunk-S3CWEVTS.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-LUNDTQ3G.js";import{b as c,ba as b}from"./chunk-27Q5KW3A.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new M,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
4
4
  `,{flag:"wx"})}catch(r){if(!c(r)||r.code!=="EEXIST")throw r}}async function k(e){try{let r=await a.readFile(e,"utf-8");return JSON.parse(r)}catch(r){if(c(r)&&r.code==="ENOENT")return[];let o=r instanceof Error?r.message:String(r);y.warn(`Quarantining corrupt inbox at ${e}: ${o}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(t){let i=t instanceof Error?t.message:String(t);throw y.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${o}`)}return[]}}export{D as a,_ as b,P as c,S as d,$ as e,I as f,x as g,X as h,A as i,z as j,G as k,K as l,Q as m};
5
5
  /**
6
6
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{I as l,L as M,Q as A,w as g}from"./chunk-MH2P4YXC.js";import{b as h}from"./chunk-GZPNIYVZ.js";h();import*as s from"node:fs";import*as t from"node:path";var f="memory",y="MEMORY.md",x="meta.json",R="extract-cursor.json",O="consolidation.lock",T="memories";function D(r){let o=t.resolve(r);for(;;){let e=t.join(o,".git");if(s.existsSync(e))return o;let n=t.dirname(o);if(n===o)return null;o=n}}function j(r){let o=D(r);if(!o)return null;try{let e=s.readFileSync(t.join(o,".git"),"utf-8").trim();if(!e.startsWith("gitdir:"))return o;let n=t.resolve(o,e.slice(7).trim()),i=t.resolve(n,s.readFileSync(t.join(n,"commondir"),"utf-8").trim());return t.resolve(t.dirname(n))!==t.join(i,"worktrees")||s.realpathSync(s.readFileSync(t.join(n,"gitdir"),"utf-8").trim())!==t.join(s.realpathSync(o),".git")?o:t.basename(i)!==".git"?i.normalize("NFC"):t.dirname(i).normalize("NFC")}catch{return o}}function _(){return process.env.MATILDA_CODE_MEMORY_BASE_DIR?M(void 0,process.env.MATILDA_CODE_MEMORY_BASE_DIR):A.getRuntimeBaseDir()}var c=new Map;function u(r){let o=process.env.MATILDA_CODE_MEMORY_LOCAL==="1",e=o?"":_(),n=`${o?"local":e}\0${r}`,i=c.get(n);if(i!==void 0)return i;let a;if(o)a=t.join(r,g,f);else{let d=j(r)??t.resolve(r);a=t.join(e,"projects",l(d),f)}return c.set(n,a),a}function S(){c.clear()}function p(r){return t.dirname(u(r))}function I(r,o){let e=t.normalize(r),n=t.normalize(u(o)),i=t.relative(n,e);return i===""||!i.startsWith("..")&&!t.isAbsolute(i)}function v(r){return t.join(u(r),y)}function U(r){return t.join(p(r),x)}function F(r){return t.join(p(r),R)}function N(r){return t.join(p(r),O)}function E(r){return`${r}.md`}function Y(r,o){return t.join(u(r),E(o))}function z(r,o){return t.join(u(r),o)}function m(){return t.join(_(),T)}function k(){return t.join(m(),y)}function b(r){return t.join(m(),E(r))}function C(r){let o=t.normalize(r),e=t.normalize(m()),n=t.relative(e,o);return n===""||!n.startsWith("..")&&!t.isAbsolute(n)}function w(r,o){return I(r,o)||C(r)}export{f as a,y as b,x as c,R as d,O as e,T as f,_ as g,u as h,S as i,p as j,I as k,v as l,U as m,F as n,N as o,E as p,Y as q,z as r,m as s,k as t,b as u,C as v,w};
3
+ import{I as l,L as M,Q as A,w as g}from"./chunk-27Q5KW3A.js";import{b as h}from"./chunk-GZPNIYVZ.js";h();import*as s from"node:fs";import*as t from"node:path";var f="memory",y="MEMORY.md",x="meta.json",R="extract-cursor.json",O="consolidation.lock",T="memories";function D(r){let o=t.resolve(r);for(;;){let e=t.join(o,".git");if(s.existsSync(e))return o;let n=t.dirname(o);if(n===o)return null;o=n}}function j(r){let o=D(r);if(!o)return null;try{let e=s.readFileSync(t.join(o,".git"),"utf-8").trim();if(!e.startsWith("gitdir:"))return o;let n=t.resolve(o,e.slice(7).trim()),i=t.resolve(n,s.readFileSync(t.join(n,"commondir"),"utf-8").trim());return t.resolve(t.dirname(n))!==t.join(i,"worktrees")||s.realpathSync(s.readFileSync(t.join(n,"gitdir"),"utf-8").trim())!==t.join(s.realpathSync(o),".git")?o:t.basename(i)!==".git"?i.normalize("NFC"):t.dirname(i).normalize("NFC")}catch{return o}}function _(){return process.env.MATILDA_CODE_MEMORY_BASE_DIR?M(void 0,process.env.MATILDA_CODE_MEMORY_BASE_DIR):A.getRuntimeBaseDir()}var c=new Map;function u(r){let o=process.env.MATILDA_CODE_MEMORY_LOCAL==="1",e=o?"":_(),n=`${o?"local":e}\0${r}`,i=c.get(n);if(i!==void 0)return i;let a;if(o)a=t.join(r,g,f);else{let d=j(r)??t.resolve(r);a=t.join(e,"projects",l(d),f)}return c.set(n,a),a}function S(){c.clear()}function p(r){return t.dirname(u(r))}function I(r,o){let e=t.normalize(r),n=t.normalize(u(o)),i=t.relative(n,e);return i===""||!i.startsWith("..")&&!t.isAbsolute(i)}function v(r){return t.join(u(r),y)}function U(r){return t.join(p(r),x)}function F(r){return t.join(p(r),R)}function N(r){return t.join(p(r),O)}function E(r){return`${r}.md`}function Y(r,o){return t.join(u(r),E(o))}function z(r,o){return t.join(u(r),o)}function m(){return t.join(_(),T)}function k(){return t.join(m(),y)}function b(r){return t.join(m(),E(r))}function C(r){let o=t.normalize(r),e=t.normalize(m()),n=t.relative(e,o);return n===""||!n.startsWith("..")&&!t.isAbsolute(n)}function w(r,o){return I(r,o)||C(r)}export{f as a,y as b,x as c,R as d,O as e,T as f,_ as g,u as h,S as i,p as j,I as k,v as l,U as m,F as n,N as o,E as p,Y as q,z as r,m as s,k as t,b as u,C as v,w};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,30 +1,30 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{M as D,N as j,O as L,g as I,ia as W,na as _}from"./chunk-WRQLIPXW.js";import{b as m,e as w}from"./chunk-4J6DC24J.js";import{k as F,n as U}from"./chunk-SDTWBD62.js";import{q as b,s as $,t as x,u as O}from"./chunk-MH2P4YXC.js";import{b as G}from"./chunk-GZPNIYVZ.js";G();var X="2026-06-23",K="auto",z="instant",Y=12e4,h=18e4,Q=5e4,R=16e3,S=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},Z=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),q=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function ee(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function y(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}var te="Your message was blocked by our content safety system.";function ne(n){let e=y(n);if(!e||e.error!=="content_blocked")return;let t=Array.isArray(e.categories)?e.categories.filter(o=>typeof o=="string"):[],s=typeof e.assistant_message=="string"&&e.assistant_message.trim().length>0?e.assistant_message:typeof e.message=="string"?e.message:te;return{categories:t,severity:typeof e.severity=="string"?e.severity:void 0,assistantMessage:s}}function u(n,e){let s=y(n)?.[e];return typeof s=="string"?s:void 0}function B(n){return P(n)}function P(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
3
+ import{M as j,N as L,O as W,g as F,ia as B,na as _}from"./chunk-3IRGBRSP.js";import{b as m,e as w}from"./chunk-4J6DC24J.js";import{k as U,n as D}from"./chunk-SDTWBD62.js";import{q as b,s as x,t as O,u as I}from"./chunk-27Q5KW3A.js";import{b as $}from"./chunk-GZPNIYVZ.js";$();var K="2026-06-23",z="auto",Y="instant",Q=12e4,h=18e4,Z=5e4,R=16e3,E=class extends Error{constructor(t,s){super(t);this.status=s;this.name="MatildaAgentHttpError"}},S=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},q=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),ee=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function te(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function y(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}var ne="Your message was blocked by our content safety system.";function se(n){let e=y(n);if(!e||e.error!=="content_blocked")return;let t=Array.isArray(e.categories)?e.categories.filter(o=>typeof o=="string"):[],s=typeof e.assistant_message=="string"&&e.assistant_message.trim().length>0?e.assistant_message:typeof e.message=="string"?e.message:ne;return{categories:t,severity:typeof e.severity=="string"?e.severity:void 0,assistantMessage:s}}function u(n,e){let s=y(n)?.[e];return typeof s=="string"?s:void 0}function H(n){return P(n)}function P(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
4
4
  `):""}function f(n,e){if(n.length<=e)return n;let t=`
5
5
  [...omitted to fit Matilda native agent context...]
6
- `,s=e-t.length,o=Math.floor(s*.6),i=s-o;return`${n.slice(0,o)}${t}${n.slice(-i)}`}function se(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function oe(n){let e=y(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function ae(n){if(C(n)<=h)return n;let e=`
6
+ `,s=e-t.length,o=Math.floor(s*.6),i=s-o;return`${n.slice(0,o)}${t}${n.slice(-i)}`}function oe(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function ae(n){let e=y(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function ie(n){if(C(n)<=h)return n;let e=`
7
7
  [...omitted to fit Matilda native request limit...]
8
- `;for(let t=0;t<n.messages.length;t+=1){let s=n.messages[t];!s||s.content.length<=R||(n.messages[t]={...s,content:f(s.content,R)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,s=n.messages[t];if(!s||s.content.length<=1e3)break;let o=C(n)-h,i=Math.max(1e3,s.content.length-o-e.length-2e3);n.messages[t]={...s,content:f(s.content,i)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function ie(n){let e=y(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let s=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:s}}function re(n){let e=y(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let s=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${s}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let s=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${s?` with ${s}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),s=u(n.data,"message");return t&&s?`**Remote tool** ${t}: ${s}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),s=u(n.data,"status"),o=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${s??"completed"}${o?`: ${f(o,600)}`:""}`:void 0}}function T(n,e,t){let s=new w;return s.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],s.createTime=Date.now().toString(),s.modelVersion=e,t&&(s.usageMetadata=t),s}function le(n,e){let t=new w;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function ce(n,e){let t=new w;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function H(n){let e=T("",n);return e.matildaReplace=!0,e}function de(n){return n.matildaReplace===!0}function J(n,e,t){let s=T("",n,t);return s.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],s}async function*ue(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let s=new TextDecoder,o="",i="message",r=[],d=!1,c,a=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},g=()=>{if(r.length===0){i="message";return}let A={event:i,data:r.join(`
9
- `)};return i="message",r=[],a(),A};a();try{for(;;){let{done:v,value:p}=await t.read();if(v||d)break;a(),o+=s.decode(p,{stream:!0});let E=o.split(`
10
- `);o=E.pop()??"";for(let k of E){let M=k.endsWith("\r")?k.slice(0,-1):k;if(M.length===0){let N=g();N&&(yield N)}else M.startsWith("event:")?i=M.slice(6).trim():M.startsWith("data:")&&r.push(M.slice(5).trimStart())}}if(o+=s.decode(),o.length>0)for(let v of o.split(`
11
- `)){let p=v.endsWith("\r")?v.slice(0,-1):v;p.startsWith("event:")?i=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=g();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var V=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let s=await this.generateContentStream(e,t),o="",i,r=m.STOP,d=!1;for await(let a of s){de(a)?o="":o+=se(a),a.usageMetadata&&(i=a.usageMetadata);let l=a.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new S;let c=T(o,this.modelFor(e),i);return c.candidates=[{content:{parts:o?[{text:o}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),s=await this.fetchNativeChat(e),o=!1,i=!1,r,d,c=!1;for await(let a of ue(s,Y))if(a.data!=="[DONE]"){if(a.event==="token"){let l=u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="thinking"||a.event==="generation_status"||a.event==="status"||a.event==="tool_start"||a.event==="tool_progress"||a.event==="tool_result"){let l=re(a);l&&(i=!0,yield le(l,t))}else if(a.event==="client_tool_call"){let l=ie(a);l&&(i=!0,yield ce(l,t))}else if(a.event==="usage")d=oe(a.data)??d;else if(a.event==="replace")yield H(t);else if(a.event==="safety_replace"){yield H(t);let l=u(a.data,"message")??u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(a.event==="done"){if(c=!0,r=u(a.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!i)throw new Error("Matilda agent returned an empty response.");yield J(t,r,d),o=!0}else if(a.event==="error"){let l=y(a.data),g=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${g}`)}}if(!o){if(e.config?.abortSignal?.aborted)return;if(!i)throw new Error("Matilda agent returned an empty response.");if(c)yield J(t,r??m.STOP,d);else throw new S}}async fetchNativeChat(e){let t=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),s=await this.postNativeChat(e,t);if(s.status!==401)return this.assertOkResponse(s);let o;try{o=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw W(r)?new b(r instanceof Error?r.message:String(r)):r}if(!o||o===t)throw new b("Matilda session expired. Please sign in again.");let i=await F("retry",()=>this.postNativeChat(e,o));return this.assertOkResponse(i)}async postNativeChat(e,t){return fetch(`${ee(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=await e.text();if(e.status===403){let o;try{o=JSON.parse(t)}catch{}if(x(o))throw new $}if(e.status===422){let o=ne(t);if(o)throw new O(`Matilda agent request blocked (422): ${t}`,o.categories,o.severity,o.assistantMessage)}let s=`Matilda agent request failed (${e.status}): ${t}`;throw e.status===401?new b(s):new Error(s)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":X,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[s,o]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))s.toLowerCase()!=="x-matilda-response-mode"&&!j(s)&&(t[s]=o);return L(this.contentGeneratorConfig,e)&&Object.assign(t,D(this.cliConfig),U()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),s=this.clientToolsFromRequest(e),o={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return s.length>0&&(o.clientTools=s),ae(o)}buildNativeMessages(e,t){let s=this.openAIMessagesFromRequest(e),i=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of s){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&i.push(c)}i.length===1&&i.push({role:"user",content:`${this.purposeLabel(t)}:
8
+ `;for(let t=0;t<n.messages.length;t+=1){let s=n.messages[t];!s||s.content.length<=R||(n.messages[t]={...s,content:f(s.content,R)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,s=n.messages[t];if(!s||s.content.length<=1e3)break;let o=C(n)-h,i=Math.max(1e3,s.content.length-o-e.length-2e3);n.messages[t]={...s,content:f(s.content,i)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function re(n){let e=y(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let s=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:s}}function le(n){let e=y(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let s=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${s}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let s=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${s?` with ${s}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),s=u(n.data,"message");return t&&s?`**Remote tool** ${t}: ${s}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),s=u(n.data,"status"),o=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${s??"completed"}${o?`: ${f(o,600)}`:""}`:void 0}}function T(n,e,t){let s=new w;return s.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],s.createTime=Date.now().toString(),s.modelVersion=e,t&&(s.usageMetadata=t),s}function ce(n,e){let t=new w;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function de(n,e){let t=new w;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function J(n){let e=T("",n);return e.matildaReplace=!0,e}function ue(n){return n.matildaReplace===!0}function V(n,e,t){let s=T("",n,t);return s.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],s}async function*ge(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let s=new TextDecoder,o="",i="message",r=[],d=!1,c,a=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},g=()=>{if(r.length===0){i="message";return}let A={event:i,data:r.join(`
9
+ `)};return i="message",r=[],a(),A};a();try{for(;;){let{done:v,value:p}=await t.read();if(v||d)break;a(),o+=s.decode(p,{stream:!0});let N=o.split(`
10
+ `);o=N.pop()??"";for(let k of N){let M=k.endsWith("\r")?k.slice(0,-1):k;if(M.length===0){let G=g();G&&(yield G)}else M.startsWith("event:")?i=M.slice(6).trim():M.startsWith("data:")&&r.push(M.slice(5).trimStart())}}if(o+=s.decode(),o.length>0)for(let v of o.split(`
11
+ `)){let p=v.endsWith("\r")?v.slice(0,-1):v;p.startsWith("event:")?i=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=g();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var X=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let s=await this.generateContentStream(e,t),o="",i,r=m.STOP,d=!1;for await(let a of s){ue(a)?o="":o+=oe(a),a.usageMetadata&&(i=a.usageMetadata);let l=a.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new S;let c=T(o,this.modelFor(e),i);return c.candidates=[{content:{parts:o?[{text:o}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),s=await this.fetchNativeChat(e),o=!1,i=!1,r,d,c=!1;for await(let a of ge(s,Q))if(a.data!=="[DONE]"){if(a.event==="token"){let l=u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="thinking"||a.event==="generation_status"||a.event==="status"||a.event==="tool_start"||a.event==="tool_progress"||a.event==="tool_result"){let l=le(a);l&&(i=!0,yield ce(l,t))}else if(a.event==="client_tool_call"){let l=re(a);l&&(i=!0,yield de(l,t))}else if(a.event==="usage")d=ae(a.data)??d;else if(a.event==="replace")yield J(t);else if(a.event==="safety_replace"){yield J(t);let l=u(a.data,"message")??u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(a.event==="done"){if(c=!0,r=u(a.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!i)throw new Error("Matilda agent returned an empty response.");yield V(t,r,d),o=!0}else if(a.event==="error"){let l=y(a.data),g=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${g}`)}}if(!o){if(e.config?.abortSignal?.aborted)return;if(!i)throw new Error("Matilda agent returned an empty response.");if(c)yield V(t,r??m.STOP,d);else throw new S}}async fetchNativeChat(e){let t=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),s=await this.postNativeChat(e,t);if(s.status!==401)return this.assertOkResponse(s);let o;try{o=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw B(r)?new b(r instanceof Error?r.message:String(r)):r}if(!o||o===t)throw new b("Matilda session expired. Please sign in again.");let i=await U("retry",()=>this.postNativeChat(e,o));return this.assertOkResponse(i)}async postNativeChat(e,t){return fetch(`${te(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=await e.text();if(e.status===403){let o;try{o=JSON.parse(t)}catch{}if(O(o))throw new x}if(e.status===422){let o=se(t);if(o)throw new I(`Matilda agent request blocked (422): ${t}`,o.categories,o.severity,o.assistantMessage)}let s=`Matilda agent request failed (${e.status}): ${t}`;throw e.status===401?new b(s):new E(s,e.status)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":K,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[s,o]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))s.toLowerCase()!=="x-matilda-response-mode"&&!L(s)&&(t[s]=o);return W(this.contentGeneratorConfig,e)&&Object.assign(t,j(this.cliConfig),D()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),s=this.clientToolsFromRequest(e),o={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return s.length>0&&(o.clientTools=s),ie(o)}buildNativeMessages(e,t){let s=this.openAIMessagesFromRequest(e),i=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of s){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&i.push(c)}i.length===1&&i.push({role:"user",content:`${this.purposeLabel(t)}:
12
12
  (empty prompt)`});let r=i[i.length-1];return r?.role!=="user"?i.push({role:"user",content:`${this.purposeLabel(t)}:
13
13
  Continue from the previous assistant response.`}):r.content.startsWith(`${this.purposeLabel(t)}:
14
14
  `)||(i[i.length-1]={...r,content:`${this.purposeLabel(t)}:
15
15
  ${r.content}`}),i}buildSystemContext(e,t){let s=["Agent: Matilda Code",t==="code"?`Routing intent:
16
- ${Z}`:void 0,`Instructions:
16
+ ${q}`:void 0,`Instructions:
17
17
  ${this.instructionsFromRequest(e)}`].filter(o=>!!o);return f(s.join(`
18
18
 
19
- `),Q)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let s=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(s)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(s)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?z:e==="analysis"?"deep":K}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(s=>s.role==="system").map(s=>P(s.content)).filter(s=>s.trim().length>0);return[q,...t,this.localAgentContext()].join(`
19
+ `),Z)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let s=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(s)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(s)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?Y:e==="analysis"?"deep":z}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(s=>s.role==="system").map(s=>P(s.content)).filter(s=>s.trim().length>0);return[ee,...t,this.localAgentContext()].join(`
20
20
 
21
21
  `)}localAgentContext(){let e=["Local agent context:","- CLI: Matilda Code terminal agent."],t=this.cliConfig.getModel?.();t&&e.push(`- Active model: ${t}`);let s=this.cliConfig.getApprovalMode?.();s&&e.push(`- Approval mode: ${s}`);let o=this.cliConfig.getSandbox?.();e.push(o?`- Sandbox: ${o.command} (${o.image}).`:"- Sandbox: disabled.");let i=[["allow",this.cliConfig.getPermissionsAllow?.()??[]],["ask",this.cliConfig.getPermissionsAsk?.()??[]],["deny",this.cliConfig.getPermissionsDeny?.()??[]]];for(let[l,g]of i)g.length>0&&e.push(`- Permission ${l} rules: ${g.join(", ")}`);let r=this.cliConfig.getIdeMode?.()?"IDE/ACP":this.cliConfig.isInteractive?.()?"interactive TUI":"headless";e.push(`- Interface mode: ${r}`);let d=this.cliConfig.getProjectRoot?.();d&&e.push(`- Project root: ${d}`);let c=this.cliConfig.getWorkingDir?.();c&&c!==d&&e.push(`- Working directory: ${c}`);let a=this.cliConfig.getToolRegistry?.()?.getAllToolNames?.().slice(0,30)??[];return a.length>0&&e.push(`- Local tools available through the CLI loop: ${a.join(", ")}`),e.join(`
22
- `)}clientToolsFromRequest(e){let t=[];for(let s of e.config?.tools??[])"functionDeclarations"in s&&t.push(...(s.functionDeclarations??[]).filter(o=>!!o.name));return t.map(s=>({name:s.name,...s.description?{description:s.description}:{},...s.parametersJsonSchema?{parameters:s.parametersJsonSchema}:s.parameters?{parameters:s.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>B(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return I.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
23
- ${f(B(e.content),R)}`;if(e.role==="assistant"){let t=P(e.content),s="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(o=>`Tool request: ${o.function.name}(${o.function.arguments})`).join(`
22
+ `)}clientToolsFromRequest(e){let t=[];for(let s of e.config?.tools??[])"functionDeclarations"in s&&t.push(...(s.functionDeclarations??[]).filter(o=>!!o.name));return t.map(s=>({name:s.name,...s.description?{description:s.description}:{},...s.parametersJsonSchema?{parameters:s.parametersJsonSchema}:s.parameters?{parameters:s.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>H(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return F.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
23
+ ${f(H(e.content),R)}`;if(e.role==="assistant"){let t=P(e.content),s="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(o=>`Tool request: ${o.function.name}(${o.function.arguments})`).join(`
24
24
  `):"";return`Assistant:
25
25
  ${f([t,s].filter(Boolean).join(`
26
26
  `),R)}`}return e.role==="tool"?`Tool result ${e.tool_call_id}:
27
- ${f(P(e.content),R)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};export{de as a,V as b};
27
+ ${f(P(e.content),R)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};export{ue as a,X as b};
28
28
  /**
29
29
  * @license
30
30
  * Copyright 2026 Matilda Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{l as Se,m as Ae,n as Ge,o as qe,p as Ue,q as ne}from"./chunk-QKYGQLWC.js";import{c as je}from"./chunk-GO2GA2GY.js";import{Q as ve,b as ke}from"./chunk-MH2P4YXC.js";import{b as d}from"./chunk-GZPNIYVZ.js";import{a as U,d as k}from"./chunk-OWGSC52X.js";var ze=k((xr,Ke)=>{d();var $=U("constants"),Ot=process.cwd,oe=null,Ft=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return oe||(oe=Ot.call(process)),oe};try{process.cwd()}catch{}typeof process.chdir=="function"&&(_e=process.chdir,process.chdir=function(e){oe=null,_e.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,_e));var _e;Ke.exports=It;function It(e){$.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=u(e.chown),e.fchown=u(e.fchown),e.lchown=u(e.lchown),e.chmod=n(e.chmod),e.fchmod=n(e.fchmod),e.lchmod=n(e.lchmod),e.chownSync=l(e.chownSync),e.fchownSync=l(e.fchownSync),e.lchownSync=l(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=p(e.stat),e.fstat=p(e.fstat),e.lstat=p(e.lstat),e.statSync=T(e.statSync),e.fstatSync=T(e.fstatSync),e.lstatSync=T(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(i,m,c){c&&process.nextTick(c)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(i,m,c,a){a&&process.nextTick(a)},e.lchownSync=function(){}),Ft==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:function(i){function m(c,a,s){var w=Date.now(),v=0;i(c,a,function E(C){if(C&&(C.code==="EACCES"||C.code==="EPERM"||C.code==="EBUSY")&&Date.now()-w<6e4){setTimeout(function(){e.stat(a,function(R,Z){R&&R.code==="ENOENT"?i(c,a,E):s(C)})},v),v<100&&(v+=10);return}s&&s(C)})}return Object.setPrototypeOf&&Object.setPrototypeOf(m,i),m}(e.rename)),e.read=typeof e.read!="function"?e.read:function(i){function m(c,a,s,w,v,E){var C;if(E&&typeof E=="function"){var R=0;C=function(Z,Re,Ce){if(Z&&Z.code==="EAGAIN"&&R<10)return R++,i.call(e,c,a,s,w,v,C);E.apply(this,arguments)}}return i.call(e,c,a,s,w,v,C)}return Object.setPrototypeOf&&Object.setPrototypeOf(m,i),m}(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:function(i){return function(m,c,a,s,w){for(var v=0;;)try{return i.call(e,m,c,a,s,w)}catch(E){if(E.code==="EAGAIN"&&v<10){v++;continue}throw E}}}(e.readSync);function t(i){i.lchmod=function(m,c,a){i.open(m,$.O_WRONLY|$.O_SYMLINK,c,function(s,w){if(s){a&&a(s);return}i.fchmod(w,c,function(v){i.close(w,function(E){a&&a(v||E)})})})},i.lchmodSync=function(m,c){var a=i.openSync(m,$.O_WRONLY|$.O_SYMLINK,c),s=!0,w;try{w=i.fchmodSync(a,c),s=!1}finally{if(s)try{i.closeSync(a)}catch{}else i.closeSync(a)}return w}}function r(i){$.hasOwnProperty("O_SYMLINK")&&i.futimes?(i.lutimes=function(m,c,a,s){i.open(m,$.O_SYMLINK,function(w,v){if(w){s&&s(w);return}i.futimes(v,c,a,function(E){i.close(v,function(C){s&&s(E||C)})})})},i.lutimesSync=function(m,c,a){var s=i.openSync(m,$.O_SYMLINK),w,v=!0;try{w=i.futimesSync(s,c,a),v=!1}finally{if(v)try{i.closeSync(s)}catch{}else i.closeSync(s)}return w}):i.futimes&&(i.lutimes=function(m,c,a,s){s&&process.nextTick(s)},i.lutimesSync=function(){})}function n(i){return i&&function(m,c,a){return i.call(e,m,c,function(s){I(s)&&(s=null),a&&a.apply(this,arguments)})}}function o(i){return i&&function(m,c){try{return i.call(e,m,c)}catch(a){if(!I(a))throw a}}}function u(i){return i&&function(m,c,a,s){return i.call(e,m,c,a,function(w){I(w)&&(w=null),s&&s.apply(this,arguments)})}}function l(i){return i&&function(m,c,a){try{return i.call(e,m,c,a)}catch(s){if(!I(s))throw s}}}function p(i){return i&&function(m,c,a){typeof c=="function"&&(a=c,c=null);function s(w,v){v&&(v.uid<0&&(v.uid+=4294967296),v.gid<0&&(v.gid+=4294967296)),a&&a.apply(this,arguments)}return c?i.call(e,m,c,s):i.call(e,m,s)}}function T(i){return i&&function(m,c){var a=c?i.call(e,m,c):i.call(e,m);return a&&(a.uid<0&&(a.uid+=4294967296),a.gid<0&&(a.gid+=4294967296)),a}}function I(i){if(!i||i.code==="ENOSYS")return!0;var m=!process.getuid||process.getuid()!==0;return!!(m&&(i.code==="EINVAL"||i.code==="EPERM"))}}});var Qe=k((Fr,Je)=>{d();var Be=U("stream").Stream;Je.exports=bt;function bt(e){return{ReadStream:t,WriteStream:r};function t(n,o){if(!(this instanceof t))return new t(n,o);Be.call(this);var u=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,o=o||{};for(var l=Object.keys(o),p=0,T=l.length;p<T;p++){var I=l[p];this[I]=o[I]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){u._read()});return}e.open(this.path,this.flags,this.mode,function(i,m){if(i){u.emit("error",i),u.readable=!1;return}u.fd=m,u.emit("open",m),u._read()})}function r(n,o){if(!(this instanceof r))return new r(n,o);Be.call(this),this.path=n,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,o=o||{};for(var u=Object.keys(o),l=0,p=u.length;l<p;l++){var T=u[l];this[T]=o[T]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var He=k((br,Xe)=>{"use strict";d();Xe.exports=Dt;var Mt=Object.getPrototypeOf||function(e){return e.__proto__};function Dt(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:Mt(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}),t}});var Oe=k((Dr,xe)=>{d();var O=U("fs"),Pt=ze(),Nt=Qe(),Lt=He(),ue=U("util"),L,ce;typeof Symbol=="function"&&typeof Symbol.for=="function"?(L=Symbol.for("graceful-fs.queue"),ce=Symbol.for("graceful-fs.previous")):(L="___graceful-fs.queue",ce="___graceful-fs.previous");function Rt(){}function et(e,t){Object.defineProperty(e,L,{get:function(){return t}})}var Y=Rt;ue.debuglog?Y=ue.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Y=function(){var e=ue.format.apply(ue,arguments);e="GFS4: "+e.split(/\n/).join(`
3
+ import{l as Se,m as Ae,n as Ge,o as qe,p as Ue,q as ne}from"./chunk-QKYGQLWC.js";import{c as je}from"./chunk-LUNDTQ3G.js";import{Q as ve,b as ke}from"./chunk-27Q5KW3A.js";import{b as d}from"./chunk-GZPNIYVZ.js";import{a as U,d as k}from"./chunk-OWGSC52X.js";var ze=k((xr,Ke)=>{d();var $=U("constants"),Ot=process.cwd,oe=null,Ft=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return oe||(oe=Ot.call(process)),oe};try{process.cwd()}catch{}typeof process.chdir=="function"&&(_e=process.chdir,process.chdir=function(e){oe=null,_e.call(process,e)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,_e));var _e;Ke.exports=It;function It(e){$.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&t(e),e.lutimes||r(e),e.chown=u(e.chown),e.fchown=u(e.fchown),e.lchown=u(e.lchown),e.chmod=n(e.chmod),e.fchmod=n(e.fchmod),e.lchmod=n(e.lchmod),e.chownSync=l(e.chownSync),e.fchownSync=l(e.fchownSync),e.lchownSync=l(e.lchownSync),e.chmodSync=o(e.chmodSync),e.fchmodSync=o(e.fchmodSync),e.lchmodSync=o(e.lchmodSync),e.stat=p(e.stat),e.fstat=p(e.fstat),e.lstat=p(e.lstat),e.statSync=T(e.statSync),e.fstatSync=T(e.fstatSync),e.lstatSync=T(e.lstatSync),e.chmod&&!e.lchmod&&(e.lchmod=function(i,m,c){c&&process.nextTick(c)},e.lchmodSync=function(){}),e.chown&&!e.lchown&&(e.lchown=function(i,m,c,a){a&&process.nextTick(a)},e.lchownSync=function(){}),Ft==="win32"&&(e.rename=typeof e.rename!="function"?e.rename:function(i){function m(c,a,s){var w=Date.now(),v=0;i(c,a,function E(C){if(C&&(C.code==="EACCES"||C.code==="EPERM"||C.code==="EBUSY")&&Date.now()-w<6e4){setTimeout(function(){e.stat(a,function(R,Z){R&&R.code==="ENOENT"?i(c,a,E):s(C)})},v),v<100&&(v+=10);return}s&&s(C)})}return Object.setPrototypeOf&&Object.setPrototypeOf(m,i),m}(e.rename)),e.read=typeof e.read!="function"?e.read:function(i){function m(c,a,s,w,v,E){var C;if(E&&typeof E=="function"){var R=0;C=function(Z,Re,Ce){if(Z&&Z.code==="EAGAIN"&&R<10)return R++,i.call(e,c,a,s,w,v,C);E.apply(this,arguments)}}return i.call(e,c,a,s,w,v,C)}return Object.setPrototypeOf&&Object.setPrototypeOf(m,i),m}(e.read),e.readSync=typeof e.readSync!="function"?e.readSync:function(i){return function(m,c,a,s,w){for(var v=0;;)try{return i.call(e,m,c,a,s,w)}catch(E){if(E.code==="EAGAIN"&&v<10){v++;continue}throw E}}}(e.readSync);function t(i){i.lchmod=function(m,c,a){i.open(m,$.O_WRONLY|$.O_SYMLINK,c,function(s,w){if(s){a&&a(s);return}i.fchmod(w,c,function(v){i.close(w,function(E){a&&a(v||E)})})})},i.lchmodSync=function(m,c){var a=i.openSync(m,$.O_WRONLY|$.O_SYMLINK,c),s=!0,w;try{w=i.fchmodSync(a,c),s=!1}finally{if(s)try{i.closeSync(a)}catch{}else i.closeSync(a)}return w}}function r(i){$.hasOwnProperty("O_SYMLINK")&&i.futimes?(i.lutimes=function(m,c,a,s){i.open(m,$.O_SYMLINK,function(w,v){if(w){s&&s(w);return}i.futimes(v,c,a,function(E){i.close(v,function(C){s&&s(E||C)})})})},i.lutimesSync=function(m,c,a){var s=i.openSync(m,$.O_SYMLINK),w,v=!0;try{w=i.futimesSync(s,c,a),v=!1}finally{if(v)try{i.closeSync(s)}catch{}else i.closeSync(s)}return w}):i.futimes&&(i.lutimes=function(m,c,a,s){s&&process.nextTick(s)},i.lutimesSync=function(){})}function n(i){return i&&function(m,c,a){return i.call(e,m,c,function(s){I(s)&&(s=null),a&&a.apply(this,arguments)})}}function o(i){return i&&function(m,c){try{return i.call(e,m,c)}catch(a){if(!I(a))throw a}}}function u(i){return i&&function(m,c,a,s){return i.call(e,m,c,a,function(w){I(w)&&(w=null),s&&s.apply(this,arguments)})}}function l(i){return i&&function(m,c,a){try{return i.call(e,m,c,a)}catch(s){if(!I(s))throw s}}}function p(i){return i&&function(m,c,a){typeof c=="function"&&(a=c,c=null);function s(w,v){v&&(v.uid<0&&(v.uid+=4294967296),v.gid<0&&(v.gid+=4294967296)),a&&a.apply(this,arguments)}return c?i.call(e,m,c,s):i.call(e,m,s)}}function T(i){return i&&function(m,c){var a=c?i.call(e,m,c):i.call(e,m);return a&&(a.uid<0&&(a.uid+=4294967296),a.gid<0&&(a.gid+=4294967296)),a}}function I(i){if(!i||i.code==="ENOSYS")return!0;var m=!process.getuid||process.getuid()!==0;return!!(m&&(i.code==="EINVAL"||i.code==="EPERM"))}}});var Qe=k((Fr,Je)=>{d();var Be=U("stream").Stream;Je.exports=bt;function bt(e){return{ReadStream:t,WriteStream:r};function t(n,o){if(!(this instanceof t))return new t(n,o);Be.call(this);var u=this;this.path=n,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,o=o||{};for(var l=Object.keys(o),p=0,T=l.length;p<T;p++){var I=l[p];this[I]=o[I]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){u._read()});return}e.open(this.path,this.flags,this.mode,function(i,m){if(i){u.emit("error",i),u.readable=!1;return}u.fd=m,u.emit("open",m),u._read()})}function r(n,o){if(!(this instanceof r))return new r(n,o);Be.call(this),this.path=n,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,o=o||{};for(var u=Object.keys(o),l=0,p=u.length;l<p;l++){var T=u[l];this[T]=o[T]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=e.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var He=k((br,Xe)=>{"use strict";d();Xe.exports=Dt;var Mt=Object.getPrototypeOf||function(e){return e.__proto__};function Dt(e){if(e===null||typeof e!="object")return e;if(e instanceof Object)var t={__proto__:Mt(e)};else var t=Object.create(null);return Object.getOwnPropertyNames(e).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r))}),t}});var Oe=k((Dr,xe)=>{d();var O=U("fs"),Pt=ze(),Nt=Qe(),Lt=He(),ue=U("util"),L,ce;typeof Symbol=="function"&&typeof Symbol.for=="function"?(L=Symbol.for("graceful-fs.queue"),ce=Symbol.for("graceful-fs.previous")):(L="___graceful-fs.queue",ce="___graceful-fs.previous");function Rt(){}function et(e,t){Object.defineProperty(e,L,{get:function(){return t}})}var Y=Rt;ue.debuglog?Y=ue.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(Y=function(){var e=ue.format.apply(ue,arguments);e="GFS4: "+e.split(/\n/).join(`
4
4
  GFS4: `),console.error(e)});O[L]||(Ve=globalThis[L]||[],et(O,Ve),O.close=function(e){function t(r,n){return e.call(O,r,function(o){o||Ze(),typeof n=="function"&&n.apply(this,arguments)})}return Object.defineProperty(t,ce,{value:e}),t}(O.close),O.closeSync=function(e){function t(r){e.apply(O,arguments),Ze()}return Object.defineProperty(t,ce,{value:e}),t}(O.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){Y(O[L]),U("assert").equal(O[L].length,0)}));var Ve;globalThis[L]||et(globalThis,O[L]);xe.exports=Te(Lt(O));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!O.__patched&&(xe.exports=Te(O),O.__patched=!0);function Te(e){Pt(e),e.gracefulify=Te,e.createReadStream=Re,e.createWriteStream=Ce;var t=e.readFile;e.readFile=r;function r(f,y,h){return typeof y=="function"&&(h=y,y=null),D(f,y,h);function D(P,b,x,F){return t(P,b,function(S){S&&(S.code==="EMFILE"||S.code==="ENFILE")?J([D,[P,b,x],S,F||Date.now(),Date.now()]):typeof x=="function"&&x.apply(this,arguments)})}}var n=e.writeFile;e.writeFile=o;function o(f,y,h,D){return typeof h=="function"&&(D=h,h=null),P(f,y,h,D);function P(b,x,F,S,N){return n(b,x,F,function(g){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}var u=e.appendFile;u&&(e.appendFile=l);function l(f,y,h,D){return typeof h=="function"&&(D=h,h=null),P(f,y,h,D);function P(b,x,F,S,N){return u(b,x,F,function(g){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}var p=e.copyFile;p&&(e.copyFile=T);function T(f,y,h,D){return typeof h=="function"&&(D=h,h=0),P(f,y,h,D);function P(b,x,F,S,N){return p(b,x,F,function(g){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}var I=e.readdir;e.readdir=m;var i=/^v[0-5]\./;function m(f,y,h){typeof y=="function"&&(h=y,y=null);var D=i.test(process.version)?function(x,F,S,N){return I(x,P(x,F,S,N))}:function(x,F,S,N){return I(x,F,P(x,F,S,N))};return D(f,y,h);function P(b,x,F,S){return function(N,g){N&&(N.code==="EMFILE"||N.code==="ENFILE")?J([D,[b,x,F],N,S||Date.now(),Date.now()]):(g&&g.sort&&g.sort(),typeof F=="function"&&F.call(this,N,g))}}}if(process.version.substr(0,4)==="v0.8"){var c=Nt(e);E=c.ReadStream,R=c.WriteStream}var a=e.ReadStream;a&&(E.prototype=Object.create(a.prototype),E.prototype.open=C);var s=e.WriteStream;s&&(R.prototype=Object.create(s.prototype),R.prototype.open=Z),Object.defineProperty(e,"ReadStream",{get:function(){return E},set:function(f){E=f},enumerable:!0,configurable:!0}),Object.defineProperty(e,"WriteStream",{get:function(){return R},set:function(f){R=f},enumerable:!0,configurable:!0});var w=E;Object.defineProperty(e,"FileReadStream",{get:function(){return w},set:function(f){w=f},enumerable:!0,configurable:!0});var v=R;Object.defineProperty(e,"FileWriteStream",{get:function(){return v},set:function(f){v=f},enumerable:!0,configurable:!0});function E(f,y){return this instanceof E?(a.apply(this,arguments),this):E.apply(Object.create(E.prototype),arguments)}function C(){var f=this;ye(f.path,f.flags,f.mode,function(y,h){y?(f.autoClose&&f.destroy(),f.emit("error",y)):(f.fd=h,f.emit("open",h),f.read())})}function R(f,y){return this instanceof R?(s.apply(this,arguments),this):R.apply(Object.create(R.prototype),arguments)}function Z(){var f=this;ye(f.path,f.flags,f.mode,function(y,h){y?(f.destroy(),f.emit("error",y)):(f.fd=h,f.emit("open",h))})}function Re(f,y){return new e.ReadStream(f,y)}function Ce(f,y){return new e.WriteStream(f,y)}var Tt=e.open;e.open=ye;function ye(f,y,h,D){return typeof h=="function"&&(D=h,h=null),P(f,y,h,D);function P(b,x,F,S,N){return Tt(b,x,F,function(g,tr){g&&(g.code==="EMFILE"||g.code==="ENFILE")?J([P,[b,x,F,S],g,N||Date.now(),Date.now()]):typeof S=="function"&&S.apply(this,arguments)})}}return e}function J(e){Y("ENQUEUE",e[0].name,e[1]),O[L].push(e),Ee()}var ae;function Ze(){for(var e=Date.now(),t=0;t<O[L].length;++t)O[L][t].length>2&&(O[L][t][3]=e,O[L][t][4]=e);Ee()}function Ee(){if(clearTimeout(ae),ae=void 0,O[L].length!==0){var e=O[L].shift(),t=e[0],r=e[1],n=e[2],o=e[3],u=e[4];if(o===void 0)Y("RETRY",t.name,r),t.apply(null,r);else if(Date.now()-o>=6e4){Y("TIMEOUT",t.name,r);var l=r.pop();typeof l=="function"&&l.call(null,n)}else{var p=Date.now()-u,T=Math.max(u-o,1),I=Math.min(T*1.2,100);p>=I?(Y("RETRY",t.name,r),t.apply(null,r.concat([o]))):O[L].push(e)}ae===void 0&&(ae=setTimeout(Ee,0))}}});var rt=k((Nr,tt)=>{d();function A(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}tt.exports=A;A.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};A.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};A.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),r=this._timeouts.shift();else return!1;var n=this,o=setTimeout(function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout(function(){n._operationTimeoutCb(n._attempts)},n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)},r);return this._options.unref&&o.unref(),!0};A.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};A.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)};A.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)};A.prototype.start=A.prototype.try;A.prototype.errors=function(){return this._errors};A.prototype.attempts=function(){return this._attempts};A.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var o=this._errors[n],u=o.message,l=(e[u]||0)+1;e[u]=l,l>=r&&(t=o,r=l)}return t}});var nt=k(K=>{d();var Ct=rt();K.operation=function(e){var t=K.timeouts(e);return new Ct(t,{forever:e&&e.forever,unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})};K.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],o=0;o<t.retries;o++)n.push(this.createTimeout(o,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(o,t)),n.sort(function(u,l){return u-l}),n};K.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*t.minTimeout*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout),n};K.wrap=function(e,t,r){if(t instanceof Array&&(r=t,t=null),!r){r=[];for(var n in e)typeof e[n]=="function"&&r.push(n)}for(var o=0;o<r.length;o++){var u=r[o],l=e[u];e[u]=function(T){var I=K.operation(t),i=Array.prototype.slice.call(arguments,1),m=i.pop();i.push(function(c){I.retry(c)||(c&&(arguments[0]=I.mainError()),m.apply(this,arguments))}),I.attempt(function(){T.apply(e,i)})}.bind(e,l),e[u].options=t}}});var ot=k((kr,it)=>{d();it.exports=nt()});var ut=k((Ar,fe)=>{d();fe.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&fe.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&fe.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var lt=k((qr,H)=>{d();var _=globalThis.process,z=function(e){return e&&typeof e=="object"&&typeof e.removeListener=="function"&&typeof e.emit=="function"&&typeof e.reallyExit=="function"&&typeof e.listeners=="function"&&typeof e.kill=="function"&&typeof e.pid=="number"&&typeof e.on=="function"};z(_)?(at=U("assert"),Q=ut(),ct=/^win/i.test(_.platform),ee=U("events"),typeof ee!="function"&&(ee=ee.EventEmitter),_.__signal_exit_emitter__?M=_.__signal_exit_emitter__:(M=_.__signal_exit_emitter__=new ee,M.count=0,M.emitted={}),M.infinite||(M.setMaxListeners(1/0),M.infinite=!0),H.exports=function(e,t){if(!z(globalThis.process))return function(){};at.equal(typeof e,"function","a callback must be provided for exit handler"),X===!1&&Fe();var r="exit";t&&t.alwaysLast&&(r="afterexit");var n=function(){M.removeListener(r,e),M.listeners("exit").length===0&&M.listeners("afterexit").length===0&&se()};return M.on(r,e),n},se=function(){!X||!z(globalThis.process)||(X=!1,Q.forEach(function(t){try{_.removeListener(t,le[t])}catch{}}),_.emit=me,_.reallyExit=Ie,M.count-=1)},H.exports.unload=se,B=function(t,r,n){M.emitted[t]||(M.emitted[t]=!0,M.emit(t,r,n))},le={},Q.forEach(function(e){le[e]=function(){if(z(globalThis.process)){var r=_.listeners(e);r.length===M.count&&(se(),B("exit",null,e),B("afterexit",null,e),ct&&e==="SIGHUP"&&(e="SIGINT"),_.kill(_.pid,e))}}}),H.exports.signals=function(){return Q},X=!1,Fe=function(){X||!z(globalThis.process)||(X=!0,M.count+=1,Q=Q.filter(function(t){try{return _.on(t,le[t]),!0}catch{return!1}}),_.emit=st,_.reallyExit=ft)},H.exports.load=Fe,Ie=_.reallyExit,ft=function(t){z(globalThis.process)&&(_.exitCode=t||0,B("exit",_.exitCode,null),B("afterexit",_.exitCode,null),Ie.call(_,_.exitCode))},me=_.emit,st=function(t,r){if(t==="exit"&&z(globalThis.process)){r!==void 0&&(_.exitCode=r);var n=me.apply(this,arguments);return B("exit",_.exitCode,null),B("afterexit",_.exitCode,null),n}else return me.apply(this,arguments)}):H.exports=function(){return function(){}};var at,Q,ct,ee,M,se,B,le,X,Fe,Ie,ft,me,st});var pt=k(($r,be)=>{"use strict";d();var mt=Symbol();function kt(e,t,r){let n=t[mt];if(n)return t.stat(e,(u,l)=>{if(u)return r(u);r(null,l.mtime,n)});let o=new Date(Math.ceil(Date.now()/1e3)*1e3+5);t.utimes(e,o,o,u=>{if(u)return r(u);t.stat(e,(l,p)=>{if(l)return r(l);let T=p.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(t,mt,{value:T}),r(null,p.mtime,T)})})}function jt(e){let t=Date.now();return e==="s"&&(t=Math.ceil(t/1e3)*1e3),new Date(t)}be.exports.probe=kt;be.exports.getMtime=jt});var St=k((Yr,re)=>{"use strict";d();var At=U("path"),Pe=Oe(),Gt=ot(),qt=lt(),ht=pt(),q={};function te(e,t){return t.lockfilePath||`${e}.lock`}function Ne(e,t,r){if(!t.realpath)return r(null,At.resolve(e));t.fs.realpath(e,r)}function De(e,t,r){let n=te(e,t);t.fs.mkdir(n,o=>{if(!o)return ht.probe(n,t.fs,(u,l,p)=>{if(u)return t.fs.rmdir(n,()=>{}),r(u);r(null,l,p)});if(o.code!=="EEXIST")return r(o);if(t.stale<=0)return r(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:e}));t.fs.stat(n,(u,l)=>{if(u)return u.code==="ENOENT"?De(e,{...t,stale:0},r):r(u);if(!dt(l,t))return r(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:e}));yt(e,t,p=>{if(p)return r(p);De(e,{...t,stale:0},r)})})})}function dt(e,t){return e.mtime.getTime()<Date.now()-t.stale}function yt(e,t,r){t.fs.rmdir(te(e,t),n=>{if(n&&n.code!=="ENOENT")return r(n);r()})}function pe(e,t){let r=q[e];r.updateTimeout||(r.updateDelay=r.updateDelay||t.update,r.updateTimeout=setTimeout(()=>{r.updateTimeout=null,t.fs.stat(r.lockfilePath,(n,o)=>{let u=r.lastUpdate+t.stale<Date.now();if(n)return n.code==="ENOENT"||u?Me(e,r,Object.assign(n,{code:"ECOMPROMISED"})):(r.updateDelay=1e3,pe(e,t));if(!(r.mtime.getTime()===o.mtime.getTime()))return Me(e,r,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let p=ht.getMtime(r.mtimePrecision);t.fs.utimes(r.lockfilePath,p,p,T=>{let I=r.lastUpdate+t.stale<Date.now();if(!r.released){if(T)return T.code==="ENOENT"||I?Me(e,r,Object.assign(T,{code:"ECOMPROMISED"})):(r.updateDelay=1e3,pe(e,t));r.mtime=p,r.lastUpdate=Date.now(),r.updateDelay=null,pe(e,t)}})})},r.updateDelay),r.updateTimeout.unref&&r.updateTimeout.unref())}function Me(e,t,r){t.released=!0,t.updateTimeout&&clearTimeout(t.updateTimeout),q[e]===t&&delete q[e],t.options.onCompromised(r)}function Ut(e,t,r){t={stale:1e4,update:null,realpath:!0,retries:0,fs:Pe,onCompromised:n=>{throw n},...t},t.retries=t.retries||0,t.retries=typeof t.retries=="number"?{retries:t.retries}:t.retries,t.stale=Math.max(t.stale||0,2e3),t.update=t.update==null?t.stale/2:t.update||0,t.update=Math.max(Math.min(t.update,t.stale/2),1e3),Ne(e,t,(n,o)=>{if(n)return r(n);let u=Gt.operation(t.retries);u.attempt(()=>{De(o,t,(l,p,T)=>{if(u.retry(l))return;if(l)return r(u.mainError());let I=q[o]={lockfilePath:te(o,t),mtime:p,mtimePrecision:T,options:t,lastUpdate:Date.now()};pe(o,t),r(null,i=>{if(I.released)return i&&i(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));vt(o,{...t,realpath:!1},i)})})})})}function vt(e,t,r){t={fs:Pe,realpath:!0,...t},Ne(e,t,(n,o)=>{if(n)return r(n);let u=q[o];if(!u)return r(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));u.updateTimeout&&clearTimeout(u.updateTimeout),u.released=!0,delete q[o],yt(o,t,r)})}function $t(e,t,r){t={stale:1e4,realpath:!0,fs:Pe,...t},t.stale=Math.max(t.stale||0,2e3),Ne(e,t,(n,o)=>{if(n)return r(n);t.fs.stat(te(o,t),(u,l)=>u?u.code==="ENOENT"?r(null,!1):r(u):r(null,!dt(l,t)))})}function Wt(){return q}qt(()=>{for(let e in q){let t=q[e].options;try{t.fs.rmdirSync(te(e,t))}catch{}}});re.exports.lock=Ut;re.exports.unlock=vt;re.exports.check=$t;re.exports.getLocks=Wt});var gt=k((zr,wt)=>{"use strict";d();var Yt=Oe();function Kt(e){let t=["mkdir","realpath","stat","rmdir","utimes"],r={...e};return t.forEach(n=>{r[n]=(...o)=>{let u=o.pop(),l;try{l=e[`${n}Sync`](...o)}catch(p){return u(p)}u(null,l)}}),r}function zt(e){return(...t)=>new Promise((r,n)=>{t.push((o,u)=>{o?n(o):r(u)}),e(...t)})}function Bt(e){return(...t)=>{let r,n;if(t.push((o,u)=>{r=o,n=u}),e(...t),r)throw r;return n}}function Jt(e){if(e={...e},e.fs=Kt(e.fs||Yt),typeof e.retries=="number"&&e.retries>0||e.retries&&typeof e.retries.retries=="number"&&e.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return e}wt.exports={toPromise:zt,toSync:Bt,toSyncOptions:Jt}});var er=k((Jr,W)=>{"use strict";d();var V=St(),{toPromise:he,toSync:de,toSyncOptions:Le}=gt();async function _t(e,t){let r=await he(V.lock)(e,t);return he(r)}function Qt(e,t){let r=de(V.lock)(e,Le(t));return de(r)}function Xt(e,t){return he(V.unlock)(e,t)}function Ht(e,t){return de(V.unlock)(e,Le(t))}function Vt(e,t){return he(V.check)(e,t)}function Zt(e,t){return de(V.check)(e,Le(t))}W.exports=_t;W.exports.lock=_t;W.exports.unlock=Xt;W.exports.lockSync=Qt;W.exports.unlockSync=Ht;W.exports.check=Vt;W.exports.checkSync=Zt});d();function $e(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}d();import*as j from"node:fs/promises";import*as G from"node:path";function Ye(){return G.join(ve.getGlobalMatildaDir(),Ae)}function we(e){return G.join(Ye(),e)}function ge(e){return G.join(we(e),qe)}function fr(e){return G.join(we(e),Ue)}function Et(e){return G.join(ve.getGlobalMatildaDir(),Ge,e)}function ie(e){return e.toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function sr(e,t){return`${ie(e)}@${ie(t)}`}function lr(e,t){let r=ie(e);if(!r)throw new Error(`Teammate name "${e}" sanitizes to an empty string. Choose a name with at least one alphanumeric character.`);if(r===Se)throw new Error(`"${Se}" is reserved for the team leader. Choose a different teammate name.`);let n=new Set(t.map(o=>o.name));if(n.has(r)){let o=[...n].join(", ")||"<none>";throw new Error(`A teammate named "${r}" already exists in this team (existing: ${o}). Choose a different name.`)}return r}function mr(e){let t=new Set(e.map(r=>r.color).filter(r=>r!==void 0));for(let r of ne)if(!t.has(r))return r;return ne[e.length%ne.length]}function pr(e){return e.map(t=>{let{color:r,...n}=t;return n})}function hr(e,t,r){return e.map(n=>n.agentId===t?{...n,isActive:r}:n)}function dr(e,t){return e.find(r=>r.agentId===t)}function yr(e,t){let r=ie(t);return e.find(n=>n.name===r)}function vr(e){let t=e.trimStart();if(/^shutdown_approved\b/i.test(t))return"shutdown_approved";if(/^shutdown_rejected\b/i.test(t))return"shutdown_rejected"}async function xt(e){let t=ge(e);try{let r=await j.readFile(t,"utf-8");return JSON.parse(r)}catch(r){if(ke(r)&&r.code==="ENOENT")return;throw r}}async function Sr(e,t){let r=ge(e);await j.mkdir(G.dirname(r),{recursive:!0}),await je(r,t)}async function wr(e,t){let r=ge(e);await j.mkdir(G.dirname(r),{recursive:!0}),await j.writeFile(r,JSON.stringify(t,null,2)+`
5
5
  `,{encoding:"utf-8",flag:"wx"})}async function gr(e){let t;try{t=await xt(e)}catch{return!1}return t?typeof t.leadPid!="number"||t.leadPid<=0||t.leadPid!==process.pid&&$e(t.leadPid)?!1:(await We(e),!0):(await We(e),!0)}async function We(e){let t=we(e),r=Et(e);await Promise.allSettled([j.rm(t,{recursive:!0,force:!0}),j.rm(r,{recursive:!0,force:!0})])}async function _r(){let e=Ye();try{return(await j.readdir(e,{withFileTypes:!0})).filter(r=>r.isDirectory()).map(r=>r.name)}catch{return[]}}export{Oe as a,er as b,$e as c,Ye as d,we as e,ge as f,fr as g,Et as h,ie as i,sr as j,lr as k,mr as l,pr as m,hr as n,dr as o,yr as p,vr as q,xt as r,Sr as s,wr as t,gr as u,We as v,_r as w};
6
6
  /**
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{f}from"./chunk-2HQMJ2IU.js";import{f as u}from"./chunk-QKYGQLWC.js";import{g as m,i as c,p as l,q as p}from"./chunk-T4P4KEDW.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();var o=2e3;function T(e){return e.length<=o?e:`${e.slice(0,o)}
3
+ import{f}from"./chunk-2MOGYHWM.js";import{f as u}from"./chunk-QKYGQLWC.js";import{g as m,i as c,p as l,q as p}from"./chunk-6E766NPX.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();var o=2e3;function T(e){return e.length<=o?e:`${e.slice(0,o)}
4
4
  \u2026 (${e.length-o} more characters)`}var s=class extends m{constructor(t,r){super(r);this.config=t}getDescription(){return`Create task: ${this.params.subject}`}async getDefaultPermission(){return"ask"}getConfirmationDetails(t){let r={type:"info",title:"Confirm TaskCreate",prompt:`Create task: ${this.params.subject}
5
5
 
6
6
  `+T(this.params.description),onConfirm:async()=>{}};return Promise.resolve(r)}async execute(){let t=u(this.config.getTeamContext()?.teamName);if(!t){let a="No active team. Create a team first.";return{llmContent:a,returnDisplay:a,error:{message:a}}}let r=await f(t,{subject:this.params.subject,description:this.params.description,activeForm:this.params.activeForm,metadata:this.params.metadata}),i=`Task #${r.id} created: "${r.subject}"`;return{llmContent:i,returnDisplay:i}}},d=class e extends c{constructor(t){super(e.Name,p.TASK_CREATE,"Create a new task in the team task list. Tasks are automatically assigned to idle teammates.","other",{type:"object",properties:{subject:{type:"string",description:"Short title for the task.",maxLength:200},description:{type:"string",description:"Detailed description of the task.",maxLength:1e4},activeForm:{type:"string",maxLength:200,description:'Present tense label for UI (e.g., "Running tests").'},metadata:{type:"object",description:"Optional arbitrary metadata."}},required:["subject","description"],additionalProperties:!1});this.config=t}static Name=l.TASK_CREATE;createInvocation(t){return new s(this.config,t)}toAutoClassifierInput(t){return{subject:t.subject,description:t.description}}};export{T as a,d as b};
@@ -0,0 +1,27 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as U}from"./chunk-KHHJYBR5.js";import{c as Q}from"./chunk-VI74YQQO.js";import{a as Y,b as N}from"./chunk-3YLXGE6T.js";import{b as X}from"./chunk-LUNDTQ3G.js";import{Q as S,ba as I}from"./chunk-27Q5KW3A.js";import{b as M}from"./chunk-GZPNIYVZ.js";M();import ie from"crypto";import q from"node:path";import{promises as b}from"node:fs";import{EventEmitter as Re}from"events";import{randomUUID as se}from"node:crypto";M();import{execFile as le,spawn as de}from"node:child_process";import{promisify as he}from"node:util";import{platform as ue}from"node:os";import{resolve as Z}from"node:path";import{URL as fe,fileURLToPath as me}from"node:url";var ee=he(le);function pe(i,{allowFile:e=!1,allowedFilePaths:r}={}){let t;try{t=new fe(i)}catch{throw new Error(`Invalid URL: ${i}`)}let o=e?["http:","https:","file:"]:["http:","https:"];if(!o.includes(t.protocol))throw new Error(`Unsafe protocol: ${t.protocol}. Only ${o.join(", ")} are allowed.`);if(t.protocol==="file:"&&e){if(!r?.length)throw new Error("allowedFilePaths is required when allowFile is true");let n=Z(me(t));if(!r.map(c=>Z(c)).includes(n))throw new Error("File URL is not in the allowed file set")}if(/[\r\n\x00-\x1f]/.test(i))throw new Error("URL contains invalid characters")}async function te(i,e={}){pe(i,e);let r=ue(),t,o,n=process.env.BROWSER?.trim(),s=r==="win32"?void 0:we(n,i);if(s)try{await re(s.command,s.args);return}catch(l){console.warn(`Failed to open BROWSER command ${s.command}: ${ge(l)}. Falling back to the platform browser opener.`)}if(!N({ignoreBrowserBlocklist:!0})){console.warn(`Browser launch is not available in this environment. Please open this URL manually: ${i}`);return}switch(r){case"darwin":t="open",o=[i];break;case"win32":t="powershell.exe",o=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${i.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":t="xdg-open",o=[i];break;default:throw new Error(`Unsupported platform: ${r}`)}let c={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await ee(t,o,c)}catch{if((r==="linux"||r==="freebsd"||r==="openbsd")&&t==="xdg-open"){let a=[{command:"gnome-open",detached:!1},{command:"kde-open",detached:!1},{command:"firefox",detached:!0},{command:"chromium",detached:!0},{command:"google-chrome",detached:!0},{command:"microsoft-edge",detached:!0}];for(let{command:d,detached:p}of a)try{p?await re(d,[i]):await ee(d,[i],c);return}catch{continue}}console.warn(`Failed to open browser automatically. Please open this URL manually: ${i}`);return}}async function re(i,e){let r={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};await new Promise((t,o)=>{let n=de(i,e,r),s=!1;n.once("error",c=>{s||(s=!0,o(c))}),n.once("spawn",()=>{s||(s=!0,n.unref(),t())})})}function ge(i){return i instanceof Error?i.message:String(i)}function we(i,e){if(!i)return;let r=ke(i);if(!r){console.warn("Invalid BROWSER environment variable, falling back to platform default.");return}if(Y(r.command))return;let t=!1,o=r.args.map(n=>n.includes("%s")?(t=!0,n.replace(/%s/g,()=>e)):n);return t||o.push(e),{command:r.command,args:o}}function ke(i){let e=[],r="",t;for(let s of i){if(t){s===t?t=void 0:r+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){r&&(e.push(r),r="");continue}r+=s}if(t)return;r&&e.push(r);let[o,...n]=e;if(o)return{command:o,args:n}}function Ve(){return N()}M();import H from"node:path";import{promises as y,unlinkSync as Ee}from"node:fs";import{randomUUID as ne}from"node:crypto";var D=I("MATILDA_OAUTH"),_e="oauth_creds.json",Ce="oauth_creds.lock",ve=30*1e3,ye=35e3,Te=5e3,oe={maxAttempts:20,attemptInterval:100,maxInterval:2e3};var h=class extends Error{constructor(r,t,o){super(t);this.type=r;this.originalError=o;this.name="TokenManagerError"}};function De(i){if(!i||typeof i!="object")throw new Error("Invalid credentials format");let e=i,r=["access_token","refresh_token","token_type"];for(let t of r)if(!e[t]||typeof e[t]!="string")throw new Error(`Invalid credentials: missing ${t}`);if(!e.expiry_date||typeof e.expiry_date!="number")throw new Error("Invalid credentials: missing expiry_date");return e}var R=class i{static instance=null;memoryCache={credentials:null,fileModTime:0,lastCheck:0};refreshPromise=null;checkPromise=null;cleanupHandlersRegistered=!1;cleanupFunction=null;lockConfig=oe;constructor(){this.registerCleanupHandlers()}static getInstance(){return i.instance||(i.instance=new i),i.instance}registerCleanupHandlers(){this.cleanupHandlersRegistered||(this.cleanupFunction=()=>{try{let e=this.getLockFilePath();Ee(e)}catch{}},process.on("exit",this.cleanupFunction),this.cleanupHandlersRegistered=!0)}async getValidCredentials(e,r=!1){try{if(await this.checkAndReloadIfNeeded(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let t=this.refreshPromise;t||(t=this.performTokenRefresh(e,r),this.refreshPromise=t);try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}catch(t){throw t instanceof h?t:new h("REFRESH_FAILED",`Failed to get valid credentials: ${t instanceof Error?t.message:String(t)}`,t)}}async checkAndReloadIfNeeded(e){if(this.checkPromise){await this.checkPromise;return}if(this.refreshPromise)return;let r=Date.now();if(!(r-this.memoryCache.lastCheck<Te)){this.checkPromise=this.performFileCheck(e,r);try{await this.checkPromise}finally{this.checkPromise=null}}}withTimeout(e,r,t="Operation"){let o;return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),new Promise((n,s)=>{o=setTimeout(()=>s(new Error(`${t} timed out after ${r}ms`)),r)})])}async performFileCheck(e,r){this.memoryCache.lastCheck=r;try{let t=this.getCredentialFilePath(),n=(await this.withTimeout(y.stat(t),3e3,"File operation")).mtimeMs;n>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=n)}catch(t){if(t instanceof Error&&"code"in t&&t.code!=="ENOENT")throw this.updateCacheState(null,0,r),new h("FILE_ACCESS_ERROR",`Failed to access credentials file: ${t.message}`,t);this.memoryCache.fileModTime=0}}async forceFileCheck(e){try{let r=this.getCredentialFilePath(),o=(await y.stat(r)).mtimeMs;o>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=o,this.memoryCache.lastCheck=Date.now())}catch(r){if(r instanceof Error&&"code"in r&&r.code!=="ENOENT")throw this.updateCacheState(null,0),new h("FILE_ACCESS_ERROR",`Failed to access credentials file during refresh: ${r.message}`,r);this.memoryCache.fileModTime=0}}async reloadCredentialsFromFile(e){try{let r=this.getCredentialFilePath(),t=await y.readFile(r,"utf-8"),o=JSON.parse(t),n=De(o),s=this.memoryCache.credentials;this.memoryCache.credentials=n;try{e&&e.setCredentials(n)}catch(c){throw this.memoryCache.credentials=s,c}}catch(r){r instanceof Error&&r.message.includes("Invalid credentials")&&D.warn(`Failed to validate credentials file: ${r.message}`),this.memoryCache.credentials=null}}async performTokenRefresh(e,r=!1){let t=Date.now(),o=this.getLockFilePath(),n=!1;try{let s=e.getCredentials();if(!s.refresh_token)throw new h("NO_REFRESH_TOKEN","No refresh token available for token refresh");await this.acquireLock(o),n=!0;let c=Date.now()-t;if(c>5e3&&D.warn(`Token refresh lock acquisition took ${c}ms`),await this.forceFileCheck(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let l=await e.refreshAccessToken(),a=Date.now()-t;if(a>1e4&&D.warn(`Token refresh operation took ${a}ms`),!l||L(l)){let w=l;throw new h("REFRESH_FAILED",`Token refresh failed: ${w?.error||"Unknown error"} - ${w?.error_description||"No details provided"}`)}let d=l;if(!d.access_token)throw new h("REFRESH_FAILED","Failed to refresh access token: no token returned");let p={access_token:d.access_token,token_type:d.token_type,refresh_token:d.refresh_token||s.refresh_token,resource_url:d.resource_url,expiry_date:Date.now()+d.expires_in*1e3};return this.memoryCache.credentials=p,e.setCredentials(p),await this.saveCredentialsToFile(p),p}catch(s){throw s instanceof F?(D.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement"),this.memoryCache.credentials=null,this.memoryCache.fileModTime=0,this.refreshPromise=null,new h("REFRESH_FAILED",s.message,s)):s instanceof h?s:s instanceof Error&&(s.message.includes("fetch")||s.message.includes("network")||s.message.includes("timeout"))?new h("NETWORK_ERROR",`Network error during token refresh: ${s.message}`,s):new h("REFRESH_FAILED",`Unexpected error during token refresh: ${s instanceof Error?s.message:String(s)}`,s)}finally{n&&await this.releaseLock(o)}}async saveCredentialsToFile(e){let r=this.getCredentialFilePath(),t=H.dirname(r);try{await this.withTimeout(y.mkdir(t,{recursive:!0,mode:448}),5e3,"File operation")}catch(n){throw new h("FILE_ACCESS_ERROR",`Failed to create credentials directory: ${n instanceof Error?n.message:String(n)}`,n)}let o=JSON.stringify(e,null,2);try{await X(r,o,{mode:384,forceMode:!0,noFollow:!0});let n=await this.withTimeout(y.stat(r),5e3,"File operation");this.memoryCache.fileModTime=n.mtimeMs}catch(n){throw new h("FILE_ACCESS_ERROR",`Failed to write credentials file: ${n instanceof Error?n.message:String(n)}`,n)}}isTokenValid(e){return!e.expiry_date||!e.access_token?!1:Date.now()<e.expiry_date-ve}getCredentialFilePath(){return H.join(S.getGlobalMatildaDir(),_e)}getLockFilePath(){return H.join(S.getGlobalMatildaDir(),Ce)}async acquireLock(e){let{maxAttempts:r,attemptInterval:t,maxInterval:o}=this.lockConfig,n=ne(),s=t;for(let c=0;c<r;c++)try{await y.writeFile(e,n,{flag:"wx"});return}catch(l){if(l.code==="EEXIST"){try{let a=await y.stat(e),d=Date.now()-a.mtimeMs;if(d>ye){let p=`${e}.stale.${ne()}`;try{await y.rename(e,p),await y.unlink(p),D.warn(`Removed stale lock file: ${e} (age: ${d}ms)`);continue}catch(w){D.warn(`Failed to remove stale lock file ${e}: ${w instanceof Error?w.message:String(w)}`)}}}catch(a){D.warn(`Failed to stat lock file ${e}: ${a instanceof Error?a.message:String(a)}`)}await new Promise(a=>setTimeout(a,s)),s=Math.min(s*1.5,o)}else throw new h("FILE_ACCESS_ERROR",`Failed to create lock file: ${l instanceof Error?l.message:String(l)}`,l)}throw new h("LOCK_TIMEOUT","Failed to acquire file lock for token refresh: timeout exceeded")}async releaseLock(e){try{await y.unlink(e)}catch(r){r.code!=="ENOENT"&&D.warn(`Failed to release lock file ${e}: ${r instanceof Error?r.message:String(r)}`)}}updateCacheState(e,r,t){this.memoryCache={credentials:e,fileModTime:r,lastCheck:t??Date.now()}}clearCache(){this.updateCacheState(null,0,0),this.refreshPromise=null,this.checkPromise=null}getCurrentCredentials(){return this.memoryCache.credentials}isRefreshInProgress(){return this.refreshPromise!==null}setLockConfig(e){this.lockConfig={...oe,...e}}cleanup(){this.cleanupFunction&&this.cleanupHandlersRegistered&&(this.cleanupFunction(),process.removeListener("exit",this.cleanupFunction),this.cleanupHandlersRegistered=!1,this.cleanupFunction=null)}getDebugInfo(){let e=!!this.memoryCache.credentials,r=e?!this.isTokenValid(this.memoryCache.credentials):!1;return{hasCredentials:e,credentialsExpired:r,isRefreshing:this.isRefreshInProgress(),cacheAge:Date.now()-this.memoryCache.lastCheck}}};var u=I("MATILDA_OAUTH"),G="https://chat.matilda.ai",Ae=`${G}/api/v1/oauth2/device/code`,K=`${G}/api/v1/oauth2/token`,z="f0304373b74a44d2b584a3fb70ca9e56",Me="openid profile email model.completion",be="urn:ietf:params:oauth:grant-type:device_code",Pe=3e4,Se="oauth_creds.json";function Fe(){return ie.randomBytes(32).toString("base64url")}function Oe(i){let e=ie.createHash("sha256");return e.update(i),e.digest("base64url")}function xe(){let i=Fe(),e=Oe(i);return{code_verifier:i,code_challenge:e}}function B(i){return Object.keys(i).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(i[e])}`).join("&")}function W(i,e){let r=e?"Token refresh timeout":"Token refresh failed";return new Error(`${r}: ${U(i,{url:K})}`,{cause:i})}var F=class extends Error{constructor(r,t){super(r);this.originalError=t;this.name="CredentialsClearRequiredError"}},j=class extends Error{status;oauthError;description;constructor(e){super(`Device token poll failed: ${e.oauthError??"Unknown error"} - ${e.description??"(no description)"}`),this.name="MatildaOAuthPollError",this.oauthError=e.oauthError,this.description=e.description,this.status=e.status}};function V(i){return"device_code"in i}function Ie(i){return"access_token"in i&&i.access_token!==null&&i.access_token!==void 0&&typeof i.access_token=="string"&&i.access_token.length>0}function Le(i){return"status"in i&&i.status==="pending"}function L(i){return"error"in i}var J=class{credentials={};sharedManager;constructor(){this.sharedManager=R.getInstance()}setCredentials(e){this.credentials=e}getCredentials(){return this.credentials}async getAccessToken(){try{return{token:(await this.sharedManager.getValidCredentials(this)).access_token}}catch(e){return u.warn("Failed to get access token from shared manager:",e),{token:void 0}}}async requestDeviceAuthorization(e,r){let t={client_id:z,scope:e.scope,code_challenge:e.code_challenge,code_challenge_method:e.code_challenge_method},o=await fetch(Ae,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","x-request-id":se()},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let s=await o.text();throw new Error(`Device authorization failed: ${o.status} ${o.statusText}. Response: ${s}`)}let n=await o.json();if(V(n))u.debug("Device authorization result (sanitized):",{ok:!0,expires_in:n.expires_in});else{let s=n;u.debug("Device authorization result (sanitized):",{ok:!1,error:s?.error})}if(!V(n)){let s=n;throw new Error(`Device authorization failed: ${s?.error||"Unknown error"} - ${s?.error_description||"No details provided"}`)}return n}async pollDeviceToken(e,r){let t={grant_type:be,client_id:z,device_code:e.device_code,code_verifier:e.code_verifier},o=await fetch(K,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let n=await o.text(),s=null;try{s=JSON.parse(n)}catch{let l=new Error(`Device token poll failed: ${o.status} ${o.statusText}. Response: ${n}`);throw l.status=o.status,l}if(o.status===400&&s.error==="authorization_pending")return{status:"pending"};if(o.status===429&&s.error==="slow_down")return{status:"pending",slowDown:!0};throw new j({oauthError:s.error,description:s.error_description,status:o.status})}return await o.json()}async refreshAccessToken(){if(!this.credentials.refresh_token)throw new Error("No refresh token available");let e={grant_type:"refresh_token",refresh_token:this.credentials.refresh_token,client_id:z},{signal:r,cleanup:t}=Q([],{timeoutMs:Pe});u.debug("Refreshing access token...");try{let o;try{o=await fetch(K,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(e),signal:r})}catch(a){throw W(a,r.aborted)}if(!o.ok){let a;try{a=await o.text()}catch(d){throw W(d,r.aborted)}throw o.status===400||o.status===401?(await ae(),new F("Refresh token expired or invalid. Please use '/auth' to re-authenticate.",{status:o.status,response:a})):new Error(`Token refresh failed: ${o.status} ${o.statusText}. Response: ${a}`)}let n;try{n=await o.text()}catch(a){throw W(a,r.aborted)}let s;try{s=JSON.parse(n)}catch{throw new Error(`Legacy OAuth refresh returned invalid JSON: ${n||"(empty response body)"}`)}if(L(s)){let a=s;throw new Error(`Token refresh failed: ${a?.error||"Unknown error"} - ${a?.error_description||"No details provided"}`)}let c=s,l={access_token:c.access_token,token_type:c.token_type,refresh_token:c.refresh_token||this.credentials.refresh_token,resource_url:c.resource_url,expiry_date:Date.now()+c.expires_in*1e3};return this.setCredentials(l),s}finally{t()}}},$e=(t=>(t.AuthUri="auth-uri",t.AuthProgress="auth-progress",t.AuthCancel="auth-cancel",t))($e||{}),P=new Re;async function wr(i,e){let r=new J,t=R.getInstance();try{let o=await t.getValidCredentials(r);return r.setCredentials(o),r}catch(o){if(o instanceof h)switch(o.type){case"NO_REFRESH_TOKEN":u.debug("No refresh token available, proceeding with device flow");break;case"REFRESH_FAILED":u.debug("Token refresh failed, proceeding with device flow");break;case"NETWORK_ERROR":u.warn("Network error during token refresh, trying device flow");break;default:u.warn("Token manager error:",o.message)}if(e?.requireCachedCredentials)throw new Error("Matilda OAuth credentials expired. Please use /auth to re-authenticate with matilda-oauth.");let n=await Ue(r,i);if(!n.success){n.reason==="timeout"&&P.emit("auth-progress","timeout","Authentication timed out. Please try again or select a different authentication method.");let s=n.message||(()=>{switch(n.reason){case"timeout":return"Legacy OAuth authentication timed out";case"cancelled":return"Legacy OAuth authentication was cancelled by user";case"rate_limit":return"Too many requests for legacy OAuth authentication, please try again later.";case"error":default:return"Legacy OAuth authentication failed"}})();throw new Error(s)}return r}}function Ne(i){let e="Legacy OAuth Device Authorization",r=i,n=Math.min(Math.max(e.length+4,70),80),s=n-4,c=(m,T)=>{if(m.startsWith("http://")||m.startsWith("https://")){let v=[];for(let x=0;x<m.length;x+=T)v.push(m.substring(x,x+T));return v}let A=m.split(" "),C=[],_="";for(let v of A)_.length+v.length+1<=T?_+=(_?" ":"")+v:(_&&C.push(_),_=v.length>T?v.substring(0,T):v);return _&&C.push(_),C},l=" "+e+" ",a=n-2-l.length,d=Math.floor(a/2),p=a-d,w="+"+"-".repeat(d)+l+"-".repeat(p)+"+",k="|"+" ".repeat(n-2)+"|",O="+"+"-".repeat(n-2)+"+",g=c("Please visit the following URL in your browser to authorize:",s),f=c(r,s),E="Waiting for authorization to complete...";process.stderr.write(`
4
+ `+w+`
5
+ `),process.stderr.write(k+`
6
+ `);for(let m of g)process.stderr.write("| "+m+" ".repeat(s-m.length)+` |
7
+ `);process.stderr.write(k+`
8
+ `);for(let m of f)process.stderr.write("| "+m+" ".repeat(s-m.length)+` |
9
+ `);process.stderr.write(k+`
10
+ `),process.stderr.write("| "+E+" ".repeat(s-E.length)+` |
11
+ `),process.stderr.write(k+`
12
+ `),process.stderr.write(O+`
13
+
14
+ `)}async function Ue(i,e){let r=!1,t=()=>{r=!0};P.once("auth-cancel",t);let o=()=>{if(!r)return null;let c="Authentication cancelled by user.";return u.debug(`
15
+ `+c),P.emit("auth-progress","error",c),{success:!1,reason:"cancelled",message:c}},n=(c,l)=>{P.emit("auth-progress",c,l)},s=async c=>{try{await te(c)}catch(l){let a=l instanceof Error?l.message:String(l);u.warn(`Failed to open browser automatically: ${a}`),u.info(`Please open this URL manually: ${c}`)}};try{let{code_verifier:c,code_challenge:l}=xe(),a=await i.requestDeviceAuthorization({scope:Me,code_challenge:l,code_challenge_method:"S256"});if(!V(a)){let k=a;throw new Error(`Device authorization failed: ${k?.error||"Unknown error"} - ${k?.error_description||"No details provided"}`)}P.emit("auth-uri",a),(e.isBrowserLaunchSuppressed()||!e.isInteractive())&&Ne(a.verification_uri_complete),e.isBrowserLaunchSuppressed()||await s(a.verification_uri_complete),n("polling","Waiting for authorization..."),u.debug(`Waiting for authorization...
16
+ `);let d=2e3,p=Math.ceil(a.expires_in/(d/1e3));for(let k=0;k<p;k++){let O=o();if(O)return O;try{u.debug("polling for token...");let g=await i.pollDeviceToken({device_code:a.device_code,code_verifier:c});if(Ie(g)){let f=g,E={access_token:f.access_token,refresh_token:f.refresh_token||void 0,token_type:f.token_type,resource_url:f.resource_url,expiry_date:f.expires_in?Date.now()+f.expires_in*1e3:void 0};return i.setCredentials(E),await He(E),n("success","Authentication successful! Access token obtained."),u.debug("Authentication successful! Access token obtained."),{success:!0}}if(Le(g)){g.slowDown?(d=Math.min(d*1.5,1e4),u.debug(`
17
+ Server requested to slow down, increasing poll interval to ${d}ms'`)):d=2e3,n("polling",`Polling... (attempt ${k+1}/${p})`),await new Promise(m=>{let A=0,C=setInterval(()=>{if(A+=100,r){clearInterval(C),m();return}if(A>=d){clearInterval(C),m();return}},100)});let E=o();if(E)return E;continue}if(L(g)){let f=g;throw new Error(`Token polling failed: ${f?.error||"Unknown error"} - ${f?.error_description||"No details provided"}`)}}catch(g){let f=g instanceof Error?g.message:String(g),E=g instanceof Error?g.status:null,m=(C,_,v="error")=>(n(v,_),{success:!1,reason:C,message:_}),T=o();if(T)return T;if(f.includes("Failed to cache credentials"))return m("error",f);if(f.includes("401")||E===401)return m("error","Device code expired or invalid, please restart the authorization process.");if(f.includes("429")||E===429)return m("rate_limit","Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.","rate_limit");let A=`Error polling for token: ${f}`;n("error",A),await new Promise(C=>setTimeout(C,d))}}let w="Authorization timeout, please restart the process.";return n("timeout",w),{success:!1,reason:"timeout",message:w}}catch(c){let a=`Device authorization flow failed: ${U(c,{url:G})}`;return n("error",a),{success:!1,reason:"error",message:a}}finally{P.off("auth-cancel",t)}}var $=384;async function He(i,e){let r=ce();try{await b.mkdir(q.dirname(r),{recursive:!0});let t=JSON.stringify(i,null,2),o=`${r}.tmp.${process.pid}.${se()}`;try{await b.writeFile(o,t,{mode:$,...e?.signal?{signal:e.signal}:{}});try{await b.chmod(o,$)}catch(n){if(process.platform!=="win32")throw new Error(`cacheMatildaCredentials: refusing to publish credentials \u2014 chmod 0o${$.toString(8)} on temp file failed: ${n instanceof Error?n.message:String(n)}`);u.warn(`cacheMatildaCredentials: chmod 0o${$.toString(8)} on Windows temp file ${o} failed; relying on NTFS ACL: ${n instanceof Error?n.message:String(n)}`)}await b.rename(o,r)}catch(n){try{await b.unlink(o)}catch{}throw n}try{R.getInstance().clearCache()}catch(n){u.warn(`cacheMatildaCredentials: SharedTokenManager.clearCache failed; in-process callers may serve stale credentials until the next mtime poll: ${n instanceof Error?n.message:String(n)}`)}}catch(t){let o=t instanceof Error?t.message:String(t);throw(t instanceof Error&&"code"in t?t.code:void 0)==="EACCES"?new Error(`Failed to cache credentials: Permission denied (EACCES). Current user has no permission to access \`${r}\`. Please check permissions.`):new Error(`Failed to cache credentials: error when creating folder \`${q.dirname(r)}\` and writing to \`${r}\`. ${o}. Please check permissions.`)}}async function ae(){try{let i=ce();await b.unlink(i),u.debug("Cached legacy OAuth credentials cleared successfully.")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;u.warn("Warning: Failed to clear cached legacy OAuth credentials:",i)}finally{try{R.getInstance().clearCache()}catch{}}}function ce(){return q.join(S.getGlobalMatildaDir(),Se)}var kr=ae;export{te as a,Ve as b,R as c,Fe as d,Oe as e,xe as f,F as g,j as h,V as i,Ie as j,Le as k,L as l,J as m,$e as n,P as o,wr as p,$ as q,He as r,ae as s,kr as t};
18
+ /**
19
+ * @license
20
+ * Copyright 2025 Google LLC
21
+ * SPDX-License-Identifier: Apache-2.0
22
+ */
23
+ /**
24
+ * @license
25
+ * Copyright 2025 Matilda
26
+ * SPDX-License-Identifier: Apache-2.0
27
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as r}from"./chunk-HYVP4472.js";import{ba as g}from"./chunk-MH2P4YXC.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();function h(n,o){return`Base directory for this skill: ${n}
3
+ import{a as r}from"./chunk-HYVP4472.js";import{ba as g}from"./chunk-27Q5KW3A.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();function h(n,o){return`Base directory for this skill: ${n}
4
4
  Important: ALWAYS resolve absolute paths from this base directory when working with skills.
5
5
 
6
6
  ${o}
@@ -1,10 +1,10 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{_h as T}from"./chunk-QFNFLE2I.js";import{Q as b}from"./chunk-MH2P4YXC.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
3
+ import{Yh as T}from"./chunk-JRECUFB3.js";import{Q as b}from"./chunk-27Q5KW3A.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
4
4
  `)?e:`${e}
5
5
  `)},m=e=>{process.stderr.write(e.endsWith(`
6
6
  `)?e:`${e}
7
- `)},W=()=>{console.clear()};o();import*as u from"node:fs";import*as f from"node:path";import{pathToFileURL as N}from"node:url";o();var p=[{code:"en",id:"en-AU",fullName:"Australian English",nativeName:"English (AU)"},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function A(e){return e.trim().replace(/_/g,"-").toLowerCase()}var M=new Set(["zh","zh-cn","zh-hans","zh-sg","zh-tw","zh-hk","zh-mo","zh-hant","chinese","traditional chinese","simplified chinese","\u4E2D\u6587","\u7B80\u4F53\u4E2D\u6587","\u7E41\u9AD4\u4E2D\u6587","\u7E41\u4F53\u4E2D\u6587"]);function E(e){let t=A(e);return t?M.has(t)?!0:t.startsWith("zh-")||t.startsWith("zh.")||t.startsWith("zh@"):!1}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function z(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function l(e){let t=A(e);if(!t)return;if(t==="english"||t==="australian"||t==="australian-english")return"en";let n;for(let r of p){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=z(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function C(e){let t=l(e);return(t?p.find(r=>r.code===t):void 0)?.fullName||"English"}function q(){return[{value:"auto",label:"Auto (detect from system)"},...p.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var I=w({"./locales/ca.js":()=>import("./ca-EUJBUYX5.js"),"./locales/de.js":()=>import("./de-DNEPG7S7.js"),"./locales/en.js":()=>import("./en-NOD6KQNM.js"),"./locales/fr.js":()=>import("./fr-2OE5WLJ4.js"),"./locales/ja.js":()=>import("./ja-3B6V5KS7.js"),"./locales/pt.js":()=>import("./pt-KP2JCPUY.js"),"./locales/ru.js":()=>import("./ru-K7IQQKHC.js")});var y="en",v={},i={},S={},R=()=>f.join(T(import.meta.url),"locales"),U=()=>f.join(b.getGlobalMatildaDir(),"locales");var D=(e,t=!1)=>{let n=t?U():R();return f.join(n,`${e}.js`)};function O(){let e=process.env.MATILDA_CODE_LANG||process.env.LANG;if(e){let t=l(e);if(t)return t}try{let t=Intl.DateTimeFormat().resolvedOptions().locale,n=l(t);if(n)return n}catch{}return"en"}async function P(e){try{let t=await import(e),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function $(e){try{let t=await I(`./locales/${e}.js`),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function j(e){if(i[e])return i[e];let t=S[e];if(t)return t;let n=(async()=>{let r=D(e,!0);if(u.existsSync(U())&&u.existsSync(r)){let s=await P(N(r).href);if(s.translations)return i[e]=s.translations,s.translations;m(`Failed to load translations from user directory for ${e}: ${s.error.message}`)}let a=D(e,!1),x=[];u.existsSync(R())&&u.existsSync(a)&&x.push(N(a).href);let c;for(let s of x){let g=await P(s);if(g.translations)return i[e]=g.translations,g.translations;c=g.error}let d=await $(e);return d.translations?(i[e]=d.translations,d.translations):(c=d.error,c&&m(`Failed to load JS translations for ${e}: ${c.message}`),i[e]={},{})})();return S[e]=n,n.finally(()=>{delete S[e]}),n}function _(e,t){return t?e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n):e}function F(e){return e==="auto"?O():E(e)?"en":l(e)??e}async function G(e){y=F(e),v=await j(y)}function le(){return y}function ue(e,t){let n=v[e]??e;return Array.isArray(n)?e:_(n,t)}function ce(e){let t=v[e];return Array.isArray(t)?t:[]}async function de(e){await G(e??"auto")}export{B as a,m as b,W as c,p as d,E as e,l as f,C as g,q as h,O as i,G as j,le as k,ue as l,ce as m,de as n};
7
+ `)},W=()=>{console.clear()};o();import*as u from"node:fs";import*as f from"node:path";import{pathToFileURL as N}from"node:url";o();var p=[{code:"en",id:"en-AU",fullName:"Australian English",nativeName:"English (AU)"},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function A(e){return e.trim().replace(/_/g,"-").toLowerCase()}var M=new Set(["zh","zh-cn","zh-hans","zh-sg","zh-tw","zh-hk","zh-mo","zh-hant","chinese","traditional chinese","simplified chinese","\u4E2D\u6587","\u7B80\u4F53\u4E2D\u6587","\u7E41\u9AD4\u4E2D\u6587","\u7E41\u4F53\u4E2D\u6587"]);function E(e){let t=A(e);return t?M.has(t)?!0:t.startsWith("zh-")||t.startsWith("zh.")||t.startsWith("zh@"):!1}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function z(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function l(e){let t=A(e);if(!t)return;if(t==="english"||t==="australian"||t==="australian-english")return"en";let n;for(let r of p){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=z(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function C(e){let t=l(e);return(t?p.find(r=>r.code===t):void 0)?.fullName||"English"}function q(){return[{value:"auto",label:"Auto (detect from system)"},...p.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var I=w({"./locales/ca.js":()=>import("./ca-I2HEEIL7.js"),"./locales/de.js":()=>import("./de-AQXFJYZI.js"),"./locales/en.js":()=>import("./en-EJLDYIBM.js"),"./locales/fr.js":()=>import("./fr-6TDHK7F2.js"),"./locales/ja.js":()=>import("./ja-GGNJR7AR.js"),"./locales/pt.js":()=>import("./pt-D6L2QTDM.js"),"./locales/ru.js":()=>import("./ru-BNJCHDYO.js")});var y="en",v={},i={},S={},R=()=>f.join(T(import.meta.url),"locales"),U=()=>f.join(b.getGlobalMatildaDir(),"locales");var D=(e,t=!1)=>{let n=t?U():R();return f.join(n,`${e}.js`)};function O(){let e=process.env.MATILDA_CODE_LANG||process.env.LANG;if(e){let t=l(e);if(t)return t}try{let t=Intl.DateTimeFormat().resolvedOptions().locale,n=l(t);if(n)return n}catch{}return"en"}async function P(e){try{let t=await import(e),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function $(e){try{let t=await I(`./locales/${e}.js`),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function j(e){if(i[e])return i[e];let t=S[e];if(t)return t;let n=(async()=>{let r=D(e,!0);if(u.existsSync(U())&&u.existsSync(r)){let s=await P(N(r).href);if(s.translations)return i[e]=s.translations,s.translations;m(`Failed to load translations from user directory for ${e}: ${s.error.message}`)}let a=D(e,!1),x=[];u.existsSync(R())&&u.existsSync(a)&&x.push(N(a).href);let c;for(let s of x){let g=await P(s);if(g.translations)return i[e]=g.translations,g.translations;c=g.error}let d=await $(e);return d.translations?(i[e]=d.translations,d.translations):(c=d.error,c&&m(`Failed to load JS translations for ${e}: ${c.message}`),i[e]={},{})})();return S[e]=n,n.finally(()=>{delete S[e]}),n}function _(e,t){return t?e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n):e}function F(e){return e==="auto"?O():E(e)?"en":l(e)??e}async function G(e){y=F(e),v=await j(y)}function le(){return y}function ue(e,t){let n=v[e]??e;return Array.isArray(n)?e:_(n,t)}function ce(e){let t=v[e];return Array.isArray(t)?t:[]}async function de(e){await G(e??"auto")}export{B as a,m as b,W as c,p as d,E as e,l as f,C as g,q as h,O as i,G as j,le as k,ue as l,ce as m,de as n};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Matilda Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{g as o,i as a,p as u,q as n}from"./chunk-T4P4KEDW.js";import{b as s}from"./chunk-GZPNIYVZ.js";s();var i=`Submit your final answer as structured JSON that conforms to the provided schema.
3
+ import{g as o,i as a,p as u,q as n}from"./chunk-6E766NPX.js";import{b as s}from"./chunk-GZPNIYVZ.js";s();var i=`Submit your final answer as structured JSON that conforms to the provided schema.
4
4
 
5
5
  CRITICAL: In structured-output mode, this is the ONLY way to deliver the final result. Call this tool to deliver the final result; the first call with valid arguments ends the session. Do not emit the final answer as plain text \u2014 it will be discarded. Use other tools (Read, Grep, etc.) to gather the information you need before calling this tool.
6
6