@maincode-ai/matilda-code 0.22.0-nightly.20261101.b0ad315a4 → 0.22.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.
Files changed (2) hide show
  1. package/cli.js +4 -4
  2. 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 N9(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=_Ke(e,t);return n?{line:r.line+1,column:r.column+1}:r}var LKe=e=>`\\u{${e.codePointAt(0).toString(16)}}`,_9=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??=`${PKe(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=OKe(n,this.#t.message);if(r)return(0,bge.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}},OKe=(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)}:N9(e,Number(r),{oneBased:!0})},PKe=e=>e.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,n,r)=>`"${r}"(${LKe(r)})`);function L9(e,t,n){typeof t=="string"&&(n=t,t=void 0);try{return JSON.parse(e,t)}catch(r){throw new _9({jsonParseError:r,fileName:n,input:e})}}var _pe=M(Fpe(),1);h();import{fileURLToPath as cZe}from"node:url";function Npe(e){return e instanceof URL?cZe(e):e}var AZe=e=>dZe.resolve(Npe(e)??".","package.json"),fZe=(e,t)=>{let n=typeof e=="string"?L9(e):e;return t&&(0,_pe.default)(n),n};async function Lpe({cwd:e,normalize:t=!0}={}){let n=await uZe.readFile(AZe(e),"utf8");return fZe(n,t)}async function Ope(e){let t=await tge("package.json",e);if(t)return{packageJson:await Lpe({...e,cwd:gZe.dirname(t)}),path:t}}import{fileURLToPath as pZe}from"node:url";import mZe from"node:path";var hZe=pZe(import.meta.url),CZe=mZe.dirname(hZe),nO;async function Ex(){if(nO)return nO;let e=await Ope({cwd:CZe});if(e)return nO=e.packageJson,nO}async function Lg(){let e=await Ex();return"0.22.0-nightly.20261101.b0ad315a4"}h();var JQ=M(qpe(),1);import*as Ype from"node:os";var Jpe=["docker","podman","sandbox-exec"];function wZe(e){return Jpe.includes(e)}function TZe(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(!wZe(e))throw new ya(`Invalid sandbox command '${e}'. Must be one of ${Jpe.join(", ")}`);if(JQ.default.sync(e))return e;throw new ya(`Missing sandbox command '${e}' (from MATILDA_SANDBOX)`)}if(Ype.platform()==="darwin"&&JQ.default.sync("sandbox-exec"))return"sandbox-exec";if(JQ.default.sync("docker")&&e===!0)return"docker";if(JQ.default.sync("podman")&&e===!0)return"podman";if(e===!0)throw new ya("MATILDA_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in MATILDA_SANDBOX");return""}async function oO(e,t){let n=t.sandbox??e.tools?.sandbox,r=TZe(n),o=await Ex(),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 vZe}from"node:events";var sl=new vZe;h();h();async function RZe(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:B,oauthScopes:b}=r,w=hr(process.cwd()),v=w.workspace.path===w.user.path;o==="project"&&v&&(st("Error: Please use --scope user to edit settings in the home directory."),process.exit(1));let Q=o==="user"?"User":"Workspace",O={},z=b?.flatMap(_=>_.split(",")).map(_=>_.trim()).filter(Boolean),q=!!(d||m||E||y||B||z&&z.length>0);q&&s==="stdio"&&(st("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http."),process.exit(1));let j=q?{enabled:!0,...d&&{clientId:d},...m&&{clientSecret:m},...E&&{redirectUri:E},...y&&{authorizationUrl:y},...B&&{tokenUrl:B},...z&&z.length>0&&{scopes:z}}:void 0,P=a?.reduce((_,H)=>{let[Y,...k]=H.split(":"),G=k.join(":").trim();return Y.trim()&&G&&(_[Y.trim()]=G),_},{});switch(s){case"sse":O={url:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"http":O={httpUrl:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"stdio":default:O={command:t,args:n?.map(String),env:i?.reduce((_,H)=>{let[Y,k]=H.split("=");return Y&&k&&(_[Y]=k),_},{}),timeout:l,trust:c,description:u,includeTools:A,excludeTools:g};break}let N=w.forScope(Q).settings.mcpServers||{},L=!!N[e];L&&St(`MCP server "${e}" is already configured within ${o} settings.`),N[e]=O,w.setValue(Q,"mcpServers",N),L?St(`MCP server "${e}" updated in ${o} settings.`):St(`MCP server "${e}" added to ${o} settings. (${s})`)}var $pe={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 RZe(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 QZe(e,t){let{scope:n}=t,r=n==="user"?"User":"Workspace",o=hr(),i=o.forScope(r).settings.mcpServers||{};if(!i[e]){St(`Server "${e}" not found in ${n} settings.`);return}delete i[e],o.setValue(r,"mcpServers",i);try{await new Vy().deleteCredentials(e)}catch{}St(`Server "${e}" removed from ${n} settings.`)}var Vpe={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 QZe(e.name,{scope:e.scope})}};h();h();h();var Zpe=M(II(),1);import*as Kpe from"node:fs";import*as Xpe from"node:path";var kZe=".mcp.json",MZe={servers:{},path:void 0,errors:[]};function eme(e){let t=Xpe.join(e,kZe),n;try{n=Kpe.readFileSync(t,"utf-8")}catch{return MZe}let r;try{r=JSON.parse((0,Zpe.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 DC(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=eme(t);for(let i of s.errors)st(`Warning: ${i}`);return{...r,...s.servers,...o,...n??{}}}h();import*as $I from"node:fs";import*as Ix from"node:path";var nme=M(II(),1);var FZe="mcpApprovals.json";function NZe(){return process.env.MATILDA_CODE_MCP_APPROVALS_PATH?process.env.MATILDA_CODE_MCP_APPROVALS_PATH:Ix.join(Ft.getGlobalMatildaDir(),FZe)}function tme(e){return Ix.resolve(e)}var l5=class{constructor(t,n){this.file=t;this.errors=n}getState(t,n,r){let o=this.file.config[tme(t)]?.[n];return!o||o.hash!==Gj(r)?"pending":o.status}async setState(t,n,r,o){let s=tme(t),i=this.file.config[s],a=i&&typeof i=="object"&&!Array.isArray(i)?i:Object.create(null);Object.defineProperty(a,n,{value:{hash:Gj(r),status:o},enumerable:!0,configurable:!0,writable:!0}),this.file.config[s]=a,await _Ze(this.file)}},sO;function SC(){if(sO)return sO;let e=[],t={},n=NZe();try{if($I.existsSync(n)){let r=$I.readFileSync(n,"utf-8"),o=JSON.parse((0,nme.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:xr(r),path:n})}sO=new l5({path:n,config:t},e);for(let r of e)st(`Warning: MCP approvals file error: ${r.message}`);return sO}function iO(e,t){let n=SC(),r=[];for(let[o,s]of Object.entries(e))Yh(s.scope)&&n.getState(t,o,s)!=="approved"&&r.push(o);return r}async function _Ze(e){try{let t=Ix.dirname(e.path);$I.existsSync(t)||$I.mkdirSync(t,{recursive:!0}),await qte(e.path,JSON.stringify(e.config,null,2),{mode:384})}catch(t){st("Error saving MCP approvals file."),st(t instanceof Error?t.message:String(t))}}h();h();toe();import{stripVTControlCharacters as PZe}from"node:util";h();var sme=M(ome(),1),LZe=new Intl.Segmenter,OZe=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function In(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=Po(e)),e.length===0)return 0;let o=0,s={ambiguousAsWide:!n};for(let{segment:i}of LZe.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)&&!OZe.test(i)){if((0,sme.default)().test(i)){o+=2;continue}o+=dc(a,s)}}return o}var d5=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=OKe(n,this.#t.message);if(r)return(0,bge.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}},OKe=(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)}:N9(e,Number(r),{oneBased:!0})},PKe=e=>e.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,n,r)=>`"${r}"(${LKe(r)})`);function L9(e,t,n){typeof t=="string"&&(n=t,t=void 0);try{return JSON.parse(e,t)}catch(r){throw new _9({jsonParseError:r,fileName:n,input:e})}}var _pe=M(Fpe(),1);h();import{fileURLToPath as cZe}from"node:url";function Npe(e){return e instanceof URL?cZe(e):e}var AZe=e=>dZe.resolve(Npe(e)??".","package.json"),fZe=(e,t)=>{let n=typeof e=="string"?L9(e):e;return t&&(0,_pe.default)(n),n};async function Lpe({cwd:e,normalize:t=!0}={}){let n=await uZe.readFile(AZe(e),"utf8");return fZe(n,t)}async function Ope(e){let t=await tge("package.json",e);if(t)return{packageJson:await Lpe({...e,cwd:gZe.dirname(t)}),path:t}}import{fileURLToPath as pZe}from"node:url";import mZe from"node:path";var hZe=pZe(import.meta.url),CZe=mZe.dirname(hZe),nO;async function Ex(){if(nO)return nO;let e=await Ope({cwd:CZe});if(e)return nO=e.packageJson,nO}async function Lg(){let e=await Ex();return"0.22.0"}h();var JQ=M(qpe(),1);import*as Ype from"node:os";var Jpe=["docker","podman","sandbox-exec"];function wZe(e){return Jpe.includes(e)}function TZe(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(!wZe(e))throw new ya(`Invalid sandbox command '${e}'. Must be one of ${Jpe.join(", ")}`);if(JQ.default.sync(e))return e;throw new ya(`Missing sandbox command '${e}' (from MATILDA_SANDBOX)`)}if(Ype.platform()==="darwin"&&JQ.default.sync("sandbox-exec"))return"sandbox-exec";if(JQ.default.sync("docker")&&e===!0)return"docker";if(JQ.default.sync("podman")&&e===!0)return"podman";if(e===!0)throw new ya("MATILDA_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in MATILDA_SANDBOX");return""}async function oO(e,t){let n=t.sandbox??e.tools?.sandbox,r=TZe(n),o=await Ex(),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 vZe}from"node:events";var sl=new vZe;h();h();async function RZe(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:B,oauthScopes:b}=r,w=hr(process.cwd()),v=w.workspace.path===w.user.path;o==="project"&&v&&(st("Error: Please use --scope user to edit settings in the home directory."),process.exit(1));let Q=o==="user"?"User":"Workspace",O={},z=b?.flatMap(_=>_.split(",")).map(_=>_.trim()).filter(Boolean),q=!!(d||m||E||y||B||z&&z.length>0);q&&s==="stdio"&&(st("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http."),process.exit(1));let j=q?{enabled:!0,...d&&{clientId:d},...m&&{clientSecret:m},...E&&{redirectUri:E},...y&&{authorizationUrl:y},...B&&{tokenUrl:B},...z&&z.length>0&&{scopes:z}}:void 0,P=a?.reduce((_,H)=>{let[Y,...k]=H.split(":"),G=k.join(":").trim();return Y.trim()&&G&&(_[Y.trim()]=G),_},{});switch(s){case"sse":O={url:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"http":O={httpUrl:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"stdio":default:O={command:t,args:n?.map(String),env:i?.reduce((_,H)=>{let[Y,k]=H.split("=");return Y&&k&&(_[Y]=k),_},{}),timeout:l,trust:c,description:u,includeTools:A,excludeTools:g};break}let N=w.forScope(Q).settings.mcpServers||{},L=!!N[e];L&&St(`MCP server "${e}" is already configured within ${o} settings.`),N[e]=O,w.setValue(Q,"mcpServers",N),L?St(`MCP server "${e}" updated in ${o} settings.`):St(`MCP server "${e}" added to ${o} settings. (${s})`)}var $pe={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 RZe(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 QZe(e,t){let{scope:n}=t,r=n==="user"?"User":"Workspace",o=hr(),i=o.forScope(r).settings.mcpServers||{};if(!i[e]){St(`Server "${e}" not found in ${n} settings.`);return}delete i[e],o.setValue(r,"mcpServers",i);try{await new Vy().deleteCredentials(e)}catch{}St(`Server "${e}" removed from ${n} settings.`)}var Vpe={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 QZe(e.name,{scope:e.scope})}};h();h();h();var Zpe=M(II(),1);import*as Kpe from"node:fs";import*as Xpe from"node:path";var kZe=".mcp.json",MZe={servers:{},path:void 0,errors:[]};function eme(e){let t=Xpe.join(e,kZe),n;try{n=Kpe.readFileSync(t,"utf-8")}catch{return MZe}let r;try{r=JSON.parse((0,Zpe.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 DC(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=eme(t);for(let i of s.errors)st(`Warning: ${i}`);return{...r,...s.servers,...o,...n??{}}}h();import*as $I from"node:fs";import*as Ix from"node:path";var nme=M(II(),1);var FZe="mcpApprovals.json";function NZe(){return process.env.MATILDA_CODE_MCP_APPROVALS_PATH?process.env.MATILDA_CODE_MCP_APPROVALS_PATH:Ix.join(Ft.getGlobalMatildaDir(),FZe)}function tme(e){return Ix.resolve(e)}var l5=class{constructor(t,n){this.file=t;this.errors=n}getState(t,n,r){let o=this.file.config[tme(t)]?.[n];return!o||o.hash!==Gj(r)?"pending":o.status}async setState(t,n,r,o){let s=tme(t),i=this.file.config[s],a=i&&typeof i=="object"&&!Array.isArray(i)?i:Object.create(null);Object.defineProperty(a,n,{value:{hash:Gj(r),status:o},enumerable:!0,configurable:!0,writable:!0}),this.file.config[s]=a,await _Ze(this.file)}},sO;function SC(){if(sO)return sO;let e=[],t={},n=NZe();try{if($I.existsSync(n)){let r=$I.readFileSync(n,"utf-8"),o=JSON.parse((0,nme.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:xr(r),path:n})}sO=new l5({path:n,config:t},e);for(let r of e)st(`Warning: MCP approvals file error: ${r.message}`);return sO}function iO(e,t){let n=SC(),r=[];for(let[o,s]of Object.entries(e))Yh(s.scope)&&n.getState(t,o,s)!=="approved"&&r.push(o);return r}async function _Ze(e){try{let t=Ix.dirname(e.path);$I.existsSync(t)||$I.mkdirSync(t,{recursive:!0}),await qte(e.path,JSON.stringify(e.config,null,2),{mode:384})}catch(t){st("Error saving MCP approvals file."),st(t instanceof Error?t.message:String(t))}}h();h();toe();import{stripVTControlCharacters as PZe}from"node:util";h();var sme=M(ome(),1),LZe=new Intl.Segmenter,OZe=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function In(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(r||(e=Po(e)),e.length===0)return 0;let o=0,s={ambiguousAsWide:!n};for(let{segment:i}of LZe.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)&&!OZe.test(i)){if((0,sme.default)().test(i)){o+=2;continue}o+=dc(a,s)}}return o}var d5=e=>{if(!e)return 0;let t=e.split(`
281
281
  `);return Math.max(...t.map(n=>ea(n)))},ime=new Map,ame=1e3;function co(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<=ame){let r=ime.get(e);if(r)return r}let n=Array.from(e);return e.length<=ame&&ime.set(e,n),n}function Rt(e){return co(e).length}function dn(e,t,n){return co(e).slice(t,n).join("")}function um(e){let t=Po(e),n=PZe(t);return co(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 c5=new Map,ea=e=>{if(/^[\x20-\x7E]*$/.test(e))return e.length;if(c5.has(e))return c5.get(e);let t=In(e);return c5.set(e,t),t};var u5=eoe();function ds(e){if(typeof e=="string")return e.search(u5)===-1?e:(u5.lastIndex=0,e.replace(u5,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=ds(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=ds(o);s!==o&&(t===null&&(t={...e}),t[r]=s)}return t!==null?t:e}var UZe=[{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 lme(e,t=200){let n=e;for(let{pattern:r,replacement:o}of UZe)n=n.replace(r,o);return n.length>t?t<=3?n.slice(0,t):n.slice(0,t-3)+"...":n}var HZe=/[\x00-\x1f\x7f-\x9f]/g;function cme(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 Dx(e){return ds(e).replace(HZe,cme)}var GZe=/[\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 Ru(e){return e.replace(GZe,ume)}var zZe=/[\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 aO(e){return e.replace(zZe,t=>t.length>2?t:ume(t))}function ume(e){let t=e.codePointAt(0);return t>65535?`\\u{${t.toString(16)}}`:cme(e)}h();var dme=["user","project","workspace","system","extension"];var jZe=10;function WZe(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 Ame(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 dme){let o=t.get(r);o&&o.length>0&&n.push({source:r,displayName:WZe(r),servers:o})}return n}function lO(e){switch(e){case"connected":return"green";case"connecting":return"yellow";case"disconnected":return"red";default:return"gray"}}function cO(e){switch(e){case"connected":return"\u2713";case"connecting":return"\u2026";case"disconnected":return"\u2717";default:return"?"}}function fme(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 uO(e){return e?e.split(/\r?\n/).map(t=>um(t.slice(t.lastIndexOf("\r")+1)).replace(/\t/g," ").trimEnd()).filter(t=>t.trim()!=="").slice(-jZe):[]}function gme(e,t){return!!e&&!!t}function pme(e,t){let n=[];return e||n.push(C("missing name")),t||n.push(C("missing description")),n}var qZe="\x1B[32m",mme="\x1B[33m",YZe="\x1B[31m",dO="\x1B[0m";async function JZe(){let e=hr(),t=new lc({isWorkspaceTrusted:!!js(e.merged),telemetrySettings:e.merged.telemetry});await t.refreshCache();let n=t.getLoadedExtensions(),r=DC(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 $Ze(e,t){let n=new mne({name:"mcp-test-client",version:"0.0.1"}),r;try{r=await xne(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 VZe(e,t){return await $Ze(e,t)}async function KZe(){let e=await JZe(),t=Object.keys(e);if(t.length===0){St("No MCP servers configured.");return}St(`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)`),Yh(s.scope)){r??=SC();let u=r.getState(n,o,s);if(u!=="approved"){St(`${mme}\u25CF${dO} ${i} - ${u==="rejected"?"Rejected":"Pending approval"}`);continue}}let a=await VZe(o,s),l="",c="";switch(a){case"connected":l=qZe+"\u2713"+dO,c="Connected";break;case"connecting":l=mme+"\u2026"+dO,c="Connecting";break;case"disconnected":default:l=YZe+"\u2717"+dO,c="Disconnected";break}if(St(`${l} ${i} - ${c}`),a==="disconnected"){let u=uO(j1(o));if(u.length>0){St(" Last stderr output:");for(let A of u)St(` ${A}`)}}}}var hme={command:"list",describe:"List all configured MCP servers",handler:async()=>{await KZe()}};h();async function A5(e){let t=hr(),n=e??new lc({isWorkspaceTrusted:!!js(t.merged),telemetrySettings:t.merged.telemetry});e||await n.refreshCache();let r=n.getLoadedExtensions(),o=DC(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 Eme(){let e=hr(),t=process.cwd(),n=new m_(t),r=await A5(),o=new B_({sessionId:"mcp-reconnect",targetDir:t,cwd:t,debugMode:!1,mcpServers:r,pendingMcpServers:iO(r,t),fileDiscoveryService:n,mcpServerCommand:e.merged.mcp?.serverCommand});return await o.initialize(),o}function Cme(e,t=1){let n=new Error(e);return n.exitCode=t,n}async function XZe(e){if(!(await A5())[e])throw Cme(`Error: Server "${e}" not found in configuration.`);St(`Reconnecting to server "${e}"...`);try{let n=await Eme();await n.getToolRegistry().discoverToolsForServer(e),St(`Successfully reconnected to server "${e}".`),await n.shutdown()}catch(n){let r=n instanceof Error?n.message:String(n);throw Cme(`Failed to reconnect to server "${e}": ${r}`)}}async function ZZe(){let e=hr(),t=new lc({isWorkspaceTrusted:!!js(e.merged),telemetrySettings:e.merged.telemetry});await t.refreshCache();let n=await A5(t),r=Object.keys(n);if(r.length===0){St("No MCP servers configured.");return}St(`Reconnecting to all MCP servers...
