@maincode-ai/matilda-code 0.19.1 → 0.19.4

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 (93) hide show
  1. package/README.md +0 -45
  2. package/chunks/agent-THT56PAJ.js +3 -0
  3. package/chunks/agent-headless-MJXXZAJ5.js +3 -0
  4. package/chunks/{askUserQuestion-QPVUWJCI.js → askUserQuestion-V5YLTC4J.js} +1 -1
  5. package/chunks/{ca-D7YSARXX.js → ca-UW3G7H5I.js} +1 -1
  6. package/chunks/{chunk-2MEHZGZJ.js → chunk-2XZIKUB6.js} +1 -1
  7. package/chunks/{chunk-F2SL32K6.js → chunk-33FV6XMQ.js} +1 -1
  8. package/chunks/{chunk-X6DODPXG.js → chunk-5U3A6KMU.js} +1 -1
  9. package/chunks/{chunk-DY6PIAAY.js → chunk-CFBZKYFB.js} +1 -1
  10. package/chunks/{chunk-ZX6WKO3S.js → chunk-GV5WGCQ4.js} +479 -495
  11. package/chunks/{chunk-WNEFIZW2.js → chunk-LDSV6752.js} +1 -1
  12. package/chunks/{chunk-YTY4VZHQ.js → chunk-NAH2MNUA.js} +2 -2
  13. package/chunks/{chunk-4M4CUQUR.js → chunk-NDR7ZFUA.js} +1 -1
  14. package/chunks/{chunk-NRYMHT3V.js → chunk-QE7JDD3Q.js} +2 -2
  15. package/chunks/{chunk-CNHY7623.js → chunk-SUORCDGS.js} +1 -1
  16. package/chunks/{chunk-S32ZN6LD.js → chunk-T3ERIC7X.js} +1 -1
  17. package/chunks/{chunk-JQSW4K4X.js → chunk-TVWOSSXE.js} +2 -2
  18. package/chunks/chunk-YNR4LJMU.js +34 -0
  19. package/chunks/{computer-use-5HO7HQCB.js → computer-use-GUYVQIGN.js} +1 -1
  20. package/chunks/contextCommand-4CKQVKP7.js +3 -0
  21. package/chunks/{cron-create-K35JKX3K.js → cron-create-JHL5JGIM.js} +1 -1
  22. package/chunks/{cron-delete-7B65R7JC.js → cron-delete-K2R3KI2W.js} +1 -1
  23. package/chunks/{cron-list-FCX6HCY7.js → cron-list-R3YHZBHA.js} +1 -1
  24. package/chunks/{de-ME75AM7Q.js → de-QSFN3SRK.js} +1 -1
  25. package/chunks/{edit-GKLQRHLW.js → edit-ZULTS2VM.js} +1 -1
  26. package/chunks/{en-KVT5FJKO.js → en-77LGBBG5.js} +1 -1
  27. package/chunks/{enter-worktree-2NIHUGOI.js → enter-worktree-CCLNWZ5Q.js} +1 -1
  28. package/chunks/{enterPlanMode-PHENGP6O.js → enterPlanMode-GXBX6ZNF.js} +1 -1
  29. package/chunks/{exit-worktree-LDVCXGEZ.js → exit-worktree-6Q45J7P4.js} +1 -1
  30. package/chunks/{exitPlanMode-U3QEDGBI.js → exitPlanMode-SKDXBN5H.js} +1 -1
  31. package/chunks/{fr-V3O5JG5W.js → fr-FKTJ4COX.js} +2 -2
  32. package/chunks/{geminiContentGenerator-56OUN5BI.js → geminiContentGenerator-AHPUJXRJ.js} +1 -1
  33. package/chunks/{glob-P43IIJJX.js → glob-YQYYXRD6.js} +1 -1
  34. package/chunks/grep-SEHIGGHQ.js +22 -0
  35. package/chunks/{ja-ZOFFSG6C.js → ja-GKS4GLZP.js} +1 -1
  36. package/chunks/{ls-ZSHUDEJV.js → ls-4QPI2E7A.js} +1 -1
  37. package/chunks/{lsp-DW3UNQQ6.js → lsp-P3GKBOP3.js} +1 -1
  38. package/chunks/{matildaAgentContentGenerator-QLZEASVN.js → matildaAgentContentGenerator-O54RMUHJ.js} +1 -1
  39. package/chunks/matildaContentGenerator-UXLQXYIJ.js +8 -0
  40. package/chunks/monitor-H5RCPLSV.js +32 -0
  41. package/chunks/notebook-edit-ZBKC73OA.js +17 -0
  42. package/chunks/{openaiContentGenerator-LBEDAHRX.js → openaiContentGenerator-4D5JS26Z.js} +1 -1
  43. package/chunks/{pt-K2W3KMTP.js → pt-VIW62ZAE.js} +1 -1
  44. package/chunks/{read-file-MUUE7CJM.js → read-file-HEVXSNSO.js} +1 -1
  45. package/chunks/ripGrep-SIK37YV5.js +3 -0
  46. package/chunks/{ru-KICZRPMQ.js → ru-FSSACF4A.js} +1 -1
  47. package/chunks/scheduler-OM5HPBCW.js +8 -0
  48. package/chunks/{send-message-BPTEYK4Y.js → send-message-K3T7GVHO.js} +1 -1
  49. package/chunks/{serve-CIN26WPX.js → serve-JLX6G5W2.js} +1 -1
  50. package/chunks/shell-YYHEBIMO.js +3 -0
  51. package/chunks/{skill-D23JCWUG.js → skill-YXHHDMLR.js} +1 -1
  52. package/chunks/src-5RWLWMNE.js +3 -0
  53. package/chunks/{symbol-search-3E5XK5S6.js → symbol-search-WVNUJRET.js} +1 -1
  54. package/chunks/{syntheticOutput-NSQJLEEY.js → syntheticOutput-LLA4WQR7.js} +1 -1
  55. package/chunks/{task-create-TQI5N4YR.js → task-create-ZZTSVXZN.js} +1 -1
  56. package/chunks/{task-list-DQBF34BK.js → task-list-6I64SK7E.js} +1 -1
  57. package/chunks/{task-stop-5R44O4NK.js → task-stop-UKRXMCZV.js} +1 -1
  58. package/chunks/{task-update-PL2JDIF6.js → task-update-XZWORLJB.js} +1 -1
  59. package/chunks/{team-create-LB3Q5Z6M.js → team-create-WNT5JVQS.js} +1 -1
  60. package/chunks/{team-delete-LWX4LMFZ.js → team-delete-DEPXAMUE.js} +1 -1
  61. package/chunks/{todoWrite-V4DQMEDR.js → todoWrite-DKJAYA4S.js} +1 -1
  62. package/chunks/{tool-search-UA3I7UV3.js → tool-search-47TA6SG4.js} +1 -1
  63. package/chunks/update-goal-6YHKDFDL.js +16 -0
  64. package/chunks/{web-fetch-XRYT2EOQ.js → web-fetch-KIAE27JH.js} +1 -1
  65. package/chunks/web-search-T6JQYRFL.js +26 -0
  66. package/chunks/{workflow-EUTO2UEN.js → workflow-S2XCUMV3.js} +2 -2
  67. package/chunks/write-file-GM4PPNIQ.js +11 -0
  68. package/chunks/{zh-C5PHBN3U.js → zh-LDF5IJ3D.js} +1 -1
  69. package/chunks/{zh-TW-IYMR6KR3.js → zh-TW-NAHJGTBA.js} +1 -1
  70. package/cli.js +417 -416
  71. package/locales/ca.js +6 -2
  72. package/locales/de.js +5 -3
  73. package/locales/en.js +5 -2
  74. package/locales/fr.js +4 -2
  75. package/locales/ja.js +6 -2
  76. package/locales/pt.js +4 -2
  77. package/locales/ru.js +4 -2
  78. package/locales/zh-TW.js +5 -2
  79. package/locales/zh.js +5 -2
  80. package/package.json +3 -3
  81. package/chunks/agent-O7L36PRI.js +0 -3
  82. package/chunks/agent-headless-ZOO3SBWV.js +0 -3
  83. package/chunks/contextCommand-3DHLUVVM.js +0 -3
  84. package/chunks/grep-6WULIUE2.js +0 -22
  85. package/chunks/matildaContentGenerator-TGCMZZC6.js +0 -8
  86. package/chunks/monitor-4N4X3QGD.js +0 -32
  87. package/chunks/notebook-edit-CY3IB63X.js +0 -17
  88. package/chunks/ripGrep-N4V3GUFZ.js +0 -3
  89. package/chunks/scheduler-QLV7TX35.js +0 -8
  90. package/chunks/shell-C3FX4NO6.js +0 -3
  91. package/chunks/src-CZPOL4AN.js +0 -3
  92. package/chunks/web-search-5PWKXHF6.js +0 -13
  93. package/chunks/write-file-SXD2ZXSI.js +0 -11
