@maincode-ai/matilda-code 0.21.13-nightly.20261028.557d917f5 → 0.21.13-preview.0
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/cli.js +4 -4
- package/package.json +2 -2
package/cli.js
CHANGED
|
@@ -277,7 +277,7 @@ ${m.join(`
|
|
|
277
277
|
`,t-1);return{line:n===-1?0:e.slice(0,n+1).match(/\n/g).length,column:t-n-1}}function s5(e,t,{oneBased:n=!1}={}){if(typeof e!="string")throw new TypeError("Text parameter should be a string");if(!Number.isInteger(t))throw new TypeError("Index parameter should be an integer");if(t<0||t>e.length)throw new RangeError("Index out of bounds");let r=vXe(e,t);return n?{line:r.line+1,column:r.column+1}:r}var RXe=e=>`\\u{${e.codePointAt(0).toString(16)}}`,i5=class e extends Error{name="JSONError";fileName;#e;#t;#n;#r;#o;constructor(t){if(typeof t=="string")super(),this.#n=t;else{let{jsonParseError:n,fileName:r,input:o}=t;super(void 0,{cause:n}),this.#e=o,this.#t=n,this.fileName=r}Error.captureStackTrace?.(this,e)}get message(){this.#n??=`${kXe(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:t}=this;return`${this.#n}${this.fileName?` in ${this.fileName}`:""}${t?`
|
|
278
278
|
|
|
279
279
|
${t}
|
|
280
|
-
`:""}`}set message(t){this.#n=t}#a(t){if(!this.#t)return;let n=this.#e,r=QXe(n,this.#t.message);if(r)return(0,ope.codeFrameColumns)(n,{start:r},{highlightCode:t})}get codeFrame(){return this.#r??=this.#a(!0),this.#r}get rawCodeFrame(){return this.#o??=this.#a(!1),this.#o}},QXe=(e,t)=>{let n=t.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!n)return;let{index:r,line:o,column:s}=n.groups;return o&&s?{line:Number(o),column:Number(s)}:s5(e,Number(r),{oneBased:!0})},kXe=e=>e.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,n,r)=>`"${r}"(${RXe(r)})`);function a5(e,t,n){typeof t=="string"&&(n=t,t=void 0);try{return JSON.parse(e,t)}catch(r){throw new i5({jsonParseError:r,fileName:n,input:e})}}var gme=M(Ame(),1);h();import{fileURLToPath as net}from"node:url";function fme(e){return e instanceof URL?net(e):e}var set=e=>oet.resolve(fme(e)??".","package.json"),iet=(e,t)=>{let n=typeof e=="string"?a5(e):e;return t&&(0,gme.default)(n),n};async function pme({cwd:e,normalize:t=!0}={}){let n=await ret.readFile(set(e),"utf8");return iet(n,t)}async function mme(e){let t=await Mge("package.json",e);if(t)return{packageJson:await pme({...e,cwd:aet.dirname(t)}),path:t}}import{fileURLToPath as cet}from"node:url";import uet from"node:path";var det=cet(import.meta.url),Aet=uet.dirname(det),TO;async function Rx(){if(TO)return TO;let e=await mme({cwd:Aet});if(e)return TO=e.packageJson,TO}async function Ug(){let e=await Rx();return"0.21.13-nightly.20261028.557d917f5"}h();var pk=M(Bme(),1);import*as xme from"node:os";var bme=["docker","podman","sandbox-exec"];function Iet(e){return bme.includes(e)}function Det(e){if(process.env.SANDBOX)return"";let t=process.env.MATILDA_SANDBOX?.toLowerCase().trim()??"";if(e=t?.length>0?t:e,e==="1"||e==="true"?e=!0:(e==="0"||e==="false"||!e)&&(e=!1),e===!1)return"";if(typeof e=="string"&&e){if(!Iet(e))throw new Ba(`Invalid sandbox command '${e}'. Must be one of ${bme.join(", ")}`);if(pk.default.sync(e))return e;throw new Ba(`Missing sandbox command '${e}' (from MATILDA_SANDBOX)`)}if(xme.platform()==="darwin"&&pk.default.sync("sandbox-exec"))return"sandbox-exec";if(pk.default.sync("docker")&&e===!0)return"docker";if(pk.default.sync("podman")&&e===!0)return"podman";if(e===!0)throw new Ba("MATILDA_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in MATILDA_SANDBOX");return""}async function RO(e,t){let n=t.sandbox??e.tools?.sandbox,r=Det(n),o=await Rx(),s=t.sandboxImage??process.env.MATILDA_SANDBOX_IMAGE??e.tools?.sandboxImage??o?.config?.sandboxImageUri;return r&&s?{command:r,image:s}:void 0}h();import{EventEmitter as Bet}from"node:events";var ul=new Bet;h();h();async function xet(e,t,n,r){let{scope:o,transport:s,env:i,header:a,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauthClientId:d,oauthClientSecret:m,oauthRedirectUri:E,oauthAuthorizationUrl:y,oauthTokenUrl:x,oauthScopes:b}=r,w=br(process.cwd()),v=w.workspace.path===w.user.path;o==="project"&&v&&(it("Error: Please use --scope user to edit settings in the home directory."),process.exit(1));let R=o==="user"?"User":"Workspace",_={},G=b?.flatMap(P=>P.split(",")).map(P=>P.trim()).filter(Boolean),W=!!(d||m||E||y||x||G&&G.length>0);W&&s==="stdio"&&(it("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http."),process.exit(1));let z=W?{enabled:!0,...d&&{clientId:d},...m&&{clientSecret:m},...E&&{redirectUri:E},...y&&{authorizationUrl:y},...x&&{tokenUrl:x},...G&&G.length>0&&{scopes:G}}:void 0,O=a?.reduce((P,U)=>{let[Y,...k]=U.split(":"),j=k.join(":").trim();return Y.trim()&&j&&(P[Y.trim()]=j),P},{});switch(s){case"sse":_={url:t,headers:O,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:z};break;case"http":_={httpUrl:t,headers:O,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:z};break;case"stdio":default:_={command:t,args:n?.map(String),env:i?.reduce((P,U)=>{let[Y,k]=U.split("=");return Y&&k&&(P[Y]=k),P},{}),timeout:l,trust:c,description:u,includeTools:A,excludeTools:g};break}let N=w.forScope(R).settings.mcpServers||{},L=!!N[e];L&&Bt(`MCP server "${e}" is already configured within ${o} settings.`),N[e]=_,w.setValue(R,"mcpServers",N),L?Bt(`MCP server "${e}" updated in ${o} settings.`):Bt(`MCP server "${e}" added to ${o} settings. (${s})`)}var wme={command:"add <name> <commandOrUrl> [args...]",describe:"Add a server",builder:e=>e.usage("Usage: matilda mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({"unknown-options-as-args":!0,"populate--":!0}).positional("name",{describe:"Name of the server",type:"string",demandOption:!0}).positional("commandOrUrl",{describe:"Command (stdio) or URL (sse, http)",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}).option("transport",{alias:"t",describe:"Transport type (stdio, sse, http). Auto-detected from URL if not specified.",type:"string",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:"Set environment variables (e.g. -e KEY=value)",type:"array",string:!0,nargs:1}).option("header",{alias:"H",describe:'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',type:"array",string:!0,nargs:1}).option("timeout",{describe:"Set connection timeout in milliseconds",type:"number"}).option("trust",{describe:"Trust the server (bypass all tool call confirmation prompts)",type:"boolean"}).option("description",{describe:"Set the description for the server",type:"string"}).option("include-tools",{describe:"A comma-separated list of tools to include",type:"array",string:!0}).option("exclude-tools",{describe:"A comma-separated list of tools to exclude",type:"array",string:!0}).option("oauth-client-id",{describe:"OAuth client ID for MCP server authentication",type:"string"}).option("oauth-client-secret",{describe:"OAuth client secret for MCP server authentication",type:"string"}).option("oauth-redirect-uri",{describe:"OAuth redirect URI (e.g., https://your-server.com/oauth/callback). Defaults to localhost for local setups.",type:"string"}).option("oauth-authorization-url",{describe:"OAuth authorization URL",type:"string"}).option("oauth-token-url",{describe:"OAuth token URL",type:"string"}).option("oauth-scopes",{describe:"OAuth scopes (comma-separated)",type:"array",string:!0}).middleware(t=>{if(t["--"]){let n=t.args||[];t.args=[...n,...t["--"]]}if(!t.transport){let n=t.commandOrUrl;n&&(n.startsWith("http://")||n.startsWith("https://"))?t.transport="http":t.transport="stdio"}}),handler:async e=>{await xet(e.name,e.commandOrUrl,e.args,{scope:e.scope,transport:e.transport,env:e.env,header:e.header,timeout:e.timeout,trust:e.trust,description:e.description,includeTools:e.includeTools,excludeTools:e.excludeTools,oauthClientId:e.oauthClientId,oauthClientSecret:e.oauthClientSecret,oauthRedirectUri:e.oauthRedirectUri,oauthAuthorizationUrl:e.oauthAuthorizationUrl,oauthTokenUrl:e.oauthTokenUrl,oauthScopes:e.oauthScopes})}};h();async function bet(e,t){let{scope:n}=t,r=n==="user"?"User":"Workspace",o=br(),i=o.forScope(r).settings.mcpServers||{};if(!i[e]){Bt(`Server "${e}" not found in ${n} settings.`);return}delete i[e],o.setValue(r,"mcpServers",i);try{await new rI().deleteCredentials(e)}catch{}Bt(`Server "${e}" removed from ${n} settings.`)}var Tme={command:"remove <name>",describe:"Remove a server",builder:e=>e.usage("Usage: matilda mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),handler:async e=>{await bet(e.name,{scope:e.scope})}};h();h();h();var Qme=M(wI(),1);import*as vme from"node:fs";import*as Rme from"node:path";var wet=".mcp.json",Tet={servers:{},path:void 0,errors:[]};function kme(e){let t=Rme.join(e,wet),n;try{n=vme.readFileSync(t,"utf-8")}catch{return Tet}let r;try{r=JSON.parse((0,Qme.default)(n))}catch(a){return{servers:{},path:t,errors:[`Failed to parse ${t}: ${a.message}`]}}let o=r?.mcpServers;if(!o||typeof o!="object"||Array.isArray(o))return{servers:{},path:t,errors:[`${t} has no "mcpServers" object`]};let s=Object.create(null),i=[];for(let[a,l]of Object.entries(o)){if(!l||typeof l!="object"||Array.isArray(l)){i.push(`${t}: server "${a}" is not an object \u2014 skipped`);continue}s[a]={...l,scope:"project"}}return{servers:s,path:t,errors:i}}function OC(e,t,n){let r={},o={};for(let[i,a]of Object.entries(e??{}))a.scope==="workspace"||a.scope==="system"?o[i]=a:r[i]=a;let s=kme(t);for(let i of s.errors)it(`Warning: ${i}`);return{...r,...s.servers,...o,...n??{}}}h();import*as tD from"node:fs";import*as kx from"node:path";var Fme=M(wI(),1);var vet="mcpApprovals.json";function Ret(){return process.env.MATILDA_CODE_MCP_APPROVALS_PATH?process.env.MATILDA_CODE_MCP_APPROVALS_PATH:kx.join(Mt.getGlobalMatildaDir(),vet)}function Mme(e){return kx.resolve(e)}var k5=class{constructor(t,n){this.file=t;this.errors=n}getState(t,n,r){let o=this.file.config[Mme(t)]?.[n];return!o||o.hash!==lW(r)?"pending":o.status}async setState(t,n,r,o){let s=Mme(t),i=this.file.config[s],a=i&&typeof i=="object"&&!Array.isArray(i)?i:Object.create(null);Object.defineProperty(a,n,{value:{hash:lW(r),status:o},enumerable:!0,configurable:!0,writable:!0}),this.file.config[s]=a,await Qet(this.file)}},QO;function PC(){if(QO)return QO;let e=[],t={},n=Ret();try{if(tD.existsSync(n)){let r=tD.readFileSync(n,"utf-8"),o=JSON.parse((0,Fme.default)(r));typeof o!="object"||o===null||Array.isArray(o)?e.push({message:"MCP approvals file is not a valid JSON object.",path:n}):t=o}}catch(r){e.push({message:vr(r),path:n})}QO=new k5({path:n,config:t},e);for(let r of e)it(`Warning: MCP approvals file error: ${r.message}`);return QO}function kO(e,t){let n=PC(),r=[];for(let[o,s]of Object.entries(e))aC(s.scope)&&n.getState(t,o,s)!=="approved"&&r.push(o);return r}async function Qet(e){try{let t=kx.dirname(e.path);tD.existsSync(t)||tD.mkdirSync(t,{recursive:!0}),await Cne(e.path,JSON.stringify(e.config,null,2),{mode:384})}catch(t){it("Error saving MCP approvals file."),it(t instanceof Error?t.message:String(t))}}h();h();Toe();import{stripVTControlCharacters as Fet}from"node:util";h();var Lme=M(_me(),1),ket=new Intl.Segmenter,Met=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Dn(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=Go(e)),e.length===0)return 0;let o=0,s={ambiguousAsWide:!n};for(let{segment:i}of ket.segment(e)){let a=i.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!Met.test(i)){if((0,Lme.default)().test(i)){o+=2;continue}o+=pc(a,s)}}return o}var N5=e=>{if(!e)return 0;let t=e.split(`
|
|
280
|
+
`:""}`}set message(t){this.#n=t}#a(t){if(!this.#t)return;let n=this.#e,r=QXe(n,this.#t.message);if(r)return(0,ope.codeFrameColumns)(n,{start:r},{highlightCode:t})}get codeFrame(){return this.#r??=this.#a(!0),this.#r}get rawCodeFrame(){return this.#o??=this.#a(!1),this.#o}},QXe=(e,t)=>{let n=t.match(/in JSON at position (?<index>\d+)(?: \(line (?<line>\d+) column (?<column>\d+)\))?$/);if(!n)return;let{index:r,line:o,column:s}=n.groups;return o&&s?{line:Number(o),column:Number(s)}:s5(e,Number(r),{oneBased:!0})},kXe=e=>e.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,n,r)=>`"${r}"(${RXe(r)})`);function a5(e,t,n){typeof t=="string"&&(n=t,t=void 0);try{return JSON.parse(e,t)}catch(r){throw new i5({jsonParseError:r,fileName:n,input:e})}}var gme=M(Ame(),1);h();import{fileURLToPath as net}from"node:url";function fme(e){return e instanceof URL?net(e):e}var set=e=>oet.resolve(fme(e)??".","package.json"),iet=(e,t)=>{let n=typeof e=="string"?a5(e):e;return t&&(0,gme.default)(n),n};async function pme({cwd:e,normalize:t=!0}={}){let n=await ret.readFile(set(e),"utf8");return iet(n,t)}async function mme(e){let t=await Mge("package.json",e);if(t)return{packageJson:await pme({...e,cwd:aet.dirname(t)}),path:t}}import{fileURLToPath as cet}from"node:url";import uet from"node:path";var det=cet(import.meta.url),Aet=uet.dirname(det),TO;async function Rx(){if(TO)return TO;let e=await mme({cwd:Aet});if(e)return TO=e.packageJson,TO}async function Ug(){let e=await Rx();return"0.21.13-preview.0"}h();var pk=M(Bme(),1);import*as xme from"node:os";var bme=["docker","podman","sandbox-exec"];function Iet(e){return bme.includes(e)}function Det(e){if(process.env.SANDBOX)return"";let t=process.env.MATILDA_SANDBOX?.toLowerCase().trim()??"";if(e=t?.length>0?t:e,e==="1"||e==="true"?e=!0:(e==="0"||e==="false"||!e)&&(e=!1),e===!1)return"";if(typeof e=="string"&&e){if(!Iet(e))throw new Ba(`Invalid sandbox command '${e}'. Must be one of ${bme.join(", ")}`);if(pk.default.sync(e))return e;throw new Ba(`Missing sandbox command '${e}' (from MATILDA_SANDBOX)`)}if(xme.platform()==="darwin"&&pk.default.sync("sandbox-exec"))return"sandbox-exec";if(pk.default.sync("docker")&&e===!0)return"docker";if(pk.default.sync("podman")&&e===!0)return"podman";if(e===!0)throw new Ba("MATILDA_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in MATILDA_SANDBOX");return""}async function RO(e,t){let n=t.sandbox??e.tools?.sandbox,r=Det(n),o=await Rx(),s=t.sandboxImage??process.env.MATILDA_SANDBOX_IMAGE??e.tools?.sandboxImage??o?.config?.sandboxImageUri;return r&&s?{command:r,image:s}:void 0}h();import{EventEmitter as Bet}from"node:events";var ul=new Bet;h();h();async function xet(e,t,n,r){let{scope:o,transport:s,env:i,header:a,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauthClientId:d,oauthClientSecret:m,oauthRedirectUri:E,oauthAuthorizationUrl:y,oauthTokenUrl:x,oauthScopes:b}=r,w=br(process.cwd()),v=w.workspace.path===w.user.path;o==="project"&&v&&(it("Error: Please use --scope user to edit settings in the home directory."),process.exit(1));let R=o==="user"?"User":"Workspace",_={},G=b?.flatMap(P=>P.split(",")).map(P=>P.trim()).filter(Boolean),W=!!(d||m||E||y||x||G&&G.length>0);W&&s==="stdio"&&(it("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http."),process.exit(1));let z=W?{enabled:!0,...d&&{clientId:d},...m&&{clientSecret:m},...E&&{redirectUri:E},...y&&{authorizationUrl:y},...x&&{tokenUrl:x},...G&&G.length>0&&{scopes:G}}:void 0,O=a?.reduce((P,U)=>{let[Y,...k]=U.split(":"),j=k.join(":").trim();return Y.trim()&&j&&(P[Y.trim()]=j),P},{});switch(s){case"sse":_={url:t,headers:O,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:z};break;case"http":_={httpUrl:t,headers:O,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:z};break;case"stdio":default:_={command:t,args:n?.map(String),env:i?.reduce((P,U)=>{let[Y,k]=U.split("=");return Y&&k&&(P[Y]=k),P},{}),timeout:l,trust:c,description:u,includeTools:A,excludeTools:g};break}let N=w.forScope(R).settings.mcpServers||{},L=!!N[e];L&&Bt(`MCP server "${e}" is already configured within ${o} settings.`),N[e]=_,w.setValue(R,"mcpServers",N),L?Bt(`MCP server "${e}" updated in ${o} settings.`):Bt(`MCP server "${e}" added to ${o} settings. (${s})`)}var wme={command:"add <name> <commandOrUrl> [args...]",describe:"Add a server",builder:e=>e.usage("Usage: matilda mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({"unknown-options-as-args":!0,"populate--":!0}).positional("name",{describe:"Name of the server",type:"string",demandOption:!0}).positional("commandOrUrl",{describe:"Command (stdio) or URL (sse, http)",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}).option("transport",{alias:"t",describe:"Transport type (stdio, sse, http). Auto-detected from URL if not specified.",type:"string",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:"Set environment variables (e.g. -e KEY=value)",type:"array",string:!0,nargs:1}).option("header",{alias:"H",describe:'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',type:"array",string:!0,nargs:1}).option("timeout",{describe:"Set connection timeout in milliseconds",type:"number"}).option("trust",{describe:"Trust the server (bypass all tool call confirmation prompts)",type:"boolean"}).option("description",{describe:"Set the description for the server",type:"string"}).option("include-tools",{describe:"A comma-separated list of tools to include",type:"array",string:!0}).option("exclude-tools",{describe:"A comma-separated list of tools to exclude",type:"array",string:!0}).option("oauth-client-id",{describe:"OAuth client ID for MCP server authentication",type:"string"}).option("oauth-client-secret",{describe:"OAuth client secret for MCP server authentication",type:"string"}).option("oauth-redirect-uri",{describe:"OAuth redirect URI (e.g., https://your-server.com/oauth/callback). Defaults to localhost for local setups.",type:"string"}).option("oauth-authorization-url",{describe:"OAuth authorization URL",type:"string"}).option("oauth-token-url",{describe:"OAuth token URL",type:"string"}).option("oauth-scopes",{describe:"OAuth scopes (comma-separated)",type:"array",string:!0}).middleware(t=>{if(t["--"]){let n=t.args||[];t.args=[...n,...t["--"]]}if(!t.transport){let n=t.commandOrUrl;n&&(n.startsWith("http://")||n.startsWith("https://"))?t.transport="http":t.transport="stdio"}}),handler:async e=>{await xet(e.name,e.commandOrUrl,e.args,{scope:e.scope,transport:e.transport,env:e.env,header:e.header,timeout:e.timeout,trust:e.trust,description:e.description,includeTools:e.includeTools,excludeTools:e.excludeTools,oauthClientId:e.oauthClientId,oauthClientSecret:e.oauthClientSecret,oauthRedirectUri:e.oauthRedirectUri,oauthAuthorizationUrl:e.oauthAuthorizationUrl,oauthTokenUrl:e.oauthTokenUrl,oauthScopes:e.oauthScopes})}};h();async function bet(e,t){let{scope:n}=t,r=n==="user"?"User":"Workspace",o=br(),i=o.forScope(r).settings.mcpServers||{};if(!i[e]){Bt(`Server "${e}" not found in ${n} settings.`);return}delete i[e],o.setValue(r,"mcpServers",i);try{await new rI().deleteCredentials(e)}catch{}Bt(`Server "${e}" removed from ${n} settings.`)}var Tme={command:"remove <name>",describe:"Remove a server",builder:e=>e.usage("Usage: matilda mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),handler:async e=>{await bet(e.name,{scope:e.scope})}};h();h();h();var Qme=M(wI(),1);import*as vme from"node:fs";import*as Rme from"node:path";var wet=".mcp.json",Tet={servers:{},path:void 0,errors:[]};function kme(e){let t=Rme.join(e,wet),n;try{n=vme.readFileSync(t,"utf-8")}catch{return Tet}let r;try{r=JSON.parse((0,Qme.default)(n))}catch(a){return{servers:{},path:t,errors:[`Failed to parse ${t}: ${a.message}`]}}let o=r?.mcpServers;if(!o||typeof o!="object"||Array.isArray(o))return{servers:{},path:t,errors:[`${t} has no "mcpServers" object`]};let s=Object.create(null),i=[];for(let[a,l]of Object.entries(o)){if(!l||typeof l!="object"||Array.isArray(l)){i.push(`${t}: server "${a}" is not an object \u2014 skipped`);continue}s[a]={...l,scope:"project"}}return{servers:s,path:t,errors:i}}function OC(e,t,n){let r={},o={};for(let[i,a]of Object.entries(e??{}))a.scope==="workspace"||a.scope==="system"?o[i]=a:r[i]=a;let s=kme(t);for(let i of s.errors)it(`Warning: ${i}`);return{...r,...s.servers,...o,...n??{}}}h();import*as tD from"node:fs";import*as kx from"node:path";var Fme=M(wI(),1);var vet="mcpApprovals.json";function Ret(){return process.env.MATILDA_CODE_MCP_APPROVALS_PATH?process.env.MATILDA_CODE_MCP_APPROVALS_PATH:kx.join(Mt.getGlobalMatildaDir(),vet)}function Mme(e){return kx.resolve(e)}var k5=class{constructor(t,n){this.file=t;this.errors=n}getState(t,n,r){let o=this.file.config[Mme(t)]?.[n];return!o||o.hash!==lW(r)?"pending":o.status}async setState(t,n,r,o){let s=Mme(t),i=this.file.config[s],a=i&&typeof i=="object"&&!Array.isArray(i)?i:Object.create(null);Object.defineProperty(a,n,{value:{hash:lW(r),status:o},enumerable:!0,configurable:!0,writable:!0}),this.file.config[s]=a,await Qet(this.file)}},QO;function PC(){if(QO)return QO;let e=[],t={},n=Ret();try{if(tD.existsSync(n)){let r=tD.readFileSync(n,"utf-8"),o=JSON.parse((0,Fme.default)(r));typeof o!="object"||o===null||Array.isArray(o)?e.push({message:"MCP approvals file is not a valid JSON object.",path:n}):t=o}}catch(r){e.push({message:vr(r),path:n})}QO=new k5({path:n,config:t},e);for(let r of e)it(`Warning: MCP approvals file error: ${r.message}`);return QO}function kO(e,t){let n=PC(),r=[];for(let[o,s]of Object.entries(e))aC(s.scope)&&n.getState(t,o,s)!=="approved"&&r.push(o);return r}async function Qet(e){try{let t=kx.dirname(e.path);tD.existsSync(t)||tD.mkdirSync(t,{recursive:!0}),await Cne(e.path,JSON.stringify(e.config,null,2),{mode:384})}catch(t){it("Error saving MCP approvals file."),it(t instanceof Error?t.message:String(t))}}h();h();Toe();import{stripVTControlCharacters as Fet}from"node:util";h();var Lme=M(_me(),1),ket=new Intl.Segmenter,Met=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function Dn(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=Go(e)),e.length===0)return 0;let o=0,s={ambiguousAsWide:!n};for(let{segment:i}of ket.segment(e)){let a=i.codePointAt(0);if(!(a<=31||a>=127&&a<=159)&&!(a>=8203&&a<=8207||a===65279)&&!(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)&&!(a>=55296&&a<=57343)&&!(a>=65024&&a<=65039)&&!Met.test(i)){if((0,Lme.default)().test(i)){o+=2;continue}o+=pc(a,s)}}return o}var N5=e=>{if(!e)return 0;let t=e.split(`
|
|
281
281
|
`);return Math.max(...t.map(n=>ia(n)))},Ome=new Map,Pme=1e3;function Ao(e){let t=!0;for(let r=0;r<e.length;r++)if(e.charCodeAt(r)>127){t=!1;break}if(t)return e.split("");if(e.length<=Pme){let r=Ome.get(e);if(r)return r}let n=Array.from(e);return e.length<=Pme&&Ome.set(e,n),n}function Qt(e){return Ao(e).length}function fn(e,t,n){return Ao(e).slice(t,n).join("")}function Cm(e){let t=Go(e),n=Fet(t);return Ao(n).filter(r=>{let o=r.codePointAt(0);return o===void 0?!1:o===9||o===10||o===13?!0:!(o>=0&&o<=31||o>=128&&o<=159)}).join("")}var M5=new Map,ia=e=>{if(/^[\x20-\x7E]*$/.test(e))return e.length;if(M5.has(e))return M5.get(e);let t=Dn(e);return M5.set(e,t),t};var F5=woe();function ps(e){if(typeof e=="string")return e.search(F5)===-1?e:(F5.lastIndex=0,e.replace(F5,r=>JSON.stringify(r).slice(1,-1)));if(e===null||typeof e!="object")return e;if(Array.isArray(e)){let r=null;for(let o=0;o<e.length;o++){let s=e[o],i=ps(s);i!==s&&(r===null&&(r=[...e]),r[o]=i)}return r!==null?r:e}let t=null,n=Object.keys(e);for(let r of n){let o=e[r],s=ps(o);s!==o&&(t===null&&(t={...e}),t[r]=s)}return t!==null?t:e}var Net=[{pattern:/(sk-[a-zA-Z0-9]{20,})/g,replacement:"sk-***REDACTED***"},{pattern:/(api[_-]?key[_-]?[=:]\s*)[a-zA-Z0-9_-]{20,}/gi,replacement:"$1***REDACTED***"},{pattern:/(Bearer\s+)[a-zA-Z0-9._-]+/gi,replacement:"$1***REDACTED***"},{pattern:/(token[_-]?[=:]\s*)[a-zA-Z0-9._-]{10,}/gi,replacement:"$1***REDACTED***"},{pattern:/(password[_-]?[=:]\s*)[^\s]+/gi,replacement:"$1***REDACTED***"},{pattern:/(pwd[_-]?[=:]\s*)[^\s]+/gi,replacement:"$1***REDACTED***"},{pattern:/(AKIA[A-Z0-9]{16})/g,replacement:"***REDACTED***"},{pattern:/(secret[_-]?[=:]\s*)[a-zA-Z0-9._-]{10,}/gi,replacement:"$1***REDACTED***"}];function Ume(e,t=200){let n=e;for(let{pattern:r,replacement:o}of Net)n=n.replace(r,o);return n.length>t?t<=3?n.slice(0,t):n.slice(0,t-3)+"...":n}var _et=/[\x00-\x1f\x7f-\x9f]/g;function Hme(e){switch(e){case"\b":return"\\b";case" ":return"\\t";case`
|
|
282
282
|
`:return"\\n";case"\f":return"\\f";case"\r":return"\\r";default:return`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`}}function Mx(e){return ps(e).replace(_et,Hme)}var Let=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u{ad}\u{61c}\u{180e}\u{200b}-\u{200f}\u{2028}-\u{202e}\u{2060}-\u{206f}\u{feff}\u{fff9}-\u{fffb}\u{13430}-\u{1343f}\u{1bca0}-\u{1bca3}\u{1d173}-\u{1d17a}\u{e0000}-\u{e007f}]|\r(?!\n)/gu;function Nu(e){return e.replace(Let,Gme)}var Oet=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u{2028}-\u{202e}\u{2066}-\u{2069}\u{fff9}-\u{fffb}\u{e0000}-\u{e007f}]|\r(?!\n)|\u{1f3f4}\u{e0067}\u{e0062}(?:\u{e0065}\u{e006e}\u{e0067}|\u{e0073}\u{e0063}\u{e0074}|\u{e0077}\u{e006c}\u{e0073})\u{e007f}/gu;function MO(e){return e.replace(Oet,t=>t.length>2?t:Gme(t))}function Gme(e){let t=e.codePointAt(0);return t>65535?`\\u{${t.toString(16)}}`:Hme(e)}h();var jme=["user","project","workspace","system","extension"];var Pet=10;function Uet(e){switch(e){case"user":return C("User MCPs");case"project":return C("Project MCPs");case"workspace":return C("Workspace Settings");case"system":return C("System Settings");case"extension":return C("Extension MCPs");default:return e}}function zme(e){let t=new Map;for(let r of e){let o=t.get(r.source);o?o.push(r):t.set(r.source,[r])}let n=[];for(let r of jme){let o=t.get(r);o&&o.length>0&&n.push({source:r,displayName:Uet(r),servers:o})}return n}function FO(e){switch(e){case"connected":return"green";case"connecting":return"yellow";case"disconnected":return"red";default:return"gray"}}function NO(e){switch(e){case"connected":return"\u2713";case"connecting":return"\u2026";case"disconnected":return"\u2717";default:return"?"}}function Wme(e){let t=e.config;if(t.httpUrl)return`${t.httpUrl} (http)`;if(t.url)return`${t.url} (sse)`;if(t.command){let n=t.args?.join(" ")||"";return`${t.command} ${n} (stdio)`.trim()}return C("Unknown")}function _O(e){return e?e.split(/\r?\n/).map(t=>Cm(t.slice(t.lastIndexOf("\r")+1)).replace(/\t/g," ").trimEnd()).filter(t=>t.trim()!=="").slice(-Pet):[]}function qme(e,t){return!!e&&!!t}function Yme(e,t){let n=[];return e||n.push(C("missing name")),t||n.push(C("missing description")),n}var Het="\x1B[32m",Jme="\x1B[33m",Get="\x1B[31m",LO="\x1B[0m";async function jet(){let e=br(),t=new Ac({isWorkspaceTrusted:!!Js(e.merged),telemetrySettings:e.merged.telemetry});await t.refreshCache();let n=t.getLoadedExtensions(),r=OC(e.merged.mcpServers,process.cwd());for(let o of n)o.isActive&&Object.entries(o.config.mcpServers||{}).forEach(([s,i])=>{r[s]||(r[s]={...i,extensionName:o.config.name})});return r}async function zet(e,t){let n=new jne({name:"mcp-test-client",version:"0.0.1"}),r;try{r=await Yne(e,t,!1)}catch{return await n.close(),"disconnected"}try{return await n.connect(r,{timeout:5e3}),await n.ping(),await n.close(),"connected"}catch{return await r.close(),"disconnected"}}async function Wet(e,t){return await zet(e,t)}async function qet(){let e=await jet(),t=Object.keys(e);if(t.length===0){Bt("No MCP servers configured.");return}Bt(`Configured MCP servers:
|
|
283
283
|
`);let n=process.cwd(),r;for(let o of t){let s=e[o],i=`${o}: `;if(s.httpUrl?i+=`${s.httpUrl} (http)`:s.url?i+=`${s.url} (sse)`:s.command&&(i+=`${s.command} ${s.args?.join(" ")||""} (stdio)`),aC(s.scope)){r??=PC();let u=r.getState(n,o,s);if(u!=="approved"){Bt(`${Jme}\u25CF${LO} ${i} - ${u==="rejected"?"Rejected":"Pending approval"}`);continue}}let a=await Wet(o,s),l="",c="";switch(a){case"connected":l=Het+"\u2713"+LO,c="Connected";break;case"connecting":l=Jme+"\u2026"+LO,c="Connecting";break;case"disconnected":default:l=Get+"\u2717"+LO,c="Disconnected";break}if(Bt(`${l} ${i} - ${c}`),a==="disconnected"){let u=_O(g_(o));if(u.length>0){Bt(" Last stderr output:");for(let A of u)Bt(` ${A}`)}}}}var $me={command:"list",describe:"List all configured MCP servers",handler:async()=>{await qet()}};h();async function _5(e){let t=br(),n=e??new Ac({isWorkspaceTrusted:!!Js(t.merged),telemetrySettings:t.merged.telemetry});e||await n.refreshCache();let r=n.getLoadedExtensions(),o=OC(t.merged.mcpServers,process.cwd());for(let s of r)s.isActive&&Object.entries(s.config.mcpServers||{}).forEach(([i,a])=>{o[i]||(o[i]={...a,extensionName:s.config.name})});return o}async function Kme(){let e=br(),t=process.cwd(),n=new P_(t),r=await _5(),o=new Y_({sessionId:"mcp-reconnect",targetDir:t,cwd:t,debugMode:!1,mcpServers:r,pendingMcpServers:kO(r,t),fileDiscoveryService:n,mcpServerCommand:e.merged.mcp?.serverCommand});return await o.initialize(),o}function Vme(e,t=1){let n=new Error(e);return n.exitCode=t,n}async function Yet(e){if(!(await _5())[e])throw Vme(`Error: Server "${e}" not found in configuration.`);Bt(`Reconnecting to server "${e}"...`);try{let n=await Kme();await n.getToolRegistry().discoverToolsForServer(e),Bt(`Successfully reconnected to server "${e}".`),await n.shutdown()}catch(n){let r=n instanceof Error?n.message:String(n);throw Vme(`Failed to reconnect to server "${e}": ${r}`)}}async function Jet(){let e=br(),t=new Ac({isWorkspaceTrusted:!!Js(e.merged),telemetrySettings:e.merged.telemetry});await t.refreshCache();let n=await _5(t),r=Object.keys(n);if(r.length===0){Bt("No MCP servers configured.");return}Bt(`Reconnecting to all MCP servers...
|
|
@@ -391,7 +391,7 @@ You can update manually with:
|
|
|
391
391
|
Matilda - Launch an interactive CLI, use -p/--prompt for non-interactive mode`).option("telemetry",{type:"boolean",description:"Enable telemetry? This flag specifically controls if telemetry is sent. Other --telemetry-* flags set specific values but do not enable telemetry on their own."}).option("telemetry-otlp-endpoint",{type:"string",description:"Set the OTLP endpoint for telemetry. Overrides environment variables and settings files."}).option("telemetry-otlp-protocol",{type:"string",choices:["grpc","http"],description:"Set the OTLP protocol for telemetry (grpc or http). Overrides settings files."}).option("telemetry-log-prompts",{type:"boolean",description:"Enable or disable logging of user prompts for telemetry. Overrides settings files."}).option("telemetry-outfile",{type:"string",description:"Redirect all telemetry output to the specified file."}).deprecateOption("telemetry",'Use the "telemetry.enabled" setting in settings.json instead. This flag will be removed in a future version.').deprecateOption("telemetry-otlp-endpoint",'Use the "telemetry.otlpEndpoint" setting in settings.json instead. This flag will be removed in a future version.').deprecateOption("telemetry-otlp-protocol",'Use the "telemetry.otlpProtocol" setting in settings.json instead. This flag will be removed in a future version.').deprecateOption("telemetry-log-prompts",'Use the "telemetry.logPrompts" setting in settings.json instead. This flag will be removed in a future version.').deprecateOption("telemetry-outfile",'Use the "telemetry.outfile" setting in settings.json instead. This flag will be removed in a future version.').option("debug",{alias:"d",type:"boolean",description:"Run in debug mode?",default:!1}).option("bare",{type:"boolean",description:"Minimal mode: skip implicit startup auto-discovery and only honor explicitly provided CLI inputs.",default:!1}).option("fresh",{alias:"no-resume",type:"boolean",description:"Start a fresh one-shot session without resuming or recording chat history, while still loading auth/config.",default:!1}).option("proxy",{type:"string",description:"Proxy for Matilda, like schema://user:password@host:port"}).deprecateOption("proxy",'Use the "proxy" setting in settings.json instead. This flag will be removed in a future version.').option("chat-recording",{type:"boolean",description:"Enable chat recording to disk. If false, chat history is not saved and --continue/--resume will not work."}).command("$0 [query..]","Launch Matilda CLI",s=>s.positional("query",{description:"Positional prompt. Defaults to one-shot; use -i/--prompt-interactive for interactive."}).option("model",{alias:"m",type:"string",description:"Model"}).option("code-credit-limit-minor",{type:"string",coerce:Sne,description:"Allow up to this many USD cents per primary Code model generation after included quota is exhausted; not a session budget."}).option("organization-id",{type:"string",coerce:sre,description:"Use this organization for Matilda Core Code requests in this invocation."}).option("prompt",{alias:"p",type:"string",description:"Prompt for one-shot non-interactive mode. When provided, ambient piped stdin is ignored to avoid headless hangs."}).option("prompt-interactive",{alias:"i",type:"string",description:"Execute the provided prompt and continue in interactive mode"}).option("system-prompt",{type:"string",description:"Override the main session system prompt for this run. Can be combined with --append-system-prompt."}).option("append-system-prompt",{type:"string",description:"Append instructions to the main session system prompt for this run. Can be combined with --system-prompt."}).option("sandbox",{alias:"s",type:"boolean",description:"Run in sandbox?"}).option("sandbox-image",{type:"string",description:"Sandbox image URI."}).option("bogan",{alias:["b","yolo"],type:"boolean",description:"Automatically accept all actions (aka BOGAN mode)?",default:!1}).option("approval-mode",{type:"string",choices:["plan","default","auto-edit","bogan","yolo"],description:"Set the approval mode: plan (plan only), default (prompt for approval), auto-edit (auto-approve edit tools), bogan/yolo (auto-approve all tools)"}).option("acp",{type:"boolean",description:"Starts the agent in ACP mode"}).option("experimental-acp",{type:"boolean",description:"Starts the agent in ACP mode (deprecated, use --acp instead)",hidden:!0}).option("experimental-skills",{type:"boolean",description:"Deprecated: Skills are now enabled by default. This flag is ignored.",hidden:!0}).option("experimental-lsp",{type:"boolean",description:"Enable experimental LSP (Language Server Protocol) feature for code intelligence",default:!1}).option("channel",{type:"string",choices:["VSCode","ACP","SDK","CI","desktop"],description:"Channel identifier (VSCode, ACP, SDK, CI, desktop)"}).option("allowed-mcp-server-names",{type:"array",string:!0,description:"Allowed MCP server names",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("mcp-config",{type:"string",description:'MCP server configuration as JSON string or file path. Can be a path to a JSON file or inline JSON with {"mcpServers": {...}} format.'}).option("allowed-tools",{type:"array",string:!0,description:"Tools that are allowed to run without confirmation",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("extensions",{alias:"e",type:"array",string:!0,description:"A list of extensions to use. If not provided, all extensions are used.",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("list-extensions",{alias:"l",type:"boolean",description:"List all available extensions and exit."}).option("include-directories",{alias:"add-dir",type:"array",string:!0,description:"Additional directories to include in the workspace (comma-separated or multiple --include-directories)",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("openai-logging",{type:"boolean",description:"Enable logging of OpenAI API calls for debugging and analysis"}).option("openai-logging-dir",{type:"string",description:"Custom directory path for OpenAI API logs. Overrides settings files."}).option("openai-api-key",{type:"string",description:"OpenAI API key to use for authentication"}).option("openai-base-url",{type:"string",description:"OpenAI base URL (for custom endpoints)"}).option("screen-reader",{type:"boolean",description:"Enable screen reader mode for accessibility."}).option("output-format",{alias:"o",type:"string",description:"The format of the CLI output.",choices:["text","json","stream-json"]}).option("include-partial-messages",{type:"boolean",description:"Include partial assistant messages when using stream-json output.",default:!1}).option("json-fd",{type:"number",description:"File descriptor for structured JSON event output (dual output mode; works in interactive and headless runs). Primary output stays on stdout while JSON events are written to this fd. The caller must provide this fd via spawn stdio configuration."}).option("json-file",{type:"string",description:"File path for structured JSON event output (dual output mode; works in interactive and headless runs). Can be a regular file, FIFO (named pipe), or /dev/fd/N. Parent directories are created when missing."}).option("json-partials",{type:"boolean",description:"Include partial (streaming) assistant messages on the dual-output JSON channel. On by default; pass --no-json-partials when the consumer only needs typed state and not the text, which is a line per token it would discard.",default:!0}).option("json-schema",{type:"string",description:'JSON Schema that the model\'s final output must conform to (headless mode only). Accepts a JSON literal or "@path/to/schema.json". Registers a synthetic `structured_output` tool; the session ends on the first valid call.'}).option("input-file",{type:"string",description:"File path for receiving remote input commands (bidirectional sync). An external process writes JSONL commands; the TUI watches and processes them."}).option("continue",{alias:"c",type:"boolean",description:"Resume the most recent session for the current project.",default:!1}).option("resume",{alias:"r",type:"string",description:"Resume a specific session by its ID. Use without an ID to show session picker."}).option("session-id",{type:"string",description:'Specify a session ID for this run. Must be a valid UUID (e.g. "123e4567-e89b-12d3-a456-426614174000").'}).option("fork-session",{type:"boolean",description:"Create a new forked session from the resumed session. Must be used with --resume or --continue.",default:!1}).option("sandbox-session-id",{type:"string",hidden:!0}).option("worktree",{type:"string",description:"Start the session inside a git worktree at <repoRoot>/.matilda/worktrees/<slug>/. Pass a slug (`--worktree my-feature`), a PR reference (`--worktree=#123` or a full GitHub pull-request URL), or use bare `--worktree` to auto-generate a slug. On exit, the WorktreeExitDialog prompts to keep or remove the worktree."}).option("max-session-turns",{type:"number",description:"Maximum number of session turns"}).option("max-wall-time",{type:"string",description:"Run-level wall-clock budget for headless / unattended runs. Accepts seconds (e.g. `90`), or a duration string with unit (e.g. `30s`, `5m`, `1h`, `1.5h`). Minimum 1s \u2014 sub-second values (`500ms`, `0.5`) are rejected as typos; max ~24 days. Aborts the run with exit code 55 when exceeded."}).option("max-tool-calls",{type:"number",description:'Maximum cumulative tool calls executed during the run (success or failure; `structured_output` under --json-schema is exempt). Aborts with exit code 55 when exceeded. -1 / unset means no limit; 0 means "no tool calls allowed" (first call aborts). Capped at 1,000,000 to catch typos.'}).option("core-tools",{type:"array",string:!0,description:"Core tool paths",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("exclude-tools",{type:"array",string:!0,description:"Tools to exclude",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("disabled-slash-commands",{type:"array",string:!0,description:"Slash command names to hide/disable (comma-separated or repeated). Merged with the `slashCommands.disabled` setting and MATILDA_DISABLED_SLASH_COMMANDS. Matched case-insensitively against the final command name.",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("allowed-tools",{type:"array",string:!0,description:"Tools to allow, will bypass confirmation",coerce:i=>i.flatMap(a=>a.split(",").map(l=>l.trim()))}).option("auth-type",{type:"string",choices:["openai"],description:"Authentication type"}).deprecateOption("sandbox-image",'Use the "tools.sandboxImage" setting in settings.json instead. This flag will be removed in a future version.').deprecateOption("prompt","Use the positional prompt instead. This flag will be removed in a future version.").fail((i,a,l)=>{it(i||a?.message||"Unknown error"),l.showHelp(),process.exit(1)}).check(i=>{let a=i.query,l=Array.isArray(a)?a.length>0:!!a;if(i.prompt&&l)return"Cannot use both a positional prompt and the --prompt (-p) flag together";if(i.prompt&&i.promptInteractive)return"Cannot use both --prompt (-p) and --prompt-interactive (-i) together";if(i.bogan&&i.approvalMode)return"Cannot use both --bogan (-b) and --approval-mode together. Use --approval-mode=bogan instead.";if(i.includePartialMessages&&i.outputFormat!=="stream-json")return"--include-partial-messages requires --output-format stream-json";if(i.continue&&i.resume)return"Cannot use both --continue and --resume together. Use --continue to resume the latest session, or --resume <sessionId> to resume a specific session.";let c=i.resume===!1,u=i.resume!==void 0&&!c;if((i.fresh||c)&&(i.continue||u||i.forkSession))return"Cannot use --fresh/--no-resume with --continue, --resume, or --fork-session.";if(i.sessionId&&(i.continue||u))return"Cannot use --session-id with --continue or --resume. Use --session-id to start a new session with a specific ID, or use --continue/--resume to resume an existing session.";if(i.forkSession&&!(i.continue||u))return"--fork-session must be used with --resume or --continue.";if(i.sandboxSessionId&&(i.sessionId||i.continue||i.resume))return"Cannot use internal --sandbox-session-id with --session-id, --continue, or --resume.";if(i.sessionId&&!CD(i.sessionId))return`Invalid --session-id: "${i.sessionId}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;if(i.sandboxSessionId&&!CD(i.sandboxSessionId))return`Invalid --sandbox-session-id: "${i.sandboxSessionId}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;if(i.jsonFd!=null&&i.jsonFile!=null)return"--json-fd and --json-file are mutually exclusive. Use one or the other.";if(i.jsonSchema){if(i.promptInteractive)return"--json-schema cannot be used with --prompt-interactive (-i); structured output only terminates the non-interactive flow.";if(i.acp||i.experimentalAcp)return"--json-schema cannot be used with --acp; structured output is only honoured by the headless non-interactive flow.";let A=!!i.prompt,g=i.query,d=Array.isArray(g)?g.length>0:!!g,m=!process.stdin.isTTY;if(!A&&!d&&!m)return"--json-schema only applies to non-interactive mode; pass a prompt via -p, as a positional argument, or piped via stdin."}return!0})).command(nhe).command(bge).command(fhe).command(_De).command(wge).command(khe).command(Ohe).command(Fhe);t.version(await Ug()).alias("v","version").help().alias("h","help").strict().demandCommand(0,0),t.wrap(t.terminalWidth());let n=await t.parse();n.resume===!1&&(n.fresh=!0,delete n.resume),n._[0]==="credits"&&process.exit(process.exitCode??0),n._.length>0&&(n._[0]==="mcp"||n._[0]==="extensions"||n._[0]==="auth"||n._[0]==="hooks"||n._[0]==="review"||n._[0]==="sessions")&&process.exit(process.exitCode??0);let r=n.query,o=Array.isArray(r)?r.join(" "):r;return o&&!n.prompt&&(n.promptInteractive===""||!!n.promptInteractive?n.promptInteractive=o:n.prompt=o),n.query=o||void 0,n.experimentalAcp&&(it("\x1B[33m\u26A0 Warning: --experimental-acp is deprecated and will be removed in a future release. Please use --acp instead.\x1B[0m"),n.acp||(n.acp=!0)),(n.acp||n.experimentalAcp)&&!n.channel&&(n.channel="ACP"),n}async function $De(e,t=[],n,r=[],o,s="tree",i=[],a={}){let l=Rd.realpathSync(ab.resolve(e)),c=Rd.realpathSync(ab.resolve(Yat()));return z_(l===c?"":e,t,n,r,o,s,i,a)}function Xat(e,t){if(e.maxWallTime!==void 0&&e.maxWallTime!==null)try{return ODe(String(e.maxWallTime))}catch(r){throw new Error(`--max-wall-time: ${r.message}`)}let n=t.model?.maxWallTimeSeconds;if(typeof n=="number")try{return PDe(n)}catch(r){throw new Error(`settings.json: ${r.message}`)}return-1}function Zat(e,t){if(e.maxToolCalls!==void 0&&e.maxToolCalls!==null)try{return mY(e.maxToolCalls)}catch(r){throw new Error(`--max-tool-calls: ${r.message}`)}let n=t.model?.maxToolCalls;if(typeof n=="number")try{return mY(n)}catch(r){throw new Error(`settings.json: ${r.message}`)}return-1}function WDe(e,t){if(e!==void 0){if(e===-1)return Number.POSITIVE_INFINITY;if(typeof e!="number"||!Number.isSafeInteger(e)||e<=0)throw new Error(`settings.json: ${t} must be a positive whole number, or -1 for unlimited; got ${JSON.stringify(e)}.`);return e}}function hY(e){if(e.debug)return!0;let t=process.env.DEBUG,n=process.env.DEBUG_MODE;return t==="true"||t==="1"||n==="true"||n==="1"}function elt(e){return typeof e!="object"||e===null||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="object"&&t!==null)}function tlt(e){if(!e)return null;try{let t;if(Rd.existsSync(e)){$C.debug(`Reading MCP config from file: ${e}`);let r=Rd.readFileSync(e,"utf-8");t=JSON.parse((0,qDe.default)(r))}else $C.debug("Parsing MCP config as JSON string"),t=JSON.parse(e);let n;if(typeof t=="object"&&t!==null&&"mcpServers"in t&&typeof t.mcpServers=="object"?n=t.mcpServers:n=t,!elt(n))throw new Error("Invalid MCP server configuration format. Expected an object with server names as keys.");return $C.debug(`Loaded ${Object.keys(n).length} MCP server(s) from --mcp-config`),n}catch(t){let n=t instanceof Error?t.message:String(t);throw new Fi(`Invalid MCP configuration provided via --mcp-config: ${n}`)}}function Zk(e){return()=>{let t=e.merged.skills?.disabled,n=Array.isArray(t)?t:[];return new Set(n.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(Boolean))}}function nlt(e){let t=0,n=0,r=o=>{try{return Rd.statSync(o).mtimeMs}catch{return 0}};return()=>{let o=XQ(),s=new Mt(e).getWorkspaceSettingsPath(),i=r(o),a=r(s);if(i===t&&a===n)return null;t=i,n=a;let l=br(e,{consumeCorruptionEnvVars:!1,skipLoadEnvironment:!0});return{allow:l.merged.permissions?.allow??[],ask:l.merged.permissions?.ask??[],deny:l.merged.permissions?.deny??[]}}}async function eM(e,t,n=process.cwd(),r,o,s,i,a,l){e=Xk(e,t.channel);let c=hY(t),u=uI(t.bare),A=t.channel==="desktop"&&!!process.env.MATILDA_TEMPORARY_SESSION;rre(),Mt.setRuntimeBaseDir(e.advanced?.runtimeOutputDir,n);let g=e.ide?.enabled??!1,d=e.security?.folderTrust?.enabled??!0,m=Js(e,void 0,n)?.isTrusted??!1;e.context?.fileName?Uz(e.context.fileName):Uz(Ed());let E=new Mt(n),y=ab.join(E.getMatildaDir(),"output-language.md"),x=ab.join(Mt.getGlobalMatildaDir(),"output-language.md"),b;u||(Rd.existsSync(y)?b=y:Rd.existsSync(x)&&(b=x));let w=new P_(n),v=r6(t.channel),R=(v??(u?[]:e.context?.includeDirectories??[])).map(fO).concat(v?[]:(t.includeDirectories||[]).map(fO)),_=!u&&t.experimentalLsp===!0,G,W=t.promptInteractive||t.prompt||"",z=zDe(t.outputFormat),O=zDe(e.output?.format),H=z??O??"text",N=H==="stream-json"?O&&O!=="stream-json"?O:"text":H,L=!!t.includePartialMessages,P;t.approvalMode?P=GDe(t.approvalMode):t.bogan?P="bogan":!u&&e.tools?.approvalMode?P=GDe(e.tools.approvalMode):P="default",!m&&P!=="default"&&P!=="plan"&&(it('Approval mode overridden to "default" because the current folder is not trusted.'),P="default");let U;try{U=await ere({argv:t,env:process.env,settings:e.telemetry})}catch(ue){throw ue instanceof Fi?new Fi(`Invalid telemetry configuration: ${ue.message}.`):ue}let Y=!!t.query,k=!!t.prompt,j;t.promptInteractive?j=!0:(H==="stream-json"||H==="json")&&(Y||k)?j=!1:!Y&&!k?j=process.stdin.isTTY??!1:j=!1;let V=[...u?[]:t.coreTools??[],...u?[]:e.tools?.core??[]],ie=[...u?[]:e.permissions?.allow??[],...u?[]:e.tools?.allowed??[]],fe=[...u?[]:e.permissions?.ask??[]],ve=[...u?[]:e.permissions?.deny??[],...u?[]:e.tools?.exclude??[]],we={allow:[...u?[]:e.tools?.allowed??[]],ask:[],deny:[...u?[]:e.tools?.exclude??[]]};for(let ue of t.allowedTools??[])ue&&(we.allow.push(ue),ie.includes(ue)||ie.push(ue));for(let ue of t.excludeTools??[])ue&&(we.deny.push(ue),ve.includes(ue)||ve.push(ue));let be=[],Ge=new Set,q=ue=>{if(!ue)return;let Be=ue.trim();if(!Be)return;let _e=Be.toLowerCase();Ge.has(_e)||(Ge.add(_e),be.push(Be))};for(let ue of e.slashCommands?.disabled??[])q(ue);for(let ue of t.disabledSlashCommands??[])q(ue);for(let ue of(process.env.MATILDA_DISABLED_SLASH_COMMANDS??"").split(","))q(ue);for(let ue of(process.env.MATILDA_DISABLED_SLASH_COMMANDS??"").split(","))q(ue);let $=Tge(e.tools?.disabled),K=ue=>ie.some(Be=>tW(ue,[Be],[]))?!0:V.length>0?tW(ue,V,[]):!1,X=t.acp||t.experimentalAcp;if(!u&&!j&&!X){let ue=Be=>{if(!K(Be)){let _e=Be;we.deny.push(_e),ve.includes(_e)||ve.push(_e)}};switch(P){case"plan":case"default":ue(In.SHELL),ue(In.MONITOR),ue(In.EDIT),ue(In.WRITE_FILE);break;case"auto":ue(In.SHELL),ue(In.MONITOR),ue(In.EDIT),ue(In.WRITE_FILE);break;case"auto-edit":ue(In.SHELL),ue(In.MONITOR);break;case"bogan":break;default:break}}let oe,ce;t.allowedMcpServerNames?(oe=new Set(t.allowedMcpServerNames.filter(Boolean)),ce=void 0):u||(oe=e.mcp?.allowed?new Set(e.mcp.allowed.filter(Boolean)):void 0,ce=e.mcp?.excluded?new Set(e.mcp.excluded.filter(Boolean)):void 0);let Oe=t.authType||(u?void 0:e.security?.auth?.selectedType)||vge(),Qe=Rge({argv:{model:t.model,openaiApiKey:t.openaiApiKey,openaiBaseUrl:t.openaiBaseUrl,openaiLogging:t.openaiLogging,openaiLoggingDir:t.openaiLoggingDir},settings:e,selectedAuthType:Oe,env:process.env}),{model:Ce}=Qe;e.tools?.toolSearch?.enabled===!1&&(we.deny.push("tool_search"),ve.includes("tool_search")||ve.push("tool_search"));let Z=await RO(u?{}:e,t),ee=t.screenReader!==void 0?t.screenReader:e.ui?.accessibility?.screenReader??!1,pe,De;if(t.continue||t.resume){let ue=new yi(a??n,l);if(t.continue&&(De=await ue.loadLastSession(),De?pe=De.conversation.sessionId:t.forkSession&&(it("Cannot use --fork-session with --continue: no saved session found to fork."),process.exit(1))),t.resume&&(pe=t.resume,De=await ue.loadSession(t.resume),!De)){let Be=`No saved session found with ID ${t.resume}. Run \`matilda --resume\` without an ID to choose from existing sessions.`;it(Be),process.exit(1)}if(t.forkSession&&pe){let Be=pe,_e=HDe();try{await ue.forkSession(Be,_e)}catch(Ze){it(`Failed to fork session ${Be}: ${Ze instanceof Error?Ze.message:String(Ze)}`),process.exit(1)}pe=_e,De=await ue.loadSession(_e),De||(it(`Failed to load forked session ${_e}.`),process.exit(1))}}else if(t.sandboxSessionId)process.env.SANDBOX||(it("--sandbox-session-id is for internal sandbox use only."),process.exit(1)),pe=t.sandboxSessionId;else if(t.sessionId){if(await new yi(n).sessionExists(t.sessionId)){let _e=`Error: Session Id ${t.sessionId} is already in use.`;it(_e),process.exit(1)}pe=t.sessionId}else t.fresh&&(pe=HDe());let he=e.modelProviders,Se=tlt(t.mcpConfig),Ae=i||Se?{...i,...Se??{}}:void 0,me=u?{}:OC(e.mcpServers,n,Ae),Te=u?void 0:kO(me,n),Ke={organizationId:t.organizationId,codeCreditLimitMinor:t.codeCreditLimitMinor,sessionId:pe,sessionData:De,sessionStorageDir:a,sessionRuntimeBaseDir:l,embeddingModel:are,sandbox:Z,targetDir:n,includeDirectories:R,loadMemoryFromIncludeDirectories:u?R.length>0:e.context?.loadFromIncludeDirectories??!1,importFormat:e.context?.importFormat||"tree",debugMode:c,question:W,systemPrompt:t.systemPrompt,appendSystemPrompt:t.appendSystemPrompt,coreTools:u?void 0:t.coreTools||e.tools?.core||void 0,allowedTools:u?t.allowedTools||void 0:t.allowedTools||e.tools?.allowed||void 0,excludeTools:ve,disabledSlashCommands:be.length>0?be:void 0,disabledSkillNamesProvider:s,disabledTools:$.length>0?$:void 0,permissions:{requireExplicitApproval:A,allow:ie.length>0?ie:void 0,ask:fe.length>0?fe:void 0,deny:ve.length>0?ve:void 0,beyondSettings:we,autoMode:e.permissions?.autoMode},onPersistPermissionRule:async(ue,Be,_e)=>{let Ze=br(n,{consumeCorruptionEnvVars:!1,skipLoadEnvironment:!0}),st=ue==="project"?"Workspace":"User";Ze.appendArrayValue(st,`permissions.${Be}`,_e)},onRefreshPermissionsFromDisk:nlt(n),toolDiscoveryCommand:u?void 0:e.tools?.discoveryCommand,toolCallCommand:u?void 0:e.tools?.callCommand,mcpServerCommand:u?void 0:e.mcp?.serverCommand,mcpServers:me,pendingMcpServers:Te,allowedMcpServers:oe?Array.from(oe):void 0,excludedMcpServers:ce?Array.from(ce):void 0,approvalMode:P,accessibility:{...e.ui?.accessibility,screenReader:ee},telemetry:U,outboundCorrelation:e.outboundCorrelation,usageStatisticsEnabled:e.privacy?.usageStatisticsEnabled??!1,clearContextOnIdle:e.context?.clearContextOnIdle,fileFiltering:e.context?.fileFiltering,plansDirectory:e.plansDirectory,proxy:t.proxy||e.proxy||process.env.HTTPS_PROXY||process.env.https_proxy||process.env.HTTP_PROXY||process.env.http_proxy,cwd:n,fileDiscoveryService:w,bugCommand:e.advanced?.bugCommand,model:Ce,outputLanguageFilePath:b,sessionTokenLimit:e.model?.sessionTokenLimit??-1,maxSessionTurns:t.maxSessionTurns??e.model?.maxSessionTurns??-1,maxWallTimeSeconds:Xat(t,e),maxToolCalls:Zat(t,e),goalTokenBudget:WDe(e.goal?.tokenBudget,"goal.tokenBudget"),goalTurnBudget:WDe(e.goal?.turnBudget,"goal.turnBudget"),experimentalZedIntegration:t.acp||t.experimentalAcp||!1,cronEnabled:e.experimental?.cron??!0,agentTeamEnabled:e.experimental?.agentTeam??!1,planGateSystemOneTriage:e.planGate?.systemOneTriage,computerUseEnabled:e.tools?.computerUse?.enabled??!1,computerUseMaxImageDimension:e.tools?.computerUse?.maxImageDimension,emitToolUseSummaries:e.experimental?.emitToolUseSummaries??!0,listExtensions:t.listExtensions||!1,overrideExtensions:r||t.extensions,noBrowser:!!process.env.NO_BROWSER,authType:Oe,outputFormat:H,includePartialMessages:L,modelProvidersConfig:he,generationConfigSources:Qe.sources,generationConfig:Qe.generationConfig,settingsGenerationConfig:e.model?.generationConfig,warnings:Qe.warnings,bareMode:u,allowedHttpHookUrls:u?[]:e.security?.allowedHttpHookUrls??[],cliVersion:await Ug(),ideMode:g,chatCompression:e.model?.chatCompression,folderTrust:d,interactive:j,trustedFolder:m,useRipgrep:e.tools?.useRipgrep,useBuiltinRipgrep:e.tools?.useBuiltinRipgrep,shouldUseNodePtyShell:A?!1:e.tools?.shell?.enableInteractiveShell,preventSystemSleep:e.general?.preventSystemSleep??!0,skipNextSpeakerCheck:e.model?.skipNextSpeakerCheck,skipLoopDetection:e.model?.skipLoopDetection??!0,skipStartupContext:e.model?.skipStartupContext??!1,truncateToolOutputThreshold:e.tools?.truncateToolOutputThreshold,truncateToolOutputLines:e.tools?.truncateToolOutputLines,toolOutputBatchBudget:e.tools?.toolOutputBatchBudget,eventEmitter:ul,gitCoAuthor:e.general?.gitCoAuthor,output:{format:N},enableManagedAutoMemory:u||A?!1:e.memory?.enableManagedAutoMemory??!0,enableManagedAutoDream:u||A?!1:e.memory?.enableManagedAutoDream??!0,enableAutoSkill:u||A?!1:e.memory?.enableAutoSkill??!0,fastModel:e.fastModel||void 0,modelDisplayName:e.ui?.modelDisplayName||void 0,userHooks:u?void 0:o?.userHooks??e.hooks,projectHooks:u?void 0:o?.projectHooks,hooks:u?void 0:e.hooks,disableAllHooks:u||A?!0:e.disableAllHooks??!1,stopHookBlockingCap:u?void 0:e.stopHookBlockingCap,channel:t.channel,jsonFd:t.jsonFd,jsonFile:t.jsonFile??e.dualOutput?.jsonFile,jsonPartials:t.jsonPartials,jsonSchema:Kat(t.jsonSchema),inputFile:t.inputFile??e.dualOutput?.inputFile,chatRecording:t.fresh?!1:t.chatRecording??e.general?.chatRecording??!0,defaultFileEncoding:e.general?.defaultFileEncoding,lsp:{enabled:_},agents:e.agents?{displayMode:e.agents.displayMode,arena:e.agents.arena?{worktreeBaseDir:e.agents.arena.worktreeBaseDir,preserveArtifacts:e.agents.arena.preserveArtifacts??!1}:void 0}:void 0,worktree:e.worktree?{symlinkDirectories:e.worktree.symlinkDirectories}:void 0},Le=new Y_(Ke);if(_)try{let ue=new pse(Le,Le.getWorkspaceContext(),ul,w,mf,{requireTrustedWorkspace:d});await ue.discoverAndPrepare(),Le.getDebugMode()&&$C.debug("Native LSP status after discovery:",ue.getStatusSnapshot()),await ue.start(),Le.getDebugMode()&&$C.debug("Native LSP status after startup:",ue.getStatusSnapshot()),G=new gse(ue),Le.setLspClient(G);try{Le.setLspInitializationError(void 0)}catch{$C.warn("Failed to clear LSP initialization error after initialization")}}catch(ue){try{Le.setLspInitializationError(ue instanceof Error?ue:String(ue))}catch{$C.warn("LSP init error occurred after initialization:",ue)}$C.warn("Failed to initialize native LSP service:",ue)}return Le}h();h();async function VDe(e,t){if(!t)return null;try{await e.refreshAuth(t);let n=new oI(t,"auto","success");nI(e,n)}catch(n){let r=`Failed to login. Message: ${vr(n)}`,o=new oI(t,"auto","error",r);return nI(e,o),r}return null}h();h();h();var Ai={type:"dark",Background:"#0b0e14",Foreground:"#aeaca6",LightBlue:"#59C2FF",AccentBlue:"#39BAE6",AccentPurple:"#D2A6FF",AccentCyan:"#95E6CB",AccentGreen:"#AAD94C",AccentYellow:"#FFB454",AccentRed:"#F26D78",AccentYellowDim:"#8B7530",AccentRedDim:"#8B3A4A",DiffAdded:"#293022",DiffRemoved:"#3D1215",Comment:"#646A71",Gray:"#3D4149",GradientColors:["#FFB454","#F26D78"]},KDe=new zr("Ayu","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Ai.Background,color:Ai.Foreground},"hljs-keyword":{color:Ai.AccentYellow},"hljs-literal":{color:Ai.AccentPurple},"hljs-symbol":{color:Ai.AccentCyan},"hljs-name":{color:Ai.LightBlue},"hljs-link":{color:Ai.AccentBlue},"hljs-function .hljs-keyword":{color:Ai.AccentYellow},"hljs-subst":{color:Ai.Foreground},"hljs-string":{color:Ai.AccentGreen},"hljs-title":{color:Ai.AccentYellow},"hljs-type":{color:Ai.AccentBlue},"hljs-attribute":{color:Ai.AccentYellow},"hljs-bullet":{color:Ai.AccentYellow},"hljs-addition":{color:Ai.AccentGreen},"hljs-variable":{color:Ai.Foreground},"hljs-template-tag":{color:Ai.AccentYellow},"hljs-template-variable":{color:Ai.AccentYellow},"hljs-comment":{color:Ai.Comment,fontStyle:"italic"},"hljs-quote":{color:Ai.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:Ai.AccentRed},"hljs-meta":{color:Ai.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Ai);h();var To={type:"light",Background:"#f8f9fa",Foreground:"#5c6166",LightBlue:"#55b4d4",AccentBlue:"#399ee6",AccentPurple:"#a37acc",AccentCyan:"#4cbf99",AccentGreen:"#86b300",AccentYellow:"#f2ae49",AccentRed:"#f07171",AccentYellowDim:"#8B7000",AccentRedDim:"#993333",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#ABADB1",Gray:"#a6aaaf",GradientColors:["#399ee6","#86b300"]},XDe=new zr("Ayu Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:To.Background,color:To.Foreground},"hljs-comment":{color:To.Comment,fontStyle:"italic"},"hljs-quote":{color:To.AccentCyan,fontStyle:"italic"},"hljs-string":{color:To.AccentGreen},"hljs-constant":{color:To.AccentCyan},"hljs-number":{color:To.AccentPurple},"hljs-keyword":{color:To.AccentYellow},"hljs-selector-tag":{color:To.AccentYellow},"hljs-attribute":{color:To.AccentYellow},"hljs-variable":{color:To.Foreground},"hljs-variable.language":{color:To.LightBlue,fontStyle:"italic"},"hljs-title":{color:To.AccentBlue},"hljs-section":{color:To.AccentGreen,fontWeight:"bold"},"hljs-type":{color:To.LightBlue},"hljs-class .hljs-title":{color:To.AccentBlue},"hljs-tag":{color:To.LightBlue},"hljs-name":{color:To.AccentBlue},"hljs-builtin-name":{color:To.AccentYellow},"hljs-meta":{color:To.AccentYellow},"hljs-symbol":{color:To.AccentRed},"hljs-bullet":{color:To.AccentYellow},"hljs-regexp":{color:To.AccentCyan},"hljs-link":{color:To.LightBlue},"hljs-deletion":{color:To.AccentRed},"hljs-addition":{color:To.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-literal":{color:To.AccentCyan},"hljs-built_in":{color:To.AccentRed},"hljs-doctag":{color:To.AccentRed},"hljs-template-variable":{color:To.AccentCyan},"hljs-selector-id":{color:To.AccentRed}},To);h();var no={type:"dark",Background:"#282c34",Foreground:"#abb2bf",LightBlue:"#61aeee",AccentBlue:"#61aeee",AccentPurple:"#c678dd",AccentCyan:"#56b6c2",AccentGreen:"#98c379",AccentYellow:"#e6c07b",AccentRed:"#e06c75",AccentYellowDim:"#8B7530",AccentRedDim:"#8B3A4A",DiffAdded:"#39544E",DiffRemoved:"#562B2F",Comment:"#5c6370",Gray:"#5c6370",GradientColors:["#61aeee","#98c379"]},ZDe=new zr("Atom One","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:no.Foreground,background:no.Background},"hljs-comment":{color:no.Comment,fontStyle:"italic"},"hljs-quote":{color:no.Comment,fontStyle:"italic"},"hljs-doctag":{color:no.AccentPurple},"hljs-keyword":{color:no.AccentPurple},"hljs-formula":{color:no.AccentPurple},"hljs-section":{color:no.AccentRed},"hljs-name":{color:no.AccentRed},"hljs-selector-tag":{color:no.AccentRed},"hljs-deletion":{color:no.AccentRed},"hljs-subst":{color:no.AccentRed},"hljs-literal":{color:no.AccentCyan},"hljs-string":{color:no.AccentGreen},"hljs-regexp":{color:no.AccentGreen},"hljs-addition":{color:no.AccentGreen},"hljs-attribute":{color:no.AccentGreen},"hljs-meta-string":{color:no.AccentGreen},"hljs-built_in":{color:no.AccentYellow},"hljs-class .hljs-title":{color:no.AccentYellow},"hljs-attr":{color:no.AccentYellow},"hljs-variable":{color:no.AccentYellow},"hljs-template-variable":{color:no.AccentYellow},"hljs-type":{color:no.AccentYellow},"hljs-selector-class":{color:no.AccentYellow},"hljs-selector-attr":{color:no.AccentYellow},"hljs-selector-pseudo":{color:no.AccentYellow},"hljs-number":{color:no.AccentYellow},"hljs-symbol":{color:no.AccentBlue},"hljs-bullet":{color:no.AccentBlue},"hljs-link":{color:no.AccentBlue,textDecoration:"underline"},"hljs-meta":{color:no.AccentBlue},"hljs-selector-id":{color:no.AccentBlue},"hljs-title":{color:no.AccentBlue},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},no);h();var Fs={type:"dark",Background:"#282a36",Foreground:"#a3afb7",LightBlue:"#8be9fd",AccentBlue:"#8be9fd",AccentPurple:"#ff79c6",AccentCyan:"#8be9fd",AccentGreen:"#50fa7b",AccentYellow:"#fff783",AccentRed:"#ff5555",AccentYellowDim:"#8B7530",AccentRedDim:"#8B3A4A",DiffAdded:"#11431d",DiffRemoved:"#6e1818",Comment:"#6272a4",Gray:"#6272a4",GradientColors:["#ff79c6","#8be9fd"]},eSe=new zr("Dracula","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Fs.Background,color:Fs.Foreground},"hljs-keyword":{color:Fs.AccentBlue,fontWeight:"bold"},"hljs-selector-tag":{color:Fs.AccentBlue,fontWeight:"bold"},"hljs-literal":{color:Fs.AccentBlue,fontWeight:"bold"},"hljs-section":{color:Fs.AccentBlue,fontWeight:"bold"},"hljs-link":{color:Fs.AccentBlue},"hljs-function .hljs-keyword":{color:Fs.AccentPurple},"hljs-subst":{color:Fs.Foreground},"hljs-string":{color:Fs.AccentYellow},"hljs-title":{color:Fs.AccentYellow,fontWeight:"bold"},"hljs-name":{color:Fs.AccentYellow,fontWeight:"bold"},"hljs-type":{color:Fs.AccentYellow,fontWeight:"bold"},"hljs-attribute":{color:Fs.AccentYellow},"hljs-symbol":{color:Fs.AccentYellow},"hljs-bullet":{color:Fs.AccentYellow},"hljs-addition":{color:Fs.AccentGreen},"hljs-variable":{color:Fs.AccentYellow},"hljs-template-tag":{color:Fs.AccentYellow},"hljs-template-variable":{color:Fs.AccentYellow},"hljs-comment":{color:Fs.Comment},"hljs-quote":{color:Fs.Comment},"hljs-deletion":{color:Fs.AccentRed},"hljs-meta":{color:Fs.Comment},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Fs);h();var vo={type:"dark",Background:"#24292e",Foreground:"#c0c4c8",LightBlue:"#79B8FF",AccentBlue:"#79B8FF",AccentPurple:"#B392F0",AccentCyan:"#9ECBFF",AccentGreen:"#85E89D",AccentYellow:"#FFAB70",AccentRed:"#F97583",AccentYellowDim:"#8B7530",AccentRedDim:"#8B3A4A",DiffAdded:"#3C4636",DiffRemoved:"#502125",Comment:"#6A737D",Gray:"#6A737D",GradientColors:["#79B8FF","#85E89D"]},tSe=new zr("GitHub","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:vo.Foreground,background:vo.Background},"hljs-comment":{color:vo.Comment,fontStyle:"italic"},"hljs-quote":{color:vo.Comment,fontStyle:"italic"},"hljs-keyword":{color:vo.AccentRed,fontWeight:"bold"},"hljs-selector-tag":{color:vo.AccentRed,fontWeight:"bold"},"hljs-subst":{color:vo.Foreground},"hljs-number":{color:vo.LightBlue},"hljs-literal":{color:vo.LightBlue},"hljs-variable":{color:vo.AccentYellow},"hljs-template-variable":{color:vo.AccentYellow},"hljs-tag .hljs-attr":{color:vo.AccentYellow},"hljs-string":{color:vo.AccentCyan},"hljs-doctag":{color:vo.AccentCyan},"hljs-title":{color:vo.AccentPurple,fontWeight:"bold"},"hljs-section":{color:vo.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:vo.AccentPurple,fontWeight:"bold"},"hljs-type":{color:vo.AccentGreen,fontWeight:"bold"},"hljs-class .hljs-title":{color:vo.AccentGreen,fontWeight:"bold"},"hljs-tag":{color:vo.AccentGreen},"hljs-name":{color:vo.AccentGreen},"hljs-attribute":{color:vo.LightBlue},"hljs-regexp":{color:vo.AccentCyan},"hljs-link":{color:vo.AccentCyan},"hljs-symbol":{color:vo.AccentPurple},"hljs-bullet":{color:vo.AccentPurple},"hljs-built_in":{color:vo.LightBlue},"hljs-builtin-name":{color:vo.LightBlue},"hljs-meta":{color:vo.LightBlue,fontWeight:"bold"},"hljs-deletion":{background:"#86181D",color:vo.AccentRed},"hljs-addition":{background:"#144620",color:vo.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},vo);h();var jo={type:"light",Background:"#f8f8f8",Foreground:"#24292E",LightBlue:"#0086b3",AccentBlue:"#458",AccentPurple:"#900",AccentCyan:"#009926",AccentGreen:"#008080",AccentYellow:"#990073",AccentRed:"#d14",AccentYellowDim:"#8B7000",AccentRedDim:"#993333",DiffAdded:"#C6EAD8",DiffRemoved:"#FFCCCC",Comment:"#998",Gray:"#999",GradientColors:["#458","#008080"]},nSe=new zr("GitHub Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:jo.Foreground,background:jo.Background},"hljs-comment":{color:jo.Comment,fontStyle:"italic"},"hljs-quote":{color:jo.Comment,fontStyle:"italic"},"hljs-keyword":{color:jo.Foreground,fontWeight:"bold"},"hljs-selector-tag":{color:jo.Foreground,fontWeight:"bold"},"hljs-subst":{color:jo.Foreground,fontWeight:"normal"},"hljs-number":{color:jo.AccentGreen},"hljs-literal":{color:jo.AccentGreen},"hljs-variable":{color:jo.AccentGreen},"hljs-template-variable":{color:jo.AccentGreen},"hljs-tag .hljs-attr":{color:jo.AccentGreen},"hljs-string":{color:jo.AccentRed},"hljs-doctag":{color:jo.AccentRed},"hljs-title":{color:jo.AccentPurple,fontWeight:"bold"},"hljs-section":{color:jo.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:jo.AccentPurple,fontWeight:"bold"},"hljs-type":{color:jo.AccentBlue,fontWeight:"bold"},"hljs-class .hljs-title":{color:jo.AccentBlue,fontWeight:"bold"},"hljs-tag":{color:jo.AccentBlue,fontWeight:"normal"},"hljs-name":{color:jo.AccentBlue,fontWeight:"normal"},"hljs-attribute":{color:jo.AccentBlue,fontWeight:"normal"},"hljs-regexp":{color:jo.AccentCyan},"hljs-link":{color:jo.AccentCyan},"hljs-symbol":{color:jo.AccentYellow},"hljs-bullet":{color:jo.AccentYellow},"hljs-built_in":{color:jo.LightBlue},"hljs-builtin-name":{color:jo.LightBlue},"hljs-meta":{color:jo.Gray,fontWeight:"bold"},"hljs-deletion":{background:"#fdd"},"hljs-addition":{background:"#dfd"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},jo);h();var Ro={type:"light",Background:"white",Foreground:"#444",LightBlue:"#066",AccentBlue:"#008",AccentPurple:"#606",AccentCyan:"#066",AccentGreen:"#080",AccentYellow:"#660",AccentRed:"#800",AccentYellowDim:"#8B7000",AccentRedDim:"#993333",DiffAdded:"#C6EAD8",DiffRemoved:"#FEDEDE",Comment:"#5f6368",Gray:Nn.Gray,GradientColors:["#066","#606"]},rSe=new zr("Google Code","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Ro.Background,color:Ro.Foreground},"hljs-comment":{color:Ro.AccentRed},"hljs-quote":{color:Ro.AccentRed},"hljs-keyword":{color:Ro.AccentBlue},"hljs-selector-tag":{color:Ro.AccentBlue},"hljs-section":{color:Ro.AccentBlue},"hljs-title":{color:Ro.AccentPurple},"hljs-name":{color:Ro.AccentBlue},"hljs-variable":{color:Ro.AccentYellow},"hljs-template-variable":{color:Ro.AccentYellow},"hljs-string":{color:Ro.AccentGreen},"hljs-selector-attr":{color:Ro.AccentGreen},"hljs-selector-pseudo":{color:Ro.AccentGreen},"hljs-regexp":{color:Ro.AccentGreen},"hljs-literal":{color:Ro.AccentCyan},"hljs-symbol":{color:Ro.AccentCyan},"hljs-bullet":{color:Ro.AccentCyan},"hljs-meta":{color:Ro.AccentCyan},"hljs-number":{color:Ro.AccentCyan},"hljs-link":{color:Ro.AccentCyan},"hljs-doctag":{color:Ro.AccentPurple,fontWeight:"bold"},"hljs-type":{color:Ro.AccentPurple},"hljs-attr":{color:Ro.AccentPurple},"hljs-built_in":{color:Ro.AccentPurple},"hljs-builtin-name":{color:Ro.AccentPurple},"hljs-params":{color:Ro.AccentPurple},"hljs-attribute":{color:Ro.Foreground},"hljs-subst":{color:Ro.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-selector-id":{color:Ro.AccentYellow},"hljs-selector-class":{color:Ro.AccentYellow},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Ro);h();var ar={type:"dark",Background:"#2d2b57",Foreground:"#e3dfff",LightBlue:"#847ace",AccentBlue:"#a599e9",AccentPurple:"#ac65ff",AccentCyan:"#a1feff",AccentGreen:"#A5FF90",AccentYellow:"#fad000",AccentRed:"#ff628c",AccentYellowDim:"#8B7530",AccentRedDim:"#8B3A4A",DiffAdded:"#383E45",DiffRemoved:"#572244",Comment:"#B362FF",Gray:"#726c86",GradientColors:["#4d21fc","#847ace","#ff628c"]},Ma={AccentYellowAlt:"#f8d000",AccentOrange:"#fb9e00",AccentPink:"#fa658d",AccentLightPurple:"#c991ff",AccentDarkPurple:"#6943ff",AccentTeal:"#2ee2fa"},oSe=new zr("Shades Of Purple","dark",{hljs:{display:"block",overflowX:"auto",background:ar.Background,color:ar.Foreground},"hljs-title":{color:ar.AccentYellow,fontWeight:"normal"},"hljs-name":{color:ar.AccentCyan,fontWeight:"normal"},"hljs-tag":{color:ar.Foreground},"hljs-attr":{color:Ma.AccentYellowAlt,fontStyle:"italic"},"hljs-built_in":{color:Ma.AccentOrange},"hljs-selector-tag":{color:Ma.AccentOrange,fontWeight:"normal"},"hljs-section":{color:Ma.AccentOrange},"hljs-keyword":{color:Ma.AccentOrange,fontWeight:"normal"},"hljs-subst":{color:ar.Foreground},"hljs-string":{color:ar.AccentGreen},"hljs-attribute":{color:ar.AccentGreen},"hljs-symbol":{color:ar.AccentGreen},"hljs-bullet":{color:ar.AccentGreen},"hljs-addition":{color:ar.AccentGreen},"hljs-code":{color:ar.AccentGreen},"hljs-regexp":{color:ar.AccentGreen},"hljs-selector-class":{color:ar.AccentGreen},"hljs-selector-attr":{color:ar.AccentGreen},"hljs-selector-pseudo":{color:ar.AccentGreen},"hljs-template-tag":{color:ar.AccentGreen},"hljs-quote":{color:ar.AccentGreen},"hljs-deletion":{color:ar.AccentRed},"hljs-meta":{color:Ma.AccentOrange},"hljs-meta-string":{color:Ma.AccentOrange},"hljs-comment":{color:ar.AccentPurple},"hljs-literal":{color:Ma.AccentPink,fontWeight:"normal"},"hljs-number":{color:Ma.AccentPink},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-diff":{color:ar.Foreground},"hljs-meta.hljs-diff":{color:ar.AccentBlue},"hljs-ln":{color:ar.Gray},"hljs-type":{color:ar.AccentYellow,fontWeight:"normal"},"hljs-variable":{color:ar.AccentYellow},"hljs-template-variable":{color:ar.AccentGreen},"hljs-function .hljs-keyword":{color:Ma.AccentOrange},"hljs-link":{color:ar.LightBlue},"hljs-doctag":{fontWeight:"bold"},"hljs-params":{color:Ma.AccentLightPurple,fontStyle:"italic"},"hljs-class":{color:ar.AccentCyan,fontWeight:"bold"},"hljs-function":{color:ar.AccentCyan},"hljs-property":{color:ar.AccentBlue},"hljs-operator":{color:Ma.AccentDarkPurple},"hljs-punctuation":{color:ar.Gray},"hljs-selector-id":{color:ar.AccentYellow,fontWeight:"bold"},"hljs-char":{color:ar.AccentGreen},"hljs-escape":{color:Ma.AccentPink,fontWeight:"bold"},"hljs-meta-keyword":{color:Ma.AccentOrange,fontWeight:"bold"},"hljs-builtin-name":{color:Ma.AccentTeal},"hljs-module":{color:ar.AccentCyan},"hljs-namespace":{color:ar.LightBlue},"hljs-important":{color:ar.AccentRed,fontWeight:"bold"},"hljs-formula":{color:ar.AccentCyan,fontStyle:"italic"},"hljs-decorator":{color:Ma.AccentTeal,fontWeight:"bold"},"hljs-symbol.ruby":{color:Ma.AccentPink},"hljs-keyword.sql":{color:Ma.AccentOrange,textTransform:"uppercase"},"hljs-section.markdown":{color:ar.AccentYellow,fontWeight:"bold"},"hljs-attr.json":{color:ar.AccentCyan},"hljs-tag .hljs-name":{color:ar.AccentRed},"hljs-tag .hljs-attr":{color:Ma.AccentYellowAlt},"hljs.hljs-line-numbers":{borderRight:`1px solid ${ar.Gray}`},"hljs.hljs-line-numbers .hljs-ln-numbers":{color:ar.Gray,paddingRight:"1em"},"hljs.hljs-line-numbers .hljs-ln-code":{paddingLeft:"1em"},"hljs::selection":{background:ar.AccentBlue+"40"},"hljs ::-moz-selection":{background:ar.AccentBlue+"40"},"hljs .hljs-highlight":{background:ar.AccentPurple+"20",display:"block",width:"100%"}},ar);h();var fo={type:"light",Background:"#fff",Foreground:"#444",LightBlue:"#0E0EFF",AccentBlue:"#1c00cf",AccentPurple:"#aa0d91",AccentCyan:"#3F6E74",AccentGreen:"#007400",AccentYellow:"#836C28",AccentRed:"#c41a16",AccentYellowDim:"#8B7000",AccentRedDim:"#993333",DiffAdded:"#C6EAD8",DiffRemoved:"#FEDEDE",Comment:"#007400",Gray:"#c0c0c0",GradientColors:["#1c00cf","#007400"]},sSe=new zr("Xcode","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:fo.Background,color:fo.Foreground},"xml .hljs-meta":{color:fo.Gray},"hljs-comment":{color:fo.Comment},"hljs-quote":{color:fo.Comment},"hljs-tag":{color:fo.AccentPurple},"hljs-attribute":{color:fo.AccentPurple},"hljs-keyword":{color:fo.AccentPurple},"hljs-selector-tag":{color:fo.AccentPurple},"hljs-literal":{color:fo.AccentPurple},"hljs-name":{color:fo.AccentPurple},"hljs-variable":{color:fo.AccentCyan},"hljs-template-variable":{color:fo.AccentCyan},"hljs-code":{color:fo.AccentRed},"hljs-string":{color:fo.AccentRed},"hljs-meta-string":{color:fo.AccentRed},"hljs-regexp":{color:fo.LightBlue},"hljs-link":{color:fo.LightBlue},"hljs-title":{color:fo.AccentBlue},"hljs-symbol":{color:fo.AccentBlue},"hljs-bullet":{color:fo.AccentBlue},"hljs-number":{color:fo.AccentBlue},"hljs-section":{color:fo.AccentYellow},"hljs-meta":{color:fo.AccentYellow},"hljs-class .hljs-title":{color:fo.AccentPurple},"hljs-type":{color:fo.AccentPurple},"hljs-built_in":{color:fo.AccentPurple},"hljs-builtin-name":{color:fo.AccentPurple},"hljs-params":{color:fo.AccentPurple},"hljs-attr":{color:fo.AccentYellow},"hljs-subst":{color:fo.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-selector-id":{color:fo.AccentYellow},"hljs-selector-class":{color:fo.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},fo);h();var ms={type:"light",Background:"#FBFDFB",Foreground:"#1A211D",LightBlue:"#3B82F6",AccentBlue:"#1F6FEB",AccentPurple:"#8B5CF6",AccentCyan:"#0E8C86",AccentGreen:"#0FA968",AccentYellow:"#9A6B00",AccentRed:"#D03548",AccentYellowDim:"#7A5200",AccentRedDim:"#993333",DiffAdded:"#D5F0E0",DiffRemoved:"#FBDDE1",Comment:"#5C6B62",Gray:"#8A988E",GradientColors:["#D99A1F","#C8860A","#9A6B00","#7A5200","#5E3F00"]},olt={text:{primary:"#1A211D",secondary:"#5C6B62",link:"#0E8C86",accent:"#9A6B00",code:"#0E8C86"},background:{primary:ms.Background,diff:{added:ms.DiffAdded,removed:ms.DiffRemoved}},border:{default:"#C5D0C9",focused:"#9A6B00",input:"#9FA896"},ui:{comment:"#5C6B62",symbol:"#5C6B62",gradient:ms.GradientColors,heatmap:["#DDF0E4","#9FD3B0","#4FB07A","#C8950A","#9A6B00"],highlightTarget:"#0A0F0D"},status:{error:"#D03548",success:"#0FA968",warning:"#C0392B",errorDim:"#993333",warningDim:"#8A2A22"}},WP=new zr("Matilda Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:ms.Background,color:ms.Foreground},"hljs-keyword":{color:ms.AccentCyan},"hljs-literal":{color:ms.AccentPurple},"hljs-symbol":{color:ms.AccentCyan},"hljs-name":{color:ms.AccentBlue},"hljs-link":{color:ms.AccentBlue},"hljs-function .hljs-keyword":{color:ms.AccentCyan},"hljs-subst":{color:ms.Foreground},"hljs-string":{color:ms.AccentGreen},"hljs-title":{color:ms.AccentYellow},"hljs-type":{color:ms.AccentBlue},"hljs-attribute":{color:ms.AccentYellow},"hljs-bullet":{color:ms.AccentYellow},"hljs-addition":{color:ms.AccentGreen},"hljs-variable":{color:ms.Foreground},"hljs-template-tag":{color:ms.AccentYellow},"hljs-template-variable":{color:ms.AccentYellow},"hljs-comment":{color:ms.Comment,fontStyle:"italic"},"hljs-quote":{color:ms.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:ms.AccentRed},"hljs-meta":{color:ms.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},ms,olt);h();var hs={type:"dark",Background:"#0A0F0D",Foreground:"#CBD6CF",LightBlue:"#59C2FF",AccentBlue:"#39BAE6",AccentPurple:"#D2A6FF",AccentCyan:"#3FD9C9",AccentGreen:"#1CD687",AccentYellow:"#F2C744",AccentRed:"#F2606E",AccentYellowDim:"#8A6D1F",AccentRedDim:"#7E3340",DiffAdded:"#16351F",DiffRemoved:"#3B1A1F",Comment:"#5A6B61",Gray:"#2C3A33",GradientColors:["#FFF1C2","#FFE08A","#F2C744","#D9930F","#A86E12"]},slt={text:{primary:"#CBD6CF",secondary:"#7C8C82",link:"#3FD9C9",accent:"#F2C744",code:"#7FE8DA"},background:{primary:hs.Background,diff:{added:hs.DiffAdded,removed:hs.DiffRemoved}},border:{default:"#2C3A33",focused:"#F2C744",input:"#5A6B61"},ui:{comment:"#5A6B61",symbol:"#7C8C82",gradient:hs.GradientColors,heatmap:["#123026","#1C8F57","#46B86E","#C9B83A","#F2C744"],highlightTarget:"#F5F7F4"},status:{error:"#F2606E",success:"#1CD687",warning:"#E8902E",errorDim:"#7E3340",warningDim:"#7A4E1A"}},tM=new zr("Matilda Dark","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:hs.Background,color:hs.Foreground},"hljs-keyword":{color:hs.AccentCyan},"hljs-literal":{color:hs.AccentPurple},"hljs-symbol":{color:hs.AccentCyan},"hljs-name":{color:hs.LightBlue},"hljs-link":{color:hs.AccentBlue},"hljs-function .hljs-keyword":{color:hs.AccentCyan},"hljs-subst":{color:hs.Foreground},"hljs-string":{color:hs.AccentGreen},"hljs-title":{color:hs.AccentYellow},"hljs-type":{color:hs.AccentBlue},"hljs-attribute":{color:hs.AccentYellow},"hljs-bullet":{color:hs.AccentYellow},"hljs-addition":{color:hs.AccentGreen},"hljs-variable":{color:hs.Foreground},"hljs-template-tag":{color:hs.AccentYellow},"hljs-template-variable":{color:hs.AccentYellow},"hljs-comment":{color:hs.Comment,fontStyle:"italic"},"hljs-quote":{color:hs.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:hs.AccentRed},"hljs-meta":{color:hs.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},hs,slt);h();h();var CY=new Set(["Matilda Dark","Matilda Light","Matilda Wattle","Matilda Outback","Matilda Reef","Matilda Southern Cross"]);function VC(e,t){let n=t.accent??e.AccentYellow;return{text:{primary:e.Foreground,secondary:t.textSecondary,link:t.link??e.AccentCyan,accent:n,code:t.code},background:{primary:e.Background,diff:{added:e.DiffAdded,removed:e.DiffRemoved}},border:{default:t.borderDefault??e.Gray,focused:n,input:t.borderInput??e.Comment},ui:{comment:e.Comment,symbol:t.textSecondary,gradient:e.GradientColors,heatmap:t.heatmap,highlightTarget:e.type==="light"?"#0A0F0D":"#F5F7F4"},status:{error:e.AccentRed,success:e.AccentGreen,warning:t.warning,errorDim:e.AccentRedDim,warningDim:t.warningDim}}}function ilt(e){return{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:e.Background,color:e.Foreground},"hljs-keyword":{color:e.AccentCyan},"hljs-literal":{color:e.AccentPurple},"hljs-symbol":{color:e.AccentCyan},"hljs-name":{color:e.LightBlue},"hljs-link":{color:e.AccentBlue},"hljs-function .hljs-keyword":{color:e.AccentCyan},"hljs-subst":{color:e.Foreground},"hljs-string":{color:e.AccentGreen},"hljs-title":{color:e.AccentYellow},"hljs-type":{color:e.AccentBlue},"hljs-attribute":{color:e.AccentYellow},"hljs-bullet":{color:e.AccentYellow},"hljs-addition":{color:e.AccentGreen},"hljs-variable":{color:e.Foreground},"hljs-template-tag":{color:e.AccentYellow},"hljs-template-variable":{color:e.AccentYellow},"hljs-comment":{color:e.Comment,fontStyle:"italic"},"hljs-quote":{color:e.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:e.AccentRed},"hljs-meta":{color:e.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}}}function KC(e,t,n,r){return new zr(e,t,ilt(n),n,r)}var iSe={type:"dark",Background:"#0B120C",Foreground:"#DCE7DA",LightBlue:"#8FC0FF",AccentBlue:"#6FB0FF",AccentPurple:"#C9A6FF",AccentCyan:"#4FC07E",AccentGreen:"#3FB36B",AccentYellow:"#F2C744",AccentRed:"#F2606E",AccentYellowDim:"#8A6D1F",AccentRedDim:"#7E3340",DiffAdded:"#16351F",DiffRemoved:"#3B1A1F",Comment:"#5E7064",Gray:"#2E3A30",GradientColors:["#1F8A53","#3FB36B","#9FD15A","#F2C744","#FFE08A"]},aSe=KC("Matilda Wattle","dark",iSe,VC(iSe,{textSecondary:"#8A9C8E",code:"#8FE0B4",link:"#4FC07E",warning:"#E8902E",warningDim:"#7A4E1A",heatmap:["#143021","#1F8A53","#3FB36B","#9FD15A","#F2C744"]}));h();var lSe={type:"dark",Background:"#140C09",Foreground:"#ECDCC9",LightBlue:"#9AB8D9",AccentBlue:"#6E9AC9",AccentPurple:"#C7A6E0",AccentCyan:"#6FB8A6",AccentGreen:"#9AAE3C",AccentYellow:"#F2A03D",AccentRed:"#E2553F",AccentYellowDim:"#8A5A1F",AccentRedDim:"#7E3326",DiffAdded:"#23300F",DiffRemoved:"#3B1A12",Comment:"#7A6553",Gray:"#3A2A20",GradientColors:["#FFD9A0","#F2A03D","#D9603B","#A8341F","#6E1F14"]},cSe=KC("Matilda Outback","dark",lSe,VC(lSe,{textSecondary:"#A98F77",code:"#F0B27A",link:"#E0704A",accent:"#F2A03D",warning:"#FFE08A",warningDim:"#8A6D1F",heatmap:["#2A1410","#8A3A1F","#D9603B","#F2A03D","#FFD9A0"]}));h();var uSe={type:"dark",Background:"#04161A",Foreground:"#D2E7E3",LightBlue:"#6FD3F0",AccentBlue:"#39BAE6",AccentPurple:"#C9A6FF",AccentCyan:"#3FD9C9",AccentGreen:"#1CD687",AccentYellow:"#F2C744",AccentRed:"#F2606E",AccentYellowDim:"#8A6D1F",AccentRedDim:"#7E3340",DiffAdded:"#0C3A2A",DiffRemoved:"#3B1A1F",Comment:"#557068",Gray:"#1E3A3F",GradientColors:["#BFF3EC","#3FD9C9","#1FA9B8","#1C7FA8","#14506E"]},dSe=KC("Matilda Reef","dark",uSe,VC(uSe,{textSecondary:"#7C9C96",code:"#7FE8DA",link:"#6FD3F0",accent:"#3FD9C9",warning:"#F2C744",warningDim:"#8A6D1F",heatmap:["#06222A","#1C7FA8","#1FA9B8","#3FD9C9","#F2C744"]}));h();var ASe={type:"dark",Background:"#070A14",Foreground:"#CBD2E6",LightBlue:"#AEC0F0",AccentBlue:"#8FA0E8",AccentPurple:"#B9A0E8",AccentCyan:"#6FC9D9",AccentGreen:"#3FD9A8",AccentYellow:"#F2C744",AccentRed:"#F2607E",AccentYellowDim:"#8A6D1F",AccentRedDim:"#7E3344",DiffAdded:"#122A20",DiffRemoved:"#2A1626",Comment:"#5A6280",Gray:"#20283F",GradientColors:["#F7EFD0","#F2C744","#B9A0E8","#6E78C8","#2E3470"]},fSe=KC("Matilda Southern Cross","dark",ASe,VC(ASe,{textSecondary:"#8A92AE",code:"#9AB0F0",link:"#8FA0E8",warning:"#E8662E",warningDim:"#7A3A1A",heatmap:["#1A1B33","#2E3470","#6E78C8","#B9A0E8","#F2C744"]}));import*as nM from"node:fs";import*as yD from"node:path";import*as SSe from"node:os";h();h();var gSe={text:{primary:Nn.Foreground,secondary:Nn.Gray,link:Nn.AccentBlue,accent:Nn.AccentPurple,code:Nn.LightBlue},background:{primary:Nn.Background,diff:{added:Nn.DiffAdded,removed:Nn.DiffRemoved}},border:{default:Nn.Gray,focused:Nn.AccentBlue},ui:{comment:Nn.Comment,symbol:Nn.Gray,gradient:Nn.GradientColors},status:{error:Nn.AccentRed,success:Nn.AccentGreen,warning:Nn.AccentYellow,errorDim:Nn.AccentRedDim,warningDim:Nn.AccentYellowDim}},pSe={text:{primary:un.Foreground,secondary:un.Gray,link:un.AccentBlue,accent:un.AccentPurple,code:un.LightBlue},background:{primary:un.Background,diff:{added:un.DiffAdded,removed:un.DiffRemoved}},border:{default:un.Gray,focused:un.AccentBlue},ui:{comment:un.Comment,symbol:un.Gray,gradient:un.GradientColors},status:{error:un.AccentRed,success:un.AccentGreen,warning:un.AccentYellow,errorDim:un.AccentRedDim,warningDim:un.AccentYellowDim}},edn={text:{primary:Ra.Foreground,secondary:Ra.Gray,link:Ra.AccentBlue,accent:Ra.AccentPurple,code:Ra.LightBlue},background:{primary:Ra.Background,diff:{added:Ra.DiffAdded,removed:Ra.DiffRemoved}},border:{default:Ra.Gray,focused:Ra.AccentBlue},ui:{comment:Ra.Comment,symbol:Ra.Gray,gradient:Ra.GradientColors},status:{error:Ra.AccentRed,success:Ra.AccentGreen,warning:Ra.AccentYellow,errorDim:Ra.AccentRedDim,warningDim:Ra.AccentYellowDim}};var alt={type:"dark",Background:"black",Foreground:"white",LightBlue:"bluebright",AccentBlue:"blue",AccentPurple:"magenta",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"yellow",AccentRed:"red",AccentYellowDim:"yellow",AccentRedDim:"red",DiffAdded:"#003300",DiffRemoved:"#4D0000",Comment:"gray",Gray:"gray",GradientColors:["cyan","green"]},mSe=new zr("ANSI","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"black",color:"white"},"hljs-keyword":{color:"blue"},"hljs-literal":{color:"blue"},"hljs-symbol":{color:"blue"},"hljs-name":{color:"blue"},"hljs-link":{color:"blue"},"hljs-built_in":{color:"cyan"},"hljs-type":{color:"cyan"},"hljs-number":{color:"green"},"hljs-class":{color:"green"},"hljs-string":{color:"yellow"},"hljs-meta-string":{color:"yellow"},"hljs-regexp":{color:"red"},"hljs-template-tag":{color:"red"},"hljs-subst":{color:"white"},"hljs-function":{color:"white"},"hljs-title":{color:"white"},"hljs-params":{color:"white"},"hljs-formula":{color:"white"},"hljs-comment":{color:"green"},"hljs-quote":{color:"green"},"hljs-doctag":{color:"green"},"hljs-meta":{color:"gray"},"hljs-meta-keyword":{color:"gray"},"hljs-tag":{color:"gray"},"hljs-variable":{color:"magenta"},"hljs-template-variable":{color:"magenta"},"hljs-attr":{color:"bluebright"},"hljs-attribute":{color:"bluebright"},"hljs-builtin-name":{color:"bluebright"},"hljs-section":{color:"yellow"},"hljs-emphasis":{},"hljs-strong":{},"hljs-bullet":{color:"yellow"},"hljs-selector-tag":{color:"yellow"},"hljs-selector-id":{color:"yellow"},"hljs-selector-class":{color:"yellow"},"hljs-selector-attr":{color:"yellow"},"hljs-selector-pseudo":{color:"yellow"}},alt,pSe);h();var llt={type:"light",Background:"white",Foreground:"#444",LightBlue:"blue",AccentBlue:"blue",AccentPurple:"purple",AccentCyan:"cyan",AccentGreen:"green",AccentYellow:"orange",AccentRed:"red",AccentYellowDim:"orange",AccentRedDim:"red",DiffAdded:"#E5F2E5",DiffRemoved:"#FFE5E5",Comment:"gray",Gray:"gray",GradientColors:["blue","green"]},hSe=new zr("ANSI Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:"white",color:"black"},"hljs-keyword":{color:"blue"},"hljs-literal":{color:"blue"},"hljs-symbol":{color:"blue"},"hljs-name":{color:"blue"},"hljs-link":{color:"blue"},"hljs-built_in":{color:"cyan"},"hljs-type":{color:"cyan"},"hljs-number":{color:"green"},"hljs-class":{color:"green"},"hljs-string":{color:"red"},"hljs-meta-string":{color:"red"},"hljs-regexp":{color:"magenta"},"hljs-template-tag":{color:"magenta"},"hljs-subst":{color:"black"},"hljs-function":{color:"black"},"hljs-title":{color:"black"},"hljs-params":{color:"black"},"hljs-formula":{color:"black"},"hljs-comment":{color:"gray"},"hljs-quote":{color:"gray"},"hljs-doctag":{color:"gray"},"hljs-meta":{color:"gray"},"hljs-meta-keyword":{color:"gray"},"hljs-tag":{color:"gray"},"hljs-variable":{color:"purple"},"hljs-template-variable":{color:"purple"},"hljs-attr":{color:"blue"},"hljs-attribute":{color:"blue"},"hljs-builtin-name":{color:"blue"},"hljs-section":{color:"orange"},"hljs-bullet":{color:"orange"},"hljs-selector-tag":{color:"orange"},"hljs-selector-id":{color:"orange"},"hljs-selector-class":{color:"orange"},"hljs-selector-attr":{color:"orange"},"hljs-selector-pseudo":{color:"orange"}},llt,gSe);h();var clt={type:"ansi",Background:"",Foreground:"",LightBlue:"",AccentBlue:"",AccentPurple:"",AccentCyan:"",AccentGreen:"",AccentYellow:"",AccentRed:"",AccentYellowDim:"",AccentRedDim:"",DiffAdded:"",DiffRemoved:"",Comment:"",Gray:""},ult={text:{primary:"",secondary:"",link:"",accent:"",code:""},background:{primary:"",diff:{added:"",removed:""}},border:{default:"",focused:""},ui:{comment:"",symbol:"",gradient:[]},status:{error:"",success:"",warning:"",errorDim:"",warningDim:""}},CSe=new zr("NoColor","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em"},"hljs-keyword":{},"hljs-literal":{},"hljs-symbol":{},"hljs-name":{},"hljs-link":{textDecoration:"underline"},"hljs-built_in":{},"hljs-type":{},"hljs-number":{},"hljs-class":{},"hljs-string":{},"hljs-meta-string":{},"hljs-regexp":{},"hljs-template-tag":{},"hljs-subst":{},"hljs-function":{},"hljs-title":{},"hljs-params":{},"hljs-formula":{},"hljs-comment":{fontStyle:"italic"},"hljs-quote":{fontStyle:"italic"},"hljs-doctag":{},"hljs-meta":{},"hljs-meta-keyword":{},"hljs-tag":{},"hljs-variable":{},"hljs-template-variable":{},"hljs-attr":{},"hljs-attribute":{},"hljs-builtin-name":{},"hljs-section":{},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-bullet":{},"hljs-selector-tag":{},"hljs-selector-id":{},"hljs-selector-class":{},"hljs-selector-attr":{},"hljs-selector-pseudo":{},"hljs-addition":{display:"inline-block",width:"100%"},"hljs-deletion":{display:"inline-block",width:"100%"}},clt,ult);import mlt from"node:process";h();import{execSync as dlt}from"node:child_process";import cb from"node:process";var ED=$e("THEME_DETECT"),Alt=200;function lb(e){let t=16**e.length-1;return parseInt(e,16)/t}function flt(e){let t=/^rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})/i.exec(e);if(t)return{r:lb(t[1]),g:lb(t[2]),b:lb(t[3])};let n=/^#([0-9a-f]+)$/i.exec(e);if(n&&n[1].length%3===0){let r=n[1],o=r.length/3;return{r:lb(r.slice(0,o)),g:lb(r.slice(o,2*o)),b:lb(r.slice(2*o))}}}function glt(e){let t=flt(e);return t?.2126*t.r+.7152*t.g+.0722*t.b>.5?"light":"dark":void 0}function plt(){return!cb.stdin.isTTY||!cb.stdout.isTTY?Promise.resolve(void 0):new Promise(e=>{let t=cb.stdin,n=!1,r="",o=a=>{n||(n=!0,clearTimeout(s),t.removeListener("data",i),e(a))},s=setTimeout(()=>o(void 0),Alt),i=a=>{r+=a.toString();let l=/\x1b\]11;(.*?)(?:\x07|\x1b\\)/.exec(r);l&&o(glt(l[1]))};t.on("data",i),cb.stdout.write("\x1B]11;?\x07")})}function ESe(){if(cb.platform==="darwin")try{return dlt("defaults read -g AppleInterfaceStyle",{encoding:"utf-8",timeout:3e3,stdio:["pipe","pipe","pipe"]}).trim().toLowerCase()==="dark"?"dark":"light"}catch(e){let t=e,n=typeof t.stderr=="string"?t.stderr:t.stderr?.toString?.()??"",r=t.message??"";return/does not exist/i.test(n)||/does not exist/i.test(r)?"light":void 0}}function ySe(){let e=cb.env.COLORFGBG;if(!e)return;let t=e.split(";"),n=t[t.length-1];if(n===void 0)return;let r=parseInt(n,10);if(!isNaN(r))return r===7||r>=9&&r<=15?"light":"dark"}function ISe(){let e=ySe();if(e)return ED.info(`Detected theme from COLORFGBG: ${e}`),e;let t=ESe();return t?(ED.info(`Detected theme from macOS system appearance: ${t}`),t):(ED.info("Could not detect terminal theme, defaulting to dark"),"dark")}async function DSe(){let e=ySe();if(e)return ED.info(`Detected theme from COLORFGBG (async path): ${e}`),e;let t=await plt();if(t)return ED.info(`Detected theme from OSC 11 background query: ${t}`),t;let n=ESe();return n?(ED.info(`Detected theme from macOS system appearance: ${n}`),n):(ED.info("Could not detect terminal theme, defaulting to dark"),"dark")}var Rm=$e("THEME_MANAGER"),XC=tM,Zc="auto";function BSe(e){return e?e.endsWith(".json")||e.startsWith(".")||yD.isAbsolute(e):!1}var EY=class{availableThemes;activeTheme;customThemes=new Map;constructor(){this.availableThemes=[tM,WP,aSe,cSe,dSe,fSe,KDe,XDe,ZDe,eSe,NQ,_Q,tSe,nSe,rSe,oSe,sSe,mSe,hSe],this.activeTheme=XC}loadCustomThemes(t){if(this.customThemes.clear(),!!t){for(let[n,r]of Object.entries(t)){let o=Z4(r);if(o.isValid){o.warning&&Rm.warn(`Theme "${n}": ${o.warning}`);let s={...XC.colors,...r,name:r.name||n,type:"custom"};try{let i=X4(s);this.customThemes.set(n,i)}catch(i){Rm.warn(`Failed to load custom theme "${n}":`,i)}}else Rm.warn(`Invalid custom theme "${n}": ${o.error}`)}this.activeTheme&&this.activeTheme.type==="custom"&&this.customThemes.has(this.activeTheme.name)&&(this.activeTheme=this.customThemes.get(this.activeTheme.name))}}setActiveTheme(t){if(t===Zc)return this.activeTheme=this.resolveAutoTheme(),Rm.info(`Auto-detected theme: ${this.activeTheme.name}`),!0;let n=this.findThemeByName(t);return n?(this.activeTheme=n,!0):!1}cachedAutoDetection;resolveAutoTheme(){return(this.cachedAutoDetection??ISe())==="light"?WP:tM}async resolveAutoThemeAsync(){let t=await DSe();this.cachedAutoDetection=t,this.activeTheme=t==="light"?WP:tM,Rm.info(`Auto-detected theme (async): ${this.activeTheme.name}`)}getActiveTheme(){if(mlt.env.NO_COLOR)return CSe;if(this.activeTheme){let t=this.availableThemes.some(r=>r.name===this.activeTheme.name),n=[...this.customThemes.values()].includes(this.activeTheme);if(t||n)return this.activeTheme}return this.activeTheme=XC,this.activeTheme}getSemanticColors(){return this.getActiveTheme().semanticColors}getCustomThemeNames(){return Array.from(this.customThemes.keys())}isCustomTheme(t){return this.customThemes.has(t)}getAvailableThemes(){let t=this.availableThemes.map(i=>({name:i.name,type:i.type,isCustom:!1})),n=Array.from(this.customThemes.values()).map(i=>({name:i.name,type:i.type,isCustom:!0})),r=t.filter(i=>CY.has(i.name)),s=[...t.filter(i=>!CY.has(i.name)),...n].sort((i,a)=>{let l=u=>{switch(u){case"dark":return 1;case"light":return 2;case"ansi":return 3;case"custom":return 4;default:return 5}},c=l(i.type)-l(a.type);return c!==0?c:i.name.localeCompare(a.name)});return[...r,...s]}getTheme(t){return this.findThemeByName(t)}isPath(t){return t.endsWith(".json")||t.startsWith(".")||yD.isAbsolute(t)}loadThemeFromFile(t){try{let n=nM.realpathSync(yD.resolve(t));if(this.customThemes.has(n))return this.customThemes.get(n);let r=yD.resolve(SSe.homedir());if(!n.startsWith(r)){Rm.warn(`Theme file at "${t}" is outside your home directory. Only load themes from trusted sources.`);return}let o=nM.readFileSync(n,"utf-8"),s=JSON.parse(o),i=Z4(s);if(!i.isValid){Rm.warn(`Invalid custom theme from file "${t}": ${i.error}`);return}i.warning&&Rm.warn(`Theme from "${t}": ${i.warning}`);let a={...XC.colors,...s,name:s.name||n,type:"custom"},l=X4(a);return this.customThemes.set(n,l),l}catch(n){n instanceof Error&&"code"in n&&n.code==="ENOENT"||Rm.warn(`Could not load theme from file "${t}":`,n);return}}findThemeByName(t){if(!t)return XC;let n=this.availableThemes.find(r=>r.name===t);if(n)return n;if(this.isPath(t))return this.loadThemeFromFile(t);if(this.customThemes.has(t))return this.customThemes.get(t)}reloadThemeFromFile(t){let n;try{n=nM.realpathSync(yD.resolve(t))}catch{return!1}let r=this.activeTheme.type==="custom"&&this.customThemes.get(n)===this.activeTheme;this.customThemes.delete(n);let o=this.loadThemeFromFile(t);return o&&(r||this.activeTheme.name===o.name)?(this.activeTheme=o,!0):!1}},Pn=new EY;function xSe(e){let t=e.merged.ui?.theme;return t&&t!==Zc&&!Pn.findThemeByName(t)?C('Theme "{{themeName}}" not found.',{themeName:t}):null}async function bSe(e,t){let n=process.env.MATILDA_CODE_LANG||t.merged.general?.language||"auto";await Mue(n);let r=e.getModelsConfig().getCurrentAuthType(),o=await VDe(e,r),s=xSe(t),i=!e.getModelsConfig().wasAuthTypeExplicitlyProvided()||!!o;return e.getIdeMode()&&(await(await rl.getInstance()).connect(),d_(e,new m_("start"))),{authError:o,themeError:s,shouldOpenAuthDialog:i,geminiMdFileCount:e.getGeminiMdFileCount()}}h();h();import{spawn as NSe}from"node:child_process";h();import*as Li from"node:fs/promises";import{constants as yY}from"node:fs";import{execSync as Clt,spawn as YP}from"node:child_process";import*as ub from"node:path";import{randomUUID as wSe}from"node:crypto";var xc=$e("CLIPBOARD_UTILS"),oM=5e3;function db(e){try{if(Buffer.byteLength(e,"utf-8")>75e3)return xc.warn(`writeOsc52: text too large (${Buffer.byteLength(e,"utf-8")} bytes), skipping`),!1;let n=Buffer.from(e,"utf-8").toString("base64"),r=Ll(`\x1B]52;c;${n}\x07`),o=process.stderr.isTTY?process.stderr:process.stdout.isTTY?process.stdout:null;return o?(o.write(r,s=>{s&&xc.warn("writeOsc52: async write failed:",s)}),!0):(xc.warn("OSC 52 clipboard requires a TTY; stdout/stderr not connected to terminal"),!1)}catch(t){return xc.warn("writeOsc52 failed:",t),!1}}var rM,qP=null,IY=null,TSe=!1;async function RSe(){if(TSe)return IY;TSe=!0;try{return IY=await import("@teddyzhu/clipboard"),IY}catch{return xc.error("Failed to load @teddyzhu/clipboard native module. Clipboard image features will be unavailable."),null}}function QSe(){if(rM!==void 0)return rM;let e=process.env.XDG_SESSION_TYPE,t=process.env.WAYLAND_DISPLAY,n=process.env.DISPLAY,r=null;if(e==="wayland"||t)r="wl-paste";else if(e==="x11"||n)r="xclip";else return rM=null,null;try{return Clt("command -v "+r,{stdio:"ignore"}),rM=r,r}catch{return xc.warn(`${r} not found`),rM=null,null}}async function DY(e,t,n){let r;try{r=await Li.open(n,yY.O_WRONLY|yY.O_CREAT|yY.O_EXCL)}catch{return!1}return new Promise(o=>{let s=YP(e,t,{stdio:["ignore","pipe","pipe"]}),i=r.createWriteStream(),a="",l=!1,c=A=>{if(!l){l=!0;try{s.killed||s.kill()}catch{}try{i.destroy()}catch{}o(A)}},u=setTimeout(()=>{xc.debug(`${e} timed out after ${oM}ms`),c(!1)},oM);s.stderr.on("data",A=>{a+=A.toString()}),s.stdout.pipe(i),s.stdout.on("error",A=>{xc.debug(`stdout error for ${e}:`,A),clearTimeout(u),c(!1)}),s.on("error",A=>{xc.debug(`Failed to spawn ${e}:`,A),clearTimeout(u),c(!1)}),i.on("error",A=>{xc.debug(`File stream error for ${n}:`,A),clearTimeout(u),c(!1)}),s.on("close",A=>{if(clearTimeout(u),l)return;if(A!==0){xc.debug(`${e} exited with code ${A}. Args: ${t.join(" ")}`),a&&xc.debug(`${e} stderr: ${a.trim()}`),c(!1);return}let g=()=>{Li.stat(n).then(d=>{c(d.size>0)}).catch(()=>{c(!1)})};i.writableFinished?g():(i.on("finish",g),i.on("close",()=>{l||g()}))})})}async function vSe(e,t){return e==="wl-paste"&&t.length===1&&t[0]==="--list-types"?(await kSe()).length>0:new Promise(n=>{try{let r=YP(e,t,{stdio:["ignore","pipe","ignore"]}),o="",s=setTimeout(()=>{try{r.kill()}catch{}n(!1)},oM);r.stdout.on("data",i=>{o+=i.toString()}),r.on("close",i=>{clearTimeout(s),n(i===0&&o.split(`
|
|
392
392
|
`).some(a=>a==="image/png"||a==="image/bmp"))}),r.on("error",()=>{clearTimeout(s),n(!1)})}catch{n(!1)}})}async function JP(){if(qP=null,process.platform==="linux"){try{let e=QSe();if(e==="wl-paste")return vSe("wl-paste",["--list-types"]);if(e==="xclip")return vSe("xclip",["-selection","clipboard","-t","TARGETS","-o"])}catch(e){xc.error("Error checking clipboard for image:",e)}return!1}try{let e=await RSe();return e?new e.ClipboardManager().hasFormat("image"):!1}catch(e){return xc.error("Error checking clipboard for image:",e),!1}}async function kSe(){return qP!==null?qP:new Promise(e=>{let t=YP("wl-paste",["--list-types"],{stdio:["ignore","pipe","ignore"]}),n="",r=setTimeout(()=>{try{t.kill()}catch{}e([])},oM);t.stdout.on("data",o=>{n+=o.toString()}),t.on("close",o=>{if(clearTimeout(r),o!==0){e([]);return}let s=n.trim().split(`
|
|
393
393
|
`).filter(i=>i==="image/png"||i==="image/bmp");qP=s,e(s)}),t.on("error",()=>{clearTimeout(r),e([])})})}async function Elt(e){let t=await kSe();if(t.includes("image/png")){if(await DY("wl-paste",["--no-newline","--type","image/png"],e))return e;try{await Li.unlink(e)}catch{}}if(t.includes("image/bmp")){let n=e.replace(/\.png$/,".bmp");if(await DY("wl-paste",["--no-newline","--type","image/bmp"],n))try{await new Promise((o,s)=>{let i=YP("python3",["-c","import sys; from PIL import Image; Image.open(sys.argv[1]).save(sys.argv[2])",n,e],{stdio:["ignore","ignore","pipe"]}),a="";i.stderr.on("data",c=>{a+=c.toString()});let l=setTimeout(()=>{try{i.kill()}catch{}s(new Error("python3 timed out"))},oM);i.on("close",c=>{clearTimeout(l),c===0?o():s(new Error(`python3 exited with code ${c}${a?": "+a.trim():""}`))}),i.on("error",c=>{clearTimeout(l),s(c)})});try{await Li.unlink(n)}catch{}return e}catch(o){xc.warn("BMP-to-PNG conversion failed (install python3-pil for BMP support):",o);try{await Li.unlink(n)}catch{}try{await Li.unlink(e)}catch{}return!1}try{await Li.unlink(n)}catch{}}return!1}async function ylt(e){if(await DY("xclip",["-selection","clipboard","-t","image/png","-o"],e))return!0;try{await Li.unlink(e)}catch{}return!1}async function MSe(e){try{let t=e||process.cwd(),n=ub.join(t,"clipboard");await Li.mkdir(n,{recursive:!0});let r=new Date().getTime();if(process.platform==="linux"){let c=ub.join(n,`clipboard-${r}-${wSe()}.png`),u=QSe();if(u==="wl-paste"){let A=await Elt(c);if(A)try{if((await Li.stat(A)).size>0)return A;await Li.unlink(A)}catch{}return null}return u==="xclip"&&await ylt(c)?c:null}let o=await RSe();if(!o)return null;let s=new o.ClipboardManager;if(!s.hasFormat("image"))return null;let i=ub.join(n,`clipboard-${r}-${wSe()}.png`),l=s.getImageData().data;return l?(await Li.writeFile(i,l),i):null}catch(t){return xc.error("Error saving clipboard image:",t),null}}async function FSe(e){try{let t=e||process.cwd(),n=ub.join(t,"clipboard"),r=await Li.readdir(n),o=100,s=50,i=[];for(let a of r)if(a.startsWith("clipboard-")&&(a.endsWith(".png")||a.endsWith(".jpg")||a.endsWith(".webp")||a.endsWith(".heic")||a.endsWith(".heif")||a.endsWith(".tiff")||a.endsWith(".gif")||a.endsWith(".bmp"))){let l=ub.join(n,a),c=await Li.stat(l);i.push({name:a,path:l,atime:c.atimeMs})}if(i.length>o){i.sort((c,u)=>c.atime-u.atime);let a=Math.min(s,i.length-o+s),l=i.slice(0,a);for(let c of l)await Li.unlink(c.path)}}catch{}}var Ilt={UTF8:65001,GBK:936,BIG5:950,LATIN1:1252},LSe=e=>e.startsWith("@")||/\s@/.test(e),Dlt=/[/\\]/,Slt=e=>e.slice(1).trimStart().split(/\s+/u)[0]??"",SY=e=>Dlt.test(Slt(e)),aa=e=>!(!e.startsWith("/")||e.startsWith("//")||e.startsWith("/*")||SY(e)),Blt=/^[/?]btw(?:\s|$)/,Ab=e=>{let t=e.trim();return t.length>0&&Blt.test(t)},gAn=$e("COMMAND_UTILS"),ID=async e=>{let t=(r,o,s)=>new Promise((i,a)=>{let l=s?NSe(r,o,s):NSe(r,o),c="";l.stderr&&l.stderr.on("data",u=>c+=u.toString()),l.on("error",a),l.on("close",u=>{if(u===0)return i();let A=c.trim();a(new Error(`'${r}' exited with code ${u}${A?`: ${A}`:""}`))}),l.stdin?(l.stdin.on("error",a),l.stdin.write(e),l.stdin.end()):a(new Error("Child process has no stdin stream to write to."))}),n={stdio:["pipe","inherit","pipe"]};switch(process.platform){case"win32":return t("cmd",["/c",`chcp ${Ilt.UTF8} >nul && clip`]);case"darwin":return t("pbcopy",[]);case"linux":try{await t("xclip",["-selection","clipboard"],n)}catch(r){try{await t("xsel",["--clipboard","--input"],n)}catch(o){let s=r instanceof Error&&r.code==="ENOENT",i=o instanceof Error&&o.code==="ENOENT";if(s&&i){if(!db(e))throw new Error("Clipboard unavailable: xclip/xsel not found and OSC 52 requires a TTY. Try running inside a terminal emulator.");return}let a=r instanceof Error?r.message:String(r);s&&(a="xclip not found");let l=o instanceof Error?o.message:String(o);if(i&&(l="xsel not found"),db(e))return;throw new Error(`Clipboard unavailable: xclip/xsel failed ("${a}", "${l}") and OSC 52 requires a TTY. Try running inside a terminal emulator.`)}}return;default:throw new Error(`Unsupported platform: ${process.platform}`)}};function OSe(e,t){if(e.startsWith("/"))return null;let r=e.slice(0,t).match(/\s\/([a-zA-Z0-9_:-]*)$/);if(!r||r.index===void 0)return null;let o=r.index+1,i=e.slice(o+1).match(/^[a-zA-Z0-9_:-]*/),a=i?i[0]:"";return t!==o+1+a.length?null:{token:"/"+a,startPos:o,partialCommand:e.slice(o+1,t)}}function PSe(e,t,n){if(!e)return null;let r=e.toLowerCase(),s=t.filter(i=>{if(!i.modelInvocable)return!1;let a=i.name.toLowerCase();return a.startsWith(r)&&(a!==r||!!i.argumentHint)}).sort((i,a)=>{let l=n?.get(i.name),u=(n?.get(a.name)?.usedAt??0)-(l?.usedAt??0);return(a.completionPriority??0)-(i.completionPriority??0)||u||i.name.localeCompare(a.name)})[0];return s?{suffix:s.name.slice(e.length),fullCommand:s.name,command:s,argumentHint:s.argumentHint}:null}var _Se=/(?:^|(?<=\s))\/([a-zA-Z][a-zA-Z0-9:_-]*)/g;function USe(e,t){if(!e)return[];let n=[];for(let i of t){n.push([i.name.toLowerCase(),i]);for(let a of i.altNames??[])n.push([a.toLowerCase(),i])}let r=new Map(n),o=[],s;for(_Se.lastIndex=0;(s=_Se.exec(e))!==null;){let i=s[0],a=s[1],l=s.index,c=l+i.length,u=l>0?e[l-1]:null,A=l===0||u===`
|
|
394
|
-
`,g=r.get(a.toLowerCase()),d=!1;g&&(A?d=g.userInvocable!==!1&&!g.hidden:d=g.modelInvocable===!0),o.push({start:l,end:c,commandName:a,valid:d})}return o}h();function xlt(e){try{return e.getGoalRuntime()}catch(t){if(t instanceof m0)return;throw t}}function HSe(e,t){let n,r=!1,o=xlt(e),s=o?.getSnapshot().goal??void 0,i=e.bindGoalTurnHost({startGoalTurn:async l=>{n=l},preemptGoalTurn:()=>{n=void 0}}),a=o?.subscribe((l,c,u)=>{let A=l.goal;!u?.replayed&&A&&A.goalId===s?.goalId&&A.turnCount>s.turnCount&&(r=!0),s=A??void 0,u?.replayed||t(l,c)});return{take(){let l=n;return n=void 0,l&&(r=!0),l},goalEnd(){if(!r)return;let l=o?.getSnapshot().goal,c=rC(l);return c.outcome==="completed"||!l?.lastReason?c:{...c,reason:l.lastReason}},async release(l=Sre){i();let c=n;n=void 0;try{await e.getGeminiClient()?.interruptGoalTurn(l);let u=o?.getSnapshot().goal;o&&u?.status==="active"&&await o.dispatch({action:"pause",expectedGoalId:u.goalId,expectedRevision:u.revision,reason:l}),o&&c&&await o.releaseTurn(`goal-runtime:${c.permit.turnId}`,{requeue:!1})}catch{}finally{a?.()}}}}h();h();import{randomUUID as xw}from"node:crypto";h();h();function GSe(e){return e.api.totalRequests===0?0:e.api.totalErrors/e.api.totalRequests*100}function jSe(e){return e.api.totalRequests===0?0:e.api.totalLatencyMs/e.api.totalRequests}function zSe(e){return e.tokens.prompt===0?0:e.tokens.cached/e.tokens.prompt*100}var fb=e=>{let{models:t,tools:n,files:r}=e,o=Object.values(t).reduce((E,y)=>E+y.api.totalLatencyMs,0),s=n.totalDurationMs,i=o+s,a=i>0?o/i*100:0,l=i>0?s/i*100:0,c=Object.values(t).reduce((E,y)=>E+y.tokens.cached,0),u=Object.values(t).reduce((E,y)=>E+y.tokens.prompt,0),A=u>0?c/u*100:0,g=n.totalDecisions.accept+n.totalDecisions.reject+n.totalDecisions.modify,d=n.totalCalls>0?n.totalSuccess/n.totalCalls*100:0,m=g>0?n.totalDecisions.accept/g*100:0;return{totalApiTime:o,totalToolTime:s,agentActiveTime:i,apiTimePercent:a,toolTimePercent:l,cacheEfficiency:A,totalDecisions:g,successRate:d,agreementRate:m,totalCachedTokens:c,totalPromptTokens:u,totalLinesAdded:r.totalLinesAdded,totalLinesRemoved:r.totalLinesRemoved}};h();h();h();var DD=(e,t)=>{let r=e.trim().substring(1).trim(),o=r.split(/\s+/),s=o.filter(g=>g),i=t,a,l=0,c=[],u=0;for(let g of s){let d=i.find(m=>m.name===g);if(d||(d=i.find(m=>m.altNames?.includes(g))),d)if(a=d,c.push(d.name),l++,u=r.indexOf(g,u)+g.length,d.subCommands)i=d.subCommands;else break;else break}let A=a?r.slice(u).trim():o.slice(l).join(" ");return{commandToExecute:a,args:A,canonicalPath:c}};h();h();function sM(e){if(e.supportedModes!==void 0)return e.supportedModes;switch(e.kind){case"built-in":return["interactive"];case"file":case"skill":case"mcp-prompt":return["interactive","non_interactive","acp"];default:return["interactive"]}}function WSe(e,t){return e.filter(n=>sM(n).includes(t))}var blt=$e("CLI_COMMANDS"),SD=class e{constructor(t){this.commands=t}static async create(t,n,r){let o=await Promise.allSettled(t.map(l=>l.loadCommands(n))),s=[];for(let l of o)l.status==="fulfilled"?s.push(...l.value):blt.debug("A command loader failed:",l.reason);let i=new Map;for(let l of s){let c=l.name;if(l.extensionName&&i.has(l.name)){let u=`${l.extensionName}.${l.name}`,A=1;for(;i.has(u);)u=`${l.extensionName}.${l.name}${A}`,A++;c=u}i.set(c,{...l,name:c})}if(r&&r.size>0){let l=new Set;for(let c of r){let u=c.trim();u&&l.add(u.toLowerCase())}if(l.size>0)for(let[c,u]of Array.from(i.entries())){let A=l.has(c.toLowerCase()),g=(u.altNames??[]).some(d=>l.has(d.toLowerCase()));(A||g)&&i.delete(c)}}let a=Object.freeze(Array.from(i.values()));return new e(a)}getCommands(){return this.commands}getCommandsForMode(t){return Object.freeze(WSe(this.commands.filter(n=>!n.hidden&&n.userInvocable!==!1),t))}getModelInvocableCommands(){return this.commands.filter(t=>!t.hidden&&t.modelInvocable===!0)}};h();h();h();var FAn=M(Ie(),1);var wlt=["achieved","aborted","failed"];function qSe(e){return wlt.includes(e)}h();import pb from"node:process";import Tlt from"node:os";import{execFile as vlt}from"node:child_process";h();var Al=e=>{let t=e/1073741824;return e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${t.toFixed(2)} GB`},gb=e=>{let n=Date.now()-e,r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60),i=Math.floor(s/24),a=Math.floor(i/7),l=Math.floor(i/30);return l>0?l===1?"1 month ago":`${l} months ago`:a>0?a===1?"1 week ago":`${a} weeks ago`:i>0?i===1?"1 day ago":`${i} days ago`:s>0?s===1?"1 hour ago":`${s} hours ago`:o>0?o===1?"1 minute ago":`${o} minutes ago`:"just now"},jg=e=>e<1e3?`${e}`:e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.floor(e/1e3)}k`,Zn=(e,t)=>{if(e<=0)return"0s";if(e<1e3)return`${Math.round(e)}ms`;let n=e/1e3;if(n<60){let a=n.toFixed(1);return t?.hideTrailingZeros&&a.endsWith(".0")?`${a.slice(0,-2)}s`:`${a}s`}let r=Math.floor(n/3600),o=Math.floor(n%3600/60),s=Math.floor(n%60),i=[];return r>0&&i.push(`${r}h`),o>0&&i.push(`${o}m`),s>0&&i.push(`${s}s`),i.length===0?r>0?`${r}h`:o>0?`${o}m`:`${s}s`:i.join(" ")};h();var $P="
|
|
394
|
+
`,g=r.get(a.toLowerCase()),d=!1;g&&(A?d=g.userInvocable!==!1&&!g.hidden:d=g.modelInvocable===!0),o.push({start:l,end:c,commandName:a,valid:d})}return o}h();function xlt(e){try{return e.getGoalRuntime()}catch(t){if(t instanceof m0)return;throw t}}function HSe(e,t){let n,r=!1,o=xlt(e),s=o?.getSnapshot().goal??void 0,i=e.bindGoalTurnHost({startGoalTurn:async l=>{n=l},preemptGoalTurn:()=>{n=void 0}}),a=o?.subscribe((l,c,u)=>{let A=l.goal;!u?.replayed&&A&&A.goalId===s?.goalId&&A.turnCount>s.turnCount&&(r=!0),s=A??void 0,u?.replayed||t(l,c)});return{take(){let l=n;return n=void 0,l&&(r=!0),l},goalEnd(){if(!r)return;let l=o?.getSnapshot().goal,c=rC(l);return c.outcome==="completed"||!l?.lastReason?c:{...c,reason:l.lastReason}},async release(l=Sre){i();let c=n;n=void 0;try{await e.getGeminiClient()?.interruptGoalTurn(l);let u=o?.getSnapshot().goal;o&&u?.status==="active"&&await o.dispatch({action:"pause",expectedGoalId:u.goalId,expectedRevision:u.revision,reason:l}),o&&c&&await o.releaseTurn(`goal-runtime:${c.permit.turnId}`,{requeue:!1})}catch{}finally{a?.()}}}}h();h();import{randomUUID as xw}from"node:crypto";h();h();function GSe(e){return e.api.totalRequests===0?0:e.api.totalErrors/e.api.totalRequests*100}function jSe(e){return e.api.totalRequests===0?0:e.api.totalLatencyMs/e.api.totalRequests}function zSe(e){return e.tokens.prompt===0?0:e.tokens.cached/e.tokens.prompt*100}var fb=e=>{let{models:t,tools:n,files:r}=e,o=Object.values(t).reduce((E,y)=>E+y.api.totalLatencyMs,0),s=n.totalDurationMs,i=o+s,a=i>0?o/i*100:0,l=i>0?s/i*100:0,c=Object.values(t).reduce((E,y)=>E+y.tokens.cached,0),u=Object.values(t).reduce((E,y)=>E+y.tokens.prompt,0),A=u>0?c/u*100:0,g=n.totalDecisions.accept+n.totalDecisions.reject+n.totalDecisions.modify,d=n.totalCalls>0?n.totalSuccess/n.totalCalls*100:0,m=g>0?n.totalDecisions.accept/g*100:0;return{totalApiTime:o,totalToolTime:s,agentActiveTime:i,apiTimePercent:a,toolTimePercent:l,cacheEfficiency:A,totalDecisions:g,successRate:d,agreementRate:m,totalCachedTokens:c,totalPromptTokens:u,totalLinesAdded:r.totalLinesAdded,totalLinesRemoved:r.totalLinesRemoved}};h();h();h();var DD=(e,t)=>{let r=e.trim().substring(1).trim(),o=r.split(/\s+/),s=o.filter(g=>g),i=t,a,l=0,c=[],u=0;for(let g of s){let d=i.find(m=>m.name===g);if(d||(d=i.find(m=>m.altNames?.includes(g))),d)if(a=d,c.push(d.name),l++,u=r.indexOf(g,u)+g.length,d.subCommands)i=d.subCommands;else break;else break}let A=a?r.slice(u).trim():o.slice(l).join(" ");return{commandToExecute:a,args:A,canonicalPath:c}};h();h();function sM(e){if(e.supportedModes!==void 0)return e.supportedModes;switch(e.kind){case"built-in":return["interactive"];case"file":case"skill":case"mcp-prompt":return["interactive","non_interactive","acp"];default:return["interactive"]}}function WSe(e,t){return e.filter(n=>sM(n).includes(t))}var blt=$e("CLI_COMMANDS"),SD=class e{constructor(t){this.commands=t}static async create(t,n,r){let o=await Promise.allSettled(t.map(l=>l.loadCommands(n))),s=[];for(let l of o)l.status==="fulfilled"?s.push(...l.value):blt.debug("A command loader failed:",l.reason);let i=new Map;for(let l of s){let c=l.name;if(l.extensionName&&i.has(l.name)){let u=`${l.extensionName}.${l.name}`,A=1;for(;i.has(u);)u=`${l.extensionName}.${l.name}${A}`,A++;c=u}i.set(c,{...l,name:c})}if(r&&r.size>0){let l=new Set;for(let c of r){let u=c.trim();u&&l.add(u.toLowerCase())}if(l.size>0)for(let[c,u]of Array.from(i.entries())){let A=l.has(c.toLowerCase()),g=(u.altNames??[]).some(d=>l.has(d.toLowerCase()));(A||g)&&i.delete(c)}}let a=Object.freeze(Array.from(i.values()));return new e(a)}getCommands(){return this.commands}getCommandsForMode(t){return Object.freeze(WSe(this.commands.filter(n=>!n.hidden&&n.userInvocable!==!1),t))}getModelInvocableCommands(){return this.commands.filter(t=>!t.hidden&&t.modelInvocable===!0)}};h();h();h();var FAn=M(Ie(),1);var wlt=["achieved","aborted","failed"];function qSe(e){return wlt.includes(e)}h();import pb from"node:process";import Tlt from"node:os";import{execFile as vlt}from"node:child_process";h();var Al=e=>{let t=e/1073741824;return e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${t.toFixed(2)} GB`},gb=e=>{let n=Date.now()-e,r=Math.floor(n/1e3),o=Math.floor(r/60),s=Math.floor(o/60),i=Math.floor(s/24),a=Math.floor(i/7),l=Math.floor(i/30);return l>0?l===1?"1 month ago":`${l} months ago`:a>0?a===1?"1 week ago":`${a} weeks ago`:i>0?i===1?"1 day ago":`${i} days ago`:s>0?s===1?"1 hour ago":`${s} hours ago`:o>0?o===1?"1 minute ago":`${o} minutes ago`:"just now"},jg=e=>e<1e3?`${e}`:e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.floor(e/1e3)}k`,Zn=(e,t)=>{if(e<=0)return"0s";if(e<1e3)return`${Math.round(e)}ms`;let n=e/1e3;if(n<60){let a=n.toFixed(1);return t?.hideTrailingZeros&&a.endsWith(".0")?`${a.slice(0,-2)}s`:`${a}s`}let r=Math.floor(n/3600),o=Math.floor(n%3600/60),s=Math.floor(n%60),i=[];return r>0&&i.push(`${r}h`),o>0&&i.push(`${o}m`),s>0&&i.push(`${s}s`),i.length===0?r>0?`${r}h`:o>0?`${o}m`:`${s}s`:i.join(" ")};h();var $P="5ed049295";var YSe=$e("STATUS"),Rlt=5e3;function JSe(e){return new Promise(t=>{vlt(e,["--version"],{timeout:Rlt,encoding:"utf-8"},(n,r)=>{if(n){t("unknown");return}t(typeof r=="string"?r.trim():"unknown")})})}async function BY(){return JSe("npm")}async function $Se(){return JSe("git")}async function Qlt(e){if(!e.services.config?.getIdeMode())return"";try{return(await rl.getInstance())?.getDetectedIdeDisplayName()??""}catch{return""}}function VSe(e=!1){let t=pb.env.SANDBOX;return!t||t==="sandbox-exec"?t==="sandbox-exec"?`sandbox-exec (${pb.env.SEATBELT_PROFILE||"unknown"})`:"no sandbox":e?t.replace(/^matilda-(?:code-)?/,""):t}async function klt(e){let t=pb.platform,n=pb.arch,r=Tlt.release(),o=pb.version,s=await BY(),i=VSe(),a=e.services.config?.getModelDisplayName()||"Unknown",l=await Ug(),c=e.services.config?.getAuthType()||"",u=await Qlt(e),A=e.services.config?.getSessionId()||"unknown",g=e.services.config?.getProxy();return{cliVersion:l,osPlatform:t,osArch:n,osRelease:r,nodeVersion:o,npmVersion:s,sandboxEnv:i,modelVersion:a,selectedAuthType:c,ideClient:u,sessionId:A,proxy:g}}async function VP(e){let t=await klt(e),n=Al(pb.memoryUsage().rss),r=VSe(!0),o=t.selectedAuthType==="openai"?e.services.config?.getContentGeneratorConfig():void 0,s=o?.baseUrl,i=o?.apiKeyEnvKey,a=$P&&!["N/A"].includes($P)?$P:void 0,l=e.services.settings?.merged?.fastModel||void 0,c=Mlt(e);return{...t,sandboxEnv:r,memoryUsage:n,baseUrl:s,apiKeyEnvKey:i,gitCommit:a,fastModel:l,lspStatus:c}}function Mlt(e){try{let t=e.services.config?.getLspStatusSnapshot?.();return t?(e.services.config?.getDebugMode?.()&&YSe.debug("LSP status snapshot for /status:",t),Flt(t)):void 0}catch(t){e.services.config?.getDebugMode?.()&&YSe.debug("Unable to read LSP status snapshot for /status:",t);return}}function Flt(e){if(!e.enabled)return"disabled";if(e.initializationError)return`enabled, initialization failed: ${e.initializationError}`;if(e.statusUnavailable)return"enabled, status unavailable";if(e.configuredServers===0)return"enabled, no servers configured";let t=[e.failedServers>0?`${e.failedServers} failed`:"",e.inProgressServers>0?`${e.inProgressServers} starting`:"",e.notStartedServers>0?`${e.notStartedServers} not started`:""].filter(Boolean),n=t.length>0?` (${t.join(", ")})`:"";return`enabled, ${e.readyServers}/${e.configuredServers} ready${n}`}h();import xY from"node:fs/promises";import Nlt from"node:path";var XSe=$e("SESSION_PATHS"),KSe=100;async function ZSe(e){let t=e.services.config,n=t?.getSessionId()||e.session.stats.sessionId||"unknown",r=t?.getContentGeneratorConfig(),o=t?.getWorkingDir()||process.cwd(),s=Zne(r?.openAILoggingDir,o),i=r?.enableOpenAILogging===!0,a=i&&n!=="unknown"?await _lt(s,n):void 0,l=t?.getTranscriptPath()||"",c=t?.getDebugMode()&&n!=="unknown"?Mt.getDebugLogPath(n):"",u=t?.getPlanFilePath()||(n==="unknown"?"":Mt.getPlanFilePath(n)),A=u?await Plt(u):!1,g=[{title:"Session files",entries:[{label:"Session ID",value:n},...l?[{label:"Transcript",value:l}]:[],...c?[{label:"Debug log",value:c}]:[],...A?[{label:"Plan file",value:u}]:[]]}];return i&&g.push({title:"OpenAI logs",entries:[{label:"Directory",value:s},{label:"Latest for session",value:a??"none yet"}]}),{sections:g}}function eBe(e){let t=[];for(let[n,r]of e.sections.entries()){n>0&&t.push(""),t.push(`${r.title}:`);for(let o of r.entries)t.push(` ${o.label}: ${o.value}`)}return t.join(`
|
|
395
395
|
`)}async function _lt(e,t){let n=await Llt(e,r=>/^openai-.*\.json$/.test(r));for(let r of n)try{let o=await xY.readFile(r,"utf-8"),s=JSON.parse(o);if(Ult(s,t))return r}catch(o){if(o instanceof SyntaxError||o.code==="ENOENT")continue;XSe.warn("Error reading OpenAI log file",r,o)}}async function Llt(e,t){try{let n=await xY.readdir(e,{withFileTypes:!0}),r=[];for(let o of n)!o.isFile()||!t(o.name)||Olt(r,Nlt.join(e,o.name));return r}catch(n){return n.code!=="ENOENT"&&XSe.warn("Unable to list OpenAI log directory",e,n),[]}}function Olt(e,t){let n=e.findIndex(r=>t>r);if(n===-1){e.length<KSe&&e.push(t);return}e.splice(n,0,t),e.length>KSe&&e.pop()}async function Plt(e){try{return await xY.access(e),!0}catch{return!1}}function Ult(e,t){if(!e||typeof e!="object")return!1;let n=e.context;if(!n||typeof n!="object")return!1;let r=n;return r.sessionId===t||r.promptId===t}var tBe={name:"status",altNames:["about"],get description(){return C("show version info")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:async e=>{let t=await VP(e);if(e.executionMode!=="interactive")return{type:"message",messageType:"info",content:[`Matilda v${t.cliVersion}`,`Model: ${t.modelVersion}`,`Fast Model: ${t.fastModel??"not set"}`,`Auth: ${t.selectedAuthType}`,`Platform: ${t.osPlatform} ${t.osArch} (${t.osRelease})`,`Node.js: ${t.nodeVersion}`,`Session: ${t.sessionId}`,...t.gitCommit?[`Git commit: ${t.gitCommit}`]:[],...t.ideClient?[`IDE: ${t.ideClient}`]:[],...t.lspStatus?[`LSP: ${t.lspStatus}`]:[]].join(`
|
|
396
396
|
`)};let n={type:"about",systemInfo:t};e.ui.addItem(n,Date.now())},subCommands:[{name:"paths",get description(){return C("show paths for current session files and logs")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:async e=>{let t=await ZSe(e);return{type:"message",messageType:"info",content:eBe(t)}}}]};h();function Hlt(e){switch(e.kind){case"agent":{let t=e.status;switch(t){case"completed":return"completed";case"failed":return`failed: ${e.error??"unknown error"}`;case"cancelled":return"cancelled";case"paused":return e.resumeBlockedReason?`paused (resume blocked): ${e.resumeBlockedReason}`:"paused";case"running":return"running";default:{let n=t;throw new Error(`statusLabel(agent): unknown status: ${JSON.stringify(n)}`)}}}case"shell":{let t=e.status;switch(t){case"completed":return`completed (exit ${e.exitCode??"?"})`;case"failed":return`failed: ${e.error??"unknown error"}`;case"cancelled":return"cancelled";case"running":return"running";default:{let n=t;throw new Error(`statusLabel(shell): unknown status: ${JSON.stringify(n)}`)}}}case"monitor":{let t=`${e.eventCount} event${e.eventCount===1?"":"s"}`,n=e.status;switch(n){case"completed":return e.error?`completed (${e.error}, ${t})`:`completed (exit ${e.exitCode??"?"}, ${t})`;case"failed":return`failed: ${e.error??"unknown error"} (${t})`;case"cancelled":return`cancelled (${t})`;case"running":return`running (${t})`;default:{let r=n;throw new Error(`statusLabel(monitor): unknown status: ${JSON.stringify(r)}`)}}}default:{let t=e;throw new Error(`statusLabel: unknown TaskEntry kind: ${JSON.stringify(t)}`)}}}function Glt(e){switch(e.kind){case"agent":return zR(e);case"shell":return e.command;case"monitor":return e.description;default:{let t=e;throw new Error(`taskLabel: unknown TaskEntry kind: ${JSON.stringify(t)}`)}}}function jlt(e){switch(e.kind){case"agent":return e.agentId;case"shell":return e.shellId;case"monitor":return e.monitorId;default:{let t=e;throw new Error(`taskId: unknown TaskEntry kind: ${JSON.stringify(t)}`)}}}function zlt(e){switch(e.kind){case"agent":case"shell":return e.outputFile;case"monitor":return;default:{let t=e;throw new Error(`taskOutputPath: unknown TaskEntry kind: ${JSON.stringify(t)}`)}}}var nBe={name:"tasks",get description(){return C("List background tasks (text dump \u2014 interactive dialog opens via the footer pill)")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:async e=>{let{config:t}=e.services;if(!t)return{type:"message",messageType:"error",content:"Config not available."};let n=[...t.getBackgroundTaskRegistry().getAll()],r=[...t.getBackgroundShellRegistry().getAll()],o=[...t.getMonitorRegistry().getAll()],s=[...n,...r,...o].sort((l,c)=>l.startTime-c.startTime);if(s.length===0)return{type:"message",messageType:"info",content:"No background tasks."};let i=Date.now(),a=[];e.executionMode==="interactive"&&a.push(C("Tip: focus the Background tasks pill in the footer (use \u2193 from an empty composer) and press Enter for the interactive dialog with detail view + live updates."),""),a.push(`Background tasks (${s.length} total)`,"");for(let l of s){let c=l.endTime??i,u=Zn(c-l.startTime,{hideTrailingZeros:!0}),A=(l.kind==="shell"||l.kind==="monitor")&&l.pid!==void 0?` pid=${l.pid}`:"";a.push(`[${jlt(l)}] ${Hlt(l)} ${u}${A} ${Glt(l)}`);let g=zlt(l);g&&a.push(` output: ${g}`)}return{type:"message",messageType:"info",content:Cm(a.join(`
|
|
397
397
|
`))}}};h();function rBe(e,t){let n=e.endTime??t,r=Zn(n-e.startTime,{hideTrailingZeros:!0}),o=e.meta?.name??e.runId,s=e.currentPhase?` \xB7 ${e.currentPhase}`:"",i=e.agentsDispatched>0?` \xB7 ${e.agentsCompleted}/${e.agentsDispatched} agents`:"",a=e.phases.length>0?` \xB7 ${e.phases.length} ${e.phases.length===1?"phase":"phases"}`:"",l=e.status==="failed"&&e.error?` \u2014 ${e.error.slice(0,80)}`:"";return` ${e.runId.padEnd(20)} ${e.status.padEnd(10)} ${r.padStart(8)} ${o}${s}${i}${a}${l}`}function Wlt(e,t){let n=[],r=e.endTime??t,o=Zn(r-e.startTime,{hideTrailingZeros:!0});if(n.push(`Workflow ${e.runId}`),e.meta?.name&&n.push(` name : ${e.meta.name}`),e.meta?.description&&n.push(` description : ${e.meta.description}`),e.meta?.whenToUse&&n.push(` whenToUse : ${e.meta.whenToUse}`),n.push(` status : ${e.status}`),n.push(` runtime : ${o}`),e.currentPhase&&n.push(` currentPhase: ${e.currentPhase}`),n.push(` agents : ${e.agentsCompleted}/${e.agentsDispatched}`),e.error&&n.push(` error : ${e.error}`),e.phases.length>0){n.push(""),n.push(` Phases (${e.phases.length})`);for(let s of e.phases)n.push(` \xB7 ${s}`)}if(e.recentLogs.length>0){n.push(""),n.push(` Logs (last ${e.recentLogs.length})`);for(let s of e.recentLogs)n.push(` ${s}`)}return n}var oBe={name:"workflows",get description(){return C("List active and completed workflow runs (text dump \u2014 interactive dialog opens via the footer pill)")},get argumentHint(){return C("[runId]")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:async(e,t)=>{let{config:n}=e.services;if(!n)return{type:"message",messageType:"error",content:"Config not available."};let r=n.getWorkflowRunRegistry(),o=r.list(),s=(t??"").trim();if(s.length>0){let u=r.get(s);return u?{type:"message",messageType:"info",content:Wlt(u,Date.now()).join(`
|
|
@@ -860,7 +860,7 @@ ${Z}
|
|
|
860
860
|
`).filter(n=>n.trim()!=="");try{await PZ.unlink(UZ)}catch{t.push("Warning: Could not delete temporary warnings file.")}return t}catch(e){return e instanceof Error&&"code"in e&&e.code==="ENOENT"?[]:[`Error checking/reading warnings file: ${vr(e)}`]}}h();import O1t from"node:fs/promises";import P1t from"node:path";var U1t={id:"root-directory",check:async e=>{try{let t=await O1t.realpath(e.workspaceRoot),n="Warning: You are running Matilda in the root directory. Your entire folder structure will be used for context. It is strongly recommended to run in a project-specific directory.";return P1t.dirname(t)===t?n:null}catch{return"Could not verify the current directory due to a file system error."}}},H1t={id:"ripgrep-availability",check:async e=>{if(!e.useRipgrep)return null;try{return await H_(e.useBuiltinRipgrep)?null:"Ripgrep not available: Please install ripgrep globally to enable faster file content search. Falling back to built-in grep."}catch(t){return`Ripgrep not available: ${t instanceof Error?t.message:"Unknown error"}. Falling back to built-in grep.`}}},G1t=[U1t,H1t];async function R8e(e){return(await Promise.all(G1t.map(n=>n.check(e)))).filter(n=>n!==null)}h();import*as nv from"node:fs";import*as Q8e from"node:path";function k8e(e){process.on("uncaughtExceptionMonitor",(t,n)=>{HZ(t,n,e)})}function HZ(e,t,n){let r=z1t(e,t,n);try{GN(),nv.writeSync(2,`Matilda crashed: ${j1t(e)}
|
|
861
861
|
${r?`The full error is saved in ${r}
|
|
862
862
|
`:""}`)}catch{}}function j1t(e){let n=(e instanceof Error?e.message:String(e)).split(`
|
|
863
|
-
`,1)[0].trim();return n.length>200?`${n.slice(0,199)}\u2026`:n}function z1t(e,t,n,r=new Date){try{let o;try{o=n.sessionId?.()}catch{o=void 0}let s=Mt.getGlobalCrashDir();nv.mkdirSync(s,{recursive:!0});let i=r.toISOString().replace(/[:.]/g,"-"),a=Q8e.join(s,`${i}-${o??`pid-${process.pid}`}.log`),l=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);return nv.writeFileSync(a,[`time: ${r.toISOString()}`,`origin: ${t}`,`matilda: ${n.version??"0.21.13-
|
|
863
|
+
`,1)[0].trim();return n.length>200?`${n.slice(0,199)}\u2026`:n}function z1t(e,t,n,r=new Date){try{let o;try{o=n.sessionId?.()}catch{o=void 0}let s=Mt.getGlobalCrashDir();nv.mkdirSync(s,{recursive:!0});let i=r.toISOString().replace(/[:.]/g,"-"),a=Q8e.join(s,`${i}-${o??`pid-${process.pid}`}.log`),l=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);return nv.writeFileSync(a,[`time: ${r.toISOString()}`,`origin: ${t}`,`matilda: ${n.version??"0.21.13-preview.0"??"unknown"}`,`node: ${process.version}`,`platform: ${process.platform} ${process.arch}`,`pid: ${process.pid}`,`session: ${o??"unknown"}`,"",l,""].join(`
|
|
864
864
|
`),{mode:384}),a}catch{return}}h();var W1t=[/MaxListenersExceededWarning.*AbortSignal/];function q1t(e){let t=`${e.name}: ${e.message}`;return W1t.some(n=>n.test(t))}function Y1t(){let e=t=>!!t&&t!=="0"&&t.toLowerCase()!=="false";return e(process.env.DEBUG)||e(process.env.MATILDA_DEBUG)}var GZ=null;function M8e(){if(GZ)return;let e=[...process.listeners("warning")];GZ=t=>{if(!(!Y1t()&&q1t(t)))for(let n of e)try{n(t)}catch{}},process.removeAllListeners("warning"),process.on("warning",GZ)}h();function F8e(e){return e.promptInteractive?!1:J1t(e.prompt??e.query??"")}function J1t(e){let t=e.trim();return t==="/help"||t==="/?"}function N8e(){return["/help is an in-session command. Start a session with `matilda` after `matilda auth login`.",""," matilda --help CLI flags and subcommands"," matilda auth login Sign in"," matilda Start an interactive session"].join(`
|
|
865
865
|
`)}h();var $1t="Warning: running headless with --bogan / approval-mode=bogan and no sandbox. All tool calls (shell, write, edit) auto-execute at this process's privilege level. Enable a sandbox via --sandbox / MATILDA_SANDBOX, or set MATILDA_CODE_SUPPRESS_BOGAN_WARNING=1 to silence this notice.";function _8e(e,t=process.env){return e.getApprovalMode()!=="bogan"||e.getSandbox()||t.SANDBOX||V1t(t.MATILDA_CODE_SUPPRESS_BOGAN_WARNING)?null:$1t}function V1t(e){return e==="1"||e==="true"}h();var nB=$e("EARLY_INPUT"),e1=64*1024,Cu={chunks:[],totalBytes:0,captured:!1},t1=null,n1=null,Cj=!1,fy=Buffer.alloc(0);function L8e(e,t){if(t>=e.length||e[t]!==27)return"user";let n=t+1;if(n>=e.length)return"incomplete";let r=e[n];if(r===80||r===95||r===94||r===93)return"terminal";if(r===91){let o=t+2;if(o>=e.length)return"incomplete";let s=e[o];return s===63||s===62?"terminal":"user"}return"user"}function K1t(e,t){if(t>=e.length||e[t]!==27)return{nextIndex:t+1,complete:!0};let n=t+1;if(n>=e.length)return{nextIndex:n,complete:!1};let r=e[n];if(r===93){let o=t+2;for(;o<e.length;){if(e[o]===7)return{nextIndex:o+1,complete:!0};if(e[o]===27&&o+1<e.length&&e[o+1]===92)return{nextIndex:o+2,complete:!0};o++}return{nextIndex:e.length,complete:!1}}if(r===80||r===95||r===94){let o=t+2;for(;o<e.length;){if(e[o]===27&&o+1<e.length&&e[o+1]===92)return{nextIndex:o+2,complete:!0};o++}return{nextIndex:e.length,complete:!1}}if(r===91){let o=t+2;for(;o<e.length;){let s=e[o];if(s>=64&&s<=126)return{nextIndex:o+1,complete:!0};o++}return{nextIndex:e.length,complete:!1}}return{nextIndex:t+1,complete:!0}}function X1t(e){let t=Buffer.allocUnsafe(e.length),n=0,r=0;for(;r<e.length;){if(e[r]===27){let o=L8e(e,r);if(o==="incomplete")return{filtered:t.subarray(0,n),trailingPartialTerminalResponse:e.subarray(r)};if(o==="terminal"){let s=K1t(e,r);if(!s.complete)return{filtered:t.subarray(0,n),trailingPartialTerminalResponse:e.subarray(r)};r=s.nextIndex;continue}}t[n++]=e[r],r++}return{filtered:t.subarray(0,n),trailingPartialTerminalResponse:Buffer.alloc(0)}}function Z1t(e){return e.length===0?!1:e.length===1&&e[0]===27?!0:L8e(e,0)==="user"}function O8e(){if(Cj||!process.stdin.isTTY){process.stdin.isTTY||nB.debug("Early input capture skipped: stdin is not a TTY");return}if(process.env.MATILDA_CODE_DISABLE_EARLY_CAPTURE==="1"){nB.debug("Early input capture disabled by environment variable");return}Cj=!0,Cu={chunks:[],totalBytes:0,captured:!1},fy=Buffer.alloc(0),nB.debug("Starting early input capture"),t1=e=>{if(Cu.captured)return;if(Cu.totalBytes>=e1){nB.warn(`Early input capture buffer full (${e1} bytes). Stopping capture; additional keystrokes during startup will be lost.`),P8e();return}let t=fy.length>0?Buffer.concat([fy,e]):e;fy=Buffer.alloc(0);let{filtered:n,trailingPartialTerminalResponse:r}=X1t(t);if(r.length>0&&(fy=Buffer.from(r)),n.length>0)if(Cu.totalBytes+n.length>e1){let s=n.subarray(0,e1-Cu.totalBytes);Cu.chunks.push(Buffer.from(s)),Cu.totalBytes+=s.length,nB.debug(`Buffer truncated at ${e1} bytes`)}else Cu.chunks.push(Buffer.from(n)),Cu.totalBytes+=n.length,nB.debug(`Captured ${n.length} bytes (total: ${Cu.totalBytes})`)},n1=process.stdin,n1.on("data",t1)}function P8e(){!Cj||!t1||!n1||(n1.removeListener("data",t1),n1=null,t1=null,Cj=!1,Cu.captured=!0,nB.debug(`Stopped early input capture: ${Cu.totalBytes} bytes`))}function e_t(){let e=[...Cu.chunks];Z1t(fy)&&e.push(Buffer.from(fy));let t=e.length>0?Buffer.concat(e):Buffer.alloc(0);return Cu.chunks=[],Cu.totalBytes=0,fy=Buffer.alloc(0),t}function jZ(){return P8e(),e_t()}h();var U8e=M(l7(),1);var cg=$e("PRECONNECT"),rv=!1,t_t=qre();function n_t(){return process.env.NODE_EXTRA_CA_CERTS?(cg.debug("Skipping preconnect: custom CA certificate configured"),!0):!1}function r_t(){return process.env.SANDBOX!==void 0}function o_t(e){let t=e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return t_t.some(n=>{let r=n.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return t===r||t.startsWith(r+"/")})}function s_t(e){if(e&&/^https?:\/\//i.test(e)){if(o_t(e))return e;cg.debug("Skipping preconnect: resolved baseUrl is not a default URL")}}function H8e(e={}){if(rv)return;if(process.env.MATILDA_CODE_DISABLE_PRECONNECT==="1"){cg.debug("Preconnect disabled by environment variable"),rv=!0;return}if(r_t()){cg.debug("Skipping preconnect: sandbox mode detected"),rv=!0;return}if(n_t()){rv=!0;return}if(Are()!=="node"){cg.debug("Skipping preconnect: unsupported runtime"),rv=!0;return}if(!e.proxy){cg.debug("Skipping preconnect dispatcher: no proxy configured");return}let t=e.proxy,n=s_t(e.resolvedBaseUrl);if(!n){cg.debug("No target URL for preconnect");return}rv=!0,cg.debug(`Preconnecting to: ${n}`);try{let r=fre(t);(0,U8e.fetch)(n,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"MatildaCode-Preconnect/1.0"},dispatcher:r}).then(()=>{cg.debug("Preconnect completed")}).catch(o=>{let s=$z(String(o));cg.debug(`Preconnect failed (ignored): ${s}`)})}catch(r){let o=$z(String(r));cg.debug(`Preconnect failed (ignored): ${o}`)}}h();async function G8e(e,t,n){try{let r=t.getModelsConfig().getCurrentAuthType();if(!r)throw new Error("No auth type is selected. Please configure an auth type (e.g. via settings or `--auth-type`) before running in non-interactive mode.");let o=r,s=n.merged.security?.auth?.enforcedType;if(s&&s!==o){let i=`The configured auth type is ${s}, but the current auth type is ${o}. Please re-authenticate with the correct type.`;throw new Error(i)}if(!e){let i=px(o,t);if(i!=null)throw new Error(i)}return await t.refreshAuth(o),t}catch(r){let o=t.getOutputFormat();if(o==="json"||o==="stream-json"){let s;o==="json"?s=new ww(t):s=new Ym(t,t.getIncludePartialMessages());let i=r instanceof Error?r.message:String(r);s.emitResult({isError:!0,errorMessage:i,durationMs:0,apiDurationMs:0,numTurns:0,usage:void 0}),await Fl(),process.exit(1)}it(r instanceof Error?r.message:String(r)),process.exit(1)}}h();var z8e=M(Ie(),1);var rB=M(re(),1);var i_t={getShouldUseNodePtyShell:()=>!1,getIdeMode:()=>!1,isTrustedFolder:()=>!1,getToolRegistry:()=>({getTool:()=>{}}),getContentGenerator:()=>({useSummarizedThinking:()=>!1})},a_t={merged:{ui:{}}};function l_t({sessionService:e,onSelect:t,onCancel:n,currentBranch:r,initialSessions:o}){let{exit:s}=J4(),[i,a]=(0,z8e.useState)(!1),l=()=>{a(!0),s()};return i?(0,rB.jsx)(S,{}):(0,rB.jsx)(qf.Provider,{value:i_t,children:(0,rB.jsx)(BD.Provider,{value:a_t,children:(0,rB.jsx)(IN,{sessionService:e,onSelect:c=>{t(c),l()},onCancel:()=>{n(),l()},currentBranch:r,centerSelection:!0,initialSessions:o,enablePreview:!0})})})}function j8e(){process.stdout.write("\x1B[2J\x1B[H")}async function zZ(e=process.cwd(),t){let n=new yi(e);if(!await n.loadLastSession()){Bt("No sessions found. Start a new session with `matilda`.");return}j8e();let o=process.stdin.isRaw;return process.stdin.isTTY&&!o&&process.stdin.setRawMode(!0),new Promise(s=>{let i,{unmount:a,waitUntilExit:l}=QQ((0,rB.jsx)(sU,{kittyProtocolEnabled:!1,pasteWorkaround:process.platform==="win32"||parseInt(process.versions.node.split(".")[0],10)<20,children:(0,rB.jsx)(l_t,{sessionService:n,onSelect:c=>{i=c},onCancel:()=>{i=void 0},currentBranch:w_(e),initialSessions:t})}),{exitOnCtrlC:!1});l().then(()=>{a(),j8e(),process.stdin.isTTY&&!o&&!i&&process.stdin.setRawMode(!1),s(i)})})}h();import{createReadStream as c_t,watchFile as u_t,unwatchFile as d_t,statSync as W8e}from"node:fs";import{createInterface as A_t}from"node:readline";var Sh=$e("REMOTE_INPUT"),Ej=class{submitFn=null;confirmationHandler=null;queue=[];processing=!1;active=!0;bytesRead=0;reading=!1;filePath;retryTimer=null;pollIntervalMs;constructor(t,n){this.filePath=t,this.pollIntervalMs=n?.pollIntervalMs??500,this.startWatching()}setSubmitFn(t){this.submitFn=t,this.processQueue()}setConfirmationHandler(t){this.confirmationHandler=t}notifyIdle(){this.queue.length>0&&!this.processing&&this.processQueue()}startWatching(){try{let t=W8e(this.filePath);this.bytesRead=t.size}catch{this.bytesRead=0}u_t(this.filePath,{interval:this.pollIntervalMs},()=>{this.active&&this.readNewLines()}),Sh.debug(`RemoteInput: watching ${this.filePath}`)}checkForNewInput(){return this.readNewLines()}readNewLines(){if(!this.active||this.reading)return Promise.resolve();let t;try{t=W8e(this.filePath).size}catch{return Promise.resolve()}if(t<=this.bytesRead)return Promise.resolve();this.reading=!0;let n=c_t(this.filePath,{start:this.bytesRead,encoding:"utf-8"}),r=A_t({input:n,crlfDelay:1/0});return r.on("line",o=>{let s=o.trim();if(s)try{let i=JSON.parse(s);i&&i.type==="confirmation_response"&&typeof i.request_id=="string"&&typeof i.allowed=="boolean"?(Sh.debug(`RemoteInput: confirmation_response for ${i.request_id} (allowed=${i.allowed})`),this.confirmationHandler?.(i.request_id,i.allowed)):i&&i.type==="submit"&&typeof i.text=="string"?(Sh.debug(`RemoteInput: queued command: ${i.text.slice(0,50)}...`),this.queue.push(i)):Sh.warn(`RemoteInput: unknown command type: ${String(i?.type)}`)}catch{Sh.warn(`RemoteInput: failed to parse line: ${s}`)}}),new Promise(o=>{r.on("close",()=>{this.bytesRead=t,this.reading=!1,this.processQueue(),o()})})}async processQueue(){if(!(this.processing||!this.submitFn||this.queue.length===0)){this.processing=!0,this.retryTimer&&(clearTimeout(this.retryTimer),this.retryTimer=null);try{for(;this.queue.length>0&&this.active&&this.submitFn;){let t=this.queue[0];Sh.debug(`RemoteInput: submitting: ${t.text.slice(0,50)}...`);try{if(await this.submitFn(t.text)===!1){Sh.debug("RemoteInput: TUI busy, will retry on idle"),this.scheduleRetry();break}this.queue.shift()}catch(n){Sh.error("RemoteInput: submit failed:",n),this.queue.shift()}this.queue.length>0&&await new Promise(n=>setTimeout(n,500))}}finally{this.processing=!1}}}scheduleRetry(){this.retryTimer||(this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.queue.length>0&&!this.processing&&this.processQueue()},2e3))}shutdown(){this.active=!1,d_t(this.filePath),this.retryTimer&&clearTimeout(this.retryTimer),this.queue.length=0,Sh.debug("RemoteInput: shut down")}};h();var Kd="\x1B[",ov=`${Kd}2K`,f_t=`${Kd}1A`,g_t=`${Kd}1B`,qZ=`${Kd}G`,p_t=new RegExp(`(?:${q8e(ov+f_t)})+${q8e(ov+qZ)}`,"g");function q8e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y8e(e,t){let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n}var yj={stdoutWriteCount:0,stdoutBytes:0,clearTerminalCount:0,eraseLinesOptimizedCount:0};function m_t(e,t){if(typeof e=="string"){let n=typeof t=="string"?t:void 0;return Buffer.byteLength(e,n)}return e.byteLength}function WZ(e,t,n){if(!e.startsWith(Kd,t))return t;let r=t+Kd.length,o=r;for(;r<e.length&&e[r]>="0"&&e[r]<="9";)r++;return r>o&&e[r]===n?r+1:t}function h_t(e){for(let t=0;t<e.length;t++)if(e.startsWith(Kd,t)){for(t+=Kd.length;t<e.length&&"0123456789;:".includes(e[t]);)t++;if(e[t]!=="m")return!1}else if(e.startsWith("\x1B]8;",t)){for(t+=4;t<e.length&&e.charCodeAt(t)>=32&&e.charCodeAt(t)!==127;)t++;if(e[t]==="\x07")continue;if(!e.startsWith("\x1B\\",t))return!1;t++}else{let n=e.charCodeAt(t);if(n<32&&e[t]!==`
|
|
866
866
|
`||n>=127&&n<=159)return!1}return!0}function C_t(e,t){if(!t||t<3)return;let n=0;if(e.startsWith(co.cursorHide)){n=WZ(e,co.cursorHide.length,"B");let c=co.cursorTo(0);if(!e.startsWith(c,n))return;n+=c.length}let r=e.slice(0,n),o=co.eraseLines(t);if(!e.startsWith(o,n))return;n+=o.length;let s=e.length;if(e.endsWith(co.cursorShow)){let c=s-co.cursorShow.length,u=e.lastIndexOf(Kd,c-1);if(u<n||WZ(e,u,"G")!==c)return;s=u;let A=e.lastIndexOf(Kd,s-1);A>=n&&WZ(e,A,"A")===s&&(s=A)}let i=e.slice(n,s),a=e.slice(s),l=i.split(`
|
|
@@ -928,7 +928,7 @@ ${u.text}`}),"blob"in u&&u.blob&&c.push(J_({inlineData:{mimeType:u.mimeType??"ap
|
|
|
928
928
|
${o.join(`
|
|
929
929
|
`)}
|
|
930
930
|
---
|
|
931
|
-
${r}`}var wze=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function Tze(e){let t;try{t=new URL(e)}catch{throw je.invalidParams(void 0,"Skill sourceUrl must be a valid URL")}if(t.protocol!=="https:")throw je.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(!wze.has(t.hostname))throw je.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function vze(e){let t=new URL(e);if(t.protocol!=="https:")throw je.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(t.hostname!=="github.com")return null;let n=t.pathname.split("/").filter(Boolean);if(n.length<5||n[2]!=="blob")return null;let r=n[0],o=n[1],s=n[3],i=n.slice(4);return!r||!o||!s||i.length===0?null:{owner:r,repo:o,ref:s,filePath:i.join("/")}}function gUt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function pUt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function wte(e,t,n){let r=e.subarray(t,t+n),o=r.indexOf(0),s=o>=0?o:r.length;return Buffer.from(r.subarray(0,s)).toString("utf8").trim()}function mUt(e,t){let n=wte(e,t+124,12);return n?Number.parseInt(n,8):0}function hUt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function CUt(e,t){let n=wte(e,t,100),r=wte(e,t+345,155);return r?`${r}/${n}`:n}function EUt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var h1=100*1024*1024,Rze=500*1024*1024,yUt=16,IUt=2e3,oz=class extends Error{};async function DUt(e,t,n={}){let r=n.maxCompressedBytes??h1,o=n.maxDecompressedBytes??Rze;if(e.length>r)throw je.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await YPt(Ize.from([Buffer.from(e)]),$Pt(),new Dze({write(A,g,d){if(u+=A.length,u>o){d(new oz);return}c.push(A),d()}})),s=Buffer.concat(c)}catch(c){throw c instanceof oz?je.invalidParams(void 0,"Decompressed skill archive exceeds the maximum allowed size"):je.invalidParams(void 0,`Failed to decompress skill archive: ${c instanceof Error?c.message:String(c)}`)}let i=t.replace(/^\/+|\/+$/g,""),a=i&&i!=="."?`${i}/`:"",l=[];for(let c=0;c+512<=s.length&&!hUt(s,c);){let u=CUt(s,c),A=String.fromCharCode(s[c+156]||0),g=mUt(s,c),d=c+512,m=d+Math.ceil(g/512)*512;if(A==="0"||A==="\0"){let E=EUt(u);if(E.startsWith(a)){let y=E.slice(a.length);y&&l.push({relativePath:y,content:s.subarray(d,d+g)})}}c=m}return l}var SUt=[".githubusercontent.com",".github.com"];function BUt(e){return wze.has(e)?!0:SUt.some(t=>e.endsWith(t))}async function Qte(e,t={},n=5){let r=e;for(let o=0;o<=n;o+=1){let s=await fetch(r,{...t,redirect:"manual"});if(s.status<300||s.status>=400)return s;let i=s.headers?.get("location");if(!i)return s;let a;try{a=new URL(i,r)}catch{throw je.invalidParams(void 0,"Skill download redirected to an invalid URL")}if(a.protocol!=="https:"||!BUt(a.hostname))throw je.invalidParams(void 0,"Skill download redirected to a disallowed host");r=a.toString()}throw je.invalidParams(void 0,"Skill download exceeded the maximum number of redirects")}async function Qze(e,t){let n=e.body;if(!n){let l=new Uint8Array(await e.arrayBuffer());if(l.byteLength>t)throw je.invalidParams(void 0,"Skill download exceeds the maximum allowed size");return l}let r=n.getReader(),o=[],s=0;for(;;){let{done:l,value:c}=await r.read();if(l)break;if(c){if(s+=c.byteLength,s>t)throw await r.cancel(),je.invalidParams(void 0,"Skill download exceeds the maximum allowed size");o.push(c)}}let i=new Uint8Array(s),a=0;for(let l of o)i.set(l,a),a+=l.byteLength;return i}async function kze(e){let t=await Qte(e);if(!t.ok)throw je.invalidParams(void 0,`Failed to download skill (${t.status})`);let n=t.headers?.get("content-length");if(n){let r=Number.parseInt(n,10);if(Number.isFinite(r)&&r>h1)throw je.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return Qze(t,h1)}async function xUt(e){let t=vze(e),n=t?gUt(t):e,r=await kze(n);return{skillContent:Buffer.from(r).toString("utf8"),files:[{relativePath:"SKILL.md",content:r}]}}async function bUt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,r=await Qte(n,{headers:{"User-Agent":"matilda-code"}});if(!r.ok)throw je.invalidParams(void 0,`Failed to download GitHub skill archive (${r.status})`);let o=r.headers?.get("content-length");if(o){let s=Number.parseInt(o,10);if(Number.isFinite(s)&&s>h1)throw je.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return DUt(await Qze(r,h1),t)}async function wUt(e,t){let n=pUt(t),r=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,o=await Qte(r,{headers:{Accept:"application/vnd.github+json","User-Agent":"matilda-code"}});if(!o.ok)throw je.invalidParams(void 0,`Failed to list GitHub skill files (${o.status})`);let s=await o.json();if(!Array.isArray(s))throw je.invalidParams(void 0,"GitHub skill URL must point to a directory-backed SKILL.md file");return s}async function Mze(e,t,n="",r=0,o={files:0,bytes:0}){if(r>yUt)throw je.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await wUt(e,t),i=[];for(let a of s){let l=oi(a),c=_p(l.name,"github.name"),u=_p(l.path,"github.path"),A=_p(l.type,"github.type"),g=n?so.posix.join(n,c):c;if(A==="dir"){i.push(...await Mze(e,u,g,r+1,o));continue}if(A!=="file")continue;if(o.files+=1,o.files>IUt)throw je.invalidParams(void 0,"Skill directory contains too many files");let d=_p(l.download_url,"github.download_url");Tze(d);let m=await kze(d);if(o.bytes+=m.length,o.bytes>Rze)throw je.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:g,content:m})}return i}async function TUt(e,t){let n=await Mze(e,t).catch(r=>(nc.warn("GitHub API directory listing failed, falling back to archive download:",r),null));return n||bUt(e,t)}async function vUt(e){Tze(e);let t=vze(e);if(!t||so.posix.basename(t.filePath)!=="SKILL.md")return xUt(e);let n=so.posix.dirname(t.filePath),r=await TUt(t,n),o=r.find(s=>s.relativePath==="SKILL.md");if(!o)throw je.invalidParams(void 0,"GitHub skill directory does not contain SKILL.md");return{skillContent:Buffer.from(o.content).toString("utf8"),files:r}}function RUt(e,t){let n=so.resolve(e),r=so.resolve(e,t);if(r!==n&&!r.startsWith(n+so.sep))throw je.invalidParams(void 0,`Invalid skill file path: ${t}`);return r}function mze(e,t){let n=so.resolve(e),r=so.resolve(e,t);if(!r.startsWith(n+so.sep))throw je.invalidParams(void 0,"Invalid skill.slug");return r}function QUt(e,t){if(typeof e.documentationUrl=="string")return e.documentationUrl;if(typeof e.documentationUrl=="function")try{return e.documentationUrl(t)}catch{return}}function kUt(e){return typeof oi(e).id=="string"}function MUt(e,t){if(!t)return;let r=oi(e.env)[t];return typeof r=="string"&&r.length>0?r:void 0}function FUt(e,t){let r=oi(e.modelProviders)[t];return Array.isArray(r)?r.filter(kUt):[]}function Fze(e,t){let n=v_(e);return n?FUt(t,e.protocol).filter(n):[]}function Nze(e,t,n){let r=typeof n[0]?.envKey=="string"?n[0].envKey:e.envKey;return MUt(t,r)}function NUt(e,t){let n=Fze(e,t),r=Nze(e,t,n);if(!r&&n.length===0)return;let o=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:wa(e);return{baseUrl:rz(o),...r?{hasApiKey:!0}:{},...n.length>0?{modelIds:n.map(s=>s.id)}:{}}}function _Ut(e,t){return Nze(e,t,Fze(e,t))}function LUt(e,t){let n=wa(e),r=NUt(e,t);return{id:e.id,label:e.label,description:e.description,protocol:e.protocol,baseUrl:e.baseUrl,defaultModelIds:jre(e),models:e.models,apiKeyPlaceholder:e.apiKeyPlaceholder,documentationUrl:QUt(e,n),uiGroup:e.uiGroup??"third-party",uiLabels:e.uiLabels,...r?{existingConfig:r}:{}}}function OUt(e,t,n){let r=wa(e),o=yy(t.apiKey,"apiKey")??n;if(!o)throw je.invalidParams(void 0,"Invalid or missing apiKey");let s=e.validateApiKey?.(o,r);if(s)throw je.invalidParams(void 0,s);return{baseUrl:r,apiKey:o}}function PUt(e){if(e!==void 0){if(e==="user")return"User";if(e==="workspace")return"Workspace";throw je.invalidParams(void 0,"Invalid scope for provider connect")}}function UUt(e,t){let n=e;for(let r of t.split(".")){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[r]}if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"||Array.isArray(n))return n}function bte(e){let t={};for(let n of xze){let r=UUt(e,n);r!==void 0&&(t[n]=r)}return t}function HUt(e,t){let n=Bze[e];switch(n.type){case"boolean":if(typeof t!="boolean")throw je.invalidParams(void 0,`${e} must be a boolean`);return t;case"number":if(typeof t!="number"||!Number.isFinite(t))throw je.invalidParams(void 0,`${e} must be a number`);if(n.min!==void 0&&t<n.min)throw je.invalidParams(void 0,`${e} must be at least ${n.min}`);return t;case"enum":{let r=n.values;if(typeof t!="string"||!r?.includes(t))throw je.invalidParams(void 0,`${e} must be one of ${r?.join(", ")}`);return t}case"string":{if(t===void 0)return;if(typeof t!="string")throw je.invalidParams(void 0,`${e} must be a string`);let r=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g;return t.replace(r," ").trim()||void 0}default:throw je.invalidParams(void 0,`${e} has an unsupported setting type`)}}function ug(e){if(e!==void 0){if(!Array.isArray(e))throw je.invalidParams(void 0,"Expected an array of strings");return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean)}}function AB(e){if(e===void 0)return;let t=oi(e),n={};for(let[r,o]of Object.entries(t))typeof o=="string"&&r.trim()&&(n[r.trim()]=o);return n}function m1(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number.parseInt(String(e),10);if(!Number.isFinite(t)||t<=0)throw je.invalidParams(void 0,"Expected a positive number");return t}function GUt(e){let t=oi(e),n=t.transport;if(n!=="stdio"&&n!=="http"&&n!=="sse")throw je.invalidParams(void 0,"MCP transport must be stdio, http, or sse");let r={transport:n},o=t.description;typeof o=="string"&&o.trim()&&(r.description=o.trim());let s=t.cwd;typeof s=="string"&&s.trim()&&(r.cwd=s.trim());let i=m1(t.timeout);if(i!==void 0&&(r.timeout=i),typeof t.trust=="boolean"&&(r.trust=t.trust),r.includeTools=ug(t.includeTools),r.excludeTools=ug(t.excludeTools),n==="stdio"){let c=t.command;if(typeof c!="string"||!c.trim())throw je.invalidParams(void 0,"Stdio MCP servers require a command");return r.command=c.trim(),r.args=ug(t.args),r.env=AB(t.env),r}let l=t[n==="http"?"httpUrl":"url"];if(typeof l!="string"||!l.trim())throw je.invalidParams(void 0,`${n.toUpperCase()} MCP servers require a URL`);return n==="http"?r.httpUrl=l.trim():r.url=l.trim(),r.headers=AB(t.headers),r}function jUt(e){let t={};for(let n of["timeout","trust","description","includeTools","excludeTools"])e[n]!==void 0&&(t[n]=e[n]);return e.transport==="stdio"?(t.command=e.command,e.args!==void 0&&(t.args=e.args),e.cwd!==void 0&&(t.cwd=e.cwd),e.env!==void 0&&(t.env=e.env)):e.transport==="http"?(t.httpUrl=e.httpUrl,e.headers!==void 0&&(t.headers=e.headers)):(t.url=e.url,e.headers!==void 0&&(t.headers=e.headers)),t}function zUt(e){let t=oi(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:AB(t.headers),timeout:m1(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:ug(t.includeTools),excludeTools:ug(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:AB(t.headers),timeout:m1(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:ug(t.includeTools),excludeTools:ug(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:ug(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:AB(t.env),timeout:m1(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:ug(t.includeTools),excludeTools:ug(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var sz="__redacted__";function WUt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(r=>[r,sz]));return{...e,env:t(e.env),headers:t(e.headers)}}function qUt(e,t){let n=(r,o)=>{if(!r)return r;let s=oi(o),i={};for(let[a,l]of Object.entries(r)){if(l!==sz){i[a]=l;continue}let c=s[a];typeof c=="string"&&(i[a]=c)}return i};return{...e,env:n(e.env,t.env),headers:n(e.headers,t.headers)}}function hze(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,sz]))}function Cze(e,t){if(!e)return e;let n=oi(t),r={};for(let[o,s]of Object.entries(e)){if(s!==sz){r[o]=s;continue}let i=n[o];typeof i=="string"&&(r[o]=i)}return r}function YUt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:hze(t.env)}:{},...t.headers?{headers:hze(t.headers)}:{}}))}}function JUt(e,t){let n=Array.isArray(t.hooks)?t.hooks:[];return{...e,hooks:e.hooks.map((r,o)=>{let s=oi(n[o]);return{...r,...r.env?{env:Cze(r.env,s.env)}:{},...r.headers?{headers:Cze(r.headers,s.headers)}:{}}})}}function g1(e,t){let n=oi(e.mcpServers);return Object.entries(n).map(([r,o])=>{try{let s=zUt(o);return s?{name:r,scope:t,server:WUt(s)}:void 0}catch(s){nc.warn(`Skipping malformed MCP server config [${t}:${r}]:`,s);return}}).filter(r=>!!r)}function Eze(e){return typeof e=="string"&&bze.includes(e)}function $Ut(e){let t=oi(e),n=t.type;if(n!=="command"&&n!=="http")throw je.invalidParams(void 0,"Hook type must be command or http");let r={type:n};if(n==="command"){let s=t.command;if(typeof s!="string"||!s.trim())throw je.invalidParams(void 0,"Command hooks require a command");r.command=s.trim(),r.env=AB(t.env),typeof t.async=="boolean"&&(r.async=t.async);let i=t.shell;(i==="bash"||i==="powershell")&&(r.shell=i)}else{let s=t.url;if(typeof s!="string"||!s.trim())throw je.invalidParams(void 0,"HTTP hooks require a URL");r.url=s.trim(),r.headers=AB(t.headers),r.allowedEnvVars=ug(t.allowedEnvVars),typeof t.once=="boolean"&&(r.once=t.once)}let o=m1(t.timeout);o!==void 0&&(r.timeout=o);for(let s of["name","description","statusMessage"]){let i=t[s];typeof i=="string"&&i.trim()&&(r[s]=i.trim())}return r}function _ze(e){let t=oi(e),n=t.hooks;if(!Array.isArray(n)||n.length===0)throw je.invalidParams(void 0,"Hook definition requires at least one hook");let r={hooks:n.map($Ut)};return typeof t.matcher=="string"&&(r.matcher=t.matcher),typeof t.sequential=="boolean"&&(r.sequential=t.sequential),r}function p1(e,t,n){let r=oi(e.hooks),o=[];for(let s of bze){let i=r[s];Array.isArray(i)&&i.forEach((a,l)=>{try{o.push({event:s,scope:t,index:l,hook:YUt(_ze(a)),extensionName:n})}catch(c){nc.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return o}function dB(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw je.invalidParams(void 0,"scope must be user or workspace")}function nz(e,t){return e.forScope(dB(t)).settings}async function yze(e,t){for(let n of Ed()){let r=so.join(e,n);try{return await bl.access(r),r}catch{}}return so.join(e,t)}async function VUt(e){let t=Ed()[0]??"MATILDA.md",n=await yze(Mt.getGlobalMatildaDir(),t),r=await yze(e.cwd,t),o=Kh(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:r,autoMemoryDir:o}}async function Lze(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let r=Dze.toWeb(process.stdout),o=Ize.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=kje(r,o),i,a=new _j(m=>(i=new Tte(e,t,n,m),i),s),l=async m=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(E){nc.error(`[ACP] MCP pool drain (${m}) error:`,E)}},c=!1,u=!1,A=async m=>{if(u)return;u=!0;let E=new Set([e]),y=i?.getActiveSessions();if(y)for(let x of y){let b=x.getConfig?.();b&&E.add(b)}for(let x of E){let b=x.getHookSystem?.();if(!(x.getDisableAllHooks?.()||!b||!x.hasHooksForEvent?.("SessionEnd")))try{await b.fireSessionEndEvent(m)}catch(v){nc.warn(`SessionEnd hook failed: ${v instanceof Error?v.message:String(v)}`)}}},g=async()=>{if(c)return;c=!0,nc.debug("[ACP] Shutdown signal received, closing streams"),await A("other");let m=i?.disposeSessions();try{process.stdin.destroy()}catch{}try{process.stdout.destroy()}catch{}await l("signal"),await m,Fl().catch(E=>{nc.error("[ACP] Cleanup error:",E)}).finally(()=>{process.exit(0)})};process.on("SIGTERM",g),process.on("SIGINT",g),await a.closed,await A("prompt_input_exit");let d=i?.disposeSessions();await l("ide_close"),await d,process.off("SIGTERM",g),process.off("SIGINT",g)}function KUt(e){if("command"in e&&"args"in e&&"env"in e)return e}function XUt(e){if("type"in e&&e.type==="sse")return e}function ZUt(e){if("type"in e&&e.type==="http")return e}var Tte=class{constructor(t,n,r,o){this.config=t;this.settings=n;this.argv=r;this.connection=o;this.mcpPool=new lse(this.config,{workspaceContext:this.config.getWorkspaceContext(),debugMode:this.config.getDebugMode()})}sessions=new Map;sessionRestoreCompletions=new Map;clientCapabilities;transcriptReadNegotiated=!1;transcriptUpdatesNegotiated=!1;backgroundExecutionNegotiated=!1;sessionStateNegotiated=!1;finalAnswersNegotiated=!1;sessionNoticesNegotiated=!1;compactionUpdatesNegotiated=!1;signInUrlNegotiated=!1;matildaAccountState;mcpPool;getActiveSessions(){return[...this.sessions.values()]}async shutdownMcpPool(t=1e4){try{let n=await this.mcpPool.drainAll({force:!0,timeoutMs:t});(n.forced>0||n.errors.length>0)&&nc.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){nc.error(`MCP pool drainAll failed: ${n instanceof Error?n.message:String(n)}`)}}async closeStoredSession(t){let n=this.sessions.get(t);if(!n){this.mcpPool.releaseSession(t);return}await n.shutdown();try{await n.getConfig().getToolRegistry()?.stop()}catch(r){nc.debug(`Session ${t} tool registry stop during close failed: ${r instanceof Error?r.message:String(r)}`)}this.mcpPool.releaseSession(t),Uo.removeSession(t),this.sessions.delete(t)}async closeSessionAndItsWork(t){await this.sessionRestoreCompletions.get(t),await this.stopSessionAndItsWork(t)}async stopSessionAndItsWork(t){let n=this.sessions.get(t)?.getConfig();await this.closeStoredSession(t),n&&(n.getBackgroundTaskRegistry().abortAll(),n.getMonitorRegistry().abortAll({notify:!1}),n.getBackgroundShellRegistry().abortAll(),n.getSkillManager()?.stopWatching())}async disposeSessions(){let t=await Promise.allSettled([...this.sessions.keys()].map(n=>this.closeStoredSession(n)));for(let n of t)n.status==="rejected"&&nc.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return Xk(t.merged,this.argv.channel)}get matildaAccount(){return this.matildaAccountState??=new Pj({channel:this.config.getChannel(),connectionSignal:this.connection.signal,install:(t,n)=>P5(Ja(process.cwd()),t,n)}),this.matildaAccountState}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[vte];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===Zj,this.transcriptUpdatesNegotiated=this.transcriptReadNegotiated&&n.transcriptUpdates===cze,this.backgroundExecutionNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.backgroundExecution===1,this.sessionStateNegotiated=this.transcriptReadNegotiated&&n.sessionState===1,this.finalAnswersNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.finalAnswers===1,this.sessionNoticesNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.sessionNotices===hte,this.compactionUpdatesNegotiated=t.clientCapabilities?.session?.compaction!=null,this.signInUrlNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.signInUrl===1;let r=gv(this.config);return{protocolVersion:VZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.21.13-nightly.20261028.557d917f5"},authMethods:r,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated||this.finalAnswersNegotiated||this.sessionNoticesNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:Zj}:{},...this.transcriptUpdatesNegotiated?{transcriptUpdates:cze}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{},...this.finalAnswersNegotiated?{finalAnswers:1}:{},...this.sessionNoticesNegotiated?{sessionNotices:hte}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0},...cB({channel:this.config.getChannel()})?{auth:{logout:{}}}:{}}}}async authenticate({methodId:t}){if(t===mte&&cB({channel:this.config.getChannel()})){await this.matildaAccount.signIn(this.signInUrlNegotiated?r=>this.connection.extNotification(zje,{...r}):void 0);return}let n=Vt.nativeEnum(Ru).parse(t);await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}async logout(){if(!cB({channel:this.config.getChannel()}))throw je.methodNotFound("logout");await this.matildaAccount.signOut()}async newSession({cwd:t,mcpServers:n}){let r=br(t),o=await this.newSessionConfig(t,n,r);await this.ensureAuthenticated(o),this.setupFileSystem(o);let s=await this.createAndStoreSession(o,r),i=this.buildAvailableModels(o),a=this.buildModesData(o),l=this.buildConfigOptions(o);return{sessionId:s.getId(),models:i,modes:a,configOptions:l,_meta:fze(o)}}async loadSession(t){return this.restoreSession(t,!0)}async resumeSession(t){return this.restoreSession(t,!1)}async restoreSession(t,n){let r=this.sessionRestoreCompletions.get(t.sessionId),o,s=new Promise(i=>{o=i});this.sessionRestoreCompletions.set(t.sessionId,s);try{await r;let i=tUt(t),a=nUt(i);if(!await new yi(i,a).sessionExists(t.sessionId))throw je.resourceNotFound(`session:${t.sessionId}`);this.sessions.has(t.sessionId)&&await this.stopSessionAndItsWork(t.sessionId);let c=br(t.cwd),u=await this.newSessionConfig(t.cwd,t.mcpServers??[],c,t.sessionId,!0,i,a),A;try{await this.ensureAuthenticated(u),this.setupFileSystem(u),A=await this.createAndStoreSession(u,c,n?u.getResumedSessionData()?.conversation:void 0)}catch(g){throw await u.getChatRecordingService()?.releaseTranscriptOwnership().catch(()=>{}),g}return await this.#e(u,A),{modes:this.buildModesData(u),models:this.buildAvailableModels(u),configOptions:this.buildConfigOptions(u),_meta:fze(u)}}finally{o(),this.sessionRestoreCompletions.get(t.sessionId)===s&&this.sessionRestoreCompletions.delete(t.sessionId)}}async#e(t,n){try{let r=t.getSessionService().getWorktreeSessionPath(t.getSessionId()),o=await B0(r);o.contextMessage&&(n.pendingWorktreeNotice=o.contextMessage)}catch(r){nc.warn(`ACP worktree restore failed: ${r}`)}}async listSessions(t){let n=t.cwd||process.cwd(),r=t._meta?.size,o=typeof r=="number"&&r>0?Math.floor(r):void 0,s=await Cv(Ja(n),n,()=>new yi(n).listSessions({cursor:t.cursor??void 0,size:o}));return{sessions:s.items.map(a=>({_meta:{createdAt:a.startTime,startTime:a.startTime,preview:a.prompt,...a.gitBranch?{gitBranch:a.gitBranch}:{},...a.titleSource?{titleSource:a.titleSource}:{}},cwd:a.cwd,sessionId:a.sessionId,title:a.customTitle||a.prompt||"(session)",updatedAt:a.lastMessageAt!==void 0?new Date(a.lastMessageAt).toISOString():a.startTime})),nextCursor:s.nextCursor!=null?String(s.nextCursor):void 0}}async setSessionMode(t){let n=this.sessions.get(t.sessionId);if(!n)throw je.invalidParams(void 0,`Session not found for id: ${t.sessionId}`);return n.setMode(t)}async setSessionConfigOption(t){let{sessionId:n,configId:r,value:o}=t,s=this.sessions.get(n);if(!s)throw je.invalidParams(void 0,`Session not found for id: ${n}`);switch(r){case"mode":{await this.setSessionMode({sessionId:n,modeId:o});break}case"model":{await s.setModel({sessionId:n,modelId:o},{persistDefault:!1});break}default:throw je.invalidParams(void 0,`Unsupported configId: ${r}`)}return{configOptions:this.buildConfigOptions(s.getConfig())}}async prompt(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);try{return await n.prompt(t)}catch(r){throw r instanceof l0?new je(r.status,r.message,{code:r.code}):r}}async cancel(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);await n.cancelPendingPrompt()}loadPermissionSettings(t){return this.settings=Ja(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:ez(t.user.settings)},workspace:{path:t.workspace.path,rules:ez(t.workspace.settings)},merged:ez(t.merged),isTrusted:t.isTrusted}}async buildCoreSettings(t,n){let r=t.user.settings,o=t.workspace.settings,s=this.effectiveSettings(t),i=[];try{let d=new Ac({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await d.refreshCache(),i=d.getLoadedExtensions()}catch(d){nc.warn("Extension loading failed, continuing without extensions:",d)}let a=await Promise.all(i.map(async d=>{let m=await S0(d.config,d.id,"user"),E=await S0(d.config,d.id,"workspace",n),y=d.settings??[];return{id:d.id,name:d.name,version:d.version,isActive:d.isActive,path:d.path,commands:d.commands??[],skills:(d.skills??[]).map(x=>x.name),mcpServers:Object.keys(d.config.mcpServers??{}),settings:y.map(x=>{let b=m[x.envVar],w=E[x.envVar],v=w!==void 0,R=b!==void 0,_=v?w:b,G=v?"workspace":R?"user":void 0;return{name:x.name,description:x.description,envVar:x.envVar,sensitive:!!x.sensitive,userValue:x.sensitive?void 0:b,workspaceValue:x.sensitive?void 0:w,effectiveValue:x.sensitive?void 0:_,effectiveScope:G,hasUserValue:R,hasWorkspaceValue:v}})}})),l=i.filter(d=>d.isActive),c=l.flatMap(d=>g1({mcpServers:d.config.mcpServers??{}},"extension").map(m=>({...m,server:{...m.server,extensionName:d.name}}))),u=l.flatMap(d=>p1({hooks:d.hooks??{}},"extension",d.name)),A=new Map;for(let d of g1(r,"user"))A.set(d.name,d);if(t.isTrusted)for(let d of g1(o,"workspace"))A.set(d.name,d);let g=[...p1(r,"user"),...t.isTrusted?p1(o,"workspace"):[]];return{user:{path:t.user.path,values:bte(r),mcpServers:g1(r,"user"),hooks:p1(r,"user")},workspace:{path:t.workspace.path,values:bte(o),mcpServers:g1(o,"workspace"),hooks:p1(o,"workspace")},merged:{values:bte(s),mcpServers:[...A.values(),...c],hooks:[...g,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){let r=t==="Workspace"?gze(n):void 0,o=new Map;for(let s of this.sessions.values()){let i=s.getConfig(),a=i.storage.getProjectRoot(),l=gze(a);if(r!==void 0&&l!==r)continue;let c=i.getPermissionManager?.();if(c)try{let u=o.get(l);u||(u=ez(Ja(a).merged),o.set(l,u));let A=i.getPermissionsBeyondSettings?.(),g=oUt(c);for(let d of rUt){let m=new Set([...u[d],...A?.[d]??[]]);for(let y of g[d])m.has(y)||c.removePersistentRule(y,d);let E=new Set(g[d]);for(let y of u[d])E.has(y)||c.addPersistentRule(y,d)}}catch(u){nc.warn(`Failed to sync permission rules to a live session: ${u instanceof Error?u.message:String(u)}`)}}}workspaceCwd(t){return t.getTargetDir()}safeWorkspaceCwd(t){try{return this.workspaceCwd(t)}catch{return""}}errorCell(t,n,r){let o=r??lze(n);return{kind:t,status:"error",error:n instanceof Error?n.message:String(n),...o?{errorKind:o}:{}}}buildWorkspaceProvidersStatus(t){try{let n=this.workspaceCwd(t),r=t.getAuthType?.(),o=t.getActiveRuntimeModelSnapshot?.(),s=o?o.id:(t.getModel()||"").trim(),i=s.length>0,a=o?.authType??r,l=i&&a?hy(s,a):s||void 0,c=new Map;for(let d of t.getAllConfiguredModels()){let m=String(d.authType),E=c.get(m);E||(E={kind:"model_provider",status:"ok",authType:m,current:!1,models:[]},c.set(m,E));let y=d.isRuntimeModel&&d.runtimeSnapshotId?d.runtimeSnapshotId:d.id,x=hy(y,d.authType),b=a===d.authType&&i&&(s===y||s===d.id||l===x),w={modelId:x,baseModelId:Kje(y),name:d.label,...d.description!==void 0?{description:d.description}:{},contextLimit:d.contextWindowSize??Jz(y),...d.modalities!==void 0?{modalities:d.modalities}:{},...d.baseUrl!==void 0?{baseUrl:rz(d.baseUrl)}:{},...d.envKey!==void 0?{envKey:d.envKey}:{},isCurrent:b,isRuntime:d.isRuntimeModel===!0};E.models.push(w),b&&(E.current=!0)}let A=t.getContentGeneratorConfig?.()?.baseUrl||void 0,g=this.effectiveSettings().fastModel||void 0;return{v:Xj,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...A?{baseUrl:rz(A)}:{},...g?{fastModelId:g}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:Xj,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!0,providers:[],errors:[this.errorCell("providers",n)]}}}sessionOrThrow(t){let n=this.sessions.get(t);if(!n)throw je.invalidParams(void 0,`Session not found for id: ${t}`);return n}async buildSessionSupportedCommandsStatus(t){let n=this.sessionOrThrow(t),{availableCommands:r,availableSkills:o,availableSkillDetails:s}=await Ste(n.getConfig());return{v:Xj,sessionId:t,availableCommands:r,availableSkills:o??[],...s?{availableSkillDetails:s}:{}}}async installSkillFromUrl(t){let n=this.config.getSkillManager();if(!n)throw je.invalidParams(void 0,"SkillManager is not available");let r=await vUt(t.sourceUrl),o=so.join(Mt.getGlobalMatildaDir(),"skills"),s=mze(o,t.slug),i=so.join(s,"SKILL.md"),a=n.parseSkillContent(r.skillContent,i,"user");if(a.name!==t.slug)throw je.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=`${s}.installing-${process.pid}-${Date.now()}`;try{await bl.rm(l,{recursive:!0,force:!0});for(let c of r.files){let u=RUt(l,c.relativePath);await bl.mkdir(so.dirname(u),{recursive:!0}),await bl.writeFile(u,c.content)}await bl.rm(s,{recursive:!0,force:!0}),await bl.rename(l,s)}catch(c){throw await bl.rm(l,{recursive:!0,force:!0}).catch(()=>{}),c}return await this.refreshSkillCaches(n),{id:t.id,slug:a.name,installed:!0,installedPath:i,sourceUrl:t.sourceUrl}}async deleteGlobalSkill(t){let n=this.config.getSkillManager();if(!n)throw je.invalidParams(void 0,"SkillManager is not available");let{skillDir:r,skillFile:o,content:s}=await this.readManagedSkillFile(t.slug,"global",n),i=n.parseSkillContent(s,o,"user");if(i.name!==t.slug)throw je.invalidParams(void 0,`Skill name "${i.name}" does not match requested slug "${t.slug}"`);let a=so.resolve(r),l=so.resolve(o),c=so.resolve(Mt.getGlobalMatildaDir());if(!(l===so.join(a,"SKILL.md"))||a===so.parse(a).root||a===c)throw je.invalidParams(void 0,`Refusing to delete unexpected skill directory: ${r}`);return await bl.rm(r,{recursive:!0,force:!0}),await this.refreshSkillCaches(n),{slug:t.slug,deleted:!0}}async refreshSkillCaches(t){let n=new Set([t]);for(let r of this.sessions.values()){let o=r.getConfig().getSkillManager();o&&n.add(o)}await Promise.all(Array.from(n,r=>r.refreshCache()))}async readManagedSkillFile(t,n,r,o){if(n==="global"){let c=mze(so.join(Mt.getGlobalMatildaDir(),"skills"),t),u=so.join(c,"SKILL.md"),A=await bl.readFile(u,"utf8").catch(()=>{});if(A!==void 0)return{skillDir:c,skillFile:u,content:A}}if(n==="project"&&o?.trim()){let c=await this.findProjectSkillFileFromCwd(t,o,r);if(c)return c}let s=n==="project"?"project":"user",a=(await r.listSkills({level:s})).find(c=>c.name===t)?.filePath;if(!a)throw je.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`);let l=await bl.readFile(a,"utf8").catch(()=>{throw je.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`)});return{skillDir:so.dirname(a),skillFile:a,content:l}}async findProjectSkillFileFromCwd(t,n,r){let o=so.resolve(n);for(let s of iUt){let i=so.join(o,s,aUt),c=(await r.loadSkillsFromDir(i,"project")).find(A=>A.name===t)?.filePath;if(!c)continue;let u=await bl.readFile(c,"utf8").catch(()=>{throw je.invalidParams(void 0,`Project skill not found: ${t}`)});return{skillDir:so.dirname(c),skillFile:c,content:u}}}async setGlobalSkillEnabled(t,n){let r=this.config.getSkillManager();if(!r)throw je.invalidParams(void 0,"SkillManager is not available");let{skillFile:o,content:s}=await this.readManagedSkillFile(t.slug,t.scope,r,n),i=t.scope==="project"?"project":"user",a=r.parseSkillContent(s,o,i);if(a.name!==t.slug)throw je.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=fUt(s,t.enabled);if(r.parseSkillContent(l,o,i),so.basename(o)!=="SKILL.md")throw je.invalidParams(void 0,`Refusing to write to unexpected skill file: ${o}`);return await bl.writeFile(o,l,"utf8"),await this.refreshSkillCaches(r),{slug:t.slug,enabled:t.enabled,installedPath:o}}async extMethod(t,n){let r=typeof n.cwd=="string"?n.cwd:void 0,o=r||process.cwd(),s=/^[0-9a-fA-F-]{32,36}$/;switch(t){case"matilda/feedback/submit":{let i=_p(n.description,"description");if(i.length>uM)throw je.invalidParams(void 0,"Bug description is too long");return{...await Eb({description:i,envSummary:`${process.platform}/${process.arch}`})}}case Yje:{let{sessionId:i,modelId:a}=n;if(typeof i!="string"||typeof a!="string")throw je.invalidParams(void 0,"sessionId and modelId must be strings");return{...await this.sessionOrThrow(i).setModel({sessionId:i,modelId:a})}}case"matilda/session/attach":{if(!this.backgroundExecutionNegotiated)throw je.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i);if(!a)throw je.resourceNotFound(`session:${i}`);return a.attachClient(),{}}case"matilda/session/readState":{if(!this.sessionStateNegotiated)throw je.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i)?.getSessionState();if(!a)throw je.resourceNotFound(`session:${i}`);return a}case"matilda/workspace/getRoots":{let i=typeof n.sessionId=="string"?n.sessionId:void 0,a=i?this.sessions.get(i):void 0;if(i&&!a)throw je.invalidParams(void 0,`Unknown session: ${i}`);let l=a?.getConfig()??this.config;return{workspaceId:process.env.MATILDA_DESKTOP_WORKSPACE_ID??null,revision:process.env.MATILDA_DESKTOP_DIRECTORY_REVISION??null,canonicalRoots:l.getWorkspaceContext().getDirectories(),restrictiveSandbox:l.isRestrictiveSandbox(),sandbox:process.env.SANDBOX??null,sandboxNonce:process.env.MATILDA_DESKTOP_SANDBOX_ACTIVE??null,seatbeltProfile:process.env.SEATBELT_PROFILE??null}}case"matilda/providers/list":{let i=this.effectiveSettings(Ja(o));return{providers:GR.map(a=>LUt(a,i))}}case"matilda/providers/connect":{let i=_p(n.providerId,"providerId"),a=Wre(i);if(!a)throw je.invalidParams(void 0,`Unknown provider: ${i}`);let l=Ja(o),c=OUt(a,n,_Ut(a,l.merged)),u=PUt(n.scope),A=gA(a,c);return await oC(A,{settings:UC(l,u),reloadModelProviders:g=>{let d=Xk({...l.merged,modelProviders:g},this.argv.channel);this.config.reloadModelProvidersConfig(d.modelProviders)},syncAuthState:(g,d)=>this.config.getModelsConfig().syncAfterAuthRefresh(g,d),refreshAuth:g=>this.config.refreshAuth(g)}),{success:!0,providerId:a.id,providerLabel:a.label,authType:A.authType,modelId:A.modelSelection?.modelId}}case"matilda/skills/install":return this.installSkillFromUrl(cUt(n));case"matilda/skills/delete":return this.deleteGlobalSkill(uUt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(dUt(n),r);case"matilda/settings/getMemory":{let i=Ja(o);return this.settings=i,{settings:pze(this.effectiveSettings(i).memory)}}case"matilda/settings/setMemory":{let i=oi(n.updates),a=Ja(o);for(let l of lUt)if(i[l]!==void 0){if(typeof i[l]!="boolean")throw je.invalidParams(void 0,`Invalid memory setting '${l}': expected boolean`);a.setValue("User",`memory.${l}`,i[l])}return this.settings=a,{settings:pze(this.effectiveSettings(a).memory)}}case"matilda/settings/getPath":return{path:this.settings.user.path};case"matilda/settings/getMemoryPaths":{let i=typeof n.projectRoot=="string"?n.projectRoot:o;return{paths:await VUt({cwd:o,projectRoot:i})}}case"matilda/memory/list":{let i=typeof n.projectRoot=="string"?n.projectRoot:o,a=n.scope;if(a!=="user"&&a!=="project")throw je.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");return{memories:(a==="user"?await Goe():await Hoe(i)).map(c=>({type:c.type,title:c.title,description:c.description,relativePath:c.relativePath,filename:c.filename,mtimeMs:c.mtimeMs}))}}case"matilda/memory/delete":{let i=typeof n.projectRoot=="string"?n.projectRoot:o,a=n.scope;if(a!=="user"&&a!=="project")throw je.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");let l=n.relativePath;if(typeof l!="string"||l.length===0)throw je.invalidParams(void 0,"Invalid or missing relativePath");return await fse({scope:a,projectRoot:i,relativePath:l}),{deleted:!0}}case Bte.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case Bte.sessionSupportedCommands:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw je.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionSupportedCommandsStatus(i)}case xte.sessionClose:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw je.invalidParams(void 0,"Invalid or missing sessionId");return await this.closeSessionAndItsWork(i),{sessionId:i,closed:!0}}case"deleteSession":{let i=n.sessionId;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");return await this.closeSessionAndItsWork(i),{success:await Cv(Ja(o),o,async()=>new yi(o).removeSession(i))}}case xte.sessionRename:{let i=n.sessionId,a=n.title;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(typeof a!="string")throw je.invalidParams(void 0,"Invalid or missing title");if(a.length>HR)throw je.invalidParams(void 0,`Title too long (max ${HR} chars)`);let l=n.titleSource==="auto"?"auto":"manual",c=this.sessions.get(i)?.getConfig().getChatRecordingService();return c?{success:await c.recordCustomTitleCommitted(a,l,{notifyObservers:!1})}:{success:await Cv(Ja(o),o,async()=>new yi(o).renameSession(i,a,l))}}case"rewindSession":{let i=n.sessionId;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i);if(!a)throw je.invalidParams(void 0,`Session not found for id: ${i}`);let l=n.targetTurnIndex,c=n.promptId;if(c&&l==null){let E=i+"########";if(!c.startsWith(E))throw new je(-32602,"Invalid promptId format",{errorKind:"invalid_rewind_target"});let y=c.slice(E.length);if(!/^\d+$/.test(y))throw new je(-32602,"Invalid promptId: non-numeric turn suffix",{errorKind:"invalid_rewind_target"});let w=a.getConfig().getFileHistoryService().getSnapshots().findIndex(v=>v.promptId===c);if(w<0)throw new je(-32602,"Snapshot not found for the given promptId",{errorKind:"invalid_rewind_target"});l=w}if(!Number.isInteger(l)||l<0)throw je.invalidParams(void 0,"Invalid or missing targetTurnIndex");let u=a.captureHistorySnapshot(),A;try{A=await a.rewindToTurn(l)}catch(E){if(E instanceof je){let y=E.message;if(y.includes("Cannot rewind while a prompt is running"))throw new je(E.code,y,{errorKind:"session_busy"});if(y.includes("compressed or does not exist"))throw new je(E.code,y,{errorKind:"invalid_rewind_target"})}throw E}let g=[],d=[];if(n.rewindFiles!==!1&&c){let E=a.getConfig().getFileHistoryService();try{let y=await E.rewind(c,!0);g=y.filesChanged,d=y.filesFailed}catch(y){let x=y instanceof Error?y.message:String(y);nc.error(`[ACP] File-history rewind failed for session=${i} promptId=${c}: ${x}`),d=[`file-history-rewind: ${x}`]}}return{success:!0,historyBeforeRewind:u,...A,filesChanged:g,filesFailed:d}}case"matilda/session/readTranscript":{if(!this.transcriptReadNegotiated)throw je.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");let a=Sze.optional().safeParse(n.cursor);if(!a.success)throw je.invalidParams(void 0,"Invalid transcript cursor");if(this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let l=this.sessions.get(i);if(!l)throw je.resourceNotFound(`session:${i}`);let c=await l.readTranscript(a.data);if(this.sessions.get(i)!==l||this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session changed during transcript read",{errorKind:"session_busy"});let u=this.sessionStateNegotiated?l.getSessionState():void 0,A={processing:!l.isIdle(),...u?{state:u}:{}};if(n.updates!==!0)return{version:Zj,sessionId:i,...c,runtime:A};if(!this.transcriptUpdatesNegotiated)throw je.invalidParams(void 0,"Transcript updates were not negotiated");let g=c.mode==="delta"?ZPt(n.projection,a.data):void 0,d=c.mode==="snapshot"||g&&!eUt(c.records,a.data.selectedLeafUuid)?c:await l.readTranscript(),m=d.mode==="delta"?g:void 0,E=m?{...m.usage}:{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0},y=[],x=yi.reconstructHistory(d.records),b=await new uB({sessionId:i,config:this.config,sendUpdate:async w=>{y.push(w)},cumulativeUsage:E},!0,l.getActiveTaskStartUuid(),this.finalAnswersNegotiated,this.compactionUpdatesNegotiated).replay(x,m?{continuation:m.continuation,partial:!0,messageIdOf:w=>l.committedMessageIdOf(w)??w}:{});return{version:Zj,sessionId:i,mode:m?"delta":"snapshot",cursor:d.cursor,updates:Aze(y),transcriptRecords:dze(x),...d.cursor?{projection:uze({v:1,cursor:d.cursor,continuation:b,usage:E})}:{},runtime:A}}case"matilda/session/loadUpdates":{let i=n.sessionId;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i)?.getActiveTaskStartUuid(),l=await Cv(Ja(o),o,async()=>new yi(o).loadSession(i));if(!l?.conversation)return{updates:[]};let c=[],u={sessionId:i,config:this.config,sendUpdate:async y=>{c.push(y)},cumulativeUsage:{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}},A,g;try{g=await new uB(u,n.taskOutcomesVersion===1,this.sessions.get(i)?.getActiveTaskStartUuid()??a,this.finalAnswersNegotiated,this.compactionUpdatesNegotiated).replay(l.conversation.messages)}catch(y){A=y instanceof Error?y.message:String(y),nc.warn("[loadUpdates] History replay failed for session %s (partial updates: %d):",i,c.length,y)}let d=l.transcriptCursor,m=Bre(l.conversation.messages),E=m.kind==="v2"?Gj(m.payload.snapshot):null;return{updates:Aze(c),transcriptRecords:dze(l.conversation.messages),...E?{goal:E}:{},...this.transcriptUpdatesNegotiated&&d&&g?{transcript:d,projection:uze({v:1,cursor:d,continuation:g,usage:u.cumulativeUsage})}:{},startTime:l.conversation.startTime,lastUpdated:l.conversation.lastUpdated,...A!==void 0?{partial:!0,replayError:A}:{}}}case"matilda/session/appendHistory":{let i=Vt.object({sessionId:Vt.string().regex(s),messages:Vt.array(Vt.object({id:Vt.string().uuid(),role:Vt.enum(["user","assistant"]),content:Vt.string(),timestamp:Vt.number().finite().min(0).max(864e13)}))}).safeParse(n);if(!i.success)throw je.invalidParams(void 0,"Invalid imported history");let a=this.sessions.get(i.data.sessionId);if(!a)throw je.invalidParams(void 0,"Session not found");return{success:!0,selectedMessageIds:await a.appendImportedHistory(i.data.messages)}}case"restoreSessionHistory":{let i=n.sessionId,a=n.history;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(!Array.isArray(a))throw je.invalidParams(void 0,"Invalid or missing history");let l=this.sessions.get(i);if(!l)throw je.invalidParams(void 0,`Session not found for id: ${i}`);return l.restoreHistory(a),{success:!0}}case Wje:return this.matildaAccountState?.cancelSignIn(),{};case"getAccountInfo":{let i=n.sessionId,a=i?this.sessions.get(i):void 0,l=a?a.getConfig():this.config,c=l.getContentGeneratorConfig();return{authType:c?.authType??l.getAuthType()??null,model:c?.model??l.getModel()??null,baseUrl:c?.baseUrl?rz(c.baseUrl):null,apiKeyEnvKey:c?.apiKeyEnvKey??null,account:qje(c?.baseUrl,l.getChannel())}}case"matilda/settings/getCore":{let i=Ja(o);return this.settings=i,this.buildCoreSettings(i,o)}case"matilda/settings/setCoreValue":{let i=n.key;if(typeof i!="string"||!xze.includes(i))throw je.invalidParams(void 0,"Unsupported Matilda setting key");let a=Ja(o),l=i,c=HUt(l,n.value),u=dB(n.scope);return a.setValue(u,i,c),l==="general.outputLanguage"&&typeof c=="string"&&u==="User"&&h6(c),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/setMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw je.invalidParams(void 0,"MCP server name is required");let a=Ja(o),l=dB(n.scope),c=l==="Workspace"?"workspace":"user",u=nz(a,c),A=oi(u.mcpServers),g={...A,[i.trim()]:jUt(qUt(GUt(n.server),oi(A[i.trim()])))};return a.setValue(l,"mcpServers",g),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/removeMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw je.invalidParams(void 0,"MCP server name is required");let a=Ja(o),l=dB(n.scope),c=l==="Workspace"?"workspace":"user",u=nz(a,c),A={...oi(u.mcpServers)};return delete A[i.trim()],a.setValue(l,"mcpServers",A),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/setHook":{let i=n.event;if(!Eze(i))throw je.invalidParams(void 0,"Invalid hook event");let a=Ja(o),l=dB(n.scope),c=l==="Workspace"?"workspace":"user",u=nz(a,c),A={...oi(u.hooks)},g=Array.isArray(A[i])?[...A[i]]:[],d=_ze(n.hook),m=n.index,E=typeof m=="number"&&Number.isInteger(m)&&m>=0&&m<g.length,y=JUt(d,E?oi(g[m]):{});return E?g[m]=y:g.push(y),A[i]=g,a.setValue(l,"hooks",A),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/removeHook":{let i=n.event;if(!Eze(i))throw je.invalidParams(void 0,"Invalid hook event");let a=n.index;if(typeof a!="number"||!Number.isInteger(a)||a<0)throw je.invalidParams(void 0,"Invalid hook index");let l=Ja(o),c=dB(n.scope),u=c==="Workspace"?"workspace":"user",A=nz(l,u),g={...oi(A.hooks)},d=Array.isArray(g[i])?[...g[i]]:[];if(a>=d.length)throw je.invalidParams(void 0,`Hook index ${a} out of range (event has ${d.length} hooks)`);return d.splice(a,1),g[i]=d,l.setValue(c,"hooks",g),this.settings=l,this.buildCoreSettings(l,o)}case"matilda/settings/setExtensionSetting":{let i=n.extensionId,a=n.settingKey,l=n.value;if(typeof i!="string"||!i)throw je.invalidParams(void 0,"extensionId is required");if(typeof a!="string"||!a)throw je.invalidParams(void 0,"settingKey is required");if(typeof l!="string")throw je.invalidParams(void 0,"value must be a string");let c=Ja(o),u=new Ac({workspaceDir:o,isWorkspaceTrusted:c.isTrusted});await u.refreshCache();let A=u.getLoadedExtensions().find(d=>d.id===i||d.name===i);if(!A)throw je.invalidParams(void 0,"Extension not found");let g=dB(n.scope)==="Workspace"?"workspace":"user";return await G_(A.config,A.id,a,async()=>l,g,o),this.settings=c,this.buildCoreSettings(c,o)}case"matilda/permissions/getSettings":{let i=this.loadPermissionSettings(o);return this.buildPermissionSettings(i)}case"matilda/permissions/setRules":{let i=n.scope,a=n.ruleType;if(i!=="user"&&i!=="workspace")throw je.invalidParams(void 0,'scope must be "user" or "workspace"');if(a!=="allow"&&a!=="ask"&&a!=="deny")throw je.invalidParams(void 0,'ruleType must be "allow", "ask", or "deny"');let l=this.loadPermissionSettings(o),c=sUt(n.rules),u=i==="workspace"?"Workspace":"User";return l.setValue(u,`permissions.${a}`,c),this.syncLivePermissionManagers(u,o),this.buildPermissionSettings(l)}default:throw je.methodNotFound(t)}}async newSessionConfig(t,n,r,o,s,i,a){let l={};for(let d of n){let m=KUt(d);if(m){let x={};for(let{name:b,value:w}of m.env)x[b]=w;l[m.name]=new q_(m.command,m.args,x,t);continue}let E=XUt(d);if(E){let x={};for(let{name:b,value:w}of E.headers)x[b]=w;l[E.name]=new q_(void 0,void 0,void 0,void 0,E.url,void 0,Object.keys(x).length>0?x:void 0);continue}let y=ZUt(d);if(y){let x={};for(let{name:b,value:w}of y.headers)x[b]=w;l[y.name]=new q_(void 0,void 0,void 0,void 0,void 0,y.url,Object.keys(x).length>0?x:void 0);continue}}let c=r.merged,u={...this.argv,...s?{resume:o}:{sessionId:o},sandboxSessionId:void 0,continue:!1},A=await eM(c,u,t,void 0,{userHooks:r.getUserHooks(),projectHooks:r.getProjectHooks()},Zk(r),l,i,a);!(this.argv.channel==="desktop"&&process.env.MATILDA_TEMPORARY_SESSION)&&typeof A.enableFileCheckpointing=="function"&&A.enableFileCheckpointing(),typeof A.setMcpTransportPool=="function"&&A.setMcpTransportPool(this.mcpPool);try{await A.initialize(),await A.waitForMcpReady()}catch(d){throw await A.getChatRecordingService()?.releaseTranscriptOwnership().catch(()=>{}),d}let g=typeof A.getFailedMcpServerNames=="function"?A.getFailedMcpServerNames():[];return g.length>0&&process.stderr.write(`Warning: MCP server(s) failed to start: ${g.join(", ")}. Continuing with built-in tools and any servers that did connect.
|
|
931
|
+
${r}`}var wze=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function Tze(e){let t;try{t=new URL(e)}catch{throw je.invalidParams(void 0,"Skill sourceUrl must be a valid URL")}if(t.protocol!=="https:")throw je.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(!wze.has(t.hostname))throw je.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function vze(e){let t=new URL(e);if(t.protocol!=="https:")throw je.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(t.hostname!=="github.com")return null;let n=t.pathname.split("/").filter(Boolean);if(n.length<5||n[2]!=="blob")return null;let r=n[0],o=n[1],s=n[3],i=n.slice(4);return!r||!o||!s||i.length===0?null:{owner:r,repo:o,ref:s,filePath:i.join("/")}}function gUt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function pUt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function wte(e,t,n){let r=e.subarray(t,t+n),o=r.indexOf(0),s=o>=0?o:r.length;return Buffer.from(r.subarray(0,s)).toString("utf8").trim()}function mUt(e,t){let n=wte(e,t+124,12);return n?Number.parseInt(n,8):0}function hUt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function CUt(e,t){let n=wte(e,t,100),r=wte(e,t+345,155);return r?`${r}/${n}`:n}function EUt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var h1=100*1024*1024,Rze=500*1024*1024,yUt=16,IUt=2e3,oz=class extends Error{};async function DUt(e,t,n={}){let r=n.maxCompressedBytes??h1,o=n.maxDecompressedBytes??Rze;if(e.length>r)throw je.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await YPt(Ize.from([Buffer.from(e)]),$Pt(),new Dze({write(A,g,d){if(u+=A.length,u>o){d(new oz);return}c.push(A),d()}})),s=Buffer.concat(c)}catch(c){throw c instanceof oz?je.invalidParams(void 0,"Decompressed skill archive exceeds the maximum allowed size"):je.invalidParams(void 0,`Failed to decompress skill archive: ${c instanceof Error?c.message:String(c)}`)}let i=t.replace(/^\/+|\/+$/g,""),a=i&&i!=="."?`${i}/`:"",l=[];for(let c=0;c+512<=s.length&&!hUt(s,c);){let u=CUt(s,c),A=String.fromCharCode(s[c+156]||0),g=mUt(s,c),d=c+512,m=d+Math.ceil(g/512)*512;if(A==="0"||A==="\0"){let E=EUt(u);if(E.startsWith(a)){let y=E.slice(a.length);y&&l.push({relativePath:y,content:s.subarray(d,d+g)})}}c=m}return l}var SUt=[".githubusercontent.com",".github.com"];function BUt(e){return wze.has(e)?!0:SUt.some(t=>e.endsWith(t))}async function Qte(e,t={},n=5){let r=e;for(let o=0;o<=n;o+=1){let s=await fetch(r,{...t,redirect:"manual"});if(s.status<300||s.status>=400)return s;let i=s.headers?.get("location");if(!i)return s;let a;try{a=new URL(i,r)}catch{throw je.invalidParams(void 0,"Skill download redirected to an invalid URL")}if(a.protocol!=="https:"||!BUt(a.hostname))throw je.invalidParams(void 0,"Skill download redirected to a disallowed host");r=a.toString()}throw je.invalidParams(void 0,"Skill download exceeded the maximum number of redirects")}async function Qze(e,t){let n=e.body;if(!n){let l=new Uint8Array(await e.arrayBuffer());if(l.byteLength>t)throw je.invalidParams(void 0,"Skill download exceeds the maximum allowed size");return l}let r=n.getReader(),o=[],s=0;for(;;){let{done:l,value:c}=await r.read();if(l)break;if(c){if(s+=c.byteLength,s>t)throw await r.cancel(),je.invalidParams(void 0,"Skill download exceeds the maximum allowed size");o.push(c)}}let i=new Uint8Array(s),a=0;for(let l of o)i.set(l,a),a+=l.byteLength;return i}async function kze(e){let t=await Qte(e);if(!t.ok)throw je.invalidParams(void 0,`Failed to download skill (${t.status})`);let n=t.headers?.get("content-length");if(n){let r=Number.parseInt(n,10);if(Number.isFinite(r)&&r>h1)throw je.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return Qze(t,h1)}async function xUt(e){let t=vze(e),n=t?gUt(t):e,r=await kze(n);return{skillContent:Buffer.from(r).toString("utf8"),files:[{relativePath:"SKILL.md",content:r}]}}async function bUt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,r=await Qte(n,{headers:{"User-Agent":"matilda-code"}});if(!r.ok)throw je.invalidParams(void 0,`Failed to download GitHub skill archive (${r.status})`);let o=r.headers?.get("content-length");if(o){let s=Number.parseInt(o,10);if(Number.isFinite(s)&&s>h1)throw je.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return DUt(await Qze(r,h1),t)}async function wUt(e,t){let n=pUt(t),r=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,o=await Qte(r,{headers:{Accept:"application/vnd.github+json","User-Agent":"matilda-code"}});if(!o.ok)throw je.invalidParams(void 0,`Failed to list GitHub skill files (${o.status})`);let s=await o.json();if(!Array.isArray(s))throw je.invalidParams(void 0,"GitHub skill URL must point to a directory-backed SKILL.md file");return s}async function Mze(e,t,n="",r=0,o={files:0,bytes:0}){if(r>yUt)throw je.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await wUt(e,t),i=[];for(let a of s){let l=oi(a),c=_p(l.name,"github.name"),u=_p(l.path,"github.path"),A=_p(l.type,"github.type"),g=n?so.posix.join(n,c):c;if(A==="dir"){i.push(...await Mze(e,u,g,r+1,o));continue}if(A!=="file")continue;if(o.files+=1,o.files>IUt)throw je.invalidParams(void 0,"Skill directory contains too many files");let d=_p(l.download_url,"github.download_url");Tze(d);let m=await kze(d);if(o.bytes+=m.length,o.bytes>Rze)throw je.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:g,content:m})}return i}async function TUt(e,t){let n=await Mze(e,t).catch(r=>(nc.warn("GitHub API directory listing failed, falling back to archive download:",r),null));return n||bUt(e,t)}async function vUt(e){Tze(e);let t=vze(e);if(!t||so.posix.basename(t.filePath)!=="SKILL.md")return xUt(e);let n=so.posix.dirname(t.filePath),r=await TUt(t,n),o=r.find(s=>s.relativePath==="SKILL.md");if(!o)throw je.invalidParams(void 0,"GitHub skill directory does not contain SKILL.md");return{skillContent:Buffer.from(o.content).toString("utf8"),files:r}}function RUt(e,t){let n=so.resolve(e),r=so.resolve(e,t);if(r!==n&&!r.startsWith(n+so.sep))throw je.invalidParams(void 0,`Invalid skill file path: ${t}`);return r}function mze(e,t){let n=so.resolve(e),r=so.resolve(e,t);if(!r.startsWith(n+so.sep))throw je.invalidParams(void 0,"Invalid skill.slug");return r}function QUt(e,t){if(typeof e.documentationUrl=="string")return e.documentationUrl;if(typeof e.documentationUrl=="function")try{return e.documentationUrl(t)}catch{return}}function kUt(e){return typeof oi(e).id=="string"}function MUt(e,t){if(!t)return;let r=oi(e.env)[t];return typeof r=="string"&&r.length>0?r:void 0}function FUt(e,t){let r=oi(e.modelProviders)[t];return Array.isArray(r)?r.filter(kUt):[]}function Fze(e,t){let n=v_(e);return n?FUt(t,e.protocol).filter(n):[]}function Nze(e,t,n){let r=typeof n[0]?.envKey=="string"?n[0].envKey:e.envKey;return MUt(t,r)}function NUt(e,t){let n=Fze(e,t),r=Nze(e,t,n);if(!r&&n.length===0)return;let o=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:wa(e);return{baseUrl:rz(o),...r?{hasApiKey:!0}:{},...n.length>0?{modelIds:n.map(s=>s.id)}:{}}}function _Ut(e,t){return Nze(e,t,Fze(e,t))}function LUt(e,t){let n=wa(e),r=NUt(e,t);return{id:e.id,label:e.label,description:e.description,protocol:e.protocol,baseUrl:e.baseUrl,defaultModelIds:jre(e),models:e.models,apiKeyPlaceholder:e.apiKeyPlaceholder,documentationUrl:QUt(e,n),uiGroup:e.uiGroup??"third-party",uiLabels:e.uiLabels,...r?{existingConfig:r}:{}}}function OUt(e,t,n){let r=wa(e),o=yy(t.apiKey,"apiKey")??n;if(!o)throw je.invalidParams(void 0,"Invalid or missing apiKey");let s=e.validateApiKey?.(o,r);if(s)throw je.invalidParams(void 0,s);return{baseUrl:r,apiKey:o}}function PUt(e){if(e!==void 0){if(e==="user")return"User";if(e==="workspace")return"Workspace";throw je.invalidParams(void 0,"Invalid scope for provider connect")}}function UUt(e,t){let n=e;for(let r of t.split(".")){if(!n||typeof n!="object"||Array.isArray(n))return;n=n[r]}if(typeof n=="string"||typeof n=="number"||typeof n=="boolean"||Array.isArray(n))return n}function bte(e){let t={};for(let n of xze){let r=UUt(e,n);r!==void 0&&(t[n]=r)}return t}function HUt(e,t){let n=Bze[e];switch(n.type){case"boolean":if(typeof t!="boolean")throw je.invalidParams(void 0,`${e} must be a boolean`);return t;case"number":if(typeof t!="number"||!Number.isFinite(t))throw je.invalidParams(void 0,`${e} must be a number`);if(n.min!==void 0&&t<n.min)throw je.invalidParams(void 0,`${e} must be at least ${n.min}`);return t;case"enum":{let r=n.values;if(typeof t!="string"||!r?.includes(t))throw je.invalidParams(void 0,`${e} must be one of ${r?.join(", ")}`);return t}case"string":{if(t===void 0)return;if(typeof t!="string")throw je.invalidParams(void 0,`${e} must be a string`);let r=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g;return t.replace(r," ").trim()||void 0}default:throw je.invalidParams(void 0,`${e} has an unsupported setting type`)}}function ug(e){if(e!==void 0){if(!Array.isArray(e))throw je.invalidParams(void 0,"Expected an array of strings");return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean)}}function AB(e){if(e===void 0)return;let t=oi(e),n={};for(let[r,o]of Object.entries(t))typeof o=="string"&&r.trim()&&(n[r.trim()]=o);return n}function m1(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number.parseInt(String(e),10);if(!Number.isFinite(t)||t<=0)throw je.invalidParams(void 0,"Expected a positive number");return t}function GUt(e){let t=oi(e),n=t.transport;if(n!=="stdio"&&n!=="http"&&n!=="sse")throw je.invalidParams(void 0,"MCP transport must be stdio, http, or sse");let r={transport:n},o=t.description;typeof o=="string"&&o.trim()&&(r.description=o.trim());let s=t.cwd;typeof s=="string"&&s.trim()&&(r.cwd=s.trim());let i=m1(t.timeout);if(i!==void 0&&(r.timeout=i),typeof t.trust=="boolean"&&(r.trust=t.trust),r.includeTools=ug(t.includeTools),r.excludeTools=ug(t.excludeTools),n==="stdio"){let c=t.command;if(typeof c!="string"||!c.trim())throw je.invalidParams(void 0,"Stdio MCP servers require a command");return r.command=c.trim(),r.args=ug(t.args),r.env=AB(t.env),r}let l=t[n==="http"?"httpUrl":"url"];if(typeof l!="string"||!l.trim())throw je.invalidParams(void 0,`${n.toUpperCase()} MCP servers require a URL`);return n==="http"?r.httpUrl=l.trim():r.url=l.trim(),r.headers=AB(t.headers),r}function jUt(e){let t={};for(let n of["timeout","trust","description","includeTools","excludeTools"])e[n]!==void 0&&(t[n]=e[n]);return e.transport==="stdio"?(t.command=e.command,e.args!==void 0&&(t.args=e.args),e.cwd!==void 0&&(t.cwd=e.cwd),e.env!==void 0&&(t.env=e.env)):e.transport==="http"?(t.httpUrl=e.httpUrl,e.headers!==void 0&&(t.headers=e.headers)):(t.url=e.url,e.headers!==void 0&&(t.headers=e.headers)),t}function zUt(e){let t=oi(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:AB(t.headers),timeout:m1(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:ug(t.includeTools),excludeTools:ug(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:AB(t.headers),timeout:m1(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:ug(t.includeTools),excludeTools:ug(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:ug(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:AB(t.env),timeout:m1(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:ug(t.includeTools),excludeTools:ug(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var sz="__redacted__";function WUt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(r=>[r,sz]));return{...e,env:t(e.env),headers:t(e.headers)}}function qUt(e,t){let n=(r,o)=>{if(!r)return r;let s=oi(o),i={};for(let[a,l]of Object.entries(r)){if(l!==sz){i[a]=l;continue}let c=s[a];typeof c=="string"&&(i[a]=c)}return i};return{...e,env:n(e.env,t.env),headers:n(e.headers,t.headers)}}function hze(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,sz]))}function Cze(e,t){if(!e)return e;let n=oi(t),r={};for(let[o,s]of Object.entries(e)){if(s!==sz){r[o]=s;continue}let i=n[o];typeof i=="string"&&(r[o]=i)}return r}function YUt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:hze(t.env)}:{},...t.headers?{headers:hze(t.headers)}:{}}))}}function JUt(e,t){let n=Array.isArray(t.hooks)?t.hooks:[];return{...e,hooks:e.hooks.map((r,o)=>{let s=oi(n[o]);return{...r,...r.env?{env:Cze(r.env,s.env)}:{},...r.headers?{headers:Cze(r.headers,s.headers)}:{}}})}}function g1(e,t){let n=oi(e.mcpServers);return Object.entries(n).map(([r,o])=>{try{let s=zUt(o);return s?{name:r,scope:t,server:WUt(s)}:void 0}catch(s){nc.warn(`Skipping malformed MCP server config [${t}:${r}]:`,s);return}}).filter(r=>!!r)}function Eze(e){return typeof e=="string"&&bze.includes(e)}function $Ut(e){let t=oi(e),n=t.type;if(n!=="command"&&n!=="http")throw je.invalidParams(void 0,"Hook type must be command or http");let r={type:n};if(n==="command"){let s=t.command;if(typeof s!="string"||!s.trim())throw je.invalidParams(void 0,"Command hooks require a command");r.command=s.trim(),r.env=AB(t.env),typeof t.async=="boolean"&&(r.async=t.async);let i=t.shell;(i==="bash"||i==="powershell")&&(r.shell=i)}else{let s=t.url;if(typeof s!="string"||!s.trim())throw je.invalidParams(void 0,"HTTP hooks require a URL");r.url=s.trim(),r.headers=AB(t.headers),r.allowedEnvVars=ug(t.allowedEnvVars),typeof t.once=="boolean"&&(r.once=t.once)}let o=m1(t.timeout);o!==void 0&&(r.timeout=o);for(let s of["name","description","statusMessage"]){let i=t[s];typeof i=="string"&&i.trim()&&(r[s]=i.trim())}return r}function _ze(e){let t=oi(e),n=t.hooks;if(!Array.isArray(n)||n.length===0)throw je.invalidParams(void 0,"Hook definition requires at least one hook");let r={hooks:n.map($Ut)};return typeof t.matcher=="string"&&(r.matcher=t.matcher),typeof t.sequential=="boolean"&&(r.sequential=t.sequential),r}function p1(e,t,n){let r=oi(e.hooks),o=[];for(let s of bze){let i=r[s];Array.isArray(i)&&i.forEach((a,l)=>{try{o.push({event:s,scope:t,index:l,hook:YUt(_ze(a)),extensionName:n})}catch(c){nc.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return o}function dB(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw je.invalidParams(void 0,"scope must be user or workspace")}function nz(e,t){return e.forScope(dB(t)).settings}async function yze(e,t){for(let n of Ed()){let r=so.join(e,n);try{return await bl.access(r),r}catch{}}return so.join(e,t)}async function VUt(e){let t=Ed()[0]??"MATILDA.md",n=await yze(Mt.getGlobalMatildaDir(),t),r=await yze(e.cwd,t),o=Kh(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:r,autoMemoryDir:o}}async function Lze(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let r=Dze.toWeb(process.stdout),o=Ize.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=kje(r,o),i,a=new _j(m=>(i=new Tte(e,t,n,m),i),s),l=async m=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(E){nc.error(`[ACP] MCP pool drain (${m}) error:`,E)}},c=!1,u=!1,A=async m=>{if(u)return;u=!0;let E=new Set([e]),y=i?.getActiveSessions();if(y)for(let x of y){let b=x.getConfig?.();b&&E.add(b)}for(let x of E){let b=x.getHookSystem?.();if(!(x.getDisableAllHooks?.()||!b||!x.hasHooksForEvent?.("SessionEnd")))try{await b.fireSessionEndEvent(m)}catch(v){nc.warn(`SessionEnd hook failed: ${v instanceof Error?v.message:String(v)}`)}}},g=async()=>{if(c)return;c=!0,nc.debug("[ACP] Shutdown signal received, closing streams"),await A("other");let m=i?.disposeSessions();try{process.stdin.destroy()}catch{}try{process.stdout.destroy()}catch{}await l("signal"),await m,Fl().catch(E=>{nc.error("[ACP] Cleanup error:",E)}).finally(()=>{process.exit(0)})};process.on("SIGTERM",g),process.on("SIGINT",g),await a.closed,await A("prompt_input_exit");let d=i?.disposeSessions();await l("ide_close"),await d,process.off("SIGTERM",g),process.off("SIGINT",g)}function KUt(e){if("command"in e&&"args"in e&&"env"in e)return e}function XUt(e){if("type"in e&&e.type==="sse")return e}function ZUt(e){if("type"in e&&e.type==="http")return e}var Tte=class{constructor(t,n,r,o){this.config=t;this.settings=n;this.argv=r;this.connection=o;this.mcpPool=new lse(this.config,{workspaceContext:this.config.getWorkspaceContext(),debugMode:this.config.getDebugMode()})}sessions=new Map;sessionRestoreCompletions=new Map;clientCapabilities;transcriptReadNegotiated=!1;transcriptUpdatesNegotiated=!1;backgroundExecutionNegotiated=!1;sessionStateNegotiated=!1;finalAnswersNegotiated=!1;sessionNoticesNegotiated=!1;compactionUpdatesNegotiated=!1;signInUrlNegotiated=!1;matildaAccountState;mcpPool;getActiveSessions(){return[...this.sessions.values()]}async shutdownMcpPool(t=1e4){try{let n=await this.mcpPool.drainAll({force:!0,timeoutMs:t});(n.forced>0||n.errors.length>0)&&nc.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){nc.error(`MCP pool drainAll failed: ${n instanceof Error?n.message:String(n)}`)}}async closeStoredSession(t){let n=this.sessions.get(t);if(!n){this.mcpPool.releaseSession(t);return}await n.shutdown();try{await n.getConfig().getToolRegistry()?.stop()}catch(r){nc.debug(`Session ${t} tool registry stop during close failed: ${r instanceof Error?r.message:String(r)}`)}this.mcpPool.releaseSession(t),Uo.removeSession(t),this.sessions.delete(t)}async closeSessionAndItsWork(t){await this.sessionRestoreCompletions.get(t),await this.stopSessionAndItsWork(t)}async stopSessionAndItsWork(t){let n=this.sessions.get(t)?.getConfig();await this.closeStoredSession(t),n&&(n.getBackgroundTaskRegistry().abortAll(),n.getMonitorRegistry().abortAll({notify:!1}),n.getBackgroundShellRegistry().abortAll(),n.getSkillManager()?.stopWatching())}async disposeSessions(){let t=await Promise.allSettled([...this.sessions.keys()].map(n=>this.closeStoredSession(n)));for(let n of t)n.status==="rejected"&&nc.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return Xk(t.merged,this.argv.channel)}get matildaAccount(){return this.matildaAccountState??=new Pj({channel:this.config.getChannel(),connectionSignal:this.connection.signal,install:(t,n)=>P5(Ja(process.cwd()),t,n)}),this.matildaAccountState}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[vte];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===Zj,this.transcriptUpdatesNegotiated=this.transcriptReadNegotiated&&n.transcriptUpdates===cze,this.backgroundExecutionNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.backgroundExecution===1,this.sessionStateNegotiated=this.transcriptReadNegotiated&&n.sessionState===1,this.finalAnswersNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.finalAnswers===1,this.sessionNoticesNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.sessionNotices===hte,this.compactionUpdatesNegotiated=t.clientCapabilities?.session?.compaction!=null,this.signInUrlNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.signInUrl===1;let r=gv(this.config);return{protocolVersion:VZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.21.13-preview.0"},authMethods:r,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated||this.finalAnswersNegotiated||this.sessionNoticesNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:Zj}:{},...this.transcriptUpdatesNegotiated?{transcriptUpdates:cze}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{},...this.finalAnswersNegotiated?{finalAnswers:1}:{},...this.sessionNoticesNegotiated?{sessionNotices:hte}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0},...cB({channel:this.config.getChannel()})?{auth:{logout:{}}}:{}}}}async authenticate({methodId:t}){if(t===mte&&cB({channel:this.config.getChannel()})){await this.matildaAccount.signIn(this.signInUrlNegotiated?r=>this.connection.extNotification(zje,{...r}):void 0);return}let n=Vt.nativeEnum(Ru).parse(t);await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}async logout(){if(!cB({channel:this.config.getChannel()}))throw je.methodNotFound("logout");await this.matildaAccount.signOut()}async newSession({cwd:t,mcpServers:n}){let r=br(t),o=await this.newSessionConfig(t,n,r);await this.ensureAuthenticated(o),this.setupFileSystem(o);let s=await this.createAndStoreSession(o,r),i=this.buildAvailableModels(o),a=this.buildModesData(o),l=this.buildConfigOptions(o);return{sessionId:s.getId(),models:i,modes:a,configOptions:l,_meta:fze(o)}}async loadSession(t){return this.restoreSession(t,!0)}async resumeSession(t){return this.restoreSession(t,!1)}async restoreSession(t,n){let r=this.sessionRestoreCompletions.get(t.sessionId),o,s=new Promise(i=>{o=i});this.sessionRestoreCompletions.set(t.sessionId,s);try{await r;let i=tUt(t),a=nUt(i);if(!await new yi(i,a).sessionExists(t.sessionId))throw je.resourceNotFound(`session:${t.sessionId}`);this.sessions.has(t.sessionId)&&await this.stopSessionAndItsWork(t.sessionId);let c=br(t.cwd),u=await this.newSessionConfig(t.cwd,t.mcpServers??[],c,t.sessionId,!0,i,a),A;try{await this.ensureAuthenticated(u),this.setupFileSystem(u),A=await this.createAndStoreSession(u,c,n?u.getResumedSessionData()?.conversation:void 0)}catch(g){throw await u.getChatRecordingService()?.releaseTranscriptOwnership().catch(()=>{}),g}return await this.#e(u,A),{modes:this.buildModesData(u),models:this.buildAvailableModels(u),configOptions:this.buildConfigOptions(u),_meta:fze(u)}}finally{o(),this.sessionRestoreCompletions.get(t.sessionId)===s&&this.sessionRestoreCompletions.delete(t.sessionId)}}async#e(t,n){try{let r=t.getSessionService().getWorktreeSessionPath(t.getSessionId()),o=await B0(r);o.contextMessage&&(n.pendingWorktreeNotice=o.contextMessage)}catch(r){nc.warn(`ACP worktree restore failed: ${r}`)}}async listSessions(t){let n=t.cwd||process.cwd(),r=t._meta?.size,o=typeof r=="number"&&r>0?Math.floor(r):void 0,s=await Cv(Ja(n),n,()=>new yi(n).listSessions({cursor:t.cursor??void 0,size:o}));return{sessions:s.items.map(a=>({_meta:{createdAt:a.startTime,startTime:a.startTime,preview:a.prompt,...a.gitBranch?{gitBranch:a.gitBranch}:{},...a.titleSource?{titleSource:a.titleSource}:{}},cwd:a.cwd,sessionId:a.sessionId,title:a.customTitle||a.prompt||"(session)",updatedAt:a.lastMessageAt!==void 0?new Date(a.lastMessageAt).toISOString():a.startTime})),nextCursor:s.nextCursor!=null?String(s.nextCursor):void 0}}async setSessionMode(t){let n=this.sessions.get(t.sessionId);if(!n)throw je.invalidParams(void 0,`Session not found for id: ${t.sessionId}`);return n.setMode(t)}async setSessionConfigOption(t){let{sessionId:n,configId:r,value:o}=t,s=this.sessions.get(n);if(!s)throw je.invalidParams(void 0,`Session not found for id: ${n}`);switch(r){case"mode":{await this.setSessionMode({sessionId:n,modeId:o});break}case"model":{await s.setModel({sessionId:n,modelId:o},{persistDefault:!1});break}default:throw je.invalidParams(void 0,`Unsupported configId: ${r}`)}return{configOptions:this.buildConfigOptions(s.getConfig())}}async prompt(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);try{return await n.prompt(t)}catch(r){throw r instanceof l0?new je(r.status,r.message,{code:r.code}):r}}async cancel(t){let n=this.sessions.get(t.sessionId);if(!n)throw new Error(`Session not found: ${t.sessionId}`);await n.cancelPendingPrompt()}loadPermissionSettings(t){return this.settings=Ja(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:ez(t.user.settings)},workspace:{path:t.workspace.path,rules:ez(t.workspace.settings)},merged:ez(t.merged),isTrusted:t.isTrusted}}async buildCoreSettings(t,n){let r=t.user.settings,o=t.workspace.settings,s=this.effectiveSettings(t),i=[];try{let d=new Ac({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await d.refreshCache(),i=d.getLoadedExtensions()}catch(d){nc.warn("Extension loading failed, continuing without extensions:",d)}let a=await Promise.all(i.map(async d=>{let m=await S0(d.config,d.id,"user"),E=await S0(d.config,d.id,"workspace",n),y=d.settings??[];return{id:d.id,name:d.name,version:d.version,isActive:d.isActive,path:d.path,commands:d.commands??[],skills:(d.skills??[]).map(x=>x.name),mcpServers:Object.keys(d.config.mcpServers??{}),settings:y.map(x=>{let b=m[x.envVar],w=E[x.envVar],v=w!==void 0,R=b!==void 0,_=v?w:b,G=v?"workspace":R?"user":void 0;return{name:x.name,description:x.description,envVar:x.envVar,sensitive:!!x.sensitive,userValue:x.sensitive?void 0:b,workspaceValue:x.sensitive?void 0:w,effectiveValue:x.sensitive?void 0:_,effectiveScope:G,hasUserValue:R,hasWorkspaceValue:v}})}})),l=i.filter(d=>d.isActive),c=l.flatMap(d=>g1({mcpServers:d.config.mcpServers??{}},"extension").map(m=>({...m,server:{...m.server,extensionName:d.name}}))),u=l.flatMap(d=>p1({hooks:d.hooks??{}},"extension",d.name)),A=new Map;for(let d of g1(r,"user"))A.set(d.name,d);if(t.isTrusted)for(let d of g1(o,"workspace"))A.set(d.name,d);let g=[...p1(r,"user"),...t.isTrusted?p1(o,"workspace"):[]];return{user:{path:t.user.path,values:bte(r),mcpServers:g1(r,"user"),hooks:p1(r,"user")},workspace:{path:t.workspace.path,values:bte(o),mcpServers:g1(o,"workspace"),hooks:p1(o,"workspace")},merged:{values:bte(s),mcpServers:[...A.values(),...c],hooks:[...g,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){let r=t==="Workspace"?gze(n):void 0,o=new Map;for(let s of this.sessions.values()){let i=s.getConfig(),a=i.storage.getProjectRoot(),l=gze(a);if(r!==void 0&&l!==r)continue;let c=i.getPermissionManager?.();if(c)try{let u=o.get(l);u||(u=ez(Ja(a).merged),o.set(l,u));let A=i.getPermissionsBeyondSettings?.(),g=oUt(c);for(let d of rUt){let m=new Set([...u[d],...A?.[d]??[]]);for(let y of g[d])m.has(y)||c.removePersistentRule(y,d);let E=new Set(g[d]);for(let y of u[d])E.has(y)||c.addPersistentRule(y,d)}}catch(u){nc.warn(`Failed to sync permission rules to a live session: ${u instanceof Error?u.message:String(u)}`)}}}workspaceCwd(t){return t.getTargetDir()}safeWorkspaceCwd(t){try{return this.workspaceCwd(t)}catch{return""}}errorCell(t,n,r){let o=r??lze(n);return{kind:t,status:"error",error:n instanceof Error?n.message:String(n),...o?{errorKind:o}:{}}}buildWorkspaceProvidersStatus(t){try{let n=this.workspaceCwd(t),r=t.getAuthType?.(),o=t.getActiveRuntimeModelSnapshot?.(),s=o?o.id:(t.getModel()||"").trim(),i=s.length>0,a=o?.authType??r,l=i&&a?hy(s,a):s||void 0,c=new Map;for(let d of t.getAllConfiguredModels()){let m=String(d.authType),E=c.get(m);E||(E={kind:"model_provider",status:"ok",authType:m,current:!1,models:[]},c.set(m,E));let y=d.isRuntimeModel&&d.runtimeSnapshotId?d.runtimeSnapshotId:d.id,x=hy(y,d.authType),b=a===d.authType&&i&&(s===y||s===d.id||l===x),w={modelId:x,baseModelId:Kje(y),name:d.label,...d.description!==void 0?{description:d.description}:{},contextLimit:d.contextWindowSize??Jz(y),...d.modalities!==void 0?{modalities:d.modalities}:{},...d.baseUrl!==void 0?{baseUrl:rz(d.baseUrl)}:{},...d.envKey!==void 0?{envKey:d.envKey}:{},isCurrent:b,isRuntime:d.isRuntimeModel===!0};E.models.push(w),b&&(E.current=!0)}let A=t.getContentGeneratorConfig?.()?.baseUrl||void 0,g=this.effectiveSettings().fastModel||void 0;return{v:Xj,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...A?{baseUrl:rz(A)}:{},...g?{fastModelId:g}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:Xj,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!0,providers:[],errors:[this.errorCell("providers",n)]}}}sessionOrThrow(t){let n=this.sessions.get(t);if(!n)throw je.invalidParams(void 0,`Session not found for id: ${t}`);return n}async buildSessionSupportedCommandsStatus(t){let n=this.sessionOrThrow(t),{availableCommands:r,availableSkills:o,availableSkillDetails:s}=await Ste(n.getConfig());return{v:Xj,sessionId:t,availableCommands:r,availableSkills:o??[],...s?{availableSkillDetails:s}:{}}}async installSkillFromUrl(t){let n=this.config.getSkillManager();if(!n)throw je.invalidParams(void 0,"SkillManager is not available");let r=await vUt(t.sourceUrl),o=so.join(Mt.getGlobalMatildaDir(),"skills"),s=mze(o,t.slug),i=so.join(s,"SKILL.md"),a=n.parseSkillContent(r.skillContent,i,"user");if(a.name!==t.slug)throw je.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=`${s}.installing-${process.pid}-${Date.now()}`;try{await bl.rm(l,{recursive:!0,force:!0});for(let c of r.files){let u=RUt(l,c.relativePath);await bl.mkdir(so.dirname(u),{recursive:!0}),await bl.writeFile(u,c.content)}await bl.rm(s,{recursive:!0,force:!0}),await bl.rename(l,s)}catch(c){throw await bl.rm(l,{recursive:!0,force:!0}).catch(()=>{}),c}return await this.refreshSkillCaches(n),{id:t.id,slug:a.name,installed:!0,installedPath:i,sourceUrl:t.sourceUrl}}async deleteGlobalSkill(t){let n=this.config.getSkillManager();if(!n)throw je.invalidParams(void 0,"SkillManager is not available");let{skillDir:r,skillFile:o,content:s}=await this.readManagedSkillFile(t.slug,"global",n),i=n.parseSkillContent(s,o,"user");if(i.name!==t.slug)throw je.invalidParams(void 0,`Skill name "${i.name}" does not match requested slug "${t.slug}"`);let a=so.resolve(r),l=so.resolve(o),c=so.resolve(Mt.getGlobalMatildaDir());if(!(l===so.join(a,"SKILL.md"))||a===so.parse(a).root||a===c)throw je.invalidParams(void 0,`Refusing to delete unexpected skill directory: ${r}`);return await bl.rm(r,{recursive:!0,force:!0}),await this.refreshSkillCaches(n),{slug:t.slug,deleted:!0}}async refreshSkillCaches(t){let n=new Set([t]);for(let r of this.sessions.values()){let o=r.getConfig().getSkillManager();o&&n.add(o)}await Promise.all(Array.from(n,r=>r.refreshCache()))}async readManagedSkillFile(t,n,r,o){if(n==="global"){let c=mze(so.join(Mt.getGlobalMatildaDir(),"skills"),t),u=so.join(c,"SKILL.md"),A=await bl.readFile(u,"utf8").catch(()=>{});if(A!==void 0)return{skillDir:c,skillFile:u,content:A}}if(n==="project"&&o?.trim()){let c=await this.findProjectSkillFileFromCwd(t,o,r);if(c)return c}let s=n==="project"?"project":"user",a=(await r.listSkills({level:s})).find(c=>c.name===t)?.filePath;if(!a)throw je.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`);let l=await bl.readFile(a,"utf8").catch(()=>{throw je.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`)});return{skillDir:so.dirname(a),skillFile:a,content:l}}async findProjectSkillFileFromCwd(t,n,r){let o=so.resolve(n);for(let s of iUt){let i=so.join(o,s,aUt),c=(await r.loadSkillsFromDir(i,"project")).find(A=>A.name===t)?.filePath;if(!c)continue;let u=await bl.readFile(c,"utf8").catch(()=>{throw je.invalidParams(void 0,`Project skill not found: ${t}`)});return{skillDir:so.dirname(c),skillFile:c,content:u}}}async setGlobalSkillEnabled(t,n){let r=this.config.getSkillManager();if(!r)throw je.invalidParams(void 0,"SkillManager is not available");let{skillFile:o,content:s}=await this.readManagedSkillFile(t.slug,t.scope,r,n),i=t.scope==="project"?"project":"user",a=r.parseSkillContent(s,o,i);if(a.name!==t.slug)throw je.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=fUt(s,t.enabled);if(r.parseSkillContent(l,o,i),so.basename(o)!=="SKILL.md")throw je.invalidParams(void 0,`Refusing to write to unexpected skill file: ${o}`);return await bl.writeFile(o,l,"utf8"),await this.refreshSkillCaches(r),{slug:t.slug,enabled:t.enabled,installedPath:o}}async extMethod(t,n){let r=typeof n.cwd=="string"?n.cwd:void 0,o=r||process.cwd(),s=/^[0-9a-fA-F-]{32,36}$/;switch(t){case"matilda/feedback/submit":{let i=_p(n.description,"description");if(i.length>uM)throw je.invalidParams(void 0,"Bug description is too long");return{...await Eb({description:i,envSummary:`${process.platform}/${process.arch}`})}}case Yje:{let{sessionId:i,modelId:a}=n;if(typeof i!="string"||typeof a!="string")throw je.invalidParams(void 0,"sessionId and modelId must be strings");return{...await this.sessionOrThrow(i).setModel({sessionId:i,modelId:a})}}case"matilda/session/attach":{if(!this.backgroundExecutionNegotiated)throw je.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i);if(!a)throw je.resourceNotFound(`session:${i}`);return a.attachClient(),{}}case"matilda/session/readState":{if(!this.sessionStateNegotiated)throw je.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i)?.getSessionState();if(!a)throw je.resourceNotFound(`session:${i}`);return a}case"matilda/workspace/getRoots":{let i=typeof n.sessionId=="string"?n.sessionId:void 0,a=i?this.sessions.get(i):void 0;if(i&&!a)throw je.invalidParams(void 0,`Unknown session: ${i}`);let l=a?.getConfig()??this.config;return{workspaceId:process.env.MATILDA_DESKTOP_WORKSPACE_ID??null,revision:process.env.MATILDA_DESKTOP_DIRECTORY_REVISION??null,canonicalRoots:l.getWorkspaceContext().getDirectories(),restrictiveSandbox:l.isRestrictiveSandbox(),sandbox:process.env.SANDBOX??null,sandboxNonce:process.env.MATILDA_DESKTOP_SANDBOX_ACTIVE??null,seatbeltProfile:process.env.SEATBELT_PROFILE??null}}case"matilda/providers/list":{let i=this.effectiveSettings(Ja(o));return{providers:GR.map(a=>LUt(a,i))}}case"matilda/providers/connect":{let i=_p(n.providerId,"providerId"),a=Wre(i);if(!a)throw je.invalidParams(void 0,`Unknown provider: ${i}`);let l=Ja(o),c=OUt(a,n,_Ut(a,l.merged)),u=PUt(n.scope),A=gA(a,c);return await oC(A,{settings:UC(l,u),reloadModelProviders:g=>{let d=Xk({...l.merged,modelProviders:g},this.argv.channel);this.config.reloadModelProvidersConfig(d.modelProviders)},syncAuthState:(g,d)=>this.config.getModelsConfig().syncAfterAuthRefresh(g,d),refreshAuth:g=>this.config.refreshAuth(g)}),{success:!0,providerId:a.id,providerLabel:a.label,authType:A.authType,modelId:A.modelSelection?.modelId}}case"matilda/skills/install":return this.installSkillFromUrl(cUt(n));case"matilda/skills/delete":return this.deleteGlobalSkill(uUt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(dUt(n),r);case"matilda/settings/getMemory":{let i=Ja(o);return this.settings=i,{settings:pze(this.effectiveSettings(i).memory)}}case"matilda/settings/setMemory":{let i=oi(n.updates),a=Ja(o);for(let l of lUt)if(i[l]!==void 0){if(typeof i[l]!="boolean")throw je.invalidParams(void 0,`Invalid memory setting '${l}': expected boolean`);a.setValue("User",`memory.${l}`,i[l])}return this.settings=a,{settings:pze(this.effectiveSettings(a).memory)}}case"matilda/settings/getPath":return{path:this.settings.user.path};case"matilda/settings/getMemoryPaths":{let i=typeof n.projectRoot=="string"?n.projectRoot:o;return{paths:await VUt({cwd:o,projectRoot:i})}}case"matilda/memory/list":{let i=typeof n.projectRoot=="string"?n.projectRoot:o,a=n.scope;if(a!=="user"&&a!=="project")throw je.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");return{memories:(a==="user"?await Goe():await Hoe(i)).map(c=>({type:c.type,title:c.title,description:c.description,relativePath:c.relativePath,filename:c.filename,mtimeMs:c.mtimeMs}))}}case"matilda/memory/delete":{let i=typeof n.projectRoot=="string"?n.projectRoot:o,a=n.scope;if(a!=="user"&&a!=="project")throw je.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");let l=n.relativePath;if(typeof l!="string"||l.length===0)throw je.invalidParams(void 0,"Invalid or missing relativePath");return await fse({scope:a,projectRoot:i,relativePath:l}),{deleted:!0}}case Bte.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case Bte.sessionSupportedCommands:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw je.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionSupportedCommandsStatus(i)}case xte.sessionClose:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw je.invalidParams(void 0,"Invalid or missing sessionId");return await this.closeSessionAndItsWork(i),{sessionId:i,closed:!0}}case"deleteSession":{let i=n.sessionId;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");return await this.closeSessionAndItsWork(i),{success:await Cv(Ja(o),o,async()=>new yi(o).removeSession(i))}}case xte.sessionRename:{let i=n.sessionId,a=n.title;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(typeof a!="string")throw je.invalidParams(void 0,"Invalid or missing title");if(a.length>HR)throw je.invalidParams(void 0,`Title too long (max ${HR} chars)`);let l=n.titleSource==="auto"?"auto":"manual",c=this.sessions.get(i)?.getConfig().getChatRecordingService();return c?{success:await c.recordCustomTitleCommitted(a,l,{notifyObservers:!1})}:{success:await Cv(Ja(o),o,async()=>new yi(o).renameSession(i,a,l))}}case"rewindSession":{let i=n.sessionId;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i);if(!a)throw je.invalidParams(void 0,`Session not found for id: ${i}`);let l=n.targetTurnIndex,c=n.promptId;if(c&&l==null){let E=i+"########";if(!c.startsWith(E))throw new je(-32602,"Invalid promptId format",{errorKind:"invalid_rewind_target"});let y=c.slice(E.length);if(!/^\d+$/.test(y))throw new je(-32602,"Invalid promptId: non-numeric turn suffix",{errorKind:"invalid_rewind_target"});let w=a.getConfig().getFileHistoryService().getSnapshots().findIndex(v=>v.promptId===c);if(w<0)throw new je(-32602,"Snapshot not found for the given promptId",{errorKind:"invalid_rewind_target"});l=w}if(!Number.isInteger(l)||l<0)throw je.invalidParams(void 0,"Invalid or missing targetTurnIndex");let u=a.captureHistorySnapshot(),A;try{A=await a.rewindToTurn(l)}catch(E){if(E instanceof je){let y=E.message;if(y.includes("Cannot rewind while a prompt is running"))throw new je(E.code,y,{errorKind:"session_busy"});if(y.includes("compressed or does not exist"))throw new je(E.code,y,{errorKind:"invalid_rewind_target"})}throw E}let g=[],d=[];if(n.rewindFiles!==!1&&c){let E=a.getConfig().getFileHistoryService();try{let y=await E.rewind(c,!0);g=y.filesChanged,d=y.filesFailed}catch(y){let x=y instanceof Error?y.message:String(y);nc.error(`[ACP] File-history rewind failed for session=${i} promptId=${c}: ${x}`),d=[`file-history-rewind: ${x}`]}}return{success:!0,historyBeforeRewind:u,...A,filesChanged:g,filesFailed:d}}case"matilda/session/readTranscript":{if(!this.transcriptReadNegotiated)throw je.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");let a=Sze.optional().safeParse(n.cursor);if(!a.success)throw je.invalidParams(void 0,"Invalid transcript cursor");if(this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let l=this.sessions.get(i);if(!l)throw je.resourceNotFound(`session:${i}`);let c=await l.readTranscript(a.data);if(this.sessions.get(i)!==l||this.sessionRestoreCompletions.has(i))throw new je(-32e3,"Session changed during transcript read",{errorKind:"session_busy"});let u=this.sessionStateNegotiated?l.getSessionState():void 0,A={processing:!l.isIdle(),...u?{state:u}:{}};if(n.updates!==!0)return{version:Zj,sessionId:i,...c,runtime:A};if(!this.transcriptUpdatesNegotiated)throw je.invalidParams(void 0,"Transcript updates were not negotiated");let g=c.mode==="delta"?ZPt(n.projection,a.data):void 0,d=c.mode==="snapshot"||g&&!eUt(c.records,a.data.selectedLeafUuid)?c:await l.readTranscript(),m=d.mode==="delta"?g:void 0,E=m?{...m.usage}:{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0},y=[],x=yi.reconstructHistory(d.records),b=await new uB({sessionId:i,config:this.config,sendUpdate:async w=>{y.push(w)},cumulativeUsage:E},!0,l.getActiveTaskStartUuid(),this.finalAnswersNegotiated,this.compactionUpdatesNegotiated).replay(x,m?{continuation:m.continuation,partial:!0,messageIdOf:w=>l.committedMessageIdOf(w)??w}:{});return{version:Zj,sessionId:i,mode:m?"delta":"snapshot",cursor:d.cursor,updates:Aze(y),transcriptRecords:dze(x),...d.cursor?{projection:uze({v:1,cursor:d.cursor,continuation:b,usage:E})}:{},runtime:A}}case"matilda/session/loadUpdates":{let i=n.sessionId;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i)?.getActiveTaskStartUuid(),l=await Cv(Ja(o),o,async()=>new yi(o).loadSession(i));if(!l?.conversation)return{updates:[]};let c=[],u={sessionId:i,config:this.config,sendUpdate:async y=>{c.push(y)},cumulativeUsage:{promptTokens:0,cachedTokens:0,candidateTokens:0,apiTimeMs:0}},A,g;try{g=await new uB(u,n.taskOutcomesVersion===1,this.sessions.get(i)?.getActiveTaskStartUuid()??a,this.finalAnswersNegotiated,this.compactionUpdatesNegotiated).replay(l.conversation.messages)}catch(y){A=y instanceof Error?y.message:String(y),nc.warn("[loadUpdates] History replay failed for session %s (partial updates: %d):",i,c.length,y)}let d=l.transcriptCursor,m=Bre(l.conversation.messages),E=m.kind==="v2"?Gj(m.payload.snapshot):null;return{updates:Aze(c),transcriptRecords:dze(l.conversation.messages),...E?{goal:E}:{},...this.transcriptUpdatesNegotiated&&d&&g?{transcript:d,projection:uze({v:1,cursor:d,continuation:g,usage:u.cumulativeUsage})}:{},startTime:l.conversation.startTime,lastUpdated:l.conversation.lastUpdated,...A!==void 0?{partial:!0,replayError:A}:{}}}case"matilda/session/appendHistory":{let i=Vt.object({sessionId:Vt.string().regex(s),messages:Vt.array(Vt.object({id:Vt.string().uuid(),role:Vt.enum(["user","assistant"]),content:Vt.string(),timestamp:Vt.number().finite().min(0).max(864e13)}))}).safeParse(n);if(!i.success)throw je.invalidParams(void 0,"Invalid imported history");let a=this.sessions.get(i.data.sessionId);if(!a)throw je.invalidParams(void 0,"Session not found");return{success:!0,selectedMessageIds:await a.appendImportedHistory(i.data.messages)}}case"restoreSessionHistory":{let i=n.sessionId,a=n.history;if(!i||!s.test(i))throw je.invalidParams(void 0,"Invalid or missing sessionId");if(!Array.isArray(a))throw je.invalidParams(void 0,"Invalid or missing history");let l=this.sessions.get(i);if(!l)throw je.invalidParams(void 0,`Session not found for id: ${i}`);return l.restoreHistory(a),{success:!0}}case Wje:return this.matildaAccountState?.cancelSignIn(),{};case"getAccountInfo":{let i=n.sessionId,a=i?this.sessions.get(i):void 0,l=a?a.getConfig():this.config,c=l.getContentGeneratorConfig();return{authType:c?.authType??l.getAuthType()??null,model:c?.model??l.getModel()??null,baseUrl:c?.baseUrl?rz(c.baseUrl):null,apiKeyEnvKey:c?.apiKeyEnvKey??null,account:qje(c?.baseUrl,l.getChannel())}}case"matilda/settings/getCore":{let i=Ja(o);return this.settings=i,this.buildCoreSettings(i,o)}case"matilda/settings/setCoreValue":{let i=n.key;if(typeof i!="string"||!xze.includes(i))throw je.invalidParams(void 0,"Unsupported Matilda setting key");let a=Ja(o),l=i,c=HUt(l,n.value),u=dB(n.scope);return a.setValue(u,i,c),l==="general.outputLanguage"&&typeof c=="string"&&u==="User"&&h6(c),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/setMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw je.invalidParams(void 0,"MCP server name is required");let a=Ja(o),l=dB(n.scope),c=l==="Workspace"?"workspace":"user",u=nz(a,c),A=oi(u.mcpServers),g={...A,[i.trim()]:jUt(qUt(GUt(n.server),oi(A[i.trim()])))};return a.setValue(l,"mcpServers",g),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/removeMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw je.invalidParams(void 0,"MCP server name is required");let a=Ja(o),l=dB(n.scope),c=l==="Workspace"?"workspace":"user",u=nz(a,c),A={...oi(u.mcpServers)};return delete A[i.trim()],a.setValue(l,"mcpServers",A),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/setHook":{let i=n.event;if(!Eze(i))throw je.invalidParams(void 0,"Invalid hook event");let a=Ja(o),l=dB(n.scope),c=l==="Workspace"?"workspace":"user",u=nz(a,c),A={...oi(u.hooks)},g=Array.isArray(A[i])?[...A[i]]:[],d=_ze(n.hook),m=n.index,E=typeof m=="number"&&Number.isInteger(m)&&m>=0&&m<g.length,y=JUt(d,E?oi(g[m]):{});return E?g[m]=y:g.push(y),A[i]=g,a.setValue(l,"hooks",A),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/removeHook":{let i=n.event;if(!Eze(i))throw je.invalidParams(void 0,"Invalid hook event");let a=n.index;if(typeof a!="number"||!Number.isInteger(a)||a<0)throw je.invalidParams(void 0,"Invalid hook index");let l=Ja(o),c=dB(n.scope),u=c==="Workspace"?"workspace":"user",A=nz(l,u),g={...oi(A.hooks)},d=Array.isArray(g[i])?[...g[i]]:[];if(a>=d.length)throw je.invalidParams(void 0,`Hook index ${a} out of range (event has ${d.length} hooks)`);return d.splice(a,1),g[i]=d,l.setValue(c,"hooks",g),this.settings=l,this.buildCoreSettings(l,o)}case"matilda/settings/setExtensionSetting":{let i=n.extensionId,a=n.settingKey,l=n.value;if(typeof i!="string"||!i)throw je.invalidParams(void 0,"extensionId is required");if(typeof a!="string"||!a)throw je.invalidParams(void 0,"settingKey is required");if(typeof l!="string")throw je.invalidParams(void 0,"value must be a string");let c=Ja(o),u=new Ac({workspaceDir:o,isWorkspaceTrusted:c.isTrusted});await u.refreshCache();let A=u.getLoadedExtensions().find(d=>d.id===i||d.name===i);if(!A)throw je.invalidParams(void 0,"Extension not found");let g=dB(n.scope)==="Workspace"?"workspace":"user";return await G_(A.config,A.id,a,async()=>l,g,o),this.settings=c,this.buildCoreSettings(c,o)}case"matilda/permissions/getSettings":{let i=this.loadPermissionSettings(o);return this.buildPermissionSettings(i)}case"matilda/permissions/setRules":{let i=n.scope,a=n.ruleType;if(i!=="user"&&i!=="workspace")throw je.invalidParams(void 0,'scope must be "user" or "workspace"');if(a!=="allow"&&a!=="ask"&&a!=="deny")throw je.invalidParams(void 0,'ruleType must be "allow", "ask", or "deny"');let l=this.loadPermissionSettings(o),c=sUt(n.rules),u=i==="workspace"?"Workspace":"User";return l.setValue(u,`permissions.${a}`,c),this.syncLivePermissionManagers(u,o),this.buildPermissionSettings(l)}default:throw je.methodNotFound(t)}}async newSessionConfig(t,n,r,o,s,i,a){let l={};for(let d of n){let m=KUt(d);if(m){let x={};for(let{name:b,value:w}of m.env)x[b]=w;l[m.name]=new q_(m.command,m.args,x,t);continue}let E=XUt(d);if(E){let x={};for(let{name:b,value:w}of E.headers)x[b]=w;l[E.name]=new q_(void 0,void 0,void 0,void 0,E.url,void 0,Object.keys(x).length>0?x:void 0);continue}let y=ZUt(d);if(y){let x={};for(let{name:b,value:w}of y.headers)x[b]=w;l[y.name]=new q_(void 0,void 0,void 0,void 0,void 0,y.url,Object.keys(x).length>0?x:void 0);continue}}let c=r.merged,u={...this.argv,...s?{resume:o}:{sessionId:o},sandboxSessionId:void 0,continue:!1},A=await eM(c,u,t,void 0,{userHooks:r.getUserHooks(),projectHooks:r.getProjectHooks()},Zk(r),l,i,a);!(this.argv.channel==="desktop"&&process.env.MATILDA_TEMPORARY_SESSION)&&typeof A.enableFileCheckpointing=="function"&&A.enableFileCheckpointing(),typeof A.setMcpTransportPool=="function"&&A.setMcpTransportPool(this.mcpPool);try{await A.initialize(),await A.waitForMcpReady()}catch(d){throw await A.getChatRecordingService()?.releaseTranscriptOwnership().catch(()=>{}),d}let g=typeof A.getFailedMcpServerNames=="function"?A.getFailedMcpServerNames():[];return g.length>0&&process.stderr.write(`Warning: MCP server(s) failed to start: ${g.join(", ")}. Continuing with built-in tools and any servers that did connect.
|
|
932
932
|
`),A}async ensureAuthenticated(t){let n=t.getModelsConfig().getCurrentAuthType();if(!n)throw je.authRequired({authMethods:gv(t)},"Use Matilda CLI to authenticate first.");try{await t.refreshAuth(n)}catch(r){throw nc.error(`Authentication failed: ${r}`),je.authRequired({authMethods:gv(t)},"Authentication failed: "+r.message)}}setupFileSystem(t){if(!this.clientCapabilities?.fs)return;let n=new Uj(this.connection,t.getSessionId(),this.clientCapabilities.fs,t.getFileSystemService());t.setFileSystemService(n)}async createAndStoreSession(t,n,r){let o=t.getSessionId(),s=t.getGeminiClient();!s.isInitialized()&&await s.initialize();let a=new Kj(o,t,this.connection,n,{waitForClientAttachment:this.backgroundExecutionNegotiated});return this.sessions.set(o,a),this.sessionNoticesNegotiated&&a.enableSessionNotices(),this.backgroundExecutionNegotiated&&a.enableBackgroundExecutionNotifications(),this.sessionStateNegotiated&&a.enableSessionStateNotifications(),this.finalAnswersNegotiated&&a.enableFinalAnswers(),this.compactionUpdatesNegotiated&&a.enableCompactionUpdates(),setTimeout(async()=>{await a.sendAvailableCommandsUpdate()},0),r&&r.messages&&await a.replayHistory(r.messages),a.installRewriter(),a.startCronScheduler(),a}buildAvailableModels(t){let n=(t.getModel()||this.config.getModel()||"").trim(),r=t.getAuthType(),o=t.getAllConfiguredModels(),s=t.getActiveRuntimeModelSnapshot?.(),i=s?hy(s.id,s.authType):this.formatCurrentModelId(n,r),a=o.map(l=>{let c=l.isRuntimeModel&&l.runtimeSnapshotId?l.runtimeSnapshotId:l.id;return{modelId:hy(c,l.authType),name:l.label,description:l.description??null,_meta:{contextLimit:l.contextWindowSize??Jz(l.id)}}});return{currentModelId:i,availableModels:a}}buildModesData(t){let n=t.getApprovalMode(),r=fc.map(o=>({id:o,name:qR[o].name,description:qR[o].description}));return{currentModeId:n,availableModes:r}}buildConfigOptions(t){let n=t.getApprovalMode(),r=t.getAllConfiguredModels(),o=(t.getModel()||"").trim(),s=t.getAuthType?.(),i=t.getActiveRuntimeModelSnapshot?.(),a=i?hy(i.id,i.authType):this.formatCurrentModelId(o,s),l=fc.map(g=>({value:g,name:qR[g].name,description:qR[g].description})),c={id:"mode",name:"Mode",description:"Session permission mode",category:"mode",type:"select",currentValue:n,options:l},u=r.map(g=>{let d=g.isRuntimeModel&&g.runtimeSnapshotId?g.runtimeSnapshotId:g.id;return{value:hy(d,g.authType),name:g.label,description:g.description??""}});return[c,{id:"model",name:"Model",description:"AI model to use",category:"model",type:"select",currentValue:a,options:u}]}formatCurrentModelId(t,n){return t&&(n?hy(t,n):t)}};var Zd=M(re(),1);var Iy=$e("STARTUP");function kte(){delete process.env[fx],delete process.env[gx]}function oHt(e){let t="ipv4first";return e===void 0?t:e==="ipv4first"||e==="verbatim"?e:(it(`Invalid value for dnsResolutionOrder in settings: "${e}". Using default "${t}".`),t)}function sHt(e){let t=tHt.totalmem()/1048576,n=rHt.getHeapStatistics(),r=Math.floor(n.heap_size_limit/1024/1024),o=Math.floor(t*.5);return e&&it(`Current heap size ${r.toFixed(2)} MB`),process.env.MATILDA_CODE_NO_RELAUNCH?[]:o>r?(e&&it(`Need to relaunch with more memory: ${o.toFixed(2)} MB`),[`--max-old-space-size=${o}`]):[]}function iHt(){let e=!1;process.on("unhandledRejection",(t,n)=>{let r=`=========================================
|
|
933
933
|
This is an unexpected error. Please file a bug report using the /bug tool.
|
|
934
934
|
CRITICAL: Unhandled Promise Rejection!
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maincode-ai/matilda-code",
|
|
3
|
-
"version": "0.21.13-
|
|
3
|
+
"version": "0.21.13-preview.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "cli.js",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"bundled"
|
|
27
27
|
],
|
|
28
28
|
"config": {
|
|
29
|
-
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.13-
|
|
29
|
+
"sandboxImageUri": "ghcr.io/maincode/matilda-code:0.21.13-preview.0"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {},
|
|
32
32
|
"optionalDependencies": {
|