@maincode-ai/matilda-code 0.22.1-nightly.20261104.f4c27782c → 0.22.1-preview.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/cli.js +4 -4
  2. package/package.json +2 -2
package/cli.js CHANGED
@@ -279,7 +279,7 @@ ${m.join(`
279
279
  `,t-1);return{line:n===-1?0:e.slice(0,n+1).match(/\n/g).length,column:t-n-1}}function H9(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=GKe(e,t);return n?{line:r.line+1,column:r.column+1}:r}var zKe=e=>`\\u{${e.codePointAt(0).toString(16)}}`,G9=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??=`${WKe(this.#t.message)}${this.#e===""?" while parsing empty string":""}`;let{codeFrame:t}=this;return`${this.#n}${this.fileName?` in ${this.fileName}`:""}${t?`
280
280
 
281
281
  ${t}
282
- `:""}`}set message(t){this.#n=t}#a(t){if(!this.#t)return;let n=this.#e,r=jKe(n,this.#t.message);if(r)return(0,Qge.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}},jKe=(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)}:H9(e,Number(r),{oneBased:!0})},WKe=e=>e.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,n,r)=>`"${r}"(${zKe(r)})`);function z9(e,t,n){typeof t=="string"&&(n=t,t=void 0);try{return JSON.parse(e,t)}catch(r){throw new G9({jsonParseError:r,fileName:n,input:e})}}var Hpe=M(Ppe(),1);h();import{fileURLToPath as pZe}from"node:url";function Upe(e){return e instanceof URL?pZe(e):e}var CZe=e=>hZe.resolve(Upe(e)??".","package.json"),EZe=(e,t)=>{let n=typeof e=="string"?z9(e):e;return t&&(0,Hpe.default)(n),n};async function Gpe({cwd:e,normalize:t=!0}={}){let n=await mZe.readFile(CZe(e),"utf8");return EZe(n,t)}async function zpe(e){let t=await ige("package.json",e);if(t)return{packageJson:await Gpe({...e,cwd:yZe.dirname(t)}),path:t}}import{fileURLToPath as IZe}from"node:url";import DZe from"node:path";var SZe=IZe(import.meta.url),BZe=DZe.dirname(SZe),aO;async function yx(){if(aO)return aO;let e=await zpe({cwd:BZe});if(e)return aO=e.packageJson,aO}async function Pg(){let e=await yx();return"0.22.1-nightly.20261104.f4c27782c"}h();var $Q=M(Kpe(),1);import*as Xpe from"node:os";var Zpe=["docker","podman","sandbox-exec"];function MZe(e){return Zpe.includes(e)}function FZe(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(!MZe(e))throw new ya(`Invalid sandbox command '${e}'. Must be one of ${Zpe.join(", ")}`);if($Q.default.sync(e))return e;throw new ya(`Missing sandbox command '${e}' (from MATILDA_SANDBOX)`)}if(Xpe.platform()==="darwin"&&$Q.default.sync("sandbox-exec"))return"sandbox-exec";if($Q.default.sync("docker")&&e===!0)return"docker";if($Q.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 cO(e,t){let n=t.sandbox??e.tools?.sandbox,r=FZe(n),o=await yx(),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 NZe}from"node:events";var ol=new NZe;h();h();async function _Ze(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",U={},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":U={url:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"http":U={httpUrl:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"stdio":default:U={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||{},O=!!N[e];O&&St(`MCP server "${e}" is already configured within ${o} settings.`),N[e]=U,w.setValue(Q,"mcpServers",N),O?St(`MCP server "${e}" updated in ${o} settings.`):St(`MCP server "${e}" added to ${o} settings. (${s})`)}var eme={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 _Ze(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 LZe(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 Xy().deleteCredentials(e)}catch{}St(`Server "${e}" removed from ${n} settings.`)}var tme={command:"remove <name>",describe:"Remove a server",builder:e=>e.usage("Usage: matilda mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),handler:async e=>{await LZe(e.name,{scope:e.scope})}};h();h();h();var ome=M(xI(),1);import*as nme from"node:fs";import*as rme from"node:path";var OZe=".mcp.json",PZe={servers:{},path:void 0,errors:[]};function sme(e){let t=rme.join(e,OZe),n;try{n=nme.readFileSync(t,"utf-8")}catch{return PZe}let r;try{r=JSON.parse((0,ome.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 BC(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=sme(t);for(let i of s.errors)st(`Warning: ${i}`);return{...r,...s.servers,...o,...n??{}}}h();import*as KI from"node:fs";import*as Dx from"node:path";var ame=M(xI(),1);var UZe="mcpApprovals.json";function HZe(){return process.env.MATILDA_CODE_MCP_APPROVALS_PATH?process.env.MATILDA_CODE_MCP_APPROVALS_PATH:Dx.join(Ft.getGlobalMatildaDir(),UZe)}function ime(e){return Dx.resolve(e)}var g5=class{constructor(t,n){this.file=t;this.errors=n}getState(t,n,r){let o=this.file.config[ime(t)]?.[n];return!o||o.hash!==Jj(r)?"pending":o.status}async setState(t,n,r,o){let s=ime(t),i=this.file.config[s],a=i&&typeof i=="object"&&!Array.isArray(i)?i:Object.create(null);Object.defineProperty(a,n,{value:{hash:Jj(r),status:o},enumerable:!0,configurable:!0,writable:!0}),this.file.config[s]=a,await GZe(this.file)}},uO;function xC(){if(uO)return uO;let e=[],t={},n=HZe();try{if(KI.existsSync(n)){let r=KI.readFileSync(n,"utf-8"),o=JSON.parse((0,ame.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})}uO=new g5({path:n,config:t},e);for(let r of e)st(`Warning: MCP approvals file error: ${r.message}`);return uO}function dO(e,t){let n=xC(),r=[];for(let[o,s]of Object.entries(e))$h(s.scope)&&n.getState(t,o,s)!=="approved"&&r.push(o);return r}async function GZe(e){try{let t=Dx.dirname(e.path);KI.existsSync(t)||KI.mkdirSync(t,{recursive:!0}),await Xte(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();uoe();import{stripVTControlCharacters as WZe}from"node:util";h();var ume=M(cme(),1),zZe=new Intl.Segmenter,jZe=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 zZe.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)&&!jZe.test(i)){if((0,ume.default)().test(i)){o+=2;continue}o+=cc(a,s)}}return o}var h5=e=>{if(!e)return 0;let t=e.split(`
282
+ `:""}`}set message(t){this.#n=t}#a(t){if(!this.#t)return;let n=this.#e,r=jKe(n,this.#t.message);if(r)return(0,Qge.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}},jKe=(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)}:H9(e,Number(r),{oneBased:!0})},WKe=e=>e.replace(/(?<=^Unexpected token )(?<quote>')?(.)\k<quote>/,(t,n,r)=>`"${r}"(${zKe(r)})`);function z9(e,t,n){typeof t=="string"&&(n=t,t=void 0);try{return JSON.parse(e,t)}catch(r){throw new G9({jsonParseError:r,fileName:n,input:e})}}var Hpe=M(Ppe(),1);h();import{fileURLToPath as pZe}from"node:url";function Upe(e){return e instanceof URL?pZe(e):e}var CZe=e=>hZe.resolve(Upe(e)??".","package.json"),EZe=(e,t)=>{let n=typeof e=="string"?z9(e):e;return t&&(0,Hpe.default)(n),n};async function Gpe({cwd:e,normalize:t=!0}={}){let n=await mZe.readFile(CZe(e),"utf8");return EZe(n,t)}async function zpe(e){let t=await ige("package.json",e);if(t)return{packageJson:await Gpe({...e,cwd:yZe.dirname(t)}),path:t}}import{fileURLToPath as IZe}from"node:url";import DZe from"node:path";var SZe=IZe(import.meta.url),BZe=DZe.dirname(SZe),aO;async function yx(){if(aO)return aO;let e=await zpe({cwd:BZe});if(e)return aO=e.packageJson,aO}async function Pg(){let e=await yx();return"0.22.1-preview.0"}h();var $Q=M(Kpe(),1);import*as Xpe from"node:os";var Zpe=["docker","podman","sandbox-exec"];function MZe(e){return Zpe.includes(e)}function FZe(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(!MZe(e))throw new ya(`Invalid sandbox command '${e}'. Must be one of ${Zpe.join(", ")}`);if($Q.default.sync(e))return e;throw new ya(`Missing sandbox command '${e}' (from MATILDA_SANDBOX)`)}if(Xpe.platform()==="darwin"&&$Q.default.sync("sandbox-exec"))return"sandbox-exec";if($Q.default.sync("docker")&&e===!0)return"docker";if($Q.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 cO(e,t){let n=t.sandbox??e.tools?.sandbox,r=FZe(n),o=await yx(),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 NZe}from"node:events";var ol=new NZe;h();h();async function _Ze(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",U={},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":U={url:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"http":U={httpUrl:t,headers:P,timeout:l,trust:c,description:u,includeTools:A,excludeTools:g,oauth:j};break;case"stdio":default:U={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||{},O=!!N[e];O&&St(`MCP server "${e}" is already configured within ${o} settings.`),N[e]=U,w.setValue(Q,"mcpServers",N),O?St(`MCP server "${e}" updated in ${o} settings.`):St(`MCP server "${e}" added to ${o} settings. (${s})`)}var eme={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 _Ze(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 LZe(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 Xy().deleteCredentials(e)}catch{}St(`Server "${e}" removed from ${n} settings.`)}var tme={command:"remove <name>",describe:"Remove a server",builder:e=>e.usage("Usage: matilda mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:!0}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),handler:async e=>{await LZe(e.name,{scope:e.scope})}};h();h();h();var ome=M(xI(),1);import*as nme from"node:fs";import*as rme from"node:path";var OZe=".mcp.json",PZe={servers:{},path:void 0,errors:[]};function sme(e){let t=rme.join(e,OZe),n;try{n=nme.readFileSync(t,"utf-8")}catch{return PZe}let r;try{r=JSON.parse((0,ome.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 BC(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=sme(t);for(let i of s.errors)st(`Warning: ${i}`);return{...r,...s.servers,...o,...n??{}}}h();import*as KI from"node:fs";import*as Dx from"node:path";var ame=M(xI(),1);var UZe="mcpApprovals.json";function HZe(){return process.env.MATILDA_CODE_MCP_APPROVALS_PATH?process.env.MATILDA_CODE_MCP_APPROVALS_PATH:Dx.join(Ft.getGlobalMatildaDir(),UZe)}function ime(e){return Dx.resolve(e)}var g5=class{constructor(t,n){this.file=t;this.errors=n}getState(t,n,r){let o=this.file.config[ime(t)]?.[n];return!o||o.hash!==Jj(r)?"pending":o.status}async setState(t,n,r,o){let s=ime(t),i=this.file.config[s],a=i&&typeof i=="object"&&!Array.isArray(i)?i:Object.create(null);Object.defineProperty(a,n,{value:{hash:Jj(r),status:o},enumerable:!0,configurable:!0,writable:!0}),this.file.config[s]=a,await GZe(this.file)}},uO;function xC(){if(uO)return uO;let e=[],t={},n=HZe();try{if(KI.existsSync(n)){let r=KI.readFileSync(n,"utf-8"),o=JSON.parse((0,ame.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})}uO=new g5({path:n,config:t},e);for(let r of e)st(`Warning: MCP approvals file error: ${r.message}`);return uO}function dO(e,t){let n=xC(),r=[];for(let[o,s]of Object.entries(e))$h(s.scope)&&n.getState(t,o,s)!=="approved"&&r.push(o);return r}async function GZe(e){try{let t=Dx.dirname(e.path);KI.existsSync(t)||KI.mkdirSync(t,{recursive:!0}),await Xte(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();uoe();import{stripVTControlCharacters as WZe}from"node:util";h();var ume=M(cme(),1),zZe=new Intl.Segmenter,jZe=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 zZe.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)&&!jZe.test(i)){if((0,ume.default)().test(i)){o+=2;continue}o+=cc(a,s)}}return o}var h5=e=>{if(!e)return 0;let t=e.split(`
283
283
  `);return Math.max(...t.map(n=>ta(n)))},dme=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=dme.get(e);if(r)return r}let n=Array.from(e);return e.length<=Ame&&dme.set(e,n),n}function Rt(e){return co(e).length}function dn(e,t,n){return co(e).slice(t,n).join("")}function Am(e){let t=Po(e),n=WZe(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 p5=new Map,ta=e=>{if(/^[\x20-\x7E]*$/.test(e))return e.length;if(p5.has(e))return p5.get(e);let t=In(e);return p5.set(e,t),t};var m5=coe();function ds(e){if(typeof e=="string")return e.search(m5)===-1?e:(m5.lastIndex=0,e.replace(m5,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 qZe=[{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 fme(e,t=200){let n=e;for(let{pattern:r,replacement:o}of qZe)n=n.replace(r,o);return n.length>t?t<=3?n.slice(0,t):n.slice(0,t-3)+"...":n}var YZe=/[\x00-\x1f\x7f-\x9f]/g;function gme(e){switch(e){case"\b":return"\\b";case" ":return"\\t";case`
284
284
  `:return"\\n";case"\f":return"\\f";case"\r":return"\\r";default:return`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`}}function Sx(e){return ds(e).replace(YZe,gme)}var JZe=/[\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(JZe,pme)}var $Ze=/[\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($Ze,t=>t.length>2?t:pme(t))}function pme(e){let t=e.codePointAt(0);return t>65535?`\\u{${t.toString(16)}}`:gme(e)}h();var mme=["user","project","workspace","system","extension"];var VZe=10;function KZe(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 hme(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 mme){let o=t.get(r);o&&o.length>0&&n.push({source:r,displayName:KZe(r),servers:o})}return n}function fO(e){switch(e){case"connected":return"green";case"connecting":return"yellow";case"disconnected":return"red";default:return"gray"}}function gO(e){switch(e){case"connected":return"\u2713";case"connecting":return"\u2026";case"disconnected":return"\u2717";default:return"?"}}function Cme(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 pO(e){return e?e.split(/\r?\n/).map(t=>Am(t.slice(t.lastIndexOf("\r")+1)).replace(/\t/g," ").trimEnd()).filter(t=>t.trim()!=="").slice(-VZe):[]}function Eme(e,t){return!!e&&!!t}function yme(e,t){let n=[];return e||n.push(C("missing name")),t||n.push(C("missing description")),n}var XZe="\x1B[32m",Ime="\x1B[33m",ZZe="\x1B[31m",mO="\x1B[0m";async function eet(){let e=hr(),t=new ic({isWorkspaceTrusted:!!js(e.merged),telemetrySettings:e.merged.telemetry});await t.refreshCache();let n=t.getLoadedExtensions(),r=BC(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 tet(e,t){let n=new xne({name:"mcp-test-client",version:"0.0.1"}),r;try{r=await Fne(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 net(e,t){return await tet(e,t)}async function ret(){let e=await eet(),t=Object.keys(e);if(t.length===0){St("No MCP servers configured.");return}St(`Configured MCP servers:
285
285
  `);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)`),$h(s.scope)){r??=xC();let u=r.getState(n,o,s);if(u!=="approved"){St(`${Ime}\u25CF${mO} ${i} - ${u==="rejected"?"Rejected":"Pending approval"}`);continue}}let a=await net(o,s),l="",c="";switch(a){case"connected":l=XZe+"\u2713"+mO,c="Connected";break;case"connecting":l=Ime+"\u2026"+mO,c="Connecting";break;case"disconnected":default:l=ZZe+"\u2717"+mO,c="Disconnected";break}if(St(`${l} ${i} - ${c}`),a==="disconnected"){let u=pO(Y1(o));if(u.length>0){St(" Last stderr output:");for(let A of u)St(` ${A}`)}}}}var Dme={command:"list",describe:"List all configured MCP servers",handler:async()=>{await ret()}};h();async function C5(e){let t=hr(),n=e??new ic({isWorkspaceTrusted:!!js(t.merged),telemetrySettings:t.merged.telemetry});e||await n.refreshCache();let r=n.getLoadedExtensions(),o=BC(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 Bme(){let e=hr(),t=process.cwd(),n=new I_(t),r=await C5(),o=new v_({sessionId:"mcp-reconnect",targetDir:t,cwd:t,debugMode:!1,mcpServers:r,pendingMcpServers:dO(r,t),fileDiscoveryService:n,mcpServerCommand:e.merged.mcp?.serverCommand});return await o.initialize(),o}function Sme(e,t=1){let n=new Error(e);return n.exitCode=t,n}async function oet(e){if(!(await C5())[e])throw Sme(`Error: Server "${e}" not found in configuration.`);St(`Reconnecting to server "${e}"...`);try{let n=await Bme();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 Sme(`Failed to reconnect to server "${e}": ${r}`)}}async function set(){let e=hr(),t=new ic({isWorkspaceTrusted:!!js(e.merged),telemetrySettings:e.merged.telemetry});await t.refreshCache();let n=await C5(t),r=Object.keys(n);if(r.length===0){St("No MCP servers configured.");return}St(`Reconnecting to all MCP servers...
@@ -401,7 +401,7 @@ You can update manually with:
401
401
  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:rne,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:Wne,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&&!gD(i.sessionId))return`Invalid --session-id: "${i.sessionId}". Must be a valid UUID (e.g., "123e4567-e89b-12d3-a456-426614174000").`;if(i.sandboxSessionId&&!gD(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(vme).command(tge).command(Gme).command(zme).command(ADe).command(nge).command(lhe).command(ghe).command(uhe);t.version(await Pg()).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"||n._[0]==="account")&&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 xDe(e,t=[],n,r=[],o,s="tree",i=[],a={}){let l=Dd.realpathSync(Kx.resolve(e)),c=Dd.realpathSync(Kx.resolve(lat()));return b_(l===c?"":e,t,n,r,o,s,i,a)}function fat(e,t){if(e.maxWallTime!==void 0&&e.maxWallTime!==null)try{return gDe(String(e.maxWallTime))}catch(r){throw new Error(`--max-wall-time: ${r.message}`)}let n=t.model?.maxWallTimeSeconds;if(typeof n=="number")try{return pDe(n)}catch(r){throw new Error(`settings.json: ${r.message}`)}return-1}function gat(e,t){if(e.maxToolCalls!==void 0&&e.maxToolCalls!==null)try{return Xq(e.maxToolCalls)}catch(r){throw new Error(`--max-tool-calls: ${r.message}`)}let n=t.model?.maxToolCalls;if(typeof n=="number")try{return Xq(n)}catch(r){throw new Error(`settings.json: ${r.message}`)}return-1}function IDe(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 Zq(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 pat(e){return typeof e!="object"||e===null||Array.isArray(e)?!1:Object.values(e).every(t=>typeof t=="object"&&t!==null)}function mat(e){if(!e)return null;try{let t;if(Dd.existsSync(e)){NC.debug(`Reading MCP config from file: ${e}`);let r=Dd.readFileSync(e,"utf-8");t=JSON.parse((0,DDe.default)(r))}else NC.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,!pat(n))throw new Error("Invalid MCP server configuration format. Expected an object with server names as keys.");return NC.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 vi(`Invalid MCP configuration provided via --mcp-config: ${n}`)}}function Mk(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 hat(e){let t=0,n=0,r=o=>{try{return Dd.statSync(o).mtimeMs}catch{return 0}};return()=>{let o=MQ(),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 Fk(e,t,n=process.cwd(),r,o,s,i,a,l){e=kk(e,t.channel);let c=Zq(t),u=iI(t.bare),A=t.channel==="desktop"&&!!process.env.MATILDA_TEMPORARY_SESSION;jne(),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?Bj(e.context.fileName):Bj(dd());let E=new Ft(n),y=Kx.join(E.getMatildaDir(),"output-language.md"),B=Kx.join(Ft.getGlobalMatildaDir(),"output-language.md"),b;u||(Dd.existsSync(y)?b=y:Dd.existsSync(B)&&(b=B));let w=new I_(n),v=KW(t.channel),Q=(v??(u?[]:e.context?.includeDirectories??[])).map(q2).concat(v?[]:(t.includeDirectories||[]).map(q2)),U=!u&&t.experimentalLsp===!0,z,q=t.promptInteractive||t.prompt||"",j=yDe(t.outputFormat),P=yDe(e.output?.format),L=j??P??"text",N=L==="stream-json"?P&&P!=="stream-json"?P:"text":L,O=!!t.includePartialMessages,_;t.approvalMode?_=CDe(t.approvalMode):t.bogan?_="bogan":!u&&e.tools?.approvalMode?_=CDe(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 Hne({argv:t,env:process.env,settings:e.telemetry})}catch(ue){throw ue instanceof vi?new vi(`Invalid telemetry configuration: ${ue.message}.`):ue}let Y=!!t.query,k=!!t.prompt,G;t.promptInteractive?G=!0:(L==="stream-json"||L==="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 $=rge(e.tools?.disabled),K=ue=>se.some(Be=>Rj(ue,[Be],[]))?!0:V.length>0?Rj(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)||gx(),Qe=px({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 cO(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=hDe();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=hDe());let he=e.modelProviders,De=mat(t.mcpConfig),Ae=i||De?{...i,...De??{}}:void 0,me=u?{}:BC(e.mcpServers,n,Ae),Te=u?void 0:dO(me,n),Ve={organizationId:t.organizationId,codeCreditLimitMinor:t.codeCreditLimitMinor,sessionId:pe,sessionData:Ie,sessionStorageDir:a,sessionRuntimeBaseDir:l,embeddingModel:Yne,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:hat(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:fat(t,e),maxToolCalls:gat(t,e),goalTokenBudget:IDe(e.goal?.tokenBudget,"goal.tokenBudget"),goalTurnBudget:IDe(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:L,includePartialMessages:O,modelProvidersConfig:he,generationConfigSources:Qe.sources,generationConfig:Qe.generationConfig,settingsGenerationConfig:e.model?.generationConfig,warnings:Qe.warnings,bareMode:u,allowedHttpHookUrls:u?[]:e.security?.allowedHttpHookUrls??[],cliVersion:await Pg(),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:ol,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:Aat(t.jsonSchema),inputFile:t.inputFile??e.dualOutput?.inputFile,chatRecording:t.fresh?!1:t.chatRecording??e.general?.chatRecording??!0,defaultFileEncoding:e.general?.defaultFileEncoding,lsp:{enabled:U},worktree:e.worktree?{symlinkDirectories:e.worktree.symlinkDirectories}:void 0},Le=new v_(Ve);if(U)try{let ue=new $oe(Le,Le.getWorkspaceContext(),ol,w,Af,{requireTrustedWorkspace:d});await ue.discoverAndPrepare(),Le.getDebugMode()&&NC.debug("Native LSP status after discovery:",ue.getStatusSnapshot()),await ue.start(),Le.getDebugMode()&&NC.debug("Native LSP status after startup:",ue.getStatusSnapshot()),z=new Joe(ue),Le.setLspClient(z);try{Le.setLspInitializationError(void 0)}catch{NC.warn("Failed to clear LSP initialization error after initialization")}}catch(ue){try{Le.setLspInitializationError(ue instanceof Error?ue:String(ue))}catch{NC.warn("LSP init error occurred after initialization:",ue)}NC.warn("Failed to initialize native LSP service:",ue)}return Le}h();h();async function bDe(e,t){if(!t)return null;try{await e.refreshAuth(t);let n=new Zy(t,"auto","success");Ky(e,n)}catch(n){let r=`Failed to login. Message: ${xr(n)}`,o=new Zy(t,"auto","error",r);return Ky(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"]},wDe=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"]},TDe=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"]},vDe=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"]},RDe=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"]},QDe=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"]},kDe=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"]},MDe=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"},FDe=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"]},NDe=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"]},Eat={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"}},TP=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,Eat);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"]},yat={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"}},Nk=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,yat);h();h();var eY=new Set(["Matilda Dark","Matilda Light","Matilda Wattle","Matilda Outback","Matilda Reef","Matilda Southern Cross"]);function _C(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 Iat(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 LC(e,t,n,r){return new Gr(e,t,Iat(n),n,r)}var _De={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"]},LDe=LC("Matilda Wattle","dark",_De,_C(_De,{textSecondary:"#8A9C8E",code:"#8FE0B4",link:"#4FC07E",warning:"#E8902E",warningDim:"#7A4E1A",heatmap:["#143021","#1F8A53","#3FB36B","#9FD15A","#F2C744"]}));h();var ODe={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"]},PDe=LC("Matilda Outback","dark",ODe,_C(ODe,{textSecondary:"#A98F77",code:"#F0B27A",link:"#E0704A",accent:"#F2A03D",warning:"#FFE08A",warningDim:"#8A6D1F",heatmap:["#2A1410","#8A3A1F","#D9603B","#F2A03D","#FFD9A0"]}));h();var UDe={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"]},HDe=LC("Matilda Reef","dark",UDe,_C(UDe,{textSecondary:"#7C9C96",code:"#7FE8DA",link:"#6FD3F0",accent:"#3FD9C9",warning:"#F2C744",warningDim:"#8A6D1F",heatmap:["#06222A","#1C7FA8","#1FA9B8","#3FD9C9","#F2C744"]}));h();var GDe={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"]},zDe=LC("Matilda Southern Cross","dark",GDe,_C(GDe,{textSecondary:"#8A92AE",code:"#9AB0F0",link:"#8FA0E8",warning:"#E8662E",warningDim:"#7A3A1A",heatmap:["#1A1B33","#2E3470","#6E78C8","#B9A0E8","#F2C744"]}));import*as _k from"node:fs";import*as mD from"node:path";import*as ZDe from"node:os";h();h();var jDe={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}},WDe={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}},Fcn={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 Dat={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"]},qDe=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"}},Dat,WDe);h();var Sat={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"]},YDe=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"}},Sat,jDe);h();var Bat={type:"ansi",Background:"",Foreground:"",LightBlue:"",AccentBlue:"",AccentPurple:"",AccentCyan:"",AccentGreen:"",AccentYellow:"",AccentRed:"",AccentYellowDim:"",AccentRedDim:"",DiffAdded:"",DiffRemoved:"",Comment:"",Gray:""},xat={text:{primary:"",secondary:"",link:"",accent:"",code:""},background:{primary:"",diff:{added:"",removed:""}},border:{default:"",focused:""},ui:{comment:"",symbol:"",gradient:[]},status:{error:"",success:"",warning:"",errorDim:"",warningDim:""}},JDe=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%"}},Bat,xat);import Qat from"node:process";h();import{execSync as bat}from"node:child_process";import Zx from"node:process";var pD=Ke("THEME_DETECT"),wat=200;function Xx(e){let t=16**e.length-1;return parseInt(e,16)/t}function Tat(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:Xx(t[1]),g:Xx(t[2]),b:Xx(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:Xx(r.slice(0,o)),g:Xx(r.slice(o,2*o)),b:Xx(r.slice(2*o))}}}function vat(e){let t=Tat(e);return t?.2126*t.r+.7152*t.g+.0722*t.b>.5?"light":"dark":void 0}function Rat(){return!Zx.stdin.isTTY||!Zx.stdout.isTTY?Promise.resolve(void 0):new Promise(e=>{let t=Zx.stdin,n=!1,r="",o=a=>{n||(n=!0,clearTimeout(s),t.removeListener("data",i),e(a))},s=setTimeout(()=>o(void 0),wat),i=a=>{r+=a.toString();let l=/\x1b\]11;(.*?)(?:\x07|\x1b\\)/.exec(r);l&&o(vat(l[1]))};t.on("data",i),Zx.stdout.write("\x1B]11;?\x07")})}function $De(){if(Zx.platform==="darwin")try{return bat("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 VDe(){let e=Zx.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 KDe(){let e=VDe();if(e)return pD.info(`Detected theme from COLORFGBG: ${e}`),e;let t=$De();return t?(pD.info(`Detected theme from macOS system appearance: ${t}`),t):(pD.info("Could not detect terminal theme, defaulting to dark"),"dark")}async function XDe(){let e=VDe();if(e)return pD.info(`Detected theme from COLORFGBG (async path): ${e}`),e;let t=await Rat();if(t)return pD.info(`Detected theme from OSC 11 background query: ${t}`),t;let n=$De();return n?(pD.info(`Detected theme from macOS system appearance: ${n}`),n):(pD.info("Could not detect terminal theme, defaulting to dark"),"dark")}var Sm=Ke("THEME_MANAGER"),OC=Nk,Xc="auto";function eSe(e){return e?e.endsWith(".json")||e.startsWith(".")||mD.isAbsolute(e):!1}var tY=class{availableThemes;activeTheme;customThemes=new Map;constructor(){this.availableThemes=[Nk,TP,LDe,PDe,HDe,zDe,wDe,TDe,vDe,RDe,hQ,CQ,QDe,kDe,MDe,FDe,NDe,qDe,YDe],this.activeTheme=OC}loadCustomThemes(t){if(this.customThemes.clear(),!!t){for(let[n,r]of Object.entries(t)){let o=t6(r);if(o.isValid){o.warning&&Sm.warn(`Theme "${n}": ${o.warning}`);let s={...OC.colors,...r,name:r.name||n,type:"custom"};try{let i=e6(s);this.customThemes.set(n,i)}catch(i){Sm.warn(`Failed to load custom theme "${n}":`,i)}}else Sm.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===Xc)return this.activeTheme=this.resolveAutoTheme(),Sm.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??KDe())==="light"?TP:Nk}async resolveAutoThemeAsync(){let t=await XDe();this.cachedAutoDetection=t,this.activeTheme=t==="light"?TP:Nk,Sm.info(`Auto-detected theme (async): ${this.activeTheme.name}`)}getActiveTheme(){if(Qat.env.NO_COLOR)return JDe;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=OC,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=>eY.has(i.name)),s=[...t.filter(i=>!eY.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(".")||mD.isAbsolute(t)}loadThemeFromFile(t){try{let n=_k.realpathSync(mD.resolve(t));if(this.customThemes.has(n))return this.customThemes.get(n);let r=mD.resolve(ZDe.homedir());if(!n.startsWith(r)){Sm.warn(`Theme file at "${t}" is outside your home directory. Only load themes from trusted sources.`);return}let o=_k.readFileSync(n,"utf-8"),s=JSON.parse(o),i=t6(s);if(!i.isValid){Sm.warn(`Invalid custom theme from file "${t}": ${i.error}`);return}i.warning&&Sm.warn(`Theme from "${t}": ${i.warning}`);let a={...OC.colors,...s,name:s.name||n,type:"custom"},l=e6(a);return this.customThemes.set(n,l),l}catch(n){n instanceof Error&&"code"in n&&n.code==="ENOENT"||Sm.warn(`Could not load theme from file "${t}":`,n);return}}findThemeByName(t){if(!t)return OC;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=_k.realpathSync(mD.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 tY;function tSe(e){let t=e.merged.ui?.theme;return t&&t!==Xc&&!_n.findThemeByName(t)?C('Theme "{{themeName}}" not found.',{themeName:t}):null}async function nSe(e,t){let n=process.env.MATILDA_CODE_LANG||t.merged.general?.language||"auto";await nue(n);let r=e.getModelsConfig().getCurrentAuthType(),o=await bDe(e,r),s=tSe(t),i=!e.getModelsConfig().wasAuthTypeExplicitlyProvided()||!!o;return e.getIdeMode()&&(await(await Ka.getInstance()).connect(),j1(e,new $1("start"))),{authError:o,themeError:s,shouldOpenAuthDialog:i,geminiMdFileCount:e.getGeminiMdFileCount()}}h();h();import{spawn as fSe}from"node:child_process";h();h();h();function Lk(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 rSe(e,t){return e.filter(n=>Lk(n).includes(t))}function vP(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 RP(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 oSe(e){let t=Lk(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 PC(e){return[...e.altNames??[],...e.hiddenAltNames??[]]}function QP(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 kP(e){return e.subCommands?.filter(t=>!t.hidden).map(t=>t.name)??[]}h();import*as ki from"node:fs/promises";import{constants as nY}from"node:fs";import{execSync as Mat,spawn as FP}from"node:child_process";import*as eb from"node:path";import{randomUUID as sSe}from"node:crypto";var Ec=Ke("CLIPBOARD_UTILS"),Pk=5e3;function tb(e){try{if(Buffer.byteLength(e,"utf-8")>75e3)return Ec.warn(`writeOsc52: text too large (${Buffer.byteLength(e,"utf-8")} bytes), skipping`),!1;let n=Buffer.from(e,"utf-8").toString("base64"),r=kl(`\x1B]52;c;${n}\x07`),o=process.stderr.isTTY?process.stderr:process.stdout.isTTY?process.stdout:null;return o?(o.write(r,s=>{s&&Ec.warn("writeOsc52: async write failed:",s)}),!0):(Ec.warn("OSC 52 clipboard requires a TTY; stdout/stderr not connected to terminal"),!1)}catch(t){return Ec.warn("writeOsc52 failed:",t),!1}}var Ok,MP=null,rY=null,iSe=!1;async function lSe(){if(iSe)return rY;iSe=!0;try{return rY=await import("@teddyzhu/clipboard"),rY}catch{return Ec.error("Failed to load @teddyzhu/clipboard native module. Clipboard image features will be unavailable."),null}}function cSe(){if(Ok!==void 0)return Ok;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 Ok=null,null;try{return Mat("command -v "+r,{stdio:"ignore"}),Ok=r,r}catch{return Ec.warn(`${r} not found`),Ok=null,null}}async function oY(e,t,n){let r;try{r=await ki.open(n,nY.O_WRONLY|nY.O_CREAT|nY.O_EXCL)}catch{return!1}return new Promise(o=>{let s=FP(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(()=>{Ec.debug(`${e} timed out after ${Pk}ms`),c(!1)},Pk);s.stderr.on("data",A=>{a+=A.toString()}),s.stdout.pipe(i),s.stdout.on("error",A=>{Ec.debug(`stdout error for ${e}:`,A),clearTimeout(u),c(!1)}),s.on("error",A=>{Ec.debug(`Failed to spawn ${e}:`,A),clearTimeout(u),c(!1)}),i.on("error",A=>{Ec.debug(`File stream error for ${n}:`,A),clearTimeout(u),c(!1)}),s.on("close",A=>{if(clearTimeout(u),l)return;if(A!==0){Ec.debug(`${e} exited with code ${A}. Args: ${t.join(" ")}`),a&&Ec.debug(`${e} stderr: ${a.trim()}`),c(!1);return}let g=()=>{ki.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 aSe(e,t){return e==="wl-paste"&&t.length===1&&t[0]==="--list-types"?(await uSe()).length>0:new Promise(n=>{try{let r=FP(e,t,{stdio:["ignore","pipe","ignore"]}),o="",s=setTimeout(()=>{try{r.kill()}catch{}n(!1)},Pk);r.stdout.on("data",i=>{o+=i.toString()}),r.on("close",i=>{clearTimeout(s),n(i===0&&o.split(`
402
402
  `).some(a=>a==="image/png"||a==="image/bmp"))}),r.on("error",()=>{clearTimeout(s),n(!1)})}catch{n(!1)}})}async function NP(){if(MP=null,process.platform==="linux"){try{let e=cSe();if(e==="wl-paste")return aSe("wl-paste",["--list-types"]);if(e==="xclip")return aSe("xclip",["-selection","clipboard","-t","TARGETS","-o"])}catch(e){Ec.error("Error checking clipboard for image:",e)}return!1}try{let e=await lSe();return e?new e.ClipboardManager().hasFormat("image"):!1}catch(e){return Ec.error("Error checking clipboard for image:",e),!1}}async function uSe(){return MP!==null?MP:new Promise(e=>{let t=FP("wl-paste",["--list-types"],{stdio:["ignore","pipe","ignore"]}),n="",r=setTimeout(()=>{try{t.kill()}catch{}e([])},Pk);t.stdout.on("data",o=>{n+=o.toString()}),t.on("close",o=>{if(clearTimeout(r),o!==0){e([]);return}let s=n.trim().split(`
403
403
  `).filter(i=>i==="image/png"||i==="image/bmp");MP=s,e(s)}),t.on("error",()=>{clearTimeout(r),e([])})})}async function Fat(e){let t=await uSe();if(t.includes("image/png")){if(await oY("wl-paste",["--no-newline","--type","image/png"],e))return e;try{await ki.unlink(e)}catch{}}if(t.includes("image/bmp")){let n=e.replace(/\.png$/,".bmp");if(await oY("wl-paste",["--no-newline","--type","image/bmp"],n))try{await new Promise((o,s)=>{let i=FP("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"))},Pk);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 ki.unlink(n)}catch{}return e}catch(o){Ec.warn("BMP-to-PNG conversion failed (install python3-pil for BMP support):",o);try{await ki.unlink(n)}catch{}try{await ki.unlink(e)}catch{}return!1}try{await ki.unlink(n)}catch{}}return!1}async function Nat(e){if(await oY("xclip",["-selection","clipboard","-t","image/png","-o"],e))return!0;try{await ki.unlink(e)}catch{}return!1}async function dSe(e){try{let t=e||process.cwd(),n=eb.join(t,"clipboard");await ki.mkdir(n,{recursive:!0});let r=new Date().getTime();if(process.platform==="linux"){let c=eb.join(n,`clipboard-${r}-${sSe()}.png`),u=cSe();if(u==="wl-paste"){let A=await Fat(c);if(A)try{if((await ki.stat(A)).size>0)return A;await ki.unlink(A)}catch{}return null}return u==="xclip"&&await Nat(c)?c:null}let o=await lSe();if(!o)return null;let s=new o.ClipboardManager;if(!s.hasFormat("image"))return null;let i=eb.join(n,`clipboard-${r}-${sSe()}.png`),l=s.getImageData().data;return l?(await ki.writeFile(i,l),i):null}catch(t){return Ec.error("Error saving clipboard image:",t),null}}async function ASe(e){try{let t=e||process.cwd(),n=eb.join(t,"clipboard"),r=await ki.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=eb.join(n,a),c=await ki.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 ki.unlink(c.path)}}catch{}}var _at={UTF8:65001,GBK:936,BIG5:950,LATIN1:1252},pSe=e=>e.startsWith("@")||/\s@/.test(e),Lat=/[/\\]/,Oat=e=>e.slice(1).trimStart().split(/\s+/u)[0]??"",sY=e=>Lat.test(Oat(e)),na=e=>!(!e.startsWith("/")||e.startsWith("//")||e.startsWith("/*")||sY(e)),Pat=/^[/?]btw(?:\s|$)/,nb=e=>{let t=e.trim();return t.length>0&&Pat.test(t)},rdn=Ke("COMMAND_UTILS"),hD=async e=>{let t=(r,o,s)=>new Promise((i,a)=>{let l=s?fSe(r,o,s):fSe(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 ${_at.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(!tb(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"),tb(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 mSe(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 hSe(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 gSe=/(?:^|(?<=\s))\/([a-zA-Z][a-zA-Z0-9:_-]*)/g;function CSe(e,t){if(!e)return[];let n=[];for(let i of t){n.push([i.name.toLowerCase(),i]);for(let a of PC(i))n.push([a.toLowerCase(),i])}let r=new Map(n),o=[],s;for(gSe.lastIndex=0;(s=gSe.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===`
404
- `,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 Uat(e){try{return e.getGoalRuntime()}catch(t){if(t instanceof i0)return;throw t}}function ESe(e,t){let n,r=!1,o=Uat(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=Wh(l);return c.outcome==="completed"||!l?.lastReason?c:{...c,reason:l.lastReason}},async release(l=dre){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 pw}from"node:crypto";h();h();function ySe(e){return e.api.totalRequests===0?0:e.api.totalErrors/e.api.totalRequests*100}function ISe(e){return e.api.totalRequests===0?0:e.api.totalLatencyMs/e.api.totalRequests}function DSe(e){return e.tokens.prompt===0?0:e.tokens.cached/e.tokens.prompt*100}var rb=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 CD=(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=>PC(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 Hat=Ke("CLI_COMMANDS"),ED=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):Hat.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=PC(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(rSe(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 ydn=M(Se(),1);var Gat=["achieved","aborted","failed"];function SSe(e){return Gat.includes(e)}h();import sb from"node:process";import zat from"node:os";import{execFile as jat}from"node:child_process";h();var il=e=>{let t=e/1073741824;return e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${t.toFixed(2)} GB`},ob=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"},Gg=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 _P="caa58eea3";var BSe=Ke("STATUS"),Wat=5e3;function xSe(e){return new Promise(t=>{jat(e,["--version"],{timeout:Wat,encoding:"utf-8"},(n,r)=>{if(n){t("unknown");return}t(typeof r=="string"?r.trim():"unknown")})})}async function iY(){return xSe("npm")}async function bSe(){return xSe("git")}async function qat(e){if(!e.services.config?.getIdeMode())return"";try{return(await Ka.getInstance())?.getDetectedIdeDisplayName()??""}catch{return""}}function wSe(e=!1){let t=sb.env.SANDBOX;return!t||t==="sandbox-exec"?t==="sandbox-exec"?`sandbox-exec (${sb.env.SEATBELT_PROFILE||"unknown"})`:"no sandbox":e?t.replace(/^matilda-(?:code-)?/,""):t}async function Yat(e){let t=sb.platform,n=sb.arch,r=zat.release(),o=sb.version,s=await iY(),i=wSe(),a=e.services.config?.getModelDisplayName()||"Unknown",l=await Pg(),c=e.services.config?.getAuthType()||"",u=await qat(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 LP(e){let t=await Yat(e),n=il(sb.memoryUsage().rss),r=wSe(!0),o=t.selectedAuthType==="openai"?e.services.config?.getContentGeneratorConfig():void 0,s=o?.baseUrl,i=o?.apiKeyEnvKey,a=_P&&!["N/A"].includes(_P)?_P:void 0,l=e.services.settings?.merged?.fastModel||void 0,c=Jat(e);return{...t,sandboxEnv:r,memoryUsage:n,baseUrl:s,apiKeyEnvKey:i,gitCommit:a,fastModel:l,lspStatus:c}}function Jat(e){try{let t=e.services.config?.getLspStatusSnapshot?.();return t?(e.services.config?.getDebugMode?.()&&BSe.debug("LSP status snapshot for /status:",t),$at(t)):void 0}catch(t){e.services.config?.getDebugMode?.()&&BSe.debug("Unable to read LSP status snapshot for /status:",t);return}}function $at(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 aY from"node:fs/promises";import Vat from"node:path";var vSe=Ke("SESSION_PATHS"),TSe=100;async function RSe(e){let t=e.services.config,n=t?.getSessionId()||e.session.stats.sessionId||"unknown",r=t?.getContentGeneratorConfig(),o=t?.getWorkingDir()||process.cwd(),s=Une(r?.openAILoggingDir,o),i=r?.enableOpenAILogging===!0,a=i&&n!=="unknown"?await Kat(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 elt(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 QSe(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(`
404
+ `,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 Uat(e){try{return e.getGoalRuntime()}catch(t){if(t instanceof i0)return;throw t}}function ESe(e,t){let n,r=!1,o=Uat(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=Wh(l);return c.outcome==="completed"||!l?.lastReason?c:{...c,reason:l.lastReason}},async release(l=dre){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 pw}from"node:crypto";h();h();function ySe(e){return e.api.totalRequests===0?0:e.api.totalErrors/e.api.totalRequests*100}function ISe(e){return e.api.totalRequests===0?0:e.api.totalLatencyMs/e.api.totalRequests}function DSe(e){return e.tokens.prompt===0?0:e.tokens.cached/e.tokens.prompt*100}var rb=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 CD=(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=>PC(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 Hat=Ke("CLI_COMMANDS"),ED=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):Hat.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=PC(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(rSe(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 ydn=M(Se(),1);var Gat=["achieved","aborted","failed"];function SSe(e){return Gat.includes(e)}h();import sb from"node:process";import zat from"node:os";import{execFile as jat}from"node:child_process";h();var il=e=>{let t=e/1073741824;return e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${t.toFixed(2)} GB`},ob=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"},Gg=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 _P="826487a9f";var BSe=Ke("STATUS"),Wat=5e3;function xSe(e){return new Promise(t=>{jat(e,["--version"],{timeout:Wat,encoding:"utf-8"},(n,r)=>{if(n){t("unknown");return}t(typeof r=="string"?r.trim():"unknown")})})}async function iY(){return xSe("npm")}async function bSe(){return xSe("git")}async function qat(e){if(!e.services.config?.getIdeMode())return"";try{return(await Ka.getInstance())?.getDetectedIdeDisplayName()??""}catch{return""}}function wSe(e=!1){let t=sb.env.SANDBOX;return!t||t==="sandbox-exec"?t==="sandbox-exec"?`sandbox-exec (${sb.env.SEATBELT_PROFILE||"unknown"})`:"no sandbox":e?t.replace(/^matilda-(?:code-)?/,""):t}async function Yat(e){let t=sb.platform,n=sb.arch,r=zat.release(),o=sb.version,s=await iY(),i=wSe(),a=e.services.config?.getModelDisplayName()||"Unknown",l=await Pg(),c=e.services.config?.getAuthType()||"",u=await qat(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 LP(e){let t=await Yat(e),n=il(sb.memoryUsage().rss),r=wSe(!0),o=t.selectedAuthType==="openai"?e.services.config?.getContentGeneratorConfig():void 0,s=o?.baseUrl,i=o?.apiKeyEnvKey,a=_P&&!["N/A"].includes(_P)?_P:void 0,l=e.services.settings?.merged?.fastModel||void 0,c=Jat(e);return{...t,sandboxEnv:r,memoryUsage:n,baseUrl:s,apiKeyEnvKey:i,gitCommit:a,fastModel:l,lspStatus:c}}function Jat(e){try{let t=e.services.config?.getLspStatusSnapshot?.();return t?(e.services.config?.getDebugMode?.()&&BSe.debug("LSP status snapshot for /status:",t),$at(t)):void 0}catch(t){e.services.config?.getDebugMode?.()&&BSe.debug("Unable to read LSP status snapshot for /status:",t);return}}function $at(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 aY from"node:fs/promises";import Vat from"node:path";var vSe=Ke("SESSION_PATHS"),TSe=100;async function RSe(e){let t=e.services.config,n=t?.getSessionId()||e.session.stats.sessionId||"unknown",r=t?.getContentGeneratorConfig(),o=t?.getWorkingDir()||process.cwd(),s=Une(r?.openAILoggingDir,o),i=r?.enableOpenAILogging===!0,a=i&&n!=="unknown"?await Kat(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 elt(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 QSe(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(`
405
405
  `)}async function Kat(e,t){let n=await Xat(e,r=>/^openai-.*\.json$/.test(r));for(let r of n)try{let o=await aY.readFile(r,"utf-8"),s=JSON.parse(o);if(tlt(s,t))return r}catch(o){if(o instanceof SyntaxError||o.code==="ENOENT")continue;vSe.warn("Error reading OpenAI log file",r,o)}}async function Xat(e,t){try{let n=await aY.readdir(e,{withFileTypes:!0}),r=[];for(let o of n)!o.isFile()||!t(o.name)||Zat(r,Vat.join(e,o.name));return r}catch(n){return n.code!=="ENOENT"&&vSe.warn("Unable to list OpenAI log directory",e,n),[]}}function Zat(e,t){let n=e.findIndex(r=>t>r);if(n===-1){e.length<TSe&&e.push(t);return}e.splice(n,0,t),e.length>TSe&&e.pop()}async function elt(e){try{return await aY.access(e),!0}catch{return!1}}function tlt(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 nlt(e){let t=e.services.config;if(!t)return{};let n=BO(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 kSe={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 LP(e),...nlt(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(`
406
406
  `)};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 RSe(e);return{type:"message",messageType:"info",content:QSe(t)}}}]};h();var MSe={name:"account",description:"Open account usage, billing or organisations (browser signs in separately)",kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:async(e,t)=>{let n=t.trim()||"usage";if(!["usage","billing","organizations"].includes(n))return{type:"message",messageType:"error",content:"Use /account usage, /account billing or /account organizations."};try{let r=e.services.config,o=O_(r?.getContentGeneratorConfig()?.baseUrl??"",n,r?.getOrganizationId());return e.executionMode==="interactive"&&await nA(o),{type:"message",messageType:"info",content:`${o}
407
407
  ${L_}`}}catch(r){return{type:"message",messageType:"error",content:r instanceof Error?r.message:"Could not open account page."}}}};h();function rlt(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 olt(e){switch(e.kind){case"agent":return BR(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 slt(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 ilt(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 FSe={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(`[${slt(l)}] ${rlt(l)} ${u}${A} ${olt(l)}`);let g=ilt(l);g&&a.push(` output: ${g}`)}return{type:"message",messageType:"info",content:Am(a.join(`
@@ -862,7 +862,7 @@ ${Z}
862
862
  `).filter(n=>n.trim()!=="");try{await CZ.unlink(EZ)}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 BNt from"node:fs/promises";import xNt from"node:path";var bNt={id:"root-directory",check:async e=>{try{let t=await BNt.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 xNt.dirname(t)===t?n:null}catch{return"Could not verify the current directory due to a file system error."}}},wNt={id:"ripgrep-availability",check:async e=>{if(!e.useRipgrep)return null;try{return await S_(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.`}}},TNt=[bNt,wNt];async function J3e(e){return(await Promise.all(TNt.map(n=>n.check(e)))).filter(n=>n!==null)}h();import*as jT from"node:fs";import*as $3e from"node:path";function V3e(e){process.on("uncaughtExceptionMonitor",(t,n)=>{yZ(t,n,e)})}function yZ(e,t,n){let r=RNt(e,t,n);try{yN(),jT.writeSync(2,`Matilda crashed: ${vNt(e)}
863
863
  ${r?`The full error is saved in ${r}
864
864
  `:""}`)}catch{}}function vNt(e){let n=(e instanceof Error?e.message:String(e)).split(`
865
- `,1)[0].trim();return n.length>200?`${n.slice(0,199)}\u2026`:n}function RNt(e,t,n,r=new Date){try{let o;try{o=n.sessionId?.()}catch{o=void 0}let s=Ft.getGlobalCrashDir();jT.mkdirSync(s,{recursive:!0});let i=r.toISOString().replace(/[:.]/g,"-"),a=$3e.join(s,`${i}-${o??`pid-${process.pid}`}.log`),l=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);return jT.writeFileSync(a,[`time: ${r.toISOString()}`,`origin: ${t}`,`matilda: ${n.version??"0.22.1-nightly.20261104.f4c27782c"??"unknown"}`,`node: ${process.version}`,`platform: ${process.platform} ${process.arch}`,`pid: ${process.pid}`,`session: ${o??"unknown"}`,"",l,""].join(`
865
+ `,1)[0].trim();return n.length>200?`${n.slice(0,199)}\u2026`:n}function RNt(e,t,n,r=new Date){try{let o;try{o=n.sessionId?.()}catch{o=void 0}let s=Ft.getGlobalCrashDir();jT.mkdirSync(s,{recursive:!0});let i=r.toISOString().replace(/[:.]/g,"-"),a=$3e.join(s,`${i}-${o??`pid-${process.pid}`}.log`),l=e instanceof Error?e.stack??`${e.name}: ${e.message}`:String(e);return jT.writeFileSync(a,[`time: ${r.toISOString()}`,`origin: ${t}`,`matilda: ${n.version??"0.22.1-preview.0"??"unknown"}`,`node: ${process.version}`,`platform: ${process.platform} ${process.arch}`,`pid: ${process.pid}`,`session: ${o??"unknown"}`,"",l,""].join(`
866
866
  `),{mode:384}),a}catch{return}}h();var QNt=[/MaxListenersExceededWarning.*AbortSignal/];function kNt(e){let t=`${e.name}: ${e.message}`;return QNt.some(n=>n.test(t))}function MNt(){let e=t=>!!t&&t!=="0"&&t.toLowerCase()!=="false";return e(process.env.DEBUG)||e(process.env.MATILDA_DEBUG)}var IZ=null;function K3e(){if(IZ)return;let e=[...process.listeners("warning")];IZ=t=>{if(!(!MNt()&&kNt(t)))for(let n of e)try{n(t)}catch{}},process.removeAllListeners("warning"),process.on("warning",IZ)}h();function X3e(e){return e.promptInteractive?!1:FNt(e.prompt??e.query??"")}function FNt(e){let t=e.trim();return t==="/help"||t==="/?"}function Z3e(){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(`
867
867
  `)}h();var NNt="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 e8e(e,t=process.env){return e.getApprovalMode()!=="bogan"||e.getSandbox()||t.SANDBOX||_Nt(t.MATILDA_CODE_SUPPRESS_BOGAN_WARNING)?null:NNt}function _Nt(e){return e==="1"||e==="true"}h();var $S=Ke("EARLY_INPUT"),kN=64*1024,hu={chunks:[],totalBytes:0,captured:!1},MN=null,FN=null,ez=!1,ZE=Buffer.alloc(0);function t8e(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 LNt(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 ONt(e){let t=Buffer.allocUnsafe(e.length),n=0,r=0;for(;r<e.length;){if(e[r]===27){let o=t8e(e,r);if(o==="incomplete")return{filtered:t.subarray(0,n),trailingPartialTerminalResponse:e.subarray(r)};if(o==="terminal"){let s=LNt(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 PNt(e){return e.length===0?!1:e.length===1&&e[0]===27?!0:t8e(e,0)==="user"}function n8e(){if(ez||!process.stdin.isTTY){process.stdin.isTTY||$S.debug("Early input capture skipped: stdin is not a TTY");return}if(process.env.MATILDA_CODE_DISABLE_EARLY_CAPTURE==="1"){$S.debug("Early input capture disabled by environment variable");return}ez=!0,hu={chunks:[],totalBytes:0,captured:!1},ZE=Buffer.alloc(0),$S.debug("Starting early input capture"),MN=e=>{if(hu.captured)return;if(hu.totalBytes>=kN){$S.warn(`Early input capture buffer full (${kN} bytes). Stopping capture; additional keystrokes during startup will be lost.`),r8e();return}let t=ZE.length>0?Buffer.concat([ZE,e]):e;ZE=Buffer.alloc(0);let{filtered:n,trailingPartialTerminalResponse:r}=ONt(t);if(r.length>0&&(ZE=Buffer.from(r)),n.length>0)if(hu.totalBytes+n.length>kN){let s=n.subarray(0,kN-hu.totalBytes);hu.chunks.push(Buffer.from(s)),hu.totalBytes+=s.length,$S.debug(`Buffer truncated at ${kN} bytes`)}else hu.chunks.push(Buffer.from(n)),hu.totalBytes+=n.length,$S.debug(`Captured ${n.length} bytes (total: ${hu.totalBytes})`)},FN=process.stdin,FN.on("data",MN)}function r8e(){!ez||!MN||!FN||(FN.removeListener("data",MN),FN=null,MN=null,ez=!1,hu.captured=!0,$S.debug(`Stopped early input capture: ${hu.totalBytes} bytes`))}function UNt(){let e=[...hu.chunks];PNt(ZE)&&e.push(Buffer.from(ZE));let t=e.length>0?Buffer.concat(e):Buffer.alloc(0);return hu.chunks=[],hu.totalBytes=0,ZE=Buffer.alloc(0),t}function DZ(){return r8e(),UNt()}h();var o8e=M(GV(),1);var og=Ke("PRECONNECT"),WT=!1,HNt=Fre();function GNt(){return process.env.NODE_EXTRA_CA_CERTS?(og.debug("Skipping preconnect: custom CA certificate configured"),!0):!1}function zNt(){return process.env.SANDBOX!==void 0}function jNt(e){let t=e.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return HNt.some(n=>{let r=n.toLowerCase().replace(/^https?:\/\//,"").replace(/\/+$/,"");return t===r||t.startsWith(r+"/")})}function WNt(e){if(e&&/^https?:\/\//i.test(e)){if(jNt(e))return e;og.debug("Skipping preconnect: resolved baseUrl is not a default URL")}}function s8e(e={}){if(WT)return;if(process.env.MATILDA_CODE_DISABLE_PRECONNECT==="1"){og.debug("Preconnect disabled by environment variable"),WT=!0;return}if(zNt()){og.debug("Skipping preconnect: sandbox mode detected"),WT=!0;return}if(GNt()){WT=!0;return}if(Xne()!=="node"){og.debug("Skipping preconnect: unsupported runtime"),WT=!0;return}if(!e.proxy){og.debug("Skipping preconnect dispatcher: no proxy configured");return}let t=e.proxy,n=WNt(e.resolvedBaseUrl);if(!n){og.debug("No target URL for preconnect");return}WT=!0,og.debug(`Preconnecting to: ${n}`);try{let r=Zne(t);(0,o8e.fetch)(n,{method:"HEAD",signal:AbortSignal.timeout(5e3),headers:{"User-Agent":"MatildaCode-Preconnect/1.0"},dispatcher:r}).then(()=>{og.debug("Preconnect completed")}).catch(o=>{let s=Nj(String(o));og.debug(`Preconnect failed (ignored): ${s}`)})}catch(r){let o=Nj(String(r));og.debug(`Preconnect failed (ignored): ${o}`)}}h();async function i8e(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=Y0(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 hw(t):s=new Um(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 vl(),process.exit(1)}st(r instanceof Error?r.message:String(r)),process.exit(1)}}h();var l8e=M(Se(),1);var VS=M(ie(),1);var qNt={getShouldUseNodePtyShell:()=>!1,getIdeMode:()=>!1,isTrustedFolder:()=>!1,getToolRegistry:()=>({getTool:()=>{}}),getContentGenerator:()=>({useSummarizedThinking:()=>!1})},YNt={merged:{ui:{}}};function JNt({sessionService:e,onSelect:t,onCancel:n,currentBranch:r,initialSessions:o}){let{exit:s}=NW(),[i,a]=(0,l8e.useState)(!1),l=()=>{a(!0),s()};return i?(0,VS.jsx)(x,{}):(0,VS.jsx)(Gf.Provider,{value:qNt,children:(0,VS.jsx)(yD.Provider,{value:YNt,children:(0,VS.jsx)(ZF,{sessionService:e,onSelect:c=>{t(c),l()},onCancel:()=>{n(),l()},currentBranch:r,centerSelection:!0,initialSessions:o,enablePreview:!0})})})}function a8e(){process.stdout.write("\x1B[2J\x1B[H")}async function SZ(e=process.cwd(),t){let n=new pi(e);if(!await n.loadLastSession()){St("No sessions found. Start a new session with `matilda`.");return}a8e();let o=process.stdin.isRaw;return process.stdin.isTTY&&!o&&process.stdin.setRawMode(!0),new Promise(s=>{let i,{unmount:a,waitUntilExit:l}=dQ((0,VS.jsx)(qP,{kittyProtocolEnabled:!1,pasteWorkaround:process.platform==="win32"||parseInt(process.versions.node.split(".")[0],10)<20,children:(0,VS.jsx)(JNt,{sessionService:n,onSelect:c=>{i=c},onCancel:()=>{i=void 0},currentBranch:l_(e),initialSessions:t})}),{exitOnCtrlC:!1});l().then(()=>{a(),a8e(),process.stdin.isTTY&&!o&&!i&&process.stdin.setRawMode(!1),s(i)})})}h();import{createReadStream as $Nt,watchFile as VNt,unwatchFile as KNt,statSync as c8e}from"node:fs";import{createInterface as XNt}from"node:readline";var ph=Ke("REMOTE_INPUT"),tz=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=c8e(this.filePath);this.bytesRead=t.size}catch{this.bytesRead=0}VNt(this.filePath,{interval:this.pollIntervalMs},()=>{this.active&&this.readNewLines()}),ph.debug(`RemoteInput: watching ${this.filePath}`)}checkForNewInput(){return this.readNewLines()}readNewLines(){if(!this.active||this.reading)return Promise.resolve();let t;try{t=c8e(this.filePath).size}catch{return Promise.resolve()}if(t<=this.bytesRead)return Promise.resolve();this.reading=!0;let n=$Nt(this.filePath,{start:this.bytesRead,encoding:"utf-8"}),r=XNt({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"?(ph.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"?(ph.debug(`RemoteInput: queued command: ${i.text.slice(0,50)}...`),this.queue.push(i)):ph.warn(`RemoteInput: unknown command type: ${String(i?.type)}`)}catch{ph.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];ph.debug(`RemoteInput: submitting: ${t.text.slice(0,50)}...`);try{if(await this.submitFn(t.text)===!1){ph.debug("RemoteInput: TUI busy, will retry on idle"),this.scheduleRetry();break}this.queue.shift()}catch(n){ph.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,KNt(this.filePath),this.retryTimer&&clearTimeout(this.retryTimer),this.queue.length=0,ph.debug("RemoteInput: shut down")}};h();var Gd="\x1B[",qT=`${Gd}2K`,ZNt=`${Gd}1A`,e1t=`${Gd}1B`,xZ=`${Gd}G`,t1t=new RegExp(`(?:${u8e(qT+ZNt)})+${u8e(qT+xZ)}`,"g");function u8e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function d8e(e,t){let n=0,r=0;for(;(r=e.indexOf(t,r))!==-1;)n++,r+=t.length;return n}var nz={stdoutWriteCount:0,stdoutBytes:0,clearTerminalCount:0,eraseLinesOptimizedCount:0};function n1t(e,t){if(typeof e=="string"){let n=typeof t=="string"?t:void 0;return Buffer.byteLength(e,n)}return e.byteLength}function BZ(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 r1t(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]!==`
868
868
  `||n>=127&&n<=159)return!1}return!0}function o1t(e,t){if(!t||t<3)return;let n=0;if(e.startsWith(ao.cursorHide)){n=BZ(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||BZ(e,u,"G")!==c)return;s=u;let A=e.lastIndexOf(Gd,s-1);A>=n&&BZ(e,A,"A")===s&&(s=A)}let i=e.slice(n,s),a=e.slice(s),l=i.split(`
@@ -930,7 +930,7 @@ ${u.text}`}),"blob"in u&&u.blob&&c.push(R_({inlineData:{mimeType:u.mimeType??"ap
930
930
  ${o.join(`
931
931
  `)}
932
932
  ---
933
- ${r}`}var Wze=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function qze(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(!Wze.has(t.hostname))throw ze.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function Yze(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 ePt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function tPt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function ite(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 nPt(e,t){let n=ite(e,t+124,12);return n?Number.parseInt(n,8):0}function rPt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function oPt(e,t){let n=ite(e,t,100),r=ite(e,t+345,155);return r?`${r}/${n}`:n}function sPt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var VN=100*1024*1024,Jze=500*1024*1024,iPt=16,aPt=2e3,Pz=class extends Error{};async function lPt(e,t,n={}){let r=n.maxCompressedBytes??VN,o=n.maxDecompressedBytes??Jze;if(e.length>r)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await MOt(Pze.from([Buffer.from(e)]),NOt(),new Uze({write(A,g,d){if(u+=A.length,u>o){d(new Pz);return}c.push(A),d()}})),s=Buffer.concat(c)}catch(c){throw c instanceof Pz?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&&!rPt(s,c);){let u=oPt(s,c),A=String.fromCharCode(s[c+156]||0),g=nPt(s,c),d=c+512,m=d+Math.ceil(g/512)*512;if(A==="0"||A==="\0"){let E=sPt(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 cPt=[".githubusercontent.com",".github.com"];function uPt(e){return Wze.has(e)?!0:cPt.some(t=>e.endsWith(t))}async function ute(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:"||!uPt(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 $ze(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 Vze(e){let t=await ute(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>VN)throw ze.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return $ze(t,VN)}async function dPt(e){let t=Yze(e),n=t?ePt(t):e,r=await Vze(n);return{skillContent:Buffer.from(r).toString("utf8"),files:[{relativePath:"SKILL.md",content:r}]}}async function APt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,r=await ute(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>VN)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return lPt(await $ze(r,VN),t)}async function fPt(e,t){let n=tPt(t),r=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,o=await ute(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 Kze(e,t,n="",r=0,o={files:0,bytes:0}){if(r>iPt)throw ze.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await fPt(e,t),i=[];for(let a of s){let l=Zs(a),c=Np(l.name,"github.name"),u=Np(l.path,"github.path"),A=Np(l.type,"github.type"),g=n?no.posix.join(n,c):c;if(A==="dir"){i.push(...await Kze(e,u,g,r+1,o));continue}if(A!=="file")continue;if(o.files+=1,o.files>aPt)throw ze.invalidParams(void 0,"Skill directory contains too many files");let d=Np(l.download_url,"github.download_url");qze(d);let m=await Vze(d);if(o.bytes+=m.length,o.bytes>Jze)throw ze.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:g,content:m})}return i}async function gPt(e,t){let n=await Kze(e,t).catch(r=>(Kl.warn("GitHub API directory listing failed, falling back to archive download:",r),null));return n||APt(e,t)}async function pPt(e){qze(e);let t=Yze(e);if(!t||no.posix.basename(t.filePath)!=="SKILL.md")return dPt(e);let n=no.posix.dirname(t.filePath),r=await gPt(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 mPt(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 Fze(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 hPt(e){return typeof Zs(e).id=="string"}function CPt(e,t){if(!t)return;let r=Zs(e.env)[t];return typeof r=="string"&&r.length>0?r:void 0}function EPt(e,t){let r=Zs(e.modelProviders)[t];return Array.isArray(r)?r.filter(hPt):[]}function Xze(e,t){return EPt(t,e.protocol).filter(u_(e))}function Zze(e,t,n){let r=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:xu(e),o=typeof n[0]?.envKey=="string"?n[0].envKey:e.envKey;return Z1(r)??CPt(t,o)}function yPt(e,t){let n=Xze(e,t),r=Zze(e,t,n);if(!r&&n.length===0)return;let o=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:xu(e);return{baseUrl:JN(o),...r?{hasApiKey:!0}:{},...n.length>0?{modelIds:n.map(s=>s.id)}:{}}}function IPt(e,t){return Zze(e,t,Xze(e,t))}function DPt(e,t){let n=yPt(e,t);return{id:e.id,label:e.label,description:e.description,protocol:e.protocol,baseUrl:e.baseUrl,defaultModelIds:Qre(e),models:e.models,documentationUrl:e.documentationUrl,...n?{existingConfig:n}:{}}}function SPt(e,t,n){let r=xu(e),o=iy(t.apiKey,"apiKey")??n;if(!o)throw ze.invalidParams(void 0,"Invalid or missing apiKey");return{baseUrl:r,apiKey:o}}function BPt(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 xPt(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 ste(e){let t={};for(let n of zze){let r=xPt(e,n);r!==void 0&&(t[n]=r)}return t}function bPt(e,t){let n=Gze[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 sg(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 sB(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 $N(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 wPt(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=$N(t.timeout);if(i!==void 0&&(r.timeout=i),typeof t.trust=="boolean"&&(r.trust=t.trust),r.includeTools=sg(t.includeTools),r.excludeTools=sg(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=sg(t.args),r.env=sB(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=sB(t.headers),r}var TPt=new Set(["command","args","cwd","env","httpUrl","url","headers","timeout","trust","description","includeTools","excludeTools"]);function vPt(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!TPt.has(t)))}function RPt(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 QPt(e){let t=Zs(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:sB(t.headers),timeout:$N(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:sg(t.includeTools),excludeTools:sg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:sB(t.headers),timeout:$N(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:sg(t.includeTools),excludeTools:sg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:sg(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:sB(t.env),timeout:$N(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:sg(t.includeTools),excludeTools:sg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var Uz="__redacted__";function kPt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(r=>[r,Uz]));return{...e,env:t(e.env),headers:t(e.headers)}}function MPt(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!==Uz){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 Nze(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,Uz]))}function _ze(e,t){if(!e)return e;let n=Zs(t),r={};for(let[o,s]of Object.entries(e)){if(s!==Uz){r[o]=s;continue}let i=n[o];typeof i=="string"&&(r[o]=i)}return r}function FPt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:Nze(t.env)}:{},...t.headers?{headers:Nze(t.headers)}:{}}))}}function NPt(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:_ze(r.env,s.env)}:{},...r.headers?{headers:_ze(r.headers,s.headers)}:{}}})}}function qN(e,t){let n=Zs(e.mcpServers);return Object.entries(n).map(([r,o])=>{try{let s=QPt(o);return s?{name:r,scope:t,server:kPt(s)}:void 0}catch(s){Kl.warn(`Skipping malformed MCP server config [${t}:${r}]:`,s);return}}).filter(r=>!!r)}function Lze(e){return typeof e=="string"&&jze.includes(e)}function _Pt(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=sB(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=sB(t.headers),r.allowedEnvVars=sg(t.allowedEnvVars),typeof t.once=="boolean"&&(r.once=t.once)}let o=$N(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 eje(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(_Pt)};return typeof t.matcher=="string"&&(r.matcher=t.matcher),typeof t.sequential=="boolean"&&(r.sequential=t.sequential),r}function YN(e,t,n){let r=Zs(e.hooks),o=[];for(let s of jze){let i=r[s];Array.isArray(i)&&i.forEach((a,l)=>{try{o.push({event:s,scope:t,index:l,hook:FPt(eje(a)),extensionName:n})}catch(c){Kl.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return o}function oB(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw ze.invalidParams(void 0,"scope must be user or workspace")}function Oz(e,t){return e.forScope(oB(t)).settings}async function Oze(e,t){for(let n of dd()){let r=no.join(e,n);try{return await yl.access(r),r}catch{}}return no.join(e,t)}async function LPt(e){let t=dd()[0]??"MATILDA.md",n=await Oze(Ft.getGlobalMatildaDir(),t),r=await Oze(e.cwd,t),o=Uh(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:r,autoMemoryDir:o}}async function tje(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let r=Uze.toWeb(process.stdout),o=Pze.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=V8e(r,o),i,a=new Cz(m=>(i=new ate(e,t,n,m),i),s),l=async m=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(E){Kl.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){Kl.warn(`SessionEnd hook failed: ${v instanceof Error?v.message:String(v)}`)}}},g=async()=>{if(c)return;c=!0,Kl.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,vl().catch(E=>{Kl.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 OPt(e){if("command"in e&&"args"in e&&"env"in e)return e}function PPt(e){if("type"in e&&e.type==="sse")return e}function UPt(e){if("type"in e&&e.type==="http")return e}var ate=class{constructor(t,n,r,o){this.config=t;this.settings=n;this.argv=r;this.connection=o;this.mcpPool=new Goe(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)&&Kl.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Kl.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){Kl.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"&&Kl.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return kk(t.merged,this.argv.channel)}get matildaAccount(){return this.matildaAccountState??=new Iz({channel:this.config.getChannel(),connectionSignal:this.connection.signal,signInBaseUrl:()=>bO(this.effectiveSettings(qi(process.cwd()))),install:t=>I5(qi(process.cwd()),t)}),this.matildaAccountState}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[lte];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===Nz,this.transcriptUpdatesNegotiated=this.transcriptReadNegotiated&&n.transcriptUpdates===wze,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===Vee,this.compactionUpdatesNegotiated=t.clientCapabilities?.session?.compaction!=null,this.signInUrlNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.signInUrl===1;let r=nv(this.config);return{protocolVersion:vZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.22.1-nightly.20261104.f4c27782c"},authMethods:r,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated||this.finalAnswersNegotiated||this.sessionNoticesNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:Nz}:{},...this.transcriptUpdatesNegotiated?{transcriptUpdates:wze}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{},...this.finalAnswersNegotiated?{finalAnswers:1}:{},...this.sessionNoticesNegotiated?{sessionNotices:Vee}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0},...nB({channel:this.config.getChannel()})?{auth:{logout:{}}}:{}}}}async authenticate({methodId:t}){if(t===$ee&&nB({channel:this.config.getChannel()})){await this.matildaAccount.signIn(this.signInUrlNegotiated?r=>this.connection.extNotification(lze,{...r}):void 0);return}let n=Vt.nativeEnum(oA).parse(t);await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}async logout(){if(!nB({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:Qze(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=HOt(t),a=GOt(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:Qze(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 f0(r);o.contextMessage&&(n.pendingWorktreeNotice=o.contextMessage)}catch(r){Kl.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 iv(qi(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 Ph?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=qi(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:_z(t.user.settings)},workspace:{path:t.workspace.path,rules:_z(t.workspace.settings)},merged:_z(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 ic({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await d.refreshCache(),i=d.getLoadedExtensions()}catch(d){Kl.warn("Extension loading failed, continuing without extensions:",d)}let a=await Promise.all(i.map(async d=>{let m=await A0(d.config,d.id,"user"),E=await A0(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,U=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:U,effectiveScope:z,hasUserValue:Q,hasWorkspaceValue:v}})}})),l=i.filter(d=>d.isActive),c=l.flatMap(d=>qN({mcpServers:d.config.mcpServers??{}},"extension").map(m=>({...m,server:{...m.server,extensionName:d.name}}))),u=l.flatMap(d=>YN({hooks:d.hooks??{}},"extension",d.name)),A=new Map;for(let d of qN(r,"user"))A.set(d.name,d);if(t.isTrusted)for(let d of qN(o,"workspace"))A.set(d.name,d);let g=[...YN(r,"user"),...t.isTrusted?YN(o,"workspace"):[]];return{user:{path:t.user.path,values:ste(r),mcpServers:qN(r,"user"),hooks:YN(r,"user")},workspace:{path:t.workspace.path,values:ste(o),mcpServers:qN(o,"workspace"),hooks:YN(o,"workspace")},merged:{values:ste(s),mcpServers:[...A.values(),...c],hooks:[...g,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){let r=t==="Workspace"?kze(n):void 0,o=new Map;for(let s of this.sessions.values()){let i=s.getConfig(),a=i.storage.getProjectRoot(),l=kze(a);if(r!==void 0&&l!==r)continue;let c=i.getPermissionManager?.();if(c)try{let u=o.get(l);u||(u=_z(qi(a).merged),o.set(l,u));let A=i.getPermissionsBeyondSettings?.(),g=jOt(c);for(let d of zOt){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){Kl.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??bze(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?ry(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=ry(y,d.authType),b=a===d.authType&&i&&(s===y||s===d.id||l===B),w={modelId:B,baseModelId:pze(y),name:d.label,...d.description!==void 0?{description:d.description}:{},contextLimit:d.contextWindowSize??Fj(y),...d.modalities!==void 0?{modalities:d.modalities}:{},...d.baseUrl!==void 0?{baseUrl:JN(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:Fz,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...A?{baseUrl:JN(A)}:{},...g?{fastModelId:g}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:Fz,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 nte(n.getConfig());return{v:Fz,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 pPt(t.sourceUrl),o=no.join(Ft.getGlobalMatildaDir(),"skills"),s=Fze(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 yl.rm(l,{recursive:!0,force:!0});for(let c of r.files){let u=mPt(l,c.relativePath);await yl.mkdir(no.dirname(u),{recursive:!0}),await yl.writeFile(u,c.content)}await yl.rm(s,{recursive:!0,force:!0}),await yl.rename(l,s)}catch(c){throw await yl.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 yl.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=Fze(no.join(Ft.getGlobalMatildaDir(),"skills"),t),u=no.join(c,"SKILL.md"),A=await yl.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 yl.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 qOt){let i=no.join(o,s,YOt),c=(await r.loadSkillsFromDir(i,"project")).find(A=>A.name===t)?.filePath;if(!c)continue;let u=await yl.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=ZOt(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 yl.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=Np(n.description,"description");if(i.length>zk)throw ze.invalidParams(void 0,"Bug description is too long");return{...await cb({description:i,envSummary:`${process.platform}/${process.arch}`})}}case dze:{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(qi(o));return{providers:DR.map(a=>DPt(a,i))}}case"matilda/providers/connect":{let i=Np(n.providerId,"providerId"),a=Mre(i);if(!a)throw ze.invalidParams(void 0,`Unknown provider: ${i}`);let l=qi(o),c=SPt(a,n,IPt(a,l.merged)),u=BPt(n.scope),A=sA(a,c);return await qh(A,{settings:bC(l,u),reloadModelProviders:g=>{let d=kk({...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($Ot(n));case"matilda/skills/delete":return this.deleteGlobalSkill(VOt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(KOt(n),r);case"matilda/settings/getMemory":{let i=qi(o);return this.settings=i,{settings:Mze(this.effectiveSettings(i).memory)}}case"matilda/settings/setMemory":{let i=Zs(n.updates),a=qi(o);for(let l of JOt)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:Mze(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 LPt({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 Doe():await Ioe(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 Yoe({scope:a,projectRoot:i,relativePath:l}),{deleted:!0}}case rte.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case rte.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 ote.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 iv(qi(o),o,async()=>new pi(o).removeSession(i))}}case ote.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>IR)throw ze.invalidParams(void 0,`Title too long (max ${IR} 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 iv(qi(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);Kl.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=Hze.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:Nz,sessionId:i,...c,runtime:A};if(!this.transcriptUpdatesNegotiated)throw ze.invalidParams(void 0,"Transcript updates were not negotiated");let g=c.mode==="delta"?POt(n.projection,a.data):void 0,d=c.mode==="snapshot"||g&&!UOt(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 rB({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:Nz,sessionId:i,mode:m?"delta":"snapshot",cursor:d.cursor,updates:Rze(y),transcriptRecords:vze(B),...d.cursor?{projection:Tze({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 iv(qi(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 rB(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),Kl.warn("[loadUpdates] History replay failed for session %s (partial updates: %d):",i,c.length,y)}let d=l.transcriptCursor,m=Are(l.conversation.messages),E=m.kind==="v2"?Bz(m.payload.snapshot):null;return{updates:Rze(c),transcriptRecords:vze(l.conversation.messages),...E?{goal:E}:{},...this.transcriptUpdatesNegotiated&&d&&g?{transcript:d,projection:Tze({v:1,cursor:d,continuation:g,usage:u.cumulativeUsage})}:{},startTime:l.conversation.startTime,lastUpdated:l.conversation.lastUpdated,...A!==void 0?{partial:!0,replayError:A}:{}}}case"matilda/session/appendHistory":{let i=Vt.object({sessionId:Vt.string().regex(s),messages:Vt.array(Vt.object({id:Vt.string().uuid(),role:Vt.enum(["user","assistant"]),content:Vt.string(),timestamp:Vt.number().finite().min(0).max(864e13)}))}).safeParse(n);if(!i.success)throw 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 cze:return this.matildaAccountState?.cancelSignIn(),{};case"getAccountInfo":{let i=n.sessionId,a=i?this.sessions.get(i):void 0;if(i!=null&&!a)throw ze.invalidParams(void 0,"The selected session is no longer available.");let 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?JN(c.baseUrl):null,organizationId:l.getOrganizationId()??null,apiKeyEnvKey:c?.apiKeyEnvKey??null,account:uze(c?.baseUrl,l.getChannel()),signInBaseUrl:JN(bO(this.effectiveSettings(qi(o))))}}case"matilda/settings/getCore":{let i=qi(o);return this.settings=i,this.buildCoreSettings(i,o)}case"matilda/settings/setCoreValue":{let i=n.key;if(typeof i!="string"||!zze.includes(i))throw ze.invalidParams(void 0,"Unsupported Matilda setting key");let a=qi(o),l=i,c=bPt(l,n.value),u=oB(n.scope);return a.setValue(u,i,c),l==="general.outputLanguage"&&typeof c=="string"&&u==="User"&&i6(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=qi(o),l=oB(n.scope),c=l==="Workspace"?"workspace":"user",u=Oz(a,c),A=Zs(u.mcpServers),g=Zs(A[i.trim()]),d={...A,[i.trim()]:{...vPt(g),...RPt(MPt(wPt(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=qi(o),l=oB(n.scope),c=l==="Workspace"?"workspace":"user",u=Oz(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(!Lze(i))throw ze.invalidParams(void 0,"Invalid hook event");let a=qi(o),l=oB(n.scope),c=l==="Workspace"?"workspace":"user",u=Oz(a,c),A={...Zs(u.hooks)},g=Array.isArray(A[i])?[...A[i]]:[],d=eje(n.hook),m=n.index,E=typeof m=="number"&&Number.isInteger(m)&&m>=0&&m<g.length,y=NPt(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(!Lze(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=qi(o),c=oB(n.scope),u=c==="Workspace"?"workspace":"user",A=Oz(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=qi(o),u=new ic({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=oB(n.scope)==="Workspace"?"workspace":"user";return await B_(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=WOt(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=OPt(d);if(m){let B={};for(let{name:b,value:w}of m.env)B[b]=w;l[m.name]=new T_(m.command,m.args,B,t);continue}let E=PPt(d);if(E){let B={};for(let{name:b,value:w}of E.headers)B[b]=w;l[E.name]=new T_(void 0,void 0,void 0,void 0,E.url,void 0,Object.keys(B).length>0?B:void 0);continue}let y=UPt(d);if(y){let B={};for(let{name:b,value:w}of y.headers)B[b]=w;l[y.name]=new T_(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 Fk(c,u,t,void 0,{userHooks:r.getUserHooks(),projectHooks:r.getProjectHooks()},Mk(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.
933
+ ${r}`}var Wze=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function qze(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(!Wze.has(t.hostname))throw ze.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function Yze(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 ePt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function tPt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function ite(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 nPt(e,t){let n=ite(e,t+124,12);return n?Number.parseInt(n,8):0}function rPt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function oPt(e,t){let n=ite(e,t,100),r=ite(e,t+345,155);return r?`${r}/${n}`:n}function sPt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var VN=100*1024*1024,Jze=500*1024*1024,iPt=16,aPt=2e3,Pz=class extends Error{};async function lPt(e,t,n={}){let r=n.maxCompressedBytes??VN,o=n.maxDecompressedBytes??Jze;if(e.length>r)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await MOt(Pze.from([Buffer.from(e)]),NOt(),new Uze({write(A,g,d){if(u+=A.length,u>o){d(new Pz);return}c.push(A),d()}})),s=Buffer.concat(c)}catch(c){throw c instanceof Pz?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&&!rPt(s,c);){let u=oPt(s,c),A=String.fromCharCode(s[c+156]||0),g=nPt(s,c),d=c+512,m=d+Math.ceil(g/512)*512;if(A==="0"||A==="\0"){let E=sPt(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 cPt=[".githubusercontent.com",".github.com"];function uPt(e){return Wze.has(e)?!0:cPt.some(t=>e.endsWith(t))}async function ute(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:"||!uPt(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 $ze(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 Vze(e){let t=await ute(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>VN)throw ze.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return $ze(t,VN)}async function dPt(e){let t=Yze(e),n=t?ePt(t):e,r=await Vze(n);return{skillContent:Buffer.from(r).toString("utf8"),files:[{relativePath:"SKILL.md",content:r}]}}async function APt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,r=await ute(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>VN)throw ze.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return lPt(await $ze(r,VN),t)}async function fPt(e,t){let n=tPt(t),r=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,o=await ute(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 Kze(e,t,n="",r=0,o={files:0,bytes:0}){if(r>iPt)throw ze.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await fPt(e,t),i=[];for(let a of s){let l=Zs(a),c=Np(l.name,"github.name"),u=Np(l.path,"github.path"),A=Np(l.type,"github.type"),g=n?no.posix.join(n,c):c;if(A==="dir"){i.push(...await Kze(e,u,g,r+1,o));continue}if(A!=="file")continue;if(o.files+=1,o.files>aPt)throw ze.invalidParams(void 0,"Skill directory contains too many files");let d=Np(l.download_url,"github.download_url");qze(d);let m=await Vze(d);if(o.bytes+=m.length,o.bytes>Jze)throw ze.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:g,content:m})}return i}async function gPt(e,t){let n=await Kze(e,t).catch(r=>(Kl.warn("GitHub API directory listing failed, falling back to archive download:",r),null));return n||APt(e,t)}async function pPt(e){qze(e);let t=Yze(e);if(!t||no.posix.basename(t.filePath)!=="SKILL.md")return dPt(e);let n=no.posix.dirname(t.filePath),r=await gPt(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 mPt(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 Fze(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 hPt(e){return typeof Zs(e).id=="string"}function CPt(e,t){if(!t)return;let r=Zs(e.env)[t];return typeof r=="string"&&r.length>0?r:void 0}function EPt(e,t){let r=Zs(e.modelProviders)[t];return Array.isArray(r)?r.filter(hPt):[]}function Xze(e,t){return EPt(t,e.protocol).filter(u_(e))}function Zze(e,t,n){let r=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:xu(e),o=typeof n[0]?.envKey=="string"?n[0].envKey:e.envKey;return Z1(r)??CPt(t,o)}function yPt(e,t){let n=Xze(e,t),r=Zze(e,t,n);if(!r&&n.length===0)return;let o=typeof n[0]?.baseUrl=="string"?n[0].baseUrl:xu(e);return{baseUrl:JN(o),...r?{hasApiKey:!0}:{},...n.length>0?{modelIds:n.map(s=>s.id)}:{}}}function IPt(e,t){return Zze(e,t,Xze(e,t))}function DPt(e,t){let n=yPt(e,t);return{id:e.id,label:e.label,description:e.description,protocol:e.protocol,baseUrl:e.baseUrl,defaultModelIds:Qre(e),models:e.models,documentationUrl:e.documentationUrl,...n?{existingConfig:n}:{}}}function SPt(e,t,n){let r=xu(e),o=iy(t.apiKey,"apiKey")??n;if(!o)throw ze.invalidParams(void 0,"Invalid or missing apiKey");return{baseUrl:r,apiKey:o}}function BPt(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 xPt(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 ste(e){let t={};for(let n of zze){let r=xPt(e,n);r!==void 0&&(t[n]=r)}return t}function bPt(e,t){let n=Gze[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 sg(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 sB(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 $N(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 wPt(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=$N(t.timeout);if(i!==void 0&&(r.timeout=i),typeof t.trust=="boolean"&&(r.trust=t.trust),r.includeTools=sg(t.includeTools),r.excludeTools=sg(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=sg(t.args),r.env=sB(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=sB(t.headers),r}var TPt=new Set(["command","args","cwd","env","httpUrl","url","headers","timeout","trust","description","includeTools","excludeTools"]);function vPt(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!TPt.has(t)))}function RPt(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 QPt(e){let t=Zs(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:sB(t.headers),timeout:$N(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:sg(t.includeTools),excludeTools:sg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:sB(t.headers),timeout:$N(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:sg(t.includeTools),excludeTools:sg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:sg(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:sB(t.env),timeout:$N(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:sg(t.includeTools),excludeTools:sg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var Uz="__redacted__";function kPt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(r=>[r,Uz]));return{...e,env:t(e.env),headers:t(e.headers)}}function MPt(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!==Uz){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 Nze(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,Uz]))}function _ze(e,t){if(!e)return e;let n=Zs(t),r={};for(let[o,s]of Object.entries(e)){if(s!==Uz){r[o]=s;continue}let i=n[o];typeof i=="string"&&(r[o]=i)}return r}function FPt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:Nze(t.env)}:{},...t.headers?{headers:Nze(t.headers)}:{}}))}}function NPt(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:_ze(r.env,s.env)}:{},...r.headers?{headers:_ze(r.headers,s.headers)}:{}}})}}function qN(e,t){let n=Zs(e.mcpServers);return Object.entries(n).map(([r,o])=>{try{let s=QPt(o);return s?{name:r,scope:t,server:kPt(s)}:void 0}catch(s){Kl.warn(`Skipping malformed MCP server config [${t}:${r}]:`,s);return}}).filter(r=>!!r)}function Lze(e){return typeof e=="string"&&jze.includes(e)}function _Pt(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=sB(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=sB(t.headers),r.allowedEnvVars=sg(t.allowedEnvVars),typeof t.once=="boolean"&&(r.once=t.once)}let o=$N(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 eje(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(_Pt)};return typeof t.matcher=="string"&&(r.matcher=t.matcher),typeof t.sequential=="boolean"&&(r.sequential=t.sequential),r}function YN(e,t,n){let r=Zs(e.hooks),o=[];for(let s of jze){let i=r[s];Array.isArray(i)&&i.forEach((a,l)=>{try{o.push({event:s,scope:t,index:l,hook:FPt(eje(a)),extensionName:n})}catch(c){Kl.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return o}function oB(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw ze.invalidParams(void 0,"scope must be user or workspace")}function Oz(e,t){return e.forScope(oB(t)).settings}async function Oze(e,t){for(let n of dd()){let r=no.join(e,n);try{return await yl.access(r),r}catch{}}return no.join(e,t)}async function LPt(e){let t=dd()[0]??"MATILDA.md",n=await Oze(Ft.getGlobalMatildaDir(),t),r=await Oze(e.cwd,t),o=Uh(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:r,autoMemoryDir:o}}async function tje(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let r=Uze.toWeb(process.stdout),o=Pze.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=V8e(r,o),i,a=new Cz(m=>(i=new ate(e,t,n,m),i),s),l=async m=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(E){Kl.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){Kl.warn(`SessionEnd hook failed: ${v instanceof Error?v.message:String(v)}`)}}},g=async()=>{if(c)return;c=!0,Kl.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,vl().catch(E=>{Kl.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 OPt(e){if("command"in e&&"args"in e&&"env"in e)return e}function PPt(e){if("type"in e&&e.type==="sse")return e}function UPt(e){if("type"in e&&e.type==="http")return e}var ate=class{constructor(t,n,r,o){this.config=t;this.settings=n;this.argv=r;this.connection=o;this.mcpPool=new Goe(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)&&Kl.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Kl.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){Kl.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"&&Kl.debug(`Session shutdown failed: ${n.reason instanceof Error?n.reason.message:String(n.reason)}`)}effectiveSettings(t=this.settings){return kk(t.merged,this.argv.channel)}get matildaAccount(){return this.matildaAccountState??=new Iz({channel:this.config.getChannel(),connectionSignal:this.connection.signal,signInBaseUrl:()=>bO(this.effectiveSettings(qi(process.cwd()))),install:t=>I5(qi(process.cwd()),t)}),this.matildaAccountState}async initialize(t){this.clientCapabilities=t.clientCapabilities;let n=t.clientCapabilities?._meta?.[lte];this.transcriptReadNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.transcriptRead===Nz,this.transcriptUpdatesNegotiated=this.transcriptReadNegotiated&&n.transcriptUpdates===wze,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===Vee,this.compactionUpdatesNegotiated=t.clientCapabilities?.session?.compaction!=null,this.signInUrlNegotiated=!!n&&typeof n=="object"&&!Array.isArray(n)&&n.signInUrl===1;let r=nv(this.config);return{protocolVersion:vZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.22.1-preview.0"},authMethods:r,agentCapabilities:{...this.transcriptReadNegotiated||this.backgroundExecutionNegotiated||this.finalAnswersNegotiated||this.sessionNoticesNegotiated?{_meta:{matilda:{...this.transcriptReadNegotiated?{transcriptRead:Nz}:{},...this.transcriptUpdatesNegotiated?{transcriptUpdates:wze}:{},...this.backgroundExecutionNegotiated?{backgroundExecution:1}:{},...this.sessionStateNegotiated?{sessionState:1}:{},...this.finalAnswersNegotiated?{finalAnswers:1}:{},...this.sessionNoticesNegotiated?{sessionNotices:Vee}:{}}}}:{},loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0},...nB({channel:this.config.getChannel()})?{auth:{logout:{}}}:{}}}}async authenticate({methodId:t}){if(t===$ee&&nB({channel:this.config.getChannel()})){await this.matildaAccount.signIn(this.signInUrlNegotiated?r=>this.connection.extNotification(lze,{...r}):void 0);return}let n=Vt.nativeEnum(oA).parse(t);await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}async logout(){if(!nB({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:Qze(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=HOt(t),a=GOt(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:Qze(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 f0(r);o.contextMessage&&(n.pendingWorktreeNotice=o.contextMessage)}catch(r){Kl.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 iv(qi(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 Ph?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=qi(t),this.settings}buildPermissionSettings(t){return{user:{path:t.user.path,rules:_z(t.user.settings)},workspace:{path:t.workspace.path,rules:_z(t.workspace.settings)},merged:_z(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 ic({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await d.refreshCache(),i=d.getLoadedExtensions()}catch(d){Kl.warn("Extension loading failed, continuing without extensions:",d)}let a=await Promise.all(i.map(async d=>{let m=await A0(d.config,d.id,"user"),E=await A0(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,U=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:U,effectiveScope:z,hasUserValue:Q,hasWorkspaceValue:v}})}})),l=i.filter(d=>d.isActive),c=l.flatMap(d=>qN({mcpServers:d.config.mcpServers??{}},"extension").map(m=>({...m,server:{...m.server,extensionName:d.name}}))),u=l.flatMap(d=>YN({hooks:d.hooks??{}},"extension",d.name)),A=new Map;for(let d of qN(r,"user"))A.set(d.name,d);if(t.isTrusted)for(let d of qN(o,"workspace"))A.set(d.name,d);let g=[...YN(r,"user"),...t.isTrusted?YN(o,"workspace"):[]];return{user:{path:t.user.path,values:ste(r),mcpServers:qN(r,"user"),hooks:YN(r,"user")},workspace:{path:t.workspace.path,values:ste(o),mcpServers:qN(o,"workspace"),hooks:YN(o,"workspace")},merged:{values:ste(s),mcpServers:[...A.values(),...c],hooks:[...g,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){let r=t==="Workspace"?kze(n):void 0,o=new Map;for(let s of this.sessions.values()){let i=s.getConfig(),a=i.storage.getProjectRoot(),l=kze(a);if(r!==void 0&&l!==r)continue;let c=i.getPermissionManager?.();if(c)try{let u=o.get(l);u||(u=_z(qi(a).merged),o.set(l,u));let A=i.getPermissionsBeyondSettings?.(),g=jOt(c);for(let d of zOt){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){Kl.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??bze(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?ry(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=ry(y,d.authType),b=a===d.authType&&i&&(s===y||s===d.id||l===B),w={modelId:B,baseModelId:pze(y),name:d.label,...d.description!==void 0?{description:d.description}:{},contextLimit:d.contextWindowSize??Fj(y),...d.modalities!==void 0?{modalities:d.modalities}:{},...d.baseUrl!==void 0?{baseUrl:JN(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:Fz,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...A?{baseUrl:JN(A)}:{},...g?{fastModelId:g}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:Fz,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 nte(n.getConfig());return{v:Fz,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 pPt(t.sourceUrl),o=no.join(Ft.getGlobalMatildaDir(),"skills"),s=Fze(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 yl.rm(l,{recursive:!0,force:!0});for(let c of r.files){let u=mPt(l,c.relativePath);await yl.mkdir(no.dirname(u),{recursive:!0}),await yl.writeFile(u,c.content)}await yl.rm(s,{recursive:!0,force:!0}),await yl.rename(l,s)}catch(c){throw await yl.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 yl.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=Fze(no.join(Ft.getGlobalMatildaDir(),"skills"),t),u=no.join(c,"SKILL.md"),A=await yl.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 yl.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 qOt){let i=no.join(o,s,YOt),c=(await r.loadSkillsFromDir(i,"project")).find(A=>A.name===t)?.filePath;if(!c)continue;let u=await yl.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=ZOt(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 yl.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=Np(n.description,"description");if(i.length>zk)throw ze.invalidParams(void 0,"Bug description is too long");return{...await cb({description:i,envSummary:`${process.platform}/${process.arch}`})}}case dze:{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(qi(o));return{providers:DR.map(a=>DPt(a,i))}}case"matilda/providers/connect":{let i=Np(n.providerId,"providerId"),a=Mre(i);if(!a)throw ze.invalidParams(void 0,`Unknown provider: ${i}`);let l=qi(o),c=SPt(a,n,IPt(a,l.merged)),u=BPt(n.scope),A=sA(a,c);return await qh(A,{settings:bC(l,u),reloadModelProviders:g=>{let d=kk({...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($Ot(n));case"matilda/skills/delete":return this.deleteGlobalSkill(VOt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(KOt(n),r);case"matilda/settings/getMemory":{let i=qi(o);return this.settings=i,{settings:Mze(this.effectiveSettings(i).memory)}}case"matilda/settings/setMemory":{let i=Zs(n.updates),a=qi(o);for(let l of JOt)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:Mze(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 LPt({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 Doe():await Ioe(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 Yoe({scope:a,projectRoot:i,relativePath:l}),{deleted:!0}}case rte.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case rte.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 ote.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 iv(qi(o),o,async()=>new pi(o).removeSession(i))}}case ote.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>IR)throw ze.invalidParams(void 0,`Title too long (max ${IR} 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 iv(qi(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);Kl.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=Hze.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:Nz,sessionId:i,...c,runtime:A};if(!this.transcriptUpdatesNegotiated)throw ze.invalidParams(void 0,"Transcript updates were not negotiated");let g=c.mode==="delta"?POt(n.projection,a.data):void 0,d=c.mode==="snapshot"||g&&!UOt(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 rB({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:Nz,sessionId:i,mode:m?"delta":"snapshot",cursor:d.cursor,updates:Rze(y),transcriptRecords:vze(B),...d.cursor?{projection:Tze({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 iv(qi(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 rB(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),Kl.warn("[loadUpdates] History replay failed for session %s (partial updates: %d):",i,c.length,y)}let d=l.transcriptCursor,m=Are(l.conversation.messages),E=m.kind==="v2"?Bz(m.payload.snapshot):null;return{updates:Rze(c),transcriptRecords:vze(l.conversation.messages),...E?{goal:E}:{},...this.transcriptUpdatesNegotiated&&d&&g?{transcript:d,projection:Tze({v:1,cursor:d,continuation:g,usage:u.cumulativeUsage})}:{},startTime:l.conversation.startTime,lastUpdated:l.conversation.lastUpdated,...A!==void 0?{partial:!0,replayError:A}:{}}}case"matilda/session/appendHistory":{let i=Vt.object({sessionId:Vt.string().regex(s),messages:Vt.array(Vt.object({id:Vt.string().uuid(),role:Vt.enum(["user","assistant"]),content:Vt.string(),timestamp:Vt.number().finite().min(0).max(864e13)}))}).safeParse(n);if(!i.success)throw 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 cze:return this.matildaAccountState?.cancelSignIn(),{};case"getAccountInfo":{let i=n.sessionId,a=i?this.sessions.get(i):void 0;if(i!=null&&!a)throw ze.invalidParams(void 0,"The selected session is no longer available.");let 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?JN(c.baseUrl):null,organizationId:l.getOrganizationId()??null,apiKeyEnvKey:c?.apiKeyEnvKey??null,account:uze(c?.baseUrl,l.getChannel()),signInBaseUrl:JN(bO(this.effectiveSettings(qi(o))))}}case"matilda/settings/getCore":{let i=qi(o);return this.settings=i,this.buildCoreSettings(i,o)}case"matilda/settings/setCoreValue":{let i=n.key;if(typeof i!="string"||!zze.includes(i))throw ze.invalidParams(void 0,"Unsupported Matilda setting key");let a=qi(o),l=i,c=bPt(l,n.value),u=oB(n.scope);return a.setValue(u,i,c),l==="general.outputLanguage"&&typeof c=="string"&&u==="User"&&i6(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=qi(o),l=oB(n.scope),c=l==="Workspace"?"workspace":"user",u=Oz(a,c),A=Zs(u.mcpServers),g=Zs(A[i.trim()]),d={...A,[i.trim()]:{...vPt(g),...RPt(MPt(wPt(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=qi(o),l=oB(n.scope),c=l==="Workspace"?"workspace":"user",u=Oz(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(!Lze(i))throw ze.invalidParams(void 0,"Invalid hook event");let a=qi(o),l=oB(n.scope),c=l==="Workspace"?"workspace":"user",u=Oz(a,c),A={...Zs(u.hooks)},g=Array.isArray(A[i])?[...A[i]]:[],d=eje(n.hook),m=n.index,E=typeof m=="number"&&Number.isInteger(m)&&m>=0&&m<g.length,y=NPt(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(!Lze(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=qi(o),c=oB(n.scope),u=c==="Workspace"?"workspace":"user",A=Oz(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=qi(o),u=new ic({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=oB(n.scope)==="Workspace"?"workspace":"user";return await B_(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=WOt(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=OPt(d);if(m){let B={};for(let{name:b,value:w}of m.env)B[b]=w;l[m.name]=new T_(m.command,m.args,B,t);continue}let E=PPt(d);if(E){let B={};for(let{name:b,value:w}of E.headers)B[b]=w;l[E.name]=new T_(void 0,void 0,void 0,void 0,E.url,void 0,Object.keys(B).length>0?B:void 0);continue}let y=UPt(d);if(y){let B={};for(let{name:b,value:w}of y.headers)B[b]=w;l[y.name]=new T_(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 Fk(c,u,t,void 0,{userHooks:r.getUserHooks(),projectHooks:r.getProjectHooks()},Mk(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.
934
934
  `),A}async ensureAuthenticated(t){let n=t.getModelsConfig().getCurrentAuthType();if(!n)throw ze.authRequired({authMethods:nv(t)},"Use Matilda CLI to authenticate first.");try{await t.refreshAuth(n)}catch(r){throw Kl.error(`Authentication failed: ${r}`),ze.authRequired({authMethods:nv(t)},"Authentication failed: "+r.message)}}setupFileSystem(t){if(!this.clientCapabilities?.fs)return;let n=new Dz(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 Mz(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?ry(s.id,s.authType):this.formatCurrentModelId(n,r),a=o.map(l=>{let c=l.isRuntimeModel&&l.runtimeSnapshotId?l.runtimeSnapshotId:l.id;return{modelId:ry(c,l.authType),name:l.label,description:l.description??null,_meta:{contextLimit:l.contextWindowSize??Fj(l.id)}}});return{currentModelId:i,availableModels:a}}buildModesData(t){let n=t.getApprovalMode(),r=ac.map(o=>({id:o,name:bR[o].name,description:bR[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?ry(i.id,i.authType):this.formatCurrentModelId(o,s),l=ac.map(g=>({value:g,name:bR[g].name,description:bR[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:ry(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?ry(t,n):t)}};var jd=M(ie(),1);var ay=Ke("STARTUP");function dte(){delete process.env[nx],delete process.env[rx]}function WPt(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 qPt(e){let t=GPt.totalmem()/1048576,n=jPt.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 YPt(){let e=!1;process.on("unhandledRejection",(t,n)=>{let r=`=========================================
935
935
  This is an unexpected error. Please file a bug report using the /bug tool.
936
936
  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.1-nightly.20261104.f4c27782c",
3
+ "version": "0.22.1-preview.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "cli.js",
@@ -26,7 +26,7 @@
26
26
  "bundled"
27
27
  ],
28
28
  "config": {
29
- "sandboxImageUri": "ghcr.io/maincode/matilda-code:0.22.1-nightly.20261104.f4c27782c"
29
+ "sandboxImageUri": "ghcr.io/maincode/matilda-code:0.22.1-preview.0"
30
30
  },
31
31
  "dependencies": {},
32
32
  "optionalDependencies": {