@maincode-ai/matilda-code 0.21.2 → 0.21.3
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.
- package/README.md +7 -0
- package/chunks/{agent-B4THN25M.js → agent-WBKEN3MM.js} +1 -1
- package/chunks/{agent-headless-CR55Q5QA.js → agent-headless-OJM6RWIA.js} +1 -1
- package/chunks/{anthropicContentGenerator-GW3P6NLQ.js → anthropicContentGenerator-EFVV6ZTA.js} +1 -1
- package/chunks/{chunk-CFBZKYFB.js → chunk-6QP5C76Y.js} +52 -52
- package/chunks/{chunk-MAQJCFZU.js → chunk-7LNKXNEZ.js} +526 -517
- package/chunks/{chunk-GIIMOLLN.js → chunk-C2ZWB2NT.js} +1 -1
- package/chunks/{chunk-NUJ63BIE.js → chunk-DBSJNFFU.js} +1 -1
- package/chunks/{chunk-SS5WUOSJ.js → chunk-FT76AZPN.js} +1 -1
- package/chunks/chunk-FU2PKCG5.js +108 -0
- package/chunks/{chunk-QEUJHX22.js → chunk-IZ6YBZWM.js} +13 -13
- package/chunks/{chunk-M3G4PG2T.js → chunk-JDXISO3F.js} +4 -4
- package/chunks/chunk-MJEXA2MA.js +8 -0
- package/chunks/chunk-MTMU7JYZ.js +11 -0
- package/chunks/chunk-SDTWBD62.js +8 -0
- package/chunks/{chunk-JEDNTIM3.js → chunk-ZYW5GLYY.js} +1 -1
- package/chunks/{computer-use-STZBQBFP.js → computer-use-MCXFHFTP.js} +1 -1
- package/chunks/{contextCommand-LB5MHXJY.js → contextCommand-G4LS5GW6.js} +1 -1
- package/chunks/edit-KNZAPSGJ.js +39 -0
- package/chunks/{enter-worktree-V6TA7IPP.js → enter-worktree-LJ66TFYR.js} +1 -1
- package/chunks/{enterPlanMode-KQCLOC2K.js → enterPlanMode-P6EIGU3Y.js} +1 -1
- package/chunks/{exit-worktree-B3SWF6PM.js → exit-worktree-QVQ3TLW5.js} +1 -1
- package/chunks/{exitPlanMode-7OHF37SX.js → exitPlanMode-I7SGPSG4.js} +1 -1
- package/chunks/{geminiContentGenerator-6VRAJ3BI.js → geminiContentGenerator-SBVCQ423.js} +1 -1
- package/chunks/{glob-ZAZPTZD5.js → glob-F5YOX6YA.js} +1 -1
- package/chunks/{grep-DNYRXQWA.js → grep-UOIHSM5U.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-S26H4H3W.js → matildaAgentContentGenerator-EIQI4YCP.js} +10 -10
- package/chunks/{matildaContentGenerator-UFATU4UK.js → matildaContentGenerator-QMMGDPIK.js} +1 -1
- package/chunks/{monitor-HQXCJQ3M.js → monitor-GDKHPTET.js} +1 -1
- package/chunks/notebook-edit-LWH7H4WX.js +17 -0
- package/chunks/{openaiContentGenerator-XAPZXISY.js → openaiContentGenerator-TNZ6SB7H.js} +1 -1
- package/chunks/{read-file-HEVXSNSO.js → read-file-URGJTANM.js} +1 -1
- package/chunks/{ripGrep-BNBRX7HQ.js → ripGrep-SL4ICAX6.js} +1 -1
- package/chunks/{scheduler-3K7OROFK.js → scheduler-EX674HYK.js} +1 -1
- package/chunks/{serve-MBVRWSOA.js → serve-FZ4FTA5D.js} +7 -7
- package/chunks/{shell-3YF6VEDO.js → shell-LLU55LCI.js} +1 -1
- package/chunks/{skill-4GKPLUND.js → skill-KSYY6BM6.js} +1 -1
- package/chunks/src-UXJDJ3RJ.js +3 -0
- package/chunks/{symbol-search-WVNUJRET.js → symbol-search-3A66G4MP.js} +1 -1
- package/chunks/{team-create-2LLJKRSY.js → team-create-7PFAVYVV.js} +1 -1
- package/chunks/{tool-search-47TA6SG4.js → tool-search-7D46IF5G.js} +1 -1
- package/chunks/{update-goal-6WDBMJ2I.js → update-goal-EUJYH23K.js} +1 -1
- package/chunks/{web-fetch-QP42GV23.js → web-fetch-UGTFUOQN.js} +1 -1
- package/chunks/{workflow-EIZTKOPX.js → workflow-2TGFLD2R.js} +2 -2
- package/chunks/write-file-DQ6NYEJ7.js +15 -0
- package/cli.js +443 -444
- package/package.json +2 -2
- package/sandbox-macos-restrictive-open.sb +22 -2
- package/chunks/chunk-I55PXD4N.js +0 -10
- package/chunks/chunk-KFULPF66.js +0 -107
- package/chunks/chunk-OCXGNAAT.js +0 -8
- package/chunks/chunk-RBG4ERTN.js +0 -11
- package/chunks/chunk-XJDC3ZQZ.js +0 -8
- package/chunks/edit-EP7HIW5W.js +0 -39
- package/chunks/notebook-edit-S63FQCCF.js +0 -17
- package/chunks/src-4XJIGVTS.js +0 -3
- package/chunks/write-file-YT7UT6TX.js +0 -15
package/chunks/{matildaAgentContentGenerator-S26H4H3W.js → matildaAgentContentGenerator-EIQI4YCP.js}
RENAMED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{M as F,N as U,O as j,g as x,la as $}from"./chunk-
|
|
3
|
+
import{M as F,N as U,O as j,g as x,la as $}from"./chunk-FU2PKCG5.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
4
|
`):""}function g(n,e){if(n.length<=e)return n;let t=`
|
|
5
5
|
[...omitted to fit Matilda native agent context...]
|
|
6
|
-
`,o=e-t.length,s=Math.floor(o*.6),
|
|
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
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,
|
|
9
|
-
`)};return
|
|
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:")?
|
|
11
|
-
`)){let p=M.endsWith("\r")?M.slice(0,-1):M;p.startsWith("event:")?
|
|
12
|
-
(empty prompt)`});let r=
|
|
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
13
|
Continue from the previous assistant response.`}):r.content.startsWith(`${this.purposeLabel(t)}:
|
|
14
|
-
`)||(
|
|
15
|
-
${r.content}`}),
|
|
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
16
|
${B}`:void 0,`Instructions:
|
|
17
17
|
${this.instructionsFromRequest(e)}`].filter(s=>!!s);return g(o.join(`
|
|
18
18
|
|
|
19
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
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
|
|
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
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
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
24
|
`):"";return`Assistant:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as d,i as u}from"./chunk-
|
|
3
|
+
import{a as d,i as u}from"./chunk-IZ6YBZWM.js";import"./chunk-QCIDUZV6.js";import"./chunk-7LNKXNEZ.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-FU2PKCG5.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
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Matilda
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
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-7LNKXNEZ.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-FU2PKCG5.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
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
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
6
|
id: ${i}
|
|
@@ -0,0 +1,17 @@
|
|
|
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-7LNKXNEZ.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-FU2PKCG5.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 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m}from"./chunk-
|
|
3
|
+
import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m}from"./chunk-IZ6YBZWM.js";import"./chunk-QCIDUZV6.js";import"./chunk-S4K76QPI.js";import{g as a}from"./chunk-FU2PKCG5.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-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{h as ContentGenerationPipeline,c as DeepSeekOpenAICompatibleProvider,i as EnhancedErrorHandler,b as MatildaOpenAICompatibleProvider,k as MatildaOpenAIContentGenerator,g as MiMoOpenAICompatibleProvider,e as MiniMaxOpenAICompatibleProvider,f as MistralOpenAICompatibleProvider,a as OpenAIContentConverter,j as OpenAIContentGenerator,d as OpenRouterOpenAICompatibleProvider,l as createOpenAIContentGenerator,m as determineProvider};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{wc as a}from"./chunk-
|
|
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 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{Lj as a,Mj as b}from"./chunk-7LNKXNEZ.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-FU2PKCG5.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,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{b as E}from"./chunk-7ZATDBWL.js";import{wa as P}from"./chunk-
|
|
3
|
+
import{b as E}from"./chunk-7ZATDBWL.js";import{wa as P}from"./chunk-7LNKXNEZ.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-FU2PKCG5.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
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|