@@ -395,7 +395,7 @@ You can update manually with:
395
395
  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:Kte,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:Lne,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)=>{st(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&&!AD(i.sessionId))return`Invalid --session-id: "${i.sessionId}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;if(i.sandboxSessionId&&!AD(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(Bme).command(Vfe).command(Lme).command(iDe).command(Kfe).command(nhe).command(lhe).command(ohe);t.version(await Lg()).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&&(st("\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 EDe(e,t=[],n,r=[],o,s="tree",i=[],a={}){let l=Dd.realpathSync(Vx.resolve(e)),c=Dd.realpathSync(Vx.resolve(tat()));return I_(l===c?"":e,t,n,r,o,s,i,a)}function iat(e,t){if(e.maxWallTime!==void 0&&e.maxWallTime!==null)try{return lDe(String(e.maxWallTime))}catch(r){throw new Error(`--max-wall-time: ${r.message}`)}let n=t.model?.maxWallTimeSeconds;if(typeof n=="number")try{return cDe(n)}catch(r){throw new Error(`settings.json: ${r.message}`)}return-1}function aat(e,t){if(e.maxToolCalls!==void 0&&e.maxToolCalls!==null)try{return qq(e.maxToolCalls)}catch(r){throw new Error(`--max-tool-calls: ${r.message}`)}let n=t.model?.maxToolCalls;if(typeof n=="number")try{return qq(n)}catch(r){throw new Error(`settings.json: ${r.message}`)}return-1}function pDe(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 Yq(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 lat(e){return typeof e!="object"||e===null||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="object"&&t!==null)}function cat(e){if(!e)return null;try{let t;if(Dd.existsSync(e)){MC.debug(`Reading MCP config from file: ${e}`);let r=Dd.readFileSync(e,"utf-8");t=JSON.parse((0,mDe.default)(r))}else MC.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,!lat(n))throw new Error("Invalid MCP server configuration format. Expected an object with server names as keys.");return MC.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 Ri(`Invalid MCP configuration provided via --mcp-config: ${n}`)}}function kk(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 uat(e){let t=0,n=0,r=o=>{try{return Dd.statSync(o).mtimeMs}catch{return 0}};return()=>{let o=QQ(),s=new Ft(e).getWorkspaceSettingsPath(),i=r(o),a=r(s);if(i===t&&a===n)return null;t=i,n=a;let l=hr(e,{consumeCorruptionEnvVars:!1,skipLoadEnvironment:!0});return{allow:l.merged.permissions?.allow??[],ask:l.merged.permissions?.ask??[],deny:l.merged.permissions?.deny??[]}}}async function Mk(e,t,n=process.cwd(),r,o,s,i,a,l){e=Qk(e,t.channel);let c=Yq(t),u=oI(t.bare),A=t.channel==="desktop"&&!!process.env.MATILDA_TEMPORARY_SESSION;_ne(),Ft.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?Cj(e.context.fileName):Cj(dd());let E=new Ft(n),y=Vx.join(E.getMatildaDir(),"output-language.md"),B=Vx.join(Ft.getGlobalMatildaDir(),"output-language.md"),b;u||(Dd.existsSync(y)?b=y:Dd.existsSync(B)&&(b=B));let w=new m_(n),v=LW(t.channel),Q=(v??(u?[]:e.context?.includeDirectories??[])).map(H2).concat(v?[]:(t.includeDirectories||[]).map(H2)),O=!u&&t.experimentalLsp===!0,z,q=t.promptInteractive||t.prompt||"",j=gDe(t.outputFormat),P=gDe(e.output?.format),U=j??P??"text",N=U==="stream-json"?P&&P!=="stream-json"?P:"text":U,L=!!t.includePartialMessages,_;t.approvalMode?_=ADe(t.approvalMode):t.bogan?_="bogan":!u&&e.tools?.approvalMode?_=ADe(e.tools.approvalMode):_="default",!m&&_!=="default"&&_!=="plan"&&(st('Approval mode overridden to "default" because the current folder is not trusted.'),_="default");let H;try{H=await kne({argv:t,env:process.env,settings:e.telemetry})}catch(ue){throw ue instanceof Ri?new Ri(`Invalid telemetry configuration: ${ue.message}.`):ue}let Y=!!t.query,k=!!t.prompt,G;t.promptInteractive?G=!0:(U==="stream-json"||U==="json")&&(Y||k)?G=!1:!Y&&!k?G=process.stdin.isTTY??!1:G=!1;let V=[...u?[]:t.coreTools??[],...u?[]:e.tools?.core??[]],se=[...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),se.includes(ue)||se.push(ue));for(let ue of t.excludeTools??[])ue&&(we.deny.push(ue),ve.includes(ue)||ve.push(ue));let be=[],Ge=new Set,W=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??[])W(ue);for(let ue of t.disabledSlashCommands??[])W(ue);for(let ue of(process.env.MATILDA_DISABLED_SLASH_COMMANDS??"").split(","))W(ue);for(let ue of(process.env.MATILDA_DISABLED_SLASH_COMMANDS??"").split(","))W(ue);let $=Xfe(e.tools?.disabled),K=ue=>se.some(Be=>Bj(ue,[Be],[]))?!0:V.length>0?Bj(ue,V,[]):!1,X=t.acp||t.experimentalAcp;if(!u&&!G&&!X){let ue=Be=>{if(!K(Be)){let _e=Be;we.deny.push(_e),ve.includes(_e)||ve.push(_e)}};switch(_){case"plan":case"default":ue(yn.SHELL),ue(yn.MONITOR),ue(yn.EDIT),ue(yn.WRITE_FILE);break;case"auto":ue(yn.SHELL),ue(yn.MONITOR),ue(yn.EDIT),ue(yn.WRITE_FILE);break;case"auto-edit":ue(yn.SHELL),ue(yn.MONITOR);break;case"bogan":break;default:break}}let re,ce;t.allowedMcpServerNames?(re=new Set(t.allowedMcpServerNames.filter(Boolean)),ce=void 0):u||(re=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)||P2(),Qe=U2({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 oO(u?{}:e,t),ee=t.screenReader!==void 0?t.screenReader:e.ui?.accessibility?.screenReader??!1,pe,Ie;if(t.continue||t.resume){let ue=new pi(a??n,l);if(t.continue&&(Ie=await ue.loadLastSession(),Ie?pe=Ie.conversation.sessionId:t.forkSession&&(st("Cannot use --fork-session with --continue: no saved session found to fork."),process.exit(1))),t.resume&&(pe=t.resume,Ie=await ue.loadSession(t.resume),!Ie)){let Be=`No saved session found with ID ${t.resume}. Run \`matilda --resume\` without an ID to choose from existing sessions.`;st(Be),process.exit(1)}if(t.forkSession&&pe){let Be=pe,_e=dDe();try{await ue.forkSession(Be,_e)}catch(Ze){st(`Failed to fork session ${Be}: ${Ze instanceof Error?Ze.message:String(Ze)}`),process.exit(1)}pe=_e,Ie=await ue.loadSession(_e),Ie||(st(`Failed to load forked session ${_e}.`),process.exit(1))}}else if(t.sandboxSessionId)process.env.SANDBOX||(st("--sandbox-session-id is for internal sandbox use only."),process.exit(1)),pe=t.sandboxSessionId;else if(t.sessionId){if(await new pi(n).sessionExists(t.sessionId)){let _e=`Error: Session Id ${t.sessionId} is already in use.`;st(_e),process.exit(1)}pe=t.sessionId}else t.fresh&&(pe=dDe());let he=e.modelProviders,De=cat(t.mcpConfig),Ae=i||De?{...i,...De??{}}:void 0,me=u?{}:DC(e.mcpServers,n,Ae),Te=u?void 0:iO(me,n),Ve={organizationId:t.organizationId,codeCreditLimitMinor:t.codeCreditLimitMinor,sessionId:pe,sessionData:Ie,sessionStorageDir:a,sessionRuntimeBaseDir:l,embeddingModel:Pne,sandbox:Z,targetDir:n,includeDirectories:Q,loadMemoryFromIncludeDirectories:u?Q.length>0:e.context?.loadFromIncludeDirectories??!1,importFormat:e.context?.importFormat||"tree",debugMode:c,question:q,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:se.length>0?se: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=hr(n,{consumeCorruptionEnvVars:!1,skipLoadEnvironment:!0}),ot=ue==="project"?"Workspace":"User";Ze.appendArrayValue(ot,`permissions.${Be}`,_e)},onRefreshPermissionsFromDisk:uat(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:re?Array.from(re):void 0,excludedMcpServers:ce?Array.from(ce):void 0,approvalMode:_,accessibility:{...e.ui?.accessibility,screenReader:ee},telemetry:H,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:iat(t,e),maxToolCalls:aat(t,e),goalTokenBudget:pDe(e.goal?.tokenBudget,"goal.tokenBudget"),goalTurnBudget:pDe(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:U,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 Lg(),ideMode:g,chatCompression:e.model?.chatCompression,folderTrust:d,interactive:G,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:sl,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:sat(t.jsonSchema),inputFile:t.inputFile??e.dualOutput?.inputFile,chatRecording:t.fresh?!1:t.chatRecording??e.general?.chatRecording??!0,defaultFileEncoding:e.general?.defaultFileEncoding,lsp:{enabled:O},worktree:e.worktree?{symlinkDirectories:e.worktree.symlinkDirectories}:void 0},Le=new B_(Ve);if(O)try{let ue=new Goe(Le,Le.getWorkspaceContext(),sl,w,df,{requireTrustedWorkspace:d});await ue.discoverAndPrepare(),Le.getDebugMode()&&MC.debug("Native LSP status after discovery:",ue.getStatusSnapshot()),await ue.start(),Le.getDebugMode()&&MC.debug("Native LSP status after startup:",ue.getStatusSnapshot()),z=new Hoe(ue),Le.setLspClient(z);try{Le.setLspInitializationError(void 0)}catch{MC.warn("Failed to clear LSP initialization error after initialization")}}catch(ue){try{Le.setLspInitializationError(ue instanceof Error?ue:String(ue))}catch{MC.warn("LSP init error occurred after initialization:",ue)}MC.warn("Failed to initialize native LSP service:",ue)}return Le}h();h();async function yDe(e,t){if(!t)return null;try{await e.refreshAuth(t);let n=new Ky(t,"auto","success");$y(e,n)}catch(n){let r=`Failed to login. Message: ${xr(n)}`,o=new Ky(t,"auto","error",r);return $y(e,o),r}return null}h();h();h();var ii={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"]},IDe=new Gr("Ayu","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:ii.Background,color:ii.Foreground},"hljs-keyword":{color:ii.AccentYellow},"hljs-literal":{color:ii.AccentPurple},"hljs-symbol":{color:ii.AccentCyan},"hljs-name":{color:ii.LightBlue},"hljs-link":{color:ii.AccentBlue},"hljs-function .hljs-keyword":{color:ii.AccentYellow},"hljs-subst":{color:ii.Foreground},"hljs-string":{color:ii.AccentGreen},"hljs-title":{color:ii.AccentYellow},"hljs-type":{color:ii.AccentBlue},"hljs-attribute":{color:ii.AccentYellow},"hljs-bullet":{color:ii.AccentYellow},"hljs-addition":{color:ii.AccentGreen},"hljs-variable":{color:ii.Foreground},"hljs-template-tag":{color:ii.AccentYellow},"hljs-template-variable":{color:ii.AccentYellow},"hljs-comment":{color:ii.Comment,fontStyle:"italic"},"hljs-quote":{color:ii.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:ii.AccentRed},"hljs-meta":{color:ii.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},ii);h();var xo={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"]},DDe=new Gr("Ayu Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:xo.Background,color:xo.Foreground},"hljs-comment":{color:xo.Comment,fontStyle:"italic"},"hljs-quote":{color:xo.AccentCyan,fontStyle:"italic"},"hljs-string":{color:xo.AccentGreen},"hljs-constant":{color:xo.AccentCyan},"hljs-number":{color:xo.AccentPurple},"hljs-keyword":{color:xo.AccentYellow},"hljs-selector-tag":{color:xo.AccentYellow},"hljs-attribute":{color:xo.AccentYellow},"hljs-variable":{color:xo.Foreground},"hljs-variable.language":{color:xo.LightBlue,fontStyle:"italic"},"hljs-title":{color:xo.AccentBlue},"hljs-section":{color:xo.AccentGreen,fontWeight:"bold"},"hljs-type":{color:xo.LightBlue},"hljs-class .hljs-title":{color:xo.AccentBlue},"hljs-tag":{color:xo.LightBlue},"hljs-name":{color:xo.AccentBlue},"hljs-builtin-name":{color:xo.AccentYellow},"hljs-meta":{color:xo.AccentYellow},"hljs-symbol":{color:xo.AccentRed},"hljs-bullet":{color:xo.AccentYellow},"hljs-regexp":{color:xo.AccentCyan},"hljs-link":{color:xo.LightBlue},"hljs-deletion":{color:xo.AccentRed},"hljs-addition":{color:xo.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-literal":{color:xo.AccentCyan},"hljs-built_in":{color:xo.AccentRed},"hljs-doctag":{color:xo.AccentRed},"hljs-template-variable":{color:xo.AccentCyan},"hljs-selector-id":{color:xo.AccentRed}},xo);h();var eo={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"]},SDe=new Gr("Atom One","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:eo.Foreground,background:eo.Background},"hljs-comment":{color:eo.Comment,fontStyle:"italic"},"hljs-quote":{color:eo.Comment,fontStyle:"italic"},"hljs-doctag":{color:eo.AccentPurple},"hljs-keyword":{color:eo.AccentPurple},"hljs-formula":{color:eo.AccentPurple},"hljs-section":{color:eo.AccentRed},"hljs-name":{color:eo.AccentRed},"hljs-selector-tag":{color:eo.AccentRed},"hljs-deletion":{color:eo.AccentRed},"hljs-subst":{color:eo.AccentRed},"hljs-literal":{color:eo.AccentCyan},"hljs-string":{color:eo.AccentGreen},"hljs-regexp":{color:eo.AccentGreen},"hljs-addition":{color:eo.AccentGreen},"hljs-attribute":{color:eo.AccentGreen},"hljs-meta-string":{color:eo.AccentGreen},"hljs-built_in":{color:eo.AccentYellow},"hljs-class .hljs-title":{color:eo.AccentYellow},"hljs-attr":{color:eo.AccentYellow},"hljs-variable":{color:eo.AccentYellow},"hljs-template-variable":{color:eo.AccentYellow},"hljs-type":{color:eo.AccentYellow},"hljs-selector-class":{color:eo.AccentYellow},"hljs-selector-attr":{color:eo.AccentYellow},"hljs-selector-pseudo":{color:eo.AccentYellow},"hljs-number":{color:eo.AccentYellow},"hljs-symbol":{color:eo.AccentBlue},"hljs-bullet":{color:eo.AccentBlue},"hljs-link":{color:eo.AccentBlue,textDecoration:"underline"},"hljs-meta":{color:eo.AccentBlue},"hljs-selector-id":{color:eo.AccentBlue},"hljs-title":{color:eo.AccentBlue},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},eo);h();var Rs={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"]},BDe=new Gr("Dracula","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:Rs.Background,color:Rs.Foreground},"hljs-keyword":{color:Rs.AccentBlue,fontWeight:"bold"},"hljs-selector-tag":{color:Rs.AccentBlue,fontWeight:"bold"},"hljs-literal":{color:Rs.AccentBlue,fontWeight:"bold"},"hljs-section":{color:Rs.AccentBlue,fontWeight:"bold"},"hljs-link":{color:Rs.AccentBlue},"hljs-function .hljs-keyword":{color:Rs.AccentPurple},"hljs-subst":{color:Rs.Foreground},"hljs-string":{color:Rs.AccentYellow},"hljs-title":{color:Rs.AccentYellow,fontWeight:"bold"},"hljs-name":{color:Rs.AccentYellow,fontWeight:"bold"},"hljs-type":{color:Rs.AccentYellow,fontWeight:"bold"},"hljs-attribute":{color:Rs.AccentYellow},"hljs-symbol":{color:Rs.AccentYellow},"hljs-bullet":{color:Rs.AccentYellow},"hljs-addition":{color:Rs.AccentGreen},"hljs-variable":{color:Rs.AccentYellow},"hljs-template-tag":{color:Rs.AccentYellow},"hljs-template-variable":{color:Rs.AccentYellow},"hljs-comment":{color:Rs.Comment},"hljs-quote":{color:Rs.Comment},"hljs-deletion":{color:Rs.AccentRed},"hljs-meta":{color:Rs.Comment},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},Rs);h();var bo={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"]},xDe=new Gr("GitHub","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:bo.Foreground,background:bo.Background},"hljs-comment":{color:bo.Comment,fontStyle:"italic"},"hljs-quote":{color:bo.Comment,fontStyle:"italic"},"hljs-keyword":{color:bo.AccentRed,fontWeight:"bold"},"hljs-selector-tag":{color:bo.AccentRed,fontWeight:"bold"},"hljs-subst":{color:bo.Foreground},"hljs-number":{color:bo.LightBlue},"hljs-literal":{color:bo.LightBlue},"hljs-variable":{color:bo.AccentYellow},"hljs-template-variable":{color:bo.AccentYellow},"hljs-tag .hljs-attr":{color:bo.AccentYellow},"hljs-string":{color:bo.AccentCyan},"hljs-doctag":{color:bo.AccentCyan},"hljs-title":{color:bo.AccentPurple,fontWeight:"bold"},"hljs-section":{color:bo.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:bo.AccentPurple,fontWeight:"bold"},"hljs-type":{color:bo.AccentGreen,fontWeight:"bold"},"hljs-class .hljs-title":{color:bo.AccentGreen,fontWeight:"bold"},"hljs-tag":{color:bo.AccentGreen},"hljs-name":{color:bo.AccentGreen},"hljs-attribute":{color:bo.LightBlue},"hljs-regexp":{color:bo.AccentCyan},"hljs-link":{color:bo.AccentCyan},"hljs-symbol":{color:bo.AccentPurple},"hljs-bullet":{color:bo.AccentPurple},"hljs-built_in":{color:bo.LightBlue},"hljs-builtin-name":{color:bo.LightBlue},"hljs-meta":{color:bo.LightBlue,fontWeight:"bold"},"hljs-deletion":{background:"#86181D",color:bo.AccentRed},"hljs-addition":{background:"#144620",color:bo.AccentGreen},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},bo);h();var Uo={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"]},bDe=new Gr("GitHub Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",color:Uo.Foreground,background:Uo.Background},"hljs-comment":{color:Uo.Comment,fontStyle:"italic"},"hljs-quote":{color:Uo.Comment,fontStyle:"italic"},"hljs-keyword":{color:Uo.Foreground,fontWeight:"bold"},"hljs-selector-tag":{color:Uo.Foreground,fontWeight:"bold"},"hljs-subst":{color:Uo.Foreground,fontWeight:"normal"},"hljs-number":{color:Uo.AccentGreen},"hljs-literal":{color:Uo.AccentGreen},"hljs-variable":{color:Uo.AccentGreen},"hljs-template-variable":{color:Uo.AccentGreen},"hljs-tag .hljs-attr":{color:Uo.AccentGreen},"hljs-string":{color:Uo.AccentRed},"hljs-doctag":{color:Uo.AccentRed},"hljs-title":{color:Uo.AccentPurple,fontWeight:"bold"},"hljs-section":{color:Uo.AccentPurple,fontWeight:"bold"},"hljs-selector-id":{color:Uo.AccentPurple,fontWeight:"bold"},"hljs-type":{color:Uo.AccentBlue,fontWeight:"bold"},"hljs-class .hljs-title":{color:Uo.AccentBlue,fontWeight:"bold"},"hljs-tag":{color:Uo.AccentBlue,fontWeight:"normal"},"hljs-name":{color:Uo.AccentBlue,fontWeight:"normal"},"hljs-attribute":{color:Uo.AccentBlue,fontWeight:"normal"},"hljs-regexp":{color:Uo.AccentCyan},"hljs-link":{color:Uo.AccentCyan},"hljs-symbol":{color:Uo.AccentYellow},"hljs-bullet":{color:Uo.AccentYellow},"hljs-built_in":{color:Uo.LightBlue},"hljs-builtin-name":{color:Uo.LightBlue},"hljs-meta":{color:Uo.Gray,fontWeight:"bold"},"hljs-deletion":{background:"#fdd"},"hljs-addition":{background:"#dfd"},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"}},Uo);h();var wo={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:kn.Gray,GradientColors:["#066","#606"]},wDe=new Gr("Google Code","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:wo.Background,color:wo.Foreground},"hljs-comment":{color:wo.AccentRed},"hljs-quote":{color:wo.AccentRed},"hljs-keyword":{color:wo.AccentBlue},"hljs-selector-tag":{color:wo.AccentBlue},"hljs-section":{color:wo.AccentBlue},"hljs-title":{color:wo.AccentPurple},"hljs-name":{color:wo.AccentBlue},"hljs-variable":{color:wo.AccentYellow},"hljs-template-variable":{color:wo.AccentYellow},"hljs-string":{color:wo.AccentGreen},"hljs-selector-attr":{color:wo.AccentGreen},"hljs-selector-pseudo":{color:wo.AccentGreen},"hljs-regexp":{color:wo.AccentGreen},"hljs-literal":{color:wo.AccentCyan},"hljs-symbol":{color:wo.AccentCyan},"hljs-bullet":{color:wo.AccentCyan},"hljs-meta":{color:wo.AccentCyan},"hljs-number":{color:wo.AccentCyan},"hljs-link":{color:wo.AccentCyan},"hljs-doctag":{color:wo.AccentPurple,fontWeight:"bold"},"hljs-type":{color:wo.AccentPurple},"hljs-attr":{color:wo.AccentPurple},"hljs-built_in":{color:wo.AccentPurple},"hljs-builtin-name":{color:wo.AccentPurple},"hljs-params":{color:wo.AccentPurple},"hljs-attribute":{color:wo.Foreground},"hljs-subst":{color:wo.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-selector-id":{color:wo.AccentYellow},"hljs-selector-class":{color:wo.AccentYellow},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},wo);h();var nr={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"]},Ta={AccentYellowAlt:"#f8d000",AccentOrange:"#fb9e00",AccentPink:"#fa658d",AccentLightPurple:"#c991ff",AccentDarkPurple:"#6943ff",AccentTeal:"#2ee2fa"},TDe=new Gr("Shades Of Purple","dark",{hljs:{display:"block",overflowX:"auto",background:nr.Background,color:nr.Foreground},"hljs-title":{color:nr.AccentYellow,fontWeight:"normal"},"hljs-name":{color:nr.AccentCyan,fontWeight:"normal"},"hljs-tag":{color:nr.Foreground},"hljs-attr":{color:Ta.AccentYellowAlt,fontStyle:"italic"},"hljs-built_in":{color:Ta.AccentOrange},"hljs-selector-tag":{color:Ta.AccentOrange,fontWeight:"normal"},"hljs-section":{color:Ta.AccentOrange},"hljs-keyword":{color:Ta.AccentOrange,fontWeight:"normal"},"hljs-subst":{color:nr.Foreground},"hljs-string":{color:nr.AccentGreen},"hljs-attribute":{color:nr.AccentGreen},"hljs-symbol":{color:nr.AccentGreen},"hljs-bullet":{color:nr.AccentGreen},"hljs-addition":{color:nr.AccentGreen},"hljs-code":{color:nr.AccentGreen},"hljs-regexp":{color:nr.AccentGreen},"hljs-selector-class":{color:nr.AccentGreen},"hljs-selector-attr":{color:nr.AccentGreen},"hljs-selector-pseudo":{color:nr.AccentGreen},"hljs-template-tag":{color:nr.AccentGreen},"hljs-quote":{color:nr.AccentGreen},"hljs-deletion":{color:nr.AccentRed},"hljs-meta":{color:Ta.AccentOrange},"hljs-meta-string":{color:Ta.AccentOrange},"hljs-comment":{color:nr.AccentPurple},"hljs-literal":{color:Ta.AccentPink,fontWeight:"normal"},"hljs-number":{color:Ta.AccentPink},"hljs-emphasis":{fontStyle:"italic"},"hljs-strong":{fontWeight:"bold"},"hljs-diff":{color:nr.Foreground},"hljs-meta.hljs-diff":{color:nr.AccentBlue},"hljs-ln":{color:nr.Gray},"hljs-type":{color:nr.AccentYellow,fontWeight:"normal"},"hljs-variable":{color:nr.AccentYellow},"hljs-template-variable":{color:nr.AccentGreen},"hljs-function .hljs-keyword":{color:Ta.AccentOrange},"hljs-link":{color:nr.LightBlue},"hljs-doctag":{fontWeight:"bold"},"hljs-params":{color:Ta.AccentLightPurple,fontStyle:"italic"},"hljs-class":{color:nr.AccentCyan,fontWeight:"bold"},"hljs-function":{color:nr.AccentCyan},"hljs-property":{color:nr.AccentBlue},"hljs-operator":{color:Ta.AccentDarkPurple},"hljs-punctuation":{color:nr.Gray},"hljs-selector-id":{color:nr.AccentYellow,fontWeight:"bold"},"hljs-char":{color:nr.AccentGreen},"hljs-escape":{color:Ta.AccentPink,fontWeight:"bold"},"hljs-meta-keyword":{color:Ta.AccentOrange,fontWeight:"bold"},"hljs-builtin-name":{color:Ta.AccentTeal},"hljs-module":{color:nr.AccentCyan},"hljs-namespace":{color:nr.LightBlue},"hljs-important":{color:nr.AccentRed,fontWeight:"bold"},"hljs-formula":{color:nr.AccentCyan,fontStyle:"italic"},"hljs-decorator":{color:Ta.AccentTeal,fontWeight:"bold"},"hljs-symbol.ruby":{color:Ta.AccentPink},"hljs-keyword.sql":{color:Ta.AccentOrange,textTransform:"uppercase"},"hljs-section.markdown":{color:nr.AccentYellow,fontWeight:"bold"},"hljs-attr.json":{color:nr.AccentCyan},"hljs-tag .hljs-name":{color:nr.AccentRed},"hljs-tag .hljs-attr":{color:Ta.AccentYellowAlt},"hljs.hljs-line-numbers":{borderRight:`1px solid ${nr.Gray}`},"hljs.hljs-line-numbers .hljs-ln-numbers":{color:nr.Gray,paddingRight:"1em"},"hljs.hljs-line-numbers .hljs-ln-code":{paddingLeft:"1em"},"hljs::selection":{background:nr.AccentBlue+"40"},"hljs ::-moz-selection":{background:nr.AccentBlue+"40"},"hljs .hljs-highlight":{background:nr.AccentPurple+"20",display:"block",width:"100%"}},nr);h();var uo={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"]},vDe=new Gr("Xcode","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:uo.Background,color:uo.Foreground},"xml .hljs-meta":{color:uo.Gray},"hljs-comment":{color:uo.Comment},"hljs-quote":{color:uo.Comment},"hljs-tag":{color:uo.AccentPurple},"hljs-attribute":{color:uo.AccentPurple},"hljs-keyword":{color:uo.AccentPurple},"hljs-selector-tag":{color:uo.AccentPurple},"hljs-literal":{color:uo.AccentPurple},"hljs-name":{color:uo.AccentPurple},"hljs-variable":{color:uo.AccentCyan},"hljs-template-variable":{color:uo.AccentCyan},"hljs-code":{color:uo.AccentRed},"hljs-string":{color:uo.AccentRed},"hljs-meta-string":{color:uo.AccentRed},"hljs-regexp":{color:uo.LightBlue},"hljs-link":{color:uo.LightBlue},"hljs-title":{color:uo.AccentBlue},"hljs-symbol":{color:uo.AccentBlue},"hljs-bullet":{color:uo.AccentBlue},"hljs-number":{color:uo.AccentBlue},"hljs-section":{color:uo.AccentYellow},"hljs-meta":{color:uo.AccentYellow},"hljs-class .hljs-title":{color:uo.AccentPurple},"hljs-type":{color:uo.AccentPurple},"hljs-built_in":{color:uo.AccentPurple},"hljs-builtin-name":{color:uo.AccentPurple},"hljs-params":{color:uo.AccentPurple},"hljs-attr":{color:uo.AccentYellow},"hljs-subst":{color:uo.Foreground},"hljs-formula":{backgroundColor:"#eee",fontStyle:"italic"},"hljs-addition":{backgroundColor:"#baeeba"},"hljs-deletion":{backgroundColor:"#ffc8bd"},"hljs-selector-id":{color:uo.AccentYellow},"hljs-selector-class":{color:uo.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},uo);h();var As={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"]},Aat={text:{primary:"#1A211D",secondary:"#5C6B62",link:"#0E8C86",accent:"#9A6B00",code:"#0E8C86"},background:{primary:As.Background,diff:{added:As.DiffAdded,removed:As.DiffRemoved}},border:{default:"#C5D0C9",focused:"#9A6B00",input:"#9FA896"},ui:{comment:"#5C6B62",symbol:"#5C6B62",gradient:As.GradientColors,heatmap:["#DDF0E4","#9FD3B0","#4FB07A","#C8950A","#9A6B00"],highlightTarget:"#0A0F0D"},status:{error:"#D03548",success:"#0FA968",warning:"#C0392B",errorDim:"#993333",warningDim:"#8A2A22"}},IP=new Gr("Matilda Light","light",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:As.Background,color:As.Foreground},"hljs-keyword":{color:As.AccentCyan},"hljs-literal":{color:As.AccentPurple},"hljs-symbol":{color:As.AccentCyan},"hljs-name":{color:As.AccentBlue},"hljs-link":{color:As.AccentBlue},"hljs-function .hljs-keyword":{color:As.AccentCyan},"hljs-subst":{color:As.Foreground},"hljs-string":{color:As.AccentGreen},"hljs-title":{color:As.AccentYellow},"hljs-type":{color:As.AccentBlue},"hljs-attribute":{color:As.AccentYellow},"hljs-bullet":{color:As.AccentYellow},"hljs-addition":{color:As.AccentGreen},"hljs-variable":{color:As.Foreground},"hljs-template-tag":{color:As.AccentYellow},"hljs-template-variable":{color:As.AccentYellow},"hljs-comment":{color:As.Comment,fontStyle:"italic"},"hljs-quote":{color:As.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:As.AccentRed},"hljs-meta":{color:As.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},As,Aat);h();var fs={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"]},fat={text:{primary:"#CBD6CF",secondary:"#7C8C82",link:"#3FD9C9",accent:"#F2C744",code:"#7FE8DA"},background:{primary:fs.Background,diff:{added:fs.DiffAdded,removed:fs.DiffRemoved}},border:{default:"#2C3A33",focused:"#F2C744",input:"#5A6B61"},ui:{comment:"#5A6B61",symbol:"#7C8C82",gradient:fs.GradientColors,heatmap:["#123026","#1C8F57","#46B86E","#C9B83A","#F2C744"],highlightTarget:"#F5F7F4"},status:{error:"#F2606E",success:"#1CD687",warning:"#E8902E",errorDim:"#7E3340",warningDim:"#7A4E1A"}},Fk=new Gr("Matilda Dark","dark",{hljs:{display:"block",overflowX:"auto",padding:"0.5em",background:fs.Background,color:fs.Foreground},"hljs-keyword":{color:fs.AccentCyan},"hljs-literal":{color:fs.AccentPurple},"hljs-symbol":{color:fs.AccentCyan},"hljs-name":{color:fs.LightBlue},"hljs-link":{color:fs.AccentBlue},"hljs-function .hljs-keyword":{color:fs.AccentCyan},"hljs-subst":{color:fs.Foreground},"hljs-string":{color:fs.AccentGreen},"hljs-title":{color:fs.AccentYellow},"hljs-type":{color:fs.AccentBlue},"hljs-attribute":{color:fs.AccentYellow},"hljs-bullet":{color:fs.AccentYellow},"hljs-addition":{color:fs.AccentGreen},"hljs-variable":{color:fs.Foreground},"hljs-template-tag":{color:fs.AccentYellow},"hljs-template-variable":{color:fs.AccentYellow},"hljs-comment":{color:fs.Comment,fontStyle:"italic"},"hljs-quote":{color:fs.AccentCyan,fontStyle:"italic"},"hljs-deletion":{color:fs.AccentRed},"hljs-meta":{color:fs.AccentYellow},"hljs-doctag":{fontWeight:"bold"},"hljs-strong":{fontWeight:"bold"},"hljs-emphasis":{fontStyle:"italic"}},fs,fat);h();h();var Jq=new Set(["Matilda Dark","Matilda Light","Matilda Wattle","Matilda Outback","Matilda Reef","Matilda Southern Cross"]);function FC(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 gat(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 NC(e,t,n,r){return new Gr(e,t,gat(n),n,r)}var RDe={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"]},QDe=NC("Matilda Wattle","dark",RDe,FC(RDe,{textSecondary:"#8A9C8E",code:"#8FE0B4",link:"#4FC07E",warning:"#E8902E",warningDim:"#7A4E1A",heatmap:["#143021","#1F8A53","#3FB36B","#9FD15A","#F2C744"]}));h();var kDe={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"]},MDe=NC("Matilda Outback","dark",kDe,FC(kDe,{textSecondary:"#A98F77",code:"#F0B27A",link:"#E0704A",accent:"#F2A03D",warning:"#FFE08A",warningDim:"#8A6D1F",heatmap:["#2A1410","#8A3A1F","#D9603B","#F2A03D","#FFD9A0"]}));h();var FDe={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"]},NDe=NC("Matilda Reef","dark",FDe,FC(FDe,{textSecondary:"#7C9C96",code:"#7FE8DA",link:"#6FD3F0",accent:"#3FD9C9",warning:"#F2C744",warningDim:"#8A6D1F",heatmap:["#06222A","#1C7FA8","#1FA9B8","#3FD9C9","#F2C744"]}));h();var _De={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"]},LDe=NC("Matilda Southern Cross","dark",_De,FC(_De,{textSecondary:"#8A92AE",code:"#9AB0F0",link:"#8FA0E8",warning:"#E8662E",warningDim:"#7A3A1A",heatmap:["#1A1B33","#2E3470","#6E78C8","#B9A0E8","#F2C744"]}));import*as Nk from"node:fs";import*as gD from"node:path";import*as YDe from"node:os";h();h();var ODe={text:{primary:kn.Foreground,secondary:kn.Gray,link:kn.AccentBlue,accent:kn.AccentPurple,code:kn.LightBlue},background:{primary:kn.Background,diff:{added:kn.DiffAdded,removed:kn.DiffRemoved}},border:{default:kn.Gray,focused:kn.AccentBlue},ui:{comment:kn.Comment,symbol:kn.Gray,gradient:kn.GradientColors},status:{error:kn.AccentRed,success:kn.AccentGreen,warning:kn.AccentYellow,errorDim:kn.AccentRedDim,warningDim:kn.AccentYellowDim}},PDe={text:{primary:ln.Foreground,secondary:ln.Gray,link:ln.AccentBlue,accent:ln.AccentPurple,code:ln.LightBlue},background:{primary:ln.Background,diff:{added:ln.DiffAdded,removed:ln.DiffRemoved}},border:{default:ln.Gray,focused:ln.AccentBlue},ui:{comment:ln.Comment,symbol:ln.Gray,gradient:ln.GradientColors},status:{error:ln.AccentRed,success:ln.AccentGreen,warning:ln.AccentYellow,errorDim:ln.AccentRedDim,warningDim:ln.AccentYellowDim}},Scn={text:{primary:xa.Foreground,secondary:xa.Gray,link:xa.AccentBlue,accent:xa.AccentPurple,code:xa.LightBlue},background:{primary:xa.Background,diff:{added:xa.DiffAdded,removed:xa.DiffRemoved}},border:{default:xa.Gray,focused:xa.AccentBlue},ui:{comment:xa.Comment,symbol:xa.Gray,gradient:xa.GradientColors},status:{error:xa.AccentRed,success:xa.AccentGreen,warning:xa.AccentYellow,errorDim:xa.AccentRedDim,warningDim:xa.AccentYellowDim}};var pat={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"]},UDe=new Gr("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"}},pat,PDe);h();var mat={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"]},HDe=new Gr("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"}},mat,ODe);h();var hat={type:"ansi",Background:"",Foreground:"",LightBlue:"",AccentBlue:"",AccentPurple:"",AccentCyan:"",AccentGreen:"",AccentYellow:"",AccentRed:"",AccentYellowDim:"",AccentRedDim:"",DiffAdded:"",DiffRemoved:"",Comment:"",Gray:""},Cat={text:{primary:"",secondary:"",link:"",accent:"",code:""},background:{primary:"",diff:{added:"",removed:""}},border:{default:"",focused:""},ui:{comment:"",symbol:"",gradient:[]},status:{error:"",success:"",warning:"",errorDim:"",warningDim:""}},GDe=new Gr("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%"}},hat,Cat);import Bat from"node:process";h();import{execSync as Eat}from"node:child_process";import Xx from"node:process";var fD=Ke("THEME_DETECT"),yat=200;function Kx(e){let t=16**e.length-1;return parseInt(e,16)/t}function Iat(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:Kx(t[1]),g:Kx(t[2]),b:Kx(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:Kx(r.slice(0,o)),g:Kx(r.slice(o,2*o)),b:Kx(r.slice(2*o))}}}function Dat(e){let t=Iat(e);return t?.2126*t.r+.7152*t.g+.0722*t.b>.5?"light":"dark":void 0}function Sat(){return!Xx.stdin.isTTY||!Xx.stdout.isTTY?Promise.resolve(void 0):new Promise(e=>{let t=Xx.stdin,n=!1,r="",o=a=>{n||(n=!0,clearTimeout(s),t.removeListener("data",i),e(a))},s=setTimeout(()=>o(void 0),yat),i=a=>{r+=a.toString();let l=/\x1b\]11;(.*?)(?:\x07|\x1b\\)/.exec(r);l&&o(Dat(l[1]))};t.on("data",i),Xx.stdout.write("\x1B]11;?\x07")})}function zDe(){if(Xx.platform==="darwin")try{return Eat("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 jDe(){let e=Xx.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 WDe(){let e=jDe();if(e)return fD.info(`Detected theme from COLORFGBG: ${e}`),e;let t=zDe();return t?(fD.info(`Detected theme from macOS system appearance: ${t}`),t):(fD.info("Could not detect terminal theme, defaulting to dark"),"dark")}async function qDe(){let e=jDe();if(e)return fD.info(`Detected theme from COLORFGBG (async path): ${e}`),e;let t=await Sat();if(t)return fD.info(`Detected theme from OSC 11 background query: ${t}`),t;let n=zDe();return n?(fD.info(`Detected theme from macOS system appearance: ${n}`),n):(fD.info("Could not detect terminal theme, defaulting to dark"),"dark")}var Im=Ke("THEME_MANAGER"),_C=Fk,Zc="auto";function JDe(e){return e?e.endsWith(".json")||e.startsWith(".")||gD.isAbsolute(e):!1}var $q=class{availableThemes;activeTheme;customThemes=new Map;constructor(){this.availableThemes=[Fk,IP,QDe,MDe,NDe,LDe,IDe,DDe,SDe,BDe,gQ,pQ,xDe,bDe,wDe,TDe,vDe,UDe,HDe],this.activeTheme=_C}loadCustomThemes(t){if(this.customThemes.clear(),!!t){for(let[n,r]of Object.entries(t)){let o=MW(r);if(o.isValid){o.warning&&Im.warn(`Theme "${n}": ${o.warning}`);let s={..._C.colors,...r,name:r.name||n,type:"custom"};try{let i=kW(s);this.customThemes.set(n,i)}catch(i){Im.warn(`Failed to load custom theme "${n}":`,i)}}else Im.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(),Im.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??WDe())==="light"?IP:Fk}async resolveAutoThemeAsync(){let t=await qDe();this.cachedAutoDetection=t,this.activeTheme=t==="light"?IP:Fk,Im.info(`Auto-detected theme (async): ${this.activeTheme.name}`)}getActiveTheme(){if(Bat.env.NO_COLOR)return GDe;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=_C,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=>Jq.has(i.name)),s=[...t.filter(i=>!Jq.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(".")||gD.isAbsolute(t)}loadThemeFromFile(t){try{let n=Nk.realpathSync(gD.resolve(t));if(this.customThemes.has(n))return this.customThemes.get(n);let r=gD.resolve(YDe.homedir());if(!n.startsWith(r)){Im.warn(`Theme file at "${t}" is outside your home directory. Only load themes from trusted sources.`);return}let o=Nk.readFileSync(n,"utf-8"),s=JSON.parse(o),i=MW(s);if(!i.isValid){Im.warn(`Invalid custom theme from file "${t}": ${i.error}`);return}i.warning&&Im.warn(`Theme from "${t}": ${i.warning}`);let a={..._C.colors,...s,name:s.name||n,type:"custom"},l=kW(a);return this.customThemes.set(n,l),l}catch(n){n instanceof Error&&"code"in n&&n.code==="ENOENT"||Im.warn(`Could not load theme from file "${t}":`,n);return}}findThemeByName(t){if(!t)return _C;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=Nk.realpathSync(gD.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}},_n=new $q;function $De(e){let t=e.merged.ui?.theme;return t&&t!==Zc&&!_n.findThemeByName(t)?C('Theme "{{themeName}}" not found.',{themeName:t}):null}async function VDe(e,t){let n=process.env.MATILDA_CODE_LANG||t.merged.general?.language||"auto";await sue(n);let r=e.getModelsConfig().getCurrentAuthType(),o=await yDe(e,r),s=$De(t),i=!e.getModelsConfig().wasAuthTypeExplicitlyProvided()||!!o;return e.getIdeMode()&&(await(await Xa.getInstance()).connect(),H1(e,new q1("start"))),{authError:o,themeError:s,shouldOpenAuthDialog:i,geminiMdFileCount:e.getGeminiMdFileCount()}}h();h();import{spawn as aSe}from"node:child_process";h();h();h();function _k(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 KDe(e,t){return e.filter(n=>_k(n).includes(t))}function DP(e){switch(e.source){case"bundled-skill":return"[Skill]";case"skill-dir-command":return e.sourceDetail==="user"?"[User]":e.sourceDetail==="project"?"[Project]":"[Custom]";case"plugin-command":return e.sourceDetail==="extension"?"[Extension]":"[Plugin]";case"mcp-prompt":return"[MCP]";case"builtin-command":default:return null}}function SP(e){switch(e.source){case"builtin-command":return{key:"built-in",title:"Built-in Commands",order:0};case"bundled-skill":return{key:"bundled-skill",title:"Bundled Skills",order:1};case"skill-dir-command":return{key:"custom",title:"Custom Commands",order:2};case"plugin-command":return{key:"plugin",title:"Plugin Commands",order:3};case"mcp-prompt":return{key:"mcp",title:"MCP Commands",order:4};default:return{key:"other",title:"Other Commands",order:5}}}function XDe(e){let t=_k(e),n=t.includes("interactive"),r=t.includes("non_interactive"),o=t.includes("acp");return n&&r&&o?"[all]":!n&&r&&o?"[headless]":n&&!r&&!o?"[interactive]":t.map(s=>{switch(s){case"interactive":return"[i]";case"non_interactive":return"[ni]";case"acp":return"[acp]";default:return`[${s}]`}}).join(" ")}function LC(e){return[...e.altNames??[],...e.hiddenAltNames??[]]}function BP(e,t={}){let r=`${t.prefix??""}${e.name}`;if(t.matchedAlias)return`${r} (alias: ${t.matchedAlias})`;if(t.includeAliases===!1)return r;let o=e.altNames?.filter(Boolean);return!o||o.length===0?r:`${r} (${o.join(", ")})`}function xP(e){return e.subCommands?.filter(t=>!t.hidden).map(t=>t.name)??[]}h();import*as Mi from"node:fs/promises";import{constants as Vq}from"node:fs";import{execSync as bat,spawn as wP}from"node:child_process";import*as Zx from"node:path";import{randomUUID as ZDe}from"node:crypto";var Ic=Ke("CLIPBOARD_UTILS"),Ok=5e3;function eb(e){try{if(Buffer.byteLength(e,"utf-8")>75e3)return Ic.warn(`writeOsc52: text too large (${Buffer.byteLength(e,"utf-8")} bytes), skipping`),!1;let n=Buffer.from(e,"utf-8").toString("base64"),r=Ml(`\x1B]52;c;${n}\x07`),o=process.stderr.isTTY?process.stderr:process.stdout.isTTY?process.stdout:null;return o?(o.write(r,s=>{s&&Ic.warn("writeOsc52: async write failed:",s)}),!0):(Ic.warn("OSC 52 clipboard requires a TTY; stdout/stderr not connected to terminal"),!1)}catch(t){return Ic.warn("writeOsc52 failed:",t),!1}}var Lk,bP=null,Kq=null,eSe=!1;async function nSe(){if(eSe)return Kq;eSe=!0;try{return Kq=await import("@teddyzhu/clipboard"),Kq}catch{return Ic.error("Failed to load @teddyzhu/clipboard native module. Clipboard image features will be unavailable."),null}}function rSe(){if(Lk!==void 0)return Lk;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 Lk=null,null;try{return bat("command -v "+r,{stdio:"ignore"}),Lk=r,r}catch{return Ic.warn(`${r} not found`),Lk=null,null}}async function Xq(e,t,n){let r;try{r=await Mi.open(n,Vq.O_WRONLY|Vq.O_CREAT|Vq.O_EXCL)}catch{return!1}return new Promise(o=>{let s=wP(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(()=>{Ic.debug(`${e} timed out after ${Ok}ms`),c(!1)},Ok);s.stderr.on("data",A=>{a+=A.toString()}),s.stdout.pipe(i),s.stdout.on("error",A=>{Ic.debug(`stdout error for ${e}:`,A),clearTimeout(u),c(!1)}),s.on("error",A=>{Ic.debug(`Failed to spawn ${e}:`,A),clearTimeout(u),c(!1)}),i.on("error",A=>{Ic.debug(`File stream error for ${n}:`,A),clearTimeout(u),c(!1)}),s.on("close",A=>{if(clearTimeout(u),l)return;if(A!==0){Ic.debug(`${e} exited with code ${A}. Args: ${t.join(" ")}`),a&&Ic.debug(`${e} stderr: ${a.trim()}`),c(!1);return}let g=()=>{Mi.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 tSe(e,t){return e==="wl-paste"&&t.length===1&&t[0]==="--list-types"?(await oSe()).length>0:new Promise(n=>{try{let r=wP(e,t,{stdio:["ignore","pipe","ignore"]}),o="",s=setTimeout(()=>{try{r.kill()}catch{}n(!1)},Ok);r.stdout.on("data",i=>{o+=i.toString()}),r.on("close",i=>{clearTimeout(s),n(i===0&&o.split(`
396
396
  `).some(a=>a==="image/png"||a==="image/bmp"))}),r.on("error",()=>{clearTimeout(s),n(!1)})}catch{n(!1)}})}async function TP(){if(bP=null,process.platform==="linux"){try{let e=rSe();if(e==="wl-paste")return tSe("wl-paste",["--list-types"]);if(e==="xclip")return tSe("xclip",["-selection","clipboard","-t","TARGETS","-o"])}catch(e){Ic.error("Error checking clipboard for image:",e)}return!1}try{let e=await nSe();return e?new e.ClipboardManager().hasFormat("image"):!1}catch(e){return Ic.error("Error checking clipboard for image:",e),!1}}async function oSe(){return bP!==null?bP:new Promise(e=>{let t=wP("wl-paste",["--list-types"],{stdio:["ignore","pipe","ignore"]}),n="",r=setTimeout(()=>{try{t.kill()}catch{}e([])},Ok);t.stdout.on("data",o=>{n+=o.toString()}),t.on("close",o=>{if(clearTimeout(r),o!==0){e([]);return}let s=n.trim().split(`
397
397
  `).filter(i=>i==="image/png"||i==="image/bmp");bP=s,e(s)}),t.on("error",()=>{clearTimeout(r),e([])})})}async function wat(e){let t=await oSe();if(t.includes("image/png")){if(await Xq("wl-paste",["--no-newline","--type","image/png"],e))return e;try{await Mi.unlink(e)}catch{}}if(t.includes("image/bmp")){let n=e.replace(/\.png$/,".bmp");if(await Xq("wl-paste",["--no-newline","--type","image/bmp"],n))try{await new Promise((o,s)=>{let i=wP("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"))},Ok);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 Mi.unlink(n)}catch{}return e}catch(o){Ic.warn("BMP-to-PNG conversion failed (install python3-pil for BMP support):",o);try{await Mi.unlink(n)}catch{}try{await Mi.unlink(e)}catch{}return!1}try{await Mi.unlink(n)}catch{}}return!1}async function Tat(e){if(await Xq("xclip",["-selection","clipboard","-t","image/png","-o"],e))return!0;try{await Mi.unlink(e)}catch{}return!1}async function sSe(e){try{let t=e||process.cwd(),n=Zx.join(t,"clipboard");await Mi.mkdir(n,{recursive:!0});let r=new Date().getTime();if(process.platform==="linux"){let c=Zx.join(n,`clipboard-${r}-${ZDe()}.png`),u=rSe();if(u==="wl-paste"){let A=await wat(c);if(A)try{if((await Mi.stat(A)).size>0)return A;await Mi.unlink(A)}catch{}return null}return u==="xclip"&&await Tat(c)?c:null}let o=await nSe();if(!o)return null;let s=new o.ClipboardManager;if(!s.hasFormat("image"))return null;let i=Zx.join(n,`clipboard-${r}-${ZDe()}.png`),l=s.getImageData().data;return l?(await Mi.writeFile(i,l),i):null}catch(t){return Ic.error("Error saving clipboard image:",t),null}}async function iSe(e){try{let t=e||process.cwd(),n=Zx.join(t,"clipboard"),r=await Mi.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=Zx.join(n,a),c=await Mi.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 Mi.unlink(c.path)}}catch{}}var vat={UTF8:65001,GBK:936,BIG5:950,LATIN1:1252},cSe=e=>e.startsWith("@")||/\s@/.test(e),Rat=/[/\\]/,Qat=e=>e.slice(1).trimStart().split(/\s+/u)[0]??"",Zq=e=>Rat.test(Qat(e)),ta=e=>!(!e.startsWith("/")||e.startsWith("//")||e.startsWith("/*")||Zq(e)),kat=/^[/?]btw(?:\s|$)/,tb=e=>{let t=e.trim();return t.length>0&&kat.test(t)},qun=Ke("COMMAND_UTILS"),pD=async e=>{let t=(r,o,s)=>new Promise((i,a)=>{let l=s?aSe(r,o,s):aSe(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 ${vat.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(!eb(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"),eb(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 uSe(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 dSe(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 lSe=/(?:^|(?<=\s))\/([a-zA-Z][a-zA-Z0-9:_-]*)/g;function ASe(e,t){if(!e)return[];let n=[];for(let i of t){n.push([i.name.toLowerCase(),i]);for(let a of LC(i))n.push([a.toLowerCase(),i])}let r=new Map(n),o=[],s;for(lSe.lastIndex=0;(s=lSe.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===`
398
- `,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 Mat(e){try{return e.getGoalRuntime()}catch(t){if(t instanceof a0)return;throw t}}function fSe(e,t){let n,r=!1,o=Mat(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=zh(l);return c.outcome==="completed"||!l?.lastReason?c:{...c,reason:l.lastReason}},async release(l=nre){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 gw}from"node:crypto";h();h();function gSe(e){return e.api.totalRequests===0?0:e.api.totalErrors/e.api.totalRequests*100}function pSe(e){return e.api.totalRequests===0?0:e.api.totalLatencyMs/e.api.totalRequests}function mSe(e){return e.tokens.prompt===0?0:e.tokens.cached/e.tokens.prompt*100}var nb=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();var mD=(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=>LC(m).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();var Fat=Ke("CLI_COMMANDS"),hD=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):Fat.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=LC(u).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(KDe(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 cdn=M(Se(),1);var Nat=["achieved","aborted","failed"];function hSe(e){return Nat.includes(e)}h();import ob from"node:process";import _at from"node:os";import{execFile as Lat}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`},rb=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"},Hg=e=>e<1e3?`${e}`:e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.floor(e/1e3)}k`,Rr=(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 vP="9ee696a44";var CSe=Ke("STATUS"),Oat=5e3;function ESe(e){return new Promise(t=>{Lat(e,["--version"],{timeout:Oat,encoding:"utf-8"},(n,r)=>{if(n){t("unknown");return}t(typeof r=="string"?r.trim():"unknown")})})}async function eY(){return ESe("npm")}async function ySe(){return ESe("git")}async function Pat(e){if(!e.services.config?.getIdeMode())return"";try{return(await Xa.getInstance())?.getDetectedIdeDisplayName()??""}catch{return""}}function ISe(e=!1){let t=ob.env.SANDBOX;return!t||t==="sandbox-exec"?t==="sandbox-exec"?`sandbox-exec (${ob.env.SEATBELT_PROFILE||"unknown"})`:"no sandbox":e?t.replace(/^matilda-(?:code-)?/,""):t}async function Uat(e){let t=ob.platform,n=ob.arch,r=_at.release(),o=ob.version,s=await eY(),i=ISe(),a=e.services.config?.getModelDisplayName()||"Unknown",l=await Lg(),c=e.services.config?.getAuthType()||"",u=await Pat(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 RP(e){let t=await Uat(e),n=al(ob.memoryUsage().rss),r=ISe(!0),o=t.selectedAuthType==="openai"?e.services.config?.getContentGeneratorConfig():void 0,s=o?.baseUrl,i=o?.apiKeyEnvKey,a=vP&&!["N/A"].includes(vP)?vP:void 0,l=e.services.settings?.merged?.fastModel||void 0,c=Hat(e);return{...t,sandboxEnv:r,memoryUsage:n,baseUrl:s,apiKeyEnvKey:i,gitCommit:a,fastModel:l,lspStatus:c}}function Hat(e){try{let t=e.services.config?.getLspStatusSnapshot?.();return t?(e.services.config?.getDebugMode?.()&&CSe.debug("LSP status snapshot for /status:",t),Gat(t)):void 0}catch(t){e.services.config?.getDebugMode?.()&&CSe.debug("Unable to read LSP status snapshot for /status:",t);return}}function Gat(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 tY from"node:fs/promises";import zat from"node:path";var SSe=Ke("SESSION_PATHS"),DSe=100;async function BSe(e){let t=e.services.config,n=t?.getSessionId()||e.session.stats.sessionId||"unknown",r=t?.getContentGeneratorConfig(),o=t?.getWorkingDir()||process.cwd(),s=Qne(r?.openAILoggingDir,o),i=r?.enableOpenAILogging===!0,a=i&&n!=="unknown"?await jat(s,n):void 0,l=t?.getTranscriptPath()||"",c=t?.getDebugMode()&&n!=="unknown"?Ft.getDebugLogPath(n):"",u=t?.getPlanFilePath()||(n==="unknown"?"":Ft.getPlanFilePath(n)),A=u?await Yat(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 xSe(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(`
398
+ `,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 Mat(e){try{return e.getGoalRuntime()}catch(t){if(t instanceof a0)return;throw t}}function fSe(e,t){let n,r=!1,o=Mat(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=zh(l);return c.outcome==="completed"||!l?.lastReason?c:{...c,reason:l.lastReason}},async release(l=nre){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 gw}from"node:crypto";h();h();function gSe(e){return e.api.totalRequests===0?0:e.api.totalErrors/e.api.totalRequests*100}function pSe(e){return e.api.totalRequests===0?0:e.api.totalLatencyMs/e.api.totalRequests}function mSe(e){return e.tokens.prompt===0?0:e.tokens.cached/e.tokens.prompt*100}var nb=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();var mD=(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=>LC(m).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();var Fat=Ke("CLI_COMMANDS"),hD=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):Fat.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=LC(u).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(KDe(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 cdn=M(Se(),1);var Nat=["achieved","aborted","failed"];function hSe(e){return Nat.includes(e)}h();import ob from"node:process";import _at from"node:os";import{execFile as Lat}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`},rb=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"},Hg=e=>e<1e3?`${e}`:e<1e4?`${(e/1e3).toFixed(1)}k`:`${Math.floor(e/1e3)}k`,Rr=(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 vP="5bfb042b3";var CSe=Ke("STATUS"),Oat=5e3;function ESe(e){return new Promise(t=>{Lat(e,["--version"],{timeout:Oat,encoding:"utf-8"},(n,r)=>{if(n){t("unknown");return}t(typeof r=="string"?r.trim():"unknown")})})}async function eY(){return ESe("npm")}async function ySe(){return ESe("git")}async function Pat(e){if(!e.services.config?.getIdeMode())return"";try{return(await Xa.getInstance())?.getDetectedIdeDisplayName()??""}catch{return""}}function ISe(e=!1){let t=ob.env.SANDBOX;return!t||t==="sandbox-exec"?t==="sandbox-exec"?`sandbox-exec (${ob.env.SEATBELT_PROFILE||"unknown"})`:"no sandbox":e?t.replace(/^matilda-(?:code-)?/,""):t}async function Uat(e){let t=ob.platform,n=ob.arch,r=_at.release(),o=ob.version,s=await eY(),i=ISe(),a=e.services.config?.getModelDisplayName()||"Unknown",l=await Lg(),c=e.services.config?.getAuthType()||"",u=await Pat(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 RP(e){let t=await Uat(e),n=al(ob.memoryUsage().rss),r=ISe(!0),o=t.selectedAuthType==="openai"?e.services.config?.getContentGeneratorConfig():void 0,s=o?.baseUrl,i=o?.apiKeyEnvKey,a=vP&&!["N/A"].includes(vP)?vP:void 0,l=e.services.settings?.merged?.fastModel||void 0,c=Hat(e);return{...t,sandboxEnv:r,memoryUsage:n,baseUrl:s,apiKeyEnvKey:i,gitCommit:a,fastModel:l,lspStatus:c}}function Hat(e){try{let t=e.services.config?.getLspStatusSnapshot?.();return t?(e.services.config?.getDebugMode?.()&&CSe.debug("LSP status snapshot for /status:",t),Gat(t)):void 0}catch(t){e.services.config?.getDebugMode?.()&&CSe.debug("Unable to read LSP status snapshot for /status:",t);return}}function Gat(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 tY from"node:fs/promises";import zat from"node:path";var SSe=Ke("SESSION_PATHS"),DSe=100;async function BSe(e){let t=e.services.config,n=t?.getSessionId()||e.session.stats.sessionId||"unknown",r=t?.getContentGeneratorConfig(),o=t?.getWorkingDir()||process.cwd(),s=Qne(r?.openAILoggingDir,o),i=r?.enableOpenAILogging===!0,a=i&&n!=="unknown"?await jat(s,n):void 0,l=t?.getTranscriptPath()||"",c=t?.getDebugMode()&&n!=="unknown"?Ft.getDebugLogPath(n):"",u=t?.getPlanFilePath()||(n==="unknown"?"":Ft.getPlanFilePath(n)),A=u?await Yat(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 xSe(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(`
399
399
  `)}async function jat(e,t){let n=await Wat(e,r=>/^openai-.*\.json$/.test(r));for(let r of n)try{let o=await tY.readFile(r,"utf-8"),s=JSON.parse(o);if(Jat(s,t))return r}catch(o){if(o instanceof SyntaxError||o.code==="ENOENT")continue;SSe.warn("Error reading OpenAI log file",r,o)}}async function Wat(e,t){try{let n=await tY.readdir(e,{withFileTypes:!0}),r=[];for(let o of n)!o.isFile()||!t(o.name)||qat(r,zat.join(e,o.name));return r}catch(n){return n.code!=="ENOENT"&&SSe.warn("Unable to list OpenAI log directory",e,n),[]}}function qat(e,t){let n=e.findIndex(r=>t>r);if(n===-1){e.length<DSe&&e.push(t);return}e.splice(n,0,t),e.length>DSe&&e.pop()}async function Yat(e){try{return await tY.access(e),!0}catch{return!1}}function Jat(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}function $at(e){let t=e.services.config;if(!t)return{};let n=CO(t);return{account:n?.kind==="sign-in"?n.account??C("signed in"):n?.kind==="none"?C("not signed in, run /login"):void 0,apiKeySource:n?.kind==="api-key"?n.source:void 0,organizationId:t.getOrganizationId()}}var bSe={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 RP(e),...$at(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}`,...t.account?[`Account: ${t.account}`]:[],...t.apiKeySource?[`API key: ${t.apiKeySource}`]:[],...t.organizationId?[`Organisation: ${t.organizationId}`]:[],...t.baseUrl?[`Base URL: ${t.baseUrl}`]:[],`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(`
