@maincode-ai/matilda-code 0.22.1 → 0.22.2-nightly.20261107.317646b99

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 (122) hide show
  1. package/README.md +1 -1
  2. package/chunks/agent-CUHHPELW.js +3 -0
  3. package/chunks/agent-headless-P2DULOWS.js +3 -0
  4. package/chunks/{askUserQuestion-A46IDHKS.js → askUserQuestion-DHYKAZWH.js} +1 -1
  5. package/chunks/ca-3NRDXS7D.js +23 -0
  6. package/chunks/chunk-355M6IU5.js +80 -0
  7. package/chunks/chunk-3TTI3ZQT.js +56 -0
  8. package/chunks/{chunk-CI5CVVGI.js → chunk-42UM7T4B.js} +53 -53
  9. package/chunks/{chunk-6RK6IJY5.js → chunk-46FFWNRO.js} +1 -1
  10. package/chunks/chunk-55YW6EUC.js +8 -0
  11. package/chunks/chunk-BQDEPKIG.js +46 -0
  12. package/chunks/{chunk-LONWTJOE.js → chunk-BS7Q7KA6.js} +8 -8
  13. package/chunks/chunk-DZKI2CAC.js +3 -0
  14. package/chunks/{chunk-TDFF4ZGY.js → chunk-E2KMVG7F.js} +1 -1
  15. package/chunks/chunk-ECXO253T.js +2580 -0
  16. package/chunks/chunk-FPGKJJJY.js +13 -0
  17. package/chunks/chunk-FY3LL4OC.js +8 -0
  18. package/chunks/chunk-HJK3NKAR.js +8 -0
  19. package/chunks/{chunk-ZABAV4XA.js → chunk-HRD7WD3P.js} +3 -3
  20. package/chunks/{chunk-GCMUSGTT.js → chunk-L2FKLLEC.js} +1 -1
  21. package/chunks/chunk-MZ73LBEY.js +9 -0
  22. package/chunks/chunk-N2BE647T.js +10 -0
  23. package/chunks/chunk-O2WOUWDJ.js +121 -0
  24. package/chunks/{chunk-UICLGQTV.js → chunk-OWEBLTAN.js} +1 -1
  25. package/chunks/{chunk-KYNP66YS.js → chunk-P24OL22U.js} +8 -8
  26. package/chunks/chunk-PFXCFIHY.js +8 -0
  27. package/chunks/{chunk-FI2FSW7J.js → chunk-VWM3GUBH.js} +1 -1
  28. package/chunks/chunk-WL27X35X.js +44 -0
  29. package/chunks/chunk-ZUQRP3N6.js +9 -0
  30. package/chunks/{computer-use-V2DT2IKO.js → computer-use-DIGHVJ7N.js} +7 -7
  31. package/chunks/{cron-create-JINCFLKY.js → cron-create-5RRFCP36.js} +1 -1
  32. package/chunks/{cron-delete-RF6JLUAV.js → cron-delete-7DTRWCSV.js} +1 -1
  33. package/chunks/{cron-list-VXLBAXZ3.js → cron-list-HY6XJD7D.js} +1 -1
  34. package/chunks/de-MINTIKBC.js +23 -0
  35. package/chunks/{edit-ZB4SONLT.js → edit-IVOZQDG7.js} +17 -17
  36. package/chunks/en-V4AM2EKE.js +23 -0
  37. package/chunks/{enter-worktree-CAFTW46C.js → enter-worktree-LQKNE24C.js} +1 -1
  38. package/chunks/{enterPlanMode-XSNXJJMC.js → enterPlanMode-AMKRMA4Q.js} +1 -1
  39. package/chunks/{exit-worktree-U37YLKJC.js → exit-worktree-353X52E6.js} +1 -1
  40. package/chunks/{exitPlanMode-XKAZCVAV.js → exitPlanMode-FA7FBOPZ.js} +1 -1
  41. package/chunks/fr-XRDTBTRU.js +23 -0
  42. package/chunks/{glob-LPIFPVGX.js → glob-OLQLERJP.js} +1 -1
  43. package/chunks/{goal-tools-VAH424PW.js → goal-tools-POD6LCKM.js} +1 -1
  44. package/chunks/grep-WCOSLJAC.js +22 -0
  45. package/chunks/ja-OYFHC7MP.js +23 -0
  46. package/chunks/{keychain-token-storage-UTWIIKCK.js → keychain-token-storage-BCODB632.js} +1 -1
  47. package/chunks/ls-JORGCXES.js +15 -0
  48. package/chunks/{lsp-H4EXPHFD.js → lsp-Y46R5DO5.js} +1 -1
  49. package/chunks/mcp-client-UUQFLTQ2.js +3 -0
  50. package/chunks/monitor-S7LII2PV.js +32 -0
  51. package/chunks/notebook-edit-R35SRELR.js +17 -0
  52. package/chunks/openaiContentGenerator-7UTX34FH.js +52 -0
  53. package/chunks/pt-6DJAKXHE.js +23 -0
  54. package/chunks/read-file-UNA4JSSL.js +3 -0
  55. package/chunks/ripGrep-LSOMEB27.js +3 -0
  56. package/chunks/ru-4UMYCMY6.js +23 -0
  57. package/chunks/scheduler-BCZEO32E.js +8 -0
  58. package/chunks/{send-message-5XHDGHSN.js → send-message-VY4DP63A.js} +1 -1
  59. package/chunks/shell-BXOPTHWD.js +3 -0
  60. package/chunks/{skill-FCVSGCSN.js → skill-3RC6M3O5.js} +4 -4
  61. package/chunks/symbol-search-YNGX4Z5T.js +19 -0
  62. package/chunks/{syntheticOutput-OIPRFBVD.js → syntheticOutput-4JANVS4D.js} +1 -1
  63. package/chunks/{task-create-QP44DKH4.js → task-create-NRBVXURQ.js} +1 -1
  64. package/chunks/{task-detach-AUTU6C4G.js → task-detach-VHDDAO2K.js} +1 -1
  65. package/chunks/{task-list-U2WAGMM7.js → task-list-T2IET466.js} +1 -1
  66. package/chunks/{task-stop-GN5WZ3IA.js → task-stop-OEAEE5R7.js} +1 -1
  67. package/chunks/{task-update-26N2AUQT.js → task-update-4ANRU74G.js} +1 -1
  68. package/chunks/{team-create-TN2KN27J.js → team-create-RUBIKSDJ.js} +1 -1
  69. package/chunks/team-delete-M4ORNSTT.js +8 -0
  70. package/chunks/{todoWrite-JN3ZV5O2.js → todoWrite-RN2OP46T.js} +1 -1
  71. package/chunks/{tool-search-VPMEQKAS.js → tool-search-O2ZT6LK7.js} +1 -1
  72. package/chunks/{web-fetch-CVAOVOZM.js → web-fetch-VA2BZ4VR.js} +1 -1
  73. package/chunks/{web-search-77CUPTFY.js → web-search-TZUX7I6D.js} +3 -5
  74. package/chunks/{workflow-JNZRGHJ4.js → workflow-7YOFJC77.js} +2 -2
  75. package/chunks/write-file-NK4IW2I5.js +15 -0
  76. package/cli.js +473 -451
  77. package/locales/ca.js +6 -3
  78. package/locales/de.js +6 -3
  79. package/locales/en.js +35 -3
  80. package/locales/fr.js +6 -3
  81. package/locales/ja.js +6 -3
  82. package/locales/pt.js +6 -3
  83. package/locales/ru.js +6 -3
  84. package/npm-postinstall.js +1 -1
  85. package/package.json +2 -2
  86. package/chunks/agent-JDATO222.js +0 -3
  87. package/chunks/agent-headless-ZOFNY4CF.js +0 -3
  88. package/chunks/ca-JKEHLTNL.js +0 -23
  89. package/chunks/chunk-2LVAK6TV.js +0 -80
  90. package/chunks/chunk-5JCW6FH6.js +0 -8
  91. package/chunks/chunk-7AEOFDY3.js +0 -8
  92. package/chunks/chunk-AEYNMLMW.js +0 -36
  93. package/chunks/chunk-DEN6RR3B.js +0 -3
  94. package/chunks/chunk-DUB7JMQV.js +0 -13
  95. package/chunks/chunk-HRCRNKY2.js +0 -8
  96. package/chunks/chunk-IV6PS6DB.js +0 -8
  97. package/chunks/chunk-QNXNECWR.js +0 -2602
  98. package/chunks/chunk-RH3AEZWO.js +0 -9
  99. package/chunks/chunk-SMTY6M3W.js +0 -10
  100. package/chunks/chunk-TKEFJ3O3.js +0 -9
  101. package/chunks/chunk-V2V3OF76.js +0 -56
  102. package/chunks/chunk-Y3SZK63U.js +0 -120
  103. package/chunks/chunk-ZSGBDQXU.js +0 -11
  104. package/chunks/de-GMGNR5CZ.js +0 -23
  105. package/chunks/en-3NQMLVKW.js +0 -23
  106. package/chunks/fr-WS3EBB36.js +0 -23
  107. package/chunks/grep-IF4GTD5A.js +0 -22
  108. package/chunks/ja-GBCDQ43R.js +0 -23
  109. package/chunks/ls-3EEHZY4W.js +0 -15
  110. package/chunks/mcp-client-EUPXG3VF.js +0 -3
  111. package/chunks/monitor-KBWRPPZ5.js +0 -32
  112. package/chunks/notebook-edit-K3KNR6DI.js +0 -17
  113. package/chunks/openaiContentGenerator-2NF5JGUC.js +0 -47
  114. package/chunks/pt-VID6J2CM.js +0 -23
  115. package/chunks/read-file-SRDZKBNS.js +0 -3
  116. package/chunks/ripGrep-675JNT4W.js +0 -3
  117. package/chunks/ru-EB6V6EAN.js +0 -23
  118. package/chunks/scheduler-O36AJTWS.js +0 -8
  119. package/chunks/shell-A7NRVDCY.js +0 -3
  120. package/chunks/symbol-search-ZM3HFCUV.js +0 -19
  121. package/chunks/team-delete-XCKD5FBZ.js +0 -8
  122. package/chunks/write-file-FJCU2PYT.js +0 -15
