@maincode-ai/matilda-code 0.21.4 → 0.21.5-nightly.20260908.0d3c624bb

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 (97) hide show
  1. package/chunks/agent-HVAPKXWX.js +3 -0
  2. package/chunks/agent-headless-PUPP3RC4.js +3 -0
  3. package/chunks/{anthropicContentGenerator-EFVV6ZTA.js → anthropicContentGenerator-EAQDRKHH.js} +1 -1
  4. package/chunks/{askUserQuestion-MFLZ7MGJ.js → askUserQuestion-7II3GVHO.js} +1 -1
  5. package/chunks/{chunk-FUNLOUYI.js → chunk-2HFKTFO5.js} +1 -1
  6. package/chunks/{chunk-2NN5YPDR.js → chunk-4RJUXDH5.js} +1 -1
  7. package/chunks/chunk-5QAKUC2D.js +14 -0
  8. package/chunks/{chunk-3FI7EEYS.js → chunk-6UGZQN4B.js} +466 -465
  9. package/chunks/{chunk-5U3A6KMU.js → chunk-BGZJUBRA.js} +1 -1
  10. package/chunks/{chunk-SUORCDGS.js → chunk-BH56I7SB.js} +1 -1
  11. package/chunks/{chunk-C2ZWB2NT.js → chunk-FQ44TPC5.js} +1 -1
  12. package/chunks/{chunk-LQWORCPO.js → chunk-FW6Z25AA.js} +1 -1
  13. package/chunks/{chunk-ENMM2K4Q.js → chunk-GADNIYGB.js} +1 -1
  14. package/chunks/chunk-I5TKBEKD.js +32 -0
  15. package/chunks/{chunk-LCYHQMKE.js → chunk-JFE3NGGK.js} +2 -2
  16. package/chunks/{chunk-4R2OFVPK.js → chunk-L5ASITMV.js} +1 -1
  17. package/chunks/{chunk-MNGFXISD.js → chunk-LNTO3FNQ.js} +1 -1
  18. package/chunks/{chunk-QEI3OETI.js → chunk-MW3LAIJW.js} +1 -1
  19. package/chunks/{chunk-IMYUVCF7.js → chunk-N6BOYL6K.js} +1 -1
  20. package/chunks/{chunk-QLEJOI4X.js → chunk-O3OUYCSO.js} +1 -1
  21. package/chunks/{chunk-LPWRRSAI.js → chunk-O5WFAAJF.js} +1 -1
  22. package/chunks/{chunk-6QP5C76Y.js → chunk-OVC5Z3EX.js} +1 -1
  23. package/chunks/{chunk-NDR7ZFUA.js → chunk-OXHC3R2R.js} +1 -1
  24. package/chunks/{chunk-FT76AZPN.js → chunk-RQIV43CR.js} +1 -1
  25. package/chunks/{chunk-EMWHQSMS.js → chunk-SOKNPND5.js} +1 -1
  26. package/chunks/{chunk-IOCF4XSR.js → chunk-SWEYYDZO.js} +1 -1
  27. package/chunks/{chunk-QCIDUZV6.js → chunk-U3O6TMV7.js} +1 -1
  28. package/chunks/{chunk-R3H6IWFK.js → chunk-UHDKX2CR.js} +1 -1
  29. package/chunks/{chunk-UY2R3ZQ4.js → chunk-VB4MJSMC.js} +1 -1
  30. package/chunks/{chunk-XKDGRW3K.js → chunk-VBOVIARK.js} +1 -1
  31. package/chunks/{chunk-QRCRXDZ5.js → chunk-VUJBVDPG.js} +2 -2
  32. package/chunks/{chunk-OMZ5SGMK.js → chunk-X4ML2NEE.js} +1 -1
  33. package/chunks/{chunk-S4K76QPI.js → chunk-XITA5WMN.js} +1 -1
  34. package/chunks/{chunk-MJEXA2MA.js → chunk-YTGWPLEA.js} +1 -1
  35. package/chunks/{computer-use-SPPVJT3E.js → computer-use-AU7ESBHR.js} +1 -1
  36. package/chunks/contextCommand-7JB3K3SS.js +3 -0
  37. package/chunks/{cron-create-JHL5JGIM.js → cron-create-HASFXYQL.js} +1 -1
  38. package/chunks/{cron-delete-K2R3KI2W.js → cron-delete-AW4S5IYT.js} +1 -1
  39. package/chunks/{cron-list-R3YHZBHA.js → cron-list-U5U5GO6A.js} +1 -1
  40. package/chunks/{edit-SLOTIPQ6.js → edit-UCNE7J7J.js} +1 -1
  41. package/chunks/{enter-worktree-Y6PQ27LA.js → enter-worktree-XMDJZHYY.js} +1 -1
  42. package/chunks/{enterPlanMode-XXL4BNEQ.js → enterPlanMode-XMH7YSWI.js} +1 -1
  43. package/chunks/{exit-worktree-ZO3CQN6M.js → exit-worktree-66I5GTOI.js} +1 -1
  44. package/chunks/{exitPlanMode-BNBCFLEU.js → exitPlanMode-B53RZAXG.js} +1 -1
  45. package/chunks/{geminiContentGenerator-H3MOBIG3.js → geminiContentGenerator-3QYSDHWO.js} +1 -1
  46. package/chunks/glob-JPWXHPZY.js +22 -0
  47. package/chunks/{grep-MFAMPUHG.js → grep-5RIPV774.js} +1 -1
  48. package/chunks/{keychain-token-storage-EAJ6RT4S.js → keychain-token-storage-5MWTIAEL.js} +1 -1
  49. package/chunks/{ls-4QPI2E7A.js → ls-IBIDQ5NV.js} +1 -1
  50. package/chunks/{lsp-P3GKBOP3.js → lsp-ELR2BGT4.js} +1 -1
  51. package/chunks/matildaAgentContentGenerator-2GOFJGOD.js +8 -0
  52. package/chunks/matildaContentGenerator-CCBXB5RF.js +8 -0
  53. package/chunks/{matildaOAuth2-LKOMJUC6.js → matildaOAuth2-5EYRIK66.js} +1 -1
  54. package/chunks/monitor-4FVSFXU5.js +32 -0
  55. package/chunks/notebook-edit-RTTGOHIQ.js +17 -0
  56. package/chunks/{openaiContentGenerator-CCKR4OUB.js → openaiContentGenerator-PEGNNLRN.js} +1 -1
  57. package/chunks/read-file-4TZCSTH7.js +3 -0
  58. package/chunks/ripGrep-MQNNJXAW.js +3 -0
  59. package/chunks/scheduler-4W7W3FPL.js +8 -0
  60. package/chunks/{send-message-K3T7GVHO.js → send-message-GFPVOTSZ.js} +1 -1
  61. package/chunks/{serve-C7WLVE45.js → serve-46RPFORU.js} +31 -31
  62. package/chunks/shell-VTOAVULB.js +3 -0
  63. package/chunks/{skill-D77VBROC.js → skill-FH6R4ZTW.js} +1 -1
  64. package/chunks/src-DBI2FFHO.js +3 -0
  65. package/chunks/{symbol-search-3A66G4MP.js → symbol-search-ZV6W6DPK.js} +1 -1
  66. package/chunks/{syntheticOutput-LLA4WQR7.js → syntheticOutput-XKGS6F2D.js} +1 -1
  67. package/chunks/task-create-T43QIG2F.js +3 -0
  68. package/chunks/{task-list-6I64SK7E.js → task-list-V27WHHHJ.js} +1 -1
  69. package/chunks/{task-stop-UKRXMCZV.js → task-stop-NON26GAN.js} +1 -1
  70. package/chunks/{task-update-XZWORLJB.js → task-update-DE7CUGPY.js} +1 -1
  71. package/chunks/{team-create-6SK4CNZ5.js → team-create-3NMISCGY.js} +1 -1
  72. package/chunks/{team-delete-DEPXAMUE.js → team-delete-LIEVUGIX.js} +1 -1
  73. package/chunks/{todoWrite-DKJAYA4S.js → todoWrite-YIMKFWIL.js} +1 -1
  74. package/chunks/{tool-search-7D46IF5G.js → tool-search-HFOHXFK5.js} +1 -1
  75. package/chunks/{update-goal-EUJYH23K.js → update-goal-2ZJ53Q3T.js} +1 -1
  76. package/chunks/{web-fetch-UGTFUOQN.js → web-fetch-EVO7GDEB.js} +1 -1
  77. package/chunks/{web-search-FURCBRRK.js → web-search-SJMJGGPE.js} +1 -1
  78. package/chunks/{workflow-DG73Y76U.js → workflow-JD3LGT4M.js} +2 -2
  79. package/chunks/write-file-UUWQNGF2.js +15 -0
  80. package/cli.js +353 -353
  81. package/package.json +2 -2
  82. package/chunks/agent-U4F2PPZK.js +0 -3
  83. package/chunks/agent-headless-HVLXIG5E.js +0 -3
  84. package/chunks/chunk-QWBNNEV2.js +0 -14
  85. package/chunks/contextCommand-B6PO2N2B.js +0 -3
  86. package/chunks/glob-JHSJXAWH.js +0 -22
  87. package/chunks/matildaAgentContentGenerator-TUOJCDZF.js +0 -32
  88. package/chunks/matildaContentGenerator-K32UBTHC.js +0 -8
  89. package/chunks/monitor-LW5DPUYE.js +0 -32
  90. package/chunks/notebook-edit-XQHVR3VY.js +0 -17
  91. package/chunks/read-file-URGJTANM.js +0 -3
  92. package/chunks/ripGrep-WLBUDFPP.js +0 -3
  93. package/chunks/scheduler-KIVES2O5.js +0 -8
  94. package/chunks/shell-FC3JNLXK.js +0 -3
  95. package/chunks/src-JTFAM72X.js +0 -3
  96. package/chunks/task-create-ZZTSVXZN.js +0 -3
  97. package/chunks/write-file-NQP7YPXV.js +0 -15
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maincode-ai/matilda-code",
3
- "version": "0.21.4",
3
+ "version": "0.21.5-nightly.20260908.0d3c624bb",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "cli.js",
@@ -26,7 +26,7 @@
26
26
  "bundled"
27
27
  ],
28
28
  "config": {
29
- "sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.4"
29
+ "sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.5-nightly.20260908.0d3c624bb"
30
30
  },
31
31
  "dependencies": {},