400
400
  `)};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 BSe(e);return{type:"message",messageType:"info",content:xSe(t)}}}]};h();function Vat(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 Kat(e){switch(e.kind){case"agent":return SR(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 Xat(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 Zat(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 wSe={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=Rr(c-l.startTime,{hideTrailingZeros:!0}),A=(l.kind==="shell"||l.kind==="monitor")&&l.pid!==void 0?` pid=${l.pid}`:"";a.push(`[${Xat(l)}] ${Vat(l)} ${u}${A} ${Kat(l)}`);let g=Zat(l);g&&a.push(` output: ${g}`)}return{type:"message",messageType:"info",content:um(a.join(`
401
401
  `))}}};h();function TSe(e,t){let n=e.endTime??t,r=Rr(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 elt(e,t){let n=[],r=e.endTime??t,o=Rr(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 vSe={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:elt(u,Date.now()).join(`
@@ -855,7 +855,7 @@ ${Z}
855
855
  `).filter(n=>n.trim()!=="");try{await AZ.unlink(fZ)}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: ${xr(e)}`]}}h();import hNt from"node:fs/promises";import CNt from"node:path";var ENt={id:"root-directory",check:async e=>{try{let t=await hNt.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 CNt.dirname(t)===t?n:null}catch{return"Could not verify the current directory due to a file system error."}}},yNt={id:"ripgrep-availability",check:async e=>{if(!e.useRipgrep)return null;try{return await C_(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.`}}},INt=[ENt,yNt];async function H3e(e){return(await Promise.all(INt.map(n=>n.check(e)))).filter(n=>n!==null)}h();import*as zT from"node:fs";import*as G3e from"node:path";function z3e(e){process.on("uncaughtExceptionMonitor",(t,n)=>{gZ(t,n,e)})}function gZ(e,t,n){let r=SNt(e,t,n);try{CN(),zT.writeSync(2,`Matilda crashed: ${DNt(e)}
856
856
  ${r?`The full error is saved in ${r}
857
857
  `:""}`)}catch{}}function DNt(e){let n=(e instanceof Error?e.message:String(e)).split(`
858
- `,1)[0].trim();return n.length>200?`${n.slice(0,199)}\u2026`:n}function SNt(e,t,n,r=new Date){try{let o;try{o=n.sessionId?.()}catch{o=void 0}let s=Ft.getGlobalCrashDir();zT.mkdirSync(s,{recursive:!0});let i=r.toISOString().replace(/[:.]/g,"-"),a=G3e.join(s,`${i}-${o??`pid-${process.pid}`}.log`),l=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);return zT.writeFileSync(a,[`time: ${r.toISOString()}`,`origin: ${t}`,`matilda: ${n.version??"0.22.0-nightly.20261101.b0ad315a4"??"unknown"}`,`node: ${process.version}`,`platform: ${process.platform} ${process.arch}`,`pid: ${process.pid}`,`session: ${o??"unknown"}`,"",l,""].join(`
858
+ `,1)[0].trim();return n.length>200?`${n.slice(0,199)}\u2026`:n}function SNt(e,t,n,r=new Date){try{let o;try{o=n.sessionId?.()}catch{o=void 0}let s=Ft.getGlobalCrashDir();zT.mkdirSync(s,{recursive:!0});let i=r.toISOString().replace(/[:.]/g,"-"),a=G3e.join(s,`${i}-${o??`pid-${process.pid}`}.log`),l=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);return zT.writeFileSync(a,[`time: ${r.toISOString()}`,`origin: ${t}`,`matilda: ${n.version??"0.22.0"??"unknown"}`,`node: ${process.version}`,`platform: ${process.platform} ${process.arch}`,`pid: ${process.pid}`,`session: ${o??"unknown"}`,"",l,""].join(`
859
859
  `),{mode:384}),a}catch{return}}h();var BNt=[/MaxListenersExceededWarning.*AbortSignal/];function xNt(e){let t=`${e.name}: ${e.message}`;return BNt.some(n=>n.test(t))}function bNt(){let e=t=>!!t&&t!=="0"&&t.toLowerCase()!=="false";return e(process.env.DEBUG)||e(process.env.MATILDA_DEBUG)}var pZ=null;function j3e(){if(pZ)return;let e=[...process.listeners("warning")];pZ=t=>{if(!(!bNt()&&xNt(t)))for(let n of e)try{n(t)}catch{}},process.removeAllListeners("warning"),process.on("warning",pZ)}h();function W3e(e){return e.promptInteractive?!1:wNt(e.prompt??e.query??"")}function wNt(e){let t=e.trim();return t==="/help"||t==="/?"}function q3e(){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(`
860
860
  `)}h();var TNt="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 Y3e(e,t=process.env){return e.getApprovalMode()!=="bogan"||e.getSandbox()||t.SANDBOX||vNt(t.MATILDA_CODE_SUPPRESS_BOGAN_WARNING)?null:TNt}function vNt(e){return e==="1"||e==="true"}h();var JS=Ke("EARLY_INPUT"),RN=64*1024,Cu={chunks:[],totalBytes:0,captured:!1},QN=null,kN=null,Y8=!1,KE=Buffer.alloc(0);function J3e(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 RNt(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 QNt(e){let t=Buffer.allocUnsafe(e.length),n=0,r=0;for(;r<e.length;){if(e[r]===27){let o=J3e(e,r);if(o==="incomplete")return{filtered:t.subarray(0,n),trailingPartialTerminalResponse:e.subarray(r)};if(o==="terminal"){let s=RNt(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 kNt(e){return e.length===0?!1:e.length===1&&e[0]===27?!0:J3e(e,0)==="user"}function $3e(){if(Y8||!process.stdin.isTTY){process.stdin.isTTY||JS.debug("Early input capture skipped: stdin is not a TTY");return}if(process.env.MATILDA_CODE_DISABLE_EARLY_CAPTURE==="1"){JS.debug("Early input capture disabled by environment variable");return}Y8=!0,Cu={chunks:[],totalBytes:0,captured:!1},KE=Buffer.alloc(0),JS.debug("Starting early input capture"),QN=e=>{if(Cu.captured)return;if(Cu.totalBytes>=RN){JS.warn(`Early input capture buffer full (${RN} bytes). Stopping capture; additional keystrokes during startup will be lost.`),V3e();return}let t=KE.length>0?Buffer.concat([KE,e]):e;KE=Buffer.alloc(0);let{filtered:n,trailingPartialTerminalResponse:r}=QNt(t);if(r.length>0&&(KE=Buffer.from(r)),n.length>0)if(Cu.totalBytes+n.length>RN){let s=n.subarray(0,RN-Cu.totalBytes);Cu.chunks.push(Buffer.from(s)),Cu.totalBytes+=s.length,JS.debug(`Buffer truncated at ${RN} bytes`)}else Cu.chunks.push(Buffer.from(n)),Cu.totalBytes+=n.length,JS.debug(`Captured ${n.length} bytes (total: ${Cu.totalBytes})`)},kN=process.stdin,kN.on("data",QN)}function V3e(){!Y8||!QN||!kN||(kN.removeListener("data",QN),kN=null,QN=null,Y8=!1,Cu.captured=!0,JS.debug(`Stopped early input capture: ${Cu.totalBytes} bytes`))}function MNt(){let e=[...Cu.chunks];kNt(KE)&&e.push(Buffer.from(KE));let t=e.length>0?Buffer.concat(e):Buffer.alloc(0);return Cu.chunks=[],Cu.totalBytes=0,KE=Buffer.alloc(0),t}function mZ(){return V3e(),MNt()}h();var K3e=M(_V(),1);var rg=Ke("PRECONNECT"),jT=!1,FNt=xre();function NNt(){return process.env.NODE_EXTRA_CA_CERTS?(rg.debug("Skipping preconnect: custom CA certificate configured"),!0):!1}function _Nt(){return process.env.SANDBOX!==void 0}function LNt(e){let t=e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return FNt.some(n=>{let r=n.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return t===r||t.startsWith(r+"/")})}function ONt(e){if(e&&/^https?:\/\//i.test(e)){if(LNt(e))return e;rg.debug("Skipping preconnect: resolved baseUrl is not a default URL")}}function X3e(e={}){if(jT)return;if(process.env.MATILDA_CODE_DISABLE_PRECONNECT==="1"){rg.debug("Preconnect disabled by environment variable"),jT=!0;return}if(_Nt()){rg.debug("Skipping preconnect: sandbox mode detected"),jT=!0;return}if(NNt()){jT=!0;return}if(jne()!=="node"){rg.debug("Skipping preconnect: unsupported runtime"),jT=!0;return}if(!e.proxy){rg.debug("Skipping preconnect dispatcher: no proxy configured");return}let t=e.proxy,n=ONt(e.resolvedBaseUrl);if(!n){rg.debug("No target URL for preconnect");return}jT=!0,rg.debug(`Preconnecting to: ${n}`);try{let r=Wne(t);(0,K3e.fetch)(n,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"MatildaCode-Preconnect/1.0"},dispatcher:r}).then(()=>{rg.debug("Preconnect completed")}).catch(o=>{let s=vj(String(o));rg.debug(`Preconnect failed (ignored): ${s}`)})}catch(r){let o=vj(String(r));rg.debug(`Preconnect failed (ignored): ${o}`)}}h();async function Z3e(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=ox(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 mw(t):s=new Om(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 Rl(),process.exit(1)}st(r instanceof Error?r.message:String(r)),process.exit(1)}}h();var t8e=M(Se(),1);var $S=M(ie(),1);var PNt={getShouldUseNodePtyShell:()=>!1,getIdeMode:()=>!1,isTrustedFolder:()=>!1,getToolRegistry:()=>({getTool:()=>{}}),getContentGenerator:()=>({useSummarizedThinking:()=>!1})},UNt={merged:{ui:{}}};function HNt({sessionService:e,onSelect:t,onCancel:n,currentBranch:r,initialSessions:o}){let{exit:s}=TW(),[i,a]=(0,t8e.useState)(!1),l=()=>{a(!0),s()};return i?(0,$S.jsx)(x,{}):(0,$S.jsx)(Uf.Provider,{value:PNt,children:(0,$S.jsx)(CD.Provider,{value:UNt,children:(0,$S.jsx)(KF,{sessionService:e,onSelect:c=>{t(c),l()},onCancel:()=>{n(),l()},currentBranch:r,centerSelection:!0,initialSessions:o,enablePreview:!0})})})}function e8e(){process.stdout.write("\x1B[2J\x1B[H")}async function hZ(e=process.cwd(),t){let n=new pi(e);if(!await n.loadLastSession()){St("No sessions found. Start a new session with `matilda`.");return}e8e();let o=process.stdin.isRaw;return process.stdin.isTTY&&!o&&process.stdin.setRawMode(!0),new Promise(s=>{let i,{unmount:a,waitUntilExit:l}=uQ((0,$S.jsx)(PP,{kittyProtocolEnabled:!1,pasteWorkaround:process.platform==="win32"||parseInt(process.versions.node.split(".")[0],10)<20,children:(0,$S.jsx)(HNt,{sessionService:n,onSelect:c=>{i=c},onCancel:()=>{i=void 0},currentBranch:r_(e),initialSessions:t})}),{exitOnCtrlC:!1});l().then(()=>{a(),e8e(),process.stdin.isTTY&&!o&&!i&&process.stdin.setRawMode(!1),s(i)})})}h();import{createReadStream as GNt,watchFile as zNt,unwatchFile as jNt,statSync as n8e}from"node:fs";import{createInterface as WNt}from"node:readline";var fh=Ke("REMOTE_INPUT"),J8=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=n8e(this.filePath);this.bytesRead=t.size}catch{this.bytesRead=0}zNt(this.filePath,{interval:this.pollIntervalMs},()=>{this.active&&this.readNewLines()}),fh.debug(`RemoteInput: watching ${this.filePath}`)}checkForNewInput(){return this.readNewLines()}readNewLines(){if(!this.active||this.reading)return Promise.resolve();let t;try{t=n8e(this.filePath).size}catch{return Promise.resolve()}if(t<=this.bytesRead)return Promise.resolve();this.reading=!0;let n=GNt(this.filePath,{start:this.bytesRead,encoding:"utf-8"}),r=WNt({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"?(fh.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"?(fh.debug(`RemoteInput: queued command: ${i.text.slice(0,50)}...`),this.queue.push(i)):fh.warn(`RemoteInput: unknown command type: ${String(i?.type)}`)}catch{fh.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];fh.debug(`RemoteInput: submitting: ${t.text.slice(0,50)}...`);try{if(await this.submitFn(t.text)===!1){fh.debug("RemoteInput: TUI busy, will retry on idle"),this.scheduleRetry();break}this.queue.shift()}catch(n){fh.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,jNt(this.filePath),this.retryTimer&&clearTimeout(this.retryTimer),this.queue.length=0,fh.debug("RemoteInput: shut down")}};h();var Gd="\x1B[",WT=`${Gd}2K`,qNt=`${Gd}1A`,YNt=`${Gd}1B`,EZ=`${Gd}G`,JNt=new RegExp(`(?:${r8e(WT+qNt)})+${r8e(WT+EZ)}`,"g");function r8e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function o8e(e,t){let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n}var $8={stdoutWriteCount:0,stdoutBytes:0,clearTerminalCount:0,eraseLinesOptimizedCount:0};function $Nt(e,t){if(typeof e=="string"){let n=typeof t=="string"?t:void 0;return Buffer.byteLength(e,n)}return e.byteLength}function CZ(e,t,n){if(!e.startsWith(Gd,t))return t;let r=t+Gd.length,o=r;for(;r<e.length&&e[r]>="0"&&e[r]<="9";)r++;return r>o&&e[r]===n?r+1:t}function VNt(e){for(let t=0;t<e.length;t++)if(e.startsWith(Gd,t)){for(t+=Gd.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]!==`
861
861
  `||n>=127&&n<=159)return!1}return!0}function KNt(e,t){if(!t||t<3)return;let n=0;if(e.startsWith(ao.cursorHide)){n=CZ(e,ao.cursorHide.length,"B");let c=ao.cursorTo(0);if(!e.startsWith(c,n))return;n+=c.length}let r=e.slice(0,n),o=ao.eraseLines(t);if(!e.startsWith(o,n))return;n+=o.length;let s=e.length;if(e.endsWith(ao.cursorShow)){let c=s-ao.cursorShow.length,u=e.lastIndexOf(Gd,c-1);if(u<n||CZ(e,u,"G")!==c)return;s=u;let A=e.lastIndexOf(Gd,s-1);A>=n&&CZ(e,A,"A")===s&&(s=A)}let i=e.slice(n,s),a=e.slice(s),l=i.split(`
@@ -923,7 +923,7 @@ ${u.text}`}),"blob"in u&&u.blob&&c.push(x_({inlineData:{mimeType:u.mimeType??"ap
923
923
  ${o.join(`
924
924
  `)}
925
925
  ---
926
- ${r}`}var Oze=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function Pze(e){let t;try{t=new URL(e)}catch{throw ze.invalidParams(void 0,"Skill sourceUrl must be a valid URL")}if(t.protocol!=="https:")throw ze.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(!Oze.has(t.hostname))throw ze.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function Uze(e){let t=new URL(e);if(t.protocol!=="https:")throw ze.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 YOt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function JOt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function ete(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 $Ot(e,t){let n=ete(e,t+124,12);return n?Number.parseInt(n,8):0}function VOt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function KOt(e,t){let n=ete(e,t,100),r=ete(e,t+345,155);return r?`${r}/${n}`:n}function XOt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var YN=100*1024*1024,Hze=500*1024*1024,ZOt=16,ePt=2e3,Mz=class extends Error{};async function tPt(e,t,n={}){let r=n.maxCompressedBytes??YN,o=n.maxDecompressedBytes??Hze;if(e.length>r)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await bOt(kze.from([Buffer.from(e)]),TOt(),new Mze({write(A,g,d){if(u+=A.length,u>o){d(new Mz);return}c.push(A),d()}})),s=Buffer.concat(c)}catch(c){throw c instanceof Mz?ze.invalidParams(void 0,"Decompressed skill archive exceeds the maximum allowed size"):ze.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&&!VOt(s,c);){let u=KOt(s,c),A=String.fromCharCode(s[c+156]||0),g=$Ot(s,c),d=c+512,m=d+Math.ceil(g/512)*512;if(A==="0"||A==="\0"){let E=XOt(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 nPt=[".githubusercontent.com",".github.com"];function rPt(e){return Oze.has(e)?!0:nPt.some(t=>e.endsWith(t))}async function ote(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 ze.invalidParams(void 0,"Skill download redirected to an invalid URL")}if(a.protocol!=="https:"||!rPt(a.hostname))throw ze.invalidParams(void 0,"Skill download redirected to a disallowed host");r=a.toString()}throw ze.invalidParams(void 0,"Skill download exceeded the maximum number of redirects")}async function Gze(e,t){let n=e.body;if(!n){let l=new Uint8Array(await e.arrayBuffer());if(l.byteLength>t)throw ze.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(),ze.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 zze(e){let t=await ote(e);if(!t.ok)throw ze.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>YN)throw ze.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return Gze(t,YN)}async function oPt(e){let t=Uze(e),n=t?YOt(t):e,r=await zze(n);return{skillContent:Buffer.from(r).toString("utf8"),files:[{relativePath:"SKILL.md",content:r}]}}async function sPt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,r=await ote(n,{headers:{"User-Agent":"matilda-code"}});if(!r.ok)throw ze.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>YN)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return tPt(await Gze(r,YN),t)}async function iPt(e,t){let n=JOt(t),r=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,o=await ote(r,{headers:{Accept:"application/vnd.github+json","User-Agent":"matilda-code"}});if(!o.ok)throw ze.invalidParams(void 0,`Failed to list GitHub skill files (${o.status})`);let s=await o.json();if(!Array.isArray(s))throw ze.invalidParams(void 0,"GitHub skill URL must point to a directory-backed SKILL.md file");return s}async function jze(e,t,n="",r=0,o={files:0,bytes:0}){if(r>ZOt)throw ze.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await iPt(e,t),i=[];for(let a of s){let l=Zs(a),c=Mp(l.name,"github.name"),u=Mp(l.path,"github.path"),A=Mp(l.type,"github.type"),g=n?no.posix.join(n,c):c;if(A==="dir"){i.push(...await jze(e,u,g,r+1,o));continue}if(A!=="file")continue;if(o.files+=1,o.files>ePt)throw ze.invalidParams(void 0,"Skill directory contains too many files");let d=Mp(l.download_url,"github.download_url");Pze(d);let m=await zze(d);if(o.bytes+=m.length,o.bytes>Hze)throw ze.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:g,content:m})}return i}async function aPt(e,t){let n=await jze(e,t).catch(r=>(Xl.warn("GitHub API directory listing failed, falling back to archive download:",r),null));return n||sPt(e,t)}async function lPt(e){Pze(e);let t=Uze(e);if(!t||no.posix.basename(t.filePath)!=="SKILL.md")return oPt(e);let n=no.posix.dirname(t.filePath),r=await aPt(t,n),o=r.find(s=>s.relativePath==="SKILL.md");if(!o)throw ze.invalidParams(void 0,"GitHub skill directory does not contain SKILL.md");return{skillContent:Buffer.from(o.content).toString("utf8"),files:r}}function cPt(e,t){let n=no.resolve(e),r=no.resolve(e,t);if(r!==n&&!r.startsWith(n+no.sep))throw ze.invalidParams(void 0,`Invalid skill file path: ${t}`);return r}function wze(e,t){let n=no.resolve(e),r=no.resolve(e,t);if(!r.startsWith(n+no.sep))throw ze.invalidParams(void 0,"Invalid skill.slug");return r}function uPt(e,t){if(typeof e.documentationUrl=="string")return e.documentationUrl;if(typeof e.documentationUrl=="function")try{return e.documentationUrl(t)}catch{return}}function dPt(e){return typeof Zs(e).id=="string"}function APt(e,t){if(!t)return;let r=Zs(e.env)[t];return typeof r=="string"&&r.length>0?r:void 0}function fPt(e,t){let r=Zs(e.modelProviders)[t];return Array.isArray(r)?r.filter(dPt):[]}function Wze(e,t){let n=s_(e);return n?fPt(t,e.protocol).filter(n):[]}function qze(e,t,n){let r=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:mi(e),o=typeof n[0]?.envKey=="string"?n[0].envKey:e.envKey;return n0(r)??APt(t,o)}function gPt(e,t){let n=Wze(e,t),r=qze(e,t,n);if(!r&&n.length===0)return;let o=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:mi(e);return{baseUrl:kz(o),...r?{hasApiKey:!0}:{},...n.length>0?{modelIds:n.map(s=>s.id)}:{}}}function pPt(e,t){return qze(e,t,Wze(e,t))}function mPt(e,t){let n=mi(e),r=gPt(e,t);return{id:e.id,label:e.label,description:e.description,protocol:e.protocol,baseUrl:e.baseUrl,defaultModelIds:Dre(e),models:e.models,apiKeyPlaceholder:e.apiKeyPlaceholder,documentationUrl:uPt(e,n),uiGroup:e.uiGroup??"third-party",uiLabels:e.uiLabels,...r?{existingConfig:r}:{}}}function hPt(e,t,n){let r=mi(e),o=oy(t.apiKey,"apiKey")??n;if(!o)throw ze.invalidParams(void 0,"Invalid or missing apiKey");let s=e.validateApiKey?.(o,r);if(s)throw ze.invalidParams(void 0,s);return{baseUrl:r,apiKey:o}}function CPt(e){if(e!==void 0){if(e==="user")return"User";if(e==="workspace")return"Workspace";throw ze.invalidParams(void 0,"Invalid scope for provider connect")}}function EPt(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 Zee(e){let t={};for(let n of _ze){let r=EPt(e,n);r!==void 0&&(t[n]=r)}return t}function yPt(e,t){let n=Nze[e];switch(n.type){case"boolean":if(typeof t!="boolean")throw ze.invalidParams(void 0,`${e} must be a boolean`);return t;case"number":if(typeof t!="number"||!Number.isFinite(t))throw ze.invalidParams(void 0,`${e} must be a number`);if(n.min!==void 0&&t<n.min)throw ze.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 ze.invalidParams(void 0,`${e} must be one of ${r?.join(", ")}`);return t}case"string":{if(t===void 0)return;if(typeof t!="string")throw ze.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 ze.invalidParams(void 0,`${e} has an unsupported setting type`)}}function og(e){if(e!==void 0){if(!Array.isArray(e))throw ze.invalidParams(void 0,"Expected an array of strings");return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean)}}function oB(e){if(e===void 0)return;let t=Zs(e),n={};for(let[r,o]of Object.entries(t))typeof o=="string"&&r.trim()&&(n[r.trim()]=o);return n}function qN(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number.parseInt(String(e),10);if(!Number.isFinite(t)||t<=0)throw ze.invalidParams(void 0,"Expected a positive number");return t}function IPt(e){let t=Zs(e),n=t.transport;if(n!=="stdio"&&n!=="http"&&n!=="sse")throw ze.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=qN(t.timeout);if(i!==void 0&&(r.timeout=i),typeof t.trust=="boolean"&&(r.trust=t.trust),r.includeTools=og(t.includeTools),r.excludeTools=og(t.excludeTools),n==="stdio"){let c=t.command;if(typeof c!="string"||!c.trim())throw ze.invalidParams(void 0,"Stdio MCP servers require a command");return r.command=c.trim(),r.args=og(t.args),r.env=oB(t.env),r}let l=t[n==="http"?"httpUrl":"url"];if(typeof l!="string"||!l.trim())throw ze.invalidParams(void 0,`${n.toUpperCase()} MCP servers require a URL`);return n==="http"?r.httpUrl=l.trim():r.url=l.trim(),r.headers=oB(t.headers),r}var DPt=new Set(["command","args","cwd","env","httpUrl","url","headers","timeout","trust","description","includeTools","excludeTools"]);function SPt(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!DPt.has(t)))}function BPt(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 xPt(e){let t=Zs(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:oB(t.headers),timeout:qN(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:og(t.includeTools),excludeTools:og(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:oB(t.headers),timeout:qN(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:og(t.includeTools),excludeTools:og(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:og(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:oB(t.env),timeout:qN(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:og(t.includeTools),excludeTools:og(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var Fz="__redacted__";function bPt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(r=>[r,Fz]));return{...e,env:t(e.env),headers:t(e.headers)}}function wPt(e,t){let n=(r,o)=>{if(!r)return r;let s=Zs(o),i={};for(let[a,l]of Object.entries(r)){if(l!==Fz){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 Tze(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,Fz]))}function vze(e,t){if(!e)return e;let n=Zs(t),r={};for(let[o,s]of Object.entries(e)){if(s!==Fz){r[o]=s;continue}let i=n[o];typeof i=="string"&&(r[o]=i)}return r}function TPt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:Tze(t.env)}:{},...t.headers?{headers:Tze(t.headers)}:{}}))}}function vPt(e,t){let n=Array.isArray(t.hooks)?t.hooks:[];return{...e,hooks:e.hooks.map((r,o)=>{let s=Zs(n[o]);return{...r,...r.env?{env:vze(r.env,s.env)}:{},...r.headers?{headers:vze(r.headers,s.headers)}:{}}})}}function jN(e,t){let n=Zs(e.mcpServers);return Object.entries(n).map(([r,o])=>{try{let s=xPt(o);return s?{name:r,scope:t,server:bPt(s)}:void 0}catch(s){Xl.warn(`Skipping malformed MCP server config [${t}:${r}]:`,s);return}}).filter(r=>!!r)}function Rze(e){return typeof e=="string"&&Lze.includes(e)}function RPt(e){let t=Zs(e),n=t.type;if(n!=="command"&&n!=="http")throw ze.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 ze.invalidParams(void 0,"Command hooks require a command");r.command=s.trim(),r.env=oB(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 ze.invalidParams(void 0,"HTTP hooks require a URL");r.url=s.trim(),r.headers=oB(t.headers),r.allowedEnvVars=og(t.allowedEnvVars),typeof t.once=="boolean"&&(r.once=t.once)}let o=qN(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 Yze(e){let t=Zs(e),n=t.hooks;if(!Array.isArray(n)||n.length===0)throw ze.invalidParams(void 0,"Hook definition requires at least one hook");let r={hooks:n.map(RPt)};return typeof t.matcher=="string"&&(r.matcher=t.matcher),typeof t.sequential=="boolean"&&(r.sequential=t.sequential),r}function WN(e,t,n){let r=Zs(e.hooks),o=[];for(let s of Lze){let i=r[s];Array.isArray(i)&&i.forEach((a,l)=>{try{o.push({event:s,scope:t,index:l,hook:TPt(Yze(a)),extensionName:n})}catch(c){Xl.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return o}function rB(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw ze.invalidParams(void 0,"scope must be user or workspace")}function Qz(e,t){return e.forScope(rB(t)).settings}async function Qze(e,t){for(let n of dd()){let r=no.join(e,n);try{return await Il.access(r),r}catch{}}return no.join(e,t)}async function QPt(e){let t=dd()[0]??"MATILDA.md",n=await Qze(Ft.getGlobalMatildaDir(),t),r=await Qze(e.cwd,t),o=Lh(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:r,autoMemoryDir:o}}async function Jze(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let r=Mze.toWeb(process.stdout),o=kze.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=z8e(r,o),i,a=new dz(m=>(i=new tte(e,t,n,m),i),s),l=async m=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(E){Xl.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 B of y){let b=B.getConfig?.();b&&E.add(b)}for(let B of E){let b=B.getHookSystem?.();if(!(B.getDisableAllHooks?.()||!b||!B.hasHooksForEvent?.("SessionEnd")))try{await b.fireSessionEndEvent(m)}catch(v){Xl.warn(`SessionEnd hook failed: ${v instanceof Error?v.message:String(v)}`)}}},g=async()=>{if(c)return;c=!0,Xl.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,Rl().catch(E=>{Xl.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 kPt(e){if("command"in e&&"args"in e&&"env"in e)return e}function MPt(e){if("type"in e&&e.type==="sse")return e}function FPt(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 Noe(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)&&Xl.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Xl.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){Xl.debug(`Session ${t} tool registry stop during close failed: ${r instanceof Error?r.message:String(r)}`)}this.mcpPool.releaseSession(t),Lo.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"&&Xl.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return Qk(t.merged,this.argv.channel)}get matildaAccount(){return this.matildaAccountState??=new gz({channel:this.config.getChannel(),connectionSignal:this.connection.signal,install:t=>p5(za(process.cwd()),t)}),this.matildaAccountState}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[nte];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===Tz,this.transcriptUpdatesNegotiated=this.transcriptReadNegotiated&&n.transcriptUpdates===yze,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===jee,this.compactionUpdatesNegotiated=t.clientCapabilities?.session?.compaction!=null,this.signInUrlNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.signInUrl===1;let r=tv(this.config);return{protocolVersion:SZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.22.0-nightly.20261101.b0ad315a4"},authMethods:r,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated||this.finalAnswersNegotiated||this.sessionNoticesNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:Tz}:{},...this.transcriptUpdatesNegotiated?{transcriptUpdates:yze}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{},...this.finalAnswersNegotiated?{finalAnswers:1}:{},...this.sessionNoticesNegotiated?{sessionNotices:jee}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0},...tB({channel:this.config.getChannel()})?{auth:{logout:{}}}:{}}}}async authenticate({methodId:t}){if(t===zee&&tB({channel:this.config.getChannel()})){await this.matildaAccount.signIn(this.signInUrlNegotiated?r=>this.connection.extNotification(tze,{...r}):void 0);return}let n=$t.nativeEnum(rA).parse(t);await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}async logout(){if(!tB({channel:this.config.getChannel()}))throw ze.methodNotFound("logout");await this.matildaAccount.signOut()}async newSession({cwd:t,mcpServers:n}){let r=hr(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:Bze(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=FOt(t),a=NOt(i);if(!await new pi(i,a).sessionExists(t.sessionId))throw ze.resourceNotFound(`session:${t.sessionId}`);this.sessions.has(t.sessionId)&&await this.stopSessionAndItsWork(t.sessionId);let c=hr(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:Bze(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 g0(r);o.contextMessage&&(n.pendingWorktreeNotice=o.contextMessage)}catch(r){Xl.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 sv(za(n),n,()=>new pi(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 ze.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 ze.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 ze.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 KB?new ze(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=za(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:vz(t.user.settings)},workspace:{path:t.workspace.path,rules:vz(t.workspace.settings)},merged:vz(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 lc({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await d.refreshCache(),i=d.getLoadedExtensions()}catch(d){Xl.warn("Extension loading failed, continuing without extensions:",d)}let a=await Promise.all(i.map(async d=>{let m=await f0(d.config,d.id,"user"),E=await f0(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(B=>B.name),mcpServers:Object.keys(d.config.mcpServers??{}),settings:y.map(B=>{let b=m[B.envVar],w=E[B.envVar],v=w!==void 0,Q=b!==void 0,O=v?w:b,z=v?"workspace":Q?"user":void 0;return{name:B.name,description:B.description,envVar:B.envVar,sensitive:!!B.sensitive,userValue:B.sensitive?void 0:b,workspaceValue:B.sensitive?void 0:w,effectiveValue:B.sensitive?void 0:O,effectiveScope:z,hasUserValue:Q,hasWorkspaceValue:v}})}})),l=i.filter(d=>d.isActive),c=l.flatMap(d=>jN({mcpServers:d.config.mcpServers??{}},"extension").map(m=>({...m,server:{...m.server,extensionName:d.name}}))),u=l.flatMap(d=>WN({hooks:d.hooks??{}},"extension",d.name)),A=new Map;for(let d of jN(r,"user"))A.set(d.name,d);if(t.isTrusted)for(let d of jN(o,"workspace"))A.set(d.name,d);let g=[...WN(r,"user"),...t.isTrusted?WN(o,"workspace"):[]];return{user:{path:t.user.path,values:Zee(r),mcpServers:jN(r,"user"),hooks:WN(r,"user")},workspace:{path:t.workspace.path,values:Zee(o),mcpServers:jN(o,"workspace"),hooks:WN(o,"workspace")},merged:{values:Zee(s),mcpServers:[...A.values(),...c],hooks:[...g,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){let r=t==="Workspace"?xze(n):void 0,o=new Map;for(let s of this.sessions.values()){let i=s.getConfig(),a=i.storage.getProjectRoot(),l=xze(a);if(r!==void 0&&l!==r)continue;let c=i.getPermissionManager?.();if(c)try{let u=o.get(l);u||(u=vz(za(a).merged),o.set(l,u));let A=i.getPermissionsBeyondSettings?.(),g=LOt(c);for(let d of _Ot){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){Xl.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??Eze(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?ty(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,B=ty(y,d.authType),b=a===d.authType&&i&&(s===y||s===d.id||l===B),w={modelId:B,baseModelId:lze(y),name:d.label,...d.description!==void 0?{description:d.description}:{},contextLimit:d.contextWindowSize??Tj(y),...d.modalities!==void 0?{modalities:d.modalities}:{},...d.baseUrl!==void 0?{baseUrl:kz(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:wz,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...A?{baseUrl:kz(A)}:{},...g?{fastModelId:g}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:wz,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!0,providers:[],errors:[this.errorCell("providers",n)]}}}sessionOrThrow(t){let n=this.sessions.get(t);if(!n)throw ze.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 Vee(n.getConfig());return{v:wz,sessionId:t,availableCommands:r,availableSkills:o??[],...s?{availableSkillDetails:s}:{}}}async installSkillFromUrl(t){let n=this.config.getSkillManager();if(!n)throw ze.invalidParams(void 0,"SkillManager is not available");let r=await lPt(t.sourceUrl),o=no.join(Ft.getGlobalMatildaDir(),"skills"),s=wze(o,t.slug),i=no.join(s,"SKILL.md"),a=n.parseSkillContent(r.skillContent,i,"user");if(a.name!==t.slug)throw ze.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=`${s}.installing-${process.pid}-${Date.now()}`;try{await Il.rm(l,{recursive:!0,force:!0});for(let c of r.files){let u=cPt(l,c.relativePath);await Il.mkdir(no.dirname(u),{recursive:!0}),await Il.writeFile(u,c.content)}await Il.rm(s,{recursive:!0,force:!0}),await Il.rename(l,s)}catch(c){throw await Il.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 ze.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 ze.invalidParams(void 0,`Skill name "${i.name}" does not match requested slug "${t.slug}"`);let a=no.resolve(r),l=no.resolve(o),c=no.resolve(Ft.getGlobalMatildaDir());if(!(l===no.join(a,"SKILL.md"))||a===no.parse(a).root||a===c)throw ze.invalidParams(void 0,`Refusing to delete unexpected skill directory: ${r}`);return await Il.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=wze(no.join(Ft.getGlobalMatildaDir(),"skills"),t),u=no.join(c,"SKILL.md"),A=await Il.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 ze.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`);let l=await Il.readFile(a,"utf8").catch(()=>{throw ze.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`)});return{skillDir:no.dirname(a),skillFile:a,content:l}}async findProjectSkillFileFromCwd(t,n,r){let o=no.resolve(n);for(let s of POt){let i=no.join(o,s,UOt),c=(await r.loadSkillsFromDir(i,"project")).find(A=>A.name===t)?.filePath;if(!c)continue;let u=await Il.readFile(c,"utf8").catch(()=>{throw ze.invalidParams(void 0,`Project skill not found: ${t}`)});return{skillDir:no.dirname(c),skillFile:c,content:u}}}async setGlobalSkillEnabled(t,n){let r=this.config.getSkillManager();if(!r)throw ze.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 ze.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=qOt(s,t.enabled);if(r.parseSkillContent(l,o,i),no.basename(o)!=="SKILL.md")throw ze.invalidParams(void 0,`Refusing to write to unexpected skill file: ${o}`);return await Il.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=Mp(n.description,"description");if(i.length>Gk)throw ze.invalidParams(void 0,"Bug description is too long");return{...await lb({description:i,envSummary:`${process.platform}/${process.arch}`})}}case oze:{let{sessionId:i,modelId:a}=n;if(typeof i!="string"||typeof a!="string")throw ze.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 ze.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new ze(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i);if(!a)throw ze.resourceNotFound(`session:${i}`);return a.attachClient(),{}}case"matilda/session/readState":{if(!this.sessionStateNegotiated)throw ze.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new ze(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i)?.getSessionState();if(!a)throw ze.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 ze.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(za(o));return{providers:IR.map(a=>mPt(a,i))}}case"matilda/providers/connect":{let i=Mp(n.providerId,"providerId"),a=Bre(i);if(!a)throw ze.invalidParams(void 0,`Unknown provider: ${i}`);let l=za(o),c=hPt(a,n,pPt(a,l.merged)),u=CPt(n.scope),A=oA(a,c);return await jh(A,{settings:BC(l,u),reloadModelProviders:g=>{let d=Qk({...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(GOt(n));case"matilda/skills/delete":return this.deleteGlobalSkill(zOt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(jOt(n),r);case"matilda/settings/getMemory":{let i=za(o);return this.settings=i,{settings:bze(this.effectiveSettings(i).memory)}}case"matilda/settings/setMemory":{let i=Zs(n.updates),a=za(o);for(let l of HOt)if(i[l]!==void 0){if(typeof i[l]!="boolean")throw ze.invalidParams(void 0,`Invalid memory setting '${l}': expected boolean`);a.setValue("User",`memory.${l}`,i[l])}return this.settings=a,{settings:bze(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 QPt({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 ze.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");return{memories:(a==="user"?await poe():await goe(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 ze.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");let l=n.relativePath;if(typeof l!="string"||l.length===0)throw ze.invalidParams(void 0,"Invalid or missing relativePath");return await Uoe({scope:a,projectRoot:i,relativePath:l}),{deleted:!0}}case Kee.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case Kee.sessionSupportedCommands:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ze.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionSupportedCommandsStatus(i)}case Xee.sessionClose:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ze.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 ze.invalidParams(void 0,"Invalid or missing sessionId");return await this.closeSessionAndItsWork(i),{success:await sv(za(o),o,async()=>new pi(o).removeSession(i))}}case Xee.sessionRename:{let i=n.sessionId,a=n.title;if(!i||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");if(typeof a!="string")throw ze.invalidParams(void 0,"Invalid or missing title");if(a.length>yR)throw ze.invalidParams(void 0,`Title too long (max ${yR} 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 sv(za(o),o,async()=>new pi(o).renameSession(i,a,l))}}case"rewindSession":{let i=n.sessionId;if(!i||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i);if(!a)throw ze.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 ze(-32602,"Invalid promptId format",{errorKind:"invalid_rewind_target"});let y=c.slice(E.length);if(!/^\d+$/.test(y))throw new ze(-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 ze(-32602,"Snapshot not found for the given promptId",{errorKind:"invalid_rewind_target"});l=w}if(!Number.isInteger(l)||l<0)throw ze.invalidParams(void 0,"Invalid or missing targetTurnIndex");let u=a.captureHistorySnapshot(),A;try{A=await a.rewindToTurn(l)}catch(E){if(E instanceof ze){let y=E.message;if(y.includes("Cannot rewind while a prompt is running"))throw new ze(E.code,y,{errorKind:"session_busy"});if(y.includes("compressed or does not exist"))throw new ze(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 B=y instanceof Error?y.message:String(y);Xl.error(`[ACP] File-history rewind failed for session=${i} promptId=${c}: ${B}`),d=[`file-history-rewind: ${B}`]}}return{success:!0,historyBeforeRewind:u,...A,filesChanged:g,filesFailed:d}}case"matilda/session/readTranscript":{if(!this.transcriptReadNegotiated)throw ze.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");let a=Fze.optional().safeParse(n.cursor);if(!a.success)throw ze.invalidParams(void 0,"Invalid transcript cursor");if(this.sessionRestoreCompletions.has(i))throw new ze(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let l=this.sessions.get(i);if(!l)throw ze.resourceNotFound(`session:${i}`);let c=await l.readTranscript(a.data);if(this.sessions.get(i)!==l||this.sessionRestoreCompletions.has(i))throw new ze(-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:Tz,sessionId:i,...c,runtime:A};if(!this.transcriptUpdatesNegotiated)throw ze.invalidParams(void 0,"Transcript updates were not negotiated");let g=c.mode==="delta"?kOt(n.projection,a.data):void 0,d=c.mode==="snapshot"||g&&!MOt(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=[],B=pi.reconstructHistory(d.records),b=await new nB({sessionId:i,config:this.config,sendUpdate:async w=>{y.push(w)},cumulativeUsage:E},!0,l.getActiveTaskStartUuid(),this.finalAnswersNegotiated,this.compactionUpdatesNegotiated).replay(B,m?{continuation:m.continuation,partial:!0,messageIdOf:w=>l.committedMessageIdOf(w)??w}:{});return{version:Tz,sessionId:i,mode:m?"delta":"snapshot",cursor:d.cursor,updates:Sze(y),transcriptRecords:Dze(B),...d.cursor?{projection:Ize({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 ze.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i)?.getActiveTaskStartUuid(),l=await sv(za(o),o,async()=>new pi(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 nB(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),Xl.warn("[loadUpdates] History replay failed for session %s (partial updates: %d):",i,c.length,y)}let d=l.transcriptCursor,m=rre(l.conversation.messages),E=m.kind==="v2"?hz(m.payload.snapshot):null;return{updates:Sze(c),transcriptRecords:Dze(l.conversation.messages),...E?{goal:E}:{},...this.transcriptUpdatesNegotiated&&d&&g?{transcript:d,projection:Ize({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=$t.object({sessionId:$t.string().regex(s),messages:$t.array($t.object({id:$t.string().uuid(),role:$t.enum(["user","assistant"]),content:$t.string(),timestamp:$t.number().finite().min(0).max(864e13)}))}).safeParse(n);if(!i.success)throw ze.invalidParams(void 0,"Invalid imported history");let a=this.sessions.get(i.data.sessionId);if(!a)throw ze.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 ze.invalidParams(void 0,"Invalid or missing sessionId");if(!Array.isArray(a))throw ze.invalidParams(void 0,"Invalid or missing history");let l=this.sessions.get(i);if(!l)throw ze.invalidParams(void 0,`Session not found for id: ${i}`);return l.restoreHistory(a),{success:!0}}case nze: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?kz(c.baseUrl):null,apiKeyEnvKey:c?.apiKeyEnvKey??null,account:rze(c?.baseUrl,l.getChannel())}}case"matilda/settings/getCore":{let i=za(o);return this.settings=i,this.buildCoreSettings(i,o)}case"matilda/settings/setCoreValue":{let i=n.key;if(typeof i!="string"||!_ze.includes(i))throw ze.invalidParams(void 0,"Unsupported Matilda setting key");let a=za(o),l=i,c=yPt(l,n.value),u=rB(n.scope);return a.setValue(u,i,c),l==="general.outputLanguage"&&typeof c=="string"&&u==="User"&&KW(c),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/setMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw ze.invalidParams(void 0,"MCP server name is required");let a=za(o),l=rB(n.scope),c=l==="Workspace"?"workspace":"user",u=Qz(a,c),A=Zs(u.mcpServers),g=Zs(A[i.trim()]),d={...A,[i.trim()]:{...SPt(g),...BPt(wPt(IPt(n.server),g))}};return a.setValue(l,"mcpServers",d),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/removeMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw ze.invalidParams(void 0,"MCP server name is required");let a=za(o),l=rB(n.scope),c=l==="Workspace"?"workspace":"user",u=Qz(a,c),A={...Zs(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(!Rze(i))throw ze.invalidParams(void 0,"Invalid hook event");let a=za(o),l=rB(n.scope),c=l==="Workspace"?"workspace":"user",u=Qz(a,c),A={...Zs(u.hooks)},g=Array.isArray(A[i])?[...A[i]]:[],d=Yze(n.hook),m=n.index,E=typeof m=="number"&&Number.isInteger(m)&&m>=0&&m<g.length,y=vPt(d,E?Zs(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(!Rze(i))throw ze.invalidParams(void 0,"Invalid hook event");let a=n.index;if(typeof a!="number"||!Number.isInteger(a)||a<0)throw ze.invalidParams(void 0,"Invalid hook index");let l=za(o),c=rB(n.scope),u=c==="Workspace"?"workspace":"user",A=Qz(l,u),g={...Zs(A.hooks)},d=Array.isArray(g[i])?[...g[i]]:[];if(a>=d.length)throw ze.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 ze.invalidParams(void 0,"extensionId is required");if(typeof a!="string"||!a)throw ze.invalidParams(void 0,"settingKey is required");if(typeof l!="string")throw ze.invalidParams(void 0,"value must be a string");let c=za(o),u=new lc({workspaceDir:o,isWorkspaceTrusted:c.isTrusted});await u.refreshCache();let A=u.getLoadedExtensions().find(d=>d.id===i||d.name===i);if(!A)throw ze.invalidParams(void 0,"Extension not found");let g=rB(n.scope)==="Workspace"?"workspace":"user";return await E_(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 ze.invalidParams(void 0,'scope must be "user" or "workspace"');if(a!=="allow"&&a!=="ask"&&a!=="deny")throw ze.invalidParams(void 0,'ruleType must be "allow", "ask", or "deny"');let l=this.loadPermissionSettings(o),c=OOt(n.rules),u=i==="workspace"?"Workspace":"User";return l.setValue(u,`permissions.${a}`,c),this.syncLivePermissionManagers(u,o),this.buildPermissionSettings(l)}default:throw ze.methodNotFound(t)}}async newSessionConfig(t,n,r,o,s,i,a){let l={};for(let d of n){let m=kPt(d);if(m){let B={};for(let{name:b,value:w}of m.env)B[b]=w;l[m.name]=new S_(m.command,m.args,B,t);continue}let E=MPt(d);if(E){let B={};for(let{name:b,value:w}of E.headers)B[b]=w;l[E.name]=new S_(void 0,void 0,void 0,void 0,E.url,void 0,Object.keys(B).length>0?B:void 0);continue}let y=FPt(d);if(y){let B={};for(let{name:b,value:w}of y.headers)B[b]=w;l[y.name]=new S_(void 0,void 0,void 0,void 0,void 0,y.url,Object.keys(B).length>0?B:void 0);continue}}let c=r.merged,u={...this.argv,...s?{resume:o}:{sessionId:o},sandboxSessionId:void 0,continue:!1},A=await Mk(c,u,t,void 0,{userHooks:r.getUserHooks(),projectHooks:r.getProjectHooks()},kk(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.
926
+ ${r}`}var Oze=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function Pze(e){let t;try{t=new URL(e)}catch{throw ze.invalidParams(void 0,"Skill sourceUrl must be a valid URL")}if(t.protocol!=="https:")throw ze.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(!Oze.has(t.hostname))throw ze.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function Uze(e){let t=new URL(e);if(t.protocol!=="https:")throw ze.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 YOt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function JOt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function ete(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 $Ot(e,t){let n=ete(e,t+124,12);return n?Number.parseInt(n,8):0}function VOt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function KOt(e,t){let n=ete(e,t,100),r=ete(e,t+345,155);return r?`${r}/${n}`:n}function XOt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var YN=100*1024*1024,Hze=500*1024*1024,ZOt=16,ePt=2e3,Mz=class extends Error{};async function tPt(e,t,n={}){let r=n.maxCompressedBytes??YN,o=n.maxDecompressedBytes??Hze;if(e.length>r)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await bOt(kze.from([Buffer.from(e)]),TOt(),new Mze({write(A,g,d){if(u+=A.length,u>o){d(new Mz);return}c.push(A),d()}})),s=Buffer.concat(c)}catch(c){throw c instanceof Mz?ze.invalidParams(void 0,"Decompressed skill archive exceeds the maximum allowed size"):ze.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&&!VOt(s,c);){let u=KOt(s,c),A=String.fromCharCode(s[c+156]||0),g=$Ot(s,c),d=c+512,m=d+Math.ceil(g/512)*512;if(A==="0"||A==="\0"){let E=XOt(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 nPt=[".githubusercontent.com",".github.com"];function rPt(e){return Oze.has(e)?!0:nPt.some(t=>e.endsWith(t))}async function ote(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 ze.invalidParams(void 0,"Skill download redirected to an invalid URL")}if(a.protocol!=="https:"||!rPt(a.hostname))throw ze.invalidParams(void 0,"Skill download redirected to a disallowed host");r=a.toString()}throw ze.invalidParams(void 0,"Skill download exceeded the maximum number of redirects")}async function Gze(e,t){let n=e.body;if(!n){let l=new Uint8Array(await e.arrayBuffer());if(l.byteLength>t)throw ze.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(),ze.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 zze(e){let t=await ote(e);if(!t.ok)throw ze.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>YN)throw ze.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return Gze(t,YN)}async function oPt(e){let t=Uze(e),n=t?YOt(t):e,r=await zze(n);return{skillContent:Buffer.from(r).toString("utf8"),files:[{relativePath:"SKILL.md",content:r}]}}async function sPt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,r=await ote(n,{headers:{"User-Agent":"matilda-code"}});if(!r.ok)throw ze.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>YN)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return tPt(await Gze(r,YN),t)}async function iPt(e,t){let n=JOt(t),r=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,o=await ote(r,{headers:{Accept:"application/vnd.github+json","User-Agent":"matilda-code"}});if(!o.ok)throw ze.invalidParams(void 0,`Failed to list GitHub skill files (${o.status})`);let s=await o.json();if(!Array.isArray(s))throw ze.invalidParams(void 0,"GitHub skill URL must point to a directory-backed SKILL.md file");return s}async function jze(e,t,n="",r=0,o={files:0,bytes:0}){if(r>ZOt)throw ze.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await iPt(e,t),i=[];for(let a of s){let l=Zs(a),c=Mp(l.name,"github.name"),u=Mp(l.path,"github.path"),A=Mp(l.type,"github.type"),g=n?no.posix.join(n,c):c;if(A==="dir"){i.push(...await jze(e,u,g,r+1,o));continue}if(A!=="file")continue;if(o.files+=1,o.files>ePt)throw ze.invalidParams(void 0,"Skill directory contains too many files");let d=Mp(l.download_url,"github.download_url");Pze(d);let m=await zze(d);if(o.bytes+=m.length,o.bytes>Hze)throw ze.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:g,content:m})}return i}async function aPt(e,t){let n=await jze(e,t).catch(r=>(Xl.warn("GitHub API directory listing failed, falling back to archive download:",r),null));return n||sPt(e,t)}async function lPt(e){Pze(e);let t=Uze(e);if(!t||no.posix.basename(t.filePath)!=="SKILL.md")return oPt(e);let n=no.posix.dirname(t.filePath),r=await aPt(t,n),o=r.find(s=>s.relativePath==="SKILL.md");if(!o)throw ze.invalidParams(void 0,"GitHub skill directory does not contain SKILL.md");return{skillContent:Buffer.from(o.content).toString("utf8"),files:r}}function cPt(e,t){let n=no.resolve(e),r=no.resolve(e,t);if(r!==n&&!r.startsWith(n+no.sep))throw ze.invalidParams(void 0,`Invalid skill file path: ${t}`);return r}function wze(e,t){let n=no.resolve(e),r=no.resolve(e,t);if(!r.startsWith(n+no.sep))throw ze.invalidParams(void 0,"Invalid skill.slug");return r}function uPt(e,t){if(typeof e.documentationUrl=="string")return e.documentationUrl;if(typeof e.documentationUrl=="function")try{return e.documentationUrl(t)}catch{return}}function dPt(e){return typeof Zs(e).id=="string"}function APt(e,t){if(!t)return;let r=Zs(e.env)[t];return typeof r=="string"&&r.length>0?r:void 0}function fPt(e,t){let r=Zs(e.modelProviders)[t];return Array.isArray(r)?r.filter(dPt):[]}function Wze(e,t){let n=s_(e);return n?fPt(t,e.protocol).filter(n):[]}function qze(e,t,n){let r=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:mi(e),o=typeof n[0]?.envKey=="string"?n[0].envKey:e.envKey;return n0(r)??APt(t,o)}function gPt(e,t){let n=Wze(e,t),r=qze(e,t,n);if(!r&&n.length===0)return;let o=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:mi(e);return{baseUrl:kz(o),...r?{hasApiKey:!0}:{},...n.length>0?{modelIds:n.map(s=>s.id)}:{}}}function pPt(e,t){return qze(e,t,Wze(e,t))}function mPt(e,t){let n=mi(e),r=gPt(e,t);return{id:e.id,label:e.label,description:e.description,protocol:e.protocol,baseUrl:e.baseUrl,defaultModelIds:Dre(e),models:e.models,apiKeyPlaceholder:e.apiKeyPlaceholder,documentationUrl:uPt(e,n),uiGroup:e.uiGroup??"third-party",uiLabels:e.uiLabels,...r?{existingConfig:r}:{}}}function hPt(e,t,n){let r=mi(e),o=oy(t.apiKey,"apiKey")??n;if(!o)throw ze.invalidParams(void 0,"Invalid or missing apiKey");let s=e.validateApiKey?.(o,r);if(s)throw ze.invalidParams(void 0,s);return{baseUrl:r,apiKey:o}}function CPt(e){if(e!==void 0){if(e==="user")return"User";if(e==="workspace")return"Workspace";throw ze.invalidParams(void 0,"Invalid scope for provider connect")}}function EPt(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 Zee(e){let t={};for(let n of _ze){let r=EPt(e,n);r!==void 0&&(t[n]=r)}return t}function yPt(e,t){let n=Nze[e];switch(n.type){case"boolean":if(typeof t!="boolean")throw ze.invalidParams(void 0,`${e} must be a boolean`);return t;case"number":if(typeof t!="number"||!Number.isFinite(t))throw ze.invalidParams(void 0,`${e} must be a number`);if(n.min!==void 0&&t<n.min)throw ze.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 ze.invalidParams(void 0,`${e} must be one of ${r?.join(", ")}`);return t}case"string":{if(t===void 0)return;if(typeof t!="string")throw ze.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 ze.invalidParams(void 0,`${e} has an unsupported setting type`)}}function og(e){if(e!==void 0){if(!Array.isArray(e))throw ze.invalidParams(void 0,"Expected an array of strings");return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean)}}function oB(e){if(e===void 0)return;let t=Zs(e),n={};for(let[r,o]of Object.entries(t))typeof o=="string"&&r.trim()&&(n[r.trim()]=o);return n}function qN(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number.parseInt(String(e),10);if(!Number.isFinite(t)||t<=0)throw ze.invalidParams(void 0,"Expected a positive number");return t}function IPt(e){let t=Zs(e),n=t.transport;if(n!=="stdio"&&n!=="http"&&n!=="sse")throw ze.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=qN(t.timeout);if(i!==void 0&&(r.timeout=i),typeof t.trust=="boolean"&&(r.trust=t.trust),r.includeTools=og(t.includeTools),r.excludeTools=og(t.excludeTools),n==="stdio"){let c=t.command;if(typeof c!="string"||!c.trim())throw ze.invalidParams(void 0,"Stdio MCP servers require a command");return r.command=c.trim(),r.args=og(t.args),r.env=oB(t.env),r}let l=t[n==="http"?"httpUrl":"url"];if(typeof l!="string"||!l.trim())throw ze.invalidParams(void 0,`${n.toUpperCase()} MCP servers require a URL`);return n==="http"?r.httpUrl=l.trim():r.url=l.trim(),r.headers=oB(t.headers),r}var DPt=new Set(["command","args","cwd","env","httpUrl","url","headers","timeout","trust","description","includeTools","excludeTools"]);function SPt(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!DPt.has(t)))}function BPt(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 xPt(e){let t=Zs(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:oB(t.headers),timeout:qN(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:og(t.includeTools),excludeTools:og(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:oB(t.headers),timeout:qN(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:og(t.includeTools),excludeTools:og(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:og(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:oB(t.env),timeout:qN(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:og(t.includeTools),excludeTools:og(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var Fz="__redacted__";function bPt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(r=>[r,Fz]));return{...e,env:t(e.env),headers:t(e.headers)}}function wPt(e,t){let n=(r,o)=>{if(!r)return r;let s=Zs(o),i={};for(let[a,l]of Object.entries(r)){if(l!==Fz){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 Tze(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,Fz]))}function vze(e,t){if(!e)return e;let n=Zs(t),r={};for(let[o,s]of Object.entries(e)){if(s!==Fz){r[o]=s;continue}let i=n[o];typeof i=="string"&&(r[o]=i)}return r}function TPt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:Tze(t.env)}:{},...t.headers?{headers:Tze(t.headers)}:{}}))}}function vPt(e,t){let n=Array.isArray(t.hooks)?t.hooks:[];return{...e,hooks:e.hooks.map((r,o)=>{let s=Zs(n[o]);return{...r,...r.env?{env:vze(r.env,s.env)}:{},...r.headers?{headers:vze(r.headers,s.headers)}:{}}})}}function jN(e,t){let n=Zs(e.mcpServers);return Object.entries(n).map(([r,o])=>{try{let s=xPt(o);return s?{name:r,scope:t,server:bPt(s)}:void 0}catch(s){Xl.warn(`Skipping malformed MCP server config [${t}:${r}]:`,s);return}}).filter(r=>!!r)}function Rze(e){return typeof e=="string"&&Lze.includes(e)}function RPt(e){let t=Zs(e),n=t.type;if(n!=="command"&&n!=="http")throw ze.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 ze.invalidParams(void 0,"Command hooks require a command");r.command=s.trim(),r.env=oB(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 ze.invalidParams(void 0,"HTTP hooks require a URL");r.url=s.trim(),r.headers=oB(t.headers),r.allowedEnvVars=og(t.allowedEnvVars),typeof t.once=="boolean"&&(r.once=t.once)}let o=qN(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 Yze(e){let t=Zs(e),n=t.hooks;if(!Array.isArray(n)||n.length===0)throw ze.invalidParams(void 0,"Hook definition requires at least one hook");let r={hooks:n.map(RPt)};return typeof t.matcher=="string"&&(r.matcher=t.matcher),typeof t.sequential=="boolean"&&(r.sequential=t.sequential),r}function WN(e,t,n){let r=Zs(e.hooks),o=[];for(let s of Lze){let i=r[s];Array.isArray(i)&&i.forEach((a,l)=>{try{o.push({event:s,scope:t,index:l,hook:TPt(Yze(a)),extensionName:n})}catch(c){Xl.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return o}function rB(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw ze.invalidParams(void 0,"scope must be user or workspace")}function Qz(e,t){return e.forScope(rB(t)).settings}async function Qze(e,t){for(let n of dd()){let r=no.join(e,n);try{return await Il.access(r),r}catch{}}return no.join(e,t)}async function QPt(e){let t=dd()[0]??"MATILDA.md",n=await Qze(Ft.getGlobalMatildaDir(),t),r=await Qze(e.cwd,t),o=Lh(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:r,autoMemoryDir:o}}async function Jze(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let r=Mze.toWeb(process.stdout),o=kze.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=z8e(r,o),i,a=new dz(m=>(i=new tte(e,t,n,m),i),s),l=async m=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(E){Xl.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 B of y){let b=B.getConfig?.();b&&E.add(b)}for(let B of E){let b=B.getHookSystem?.();if(!(B.getDisableAllHooks?.()||!b||!B.hasHooksForEvent?.("SessionEnd")))try{await b.fireSessionEndEvent(m)}catch(v){Xl.warn(`SessionEnd hook failed: ${v instanceof Error?v.message:String(v)}`)}}},g=async()=>{if(c)return;c=!0,Xl.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,Rl().catch(E=>{Xl.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 kPt(e){if("command"in e&&"args"in e&&"env"in e)return e}function MPt(e){if("type"in e&&e.type==="sse")return e}function FPt(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 Noe(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)&&Xl.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Xl.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){Xl.debug(`Session ${t} tool registry stop during close failed: ${r instanceof Error?r.message:String(r)}`)}this.mcpPool.releaseSession(t),Lo.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"&&Xl.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return Qk(t.merged,this.argv.channel)}get matildaAccount(){return this.matildaAccountState??=new gz({channel:this.config.getChannel(),connectionSignal:this.connection.signal,install:t=>p5(za(process.cwd()),t)}),this.matildaAccountState}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[nte];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===Tz,this.transcriptUpdatesNegotiated=this.transcriptReadNegotiated&&n.transcriptUpdates===yze,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===jee,this.compactionUpdatesNegotiated=t.clientCapabilities?.session?.compaction!=null,this.signInUrlNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.signInUrl===1;let r=tv(this.config);return{protocolVersion:SZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.22.0"},authMethods:r,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated||this.finalAnswersNegotiated||this.sessionNoticesNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:Tz}:{},...this.transcriptUpdatesNegotiated?{transcriptUpdates:yze}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{},...this.finalAnswersNegotiated?{finalAnswers:1}:{},...this.sessionNoticesNegotiated?{sessionNotices:jee}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0},...tB({channel:this.config.getChannel()})?{auth:{logout:{}}}:{}}}}async authenticate({methodId:t}){if(t===zee&&tB({channel:this.config.getChannel()})){await this.matildaAccount.signIn(this.signInUrlNegotiated?r=>this.connection.extNotification(tze,{...r}):void 0);return}let n=$t.nativeEnum(rA).parse(t);await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}async logout(){if(!tB({channel:this.config.getChannel()}))throw ze.methodNotFound("logout");await this.matildaAccount.signOut()}async newSession({cwd:t,mcpServers:n}){let r=hr(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:Bze(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=FOt(t),a=NOt(i);if(!await new pi(i,a).sessionExists(t.sessionId))throw ze.resourceNotFound(`session:${t.sessionId}`);this.sessions.has(t.sessionId)&&await this.stopSessionAndItsWork(t.sessionId);let c=hr(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:Bze(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 g0(r);o.contextMessage&&(n.pendingWorktreeNotice=o.contextMessage)}catch(r){Xl.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 sv(za(n),n,()=>new pi(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 ze.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 ze.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 ze.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 KB?new ze(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=za(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:vz(t.user.settings)},workspace:{path:t.workspace.path,rules:vz(t.workspace.settings)},merged:vz(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 lc({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await d.refreshCache(),i=d.getLoadedExtensions()}catch(d){Xl.warn("Extension loading failed, continuing without extensions:",d)}let a=await Promise.all(i.map(async d=>{let m=await f0(d.config,d.id,"user"),E=await f0(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(B=>B.name),mcpServers:Object.keys(d.config.mcpServers??{}),settings:y.map(B=>{let b=m[B.envVar],w=E[B.envVar],v=w!==void 0,Q=b!==void 0,O=v?w:b,z=v?"workspace":Q?"user":void 0;return{name:B.name,description:B.description,envVar:B.envVar,sensitive:!!B.sensitive,userValue:B.sensitive?void 0:b,workspaceValue:B.sensitive?void 0:w,effectiveValue:B.sensitive?void 0:O,effectiveScope:z,hasUserValue:Q,hasWorkspaceValue:v}})}})),l=i.filter(d=>d.isActive),c=l.flatMap(d=>jN({mcpServers:d.config.mcpServers??{}},"extension").map(m=>({...m,server:{...m.server,extensionName:d.name}}))),u=l.flatMap(d=>WN({hooks:d.hooks??{}},"extension",d.name)),A=new Map;for(let d of jN(r,"user"))A.set(d.name,d);if(t.isTrusted)for(let d of jN(o,"workspace"))A.set(d.name,d);let g=[...WN(r,"user"),...t.isTrusted?WN(o,"workspace"):[]];return{user:{path:t.user.path,values:Zee(r),mcpServers:jN(r,"user"),hooks:WN(r,"user")},workspace:{path:t.workspace.path,values:Zee(o),mcpServers:jN(o,"workspace"),hooks:WN(o,"workspace")},merged:{values:Zee(s),mcpServers:[...A.values(),...c],hooks:[...g,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){let r=t==="Workspace"?xze(n):void 0,o=new Map;for(let s of this.sessions.values()){let i=s.getConfig(),a=i.storage.getProjectRoot(),l=xze(a);if(r!==void 0&&l!==r)continue;let c=i.getPermissionManager?.();if(c)try{let u=o.get(l);u||(u=vz(za(a).merged),o.set(l,u));let A=i.getPermissionsBeyondSettings?.(),g=LOt(c);for(let d of _Ot){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){Xl.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??Eze(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?ty(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,B=ty(y,d.authType),b=a===d.authType&&i&&(s===y||s===d.id||l===B),w={modelId:B,baseModelId:lze(y),name:d.label,...d.description!==void 0?{description:d.description}:{},contextLimit:d.contextWindowSize??Tj(y),...d.modalities!==void 0?{modalities:d.modalities}:{},...d.baseUrl!==void 0?{baseUrl:kz(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:wz,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...A?{baseUrl:kz(A)}:{},...g?{fastModelId:g}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:wz,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!0,providers:[],errors:[this.errorCell("providers",n)]}}}sessionOrThrow(t){let n=this.sessions.get(t);if(!n)throw ze.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 Vee(n.getConfig());return{v:wz,sessionId:t,availableCommands:r,availableSkills:o??[],...s?{availableSkillDetails:s}:{}}}async installSkillFromUrl(t){let n=this.config.getSkillManager();if(!n)throw ze.invalidParams(void 0,"SkillManager is not available");let r=await lPt(t.sourceUrl),o=no.join(Ft.getGlobalMatildaDir(),"skills"),s=wze(o,t.slug),i=no.join(s,"SKILL.md"),a=n.parseSkillContent(r.skillContent,i,"user");if(a.name!==t.slug)throw ze.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=`${s}.installing-${process.pid}-${Date.now()}`;try{await Il.rm(l,{recursive:!0,force:!0});for(let c of r.files){let u=cPt(l,c.relativePath);await Il.mkdir(no.dirname(u),{recursive:!0}),await Il.writeFile(u,c.content)}await Il.rm(s,{recursive:!0,force:!0}),await Il.rename(l,s)}catch(c){throw await Il.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 ze.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 ze.invalidParams(void 0,`Skill name "${i.name}" does not match requested slug "${t.slug}"`);let a=no.resolve(r),l=no.resolve(o),c=no.resolve(Ft.getGlobalMatildaDir());if(!(l===no.join(a,"SKILL.md"))||a===no.parse(a).root||a===c)throw ze.invalidParams(void 0,`Refusing to delete unexpected skill directory: ${r}`);return await Il.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=wze(no.join(Ft.getGlobalMatildaDir(),"skills"),t),u=no.join(c,"SKILL.md"),A=await Il.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 ze.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`);let l=await Il.readFile(a,"utf8").catch(()=>{throw ze.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`)});return{skillDir:no.dirname(a),skillFile:a,content:l}}async findProjectSkillFileFromCwd(t,n,r){let o=no.resolve(n);for(let s of POt){let i=no.join(o,s,UOt),c=(await r.loadSkillsFromDir(i,"project")).find(A=>A.name===t)?.filePath;if(!c)continue;let u=await Il.readFile(c,"utf8").catch(()=>{throw ze.invalidParams(void 0,`Project skill not found: ${t}`)});return{skillDir:no.dirname(c),skillFile:c,content:u}}}async setGlobalSkillEnabled(t,n){let r=this.config.getSkillManager();if(!r)throw ze.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 ze.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=qOt(s,t.enabled);if(r.parseSkillContent(l,o,i),no.basename(o)!=="SKILL.md")throw ze.invalidParams(void 0,`Refusing to write to unexpected skill file: ${o}`);return await Il.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=Mp(n.description,"description");if(i.length>Gk)throw ze.invalidParams(void 0,"Bug description is too long");return{...await lb({description:i,envSummary:`${process.platform}/${process.arch}`})}}case oze:{let{sessionId:i,modelId:a}=n;if(typeof i!="string"||typeof a!="string")throw ze.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 ze.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new ze(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i);if(!a)throw ze.resourceNotFound(`session:${i}`);return a.attachClient(),{}}case"matilda/session/readState":{if(!this.sessionStateNegotiated)throw ze.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");if(this.sessionRestoreCompletions.has(i))throw new ze(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let a=this.sessions.get(i)?.getSessionState();if(!a)throw ze.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 ze.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(za(o));return{providers:IR.map(a=>mPt(a,i))}}case"matilda/providers/connect":{let i=Mp(n.providerId,"providerId"),a=Bre(i);if(!a)throw ze.invalidParams(void 0,`Unknown provider: ${i}`);let l=za(o),c=hPt(a,n,pPt(a,l.merged)),u=CPt(n.scope),A=oA(a,c);return await jh(A,{settings:BC(l,u),reloadModelProviders:g=>{let d=Qk({...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(GOt(n));case"matilda/skills/delete":return this.deleteGlobalSkill(zOt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(jOt(n),r);case"matilda/settings/getMemory":{let i=za(o);return this.settings=i,{settings:bze(this.effectiveSettings(i).memory)}}case"matilda/settings/setMemory":{let i=Zs(n.updates),a=za(o);for(let l of HOt)if(i[l]!==void 0){if(typeof i[l]!="boolean")throw ze.invalidParams(void 0,`Invalid memory setting '${l}': expected boolean`);a.setValue("User",`memory.${l}`,i[l])}return this.settings=a,{settings:bze(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 QPt({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 ze.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");return{memories:(a==="user"?await poe():await goe(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 ze.invalidParams(void 0,"Invalid memory scope: expected 'user' or 'project'");let l=n.relativePath;if(typeof l!="string"||l.length===0)throw ze.invalidParams(void 0,"Invalid or missing relativePath");return await Uoe({scope:a,projectRoot:i,relativePath:l}),{deleted:!0}}case Kee.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case Kee.sessionSupportedCommands:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ze.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionSupportedCommandsStatus(i)}case Xee.sessionClose:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw ze.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 ze.invalidParams(void 0,"Invalid or missing sessionId");return await this.closeSessionAndItsWork(i),{success:await sv(za(o),o,async()=>new pi(o).removeSession(i))}}case Xee.sessionRename:{let i=n.sessionId,a=n.title;if(!i||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");if(typeof a!="string")throw ze.invalidParams(void 0,"Invalid or missing title");if(a.length>yR)throw ze.invalidParams(void 0,`Title too long (max ${yR} 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 sv(za(o),o,async()=>new pi(o).renameSession(i,a,l))}}case"rewindSession":{let i=n.sessionId;if(!i||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i);if(!a)throw ze.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 ze(-32602,"Invalid promptId format",{errorKind:"invalid_rewind_target"});let y=c.slice(E.length);if(!/^\d+$/.test(y))throw new ze(-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 ze(-32602,"Snapshot not found for the given promptId",{errorKind:"invalid_rewind_target"});l=w}if(!Number.isInteger(l)||l<0)throw ze.invalidParams(void 0,"Invalid or missing targetTurnIndex");let u=a.captureHistorySnapshot(),A;try{A=await a.rewindToTurn(l)}catch(E){if(E instanceof ze){let y=E.message;if(y.includes("Cannot rewind while a prompt is running"))throw new ze(E.code,y,{errorKind:"session_busy"});if(y.includes("compressed or does not exist"))throw new ze(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 B=y instanceof Error?y.message:String(y);Xl.error(`[ACP] File-history rewind failed for session=${i} promptId=${c}: ${B}`),d=[`file-history-rewind: ${B}`]}}return{success:!0,historyBeforeRewind:u,...A,filesChanged:g,filesFailed:d}}case"matilda/session/readTranscript":{if(!this.transcriptReadNegotiated)throw ze.methodNotFound(t);let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw ze.invalidParams(void 0,"Invalid or missing sessionId");let a=Fze.optional().safeParse(n.cursor);if(!a.success)throw ze.invalidParams(void 0,"Invalid transcript cursor");if(this.sessionRestoreCompletions.has(i))throw new ze(-32e3,"Session restore is in progress",{errorKind:"session_busy"});let l=this.sessions.get(i);if(!l)throw ze.resourceNotFound(`session:${i}`);let c=await l.readTranscript(a.data);if(this.sessions.get(i)!==l||this.sessionRestoreCompletions.has(i))throw new ze(-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:Tz,sessionId:i,...c,runtime:A};if(!this.transcriptUpdatesNegotiated)throw ze.invalidParams(void 0,"Transcript updates were not negotiated");let g=c.mode==="delta"?kOt(n.projection,a.data):void 0,d=c.mode==="snapshot"||g&&!MOt(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=[],B=pi.reconstructHistory(d.records),b=await new nB({sessionId:i,config:this.config,sendUpdate:async w=>{y.push(w)},cumulativeUsage:E},!0,l.getActiveTaskStartUuid(),this.finalAnswersNegotiated,this.compactionUpdatesNegotiated).replay(B,m?{continuation:m.continuation,partial:!0,messageIdOf:w=>l.committedMessageIdOf(w)??w}:{});return{version:Tz,sessionId:i,mode:m?"delta":"snapshot",cursor:d.cursor,updates:Sze(y),transcriptRecords:Dze(B),...d.cursor?{projection:Ize({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 ze.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i)?.getActiveTaskStartUuid(),l=await sv(za(o),o,async()=>new pi(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 nB(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),Xl.warn("[loadUpdates] History replay failed for session %s (partial updates: %d):",i,c.length,y)}let d=l.transcriptCursor,m=rre(l.conversation.messages),E=m.kind==="v2"?hz(m.payload.snapshot):null;return{updates:Sze(c),transcriptRecords:Dze(l.conversation.messages),...E?{goal:E}:{},...this.transcriptUpdatesNegotiated&&d&&g?{transcript:d,projection:Ize({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=$t.object({sessionId:$t.string().regex(s),messages:$t.array($t.object({id:$t.string().uuid(),role:$t.enum(["user","assistant"]),content:$t.string(),timestamp:$t.number().finite().min(0).max(864e13)}))}).safeParse(n);if(!i.success)throw ze.invalidParams(void 0,"Invalid imported history");let a=this.sessions.get(i.data.sessionId);if(!a)throw ze.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 ze.invalidParams(void 0,"Invalid or missing sessionId");if(!Array.isArray(a))throw ze.invalidParams(void 0,"Invalid or missing history");let l=this.sessions.get(i);if(!l)throw ze.invalidParams(void 0,`Session not found for id: ${i}`);return l.restoreHistory(a),{success:!0}}case nze: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?kz(c.baseUrl):null,apiKeyEnvKey:c?.apiKeyEnvKey??null,account:rze(c?.baseUrl,l.getChannel())}}case"matilda/settings/getCore":{let i=za(o);return this.settings=i,this.buildCoreSettings(i,o)}case"matilda/settings/setCoreValue":{let i=n.key;if(typeof i!="string"||!_ze.includes(i))throw ze.invalidParams(void 0,"Unsupported Matilda setting key");let a=za(o),l=i,c=yPt(l,n.value),u=rB(n.scope);return a.setValue(u,i,c),l==="general.outputLanguage"&&typeof c=="string"&&u==="User"&&KW(c),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/setMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw ze.invalidParams(void 0,"MCP server name is required");let a=za(o),l=rB(n.scope),c=l==="Workspace"?"workspace":"user",u=Qz(a,c),A=Zs(u.mcpServers),g=Zs(A[i.trim()]),d={...A,[i.trim()]:{...SPt(g),...BPt(wPt(IPt(n.server),g))}};return a.setValue(l,"mcpServers",d),this.settings=a,this.buildCoreSettings(a,o)}case"matilda/settings/removeMcpServer":{let i=n.name;if(typeof i!="string"||!i.trim())throw ze.invalidParams(void 0,"MCP server name is required");let a=za(o),l=rB(n.scope),c=l==="Workspace"?"workspace":"user",u=Qz(a,c),A={...Zs(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(!Rze(i))throw ze.invalidParams(void 0,"Invalid hook event");let a=za(o),l=rB(n.scope),c=l==="Workspace"?"workspace":"user",u=Qz(a,c),A={...Zs(u.hooks)},g=Array.isArray(A[i])?[...A[i]]:[],d=Yze(n.hook),m=n.index,E=typeof m=="number"&&Number.isInteger(m)&&m>=0&&m<g.length,y=vPt(d,E?Zs(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(!Rze(i))throw ze.invalidParams(void 0,"Invalid hook event");let a=n.index;if(typeof a!="number"||!Number.isInteger(a)||a<0)throw ze.invalidParams(void 0,"Invalid hook index");let l=za(o),c=rB(n.scope),u=c==="Workspace"?"workspace":"user",A=Qz(l,u),g={...Zs(A.hooks)},d=Array.isArray(g[i])?[...g[i]]:[];if(a>=d.length)throw ze.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 ze.invalidParams(void 0,"extensionId is required");if(typeof a!="string"||!a)throw ze.invalidParams(void 0,"settingKey is required");if(typeof l!="string")throw ze.invalidParams(void 0,"value must be a string");let c=za(o),u=new lc({workspaceDir:o,isWorkspaceTrusted:c.isTrusted});await u.refreshCache();let A=u.getLoadedExtensions().find(d=>d.id===i||d.name===i);if(!A)throw ze.invalidParams(void 0,"Extension not found");let g=rB(n.scope)==="Workspace"?"workspace":"user";return await E_(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 ze.invalidParams(void 0,'scope must be "user" or "workspace"');if(a!=="allow"&&a!=="ask"&&a!=="deny")throw ze.invalidParams(void 0,'ruleType must be "allow", "ask", or "deny"');let l=this.loadPermissionSettings(o),c=OOt(n.rules),u=i==="workspace"?"Workspace":"User";return l.setValue(u,`permissions.${a}`,c),this.syncLivePermissionManagers(u,o),this.buildPermissionSettings(l)}default:throw ze.methodNotFound(t)}}async newSessionConfig(t,n,r,o,s,i,a){let l={};for(let d of n){let m=kPt(d);if(m){let B={};for(let{name:b,value:w}of m.env)B[b]=w;l[m.name]=new S_(m.command,m.args,B,t);continue}let E=MPt(d);if(E){let B={};for(let{name:b,value:w}of E.headers)B[b]=w;l[E.name]=new S_(void 0,void 0,void 0,void 0,E.url,void 0,Object.keys(B).length>0?B:void 0);continue}let y=FPt(d);if(y){let B={};for(let{name:b,value:w}of y.headers)B[b]=w;l[y.name]=new S_(void 0,void 0,void 0,void 0,void 0,y.url,Object.keys(B).length>0?B:void 0);continue}}let c=r.merged,u={...this.argv,...s?{resume:o}:{sessionId:o},sandboxSessionId:void 0,continue:!1},A=await Mk(c,u,t,void 0,{userHooks:r.getUserHooks(),projectHooks:r.getProjectHooks()},kk(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.
927
927
  `),A}async ensureAuthenticated(t){let n=t.getModelsConfig().getCurrentAuthType();if(!n)throw ze.authRequired({authMethods:tv(t)},"Use Matilda CLI to authenticate first.");try{await t.refreshAuth(n)}catch(r){throw Xl.error(`Authentication failed: ${r}`),ze.authRequired({authMethods:tv(t)},"Authentication failed: "+r.message)}}setupFileSystem(t){if(!this.clientCapabilities?.fs)return;let n=new pz(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 bz(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?ty(s.id,s.authType):this.formatCurrentModelId(n,r),a=o.map(l=>{let c=l.isRuntimeModel&&l.runtimeSnapshotId?l.runtimeSnapshotId:l.id;return{modelId:ty(c,l.authType),name:l.label,description:l.description??null,_meta:{contextLimit:l.contextWindowSize??Tj(l.id)}}});return{currentModelId:i,availableModels:a}}buildModesData(t){let n=t.getApprovalMode(),r=cc.map(o=>({id:o,name:xR[o].name,description:xR[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?ty(i.id,i.authType):this.formatCurrentModelId(o,s),l=cc.map(g=>({value:g,name:xR[g].name,description:xR[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:ty(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?ty(t,n):t)}};var jd=M(ie(),1);var sy=Ke("STARTUP");function ste(){delete process.env[nx],delete process.env[rx]}function PPt(e){let t="ipv4first";return e===void 0?t:e==="ipv4first"||e==="verbatim"?e:(st(`Invalid value for dnsResolutionOrder in settings: "${e}". Using default "${t}".`),t)}function UPt(e){let t=_Pt.totalmem()/1048576,n=OPt.getHeapStatistics(),r=Math.floor(n.heap_size_limit/1024/1024),o=Math.floor(t*.5);return e&&st(`Current heap size ${r.toFixed(2)} MB`),process.env.MATILDA_CODE_NO_RELAUNCH?[]:o>r?(e&&st(`Need to relaunch with more memory: ${o.toFixed(2)} MB`),[`--max-old-space-size=${o}`]):[]}function HPt(){let e=!1;process.on("unhandledRejection",(t,n)=>{let r=`=========================================
928
928
  This is an unexpected error. Please file a bug report using the /bug tool.
929
929
  CRITICAL: Unhandled Promise Rejection!
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maincode-ai/matilda-code",
3
- "version": "0.22.0-nightly.20261101.b0ad315a4",
3
+ "version": "0.22.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.22.0-nightly.20261101.b0ad315a4"
29
+ "sandboxImageUri": "ghcr.io/maincode/matilda-code:0.22.0"
30
30
  },
31
31
  "dependencies": {},
32
32
  "optionalDependencies": {