@@ -1,13 +1,13 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as U,d as rt}from"./chunk-4F4DA5UI.js";import{a as ot,b as it,e as Ie,n as at,q as W,r as st}from"./chunk-LN2DRVOB.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{Jc as et,Kc as tt,Mb as Xe,Mc as nt,Pb as Ze,Rb as Qe,Sa as K,Wa as ve,Xa as _e,Ya as xe,eb as be,f as P,fb as F,tb as Q,ub as ee}from"./chunk-DY6PIAAY.js";import{L as Ye,Y as b,c as qe,d as j,e as H}from"./chunk-QWBNNEV2.js";import{h as k,l as Se,n as Bt}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();f();var te=b("TAGGED_THINKING_PARSER"),lt=["<think>","<thinking>"],dt=["</think>","</thinking>"],Wt=Math.max(...lt.map(t=>t.length),...dt.map(t=>t.length));function ke(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Vt(t,e,n){let o=t.length-e;return o<=0||o>Wt?!1:n.some(i=>i.startsWith(t.slice(e,e+o)))}function Jt(t,e,n){return n.find(o=>t.startsWith(o,e))}var we=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),i=[],r="",a=0;for(;a<this.buffer.length;){let s=this.mode==="text"?lt:dt,l=Jt(o,a,s);if(l){te.debug(`taggedThinking: detected tag "${l}" at offset ${a}`),ke(i,r,this.mode),r="",this.mode=this.mode==="text"?"thought":"text",a+=l.length;continue}if(!n&&Vt(o,a,s))break;r+=this.buffer[a],a+=1}return a<this.buffer.length?(ke(i,r,this.mode),this.buffer=this.buffer.slice(a),te.debug(`taggedThinking: emitted ${i.length} part(s), buffered ${this.buffer.length} char(s)`),i):(this.buffer="",this.mode==="thought"&&r&&te.warn(`taggedThinking: flushing ${r.length} chars of unclosed thought on stream end`),ke(i,r,this.mode),te.debug(`taggedThinking: emitted ${i.length} part(s), flush complete`),i)}};function ct(t){return new we().parse(t,!0)}var w=b("CONVERTER"),Ct="(attached media from previous tool call)";function yt(t){let e=t.prompt_tokens||0,n=t.completion_tokens||0,o=t.total_tokens||0,i=t.prompt_tokens_details?.cached_tokens??t.cached_tokens??0,r=t.completion_tokens_details?.reasoning_tokens||0,a=t.usage_is_incomplete===!0||n>0&&e===0||o>0&&e===0&&n===0,s=e,l=n,d=o;return d===0&&(s>0||l>0)&&(d=s+l),{promptTokenCount:s,candidatesTokenCount:l,totalTokenCount:d,cachedContentTokenCount:i,thoughtsTokenCount:r,...a?{usageIsIncomplete:!0}:{}}}var qt=64,ut=1024;function pt(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(w.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(w.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,i=n>=ut&&e.emittedLength>n?e.emittedLength:n;if(t.length>i){let r=t.slice(i);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${i}b -> curr=${t.length}b)`),r}}return t===e.emittedText?t.length>=qt?(e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<ut&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function Tt(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let i={};for(let[r,a]of Object.entries(o))if(r==="type"&&typeof a=="string"){let s=a.toLowerCase();s==="integer"?i[r]="integer":s==="number"?i[r]="number":i[r]=s}else r==="minimum"||r==="maximum"||r==="multipleOf"?typeof a=="string"&&!isNaN(Number(a))?i[r]=Number(a):i[r]=a:r==="minLength"||r==="maxLength"||r==="minItems"||r==="maxItems"?typeof a=="string"&&!isNaN(Number(a))?i[r]=parseInt(a,10):i[r]=a:typeof a=="object"?i[r]=n(a):i[r]=a;return i};return n(e)}async function Yt(t,e="auto"){let n=[];for(let o of t){let i;if("tool"in o?i=await o.tool():i=o,i.functionDeclarations){for(let r of i.functionDeclarations)if(r.name&&r.description){let a;r.parametersJsonSchema?a={...r.parametersJsonSchema}:r.parameters&&(a=Tt(r.parameters)),a&&(a=it(a,e)),n.push({type:"function",function:{name:r.name,description:r.description,parameters:a}})}}}return n}function Xt(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return Qt(t,o),en(t.contents,o,e),o=mt(o),n.cleanOrphanToolCalls&&(o=dn(o),o=mt(o)),o}function Zt(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],i=[],r=[],a=[],s=0;for(let p of o)typeof p=="string"?r.push(p):"text"in p&&p.text?"thought"in p&&p.thought?i.push(p.text):r.push(p.text):"functionCall"in p&&p.functionCall&&(a.push({id:p.functionCall.id||`call_${s}`,type:"function",function:{name:p.functionCall.name||"",arguments:JSON.stringify(p.functionCall.args||{})}}),s+=1);let l={role:"assistant",content:r.join("")||null,refusal:null},d=i.join("");d&&(l.reasoning_content=d),a.length>0&&(l.tool_calls=a);let c=ln(n?.finishReason),g=t.usageMetadata,u={prompt_tokens:g?.promptTokenCount||0,completion_tokens:g?.candidatesTokenCount||0,total_tokens:g?.totalTokenCount||0};g?.cachedContentTokenCount!==void 0&&(u.prompt_tokens_details={cached_tokens:g.cachedContentTokenCount});let m=t.createTime?Number(t.createTime):Date.now(),h=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:h,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:c,logprobs:null}],usage:u}}function Qt(t,e){if(!t.config?.systemInstruction)return;let n=Mt(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function en(t,e,n){if(Array.isArray(t))for(let o of t)gt(o,e,n);else t&&gt(t,e,n)}function gt(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!rn(t))return;let o=t.parts||[],i=t.role==="model"?"assistant":"user",r=[],a=[],s=[],l=0,d=new Set,c=new Set,g=[];for(let u of o){if(typeof u=="string"){r.push({type:"text",text:u});continue}"text"in u&&"thought"in u&&u.thought&&i==="assistant"&&u.text&&a.push(u.text),"text"in u&&u.text&&!("thought"in u&&u.thought)&&r.push({type:"text",text:u.text});let m=At(u,n);if(m&&i==="user"&&r.push(m),"functionCall"in u&&u.functionCall&&i==="assistant"){let h=u.functionCall.id;if(h){if(d.has(h)){w.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}d.add(h)}s.push({id:h||`call_${l}`,type:"function",function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})}}),l+=1}if(u.functionResponse&&i==="user"){let h=u.functionResponse.id;if(h){if(c.has(h))continue;c.add(h)}let p=nn(u.functionResponse,n);if(p){if(n.splitToolMedia&&Array.isArray(p.content)){let C=[],y=[];for(let T of p.content)T&&(T.type==="image_url"||T.type==="input_audio"||T.type==="video_url"||T.type==="file")?C.push(T):T&&T.type==="text"&&y.push(T);if(C.length>0){let T=y.map(S=>S.text).join(`
3
+ import{a as U,d as rt}from"./chunk-4F4DA5UI.js";import{a as ot,b as it,e as Ie,n as at,q as W,r as st}from"./chunk-LN2DRVOB.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{Jc as et,Kc as tt,Mb as Xe,Mc as nt,Pb as Ze,Rb as Qe,Sa as K,Wa as ve,Xa as _e,Ya as xe,eb as be,f as P,fb as F,tb as Q,ub as ee}from"./chunk-CFBZKYFB.js";import{L as Ye,Y as b,c as qe,d as j,e as H}from"./chunk-QWBNNEV2.js";import{h as k,l as Se,n as Bt}from"./chunk-FWDMPRKU.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();f();var te=b("TAGGED_THINKING_PARSER"),lt=["<think>","<thinking>"],dt=["</think>","</thinking>"],Wt=Math.max(...lt.map(t=>t.length),...dt.map(t=>t.length));function ke(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Vt(t,e,n){let o=t.length-e;return o<=0||o>Wt?!1:n.some(i=>i.startsWith(t.slice(e,e+o)))}function Jt(t,e,n){return n.find(o=>t.startsWith(o,e))}var we=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),i=[],r="",a=0;for(;a<this.buffer.length;){let s=this.mode==="text"?lt:dt,l=Jt(o,a,s);if(l){te.debug(`taggedThinking: detected tag "${l}" at offset ${a}`),ke(i,r,this.mode),r="",this.mode=this.mode==="text"?"thought":"text",a+=l.length;continue}if(!n&&Vt(o,a,s))break;r+=this.buffer[a],a+=1}return a<this.buffer.length?(ke(i,r,this.mode),this.buffer=this.buffer.slice(a),te.debug(`taggedThinking: emitted ${i.length} part(s), buffered ${this.buffer.length} char(s)`),i):(this.buffer="",this.mode==="thought"&&r&&te.warn(`taggedThinking: flushing ${r.length} chars of unclosed thought on stream end`),ke(i,r,this.mode),te.debug(`taggedThinking: emitted ${i.length} part(s), flush complete`),i)}};function ct(t){return new we().parse(t,!0)}var w=b("CONVERTER"),Ct="(attached media from previous tool call)";function yt(t){let e=t.prompt_tokens||0,n=t.completion_tokens||0,o=t.total_tokens||0,i=t.prompt_tokens_details?.cached_tokens??t.cached_tokens??0,r=t.completion_tokens_details?.reasoning_tokens||0,a=t.usage_is_incomplete===!0||n>0&&e===0||o>0&&e===0&&n===0,s=e,l=n,d=o;return d===0&&(s>0||l>0)&&(d=s+l),{promptTokenCount:s,candidatesTokenCount:l,totalTokenCount:d,cachedContentTokenCount:i,thoughtsTokenCount:r,...a?{usageIsIncomplete:!0}:{}}}var qt=64,ut=1024;function pt(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(w.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(w.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,i=n>=ut&&e.emittedLength>n?e.emittedLength:n;if(t.length>i){let r=t.slice(i);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${i}b -> curr=${t.length}b)`),r}}return t===e.emittedText?t.length>=qt?(e.cumulativeMode=!0,w.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<ut&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function Tt(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let i={};for(let[r,a]of Object.entries(o))if(r==="type"&&typeof a=="string"){let s=a.toLowerCase();s==="integer"?i[r]="integer":s==="number"?i[r]="number":i[r]=s}else r==="minimum"||r==="maximum"||r==="multipleOf"?typeof a=="string"&&!isNaN(Number(a))?i[r]=Number(a):i[r]=a:r==="minLength"||r==="maxLength"||r==="minItems"||r==="maxItems"?typeof a=="string"&&!isNaN(Number(a))?i[r]=parseInt(a,10):i[r]=a:typeof a=="object"?i[r]=n(a):i[r]=a;return i};return n(e)}async function Yt(t,e="auto"){let n=[];for(let o of t){let i;if("tool"in o?i=await o.tool():i=o,i.functionDeclarations){for(let r of i.functionDeclarations)if(r.name&&r.description){let a;r.parametersJsonSchema?a={...r.parametersJsonSchema}:r.parameters&&(a=Tt(r.parameters)),a&&(a=it(a,e)),n.push({type:"function",function:{name:r.name,description:r.description,parameters:a}})}}}return n}function Xt(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return Qt(t,o),en(t.contents,o,e),o=mt(o),n.cleanOrphanToolCalls&&(o=dn(o),o=mt(o)),o}function Zt(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],i=[],r=[],a=[],s=0;for(let p of o)typeof p=="string"?r.push(p):"text"in p&&p.text?"thought"in p&&p.thought?i.push(p.text):r.push(p.text):"functionCall"in p&&p.functionCall&&(a.push({id:p.functionCall.id||`call_${s}`,type:"function",function:{name:p.functionCall.name||"",arguments:JSON.stringify(p.functionCall.args||{})}}),s+=1);let l={role:"assistant",content:r.join("")||null,refusal:null},d=i.join("");d&&(l.reasoning_content=d),a.length>0&&(l.tool_calls=a);let c=ln(n?.finishReason),g=t.usageMetadata,u={prompt_tokens:g?.promptTokenCount||0,completion_tokens:g?.candidatesTokenCount||0,total_tokens:g?.totalTokenCount||0};g?.cachedContentTokenCount!==void 0&&(u.prompt_tokens_details={cached_tokens:g.cachedContentTokenCount});let m=t.createTime?Number(t.createTime):Date.now(),h=Number.isFinite(m)?Math.floor(m/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:h,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:c,logprobs:null}],usage:u}}function Qt(t,e){if(!t.config?.systemInstruction)return;let n=Mt(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function en(t,e,n){if(Array.isArray(t))for(let o of t)gt(o,e,n);else t&&gt(t,e,n)}function gt(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!rn(t))return;let o=t.parts||[],i=t.role==="model"?"assistant":"user",r=[],a=[],s=[],l=0,d=new Set,c=new Set,g=[];for(let u of o){if(typeof u=="string"){r.push({type:"text",text:u});continue}"text"in u&&"thought"in u&&u.thought&&i==="assistant"&&u.text&&a.push(u.text),"text"in u&&u.text&&!("thought"in u&&u.thought)&&r.push({type:"text",text:u.text});let m=At(u,n);if(m&&i==="user"&&r.push(m),"functionCall"in u&&u.functionCall&&i==="assistant"){let h=u.functionCall.id;if(h){if(d.has(h)){w.debug(`Dropping duplicate functionCall id=${h} while converting content`);continue}d.add(h)}s.push({id:h||`call_${l}`,type:"function",function:{name:u.functionCall.name||"",arguments:JSON.stringify(u.functionCall.args||{})}}),l+=1}if(u.functionResponse&&i==="user"){let h=u.functionResponse.id;if(h){if(c.has(h))continue;c.add(h)}let p=nn(u.functionResponse,n);if(p){if(n.splitToolMedia&&Array.isArray(p.content)){let C=[],y=[];for(let T of p.content)T&&(T.type==="image_url"||T.type==="input_audio"||T.type==="video_url"||T.type==="file")?C.push(T):T&&T.type==="text"&&y.push(T);if(C.length>0){let T=y.map(S=>S.text).join(`
4
4
  `);p.content=T||"[media attached in following user message]",g.push(...C)}}e.push(p)}}}if(g.length>0&&e.push({role:"user",content:[{type:"text",text:Ct},...g]}),i==="assistant"){if(r.length===0&&s.length===0&&a.length===0)return;let m={role:"assistant",content:r.filter(p=>p.type==="text").map(p=>p.text).join("")||(a.length>0?"":null)};s.length>0&&(m.tool_calls=s);let h=a.join("");h&&(m.reasoning_content=h),e.push(m);return}r.length>0&&e.push({role:"user",content:r})}function tn(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function nn(t,e){let n=tn(t.response),o=[];n&&o.push({type:"text",text:n});for(let i of t.parts||[]){if("text"in i&&typeof i.text=="string"){i.text.length>0&&o.push({type:"text",text:i.text});continue}let r=At(i,e);r&&o.push(r)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function At(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,i=ft(o),r=t.inlineData.displayName||o;if(i==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:L("image",r,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:L("pdf",r,e);if(i==="audio"){if(!n.audio)return L("audio",r,e);let a=on(o);if(a)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:a}}}return i==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:L("video",r,e):{type:"text",text:`Unsupported inline media type: ${o} (${r}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",i=t.fileData.fileUri,r=t.fileData.mimeType,a=ft(r);if(a==="image")return n.image?{type:"image_url",image_url:{url:i}}:L("image",o,e);if(r==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:i}}:L("pdf",o,e);if(a==="video")return n.video?{type:"video_url",video_url:{url:i}}:L("video",o,e);let s=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${r}${s}.`}}return null}function L(t,e,n){w.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
5
5
  /extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${t} file: "${e}". ${o}]`}}function ft(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function on(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function rn(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Mt(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Mt(e)).filter(Boolean).join(`
6
6
  `):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
7
7
  `)||""}function Pe(t,e,n=!0){return e.responseParsingOptions?.taggedThinkingTags?e.taggedThinkingParser?e.taggedThinkingParser.parse(t,n):ct(t):t?[{text:t}]:[]}function an(t,e){let n=t.choices?.[0],o=new B;if(n){let i=[];if(!e.responseParsingOptions?.taggedThinkingTags){let r=n.message.reasoning_content??n.message.reasoning;r&&i.push({text:r,thought:!0})}if(n.message.content&&i.push(...Pe(n.message.content,e)),n.message.tool_calls){for(let r of n.message.tool_calls)if(r.function){let a={};r.function.arguments&&(a=ot(r.function.arguments,{})),i.push({functionCall:{id:r.id,name:r.function.name,args:a}})}}o.candidates=[{content:{parts:i,role:"model"},finishReason:St(n.finish_reason||"stop"),index:0,safetyRatings:[]}]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=yt(t.usage)),o}function sn(t,e){let n=t.choices?.[0],o=new B,i=e.toolCallParser;if(!i)throw new Error("convertOpenAIChunkToGemini requires requestContext.toolCallParser \u2014 attach a fresh StreamingToolCallParser at stream start.");if(n){let r=[];if(!e.responseParsingOptions?.taggedThinkingTags){let d=n.delta?.reasoning_content??n.delta?.reasoning;if(d){let c=pt(d,e.reasoningDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});c&&r.push({text:c,thought:!0})}}if(typeof n.delta?.content=="string"){let d=pt(n.delta.content,e.textDeltaState??={emittedText:"",emittedLength:0,cumulativeMode:!1});(d||n.finish_reason)&&r.push(...Pe(d,e,!!n.finish_reason))}else n.finish_reason&&r.push(...Pe("",e,!0));if(n.delta?.tool_calls)for(let d of n.delta.tool_calls){let c=d.index??0;d.function?.arguments?i.addChunk(c,d.function.arguments,d.id,d.function.name):i.addChunk(c,"",d.id,d.function?.name)}let a=!1;if(n.finish_reason){a=i.hasIncompleteToolCalls();let d=i.getCompletedToolCalls();for(let c of d)c.name&&r.push({functionCall:{id:c.id||`call_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,name:c.name,args:c.args}})}let s=a&&n.finish_reason!=="length"?"length":n.finish_reason,l={content:{parts:r,role:"model"},index:0,safetyRatings:[]};s&&(l.finishReason=St(s)),o.candidates=[l]}else o.candidates=[];return o.responseId=t.id,o.createTime=t.created?t.created.toString():new Date().getTime().toString(),o.modelVersion=e.model,o.promptFeedback={safetyRatings:[]},t.usage&&(o.usageMetadata=yt(t.usage)),o}function St(t){return t?{stop:A.STOP,length:A.MAX_TOKENS,content_filter:A.SAFETY,function_call:A.STOP,tool_calls:A.STOP}[t]||A.FINISH_REASON_UNSPECIFIED:A.FINISH_REASON_UNSPECIFIED}function ln(t){if(!t)return"stop";switch(t){case A.STOP:return"stop";case A.MAX_TOKENS:return"length";case A.SAFETY:case A.RECITATION:case A.BLOCKLIST:case A.PROHIBITED_CONTENT:case A.SPII:case A.IMAGE_SAFETY:case A.IMAGE_RECITATION:case A.IMAGE_PROHIBITED_CONTENT:case A.IMAGE_OTHER:return"content_filter";case A.NO_IMAGE:return"stop";default:return"stop"}}function Re(t){return t.role==="assistant"&&"tool_calls"in t&&Array.isArray(t.tool_calls)&&t.tool_calls.length>0}function ht(t){if(t.role!=="user"||!("content"in t)||!Array.isArray(t.content))return!1;let e=t.content[0];return e?.type==="text"&&e.text===Ct}function dn(t){let e=[],n=new Map,o=new Map,i=new Map,r=new Set,a=new Set;for(let s=0;s<t.length;s+=1){let l=t[s];if(Re(l)){let d=[],c=new Set;for(let C of l.tool_calls){let y=C.id;!y||a.has(y)||c.has(y)||(c.add(y),d.push(C))}let g=new Set,u=[],m=[],h=!1;for(let C=s+1;C<t.length;C+=1){let y=t[C];if(y.role==="tool"&&"tool_call_id"in y){if(!y.tool_call_id){h=!1;continue}c.has(y.tool_call_id)&&!g.has(y.tool_call_id)?(g.add(y.tool_call_id),u.push(C),h=!0):h=!1;continue}if(ht(y)){h&&m.push(C);continue}if(!(y.role==="assistant"&&!Re(y)))break}let p=d.filter(C=>g.has(C.id));for(let C of p)a.add(C.id);n.set(s,p),o.set(s,u),i.set(s,m)}}for(let s=0;s<t.length;s+=1){if(r.has(s))continue;let l=t[s];if(Re(l)){let d=l.reasoning_content,c=n.get(s)??[];if(c.length>0){let g={...l};g.tool_calls=c,e.push(g);for(let u of o.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}for(let u of i.get(s)??[]){let m=t[u];m&&(e.push(m),r.add(u))}}else if(typeof l.content=="string"&&l.content.trim()||d){let g={...l};delete g.tool_calls,e.push(g)}else w.debug(`cleanOrphanedToolCalls: dropping assistant with ${l.tool_calls.length} orphaned tool call(s) and no text/reasoning content`)}else l.role==="tool"&&"tool_call_id"in l?w.debug(`cleanOrphanedToolCalls: dropping orphaned tool response ${l.tool_call_id||"<empty>"}`):ht(l)?w.debug("cleanOrphanedToolCalls: dropping orphaned split tool media message"):e.push(l)}return e}function mt(t){let e=[];for(let n of t){if(n.role==="assistant"&&e.length>0){let o=e[e.length-1];if(o.role==="assistant"){let i="tool_calls"in o?o.tool_calls||[]:[],r="tool_calls"in n?n.tool_calls||[]:[],a=o.content,s=n.content,l=Array.isArray(a)||Array.isArray(s),d;if(l){let g=Array.isArray(a)?a:typeof a=="string"&&a?[{type:"text",text:a}]:[],u=Array.isArray(s)?s:typeof s=="string"&&s?[{type:"text",text:s}]:[];d=[...g,...u]}else d=[typeof a=="string"?a:"",typeof s=="string"?s:""].filter(Boolean).join("")||null;let c=[...i,...r];o.content=d||null,c.length>0&&(o.tool_calls=c);continue}}e.push(n)}return e}var ne={convertGeminiToolParametersToOpenAI:Tt,convertGeminiToolsToOpenAI:Yt,convertGeminiRequestToOpenAI:Xt,convertGeminiResponseToOpenAI:Zt,convertOpenAIResponseToGemini:an,convertOpenAIChunkToGemini:sn};f();import*as _ from"node:path";import{promises as re}from"node:fs";f();f();import cn from"crypto";var ie=new Uint8Array(256),oe=ie.length;function Ee(){return oe>ie.length-16&&(cn.randomFillSync(ie),oe=0),ie.slice(oe,oe+=16)}f();var M=[];for(let t=0;t<256;++t)M.push((t+256).toString(16).slice(1));function vt(t,e=0){return M[t[e+0]]+M[t[e+1]]+M[t[e+2]]+M[t[e+3]]+"-"+M[t[e+4]]+M[t[e+5]]+"-"+M[t[e+6]]+M[t[e+7]]+"-"+M[t[e+8]]+M[t[e+9]]+"-"+M[t[e+10]]+M[t[e+11]]+M[t[e+12]]+M[t[e+13]]+M[t[e+14]]+M[t[e+15]]}f();f();import un from"crypto";var Oe={randomUUID:un.randomUUID};function pn(t,e,n){if(Oe.randomUUID&&!e&&!t)return Oe.randomUUID();t=t||{};let o=t.random||(t.rng||Ee)();if(o[6]=o[6]&15|64,o[8]=o[8]&63|128,e){n=n||0;for(let i=0;i<16;++i)e[n+i]=o[i];return e}return vt(o)}var Ue=pn;import*as E from"os";var ae=b("OPENAI_LOGGER"),gn="########",fn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function hn(t,e){let n=e||process.cwd();if(!t)return _.join(n,"logs","openai");let o=t;return t==="~"||t.startsWith("~/")?o=_.join(E.homedir(),t.slice(1)):_.isAbsolute(t)||(o=_.resolve(n,t)),_.normalize(o)}function _t(t){return t&&t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||void 0}function mn(t){let e=t.split("#");if(e.length!==3)return;let[,n,o]=e;if(!(!n||!o||!/^\d+$/.test(o)))return`subagent-${n}`}function Cn(t){if(t)return K(t)?_t(t):_t(mn(t))}function yn(t){if(!t)return;let e=t.indexOf(gn);if(e>0)return t.slice(0,e);if(fn.test(t))return t;let n=t.split("#");if(n.length>=3&&n[0])return n[0]}function Tn(t){let e=t?.trim(),n=yn(e);return!e&&!n?null:{...e?{promptId:e}:{},...n?{sessionId:n}:{}}}var V=class{logDir;initialized=!1;constructor(e,n){this.logDir=hn(e,n)}async initialize(){if(!this.initialized)try{await re.mkdir(this.logDir,{recursive:!0}),this.initialized=!0}catch(e){throw ae.error("Failed to initialize OpenAI logger:",e),new Error(`Failed to initialize OpenAI logger: ${e}`)}}async logInteraction(e,n,o,i){this.initialized||await this.initialize();let r=new Date().toISOString().replace(/:/g,"-"),a=Ue().slice(0,8),s=Cn(i),l=s?`openai-${r}-${a}-${s}.json`:`openai-${r}-${a}.json`,d=_.join(this.logDir,l),c={timestamp:new Date().toISOString(),request:e,response:n||null,error:o?{message:o.message,stack:o.stack}:null,context:Tn(i),system:{hostname:E.hostname(),platform:E.platform(),release:E.release(),nodeVersion:process.version}};try{return await re.writeFile(d,JSON.stringify(c,null,2),"utf-8"),d}catch(g){throw ae.error("Failed to write OpenAI log file:",g),new Error(`Failed to write OpenAI log file: ${g}`)}}async getLogFiles(e){this.initialized||await this.initialize();try{let o=(await re.readdir(this.logDir)).filter(i=>i.startsWith("openai-")&&i.endsWith(".json")).map(i=>_.join(this.logDir,i)).sort().reverse();return e?o.slice(0,e):o}catch(n){return n.code==="ENOENT"?[]:(ae.error("Failed to read OpenAI log directory:",n),[])}}async readLogFile(e){try{let n=await re.readFile(e,"utf-8");return JSON.parse(n)}catch(n){throw ae.error(`Failed to read log file ${e}:`,n),new Error(`Failed to read log file: ${n}`)}}},Lo=new V;f();var se="$runtime|";function No(t){let e=t;for(;e.startsWith(se);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}f();var le=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],xt=["model","apiKey","apiKeyEnvKey","baseUrl"],de=[...xt,...le],zo={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"matilda-oauth":{apiKey:[],baseUrl:[],model:[]}},jo={openai:rt,"matilda-oauth":U},ce=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Ho=ce.map(t=>t.id);f();f();f();f();Bt();f();import{AsyncLocalStorage as An}from"node:async_hooks";var bt=new An;f();function It(t){let e=t.candidates?.[0]?.content?.parts;return!e||e.length===0?!1:e.some(Mn)}function Mn(t){if(t===null||typeof t!="object")return!1;let e=t;return typeof e.text=="string"&&e.text.length>0||e.functionCall!==void 0||e.inlineData!==void 0||e.executableCode!==void 0||e.thought===!0}f();import{AsyncLocalStorage as Sn}from"node:async_hooks";var kt=new Sn;function wt(){let t=kt.getStore();return{attempt:t?.attempt??1,requestSetupMs:t?.requestSetupMs,retryTotalDelayMs:t?.retryTotalDelayMs}}var D=b("LOGGING_CONTENT_GENERATOR"),vn=4096,Rt="...[truncated]",_n=vn-Rt.length,J=class{constructor(e,n,o){this.wrapped=e;this.config=n;this.modalities=o.modalities,this.splitToolMedia=o.splitToolMedia,this.generatorAuthType=o.authType,o.enableOpenAILogging&&(this.openaiLogger=new V(o.openAILoggingDir,n.getWorkingDir()),this.schemaCompliance=o.schemaCompliance)}openaiLogger;schemaCompliance;modalities;splitToolMedia;generatorAuthType;getWrapped(){return this.wrapped}logApiRequest(e,n,o){let i=JSON.stringify(e);Xe(this.config,new et(n,o,i,P.getStore()))}_logApiResponse(e,n,o,i,r,a){Qe(this.config,new nt(e,o,n,i,this.generatorAuthType,r,a,P.getStore()))}_logApiError(e,n,o,i,r){let a=qe(o),s=H(o),l=o?.requestID||o?.request_id||e,d=j(o);Ze(this.config,new tt({responseId:l,model:i,durationMs:n,promptId:r,authType:this.generatorAuthType,errorMessage:a,errorType:s,statusCode:d,subagentName:P.getStore()}))}safelyLogApiError(e,n,o,i,r){try{this._logApiError(e,n,o,i,r)}catch(a){D.warn("Failed to log API error:",a)}}safelyLogApiResponse(e,n,o,i,r,a){try{this._logApiResponse(e,n,o,i,r,a)}catch(s){D.warn("Failed to log API response:",s)}}async generateContent(e,n){let o=wt(),i=be(e.model,n);try{i.setAttribute("llm_request.stream",!1)}catch{}let r=Se.setSpan(k.active(),i),a=Date.now(),s=K(n),l=this.startCaptureSession();try{Ie.recordGenerateContentRequest(e,{stream:!1,source:"generateContent"}),s||(ve(this.config,i,e.config?.systemInstruction),_e(this.config,i,e.config?.tools));let d=await k.with(r,async()=>{s||this.logApiRequest(this.toContents(e.contents),e.model,n);let c=await l.wrap(()=>this.wrapped.generateContent(e,n)),g=Date.now()-a,u=s?void 0:this.extractResponseText(c);s||xe(this.config,i,u),this.safelyLogApiResponse(c.responseId??"",g,c.modelVersion||e.model,n,c.usageMetadata,u);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),c,void 0,n)}catch(m){D.warn("Failed to log OpenAI interaction:",m)}return c});return F(i,{success:!0,inputTokens:d.usageMetadata?.promptTokenCount,outputTokens:d.usageMetadata?.candidatesTokenCount,cachedInputTokens:d.usageMetadata?.cachedContentTokenCount,durationMs:Date.now()-a,responseId:d.responseId||void 0,finishReason:d.candidates?.[0]?.finishReason||void 0,thoughtsTokenCount:d.usageMetadata?.thoughtsTokenCount,subagentName:P.getStore()||void 0,...o}),d}catch(d){let c=Date.now()-a,g=e.config?.abortSignal?.aborted??!1;throw F(i,{success:!1,durationMs:c,error:g?ee:Q,errorType:H(d),errorStatusCode:j(d),subagentName:P.getStore()||void 0,...o}),await k.with(r,async()=>{this.safelyLogApiError("",c,d,e.model,n);try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,d,n)}catch(u){D.warn("Failed to log OpenAI interaction:",u)}}),d}}async generateContentStream(e,n){let o=wt(),i=be(e.model,n);try{i.setAttribute("llm_request.stream",!0)}catch{}let r=Se.setSpan(k.active(),i),a=Date.now(),s=K(n),l=this.startCaptureSession(),d;try{Ie.recordGenerateContentRequest(e,{stream:!0,source:"generateContentStream"}),s||(ve(this.config,i,e.config?.systemInstruction),_e(this.config,i,e.config?.tools)),d=await k.with(r,async()=>(s||this.logApiRequest(this.toContents(e.contents),e.model,n),l.wrap(()=>this.wrapped.generateContentStream(e,n))))}catch(g){let u=Date.now()-a;k.with(r,()=>this.safelyLogApiError("",u,g,e.model,n));let m=e.config?.abortSignal?.aborted??!1;F(i,{success:!1,durationMs:u,error:m?ee:Q,errorType:H(g),errorStatusCode:j(g),subagentName:P.getStore()||void 0,...o});try{await this.safelyLogOpenAIInteraction(await l.resolve(e),void 0,g,n)}catch(h){D.warn("Failed to log OpenAI interaction:",h)}throw g}let c;if(this.openaiLogger)try{c=await l.resolve(e)}catch(g){D.warn("Failed to resolve OpenAI request:",g)}return k.with(r,()=>this.loggingStreamWrapper(d,a,n,e.model,c,i,r,e.config?.abortSignal,o))}startCaptureSession(){let e,n=!this.openaiLogger;return{wrap:o=>n?o():bt.run(i=>{e=i},o),resolve:async o=>this.openaiLogger?e??await this.buildOpenAIRequestForLogging(o):void 0}}async*loggingStreamWrapper(e,n,o,i,r,a,s,l,d){let c=K(o),g=!c||!!this.openaiLogger,u=[],m="",h="",p,C=!1,y,T,S=P.getStore(),R,z=!1,X=v=>s?k.with(s,v):v(),Ht=5*6e4,I,We=a?()=>{z||(I!==void 0&&clearTimeout(I),I=setTimeout(()=>{try{a.setAttribute("stream.timed_out",!0)}catch{}F(a,{success:!1,durationMs:Date.now()-n,error:"Stream span timed out (idle)",responseId:m||void 0,subagentName:S||void 0,...d}),z=!0},Ht),I.unref())}:void 0;We?.();try{for await(let x of e){!m&&x.responseId&&(m=x.responseId),!h&&x.modelVersion&&(h=x.modelVersion),g&&u.push(x),x.usageMetadata&&(p=x.usageMetadata);let Je=x.candidates?.[0];Je?.finishReason&&(y=Je.finishReason),R===void 0&&It(x)&&(R=Date.now()-n),We?.(),yield x}I!==void 0&&(clearTimeout(I),I=void 0);let v=Date.now()-n,Z=g?this.consolidateGeminiResponsesForLogging(u):void 0,Ve=c?void 0:this.extractResponseText(Z);z||(X(()=>this.safelyLogApiResponse(m,v,h||i,o,p,Ve)),!c&&a&&xe(this.config,a,Ve),await X(()=>this.safelyLogOpenAIInteraction(r,Z,void 0,o)))}catch(v){if(C=!0,T=v,!z){let Z=Date.now()-n;X(()=>this.safelyLogApiError(m,Z,v,h||i,o)),await X(()=>this.safelyLogOpenAIInteraction(r,void 0,v,o))}throw v}finally{if(I!==void 0&&clearTimeout(I),a&&!z){let v=l?.aborted??!1;F(a,{success:!C,inputTokens:p?.promptTokenCount,outputTokens:p?.candidatesTokenCount,cachedInputTokens:p?.cachedContentTokenCount,ttftMs:R,durationMs:Date.now()-n,error:C?v?ee:Q:void 0,responseId:m||void 0,finishReason:y,thoughtsTokenCount:p?.thoughtsTokenCount,subagentName:S||void 0,errorType:T?H(T):void 0,errorStatusCode:T?j(T):void 0,...d})}}}async buildOpenAIRequestForLogging(e){if(!this.openaiLogger)return;let n=this.createLoggingRequestContext(e.model),o=ne.convertGeminiRequestToOpenAI(e,n,{cleanOrphanToolCalls:!1}),i={model:e.model,messages:o};return e.config?.tools&&(i.tools=await ne.convertGeminiToolsToOpenAI(e.config.tools,this.schemaCompliance??"auto")),e.config?.temperature!==void 0&&(i.temperature=e.config.temperature),e.config?.topP!==void 0&&(i.top_p=e.config.topP),e.config?.maxOutputTokens!==void 0&&(i.max_tokens=e.config.maxOutputTokens),e.config?.presencePenalty!==void 0&&(i.presence_penalty=e.config.presencePenalty),e.config?.frequencyPenalty!==void 0&&(i.frequency_penalty=e.config.frequencyPenalty),i}createLoggingRequestContext(e){return{model:e,modalities:this.modalities??{},splitToolMedia:this.splitToolMedia??!0,startTime:0}}async logOpenAIInteraction(e,n,o,i){if(!this.openaiLogger||!e)return;let r=n?this.convertGeminiResponseToOpenAIForLogging(n,e):void 0;await this.openaiLogger.logInteraction(e,r,o instanceof Error?o:o?new Error(String(o)):void 0,i)}async safelyLogOpenAIInteraction(e,n,o,i){try{await this.logOpenAIInteraction(e,n,o,i)}catch(r){D.warn("Failed to log OpenAI interaction:",r)}}convertGeminiResponseToOpenAIForLogging(e,n){return ne.convertGeminiResponseToOpenAI(e,this.createLoggingRequestContext(n.model))}consolidateGeminiResponsesForLogging(e){if(e.length===0)return;let n=new B,o=[],i=new Map,r,a;for(let d of e){d.usageMetadata&&(a=d.usageMetadata);let c=d.candidates?.[0];c?.finishReason&&(r=c.finishReason);let g=c?.content?.parts??[];for(let u of g){if(typeof u=="string"){o.push({text:u});continue}if("text"in u){u.text&&o.push({text:u.text,...u.thought?{thought:!0}:{},...u.thoughtSignature?{thoughtSignature:u.thoughtSignature}:{}});continue}if("functionCall"in u&&u.functionCall){let m=u.functionCall.id||u.functionCall.name||"tool_call",h=i.get(m),p={functionCall:u.functionCall};h!==void 0?o[h]=p:(i.set(m,o.length),o.push(p));continue}if("functionResponse"in u&&u.functionResponse){o.push({functionResponse:u.functionResponse});continue}o.push(u)}}let s=e[e.length-1],l=s.candidates?.[0];return n.responseId=s.responseId,n.createTime=s.createTime,n.modelVersion=s.modelVersion,n.promptFeedback=s.promptFeedback,n.usageMetadata=a,n.candidates=[{content:{role:l?.content?.role||"model",parts:o},...r?{finishReason:r}:{},index:0,safetyRatings:l?.safetyRatings||[]}],n}extractResponseText(e){let n=e?.candidates?.[0]?.content?.parts;if(!n?.length)return;let o="",i=!1,r=!1,a=s=>{if(i=!0,r)return;let l=_n-o.length;if(s.length<=l){o+=s;return}o+=s.slice(0,Math.max(0,l)),r=!0};for(let s of n){if(typeof s=="string"){a(s);continue}"text"in s&&typeof s.text=="string"&&!("thought"in s&&s.thought)&&a(s.text)}if(i)return r?`${o}${Rt}`:o}async countTokens(e){return this.wrapped.countTokens(e)}async embedContent(e){return this.wrapped.embedContent(e)}useSummarizedThinking(){return this.wrapped.useSummarizedThinking()}toContents(e){return Array.isArray(e)?e.map(n=>this.toContent(n)):[this.toContent(e)]}toContent(e){return Array.isArray(e)?{role:"user",parts:this.toParts(e)}:typeof e=="string"?{role:"user",parts:[{text:e}]}:"parts"in e?{...e,parts:e.parts?this.toParts(e.parts.filter(n=>n!=null)):[]}:{role:"user",parts:[this.toPart(e)]}}toParts(e){return e.map(n=>this.toPart(n))}toPart(e){if(typeof e=="string")return{text:e};if("thought"in e&&e.thought){let n=`[Thought: ${e.thought}]`,o={...e};if(delete o.thought,"functionCall"in o||"functionResponse"in o||"inlineData"in o||"fileData"in o)return o;let r=o.text,a=r?String(r):"",s=a?`${a}
8
8
  ${n}`:n;return{...o,text:s}}return e}};f();function Pt(t){switch(t){case"openai":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}function Et(t){switch(t){case"openai":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}var O=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},ue=class extends O{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let i=e||"(unknown)",r=n||"(unknown)";super(`Missing credentials for modelProviders model '${r}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${i}[].envKey.`:`Configure modelProviders.${i}[].envKey and set that environment variable.`))}},pe=class extends O{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},ge=class extends O{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},fe=class extends O{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},he=class extends O{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},me=class extends O{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};f();import bn from"node:process";f();var Ot={image:!0,pdf:!0,audio:!0,video:!0},xn=[[/^gemini-3/,Ot],[/^gemini-/,Ot],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^deepseek/,{}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^minimax-m3/i,{image:!0,video:!0}],[/^minimax-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function q(t){let e=at(t);for(let[n,o]of xn)if(n.test(e))return{...o};return{}}f();var Ut=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new Ce(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=e.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||U}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values(G),o=new Set,i=[];for(let l of n)o.has(l)||(o.add(l),i.push(l));let r=[];i.includes("matilda-oauth")&&r.push("matilda-oauth");for(let l of i)l!=="matilda-oauth"&&r.push(l);let a=this.getRuntimeModelOption(),s=[];for(let l of r)a&&a.authType===l&&s.push(a),s.push(...this.modelRegistry.getModelsForAuthType(l));return s}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}getModelDisplayName(e){return this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===U){this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.onModelChange&&await this.onModelChange("matilda-oauth",!1);return}if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(i){throw this.rollbackToStateSnapshot(o),i}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=q(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=W(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let i=this.extractRuntimeModelSnapshotId(n);if(i){await this.switchToRuntimeModel(i);return}let r=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let a=e!==this.currentAuthType;this.currentAuthType=e;let s=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!s)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=r.generationConfig.model||"",d=!a&&l?this.modelRegistry.getModel(e,l,r.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,c=e!=="matilda-oauth"&&!a&&!!r.generationConfig.apiKey&&!!s.envKey&&d?.envKey===s.envKey&&d.baseUrl===s.baseUrl,g=c?r.generationConfig.apiKey:void 0,u=c?r.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(s),!this._generationConfig.apiKey&&g&&(this._generationConfig.apiKey=g,u&&(this.generationConfigSources.apiKey=t.deepClone(u))),this.activeRuntimeModelSnapshotId=void 0;let m=a?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,m)}catch(a){throw this.rollbackToStateSnapshot(r),a}}buildRuntimeModelSnapshotId(e,n){return`${se}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(se))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of le)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:i}=this._generationConfig;if(!(!n||!e||!o||!i)&&!this.modelRegistry.hasModel(e,n,i))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let r=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);r.apiKey=o,r.baseUrl=i,r.modelId=n;let a=this.buildRuntimeModelSnapshotId(r.authType,r.modelId);a!==r.id&&(this.runtimeModelSnapshots.delete(r.id),r.id=a,this.runtimeModelSnapshots.set(a,r),this.activeRuntimeModelSnapshotId=a),r.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let e of de)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let e=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,e}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"model.id"},this.currentAuthType==="matilda-oauth"?(this._generationConfig.apiKey="MATILDA_OAUTH_DYNAMIC_TOKEN",this.generationConfigSources.apiKey={kind:"computed",detail:"Matilda OAuth placeholder token"},this._generationConfig.apiKeyEnvKey=void 0,delete this.generationConfigSources.apiKeyEnvKey):(this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0),e.envKey!==void 0){let o=bn.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=e.generationConfig;for(let o of le)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=W(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=q(e.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(e){let n=this.currentAuthType;if(!n)return!0;if(n==="matilda-oauth")return!1;let o=this.modelRegistry.getModel(n,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0),i=this.modelRegistry.getModel(n,e);return!i||!o||i.envKey!==o.envKey||i.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let i=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,r=n?this.modelRegistry.getModel(e,n,i)??this.modelRegistry.getModel(e,n):void 0;if(r){let m=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==r.envKey||this._generationConfig.baseUrl!==r.baseUrl),h=o===e&&this._generationConfig.model===n&&!m,p=h?this._generationConfig.apiKey:void 0,C=h&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,y=this.generationConfigSources.baseUrl,T=h&&!!this._generationConfig.baseUrl&&(y?.kind==="cli"||y?.kind==="env"||y?.kind==="settings"),S=T?this._generationConfig.baseUrl:void 0,R=T&&y?{...y}:void 0;this.applyResolvedModelDefaults(r),h&&!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let a=this.generationConfigSources.apiKey,s=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&a?.kind!=="modelProviders"||this._generationConfig.baseUrl&&s?.kind!=="modelProviders";if(!(o!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let g=this.modelRegistry.getDefaultModelForAuthType(e);if(g){this.applyResolvedModelDefaults(g),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,...r}=this._generationConfig,a=this.currentAuthType;if(!e||!a)return;if(this.modelRegistry.hasModel(a,e,o)){this.clearRuntimeModelSnapshotForAuthType(a);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(a,e),d={id:l,authType:a,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:i,generationConfig:r,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,d),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{let i=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig);let r=i;this.onModelChange&&await this.onModelChange(n.authType,r)}catch(i){throw this.rollbackToStateSnapshot(o),i}}getRuntimeModelOption(){let e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};f();import{readFileSync as jn}from"node:fs";import{join as Hn}from"node:path";f();f();import{randomBytes as In,createHash as kn}from"node:crypto";function Lt(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function Le(){let t=In(32).toString("base64url"),e=kn("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Y(t,e){return{accessToken:t.access_token,refreshToken:t.refresh_token??e?.refreshToken,expiresAt:Date.now()+(t.expires_in??3600)*1e3,idToken:t.id_token??e?.idToken}}async function De(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!Lt(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"}});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let i=await o.json();if(!i.issuer||!i.authorization_endpoint||!i.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:i.issuer,authorization_endpoint:i.authorization_endpoint,token_endpoint:i.token_endpoint,device_authorization_endpoint:i.device_authorization_endpoint}}f();import{promises as ye,openSync as wn,closeSync as Rn,unlinkSync as Dt,statSync as Pn}from"node:fs";import{dirname as En}from"node:path";var On=1e4,Un=3e4,Ln=50;function Ge(t){let e=async()=>{try{let i=await ye.readFile(t,"utf8"),r=JSON.parse(i);return r&&typeof r=="object"?r:{}}catch(i){if(i.code==="ENOENT")return{};throw i}},n=async i=>{await ye.mkdir(En(t),{recursive:!0}),await ye.writeFile(t,JSON.stringify(i,null,2),{mode:384}),await ye.chmod(t,384).catch(()=>{})};return{store:{async get(i){return(await e())[i]??null},async set(i,r){let a=await e();a[i]=r,await n(a)},async remove(i){let r=await e();i in r&&(delete r[i],await n(r))}},lock:Dn(`${t}.lock`)}}function Dn(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Gn(t);try{return await n()}finally{Nn(t)}});return e=o.then(()=>{},()=>{}),o}}async function Gn(t){let e=Date.now()+On;for(;;)try{Rn(wn(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-Pn(t).mtimeMs>Un){Dt(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Kn(Ln)}}function Nn(t){try{Dt(t)}catch{}}function Kn(t){return new Promise(e=>setTimeout(e,t))}f();var $=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Ne(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,i=null,r=async()=>{let l=await t.store.get(e);if(!l)return null;try{let d=JSON.parse(l);return d.accessToken?d:null}catch{return null}},a=l=>l.expiresAt-Date.now()>o,s=l=>t.lock(async()=>{let d=await r()??l;if(d.accessToken!==l.accessToken&&a(d))return d.accessToken;if(!d.refreshToken)throw new $("No refresh token available \u2014 sign in again.");let c=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:d.refreshToken})});if(!c.ok){let m=await c.text().catch(()=>"");throw c.status>=400&&c.status<500&&Fn(m)==="invalid_grant"?(await t.store.remove(e),new $):new Error(`Token refresh failed (${c.status})`)}let g=await c.json(),u=Y(g,d);return await t.store.set(e,JSON.stringify(u)),u.accessToken});return{async getAccessToken(l){let d=await r();if(!d)throw new $("Not signed in.");return!l?.forceRefresh&&a(d)?d.accessToken:(i||(i=s(d).finally(()=>{i=null})),i)}}}function Fn(t){try{return JSON.parse(t).error}catch{return}}f();import{createServer as $n}from"node:http";import{randomBytes as zn}from"node:crypto";async function Ke(t){if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=h=>t.onEvent?.(h),{codeVerifier:n,codeChallenge:o}=Le(),i=zn(16).toString("hex"),r=t.timeoutMs??5*60*1e3,a=t.transport.successRedirect;e({type:"state",status:"idle"});let s,l,d=new Promise((h,p)=>{s=h,l=p});d.catch(()=>{});let c=$n((h,p)=>{let C=new URL(h.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){p.writeHead(404).end();return}let y=C.searchParams.get("error"),T=C.searchParams.get("state"),S=C.searchParams.get("code");if(y){Gt(p,a,()=>l(new Error(`OAuth error: ${y}`)));return}if(T!==i){p.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){p.writeHead(400).end("Missing authorization code");return}Gt(p,a,()=>s(S))}),g=await new Promise((h,p)=>{c.once("error",p),c.listen(t.transport.port??0,"127.0.0.1",()=>{h(c.address().port)})}),u=setTimeout(()=>l(new Error("Login timed out \u2014 no callback received")),r),m=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",m,{once:!0});try{let h=`http://127.0.0.1:${g}/callback`,p=new URL(t.metadata.authorization_endpoint);p.searchParams.set("client_id",t.clientId),p.searchParams.set("response_type","code"),p.searchParams.set("redirect_uri",h),p.searchParams.set("code_challenge",o),p.searchParams.set("code_challenge_method","S256"),p.searchParams.set("state",i),p.searchParams.set("scope",t.scope??"openid offline_access");let C=p.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let y=await d;e({type:"state",status:"exchanging"});let T=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:y,code_verifier:n,redirect_uri:h})});if(!T.ok){let R=await T.text().catch(()=>"");throw new Error(`Token exchange failed (${T.status}): ${R}`)}let S=Y(await T.json());return e({type:"state",status:"authenticated"}),S}catch(h){throw e({type:"state",status:"error"}),h}finally{clearTimeout(u),t.signal?.removeEventListener("abort",m),c.close()}}function Gt(t,e,n){t.writeHead(302,{location:e}).end(n)}var Fe="matilda-code",Te="MATILDA_API_KEY",Bn="openid profile email offline_access matilda:code",Ae="matilda";function $e(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Nt(){return Hn(Ye.getGlobalMatildaDir(),"matilda-auth.json")}function ze(){return Ge(Nt())}function Wn(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function Vn(t,e){let n=Wn(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}async function Kt(t){try{return await De(t)}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function N(){try{let t=jn(Nt(),"utf8"),n=JSON.parse(t)[Ae];if(!n)return null;let o=JSON.parse(n);return typeof o?.accessToken=="string"&&typeof o?.baseUrl=="string"?o:null}catch{return null}}async function Jn(t){await ze().store.set(Ae,JSON.stringify(t)),process.env[Te]=t.accessToken}async function qn(){await ze().store.remove(Ae),delete process.env[Te]}function gr(){let t=N();return t?{authenticated:!0,userId:t.userId,email:t.email,displayName:t.displayName,baseUrl:t.baseUrl,accessTokenExpiresAt:t.accessTokenExpiresAt}:{authenticated:!1}}async function fr(t){let e=N();if(e?.accessToken){let n=$e(e.baseUrl);await fetch(`${n}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(e.refreshToken?{refreshToken:e.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await qn()}async function je(t){let e=N();if(!e||t?.baseUrl&&e.baseUrl!==t.baseUrl)return t?.fallbackAccessToken??process.env[Te]??"";let n=$e(e.baseUrl),o=await Kt(n),{store:i,lock:r}=ze(),s=await Yn(i,r,o.token_endpoint,e.baseUrl,t?.signal).getAccessToken({forceRefresh:t?.forceRefresh});return process.env[Te]=s,s}async function hr(){await je();let t=N();if(!t)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return t}function Yn(t,e,n,o,i){return Ne({tokenEndpoint:n,clientId:Fe,store:{get:async s=>{let l=JSON.parse(await t.get(s)??"{}");if(!l.accessToken)return null;let d={accessToken:l.accessToken,refreshToken:l.refreshToken,expiresAt:l.accessTokenExpiresAt};return JSON.stringify(d)},set:async(s,l)=>{let d=JSON.parse(l),c=JSON.parse(await t.get(s)??"{}"),g={...c,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??c.refreshToken??"",baseUrl:c.baseUrl??o};await t.set(s,JSON.stringify(g))},remove:s=>t.remove(s)},storageKey:Ae,lock:e,fetchImpl:(s,l)=>fetch(s,{...l,signal:i})})}async function mr(t){let e=$e(t.baseUrl),n=await Kt(e),o="",i=s=>Ke({metadata:n,clientId:Fe,scope:s,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(Fe)}`},signal:t.signal,onEvent:l=>{l.type==="authorize_url"&&(o=l.url,t.onAuthorizeUrl?.(l.url))},openBrowser:async l=>{if(t.openBrowser===!1||process.env.MATILDA_AUTH_SKIP_BROWSER==="1")return;let{default:d}=await import("./open-QQ7FWG4A.js");await d(l).catch(()=>{})}}),r;try{r=await i(Bn)}catch(s){if(s instanceof Error&&s.message.includes("invalid_scope"))r=await i("openid offline_access");else throw s}let a=Vn(r,t.baseUrl);return await Jn(a),{...a,authorizeUrl:o}}var G=(r=>(r.USE_OPENAI="openai",r.MATILDA_OAUTH="matilda-oauth",r.USE_GEMINI="gemini",r.USE_VERTEX_AI="vertex-ai",r.USE_ANTHROPIC="anthropic",r))(G||{}),Xn="MATILDA_AGENT_SDK",Me="MATILDA_API_KEY";function Zn(t){if(t.apiKey||t.apiKeyEnvKey!==Me)return;let e=N();e?.accessToken&&(t.apiKey=e.accessToken,process.env[Me]=e.accessToken)}async function Qn(t){if(t.apiKeyEnvKey!==Me)return;let e=N();if(!e?.accessToken)return;let n=await je({baseUrl:t.baseUrl,fallbackAccessToken:e.accessToken});n&&(t.apiKey=n,process.env[Me]=n)}function eo(t){return t.matildaAgentSdk===!0||process.env[Xn]==="1"}function He(t,e,n){t[e]=n}function to(t,e){return t?.[e]}function no(t,e,n,o,i){let r={...o||{}},a=i?.strictModelProvider===!0,s={...n||{},authType:e,proxy:t?.getProxy()};He(r,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&He(r,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=c=>to(o,c)??{kind:"unknown"};for(let c of de)n&&c in n&&!r[c]&&He(r,c,l(c));Zn(s);let d=$t(s,a);if(!d.valid)throw new Error(d.errors.map(c=>c.message).join(`
9
9
  `));return{config:s,sources:r}}function $t(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new ue(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Pt(t.authType);n.push(new ge({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new pe(t.authType));else{let o=Et(t.authType);n.push(new fe({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new he({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new me)),{valid:n.length===0,errors:n}}function vr(t,e,n){return no(t,e,n).config}function Ft(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function _r(t,e,n){await Qn(t);let o=$t(t,!1);if(!o.valid)throw new Error(o.errors.map(a=>a.message).join(`
10
- `));let i=t.authType;if(!i)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(i==="openai")if(eo(t)){let{createMatildaAgentContentGenerator:a}=await import("./matildaAgentContentGenerator-QLZEASVN.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-LBEDAHRX.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-2IUZAZEO.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-TGCMZZC6.js");try{let l=await a(e,n?{requireCachedCredentials:!0}:void 0);r=new s(l,t,e)}catch(l){throw Ft(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(i==="anthropic"){let{createAnthropicContentGenerator:a}=await import("./anthropicContentGenerator-BRG6WZK3.js");r=a(t,e)}else if(i==="gemini"||i==="vertex-ai"){let{createGeminiContentGenerator:a}=await import("./geminiContentGenerator-56OUN5BI.js");r=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${i}`)}catch(a){let s=Ft(a);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
10
+ `));let i=t.authType;if(!i)throw new Error("ContentGeneratorConfig must have an authType");let r;try{if(i==="openai")if(eo(t)){let{createMatildaAgentContentGenerator:a}=await import("./matildaAgentContentGenerator-O54RMUHJ.js");r=a(t,e)}else{let{createOpenAIContentGenerator:a}=await import("./openaiContentGenerator-4D5JS26Z.js");r=a(t,e)}else if(i==="matilda-oauth"){let{getMatildaOAuthClient:a}=await import("./matildaOAuth2-2IUZAZEO.js"),{MatildaContentGenerator:s}=await import("./matildaContentGenerator-UXLQXYIJ.js");try{let l=await a(e,n?{requireCachedCredentials:!0}:void 0);r=new s(l,t,e)}catch(l){throw Ft(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(i==="anthropic"){let{createAnthropicContentGenerator:a}=await import("./anthropicContentGenerator-BRG6WZK3.js");r=a(t,e)}else if(i==="gemini"||i==="vertex-ai"){let{createGeminiContentGenerator:a}=await import("./geminiContentGenerator-AHPUJXRJ.js");r=a(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${i}`)}catch(a){let s=Ft(a);throw s?new Error(`Matilda was updated in the background and needs to be restarted.
11
11
  Please exit and restart Matilda to use the '${i}' provider.`,{cause:s}):a}return new J(r,e,t)}var Be=b("MODEL_REGISTRY");function zt(t){if(Object.values(G).includes(t))return t}function oo(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function jt(t,e){return e?`${t}\0${e}`:t}var Ce=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return st;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",ce),e)for(let[n,o]of Object.entries(e)){let i=zt(n);if(!i){Be.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let i of n){let r=jt(i.id,i.baseUrl);if(o.has(r)){Be.warn(`Duplicate model id "${i.id}"${i.baseUrl?` with baseUrl "${i.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let a=this.resolveModelConfig(i,e);o.set(r,a)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??W(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let i=this.modelsByAuthType.get(e);if(!i)return;if(o)return i.get(jt(n,o));let r=i.get(n);if(r)return r;for(let a of i.values())if(a.id===n)return a}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,U);let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){this.validateModelConfig(e,n);let o={...e.generationConfig??{}};return(o.modalities===void 0||oo(e.id))&&(o.modalities=q(e.id)),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(e)for(let[n,o]of Object.entries(e)){let i=zt(n);if(!i){Be.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}i!=="matilda-oauth"&&this.registerAuthTypeModels(i,o)}}};export{we as a,ne as b,bt as c,hn as d,V as e,Lo as f,kt as g,q as h,se as i,No as j,le as k,zo as l,jo as m,ce as n,Ho as o,jt as p,Ce as q,Ut as r,Nt as s,N as t,Jn as u,qn as v,gr as w,fr as x,je as y,hr as z,mr as A,G as B,no as C,$t as D,vr as E,_r as F};
12
12
  /**
13
13
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{f}from"./chunk-R3H6IWFK.js";import{f as u}from"./chunk-QKYGQLWC.js";import{g as m,i as c,p as l,q as p}from"./chunk-X6DODPXG.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();var o=2e3;function T(e){return e.length<=o?e:`${e.slice(0,o)}
3
+ import{f}from"./chunk-R3H6IWFK.js";import{f as u}from"./chunk-QKYGQLWC.js";import{g as m,i as c,p as l,q as p}from"./chunk-5U3A6KMU.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};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as l}from"./chunk-4F4DA5UI.js";import{e as g}from"./chunk-X6DODPXG.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();import{readFile as m}from"node:fs/promises";function c(n){return n?`side-query:${n}`:"side-query"}function y(n,e){return e??n.getFastModel?.()??n.getModel()??l}function S(n){let e=n?.thinkingConfig;return{...n??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function T(n){let e=n.getOutputLanguageFilePath?.();if(e)try{let t=(await m(e,"utf8")).trim();return t?["Follow the user-visible output language preference below for this side query.",t].join(`
3
+ import{a as l}from"./chunk-4F4DA5UI.js";import{e as g}from"./chunk-5U3A6KMU.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();import{readFile as m}from"node:fs/promises";function c(n){return n?`side-query:${n}`:"side-query"}function y(n,e){return e??n.getFastModel?.()??n.getModel()??l}function S(n){let e=n?.thinkingConfig;return{...n??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function T(n){let e=n.getOutputLanguageFilePath?.();if(e)try{let t=(await m(e,"utf8")).trim();return t?["Follow the user-visible output language preference below for this side query.",t].join(`
4
4
 
5
5
  `):void 0}catch{return}}function x(n,e){return e?n===void 0?e:typeof n=="string"?`${n}
6
6
 
@@ -1,10 +1,10 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{sh as T}from"./chunk-ZX6WKO3S.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var W=e=>{process.stdout.write(e.endsWith(`
3
+ import{$g as T}from"./chunk-GV5WGCQ4.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var W=e=>{process.stdout.write(e.endsWith(`
4
4
  `)?e:`${e}
5
5
  `)},m=e=>{process.stderr.write(e.endsWith(`
6
6
  `)?e:`${e}
7
- `)},G=()=>{console.clear()};o();import*as c from"node:fs";import*as f from"node:path";import{pathToFileURL as E}from"node:url";o();var l=[{code:"en",id:"en-US",fullName:"English",nativeName:"English"},{code:"zh-TW",id:"zh-TW",fullName:"Traditional Chinese",nativeName:"\u7E41\u9AD4\u4E2D\u6587",strictParity:!0},{code:"zh",id:"zh-CN",fullName:"Chinese",nativeName:"\u4E2D\u6587",strictParity:!0},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function R(e){return e.trim().replace(/_/g,"-").toLowerCase()}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function U(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function u(e){let t=R(e);if(!t)return;let n;for(let r of l){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=U(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function M(e){let t=u(e);return(t?l.find(r=>r.code===t):void 0)?.fullName||"English"}function J(){return[{value:"auto",label:"Auto (detect from system)"},...l.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}function V(e="|"){return l.map(t=>t.id).join(e)}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var C=w({"./locales/ca.js":()=>import("./ca-D7YSARXX.js"),"./locales/de.js":()=>import("./de-ME75AM7Q.js"),"./locales/en.js":()=>import("./en-KVT5FJKO.js"),"./locales/fr.js":()=>import("./fr-V3O5JG5W.js"),"./locales/ja.js":()=>import("./ja-ZOFFSG6C.js"),"./locales/pt.js":()=>import("./pt-K2W3KMTP.js"),"./locales/ru.js":()=>import("./ru-KICZRPMQ.js"),"./locales/zh-TW.js":()=>import("./zh-TW-IYMR6KR3.js"),"./locales/zh.js":()=>import("./zh-C5PHBN3U.js")});var y="en",v={},s={},S={},P=()=>f.join(T(import.meta.url),"locales"),D=()=>f.join(b.getGlobalMatildaDir(),"locales");var N=(e,t=!1)=>{let n=t?D():P();return f.join(n,`${e}.js`)};function I(){let e=process.env.MATILDA_CODE_LANG||process.env.LANG;if(e){let t=u(e);if(t)return t}try{let t=Intl.DateTimeFormat().resolvedOptions().locale,n=u(t);if(n)return n}catch{}return"en"}async function A(e){try{let t=await import(e),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function O(e){try{let t=await C(`./locales/${e}.js`),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function $(e){if(s[e])return s[e];let t=S[e];if(t)return t;let n=(async()=>{let r=N(e,!0);if(c.existsSync(D())&&c.existsSync(r)){let i=await A(E(r).href);if(i.translations)return s[e]=i.translations,i.translations;m(`Failed to load translations from user directory for ${e}: ${i.error.message}`)}let a=N(e,!1),x=[];c.existsSync(P())&&c.existsSync(a)&&x.push(E(a).href);let d;for(let i of x){let p=await A(i);if(p.translations)return s[e]=p.translations,p.translations;d=p.error}let g=await O(e);return g.translations?(s[e]=g.translations,g.translations):(d=g.error,d&&m(`Failed to load JS translations for ${e}: ${d.message}`),s[e]={},{})})();return S[e]=n,n.finally(()=>{delete S[e]}),n}function j(e,t){return t?e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n):e}function z(e){return e==="auto"?I():u(e)??e}async function F(e){y=z(e),v=await $(y)}function se(){return y}function le(e,t){let n=v[e]??e;return Array.isArray(n)?e:j(n,t)}function ue(e){let t=v[e];return Array.isArray(t)?t:[]}async function ce(e){await F(e??"auto")}export{W as a,m as b,G as c,l as d,u as e,M as f,J as g,V as h,I as i,F as j,se as k,le as l,ue as m,ce as n};
7
+ `)},G=()=>{console.clear()};o();import*as c from"node:fs";import*as f from"node:path";import{pathToFileURL as E}from"node:url";o();var l=[{code:"en",id:"en-US",fullName:"English",nativeName:"English"},{code:"zh-TW",id:"zh-TW",fullName:"Traditional Chinese",nativeName:"\u7E41\u9AD4\u4E2D\u6587",strictParity:!0},{code:"zh",id:"zh-CN",fullName:"Chinese",nativeName:"\u4E2D\u6587",strictParity:!0},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function R(e){return e.trim().replace(/_/g,"-").toLowerCase()}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function U(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function u(e){let t=R(e);if(!t)return;let n;for(let r of l){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=U(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function M(e){let t=u(e);return(t?l.find(r=>r.code===t):void 0)?.fullName||"English"}function J(){return[{value:"auto",label:"Auto (detect from system)"},...l.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}function V(e="|"){return l.map(t=>t.id).join(e)}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var C=w({"./locales/ca.js":()=>import("./ca-UW3G7H5I.js"),"./locales/de.js":()=>import("./de-QSFN3SRK.js"),"./locales/en.js":()=>import("./en-77LGBBG5.js"),"./locales/fr.js":()=>import("./fr-FKTJ4COX.js"),"./locales/ja.js":()=>import("./ja-GKS4GLZP.js"),"./locales/pt.js":()=>import("./pt-VIW62ZAE.js"),"./locales/ru.js":()=>import("./ru-FSSACF4A.js"),"./locales/zh-TW.js":()=>import("./zh-TW-NAHJGTBA.js"),"./locales/zh.js":()=>import("./zh-LDF5IJ3D.js")});var y="en",v={},s={},S={},P=()=>f.join(T(import.meta.url),"locales"),D=()=>f.join(b.getGlobalMatildaDir(),"locales");var N=(e,t=!1)=>{let n=t?D():P();return f.join(n,`${e}.js`)};function I(){let e=process.env.MATILDA_CODE_LANG||process.env.LANG;if(e){let t=u(e);if(t)return t}try{let t=Intl.DateTimeFormat().resolvedOptions().locale,n=u(t);if(n)return n}catch{}return"en"}async function A(e){try{let t=await import(e),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function O(e){try{let t=await C(`./locales/${e}.js`),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function $(e){if(s[e])return s[e];let t=S[e];if(t)return t;let n=(async()=>{let r=N(e,!0);if(c.existsSync(D())&&c.existsSync(r)){let i=await A(E(r).href);if(i.translations)return s[e]=i.translations,i.translations;m(`Failed to load translations from user directory for ${e}: ${i.error.message}`)}let a=N(e,!1),x=[];c.existsSync(P())&&c.existsSync(a)&&x.push(E(a).href);let d;for(let i of x){let p=await A(i);if(p.translations)return s[e]=p.translations,p.translations;d=p.error}let g=await O(e);return g.translations?(s[e]=g.translations,g.translations):(d=g.error,d&&m(`Failed to load JS translations for ${e}: ${d.message}`),s[e]={},{})})();return S[e]=n,n.finally(()=>{delete S[e]}),n}function j(e,t){return t?e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n):e}function z(e){return e==="auto"?I():u(e)??e}async function F(e){y=z(e),v=await $(y)}function se(){return y}function le(e,t){let n=v[e]??e;return Array.isArray(n)?e:j(n,t)}function ue(e){let t=v[e];return Array.isArray(t)?t:[]}async function ce(e){await F(e??"auto")}export{W as a,m as b,G as c,l as d,u as e,M as f,J as g,V as h,I as i,F as j,se as k,le as l,ue as m,ce as n};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Matilda Team
@@ -0,0 +1,34 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{Y as p}from"./chunk-QWBNNEV2.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();var u=new Map;function de(e,t){return e===t?!0:!e||!t?!1:C(e)===C(t)}function C(e){let t={};for(let n of Object.keys(e).sort()){let o=e[n];o!==void 0&&(t[n]=o)}return JSON.stringify(t)}function v(e){return u.get(e)}function _(e,t){u.set(e,t)}function R(e){let t=u.get(e);return u.delete(e),t}function I(e,t){let n=u.get(e);if(!n)return;let o={...n,iterations:n.iterations+1,lastReason:t};return u.set(e,o),o}function ge(e,t,n){let o=u.get(e);if(!o)return;let i={...o,status:t,statusNote:t==="active"?void 0:n?.trim()||o.statusNote};return t==="active"&&delete i.statusNote,u.set(e,i),i}function L(e){return e.status??"active"}function fe(){u.clear(),b.clear(),k.clear()}var b=new Map;function pe(e,t){b.set(e,t)}function w(e){b.delete(e)}function M(e,t){B(e,t);let n=b.get(e);if(n)try{n(t)}catch{}}var k=new Map;function B(e,t){k.set(e,t)}function me(e){return k.get(e)}function ye(e,t){if(!t){k.delete(e);return}k.set(e,t)}g();g();var A=p("ERROR_REPORT");async function N(e,t,n,o="general"){let i;e instanceof Error?i={message:e.message,stack:e.stack}:typeof e=="object"&&e!==null&&"message"in e?i={message:String(e.message)}:i={message:String(e)};let r={error:i};n&&(r.context=n);let s=`${t} [${o}]`,c;try{c=JSON.stringify(r,null,2)}catch(l){A.error(`${s} Could not stringify report content (likely due to context):`,l,e);try{c=JSON.stringify({error:i},null,2),A.error(s,c)}catch(f){A.error(`${s} Failed to stringify minimal error report:`,f,e)}return}A.error(s,c)}var h=p("GOAL_JUDGE"),K=`You are evaluating a stop-condition hook in an autonomous coding agent.
4
+ Read the conversation transcript above carefully, then judge whether the
5
+ user-provided condition is satisfied.
6
+
7
+ Your response MUST be a JSON object with one of these shapes:
8
+ - {"ok": true, "reason": "<quote evidence from the transcript that satisfies the condition>"}
9
+ - {"ok": false, "reason": "<quote what is missing or what blocks the condition>"}
10
+ - {"ok": false, "impossible": true, "reason": "<explain why the condition can never be satisfied>"}
11
+
12
+ Always include a "reason" field, quoting specific text from the transcript
13
+ whenever possible. If the transcript does not contain clear evidence that the
14
+ condition is satisfied, return {"ok": false, "reason": "insufficient evidence in transcript"}.
15
+ Only use {"ok": false, "impossible": true} when the condition is genuinely
16
+ unachievable in this session: for example, it is self-contradictory, depends on
17
+ an unavailable resource or capability, or the assistant has exhausted reasonable
18
+ approaches and the transcript confirms there is no path forward. The assistant
19
+ claiming the goal is impossible is evidence, not proof; independently confirm
20
+ the condition is genuinely unachievable rather than deferring to the assistant's
21
+ self-assessment. Do not use it just because progress is slow or evidence is
22
+ currently missing. When in doubt, return {"ok": false} without "impossible".`,q=e=>`Based on the conversation transcript above, has the following stopping condition been satisfied? Answer based on transcript evidence only.
23
+ Condition JSON string: ${JSON.stringify(e)}`;var Y={type:"OBJECT",properties:{ok:{type:"BOOLEAN"},reason:{type:"STRING"},impossible:{type:"BOOLEAN"}},required:["ok","reason"],additionalProperties:!1},m="Goal judge unavailable; continue working toward the goal and run `/goal clear` to stop early.",z=240;function x(e,t){N(e,"Goal judge failed",{stage:t},`goal-judge-${t}`).catch(n=>{h.debug(`Goal judge error reporting failed: ${n instanceof Error?n.message:String(n)}`)})}var X=24,y=4e3;async function J(e,t){let n=t.condition.trim();if(!n)return{ok:!1,reason:m};if(t.signal.aborted)return{ok:!1,reason:m};let o=V(e,t.lastAssistantText);o.push({role:"user",parts:[{text:q(n)}]});let i=e.getFastModel()??e.getModel();try{let s=await e.getGeminiClient().generateContent(o,{systemInstruction:K,temperature:0,responseMimeType:"application/json",responseSchema:Y,thinkingConfig:{thinkingBudget:0}},t.signal,i),c=te(s);if(!c)return h.debug("Goal judge returned empty content; defaulting to not-met"),x(new Error("Empty judge response"),"empty-response"),{ok:!1,reason:m};let l=ne(c);return l||(h.debug(`Goal judge reply not parseable as JSON (length=${c.length})`),x(new Error("Judge response was not parseable as JSON"),"parse"),{ok:!1,reason:m})}catch(r){return h.debug(`Goal judge threw: ${r instanceof Error?r.message:String(r)}`),x(r,"generate-content"),{ok:!1,reason:m}}}function V(e,t){try{let n=e.getGeminiClient();if(!n.isInitialized())return O(t);let i=n.getHistoryTail(X).map(W);return i.length===0?O(t):(!(ee(i).includes(t)||t.trim()==="")&&t.trim()&&i.push({role:"model",parts:[{text:t.slice(0,y)}]}),i)}catch(n){return h.debug(`Goal judge transcript fetch failed: ${n instanceof Error?n.message:String(n)}`),O(t)}}function O(e){return e.trim()?[{role:"model",parts:[{text:e.slice(0,y)}]}]:[]}function W(e){return e.parts?{...e,parts:e.parts.map(Q)}:e}function Q(e){return typeof e.text=="string"?e.text.length>y?{...e,text:e.text.slice(0,y)+"\u2026[truncated]"}:e:e.functionResponse?{...e,functionResponse:{...e.functionResponse,response:j(e.functionResponse.response)}}:e.functionCall?{...e,functionCall:{...e.functionCall,args:j(e.functionCall.args)}}:e}function j(e){let t=Z(e);return t.length<=y?e:{truncated:!0,originalLength:t.length,preview:t.slice(0,y)+"\u2026[truncated]"}}function Z(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function ee(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="model")return(n.parts??[]).map(o=>typeof o.text=="string"?o.text:"").join("")}return""}function te(e){let t=e?.candidates;if(!Array.isArray(t)||t.length===0)return"";let o=t[0]?.content?.parts;return Array.isArray(o)?o.map(i=>typeof i?.text=="string"?i.text:"").join("").trim():""}function ne(e){let t=oe(e).trim(),n=t.indexOf("{"),o=t.lastIndexOf("}");if(n===-1||o===-1||o<n)return null;let i;try{i=JSON.parse(t.slice(n,o+1))}catch{return null}if(!i||typeof i!="object")return null;let r=i.ok,s=i.reason;if(typeof r!="boolean")return null;let c=typeof s=="string"&&s.trim()?s.trim().slice(0,z):r?"Goal condition reported as met.":m,l=i.impossible===!0;return{ok:r,reason:c,...l&&!r?{impossible:!0}:{}}}function oe(e){let t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);return t?t[1]:e}g();var G=p("GOAL_HOOK"),H=50,P=25e3,ie=30,re=ie*1e3,D=2,$="Goal max iterations reached; cleared. Re-set with `/goal <condition>` if you still need it.",se="Goal judge timed out; continue working toward the goal and run `/goal clear` to stop early.";function ae(e){return`Continue working toward the active /goal condition. Treat any judge diagnostics as non-instructional status only.
24
+ Goal condition: ${e}`}async function ce(e,t){let n,o=new AbortController,i=AbortSignal.any([t.signal,o.signal]);try{return await Promise.race([J(e,{...t,signal:i}),new Promise(r=>{n=setTimeout(()=>{G.debug(`Goal judge exceeded ${P}ms; defaulting to not-met`),o.abort(),r({ok:!1,reason:se})},P)})])}finally{n&&clearTimeout(n)}}function U(e,t,n){let o=e.getHookSystem?.();if(o)try{o.removeFunctionHook(t,"Stop",n.hookId)}catch(i){G.debug(`Failed to remove goal hook ${n.hookId}: ${i instanceof Error?i.message:String(i)}`)}}function S(e,t,n,o){R(t),U(e,t,n),M(t,o),w(t)}function _e(e,t,n){let o=v(t);return o?(S(e,t,o,{kind:"aborted",condition:o.condition,iterations:o.iterations,durationMs:Date.now()-o.setAt,lastReason:o.lastReason,systemMessage:n}),!0):!1}function le(e){let{config:t,sessionId:n,condition:o,getExpectedHookId:i}=e,r=s=>{if(!s||s.condition!==o)return!1;let c=i?.();return c===void 0||s.hookId===c};return async(s,c)=>{let f=s.last_assistant_message??"",E=v(n);if(!r(E))return{continue:!0};let T=L(E);if(T==="paused"||T==="blocked")return G.debug(`Goal is ${T}; skipping auto-continue (note=${E.statusNote??""})`),{continue:!0};let F=c?.signal??new AbortController().signal,d=await ce(t,{condition:o,lastAssistantText:f,signal:F}),a=v(n);return r(a)?d.ok?(S(t,n,a,{kind:"achieved",condition:a.condition,iterations:a.iterations,durationMs:Date.now()-a.setAt,lastReason:d.reason}),{continue:!0}):d.impossible&&a.iterations>=D?(G.debug("Goal judge ruled impossible; clearing goal.",{reason:d.reason,iterations:a.iterations}),S(t,n,a,{kind:"failed",condition:a.condition,iterations:a.iterations,durationMs:Date.now()-a.setAt,lastReason:d.reason}),{continue:!0}):(d.impossible&&G.debug(`Impossible goal verdict suppressed: iterations=${a.iterations} < MIN_IMPOSSIBLE_GOAL_ITERATIONS=${D}; continuing.`),a.iterations>=H?(G.debug(`Goal exceeded MAX_GOAL_ITERATIONS=${H}; clearing.`),S(t,n,a,{kind:"aborted",condition:a.condition,iterations:a.iterations,durationMs:Date.now()-a.setAt,lastReason:d.reason||a.lastReason,systemMessage:$}),{continue:!0,systemMessage:$}):(I(n,d.reason),{decision:"block",reason:ae(o)})):{continue:!0}}}function ue(e,t){let n=R(t);if(w(t),!!n)return U(e,t,n),n}function Ie(e){let{config:t,sessionId:n,condition:o,tokensAtStart:i}=e,r=t.getHookSystem();if(!r)throw new Error("Hook system is not initialized; cannot register /goal");ue(t,n);let s={},c=le({config:t,sessionId:n,condition:o,getExpectedHookId:()=>s.hookId}),l=r.addFunctionHook(n,"Stop","*",c,"Goal evaluator failed",{name:"goal-stop-hook",description:`Continue until: ${o}`,statusMessage:"Checking goal\u2026",timeout:re});s.hookId=l;let f={condition:o,status:"active",iterations:Math.max(0,e.initialIterations??0),setAt:Date.now(),tokensAtStart:i,hookId:l};return _(n,f),f}export{N as a,de as b,v as c,_ as d,R as e,I as f,ge as g,L as h,fe as i,pe as j,w as k,M as l,me as m,ye as n,J as o,H as p,ie as q,re as r,_e as s,le as t,ue as u,Ie as v};
25
+ /**
26
+ * @license
27
+ * Copyright 2026 Matilda Team
28
+ * SPDX-License-Identifier: Apache-2.0
29
+ */
30
+ /**
31
+ * @license
32
+ * Copyright 2025 Google LLC
33
+ * SPDX-License-Identifier: Apache-2.0
34
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ef as X,gf as H,ni as K}from"./chunk-ZX6WKO3S.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-S32ZN6LD.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-NRYMHT3V.js";import"./chunk-4F4DA5UI.js";import"./chunk-2MEHZGZJ.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{i as S}from"./chunk-DY6PIAAY.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-4M4CUQUR.js";import{g as B,i as G}from"./chunk-X6DODPXG.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as ye}from"node:os";d();import{join as I}from"node:path";import{homedir as R}from"node:os";var l="0.5.2",ue="https://matilda.maincode.com/assets/computer-use",me="https://github.com/trycua/cua/releases/download";function E(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 U(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ge(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${ue}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs-v${o}/${e}`),r}function J(e=process.env,t=l){return U("checksums.txt",e,t)}var he="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function V(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 Y(e,t=process.env){let o=V(t[he]);return o!==void 0?o:V(e)}function fe(e=R()){return I(e,".matilda","computer-use")}function N(e=R(),t=l){return I(fe(e),`cua-driver-rs-${t}`)}function u(e=R(),t=process.platform,o=process.arch,r=l){let i=E(t,o,r);return I(N(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ge(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(ye())})),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 H({command:this.binary,args:["mcp"],env:{...process.env}}),i=new X({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(!Q(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(!Q(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 Q(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 M=["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{Ne as X,Pe as H,Wh as K}from"./chunk-GV5WGCQ4.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-T3ERIC7X.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-YNR4LJMU.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-QE7JDD3Q.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{i as S}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as B,i as G}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as ye}from"node:os";d();import{join as I}from"node:path";import{homedir as R}from"node:os";var l="0.5.2",ue="https://matilda.maincode.com/assets/computer-use",me="https://github.com/trycua/cua/releases/download";function E(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 U(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ge(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${ue}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs-v${o}/${e}`),r}function J(e=process.env,t=l){return U("checksums.txt",e,t)}var he="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function V(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 Y(e,t=process.env){let o=V(t[he]);return o!==void 0?o:V(e)}function fe(e=R()){return I(e,".matilda","computer-use")}function N(e=R(),t=l){return I(fe(e),`cua-driver-rs-${t}`)}function u(e=R(),t=process.platform,o=process.arch,r=l){let i=E(t,o,r);return I(N(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ge(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(ye())})),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 H({command:this.binary,args:["mcp"],env:{...process.env}}),i=new X({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(!Q(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(!Q(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 Q(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 M=["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
 
@@ -0,0 +1,3 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as a,d as b,e as c}from"./chunk-LDSV6752.js";import"./chunk-TVWOSSXE.js";import"./chunk-GV5WGCQ4.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-T3ERIC7X.js";import"./chunk-OQ73WWR4.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-YNR4LJMU.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-QE7JDD3Q.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-LN2DRVOB.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as collectContextData,c as contextCommand,b as formatContextUsageText};
@@ -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-LQWORCPO.js";import"./chunk-TISQNFB5.js";import{g as m,i as c,p as d,q as h}from"./chunk-X6DODPXG.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.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-LQWORCPO.js";import"./chunk-TISQNFB5.js";import{g as m,i as c,p as d,q as h}from"./chunk-5U3A6KMU.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.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
 
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as d,f as u}from"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p as m,q as p}from"./chunk-X6DODPXG.js";import"./chunk-IOCF4XSR.js";import{c as n}from"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import{b as i}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";i();var s=class extends l{constructor(r,o){super(o);this.config=r}getDescription(){return this.params.id}async execute(){let r=this.config.getCronScheduler(),o;try{o=await r.delete(this.params.id),o||(o=await u(this.config.getProjectRoot(),[this.params.id])>0)}catch(e){let t=`Failed to cancel job ${this.params.id}: ${n(e)}`;return{llmContent:t,returnDisplay:t,error:{message:t}}}if(o){let e=`Cancelled job ${this.params.id}.`,t=`Cancelled ${this.params.id}`;return{llmContent:e,returnDisplay:t}}else{let e=`Job ${this.params.id} not found.`;return{llmContent:e,returnDisplay:e,error:{message:e}}}}},f=class a extends c{constructor(r){super(a.Name,p.CRON_DELETE,`Cancel a cron job previously scheduled with CronCreate. Removes it from the in-memory session store or from ${d} (durable jobs).`,"other",{type:"object",properties:{id:{type:"string",description:"Job ID returned by CronCreate."}},required:["id"],additionalProperties:!1},!0,!1,!0,!1,"cron delete cancel remove");this.config=r}static Name=m.CRON_DELETE;createInvocation(r){return new s(this.config,r)}};export{f as CronDeleteTool};
3
+ import{a as d,f as u}from"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p as m,q as p}from"./chunk-5U3A6KMU.js";import"./chunk-IOCF4XSR.js";import{c as n}from"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import{b as i}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";i();var s=class extends l{constructor(r,o){super(o);this.config=r}getDescription(){return this.params.id}async execute(){let r=this.config.getCronScheduler(),o;try{o=await r.delete(this.params.id),o||(o=await u(this.config.getProjectRoot(),[this.params.id])>0)}catch(e){let t=`Failed to cancel job ${this.params.id}: ${n(e)}`;return{llmContent:t,returnDisplay:t,error:{message:t}}}if(o){let e=`Cancelled job ${this.params.id}.`,t=`Cancelled ${this.params.id}`;return{llmContent:e,returnDisplay:t}}else{let e=`Job ${this.params.id} not found.`;return{llmContent:e,returnDisplay:e,error:{message:e}}}}},f=class a extends c{constructor(r){super(a.Name,p.CRON_DELETE,`Cancel a cron job previously scheduled with CronCreate. Removes it from the in-memory session store or from ${d} (durable jobs).`,"other",{type:"object",properties:{id:{type:"string",description:"Job ID returned by CronCreate."}},required:["id"],additionalProperties:!1},!0,!1,!0,!1,"cron delete cancel remove");this.config=r}static Name=m.CRON_DELETE;createInvocation(r){return new s(this.config,r)}};export{f as CronDeleteTool};
@@ -1,5 +1,5 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as m}from"./chunk-YULUB745.js";import{a as d,c as g}from"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p,q as u}from"./chunk-X6DODPXG.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var s=class extends l{constructor(e,t){super(t);this.config=e}getDescription(){return""}async execute(){let e=this.config.getCronScheduler(),t;try{t=await g(this.config.getProjectRoot())}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error listing cron jobs: ${o}`,returnDisplay:o,error:{message:o}}}let n=[...t.map(r=>({id:r.id,cron:r.cron,prompt:r.prompt,recurring:r.recurring,durable:!0})),...e.list().filter(r=>!r.durable).map(r=>({id:r.id,cron:r.cronExpr,prompt:r.prompt,recurring:r.recurring,durable:!1}))];if(n.length===0){let r="No active cron jobs.";return{llmContent:r,returnDisplay:r}}let y=n.map(r=>{let o=r.recurring?"recurring":"one-shot",h=r.durable?"durable":"session-only";return`${r.id} \u2014 ${r.cron} (${o}) [${h}]: ${r.prompt}`}).join(`
3
+ import{a as m}from"./chunk-YULUB745.js";import{a as d,c as g}from"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p,q as u}from"./chunk-5U3A6KMU.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var s=class extends l{constructor(e,t){super(t);this.config=e}getDescription(){return""}async execute(){let e=this.config.getCronScheduler(),t;try{t=await g(this.config.getProjectRoot())}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error listing cron jobs: ${o}`,returnDisplay:o,error:{message:o}}}let n=[...t.map(r=>({id:r.id,cron:r.cron,prompt:r.prompt,recurring:r.recurring,durable:!0})),...e.list().filter(r=>!r.durable).map(r=>({id:r.id,cron:r.cronExpr,prompt:r.prompt,recurring:r.recurring,durable:!1}))];if(n.length===0){let r="No active cron jobs.";return{llmContent:r,returnDisplay:r}}let y=n.map(r=>{let o=r.recurring?"recurring":"one-shot",h=r.durable?"durable":"session-only";return`${r.id} \u2014 ${r.cron} (${o}) [${h}]: ${r.prompt}`}).join(`
4
4
  `),T=n.map(r=>`${r.id} ${m(r.cron)} [${r.durable?"durable":"session-only"}]`).join(`
5
5
  `);return{llmContent:y,returnDisplay:T}}},f=class i extends c{constructor(e){super(i.Name,u.CRON_LIST,`List all cron jobs scheduled via CronCreate, both session-only and durable (${d}).`,"other",{type:"object",properties:{},additionalProperties:!1},!0,!1,!0,!1,"cron list scheduled jobs");this.config=e}static Name=p.CRON_LIST;createInvocation(e){return new s(this.config,e)}};export{f as CronListTool};