@@ -0,0 +1,8 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as u,ea as M}from"./chunk-WL27X35X.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{B as a,X as b,D as c,V as d};
4
+ /**
5
+ * @license
6
+ * Copyright 2025 Matilda Team
7
+ * SPDX-License-Identifier: Apache-2.0
8
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{d as f}from"./chunk-HRCRNKY2.js";import{d as u}from"./chunk-QXSBPCBA.js";import{f as m,g as c,m as l,n as p}from"./chunk-KYNP66YS.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{d as f}from"./chunk-FY3LL4OC.js";import{d as u}from"./chunk-QXSBPCBA.js";import{f as m,g as c,m as l,n as p}from"./chunk-P24OL22U.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,44 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{e as jn,k as zr,m as Ro}from"./chunk-HEJO7OBH.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();i();i();i();function w(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t}function l(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}i();var Jr=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return Jr=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};i();i();i();function Ut(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Wt=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var y=class extends Error{},F=class r extends y{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new me({message:n,cause:Wt(t)});let o=t?.error;return e===400?new tt(e,o,n,s):e===401?new rt(e,o,n,s):e===403?new nt(e,o,n,s):e===404?new st(e,o,n,s):e===409?new ot(e,o,n,s):e===422?new it(e,o,n,s):e===429?new at(e,o,n,s):e>=500?new ct(e,o,n,s):new r(e,o,n,s)}},v=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},me=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends me{constructor({message:e}={}){super({message:e??"Request timed out."})}},tt=class extends F{},rt=class extends F{},nt=class extends F{},st=class extends F{},ot=class extends F{},it=class extends F{},at=class extends F{},ct=class extends F{},lt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},ut=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},te=class extends Error{constructor(e){super(e)}};var vo=/^[a-z][a-z0-9+.-]*:/i,Bn=r=>vo.test(r),q=r=>(q=Array.isArray,q(r)),Vr=q;function Un(r){return typeof r!="object"?{}:r??{}}function Wn(r){if(!r)return!0;for(let e in r)return!1;return!0}function Hn(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Ht(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var qn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${r} must be an integer`);if(e<0)throw new y(`${r} must be a positive integer`);return e};var Gn=r=>{try{return JSON.parse(r)}catch{return}};i();var re=r=>new Promise(e=>setTimeout(e,r));i();i();var _e="5.11.0";var Xn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Oo(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var To=()=>{let r=Oo();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":Jn(Deno.build.os),"X-Stainless-Arch":zn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":Jn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ko();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ko(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:e,version:`${s}.${o}.${a}`}}}return null}var zn=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Jn=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Vn,Kn=()=>Vn??(Vn=To());i();function Yn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Xr(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function fr(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Xr({start(){},async pull(t){let{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Kr(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Qn(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}i();var Zn=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});i();i();var dr="RFC3986",Yr=r=>String(r),pr={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:Yr},Qr="RFC1738";i();i();var hr=(r,e)=>(hr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),hr(r,e)),ne=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var Zr=1024,es=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let a="";for(let c=0;c<o.length;c+=Zr){let u=o.length>=Zr?o.slice(c,c+Zr):o,h=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===Qr&&(p===40||p===41)){h[h.length]=u.charAt(g);continue}if(p<128){h[h.length]=ne[p];continue}if(p<2048){h[h.length]=ne[192|p>>6]+ne[128|p&63];continue}if(p<55296||p>=57344){h[h.length]=ne[224|p>>12]+ne[128|p>>6&63]+ne[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),h[h.length]=ne[240|p>>18]+ne[128|p>>12&63]+ne[128|p>>6&63]+ne[128|p&63]}a+=h.join("")}return a};function ts(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function en(r,e){if(q(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var ns={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},ss=function(r,e){Array.prototype.push.apply(r,q(e)?e:[e])},rs,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:es,encodeValuesOnly:!1,format:dr,formatter:Yr,indices:!1,serializeDate(r){return(rs??(rs=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function No(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var tn={};function os(r,e,t,n,s,o,a,c,u,h,g,p,b,f,P,A,k,R){let x=r,j=R,C=0,J=!1;for(;(j=j.get(tn))!==void 0&&!J;){let $=j.get(r);if(C+=1,typeof $<"u"){if($===C)throw new RangeError("Cyclic object value");J=!0}typeof j.get(tn)>"u"&&(C=0)}if(typeof h=="function"?x=h(e,x):x instanceof Date?x=b?.(x):t==="comma"&&q(x)&&(x=en(x,function($){return $ instanceof Date?b?.($):$})),x===null){if(o)return u&&!A?u(e,M.encoder,k,"key",f):e;x=""}if(No(x)||ts(x)){if(u){let $=A?e:u(e,M.encoder,k,"key",f);return[P?.($)+"="+P?.(u(x,M.encoder,k,"value",f))]}return[P?.(e)+"="+P?.(String(x))]}let G=[];if(typeof x>"u")return G;let O;if(t==="comma"&&q(x))A&&u&&(x=en(x,u)),O=[{value:x.length>0?x.join(",")||null:void 0}];else if(q(h))O=h;else{let $=Object.keys(x);O=g?$.sort(g):$}let B=c?String(e).replace(/\./g,"%2E"):String(e),U=n&&q(x)&&x.length===1?B+"[]":B;if(s&&q(x)&&x.length===0)return U+"[]";for(let $=0;$<O.length;++$){let N=O[$],Mn=typeof N=="object"&&typeof N.value<"u"?N.value:x[N];if(a&&Mn===null)continue;let Gr=p&&c?N.replace(/\./g,"%2E"):N,Eo=q(x)?typeof t=="function"?t(U,Gr):U:U+(p?"."+Gr:"["+Gr+"]");R.set(r,C);let Ln=new WeakMap;Ln.set(tn,R),ss(G,os(Mn,Eo,t,n,s,o,a,c,t==="comma"&&A&&q(x)?null:u,h,g,p,b,f,P,A,k,Ln))}return G}function Fo(r=M){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||M.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=dr;if(typeof r.format<"u"){if(!hr(pr,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=pr[t],s=M.filter;(typeof r.filter=="function"||q(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in ns?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=M.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:M.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:M.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?M.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:M.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:M.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:M.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:M.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:M.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:M.strictNullHandling}}function rn(r,e={}){let t=r,n=Fo(e),s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):q(n.filter)&&(o=n.filter,s=o);let a=[];if(typeof t!="object"||t===null)return"";let c=ns[n.arrayFormat],u=c==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);let h=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];n.skipNulls&&t[f]===null||ss(a,os(t[f],f,c,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,h))}let g=a.join(n.delimiter),p=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}i();i();i();i();i();function cs(r){let e=0;for(let s of r)e+=s.length;let t=new Uint8Array(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return t}var is;function ft(r){let e;return(is??(e=new globalThis.TextEncoder,is=e.encode.bind(e)))(r)}var as;function nn(r){let e;return(as??(e=new globalThis.TextDecoder,as=e.decode.bind(e)))(r)}var V,X,Te=class{constructor(){V.set(this,void 0),X.set(this,void 0),w(this,V,new Uint8Array,"f"),w(this,X,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ft(e):e;w(this,V,cs([l(this,V,"f"),t]),"f");let n=[],s;for(;(s=Lo(l(this,V,"f"),l(this,X,"f")))!=null;){if(s.carriage&&l(this,X,"f")==null){w(this,X,s.index,"f");continue}if(l(this,X,"f")!=null&&(s.index!==l(this,X,"f")+1||s.carriage)){n.push(nn(l(this,V,"f").subarray(0,l(this,X,"f")-1))),w(this,V,l(this,V,"f").subarray(l(this,X,"f")),"f"),w(this,X,null,"f");continue}let o=l(this,X,"f")!==null?s.preceding-1:s.preceding,a=nn(l(this,V,"f").subarray(0,o));n.push(a),w(this,V,l(this,V,"f").subarray(s.index),"f"),w(this,X,null,"f")}return n}flush(){return l(this,V,"f").length?this.decode(`
4
+ `):[]}};V=new WeakMap,X=new WeakMap;Te.NEWLINE_CHARS=new Set([`
5
+ `,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Lo(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function ls(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}i();var gr={off:0,error:200,warn:300,info:400,debug:500},sn=(r,e,t)=>{if(r){if(Hn(gr,r))return r;T(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(gr))}`)}};function qt(){}function mr(r,e,t){return!e||gr[r]>gr[t]?qt:e[r].bind(e)}var jo={error:qt,warn:qt,info:qt,debug:qt},us=new WeakMap;function T(r){let e=r.logger,t=r.logLevel??"off";if(!e)return jo;let n=us.get(e);if(n&&n[0]===t)return n[1];let s={error:mr("error",e,t),warn:mr("warn",e,t),info:mr("info",e,t),debug:mr("debug",e,t)};return us.set(e,[t,s]),s}var le=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var Gt,se=class r{constructor(e,t,n){this.iterator=e,Gt.set(this,void 0),this.controller=t,w(this,Gt,n,"f")}static fromSSEResponse(e,t,n){let s=!1,o=n?T(n):console;async function*a(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of Bo(e,t))if(!c){if(u.data.startsWith("[DONE]")){c=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let h;try{h=JSON.parse(u.data)}catch(g){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),g}if(h&&h.error)throw new F(void 0,h.error,void 0,e.headers);yield h}else{let h;try{h=JSON.parse(u.data)}catch(g){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),g}if(u.event=="error")throw new F(void 0,h.error,h.message,void 0);yield{event:u.event,data:h}}}c=!0}catch(u){if(Ut(u))return;throw u}finally{c||t.abort()}}return new r(a,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*o(){let c=new Te,u=Kr(e);for await(let h of u)for(let g of c.decode(h))yield g;for(let h of c.flush())yield h}async function*a(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of o())c||u&&(yield JSON.parse(u));c=!0}catch(u){if(Ut(u))return;throw u}finally{c||t.abort()}}return new r(a,t,n)}[(Gt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let a=n.next();e.push(a),t.push(a)}return o.shift()}});return[new r(()=>s(e),this.controller,l(this,Gt,"f")),new r(()=>s(t),this.controller,l(this,Gt,"f"))]}toReadableStream(){let e=this,t;return Xr({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await t.next();if(o)return n.close();let a=ft(JSON.stringify(s)+`
6
+ `);n.enqueue(a)}catch(s){n.error(s)}},async cancel(){await t.return?.()}})}};async function*Bo(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");let t=new on,n=new Te,s=Kr(r.body);for await(let o of Uo(s))for(let a of n.decode(o)){let c=t.decode(a);c&&(yield c)}for(let o of n.flush()){let a=t.decode(o);a&&(yield a)}}async function*Uo(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ft(t):t,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=ls(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var on=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
7
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=Wo(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function Wo(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function _r(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,a=await(async()=>{if(e.options.stream)return T(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r):se.fromSSEResponse(t,e.controller,r);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let p=await t.json();return an(p,t)}return await t.text()})();return T(r).debug(`[${n}] response parsed`,le({retryOfRequestLogID:s,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function an(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}i();var zt,ke=class r extends Promise{constructor(e,t,n=_r){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,zt.set(this,void 0),w(this,zt,e,"f")}_thenUnwrap(e){return new r(l(this,zt,"f"),this.responsePromise,async(t,n)=>an(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(l(this,zt,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};zt=new WeakMap;var br,yr=class{constructor(e,t,n,s){br.set(this,void 0),w(this,br,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await l(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Jt=class extends ke{constructor(e,t,n){super(e,t,async(s,o)=>new n(s,o.response,await _r(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},oe=class extends yr{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},E=class extends yr{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Un(this.options.query),after:t}}:null}};i();i();i();var ln=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function dt(r,e,t){return ln(),new File(r,e??"unknown_file",t)}function Vt(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var un=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function";var K=async(r,e)=>({...r,body:await Go(r.body,e)}),fs=new WeakMap;function qo(r){let e=typeof r=="function"?r:r.fetch,t=fs.get(e);if(t)return t;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return fs.set(e,n),n}var Go=async(r,e)=>{if(!await qo(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([n,s])=>cn(t,n,s))),t},zo=r=>r instanceof Blob&&"name"in r;var cn=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,dt([await t.blob()],Vt(t)));else if(un(t))r.append(e,dt([await new Response(fr(t)).blob()],Vt(t)));else if(zo(t))r.append(e,t,Vt(t));else if(Array.isArray(t))await Promise.all(t.map(n=>cn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>cn(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var ds=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Jo=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&ds(r),Vo=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function wr(r,e,t){if(ln(),r=await r,Jo(r))return r instanceof File?r:dt([await r.arrayBuffer()],r.name);if(Vo(r)){let s=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),dt(await fn(s),e,t)}let n=await fn(r);if(e||(e=Vt(r)),!t?.type){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return dt(n,e,t)}async function fn(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(ds(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(un(r))for await(let t of r)e.push(...await fn(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Xo(r)}`)}return e}function Xo(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}i();i();i();i();var m=class{constructor(e){this._client=e}};i();i();i();function hs(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ps=Object.freeze(Object.create(null)),Yo=(r=hs)=>function(t,...n){if(t.length===1)return t[0];let s=!1,o=[],a=t.reduce((g,p,b)=>{/[?#]/.test(p)&&(s=!0);let f=n[b],P=(s?encodeURIComponent:r)(""+f);return b!==n.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??ps)??ps)?.toString)&&(P=f+"",o.push({start:g.length+p.length,length:P.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+p+(b===n.length?"":P)},""),c=a.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,h;for(;(h=u.exec(c))!==null;)o.push({start:h.index,length:h[0].length,error:`Value "${h[0]}" can't be safely passed as a path parameter`});if(o.sort((g,p)=>g.start-p.start),o.length>0){let g=0,p=o.reduce((b,f)=>{let P=" ".repeat(f.start-g),A="^".repeat(f.length);return g=f.start+f.length,b+P+A},"");throw new y(`Path parameters result in path with invalid segments:
8
+ ${o.map(b=>b.error).join(`
9
+ `)}
10
+ ${a}
11
+ ${p}`)}return a},d=Yo(hs);var $e=class extends m{list(e,t={},n){return this._client.getAPIList(d`/chat/completions/${e}/messages`,E,{query:t,...n})}};i();i();i();i();function ms(r){return typeof r.parse=="function"}i();var pt=r=>r?.role==="assistant",dn=r=>r?.role==="tool";i();var pn,xr,Ar,Xt,Kt,Ir,Yt,ue,Qt,Pr,Sr,ht,gs,be=class{constructor(){pn.add(this),this.controller=new AbortController,xr.set(this,void 0),Ar.set(this,()=>{}),Xt.set(this,()=>{}),Kt.set(this,void 0),Ir.set(this,()=>{}),Yt.set(this,()=>{}),ue.set(this,{}),Qt.set(this,!1),Pr.set(this,!1),Sr.set(this,!1),ht.set(this,!1),w(this,xr,new Promise((e,t)=>{w(this,Ar,e,"f"),w(this,Xt,t,"f")}),"f"),w(this,Kt,new Promise((e,t)=>{w(this,Ir,e,"f"),w(this,Yt,t,"f")}),"f"),l(this,xr,"f").catch(()=>{}),l(this,Kt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},l(this,pn,"m",gs).bind(this))},0)}_connected(){this.ended||(l(this,Ar,"f").call(this),this._emit("connect"))}get ended(){return l(this,Qt,"f")}get errored(){return l(this,Pr,"f")}get aborted(){return l(this,Sr,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,ue,"f")[e]||(l(this,ue,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=l(this,ue,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(l(this,ue,"f")[e]||(l(this,ue,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,ht,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){w(this,ht,!0,"f"),await l(this,Kt,"f")}_emit(e,...t){if(l(this,Qt,"f"))return;e==="end"&&(w(this,Qt,!0,"f"),l(this,Ir,"f").call(this));let n=l(this,ue,"f")[e];if(n&&(l(this,ue,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!l(this,ht,"f")&&!n?.length&&Promise.reject(s),l(this,Xt,"f").call(this,s),l(this,Yt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!l(this,ht,"f")&&!n?.length&&Promise.reject(s),l(this,Xt,"f").call(this,s),l(this,Yt,"f").call(this,s),this._emit("end")}}_emitFinal(){}};xr=new WeakMap,Ar=new WeakMap,Xt=new WeakMap,Kt=new WeakMap,Ir=new WeakMap,Yt=new WeakMap,ue=new WeakMap,Qt=new WeakMap,Pr=new WeakMap,Sr=new WeakMap,ht=new WeakMap,pn=new WeakSet,gs=function(e){if(w(this,Pr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new v),e instanceof v)return w(this,Sr,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};i();function Zt(r){return r?.$brand==="auto-parseable-response-format"}function De(r){return r?.$brand==="auto-parseable-tool"}function _s(r,e){return!e||!hn(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:er(r,e)}function er(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new lt;if(n.finish_reason==="content_filter")throw new ut;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>ti(e,s))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ei(e,n.message.content):null}}});return{...r,choices:t}}function ei(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function ti(r,e){let t=r.tools?.find(n=>n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:De(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function bs(r,e){if(!r)return!1;let t=r.tools?.find(n=>n.function?.name===e.function.name);return De(t)||t?.function.strict||!1}function hn(r){return Zt(r.response_format)?!0:r.tools?.some(e=>De(e)||e.type==="function"&&e.function.strict===!0)??!1}function ys(r){for(let e of r??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var z,mn,Er,gn,_n,bn,ws,xs,ri=10,mt=class extends be{constructor(){super(...arguments),z.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),dn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(pt(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),l(this,z,"m",mn).call(this)}async finalMessage(){return await this.done(),l(this,z,"m",Er).call(this)}async finalFunctionToolCall(){return await this.done(),l(this,z,"m",gn).call(this)}async finalFunctionToolCallResult(){return await this.done(),l(this,z,"m",_n).call(this)}async totalUsage(){return await this.done(),l(this,z,"m",bn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=l(this,z,"m",Er).call(this);t&&this._emit("finalMessage",t);let n=l(this,z,"m",mn).call(this);n&&this._emit("finalContent",n);let s=l(this,z,"m",gn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=l(this,z,"m",_n).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",l(this,z,"m",bn).call(this))}async _createChatCompletion(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,z,"m",ws).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(er(o,t))}async _runChatCompletion(e,t,n){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){let s="tool",{tool_choice:o="auto",stream:a,...c}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:h=ri}=n||{},g=t.tools.map(f=>{if(De(f)){if(!f.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),p={};for(let f of g)f.type==="function"&&(p[f.function.name||f.function.function.name]=f.function);let b="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<h;++f){let A=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:b,messages:[...this.messages]},n)).choices[0]?.message;if(!A)throw new y("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let k of A.tool_calls){if(k.type!=="function")continue;let R=k.id,{name:x,arguments:j}=k.function,C=p[x];if(C){if(u&&u!==x){let B=`Invalid tool_call: ${JSON.stringify(x)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:R,content:B});continue}}else{let B=`Invalid tool_call: ${JSON.stringify(x)}. Available options are: ${Object.keys(p).map(U=>JSON.stringify(U)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:R,content:B});continue}let J;try{J=ms(C)?await C.parse(j):j}catch(B){let U=B instanceof Error?B.message:String(B);this._addMessage({role:s,tool_call_id:R,content:U});continue}let G=await C.function(J,this),O=l(this,z,"m",xs).call(this,G);if(this._addMessage({role:s,tool_call_id:R,content:O}),u)return}}}};z=new WeakSet,mn=function(){return l(this,z,"m",Er).call(this).content??null},Er=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(pt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},gn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(pt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},_n=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(dn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},bn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},ws=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var tr=class r extends mt{static runTools(e,t,n){let s=new r,o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),pt(e)&&e.content&&this._emit("content",e.content)}};i();i();i();i();var W={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},yn=class extends Error{},wn=class extends Error{};function ni(r,e=W.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return si(r.trim(),e)}var si=(r,e)=>{let t=r.length,n=0,s=b=>{throw new yn(`${b} at position ${n}`)},o=b=>{throw new wn(`${b} at position ${n}`)},a=()=>(p(),n>=t&&s("Unexpected end of input"),r[n]==='"'?c():r[n]==="{"?u():r[n]==="["?h():r.substring(n,n+4)==="null"||W.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||W.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||W.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||W.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||W.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||W.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):g()),c=()=>{let b=n,f=!1;for(n++;n<t&&(r[n]!=='"'||f&&r[n-1]==="\\");)f=r[n]==="\\"?!f:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(b,++n-Number(f)))}catch(P){o(String(P))}else if(W.STR&e)try{return JSON.parse(r.substring(b,n-Number(f))+'"')}catch{return JSON.parse(r.substring(b,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,p();let b={};try{for(;r[n]!=="}";){if(p(),n>=t&&W.OBJ&e)return b;let f=c();p(),n++;try{let P=a();Object.defineProperty(b,f,{value:P,writable:!0,enumerable:!0,configurable:!0})}catch(P){if(W.OBJ&e)return b;throw P}p(),r[n]===","&&n++}}catch{if(W.OBJ&e)return b;s("Expected '}' at end of object")}return n++,b},h=()=>{n++;let b=[];try{for(;r[n]!=="]";)b.push(a()),p(),r[n]===","&&n++}catch{if(W.ARR&e)return b;s("Expected ']' at end of array")}return n++,b},g=()=>{if(n===0){r==="-"&&W.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(f){if(W.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(f))}}let b=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(W.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(b,n))}catch{r.substring(b,n)==="-"&&W.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(b,r.lastIndexOf("e")))}catch(P){o(String(P))}}},p=()=>{for(;n<t&&`
12
+ \r `.includes(r[n]);)n++};return a()},xn=r=>ni(r,W.ALL^W.NUM);var L,fe,gt,ye,An,Rr,In,Pn,Sn,Cr,En,As,Ne=class r extends mt{constructor(e){super(),L.add(this),fe.set(this,void 0),gt.set(this,void 0),ye.set(this,void 0),w(this,fe,e,"f"),w(this,gt,[],"f")}get currentChatCompletionSnapshot(){return l(this,ye,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new r(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){super._createChatCompletion;let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,L,"m",An).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of o)l(this,L,"m",In).call(this,a);if(o.controller.signal?.aborted)throw new v;return this._addChatCompletion(l(this,L,"m",Cr).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,L,"m",An).call(this),this._connected();let s=se.fromReadableStream(e,this.controller),o;for await(let a of s)o&&o!==a.id&&this._addChatCompletion(l(this,L,"m",Cr).call(this)),l(this,L,"m",In).call(this,a),o=a.id;if(s.controller.signal?.aborted)throw new v;return this._addChatCompletion(l(this,L,"m",Cr).call(this))}[(fe=new WeakMap,gt=new WeakMap,ye=new WeakMap,L=new WeakSet,An=function(){this.ended||w(this,ye,void 0,"f")},Rr=function(t){let n=l(this,gt,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},l(this,gt,"f")[t.index]=n,n)},In=function(t){if(this.ended)return;let n=l(this,L,"m",As).call(this,t);this._emit("chunk",t,n);for(let s of t.choices){let o=n.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let a=l(this,L,"m",Rr).call(this,o);o.finish_reason&&(l(this,L,"m",Sn).call(this,o),a.current_tool_call_index!=null&&l(this,L,"m",Pn).call(this,o,a.current_tool_call_index));for(let c of s.delta.tool_calls??[])a.current_tool_call_index!==c.index&&(l(this,L,"m",Sn).call(this,o),a.current_tool_call_index!=null&&l(this,L,"m",Pn).call(this,o,a.current_tool_call_index)),a.current_tool_call_index=c.index;for(let c of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[c.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:c.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:c.function?.arguments??""}):(u?.type,void 0))}}},Pn=function(t,n){if(l(this,L,"m",Rr).call(this,t).done_tool_calls.has(n))return;let o=t.message.tool_calls?.[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let a=l(this,fe,"f")?.tools?.find(c=>c.type==="function"&&c.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:De(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Sn=function(t){let n=l(this,L,"m",Rr).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;let s=l(this,L,"m",En).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Cr=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,ye,"f");if(!t)throw new y("request ended without sending any chunks");return w(this,ye,void 0,"f"),w(this,gt,[],"f"),oi(t,l(this,fe,"f"))},En=function(){let t=l(this,fe,"f")?.response_format;return Zt(t)?t:null},As=function(t){var n,s,o,a;let c=l(this,ye,"f"),{choices:u,...h}=t;c?Object.assign(c,h):c=w(this,ye,{...h,choices:[]},"f");for(let{delta:g,finish_reason:p,index:b,logprobs:f=null,...P}of t.choices){let A=c.choices[b];if(A||(A=c.choices[b]={finish_reason:p,index:b,message:{},logprobs:f,...P}),f)if(!A.logprobs)A.logprobs=Object.assign({},f);else{let{content:G,refusal:O,...B}=f;Object.assign(A.logprobs,B),G&&((n=A.logprobs).content??(n.content=[]),A.logprobs.content.push(...G)),O&&((s=A.logprobs).refusal??(s.refusal=[]),A.logprobs.refusal.push(...O))}if(p&&(A.finish_reason=p,l(this,fe,"f")&&hn(l(this,fe,"f")))){if(p==="length")throw new lt;if(p==="content_filter")throw new ut}if(Object.assign(A,P),!g)continue;let{content:k,refusal:R,function_call:x,role:j,tool_calls:C,...J}=g;if(Object.assign(A.message,J),R&&(A.message.refusal=(A.message.refusal||"")+R),j&&(A.message.role=j),x&&(A.message.function_call?(x.name&&(A.message.function_call.name=x.name),x.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=x.arguments)):A.message.function_call=x),k&&(A.message.content=(A.message.content||"")+k,!A.message.refusal&&l(this,L,"m",En).call(this)&&(A.message.parsed=xn(A.message.content))),C){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:G,id:O,type:B,function:U,...$}of C){let N=(a=A.message.tool_calls)[G]??(a[G]={});Object.assign(N,$),O&&(N.id=O),B&&(N.type=B),U&&(N.function??(N.function={name:U.name??"",arguments:""})),U?.name&&(N.function.name=U.name),U?.arguments&&(N.function.arguments+=U.arguments,bs(l(this,fe,"f"),N)&&(N.function.parsed_arguments=xn(N.function.arguments)))}}}return c},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new se(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function oi(r,e){let{id:t,choices:n,created:s,model:o,system_fingerprint:a,...c}=r,u={...c,id:t,choices:n.map(({message:h,finish_reason:g,index:p,logprobs:b,...f})=>{if(!g)throw new y(`missing finish_reason for choice ${p}`);let{content:P=null,function_call:A,tool_calls:k,...R}=h,x=h.role;if(!x)throw new y(`missing role for choice ${p}`);if(A){let{arguments:j,name:C}=A;if(j==null)throw new y(`missing function_call.arguments for choice ${p}`);if(!C)throw new y(`missing function_call.name for choice ${p}`);return{...f,message:{content:P,function_call:{arguments:j,name:C},role:x,refusal:h.refusal??null},finish_reason:g,index:p,logprobs:b}}return k?{...f,index:p,finish_reason:g,logprobs:b,message:{...R,role:x,content:P,refusal:h.refusal??null,tool_calls:k.map((j,C)=>{let{function:J,type:G,id:O,...B}=j,{arguments:U,name:$,...N}=J||{};if(O==null)throw new y(`missing choices[${p}].tool_calls[${C}].id
13
+ ${vr(r)}`);if(G==null)throw new y(`missing choices[${p}].tool_calls[${C}].type
14
+ ${vr(r)}`);if($==null)throw new y(`missing choices[${p}].tool_calls[${C}].function.name
15
+ ${vr(r)}`);if(U==null)throw new y(`missing choices[${p}].tool_calls[${C}].function.arguments
16
+ ${vr(r)}`);return{...B,id:O,type:G,function:{...N,name:$,arguments:U}}})}}:{...f,message:{...R,content:P,role:x,refusal:h.refusal??null},finish_reason:g,index:p,logprobs:b}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return _s(u,e)}function vr(r){return JSON.stringify(r)}var rr=class r extends Ne{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let s=new r(t),o={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var de=class extends m{constructor(){super(...arguments),this.messages=new $e(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(d`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(d`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",E,{query:e,...t})}delete(e,t){return this._client.delete(d`/chat/completions/${e}`,t)}parse(e,t){return ys(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>er(n,e))}runTools(e,t){return e.stream?rr.runTools(this._client,e,t):tr.runTools(this._client,e,t)}stream(e,t){return Ne.createChatCompletion(this._client,e,t)}};de.Messages=$e;var we=class extends m{constructor(){super(...arguments),this.completions=new de(this._client)}};we.Completions=de;i();i();i();i();i();var Is=Symbol("brand.privateNullableHeaders");function*ai(r){if(!r)return;if(Is in r){let{values:n,nulls:s}=r;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Vr(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Vr(n[1])?n[1]:[n[1]],a=!1;for(let c of o)c!==void 0&&(e&&!a&&(a=!0,yield[s,null]),yield[s,c])}}var _=r=>{let e=new Headers,t=new Set;for(let n of r){let s=new Set;for(let[o,a]of ai(n)){let c=o.toLowerCase();s.has(c)||(e.delete(o),s.add(c)),a===null?(e.delete(o),t.add(c)):(e.append(o,a),t.delete(c))}}return{[Is]:!0,values:e,nulls:t}};var _t=class extends m{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};i();var bt=class extends m{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};i();var yt=class extends m{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}};var ie=class extends m{constructor(){super(...arguments),this.transcriptions=new bt(this._client),this.translations=new yt(this._client),this.speech=new _t(this._client)}};ie.Transcriptions=bt;ie.Translations=yt;ie.Speech=_t;i();var Fe=class extends m{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",E,{query:e,...t})}cancel(e,t){return this._client.post(d`/batches/${e}/cancel`,t)}};i();i();var wt=class extends m{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/assistants/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",E,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};i();i();var xt=class extends m{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};i();var At=class extends m{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var xe=class extends m{constructor(){super(...arguments),this.sessions=new xt(this._client),this.transcriptionSessions=new At(this._client)}};xe.Sessions=xt;xe.TranscriptionSessions=At;i();i();var It=class extends m{create(e,t,n){return this._client.post(d`/threads/${e}/messages`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/messages/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/messages/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/messages`,E,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(d`/threads/${s}/messages/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};i();i();var Pt=class extends m{retrieve(e,t,n){let{thread_id:s,run_id:o,...a}=t;return this._client.get(d`/threads/${s}/runs/${o}/steps/${e}`,{query:a,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:s,...o}=t;return this._client.getAPIList(d`/threads/${s}/runs/${e}/steps`,E,{query:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};i();i();i();var Ps=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};i();var Ae=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var H,Le,Rn,ae,Or,Z,je,St,Me,$r,Y,Tr,kr,or,nr,sr,Ss,Es,Rs,Cs,vs,Os,Ts,pe=class extends be{constructor(){super(...arguments),H.add(this),Rn.set(this,[]),ae.set(this,{}),Or.set(this,{}),Z.set(this,void 0),je.set(this,void 0),St.set(this,void 0),Me.set(this,void 0),$r.set(this,void 0),Y.set(this,void 0),Tr.set(this,void 0),kr.set(this,void 0),or.set(this,void 0)}[(Rn=new WeakMap,ae=new WeakMap,Or=new WeakMap,Z=new WeakMap,je=new WeakMap,St=new WeakMap,Me=new WeakMap,$r=new WeakMap,Y=new WeakMap,Tr=new WeakMap,kr=new WeakMap,or=new WeakMap,H=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Le;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=se.fromReadableStream(e,this.controller);for await(let o of s)l(this,H,"m",nr).call(this,o);if(s.controller.signal?.aborted)throw new v;return this._addRun(l(this,H,"m",sr).call(this))}toReadableStream(){return new se(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let o=new Le;return o._run(()=>o._runToolAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.submitToolOutputs(t,a,{...s,signal:this.controller.signal});this._connected();for await(let u of c)l(this,H,"m",nr).call(this,u);if(c.controller.signal?.aborted)throw new v;return this._addRun(l(this,H,"m",sr).call(this))}static createThreadAssistantStream(e,t,n){let s=new Le;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){let o=new Le;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return l(this,Tr,"f")}currentRun(){return l(this,kr,"f")}currentMessageSnapshot(){return l(this,Z,"f")}currentRunStepSnapshot(){return l(this,or,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,ae,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,Or,"f"))}async finalRun(){if(await this.done(),!l(this,je,"f"))throw Error("Final run was not received.");return l(this,je,"f")}async _createThreadAssistantStream(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},a=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let c of a)l(this,H,"m",nr).call(this,c);if(a.controller.signal?.aborted)throw new v;return this._addRun(l(this,H,"m",sr).call(this))}async _createAssistantStream(e,t,n,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.create(t,a,{...s,signal:this.controller.signal});this._connected();for await(let u of c)l(this,H,"m",nr).call(this,u);if(c.controller.signal?.aborted)throw new v;return this._addRun(l(this,H,"m",sr).call(this))}static accumulateDelta(e,t){for(let[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Ht(o)&&Ht(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...s);continue}for(let a of s){if(!Ht(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let c=a.index;if(c==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof c!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${c}`);let u=o[c];u==null?o.push(a):o[c]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}};Le=pe,nr=function(e){if(!this.ended)switch(w(this,Tr,e,"f"),l(this,H,"m",Rs).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":l(this,H,"m",Ts).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":l(this,H,"m",Es).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":l(this,H,"m",Ss).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},sr=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!l(this,je,"f"))throw Error("Final run has not been received");return l(this,je,"f")},Ss=function(e){let[t,n]=l(this,H,"m",vs).call(this,e,l(this,Z,"f"));w(this,Z,t,"f"),l(this,Or,"f")[t.id]=t;for(let s of n){let o=t.content[s.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,a=t.content[s.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=l(this,St,"f")){if(l(this,Me,"f"))switch(l(this,Me,"f").type){case"text":this._emit("textDone",l(this,Me,"f").text,l(this,Z,"f"));break;case"image_file":this._emit("imageFileDone",l(this,Me,"f").image_file,l(this,Z,"f"));break}w(this,St,s.index,"f")}w(this,Me,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,St,"f")!==void 0){let s=e.data.content[l(this,St,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,l(this,Z,"f"));break;case"text":this._emit("textDone",s.text,l(this,Z,"f"));break}}l(this,Z,"f")&&this._emit("messageDone",e.data),w(this,Z,void 0,"f")}},Es=function(e){let t=l(this,H,"m",Cs).call(this,e);switch(w(this,or,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==l(this,$r,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(l(this,Y,"f")&&this._emit("toolCallDone",l(this,Y,"f")),w(this,$r,o.index,"f"),w(this,Y,t.step_details.tool_calls[o.index],"f"),l(this,Y,"f")&&this._emit("toolCallCreated",l(this,Y,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,or,void 0,"f"),e.data.step_details.type=="tool_calls"&&l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),w(this,Y,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Rs=function(e){l(this,Rn,"f").push(e),this._emit("event",e)},Cs=function(e){switch(e.event){case"thread.run.step.created":return l(this,ae,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=l(this,ae,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let s=Le.accumulateDelta(t,n.delta);l(this,ae,"f")[e.data.id]=s}return l(this,ae,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":l(this,ae,"f")[e.data.id]=e.data;break}if(l(this,ae,"f")[e.data.id])return l(this,ae,"f")[e.data.id];throw new Error("No snapshot available")},vs=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=l(this,H,"m",Os).call(this,o,a)}else t.content[o.index]=o,n.push(o);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Os=function(e,t){return Le.accumulateDelta(t,e)},Ts=function(e){switch(w(this,kr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":w(this,je,e.data,"f"),l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),w(this,Y,void 0,"f"));break;case"thread.run.cancelling":break}};var Be=class extends m{constructor(){super(...arguments),this.steps=new Pt(this._client)}create(e,t,n){let{include:s,...o}=t;return this._client.post(d`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/runs/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/threads/${e}/runs`,E,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(d`/threads/${s}/runs/${e}/cancel`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let s=_([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let h=parseInt(u);isNaN(h)||(c=h)}}await re(c);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return pe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Be.Steps=Pt;var Ie=class extends m{constructor(){super(...arguments),this.runs=new Be(this._client),this.messages=new It(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/threads/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(d`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ie.Runs=Be;Ie.Messages=It;var ce=class extends m{constructor(){super(...arguments),this.realtime=new xe(this._client),this.assistants=new wt(this._client),this.threads=new Ie(this._client)}};ce.Realtime=xe;ce.Assistants=wt;ce.Threads=Ie;i();var Ue=class extends m{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};i();i();i();var Et=class extends m{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}/content`,{...n,headers:_([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var We=class extends m{constructor(){super(...arguments),this.content=new Et(this._client)}create(e,t,n){return this._client.post(d`/containers/${e}/files`,K({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(d`/containers/${e}/files`,E,{query:t,...n})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(d`/containers/${s}/files/${e}`,{...n,headers:_([{Accept:"*/*"},n?.headers])})}};We.Content=Et;var Pe=class extends m{constructor(){super(...arguments),this.files=new We(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(d`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",E,{query:e,...t})}delete(e,t){return this._client.delete(d`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Pe.Files=We;i();var He=class extends m{create(e,t){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&T(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(T(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(c=>{let u=c.embedding;c.embedding=Ps(u)}),a)))}};i();i();i();var Rt=class extends m{retrieve(e,t,n){let{eval_id:s,run_id:o}=t;return this._client.get(d`/evals/${s}/runs/${o}/output_items/${e}`,n)}list(e,t,n){let{eval_id:s,...o}=t;return this._client.getAPIList(d`/evals/${s}/runs/${e}/output_items`,E,{query:o,...n})}};var qe=class extends m{constructor(){super(...arguments),this.outputItems=new Rt(this._client)}create(e,t,n){return this._client.post(d`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(d`/evals/${s}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(d`/evals/${e}/runs`,E,{query:t,...n})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(d`/evals/${s}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(d`/evals/${s}/runs/${e}`,n)}};qe.OutputItems=Rt;var Se=class extends m{constructor(){super(...arguments),this.runs=new qe(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(d`/evals/${e}`,t)}update(e,t,n){return this._client.post(d`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",E,{query:e,...t})}delete(e,t){return this._client.delete(d`/evals/${e}`,t)}};Se.Runs=qe;i();var Ge=class extends m{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(d`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",E,{query:e,...t})}delete(e,t){return this._client.delete(d`/files/${e}`,t)}content(e,t){return this._client.get(d`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!s.has(a.status);)if(await re(t),a=await this.retrieve(e),Date.now()-o>n)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};i();i();var Ct=class extends m{};i();i();var vt=class extends m{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var ze=class extends m{constructor(){super(...arguments),this.graders=new vt(this._client)}};ze.Graders=vt;i();i();var Ot=class extends m{create(e,t,n){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,oe,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(d`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(d`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}};var Je=class extends m{constructor(){super(...arguments),this.permissions=new Ot(this._client)}};Je.Permissions=Ot;i();i();var Tt=class extends m{list(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/checkpoints`,E,{query:t,...n})}};var Ve=class extends m{constructor(){super(...arguments),this.checkpoints=new Tt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(d`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",E,{query:e,...t})}cancel(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/events`,E,{query:t,...n})}pause(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/resume`,t)}};Ve.Checkpoints=Tt;var ee=class extends m{constructor(){super(...arguments),this.methods=new Ct(this._client),this.jobs=new Ve(this._client),this.checkpoints=new Je(this._client),this.alpha=new ze(this._client)}};ee.Methods=Ct;ee.Jobs=Ve;ee.Checkpoints=Je;ee.Alpha=ze;i();i();var kt=class extends m{};var Ee=class extends m{constructor(){super(...arguments),this.graderModels=new kt(this._client)}};Ee.GraderModels=kt;i();var Xe=class extends m{createVariation(e,t){return this._client.post("/images/variations",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};i();var Ke=class extends m{retrieve(e,t){return this._client.get(d`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oe,e)}delete(e,t){return this._client.delete(d`/models/${e}`,t)}};i();var Ye=class extends m{create(e,t){return this._client.post("/moderations",{body:e,...t})}};i();i();function ks(r,e){return!e||!ki(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:Cn(r,e)}function Cn(r,e){let t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Ni(e,s)};if(s.type==="message"){let o=s.content.map(a=>a.type==="output_text"?{...a,parsed:Ti(e,a.text)}:a);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||Dr(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function Ti(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function ki(r){return!!Zt(r.text?.format)}function $i(r){return r?.$brand==="auto-parseable-tool"}function Di(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function Ni(r,e){let t=Di(r.tools??[],e.name);return{...e,...e,parsed_arguments:$i(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Dr(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}i();var $t,Nr,Re,Fr,$s,Ds,Ns,Fs,Mr=class r extends be{constructor(e){super(),$t.add(this),Nr.set(this,void 0),Re.set(this,void 0),Fr.set(this,void 0),w(this,Nr,e,"f")}static createResponse(e,t,n){let s=new r(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){let s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),l(this,$t,"m",$s).call(this);let o,a=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let c of o)l(this,$t,"m",Ds).call(this,c,a);if(o.controller.signal?.aborted)throw new v;return l(this,$t,"m",Ns).call(this)}[(Nr=new WeakMap,Re=new WeakMap,Fr=new WeakMap,$t=new WeakSet,$s=function(){this.ended||w(this,Re,void 0,"f")},Ds=function(t,n){if(this.ended)return;let s=(a,c)=>{(n==null||c.sequence_number>n)&&this._emit(a,c)},o=l(this,$t,"m",Fs).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new y(`missing output at index ${t.output_index}`);if(a.type==="message"){let c=a.content[t.content_index];if(!c)throw new y(`missing content at index ${t.content_index}`);if(c.type!=="output_text")throw new y(`expected content to be 'output_text', got ${c.type}`);s("response.output_text.delta",{...t,snapshot:c.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new y(`missing output at index ${t.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:s(t.type,t);break}},Ns=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,Re,"f");if(!t)throw new y("request ended without sending any events");w(this,Re,void 0,"f");let n=Fi(t,l(this,Nr,"f"));return w(this,Fr,n,"f"),n},Fs=function(t){let n=l(this,Re,"f");if(!n){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=w(this,Re,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{w(this,Re,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=l(this,Fr,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}};function Fi(r,e){return ks(r,e)}i();var Dt=class extends m{list(e,t={},n){return this._client.getAPIList(d`/responses/${e}/input_items`,E,{query:t,...n})}};var Ce=class extends m{constructor(){super(...arguments),this.inputItems=new Dt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Dr(n),n))}retrieve(e,t={},n){return this._client.get(d`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Dr(s),s))}delete(e,t){return this._client.delete(d`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>Cn(n,e))}stream(e,t){return Mr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d`/responses/${e}/cancel`,t)}};Ce.InputItems=Dt;i();i();var Nt=class extends m{create(e,t,n){return this._client.post(d`/uploads/${e}/parts`,K({body:t,...n},this._client))}};var ve=class extends m{constructor(){super(...arguments),this.parts=new Nt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(d`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(d`/uploads/${e}/complete`,{body:t,...n})}};ve.Parts=Nt;i();i();i();var Ms=async r=>{let e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};var Ft=class extends m{create(e,t,n){return this._client.post(d`/vector_stores/${e}/file_batches`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/file_batches/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(d`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...o}=t;return this._client.getAPIList(d`/vector_stores/${s}/file_batches/${e}/files`,E,{query:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let s=_([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=a.headers.get("openai-poll-after-ms");if(u){let h=parseInt(u);isNaN(h)||(c=h)}}await re(c);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=s?.maxConcurrency??5,a=Math.min(o,t.length),c=this._client,u=t.values(),h=[...n];async function g(b){for(let f of b){let P=await c.files.create({file:f,purpose:"assistants"},s);h.push(P.id)}}let p=Array(a).fill(u).map(g);return await Ms(p),await this.createAndPoll(e,{file_ids:h})}};i();var Mt=class extends m{create(e,t,n){return this._client.post(d`/vector_stores/${e}/files`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/files/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:s,...o}=t;return this._client.post(d`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(d`/vector_stores/${e}/files`,E,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(d`/vector_stores/${s}/files/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){let s=_([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse(),a=o.data;switch(a.status){case"in_progress":let c=5e3;if(n?.pollIntervalMs)c=n.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let h=parseInt(u);isNaN(h)||(c=h)}}await re(c);break;case"failed":case"completed":return a}}}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(d`/vector_stores/${s}/files/${e}/content`,oe,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var he=class extends m{constructor(){super(...arguments),this.files=new Mt(this._client),this.fileBatches=new Ft(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(d`/vector_stores/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",E,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(d`/vector_stores/${e}/search`,oe,{body:t,method:"post",...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};he.Files=Mt;he.FileBatches=Ft;i();var Lt,Ls,Lr,Qe=class extends m{constructor(){super(...arguments),Lt.add(this)}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");l(this,Lt,"m",Ls).call(this,n);let o=_([t]).values,a=l(this,Lt,"m",Lr).call(this,o,"webhook-signature"),c=l(this,Lt,"m",Lr).call(this,o,"webhook-timestamp"),u=l(this,Lt,"m",Lr).call(this,o,"webhook-id"),h=parseInt(c,10);if(isNaN(h))throw new te("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-h>s)throw new te("Webhook timestamp is too old");if(h>g+s)throw new te("Webhook timestamp is too new");let p=a.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),b=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),f=u?`${u}.${c}.${e}`:`${c}.${e}`,P=await crypto.subtle.importKey("raw",b,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of p)try{let k=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",P,k,new TextEncoder().encode(f)))return}catch{continue}throw new te("The given webhook signature does not match the expected signature")}};Lt=new WeakSet,Ls=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Lr=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var vn,On,jr,js,S=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:n=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(vn.add(this),jr.set(this,void 0),this.completions=new Ue(this),this.chat=new we(this),this.embeddings=new He(this),this.files=new Ge(this),this.images=new Xe(this),this.audio=new ie(this),this.moderations=new Ye(this),this.models=new Ke(this),this.fineTuning=new ee(this),this.graders=new Ee(this),this.vectorStores=new he(this),this.webhooks=new Qe(this),this.beta=new ce(this),this.batches=new Fe(this),this.uploads=new ve(this),this.responses=new Ce(this),this.evals=new Se(this),this.containers=new Pe(this),t===void 0)throw new y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let c={apiKey:t,organization:n,project:s,webhookSecret:o,...a,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&Xn())throw new y(`It looks like you're running in a browser-like environment.
17
+
18
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
19
+ If you understand the risks and have appropriate mitigations in place,
20
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
21
+
22
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
23
+
24
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
25
+ `);this.baseURL=c.baseURL,this.timeout=c.timeout??On.DEFAULT_TIMEOUT,this.logger=c.logger??console;let u="warn";this.logLevel=u,this.logLevel=sn(c.logLevel,"ClientOptions.logLevel",this)??sn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??Yn(),w(this,jr,Zn,"f"),this._options=c,this.apiKey=t,this.organization=n,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return _([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return rn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jr()}`}makeStatusError(e,t,n,s){return F.generate(e,t,n,s)}buildURL(e,t,n){let s=!l(this,vn,"m",js).call(this)&&n||this.baseURL,o=Bn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Wn(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:a,url:c,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(a,{url:c,options:s});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=n===void 0?"":`, retryOf: ${n}`,p=Date.now();if(T(this).debug(`[${h}] sending request`,le({retryOfRequestLogID:n,method:s.method,url:c,options:s,headers:a.headers})),s.signal?.aborted)throw new v;let b=new AbortController,f=await this.fetchWithTimeout(c,a,u,b).catch(Wt),P=Date.now();if(f instanceof Error){let R=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new v;let x=Ut(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return T(this).info(`[${h}] connection ${x?"timed out":"failed"} - ${R}`),T(this).debug(`[${h}] connection ${x?"timed out":"failed"} (${R})`,le({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),this.retryRequest(s,t,n??h);throw T(this).info(`[${h}] connection ${x?"timed out":"failed"} - error; no more retries left`),T(this).debug(`[${h}] connection ${x?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:n,url:c,durationMs:P-p,message:f.message})),x?new ge:new me({cause:f})}let A=[...f.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,x])=>", "+R+": "+JSON.stringify(x)).join(""),k=`[${h}${g}${A}] ${a.method} ${c} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${P-p}ms`;if(!f.ok){let R=await this.shouldRetry(f);if(t&&R){let O=`retrying, ${t} attempts remaining`;return await Qn(f.body),T(this).info(`${k} - ${O}`),T(this).debug(`[${h}] response error (${O})`,le({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),this.retryRequest(s,t,n??h,f.headers)}let x=R?"error; no more retries left":"error; not retryable";T(this).info(`${k} - ${x}`);let j=await f.text().catch(O=>Wt(O).message),C=Gn(j),J=C?void 0:j;throw T(this).debug(`[${h}] response error (${x})`,le({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,C,J,f.headers)}return T(this).info(k),T(this).debug(`[${h}] response start`,le({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:P-p})),{response:f,options:s,controller:b,requestLogID:h,retryOfRequestLogID:n,startTime:p}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new Jt(this,n,e)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:a,...c}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),n),h=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,g={signal:s.signal,...h?{duplex:"half"}:{},method:"GET",...c};a&&(g.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s){let o,a=s?.get("retry-after-ms");if(a){let u=parseFloat(a);Number.isNaN(u)||(o=u)}let c=s?.get("retry-after");if(c&&!o){let u=parseFloat(c);Number.isNaN(u)?o=Date.parse(c)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await re(o),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return a*c*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:s,path:o,query:a,defaultBaseURL:c}=n,u=this.buildURL(o,a,c);"timeout"in n&&qn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:h,body:g}=this.buildBody({options:n}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:h,retryCount:t});return{req:{method:s,headers:p,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...n.fetchOptions??{}},url:u,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=_([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Kn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:fr(e)}:l(this,jr,"f").call(this,{body:e,headers:n})}};On=S,jr=new WeakMap,vn=new WeakSet,js=function(){return this.baseURL!=="https://api.openai.com/v1"};S.OpenAI=On;S.DEFAULT_TIMEOUT=6e5;S.OpenAIError=y;S.APIError=F;S.APIConnectionError=me;S.APIConnectionTimeoutError=ge;S.APIUserAbortError=v;S.NotFoundError=st;S.ConflictError=ot;S.RateLimitError=at;S.BadRequestError=tt;S.AuthenticationError=rt;S.InternalServerError=ct;S.PermissionDeniedError=nt;S.UnprocessableEntityError=it;S.InvalidWebhookSignatureError=te;S.toFile=wr;S.Completions=Ue;S.Chat=we;S.Embeddings=He;S.Files=Ge;S.Images=Xe;S.Audio=ie;S.Moderations=Ye;S.Models=Ke;S.FineTuning=ee;S.Graders=Ee;S.VectorStores=he;S.Webhooks=Qe;S.Beta=ce;S.Batches=Fe;S.Uploads=ve;S.Responses=Ce;S.Evals=Se;S.Containers=Pe;i();function $n(r){return r instanceof Error&&"code"in r}function bg(r){return!r||typeof r!="object"?!1:!!(r instanceof v||r instanceof Error&&r.name==="AbortError"||$n(r)&&r.code==="ABORT_ERR")}function yg(r){if(r instanceof Error){let e=r.cause;return e instanceof Error&&e.message!==r.message?`${r.message} (cause: ${e.message})`:r.message}try{return String(r)}catch{return"Failed to get error details"}}function wg(r){if(typeof r!="object"||r===null)return;let e=r,t=e.status??e.statusCode??e.response?.status??e.error?.code;if(typeof t=="number"&&t>=100&&t<=599)return t;if(typeof e.message=="string"){let n=e.message.match(/HTTP_STATUS\/(\d{3})\b/);if(n){let s=Number(n[1]);if(s>=100&&s<=599)return s}}}function Wi(r){return Object.entries(S).find(([,e])=>e===r.constructor)?.[0]}function xg(r){if(typeof r!="object"||r===null)return"unknown";let e=r instanceof Error&&r.name!=="Error"?r.name:void 0,t=r.type,n=Wi(r)??e??t??(r instanceof Error?r.name:"unknown"),{code:s,cause:o}=r,a=[s,o?.code,o?.cause?.code].find(c=>typeof c=="string");return a?`${n}:${a}`:n}var Oe=class extends Error{constructor(t,n){super(t);this.exitCode=n}name="FatalError"};var Bs=class extends Oe{name="FatalInputError";constructor(e){super(e,42)}},Us=class extends Oe{name="FatalSandboxError";constructor(e){super(e,44)}},ir=class extends Oe{name="FatalConfigError";constructor(e){super(e,52)}},Ws=class extends Oe{name="FatalTurnLimitedError";constructor(e){super(e,53)}};var Hs=class extends Oe{name="FatalBudgetExceededError";constructor(e){super(e,55)}},qs=class extends Oe{name="FatalCancellationError";constructor(e){super(e,130)}},Tn=class extends Error{},Br=class extends Error{name="UnauthorizedError"},kn=class extends Error{},ar=class extends Error{constructor(t,n,s,o=403){super(s);this.code=t;this.title=n;this.status=o;this.name="MatildaAccessError"}},Gs=class extends ar{constructor(e,t){super("insufficient_quota","Usage limit reached",`You have reached your usage limit on ${e}. ${t===null?"Try again later.":`Try again ${Hi(t)}.`}`,429),this.name="MatildaUsageLimitError"}};function Hi(r){let e=Math.ceil(r/6e4);if(e<=1)return"in a minute";if(e<90)return`in about ${e} minutes`;let t=Math.round(e/60);return t<36?`in about ${t} hours`:`in about ${Math.round(t/24)} days`}var zs=class extends Error{constructor(t,n){super(t);this.code=n;this.name="MatildaServerUnreachableError"}},Js=class extends ar{constructor(){super("ACCOUNT_INACTIVE","Account access restricted","Your account is suspended or restricted from sending messages. Contact Matilda support to review your access. Signing in again will not remove this restriction."),this.name="AccountRestrictedError"}},Vs=class extends ar{constructor(){super("organization_access_unavailable","Organisation access refused","Matilda refused access to this run's organisation: you are not an active member of it, or no seat in it is assigned to you. Ask the organisation's admin."),this.name="OrganizationAccessError"}};function Ag(r){if(!r||typeof r!="object")return!1;let e=r;return Number(e.status)===403&&e.code==="organization_access_unavailable"}function qi(r,e){return r==="desktop"?"Sign in again in account settings.":e}var Xs=class extends Br{code="invalid_grant";constructor(e){super(`Your Matilda sign-in has ended. ${qi(e?.channel,"Run /login to sign in again.")}`,e),this.name="MatildaSignInEndedError"}};function Ig(r){if(!r||typeof r!="object")return!1;let e=r;if(e.status!==void 0&&Number(e.status)!==403)return!1;let t=e.error;return e.code==="ACCOUNT_INACTIVE"||e.code==="account_inactive"||t==="account_inactive"||typeof t=="object"&&t!==null&&"code"in t&&t.code==="ACCOUNT_INACTIVE"}var Ks=class extends Error{constructor(t,n,s,o){super(t);this.categories=n;this.severity=s;this.assistantMessage=o;this.name="ContentBlockedError"}};function Pg(r){if(r&&typeof r=="object"&&"response"in r){let t=Gi(r);if(t.error&&t.error.message&&t.error.code)switch(t.error.code){case 400:return new kn(t.error.message);case 401:return new Br(t.error.message);case 403:return new Tn(t.error.message);default:}}return r}function Gi(r){return typeof r.response?.data=="string"?JSON.parse(r.response?.data):r.response?.data}i();import zi from"node:fs";import Q from"node:path";import jt from"node:os";import*as Ys from"node:crypto";var lr=".matilda",cr=new Map,Ji=1024;var Qs=/[ \t()[\]{};|*?$`'"#&<>!~,]/,Tg=["file_path","path","filePath","notebook_path"],Vi=(()=>{let r=Qs.source.slice(1,-1);return new RegExp(`\\\\([${r}])`,"g")})();function kg(r){let e=jt.homedir();return r.startsWith(e)?r.replace(e,"~"):r}function $g(r,e=80){if(r.length<=e)return r;let t=Q.sep,n="...";if(e<10)return r.substring(0,e-3)+n;let o=Q.parse(r).root,c=r.substring(o.length).split(t).filter(g=>g!=="");if(c.length===0)return o.length<=e?o:o.substring(0,e-3)+n;if(c.length===1){let g=o+c[0];if(g.length<=e)return g;let p=Math.floor((e-3)/2),b=g.substring(0,p),f=g.substring(g.length-p);return`${b}${n}${f}`}let u=o+c[0],h=[];for(let g=c.length-1;g>=1;g--){let p=c[g],b=[p,...h].join(t),f=g>1,P;if(f?P=u+t+n+t+b:P=u+t+b,P.length<=e){if(h.unshift(p),g===1)return P}else break}if(h.length===0){let g=Math.floor((e-3)/2),p=r.substring(0,g),b=r.substring(r.length-g);return`${p}${n}${b}`}return u+t+n+t+h.join(t)}function Dg(r,e){let t=Q.resolve(r),n=Q.resolve(e);return to(n,t)?Q.relative(n,t)||".":t}function Ng(r){let e="";for(let t=0;t<r.length;t++){let n=r[t],s=0;for(let a=t-1;a>=0&&r[a]==="\\";a--)s++;!(s%2===1)&&Qs.test(n)?e+="\\"+n:e+=n}return e}function Fg(r){return jt.platform()==="win32"?r:r.replace(Vi,"$1")}function Zs(r){let e=jt.platform()==="win32"?r.toLowerCase():r;return Ys.createHash("sha256").update(e).digest("hex")}function eo(r){return(jt.platform()==="win32"?r.toLowerCase():r).replace(/[^a-zA-Z0-9]/g,"-")}function to(r,e){let n=jt.platform()==="win32"?Q.win32:Q,s=n.relative(r,e);return!s.startsWith(`..${n.sep}`)&&s!==".."&&!n.isAbsolute(s)}function Mg(r,e){return r.some(t=>to(t,e))}function Xi(r=process.cwd(),e){let t=jt.homedir();return e==="~"?t:e.startsWith("~/")?Q.join(t,e.slice(2)):Q.isAbsolute(e)?e:Q.resolve(r,e)}function Ki(r,e,t={}){let{allowFiles:n=!1,allowExternalPaths:s=!1}=t,a=r.getWorkspaceContext().isPathWithinWorkspace(e);if(!s&&!a)throw new Error("Path is not within workspace");if(s&&!a)return;let c=cr.get(e);if(c===void 0){try{c=zi.statSync(e).isDirectory()}catch(u){throw $n(u)&&u.code==="ENOENT"?new Error(`Path does not exist: ${e}`):u}if(cr.size>=Ji){let u=cr.keys().next().value;u!==void 0&&cr.delete(u)}cr.set(e,c)}if(!n&&!c)throw new Error(`Path is not a directory: ${e}`)}function Lg(r,e){let t=r.getTranscriptPath?.();return!!t&&Q.resolve(e)===Q.resolve(t)}function jg(r,e,t={}){let n=r.getTargetDir();if(!e)return n;let s=Xi(n,e);return Ki(r,s,t),s}i();import*as I from"node:path";import*as Ze from"node:os";import*as Ur from"node:fs";import{AsyncLocalStorage as Yi}from"node:async_hooks";var Qi=[".matilda",".agents"],ro="tmp",Zi="bin",ea="projects",ta="ide",ra="plans",na="debug",sa="crash",et=class r{targetDir;pinnedRuntimeBaseDir;static runtimeBaseDir=null;static runtimeBaseDirContext=new Yi;constructor(e,t){this.targetDir=e,this.pinnedRuntimeBaseDir=t?r.resolvePath(t):void 0}getRuntimeBaseDir(){return this.pinnedRuntimeBaseDir??r.getRuntimeBaseDir()}static resolvePath(e,t){let n=e;if(n==="~"||n.startsWith("~/")||n.startsWith("~\\")){let s=n==="~"?[]:n.slice(2).split(/[/\\]+/).filter(Boolean);n=I.join(Ze.homedir(),...s)}return I.isAbsolute(n)||(n=t?I.resolve(t,n):I.resolve(n)),n}static sanitizePlanSessionId(e){return I.basename(e.replace(/\\/g,"/")).replace(/^\.+/g,"_").replace(/[<>:"|?*\x00-\x1F]/g,"_")||"_"}static resolveRuntimeBaseDir(e,t){return e?r.resolvePath(e,t):null}static setRuntimeBaseDir(e,t){r.runtimeBaseDir=r.resolveRuntimeBaseDir(e,t)}static runWithRuntimeBaseDir(e,t,n){let s=r.resolveRuntimeBaseDir(e,t);return r.runtimeBaseDirContext.run(s,n)}static getRuntimeBaseDir(){let e=process.env.MATILDA_RUNTIME_DIR;if(e)return r.resolveRuntimeBaseDir(e)??r.getGlobalMatildaDir();let t=r.runtimeBaseDirContext.getStore();return t!==void 0?t??r.getGlobalMatildaDir():r.runtimeBaseDir?r.runtimeBaseDir:r.getGlobalMatildaDir()}static getGlobalMatildaDir(){let e=process.env.MATILDA_HOME;if(e)return r.resolvePath(e);let t=Ze.homedir();return t?I.join(t,lr):I.join(Ze.tmpdir(),".matilda")}static getMcpOAuthTokensPath(){return I.join(r.getGlobalMatildaDir(),"mcp-oauth-tokens.json")}static getGlobalSettingsPath(){return I.join(r.getGlobalMatildaDir(),"settings.json")}static getInstallationIdPath(){return I.join(r.getGlobalMatildaDir(),"installation_id")}static getUserCommandsDir(){return I.join(r.getGlobalMatildaDir(),"commands")}static getGlobalMemoryFilePath(){return I.join(r.getGlobalMatildaDir(),"memory.md")}static getGlobalTempDir(){return I.join(r.getRuntimeBaseDir(),ro)}static getGlobalDebugDir(){return I.join(r.getRuntimeBaseDir(),na)}static getDebugLogPath(e){return I.join(r.getGlobalDebugDir(),`${e}.txt`)}static getGlobalCrashDir(){return I.join(r.getRuntimeBaseDir(),sa)}static getGlobalIdeDir(){return I.join(r.getGlobalMatildaDir(),ta)}static resolvePathThroughExistingAncestor(e){let t=e;for(;;)try{let n=Ur.realpathSync(t),s=I.relative(t,e);return I.join(n,s)}catch(n){if(n.code!=="ENOENT")throw n;let s=I.dirname(t);if(s===t)return e;t=s}}static isPathWithinDirectory(e,t){let n=r.resolvePathThroughExistingAncestor(t),s=r.resolvePathThroughExistingAncestor(e),o=I.relative(n,s);return o===""||!o.startsWith("..")&&!I.isAbsolute(o)}static assertPathWithinDirectory(e,t,n){if(!r.isPathWithinDirectory(e,t))throw new ir(n)}static getPlansDir(e,t){let n=t?.trim();if(n){if(!e)throw new ir("projectRoot is required when plansDirectory is configured.");let s=I.resolve(e),o=r.resolvePath(n,s);return r.assertPathWithinDirectory(o,s,"plansDirectory must resolve within the project root."),o}return I.join(r.getGlobalMatildaDir(),ra)}static getPlanFilePath(e,t,n){return I.join(r.getPlansDir(t,n),`${r.sanitizePlanSessionId(e)}.md`)}static getGlobalBinDir(){return I.join(r.getGlobalMatildaDir(),Zi)}getMatildaDir(){return I.join(this.targetDir,lr)}getProjectDir(){let e=eo(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),ea);return I.join(t,e)}getProjectTempDir(){let e=Zs(this.getProjectRoot()),t=I.join(this.getRuntimeBaseDir(),ro);return I.join(t,e)}getToolResultsDir(){return I.join(this.getProjectTempDir(),"tool-results")}ensureProjectTempDirExists(){Ur.mkdirSync(this.getProjectTempDir(),{recursive:!0})}getProjectRoot(){return this.targetDir}getWorkspaceSettingsPath(){return I.join(this.getMatildaDir(),"settings.json")}getProjectCommandsDir(){return I.join(this.getMatildaDir(),"commands")}getRuntimeStatusPath(e){return I.join(this.getProjectDir(),"chats",`${e}.runtime.json`)}getProjectTempCheckpointsDir(){return I.join(this.getProjectTempDir(),"checkpoints")}getExtensionsDir(){return I.join(this.getMatildaDir(),"extensions")}getExtensionsConfigPath(){return I.join(this.getExtensionsDir(),"matilda-extension.json")}getUserSkillsDirs(){let e=Ze.homedir()||Ze.tmpdir();return Qi.map(t=>t===lr?I.join(r.getGlobalMatildaDir(),"skills"):I.join(e,t,"skills"))}static getUserExtensionsDir(){return I.join(r.getGlobalMatildaDir(),"extensions")}getHistoryFilePath(){return I.join(this.getProjectTempDir(),"shell_history")}};i();import{promises as Ao}from"node:fs";import Ia from"node:path";import{AsyncLocalStorage as Pa}from"node:async_hooks";import Sa from"node:util";i();i();var Bt=[];function Vg(r){typeof r!="string"||r===""||Bt.includes(r)||(Bt.push(r),Bt.sort((e,t)=>t.length-e.length))}function oa(r,e){return r===e?e.length>=8:e.length>=16&&r.includes(e)}function Xg(r){return r!==void 0&&Bt.includes(r)}function Kg(r){return r!==void 0&&Bt.some(e=>oa(r,e))}function no(r,e){let t=r;for(let n of Bt)n.length>=16&&t.includes(n)&&(t=t.split(n).join(e));return t}var D="***REDACTED***",ia=[[/-----BEGIN [A-Z ]*PRIVATE KEY-----(?:(?!-----)[\w+/=\s:,-])*-----END [A-Z ]*PRIVATE KEY-----/g,D],[/\beyJ[\w-]{8,512}\.eyJ[\w-]{8,}\.[\w-]{8,}/g,D],[/\bsk-[\w-]{20,}/g,`sk-${D}`],[/\bmc_(?:live|test)_[0-9a-zA-Z]{16,}/g,D],[/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,D],[/\b(?:gh[pousr]|github_pat)_\w{20,}/g,D],[/\b(?:glpat-|pypi-|ya29\.)[\w.-]{20,}/g,D],[/\b(?:gsk_|hf_|xai-)[0-9a-zA-Z]{30,}/g,D],[/\bnpm_[0-9a-zA-Z]{36}\b/g,D],[/\bAIza[\w-]{35}\b/g,D],[/\bxox[abeoprs]-[\w-]{10,}/g,D],[/\b[rs]k_(?:live|test)_[0-9a-zA-Z]{16,}/g,D],[/\bhooks\.slack\.com\/services\/[\w/]{20,}/g,D],[/\b(Bearer[ \t]+)(?:[\w.~+/-]{16,}|(?=[\w.~+/-]*\d)(?=[\w.~+/-]*[a-z])[\w.~+/-]+)=*/gi,`$1${D}`],[/\b(Authorization["']?[ \t]*:[ \t]*["']?Basic[ \t]+)[\w+/-]{8,}=*/gi,`$1${D}`],[/\b([a-z][a-z0-9+.-]{0,40}:\/\/)(?:[^/\s?#:@]*:(?![$<{%])[^/\s?#),\]]*|(?=[^/\s?#:@]*\d)[^/\s?#:@]{20,})@/gi,`$1${D}@`]],io="password|passwd|pwd",ao="api[_-]?key|access[_-]?key|(?:account|encryption|private|secret|signing)[_-]?key|secret|token",co=String.raw`(?![,;&][ \t]*[\w.-]+=)[^\s"'\\]`,lo=String.raw`[^\s"'\\,;&]`,so=String.raw`(?:[ \t]*=[ \t]*|:[ \t]*)`,oo=String.raw`^[ \t]*(?:export[ \t]+)?[A-Z0-9_]*`,aa=/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*$/;function Wr(r,e,t,n,s="gim"){return new RegExp(String.raw`(${r}(${e})\\*["']?${t})`+String.raw`(?:(\\*["'])|((?:${n}|\\(?!["'nrt]))+))`,s)}var ca=[Wr("",io,so,co),Wr("",ao,so,lo)],la=[Wr(oo,io.toUpperCase(),"=",co,"gm"),Wr(oo,ao.toUpperCase(),"=",lo,"gm")],ua=/^(?:\$[A-Za-z_{(]|[`<{%([…]|\.\.\.|\*\*\*)/,fa=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*[([]|^[a-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+;?$/,da=/^([ \t]*)(`{3,}(?=[^`]*$)|~{3,})/;function pa(r,e){return new RegExp(`^[ \\t]{0,${r.length+3}}${e[0]}{${e.length},}[ \\t\\r]*$`)}var ha=/^(?:[/~.]|[A-Za-z]:[\\/])/,ma=8,ga=")]}>;,.`",_a=/[\s,;&)]/,ba=512;function ya(r,e,t){if(_a.test(r.charAt(e))){let[s=""]=r.slice(e,e+ba).split(/[\r\n]/,1);if(!s.includes(t))return e}let n=e;for(;n<r.length&&!r.startsWith(t,n);){for(;r[n]==="\\";)n++;if(n===r.length||r[n]===`
26
+ `||r[n]==="\r")break;n++}return n}function wa(r){let e=r.length;for(;e>0&&ga.includes(r[e-1]);)e--;return e}function uo(r,e,t=()=>!0){return e.reduce((n,s)=>{let o="",a=0;s.lastIndex=0;for(let c=s.exec(n);c;c=s.exec(n)){let u=c[2],h=c[3],g=c.index+c[0].length,p=h===void 0?c.index+c[1].length:g,b=h===void 0?g:ya(n,p,h);s.lastIndex=b;let f=n.slice(p,b),P=/pass|pwd/i.test(u);!f||ua.test(f)||!t(f)||/pwd/i.test(u)&&ha.test(f)||!P&&f.length<ma||(o+=n.slice(a,p)+D,a=h===void 0?p+wa(f):b)}return o+n.slice(a)},r)}function fo(r){let e=no(r,D);for(let[t,n]of ia)e=e.replace(t,n);return e}function po(r){try{return uo(fo(r).replace(aa,D),ca)}catch{return D}}function e_(r){let e;return fo(r).split(`
27
+ `).map(t=>{if(e)return e.test(t)&&(e=void 0),t;let n=da.exec(t);return n?(e=pa(n[1],n[2]),t):uo(t,la,s=>!fa.test(s))}).join(`
28
+ `)}i();import{promises as Dn}from"node:fs";import ho from"node:path";async function mo(r,e,t){let{fallbackCopy:n=!0}=t??{},s=ho.dirname(r),o=ho.relative(s,e);try{await Dn.unlink(r)}catch{}try{await Dn.symlink(o,r);return}catch{}if(n)try{await Dn.copyFile(e,r)}catch{}}i();Ro();i();var go,_o;function a_(r,e){go=r,_o=e}function bo(){return go}function c_(){return _o}function yo(r){let e=r?.spanContext();return e&&jn(e)?{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}:null}function xa(){try{return yo(zr.getActiveSpan())}catch{return null}}function Aa(){try{let r=bo();return yo(r?zr.getSpan(r):void 0)}catch{return null}}function wo(){return xa()??Aa()}function h_(r){let e=(r.traceFlags&255).toString(16).padStart(2,"0");return`00-${r.traceId}-${r.spanId}-${e}`}var xo=!1;function m_(r){xo=r}function g_(){return xo}var Hr=null,Nn=null,Fn=!1,Io=null,Ea=new Pa;function Po(){let r=process.env.MATILDA_DEBUG_LOG_FILE;if(!r)return!1;let e=r.trim().toLowerCase();return!["","0","false","off","no"].includes(e)}function ur(){return Ea.getStore()??Io}function So(){let r=et.getGlobalDebugDir();return(!Hr||Nn!==r)&&(Nn=r,Hr=Ao.mkdir(r,{recursive:!0}).then(()=>{}).catch(()=>{Fn=!0,Hr=null,Nn=null})),Hr??Promise.resolve()}function Ra(r){return r.map(e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:e).map(e=>typeof e=="string"?e:Sa.inspect(e)).join(" ")}function Ca(r,e,t,n){let s=new Date().toISOString(),o=t?` [${t}]`:"",a=n?` [trace_id=${n.traceId} span_id=${n.spanId}]`:"";return`${s} [${r}]${o}${a} ${e}
29
+ `}function qr(r,e,t,n){if(!Po())return;let s=r.getSessionId(),o=et.getDebugLogPath(s),a=po(Ra(n)),c=wo(),u=Ca(e,a,t,c);So().then(()=>Ao.appendFile(o,u,"utf8")).catch(()=>{Fn=!0})}function R_(){return Fn}var va="latest";function Oa(r){if(!Po())return;let e=Ia.join(et.getGlobalDebugDir(),va),t=et.getDebugLogPath(r);So().then(()=>mo(e,t,{fallbackCopy:!1})).catch(()=>{})}function C_(r){Io=r??null,r&&Oa(r.getSessionId())}function v_(r){return{isEnabled:()=>ur()!==null,debug:(...e)=>{let t=ur();t&&qr(t,"DEBUG",r,e)},info:(...e)=>{let t=ur();t&&qr(t,"INFO",r,e)},warn:(...e)=>{let t=ur();t&&qr(t,"WARN",r,e)},error:(...e)=>{let t=ur();t&&qr(t,"ERROR",r,e)}}}export{ge as a,S as b,$n as c,bg as d,yg as e,wg as f,xg as g,Oe as h,Bs as i,Us as j,ir as k,Ws as l,Hs as m,qs as n,Br as o,ar as p,Gs as q,zs as r,Js as s,Vs as t,Ag as u,qi as v,Xs as w,Ig as x,Ks as y,Pg as z,lr as A,Tg as B,kg as C,$g as D,Dg as E,Ng as F,Fg as G,Zs as H,eo as I,to as J,Mg as K,Xi as L,Lg as M,jg as N,Qi as O,et as P,Vg as Q,oa as R,Xg as S,Kg as T,no as U,po as V,e_ as W,mo as X,a_ as Y,c_ as Z,wo as _,h_ as $,m_ as aa,g_ as ba,R_ as ca,C_ as da,v_ as ea};
30
+ /**
31
+ * @license
32
+ * Copyright 2025 Google LLC
33
+ * SPDX-License-Identifier: Apache-2.0
34
+ */
35
+ /**
36
+ * @license
37
+ * Copyright 2026 Matilda
38
+ * SPDX-License-Identifier: Apache-2.0
39
+ */
40
+ /**
41
+ * @license
42
+ * Copyright 2025 Matilda
43
+ * SPDX-License-Identifier: Apache-2.0
44
+ */
@@ -0,0 +1,9 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as p}from"./chunk-OWEBLTAN.js";import{b as h}from"./chunk-7ZODGQO6.js";import{a as M}from"./chunk-GT6MSEK4.js";import{b as d}from"./chunk-PFXCFIHY.js";import{c as f,ea as b}from"./chunk-WL27X35X.js";import{b as u}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";u();var x=null;function D(){x=null}function _(e,r,t){return x?(x.enqueueApproval({teammateName:e,teammateColor:r,details:t}),!0):!1}function P(e,r,t,o){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await t(i,s)}}}u();var C=E(h(),1);import*as a from"node:fs/promises";import*as c from"node:path";var w=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{w.debug("mailbox lock compromised:",e?.message??e)}},g=new Map;function O(e){let r=g.get(e);return r||(r=new M,g.set(e,r)),r}function I(e){let r=p(e),t=0;for(let o of g.keys())c.dirname(o)===r&&(g.delete(o),t++);return t}async function T(e,r){return O(e).runExclusive(async()=>{let t=await C.default.lock(e,N);try{return await r()}finally{await t()}})}function y(e,r){return c.join(p(e),`${r}.json`)}async function B(e,r){let t=y(e,r);try{let o=await a.readFile(t,"utf-8");return JSON.parse(o)}catch(o){if(f(o)&&o.code==="ENOENT")return[];throw o}}var L=5*60*1e3;async function A(e,r,t){let o=y(e,r);await v(o),await T(o,async()=>{let i=await k(o),s=Date.now()-L,l=i.filter(m=>{if(!m.read)return!0;let n=Date.parse(m.timestamp);return Number.isNaN(n)||n>=s});l.push(t),await d(o,l)})}async function W(e,r,t){let o=y(e,r);return await v(o),T(o,async()=>{let i=await k(o),s=n=>!n.read&&(t===void 0||n.type===t),l=i.filter(s);if(l.length===0)return[];let m=i.map(n=>s(n)?{...n,read:!0}:n);return await d(o,m),l})}async function X(e){let r=p(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function z(e,r,t){await A(e,r,{from:t.from,text:t.text,timestamp:new Date().toISOString(),read:!1,type:t.type,color:t.color,summary:t.summary})}async function v(e){await a.mkdir(c.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
4
+ `,{flag:"wx"})}catch(r){if(!f(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(f(r)&&r.code==="ENOENT")return[];let t=r instanceof Error?r.message:String(r);w.warn(`Quarantining corrupt inbox at ${e}: ${t}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(o){let i=o instanceof Error?o.message:String(o);throw w.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${t}`)}return[]}}export{D as a,_ as b,P as c,I as d,y as e,B as f,A as g,W as h,X as i,z as j};
5
+ /**
6
+ * @license
7
+ * Copyright 2025 Matilda
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{dd as V,q as H,r as K,t as x}from"./chunk-QNXNECWR.js";import"./chunk-HRCRNKY2.js";import"./chunk-ZSGBDQXU.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-DEN6RR3B.js";import"./chunk-RH3AEZWO.js";import"./chunk-UICLGQTV.js";import"./chunk-V2V3OF76.js";import"./chunk-GCMUSGTT.js";import"./chunk-SMTY6M3W.js";import"./chunk-QXSBPCBA.js";import"./chunk-ZABAV4XA.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-5JCW6FH6.js";import"./chunk-2LVAK6TV.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-Y3SZK63U.js";import"./chunk-225CZWD7.js";import"./chunk-LBQNFSZ2.js";import"./chunk-DUB7JMQV.js";import{a as S}from"./chunk-CI5CVVGI.js";import"./chunk-IV6PS6DB.js";import"./chunk-6RK6IJY5.js";import"./chunk-LONWTJOE.js";import"./chunk-TKEFJ3O3.js";import"./chunk-7AEOFDY3.js";import"./chunk-XPVKH5TC.js";import{f as G,g as X}from"./chunk-KYNP66YS.js";import"./chunk-AEYNMLMW.js";import"./chunk-UM6CLO7D.js";import"./chunk-HEJO7OBH.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as we}from"node:os";d();import{join as R}from"node:path";import{homedir as E}from"node:os";var l="0.5.2",me="https://matilda.maincode.com/assets/computer-use",he="https://github.com/trycua/cua/releases/download";function U(e=process.platform,t=process.arch,o=l){let r=o;if(e==="darwin"){let n=`cua-driver-rs-${r}-${t==="arm64"?"darwin-arm64":"darwin-x86_64"}`;return{asset:`${n}.tar.gz`,extractDir:n,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0}}if(e==="linux"){if(t!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${t}' (only x64).`);return{asset:`cua-driver-rs-${r}-linux-x86_64-binary.tar.gz`,extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(e==="win32"){let n=`cua-driver-rs-${r}-${t==="arm64"?"windows-arm64":"windows-x86_64"}`;return{asset:`${n}.zip`,extractDir:n,binaryRelPath:"cua-driver.exe",hasApp:!1}}throw new Error(`Computer Use: unsupported platform '${e}'.`)}function N(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ye(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs/v${o}/${e}`),r.push(`${he}/cua-driver-rs-v${o}/${e}`),r}function Y(e=process.env,t=l){return N("checksums.txt",e,t)}var fe="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function J(e){if(e===void 0||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!(!Number.isInteger(t)||t<0))return t}function Q(e,t=process.env){let o=J(t[fe]);return o!==void 0?o:J(e)}function ge(e=E()){return R(e,".matilda","computer-use")}function M(e=E(),t=l){return R(ge(e),`cua-driver-rs-${t}`)}function u(e=E(),t=process.platform,o=process.arch,r=l){let i=U(t,o,r);return R(M(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ye(e){return e.endsWith("/")?e.slice(0,-1):e}var f=class e{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(t){this.binary=t.binary,this.onProgress=t.onProgress??(()=>{}),this.maxImageDimension=t.maxImageDimension}setMaxImageDimension(t){this.maxImageDimension=t}static shared(){return e.singleton||(e.singleton=new e({binary:u(we())})),e.singleton}static setSharedForTest(t){e.singleton=t}isStarted(){return this.client!==void 0}async start(t){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(t).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(t){let o=t??this.onProgress;o("Starting Computer Use driver...");let r=new K({command:this.binary,args:["mcp"],env:x()}),i=new H({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await i.connect(r),this.client=i,await this.applyRuntimeConfig(i,o)}async applyRuntimeConfig(t,o){if(this.maxImageDimension!==void 0)try{await t.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let i=r instanceof Error?r.message:String(r);o(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${i}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(t,o){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:t,arguments:o})}catch(r){if(!Z(r))throw r;let i=r;for(let n=0;n<3;n++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:t,arguments:o})}catch(s){if(!Z(s))throw s;i=s,await new Promise(a=>setTimeout(a,1e3))}}throw i}}async stop(){let t=this.client;if(this.client=void 0,t)try{await t.close()}catch{}}};function Z(e){let t=e instanceof Error?e.message:String(e);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(t)}d();var j=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],g={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
3
+ import{Uc as J,b as H}from"./chunk-ECXO253T.js";import"./chunk-FY3LL4OC.js";import{ka as K,ta as x,va as V}from"./chunk-BQDEPKIG.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-DZKI2CAC.js";import"./chunk-ZUQRP3N6.js";import"./chunk-OWEBLTAN.js";import"./chunk-3TTI3ZQT.js";import"./chunk-L2FKLLEC.js";import"./chunk-N2BE647T.js";import"./chunk-QXSBPCBA.js";import"./chunk-HRD7WD3P.js";import"./chunk-V6UPUMP3.js";import"./chunk-5B2QERWR.js";import"./chunk-55YW6EUC.js";import"./chunk-355M6IU5.js";import"./chunk-7ZODGQO6.js";import"./chunk-GT6MSEK4.js";import"./chunk-O2WOUWDJ.js";import"./chunk-225CZWD7.js";import"./chunk-LBQNFSZ2.js";import"./chunk-FPGKJJJY.js";import{a as S}from"./chunk-42UM7T4B.js";import"./chunk-HJK3NKAR.js";import"./chunk-46FFWNRO.js";import"./chunk-BS7Q7KA6.js";import"./chunk-MZ73LBEY.js";import"./chunk-PFXCFIHY.js";import"./chunk-XPVKH5TC.js";import{f as G,g as X}from"./chunk-P24OL22U.js";import"./chunk-WL27X35X.js";import"./chunk-UM6CLO7D.js";import"./chunk-HEJO7OBH.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as _e}from"node:os";d();import{join as I}from"node:path";import{homedir as R}from"node:os";var l="0.5.2",he="https://matilda.maincode.com/assets/computer-use",fe="https://github.com/trycua/cua/releases/download";function U(e=process.platform,t=process.arch,o=l){let r=o;if(e==="darwin"){let n=`cua-driver-rs-${r}-${t==="arm64"?"darwin-arm64":"darwin-x86_64"}`;return{asset:`${n}.tar.gz`,extractDir:n,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0}}if(e==="linux"){if(t!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${t}' (only x64).`);return{asset:`cua-driver-rs-${r}-linux-x86_64-binary.tar.gz`,extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(e==="win32"){let n=`cua-driver-rs-${r}-${t==="arm64"?"windows-arm64":"windows-x86_64"}`;return{asset:`${n}.zip`,extractDir:n,binaryRelPath:"cua-driver.exe",hasApp:!1}}throw new Error(`Computer Use: unsupported platform '${e}'.`)}function N(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${we(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${he}/cua-driver-rs/v${o}/${e}`),r.push(`${fe}/cua-driver-rs-v${o}/${e}`),r}function Q(e=process.env,t=l){return N("checksums.txt",e,t)}var ge="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function Y(e){if(e===void 0||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!(!Number.isInteger(t)||t<0))return t}function Z(e,t=process.env){let o=Y(t[ge]);return o!==void 0?o:Y(e)}function ye(e=R()){return I(e,".matilda","computer-use")}function M(e=R(),t=l){return I(ye(e),`cua-driver-rs-${t}`)}function u(e=R(),t=process.platform,o=process.arch,r=l){let i=U(t,o,r);return I(M(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function we(e){return e.endsWith("/")?e.slice(0,-1):e}var f=class e{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(t){this.binary=t.binary,this.onProgress=t.onProgress??(()=>{}),this.maxImageDimension=t.maxImageDimension}setMaxImageDimension(t){this.maxImageDimension=t}static shared(){return e.singleton||(e.singleton=new e({binary:u(_e())})),e.singleton}static setSharedForTest(t){e.singleton=t}isStarted(){return this.client!==void 0}async start(t){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(t).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(t){let o=t??this.onProgress;o("Starting Computer Use driver...");let r=new K({command:this.binary,args:["mcp"],env:V(x())}),i=new H({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await i.connect(r),this.client=i,await this.applyRuntimeConfig(i,o)}async applyRuntimeConfig(t,o){if(this.maxImageDimension!==void 0)try{await t.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let i=r instanceof Error?r.message:String(r);o(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${i}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(t,o){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:t,arguments:o})}catch(r){if(!ee(r))throw r;let i=r;for(let n=0;n<3;n++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:t,arguments:o})}catch(s){if(!ee(s))throw s;i=s,await new Promise(a=>setTimeout(a,1e3))}}throw i}}async stop(){let t=this.client;if(this.client=void 0,t)try{await t.close()}catch{}}};function ee(e){let t=e instanceof Error?e.message:String(e);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(t)}d();var j=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],g={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
4
4
 
5
5
  Two addressing modes:
6
6
 
@@ -87,15 +87,15 @@ All parameters are optional; omit any you do not want to change.`,parameterSchem
87
87
 
88
88
  - **All other elements**: writes AXValue directly (sliders, steppers, date pickers, native text fields that expose settable AXValue).
89
89
 
90
- For free-form text entry into web inputs, prefer \`type_text_chars\` which synthesises key events \u2014 AXValue writes are ignored by WebKit.`,parameterSchema:{additionalProperties:!1,properties:{element_index:{type:"integer"},pid:{type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},value:{description:"New value. AX will coerce to the element's native type.",type:"string"},window_id:{description:"CGWindowID for the window whose get_window_state produced the element_index.",type:"integer"}},required:["pid","window_id","element_index","value"],type:"object"}},start_recording:{description:"Start trajectory recording. Every subsequent action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) writes a turn folder under `output_dir`:\n\n- `app_state.json` \u2014 post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` \u2014 post-action per-window screenshot of the target's frontmost on-screen window.\n- `action.json` \u2014 tool name, full input arguments, result summary, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` \u2014 for click-family actions only, `screenshot.png` with a red dot drawn at the click point.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (in-process SCStream + SCRecordingOutput) so video inherits Cua Driver's own Screen Recording grant \u2014 no extra TCC prompt, no ffmpeg subprocess. Requires macOS 15.0+.\n\n**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\nState persists for the life of the daemon / MCP session; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.",parameterSchema:{additionalProperties:!1,properties:{output_dir:{description:"Absolute or ~-rooted directory where turn folders and (when enabled) the video file are written.",type:"string"},record_video:{description:"Capture the main display to <output_dir>/recording.mp4. Default: false. Set to true to also capture the main display to recording.mp4 (otherwise only the per-turn screenshots + JSON are recorded). On macOS this uses native ScreenCaptureKit (no extra TCC prompt, macOS 15.0+); on Windows + Linux it requires ffmpeg on PATH.",type:"boolean"}},required:["output_dir"],type:"object"}},start_session:{description:"Declare a session \u2014 a named, color-coded identity for THIS agent run. Pass a stable `session` id; the agent cursor, per-session config, and recording all key on it, and it follows the run across any apps/windows. The cursor's color is derived from the id, so distinct runs are visually distinct. A cursor is shown only for a declared session \u2014 call this (or pass `session` on your first action) to opt in. Idempotent: re-calling with the same id just refreshes its idle-TTL. End it with `end_session` (or let the idle-TTL reclaim it). Concurrent runs/subagents each pass their own `session` to get their own cursor.",parameterSchema:{additionalProperties:!0,properties:{session:{description:'Stable session id for this run (e.g. "research-run-1").',type:"string"}},required:["session"],type:"object"}},stop_recording:{description:"Stop trajectory recording. Disables further per-turn capture and, when video was enabled, gracefully terminates the ffmpeg subprocess so the mp4's moov atom is finalized (the file is playable). Calling stop on an already-stopped session is a no-op. The response carries `last_video_path` pointing at the finalized mp4 (when video was on).\n\nA manual `stop_recording` is **unconditional** \u2014 it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one MCP client disconnecting can't stop a recording a later client started) is handled by the daemon's `session_end` lifecycle signal, not by this tool.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},type_text:{description:"Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa text fields and text views. No keystrokes are synthesized \u2014 special keys (Return / Escape / arrows) go through `press_key` / `hotkey`. For Chromium / Electron inputs that don't implement `kAXSelectedText`, the tool falls back to CGEvent character synthesis automatically.\n\nOptional `element_index` + `window_id` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_index`, the write goes to the pid's currently focused element.",parameterSchema:{additionalProperties:!1,properties:{delay_ms:{description:"Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.",maximum:200,minimum:0,type:"integer"},element_index:{description:"Element index from last get_window_state. Directs the write to a specific field. Requires window_id.",type:"integer"},pid:{description:"Target process ID.",type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},text:{description:"Text to insert at the target's cursor.",type:"string"},window_id:{description:"CGWindowID. Required when element_index is used.",type:"integer"}},required:["pid","text"],type:"object"}},zoom:{description:"Capture a cropped JPEG of a window region (x1,y1)\u2013(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.\n\nAfter a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space.",parameterSchema:{additionalProperties:!1,properties:{pid:{description:"Target pid \u2014 required for from_zoom click/type translation.",type:"integer"},window_id:{description:"CGWindowID from list_windows.",type:"integer"},x1:{description:"Left edge of region in screenshot pixels.",type:"number"},x2:{description:"Right edge of region in screenshot pixels.",type:"number"},y1:{description:"Top edge of region in screenshot pixels.",type:"number"},y2:{description:"Bottom edge of region in screenshot pixels.",type:"number"}},required:["window_id","x1","y1","x2","y2"],type:"object"}}};d();import{execFile as Le,spawnSync as $}from"node:child_process";import{promisify as qe}from"node:util";import{rmSync as ze}from"node:fs";import{homedir as W}from"node:os";import{join as Be}from"node:path";d();import{readFile as _e,writeFile as ve,mkdir as be}from"node:fs/promises";import{homedir as C}from"node:os";import{join as Se,dirname as xe}from"node:path";function ee(e=C()){return Se(e,".matilda","computer-use","installed.json")}async function Ce(e=C()){try{let t=await _e(ee(e),"utf8"),o=JSON.parse(t);return typeof o?.approvedPackageSpec!="string"||typeof o?.approvedAtIso!="string"?void 0:o}catch(t){return t?.code==="ENOENT",void 0}}async function P(e=C(),t){let o=ee(e);await be(xe(o),{recursive:!0}),await ve(o,JSON.stringify(t,null,2),"utf8")}async function k(e=C(),t){return(await Ce(e))?.approvedPackageSpec===t}d();import{createHash as Pe}from"node:crypto";import{createWriteStream as ke}from"node:fs";import{mkdir as te,rm as T,stat as Te,chmod as De,rename as Ae}from"node:fs/promises";import{join as D}from"node:path";import{tmpdir as Oe}from"node:os";import{pipeline as Ie}from"node:stream/promises";import{Readable as Re}from"node:stream";function Ee(e){let t=new Map;for(let o of e.split(`
91
- `)){let r=o.trim().match(/^([0-9a-f]{64})\s+\*?(.+)$/i);r&&t.set(r[2].trim(),r[1].toLowerCase())}return t}async function Ue(e,t=process.platform,o=process.arch,r=l){let i=u(e,t,o,r);try{if((await Te(i)).isFile())return i}catch{}}async function re(e,t,o){let r;for(let i of e)try{let n=new AbortController,s=setTimeout(()=>{n.abort(new Error(`headers timeout after 30s for ${i}`))},3e4);try{let a=await t(i,{redirect:"follow",signal:n.signal});if(a.ok&&a.body)return{url:i,res:a};await a.body?.cancel(),r=new Error(`HTTP ${a.status} for ${i}`)}finally{clearTimeout(s)}}catch(n){r=n,o?.("Source unreachable, trying fallback\u2026")}throw new Error(`Computer Use: all download sources failed. Last error: ${r instanceof Error?r.message:String(r)}`)}async function se(e){let t=e.platform??process.platform,o=e.arch??process.arch,r=e.version??l,i=e.env??process.env,n=e.fetchImpl??fetch,s=e.onProgress,a=await Ue(e.home,t,o,r);if(a)return a;let p=U(t,o,r);s?.("Downloading Computer Use driver (~20MB, one time)...");let{res:c}=await re(Y(i,r),n),A=Ee(await c.text()).get(p.asset);if(!A)throw new Error(`Computer Use: ${p.asset} missing from checksums.txt.`);let{res:le}=await re(N(p.asset,i,r),n,s);await te(oe(e.home),{recursive:!0});let w=D(oe(e.home),p.asset),L=Pe("sha256"),O=Re.fromWeb(le.body),I,q=()=>{clearTimeout(I),I=setTimeout(()=>{O.destroy(new Error("download stalled: no data for 60s"))},6e4)};O.on("data",b=>{L.update(b),q()}),q();try{await Ie(O,ke(w))}finally{clearTimeout(I)}let z=L.digest("hex");if(z!==A)throw await T(w,{force:!0}),new Error(`Computer Use: checksum mismatch for ${p.asset} (expected ${A.slice(0,12)}\u2026, got ${z.slice(0,12)}\u2026).`);let _=M(e.home,r),v=`${_}.staging`;await T(v,{recursive:!0,force:!0}),await te(v,{recursive:!0}),await $e(w,v,p.asset,e.unzipImpl),await T(w,{force:!0}),await T(_,{recursive:!0,force:!0}),await Ae(v,_);let B=u(e.home,t,o,r);if(t!=="win32"&&await De(B,493),t==="darwin"&&p.hasApp){let b=D(_,p.extractDir),ue=D(b,"CuaDriver.app");await je(b),await Me(ue)}return s?.("Computer Use driver ready."),B}var Ne="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister";async function Me(e){try{let{execFile:t}=await import("node:child_process"),{promisify:o}=await import("node:util");await o(t)(Ne,["-f",e],{timeout:15e3})}catch{}}function oe(e){return D(Oe(),"matilda-computer-use-dl",Buffer.from(e).toString("hex").slice(0,8))}async function je(e){try{let{execFile:t}=await import("node:child_process"),{promisify:o}=await import("node:util");await o(t)("xattr",["-dr","com.apple.quarantine",e],{timeout:1e4})}catch{}}async function $e(e,t,o,r){o.endsWith(".zip")?await(r??We)(e,t):await V({file:e,cwd:t})}async function We(e,t){let{execFile:o}=await import("node:child_process"),{promisify:r}=await import("node:util"),i=r(o),n=`Expand-Archive -LiteralPath ${ie(e)} -DestinationPath ${ie(t)} -Force`,s=[{cmd:"tar",args:["-xf",e,"-C",t]},{cmd:"tar",args:["--force-local","-xf",e,"-C",t]},{cmd:"powershell",args:["-NoProfile","-NonInteractive","-Command",n]}],a=[];for(let{cmd:p,args:c}of s)try{await i(p,c,{timeout:18e4});return}catch(m){a.push(`${p} ${c[0]}: ${Fe(m)}`)}throw new Error(`Computer Use: failed to unzip ${e} on Windows (${a.join("; ")}).`)}function ie(e){return`'${e.replace(/'/g,"''")}'`}function Fe(e){return e instanceof Error?e.message:String(e)}var Ge=qe(Le);function Xe(e){try{let t=JSON.parse(e);return typeof t.accessibility!="boolean"?"unknown":t.accessibility?t.screen_recording?"ok":"screenRecording":"accessibility"}catch{return"unknown"}}var He=()=>Be(W(),"Library","Caches","cua-driver","cua-driver.sock");function ne(){try{$("pkill",["-f","CuaDriver.app/Contents/MacOS/cua-driver serve"],{stdio:"ignore"})}catch{}try{ze(He(),{force:!0})}catch{}}async function Ke(){try{let{stdout:e}=await Ge(u(W()),["permissions","status","--json"],{timeout:1e4,env:x()});return Xe(e)}catch{return"unknown"}}function Ve(){ne();try{$("open",["-n","-g","-a","CuaDriver","--args","serve","--no-permissions-gate"],{stdio:"ignore"})}catch{}return{kill:ne}}function Je(e){let t=e==="accessibility"?"Privacy_Accessibility":"Privacy_ScreenCapture";try{$("open",[`x-apple.systempreferences:com.apple.preference.security?${t}`],{stdio:"ignore"})}catch{}}function Ye(){let e=W();return{homeDir:e,approvalKey:h(),platform:process.platform,promptInstallApproval:async t=>(process.stderr.write(`
90
+ For free-form text entry into web inputs, prefer \`type_text_chars\` which synthesises key events \u2014 AXValue writes are ignored by WebKit.`,parameterSchema:{additionalProperties:!1,properties:{element_index:{type:"integer"},pid:{type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},value:{description:"New value. AX will coerce to the element's native type.",type:"string"},window_id:{description:"CGWindowID for the window whose get_window_state produced the element_index.",type:"integer"}},required:["pid","window_id","element_index","value"],type:"object"}},start_recording:{description:"Start trajectory recording. Every subsequent action-tool invocation (click, right_click, scroll, type_text, press_key, hotkey, set_value) writes a turn folder under `output_dir`:\n\n- `app_state.json` \u2014 post-action AX/UIA snapshot for the target pid.\n- `screenshot.png` \u2014 post-action per-window screenshot of the target's frontmost on-screen window.\n- `action.json` \u2014 tool name, full input arguments, result summary, pid, click point (when applicable), ISO-8601 timestamp.\n- `click.png` \u2014 for click-family actions only, `screenshot.png` with a red dot drawn at the click point.\n\nTurn folders are named `turn-00001/`, `turn-00002/`, etc. Turn numbering restarts at 1 each time recording is (re-)started.\n\n**Video is off by default.** Pass `record_video: true` to also capture the main display to `<output_dir>/recording.mp4` (H.264 / 30 fps) for the lifetime of the session. The recording is torn down automatically when the MCP client disconnects.\n\n**macOS uses native ScreenCaptureKit** (in-process SCStream + SCRecordingOutput) so video inherits Cua Driver's own Screen Recording grant \u2014 no extra TCC prompt, no ffmpeg subprocess. Requires macOS 15.0+.\n\n**Windows + Linux use an ffmpeg subprocess** (`gdigrab` / `x11grab` + libx264). Requires ffmpeg on PATH (winget install Gyan.FFmpeg / apt install ffmpeg); when ffmpeg is missing or fails on startup the per-turn capture (screenshots + action.json) still runs and the session's `last_error` field carries the diagnostic.\n\nState persists for the life of the daemon / MCP session; a restart resets to disabled with no on-disk state. Call `stop_recording` to disable + finalize the mp4.",parameterSchema:{additionalProperties:!1,properties:{output_dir:{description:"Absolute or ~-rooted directory where turn folders and (when enabled) the video file are written.",type:"string"},record_video:{description:"Capture the main display to <output_dir>/recording.mp4. Default: false. Set to true to also capture the main display to recording.mp4 (otherwise only the per-turn screenshots + JSON are recorded). On macOS this uses native ScreenCaptureKit (no extra TCC prompt, macOS 15.0+); on Windows + Linux it requires ffmpeg on PATH.",type:"boolean"}},required:["output_dir"],type:"object"}},start_session:{description:"Declare a session \u2014 a named, color-coded identity for THIS agent run. Pass a stable `session` id; the agent cursor, per-session config, and recording all key on it, and it follows the run across any apps/windows. The cursor's color is derived from the id, so distinct runs are visually distinct. A cursor is shown only for a declared session \u2014 call this (or pass `session` on your first action) to opt in. Idempotent: re-calling with the same id just refreshes its idle-TTL. End it with `end_session` (or let the idle-TTL reclaim it). Concurrent runs/subagents each pass their own `session` to get their own cursor.",parameterSchema:{additionalProperties:!0,properties:{session:{description:'Stable session id for this run (e.g. "research-run-1").',type:"string"}},required:["session"],type:"object"}},stop_recording:{description:"Stop trajectory recording. Disables further per-turn capture and, when video was enabled, gracefully terminates the ffmpeg subprocess so the mp4's moov atom is finalized (the file is playable). Calling stop on an already-stopped session is a no-op. The response carries `last_video_path` pointing at the finalized mp4 (when video was on).\n\nA manual `stop_recording` is **unconditional** \u2014 it stops whatever recording is active regardless of which session started it. Ownership-scoped teardown (so one MCP client disconnecting can't stop a recording a later client started) is handled by the daemon's `session_end` lifecycle signal, not by this tool.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},type_text:{description:"Insert text into the target pid via `AXSetAttribute(kAXSelectedText)`. Works for standard Cocoa text fields and text views. No keystrokes are synthesized \u2014 special keys (Return / Escape / arrows) go through `press_key` / `hotkey`. For Chromium / Electron inputs that don't implement `kAXSelectedText`, the tool falls back to CGEvent character synthesis automatically.\n\nOptional `element_index` + `window_id` (from the last `get_window_state` snapshot) directs the write to a specific field. Without `element_index`, the write goes to the pid's currently focused element.",parameterSchema:{additionalProperties:!1,properties:{delay_ms:{description:"Milliseconds between characters in the CGEvent fallback path. Default 30. Ignored when the AX path succeeds.",maximum:200,minimum:0,type:"integer"},element_index:{description:"Element index from last get_window_state. Directs the write to a specific field. Requires window_id.",type:"integer"},pid:{description:"Target process ID.",type:"integer"},session:{description:"Optional session id: declares/uses the agent cursor and per-session state for this run. The same id works over MCP, the CLI, or the raw socket, and follows the run across apps/windows. Omit to run cursor-less.",type:"string"},text:{description:"Text to insert at the target's cursor.",type:"string"},window_id:{description:"CGWindowID. Required when element_index is used.",type:"integer"}},required:["pid","text"],type:"object"}},zoom:{description:"Capture a cropped JPEG of a window region (x1,y1)\u2013(x2,y2) in screenshot pixel coordinates, with 20% padding added on each side. The output image is at most 500 px wide.\n\nAfter a zoom, pass `from_zoom=true` to click/type_text to auto-translate coordinates back to full-window space.",parameterSchema:{additionalProperties:!1,properties:{pid:{description:"Target pid \u2014 required for from_zoom click/type translation.",type:"integer"},window_id:{description:"CGWindowID from list_windows.",type:"integer"},x1:{description:"Left edge of region in screenshot pixels.",type:"number"},x2:{description:"Right edge of region in screenshot pixels.",type:"number"},y1:{description:"Top edge of region in screenshot pixels.",type:"number"},y2:{description:"Bottom edge of region in screenshot pixels.",type:"number"}},required:["window_id","x1","y1","x2","y2"],type:"object"}}};d();import{execFile as qe,spawnSync as $}from"node:child_process";import{promisify as ze}from"node:util";import{rmSync as Be}from"node:fs";import{homedir as W}from"node:os";import{join as Ge}from"node:path";d();import{readFile as ve,writeFile as be,mkdir as Se}from"node:fs/promises";import{homedir as C}from"node:os";import{join as xe,dirname as Ce}from"node:path";function te(e=C()){return xe(e,".matilda","computer-use","installed.json")}async function Pe(e=C()){try{let t=await ve(te(e),"utf8"),o=JSON.parse(t);return typeof o?.approvedPackageSpec!="string"||typeof o?.approvedAtIso!="string"?void 0:o}catch(t){return t?.code==="ENOENT",void 0}}async function P(e=C(),t){let o=te(e);await Se(Ce(o),{recursive:!0}),await be(o,JSON.stringify(t,null,2),"utf8")}async function k(e=C(),t){return(await Pe(e))?.approvedPackageSpec===t}d();import{createHash as ke}from"node:crypto";import{createWriteStream as Te}from"node:fs";import{mkdir as re,rm as T,stat as De,chmod as Ae,rename as Oe}from"node:fs/promises";import{join as D}from"node:path";import{tmpdir as Ee}from"node:os";import{pipeline as Ie}from"node:stream/promises";import{Readable as Re}from"node:stream";function Ue(e){let t=new Map;for(let o of e.split(`
91
+ `)){let r=o.trim().match(/^([0-9a-f]{64})\s+\*?(.+)$/i);r&&t.set(r[2].trim(),r[1].toLowerCase())}return t}async function Ne(e,t=process.platform,o=process.arch,r=l){let i=u(e,t,o,r);try{if((await De(i)).isFile())return i}catch{}}async function oe(e,t,o){let r;for(let i of e)try{let n=new AbortController,s=setTimeout(()=>{n.abort(new Error(`headers timeout after 30s for ${i}`))},3e4);try{let a=await t(i,{redirect:"follow",signal:n.signal});if(a.ok&&a.body)return{url:i,res:a};await a.body?.cancel(),r=new Error(`HTTP ${a.status} for ${i}`)}finally{clearTimeout(s)}}catch(n){r=n,o?.("Source unreachable, trying fallback\u2026")}throw new Error(`Computer Use: all download sources failed. Last error: ${r instanceof Error?r.message:String(r)}`)}async function ne(e){let t=e.platform??process.platform,o=e.arch??process.arch,r=e.version??l,i=e.env??process.env,n=e.fetchImpl??fetch,s=e.onProgress,a=await Ne(e.home,t,o,r);if(a)return a;let p=U(t,o,r);s?.("Downloading Computer Use driver (~20MB, one time)...");let{res:c}=await oe(Q(i,r),n),A=Ue(await c.text()).get(p.asset);if(!A)throw new Error(`Computer Use: ${p.asset} missing from checksums.txt.`);let{res:ue}=await oe(N(p.asset,i,r),n,s);await re(ie(e.home),{recursive:!0});let w=D(ie(e.home),p.asset),L=ke("sha256"),O=Re.fromWeb(ue.body),E,q=()=>{clearTimeout(E),E=setTimeout(()=>{O.destroy(new Error("download stalled: no data for 60s"))},6e4)};O.on("data",b=>{L.update(b),q()}),q();try{await Ie(O,Te(w))}finally{clearTimeout(E)}let z=L.digest("hex");if(z!==A)throw await T(w,{force:!0}),new Error(`Computer Use: checksum mismatch for ${p.asset} (expected ${A.slice(0,12)}\u2026, got ${z.slice(0,12)}\u2026).`);let _=M(e.home,r),v=`${_}.staging`;await T(v,{recursive:!0,force:!0}),await re(v,{recursive:!0}),await We(w,v,p.asset,e.unzipImpl),await T(w,{force:!0}),await T(_,{recursive:!0,force:!0}),await Oe(v,_);let B=u(e.home,t,o,r);if(t!=="win32"&&await Ae(B,493),t==="darwin"&&p.hasApp){let b=D(_,p.extractDir),me=D(b,"CuaDriver.app");await $e(b),await je(me)}return s?.("Computer Use driver ready."),B}var Me="/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/LaunchServices.framework/Versions/A/Support/lsregister";async function je(e){try{let{execFile:t}=await import("node:child_process"),{promisify:o}=await import("node:util");await o(t)(Me,["-f",e],{timeout:15e3})}catch{}}function ie(e){return D(Ee(),"matilda-computer-use-dl",Buffer.from(e).toString("hex").slice(0,8))}async function $e(e){try{let{execFile:t}=await import("node:child_process"),{promisify:o}=await import("node:util");await o(t)("xattr",["-dr","com.apple.quarantine",e],{timeout:1e4})}catch{}}async function We(e,t,o,r){o.endsWith(".zip")?await(r??Fe)(e,t):await J({file:e,cwd:t})}async function Fe(e,t){let{execFile:o}=await import("node:child_process"),{promisify:r}=await import("node:util"),i=r(o),n=`Expand-Archive -LiteralPath ${se(e)} -DestinationPath ${se(t)} -Force`,s=[{cmd:"tar",args:["-xf",e,"-C",t]},{cmd:"tar",args:["--force-local","-xf",e,"-C",t]},{cmd:"powershell",args:["-NoProfile","-NonInteractive","-Command",n]}],a=[];for(let{cmd:p,args:c}of s)try{await i(p,c,{timeout:18e4});return}catch(m){a.push(`${p} ${c[0]}: ${Le(m)}`)}throw new Error(`Computer Use: failed to unzip ${e} on Windows (${a.join("; ")}).`)}function se(e){return`'${e.replace(/'/g,"''")}'`}function Le(e){return e instanceof Error?e.message:String(e)}var Xe=ze(qe);function He(e){try{let t=JSON.parse(e);return typeof t.accessibility!="boolean"?"unknown":t.accessibility?t.screen_recording?"ok":"screenRecording":"accessibility"}catch{return"unknown"}}var Ke=()=>Ge(W(),"Library","Caches","cua-driver","cua-driver.sock");function ae(){try{$("pkill",["-f","CuaDriver.app/Contents/MacOS/cua-driver serve"],{stdio:"ignore"})}catch{}try{Be(Ke(),{force:!0})}catch{}}async function Ve(){try{let{stdout:e}=await Xe(u(W()),["permissions","status","--json"],{timeout:1e4,env:x()});return He(e)}catch{return"unknown"}}function Je(){ae();try{$("open",["-n","-g","-a","CuaDriver","--args","serve","--no-permissions-gate"],{stdio:"ignore"})}catch{}return{kill:ae}}function Ye(e){let t=e==="accessibility"?"Privacy_Accessibility":"Privacy_ScreenCapture";try{$("open",[`x-apple.systempreferences:com.apple.preference.security?${t}`],{stdio:"ignore"})}catch{}}function Qe(){let e=W();return{homeDir:e,approvalKey:h(),platform:process.platform,promptInstallApproval:async t=>(process.stderr.write(`
92
92
  [Computer Use] First-time setup
93
93
  Driver: ${t}
94
94
  This downloads a ~20MB signed + notarized binary into ~/.matilda/computer-use/.
95
95
  Computer Use can click, type, and read your desktop apps in the background.
96
96
  On macOS you'll be guided through Accessibility and Screen Recording permissions next.
97
97
  Set MATILDA_COMPUTER_USE_AUTO_APPROVE=1 to skip this prompt.
98
- `),process.env.MATILDA_COMPUTER_USE_AUTO_APPROVE==="1"),install:t=>se({home:e,onProgress:t}),startStatusDaemon:Ve,probePermissions:Ke,openPermissionPane:Je}}async function ae(e,t,o){let r={...Ye(),...o},i=r.pollIntervalMs??5e3,n=r.pollTimeoutMs??10*6e4;if(e.isStarted())return;if(!await k(r.homeDir,r.approvalKey)){if(t.autoApproveInstall)t.updateOutput?.("Computer Use install auto-approved (approval mode).");else if(t.updateOutput?.("Computer Use needs a one-time driver download (first use)."),!await r.promptInstallApproval(r.approvalKey))throw new Error("Computer Use install declined by user. Re-invoke the tool to be prompted again.");await P(r.homeDir,{approvedPackageSpec:r.approvalKey,approvedAtIso:new Date().toISOString()})}await r.install(t.updateOutput),r.platform==="darwin"&&await Qe(r,t,i,n),await e.start(t.updateOutput)}async function Qe(e,t,o,r){let i=e.startStatusDaemon(),n=!1,s=!1;try{let a=Date.now();for(;;){if(t.signal.aborted)throw new Error("Computer Use bootstrap aborted.");if(Date.now()-a>r)throw new Error(`Computer Use permission grant timed out after ${Math.round(r/1e3)}s. Re-invoke the tool to retry.`);await Ze(o);let p=await e.probePermissions();if(p==="ok")return;if(p==="unknown"){i.kill(),i=e.startStatusDaemon();let c=Math.round((Date.now()-a)/1e3);t.updateOutput?.(`Bringing up Computer Use permissions check\u2026 (${c}s)`);continue}if(p==="accessibility"){if(!n)n=!0,e.openPermissionPane("accessibility"),t.updateOutput?.("Step 1/2 \u2014 In the System Settings window that opened (Privacy & Security \u2192 Accessibility), turn ON CuaDriver. This continues automatically.");else{let c=Math.round((Date.now()-a)/1e3);t.updateOutput?.(`Waiting for Accessibility\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}continue}if(!s)s=!0,e.openPermissionPane("screenRecording"),t.updateOutput?.("Step 2/2 \u2014 Accessibility granted. Now in System Settings (Privacy & Security \u2192 Screen & System Audio Recording), turn ON CuaDriver. macOS will ask to restart CuaDriver \u2014 allow it; that is expected. This continues automatically.");else{let c=Math.round((Date.now()-a)/1e3);t.updateOutput?.(`Waiting for Screen Recording\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}}}finally{i.kill()}}var Ze=e=>new Promise(t=>setTimeout(t,e));import{homedir as pe}from"node:os";var et="This downloads the Computer Use driver (~20MB, signed + notarized) into ~/.matilda/computer-use/ the first time. Computer Use can click, type, and read your desktop apps in the background. On macOS you'll be guided through Accessibility / Screen Recording permissions next.",de=new Set(["kill_app","launch_app","start_recording","set_config","replay_trajectory"]),tt=new Set(["execute_javascript","enable_javascript_apple_events"]);for(let e of de)if(!(e in g))throw new Error(`HIGH_RISK_TOOLS contains unknown tool: ${e}`);function rt(e,t){return de.has(e)?!0:e==="page"&&tt.has(t.action)}var F=class extends G{constructor(o,r,i){super(r);this.upstreamName=o;this.config=i}getDescription(){return S(this.params)}async getDefaultPermission(){return"ask"}async getConfirmationDetails(o){let r=[`computer_use__${this.upstreamName}`],i=await k(pe(),h()),n=async(p,c)=>{p!=="cancel"&&await P(pe(),{approvedPackageSpec:h(),approvedAtIso:new Date().toISOString()})};if(rt(this.upstreamName,this.params))return{type:"mcp",title:i?`Allow high-risk Computer Use (${this.upstreamName})`:`Allow high-risk Computer Use (${this.upstreamName}) \u2014 first use also downloads the driver`,serverName:"cua-driver",toolName:this.upstreamName,toolDisplayName:`computer_use__${this.upstreamName}`,permissionRules:r,onConfirm:n};let s=S(this.params),a=i?`Tool: computer_use__${this.upstreamName}
98
+ `),process.env.MATILDA_COMPUTER_USE_AUTO_APPROVE==="1"),install:t=>ne({home:e,onProgress:t}),startStatusDaemon:Je,probePermissions:Ve,openPermissionPane:Ye}}async function pe(e,t,o){let r={...Qe(),...o},i=r.pollIntervalMs??5e3,n=r.pollTimeoutMs??10*6e4;if(e.isStarted())return;if(!await k(r.homeDir,r.approvalKey)){if(t.autoApproveInstall)t.updateOutput?.("Computer Use install auto-approved (approval mode).");else if(t.updateOutput?.("Computer Use needs a one-time driver download (first use)."),!await r.promptInstallApproval(r.approvalKey))throw new Error("Computer Use install declined by user. Re-invoke the tool to be prompted again.");await P(r.homeDir,{approvedPackageSpec:r.approvalKey,approvedAtIso:new Date().toISOString()})}await r.install(t.updateOutput),r.platform==="darwin"&&await Ze(r,t,i,n),await e.start(t.updateOutput)}async function Ze(e,t,o,r){let i=e.startStatusDaemon(),n=!1,s=!1;try{let a=Date.now();for(;;){if(t.signal.aborted)throw new Error("Computer Use bootstrap aborted.");if(Date.now()-a>r)throw new Error(`Computer Use permission grant timed out after ${Math.round(r/1e3)}s. Re-invoke the tool to retry.`);await et(o);let p=await e.probePermissions();if(p==="ok")return;if(p==="unknown"){i.kill(),i=e.startStatusDaemon();let c=Math.round((Date.now()-a)/1e3);t.updateOutput?.(`Bringing up Computer Use permissions check\u2026 (${c}s)`);continue}if(p==="accessibility"){if(!n)n=!0,e.openPermissionPane("accessibility"),t.updateOutput?.("Step 1/2 \u2014 In the System Settings window that opened (Privacy & Security \u2192 Accessibility), turn ON CuaDriver. This continues automatically.");else{let c=Math.round((Date.now()-a)/1e3);t.updateOutput?.(`Waiting for Accessibility\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}continue}if(!s)s=!0,e.openPermissionPane("screenRecording"),t.updateOutput?.("Step 2/2 \u2014 Accessibility granted. Now in System Settings (Privacy & Security \u2192 Screen & System Audio Recording), turn ON CuaDriver. macOS will ask to restart CuaDriver \u2014 allow it; that is expected. This continues automatically.");else{let c=Math.round((Date.now()-a)/1e3);t.updateOutput?.(`Waiting for Screen Recording\u2026 (${c}s) \u2014 enable CuaDriver in System Settings.`)}}}finally{i.kill()}}var et=e=>new Promise(t=>setTimeout(t,e));import{homedir as ce}from"node:os";var tt="This downloads the Computer Use driver (~20MB, signed + notarized) into ~/.matilda/computer-use/ the first time. Computer Use can click, type, and read your desktop apps in the background. On macOS you'll be guided through Accessibility / Screen Recording permissions next.",le=new Set(["kill_app","launch_app","start_recording","set_config","replay_trajectory"]),rt=new Set(["execute_javascript","enable_javascript_apple_events"]);for(let e of le)if(!(e in g))throw new Error(`HIGH_RISK_TOOLS contains unknown tool: ${e}`);function ot(e,t){return le.has(e)?!0:e==="page"&&rt.has(t.action)}var F=class extends G{constructor(o,r,i){super(r);this.upstreamName=o;this.config=i}getDescription(){return S(this.params)}async getDefaultPermission(){return"ask"}async getConfirmationDetails(o){let r=[`computer_use__${this.upstreamName}`],i=await k(ce(),h()),n=async(p,c)=>{p!=="cancel"&&await P(ce(),{approvedPackageSpec:h(),approvedAtIso:new Date().toISOString()})};if(ot(this.upstreamName,this.params))return{type:"mcp",title:i?`Allow high-risk Computer Use (${this.upstreamName})`:`Allow high-risk Computer Use (${this.upstreamName}) \u2014 first use also downloads the driver`,serverName:"cua-driver",toolName:this.upstreamName,toolDisplayName:`computer_use__${this.upstreamName}`,permissionRules:r,onConfirm:n};let s=S(this.params),a=i?`Tool: computer_use__${this.upstreamName}
99
99
 
100
100
  Args: ${s}
101
101
 
@@ -103,9 +103,9 @@ This will act on your desktop via the Computer Use binary.`:`Tool: computer_use_
103
103
 
104
104
  Args: ${s}
105
105
 
106
- ${et}`;return{type:"info",title:`Allow Computer Use (${this.upstreamName})`,prompt:a,permissionRules:r,onConfirm:n}}async execute(o,r){let i=f.shared();i.setMaxImageDimension(Q(this.config?.getComputerUseMaxImageDimension()));let n=!!this.config;await ae(i,{signal:o,updateOutput:r,autoApproveInstall:n});let s;try{s=await i.callTool(this.upstreamName,this.params)}catch(c){let m=c instanceof Error?c.message:String(c);return{llmContent:`Computer Use tool '${this.upstreamName}' failed: ${m}`,returnDisplay:`Error: ${m}`,error:{message:m}}}let a=ot(s.content,this.upstreamName,s.structuredContent),p=it(s.content);if(s.isError){let c=p||`Tool '${this.upstreamName}' returned isError=true`;return{llmContent:a||c,returnDisplay:c,error:{message:c}}}return{llmContent:a,returnDisplay:p}}},y=class extends X{constructor(o,r,i){let n=`computer_use__${o}`;super(n,n,r.description,"other",r.parameterSchema,!0,!0,!0,!1,"computer use desktop click type screenshot mouse keyboard scroll drag automation gui app native");this.upstreamName=o;this.config=i}validateToolParams(o){let r=ce(o,this.parameterSchema);return super.validateToolParams(r)}build(o){let r=ce(o,this.parameterSchema);return super.build(r)}createInvocation(o){return new F(this.upstreamName,o,this.config)}};function ce(e,t){let o=t.properties;if(!o)return e;let r={...e};for(let[i,n]of Object.entries(r)){let s=o[i]?.type;if((s==="integer"||s==="number")&&typeof n=="string"){let a=n.trim();if(/^-?\d+(\.\d+)?$/.test(a)){let p=s==="integer"?parseInt(a,10):parseFloat(a);Number.isFinite(p)&&(r[i]=p)}}else s==="string"&&typeof n=="number"&&(r[i]=String(n))}return r}function ot(e,t,o){let r=[];for(let s of e)s.type==="text"&&s.text?r.push({text:s.text}):(s.type==="image"||s.type==="audio")&&s.mimeType&&s.data&&(r.push({text:`[Tool '${t}' provided the following ${s.type} data with mime-type: ${s.mimeType}]`}),r.push({inlineData:{mimeType:s.mimeType,data:s.data}}));let i=st(o);return i&&r.push({text:`Structured result: ${i}`}),r.some(s=>s.inlineData!==void 0)?r:r.map(s=>s.text??"").filter(Boolean).join(`
107
- `)}function it(e){return e.map(t=>t.type==="text"?t.text??"":"").filter(Boolean).join(`
108
- `)}function st(e){if(!e||typeof e!="object")return;let t={};for(let[o,r]of Object.entries(e))o!=="tree_markdown"&&(t[o]=r);if(Object.keys(t).length!==0)return S(t)}async function ar(e,t){for(let o of j){let r=g[o],i=`computer_use__${o}`;await e(i,async()=>new y(o,r,t))}}export{g as COMPUTER_USE_SCHEMAS,j as COMPUTER_USE_TOOL_NAMES,f as ComputerUseClient,y as ComputerUseTool,ar as registerComputerUseTools};
106
+ ${tt}`;return{type:"info",title:`Allow Computer Use (${this.upstreamName})`,prompt:a,permissionRules:r,onConfirm:n}}async execute(o,r){let i=f.shared();i.setMaxImageDimension(Z(this.config?.getComputerUseMaxImageDimension()));let n=!!this.config;await pe(i,{signal:o,updateOutput:r,autoApproveInstall:n});let s;try{s=await i.callTool(this.upstreamName,this.params)}catch(c){let m=c instanceof Error?c.message:String(c);return{llmContent:`Computer Use tool '${this.upstreamName}' failed: ${m}`,returnDisplay:`Error: ${m}`,error:{message:m}}}let a=it(s.content,this.upstreamName,s.structuredContent),p=st(s.content);if(s.isError){let c=p||`Tool '${this.upstreamName}' returned isError=true`;return{llmContent:a||c,returnDisplay:c,error:{message:c}}}return{llmContent:a,returnDisplay:p}}},y=class extends X{constructor(o,r,i){let n=`computer_use__${o}`;super(n,n,r.description,"other",r.parameterSchema,!0,!0,!0,!1,"computer use desktop click type screenshot mouse keyboard scroll drag automation gui app native");this.upstreamName=o;this.config=i}validateToolParams(o){let r=de(o,this.parameterSchema);return super.validateToolParams(r)}build(o){let r=de(o,this.parameterSchema);return super.build(r)}createInvocation(o){return new F(this.upstreamName,o,this.config)}};function de(e,t){let o=t.properties;if(!o)return e;let r={...e};for(let[i,n]of Object.entries(r)){let s=o[i]?.type;if((s==="integer"||s==="number")&&typeof n=="string"){let a=n.trim();if(/^-?\d+(\.\d+)?$/.test(a)){let p=s==="integer"?parseInt(a,10):parseFloat(a);Number.isFinite(p)&&(r[i]=p)}}else s==="string"&&typeof n=="number"&&(r[i]=String(n))}return r}function it(e,t,o){let r=[];for(let s of e)s.type==="text"&&s.text?r.push({text:s.text}):(s.type==="image"||s.type==="audio")&&s.mimeType&&s.data&&(r.push({text:`[Tool '${t}' provided the following ${s.type} data with mime-type: ${s.mimeType}]`}),r.push({inlineData:{mimeType:s.mimeType,data:s.data}}));let i=nt(o);return i&&r.push({text:`Structured result: ${i}`}),r.some(s=>s.inlineData!==void 0)?r:r.map(s=>s.text??"").filter(Boolean).join(`
107
+ `)}function st(e){return e.map(t=>t.type==="text"?t.text??"":"").filter(Boolean).join(`
108
+ `)}function nt(e){if(!e||typeof e!="object")return;let t={};for(let[o,r]of Object.entries(e))o!=="tree_markdown"&&(t[o]=r);if(Object.keys(t).length!==0)return S(t)}async function pr(e,t){for(let o of j){let r=g[o],i=`computer_use__${o}`;await e(i,async()=>new y(o,r,t))}}export{g as COMPUTER_USE_SCHEMAS,j as COMPUTER_USE_TOOL_NAMES,f as ComputerUseClient,y as ComputerUseTool,pr as registerComputerUseTools};
109
109
  /**
110
110
  * @license
111
111
  * 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 p,c as f}from"./chunk-TXMXCR7D.js";import{a as y}from"./chunk-YULUB745.js";import{a as n}from"./chunk-DEN6RR3B.js";import"./chunk-GT6MSEK4.js";import"./chunk-7AEOFDY3.js";import{f as m,g as c,m as d,n as h}from"./chunk-KYNP66YS.js";import"./chunk-AEYNMLMW.js";import"./chunk-HEJO7OBH.js";import{b as u}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";u();var i=class extends m{constructor(e,t){super(t);this.config=e}getDescription(){return`${this.params.cron}: ${this.params.prompt}`}async getDefaultPermission(){return"ask"}async execute(){let e=this.config.getCronScheduler(),t=this.params.recurring!==!1,s=this.params.durable===!0;try{p(this.params.cron),f(this.params.cron,new Date);let r=s?await e.createDurable(this.params.cron,this.params.prompt,t):e.create(this.params.cron,this.params.prompt,t),o=y(r.cronExpr),w=`Scheduled ${r.id} (${o})${s?" [durable]":""}`,l=s?`Persisted to ${n}`:"Session-only (not written to disk, dies when Matilda exits)";return{llmContent:t?`Scheduled recurring job ${r.id} (${r.cronExpr}). ${l}. Auto-expires after 7 days. Use CronDelete to cancel sooner.`:`Scheduled one-shot task ${r.id} (${r.cronExpr}). ${l}. It will fire once then auto-delete.`,returnDisplay:w}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error creating cron job: ${o}`,returnDisplay:o,error:{message:o}}}}},g=class a extends c{constructor(e){super(a.Name,h.CRON_CREATE,`Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.
3
+ import{a as p,c as f}from"./chunk-TXMXCR7D.js";import{a as y}from"./chunk-YULUB745.js";import{a as n}from"./chunk-DZKI2CAC.js";import"./chunk-GT6MSEK4.js";import"./chunk-PFXCFIHY.js";import{f as m,g as c,m as d,n as h}from"./chunk-P24OL22U.js";import"./chunk-WL27X35X.js";import"./chunk-HEJO7OBH.js";import{b as u}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";u();var i=class extends m{constructor(e,t){super(t);this.config=e}getDescription(){return`${this.params.cron}: ${this.params.prompt}`}async getDefaultPermission(){return"ask"}async execute(){let e=this.config.getCronScheduler(),t=this.params.recurring!==!1,s=this.params.durable===!0;try{p(this.params.cron),f(this.params.cron,new Date);let r=s?await e.createDurable(this.params.cron,this.params.prompt,t):e.create(this.params.cron,this.params.prompt,t),o=y(r.cronExpr),w=`Scheduled ${r.id} (${o})${s?" [durable]":""}`,l=s?`Persisted to ${n}`:"Session-only (not written to disk, dies when Matilda exits)";return{llmContent:t?`Scheduled recurring job ${r.id} (${r.cronExpr}). ${l}. Auto-expires after 7 days. Use CronDelete to cancel sooner.`:`Scheduled one-shot task ${r.id} (${r.cronExpr}). ${l}. It will fire once then auto-delete.`,returnDisplay:w}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error creating cron job: ${o}`,returnDisplay:o,error:{message:o}}}}},g=class a extends c{constructor(e){super(a.Name,h.CRON_CREATE,`Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.
4
4
 
5
5
  Uses standard 5-field cron in the user's local timezone: minute hour day-of-month month day-of-week. "0 9 * * *" means 9am local \u2014 no timezone conversion needed.
6
6