@maincode-ai/matilda-code 0.20.0 → 0.20.2

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 (65) hide show
  1. package/bundled/mainy/docs/features/headless.md +37 -0
  2. package/bundled/mainy/docs/features/mcp.md +3 -3
  3. package/chunks/{agent-N5H7ZVZN.js → agent-WQRHTEJK.js} +1 -1
  4. package/chunks/{agent-headless-LBLAX66M.js → agent-headless-VPF3VPXU.js} +1 -1
  5. package/chunks/{anthropicContentGenerator-DKMAJXYA.js → anthropicContentGenerator-ATLOKYPR.js} +1 -1
  6. package/chunks/chunk-3YLXGE6T.js +8 -0
  7. package/chunks/{chunk-TRM7SXZ5.js → chunk-A7VPKVYG.js} +1 -1
  8. package/chunks/{chunk-GTR4V2PV.js → chunk-DC7LAFZZ.js} +1 -1
  9. package/chunks/chunk-DORRYU7L.js +101 -0
  10. package/chunks/{chunk-KP6BLFQS.js → chunk-GIIMOLLN.js} +1 -1
  11. package/chunks/{chunk-RO6LKQPB.js → chunk-IGQPRDMV.js} +547 -544
  12. package/chunks/chunk-IMYUVCF7.js +27 -0
  13. package/chunks/{chunk-3KCDX6MY.js → chunk-ISW2QC5B.js} +1 -1
  14. package/chunks/chunk-OCXGNAAT.js +8 -0
  15. package/chunks/{chunk-QT4UNNZ4.js → chunk-QJO23A2D.js} +4 -4
  16. package/chunks/chunk-RGBIKCMN.js +95 -0
  17. package/chunks/{chunk-XXZH7C44.js → chunk-SS5WUOSJ.js} +1 -1
  18. package/chunks/chunk-XJDC3ZQZ.js +8 -0
  19. package/chunks/{chunk-Z7OHKQ7V.js → chunk-YZVC65QR.js} +2 -2
  20. package/chunks/{computer-use-LG4QQFMP.js → computer-use-3BJWOZSA.js} +1 -1
  21. package/chunks/contextCommand-SOQLJJIW.js +3 -0
  22. package/chunks/edit-ZIPLKFNT.js +38 -0
  23. package/chunks/{en-ZU6RPTEW.js → en-75JQMW7P.js} +1 -1
  24. package/chunks/{enter-worktree-OIP2B3NM.js → enter-worktree-MWQ3Z7HX.js} +1 -1
  25. package/chunks/enterPlanMode-XT6MNE2L.js +18 -0
  26. package/chunks/{exit-worktree-VN5I5XWV.js → exit-worktree-O7DBPVFA.js} +1 -1
  27. package/chunks/{exitPlanMode-HE6EEGTO.js → exitPlanMode-FDXKFQJF.js} +14 -14
  28. package/chunks/geminiContentGenerator-HXWUQ2DI.js +8 -0
  29. package/chunks/{glob-EGOAJNOQ.js → glob-GYLGTXYL.js} +1 -1
  30. package/chunks/{grep-JYHW6SSG.js → grep-ZNYUS2MU.js} +1 -1
  31. package/chunks/{matildaAgentContentGenerator-AKNRQW6A.js → matildaAgentContentGenerator-HG4ABAJG.js} +1 -1
  32. package/chunks/matildaContentGenerator-WEAUMFNT.js +8 -0
  33. package/chunks/matildaOAuth2-LKOMJUC6.js +3 -0
  34. package/chunks/{monitor-IDNOTNUP.js → monitor-755GJUC4.js} +1 -1
  35. package/chunks/{notebook-edit-4VBYBZFJ.js → notebook-edit-SWCJ3FMF.js} +1 -1
  36. package/chunks/{openaiContentGenerator-WTRQK5RJ.js → openaiContentGenerator-JIODOCNJ.js} +1 -1
  37. package/chunks/ripGrep-5GE6ECVF.js +3 -0
  38. package/chunks/{scheduler-AOKJEAXJ.js → scheduler-VA6HAYT4.js} +1 -1
  39. package/chunks/{serve-2JJY265V.js → serve-TVYEQNS6.js} +2 -2
  40. package/chunks/shell-JNZXS437.js +3 -0
  41. package/chunks/src-MMNXN6E3.js +3 -0
  42. package/chunks/{team-create-Z6636NPD.js → team-create-CUBBNHIF.js} +1 -1
  43. package/chunks/{update-goal-DH2TEYYU.js → update-goal-6WDBMJ2I.js} +1 -1
  44. package/chunks/{web-fetch-5F7C7MXU.js → web-fetch-QP42GV23.js} +1 -1
  45. package/chunks/{web-search-W2FYCGK5.js → web-search-FURCBRRK.js} +1 -1
  46. package/chunks/{workflow-M7KXXDO6.js → workflow-WRWIXJCG.js} +2 -2
  47. package/chunks/write-file-7BFZXGIJ.js +11 -0
  48. package/cli.js +476 -462
  49. package/locales/en.js +6 -0
  50. package/package.json +2 -2
  51. package/chunks/chunk-7VGUNT5L.js +0 -8
  52. package/chunks/chunk-CLUEFPSU.js +0 -8
  53. package/chunks/chunk-CYTN3WRM.js +0 -101
  54. package/chunks/chunk-IB7TWUWM.js +0 -90
  55. package/chunks/chunk-LLQVLTPB.js +0 -27
  56. package/chunks/contextCommand-7KHYFQ6G.js +0 -3
  57. package/chunks/edit-U4PMKZYZ.js +0 -38
  58. package/chunks/enterPlanMode-6LZSSWFT.js +0 -17
  59. package/chunks/geminiContentGenerator-GWGLIDJJ.js +0 -8
  60. package/chunks/matildaContentGenerator-MXP3V2UQ.js +0 -8
  61. package/chunks/matildaOAuth2-2IUZAZEO.js +0 -3
  62. package/chunks/ripGrep-DOB57AMM.js +0 -3
  63. package/chunks/shell-WFONAKPV.js +0 -3
  64. package/chunks/src-IHYMMU26.js +0 -3
  65. package/chunks/write-file-O4DJX4LP.js +0 -11
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Bf as te,Ye as V,jf as q,qf as Q,rf as W,tf as Z,uf as ee}from"./chunk-RO6LKQPB.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-KP6BLFQS.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-XXZH7C44.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-GTR4V2PV.js";import"./chunk-S4K76QPI.js";import"./chunk-CYTN3WRM.js";import"./chunk-4F4DA5UI.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-CLUEFPSU.js";import"./chunk-7VGUNT5L.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import{b as Y}from"./chunk-NDR7ZFUA.js";import{g as K,i as X,p as v,q as H}from"./chunk-5U3A6KMU.js";import"./chunk-LLQVLTPB.js";import"./chunk-XKDGRW3K.js";import{b as z}from"./chunk-ESSYHTAZ.js";import"./chunk-IOCF4XSR.js";import{Y as G}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as k}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";k();k();import{randomBytes as ke}from"node:crypto";import*as ae from"node:os";k();import*as O from"node:vm";function he(e){let r=/^\s*export\s+const\s+meta\s*=\s*\{/.exec(e);if(!r)return null;let n=r.index,a=e.indexOf("{",n),i=1,o=a+1;for(;o<e.length&&i>0;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(o+=2;o<e.length&&e[o]!==`
3
+ import{Cf as te,Ze as V,kf as q,rf as Q,sf as W,uf as Z,vf as ee}from"./chunk-IGQPRDMV.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.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-DORRYU7L.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import{b as Y}from"./chunk-NDR7ZFUA.js";import{g as K,i as X,p as v,q as H}from"./chunk-5U3A6KMU.js";import"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import{b as z}from"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{Y as G}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as k}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";k();k();import{randomBytes as ke}from"node:crypto";import*as ae from"node:os";k();import*as O from"node:vm";function he(e){let r=/^\s*export\s+const\s+meta\s*=\s*\{/.exec(e);if(!r)return null;let n=r.index,a=e.indexOf("{",n),i=1,o=a+1;for(;o<e.length&&i>0;){let l=e[o],c=e[o+1];if(l==="/"&&c==="/"){for(o+=2;o<e.length&&e[o]!==`
4
4
  `;)o++;continue}if(l==="/"&&c==="*"){for(o+=2;o<e.length&&!(e[o]==="*"&&e[o+1]==="/");)o++;o+=2;continue}if(l==="/"&&me(e,o)){o++;let u=!1;for(;o<e.length&&(u||e[o]!=="/")&&e[o]!==`
5
5
  `;)e[o]==="\\"?o+=2:e[o]==="["?(u=!0,o++):(e[o]==="]"&&(u=!1),o++);for(o++;o<e.length&&/[gimsuy]/.test(e[o]);)o++;continue}if(l==='"'||l==="'"||l==="`"){let u=l;for(o++;o<e.length&&e[o]!==u;)e[o]==="\\"&&o++,o++;o++;continue}l==="{"?i++:l==="}"&&i--,o++}if(i!==0)throw new Error("stripExportMeta: unbalanced braces in export const meta declaration \u2014 the workflow script cannot be safely stripped. Check the meta block syntax.");let g=o-1;for(;o<e.length&&/[\s;]/.test(e[o]);)o++;return{exportIdx:n,startBrace:a,endBraceIncl:g,afterMeta:o}}function de(e){let t=he(e);if(!t)return{stripped:e,meta:null};let r=e.slice(t.startBrace,t.endBraceIncl+1),n=e.slice(0,t.exportIdx)+e.slice(t.afterMeta),a=O.createContext(Object.create(null)),i;try{i=new O.Script(`(${r})`).runInContext(a)}catch(g){let l=g instanceof Error?g.message:String(g);throw new Error(`extractAndStripMeta: failed to evaluate meta object literal: ${l}`)}C(i);let o=fe(i);return{stripped:n,meta:o}}function C(e,t=new WeakSet){if(e===null||typeof e!="object"||t.has(e))return;if(t.add(e),typeof e.then=="function"){try{e.catch(()=>{})}catch{}throw new Error("extractAndStripMeta: meta values must not be Promises (no async / dynamic import allowed in meta literal)")}if(Array.isArray(e)){for(let n of e)C(n,t);return}for(let n of Object.values(e))C(n,t)}function fe(e){if(e===null||typeof e!="object")throw new Error("meta must be an object");let t=e;if(typeof t.name!="string"||t.name.length===0)throw new Error("meta.name must be a non-empty string");if(typeof t.description!="string"||t.description.length===0)throw new Error("meta.description must be a non-empty string");if(t.whenToUse!==void 0&&typeof t.whenToUse!="string")throw new Error("meta.whenToUse must be a string");let r;if(t.phases!==void 0){if(!Array.isArray(t.phases))throw new Error("meta.phases must be an array");r=[];for(let a of t.phases){if(a===null||typeof a!="object")throw new Error("meta.phases entries must be objects");let i=a;if(typeof i.title!="string"||i.title.length===0)throw new Error("meta.phases[].title must be a non-empty string");let o={title:i.title};if(i.detail!==void 0){if(typeof i.detail!="string")throw new Error("meta.phases[].detail must be a string");o.detail=i.detail}if(i.model!==void 0){if(typeof i.model!="string")throw new Error("meta.phases[].model must be a string");o.model=i.model}r.push(o)}}let n={name:t.name,description:t.description};return t.whenToUse!==void 0&&(n.whenToUse=t.whenToUse),r!==void 0&&(n.phases=r),n}function me(e,t){let r=t-1;for(;r>=0&&/\s/.test(e[r]);)r--;if(r<0)return!0;let n=e[r];return/[{[(,;:=!&|?+\-*/%^~<>]/.test(n)}var p=G("WORKFLOW"),_=1e4,P=1e4,re=64,we=30*60*1e3;function be(e){if(typeof e.maxWallClockMs=="number"&&e.maxWallClockMs>0)return e.maxWallClockMs;let t=Number(process.env.MATILDA_CODE_MAX_WORKFLOW_SECONDS);return Number.isFinite(t)&&t>0?t*1e3:we}function R(e,t=0,r=new WeakSet){if(t>re)throw new Error(`WorkflowSandbox: args exceeded max nesting depth of ${re}`);if(e===null)return;let n=typeof e;if(n==="function")throw new Error("WorkflowSandbox: args must be JSON-serializable (functions are not allowed).");if(n==="bigint")throw new Error("WorkflowSandbox: args must be JSON-serializable (BigInt is not allowed \u2014 pass as string).");if(n!=="object")return;let a=e;if(r.has(a))throw new Error("WorkflowSandbox: args must be JSON-serializable (circular reference detected).");if(r.add(a),Array.isArray(e))for(let i of e)R(i,t+1,r);else for(let i of Object.values(e))R(i,t+1,r)}function ne(e){let t=[],r=[],n=h=>{if(r.length<_){let s=String(h);r.push(s);try{e.emitter?.logAppended?.(s)}catch(d){p.warn("emitter.logAppended threw:",d)}}else r.length===_&&r.push(`[workflow log truncated at ${_} lines]`)},a=h=>{if(t.length<P){let s=String(h);if(t[t.length-1]===s)return;t.push(s);try{e.emitter?.phaseStarted?.(s)}catch(d){p.warn("emitter.phaseStarted threw:",d)}}else t.length===P&&t.push(`[workflow phases truncated at ${P} entries]`)};e.args!==void 0&&R(e.args);let o={argsJson:e.args===void 0?null:JSON.stringify(e.args),pushPhase:a,pushLog:n,lastPhase:()=>t[t.length-1],hostAgent:e.dispatch,logRevivalFailure:(h,s)=>{p.warn(`Workflow result revival failed at index ${h}: ${s}; slot set to null (non-JSON-serializable thunk return).`)},hasParallel:!!e.parallel,hasPipeline:!!e.pipeline,hasBudget:!!e.budget,hostParallel:e.parallel,hostPipeline:e.pipeline,budgetTotal:e.budget?e.budget.total:null,hostBudgetSpent:e.budget?e.budget.spent.bind(e.budget):null,hostBudgetRemaining:e.budget?e.budget.remaining.bind(e.budget):null};Object.setPrototypeOf(o,null);let g=Object.assign(Object.create(null),{__workflowBridge:o}),l=O.createContext(g);O.runInContext(`(() => {
6
6
  const __b = globalThis.__workflowBridge;
@@ -327,7 +327,7 @@ CRITICAL: You MUST deliver your final answer by calling the \`structured_output\
327
327
  - If validation fails, the error tells you what to fix. Try again with corrected fields.
328
328
  - After two failed attempts, the run terminates \u2014 get the arguments right.
329
329
  - Do NOT use SendUserMessage to deliver your answer.
330
- - Be concise; the script reads only the structured payload, not your prose.`;k();function j(){return new DOMException("Concurrency limiter aborted.","AbortError")}function oe(e,t){if(!Number.isInteger(e)||e<1)throw new Error(`Concurrency limit must be a positive integer, got ${String(e)}.`);let r=0,n=[],a=()=>{for(;r<e&&n.length>0;){let o=n.shift();if(t?.aborted){o.reject(j());continue}r++,Promise.resolve().then(o.thunk).then(o.resolve,o.reject).finally(()=>{r--,a()})}},i=o=>new Promise((g,l)=>{if(t?.aborted){l(j());return}n.push({thunk:o,resolve:g,reject:l}),a()});return t&&!t.aborted&&t.addEventListener("abort",()=>{for(;n.length>0;)n.shift().reject(j())},{once:!0}),{run:i}}var D=1e3,I="MATILDA_CODE_MAX_WORKFLOW_AGENTS",L=1e4;function ye(e=process.env){let t=e[I];if(t===void 0||t.trim()==="")return D;let r=Number(t);return!Number.isInteger(r)||r<1?(p.warn(`Invalid ${I}=${JSON.stringify(t)}, using default (${D})`),D):r>L?(p.warn(`${I}=${r} exceeds hard ceiling (${L}); clamping.`),L):r}var $="MATILDA_CODE_MAX_WORKFLOW_CONCURRENCY",U=64;function ve(e=process.env){let t=e[$];if(t!==void 0&&t.trim()!==""){let r=Number(t);if(Number.isInteger(r)&&r>=1)return r>U?(p.warn(`${$}=${r} exceeds hard ceiling (${U}); clamping.`),U):r;p.warn(`Invalid ${$}=${JSON.stringify(t)}, using cpu-derived default`)}return Math.max(1,Math.min(16,ae.cpus().length-2))}var se=50,ie=10,le=[v.SEND_MESSAGE,v.EXIT_PLAN_MODE],T=class extends Error{constructor(r,n,a,i=null){super(r);this.phases=n;this.logs=a;this.meta=i}name="WorkflowExecutionError"};function Oe(){return`wf_${ke(8).toString("hex")}`}function Se(e){return e.replace(/[\u0000-\u001f\u007f]+/g," ")}function ce(e,t){return async(r,n)=>{let{AgentHeadless:a,ContextState:i}=await import("./agent-headless-LBLAX66M.js"),o=new i;if(o.set("task_prompt",r),n.agentType===void 0&&n.model===void 0&&n.isolation===void 0&&n.schema===void 0){let g=await a.create(n.label??"workflow-agent",e,{systemPrompt:M,initialMessages:[]},{},{max_turns:se,max_time_minutes:ie},{tools:["*"],disallowedTools:le});await g.execute(o,t);let l=g.getTerminateMode();if(l!=="GOAL")throw new Error(`Workflow subagent did not complete (terminate mode: ${l}).`);return g.getFinalText()}return Te(e,o,n,t)}}async function Te(e,t,r,n){if(r.isolation==="remote")throw new Error("agent({isolation:'remote'}) is not available in this build.");let a=e.getSubagentManager(),i;if(r.agentType!==void 0){let s=await a.findSubagentByName(r.agentType);if(!s){let d=Se(r.agentType);throw new Error(`agent({agentType}): agent type '${d}' not found.`)}i=s}else i={name:r.label??"workflow-agent",description:"Default workflow subagent (per-call overrides).",systemPrompt:M,level:"session",isBuiltin:!1};let o;r.schema!==void 0&&(o=r.agentType!==void 0&&i.systemPrompt?`${i.systemPrompt}
330
+ - Be concise; the script reads only the structured payload, not your prose.`;k();function j(){return new DOMException("Concurrency limiter aborted.","AbortError")}function oe(e,t){if(!Number.isInteger(e)||e<1)throw new Error(`Concurrency limit must be a positive integer, got ${String(e)}.`);let r=0,n=[],a=()=>{for(;r<e&&n.length>0;){let o=n.shift();if(t?.aborted){o.reject(j());continue}r++,Promise.resolve().then(o.thunk).then(o.resolve,o.reject).finally(()=>{r--,a()})}},i=o=>new Promise((g,l)=>{if(t?.aborted){l(j());return}n.push({thunk:o,resolve:g,reject:l}),a()});return t&&!t.aborted&&t.addEventListener("abort",()=>{for(;n.length>0;)n.shift().reject(j())},{once:!0}),{run:i}}var D=1e3,I="MATILDA_CODE_MAX_WORKFLOW_AGENTS",L=1e4;function ye(e=process.env){let t=e[I];if(t===void 0||t.trim()==="")return D;let r=Number(t);return!Number.isInteger(r)||r<1?(p.warn(`Invalid ${I}=${JSON.stringify(t)}, using default (${D})`),D):r>L?(p.warn(`${I}=${r} exceeds hard ceiling (${L}); clamping.`),L):r}var $="MATILDA_CODE_MAX_WORKFLOW_CONCURRENCY",U=64;function ve(e=process.env){let t=e[$];if(t!==void 0&&t.trim()!==""){let r=Number(t);if(Number.isInteger(r)&&r>=1)return r>U?(p.warn(`${$}=${r} exceeds hard ceiling (${U}); clamping.`),U):r;p.warn(`Invalid ${$}=${JSON.stringify(t)}, using cpu-derived default`)}return Math.max(1,Math.min(16,ae.cpus().length-2))}var se=50,ie=10,le=[v.SEND_MESSAGE,v.EXIT_PLAN_MODE],T=class extends Error{constructor(r,n,a,i=null){super(r);this.phases=n;this.logs=a;this.meta=i}name="WorkflowExecutionError"};function Oe(){return`wf_${ke(8).toString("hex")}`}function Se(e){return e.replace(/[\u0000-\u001f\u007f]+/g," ")}function ce(e,t){return async(r,n)=>{let{AgentHeadless:a,ContextState:i}=await import("./agent-headless-VPF3VPXU.js"),o=new i;if(o.set("task_prompt",r),n.agentType===void 0&&n.model===void 0&&n.isolation===void 0&&n.schema===void 0){let g=await a.create(n.label??"workflow-agent",e,{systemPrompt:M,initialMessages:[]},{},{max_turns:se,max_time_minutes:ie},{tools:["*"],disallowedTools:le});await g.execute(o,t);let l=g.getTerminateMode();if(l!=="GOAL")throw new Error(`Workflow subagent did not complete (terminate mode: ${l}).`);return g.getFinalText()}return Te(e,o,n,t)}}async function Te(e,t,r,n){if(r.isolation==="remote")throw new Error("agent({isolation:'remote'}) is not available in this build.");let a=e.getSubagentManager(),i;if(r.agentType!==void 0){let s=await a.findSubagentByName(r.agentType);if(!s){let d=Se(r.agentType);throw new Error(`agent({agentType}): agent type '${d}' not found.`)}i=s}else i={name:r.label??"workflow-agent",description:"Default workflow subagent (per-call overrides).",systemPrompt:M,level:"session",isBuiltin:!1};let o;r.schema!==void 0&&(o=r.agentType!==void 0&&i.systemPrompt?`${i.systemPrompt}
331
331
 
332
332
  ${N}`:N);let g;r.schema!==void 0&&i.tools&&i.tools.length>0&&!i.tools.includes("*")&&!i.tools.includes(v.STRUCTURED_OUTPUT)&&(g=[...i.tools,v.STRUCTURED_OUTPUT]);let l={...i,...r.model!==void 0?{model:r.model}:{},...o!==void 0?{systemPrompt:o}:{},...g!==void 0?{tools:g}:{},disallowedTools:Array.from(new Set([...i.disallowedTools??[],...le]))},c=null,u=e;r.isolation==="worktree"&&(c=await Ee(e),u=Ae(e,c.path));let h;try{let s=null;r.schema!==void 0&&(u=await Pe(u,r.schema),s=xe());let d=n;if(s){let w=new AbortController;n&&(n.aborted?w.abort(n.reason):(h=()=>w.abort(n.reason),n.addEventListener("abort",h))),s.abortController=w,d=w.signal}let b=s?_e(s):void 0,{subagent:f,dispose:m}=await a.createAgentHeadless(l,u,{runConfigOverrides:{max_turns:se,max_time_minutes:ie},eventEmitter:b});try{if(await f.execute(t,d),s){if(s.result!==null){if(c){let E=c;c=null;let A=await J(E);A&&p.info(`[Workflow] Schema-mode subagent preserved worktree at ${A.path??"(directory removed)"} on branch ${A.branch}. The structured payload is returned verbatim; recover the work from the preserved path / branch.`)}return s.result}if(n?.aborted)throw new DOMException("Workflow aborted.","AbortError");let S=f.getTerminateMode();throw S!=="GOAL"&&S!=="CANCELLED"?new Error(`Workflow subagent did not complete (terminate mode: ${S}).`):s.attempts>2?new Error("subagent completed without calling StructuredOutput (after 2 in-conversation nudges)."):new Error("subagent completed without calling structured_output (no validation attempt \u2014 model produced plain-text content).")}let w=f.getTerminateMode();if(w!=="GOAL")throw new Error(`Workflow subagent did not complete (terminate mode: ${w}).`);let y=f.getFinalText();if(c){let S=c;c=null;let E=await J(S);E&&typeof y=="string"&&(y=We(y,E))}return y}finally{await m()}}finally{if(h&&n&&n.removeEventListener("abort",h),c)try{await J(c)}catch(s){p.warn(`Workflow worktree cleanup in fallback finally failed for ${c.path}: ${s instanceof Error?s.message:String(s)}`)}}}async function Ee(e){let t=e.getTargetDir();if(/\.matilda[\\/]worktrees[\\/]/.test(t))throw new Error(`agent({isolation:'worktree'}): parent is already inside a worktree (${t}). Nested isolation worktrees are not supported \u2014 the subagent's inherited paths would still reference the outer worktree.`);let r=new W(t),n=await r.checkGitAvailable();if(!n.available)throw new Error(`agent({isolation:'worktree'}): ${n.error??"git is not available"}.`);if(!await r.isGitRepository())throw new Error(`agent({isolation:'worktree'}): ${t} is not a git repository.`);let a=await r.getRepoTopLevel()??t,i=a===t?r:new W(a),o=!1;try{o=await i.hasWorktreeChanges(a)}catch(u){p.warn(`[Workflow] hasWorktreeChanges failed at ${a}: ${u}`),o=!0}if(o)throw new Error(`agent({isolation:'worktree'}): parent working tree at ${a} has uncommitted changes that would not propagate into the isolated worktree. The subagent would see the prior HEAD instead of the current state. Commit or stash the changes, then re-run.`);let g=Q(),l;try{l=await i.getCurrentBranch()}catch(u){p.warn(`[Workflow] getCurrentBranch failed at ${a}: ${u}`)}let c=await i.createUserWorktree(g,l,{symlinkDirectories:e.getWorktreeSymlinkDirectories()});if(!c.success||!c.worktree)throw new Error(`agent({isolation:'worktree'}): failed to create worktree: ${c.error??"unknown error"}.`);try{await q(c.worktree.path,e.getSessionId())}catch(u){p.warn(`[Workflow] failed to write session marker at ${c.worktree.path}: ${u}`)}return{slug:g,path:c.worktree.path,branch:c.worktree.branch,repoRoot:a}}function Ae(e,t){let r=Object.create(e);r.targetDir=t,r.cwd=t,r.getTargetDir=()=>t,r.getCwd=()=>t,r.getWorkingDir=()=>t,r.getProjectRoot=()=>t;let n=new Z(t);r.fileDiscoveryService=n,r.getFileService=()=>n;let a=new ee(t);return r.workspaceContext=a,r.getWorkspaceContext=()=>a,r}async function J(e){let t=new W(e.repoRoot),[r,n]=await Promise.all([t.hasWorktreeChanges(e.path).catch(a=>(p.warn(`[Workflow] hasWorktreeChanges failed for ${e.path}: ${a}`),!0)),t.hasUnmergedWorktreeCommits(e.slug).catch(a=>(p.warn(`[Workflow] hasUnmergedWorktreeCommits failed for ${e.slug}: ${a}`),!0))]);if(r||n)return p.info(`[Workflow] Preserving isolation worktree ${e.path} (branch ${e.branch}, hasChanges=${r}, hasUnmerged=${n})`),{path:e.path,branch:e.branch};try{let a=await t.removeUserWorktree(e.slug,{deleteBranch:!0});if(!a.success)return p.warn(`[Workflow] Failed to remove ephemeral worktree ${e.path}: ${a.error}`),{path:e.path,branch:e.branch};if(a.branchPreserved)return p.warn(`[Workflow] Removed worktree directory ${e.path} but kept branch ${e.branch} (unmerged commits at delete time)`),{branch:e.branch}}catch(a){return p.warn(`[Workflow] Failed to remove ephemeral worktree ${e.path}: ${a}`),{path:e.path,branch:e.branch}}return null}function We(e,t){let r=e.endsWith(`
333
333
  `)?`
@@ -0,0 +1,11 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as Y}from"./chunk-OCXGNAAT.js";import{a as V}from"./chunk-I55PXD4N.js";import{Kd as D,Ld as G,Ob as B,de as P,ee as p,ja as F,ke as q,le as H,oe as K}from"./chunk-IGQPRDMV.js";import"./chunk-TZIDSCTF.js";import"./chunk-FUNLOUYI.js";import"./chunk-R3H6IWFK.js";import"./chunk-OMZ5SGMK.js";import"./chunk-GIIMOLLN.js";import"./chunk-RBG4ERTN.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-LQWORCPO.js";import"./chunk-TISQNFB5.js";import"./chunk-SS5WUOSJ.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-DORRYU7L.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import{Lb as k,Oa as N,_c as U,ca as L,ha as h}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{w as j}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as $,i as W,p as O,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{A as C,C as I,Y as M,a as f,c as _,z as w}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as x}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";x();import y from"node:fs";import g from"node:path";var u=M("WRITE_FILE"),b=class extends ${constructor(a,t){super(t);this.config=a}toolLocations(){return[{path:this.params.file_path}]}getDescription(){let a=C(this.params.file_path,this.config.getTargetDir());return`Writing to ${w(a)}`}async getDefaultPermission(){let a=this.config.getProjectRoot();return j(g.resolve(this.params.file_path),a)?"allow":"ask"}async getConfirmationDetails(a){let t="",o=await h(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){let i=await p(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!i.ok)throw new P(i.rawMessage,i.type)}if(o)try{let{content:i}=await this.config.getFileSystemService().readTextFile({path:this.params.file_path});t=i}catch(i){if(f(i)&&i.code==="ENOENT")o=!1;else throw new Error(`Error reading existing file for confirmation: ${_(i)}`)}if(o&&!this.config.getFileReadCacheDisabled()){let i=await p(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:!0});if(!i.ok)throw u.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:i.type}),new P(i.rawMessage,i.type)}let r=C(this.params.file_path,this.config.getTargetDir()),c=g.basename(this.params.file_path),s=F(c,t,this.params.content,"Current","Proposed",D);return{type:"edit",title:`Confirm Write: ${w(r)}`,fileName:c,filePath:this.params.file_path,fileDiff:s,originalContent:t,newContent:this.params.content,onConfirm:async i=>{i==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}async execute(a){let{file_path:t,content:o,ai_proposed_content:r,modified_by_user:c}=this.params,s=await h(t),m="",i=!1,E,R,J=g.dirname(t);if(!this.config.getFileReadCacheDisabled()){let e=await p(this.config.getFileReadCache(),t,"overwriting");if(!e.ok)return{llmContent:e.rawMessage,returnDisplay:`Error: ${e.displayMessage}`,error:{message:e.rawMessage,type:e.type}}}if(s)try{let e=await this.config.getFileSystemService().readTextFile({path:t});e._meta?.bom!==void 0?i=e._meta.bom:i=e.content.length>0&&e.content.codePointAt(0)===65279,E=e._meta?.encoding||"utf-8",R=K(e.content),m=e.content,s=!0}catch(e){if(f(e)&&e.code==="ENOENT")s=!1;else{let n={message:_(e),code:f(e)?e.code:void 0},l=n.code?`Error checking existing file '${t}': ${n.message} (${n.code})`:`Error checking existing file: ${n.message}`;return{llmContent:l,returnDisplay:l,error:{message:l,type:"file_write_failure"}}}}if(s&&!this.config.getFileReadCacheDisabled()){let e=await p(this.config.getFileReadCache(),t,"overwriting",{expectExisting:!0});if(!e.ok)return u.warn("post-read TOCTOU rejection (execute)",{path:t,reason:e.type}),{llmContent:e.rawMessage,returnDisplay:`Error: ${e.displayMessage}`,error:{message:e.rawMessage,type:e.type}}}if(!s){let e=this.config.getDefaultFileEncoding();e===q.UTF8_BOM?i=!0:e===void 0&&(i=H(t)),E=void 0}try{await this.config.getFileHistoryService().trackEdit(t)}catch{}if(!this.config.getFileReadCacheDisabled()){let e=await p(this.config.getFileReadCache(),t,"overwriting",{expectExisting:s});if(!e.ok)return u.warn("pre-write TOCTOU rejection",{path:t,reason:e.type}),{llmContent:e.rawMessage,returnDisplay:`Error: ${e.displayMessage}`,error:{message:e.rawMessage,type:e.type}}}s||y.mkdirSync(J,{recursive:!0});try{await this.config.getFileSystemService().writeTextFile({path:t,content:o,_meta:{bom:i,encoding:E,lineEnding:R}}),c||B.getInstance().recordEdit(t,s?m:null,o);try{let d=y.statSync(t);this.config.getFileReadCache().recordWrite(t,d)}catch{}let e=g.basename(t),n=m,l=F(e,n,o,"Original","Written",D),Q=G(e,n,r||o,o),T=[s?`Successfully overwrote file: ${t}.`:`Successfully created and wrote to new file: ${t}.`];c&&T.push(`User modified the \`content\` to be: ${o}`);let X=L(t),Z=N(t),ee=g.extname(t),te=s?"update":"create",ie=o.split(`
4
+ `).length;k(this.config,new U(v.Name,te,ie,X,ee,Z));let oe={fileDiff:l,fileName:e,originalContent:m,newContent:o,diffStat:Q};try{let d=await V(this.config,t);d&&T.push(`
5
+
6
+ ${d}`)}catch{}return{llmContent:T.join(" "),returnDisplay:oe}}catch(e){let n,l="file_write_failure";return f(e)?(n=`Error writing to file '${t}': ${e.message} (${e.code})`,e.code==="EACCES"?(n=`Permission denied writing to file: ${t} (${e.code})`,l="permission_denied"):e.code==="ENOSPC"?(n=`No space left on device: ${t} (${e.code})`,l="no_space_left"):e.code==="EISDIR"&&(n=`Target is a directory, not a file: ${t} (${e.code})`,l="target_is_directory"),this.config.getDebugMode()&&e.stack&&u.debug("Write file error stack:",e.stack)):e instanceof Error?n=`Error writing to file: ${e.message}`:n=`Error writing to file: ${String(e)}`,{llmContent:n,returnDisplay:n,error:{message:n,type:l}}}}},v=class S extends W{constructor(a){super(S.Name,A.WRITE_FILE,"Writes content to a specified file in the local filesystem. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.\n\nThe user has the ability to modify `content`. If modified, this will be stated in the response.","edit",{properties:{file_path:{description:"The absolute path to the file to write to (e.g., '/home/user/project/file.txt'). Relative paths are not supported.",type:"string"},content:{description:"The content to write to the file.",type:"string"}},required:["file_path","content"],type:"object"});this.config=a}static Name=O.WRITE_FILE;validateToolParamValues(a){let t=I(a.file_path.trim());if(a.file_path=t,!t)return'Missing or empty "file_path"';if(!g.isAbsolute(t))return`File path must be absolute: ${t}`;let o=Y(this.config,t);if(o)return o;try{if(y.existsSync(t)&&y.lstatSync(t).isDirectory())return`Path is a directory, not a file: ${t}`}catch(r){return`Error accessing path properties for validation: ${t}. Reason: ${r instanceof Error?r.message:String(r)}`}return null}createInvocation(a){return new b(this.config,a)}toAutoClassifierInput(a){let t=a.content??"";return{file_path:a.file_path,byte_count:Buffer.byteLength(t,"utf8"),content_preview:t.slice(0,300),content_truncated:t.length>300}}getModifyContext(a){return{getFilePath:t=>t.file_path,getCurrentContent:async t=>{if(await h(t.file_path))try{let{content:r}=await this.config.getFileSystemService().readTextFile({path:t.file_path});return r}catch(r){if(!f(r)||r.code!=="ENOENT")throw r;return""}else return""},getProposedContent:async t=>t.content,createUpdatedParams:(t,o,r)=>{let c=r.content;return{...r,ai_proposed_content:c,content:o,modified_by_user:!0}}}}};export{v as WriteFileTool};
7
+ /**
8
+ * @license
9
+ * Copyright 2025 Google LLC
10
+ * SPDX-License-Identifier: Apache-2.0
11
+ */