@maincode-ai/matilda-code 0.20.1 → 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.
- package/chunks/{agent-CE34X462.js → agent-WQRHTEJK.js} +1 -1
- package/chunks/{agent-headless-CNI7H4BU.js → agent-headless-VPF3VPXU.js} +1 -1
- package/chunks/{chunk-WUQZ3WFM.js → chunk-A7VPKVYG.js} +1 -1
- package/chunks/{chunk-T75X5DJI.js → chunk-DORRYU7L.js} +1 -1
- package/chunks/{chunk-J56KRT6Z.js → chunk-IGQPRDMV.js} +525 -522
- package/chunks/{chunk-SKBC2YV2.js → chunk-QJO23A2D.js} +1 -1
- package/chunks/{chunk-DHBNZZZO.js → chunk-RGBIKCMN.js} +3 -3
- package/chunks/{chunk-OQVITNHW.js → chunk-YZVC65QR.js} +2 -2
- package/chunks/{computer-use-4533FJAL.js → computer-use-3BJWOZSA.js} +1 -1
- package/chunks/{contextCommand-M7LA5BRD.js → contextCommand-SOQLJJIW.js} +1 -1
- package/chunks/{edit-U4P4JWQ6.js → edit-ZIPLKFNT.js} +1 -1
- package/chunks/{en-ZU6RPTEW.js → en-75JQMW7P.js} +1 -1
- package/chunks/{enter-worktree-CUDNIQNH.js → enter-worktree-MWQ3Z7HX.js} +1 -1
- package/chunks/{enterPlanMode-SUTLQUZO.js → enterPlanMode-XT6MNE2L.js} +1 -1
- package/chunks/{exit-worktree-72O3N4X4.js → exit-worktree-O7DBPVFA.js} +1 -1
- package/chunks/{exitPlanMode-ZP75YCUK.js → exitPlanMode-FDXKFQJF.js} +1 -1
- package/chunks/{geminiContentGenerator-KPR5Q3XX.js → geminiContentGenerator-HXWUQ2DI.js} +1 -1
- package/chunks/{glob-V7YUXA6Z.js → glob-GYLGTXYL.js} +1 -1
- package/chunks/{grep-WOVNDJPG.js → grep-ZNYUS2MU.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-Y5CHD2WJ.js → matildaAgentContentGenerator-HG4ABAJG.js} +1 -1
- package/chunks/{matildaContentGenerator-F2DTT47Z.js → matildaContentGenerator-WEAUMFNT.js} +1 -1
- package/chunks/{monitor-G7G765XR.js → monitor-755GJUC4.js} +1 -1
- package/chunks/{notebook-edit-QK7K5ALF.js → notebook-edit-SWCJ3FMF.js} +1 -1
- package/chunks/{openaiContentGenerator-XLDE2S4K.js → openaiContentGenerator-JIODOCNJ.js} +1 -1
- package/chunks/{ripGrep-W5JZVWA4.js → ripGrep-5GE6ECVF.js} +1 -1
- package/chunks/{scheduler-C7N3Q67S.js → scheduler-VA6HAYT4.js} +1 -1
- package/chunks/{serve-WDV5Q7R4.js → serve-TVYEQNS6.js} +2 -2
- package/chunks/{shell-IEGVNM6S.js → shell-JNZXS437.js} +1 -1
- package/chunks/{src-Y3JZTLKR.js → src-MMNXN6E3.js} +1 -1
- package/chunks/{team-create-OPP7B3G2.js → team-create-CUBBNHIF.js} +1 -1
- package/chunks/{workflow-B3DRPVNT.js → workflow-WRWIXJCG.js} +2 -2
- package/chunks/{write-file-T7MBHX53.js → write-file-7BFZXGIJ.js} +1 -1
- package/cli.js +380 -386
- package/locales/en.js +6 -0
- package/package.json +2 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{he as _,ie as j}from"./chunk-
|
|
3
|
+
import{he as _,ie as j}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{b as D}from"./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{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
4
|
|
|
5
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
6
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{$i as K,aa as q,aj as Y,ie as z,zc as F}from"./chunk-
|
|
3
|
+
import{$i as K,aa as q,aj as Y,ie as z,zc as F}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{g as _}from"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import{g as U,i as V,p as H,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{C as O,F as W,J as S,Y as j,a as I,c as P}from"./chunk-QWBNNEV2.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as B}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";B();import tt from"node:fs/promises";import y from"node:path";import{EOL as et}from"node:os";import{spawn as X}from"node:child_process";var k=j("GREP"),M=class extends U{constructor(e,s){super(s);this.config=e;this.fileExclusions=e.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let e=this.config.getWorkspaceContext(),s=y.resolve(this.config.getTargetDir(),this.params.path);return e.isPathWithinWorkspace(s)||W(_(),s)?"allow":"ask"}async execute(e){try{let s=[],i;if(this.params.path){let t=S(this.config,this.params.path,{allowExternalPaths:!0});s.push(t),i=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();s.push(...t),i=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let l=[];for(let t of s){let o=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:e});if(s.length>1)for(let a of o)y.isAbsolute(a.filePath)||(a.filePath=y.resolve(t,a.filePath));l.push(...o)}if(s.length>1){let t=new Set;l=l.filter(o=>{let a=`${o.filePath}:${o.lineNumber}`;return t.has(a)?!1:(t.add(a),!0)})}let f=this.params.glob?` (filter: "${this.params.glob}")`:"";if(l.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${i}${f}.`,returnDisplay:"No matches found"};let h=this.config.getTruncateToolOutputThreshold(),w=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),$=!1,C=l;l.length>w&&(C=l.slice(0,w),$=!0);let E=l.length,x=E===1?"match":"matches",G=`Found ${E} ${x} for pattern "${this.params.pattern}" ${i}${f}:
|
|
4
4
|
---
|
|
5
5
|
`,v=C.reduce((t,o)=>{let a=o.filePath;return t[a]||(t[a]=[]),t[a].push(o),t[a].sort((L,D)=>L.lineNumber-D.lineNumber),t},{}),n="",g=[],m=!1,c=(t,o)=>Number.isFinite(h)&&n.length+t.length>h?(n+=t.slice(0,Math.max(h-n.length,0)),n+="...",o&&g.push(o),m=!0,!1):(n+=t,o&&g.push(o),!0);for(let t in v){if(!c(`File: ${t}
|
|
6
6
|
`))break;let o=!1;for(let a of v[t]){let L=a.line.trim();if(!c(`L${a.lineNumber}: ${L}
|
package/chunks/{matildaAgentContentGenerator-Y5CHD2WJ.js → matildaAgentContentGenerator-HG4ABAJG.js}
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as I,b as F,c as U}from"./chunk-ISW2QC5B.js";import{b as x,x as $}from"./chunk-
|
|
3
|
+
import{a as I,b as F,c as U}from"./chunk-ISW2QC5B.js";import{b as x,x as $}from"./chunk-DORRYU7L.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import{b as M,e as w}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as E,n as O}from"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import"./chunk-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}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";b();b();var L="2026-06-23",W="auto",H="instant",J=12e4,g=18e4,V=5e4,v=16e3,X=["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(" "),B=["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 K(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 A(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}function d(n,e){let o=A(n)?.[e];return typeof o=="string"?o:void 0}function j(n){return G(n)}function G(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 u(n,e){if(n.length<=e)return n;let t=`
|
|
5
5
|
[...omitted to fit Matilda native agent context...]
|
|
6
6
|
`,o=e-t.length,s=Math.floor(o*.6),i=o-s;return`${n.slice(0,s)}${t}${n.slice(-i)}`}function z(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 Q(n){let e=A(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t}}function p(n){return JSON.stringify(n).length}function Y(n){if(p(n)<=g)return n;let e=`
|
|
@@ -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-QJO23A2D.js";import"./chunk-QCIDUZV6.js";import"./chunk-ISW2QC5B.js";import"./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{d as s}from"./chunk-DC7LAFZZ.js";import"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as o}from"./chunk-XJDC3ZQZ.js";import"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import{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||s,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 o("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{Gh as P,Ih as lt,Rd as rt,Yb as tt,ae as st,fe as L,ge as at,hc as et,kc as ot,lc as A,qc as C,rc as nt,vc as it}from"./chunk-
|
|
3
|
+
import{Gh as P,Ih as lt,Rd as rt,Yb as tt,ae as st,fe as L,ge as at,hc as et,kc as ot,lc as A,qc as C,rc as nt,vc as it}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"./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}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as Z}from"./chunk-I55PXD4N.js";import{Kd as D,Ld as Y,Ob as Q,de as y,ja as R,oe as X}from"./chunk-
|
|
3
|
+
import{a as Z}from"./chunk-I55PXD4N.js";import{Kd as D,Ld as Y,Ob as Q,de as y,ja as R,oe as X}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{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-CFBZKYFB.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
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
5
|
|
|
6
6
|
Updated source:
|
|
@@ -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-QJO23A2D.js";import"./chunk-QCIDUZV6.js";import"./chunk-ISW2QC5B.js";import"./chunk-S4K76QPI.js";import{b as a}from"./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"./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{bj as a,cj as b}from"./chunk-
|
|
3
|
+
import{bj as a,cj as b}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"./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-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"./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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as Ru}from"./chunk-PA6532AY.js";import{a as wv}from"./chunk-XMZIY7XX.js";import{$a as Zi,Aa as or,B as ns,Ba as an,Ca as ar,D as Iu,Da as Mr,Ea as mt,Fa as cr,Ga as Or,Ha as Dr,Ia as cn,Ja as dn,Ka as un,La as ot,Ma as bv,Na as Ki,Oa as ss,Pa as Mu,Qa as ke,Ra as fe,Sa as Sv,Ta as ln,U as xu,Ua as pn,Va as Ou,W as Tt,Wa as Ji,Xa as Xi,Ya as Yi,Za as Qi,_a as Ev,ab as Mt,bb as Du,cb as Fu,fa as _u,ga as Cu,gb as Lu,ha as Pt,hb as Nu,ia as Tu,ja as zi,ka as Ye,la as wt,na as Pu,oa as ie,pa as nn,qa as sn,ra as sr,sa as Cr,ta as on,ua as Tr,va as bt,wa as St,x as Ui,xa as ir,ya as Pr,za as Gi}from"./chunk-
|
|
3
|
+
import{a as Ru}from"./chunk-PA6532AY.js";import{a as wv}from"./chunk-XMZIY7XX.js";import{$a as Zi,Aa as or,B as ns,Ba as an,Ca as ar,D as Iu,Da as Mr,Ea as mt,Fa as cr,Ga as Or,Ha as Dr,Ia as cn,Ja as dn,Ka as un,La as ot,Ma as bv,Na as Ki,Oa as ss,Pa as Mu,Qa as ke,Ra as fe,Sa as Sv,Ta as ln,U as xu,Ua as pn,Va as Ou,W as Tt,Wa as Ji,Xa as Xi,Ya as Yi,Za as Qi,_a as Ev,ab as Mt,bb as Du,cb as Fu,fa as _u,ga as Cu,gb as Lu,ha as Pt,hb as Nu,ia as Tu,ja as zi,ka as Ye,la as wt,na as Pu,oa as ie,pa as nn,qa as sn,ra as sr,sa as Cr,ta as on,ua as Tr,va as bt,wa as St,x as Ui,xa as ir,ya as Pr,za as Gi}from"./chunk-RGBIKCMN.js";import{a as Su,b as D,d as Eu}from"./chunk-YZVC65QR.js";import{a as ku,b as rn,d as Au,e as Vi}from"./chunk-JSFA3NEP.js";import{Ak as ts,Bk as rs,Fh as fu,Ma as kr,Oe as du,Pe as uu,Pj as mu,Qe as lu,Sj as gu,Tj as vu,Uj as yu,_h as yv,ce as iu,ef as Ar,ff as Ve,fk as Hi,hh as pu,hk as wu,ij as tt,je as ou,jj as Zn,lk as bu,oe as Wi,pe as au,qe as cu,wl as Rr,yf as Qn,zk as es}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{e as hu}from"./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{b as Yd,e as Qd}from"./chunk-S4K76QPI.js";import"./chunk-DORRYU7L.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import{A as Kd,D as Jd,E as Xd,c as Fd,d as $i,e as Bi,f as Yn,h as Ld,j as Nd,k as $d,l as qi,m as _r,r as Bd,s as qd,t as jd,u as Wd,v as Hd,w as Ud,x as Vd,y as zd,z as Gd}from"./chunk-2XZIKUB6.js";import"./chunk-XYA3SFGC.js";import"./chunk-4J6DC24J.js";import{b as Rd}from"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-XJDC3ZQZ.js";import{Cb as Md,Eb as Od,Fb as Dd,Y as Td,da as xr,ea as Pd,j as He,t as Cd}from"./chunk-CFBZKYFB.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-UY2R3ZQ4.js";import"./chunk-NDR7ZFUA.js";import"./chunk-5U3A6KMU.js";import{f as Zd,h as ji,i as eu,j as tu,k as ru,m as nu,r as su}from"./chunk-IMYUVCF7.js";import"./chunk-XKDGRW3K.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-IOCF4XSR.js";import{L as Xn,M as Ad}from"./chunk-QWBNNEV2.js";import{a as ht}from"./chunk-G7R2XEEF.js";import{a as vv}from"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as w}from"./chunk-GZPNIYVZ.js";import{a as se,d as L,f as gv}from"./chunk-OWGSC52X.js";var fn=L((k_,ju)=>{w();var Iv=se("path").relative;ju.exports=Rv;var xv=process.cwd();function Bu(t,e){for(var r=t.split(/[ ,]+/),n=String(e).toLowerCase(),s=0;s<r.length;s++){var i=r[s];if(i&&(i==="*"||i.toLowerCase()===n))return!0}return!1}function _v(t,e,r){var n=Object.getOwnPropertyDescriptor(t,e),s=n.value;return n.get=function(){return s},n.writable&&(n.set=function(o){return s=o}),delete n.value,delete n.writable,Object.defineProperty(t,e,n),n}function kv(t){for(var e="",r=0;r<t;r++)e+=", arg"+r;return e.substr(2)}function Av(t){var e=this.name+": "+this.namespace;this.message&&(e+=" deprecated "+this.message);for(var r=0;r<t.length;r++)e+=`
|
|
4
4
|
at `+t[r].toString();return e}function Rv(t){if(!t)throw new TypeError("argument namespace is required");var e=os(),r=Fr(e[1]),n=r[0];function s(i){is.call(s,i)}return s._file=n,s._ignored=Tv(t),s._namespace=t,s._traced=Pv(t),s._warned=Object.create(null),s.function=Fv,s.property=Lv,s}function Cv(t,e){var r=typeof t.listenerCount!="function"?t.listeners(e).length:t.listenerCount(e);return r>0}function Tv(t){if(process.noDeprecation)return!0;var e=process.env.NO_DEPRECATION||"";return Bu(e,t)}function Pv(t){if(process.traceDeprecation)return!0;var e=process.env.TRACE_DEPRECATION||"";return Bu(e,t)}function is(t,e){var r=Cv(process,"deprecation");if(!(!r&&this._ignored)){var n,s,i,o,a=0,c=!1,d=os(),u=this._file;for(e?(o=e,i=Fr(d[1]),i.name=o.name,u=i[0]):(a=2,o=Fr(d[a]),i=o);a<d.length;a++)if(n=Fr(d[a]),s=n[0],s===u)c=!0;else if(s===this._file)u=this._file;else if(c)break;var l=n?o.join(":")+"__"+n.join(":"):void 0;if(!(l!==void 0&&l in this._warned)){this._warned[l]=!0;var p=t;if(p||(p=i===o||!i.name?$u(o):$u(i)),r){var f=qu(this._namespace,p,d.slice(a));process.emit("deprecation",f);return}var g=process.stderr.isTTY?Ov:Mv,v=g.call(this,p,n,d.slice(a));process.stderr.write(v+`
|
|
5
5
|
`,"utf8")}}}function Fr(t){var e=t.getFileName()||"<anonymous>",r=t.getLineNumber(),n=t.getColumnNumber();t.isEval()&&(e=t.getEvalOrigin()+", "+e);var s=[e,r,n];return s.callSite=t,s.name=t.getFunctionName(),s}function $u(t){var e=t.callSite,r=t.name;r||(r="<anonymous@"+eo(t)+">");var n=e.getThis(),s=n&&e.getTypeName();return s==="Object"&&(s=void 0),s==="Function"&&(s=n.name||s),s&&e.getMethodName()?s+"."+r:r}function Mv(t,e,r){var n=new Date().toUTCString(),s=n+" "+this._namespace+" deprecated "+t;if(this._traced){for(var i=0;i<r.length;i++)s+=`
|
|
6
6
|
at `+r[i].toString();return s}return e&&(s+=" at "+eo(e)),s}function Ov(t,e,r){var n="\x1B[36;1m"+this._namespace+"\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m"+t+"\x1B[39m";if(this._traced){for(var s=0;s<r.length;s++)n+=`
|
|
@@ -726,7 +726,7 @@ data: ${i}
|
|
|
726
726
|
`)+`
|
|
727
727
|
`:""}function rv(t){let e=t.now.toISOString(),r=p_(t.ctx);return`${e} [${t.level}] [DAEMON] ${r}${t.message}
|
|
728
728
|
${f_(t.err)}`}var nv={info:()=>{},warn:()=>{},error:()=>{},raw:()=>{},getLogPath:()=>"",getDaemonId:()=>"",flush:()=>Promise.resolve()};function h_(){let t=process.env.MATILDA_DAEMON_LOG_FILE;return t?["0","false","off","no"].includes(t.trim().toLowerCase()):!1}function m_(t,e){let r=sv.createHash("sha256").update(e).digest("hex").slice(0,8);return`serve-${t}-${r}`}function ov(t){if(h_())return nv;let e=t.pid??process.pid,r=t.now??(()=>new Date),n=t.stderr??D,s=t.baseDir??Xn.getGlobalDebugDir(),i=m_(e,t.boundWorkspace),o=Di.join(s,"daemon"),a=Di.join(o,`${i}.log`);try{Zr.mkdirSync(o,{recursive:!0});let p=rv({level:"INFO",message:`daemon started pid=${e} workspace=${t.boundWorkspace}`,now:r()});Zr.appendFileSync(a,p)}catch(p){return n(`matilda serve: daemon log disabled \u2014 init failed: ${p instanceof Error?p.message:String(p)}`),nv}try{let p=Di.join(o,"latest");Ad(p,a,{fallbackCopy:!1}).catch(()=>{})}catch{}let c=Promise.resolve(),d=!1,u=p=>{c=c.then(()=>Zr.promises.appendFile(a,p).catch(f=>{d||(d=!0,n(`matilda serve: daemon log write failed \u2014 entering degraded mode: ${f instanceof Error?f.message:String(f)}`))}))},l=(p,f,g,v)=>{let x=rv({level:p,message:f,now:r(),ctx:g,err:v});n(x.trimEnd()),u(x)};return{info:(p,f)=>l("INFO",p,f),warn:(p,f)=>l("WARN",p,f),error:(p,f,g)=>l("ERROR",p,g,f??void 0),raw:(p,f="info")=>{let g=f.toUpperCase(),v=`${r().toISOString()} [${g}] [DAEMON] ${p}
|
|
729
|
-
`;u(v)},getLogPath:()=>a,getDaemonId:()=>i,flush:()=>c}}var en="MATILDA_SERVER_TOKEN",av="MATILDA_SERVE_PROMPT_DEADLINE_MS",cv="MATILDA_SERVE_WRITER_IDLE_TIMEOUT_MS",dv=5e3;function Id(t){return Number.isFinite(t)&&Number.isInteger(t)&&t>0}function g_(t){return t===Number.POSITIVE_INFINITY||Number.isFinite(t)&&Number.isInteger(t)&&t>=0}var uv=2147483647;function v_(t,e){if(e>uv)throw new TypeError(`Invalid ${t}: ${e}. Exceeds maximum JS timer delay of ${uv} ms (~24.8 days); Node would silently compress longer delays to 1ms.`)}function lv(t,e){if(e===void 0)return;let r=e.trim(),n=Number(r);if(!Id(n))throw new Error(`Invalid ${t}="${e}": must be a positive integer (milliseconds).`);return n}function y_(t,e,r){return{getTelemetryEnabled:()=>t.enabled??!1,getTelemetryOtlpEndpoint:()=>t.otlpEndpoint??Xd,getTelemetryOtlpProtocol:()=>t.otlpProtocol??"grpc",getTelemetryOtlpTracesEndpoint:()=>t.otlpTracesEndpoint,getTelemetryOtlpLogsEndpoint:()=>t.otlpLogsEndpoint,getTelemetryOtlpMetricsEndpoint:()=>t.otlpMetricsEndpoint,getTelemetryTarget:()=>t.target??Jd,getTelemetryOutfile:()=>t.outfile,getTelemetryIncludeSensitiveSpanAttributes:()=>t.includeSensitiveSpanAttributes??!1,getTelemetryResourceAttributes:()=>({"service.instance.id":r,...t.resourceAttributes??{}}),getTelemetryMetricsIncludeSessionId:()=>t.metrics?.includeSessionId??!1,getTelemetryResourceAttributeWarnings:()=>t.resourceAttributeWarnings??[],getCliVersion:()=>e,getSessionId:()=>r,isInteractive:()=>!1,getOutboundCorrelationPropagateTraceContext:()=>!1}}var Hn=class extends Error{name="InvalidPolicyConfigError";constructor(e){super(e)}};function w_(t={},e=D){let r=new Set(Ln.permission_mediation.modes);if(t.permissionStrategy!==void 0&&!r.has(t.permissionStrategy))throw new Hn(`matilda serve: invalid policy.permissionStrategy "${String(t.permissionStrategy)}"; must be one of ${Array.from(r).join(", ")}`);if(t.consensusQuorum!==void 0&&(!Number.isInteger(t.consensusQuorum)||t.consensusQuorum<1))throw new Hn(`matilda serve: invalid policy.consensusQuorum ${String(t.consensusQuorum)}; must be a positive integer`);let n=t.consensusQuorum!==void 0&&t.permissionStrategy==="consensus";return t.consensusQuorum!==void 0&&t.permissionStrategy!=="consensus"&&e('matilda serve: policy.consensusQuorum is set but policy.permissionStrategy is not "consensus"; the override will be ignored.'),{permissionPolicy:t.permissionStrategy,permissionConsensusQuorum:n?t.consensusQuorum:void 0}}function b_(t){return t.startsWith("[")?t:t.includes(":")?`[${t.includes("%")?t.replace(/%/g,"%25"):t}]`:t}function S_(t){if(typeof t=="string"){let e=t.trim();return e===""?void 0:e}if(Array.isArray(t)){for(let e of t)if(typeof e=="string"){let r=e.trim();if(r!=="")return r}return}}var pv=new Map;function Wn(t,e){let n=(pv.get(t)??Promise.resolve()).then(e,e);return pv.set(t,n),n}function E_(t,e){let r=t.modelIds?.map(s=>s.trim()).filter(s=>s.length>0),n=r&&r.length>0?r:vu(e);return[...new Set(n)]}function I_(t,e){let r=t.protocol??e.protocol,n=gu(e,t.baseUrl);return{...e.protocolOptions?{protocol:r}:{},baseUrl:n,apiKey:t.apiKey.trim(),modelIds:E_(t,e),...t.advancedConfig?{advancedConfig:t.advancedConfig}:{}}}function x_(t){return t.preheatBridge!==void 0?t.preheatBridge:process.env.VITEST_WORKER_ID===void 0}async function __(t,e={}){let r=t.token??process.env[en],n=typeof r=="string"&&r.trim().length>0?r.trim():void 0,s=t.enableSessionShell===!0&&n!==void 0;t.enableSessionShell===!0&&n===void 0&&D(`matilda serve: --enable-session-shell ignored because no bearer token is configured. Set ${en} or pass --token to enable direct session shell.`);let i=t.promptDeadlineMs??lv(av,process.env[av]),o=t.writerIdleTimeoutMs??lv(cv,process.env[cv]),a={...t,token:n,promptDeadlineMs:i,writerIdleTimeoutMs:o};if(!a.hostname.startsWith("[")&&a.hostname.split(":").length===2){let[S,R]=a.hostname.split(":");throw new Error(`Invalid --hostname "${a.hostname}": looks like a "host:port" combination. Use --port for the port, e.g. "--hostname ${S} --port ${R}".`)}if(!_t(a.hostname)&&!n)throw new Error(`Refusing to bind ${a.hostname}:${a.port} without a bearer token. Set ${en} or pass --token, or rebind to loopback (127.0.0.1, localhost, ::1, or [::1]).`);if(a.requireAuth&&!n)throw new Error(`Refusing to start with --require-auth set but no bearer token configured. Set ${en} or pass --token, or omit --require-auth to keep the loopback developer default.`);if(a.allowOrigins&&a.allowOrigins.length>0){let S=ti(a.allowOrigins);if(S.allowAny&&!n)throw new Error(`Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set ${en} or pass --token, or list specific origins instead of '*'.`);D(`matilda serve: --allow-origin: ${a.allowOrigins.join(", ")}`+(S.allowAny?" (WARNING: `*` admits any cross-origin browser \u2014 bearer token gates API routes; /health and /demo remain pre-auth on loopback unless --require-auth is set)":""))}a.allowPrivateAuthBaseUrl&&D("matilda serve: --allow-private-auth-base-url enabled; /workspace/auth/provider may install localhost/private-network model endpoints. Use only for local development with trusted clients.");let c=a.workspace??process.cwd();if(!hv.isAbsolute(c))throw new Error(`Invalid --workspace "${c}": must be an absolute path.`);try{if(!fv.statSync(c).isDirectory())throw new Error(`Invalid --workspace "${c}": exists but is not a directory.`)}catch(S){if(S&&typeof S=="object"&&"code"in S){let R=S.code;if(R==="ENOENT")throw new Error(`Invalid --workspace "${c}": directory does not exist.`);if(R==="EACCES"||R==="EPERM")throw new Error(`Invalid --workspace "${c}": permission denied (${String(R)}). The path exists but cannot be stat'd by the current user.`)}throw S}let d=Ye(c),u=ov({boundWorkspace:d});if(D(`matilda serve: daemon log \u2192 ${u.getLogPath()||"(disabled)"}`),a.mcpClientBudget!==void 0&&(!Number.isFinite(a.mcpClientBudget)||!Number.isInteger(a.mcpClientBudget)||a.mcpClientBudget<=0))throw new TypeError(`Invalid mcpClientBudget: ${a.mcpClientBudget}. Must be a positive integer.`);if(a.mcpBudgetMode==="enforce"&&a.mcpClientBudget===void 0)throw new Error('mcpBudgetMode="enforce" requires a positive mcpClientBudget. Pass mcpClientBudget=N, or set mcpBudgetMode to "warn" or "off".');if(a.promptDeadlineMs!==void 0){if(!Id(a.promptDeadlineMs))throw new TypeError(`Invalid promptDeadlineMs: ${a.promptDeadlineMs}. Must be a positive integer (milliseconds).`);v_("promptDeadlineMs",a.promptDeadlineMs)}if(a.maxPendingPromptsPerSession!==void 0&&!g_(a.maxPendingPromptsPerSession))throw new TypeError(`Invalid maxPendingPromptsPerSession: ${a.maxPendingPromptsPerSession}. Must be a non-negative integer (0 / Infinity = unlimited).`);if(a.writerIdleTimeoutMs!==void 0&&!Id(a.writerIdleTimeoutMs))throw new TypeError(`Invalid writerIdleTimeoutMs: ${a.writerIdleTimeoutMs}. Must be a positive integer (milliseconds).`);if(a.channelIdleTimeoutMs!==void 0&&(!Number.isFinite(a.channelIdleTimeoutMs)||!Number.isInteger(a.channelIdleTimeoutMs)||a.channelIdleTimeoutMs<0))throw new TypeError(`Invalid channelIdleTimeoutMs: ${a.channelIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = immediate kill).`);let l=process.env.MATILDA_SERVE_NO_MCP_POOL==="1";a.mcpPoolActive===void 0&&l&&(a.mcpPoolActive=!1);let p={MATILDA_SERVE_MCP_CLIENT_BUDGET:a.mcpClientBudget!==void 0?String(a.mcpClientBudget):void 0,MATILDA_SERVE_MCP_BUDGET_MODE:a.mcpBudgetMode},f,g,v,x;try{x=Tt(d),f=S_(x.merged.context?.fileName);let S=x.merged.policy??{},R=w_(S);g=R.permissionPolicy,v=R.permissionConsensusQuorum}catch(S){if(S instanceof Hn)throw S;D(`matilda serve: could not read settings for context.fileName / policy.* (${S instanceof Error?S.message:String(S)}); falling back to defaults. Restart with a valid settings.json to apply context.fileName / policy.* overrides.`)}let O=Yn(d),P=await Fd({env:process.env,settings:x?.merged.telemetry}),q=await _u();Md(y_(P,q,`daemon:${O}:${process.pid}`)),qd();let U=Bd();U.metrics={sessionLifecycle(S){Hd(S),_r(`Session ${S}.`,{"matilda-code.workspace.hash":O},{eventName:`matilda-code.daemon.session.${S}`})},channelLifecycle(S,R){Ud(S,R),_r(S==="spawn"?"ACP channel spawned.":`ACP channel exited (expected=${R??!0}).`,{...S==="exit"?{"matilda-code.daemon.channel.expected":R??!0}:{}},{eventName:`matilda-code.daemon.channel.${S}`,...R===!1&&S==="exit"?{severityNumber:13}:{}})},promptQueueWait:Vd,promptDuration:zd,cancelled:Kd};let ae=new Oi,le=tv({ring:ae}),V=e.trustedWorkspace??!0,Se=bd({boundWorkspace:d,injected:e.fsFactory,trusted:V,emit:e.fsAuditEmit}),Te=(S,R)=>u.raw(S,R),Ze=xc({onDiagnosticLine:Te}),Me=(S,R,F)=>Wn(S,async()=>{let H=Tt(S),X=H.forScope("Workspace").settings.tools?.disabled,pe=Array.isArray(X)?X.filter(re=>typeof re=="string"):[],de=new Set(pe);F?de.delete(R):de.add(R),H.setValue("Workspace","tools.disabled",[...de].sort())}),Ue=Mn(),be=e.bridge??gr({maxSessions:a.maxSessions,...a.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:a.maxPendingPromptsPerSession}:{},...a.eventRingSize!==void 0?{eventRingSize:a.eventRingSize}:{},...a.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:a.channelIdleTimeoutMs}:{},...a.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:a.sessionReapIntervalMs}:{},...a.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:a.sessionIdleTimeoutMs}:{},boundWorkspace:d,sessionShellCommandEnabled:s,childEnvOverrides:p,channelFactory:Ze,onDiagnosticLine:Te,telemetry:U,...g!==void 0?{permissionPolicy:g}:{},...v!==void 0?{permissionConsensusQuorum:v}:{},permissionAudit:le,statusProvider:Ue,fileSystem:pi(Se),persistApprovalMode:(S,R)=>Wn(S,async()=>{Tt(S).setValue("Workspace","tools.approvalMode",R)})}),b=Ri({boundWorkspace:d,contextFilename:f??"MATILDA.md",statusProvider:Ue,isChannelLive:()=>be.isChannelLive(),persistDisabledTools:Me,reloadDaemonEnv:S=>Wn(S,async()=>{let R=Tt(S,{skipLoadEnvironment:!0});return xu(R.merged,S)}),queryWorkspaceStatus:(S,R)=>be.queryWorkspaceStatus(S,R),invokeWorkspaceCommand:(S,R,F)=>be.invokeWorkspaceCommand(S,R,F),publishWorkspaceEvent:S=>be.publishWorkspaceEvent(S)});jd({sessionCount:()=>be.sessionCount,sseCount:()=>wd(),heapUsed:()=>process.memoryUsage().heapUsed});let h=a.port,y=Sd(a,()=>h,{bridge:be,boundWorkspace:d,matildaCodeVersion:q,fsFactory:Se,daemonLog:u,workspace:b,persistDisabledTools:Me,persistSetting:(S,R,F,H)=>Wn(S,async()=>{Tt(S).setValue(R,F,H)}),installAuthProvider:S=>Wn(d,async()=>{let R=wu(S.providerId);if(!R)throw new Error(`Unsupported auth provider: ${S.providerId}`);let F=I_(S,R),H=mu(R,F),Z=Tt(d);return await bu(H,{settings:Cu(Z),doRefreshAuth:!1}),_r("Auth provider installed.",{"matilda-code.daemon.auth.provider_id":R.id,"matilda-code.daemon.auth.auth_type":H.authType}),{v:1,providerId:R.id,providerLabel:R.label,authType:H.authType,...H.modelSelection?.modelId?{modelId:H.modelSelection.modelId}:{},...F.baseUrl?{baseUrl:F.baseUrl}:{},message:`Successfully configured ${R.label}. Use /model to switch models.`}})}),A=Gm(y),k=a.hostname;if(a.hostname.startsWith("[")){let S=a.hostname.slice(1,-1);if(!a.hostname.endsWith("]")||S.length===0||S.includes("]"))throw new Error(`Invalid --hostname "${a.hostname}": brackets indicate an IPv6 literal but the value isn't a clean [addr] form. Pass the address without a trailing :port (use --port for that), e.g. "--hostname [::1] --port 4170".`);k=S}if(a.maxConnections!==void 0&&(Number.isNaN(a.maxConnections)||a.maxConnections<0))throw new TypeError(`Invalid maxConnections: ${a.maxConnections}. Must be >= 0 (0 / Infinity = unlimited).`);return await new Promise((S,R)=>{let F=y.listen(a.port,k,()=>{let H=a.maxConnections??256;H>0&&Number.isFinite(H)&&(F.maxConnections=H);let Z=F.address();h=typeof Z=="object"&&Z?Z.port:a.port;let X=`http://${b_(a.hostname)}:${h}`;Su(`matilda serve listening on ${X} (mode=${a.mode}, workspace=${d})`),D(`matilda serve: bound to workspace ${JSON.stringify(d)}`),n?a.requireAuth&&D("matilda serve: --require-auth enabled (bearer token mandatory on every route, including loopback /health)."):D(`matilda serve: bearer auth disabled (loopback default). Set ${en} to enable.`);let pe=!1,de,re=async K=>{if(pe){u.warn(`received ${K} during drain \u2014 forcing exit`);try{be.killAllSync()}catch(Y){u.error("force-kill error",Y instanceof Error?Y:null)}await u.flush().catch(()=>{}),process.exit(1);return}u.warn(`received ${K}, draining`);try{await xe.close(),await u.flush(),process.exit(0)}catch(Y){u.error("shutdown error",Y instanceof Error?Y:null),await u.flush().catch(()=>{}),process.exit(1)}},xe={server:F,url:X,bridge:be,close:()=>de||(de=new Promise((K,Y)=>{pe=!0;let Ee=!1,et,Oe=ne=>{Ee||(Ee=!0,process.removeListener("SIGINT",re),process.removeListener("SIGTERM",re),Od().catch(ye=>{D(`matilda serve: telemetry shutdown error: ${ye instanceof Error?ye.message:String(ye)}`)}).finally(()=>{let ye=ne??et;ye?Y(ye):K()}))};if(A)try{A.dispose()}catch(ne){u.warn(`device-flow registry dispose error: ${ne instanceof Error?ne.message:String(ne)}`)}let Fe=y.locals?.acpHandle;if(Fe?.dispose)try{Fe.dispose()}catch(ne){u.warn(`ACP handle dispose error: ${ne instanceof Error?ne.message:String(ne)}`)}let Le=W0(y);Le&&(Le.setDraining(!0),Le.dispose()),Dd().catch(ne=>{u.warn(`pre-shutdown metrics flush failed: ${ne instanceof Error?ne.message:String(ne)}`)}).then(()=>{be.shutdown().catch(ne=>{u.error("bridge shutdown error",ne instanceof Error?ne:null),et=ne instanceof Error?ne:new Error(String(ne))}).finally(()=>{let ye,tn=setTimeout(()=>{u.warn(`${dv}ms listener-drain timeout reached; force-closing remaining connections`),F.closeAllConnections(),ye=setTimeout(()=>{u.warn("server.close did not fire 2000ms after force-close; resolving anyway"),Oe()},2e3),ye.unref()},dv);tn.unref(),F.close(nr=>{clearTimeout(tn),ye&&clearTimeout(ye),Oe(nr)})})})}),de)};process.on("SIGINT",re),process.on("SIGTERM",re),F.removeAllListeners("error"),F.on("error",K=>{u.error("server error",K instanceof Error?K:null)}),!e.bridge&&x_(e)&&be.preheat().catch(K=>{D(`matilda serve: ACP preheat failed, will retry on first session: ${K instanceof Error?K.message:String(K)}`)}),y.locals?.acpHandle?.attachServer?.(F),S(xe)});F.once("error",R)})}w();export{Ev as ACP_PREFLIGHT_KINDS,Ki as BridgeTimeoutError,Xc as CAPABILITIES_SCHEMA_VERSION,o0 as CONDITIONAL_SERVE_FEATURES,jE as ENV_NONSECRET_VARS,WE as ENV_PROXY_VARS,qE as ENV_SECRET_VARS,Pt as EVENT_SCHEMA_VERSION,zi as EventBus,Sv as IDLE_HOOK_EVENTS,Or as McpServerNotFoundError,Dr as McpServerRestartFailedError,Ln as SERVE_CAPABILITY_REGISTRY,fe as SERVE_CONTROL_EXT_METHODS,bv as SERVE_ERROR_KINDS,Nn as SERVE_FEATURES,_i as SERVE_PROTOCOL_VERSION,ke as SERVE_STATUS_EXT_METHODS,AI as STAGE1_FEATURES,ot as STATUS_SCHEMA_VERSION,Jc as SUPPORTED_SERVE_PROTOCOL_VERSIONS,ie as SessionNotFoundError,St as SessionShellClientRequiredError,bt as SessionShellDisabledError,ar as WorkspaceInitConflictError,Mr as WorkspaceInitPathEscapeError,cr as WorkspaceInitRaceError,mt as WorkspaceInitSymlinkError,bc as bearerAuth,Cc as buildEnvStatusFromProcess,gr as createAcpSessionBridge,hg as createHttpAcpBridge,Zi as createIdleAcpPreflightCells,ln as createIdleWorkspaceExtensionsStatus,pn as createIdleWorkspaceHooksStatus,Ji as createIdleWorkspaceMcpStatus,Yi as createIdleWorkspaceProvidersStatus,Xi as createIdleWorkspaceSkillsStatus,N4 as createInMemoryChannel,Sc as createMutationGate,Sd as createServeApp,oi as defaultSpawnChannelFactory,yc as denyBrowserOriginCors,ki as getAdvertisedServeFeatures,_I as getRegisteredServeFeatures,kI as getServeFeatures,Ai as getServeProtocolVersions,wc as hostAllowlist,Mt as mapDomainErrorToErrorKind,__ as runMatildaServe};
|
|
729
|
+
`;u(v)},getLogPath:()=>a,getDaemonId:()=>i,flush:()=>c}}var en="MATILDA_SERVER_TOKEN",av="MATILDA_SERVE_PROMPT_DEADLINE_MS",cv="MATILDA_SERVE_WRITER_IDLE_TIMEOUT_MS",dv=5e3;function Id(t){return Number.isFinite(t)&&Number.isInteger(t)&&t>0}function g_(t){return t===Number.POSITIVE_INFINITY||Number.isFinite(t)&&Number.isInteger(t)&&t>=0}var uv=2147483647;function v_(t,e){if(e>uv)throw new TypeError(`Invalid ${t}: ${e}. Exceeds maximum JS timer delay of ${uv} ms (~24.8 days); Node would silently compress longer delays to 1ms.`)}function lv(t,e){if(e===void 0)return;let r=e.trim(),n=Number(r);if(!Id(n))throw new Error(`Invalid ${t}="${e}": must be a positive integer (milliseconds).`);return n}function y_(t,e,r){return{getTelemetryEnabled:()=>t.enabled??!1,getTelemetryOtlpEndpoint:()=>t.otlpEndpoint??Xd,getTelemetryOtlpProtocol:()=>t.otlpProtocol??"grpc",getTelemetryOtlpTracesEndpoint:()=>t.otlpTracesEndpoint,getTelemetryOtlpLogsEndpoint:()=>t.otlpLogsEndpoint,getTelemetryOtlpMetricsEndpoint:()=>t.otlpMetricsEndpoint,getTelemetryTarget:()=>t.target??Jd,getTelemetryOutfile:()=>t.outfile,getTelemetryIncludeSensitiveSpanAttributes:()=>t.includeSensitiveSpanAttributes??!1,getTelemetryResourceAttributes:()=>({"service.instance.id":r,...t.resourceAttributes??{}}),getTelemetryMetricsIncludeSessionId:()=>t.metrics?.includeSessionId??!1,getTelemetryResourceAttributeWarnings:()=>t.resourceAttributeWarnings??[],getCliVersion:()=>e,getSessionId:()=>r,isInteractive:()=>!1,getOutboundCorrelationPropagateTraceContext:()=>!1}}var Hn=class extends Error{name="InvalidPolicyConfigError";constructor(e){super(e)}};function w_(t={},e=D){let r=new Set(Ln.permission_mediation.modes);if(t.permissionStrategy!==void 0&&!r.has(t.permissionStrategy))throw new Hn(`matilda serve: invalid policy.permissionStrategy "${String(t.permissionStrategy)}"; must be one of ${Array.from(r).join(", ")}`);if(t.consensusQuorum!==void 0&&(!Number.isInteger(t.consensusQuorum)||t.consensusQuorum<1))throw new Hn(`matilda serve: invalid policy.consensusQuorum ${String(t.consensusQuorum)}; must be a positive integer`);let n=t.consensusQuorum!==void 0&&t.permissionStrategy==="consensus";return t.consensusQuorum!==void 0&&t.permissionStrategy!=="consensus"&&e('matilda serve: policy.consensusQuorum is set but policy.permissionStrategy is not "consensus"; the override will be ignored.'),{permissionPolicy:t.permissionStrategy,permissionConsensusQuorum:n?t.consensusQuorum:void 0}}function b_(t){return t.startsWith("[")?t:t.includes(":")?`[${t.includes("%")?t.replace(/%/g,"%25"):t}]`:t}function S_(t){if(typeof t=="string"){let e=t.trim();return e===""?void 0:e}if(Array.isArray(t)){for(let e of t)if(typeof e=="string"){let r=e.trim();if(r!=="")return r}return}}var pv=new Map;function Wn(t,e){let n=(pv.get(t)??Promise.resolve()).then(e,e);return pv.set(t,n),n}function E_(t,e){let r=t.modelIds?.map(s=>s.trim()).filter(s=>s.length>0),n=r&&r.length>0?r:vu(e);return[...new Set(n)]}function I_(t,e){let r=t.protocol??e.protocol,n=gu(e,t.baseUrl);return{...e.protocolOptions?{protocol:r}:{},baseUrl:n,apiKey:t.apiKey.trim(),modelIds:E_(t,e),...t.advancedConfig?{advancedConfig:t.advancedConfig}:{}}}function x_(t){return t.preheatBridge!==void 0?t.preheatBridge:process.env.VITEST_WORKER_ID===void 0}async function __(t,e={}){let r=t.token??process.env[en],n=typeof r=="string"&&r.trim().length>0?r.trim():void 0,s=t.enableSessionShell===!0&&n!==void 0;t.enableSessionShell===!0&&n===void 0&&D(`matilda serve: --enable-session-shell ignored because no bearer token is configured. Set ${en} or pass --token to enable direct session shell.`);let i=t.promptDeadlineMs??lv(av,process.env[av]),o=t.writerIdleTimeoutMs??lv(cv,process.env[cv]),a={...t,token:n,promptDeadlineMs:i,writerIdleTimeoutMs:o};if(!a.hostname.startsWith("[")&&a.hostname.split(":").length===2){let[S,R]=a.hostname.split(":");throw new Error(`Invalid --hostname "${a.hostname}": looks like a "host:port" combination. Use --port for the port, e.g. "--hostname ${S} --port ${R}".`)}if(!_t(a.hostname)&&!n)throw new Error(`Refusing to bind ${a.hostname}:${a.port} without a bearer token. Set ${en} or pass --token, or rebind to loopback (127.0.0.1, localhost, ::1, or [::1]).`);if(a.requireAuth&&!n)throw new Error(`Refusing to start with --require-auth set but no bearer token configured. Set ${en} or pass --token, or omit --require-auth to keep the loopback developer default.`);if(a.allowOrigins&&a.allowOrigins.length>0){let S=ti(a.allowOrigins);if(S.allowAny&&!n)throw new Error(`Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set ${en} or pass --token, or list specific origins instead of '*'.`);D(`matilda serve: --allow-origin: ${a.allowOrigins.join(", ")}`+(S.allowAny?" (WARNING: `*` admits any cross-origin browser \u2014 bearer token gates API routes; /health and /demo remain pre-auth on loopback unless --require-auth is set)":""))}a.allowPrivateAuthBaseUrl&&D("matilda serve: --allow-private-auth-base-url enabled; /workspace/auth/provider may install localhost/private-network model endpoints. Use only for local development with trusted clients.");let c=a.workspace??process.cwd();if(!hv.isAbsolute(c))throw new Error(`Invalid --workspace "${c}": must be an absolute path.`);try{if(!fv.statSync(c).isDirectory())throw new Error(`Invalid --workspace "${c}": exists but is not a directory.`)}catch(S){if(S&&typeof S=="object"&&"code"in S){let R=S.code;if(R==="ENOENT")throw new Error(`Invalid --workspace "${c}": directory does not exist.`);if(R==="EACCES"||R==="EPERM")throw new Error(`Invalid --workspace "${c}": permission denied (${String(R)}). The path exists but cannot be stat'd by the current user.`)}throw S}let d=Ye(c),u=ov({boundWorkspace:d});if(D(`matilda serve: daemon log \u2192 ${u.getLogPath()||"(disabled)"}`),a.mcpClientBudget!==void 0&&(!Number.isFinite(a.mcpClientBudget)||!Number.isInteger(a.mcpClientBudget)||a.mcpClientBudget<=0))throw new TypeError(`Invalid mcpClientBudget: ${a.mcpClientBudget}. Must be a positive integer.`);if(a.mcpBudgetMode==="enforce"&&a.mcpClientBudget===void 0)throw new Error('mcpBudgetMode="enforce" requires a positive mcpClientBudget. Pass mcpClientBudget=N, or set mcpBudgetMode to "warn" or "off".');if(a.promptDeadlineMs!==void 0){if(!Id(a.promptDeadlineMs))throw new TypeError(`Invalid promptDeadlineMs: ${a.promptDeadlineMs}. Must be a positive integer (milliseconds).`);v_("promptDeadlineMs",a.promptDeadlineMs)}if(a.maxPendingPromptsPerSession!==void 0&&!g_(a.maxPendingPromptsPerSession))throw new TypeError(`Invalid maxPendingPromptsPerSession: ${a.maxPendingPromptsPerSession}. Must be a non-negative integer (0 / Infinity = unlimited).`);if(a.writerIdleTimeoutMs!==void 0&&!Id(a.writerIdleTimeoutMs))throw new TypeError(`Invalid writerIdleTimeoutMs: ${a.writerIdleTimeoutMs}. Must be a positive integer (milliseconds).`);if(a.channelIdleTimeoutMs!==void 0&&(!Number.isFinite(a.channelIdleTimeoutMs)||!Number.isInteger(a.channelIdleTimeoutMs)||a.channelIdleTimeoutMs<0))throw new TypeError(`Invalid channelIdleTimeoutMs: ${a.channelIdleTimeoutMs}. Must be a non-negative integer (milliseconds, 0 = immediate kill).`);let l=process.env.MATILDA_SERVE_NO_MCP_POOL==="1";a.mcpPoolActive===void 0&&l&&(a.mcpPoolActive=!1);let p={MATILDA_SERVE_MCP_CLIENT_BUDGET:a.mcpClientBudget!==void 0?String(a.mcpClientBudget):void 0,MATILDA_SERVE_MCP_BUDGET_MODE:a.mcpBudgetMode},f,g,v,x;try{x=Tt(d),f=S_(x.merged.context?.fileName);let S=x.merged.policy??{},R=w_(S);g=R.permissionPolicy,v=R.permissionConsensusQuorum}catch(S){if(S instanceof Hn)throw S;D(`matilda serve: could not read settings for context.fileName / policy.* (${S instanceof Error?S.message:String(S)}); falling back to defaults. Restart with a valid settings.json to apply context.fileName / policy.* overrides.`)}let O=Yn(d),P=await Fd({env:process.env,settings:x?.merged.telemetry}),q=await _u();Md(y_(P,q,`daemon:${O}:${process.pid}`)),qd();let U=Bd();U.metrics={sessionLifecycle(S){Hd(S),_r(`Session ${S}.`,{"matilda-code.workspace.hash":O},{eventName:`matilda-code.daemon.session.${S}`})},channelLifecycle(S,R){Ud(S,R),_r(S==="spawn"?"ACP channel spawned.":`ACP channel exited (expected=${R??!0}).`,{...S==="exit"?{"matilda-code.daemon.channel.expected":R??!0}:{}},{eventName:`matilda-code.daemon.channel.${S}`,...R===!1&&S==="exit"?{severityNumber:13}:{}})},promptQueueWait:Vd,promptDuration:zd,cancelled:Kd};let ae=new Oi,le=tv({ring:ae}),V=e.trustedWorkspace??!0,Se=bd({boundWorkspace:d,injected:e.fsFactory,trusted:V,emit:e.fsAuditEmit}),Te=(S,R)=>u.raw(S,R),Ze=xc({onDiagnosticLine:Te}),Me=(S,R,F)=>Wn(S,async()=>{let H=Tt(S),X=H.forScope("Workspace").settings.tools?.disabled,pe=Array.isArray(X)?X.filter(re=>typeof re=="string"):[],de=new Set(pe);F?de.delete(R):de.add(R),H.setValue("Workspace","tools.disabled",[...de].sort())}),Ue=Mn(),be=e.bridge??gr({maxSessions:a.maxSessions,...a.maxPendingPromptsPerSession!==void 0?{maxPendingPromptsPerSession:a.maxPendingPromptsPerSession}:{},...a.eventRingSize!==void 0?{eventRingSize:a.eventRingSize}:{},...a.channelIdleTimeoutMs!==void 0?{channelIdleTimeoutMs:a.channelIdleTimeoutMs}:{},...a.sessionReapIntervalMs!==void 0?{sessionReapIntervalMs:a.sessionReapIntervalMs}:{},...a.sessionIdleTimeoutMs!==void 0?{sessionIdleTimeoutMs:a.sessionIdleTimeoutMs}:{},boundWorkspace:d,sessionShellCommandEnabled:s,childEnvOverrides:p,channelFactory:Ze,onDiagnosticLine:Te,telemetry:U,...g!==void 0?{permissionPolicy:g}:{},...v!==void 0?{permissionConsensusQuorum:v}:{},permissionAudit:le,statusProvider:Ue,fileSystem:pi(Se),persistApprovalMode:(S,R)=>Wn(S,async()=>{Tt(S).setValue("Workspace","tools.approvalMode",R)})}),b=Ri({boundWorkspace:d,contextFilename:f??"MATILDA.md",statusProvider:Ue,isChannelLive:()=>be.isChannelLive(),persistDisabledTools:Me,reloadDaemonEnv:S=>Wn(S,async()=>{let R=Tt(S,{skipLoadEnvironment:!0});return xu(R.merged,S)}),queryWorkspaceStatus:(S,R)=>be.queryWorkspaceStatus(S,R),invokeWorkspaceCommand:(S,R,F)=>be.invokeWorkspaceCommand(S,R,F),publishWorkspaceEvent:S=>be.publishWorkspaceEvent(S)});jd({sessionCount:()=>be.sessionCount,sseCount:()=>wd(),heapUsed:()=>process.memoryUsage().heapUsed});let h=a.port,y=Sd(a,()=>h,{bridge:be,boundWorkspace:d,matildaCodeVersion:q,fsFactory:Se,daemonLog:u,workspace:b,persistDisabledTools:Me,persistSetting:(S,R,F,H)=>Wn(S,async()=>{Tt(S).setValue(R,F,H)}),installAuthProvider:S=>Wn(d,async()=>{let R=wu(S.providerId);if(!R)throw new Error(`Unsupported auth provider: ${S.providerId}`);let F=I_(S,R),H=mu(R,F),Z=Tt(d);return await bu(H,{settings:Cu(Z),doRefreshAuth:!1}),_r("Auth provider installed.",{"matilda-code.daemon.auth.provider_id":R.id,"matilda-code.daemon.auth.auth_type":H.authType}),{v:1,providerId:R.id,providerLabel:R.label,authType:H.authType,...H.modelSelection?.modelId?{modelId:H.modelSelection.modelId}:{},...F.baseUrl?{baseUrl:F.baseUrl}:{},message:`Successfully configured ${R.label}.`}})}),A=Gm(y),k=a.hostname;if(a.hostname.startsWith("[")){let S=a.hostname.slice(1,-1);if(!a.hostname.endsWith("]")||S.length===0||S.includes("]"))throw new Error(`Invalid --hostname "${a.hostname}": brackets indicate an IPv6 literal but the value isn't a clean [addr] form. Pass the address without a trailing :port (use --port for that), e.g. "--hostname [::1] --port 4170".`);k=S}if(a.maxConnections!==void 0&&(Number.isNaN(a.maxConnections)||a.maxConnections<0))throw new TypeError(`Invalid maxConnections: ${a.maxConnections}. Must be >= 0 (0 / Infinity = unlimited).`);return await new Promise((S,R)=>{let F=y.listen(a.port,k,()=>{let H=a.maxConnections??256;H>0&&Number.isFinite(H)&&(F.maxConnections=H);let Z=F.address();h=typeof Z=="object"&&Z?Z.port:a.port;let X=`http://${b_(a.hostname)}:${h}`;Su(`matilda serve listening on ${X} (mode=${a.mode}, workspace=${d})`),D(`matilda serve: bound to workspace ${JSON.stringify(d)}`),n?a.requireAuth&&D("matilda serve: --require-auth enabled (bearer token mandatory on every route, including loopback /health)."):D(`matilda serve: bearer auth disabled (loopback default). Set ${en} to enable.`);let pe=!1,de,re=async K=>{if(pe){u.warn(`received ${K} during drain \u2014 forcing exit`);try{be.killAllSync()}catch(Y){u.error("force-kill error",Y instanceof Error?Y:null)}await u.flush().catch(()=>{}),process.exit(1);return}u.warn(`received ${K}, draining`);try{await xe.close(),await u.flush(),process.exit(0)}catch(Y){u.error("shutdown error",Y instanceof Error?Y:null),await u.flush().catch(()=>{}),process.exit(1)}},xe={server:F,url:X,bridge:be,close:()=>de||(de=new Promise((K,Y)=>{pe=!0;let Ee=!1,et,Oe=ne=>{Ee||(Ee=!0,process.removeListener("SIGINT",re),process.removeListener("SIGTERM",re),Od().catch(ye=>{D(`matilda serve: telemetry shutdown error: ${ye instanceof Error?ye.message:String(ye)}`)}).finally(()=>{let ye=ne??et;ye?Y(ye):K()}))};if(A)try{A.dispose()}catch(ne){u.warn(`device-flow registry dispose error: ${ne instanceof Error?ne.message:String(ne)}`)}let Fe=y.locals?.acpHandle;if(Fe?.dispose)try{Fe.dispose()}catch(ne){u.warn(`ACP handle dispose error: ${ne instanceof Error?ne.message:String(ne)}`)}let Le=W0(y);Le&&(Le.setDraining(!0),Le.dispose()),Dd().catch(ne=>{u.warn(`pre-shutdown metrics flush failed: ${ne instanceof Error?ne.message:String(ne)}`)}).then(()=>{be.shutdown().catch(ne=>{u.error("bridge shutdown error",ne instanceof Error?ne:null),et=ne instanceof Error?ne:new Error(String(ne))}).finally(()=>{let ye,tn=setTimeout(()=>{u.warn(`${dv}ms listener-drain timeout reached; force-closing remaining connections`),F.closeAllConnections(),ye=setTimeout(()=>{u.warn("server.close did not fire 2000ms after force-close; resolving anyway"),Oe()},2e3),ye.unref()},dv);tn.unref(),F.close(nr=>{clearTimeout(tn),ye&&clearTimeout(ye),Oe(nr)})})})}),de)};process.on("SIGINT",re),process.on("SIGTERM",re),F.removeAllListeners("error"),F.on("error",K=>{u.error("server error",K instanceof Error?K:null)}),!e.bridge&&x_(e)&&be.preheat().catch(K=>{D(`matilda serve: ACP preheat failed, will retry on first session: ${K instanceof Error?K.message:String(K)}`)}),y.locals?.acpHandle?.attachServer?.(F),S(xe)});F.once("error",R)})}w();export{Ev as ACP_PREFLIGHT_KINDS,Ki as BridgeTimeoutError,Xc as CAPABILITIES_SCHEMA_VERSION,o0 as CONDITIONAL_SERVE_FEATURES,jE as ENV_NONSECRET_VARS,WE as ENV_PROXY_VARS,qE as ENV_SECRET_VARS,Pt as EVENT_SCHEMA_VERSION,zi as EventBus,Sv as IDLE_HOOK_EVENTS,Or as McpServerNotFoundError,Dr as McpServerRestartFailedError,Ln as SERVE_CAPABILITY_REGISTRY,fe as SERVE_CONTROL_EXT_METHODS,bv as SERVE_ERROR_KINDS,Nn as SERVE_FEATURES,_i as SERVE_PROTOCOL_VERSION,ke as SERVE_STATUS_EXT_METHODS,AI as STAGE1_FEATURES,ot as STATUS_SCHEMA_VERSION,Jc as SUPPORTED_SERVE_PROTOCOL_VERSIONS,ie as SessionNotFoundError,St as SessionShellClientRequiredError,bt as SessionShellDisabledError,ar as WorkspaceInitConflictError,Mr as WorkspaceInitPathEscapeError,cr as WorkspaceInitRaceError,mt as WorkspaceInitSymlinkError,bc as bearerAuth,Cc as buildEnvStatusFromProcess,gr as createAcpSessionBridge,hg as createHttpAcpBridge,Zi as createIdleAcpPreflightCells,ln as createIdleWorkspaceExtensionsStatus,pn as createIdleWorkspaceHooksStatus,Ji as createIdleWorkspaceMcpStatus,Yi as createIdleWorkspaceProvidersStatus,Xi as createIdleWorkspaceSkillsStatus,N4 as createInMemoryChannel,Sc as createMutationGate,Sd as createServeApp,oi as defaultSpawnChannelFactory,yc as denyBrowserOriginCors,ki as getAdvertisedServeFeatures,_I as getRegisteredServeFeatures,kI as getServeFeatures,Ai as getServeProtocolVersions,wc as hostAllowlist,Mt as mapDomainErrorToErrorKind,__ as runMatildaServe};
|
|
730
730
|
/**
|
|
731
731
|
* @license
|
|
732
732
|
* Copyright 2025 Matilda Team
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{re as a,se as b,te as c,ue as d,ve as e,we as f,xe as g}from"./chunk-
|
|
3
|
+
import{re as a,se as b,te as c,ue as d,ve as e,we as f,xe as g}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"./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};
|