32
32
  "optionalDependencies": {
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{gg as a,hg as b,ig as c,jg as d,kg as e,lg as f}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.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{f as AgentTool,b as TOOL_REGISTRY_REBUILT,e as createApprovalModeOverride,c as hasRebuiltToolRegistry,d as rebuildToolRegistryOnOverride,a as resolveSubagentApprovalMode};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Hf as a,If as b,Jf as c}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.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{c as AgentHeadless,a as ContextState,b as templateString};
@@ -1,14 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{e as $,l as I,n as ut}from"./chunk-FWDMPRKU.js";import{b as c}from"./chunk-GZPNIYVZ.js";c();function G(t){return t instanceof Error&&"code"in t}function Nt(t){return!t||typeof t!="object"?!1:!!(t instanceof Error&&t.name==="AbortError"||G(t)&&t.code==="ABORT_ERR")}function $t(t){if(t instanceof Error){let e=t.cause;return e instanceof Error&&e.message!==t.message?`${t.message} (cause: ${e.message})`:t.message}try{return String(t)}catch{return"Failed to get error details"}}function Ot(t){if(typeof t!="object"||t===null)return;let e=t,n=e.status??e.statusCode??e.response?.status??e.error?.code;if(typeof n=="number"&&n>=100&&n<=599)return n;if(typeof e.message=="string"){let r=e.message.match(/HTTP_STATUS\/(\d{3})\b/);if(r){let o=Number(r[1]);if(o>=100&&o<=599)return o}}}function Wt(t){if(typeof t!="object"||t===null)return"unknown";let e=t instanceof Error&&t.constructor.name!=="Error"?t.constructor.name:void 0,n=t.type,r=e??n??(t instanceof Error?t.name:"unknown"),o=t instanceof Error?t.cause:void 0,i=o&&typeof o=="object"&&"code"in o?o.code:void 0;return i?`${r}:${i}`:r}var d=class extends Error{constructor(n,r){super(n);this.exitCode=r}},O=class extends d{constructor(e){super(e,41)}},W=class extends d{constructor(e){super(e,42)}},B=class extends d{constructor(e){super(e,44)}},E=class extends d{constructor(e){super(e,52)}},_=class extends d{constructor(e){super(e,53)}},F=class extends d{constructor(e){super(e,54)}},U=class extends d{constructor(e){super(e,55)}},H=class extends d{constructor(e){super(e,130)}},R=class extends Error{},L=class extends Error{},M=class extends Error{};function Bt(t){if(t&&typeof t=="object"&&"response"in t){let n=lt(t);if(n.error&&n.error.message&&n.error.code)switch(n.error.code){case 400:return new M(n.error.message);case 401:return new L(n.error.message);case 403:return new R(n.error.message);default:}}return t}function lt(t){return typeof t.response?.data=="string"?JSON.parse(t.response?.data):t.response?.data}c();import gt from"node:fs";import p from"node:path";import f from"node:os";import*as z from"node:crypto";var w=".matilda",Jt="google_accounts.json",b=new Map,pt=1024;function Kt(){b.clear()}var V=/[ \t()[\]{};|*?$`'"#&<>!~,]/,Xt=["file_path","path","filePath","notebook_path"],dt=(()=>{let t=V.source.slice(1,-1);return new RegExp(`\\\\([${t}])`,"g")})();function Zt(t){let e=f.homedir();return t.startsWith(e)?t.replace(e,"~"):t}function Yt(t){if(!t)return"";let e=t;return t.toLowerCase().startsWith("%userprofile%")?e=f.homedir()+t.substring(13):(t==="~"||t.startsWith("~/"))&&(e=f.homedir()+t.substring(1)),p.normalize(e)}function qt(t,e=80){if(t.length<=e)return t;let n=p.sep,r="...";if(e<10)return t.substring(0,e-3)+r;let i=p.parse(t).root,u=t.substring(i.length).split(n).filter(a=>a!=="");if(u.length===0)return i.length<=e?i:i.substring(0,e-3)+r;if(u.length===1){let a=i+u[0];if(a.length<=e)return a;let h=Math.floor((e-3)/2),x=a.substring(0,h),k=a.substring(a.length-h);return`${x}${r}${k}`}let l=i+u[0],v=[];for(let a=u.length-1;a>=1;a--){let h=u[a],x=[h,...v].join(n),k=a>1,S;if(k?S=l+n+r+n+x:S=l+n+x,S.length<=e){if(v.unshift(h),a===1)return S}else break}if(v.length===0){let a=Math.floor((e-3)/2),h=t.substring(0,a),x=t.substring(t.length-a);return`${h}${r}${x}`}return l+n+r+n+v.join(n)}function Qt(t,e){let n=p.resolve(t),r=p.resolve(e);return X(r,n)?p.relative(r,n)||".":n}function te(t){let e="";for(let n=0;n<t.length;n++){let r=t[n],o=0;for(let g=n-1;g>=0&&t[g]==="\\";g--)o++;!(o%2===1)&&V.test(r)?e+="\\"+r:e+=r}return e}function ee(t){return f.platform()==="win32"?t:t.replace(dt,"$1")}function J(t){let e=f.platform()==="win32"?t.toLowerCase():t;return z.createHash("sha256").update(e).digest("hex")}function K(t){return(f.platform()==="win32"?t.toLowerCase():t).replace(/[^a-zA-Z0-9]/g,"-")}function X(t,e){let r=f.platform()==="win32"?p.win32:p,o=r.relative(t,e);return!o.startsWith(`..${r.sep}`)&&o!==".."&&!r.isAbsolute(o)}function ne(t,e){return t.some(n=>X(n,e))}function ft(t=process.cwd(),e){let n=f.homedir();return e==="~"?n:e.startsWith("~/")?p.join(n,e.slice(2)):p.isAbsolute(e)?e:p.resolve(t,e)}function ht(t,e,n={}){let{allowFiles:r=!1,allowExternalPaths:o=!1}=n,g=t.getWorkspaceContext().isPathWithinWorkspace(e);if(!o&&!g)throw new Error("Path is not within workspace");if(o&&!g)return;let u=b.get(e);if(u===void 0){try{u=gt.statSync(e).isDirectory()}catch(l){throw G(l)&&l.code==="ENOENT"?new Error(`Path does not exist: ${e}`):l}if(b.size>=pt){let l=b.keys().next().value;l!==void 0&&b.delete(l)}b.set(e,u)}if(!r&&!u)throw new Error(`Path is not a directory: ${e}`)}function re(t,e,n={}){let r=t.getTargetDir();if(!e)return r;let o=ft(r,e);return ht(t,o,n),o}c();import*as s from"node:path";import*as m from"node:os";import*as y from"node:fs";import{AsyncLocalStorage as mt}from"node:async_hooks";var Dt="google_accounts.json",xt="oauth_creds.json",bt=[".matilda",".agents"],Et="tmp",wt="bin",Pt="projects",jt="ide",vt="plans",St="debug",yt="arena",D=class t{targetDir;static runtimeBaseDir=null;static runtimeBaseDirContext=new mt;constructor(e){this.targetDir=e}static resolvePath(e,n){let r=e;if(r==="~"||r.startsWith("~/")||r.startsWith("~\\")){let o=r==="~"?[]:r.slice(2).split(/[/\\]+/).filter(Boolean);r=s.join(m.homedir(),...o)}return s.isAbsolute(r)||(r=n?s.resolve(n,r):s.resolve(r)),r}static sanitizePlanSessionId(e){return s.basename(e.replace(/\\/g,"/")).replace(/^\.+/g,"_").replace(/[<>:"|?*\x00-\x1F]/g,"_")||"_"}static resolveRuntimeBaseDir(e,n){return e?t.resolvePath(e,n):null}static setRuntimeBaseDir(e,n){t.runtimeBaseDir=t.resolveRuntimeBaseDir(e,n)}static runWithRuntimeBaseDir(e,n,r){let o=t.resolveRuntimeBaseDir(e,n);return t.runtimeBaseDirContext.run(o,r)}static getRuntimeBaseDir(){let e=process.env.MATILDA_RUNTIME_DIR;if(e)return t.resolveRuntimeBaseDir(e)??t.getGlobalMatildaDir();let n=t.runtimeBaseDirContext.getStore();return n!==void 0?n??t.getGlobalMatildaDir():t.runtimeBaseDir?t.runtimeBaseDir:t.getGlobalMatildaDir()}static getGlobalMatildaDir(){let e=process.env.MATILDA_HOME;if(e)return t.resolvePath(e);let n=m.homedir();return n?s.join(n,w):s.join(m.tmpdir(),".matilda")}static getMcpOAuthTokensPath(){return s.join(t.getGlobalMatildaDir(),"mcp-oauth-tokens.json")}static getGlobalSettingsPath(){return s.join(t.getGlobalMatildaDir(),"settings.json")}static getInstallationIdPath(){return s.join(t.getGlobalMatildaDir(),"installation_id")}static getGoogleAccountsPath(){return s.join(t.getGlobalMatildaDir(),Dt)}static getUserCommandsDir(){return s.join(t.getGlobalMatildaDir(),"commands")}static getGlobalMemoryFilePath(){return s.join(t.getGlobalMatildaDir(),"memory.md")}static getGlobalTempDir(){return s.join(t.getRuntimeBaseDir(),Et)}static getGlobalDebugDir(){return s.join(t.getRuntimeBaseDir(),St)}static getDebugLogPath(e){return s.join(t.getGlobalDebugDir(),`${e}.txt`)}static getGlobalIdeDir(){return s.join(t.getGlobalMatildaDir(),jt)}static resolvePathThroughExistingAncestor(e){let n=e;for(;;)try{let r=y.realpathSync(n),o=s.relative(n,e);return s.join(r,o)}catch(r){if(r.code!=="ENOENT")throw r;let o=s.dirname(n);if(o===n)return e;n=o}}static isPathWithinDirectory(e,n){let r=t.resolvePathThroughExistingAncestor(n),o=t.resolvePathThroughExistingAncestor(e),i=s.relative(r,o);return i===""||!i.startsWith("..")&&!s.isAbsolute(i)}static assertPathWithinDirectory(e,n,r){if(!t.isPathWithinDirectory(e,n))throw new E(r)}static getPlansDir(e,n){let r=n?.trim();if(r){if(!e)throw new E("projectRoot is required when plansDirectory is configured.");let o=s.resolve(e),i=t.resolvePath(r,o);return t.assertPathWithinDirectory(i,o,"plansDirectory must resolve within the project root."),i}return s.join(t.getGlobalMatildaDir(),vt)}static getPlanFilePath(e,n,r){return s.join(t.getPlansDir(n,r),`${t.sanitizePlanSessionId(e)}.md`)}static getGlobalBinDir(){return s.join(t.getGlobalMatildaDir(),wt)}static getGlobalArenaDir(){return s.join(t.getGlobalMatildaDir(),yt)}getMatildaDir(){return s.join(this.targetDir,w)}getProjectDir(){let e=K(this.getProjectRoot()),n=s.join(t.getRuntimeBaseDir(),Pt);return s.join(n,e)}getProjectTempDir(){let e=J(this.getProjectRoot()),n=t.getGlobalTempDir();return s.join(n,e)}getToolResultsDir(){return s.join(this.getProjectTempDir(),"tool-results")}ensureProjectTempDirExists(){y.mkdirSync(this.getProjectTempDir(),{recursive:!0})}static getOAuthCredsPath(){return s.join(t.getGlobalMatildaDir(),xt)}getProjectRoot(){return this.targetDir}getWorkspaceSettingsPath(){return s.join(this.getMatildaDir(),"settings.json")}getProjectCommandsDir(){return s.join(this.getMatildaDir(),"commands")}getRuntimeStatusPath(e){return s.join(this.getProjectDir(),"chats",`${e}.runtime.json`)}getProjectTempCheckpointsDir(){return s.join(this.getProjectTempDir(),"checkpoints")}getExtensionsDir(){return s.join(this.getMatildaDir(),"extensions")}getExtensionsConfigPath(){return s.join(this.getExtensionsDir(),"matilda-extension.json")}getUserSkillsDirs(){let e=m.homedir()||m.tmpdir();return bt.map(n=>n===w?s.join(t.getGlobalMatildaDir(),"skills"):s.join(e,n,"skills"))}static getUserExtensionsDir(){return s.join(t.getGlobalMatildaDir(),"extensions")}getHistoryFilePath(){return s.join(this.getProjectTempDir(),"shell_history")}};c();import{promises as N}from"node:fs";import Z from"node:path";async function Y(t,e,n){let{fallbackCopy:r=!0}=n??{},o=Z.dirname(t),i=Z.relative(o,e);try{await N.unlink(t)}catch{}try{await N.symlink(i,t);return}catch{}if(r)try{await N.copyFile(e,t)}catch{}}c();ut();c();var q,Q;function me(t,e){q=t,Q=e}function tt(){return q}function De(){return Q}function et(t){let e=t?.spanContext();return e&&$(e)?{traceId:e.traceId,spanId:e.spanId,traceFlags:e.traceFlags}:null}function Ct(){try{return et(I.getActiveSpan())}catch{return null}}function At(){try{let t=tt();return et(t?I.getSpan(t):void 0)}catch{return null}}function nt(){return Ct()??At()}function je(t){let e=(t.traceFlags&255).toString(16).padStart(2,"0");return`00-${t.traceId}-${t.spanId}-${e}`}var rt=!1;function ve(t){rt=t}function Se(){return rt}c();import{promises as st}from"node:fs";import Tt from"node:path";import{AsyncLocalStorage as kt}from"node:async_hooks";import It from"node:util";var j=null,A=null,T=!1,ot=null,it=new kt;function at(){let t=process.env.MATILDA_DEBUG_LOG_FILE;if(!t)return!1;let e=t.trim().toLowerCase();return!["","0","false","off","no"].includes(e)}function P(){return it.getStore()??ot}function ct(){let t=D.getGlobalDebugDir();return(!j||A!==t)&&(A=t,j=st.mkdir(t,{recursive:!0}).then(()=>{}).catch(()=>{T=!0,j=null,A=null})),j??Promise.resolve()}function Rt(t){return t.map(e=>e instanceof Error?e.stack??`${e.name}: ${e.message}`:e).map(e=>typeof e=="string"?e:It.inspect(e)).join(" ")}function Lt(t,e,n,r){let o=new Date().toISOString(),i=n?` [${n}]`:"",g=r?` [trace_id=${r.traceId} span_id=${r.spanId}]`:"";return`${o} [${t}]${i}${g} ${e}
4
- `}function C(t,e,n,r){if(!at())return;let o=t.getSessionId(),i=D.getDebugLogPath(o),g=Rt(r),u=nt(),l=Lt(e,g,n,u);ct().then(()=>st.appendFile(i,l,"utf8")).catch(()=>{T=!0})}function Ge(){return T}function Ne(){T=!1,j=null,A=null}var Mt="latest";function Gt(t){if(!at())return;let e=Tt.join(D.getGlobalDebugDir(),Mt),n=D.getDebugLogPath(t);ct().then(()=>Y(e,n,{fallbackCopy:!1})).catch(()=>{})}function $e(t){ot=t??null,t&&Gt(t.getSessionId())}function Oe(t,e){return it.run(t,e)}function We(t){return{isEnabled:()=>P()!==null,debug:(...e)=>{let n=P();n&&C(n,"DEBUG",t,e)},info:(...e)=>{let n=P();n&&C(n,"INFO",t,e)},warn:(...e)=>{let n=P();n&&C(n,"WARN",t,e)},error:(...e)=>{let n=P();n&&C(n,"ERROR",t,e)}}}export{G as a,Nt as b,$t as c,Ot as d,Wt as e,d as f,O as g,W as h,B as i,E as j,_ as k,F as l,U as m,H as n,R as o,L as p,M as q,Bt as r,w as s,Jt as t,Kt as u,V as v,Xt as w,Zt as x,Yt as y,qt as z,Qt as A,te as B,ee as C,J as D,K as E,X as F,ne as G,ft as H,ht as I,re as J,bt as K,D as L,Y as M,me as N,De as O,Ct as P,nt as Q,je as R,ve as S,Se as T,Ge as U,Ne as V,$e as W,Oe as X,We as Y};
5
- /**
6
- * @license
7
- * Copyright 2025 Google LLC
8
- * SPDX-License-Identifier: Apache-2.0
9
- */
10
- /**
11
- * @license
12
- * Copyright 2025 Matilda
13
- * SPDX-License-Identifier: Apache-2.0
14
- */
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{c as a,d as b,e as c}from"./chunk-LPWRRSAI.js";import"./chunk-ENMM2K4Q.js";import"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.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,22 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Pe as _,Qe as j}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.js";import"./chunk-47XR7IMP.js";import"./chunk-QEI3OETI.js";import"./chunk-QKYGQLWC.js";import"./chunk-MNGFXISD.js";import"./chunk-4R2OFVPK.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import"./chunk-S4K76QPI.js";import"./chunk-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as M,i as C,p as N,q as A}from"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{C as $,F as O,J as v,Y as R,c as x}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as L}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";L();import z from"node:fs";import T from"node:path";var V=R("GLOB"),Y=100,B=2e4,W=15e3,q=500;function K(u,g,t){let e=[...u];return e.sort((r,s)=>{let c=r.mtimeMs??0,a=s.mtimeMs??0,o=g-c<t,l=g-a<t;return o&&l?a-c:o?-1:l?1:r.fullpath().localeCompare(s.fullpath())}),e}var S=class extends M{constructor(t,e){super(e);this.config=t;this.fileService=t.getFileService()}fileService;getDescription(){let t=`'${this.params.pattern}'`;return this.params.path&&(t+=` in path '${this.params.path}'`),t}async getDefaultPermission(){if(!this.params.path)return"allow";let t=this.config.getWorkspaceContext(),e=T.resolve(this.config.getTargetDir(),this.params.path);return t.isPathWithinWorkspace(e)||O(k(),e)?"allow":"ask"}async globInDirectory(t,e,r){let s=e,c=T.join(t,s);z.existsSync(c)&&(s=_(s));let a=j(s,{cwd:t,withFileTypes:!0,nodir:!0,stat:!0,nocase:!0,dot:!0,ignore:this.config.getFileExclusions().getGlobExcludes(),follow:!1,signal:r}),o=[],l=Date.now(),p=null;for await(let n of a){if(o.push(n),o.length>=B){p="count";break}if(Date.now()-l>W){p="time";break}o.length%q===0&&await new Promise(b=>setImmediate(b))}p&&a.destroy?.();let d=this.config.getTargetDir(),P=o.map(n=>T.relative(d,n.fullpath())),{filteredPaths:m}=this.fileService.filterFilesWithReport(P,this.getFileFilteringOptions()),h=n=>process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n,f=new Set(m.map(n=>h(T.resolve(d,n))));return{entries:o.filter(n=>f.has(h(n.fullpath()))),limited:p}}async execute(t){try{let e=[],r;if(this.params.path){let i=v(this.config,this.params.path,{allowExternalPaths:!0});e.push(i),r=`within ${i}`}else{let i=this.config.getWorkspaceContext().getDirectories();e.push(...i),r=i.length>1?`across ${i.length} workspace directories`:"in the workspace directory"}let s=this.params.pattern,c=[],a=new Set,o=null;for(let i of e){let{entries:F,limited:E}=await this.globInDirectory(i,s,t);E&&(o=E);for(let G of F){let I=G.fullpath();a.has(I)||(a.add(I),c.push(G))}}let l=c,p=o==="time"?`
4
-
5
- [Search stopped after ${W/1e3}s before scanning the whole tree. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:o==="count"?`
6
-
7
- [Search stopped after scanning ${B} entries. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:"";if(!l||l.length===0)return{llmContent:`No files found matching pattern "${this.params.pattern}" ${r}${p}`,returnDisplay:o?"No files found (search truncated)":"No files found"};let d=24*60*60*1e3,P=new Date().getTime(),m=K(l,P,d),h=m.length,f=Math.min(Y,this.config.getTruncateToolOutputLines()),y=h>f,b=(y?m.slice(0,f):m).map(i=>i.fullpath()),X=b.join(`
8
- `),w=`Found ${h} file(s) matching "${this.params.pattern}" ${r}`;if(w+=`, sorted by modification time (newest first):
9
- ---
10
- ${X}`,y){let i=h-f;w+=`
11
- ---
12
- [${i} ${i===1?"file":"files"} truncated] ...`}return w+=p,{llmContent:w,returnDisplay:`Found ${h} matching file(s)${y?" (truncated)":""}`,resultFilePaths:b}}catch(e){let r=e instanceof Error?e.message:String(e);V.error(`GlobLogic execute Error: ${r}`,e);let s=`Error during glob search operation: ${r}`;return{llmContent:s,returnDisplay:`Error: ${r||"An unexpected error occurred."}`,error:{message:s,type:"glob_execution_error"}}}}getFileFilteringOptions(){let t=this.config.getFileFilteringOptions?.();return{respectGitIgnore:t?.respectGitIgnore??D.respectGitIgnore,respectMatildaIgnore:t?.respectMatildaIgnore??D.respectMatildaIgnore}}},U=class u extends C{constructor(t){super(u.Name,A.GLOB,`Fast file pattern matching tool that works with any codebase size
13
- - Supports glob patterns like "**/*.js" or "src/**/*.ts"
14
- - Returns matching file paths sorted by modification time
15
- - Use this tool when you need to find files by name patterns
16
- - When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead
17
- - You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.`,"search",{properties:{pattern:{description:"The glob pattern to match files against",type:"string"},path:{description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.',type:"string"}},required:["pattern"],type:"object"});this.config=t}static Name=N.GLOB;validateToolParamValues(t){if(!t.pattern||typeof t.pattern!="string"||t.pattern.trim()==="")return"The 'pattern' parameter cannot be empty.";if(t.path){t.path=$(t.path.trim());try{v(this.config,t.path,{allowExternalPaths:!0})}catch(e){return x(e)}}return null}createInvocation(t){return new S(this.config,t)}};export{U as GlobTool,B as MAX_SCAN_ENTRIES,W as MAX_SCAN_MS,K as sortFileEntries};
18
- /**
19
- * @license
20
- * Copyright 2025 Google LLC
21
- * SPDX-License-Identifier: Apache-2.0
22
- */
@@ -1,32 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{M as F,N as U,O as j,g as x,la as $}from"./chunk-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import{b as m,e as b}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as O,n as I}from"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{p as P}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as w}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";w();w();var W="2026-06-23",H="auto",J="instant",V=12e4,h=18e4,X=5e4,v=16e3,k=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},B=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),K=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function z(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function T(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}function u(n,e){let o=T(n)?.[e];return typeof o=="string"?o:void 0}function D(n){return S(n)}function S(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
4
- `):""}function g(n,e){if(n.length<=e)return n;let t=`
5
- [...omitted to fit Matilda native agent context...]
6
- `,o=e-t.length,s=Math.floor(o*.6),i=o-s;return`${n.slice(0,s)}${t}${n.slice(-i)}`}function Q(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function Y(n){let e=T(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function Z(n){if(C(n)<=h)return n;let e=`
7
- [...omitted to fit Matilda native request limit...]
8
- `;for(let t=0;t<n.messages.length;t+=1){let o=n.messages[t];!o||o.content.length<=v||(n.messages[t]={...o,content:g(o.content,v)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,o=n.messages[t];if(!o||o.content.length<=1e3)break;let s=C(n)-h,i=Math.max(1e3,o.content.length-s-e.length-2e3);n.messages[t]={...o,content:g(o.content,i)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function q(n){let e=T(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let o=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:o}}function ee(n){let e=T(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let o=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${o}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let o=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${o?` with ${o}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),o=u(n.data,"message");return t&&o?`**Remote tool** ${t}: ${o}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),o=u(n.data,"status"),s=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${o??"completed"}${s?`: ${g(s,600)}`:""}`:void 0}}function G(n,e,t){let o=new b;return o.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],o.createTime=Date.now().toString(),o.modelVersion=e,t&&(o.usageMetadata=t),o}function te(n,e){let t=new b;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function ne(n,e){let t=new b;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function L(n,e,t){let o=G("",n,t);return o.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],o}async function*oe(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let o=new TextDecoder,s="",i="message",r=[],d=!1,c,a=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},f=()=>{if(r.length===0){i="message";return}let A={event:i,data:r.join(`
9
- `)};return i="message",r=[],a(),A};a();try{for(;;){let{done:M,value:p}=await t.read();if(M||d)break;a(),s+=o.decode(p,{stream:!0});let _=s.split(`
10
- `);s=_.pop()??"";for(let N of _){let y=N.endsWith("\r")?N.slice(0,-1):N;if(y.length===0){let E=f();E&&(yield E)}else y.startsWith("event:")?i=y.slice(6).trim():y.startsWith("data:")&&r.push(y.slice(5).trimStart())}}if(s+=o.decode(),s.length>0)for(let M of s.split(`
11
- `)){let p=M.endsWith("\r")?M.slice(0,-1):M;p.startsWith("event:")?i=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=f();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var R=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let o=await this.generateContentStream(e,t),s="",i,r=m.STOP,d=!1;for await(let a of o){s+=Q(a),a.usageMetadata&&(i=a.usageMetadata);let l=a.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new k;let c=G(s,this.modelFor(e),i);return c.candidates=[{content:{parts:s?[{text:s}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),o=await this.fetchNativeChat(e),s=!1,i=!1,r,d,c=!1;for await(let a of oe(o,V))if(a.data!=="[DONE]"){if(a.event==="token"){let l=u(a.data,"content");l&&(i=!0,yield G(l,t))}else if(a.event==="thinking"||a.event==="generation_status"||a.event==="status"||a.event==="tool_start"||a.event==="tool_progress"||a.event==="tool_result"){let l=ee(a);l&&(i=!0,yield te(l,t))}else if(a.event==="client_tool_call"){let l=q(a);l&&(i=!0,yield ne(l,t))}else if(a.event==="usage")d=Y(a.data)??d;else if(a.event==="safety_replace"){let l=u(a.data,"message")??u(a.data,"content");l&&(i=!0,yield G(l,t))}else if(a.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(a.event==="done"){if(c=!0,r=u(a.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!i)throw new Error("Matilda agent returned an empty response.");yield L(t,r,d),s=!0}else if(a.event==="error"){let l=T(a.data),f=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${f}`)}}if(!s){if(e.config?.abortSignal?.aborted)return;if(!i)throw new Error("Matilda agent returned an empty response.");if(c)yield L(t,r??m.STOP,d);else throw new k}}async fetchNativeChat(e){let t=await $({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),o=await this.postNativeChat(e,t);if(o.status!==401)return this.assertOkResponse(o);let s;try{s=await $({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw new P(r instanceof Error?r.message:String(r))}if(!s||s===t)throw new P("Matilda session expired. Please sign in again.");let i=await O("retry",()=>this.postNativeChat(e,s));return this.assertOkResponse(i)}async postNativeChat(e,t){return fetch(`${z(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=`Matilda agent request failed (${e.status}): ${await e.text()}`;throw e.status===401?new P(t):new Error(t)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":W,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[o,s]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))o.toLowerCase()!=="x-matilda-response-mode"&&!U(o)&&(t[o]=s);return j(this.contentGeneratorConfig,e)&&Object.assign(t,F(this.cliConfig),I()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),o=this.clientToolsFromRequest(e),s={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return o.length>0&&(s.clientTools=o),Z(s)}buildNativeMessages(e,t){let o=this.openAIMessagesFromRequest(e),i=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of o){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&i.push(c)}i.length===1&&i.push({role:"user",content:`${this.purposeLabel(t)}:
12
- (empty prompt)`});let r=i[i.length-1];return r?.role!=="user"?i.push({role:"user",content:`${this.purposeLabel(t)}:
13
- Continue from the previous assistant response.`}):r.content.startsWith(`${this.purposeLabel(t)}:
14
- `)||(i[i.length-1]={...r,content:`${this.purposeLabel(t)}:
15
- ${r.content}`}),i}buildSystemContext(e,t){let o=["Agent: Matilda Code",t==="code"?`Routing intent:
16
- ${B}`:void 0,`Instructions:
17
- ${this.instructionsFromRequest(e)}`].filter(s=>!!s);return g(o.join(`
18
-
19
- `),X)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let o=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(o)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(o)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?J:e==="analysis"?"deep":H}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(o=>o.role==="system").map(o=>S(o.content)).filter(o=>o.trim().length>0);return[K,...t,this.localAgentContext()].join(`
20
-
21
- `)}localAgentContext(){let e=["Local agent context:","- CLI: Matilda Code terminal agent."],t=this.cliConfig.getModel?.();t&&e.push(`- Active model: ${t}`);let o=this.cliConfig.getApprovalMode?.();o&&e.push(`- Approval mode: ${o}`);let s=this.cliConfig.getSandbox?.();e.push(s?`- Sandbox: ${s.command} (${s.image}).`:"- Sandbox: disabled.");let i=[["allow",this.cliConfig.getPermissionsAllow?.()??[]],["ask",this.cliConfig.getPermissionsAsk?.()??[]],["deny",this.cliConfig.getPermissionsDeny?.()??[]]];for(let[l,f]of i)f.length>0&&e.push(`- Permission ${l} rules: ${f.join(", ")}`);let r=this.cliConfig.getIdeMode?.()?"IDE/ACP":this.cliConfig.isInteractive?.()?"interactive TUI":"headless";e.push(`- Interface mode: ${r}`);let d=this.cliConfig.getProjectRoot?.();d&&e.push(`- Project root: ${d}`);let c=this.cliConfig.getWorkingDir?.();c&&c!==d&&e.push(`- Working directory: ${c}`);let a=this.cliConfig.getToolRegistry?.()?.getAllToolNames?.().slice(0,30)??[];return a.length>0&&e.push(`- Local tools available through the CLI loop: ${a.join(", ")}`),e.join(`
22
- `)}clientToolsFromRequest(e){let t=[];for(let o of e.config?.tools??[])"functionDeclarations"in o&&t.push(...(o.functionDeclarations??[]).filter(s=>!!s.name));return t.map(o=>({name:o.name,...o.description?{description:o.description}:{},...o.parametersJsonSchema?{parameters:o.parametersJsonSchema}:o.parameters?{parameters:o.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>D(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return x.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
23
- ${g(D(e.content),v)}`;if(e.role==="assistant"){let t=S(e.content),o="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(s=>`Tool request: ${s.function.name}(${s.function.arguments})`).join(`
24
- `):"";return`Assistant:
25
- ${g([t,o].filter(Boolean).join(`
26
- `),v)}`}return e.role==="tool"?`Tool result ${e.tool_call_id}:
27
- ${g(S(e.content),v)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};function ge(n,e){return new R(n,e)}export{R as MatildaAgentContentGenerator,ge as createMatildaAgentContentGenerator};
28
- /**
29
- * @license
30
- * Copyright 2026 Matilda Team
31
- * SPDX-License-Identifier: Apache-2.0
32
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a as d,i as u}from"./chunk-2NN5YPDR.js";import"./chunk-QCIDUZV6.js";import"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import{d as o}from"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as s}from"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import{c}from"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{Y as i}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var l=class extends u{debugLogger=i("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,r){let n=new d(t,r);super(t,r,n),this.matildaClient=e,this.sharedManager=c.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||o,r="/v1",n=t.startsWith("http")?t:`https://${t}`;return n.endsWith(r)||n.endsWith("/api/v1")||n.endsWith("/api/v1/code")?n:`${n}${r}`}shouldSuppressErrorLogging(e,t){return this.isAuthError(e)}async getValidToken(){try{let e=await this.sharedManager.getValidCredentials(this.matildaClient);if(!e.access_token)throw new Error("No access token available");return{token:e.access_token,endpoint:this.getCurrentEndpoint(e.resource_url)}}catch(e){throw this.isAuthError(e)?e:(this.debugLogger.warn("Failed to get token from shared manager:",e),new Error("Failed to obtain a valid legacy OAuth access token. Please re-authenticate with Matilda."))}}async executeWithCredentialManagement(e){let t=async()=>{let{token:r,endpoint:n}=await this.getValidToken();return this.pipeline.client.apiKey=r,this.pipeline.client.baseURL=n,await e()};try{return await t()}catch(r){if(this.isAuthError(r))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await s("retry",t);throw r}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.executeWithCredentialManagement(()=>super.generateContentStream(e,t))}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e,n=r?.status||r?.code;return n===401||n===403||n==="401"||n==="403"||t.includes("unauthorized")||t.includes("forbidden")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("access denied")||t.includes("token")&&t.includes("expired")}getCurrentToken(){return this.currentToken?this.currentToken:this.sharedManager.getCurrentCredentials()?.access_token||null}clearToken(){this.currentToken=void 0,this.sharedManager.clearCache()}};export{l as MatildaContentGenerator};
4
- /**
5
- * @license
6
- * Copyright 2025 Matilda
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,32 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Dc as tt,Ie as st,Ne as L,Oc as et,Oe as at,Rc as ot,Sc as A,Xc as C,Yc as nt,ad as it,oi as P,qi as lt,xe as rt}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as Z,i as q,p as Y,q as Q}from"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{G as J,Y as K,c as m}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as H}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";H();import{spawn as ct}from"node:child_process";import mt from"node:path";import{randomUUID as wt}from"node:crypto";var u=K("MONITOR"),Et=1e3,O=1e4,St=3e5,N=6e5,dt=80,R=4096,ut=5,ft=1e3;function pt(l){return l.length>dt?l.slice(0,dt-1)+"\u2026":l}var kt=new Set(["task-notification","task-id","tool-use-id","kind","status","event-count","summary","result"]),xt=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)>/g;function gt(l){let y="";for(let t=0;t<l.length;t++){let o=l.charCodeAt(t);if(o===9){y+=l[t];continue}o<32||o>=128&&o<=159||(y+=l[t])}return y=y.replace(xt,(t,o,a)=>kt.has(String(a).toLowerCase())?o==="/"?`</\u200B${a}>`:`<\u200B${a}>`:t),y}var U=class extends Z{constructor(t,o){super(o);this.config=t}callId;setCallId(t){this.callId=t}getDescription(){let t=this.params.description||C(this.params.command).spawnCommand;return`Monitor: ${pt(t)}`}async getDefaultPermission(){let t=C(this.params.command).safetyCommand;try{if(await L(t))return"allow"}catch(o){u.warn("AST read-only check failed, falling back to ask:",o)}return"ask"}async getConfirmationDetails(t){let o=C(this.params.command),a=ot(o.safetyCommand),f=[];for(let s of a){let p=!1;try{p=await L(s)}catch(d){u.warn("AST read-only check failed for monitor sub-command, falling back to ask:",d)}p||f.push(s)}let S=f.length>0?f:a,M=[...new Set(S.map(s=>A(s)).filter(s=>!!s))],v=[];try{let s=[];for(let p of S){let d=await at(p);s.push(...d)}v=[...new Set(s)].map(p=>`Monitor(${p})`)}catch(s){u.warn("Failed to extract monitor command rules:",s),v=[`Monitor(${o.safetyCommand})`]}let i=it(o.safetyCommand,this.params.command),c={type:"exec",title:"Monitor",command:o.spawnCommand,rootCommand:M.join(", ")||(A(o.safetyCommand)??o.spawnCommand),permissionRules:v,onConfirm:async(s,p)=>{}};return i&&(c.warnings=i),c}async execute(t){if(t.aborted)return{llmContent:"Monitor was cancelled before it could start.",returnDisplay:"Monitor cancelled."};let o=C(this.params.command),a=o.spawnCommand;o.strippedTrailingAmp&&u.warn("Stripped trailing & from monitor command \u2014 monitor lifecycle handles backgrounding");let f=gt(this.params.description||a),S=pt(f),M=Math.min(this.params.max_events??Et,O),v=Math.min(this.params.idle_timeout_ms??St,N),i=`mon_${wt().replace(/-/g,"").slice(0,16)}`,c=this.config.getMonitorRegistry(),s=tt()??void 0;if(c.getRunning().length>=P)return{llmContent:`Cannot start monitor: maximum concurrent monitors (${P}) reached. Stop an existing monitor first.`,returnDisplay:"Monitor rejected: too many concurrent monitors."};let d=new AbortController,g={monitorId:i,command:a,description:f,status:"running",startTime:Date.now(),abortController:d,toolUseId:this.callId,eventCount:0,lastEventTime:0,maxEvents:M,idleTimeoutMs:v,droppedLines:0,outputFile:lt(this.config.storage.getProjectDir(),this.config.getSessionId(),i),...s?{ownerAgentId:s}:{}},{executable:yt,argsPrefix:vt}=et(),n;try{n=ct(yt,[...vt,a],{cwd:this.params.directory||this.config.getTargetDir(),stdio:["ignore","pipe","pipe"],detached:!0,env:{...process.env,MATILDA_CODE:"1",TERM:"dumb",PAGER:"cat",...st()}})}catch(e){return{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}g.pid=n.pid;let b=!1,w,D=e=>{w??=e};n.on("error",D);let B={value:""},G={value:""},k=ut,I=Date.now(),$=e=>{let r=gt(e);if(r.length===0||r.trim().length===0)return;let T=Date.now(),_=T-I;if(_<0)u.warn(`Monitor ${i}: clock moved backwards by ${-_}ms, resetting refill timestamp`),I=T;else{let h=Math.floor(_/ft);h>0&&(k=Math.min(ut,k+h),I+=h*ft)}k>0?(k--,c.emitEvent(i,r)):g.droppedLines++},j=()=>{for(let e of[B,G]){let r=e.value.trim();r.length>0&&$(r),e.value=""}},Tt=()=>{if(!(b||!n.pid))if(process.platform==="win32")ct("taskkill",["/pid",n.pid.toString(),"/f","/t"],{stdio:"ignore"}).on("error",r=>u.warn(`Monitor taskkill failed for pid ${n.pid}: ${m(r)}`));else{try{process.kill(-n.pid,"SIGTERM")}catch(e){u.warn(`Monitor ${i} SIGTERM failed (pid=${n.pid}): ${m(e)}`)}setTimeout(()=>{if(!b&&n.pid)try{process.kill(-n.pid,"SIGKILL")}catch(e){u.warn(`Monitor ${i} SIGKILL escalation failed (pid=${n.pid}): ${m(e)}`)}},200).unref?.()}},E=()=>{j(),Tt()};d.signal.addEventListener("abort",E,{once:!0}),d.signal.aborted&&E();try{c.register(g)}catch(e){return E(),d.signal.removeEventListener("abort",E),n.stdout?.destroy?.(),n.stderr?.destroy?.(),n.removeListener("error",D),n.on("error",()=>{}),{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}let z=(e,r)=>{if(g.status!=="running")return;let T=rt(r.toString("utf-8"));if(e.value+=T,!e.value.includes(`
4
- `)&&e.value.length>R){let h=e.value.trim();h.length>0&&$(h.slice(0,R)+"..."),e.value="";return}let _=e.value.split(`
5
- `);e.value=_.pop()??"";for(let h of _){let x=h.trim();if(x.length===0)continue;let bt=x.length>R?x.slice(0,R)+"...":x;$(bt)}};n.stdout?.on("data",e=>z(B,e)),n.stderr?.on("data",e=>z(G,e));let F=!1,X=()=>{F||(F=!0,j(),d.signal.removeEventListener("abort",E),g.droppedLines>0&&u.info(`Monitor ${i} dropped ${g.droppedLines} lines due to throttling`))},V=null,_t=(e,r)=>{g.status==="running"&&(d.signal.aborted?c.cancel(i):e!==null&&e!==0?c.fail(i,`Exit code ${e}`):r?c.fail(i,`Killed by signal ${r}`):c.complete(i,e))},Ct=(e,r)=>{b=!0,V={code:e,sig:r}},Mt=(e,r)=>{b=!0,X();let T=V??{code:e,sig:r};_t(T.code,T.sig)},W=e=>{b=!0,X(),g.status==="running"&&c.fail(i,m(e))};return n.on("exit",Ct),n.on("close",Mt),n.on("error",W),n.removeListener("error",D),w?(W(w),{llmContent:`Monitor failed to start: ${m(w)}`,returnDisplay:`Monitor failed: ${m(w)}`}):{llmContent:`Monitor started.
6
- id: ${i}
7
- command: ${a}
8
- description: ${f}
9
- max_events: ${M}
10
- idle_timeout: ${v}ms
11
- Events will be delivered as notifications. The monitor auto-stops after ${M} events or ${v}ms of silence.
12
- To inspect: /tasks (text) or the interactive Background tasks dialog (focus the footer Background tasks pill, then Enter \u2014 detail view + live updates).`,returnDisplay:`Monitor started: ${S} (${i})`}}},ht=class l extends q{constructor(t){super(l.Name,Q.MONITOR,`Starts a long-running shell command and streams its stdout/stderr as event notifications back to you.
13
-
14
- Use this tool for:
15
- - Watching log files: \`tail -f /var/log/app.log\`
16
- - Monitoring build output: \`npm run build --watch\`
17
- - Polling for state changes: \`while true; do curl -s http://localhost:8080/health; sleep 1; done\`
18
- - Watching file changes: \`fswatch -r ./src\`
19
-
20
- Each output line from the command becomes a notification event delivered to you. The monitor runs in the background \u2014 you can continue working while it streams events.
21
-
22
- **Auto-stop:** The monitor automatically stops after max_events (default 1000) events or after idle_timeout_ms (default 5 minutes) of silence. The process is killed when the monitor stops.
23
-
24
- **Do NOT use this tool for:**
25
- - One-shot commands (use run_shell_command instead)
26
- - Commands you need the full output from (use run_shell_command instead)
27
- - Commands with no output (use run_shell_command with is_background: true instead)`,"execute",{type:"object",properties:{command:{type:"string",description:"Shell command to run and monitor. Each output line (stdout and stderr) becomes an event notification."},description:{type:"string",description:'Brief description of what this monitor watches (e.g., "webpack build output"). Truncated to 80 characters in display.'},max_events:{type:"number",description:"Stop the monitor after this many events. Default 1000. Max 10000."},idle_timeout_ms:{type:"number",description:"Stop the monitor if no output for this many milliseconds. Default 300000 (5 min). Max 600000."},directory:{type:"string",description:"(OPTIONAL) The absolute path of the directory to run the command in. If not provided, the project root directory is used. Must be within the workspace."}},required:["command"],additionalProperties:!1},!0,!1,!0,!1,"monitor watch tail log stream background");this.config=t}static Name=Y.MONITOR;validateToolParamValues(t){if(typeof t.command!="string"||!C(t.command).analysisCommand)return"Command cannot be empty.";if(nt(t.command))return'Monitor commands must not contain non-final top-level background operators. Remove "&" and let the monitor manage process lifetime.';if(t.max_events!==void 0){if(typeof t.max_events!="number"||!Number.isInteger(t.max_events)||t.max_events<=0)return"max_events must be a positive integer.";if(t.max_events>O)return`max_events cannot exceed ${O}.`}if(t.idle_timeout_ms!==void 0){if(typeof t.idle_timeout_ms!="number"||!Number.isInteger(t.idle_timeout_ms)||t.idle_timeout_ms<=0)return"idle_timeout_ms must be a positive integer.";if(t.idle_timeout_ms>N)return`idle_timeout_ms cannot exceed ${N}ms (10 minutes).`}if(t.directory){if(!mt.isAbsolute(t.directory))return"Directory must be an absolute path.";let o=mt.resolve(t.directory),a=this.config.storage.getUserSkillsDirs();if(J(a,o))return"Explicitly running monitor commands from within the user skills directory is not allowed. Please use absolute paths for command parameter instead.";if(!this.config.getWorkspaceContext().isPathWithinWorkspace(t.directory))return`Directory '${t.directory}' is not within any of the registered workspace directories.`}return null}createInvocation(t){return new U(this.config,t)}toAutoClassifierInput(t){let o={command:t.command};return t.directory&&(o.directory=t.directory),o}};export{ht as MonitorTool,gt as sanitizeMonitorLine};
28
- /**
29
- * @license
30
- * Copyright 2025 Matilda
31
- * SPDX-License-Identifier: Apache-2.0
32
- */
@@ -1,17 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Le as y,We as X,Ze as Z,ja as R,qe as D,re as Y,tc as Q}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{J as B,K as k,L as U,Lb as z,M as K,N as q,O as b,P as W,Q as j,R as C,S as J,T as V,U as w,V as M,_c as H,ca as G}from"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as $,i as L,p as c,q as x}from"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{A as N,C as T,Y as F,z as _}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();import*as E from"node:fs";import*as m from"node:path";var ee=F("NOTEBOOK_EDIT");function g(d,r,t){return ee.debug("prior-read-rejected",{path:d,reason:r,type:t.type,displayMessage:t.displayMessage}),t}var u=class extends Error{constructor(t,e){super(t);this.type=e;this.name="NotebookEditError"}};function te(d,r){if(r==="delete")return"";if(typeof d!="string")throw new u(`new_source is required when edit_mode is "${r}".`,"invalid_tool_params");return d}function I(d,r){return d?q(d,r):`cell-${r}`}function oe(d,r,t){if(!r){if(t==="insert")return-1;throw new u("cell_id is required for replace and delete operations.","invalid_tool_params")}if(W(d,r))throw new u(`Cell ID "${r}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params");let e=j(d,r);if(e===-1)throw new u(`Cell with ID "${r}" not found in notebook.`,"notebook_cell_not_found");return e}function ie(d,r,t,e){let o={cell_type:r,metadata:{},source:w(t,e)},i=J(d);return i&&(o.id=i),M(o,r),o}function O(d,r){let t;try{t=k(d)}catch(a){throw new u(a instanceof Error?a.message:String(a),"notebook_invalid_json")}let e=r.edit_mode??"replace",o=te(r.new_source,e),i=b(t),n=oe(t,r.cell_id,e),l=C(t),p=U(d),s=(a,f)=>{let h=e==="insert"||e==="delete";return{...f,updatedContent:K(a,p),requiresReadAfterWrite:h&&!(i&&b(a))}};switch(e){case"insert":{let a=r.cell_type??"code",f=n===-1?0:n+1,h=ie(t,a,o,V(t,f));return t.cells.splice(f,0,h),s(t,{editedCellId:I(h,f),editedCellType:a,language:l,mode:e})}case"delete":{let[a]=t.cells.splice(n,1);return s(t,{editedCellId:I(a,n),editedCellType:a?.cell_type,language:l,mode:e})}case"replace":{let a=t.cells[n];if(!a)throw new u(`Cell index ${n} is out of range.`,"notebook_cell_not_found");let f=r.cell_type??a.cell_type;return a.source=w(o,Array.isArray(a.source)),M(a,f),s(t,{editedCellId:I(a,n),editedCellType:f,language:l,mode:e})}default:throw new u(`Unsupported notebook edit mode: ${e}`,"invalid_tool_params")}}function re(d,r,t){let e,o;try{e=k(r),o=k(d)}catch(i){throw new u(i instanceof Error?i.message:String(i),"notebook_invalid_json")}return{updatedContent:r,editedCellId:t.cell_id??"user-modified-notebook",editedCellType:void 0,language:C(e),mode:t.edit_mode??"replace",requiresReadAfterWrite:!b(o)||!b(e)}}async function A(d,r,t={}){if(d.getFileReadCacheDisabled())return{ok:!0};let e;try{e=await E.promises.stat(r)}catch(i){let n=i?.code;return n==="ENOENT"?t.expectExisting?g(r,"missing-after-read",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} disappeared after it was read. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${c.READ_FILE} first.`}):{ok:!0}:g(r,"stat-failed",{ok:!1,type:"prior_read_verification_failed",rawMessage:`Could not stat ${r} to verify prior notebook read (${n??"unknown error"}). Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${r}; re-run ${c.READ_FILE} before editing this notebook.`})}if(e.isDirectory())return g(r,"target-is-directory",{ok:!1,type:"target_is_directory",rawMessage:`${r} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."});if(!e.isFile())return g(r,"target-not-regular-file",{ok:!1,type:"target_not_regular_file",rawMessage:`${r} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."});let o=d.getFileReadCache().check(e);return o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadWasFull?{ok:!0}:o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadWasFull?g(r,"truncated-cache-entry",{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."}):o.state==="stale"?g(r,"stale-cache-entry",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} has been modified since you last read it. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${c.READ_FILE} first.`}):g(r,`cache-${o.state}`,{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} has not been fully read in this session. Use the ${c.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${c.READ_FILE} required before editing this notebook.`})}var P=class extends ${constructor(t,e,o){super(e);this.config=t;this.modifyMetadata=o}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){let t=N(this.params.notebook_path,this.config.getTargetDir()),e=this.params.edit_mode??"replace",o=this.params.cell_id??"beginning";return`${e} notebook cell ${o} in ${_(t)}`}async getDefaultPermission(){return"ask"}async getConfirmationDetails(t){let e=await this.prepareEdit(t),o=m.basename(this.params.notebook_path),i=R(o,e.originalContent,e.updatedContent,"Current","Proposed",D);return{type:"edit",title:`Confirm Notebook Edit: ${_(N(this.params.notebook_path,this.config.getTargetDir()))}`,fileName:o,filePath:this.params.notebook_path,fileDiff:i,originalContent:e.originalContent,newContent:e.updatedContent,onConfirm:async l=>{l==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}async prepareEdit(t){let e=await A(this.config,this.params.notebook_path);if(!e.ok)throw new y(e.rawMessage,e.type);let o,i=!1,n,l="lf";try{let s=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});o=s.content,i=s._meta?.bom??!1,n=s._meta?.encoding,l=s._meta?.lineEnding??X(s.content)}catch(s){throw t.aborted?s:s?.code==="ENOENT"?new y(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found"):new y(`Error reading notebook: ${s instanceof Error?s.message:String(s)}`,"read_content_failure")}let p=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!p.ok)throw new y(p.rawMessage,p.type);try{return this.modifyMetadata?.modifiedNotebookContent!==void 0?{...re(o,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}:{...O(o,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}}catch(s){throw s instanceof u?new y(s.message,s.type):s}}async execute(t){let e;try{e=await this.prepareEdit(t)}catch(o){if(t.aborted)throw o;let i=o instanceof y?o.errorType:"notebook_edit_failure",n=o instanceof Error?o.message:String(o);return{llmContent:n,returnDisplay:`Error: ${n}`,error:{message:n,type:i}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}let o=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!o.ok)return{llmContent:o.rawMessage,returnDisplay:`Error: ${o.displayMessage}`,error:{message:o.rawMessage,type:o.type}};await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:e.updatedContent,_meta:{bom:e.bom,encoding:e.encoding,lineEnding:e.lineEnding}}),this.modifyMetadata?.modifiedByUser||Q.getInstance().recordEdit(this.params.notebook_path,e.originalContent,e.updatedContent);try{let a=E.statSync(this.params.notebook_path),f=this.config.getFileReadCache();e.requiresReadAfterWrite?f.invalidate(a):f.recordWrite(this.params.notebook_path,a,{cacheable:!1})}catch(a){ee.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${a instanceof Error?a.message:String(a)}`)}let i=m.basename(this.params.notebook_path),n=R(i,e.originalContent,e.updatedContent,"Current","Proposed",D),l=Y(i,e.originalContent,this.modifyMetadata?.aiProposedContent??e.updatedContent,e.updatedContent);z(this.config,new H(S.Name,"update",e.updatedContent.split(`
4
- `).length,G(this.params.notebook_path),".ipynb",e.language));let p={fileDiff:n,fileName:i,originalContent:e.originalContent,newContent:e.updatedContent,diffStat:l},s=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated. Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${e.mode} cell ${e.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated. ${e.mode} cell ${e.editedCellId}.${e.mode==="delete"?"":`
5
-
6
- Updated source:
7
-
8
- ---
9
-
10
- ${B(this.params.new_source??"")}`}`;try{let a=await Z(this.config,this.params.notebook_path);a&&(s+=`
11
-
12
- ${a}`)}catch{}return{llmContent:s,returnDisplay:p,resultFilePaths:[this.params.notebook_path]}}catch(o){let i=o instanceof Error?o.message:String(o);return{llmContent:`Error writing notebook: ${i}`,returnDisplay:`Error writing notebook: ${i}`,error:{message:i,type:"file_write_failure"}}}}},S=class d extends L{constructor(t){super(d.Name,x.NOTEBOOK_EDIT,`Edits a Jupyter notebook (.ipynb) safely at the cell level. Use this instead of ${c.EDIT} or ${c.WRITE_FILE} for notebook cells. Supports replacing, inserting, and deleting cells. Always read the notebook first with ${c.READ_FILE}; then use the cell IDs shown in that output.`,"edit",{properties:{notebook_path:{description:"Absolute path to the Jupyter notebook file to edit. Must end with .ipynb.",type:"string"},cell_id:{description:"Target cell ID from read_file output, or cell-N 0-based fallback. Required for replace and delete. For insert, the new cell is inserted after this cell; if omitted, inserted at the beginning.",type:"string"},new_source:{description:"New source content for replace and insert operations. Not required for delete.",type:"string"},cell_type:{description:"Cell type for inserted cells or type conversion on replace.",type:"string",enum:["code","markdown"]},edit_mode:{description:"Notebook edit operation. Defaults to replace.",type:"string",enum:["replace","insert","delete"]}},required:["notebook_path"],additionalProperties:!1,type:"object"});this.config=t}static Name=c.NOTEBOOK_EDIT;modifyMetadataByParams=new WeakMap;modifyMetadataByKey=new Map;validateToolParamValues(t){if(t.notebook_path=T(t.notebook_path.trim()),!t.notebook_path)return"The 'notebook_path' parameter must be non-empty.";if(!m.isAbsolute(t.notebook_path))return`Notebook path must be absolute: ${t.notebook_path}`;if(m.extname(t.notebook_path).toLowerCase()!==".ipynb")return"File must be a Jupyter notebook (.ipynb). Use the edit tool for other file types.";let e=t.edit_mode??"replace";return["replace","insert","delete"].includes(e)?t.cell_type&&!["code","markdown"].includes(t.cell_type)?"cell_type must be 'code' or 'markdown'.":e!=="insert"&&!t.cell_id?"cell_id is required for replace and delete operations.":e!=="delete"&&typeof t.new_source!="string"?`new_source is required when edit_mode is "${e}".`:this.config.getFileService().shouldMatildaIgnoreFile(t.notebook_path)?`File path '${t.notebook_path}' is ignored by .matildaignore pattern(s).`:null:"edit_mode must be 'replace', 'insert', or 'delete'."}createInvocation(t){return new P(this.config,t,this.consumeModifyMetadata(t))}getModifyMetadataKey(t){return JSON.stringify({notebook_path:T(t.notebook_path.trim()),cell_id:t.cell_id,new_source:t.new_source,cell_type:t.cell_type,edit_mode:t.edit_mode})}rememberModifyMetadata(t,e){this.modifyMetadataByParams.set(t,e);let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o)??[];i.push(e),this.modifyMetadataByKey.set(o,i)}consumeModifyMetadata(t){let e=this.modifyMetadataByParams.get(t);if(e)return this.modifyMetadataByParams.delete(t),this.removeQueuedModifyMetadata(t,e),e;let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o),n=i?.shift();return i&&i.length===0&&this.modifyMetadataByKey.delete(o),n}removeQueuedModifyMetadata(t,e){let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o);if(!i)return;let n=i.indexOf(e);n!==-1&&i.splice(n,1),i.length===0&&this.modifyMetadataByKey.delete(o)}getModifyContext(t){let e=new Map,o=async i=>{let n=e.get(i.notebook_path);if(n!==void 0)return n;let{content:l}=await this.config.getFileSystemService().readTextFile({path:i.notebook_path});return e.set(i.notebook_path,l),l};return{getFilePath:i=>i.notebook_path,getCurrentContent:async i=>o(i),getProposedContent:async i=>{let n=await o(i);return O(n,i).updatedContent},createUpdatedParams:(i,n,l)=>{let p=this.modifyMetadataByParams.get(l)?.aiProposedContent;if(p===void 0)try{p=O(i,l).updatedContent}catch{p=n}let s={...l};return this.rememberModifyMetadata(s,{aiProposedContent:p,modifiedByUser:!0,modifiedNotebookContent:n}),s}}}};export{S as NotebookEditTool,O as applyNotebookEdit};
13
- /**
14
- * @license
15
- * Copyright 2026 Matilda Team
16
- * SPDX-License-Identifier: Apache-2.0
17
- */
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{wc as a}from"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.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 ReadFileTool};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Lj as a,Mj as b}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.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{b as RipGrepTool,a as _resetRipGrepCachesForTest};
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as E}from"./chunk-7ZATDBWL.js";import{wa as P}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{L as l,Y as c}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as s}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";s();import{stat as V}from"node:fs/promises";import{join as p}from"node:path";s();import{readdir as N,stat as H,rm as F,rmdir as A}from"node:fs/promises";import{join as y}from"node:path";var k=c("HOUSEKEEPING"),U=24*60*60*1e3,$=60*60*1e3,_=20;function T(e){let t=e>0?e*U:$;return new Date(Date.now()-t)}async function b(e){let t={removed:0,errors:0},r=y(l.getGlobalMatildaDir(),P),i=e.excludeSessionIds??new Set,o;try{o=await N(r,{withFileTypes:!0})}catch(n){return G(n)||k.error("readdir failed",n),t}let a=o.filter(n=>n.isDirectory()&&!i.has(n.name)).map(n=>y(r,n.name));for(let n=0;n<a.length;n+=_){let v=a.slice(n,n+_);await Promise.all(v.map(async g=>{try{(await H(g)).mtime<e.cutoffDate&&(await F(g,{recursive:!0,force:!0}),t.removed++)}catch(w){t.errors++,k.error(`failed to sweep ${g}`,w)}}))}return await A(r).catch(()=>{}),t}function G(e){return e?.code==="ENOENT"}s();import{mkdir as Y,open as K,stat as I,unlink as D,writeFile as j}from"node:fs/promises";import{dirname as B}from"node:path";var m=c("HOUSEKEEPING"),q=24*60*60*1e3,J=60*60*1e3;async function R(e,t){let r=e.minIntervalMs??q,i=e.staleLockMs??J;if(await Y(B(e.lockPath),{recursive:!0,mode:448}).catch(()=>{}),await C(e.markerPath,r,e.name))return!1;let o=await h(e.lockPath);if(!o){try{let a=await I(e.lockPath);Date.now()-a.mtimeMs>i&&(await D(e.lockPath).catch(()=>{}),o=await h(e.lockPath))}catch{o=await h(e.lockPath)}if(!o)return m.debug(`${e.name}: skipping, lock held`),!1}try{if(await C(e.markerPath,r,e.name))return!1;let a=!1;try{await t(),a=!0}finally{if(a)try{await j(e.markerPath,new Date().toISOString())}catch(n){m.debug(`${e.name}: marker write failed (cleanup succeeded)`,n)}}return a}finally{await D(e.lockPath).catch(()=>{m.debug(`${e.name}: lock unlink failed (harmless)`)})}}async function C(e,t,r){try{let i=await I(e),o=Date.now()-i.mtimeMs;if(o<t)return m.debug(`${r}: skipping, ran ${o}ms ago`),!0}catch{}return!1}async function h(e){try{return await(await K(e,"wx")).close(),!0}catch(t){if(t?.code==="EEXIST")return!1;throw t}}var u=c("HOUSEKEEPING"),O=10*60*1e3,W=24*60*60*1e3,X=60*1e3,z=7*24*60*60*1e3,Q=60*1e3,f=".file-history-cleanup",d=!1;function pe(e,t){d||(d=!0,Z(e,t).catch(r=>{d=!1,u.error("scheduleFirstPass failed; chain will retry on next start",r)}))}async function Z(e,t){let r=p(l.getGlobalMatildaDir(),f),i=await L(r)?Q:O;u.debug(`first pass in ${i/1e3}s`),setTimeout(()=>S(e,t),i).unref()}async function L(e){try{let t=await V(e);return Date.now()-t.mtimeMs>z}catch{return!0}}async function M(e,t){if(E()<X){u.debug("user active, deferring 10 min"),setTimeout(()=>S(e,t),O).unref();return}try{await x(e,t)}catch(r){u.error("housekeeping pass failed; will retry next cycle",r)}setTimeout(()=>S(e,t),W).unref()}function S(e,t){M(e,t).catch(r=>{u.error("runPass rejected unexpectedly",r)})}async function x(e,t){let r=t.merged.general?.cleanupPeriodDays??30,i=T(r),o=e.getSessionId(),a=l.getGlobalMatildaDir();await R({name:"file-history-cleanup",markerPath:p(a,f),lockPath:p(a,f+".lock")},async()=>{let n=await b({cutoffDate:i,excludeSessionIds:new Set([o])});u.debug(`file-history: removed=${n.removed} errors=${n.errors}`)})}function Se(){d=!1}var we=L,Pe=x,Ee=M,ye=f;export{ye as _FILE_HISTORY_MARKER_FOR_TESTING,we as _needsCatchUpForTesting,Se as _resetForTesting,Pe as _runHousekeepingForTesting,Ee as _runPassForTesting,pe as startBackgroundHousekeeping};
4
- /**
5
- * @license
6
- * Copyright 2025 Google LLC
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{$e as b,_e as a,af as c,bf as d,cf as e,df as f,ef as g}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.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{b as OUTPUT_UPDATE_INTERVAL_MS,g as ShellTool,f as ShellToolInvocation,c as buildLongRunningForegroundHint,d as detectBlockedSleepPattern,a as parseNumstat,e as repairLeakedShellToolArgMarkup};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{$ as pi,$a as pj,$b as tk,$c as ql,$d as qm,$f as co,$g as aq,$h as br,$i as as,$j as $s,$k as $t,A as Zg,Aa as Qi,Ab as Qj,Ac as Tk,Ad as Rl,Ae as Lm,Af as tn,Ag as Fo,Ah as Cq,Ai as Er,Aj as zs,Ak as At,Al as zu,B as _g,Ba as Ri,Bb as Rj,Bc as Uk,Bd as Sl,Be as Mm,Bf as un,Bg as Cp,Bh as Dq,Bi as Fr,Bj as As,Bk as Bt,Bl as Au,C as $g,Ca as Si,Cb as Sj,Cc as Vk,Cd as Tl,Ce as Nm,Cf as vn,Cg as Dp,Ch as Eq,Ci as Gr,Cj as Bs,Ck as Ct,Cl as Bu,D as ah,Da as Ti,Db as Tj,Dd as Ul,De as Om,Df as wn,Dg as Ep,Dh as Fq,Di as Hr,Dj as Cs,Dk as Dt,Dl as Cu,E as bh,Ea as Ui,Eb as Uj,Ec as Wk,Ed as Vl,Ee as Pm,Ef as xn,Eg as Fp,Eh as Gq,Ei as Ir,Ej as Ds,Ek as Et,El as Du,F as ch,Fa as Vi,Fb as Vj,Fc as Xk,Fd as Wl,Fe as Qm,Ff as yn,Fg as Gp,Fh as Hq,Fi as Jr,Fj as Es,Fk as Ft,Fl as Eu,G as dh,Ga as Wi,Gb as Wj,Gc as Yk,Gd as Xl,Ge as Rm,Gf as zn,Gg as Hp,Gh as Iq,Gi as Kr,Gj as Fs,Gk as Gt,Gl as Fu,H as eh,Ha as Xi,Hb as Xj,Hc as Zk,Hd as Yl,He as Sm,Hf as An,Hg as Ip,Hh as Jq,Hj as Gs,Hk as Ht,Hl as Gu,Ia as Yi,Ib as Yj,Ic as _k,Id as Zl,If as Bn,Ig as Jp,Ih as Kq,Ij as Hs,Ik as It,Il as Hu,J as fh,Ja as Zi,Jb as Zj,Jc as $k,Jd as _l,Je as Tm,Jf as Cn,Jg as Kp,Jh as Lq,Ji as Lr,Jk as Jt,Jl as Iu,K as gh,Ka as _i,Kb as _j,Kc as al,Kd as $l,Ke as Um,Kf as Nn,Kg as Lp,Kh as Mq,Ki as Mr,Kk as Kt,Kl as Ju,L as hh,La as $i,Lb as $j,Ld as am,Lf as On,Lg as Mp,Lh as Nq,Li as Nr,Lj as Is,Lk as Lt,Ll as Ku,M as ai,Ma as aj,Mb as ak,Mc as bl,Md as bm,Mf as Pn,Mg as Np,Mh as Oq,Mi as Or,Mj as Js,Mk as Mt,Ml as Lu,N as bi,Na as bj,Nb as bk,Nc as cl,Nd as cm,Nf as Qn,Ng as Op,Nh as Pq,Ni as Pr,Nj as Ks,Nk as Nt,Nl as Mu,O as ci,Oa as cj,Ob as ck,Oc as dl,Od as dm,Of as Rn,Og as Pp,Oh as Qq,Oi as Qr,Oj as Ls,Ok as Ot,Ol as Nu,P as di,Pa as dj,Pb as dk,Pc as el,Pd as em,Pf as Sn,Pg as Qp,Ph as Rq,Pi as Rr,Pj as Ms,Pk as Pt,Pl as Ou,Q as ei,Qa as ej,Qb as ek,Qc as fl,Qd as fm,Qf as Tn,Qg as Rp,Qh as Sq,Qi as Sr,Qj as Ns,Qk as Qt,Ql as Pu,R as fi,Ra as fj,Rb as fk,Rc as gl,Rd as gm,Rf as Un,Rg as Sp,Rh as Tq,Ri as Tr,Rj as Rs,Rk as Rt,Rl as Qu,S as gi,Sa as gj,Sb as ik,Sc as hl,Sd as hm,Se as Vm,Sf as Vn,Sg as Tp,Sh as Uq,Si as Ur,Sj as Ss,Sk as St,T as hi,Ta as hj,Tb as lk,Tc as il,Td as im,Te as Wm,Tf as Wn,Tg as Up,Th as Vq,Ti as Vr,Tj as Ts,Tk as Tt,U as ii,Ua as ij,Ub as mk,Uc as jl,Ud as jm,Ue as Xm,Uf as Xn,Ug as Vp,Uh as Wq,Ui as Wr,Uj as Us,Uk as Ut,V as ji,Va as jj,Vb as nk,Vc as kl,Vd as km,Ve as Ym,Vf as Yn,Vg as Wp,Vh as Xq,Vi as Xr,Vj as Vs,Vk as Vt,W as ki,Wa as kj,Wb as ok,Wc as ll,Wd as lm,We as Zm,Wf as Zn,Wg as Xp,Wh as Yq,Wj as Ws,Wk as Wt,X as li,Xa as lj,Xb as pk,Xc as ml,Xd as mm,Xe as _m,Xf as _n,Xg as Yp,Xh as Zq,Xi as Yr,Xj as Xs,Xk as Xt,Y as mi,Ya as mj,Yb as qk,Yc as nl,Yd as nm,Ye as $m,Yf as $n,Yg as Zp,Yh as _q,Yi as Zr,Yj as Ys,Yk as Yt,Z as ni,Za as nj,Zb as rk,Zc as ol,Zd as om,Zf as ao,Zg as _p,Zh as $q,Zi as _r,Zj as Zs,Zk as Zt,_ as oi,_a as oj,_b as sk,_c as pl,_d as pm,_f as bo,_g as $p,_h as ar,_i as $r,_j as _s,_k as _t,a as qa,aa as qi,ab as qj,ac as uk,ad as rl,ae as rm,ag as eo,ah as bq,ai as cr,aj as bs,ak as at,al as au,b as ra,ba as ri,bb as rj,bc as vk,bd as sl,be as sm,bg as fo,bh as cq,bi as dr,bj as cs,bk as bt,bl as bu,c as sa,ca as si,cb as sj,cc as wk,cd as tl,ce as tm,cg as go,ch as dq,ci as er,ck as ct,cl as cu,d as ta,da as ti,db as tj,dc as xk,dd as ul,de as um,dg as ho,dh as eq,di as fr,dk as dt,dl as du,e as ua,ea as ui,eb as uj,ec as yk,ed as vl,ee as vm,eg as io,eh as fq,ei as ir,ej as ds,ek as et,el as eu,f as va,fa as wi,fb as vj,fc as zk,fd as wl,fe as wm,ff as an,fg as jo,fh as gq,fi as jr,fj as es,fk as ft,fl as fu,g as wa,ga as xi,gb as wj,gc as Ak,gd as xl,ge as xm,gf as bn,gh as iq,gi as kr,gj as fs,gk as gt,gl as gu,h as xa,ha as yi,hb as xj,hc as Bk,hd as yl,he as ym,hf as cn,hh as jq,hi as lr,hj as gs,hk as ht,hl as hu,i as ya,ia as zi,ib as yj,ic as Ck,id as zl,ie as zm,if as dn,ih as kq,ii as mr,ij as hs,ik as it,il as iu,j as Ig,jb as zj,jc as Dk,jd as Al,je as Am,jf as en,jh as lq,ji as nr,jj as is,jk as jt,jl as ju,k as Jg,ka as Ai,kb as Aj,kc as Ek,kd as Bl,ke as Bm,kf as fn,kh as mq,ki as or,kj as js,kk as kt,kl as ku,l as Kg,la as Bi,lb as Bj,lc as Fk,ld as Cl,le as Cm,lf as gn,lh as nq,li as pr,lj as ks,lk as lt,ll as lu,m as Lg,ma as Ci,mb as Cj,mc as Gk,md as Dl,me as Dm,mf as hn,mg as ko,mh as oq,mi as qr,mj as ls,mk as mt,ml as mu,n as Mg,na as Di,nb as Dj,nc as Hk,nd as El,ne as Em,nf as jn,ng as lo,nh as pq,ni as rr,nj as ms,nk as nt,nl as nu,o as Ng,oa as Ei,ob as Ej,oc as Ik,od as Fl,oe as Fm,of as kn,og as mo,oh as qq,oi as sr,oj as ns,ok as ot,ol as ou,p as Og,pa as Fi,pb as Fj,pc as Jk,pd as Gl,pe as Gm,pf as ln,pg as no,ph as rq,pi as tr,pj as os,pk as pt,pl as pu,q as Pg,qa as Gi,qb as Gj,qc as Kk,qd as Hl,qf as mn,qg as oo,qh as sq,qi as ur,qj as ps,qk as qt,ql as qu,r as Qg,ra as Hi,rb as Hj,rc as Lk,rd as Il,rf as nn,rg as po,rh as tq,ri as vr,rj as qs,rk as rt,rl as ru,s as Rg,sa as Ii,sb as Ij,sc as Mk,sd as Jl,se as Hm,sf as on,sg as qo,sh as uq,si as wr,sj as rs,sk as st,sl as su,t as Sg,ta as Ji,tb as Jj,td as Kl,te as Im,tf as pn,tg as ro,th as vq,ti as xr,tj as ss,tk as tt,tl as tu,u as Tg,ua as Ki,ub as Kj,uc as Nk,ud as Ll,uf as qn,ug as so,uh as wq,ui as yr,uj as ts,uk as ut,ul as uu,v as Ug,va as Li,vb as Lj,vc as Ok,vd as Ml,vg as to,vh as xq,vi as zr,vj as us,vk as vt,vl as vu,w as Vg,wa as Mi,wb as Mj,wc as Pk,wd as Nl,wg as uo,wh as yq,wi as Ar,wj as vs,wk as wt,x as Wg,xa as Ni,xb as Nj,xc as Qk,xd as Ol,xg as vo,xh as zq,xi as Br,xj as ws,xk as xt,xl as wu,y as Xg,ya as Oi,yb as Oj,yc as Rk,yd as Pl,ye as Jm,yf as rn,yg as wo,yh as Aq,yi as Cr,yj as xs,yk as yt,yl as xu,z as Yg,za as Pi,zb as Pj,zc as Sk,zd as Ql,ze as Km,zf as sn,zg as Eo,zh as Bq,zi as Dr,zj as ys,zk as zt,zl as yu}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import{a as Go,b as Ho,c as Io,d as Jo,e as Ko,f as dp,g as ep,h as fp,i as gp,j as hp,k as ip,l as jp,m as kp}from"./chunk-FUNLOUYI.js";import{a as lp,b as mp,c as np,d as op,e as pp,f as qp,g as rp,h as sp,i as tp,j as up,k as vp,l as wp,m as xp,n as yp,o as zp,p as Ap,q as Bp}from"./chunk-R3H6IWFK.js";import{a as Lo,b as Mo,c as No,d as Oo,e as Po,f as Qo,g as Ro,h as So,i as To,j as Uo,k as Vo,l as Wo,m as Xo,n as Yo,o as Zo,p as _o,q as $o,r as ap,s as bp,t as cp}from"./chunk-OMZ5SGMK.js";import{a as vi}from"./chunk-C2ZWB2NT.js";import{c as Os,e as Ps,f as Qs}from"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import{b as ih,c as jh,d as kh,e as lh,f as mh,g as nh,h as oh,i as ph,j as qh,k as rh,l as sh,m as th,n as uh,o as Uh,p as Vh,q as Wh,r as Xh,s as Yh,t as Zh,u as _h,v as $h}from"./chunk-FT76AZPN.js";import{a as gr,b as hr}from"./chunk-47XR7IMP.js";import{b as hq}from"./chunk-QEI3OETI.js";import{a as Dn,b as En,c as Fn,d as Gn,e as Hn,f as In,g as Jn,h as Kn,i as Ln,j as Mn,k as xo,l as yo,m as zo,n as Ao,o as Bo,p as Co,q as Do}from"./chunk-QKYGQLWC.js";import{c as jk,f as kk}from"./chunk-MNGFXISD.js";import{a as vh,b as wh,c as xh,d as yh,e as zh,f as Ah,g as Bh,h as Ch,i as Dh,j as Eh,k as Fh,l as Gh,m as Hh,n as Ih,o as Jh,p as Kh,q as Lh,r as Mh,s as Nh,t as Oh,u as Ph,v as Qh,w as Rh,x as Sh,y as Th}from"./chunk-4R2OFVPK.js";import{a as gk,b as hk}from"./chunk-RNKDFE2S.js";import"./chunk-EMWHQSMS.js";import{b as dg,d as eg,e as fg,g as gg,h as hg,i as ig,j as jg,k as kg}from"./chunk-S4K76QPI.js";import{A as Re,B as Se,C as Te,D as Ue,E as Ve,F as We,G as Xe,H as Ye,I as Ze,J as _e,K as $e,L as af,P as pf,Q as qf,T as rf,U as sf,V as tf,X as Mf,Y as Nf,Z as Of,aa as Pf,b as qe,c as re,ca as Qf,d as se,da as Rf,e as te,ea as Sf,fa as Vf,ga as Wf,ha as Xf,i as ue,ia as Yf,j as ve,ja as Zf,k as we,ka as _f,l as Ce,la as $f,m as De,ma as ag,n as Ee,na as bg,o as Fe,oa as cg,p as Ge,pa as Dg,q as He,qa as Eg,r as Ie,ra as Fg,s as Je,sa as Gg,t as Ke,ta as Hg,u as Le,v as Me,w as Ne,x as Oe,y as Pe,z as Qe}from"./chunk-LCYHQMKE.js";import{a as uf,b as vf,c as wf,d as xf}from"./chunk-4F4DA5UI.js";import{a as If,e as Jf,f as Kf,g as Lf}from"./chunk-DC7LAFZZ.js";import{e as xe,f as ye,g as ze,h as Ae,i as Be,m as yf,n as zf,o as Af,p as Bf,q as Cf,r as Df,s as Ef,t as Ff,u as Gf,v as Hf}from"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{b as bf,c as cf,d as df,e as ef,f as ff,g as gf,h as hf,i as jf,j as kf,k as lf,l as mf,m as nf,n as of}from"./chunk-SDTWBD62.js";import{$ as cb,A as Qa,Aa as Cb,Ab as uc,B as Ra,Ba as Db,Bb as vc,C as Sa,Ca as Eb,Cb as wc,Cc as Ed,D as Ta,Da as Fb,Db as xc,Dc as Fd,E as Ua,Ea as Gb,Eb as yc,Ec as Gd,F as Va,Fa as Hb,Fb as zc,Fc as Hd,G as Wa,Ga as Ib,Gb as Ac,Gc as Id,H as Xa,Ha as Jb,Hb as Bc,Hc as Jd,I as Ya,Ia as Kb,Ib as Cc,Ic as Kd,Ja as Lb,Jb as Dc,Jc as Ld,Ka as Mb,Kb as Ec,Kc as Md,La as Nb,Lc as Nd,Ma as Ob,Mb as Fc,Mc as Od,Na as Pb,Nb as Gc,Nc as Pd,Ob as Hc,Oc as Qd,Pb as Ic,Pc as Rd,Qa as Qb,Qb as Jc,Rb as Kc,Sc as Sd,Ta as Rb,Tc as Td,Ua as Sb,Ub as Lc,Uc as Ud,Va as Tb,Vb as Mc,Vc as Vd,W as Za,Wa as Ub,Wb as Nc,Wc as Wd,X as _a,Xa as Vb,Xb as Oc,Xc as Xd,Y as $a,Ya as Wb,Yb as Pc,Yc as Yd,Z as ab,Za as Xb,Zb as Qc,Zc as Zd,_ as bb,_a as Yb,aa as db,ab as Zb,b as _,ba as eb,bb as _b,c as $,ca as fb,cb as $b,cc as Rc,cd as _d,d as aa,da as gb,db as ac,dd as $d,e as na,ea as hb,eb as bc,ec as Sc,ed as ae,fa as ib,fb as cc,fc as Tc,g as oa,ga as jb,gb as dc,gc as Uc,gd as be,h as pa,ha as kb,hb as ec,hc as Vc,hd as ce,ia as lb,ib as fc,ic as Wc,ja as mb,jb as gc,jc as Xc,jd as de,ka as nb,kb as hc,kc as Yc,la as ob,lb as ic,lc as Zc,ld as ee,ma as pb,mb as jc,mc as _c,md as fe,n as Da,nb as kc,nc as $c,nd as ge,o as Ea,oa as qb,ob as lc,oc as ad,od as he,p as Fa,pa as rb,pb as mc,pc as bd,pd as ie,q as Ga,qa as sb,qb as nc,qc as cd,qd as je,r as Ha,ra as tb,rb as oc,rc as dd,rd as ke,s as Ia,sa as ub,sb as pc,sc as ed,sd as le,t as Ja,ta as vb,tc as fd,td as me,u as Ka,ua as wb,ud as ne,v as La,va as xb,vd as oe,w as Ma,wa as yb,wb as qc,wc as Dd,wd as pe,x as Na,xa as zb,xb as rc,y as Oa,ya as Ab,yb as sc,z as Pa,za as Bb,zb as tc}from"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{a as gd,b as hd,c as id,d as jd,e as kd,f as ld,g as md,h as nd,i as od,j as pd,k as qd,l as rd,m as sd,n as td,o as ud,p as vd,q as wd,r as xd,s as yd,t as zd,u as Ad,v as Bd,w as Cd}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{a as ba,e as ca,f as da,g as ea,h as fa,i as ga,j as ha,k as ia,l as ja,m as ka,n as la,o as ma,p as za,q as Aa,r as Ba,s as Ca}from"./chunk-5U3A6KMU.js";import{a as lg,b as mg,d as ng,e as og,f as pg,g as qg,h as rg,i as sg,j as tg,k as ug,l as vg,m as wg,n as xg,o as yg,p as zg,q as Ag,r as Bg,t as Cg}from"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import{a as Tf,b as Uf}from"./chunk-3YLXGE6T.js";import{a as V,b as W,c as X,d as Y,e as Z}from"./chunk-IOCF4XSR.js";import{A,B,C,D,E,F,G,H,I,J,L as K,M as L,Q as O,R as P,U as Q,V as R,W as S,X as T,Y as U,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import{c as M,g as N}from"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{Ea as AGENT_CONTEXT_FILENAME,$n as AGENT_WORKTREE_HEX_LENGTH,_n as AGENT_WORKTREE_PREFIX,ao as AGENT_WORKTREE_SLUG_PATTERN,Dj as ALL_PROVIDERS,Ss as APPROVAL_MODES,Us as APPROVAL_MODE_INFO,qa as ARENA_MAX_AGENTS,kd as AUTO_MEMORY_CONSOLIDATION_LOCK_FILENAME,gd as AUTO_MEMORY_DIRNAME,jd as AUTO_MEMORY_EXTRACT_CURSOR_FILENAME,hd as AUTO_MEMORY_INDEX_FILENAME,id as AUTO_MEMORY_METADATA_FILENAME,Ok as AUTO_MEMORY_SCHEMA_VERSION,Nk as AUTO_MEMORY_TYPES,bm as AUTO_MODE_DENIAL_LIMITS,Wp as AUTO_SKILL_THRESHOLD,wu as AbortError,Pn as AgentCore,zn as AgentEventEmitter,yn as AgentEventType,Cn as AgentHeadless,oo as AgentInteractive,da as AgentStatistics,ua as AgentStatus,ta as AgentTerminateMode,Sh as AgentType,Nd as ApiCancelEvent,Md as ApiErrorEvent,Ld as ApiRequestEvent,pb as ApiRequestPhase,Od as ApiResponseEvent,Rs as ApprovalMode,ya as ArenaAgentClient,so as ArenaEventEmitter,ro as ArenaEventType,wo as ArenaManager,ra as ArenaSessionStatus,no as AsyncMessageQueue,de as AuthEvent,at as AuthProviderType,Dg as AuthType,Fp as BACKGROUND_AGENT_CONCURRENCY_ENV,Yn as BASELINE_COMMIT_MESSAGE,Ta as BINARY_EXTENSIONS,La as BINARY_FILE_PATTERNS,Gu as BTW_MAX_INPUT_LENGTH,Nq as BUNDLE_CHUNK_DIR,Mp as BackgroundAgentResumeService,yr as BackgroundShellRegistry,Kp as BackgroundTaskRegistry,q as BadRequestError,ga as BaseDeclarativeTool,ea as BaseToolInvocation,br as BudgetExhaustedError,jo as BuiltinAgentRegistry,Af as CAPPED_DEFAULT_MAX_TOKENS,_t as CODE_ACTION_KIND_LABELS,pl as COMMAND_SUBSTITUTION_WARNING,Na as COMMON_DIRECTORY_EXCLUDES,Ka as COMMON_IGNORE_PATTERNS,ma as CONCURRENCY_SAFE_KINDS,Aj as CUSTOM_API_KEY_ENV_PREFIX,Qj as ChatRecordingService,qn as CloseDiffRequestSchema,Nm as ColorMode,Uj as CompressionStatus,ws as ConditionalRulesRegistry,bt as Config,An as ContextState,Yd as ConversationFinishedEvent,xn as CoreToolScheduler,qg as CredentialsClearRequiredError,dq as CronScheduler,Fe as DAEMON_TRACEPARENT_META_KEY,Ge as DAEMON_TRACESTATE_META_KEY,Xp as DEFAULT_AUTO_DREAM_MIN_HOURS,Yp as DEFAULT_AUTO_DREAM_MIN_SESSIONS,Lp as DEFAULT_BACKGROUND_AGENT_CONTINUATION_MESSAGE,io as DEFAULT_BUILTIN_SUBAGENT_TYPE,Da as DEFAULT_CONTEXT_FILENAME,Za as DEFAULT_ENCODING,Qa as DEFAULT_FILE_EXCLUDES,hk as DEFAULT_FILE_FILTERING_OPTIONS,St as DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS,Rt as DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS,Ut as DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS,Vt as DEFAULT_LSP_MAX_RESTARTS,Pt as DEFAULT_LSP_REQUEST_TIMEOUT_MS,Xt as DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS,Wt as DEFAULT_LSP_SOCKET_RETRY_DELAY_MS,Ot as DEFAULT_LSP_STARTUP_TIMEOUT_MS,Qt as DEFAULT_LSP_WARMUP_DELAY_MS,Tt as DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS,wf as DEFAULT_MATILDA_EMBEDDING_MODEL,vf as DEFAULT_MATILDA_FLASH_MODEL,uf as DEFAULT_MATILDA_MODEL,Ep as DEFAULT_MAX_CONCURRENT_BACKGROUND_AGENTS,et as DEFAULT_MAX_INLINE_MEDIA_BYTES,gk as DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,tf as DEFAULT_OTLP_ENDPOINT,zf as DEFAULT_OUTPUT_TOKEN_LIMIT,Vs as DEFAULT_PR_ATTRIBUTION_MESSAGE,ai as DEFAULT_STOP_HOOK_BLOCK_CAP,sf as DEFAULT_TELEMETRY_TARGET,yf as DEFAULT_TOKEN_LIMIT,Ys as DEFAULT_TOOL_OUTPUT_BATCH_BUDGET,hh as DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD,Xs as DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,Ws as DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,Zt as DIAGNOSTIC_SEVERITY_LABELS,ko as DISPLAY_MODE,Up as DREAM_TASK_TYPE,fa as DeclarativeTool,Eh as DefaultHookOutput,Ed as DiscoveredMCPTool,er as DiscoveredTool,Bf as ESCALATED_MAX_TOKENS,$ as EVENT_API_ERROR,aa as EVENT_API_RESPONSE,_ as EVENT_TOOL_CALL,Nn as EXCLUDED_TOOLS_FOR_SUBAGENTS,Dr as EXTENSIONS_CONFIG_FILENAME,Cr as EXTENSIONS_DIRECTORY_NAME,Fr as EXTENSION_SETTINGS_FILENAME,On as EXTERNAL_MESSAGE_PREFIX,Tp as EXTRACT_TASK_TYPE,Hd as EndSessionEvent,ke as ExtensionDisableEvent,be as ExtensionEnableEvent,_d as ExtensionInstallEvent,ls as ExtensionManager,ds as ExtensionSettingScope,ae as ExtensionUninstallEvent,ks as ExtensionUpdateState,Mi as FILE_HISTORY_DIR,Sn as FORK_SUBAGENT_TYPE,g as FatalAuthenticationError,m as FatalBudgetExceededError,n as FatalCancellationError,j as FatalConfigError,f as FatalError,h as FatalInputError,i as FatalSandboxError,l as FatalToolExecutionError,k as FatalTurnLimitedError,fo as FileDiscoveryService,Vm as FileEncoding,Ra as FileExclusions,Pi as FileHistoryService,lb as FileOperation,Br as FileReadCache,jn as FileSchema,yu as FileSearchFactory,Pd as FlashFallbackEvent,o as ForbiddenError,Xh as GOAL_HOOK_TIMEOUT_MS,Wh as GOAL_HOOK_TIMEOUT_SECONDS,t as GOOGLE_ACCOUNTS_FILENAME,Kk as GeminiChat,cq as GeminiClient,Tj as GeminiEventType,eo as GitIgnoreParser,co as GitWorktreeService,yh as HOOKS_CONFIG_FIELDS,wh as HookEventName,xh as HookPhase,qs as HookRegistry,ss as HookSystem,zh as HookType,vh as HooksConfigSource,rn as IDEConnectionStatus,an as IDE_DEFINITIONS,dn as IDE_MAX_OPEN_FILES,en as IDE_MAX_SELECTED_TEXT_LENGTH,fn as IDE_REQUEST_TIMEOUT_MS,ru as IDLE_SPECULATION,Co as INBOXES_DIR,iu as INITIAL_FOLLOWUP_STATE,Er as INSTALL_METADATA_FILENAME,mo as ITermBackend,sn as IdeClient,Xd as IdeConnectionEvent,Wd as IdeConnectionType,ln as IdeContextNotificationSchema,kn as IdeContextSchema,gn as IdeContextStore,mn as IdeDiffAcceptedNotificationSchema,on as IdeDiffClosedNotificationSchema,nn as IdeDiffRejectedNotificationSchema,Qs as Ignore,po as InProcessBackend,gr as InputFormat,_q as InvalidMcpConfigError,Ik as InvalidStreamError,ct as JsonFormatter,hq as KeychainTokenStorage,ka as Kind,Zd as KittySequenceOverflowEvent,yo as LEADER_NAME,Ui as LITE_READ_BUF_SIZE,Fa as LOCAL_CONTEXT_FILENAME,qt as Logger,Rd as LoopType,$t as LspConfigLoader,au as LspConnectionFactory,bu as LspResponseNormalizer,cu as LspServerManager,xf as MAINLINE_CODER_MODEL,na as MAIN_SOURCE,If as MATILDA_API_KEY_ENV_KEY,cn as MATILDA_CODE_COMPANION_EXTENSION_NAME,It as MATILDA_CODE_SIMPLE_ENV_VAR,Ag as MATILDA_CREDENTIAL_FILE_MODE,s as MATILDA_DIR,Pf as MATILDA_OAUTH_MODELS,rc as MATILDA_SESSION_ID_HASH_ATTR,qc as MATILDA_USER_ID_HASH_ATTR,Hp as MAX_CONCURRENT_BACKGROUND_AGENTS,sr as MAX_CONCURRENT_MONITORS,Bi as MAX_DIFF_SIZE_BYTES,Ai as MAX_FILES,Di as MAX_FILES_FOR_DETAILS,Vh as MAX_GOAL_ITERATIONS,Ci as MAX_LINES_PER_FILE,wr as MAX_NOTIFICATION_OUTPUT_TAIL_BYTES,Ip as MAX_RETAINED_TERMINAL_AGENTS,tr as MAX_RETAINED_TERMINAL_MONITORS,xr as MAX_RETAINED_TERMINAL_SHELLS,zr as MAX_RETAINED_TERMINAL_WORKFLOWS,Li as MAX_SNAPSHOTS,xo as MAX_TEAMMATES,$l as MAX_TRANSCRIPT_MESSAGES,Bh as MAX_USER_PROMPT_EXPANSION_ADDITIONAL_CONTEXT_LENGTH,qq as MCPDiscoveryState,mq as MCPOAuthProvider,iq as MCPOAuthTokenStorage,_s as MCPServerConfig,pq as MCPServerStatus,ar as MCP_BUDGET_REARM_FRACTION,$q as MCP_BUDGET_WARN_FRACTION,nq as MCP_DEFAULT_TIMEOUT_MSEC,Ma as MEDIA_FILE_PATTERNS,Ga as MEMORY_SECTION_HEADER,Mu as MOCK_TOOL_GET_CONFIRMATION_DETAILS,Lu as MOCK_TOOL_GET_DEFAULT_PERMISSION,Of as MODEL_GENERATION_CONFIG_FIELDS,la as MUTATOR_KINDS,wg as MatildaOAuth2Client,xg as MatildaOAuth2Event,rg as MatildaOAuthPollError,Yq as McpBudgetWouldExceedError,rq as McpClient,dr as McpClientManager,Zq as McpServerSpawnFailedError,st as McpTransportPool,oe as MemoryDreamEvent,ne as MemoryExtractEvent,Zp as MemoryManager,nb as MemoryMetricType,pe as MemoryRecallEvent,us as MessageBus,Wk as MessageBusType,nt as MessageSenderType,Ou as MockModifiableTool,Nu as MockModifiableToolInvocation,Ku as MockTool,Rf as ModelRegistry,ce as ModelSlashCommandEvent,Sf as ModelsConfig,vr as MonitorRegistry,du as NativeLspClient,eu as NativeLspService,Sd as NextSpeakerCheckEvent,Mh as NotificationType,lq as OAUTH_AUTH_URL_EVENT,kq as OAUTH_DISPLAY_MESSAGE_EVENT,jq as OAuthUtils,uj as OPENROUTER_BASE_URL,tj as OPENROUTER_ENV_KEY,Cf as OUTPUT_TOKEN_SAFETY_MARGIN,ve as OpenAILogger,pn as OpenDiffRequestSchema,hr as OutputFormat,ou as OverlayFs,w as PATH_ARG_KEYS,Vq as POOLED_TRANSPORTS_DEFAULT,kj as PROVIDER_METADATA_NS,Oa as PYTHON_EXCLUDES,mb as PerformanceMetricType,pr as PermissionManager,Oh as PermissionMode,Lh as PermissionRequestHookOutput,Rh as PostCompactTrigger,Jh as PostToolBatchHookOutput,Hh as PostToolUseFailureHookOutput,Gh as PostToolUseHookOutput,Qh as PreCompactTrigger,Fh as PreToolUseHookOutput,le as PromptSuggestionEvent,Ij as ProviderInstallError,lp as RECIPROCAL_CALLER,Lr as REDACTED_URL_CREDENTIAL,ef as REPORTED_ATTEMPT_PURPOSES,cf as REPORTED_ATTEMPT_PURPOSE_HEADER,df as REPORTED_OPERATION_HEADER_NAMES,bf as REPORTED_OPERATION_ID_HEADER,Mf as RUNTIME_SNAPSHOT_PREFIX,Qi as RUNTIME_STATUS_SCHEMA_VERSION,Dd as ReadFileTool,hf as ReportedOperationTracker,Js as RipGrepTool,Qd as RipgrepFallbackEvent,ye as RuntimeDiagnosticsCollector,mm as SAFE_TOOL_ALLOWLIST,$i as SESSION_TITLE_MAX_LENGTH,v as SHELL_SPECIAL_CHARS,Cl as SHELL_TOOL_NAMES,Vp as SKILL_REVIEW_TASK_TYPE,bi as STOP_HOOK_BLOCK_CAP_ENV,Pj as STREAM_RECOVERY_PARTIAL_DISPOSITION,Oj as STREAM_RECOVERY_SNAPSHOT_DISPOSITION,ku as SUGGESTION_PROMPT,hg as SUPPORTED_IMAGE_MIME_TYPES,Yt as SYMBOL_KIND_LABELS,Pa as SYSTEM_FILE_EXCLUDES,mk as SYSTEM_REMINDER_CLOSE,lk as SYSTEM_REMINDER_OPEN,ca as SchemaValidator,gq as SdkControlClientTransport,Qb as SemanticAttributes,$p as SendMessageType,Ph as SessionEndReason,aj as SessionService,Nh as SessionStartSource,js as SettingScope,Um as ShellExecutionService,nr as SkillActivationRegistry,kr as SkillError,ee as SkillLaunchEvent,or as SkillManager,Ud as SlashCommandStatus,dk as SleepInhibitor,N as SpanStatusCode,me as SpeculationEvent,$m as StandardFileSystemService,Gd as StartSessionEvent,Kh as StopHookOutput,K as Storage,Ek as StreamEventType,Qn as SubagentError,Rn as SubagentErrorCode,rr as SubagentManager,qr as SubagentValidator,Ao as TASKS_DIR,Do as TEAMMATE_COLORS,zo as TEAMS_DIR,Bo as TEAM_CONFIG_FILENAME,xi as TERMINAL_CSI_REGEX,wi as TERMINAL_OSC_REGEX,yi as TERMINAL_SHIFT_DCS_REGEX,Ej as THIRD_PARTY_PROVIDERS,Nj as THOUGHT_ONLY_MAX_TOKENS_DISPOSITION,Bl as TOOL_NAME_ALIASES,wt as TOOL_USE_SUMMARY_SYSTEM_PROMPT,sp as TaskOwnershipError,Fo as TeamEventEmitter,Eo as TeamEventType,Dp as TeamManager,rf as TelemetryTarget,gg as TextTokenizer,lo as TmuxBackend,Kd as ToolCallEvent,ja as ToolConfirmationOutcome,Aa as ToolDisplayNames,Ca as ToolDisplayNamesMigration,ba as ToolErrorType,ob as ToolExecutionPhase,za as ToolNames,Ba as ToolNamesMigration,$d as ToolOutputTruncatedEvent,fr as ToolRegistry,Ts as TrustGateError,Vj as Turn,ld as USER_AUTO_MEMORY_DIRNAME,oa as UiTelemetryService,p as UnauthorizedError,ge as UserFeedbackEvent,fe as UserFeedbackRating,Id as UserPromptEvent,Ih as UserPromptExpansionHookOutput,Jd as UserRetryEvent,M as ValueType,Zn as WORKTREES_DIR,Tn as WORKTREE_BRANCH_PREFIX,Vn as WORKTREE_SESSION_FILE,Ar as WorkflowRunRegistry,go as WorkspaceContext,tt as WorkspaceMcpBudget,Mt as WorkspaceMemoryFileTooLargeError,Kt as WorkspaceMemoryWriteTimeoutError,ph as __resetActiveGoalStoreForTests,gi as _recoverObjectsFromLine,tn as _resetCachedIdeServerHost,ki as _resetEnsuredDirsCacheForTest,Is as _resetRipGrepCachesForTest,u as _resetValidatePathCacheForTest,Yh as abortGoalForStopHookCap,uu as abortSpeculation,tu as acceptSpeculation,fk as acquireSleepInhibitor,ih as activeGoalEquals,Me as addDaemonRequestAttribute,tq as addMCPStatusChangeListener,Wb as addModelOutputAttributes,Ub as addSystemPromptAttributes,Xb as addToolInputAttributes,Yb as addToolResultAttributes,Vb as addToolSchemaAttributes,Tb as addUserPromptAttributes,Ht as aggregateUsage,Dm as allowEditorTypeInSandbox,Yg as appendToLastTextPart,rm as applyAutoModeDecision,Jj as applyProviderInstallPlan,kk as applySkillAllowedTools,gt as approxBase64Bytes,mp as assertValidTaskId,To as assignTeammateColor,W as atomicWriteFile,Z as atomicWriteFileSync,X as atomicWriteJSON,xp as blockTask,rk as buildAddedMcpToolsReminder,uk as buildAddedSkillsReminder,bj as buildApiHistoryFromConversation,tk as buildAvailableSkillsReminder,Jp as buildBackgroundEntryLabel,Iu as buildBtwCacheSafeParams,Hu as buildBtwPrompt,qk as buildDeferredToolsReminder,uo as buildFallbackApproachSummary,Kl as buildHumanReadableRuleLabel,lj as buildInstallPlan,sk as buildMcpServerInstructionsReminder,eq as buildMissedCronNotification,Jg as buildModelIdContext,Sl as buildPermissionCheckContext,Jl as buildPermissionRules,sj as buildProviderTemplate,of as buildReportedOperationHeaders,rl as buildShellExecWarnings,jk as buildSkillLlmContent,vk as buildStartupContextReminder,Cp as buildTeammatePromptAddendum,Bg as cacheMatildaCredentials,Tq as canUseRipgrep,Pe as captureDaemonTelemetryContext,yl as checkArgumentSafety,sl as checkCommandPermissions,Ur as checkForExtensionUpdate,Cm as checkHasEditorType,Rr as checkNpmUpdate,yp as claimTask,it as clampInlineMediaPart,Df as clampOutputToContextWindow,Yo as classifyShutdownResponse,zt as cleanSummary,Qu as cleanupTmpDir,lh as clearActiveGoal,jp as clearAllInboxes,od as clearAutoMemoryRootCache,Pp as clearCacheSafeParams,Cg as clearCachedCredentialFile,rh as clearGoalTerminalObserver,ip as clearInbox,uc as clearMatildaCorrelationHashes,Yf as clearMatildaCredentials,Ti as clearRuntimeStatus,Uo as clearTeammateColors,Cu as clearWelcomeBackState,Ms as clearWorktreeSession,As as cliSource,Sr as cloneFromGit,fq as collectMemoryDiagnostics,Ak as collectToolCallIdsFromHistory,xm as commandExists,Gk as compactPendingUserContentToBudget,Fk as compactTextMiddle,mj as computeModelListVersion,ck as computeThresholds,fj as computeUniqueBranchTitle,Es as computedSource,Eq as connectAndDiscover,Kq as connectToMcpServer,Wq as connectionIdOf,hp as consumeUnread,_r as convertClaudeAgentConfig,as as convertClaudePluginPackage,$r as convertClaudeToMatildaConfig,Pm as convertColorToHex,wn as convertToFunctionResponse,Yr as convertTomlToMarkdown,ms as copyExtension,cb as countFileLines,oi as countLines,Os as crawlCache,Hg as createContentGenerator,Gg as createContentGeneratorConfig,Te as createDaemonBridgeTelemetry,U as createDebugLogger,Qk as createDefaultAutoMemoryExtractCursor,Rk as createDefaultAutoMemoryIndex,Pk as createDefaultAutoMemoryMetadata,cm as createDenialState,ju as createFollowupController,Qp as createForkedChat,Zh as createGoalStopHookCallback,Dh as createHookOutput,ts as createInstructionsLoadedCallback,oq as createStreamableHttpCompatibilityFetch,qp as createTask,$o as createTeamFile,Pu as createTmpDir,vt as createToolUseSummaryMessage,Lq as createTransport,Cj as customProvider,$a as decodeBufferWithEncodingInfo,pt as decodeTagName,Ck as dedupeToolCallsById,wj as deepseekProvider,Ds as defaultSource,up as deleteTask,bp as deleteTeamDirs,Oi as deserializeSnapshots,_a as detectBOM,qo as detectBackend,ol as detectCommandSubstitution,Ya as detectEncodingFromBuffer,eb as detectFileEncoding,ib as detectFileType,bn as detectIdeFromEnv,Zm as detectLineEnding,dg as detectRuntime,Th as detectTodoChanges,Cq as discoverMcpTools,Hq as discoverPrompts,Fq as discoverTools,dp as disposeInboxLocks,cl as doesToolInvocationMatch,Vr as downloadFromGitHubRelease,Qr as downloadFromNpmRegistry,ym as editorCommands,Oe as emitDaemonLog,lt as encodeInsightErrorMessage,jt as encodeInsightProgressMessage,kt as encodeInsightReadyMessage,ot as encodeTagName,_m as encodeTextFileContent,lc as endHookSpan,$b as endInteractionSpan,cc as endLLMRequestSpan,oc as endSubagentSpan,jc as endToolBlockedOnUserSpan,hc as endToolExecutionSpan,fc as endToolSpan,Sk as ensureAutoMemoryScaffold,Ym as ensureCrlfLineEndings,Sq as ensureMacBinarySigned,Rq as ensureRipgrepHealthy,vu as ensureToolResultPairing,Uk as ensureUserAutoMemoryScaffold,kf as enterReportedOperationContext,Fs as envLayer,B as escapePath,fl as escapeShellArg,qe as estimateTokensFromChars,vm as evaluateAutoMode,Wl as evaluatePermissionFlow,Tl as evaluatePermissionRules,pu as evaluateToolCall,tl as execCommand,rt as executeToolCall,pi as exists,y as expandHomeDir,Se as extractDaemonTraceContext,Sa as extractExtensionsFromPatterns,Xr as extractFile,Wi as extractJsonStringField,Yi as extractLastJsonStringField,Xi as extractLastJsonStringFields,am as extractShellOperations,vn as extractToolFilePaths,Ei as fetchGitDiff,Fi as fetchGitDiffHunks,kb as fileExists,xu as filter,ri as findGitRoot,Wo as findMemberById,Xo as findMemberByName,Gj as findProviderByCredentials,Fj as findProviderById,Wr as findReleaseAsset,$k as fireNotificationHook,al as firePermissionRequestHook,_k as firePostToolUseFailureHook,Zk as firePostToolUseHook,Yk as firePreToolUseHook,Xg as flatMapTextParts,zc as forceFlushMetrics,Ro as formatAgentId,um as formatClassifierBlockMessage,nk as formatDateForContext,dm as formatDenialStateLog,vo as formatLineStats,Qm as formatMemoryUsage,ei as formatStopHookBlockingCapWarning,P as formatTraceparent,Jo as forwardApproval,bo as generateAgentWorktreeSlug,og as generateCodeChallenge,ng as generateCodeVerifier,Bj as generateCustomEnvKey,pg as generatePKCEPair,lu as generatePromptSuggestion,ut as generateSessionRecap,Xk as generateToolUseId,xt as generateToolUseSummary,So as generateUniqueTeammateName,Fd as generateValidName,re as generatedOutputTokens,jh as getActiveGoal,pc as getActiveInteractionSpan,Gn as getAgentName,Bp as getAgentStatuses,Ja as getAllGeminiMdFilenames,yq as getAllMCPServerStatuses,Hj as getAllProviderBaseUrls,ak as getArenaSystemReminder,ud as getAutoMemoryConsolidationLockPath,td as getAutoMemoryExtractCursorPath,xd as getAutoMemoryFilePath,rd as getAutoMemoryIndexPath,sd as getAutoMemoryMetadataPath,pd as getAutoMemoryProjectStateDir,nd as getAutoMemoryRoot,vd as getAutoMemoryTopicFilename,wd as getAutoMemoryTopicPath,tm as getAutoModePermissionDeniedReason,Pq as getBuiltinRipgrep,Op as getCacheSafeParams,Va as getCachedEncodingForBuffer,hl as getCommandRoot,il as getCommandRoots,Zj as getCompressionPrompt,Yj as getCoreSystemPrompt,Ia as getCurrentGeminiMdFilename,Xj as getCustomSystemPrompt,nj as getDefaultBaseUrlForProtocol,pj as getDefaultModelIds,Fm as getDiffCommand,ok as getDirectoryContextString,zm as getEditorExecutable,Yl as getEffectivePermissionForConfirmation,hs as getEnvContents,pk as getEnvironmentContext,c as getErrorMessage,d as getErrorStatus,e as getErrorType,ns as getExtensionId,Bm as getExternalEditorCommand,mu as getFilterReason,ik as getFolderStructure,$g as getFunctionCalls,bh as getFunctionCallsAsJson,ah as getFunctionCallsFromParts,ch as getFunctionCallsFromPartsAsJson,si as getGitBranch,ti as getGitRepoName,Ah as getHookKey,Nt as getIdeInstaller,un as getIdeServerHost,ep as getInboxPath,Oo as getInboxesDir,wk as getInitialChatHistory,bk as getInsightPrompt,th as getLastGoalTerminal,Ho as getLeader,zq as getMCPDiscoveryState,hu as getMCPServerPrompts,xq as getMCPServerStatus,Kf as getMatildaAuthBaseUrl,Zf as getMatildaAuthStatus,tc as getMatildaCorrelationHashes,Vf as getMatildaCredentialsPath,zg as getMatildaOAuthClient,ft as getMaxInlineMediaBytes,md as getMemoryBaseDir,ur as getMonitorOutputPath,eg as getOrCreateSharedDispatcher,$j as getPlanModeSystemReminder,D as getProjectHash,Du as getProjectSummaryInfo,_j as getProjectSummaryPrompt,Qg as getRateLimitErrorDetails,Rg as getRateLimitRetryDelayMs,ui as getRecentGitStatus,gf as getReportedOperationContext,Wg as getResponseText,_g as getResponseTextFromParts,dj as getResumePromptTokenCount,ej as getResumeTokenCounts,Il as getRuleDisplayName,gs as getScopedEnvContents,Tm as getShellAbortReasonKind,dl as getShellConfiguration,fb as getSpecificMimeType,El as getSpecifierKind,xk as getStartupContextLength,dh as getStructuredResponse,eh as getStructuredResponseFromParts,jg as getSupportedImageFormatsString,Wa as getSystemEncoding,rp as getTask,np as getTaskPath,Po as getTasksDir,Mo as getTeamDir,No as getTeamFilePath,Hn as getTeamName,Ln as getTeammateColor,En as getTeammateContext,Lo as getTeamsRootDir,Sj as getThoughtText,Gt as getTimeRangeBounds,O as getTraceContext,kg as getUnsupportedImageFormatWarning,zd as getUserAutoMemoryIndexPath,yd as getUserAutoMemoryRoot,Ad as getUserAutoMemoryTopicPath,$f as getValidMatildaAccessToken,Au as getWelcomeBackState,_p as globalMemoryManager,Bq as handleAutomaticOAuth,ia as hasCycleInSchema,Ff as hasExplicitOutputLimit,Jq as hasNetworkTransport,ll as hasNonFinalTopLevelBackgroundOperator,ql as hasShellSubstitution,nl as hasUnsafeMonitorBackgroundOperator,He as hashDaemonWorkspace,fu as hashMcpServerConfig,os as hashValue,rs as hookEventSupportsMatcher,Hr as hydrateString,hn as ideContextStore,Ue as initializeDaemonMetrics,wc as initializeTelemetry,Re as injectDaemonTraceContext,Ul as injectPermissionRulesIfMissing,Iq as invokeMcpPrompt,b as isAbortError,Cd as isAnyAutoMemPath,Kg as isApiError,km as isApproveOutcome,_l as isAutoEditApproved,qd as isAutoMemPath,Jt as isBareMode,Km as isBinary,hb as isBinaryFile,Tf as isBrowserCommandBlocked,cs as isClaudePluginConfig,wl as isCommandAllowed,vl as isCommandAvailable,xl as isCommandNeedsPermission,Q as isDebugLoggingDegraded,em as isDenialFallbackReason,sg as isDeviceAuthorizationSuccess,ug as isDeviceTokenPending,tg as isDeviceTokenSuccess,Em as isEditorAvailable,Mq as isEnabled,vg as isErrorResponse,Zs as isGatedMcpScope,Ng as isGenericQuotaExceededError,qi as isGitRepository,Fn as isInProcessTeammate,nm as isInSafeToolAllowlist,Mk as isInvalidArgumentError,Og as isMatildaQuotaExceededError,Hm as isModifiableDeclarativeTool,a as isNodeError,ho as isPathWithinRoot,Jb as isPerformanceMonitoringActive,Zl as isPlanModeBlocked,Mg as isProQuotaExceededError,Pg as isRateLimitError,ff as isReportedOperationHeaderName,xe as isRuntimeDiagnosticsEnabled,Lk as isSchemaDepthError,Or as isScopedNpmPackage,$s as isSdkMcpServerConfig,xa as isSettledStatus,Lg as isStructuredError,F as isSubpath,G as isSubpaths,wa as isSuccessStatus,ig as isSupportedImageMimeType,yk as isSystemReminderContent,Kn as isTeamLead,Jn as isTeammate,vc as isTelemetrySdkInitialized,Am as isTerminalEditor,va as isTerminalStatus,Zr as isTomlFormat,ha as isTool,bl as isToolEnabled,Sg as isTransientCapacityError,Tg as isUnattendedMode,Bd as isUserAutoMemPath,wm as isValidEditorType,Hk as isValidNonThoughtTextPart,el as isWindows,gb as isWithinRoot,Uh as judgeGoal,Gf as knownTokenLimit,Gs as layer,Gq as listMcpPrompts,vp as listTasks,cp as listTeamNames,Ps as loadIgnoreRules,xs as loadServerHierarchicalMemory,Ft as loadUsageHistory,Jc as logApiCancel,Ic as logApiError,Fc as logApiRequest,Kc as logApiResponse,$c as logArenaAgentCompleted,ad as logArenaSessionEnded,_c as logArenaSessionStarted,Xc as logAuth,Pc as logChatCompression,Oc as logConversationFinishedEvent,Wc as logExtensionDisable,Vc as logExtensionEnable,Sc as logExtensionInstallEvent,Tc as logExtensionUninstall,Uc as logExtensionUpdateEvent,Gc as logFlashFallback,Nc as logIdeConnection,Qc as logKittySequenceOverflow,ed as logMemoryDream,dd as logMemoryExtract,fd as logMemoryRecall,Rc as logModelSlashCommand,Lc as logNextSpeakerCheck,bd as logPromptSuggestion,Hc as logRipgrepFallback,Yc as logSkillLaunch,Mc as logSlashCommand,cd as logSpeculation,Ac as logStartSession,Dc as logToolCall,Ec as logToolOutputTruncated,Zc as logUserFeedback,Bc as logUserPrompt,Cc as logUserRetry,Lf as loginToMatilda,cg as loginToMatildaWithBrowser,_f as logoutMatilda,ie as makeArenaAgentCompletedEvent,je as makeArenaSessionEndedEvent,he as makeArenaSessionStartedEvent,Vd as makeChatCompressionEvent,Ju as makeFakeConfig,A as makeRelative,Td as makeSlashCommandEvent,Ml as matchesCommandPattern,Pl as matchesDomainPattern,Ql as matchesMcpPattern,Ol as matchesPathPattern,Rl as matchesRule,yg as matildaOAuth2Events,Jf as matildaProvider,es as maybePromptForSettings,sq as mcpServerRequiresOAuth,cr as mcpTransportOf,bs as mergeClaudeConfigs,Bt as metricsToUsageRecord,xj as minimaxProvider,Cs as modelProvidersSource,Qf as modelRegistryKey,zj as modelscopeProvider,Im as modifyWithEditor,Xl as needsConfirmation,Wm as needsUtf8Bom,Ef as normalize,Lm as normalizeContent,Bk as normalizeModelToolCallIds,ml as normalizeMonitorCommand,vs as normalizeProxyUrl,lr as normalizeSkillPriority,ci as normalizeStopHookBlockingCap,te as normalizeStoredModelUsage,Ct as normalizeUsageRecord,sh as notifyGoalTerminal,pp as notifyTasksUpdated,op as onTasksUpdated,lg as openBrowserSecurely,Gm as openDiff,vj as openRouterProvider,we as openaiLogger,ht as oversizedMediaPlaceholder,ir as parse,fi as parseAndFormatApiError,Ce as parseBooleanEnvFlag,Xq as parseConnectionId,Ji as parseDeletedFromNameStatus,Hi as parseGitDiff,Tr as parseGitHubRepoForReleases,Gi as parseGitNumstat,mt as parseInsightMessage,gu as parseInstallSource,hi as parseLineTolerant,Nr as parseNpmPackageSource,Gl as parseRule,Hl as parseRules,Ii as parseShortstat,De as parseTelemetryTargetValue,Rj as parseThought,dt as partListUnionToString,Vg as partToString,qm as passesAcceptEditsFastPath,Kr as performVariableReplacement,Vl as persistPermissionOutcome,At as persistSessionUsage,Dq as populateMcpServerCommand,Zg as prependToFirstTextPart,jb as processSingleFileContent,fs as promptForSetting,Rm as promptIdContext,rj as providerMatchesCredentials,ji as read,Tk as readAutoMemoryIndex,bb as readFileWithEncoding,ab as readFileWithEncodingInfo,db as readFileWithLineAndLimit,fp as readInbox,Zi as readLastJsonStringFieldSync,_i as readLastJsonStringFieldsSync,ii as readLines,Eu as readManyFiles,Wf as readMatildaCredentials,zu as readPathFromWorkspace,Si as readRuntimeStatus,Zo as readTeamFile,Vk as readUserAutoMemoryIndex,Ks as readWorktreeSession,Xn as readWorktreeSessionMarker,fm as recordAllow,tb as recordApiErrorMetrics,Fb as recordApiRequestBreakdown,sb as recordApiResponseMetrics,yb as recordApiRetry,Lb as recordArenaAgentCompletedMetrics,Mb as recordArenaSessionEndedMetrics,Kb as recordArenaSessionStartedMetrics,Ib as recordBaselineComparison,gm as recordBlock,wb as recordContentRetry,xb as recordContentRetryFailure,Bb as recordCpuUsage,$e as recordDaemonBridgeError,af as recordDaemonCancel,Ye as recordDaemonChannelLifecycle,Ne as recordDaemonError,We as recordDaemonHttpRequest,Le as recordDaemonHttpResponse,_e as recordDaemonPromptDuration,Ze as recordDaemonPromptQueueWait,Xe as recordDaemonSessionLifecycle,jm as recordFallbackApprove,ub as recordFileOperationMetric,mh as recordGoalIteration,vb as recordInvalidChunk,Ob as recordMemoryDreamMetrics,Nb as recordMemoryExtractMetrics,Pb as recordMemoryRecallMetrics,Ab as recordMemoryUsage,Hb as recordPerformanceRegression,Gb as recordPerformanceScore,gh as recordStartupEvent,zb as recordStartupPerformance,Eb as recordTokenEfficiency,rb as recordTokenUsageMetrics,qb as recordToolCallMetrics,Db as recordToolExecutionBreakdown,Cb as recordToolQueueDepth,hm as recordUnavailable,Ir as recursivelyHydrateStrings,fg as redactProxyCredentials,Dk as redactStructuredOutputArgsForRecording,Mr as redactUrlCredentials,Dt as reestimateUsageFromAssistantRecord,ag as refreshMatildaCredentials,xc as refreshSessionContext,Ve as registerDaemonGaugeCallbacks,$h as registerGoalHook,Go as registerLeader,zp as releaseOwnedTask,wq as removeMCPServerStatus,uq as removeMCPStatusChangeListener,V as renameWithRetry,Y as renameWithRetrySync,Jk as repairOrphanedToolUseTurns,cj as replayUiTelemetryFromConversation,qf as reportCliAuthFunnelEvent,pf as reportCliClientEvent,aq as reportedAttemptPurposeForSendMessageType,R as resetDebugLoggingState,lm as resetDenialState,Ua as resetEncodingCache,wp as resetTaskList,Xm as resetUtf8BomCache,In as resolveActiveTeamName,J as resolveAndValidatePath,oj as resolveBaseUrl,Oq as resolveBundleDir,ul as resolveCommandPath,Eg as resolveContentGeneratorConfigWithSources,ys as resolveField,Ki as resolveGitDir,oh as resolveGoalLifecycleStatus,Kj as resolveLocalHistoryAccountScopeId,Lj as resolveLocalHistoryAccountScopeIdForCredentials,Gp as resolveMaxConcurrentBackgroundAgents,jj as resolveMetadataKey,Hs as resolveModelConfig,Ig as resolveModelId,Pr as resolveNpmRegistry,ue as resolveOpenAILogDir,zs as resolveOptionalField,ij as resolveOwnsModel,H as resolvePath,Wj as resolvePathFromEnv,Nl as resolvePathPattern,Qq as resolveRipgrep,di as resolveStopHookBlockingCap,Ee as resolveTelemetrySettings,Dl as resolveToolName,Ns as restoreWorktreeContext,Ug as retryWithBackoff,qu as rewritePathArgs,Et as rewriteUsageHistoryFromChats,mf as runAsyncGeneratorWithReportedOperationContext,Sp as runForkedAgent,nc as runInSubagentSpanContext,ec as runInToolSpanContext,Uq as runRipgrep,vi as runSideQuery,Qe as runWithDaemonTelemetryContext,T as runWithDebugLogSession,Rp as runWithForkedChatModel,lf as runWithReportedAttemptPurpose,jf as runWithReportedOperationContext,Mn as runWithTeammateIdentity,ze as runtimeDiagnostics,sa as safeAgentId,Jm as safeLiteralReplace,E as sanitizeCwd,Rb as sanitizeHookName,Qo as sanitizeName,hj as sanitizeTitle,Mj as sanitizeToolCallResultForRecording,Ch as sanitizeUserPromptExpansionAdditionalContext,Np as saveCacheSafeParams,Bu as saveWelcomeBackRestartChoice,kp as sendStructuredMessage,Ni as serializeSnapshot,Om as serializeTerminalToObject,Mm as serializeTerminalToText,Sm as sessionIdContext,kh as setActiveGoal,S as setDebugLogSession,Ha as setGeminiMdFilename,qh as setGoalTerminalObserver,uh as setLastGoalTerminal,Aq as setMCPDiscoveryState,sc as setMatildaCorrelationHashes,Vo as setMemberActive,fh as setStartupEventSink,Bs as settingsSource,z as shortenPath,Uf as shouldAttemptBrowserLaunch,zl as shouldDefaultToNodePty,im as shouldFallback,nu as shouldFilterSuggestion,sm as shouldFirePermissionDeniedForAutoMode,pm as shouldForceAutoModeReviewForAllow,mg as shouldLaunchBrowser,om as shouldRunAutoModeForCall,qj as shouldShowStep,yc as shutdownTelemetry,ek as sleepInhibitor,gl as splitCommands,Ll as splitCompoundCommand,mr as splitConditionalSkills,kc as startHookSpan,_b as startInteractionSpan,bc as startLLMRequestSpan,su as startSpeculation,mc as startSubagentSpan,ic as startToolBlockedOnUserSpan,gc as startToolExecutionSpan,dc as startToolSpan,bq as startsReportedOperation,jr as stringify,Nf as stripRuntimeSnapshotPrefix,jl as stripShellWrapper,zk as stripStartupContext,zi as stripTerminalControlSequences,kl as stripTrailingBackgroundAmp,Fu as subagentGenerator,Jr as substituteHookVariables,Be as summarizeAnthropicWireRequest,Ae as summarizeOpenAIWireRequest,to as summarizeUnifiedDiff,Dn as teammateIdentityStore,Bn as templateString,x as tildeifyPath,r as toFriendlyError,Al as toPosixPath,Hf as tokenLimit,Fl as toolMatchesRuleToolName,se as totalTokensFromBuckets,Sb as truncateContent,yt as truncateJson,Zb as truncateSpanError,gj as tryGenerateSessionTitle,ap as tryReclaimStaleTeam,pa as uiTelemetryService,Ap as unassignTeammateTasks,Vi as unescapeJsonString,C as unescapePath,_h as unregisterGoalHook,Io as unregisterLeader,nh as updateActiveGoalStatus,vq as updateMCPServerStatus,is as updateSetting,L as updateSymlink,tp as updateTask,Fg as validateModelConfig,ps as validateName,I as validatePath,Gr as validateVariables,bg as willOpenMatildaAuthBrowser,Xa as windowsCodePageToEncoding,Ke as withDaemonBridgeSpan,Je as withDaemonRequestSpan,Ie as withDaemonSpan,ac as withInteractionSpan,nf as withReportedAttemptPurpose,Un as worktreeBranchForSlug,Ko as wrapConfirmWithBadge,ni as write,li as writeLine,mi as writeLineSync,Xf as writeMatildaCredentials,gp as writeMessage,Ri as writeRuntimeStatus,_o as writeTeamFile,Lt as writeWorkspaceContextFile,Ls as writeWorktreeSession,Wn as writeWorktreeSessionMarker,yj as zaiProvider};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a,b}from"./chunk-SUORCDGS.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-TISQNFB5.js";import"./chunk-QKYGQLWC.js";import"./chunk-5U3A6KMU.js";import"./chunk-IOCF4XSR.js";import"./chunk-QWBNNEV2.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{b as TaskCreateTool,a as truncateForConfirmation};
@@ -1,15 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a as _}from"./chunk-MJEXA2MA.js";import{Le as C,Me as u,Se as G,Te as Q,We as V,Ze as Y,ja as S,qe as k,re as q,tc as Z}from"./chunk-3FI7EEYS.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-C2ZWB2NT.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-FT76AZPN.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-LCYHQMKE.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-QLEJOI4X.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{Lb as z,Oa as B,_c as K,ca as U,ha as w}from"./chunk-6QP5C76Y.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{w as H}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as $,i as N,p as L,q as j}from"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{A as b,C as O,Y as M,a as d,c as D,z as R}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as I}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";I();import P from"node:fs";import y from"node:path";var F=M("WRITE_FILE"),ae=["filePath","filepath","path","file","filename"];function le(f){if(!(typeof f.file_path=="string"&&f.file_path.trim()))for(let a of ae){let o=f[a];if(typeof o=="string"&&o.trim()){f.file_path=o,delete f[a];return}}}function ce(f){let a=f.content;if(typeof a!="string"||!a.includes("<arg_")&&!a.includes("</arg_"))return;let o={},e=/<arg_key>\s*([A-Za-z_][\w]*)\s*<\/arg_key>\s*<arg_value>\s*([\s\S]+?)(?:<\/arg_value>|(?=<arg_key\b)|$)/gi,r;for(;(r=e.exec(a))!==null;){let i=r[1].toLowerCase(),n=r[2].trim();n&&(o[i]=n)}let l=/(?:^|[^>])([A-Za-z_][\w]*)\s*<\/arg_key>\s*<arg_value>\s*([\s\S]+?)(?:<\/arg_value>|(?=<arg_key\b)|(?=[A-Za-z_][\w]*\s*<\/arg_key>)|$)/gi;for(;(r=l.exec(a))!==null;){let i=r[1].toLowerCase(),n=r[2].trim();(n&&!o[i]||n&&n.length>=(o[i]?.length??0))&&(o[i]=n)}let h=[a.search(/<arg_key\b/i),a.search(/<\/arg_key\b/i),a.search(/<arg_value\b/i)].filter(i=>i>=0),g=h.length>0?Math.min(...h):-1;if(g>=0&&a.slice(g,g+10).startsWith("</arg_key")){let i=a.slice(0,g),n=/([A-Za-z_][\w]*)\s*$/.exec(i);n&&(g=n.index)}let c=g>=0?a.slice(0,g).trimEnd():a;c=c.replace(/<\/?arg_(?:key|value)\b[^>]*>/gi,"").trimEnd(),f.content=c;let m=new Set(["file_path","filepath","path","file","filename"]);for(let[i,n]of Object.entries(o))!m.has(i)||!n||!n.startsWith("/")&&!/^[A-Za-z]:[\\/]/.test(n)||(typeof f.file_path!="string"||!String(f.file_path).trim()||n.length>String(f.file_path).length)&&(f.file_path=n)}var A=class extends ${constructor(o,e){super(e);this.config=o}toolLocations(){return[{path:this.params.file_path}]}getDescription(){let o=b(this.params.file_path,this.config.getTargetDir());return`Writing to ${R(o)}`}async getDefaultPermission(){let o=this.config.getProjectRoot();return H(y.resolve(this.params.file_path),o)?"allow":"ask"}async getConfirmationDetails(o){let e=_(this.config,this.params.file_path);if(e)throw new C(e,"path_not_in_workspace");let r="",l=await w(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){let i=await u(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!i.ok)throw new C(i.rawMessage,i.type)}if(l)try{let{content:i}=await this.config.getFileSystemService().readTextFile({path:this.params.file_path});r=i}catch(i){if(d(i)&&i.code==="ENOENT")l=!1;else throw new Error(`Error reading existing file for confirmation: ${D(i)}`)}if(l&&!this.config.getFileReadCacheDisabled()){let i=await u(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:!0});if(!i.ok)throw F.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:i.type}),new C(i.rawMessage,i.type)}let h=b(this.params.file_path,this.config.getTargetDir()),g=y.basename(this.params.file_path),c=S(g,r,this.params.content,"Current","Proposed",k);return{type:"edit",title:`Confirm Write: ${R(h)}`,fileName:g,filePath:this.params.file_path,fileDiff:c,originalContent:r,newContent:this.params.content,onConfirm:async i=>{i==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}async execute(o){let{file_path:e,content:r,ai_proposed_content:l,modified_by_user:h}=this.params,g=_(this.config,e);if(g)return{llmContent:g,returnDisplay:g,error:{message:g,type:"path_not_in_workspace"}};let c=await w(e),m="",i=!1,n,W,J=y.dirname(e);if(!this.config.getFileReadCacheDisabled()){let t=await u(this.config.getFileReadCache(),e,"overwriting");if(!t.ok)return{llmContent:t.rawMessage,returnDisplay:`Error: ${t.displayMessage}`,error:{message:t.rawMessage,type:t.type}}}if(c)try{let t=await this.config.getFileSystemService().readTextFile({path:e});t._meta?.bom!==void 0?i=t._meta.bom:i=t.content.length>0&&t.content.codePointAt(0)===65279,n=t._meta?.encoding||"utf-8",W=V(t.content),m=t.content,c=!0}catch(t){if(d(t)&&t.code==="ENOENT")c=!1;else{let s={message:D(t),code:d(t)?t.code:void 0},p=s.code?`Error checking existing file '${e}': ${s.message} (${s.code})`:`Error checking existing file: ${s.message}`;return{llmContent:p,returnDisplay:p,error:{message:p,type:"file_write_failure"}}}}if(c&&!this.config.getFileReadCacheDisabled()){let t=await u(this.config.getFileReadCache(),e,"overwriting",{expectExisting:!0});if(!t.ok)return F.warn("post-read TOCTOU rejection (execute)",{path:e,reason:t.type}),{llmContent:t.rawMessage,returnDisplay:`Error: ${t.displayMessage}`,error:{message:t.rawMessage,type:t.type}}}if(!c){let t=this.config.getDefaultFileEncoding();t===G.UTF8_BOM?i=!0:t===void 0&&(i=Q(e)),n=void 0}try{await this.config.getFileHistoryService().trackEdit(e)}catch{}if(!this.config.getFileReadCacheDisabled()){let t=await u(this.config.getFileReadCache(),e,"overwriting",{expectExisting:c});if(!t.ok)return F.warn("pre-write TOCTOU rejection",{path:e,reason:t.type}),{llmContent:t.rawMessage,returnDisplay:`Error: ${t.displayMessage}`,error:{message:t.rawMessage,type:t.type}}}let E=_(this.config,e);if(E)return{llmContent:E,returnDisplay:E,error:{message:E,type:"path_not_in_workspace"}};c||P.mkdirSync(J,{recursive:!0});try{let t=_(this.config,e);if(t)return{llmContent:t,returnDisplay:t,error:{message:t,type:"path_not_in_workspace"}};await this.config.getFileSystemService().writeTextFile({path:e,content:r,_meta:{bom:i,encoding:n,lineEnding:W}}),h||Z.getInstance().recordEdit(e,c?m:null,r);try{let T=P.statSync(e);this.config.getFileReadCache().recordWrite(e,T)}catch{}let s=y.basename(e),p=m,X=S(s,p,r,"Original","Written",k),ee=q(s,p,l||r,r),v=[c?`Successfully overwrote file: ${e}.`:`Successfully created and wrote to new file: ${e}.`];h&&v.push(`User modified the \`content\` to be: ${r}`);let te=U(e),ie=B(e),oe=y.extname(e),re=c?"update":"create",ne=r.split(`
4
- `).length;z(this.config,new K(x.Name,re,ne,te,oe,ie));let se={fileDiff:X,fileName:s,originalContent:m,newContent:r,diffStat:ee};try{let T=await Y(this.config,e);T&&v.push(`
5
-
6
- ${T}`)}catch{}return{llmContent:v.join(" "),returnDisplay:se}}catch(t){let s,p="file_write_failure";return d(t)?(s=`Error writing to file '${e}': ${t.message} (${t.code})`,t.code==="EACCES"?(s=`Permission denied writing to file: ${e} (${t.code})`,p="permission_denied"):t.code==="ENOSPC"?(s=`No space left on device: ${e} (${t.code})`,p="no_space_left"):t.code==="EISDIR"&&(s=`Target is a directory, not a file: ${e} (${t.code})`,p="target_is_directory"),this.config.getDebugMode()&&t.stack&&F.debug("Write file error stack:",t.stack)):t instanceof Error?s=`Error writing to file: ${t.message}`:s=`Error writing to file: ${String(t)}`,{llmContent:s,returnDisplay:s,error:{message:s,type:p}}}}},x=class f extends N{constructor(o){super(f.Name,j.WRITE_FILE,`Writes content to a specified file in the local filesystem.
7
-
8
- CRITICAL: Always emit file_path FIRST (absolute path), then content. Never omit file_path. Construct absolute paths from the project root + relative path (e.g. '/path/to/project/' + 'foo/bar.txt'). Relative paths are not supported.
9
-
10
- The user has the ability to modify \`content\`. If modified, this will be stated in the response.`,"edit",{properties:{file_path:{description:"REQUIRED. Absolute path to write (e.g. '/home/user/project/src/auth.ts'). Emit this BEFORE content.",type:"string"},content:{description:"The full file contents to write. Only after file_path is set.",type:"string"}},required:["file_path","content"],type:"object"});this.config=o}static Name=L.WRITE_FILE;validateToolParams(o){let e=o;return ce(e),le(e),(typeof o.file_path!="string"||!o.file_path.trim())&&typeof o.content=="string"&&o.content.length>0?'WriteFile requires absolute "file_path" (emit file_path first, then content). Retry with both file_path and content.':super.validateToolParams(o)}validateToolParamValues(o){let e=O(o.file_path.trim());if(o.file_path=e,!e)return'Missing or empty "file_path"';if(!y.isAbsolute(e))return`File path must be absolute: ${e}`;try{if(P.existsSync(e)&&P.lstatSync(e).isDirectory())return`Path is a directory, not a file: ${e}`}catch(r){return`Error accessing path properties for validation: ${e}. Reason: ${r instanceof Error?r.message:String(r)}`}return null}createInvocation(o){return new A(this.config,o)}toAutoClassifierInput(o){let e=o.content??"";return{file_path:o.file_path,byte_count:Buffer.byteLength(e,"utf8"),content_preview:e.slice(0,300),content_truncated:e.length>300}}getModifyContext(o){return{getFilePath:e=>e.file_path,getCurrentContent:async e=>{if(await w(e.file_path))try{let{content:l}=await this.config.getFileSystemService().readTextFile({path:e.file_path});return l}catch(l){if(!d(l)||l.code!=="ENOENT")throw l;return""}else return""},getProposedContent:async e=>e.content,createUpdatedParams:(e,r,l)=>{let h=l.content;return{...l,ai_proposed_content:h,content:r,modified_by_user:!0}}}}};export{x as WriteFileTool,le as normalizeWriteFilePathAliases,ce as repairLeakedWriteFileToolArgMarkup};
11
- /**
12
- * @license
13
- * Copyright 2025 Google LLC
14
- * SPDX-License-Identifier: Apache-2.0
15
- */