makecoder 3.0.1 → 3.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cc.mjs CHANGED
@@ -20,13 +20,13 @@ import{createRequire as vP5}from"node:module";var MP5=Object.create;var{getProto
20
20
  Object.assign(A, {
21
21
  post(...args) {
22
22
  const [url, payload, ...remainArgs] = args;
23
- const patchedUrl = url + (url.includes('?') ? '&' : ':') + '&app=codev-cli' + '&version=3.0.1' + '&session_id=' + I8();
23
+ const patchedUrl = url + (url.includes('?') ? '&' : ':') + '&app=codev-cli' + '&version=3.0.2' + '&session_id=' + I8();
24
24
  if (process.env.CODEV_AUTH_SK && process.env.CODEV_AUTH_AK) {
25
25
  const headerValues = payload.headers.values;
26
26
  headerValues.set('AUTHORIZATION', `Bearer ${process.env.CODEV_AUTH_AK}.${process.env.CODEV_AUTH_SK}`)
27
27
  }
28
28
 
29
- payload.headers.values.set('X-Coder-Version', '3.0.1');
29
+ payload.headers.values.set('X-Coder-Version', '3.0.2');
30
30
  payload.headers.values.set('X-Coder-Platform', process.platform);
31
31
  payload.headers.values.set('X-Coder-Arch', process.arch);
32
32
 
package/dist/coder.js CHANGED
@@ -132,7 +132,7 @@ var gt=Object.create;var ge=Object.defineProperty;var mt=Object.getOwnPropertyDe
132
132
  `);try{let r=(await import("open")).default;await r(s)}catch(r){console.warn("\u26A0\uFE0F \u65E0\u6CD5\u81EA\u52A8\u6253\u5F00\u6D4F\u89C8\u5668,\u8BF7\u624B\u52A8\u590D\u5236\u4E0A\u8FF0\u94FE\u63A5\u5230\u6D4F\u89C8\u5668\u6253\u5F00"),process.env.CODEV_DEBUG&&console.error("Browser open error:",r)}let o=await this.callbackServer.waitForCallback(e);return console.log(`\u2705 API Key \u83B7\u53D6\u6210\u529F!
133
133
  `),o}catch(t){throw console.error(`
134
134
  \u274C OAuth \u767B\u5F55\u5931\u8D25: ${t.message}
135
- `),t}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};we.exports=Y});var A=m((Cs,xt)=>{xt.exports={name:"makecoder",version:"3.0.1",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var ve=m((Is,be)=>{var _=require("fs"),Ce=require("path"),$t=require("os"),Ie=require("readline"),Dt=Se(),Pt=new Set(["login","skills","wiki","channel"]),Ee=new Set(["claude","gemini","codex"]),_t=new Set(["pub","login","update","skills","wiki","channel"]),X=class{constructor(){let e=process.env.CODER_PROFILE,t=e?`.coder.${e}`:".coder";this.configPath=Ce.join($t.homedir(),t,"config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}loadConfig(){let e=Ce.dirname(this.configPath);try{return _.existsSync(e)||_.mkdirSync(e,{recursive:!0}),_.existsSync(this.configPath)||_.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2)),JSON.parse(_.readFileSync(this.configPath,"utf8"))}catch{return{...this.defaultConfig}}}saveAuthToConfig(e,t){let s=this.loadConfig();s.auth={...s.auth,ak:e,sk:t};try{return _.writeFileSync(this.configPath,JSON.stringify(s,null,2)),!0}catch{return!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth={ak:null,sk:null});try{return _.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch{return!1}}promptForAKSK(){let e=Ie.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{console.log(`
135
+ `),t}finally{this.callbackServer&&this.callbackServer.cleanup()}}cleanup(){this.callbackServer&&this.callbackServer.cleanup()}};we.exports=Y});var A=m((Cs,xt)=>{xt.exports={name:"makecoder",version:"3.0.2",description:"MakeCoder: Unified AI agent CLI tool integrating Claude Code, Codex and Gemini CLI",main:"./dist/coder.js",bin:{coder:"./dist/coder.js"},scripts:{test:'echo "Error: no test specified" && exit 1',start:"node ./src/coder.js",build:"node scripts/build.js","build:clean":"node scripts/build.js --clean","build:dev":"node scripts/build.js --no-minify --sourcemap",postinstall:"node scripts/postinstall.js"},keywords:["cli","ai","claude","gemini","codex","agent"],author:"makecoder",license:"MIT",repository:{type:"git",url:"https://github.com/makecoderai/coder.git"},homepage:"https://github.com/makecoderai/coder",dependencies:{"node-fetch":"^3.3.2",open:"^10.1.0",zod:"^3.25.76"},optionalDependencies:{"makecoder-codex-linux-x64":"*","makecoder-codex-darwin-arm64":"*","makecoder-codex-win32-x64":"*"},engines:{node:">=20.0.0"},devDependencies:{chokidar:"^4.0.3"},files:["dist","claude","scripts/postinstall.js"]}});var ve=m((Is,be)=>{var _=require("fs"),Ce=require("path"),$t=require("os"),Ie=require("readline"),Dt=Se(),Pt=new Set(["login","skills","wiki","channel"]),Ee=new Set(["claude","gemini","codex"]),_t=new Set(["pub","login","update","skills","wiki","channel"]),X=class{constructor(){let e=process.env.CODER_PROFILE,t=e?`.coder.${e}`:".coder";this.configPath=Ce.join($t.homedir(),t,"config.json"),this.defaultConfig={agent:"claude",auth:{ak:null,sk:null}}}loadConfig(){let e=Ce.dirname(this.configPath);try{return _.existsSync(e)||_.mkdirSync(e,{recursive:!0}),_.existsSync(this.configPath)||_.writeFileSync(this.configPath,JSON.stringify(this.defaultConfig,null,2)),JSON.parse(_.readFileSync(this.configPath,"utf8"))}catch{return{...this.defaultConfig}}}saveAuthToConfig(e,t){let s=this.loadConfig();s.auth={...s.auth,ak:e,sk:t};try{return _.writeFileSync(this.configPath,JSON.stringify(s,null,2)),!0}catch{return!1}}clearAuthFromConfig(){let e=this.loadConfig();e.auth&&(e.auth={ak:null,sk:null});try{return _.writeFileSync(this.configPath,JSON.stringify(e,null,2)),!0}catch{return!1}}promptForAKSK(){let e=Ie.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{console.log(`
136
136
  \u{1F510} \u8BF7\u8F93\u5165\u60A8\u7684 API Key\uFF1A`),e.question("\u8BF7\u8F93\u5165 API Key: ",o=>{e.close();let r=o.indexOf(".");if(r<=0||r===o.length-1)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));let n=o.substring(0,r).trim(),i=o.substring(r+1).trim();if(!n||!i)return s(new Error("\u683C\u5F0F\u9519\u8BEF"));t({ak:n,sk:i})})})}promptForName(){let e=Ie.createInterface({input:process.stdin,output:process.stdout});return new Promise((t,s)=>{e.question("\u8BF7\u8F93\u5165\u9879\u76EE\u540D\u79F0 (name): ",o=>{e.close();let r=o.trim();if(!r)return s(new Error("\u9879\u76EE\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A"));if(!/^[a-zA-Z0-9_-]+$/.test(r))return s(new Error("\u9879\u76EE\u540D\u79F0\u53EA\u80FD\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u4E0B\u5212\u7EBF\u548C\u8FDE\u5B57\u7B26"));t(r)})})}async parse(e=process.argv.slice(2)){let t=this.loadConfig(),s={agent:t.agent||"claude",remainingArgs:[]},o=0;if(e.length>0){if(Ee.has(e[0]))s.agent=e[0],s.agentSetBySubcommand=!0,o=1;else if(_t.has(e[0])){if(s.command=e[0],o=1,e[0]==="skills"){let n=e[1];s.skillsSubcommand=n==="--help"||n==="-h"?void 0:n,s.skillsArg=e[2],s.skillsRemainingArgs=e.slice(2),o=e.length}else if(e[0]==="wiki"){let n=e[1];s.wikiSubcommand=n==="--help"||n==="-h"?void 0:n,s.wikiArg=e[2],s.wikiRemainingArgs=e.slice(2),o=e.length}else if(e[0]==="channel"){let n=e[1];n==="--help"||n==="-h"?s.channelSubcommand="--help":n==="list"||n==="show"||n==="add"||n==="remove"||n==="update"?(s.channelSubcommand=n,s.channelArg=e[2],s.channelRemainingArgs=e.slice(2)):s.channelRemainingArgs=e.slice(1),o=e.length}}}for(;o<e.length;){let n=e[o];if(n==="--agent"){if(s.agentSetBySubcommand)throw new Error(`\u4E0D\u80FD\u540C\u65F6\u4F7F\u7528\u5B50\u547D\u4EE4 '${s.agent}' \u548C --agent\uFF0C\u8BF7\u9009\u62E9\u5176\u4E00`);let i=e[o+1];if(!i||!Ee.has(i))throw new Error("--agent \u9700\u8981\u6307\u5B9A\u4EE3\u7406\u7C7B\u578B\uFF08claude|gemini|codex\uFF09");s.agent=i,o+=2}else if(n==="--apikey"||n==="--aksk"){let i=e[o+1];if(!i||i.startsWith("--"))s.needAKSKPrompt=!0,o+=1;else{let a=i.indexOf(".");if(a===-1)throw new Error("API Key \u683C\u5F0F\u9519\u8BEF\uFF0C\u5E94\u4E3A <ak>.<sk>");s.auth_ak=i.substring(0,a),s.auth_sk=i.substring(a+1),o+=2}}else if(n==="--save-auth")s.saveAuth=!0,o+=1;else if(n==="--clear-auth")s.clearAuth=!0,o+=1;else if(n==="--name"){let i=e[o+1];i&&!i.startsWith("--")?(s.pubName=i,o+=2):o+=1}else if(n==="--allow-clone")s.allowClone=!0,o+=1;else if(n==="--meta-data"){let i=e[o+1];if(!i||i.startsWith("--"))throw new Error("--meta-data \u9700\u8981\u4E00\u4E2A JSON \u5B57\u7B26\u4E32\u503C");try{JSON.parse(i)}catch(a){throw new Error(`--meta-data \u4E0D\u662F\u5408\u6CD5\u7684 JSON\uFF1A${a.message}`)}s.pubMetaData=i,o+=2}else{s.remainingArgs=e.slice(o);break}}if(s.needAKSKPrompt)try{let{ak:n,sk:i}=await this.promptForAKSK();s.auth_ak=n,s.auth_sk=i,delete s.needAKSKPrompt}catch(n){console.error(`\u274C ${n.message}`),process.exit(1)}s.clearAuth&&(console.log(this.clearAuthFromConfig()?"\u2705 API Key \u5DF2\u4ECE\u914D\u7F6E\u6587\u4EF6\u6E05\u9664":"\u274C \u6E05\u9664 API Key \u5931\u8D25"),process.exit(0)),s.saveAuth&&s.auth_ak&&s.auth_sk&&(console.log(this.saveAuthToConfig(s.auth_ak,s.auth_sk)?"\u2705 API Key \u5DF2\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6":"\u274C \u4FDD\u5B58 API Key \u5931\u8D25"),process.exit(0)),s.command!=="login"&&(s.auth_ak||=t.auth?.ak||process.env.CODEV_AUTH_AK,s.auth_sk||=t.auth?.sk||process.env.CODEV_AUTH_SK),s.codevServer=process.env.CODEV_SERVER||t.codevServer||"https://makecoder.com/bigapis/codev/v1";let r=s.remainingArgs.includes("--version")||s.remainingArgs.includes("-v")||s.remainingArgs.includes("--help")||s.remainingArgs.includes("-h");return!Pt.has(s.command)&&!r&&(!s.auth_ak||!s.auth_sk)&&await this._oauthLogin(s),s}async _oauthLogin(e){console.log(`\u274C \u7F3A\u5C11\u5FC5\u8981\u7684 API Key
137
137
  `),console.log(`\u{1F510} \u6B63\u5728\u542F\u52A8\u767B\u5F55\u6D41\u7A0B...
138
138
  `);try{let s=await new Dt({baseUrl:"https://makecoder.com",apiBaseUrl:e.codevServer}).login();e.auth_ak=s.ak,e.auth_sk=s.sk,console.log(this.saveAuthToConfig(s.ak,s.sk)?`\u2705 API Key \u5DF2\u81EA\u52A8\u4FDD\u5B58\u5230\u914D\u7F6E\u6587\u4EF6
package/dist/codex.mjs CHANGED
@@ -15,9 +15,9 @@ const __dirname = path.dirname(__filename);
15
15
  const require = createRequire(import.meta.url);
16
16
 
17
17
  const PLATFORM_PACKAGE = {
18
- "linux-x64": "makecoder-codex-linux-x64",
18
+ "linux-x64": "makecoder-codex-linux-x64",
19
19
  "darwin-arm64": "makecoder-codex-darwin-arm64",
20
- "win32-x64": "makecoder-codex-win32-x64",
20
+ "win32-x64": "makecoder-codex-win32-x64",
21
21
  };
22
22
 
23
23
  const { platform, arch } = process;
@@ -34,7 +34,11 @@ const platformPackage = PLATFORM_PACKAGE[platformKey];
34
34
  let binaryPath = null;
35
35
  try {
36
36
  const pkgJsonPath = require.resolve(`${platformPackage}/package.json`);
37
- const candidate = path.join(path.dirname(pkgJsonPath), "bin", codexBinaryName);
37
+ const candidate = path.join(
38
+ path.dirname(pkgJsonPath),
39
+ "bin",
40
+ codexBinaryName,
41
+ );
38
42
  if (existsSync(candidate)) {
39
43
  binaryPath = candidate;
40
44
  }
@@ -53,26 +57,19 @@ if (!binaryPath) {
53
57
  if (!binaryPath) {
54
58
  throw new Error(
55
59
  `Codex binary not found for ${platformKey}.\n` +
56
- `Expected sub-package ${platformPackage} to be installed.\n` +
57
- `Try reinstalling: npm install -g makecoder@latest`
60
+ `Expected sub-package ${platformPackage} to be installed.\n` +
61
+ `Try reinstalling: npm install -g makecoder@latest`,
58
62
  );
59
63
  }
60
64
 
61
65
  // ---- process helpers ----
62
66
 
63
- function detectPackageManager() {
64
- const userAgent = process.env.npm_config_user_agent || "";
65
- if (/\bbun\//.test(userAgent)) return "bun";
66
- const execPath = process.env.npm_execpath || "";
67
- if (execPath.includes("bun")) return "bun";
68
- if (__dirname.includes(".bun/install/global") || __dirname.includes(".bun\\install\\global")) return "bun";
69
- return userAgent ? "npm" : null;
70
- }
71
-
72
67
  const env = { ...process.env };
73
- env[detectPackageManager() === "bun" ? "CODEX_MANAGED_BY_BUN" : "CODEX_MANAGED_BY_NPM"] = "1";
74
68
 
75
- const child = spawn(binaryPath, process.argv.slice(2), { stdio: "inherit", env });
69
+ const child = spawn(binaryPath, process.argv.slice(2), {
70
+ stdio: "inherit",
71
+ env,
72
+ });
76
73
 
77
74
  child.on("error", (err) => {
78
75
  console.error(err);
@@ -81,13 +78,23 @@ child.on("error", (err) => {
81
78
 
82
79
  const forwardSignal = (signal) => {
83
80
  if (child.killed) return;
84
- try { child.kill(signal); } catch { /* ignore */ }
81
+ try {
82
+ child.kill(signal);
83
+ } catch {
84
+ /* ignore */
85
+ }
85
86
  };
86
- ["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => process.on(sig, () => forwardSignal(sig)));
87
+ ["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) =>
88
+ process.on(sig, () => forwardSignal(sig)),
89
+ );
87
90
 
88
91
  const childResult = await new Promise((resolve) => {
89
92
  child.on("exit", (code, signal) => {
90
- resolve(signal ? { type: "signal", signal } : { type: "code", exitCode: code ?? 1 });
93
+ resolve(
94
+ signal
95
+ ? { type: "signal", signal }
96
+ : { type: "code", exitCode: code ?? 1 },
97
+ );
91
98
  });
92
99
  });
93
100
 
@@ -814,7 +814,7 @@ ${s}
814
814
 
815
815
  ... [${u.toLocaleString()} characters omitted] ...
816
816
 
817
- ${c}`}var bbr="tool-outputs";async function PS(t,e,r,n,o){let s=Nu(e).toLowerCase(),c=Nu(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=ku.join(n,bbr);if(o){let a=Nu(o);d=ku.join(d,`session-${a}`)}let l=ku.join(d,u);return await px.mkdir(d,{recursive:!0}),await px.writeFile(l,t),{outputFile:l}}async function ZZe(t,e){await Ya();let r=[t,...e].join(" "),n=Gc(r),o=Xm(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:Uq.basename(t)}function gx(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var oh=["run_shell_command","ShellTool"];async function tet(t){if(Uq.isAbsolute(t))try{return await Mq.promises.access(t,Mq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(Uq.delimiter),r=JZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=Uq.join(n,t+o);try{return await Mq.promises.access(s,Mq.constants.X_OK),s}catch{continue}}}var kS=null,Bq=null,hx=null,Fq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function Tbr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function Cbr(){try{hx=null;let[t,e]=await Promise.all([Tme(()=>import("./tree-sitter-N6IY6JNB.js"),"web-tree-sitter/tree-sitter.wasm"),Tme(()=>import("./tree-sitter-bash-4FEPBSIN.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await _me.init({wasmBinary:t}),kS=await Eme.load(e)}catch(t){kS=null;let e=Tbr(t),r=e instanceof Fq?e:new Fq(e);throw hx=r,r}}async function Ya(){Bq||(Bq=Cbr().catch(t=>{Bq=null,B.debug("Failed to initialize shell parsers:",t)})),await Bq}var ret="__GCLI_POWERSHELL_COMMAND__",wbr=1e3*1e3,xbr=Buffer.from(`
817
+ ${c}`}var bbr="tool-outputs";async function PS(t,e,r,n,o){let s=Nu(e).toLowerCase(),c=Nu(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=ku.join(n,bbr);if(o){let a=Nu(o);d=ku.join(d,`session-${a}`)}let l=ku.join(d,u);return await px.mkdir(d,{recursive:!0}),await px.writeFile(l,t),{outputFile:l}}async function ZZe(t,e){await Ya();let r=[t,...e].join(" "),n=Gc(r),o=Xm(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:Uq.basename(t)}function gx(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var oh=["run_shell_command","ShellTool"];async function tet(t){if(Uq.isAbsolute(t))try{return await Mq.promises.access(t,Mq.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(Uq.delimiter),r=JZe.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=Uq.join(n,t+o);try{return await Mq.promises.access(s,Mq.constants.X_OK),s}catch{continue}}}var kS=null,Bq=null,hx=null,Fq=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function Tbr(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function Cbr(){try{hx=null;let[t,e]=await Promise.all([Tme(()=>import("./tree-sitter-44HBOLVO.js"),"web-tree-sitter/tree-sitter.wasm"),Tme(()=>import("./tree-sitter-bash-2VW3T3MV.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await _me.init({wasmBinary:t}),kS=await Eme.load(e)}catch(t){kS=null;let e=Tbr(t),r=e instanceof Fq?e:new Fq(e);throw hx=r,r}}async function Ya(){Bq||(Bq=Cbr().catch(t=>{Bq=null,B.debug("Failed to initialize shell parsers:",t)})),await Bq}var ret="__GCLI_POWERSHELL_COMMAND__",wbr=1e3*1e3,xbr=Buffer.from(`
818
818
  $ErrorActionPreference = 'Stop'
819
819
  $commandText = $env:${ret}
820
820
  if ([string]::IsNullOrEmpty($commandText)) {
@@ -2941,7 +2941,7 @@ When adding a memory, route it to the right store:
2941
2941
  # Insufficient context
2942
2942
  If you find that you have insufficient context to read or modify the memories as described,
2943
2943
  reply with what you need, and exit. Do not search the codebase for the missing context.
2944
- `.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:Lvi},modelConfig:{model:ox},workspaceDirectories:[e],toolConfig:{tools:[jn,fa,pa,bA,da,hi,ko]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var Qf=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var qfr=6e4;async function Fb(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return B.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");B.debug("[AuthValueResolver] Executing command for auth value");let r=IA();try{let{stdout:n}=await Ul(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(qfr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${qfr/1e3} seconds`):n}}return t}function Gfr(t){return t.startsWith("$")||t.startsWith("!")}var Mvi="X-API-Key",tpe=class extends Qf{constructor(r){super();this.config=r;this.headerName=r.name??Mvi}type="apiKey";resolvedKey;headerName;async initialize(){Gfr(this.config.key)?(this.resolvedKey=await Fb(this.config.key),B.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=Qf.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Fb(this.config.key),this.headers()}};var rpe=class extends Qf{constructor(r){super();this.config=r}type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;async initialize(){let r=this.config;"token"in r?this.resolvedToken=await Fb(r.token):"username"in r?(this.resolvedUsername=await Fb(r.username),this.resolvedPassword=await Fb(r.password)):this.resolvedValue=await Fb(r.value),B.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let r=this.config;if("token"in r){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in r){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${r.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(r,n){if(n.status===401||n.status===403){if(this.authRetryCount>=Qf.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(r,n)}};var Vfr=Me(ts(),1);var kw=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},ZN=5*60*1e3,Cs=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch protected resource metadata from ${e}: ${Se(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch authorization server metadata from ${e}: ${Se(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return B.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new kw(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&B.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}B.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&B.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof kw)throw r;return B.debug(`Failed to discover OAuth configuration: ${Se(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new kw(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){B.error("Failed to parse ID token for expiry time with error:",r)}}};var Hfr=/^(.*\.)?run\.app$/,Bvi=[/^.+\.googleapis\.com$/,Hfr],npe=class extends Qf{constructor(r,n){super();this.config=r;if(!n)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let o=new URL(n).hostname;if(Hfr.test(o)&&(this.useIdToken=!0),this.audience=o,!this.useIdToken&&!Bvi.some(u=>u.test(o)))throw new Error(`Host "${o}" is not an allowed host for Google Credential provider.`);let c=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new Vfr.GoogleAuth({scopes:c})}type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-ZN)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let n=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),o=Cs.parseTokenExpiry(n);return o&&(this.tokenExpiryTime=o,this.cachedToken=n),{Authorization:`Bearer ${n}`}}catch(r){let n=`Failed to get ADC ID token: ${r instanceof Error?r.message:String(r)}`;throw B.error(n,r),new Error(n)}try{let r=await this.auth.getClient(),n=await r.getAccessToken();if(n.token){this.cachedToken=n.token;let o=r.credentials;return o.expiry_date&&(this.tokenExpiryTime=o.expiry_date),{Authorization:`Bearer ${n.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(r){let n=`Failed to get ADC access token: ${r instanceof Error?r.message:String(r)}`;throw B.error(n,r),new Error(n)}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=Qf.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var jb=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new npe(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new tpe(n);return await s.initialize(),s}case"http":{let s=new rpe(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-BHML6B32.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var Cm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},VHe=class extends Cm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},ipe=class extends Cm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},ope=class extends Cm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},spe=class extends Cm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function Uvi(t){return typeof t=="object"&&t!==null}function Fvi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(Uvi(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function $fr(t,e,r){let n=Fvi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new spe(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new VHe(t,e):/\b401\b|unauthorized/i.test(n)?new ipe(t,e,401):/\b403\b|forbidden/i.test(n)?new ipe(t,e,403):new spe(t,e,r)}function gj(t){return`${t.name}-config`}var ape=class{constructor(e){this.config=e}agents=new Map;allDefinitions=new Map;builtInAgents=new Set;async initialize(){_e.on("model-changed",this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{B.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),_e.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),_e.emitAgentsRefreshed())}dispose(){_e.off("model-changed",this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=Qt.getUserAgentsDir(),r=await jHe(e);for(let s of r.errors)B.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),_e.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){B.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),_e.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await jHe(s);for(let p of c.errors)_e.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?zfr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&_e.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){B.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),_e.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else _e.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){B.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),_e.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=xue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=Bfr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=Ufr(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")_e.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=epe(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}this.config.isMemoryManagerEnabled()&&this.registerLocalAgent(Qfr(this.config))}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&B.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?"allow":"ask_user",priority:VQ,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=Vde(n),c;if(e.auth){let p=await jb.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,Gde(n),c);if(u.securitySchemes){let p=jb.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=jb.describeRequiredAuth(u.securitySchemes),g=new ope(e.name,f,p.diff.missingConfig);_e.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),B.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
2944
+ `.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:Lvi},modelConfig:{model:ox},workspaceDirectories:[e],toolConfig:{tools:[jn,fa,pa,bA,da,hi,ko]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var Qf=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var qfr=6e4;async function Fb(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return B.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");B.debug("[AuthValueResolver] Executing command for auth value");let r=IA();try{let{stdout:n}=await Ul(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(qfr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${qfr/1e3} seconds`):n}}return t}function Gfr(t){return t.startsWith("$")||t.startsWith("!")}var Mvi="X-API-Key",tpe=class extends Qf{constructor(r){super();this.config=r;this.headerName=r.name??Mvi}type="apiKey";resolvedKey;headerName;async initialize(){Gfr(this.config.key)?(this.resolvedKey=await Fb(this.config.key),B.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=Qf.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await Fb(this.config.key),this.headers()}};var rpe=class extends Qf{constructor(r){super();this.config=r}type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;async initialize(){let r=this.config;"token"in r?this.resolvedToken=await Fb(r.token):"username"in r?(this.resolvedUsername=await Fb(r.username),this.resolvedPassword=await Fb(r.password)):this.resolvedValue=await Fb(r.value),B.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let r=this.config;if("token"in r){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in r){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${r.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(r,n){if(n.status===401||n.status===403){if(this.authRetryCount>=Qf.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(r,n)}};var Vfr=Me(ts(),1);var kw=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},ZN=5*60*1e3,Cs=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch protected resource metadata from ${e}: ${Se(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch authorization server metadata from ${e}: ${Se(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return B.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new kw(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&B.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}B.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&B.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof kw)throw r;return B.debug(`Failed to discover OAuth configuration: ${Se(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new kw(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){B.error("Failed to parse ID token for expiry time with error:",r)}}};var Hfr=/^(.*\.)?run\.app$/,Bvi=[/^.+\.googleapis\.com$/,Hfr],npe=class extends Qf{constructor(r,n){super();this.config=r;if(!n)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let o=new URL(n).hostname;if(Hfr.test(o)&&(this.useIdToken=!0),this.audience=o,!this.useIdToken&&!Bvi.some(u=>u.test(o)))throw new Error(`Host "${o}" is not an allowed host for Google Credential provider.`);let c=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new Vfr.GoogleAuth({scopes:c})}type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-ZN)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let n=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),o=Cs.parseTokenExpiry(n);return o&&(this.tokenExpiryTime=o,this.cachedToken=n),{Authorization:`Bearer ${n}`}}catch(r){let n=`Failed to get ADC ID token: ${r instanceof Error?r.message:String(r)}`;throw B.error(n,r),new Error(n)}try{let r=await this.auth.getClient(),n=await r.getAccessToken();if(n.token){this.cachedToken=n.token;let o=r.credentials;return o.expiry_date&&(this.tokenExpiryTime=o.expiry_date),{Authorization:`Bearer ${n.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(r){let n=`Failed to get ADC access token: ${r instanceof Error?r.message:String(r)}`;throw B.error(n,r),new Error(n)}}async shouldRetryWithHeaders(r,n){if(n.status!==401&&n.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=Qf.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var jb=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new npe(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new tpe(n);return await s.initialize(),s}case"http":{let s=new rpe(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-QVGZD7NX.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var Cm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},VHe=class extends Cm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},ipe=class extends Cm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},ope=class extends Cm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},spe=class extends Cm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function Uvi(t){return typeof t=="object"&&t!==null}function Fvi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(Uvi(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function $fr(t,e,r){let n=Fvi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new spe(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new VHe(t,e):/\b401\b|unauthorized/i.test(n)?new ipe(t,e,401):/\b403\b|forbidden/i.test(n)?new ipe(t,e,403):new spe(t,e,r)}function gj(t){return`${t.name}-config`}var ape=class{constructor(e){this.config=e}agents=new Map;allDefinitions=new Map;builtInAgents=new Set;async initialize(){_e.on("model-changed",this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{B.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),_e.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),_e.emitAgentsRefreshed())}dispose(){_e.off("model-changed",this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=Qt.getUserAgentsDir(),r=await jHe(e);for(let s of r.errors)B.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),_e.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){B.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),_e.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await jHe(s);for(let p of c.errors)_e.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?zfr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&_e.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){B.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),_e.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else _e.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){B.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),_e.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=xue(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=Bfr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=Ufr(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")_e.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=epe(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}this.config.isMemoryManagerEnabled()&&this.registerLocalAgent(Qfr(this.config))}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&B.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?"allow":"ask_user",priority:VQ,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=Vde(n),c;if(e.auth){let p=await jb.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,Gde(n),c);if(u.securitySchemes){let p=jb.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=jb.describeRequiredAuth(u.securitySchemes),g=new ope(e.name,f,p.diff.missingConfig);_e.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),B.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
2945
2945
  `);a.push(`Skills:
2946
2946
  ${p}`)}a.length>0&&(e.description=a.join(`
2947
2947
  `)),this.config.getDebugMode()&&B.log(`[AgentRegistry] Registered remote agent '${e.name}' with card: ${e.agentCardUrl??"inline JSON"}`),this.agents.set(e.name,e),this.addAgentPolicy(e)}catch(o){o instanceof Cm?_e.emitFeedback("error",`[${e.name}] ${o.userMessage}`):_e.emitFeedback("error",`[${e.name}] Failed to load remote agent: ${o instanceof Error?o.message:String(o)}`),B.warn(`[AgentRegistry] Error loading A2A agent "${e.name}":`,o)}}applyOverrides(e,r){if(e.kind!=="local"||!r)return e;let n={get kind(){return e.kind},get name(){return e.name},get displayName(){return e.displayName},get description(){return e.description},get experimental(){return e.experimental},get metadata(){return e.metadata},get inputConfig(){return e.inputConfig},get outputConfig(){return e.outputConfig},get promptConfig(){return e.promptConfig},get toolConfig(){return e.toolConfig},get processOutput(){return e.processOutput},get runConfig(){return r.runConfig?{...e.runConfig,...r.runConfig}:e.runConfig},get modelConfig(){return r.modelConfig?jN.merge(e.modelConfig,r.modelConfig):e.modelConfig}};return r.tools&&(n.toolConfig={tools:r.tools}),r.mcpServers&&(n.mcpServers={...e.mcpServers,...r.mcpServers}),n}registerModelConfigs(e){let r=e.modelConfig,n=r.model;n==="inherit"&&(n=this.config.getModel());let o={...r,model:n};this.config.modelConfigService.registerRuntimeModelConfig(gj(e),{modelConfig:o}),o.model&&ks(o.model)&&this.config.modelConfigService.registerRuntimeModelOverride({match:{overrideScope:e.name},modelConfig:{generateContentConfig:o.generateContentConfig}})}getDefinition(e){return this.agents.get(e)}getAllDefinitions(){return Array.from(this.agents.values())}getAllAgentNames(){return Array.from(this.agents.keys())}getAllDiscoveredAgentNames(){return Array.from(this.allDefinitions.keys())}getDiscoveredDefinition(e){return this.allDefinitions.get(e)}};import*as eD from"node:fs/promises";import*as Wfr from"node:path";var lpe=class{acknowledgedAgents={};loaded=!1;async load(){if(this.loaded)return;let e=Qt.getAcknowledgedAgentsPath();try{let r=await eD.readFile(e,"utf-8");this.acknowledgedAgents=JSON.parse(r)}catch(r){(!_t(r)||r.code!=="ENOENT")&&B.error("Failed to load acknowledged agents:",Se(r)),this.acknowledgedAgents={}}this.loaded=!0}async save(){let e=Qt.getAcknowledgedAgentsPath();try{let r=Wfr.dirname(e);await eD.mkdir(r,{recursive:!0}),await eD.writeFile(e,JSON.stringify(this.acknowledgedAgents,null,2),"utf-8")}catch(r){B.error("Failed to save acknowledged agents:",Se(r))}}async isAcknowledged(e,r,n){await this.load();let o=this.acknowledgedAgents[e];return o?o[r]===n:!1}async acknowledge(e,r,n){await this.load(),this.acknowledgedAgents[e]||(this.acknowledgedAgents[e]={}),this.acknowledgedAgents[e][r]=n,await this.save()}};function cpe(t,e){let r=/\$\{(\w+)\}/g,n=new Set(Array.from(t.matchAll(r),c=>c[1])),o=new Set(Object.keys(e)),s=Array.from(n).filter(c=>!o.has(c));if(s.length>0)throw new Error(`Template validation failed: Missing required input parameters: ${s.join(", ")}. Available inputs: ${Object.keys(e).join(", ")}`);return t.replace(r,(c,u)=>String(e[u]))}import{AsyncLocalStorage as jvi}from"node:async_hooks";var Yfr=new jvi;function HHe(t,e){return Yfr.run(t,e)}function upe(){return Yfr.getStore()}var Jfr=Me(Bse(),1);function mj(t){return typeof t=="object"&&t!==null&&"callId"in t&&"responseParts"in t}function C8o(t){let{displayName:e,status:r,approvalMode:n,hasResultDisplay:o,parentCallId:s}=t;if(s)return!0;switch(e){case oL:switch(r){case"scheduled":case"validating":case"executing":case"awaiting_approval":return!0;case"error":return!o;default:return!1}case gq:case mq:return n==="plan";default:return!1}}function yj(t,e,r=3){let n=e.map(c=>({name:c,distance:Jfr.default.get(t,c)}));n.sort((c,u)=>c.distance-u.distance);let o=n.slice(0,r);if(o.length===0)return"";let s=o.map(c=>`"${c.name}"`).join(", ");return o.length>1?` Did you mean one of: ${s}?`:` Did you mean ${s}?`}function w8o(t,e,r){let n;$Q(t)?n=[t.name,t.constructor.name]:n=[t],n.some(o=>oh.includes(o))&&(n=[...new Set([...n,...oh])]);for(let o of r){let s=o.indexOf("(");if(s===-1){if(n.includes(o))return!0;continue}let c=o.substring(0,s);if(!n.includes(c)||!o.endsWith(")"))continue;let u=o.substring(s+1,o.length-1),d;if(typeof e=="string")d=e;else{if(!("command"in e.params))continue;d=String(e.params.command)}if(n.some(l=>oh.includes(l))&&(d===u||d.startsWith(u+" ")))return!0}return!1}var dpe=class{constructor(e,r=wit,n){this.messageBus=e;this.schedulerId=r;this.onTerminalCall=n}activeCalls=new Map;queue=[];_completedBatch=[];addToolCalls(e){this.enqueue(e)}getToolCall(e){return this.activeCalls.get(e)||this.queue.find(r=>r.request.callId===e)||this._completedBatch.find(r=>r.request.callId===e)}enqueue(e){this.queue.push(...e),this.emitUpdate()}dequeue(){let e=this.queue.shift();return e&&(this.activeCalls.set(e.request.callId,e),this.emitUpdate()),e}peekQueue(){return this.queue[0]}get isActive(){return this.activeCalls.size>0}get allActiveCalls(){return Array.from(this.activeCalls.values())}get activeCallCount(){return this.activeCalls.size}get queueLength(){return this.queue.length}get firstActiveCall(){return this.activeCalls.values().next().value}updateStatus(e,r,n){let o=this.activeCalls.get(e);if(!o)return;let s=this.transitionCall(o,r,n);this.activeCalls.set(e,s),this.emitUpdate()}finalizeCall(e){let r=this.activeCalls.get(e);r&&this.isTerminalCall(r)&&(this._completedBatch.push(r),this.activeCalls.delete(e),this.onTerminalCall?.(r),this.emitUpdate())}updateArgs(e,r,n){let o=this.activeCalls.get(e);!o||o.status==="error"||(this.activeCalls.set(e,this.patchCall(o,{request:{...o.request,args:r},invocation:n})),this.emitUpdate())}setOutcome(e,r){let n=this.activeCalls.get(e);n&&(this.activeCalls.set(e,this.patchCall(n,{outcome:r})),this.emitUpdate())}replaceActiveCallWithTailCall(e,r){this.activeCalls.has(e)&&(this.activeCalls.delete(e),this.queue.unshift(r),this.emitUpdate())}cancelAllQueued(e){if(this.queue.length!==0){for(;this.queue.length>0;){let r=this.queue.shift();if(r.status==="error"){this._completedBatch.push(r),this.onTerminalCall?.(r);continue}let n=this.toCancelled(r,e);this._completedBatch.push(n),this.onTerminalCall?.(n)}this.emitUpdate()}}getSnapshot(){return[...this._completedBatch,...Array.from(this.activeCalls.values()),...this.queue]}clearBatch(){this._completedBatch.length!==0&&(this._completedBatch=[],this.emitUpdate())}get completedBatch(){return[...this._completedBatch]}emitUpdate(){let e=this.getSnapshot();this.messageBus.publish({type:"tool-calls-update",toolCalls:e,schedulerId:this.schedulerId})}isTerminalCall(e){let{status:r}=e;return r==="success"||r==="error"||r==="cancelled"}transitionCall(e,r,n){switch(r){case"success":{if(!mj(n))throw new Error(`Invalid data for 'success' transition (callId: ${e.request.callId})`);return this.toSuccess(e,n)}case"error":{if(!mj(n))throw new Error(`Invalid data for 'error' transition (callId: ${e.request.callId})`);return this.toError(e,n)}case"awaiting_approval":{if(!n)throw new Error(`Missing data for 'awaiting_approval' transition (callId: ${e.request.callId})`);return this.toAwaitingApproval(e,n)}case"scheduled":return this.toScheduled(e);case"cancelled":{if(typeof n!="string"&&!mj(n))throw new Error(`Invalid reason (string) or response for 'cancelled' transition (callId: ${e.request.callId})`);return this.toCancelled(e,n)}case"validating":return this.toValidating(e);case"executing":{if(n!==void 0&&!this.isExecutingToolCallPatch(n))throw new Error(`Invalid patch for 'executing' transition (callId: ${e.request.callId})`);return this.toExecuting(e,n)}default:return r}}isExecutingToolCallPatch(e){return typeof e=="object"&&e!==null}validateHasToolAndInvocation(e,r){if(!("tool"in e&&e.tool&&"invocation"in e&&e.invocation))throw new Error(`Invalid state transition: cannot transition to ${r} without tool/invocation (callId: ${e.request.callId})`)}toSuccess(e,r){this.validateHasToolAndInvocation(e,"success");let n="startTime"in e?e.startTime:void 0;return{request:e.request,tool:e.tool,invocation:e.invocation,status:"success",response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toError(e,r){let n="startTime"in e?e.startTime:void 0;return{request:e.request,status:"error",tool:"tool"in e?e.tool:void 0,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toAwaitingApproval(e,r){this.validateHasToolAndInvocation(e,"awaiting_approval");let n,o;return this.isEventDrivenApprovalData(r)?(o=r.correlationId,n=r.confirmationDetails):n=r,{request:e.request,tool:e.tool,status:"awaiting_approval",correlationId:o,confirmationDetails:n,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isEventDrivenApprovalData(e){return typeof e=="object"&&e!==null&&"correlationId"in e&&"confirmationDetails"in e}toScheduled(e){return this.validateHasToolAndInvocation(e,"scheduled"),{request:e.request,tool:e.tool,status:"scheduled",startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toCancelled(e,r){this.validateHasToolAndInvocation(e,"cancelled");let n="startTime"in e?e.startTime:void 0,o;if(this.isWaitingToolCall(e)){let u=e.confirmationDetails;u.type==="edit"&&"fileDiff"in u&&"fileName"in u&&"filePath"in u&&"originalContent"in u&&"newContent"in u&&(o={fileDiff:u.fileDiff,fileName:u.fileName,filePath:u.filePath,originalContent:u.originalContent,newContent:u.newContent,diffStat:u.diffStat??NKe(u.fileDiff)})}let s;if(e.status==="executing"&&e.liveOutput&&(s=e.liveOutput),mj(r)){let u={...r};return u.resultDisplay||(u.resultDisplay=o??s),{request:e.request,tool:e.tool,invocation:e.invocation,status:"cancelled",response:u,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}let c=`[Operation Cancelled] Reason: ${r}`;return{request:e.request,tool:e.tool,invocation:e.invocation,status:"cancelled",response:{callId:e.request.callId,responseParts:[{functionResponse:{id:e.request.callId,name:e.request.originalRequestName??e.request.name,response:{error:c}}}],resultDisplay:o??s,error:void 0,errorType:void 0,contentLength:c.length},durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isWaitingToolCall(e){return e.status==="awaiting_approval"}patchCall(e,r){return{...e,...r}}toValidating(e){return this.validateHasToolAndInvocation(e,"validating"),{request:e.request,tool:e.tool,status:"validating",startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toExecuting(e,r){this.validateHasToolAndInvocation(e,"executing");let n=r,o=n?.liveOutput??("liveOutput"in e?e.liveOutput:void 0),s=n?.pid??("pid"in e?e.pid:void 0),c=n?.progressMessage??("progressMessage"in e?e.progressMessage:void 0),u=n?.progressPercent??("progressPercent"in e?e.progressPercent:void 0),d=n?.progress??("progress"in e?e.progress:void 0),l=n?.progressTotal??("progressTotal"in e?e.progressTotal:void 0);return{request:e.request,tool:e.tool,status:"executing",startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,liveOutput:o,pid:s,progressMessage:c,progressPercent:u,progress:d,progressTotal:l,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}};import{on as Qvi}from"node:events";import{randomUUID as qvi}from"node:crypto";async function Gvi(t,e,r){if(r.aborted)throw new Error("Operation cancelled");try{for await(let[n]of Qvi(t,"tool-confirmation-response",{signal:r})){let o=n;if(o.correlationId===e)return{outcome:o.outcome??(o.confirmed?"proceed_once":"cancel"),payload:o.payload}}}catch(n){throw r.aborted||n.name==="AbortError"?new Error("Operation cancelled"):n}throw new Error("Operation cancelled")}async function $He(t,e,r){let{state:n,onWaitingForConfirmation:o}=r,s=t.request.callId,c="modify_with_editor",u;for(;c==="modify_with_editor";){if(e.aborted)throw new Error("Operation cancelled by user");let d=n.getToolCall(s);if(!d||!("invocation"in d))throw new Error(`Tool call ${s} lost during confirmation loop`);let a=await d.invocation.shouldConfirmExecute(e,r.forcedDecision);if(!a){c="proceed_once";break}r.systemMessage&&(a.systemMessage=r.systemMessage),await Vvi(r,a);let p=qvi(),f=a;u=f;let g="ideConfirmation"in a?a.ideConfirmation:void 0;n.updateStatus(s,"awaiting_approval",{confirmationDetails:f,correlationId:p}),o?.(!0);let y=await zvi(r.messageBus,p,e,g);if(o?.(!1),c=y.outcome,"onConfirm"in a&&typeof a.onConfirm=="function"&&await a.onConfirm(c,y.payload),c==="modify_with_editor"){let E=await Hvi(r,t,e);E.error&&_e.emitFeedback("error",E.error)}else y.payload&&"newContent"in y.payload&&(await $vi(r,t,y.payload,e),c="proceed_once")}return{outcome:c,lastDetails:u}}async function Vvi(t,e){t.config.getHookSystem()&&await t.config.getHookSystem()?.fireToolNotificationEvent({...e,onConfirm:async()=>{}})}async function Hvi(t,e,r){let{state:n,modifier:o,getPreferredEditor:s}=t,c=s(),u=await D6t(c,r);if(!u)return{error:R6t};let d=await o.handleModifyWithEditor(n.firstActiveCall,u,r);if(d){let l=e.tool.build(d.updatedParams);n.updateArgs(e.request.callId,d.updatedParams,l)}return{}}async function $vi(t,e,r,n){let{state:o,modifier:s}=t,c=await s.applyInlineModify(o.firstActiveCall,r,n);if(c){let u=e.tool.build(c.updatedParams);o.updateArgs(e.request.callId,c.updatedParams,u)}}async function zvi(t,e,r,n){let o=new AbortController,s=o.signal,c=()=>o.abort();r.aborted?o.abort():r.addEventListener("abort",c);try{let u=Gvi(t,e,s);if(!n)return await u;let d=n.then(l=>({outcome:l.status==="accepted"?"proceed_once":"cancel",payload:l.content?{newContent:l.content}:void 0})).catch(l=>(B.warn("Error waiting for confirmation via IDE",l),new Promise(()=>{})));return await Promise.race([u,d])}finally{r.removeEventListener("abort",c),o.abort()}}function Kfr(t,e){return{errorMessage:`Tool execution denied by policy.${e?.denyMessage?` ${e.denyMessage}`:""}`,errorType:"policy_violation"}}async function Xfr(t,e,r){let n=t.tool instanceof ri?t.tool.serverName:void 0,o=t.tool.toolAnnotations,s=await e.getPolicyEngine().check({name:t.request.name,args:t.request.args},n,o,r),{decision:c}=s;if(c==="ask_user"&&t.request.isClientInitiated&&!t.request.args?.additional_permissions)return{decision:"allow",rule:s.rule};if(c==="ask_user"&&!e.isInteractive())throw new Error(`Tool execution for "${t.tool.displayName||t.tool.name}" requires user confirmation, which is not supported in non-interactive mode.`);return{decision:c,rule:s.rule}}async function Zfr(t,e,r,n,o,s){if(Wvi(t,e)){n.config.setApprovalMode("autoEdit");return}let c,u,d=n.config.getApprovalMode();if(e==="proceed_always"||e==="proceed_always_tool"||e==="proceed_always_server"||e==="proceed_always_and_save"){let l=Bge.indexOf(d);l!==-1&&(u=Bge.slice(l))}if(e==="proceed_always_and_save"&&(n.config&&n.config.isTrustedFolder()&&n.config.getWorkspacePoliciesDir()!==void 0?c="workspace":c="user"),r?.type==="mcp"){await Jvi(t,e,r,o,c,u);return}await Yvi(t,e,r,o,c,s,n.config,u)}function Wvi(t,e){return e==="proceed_always"&&iL.has(t.name)}async function Yvi(t,e,r,n,o,s,c,u){if(e==="proceed_always"||e==="proceed_always_and_save"){let d=s?.getPolicyUpdateOptions?.(e)||{};if(!d.commandPrefix&&r?.type==="exec")d.commandPrefix=r.rootCommands;else if(!d.argsPattern&&r?.type==="edit"){let l=c?Ro(r.filePath,c.getTargetDir()):r.filePath;d.argsPattern=fv(l)}await n.publish({type:"update-policy",toolName:t.name,persist:e==="proceed_always_and_save",persistScope:o,modes:u,...d})}}async function Jvi(t,e,r,n,o,s){if(!(e==="proceed_always"||e==="proceed_always_tool"||e==="proceed_always_server"||e==="proceed_always_and_save"))return;let u=t.name,d=e==="proceed_always_and_save";e==="proceed_always_server"&&(u=bS(r.serverName,"*")),await n.publish({type:"update-policy",toolName:u,mcpName:r.serverName,persist:d,persistScope:o,modes:s})}function zHe(t,e){if(!(t instanceof tXe))return;let n=(e.getMcpClientManager()?.getMcpServers()??e.getMcpServers()??{})[t.serverName];if(n)return{server_name:t.serverName,tool_name:t.serverToolName,command:n.command,args:n.args,cwd:n.cwd,url:n.url??n.httpUrl,tcp:n.tcp}}async function ehr(t,e,r,n,o,s,c,u,d){let l=t.params||{},a=!1,p=[],f=c?zHe(t,c):void 0,g=c?.getHookSystem();if(g&&!d){let E=await g.fireBeforeToolEvent(e,l,f,u);if(E?.shouldStopExecution()){let v=E.getEffectiveReason();return{llmContent:`Agent execution stopped by hook: ${v}`,returnDisplay:`Agent execution stopped by hook: ${v}`,error:{type:"stop_execution",message:v}}}let _=E?.getBlockingError();if(_?.blocked)return{llmContent:`Tool execution blocked: ${_.reason}`,returnDisplay:`Tool execution blocked: ${_.reason}`,error:{type:"execution_failed",message:_.reason}};if(E instanceof K0){let v=E.getModifiedToolInput();if(v){Object.assign(t.params,v),B.debug(`Tool input modified by hook for ${e}`),a=!0,p=Object.keys(v);try{t=n.build(t.params)}catch(b){return{llmContent:`Tool parameter modification by hook failed validation: ${b instanceof Error?b.message:String(b)}`,returnDisplay:"Tool parameter modification by hook failed validation.",error:{type:"invalid_tool_params",message:String(b)}}}}}}let y=await t.execute(r,o,s);if(a){let E=`
@@ -814,7 +814,7 @@ ${s}
814
814
 
815
815
  ... [${u.toLocaleString()} characters omitted] ...
816
816
 
817
- ${c}`}var Q1r="tool-outputs";async function aS(t,e,r,n,o){let s=rd(e).toLowerCase(),c=rd(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=td.join(n,Q1r);if(o){let a=rd(o);d=td.join(d,`session-${a}`)}let l=td.join(d,u);return await qx.mkdir(d,{recursive:!0}),await qx.writeFile(l,t),{outputFile:l}}async function Met(t,e){await ml();let r=[t,...e].join(" "),n=du(r),o=w0(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:AG.basename(t)}function $x(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var Ih=["run_shell_command","ShellTool"];async function Uet(t){if(AG.isAbsolute(t))try{return await mG.promises.access(t,mG.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(AG.delimiter),r=ket.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=AG.join(n,t+o);try{return await mG.promises.access(s,mG.constants.X_OK),s}catch{continue}}}var lS=null,yG=null,Vx=null,_G=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function G1r(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function V1r(){try{Vx=null;let[t,e]=await Promise.all([t0e(()=>import("./tree-sitter-N6IY6JNB.js"),"web-tree-sitter/tree-sitter.wasm"),t0e(()=>import("./tree-sitter-bash-4FEPBSIN.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await Kme.init({wasmBinary:t}),lS=await Jme.load(e)}catch(t){lS=null;let e=G1r(t),r=e instanceof _G?e:new _G(e);throw Vx=r,r}}async function ml(){yG||(yG=V1r().catch(t=>{yG=null,B.debug("Failed to initialize shell parsers:",t)})),await yG}var Fet="__GCLI_POWERSHELL_COMMAND__",$1r=1e3*1e3,H1r=Buffer.from(`
817
+ ${c}`}var Q1r="tool-outputs";async function aS(t,e,r,n,o){let s=rd(e).toLowerCase(),c=rd(r.toString()).toLowerCase(),u=c.startsWith(s)?`${c}.txt`:`${s}_${c}.txt`,d=td.join(n,Q1r);if(o){let a=rd(o);d=td.join(d,`session-${a}`)}let l=td.join(d,u);return await qx.mkdir(d,{recursive:!0}),await qx.writeFile(l,t),{outputFile:l}}async function Met(t,e){await ml();let r=[t,...e].join(" "),n=du(r),o=w0(n).filter(s=>s!=="shopt"&&s!=="set");return o.length>0?o[0]:AG.basename(t)}function $x(t){return typeof t=="string"?t:"pattern"in t?t.pattern:"op"in t?t.op:("comment"in t,"")}var Ih=["run_shell_command","ShellTool"];async function Uet(t){if(AG.isAbsolute(t))try{return await mG.promises.access(t,mG.constants.X_OK),t}catch{return}let e=(process.env.PATH||"").split(AG.delimiter),r=ket.platform()==="win32"?[".exe",".cmd",".bat",""]:[""];for(let n of e)for(let o of r){let s=AG.join(n,t+o);try{return await mG.promises.access(s,mG.constants.X_OK),s}catch{continue}}}var lS=null,yG=null,Vx=null,_G=class extends Error{constructor(e){super(`Failed to initialize bash parser: ${e.message}`,{cause:e}),this.name="ShellParserInitializationError"}};function G1r(t){return t instanceof Error?t:typeof t=="string"?new Error(t):new Error("Unknown tree-sitter initialization error",{cause:t})}async function V1r(){try{Vx=null;let[t,e]=await Promise.all([t0e(()=>import("./tree-sitter-44HBOLVO.js"),"web-tree-sitter/tree-sitter.wasm"),t0e(()=>import("./tree-sitter-bash-2VW3T3MV.js"),"tree-sitter-bash/tree-sitter-bash.wasm")]);await Kme.init({wasmBinary:t}),lS=await Jme.load(e)}catch(t){lS=null;let e=G1r(t),r=e instanceof _G?e:new _G(e);throw Vx=r,r}}async function ml(){yG||(yG=V1r().catch(t=>{yG=null,B.debug("Failed to initialize shell parsers:",t)})),await yG}var Fet="__GCLI_POWERSHELL_COMMAND__",$1r=1e3*1e3,H1r=Buffer.from(`
818
818
  $ErrorActionPreference = 'Stop'
819
819
  $commandText = $env:${Fet}
820
820
  if ([string]::IsNullOrEmpty($commandText)) {
@@ -2941,7 +2941,7 @@ When adding a memory, route it to the right store:
2941
2941
  # Insufficient context
2942
2942
  If you find that you have insufficient context to read or modify the memories as described,
2943
2943
  reply with what you need, and exit. Do not search the codebase for the missing context.
2944
- `.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:Hbi},modelConfig:{model:Lx},workspaceDirectories:[e],toolConfig:{tools:[ti,Pa,Ra,XA,Ia,Oi,Wo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var dh=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var uhr=6e4;async function gv(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return B.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");B.debug("[AuthValueResolver] Executing command for auth value");let r=o_();try{let{stdout:n}=await oc(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(uhr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${uhr/1e3} seconds`):n}}return t}function dhr(t){return t.startsWith("$")||t.startsWith("!")}var zbi="X-API-Key",kpe=class extends dh{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??zbi}async initialize(){dhr(this.config.key)?(this.resolvedKey=await gv(this.config.key),B.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=dh.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await gv(this.config.key),this.headers()}};var Dpe=class extends dh{config;type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;constructor(e){super(),this.config=e}async initialize(){let e=this.config;"token"in e?this.resolvedToken=await gv(e.token):"username"in e?(this.resolvedUsername=await gv(e.username),this.resolvedPassword=await gv(e.password)):this.resolvedValue=await gv(e.value),B.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let e=this.config;if("token"in e){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in e){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${e.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403){if(this.authRetryCount>=dh.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var phr=Fe(_s(),1);var lx=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},ID=5*60*1e3,qs=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch protected resource metadata from ${e}: ${Te(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch authorization server metadata from ${e}: ${Te(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return B.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new lx(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&B.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}B.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&B.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof lx)throw r;return B.debug(`Failed to discover OAuth configuration: ${Te(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new lx(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){B.error("Failed to parse ID token for expiry time with error:",r)}}};var fhr=/^(.*\.)?run\.app$/,Wbi=[/^.+\.googleapis\.com$/,fhr],Lpe=class extends dh{config;type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;constructor(e,r){if(super(),this.config=e,!r)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let n=new URL(r).hostname;if(fhr.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!Wbi.some(c=>c.test(n)))throw new Error(`Host "${n}" is not an allowed host for Google Credential provider.`);let s=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new phr.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-ID)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let r=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),n=qs.parseTokenExpiry(r);return n&&(this.tokenExpiryTime=n,this.cachedToken=r),{Authorization:`Bearer ${r}`}}catch(e){let r=`Failed to get ADC ID token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}try{let e=await this.auth.getClient(),r=await e.getAccessToken();if(r.token){this.cachedToken=r.token;let n=e.credentials;return n.expiry_date&&(this.tokenExpiryTime=n.expiry_date),{Authorization:`Bearer ${r.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(e){let r=`Failed to get ADC access token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=dh.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var mv=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new Lpe(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new kpe(n);return await s.initialize(),s}case"http":{let s=new Dpe(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-XRTDUVAE.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var Xm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},SHe=class extends Xm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},Mpe=class extends Xm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},Bpe=class extends Xm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},Upe=class extends Xm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function Ybi(t){return typeof t=="object"&&t!==null}function Jbi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(Ybi(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function hhr(t,e,r){let n=Jbi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new Upe(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new SHe(t,e):/\b401\b|unauthorized/i.test(n)?new Mpe(t,e,401):/\b403\b|forbidden/i.test(n)?new Mpe(t,e,403):new Upe(t,e,r)}function Wj(t){return`${t.name}-config`}var Fpe=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;constructor(e){this.config=e}async initialize(){be.on(Nr.ModelChanged,this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{B.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),be.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),be.emitAgentsRefreshed())}dispose(){be.off(Nr.ModelChanged,this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=Jt.getUserAgentsDir(),r=await _He(e);for(let s of r.errors)B.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),be.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){B.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),be.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await _He(s);for(let p of c.errors)be.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?ghr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&be.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){B.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),be.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else be.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){B.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),be.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=lde(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=ohr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=shr(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")be.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=Npe(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}this.config.isMemoryManagerEnabled()&&this.registerLocalAgent(chr(this.config))}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&B.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?tt.ALLOW:tt.ASK_USER,priority:Tq,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=vpe(n),c;if(e.auth){let p=await mv.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,bpe(n),c);if(u.securitySchemes){let p=mv.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=mv.describeRequiredAuth(u.securitySchemes),g=new Bpe(e.name,f,p.diff.missingConfig);be.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),B.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
2944
+ `.trim();return{kind:"local",name:"save_memory",displayName:"Memory Manager",description:"Writes and reads memory, preferences or facts across ALL future sessions. Use this for recurring instructions like coding styles or tool aliases.",inputConfig:{inputSchema:{type:"object",properties:{request:{type:"string",description:'The memory operation to perform. Examples: "Remember that I prefer tabs over spaces", "Clean up stale memories", "De-duplicate my memories", "Organize my memories".'}},required:["request"]}},outputConfig:{outputName:"result",description:"A summary of the memory operations performed.",schema:Hbi},modelConfig:{model:Lx},workspaceDirectories:[e],toolConfig:{tools:[ti,Pa,Ra,XA,Ia,Oi,Wo]},get promptConfig(){return{systemPrompt:n(),query:`${r()}\${request}`}},runConfig:{maxTimeMinutes:5,maxTurns:10}}};var dh=class t{static MAX_AUTH_RETRIES=2;authRetryCount=0;async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403)return this.authRetryCount>=t.MAX_AUTH_RETRIES?void 0:(this.authRetryCount++,this.headers());this.authRetryCount=0}async initialize(){}};var uhr=6e4;async function gv(t){if(t.startsWith("$$")||t.startsWith("!!"))return t.slice(1);if(t.startsWith("$")){let e=t.slice(1),r=process.env[e];if(r===void 0||r==="")throw new Error(`Environment variable '${e}' is not set or is empty. Please set it before using this agent.`);return B.debug(`[AuthValueResolver] Resolved env var: ${e}`),r}if(t.startsWith("!")){let e=t.slice(1).trim();if(!e)throw new Error("Empty command in auth value. Expected format: !command");B.debug("[AuthValueResolver] Executing command for auth value");let r=o_();try{let{stdout:n}=await oc(r.executable,[...r.argsPrefix,e],{signal:AbortSignal.timeout(uhr),windowsHide:!0}),o=n.trim();if(!o)throw new Error(`Command '${e}' returned empty output`);return o}catch(n){throw n instanceof Error&&n.name==="AbortError"?new Error(`Command '${e}' timed out after ${uhr/1e3} seconds`):n}}return t}function dhr(t){return t.startsWith("$")||t.startsWith("!")}var zbi="X-API-Key",kpe=class extends dh{config;type="apiKey";resolvedKey;headerName;constructor(e){super(),this.config=e,this.headerName=e.name??zbi}async initialize(){dhr(this.config.key)?(this.resolvedKey=await gv(this.config.key),B.debug(`[ApiKeyAuthProvider] Resolved API key from: ${this.config.key.startsWith("$")?"env var":"command"}`)):this.resolvedKey=this.config.key}async headers(){if(!this.resolvedKey)throw new Error("ApiKeyAuthProvider not initialized. Call initialize() first.");return{[this.headerName]:this.resolvedKey}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(!this.config.key.startsWith("!")||this.config.key.startsWith("!!"))&&!(this.authRetryCount>=dh.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[ApiKeyAuthProvider] Re-resolving API key after auth failure"),this.resolvedKey=await gv(this.config.key),this.headers()}};var Dpe=class extends dh{config;type="http";resolvedToken;resolvedUsername;resolvedPassword;resolvedValue;constructor(e){super(),this.config=e}async initialize(){let e=this.config;"token"in e?this.resolvedToken=await gv(e.token):"username"in e?(this.resolvedUsername=await gv(e.username),this.resolvedPassword=await gv(e.password)):this.resolvedValue=await gv(e.value),B.debug(`[HttpAuthProvider] Initialized with scheme: ${this.config.scheme}`)}async headers(){let e=this.config;if("token"in e){if(!this.resolvedToken)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Bearer ${this.resolvedToken}`}}if("username"in e){if(!this.resolvedUsername||!this.resolvedPassword)throw new Error("HttpAuthProvider not initialized");return{Authorization:`Basic ${Buffer.from(`${this.resolvedUsername}:${this.resolvedPassword}`).toString("base64")}`}}if(!this.resolvedValue)throw new Error("HttpAuthProvider not initialized");return{Authorization:`${e.scheme} ${this.resolvedValue}`}}async shouldRetryWithHeaders(e,r){if(r.status===401||r.status===403){if(this.authRetryCount>=dh.MAX_AUTH_RETRIES)return;B.debug("[HttpAuthProvider] Re-resolving values after auth failure"),await this.initialize()}return super.shouldRetryWithHeaders(e,r)}};var phr=Fe(_s(),1);var lx=class extends Error{constructor(e){super(e),this.name="ResourceMismatchError"}},ID=5*60*1e3,qs=class{static buildWellKnownUrls(e,r=!1){let n=new URL(e),o=`${n.protocol}//${n.host}`,s=r?"":n.pathname.replace(/\/$/,"");return{protectedResource:new URL(`/.well-known/oauth-protected-resource${s}`,o).toString(),authorizationServer:new URL(`/.well-known/oauth-authorization-server${s}`,o).toString()}}static async fetchProtectedResourceMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch protected resource metadata from ${e}: ${Te(r)}`),null}}static async fetchAuthorizationServerMetadata(e){try{let r=await fetch(e);return r.ok?await r.json():null}catch(r){return B.debug(`Failed to fetch authorization server metadata from ${e}: ${Te(r)}`),null}}static metadataToOAuthConfig(e){return{authorizationUrl:e.authorization_endpoint,issuer:e.issuer,tokenUrl:e.token_endpoint,scopes:e.scopes_supported||[],registrationUrl:e.registration_endpoint}}static async discoverAuthorizationServerMetadata(e){let r=new URL(e),n=`${r.protocol}//${r.host}`,o=[];r.pathname!=="/"&&(o.push(new URL(`/.well-known/oauth-authorization-server${r.pathname}`,n).toString()),o.push(new URL(`/.well-known/openid-configuration${r.pathname}`,n).toString()),o.push(new URL(`${r.pathname}/.well-known/openid-configuration`,n).toString())),o.push(new URL("/.well-known/oauth-authorization-server",n).toString()),o.push(new URL("/.well-known/openid-configuration",n).toString());for(let s of o){let c=await this.fetchAuthorizationServerMetadata(s);if(c)return c}return B.debug(`Metadata discovery failed for authorization server ${e}`),null}static async discoverOAuthConfig(e){try{let r=this.buildWellKnownUrls(e),n=await this.fetchProtectedResourceMetadata(r.protectedResource);if(!n){let s=new URL(e);if(s.pathname&&s.pathname!=="/"){let c=this.buildWellKnownUrls(e,!0);n=await this.fetchProtectedResourceMetadata(c.protectedResource)}}if(n){let s=this.buildResourceParameter(e);if(!this.isEquivalentResourceIdentifier(n.resource,s))throw new lx(`Protected resource ${n.resource} does not match expected ${s}`)}if(n?.authorization_servers?.length){let s=n.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);if(c){let u=this.metadataToOAuthConfig(c);return c.registration_endpoint&&B.log("Dynamic client registration is supported at:",c.registration_endpoint),u}}B.debug(`Trying OAuth discovery fallback at ${e}`);let o=await this.discoverAuthorizationServerMetadata(e);if(o){let s=this.metadataToOAuthConfig(o);return o.registration_endpoint&&B.log("Dynamic client registration is supported at:",o.registration_endpoint),s}return null}catch(r){if(r instanceof lx)throw r;return B.debug(`Failed to discover OAuth configuration: ${Te(r)}`),null}}static parseWWWAuthenticateHeader(e){let r=e.match(/resource_metadata="([^"]+)"/);return r?r[1]:null}static async discoverOAuthFromWWWAuthenticate(e,r){let n=this.parseWWWAuthenticateHeader(e);if(!n)return null;let o=await this.fetchProtectedResourceMetadata(n);if(o&&r){let u=this.buildResourceParameter(r);if(!this.isEquivalentResourceIdentifier(o.resource,u))throw new lx(`Protected resource ${o.resource} does not match expected ${u}`)}if(!o?.authorization_servers?.length)return null;let s=o.authorization_servers[0],c=await this.discoverAuthorizationServerMetadata(s);return c?this.metadataToOAuthConfig(c):null}static extractBaseUrl(e){let r=new URL(e);return`${r.protocol}//${r.host}`}static isSSEEndpoint(e){return e.includes("/sse")||!e.includes("/mcp")}static buildResourceParameter(e){let r=new URL(e);return`${r.protocol}//${r.host}${r.pathname}`}static isEquivalentResourceIdentifier(e,r){let n=o=>{try{return this.buildResourceParameter(o)}catch{return o}};return n(e)===n(r)}static parseTokenExpiry(e){try{let r=JSON.parse(Buffer.from(e.split(".")[1],"base64").toString());if(r&&typeof r.exp=="number")return r.exp*1e3}catch(r){B.error("Failed to parse ID token for expiry time with error:",r)}}};var fhr=/^(.*\.)?run\.app$/,Wbi=[/^.+\.googleapis\.com$/,fhr],Lpe=class extends dh{config;type="google-credentials";auth;useIdToken=!1;audience;cachedToken;tokenExpiryTime;constructor(e,r){if(super(),this.config=e,!r)throw new Error("targetUrl must be provided to GoogleCredentialsAuthProvider to determine token audience.");let n=new URL(r).hostname;if(fhr.test(n)&&(this.useIdToken=!0),this.audience=n,!this.useIdToken&&!Wbi.some(c=>c.test(n)))throw new Error(`Host "${n}" is not an allowed host for Google Credential provider.`);let s=this.config.scopes&&this.config.scopes.length>0?this.config.scopes:["https://www.googleapis.com/auth/cloud-platform"];this.auth=new phr.GoogleAuth({scopes:s})}async initialize(){}async headers(){if(this.cachedToken&&this.tokenExpiryTime&&Date.now()<this.tokenExpiryTime-ID)return{Authorization:`Bearer ${this.cachedToken}`};if(this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.useIdToken)try{let r=await(await this.auth.getIdTokenClient(this.audience)).idTokenProvider.fetchIdToken(this.audience),n=qs.parseTokenExpiry(r);return n&&(this.tokenExpiryTime=n,this.cachedToken=r),{Authorization:`Bearer ${r}`}}catch(e){let r=`Failed to get ADC ID token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}try{let e=await this.auth.getClient(),r=await e.getAccessToken();if(r.token){this.cachedToken=r.token;let n=e.credentials;return n.expiry_date&&(this.tokenExpiryTime=n.expiry_date),{Authorization:`Bearer ${r.token}`}}throw new Error("Failed to retrieve ADC access token.")}catch(e){let r=`Failed to get ADC access token: ${e instanceof Error?e.message:String(e)}`;throw B.error(r,e),new Error(r)}}async shouldRetryWithHeaders(e,r){if(r.status!==401&&r.status!==403){this.authRetryCount=0;return}if(!(this.authRetryCount>=dh.MAX_AUTH_RETRIES))return this.authRetryCount++,B.debug("[GoogleCredentialsAuthProvider] Re-fetching token after auth failure"),this.cachedToken=void 0,this.tokenExpiryTime=void 0,this.headers()}};var mv=class t{static async create(e){let{agentName:r,authConfig:n,agentCard:o}=e;if(!n)return o?.securitySchemes&&Object.keys(o.securitySchemes).length>0,void 0;switch(n.type){case"google-credentials":{let s=new Lpe(n,e.targetUrl);return await s.initialize(),s}case"apiKey":{let s=new kpe(n);return await s.initialize(),s}case"http":{let s=new Dpe(n);return await s.initialize(),s}case"oauth2":{let{OAuth2AuthProvider:s}=await import("./oauth2-provider-SWSDEUUE.js"),c=new s(n,e.agentName??"unknown",o,e.agentCardUrl);return await c.initialize(),c}case"openIdConnect":throw new Error("openIdConnect auth provider not yet implemented");default:{let s=n;throw new Error(`Unknown auth type: ${s.type}`)}}}static async createFromConfig(e,r){return await t.create({authConfig:e,agentName:r})}static validateAuthConfig(e,r){if(!r||Object.keys(r).length===0)return{valid:!0};let n=Object.keys(r);if(!e)return{valid:!1,diff:{requiredSchemes:n,configuredType:void 0,missingConfig:["Authentication is required but not configured"]}};let o=t.findMatchingScheme(e,r);return o.matched?{valid:!0}:{valid:!1,diff:{requiredSchemes:n,configuredType:e.type,missingConfig:o.missingConfig}}}static findMatchingScheme(e,r){let n=[];for(let[o,s]of Object.entries(r))switch(s.type){case"apiKey":if(e.type==="apiKey")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires apiKey authentication`);break;case"http":if(e.type==="http"){if(e.scheme.toLowerCase()===s.scheme.toLowerCase())return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication, but ${e.scheme} was configured`)}else{if(e.type==="google-credentials"&&s.scheme.toLowerCase()==="bearer")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires HTTP ${s.scheme} authentication`)}break;case"oauth2":if(e.type==="oauth2")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OAuth 2.0 authentication`);break;case"openIdConnect":if(e.type==="openIdConnect")return{matched:!0,missingConfig:[]};n.push(`Scheme '${o}' requires OpenID Connect authentication`);break;case"mutualTLS":n.push(`Scheme '${o}' requires mTLS authentication (not yet supported)`);break;default:{let c=s;n.push(`Unknown security scheme type: ${c.type}`)}}return{matched:!1,missingConfig:n}}static describeRequiredAuth(e){let r=[];for(let[n,o]of Object.entries(e))switch(o.type){case"apiKey":r.push(`API Key (${n}): Send ${o.name} in ${o.in}`);break;case"http":r.push(`HTTP ${o.scheme} (${n})`);break;case"oauth2":r.push(`OAuth 2.0 (${n})`);break;case"openIdConnect":r.push(`OpenID Connect (${n})`);break;case"mutualTLS":r.push(`Mutual TLS (${n})`);break;default:{let s=o;r.push(`Unknown (${n}): ${s.type}`)}}return r.join(" OR ")}};var Xm=class extends Error{userMessage;agentName;constructor(e,r,n,o){super(r,o),this.name="A2AAgentError",this.agentName=e,this.userMessage=n}},SHe=class extends Xm{constructor(e,r){let n=`Agent card not found at ${r} (HTTP 404)`,o=`Agent card not found (404) at ${r}. Verify the agent_card_url in your agent definition.`;super(e,n,o),this.name="AgentCardNotFoundError"}},Mpe=class extends Xm{statusCode;constructor(e,r,n){let o=n===401?"Unauthorized":"Forbidden",s=`Agent card request returned ${n} ${o} for ${r}`,c=`Authentication failed (${n} ${o}) at ${r}. Check the "auth" configuration in your agent definition.`;super(e,s,c),this.name="AgentCardAuthError",this.statusCode=n}},Bpe=class extends Xm{requiredAuth;missingFields;constructor(e,r,n){let o=`Agent "${e}" requires authentication but none is configured`,s=`Agent requires ${r} but no auth is configured. Missing: ${n.join(", ")}`;super(e,o,s),this.name="AgentAuthConfigMissingError",this.requiredAuth=r,this.missingFields=n}},Upe=class extends Xm{constructor(e,r,n){let o=n instanceof Error?n.message:String(n),s=`Failed to connect to agent "${e}" at ${r}: ${o}`,c=`Connection failed for ${r}: ${o}`;super(e,s,c,{cause:n}),this.name="AgentConnectionError"}};function Ybi(t){return typeof t=="object"&&t!==null}function Jbi(t){let e=[],r=t,n=0,o=10;for(;r&&n<o;){if(Ybi(r)){let s=r;r instanceof Error?e.push(r.message):typeof s.message=="string"&&e.push(s.message),typeof s.code=="string"&&e.push(s.code),typeof s.status=="number"?e.push(String(s.status)):typeof s.statusCode=="number"&&e.push(String(s.statusCode)),r=s.cause}else if(typeof r=="string"){e.push(r);break}else{e.push(String(r));break}n++}return e.join(" ")}function hhr(t,e,r){let n=Jbi(r);return/\b(ECONNREFUSED|ENOTFOUND|EHOSTUNREACH|ETIMEDOUT)\b/i.test(n)?new Upe(t,e,r):/\b404\b|\bnot[\s_-]?found\b/i.test(n)?new SHe(t,e):/\b401\b|unauthorized/i.test(n)?new Mpe(t,e,401):/\b403\b|forbidden/i.test(n)?new Mpe(t,e,403):new Upe(t,e,r)}function Wj(t){return`${t.name}-config`}var Fpe=class{config;agents=new Map;allDefinitions=new Map;builtInAgents=new Set;constructor(e){this.config=e}async initialize(){be.on(Nr.ModelChanged,this.onModelChanged),await this.loadAgents()}isBuiltIn(e){return this.builtInAgents.has(e)}onModelChanged=()=>{this.refreshAgents("local").catch(e=>{B.error("[AgentRegistry] Failed to refresh agents on model change:",e)})};async reload(){this.config.getA2AClientManager()?.clearCache(),await this.config.reloadAgents(),this.agents.clear(),this.allDefinitions.clear(),await this.loadAgents(),be.emitAgentsRefreshed()}async acknowledgeAgent(e){let r=this.config.getAcknowledgedAgentsService(),n=this.config.getProjectRoot();e.metadata?.hash&&(await r.acknowledge(n,e.name,e.metadata.hash),await this.registerAgent(e),be.emitAgentsRefreshed())}dispose(){be.off(Nr.ModelChanged,this.onModelChanged)}async loadAgents(){if(this.agents.clear(),this.allDefinitions.clear(),this.loadBuiltInAgents(),!this.config.isAgentsEnabled())return;let e=Jt.getUserAgentsDir(),r=await _He(e);for(let s of r.errors)B.warn(`[AgentRegistry] Error loading user agent: ${s.message}`),be.emitFeedback("error",`Agent loading error: ${s.message}`);await Promise.allSettled(r.agents.map(async s=>{try{await this.registerAgent(s)}catch(c){B.warn(`[AgentRegistry] Error registering user agent "${s.name}":`,c),be.emitFeedback("error",`Error registering user agent "${s.name}": ${c instanceof Error?c.message:String(c)}`)}}));let n=this.config.getFolderTrust(),o=this.config.isTrustedFolder();if(!n||o){let s=this.config.storage.getProjectAgentsDir(),c=await _He(s);for(let p of c.errors)be.emitFeedback("error",`Agent loading error: ${p.message}`);let u=this.config.getAcknowledgedAgentsService(),d=this.config.getProjectRoot(),l=[],a=[];for(let p of c.agents){if(p.kind==="remote"&&(p.metadata||(p.metadata={}),p.metadata.hash=p.agentCardUrl??(p.agentCardJson?ghr.createHash("sha256").update(p.agentCardJson).digest("hex"):void 0)),!p.metadata?.hash){a.push(p);continue}await u.isAcknowledged(d,p.name,p.metadata.hash)?a.push(p):l.push(p)}l.length>0&&be.emitAgentsDiscovered(l),await Promise.allSettled(a.map(async p=>{try{await this.registerAgent(p)}catch(f){B.warn(`[AgentRegistry] Error registering project agent "${p.name}":`,f),be.emitFeedback("error",`Error registering project agent "${p.name}": ${f instanceof Error?f.message:String(f)}`)}}))}else be.emitFeedback("info","Skipping project agents due to untrusted folder. To enable, ensure that the project root is trusted.");for(let s of this.config.getExtensions())s.isActive&&s.agents&&await Promise.allSettled(s.agents.map(async c=>{try{await this.registerAgent(c)}catch(u){B.warn(`[AgentRegistry] Error registering extension agent "${c.name}":`,u),be.emitFeedback("error",`Error registering extension agent "${c.name}": ${u instanceof Error?u.message:String(u)}`)}}));this.config.getDebugMode()&&B.log(`[AgentRegistry] Loaded with ${this.agents.size} agents.`)}loadBuiltInAgents(){let e=lde(this.config);this.builtInAgents.add(e.name),this.registerLocalAgent(e);let r=ohr(this.config);this.builtInAgents.add(r.name),this.registerLocalAgent(r);let n=shr(this.config);this.builtInAgents.add(n.name),this.registerLocalAgent(n);let o=this.config.getBrowserAgentConfig();if(o.enabled){let s=process.env.SANDBOX,c=!!s&&s!=="sandbox-exec"&&s!=="sandbox:none",u=o.customConfig.sessionMode??"persistent";if(c&&u!=="existing")be.emitFeedback("info",'Browser agent disabled in container sandbox. To use it, set sessionMode to "existing" in settings and start Chrome with --remote-debugging-port=9222 on the host.');else{let d=Npe(this.config);this.builtInAgents.add(d.name),this.registerLocalAgent(d)}}this.config.isMemoryManagerEnabled()&&this.registerLocalAgent(chr(this.config))}async refreshAgents(e="all"){this.loadBuiltInAgents(),await Promise.allSettled(Array.from(this.agents.values()).map(async r=>{(e==="all"||r.kind===e)&&await this.registerAgent(r)}))}async registerAgent(e){e.kind==="local"?this.registerLocalAgent(e):e.kind==="remote"&&await this.registerRemoteAgent(e)}registerLocalAgent(e){if(e.kind!=="local")return;if(!e.name||!e.description){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name or description.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=this.applyOverrides(e,r);this.agents.set(n.name,n),this.registerModelConfigs(n),this.addAgentPolicy(n)}addAgentPolicy(e){let r=this.config.getPolicyEngine();if(r){if(r.hasRuleForTool(e.name,!0)){this.config.getDebugMode()&&B.log(`[AgentRegistry] User policy exists for '${e.name}', skipping dynamic registration.`);return}r.removeRulesForTool(e.name,"AgentRegistry (Dynamic)"),r.addRule({toolName:e.name,decision:e.kind==="local"?tt.ALLOW:tt.ASK_USER,priority:Tq,source:"AgentRegistry (Dynamic)"})}}isAgentEnabled(e,r){let o=!(e.experimental===!0);return r&&r.enabled!==void 0&&(o=r.enabled),o}async registerRemoteAgent(e){if(e.kind!=="remote")return;if(!e.name){B.warn("[AgentRegistry] Skipping invalid agent definition. Missing name.");return}this.allDefinitions.set(e.name,e);let r=this.config.getAgentsSettings().overrides?.[e.name];if(!this.isAgentEnabled(e,r)){this.config.getDebugMode()&&B.log(`[AgentRegistry] Skipping disabled remote agent '${e.name}'`);return}this.agents.has(e.name)&&this.config.getDebugMode()&&B.log(`[AgentRegistry] Overriding agent '${e.name}'`);let n=e;n.originalDescription===void 0&&(n.originalDescription=n.description);try{let o=this.config.getA2AClientManager();if(!o){B.warn(`[AgentRegistry] Skipping remote agent '${e.name}': A2AClientManager is not available.`);return}let s=vpe(n),c;if(e.auth){let p=await mv.create({authConfig:e.auth,agentName:e.name,targetUrl:s,agentCardUrl:n.agentCardUrl});if(!p)throw new Error(`Failed to create auth provider for agent '${e.name}'`);c=p}let u=await o.loadAgent(n.name,bpe(n),c);if(u.securitySchemes){let p=mv.validateAuthConfig(e.auth,u.securitySchemes);if(!p.valid&&p.diff){let f=mv.describeRequiredAuth(u.securitySchemes),g=new Bpe(e.name,f,p.diff.missingConfig);be.emitFeedback("warning",`[${e.name}] Agent requires authentication: ${f}`),B.warn(`[AgentRegistry] ${g.message}`)}}let d=n.originalDescription,l=u.description,a=[];if(d?.trim()&&a.push(`User Description: ${d.trim()}`),l?.trim()&&a.push(`Agent Description: ${l.trim()}`),u.skills&&u.skills.length>0){let p=u.skills.map(f=>`${f.name}: ${f.description||"No description provided"}`).join(`
2945
2945
  `);a.push(`Skills:
2946
2946
  ${p}`)}a.length>0&&(e.description=a.join(`
2947
2947
  `)),this.config.getDebugMode()&&B.log(`[AgentRegistry] Registered remote agent '${e.name}' with card: ${e.agentCardUrl??"inline JSON"}`),this.agents.set(e.name,e),this.addAgentPolicy(e)}catch(o){o instanceof Xm?be.emitFeedback("error",`[${e.name}] ${o.userMessage}`):be.emitFeedback("error",`[${e.name}] Failed to load remote agent: ${o instanceof Error?o.message:String(o)}`),B.warn(`[AgentRegistry] Error loading A2A agent "${e.name}":`,o)}}applyOverrides(e,r){if(e.kind!=="local"||!r)return e;let n={get kind(){return e.kind},get name(){return e.name},get displayName(){return e.displayName},get description(){return e.description},get experimental(){return e.experimental},get metadata(){return e.metadata},get inputConfig(){return e.inputConfig},get outputConfig(){return e.outputConfig},get promptConfig(){return e.promptConfig},get toolConfig(){return e.toolConfig},get processOutput(){return e.processOutput},get runConfig(){return r.runConfig?{...e.runConfig,...r.runConfig}:e.runConfig},get modelConfig(){return r.modelConfig?yD.merge(e.modelConfig,r.modelConfig):e.modelConfig}};return r.tools&&(n.toolConfig={tools:r.tools}),r.mcpServers&&(n.mcpServers={...e.mcpServers,...r.mcpServers}),n}registerModelConfigs(e){let r=e.modelConfig,n=r.model;n==="inherit"&&(n=this.config.getModel());let o={...r,model:n};this.config.modelConfigService.registerRuntimeModelConfig(Wj(e),{modelConfig:o}),o.model&&Ys(o.model)&&this.config.modelConfigService.registerRuntimeModelOverride({match:{overrideScope:e.name},modelConfig:{generateContentConfig:o.generateContentConfig}})}getDefinition(e){return this.agents.get(e)}getAllDefinitions(){return Array.from(this.agents.values())}getAllAgentNames(){return Array.from(this.agents.keys())}getAllDiscoveredAgentNames(){return Array.from(this.allDefinitions.keys())}getDiscoveredDefinition(e){return this.allDefinitions.get(e)}};import*as RD from"node:fs/promises";import*as mhr from"node:path";var jpe=class{acknowledgedAgents={};loaded=!1;async load(){if(this.loaded)return;let e=Jt.getAcknowledgedAgentsPath();try{let r=await RD.readFile(e,"utf-8");this.acknowledgedAgents=JSON.parse(r)}catch(r){(!xt(r)||r.code!=="ENOENT")&&B.error("Failed to load acknowledged agents:",Te(r)),this.acknowledgedAgents={}}this.loaded=!0}async save(){let e=Jt.getAcknowledgedAgentsPath();try{let r=mhr.dirname(e);await RD.mkdir(r,{recursive:!0}),await RD.writeFile(e,JSON.stringify(this.acknowledgedAgents,null,2),"utf-8")}catch(r){B.error("Failed to save acknowledged agents:",Te(r))}}async isAcknowledged(e,r,n){await this.load();let o=this.acknowledgedAgents[e];return o?o[r]===n:!1}async acknowledge(e,r,n){await this.load(),this.acknowledgedAgents[e]||(this.acknowledgedAgents[e]={}),this.acknowledgedAgents[e][r]=n,await this.save()}};function Qpe(t,e){let r=/\$\{(\w+)\}/g,n=new Set(Array.from(t.matchAll(r),c=>c[1])),o=new Set(Object.keys(e)),s=Array.from(n).filter(c=>!o.has(c));if(s.length>0)throw new Error(`Template validation failed: Missing required input parameters: ${s.join(", ")}. Available inputs: ${Object.keys(e).join(", ")}`);return t.replace(r,(c,u)=>String(e[u]))}import{AsyncLocalStorage as Kbi}from"node:async_hooks";var yhr=new Kbi;function THe(t,e){return yhr.run(t,e)}function qpe(){return yhr.getStore()}var Ahr=Fe(_ae(),1);function Yj(t){return typeof t=="object"&&t!==null&&"callId"in t&&"responseParts"in t}function I8o(t){let{displayName:e,status:r,approvalMode:n,hasResultDisplay:o,parentCallId:s}=t;if(s)return!0;switch(e){case M3:switch(r){case Be.Scheduled:case Be.Validating:case Be.Executing:case Be.AwaitingApproval:return!0;case Be.Error:return!o;default:return!1}case Yq:case Jq:return n===Kt.PLAN;default:return!1}}function Jj(t,e,r=3){let n=e.map(c=>({name:c,distance:Ahr.default.get(t,c)}));n.sort((c,u)=>c.distance-u.distance);let o=n.slice(0,r);if(o.length===0)return"";let s=o.map(c=>`"${c.name}"`).join(", ");return o.length>1?` Did you mean one of: ${s}?`:` Did you mean ${s}?`}function R8o(t,e,r){let n;Cq(t)?n=[t.name,t.constructor.name]:n=[t],n.some(o=>Ih.includes(o))&&(n=[...new Set([...n,...Ih])]);for(let o of r){let s=o.indexOf("(");if(s===-1){if(n.includes(o))return!0;continue}let c=o.substring(0,s);if(!n.includes(c)||!o.endsWith(")"))continue;let u=o.substring(s+1,o.length-1),d;if(typeof e=="string")d=e;else{if(!("command"in e.params))continue;d=String(e.params.command)}if(n.some(l=>Ih.includes(l))&&(d===u||d.startsWith(u+" ")))return!0}return!1}var Gpe=class{messageBus;schedulerId;onTerminalCall;activeCalls=new Map;queue=[];_completedBatch=[];constructor(e,r=aot,n){this.messageBus=e,this.schedulerId=r,this.onTerminalCall=n}addToolCalls(e){this.enqueue(e)}getToolCall(e){return this.activeCalls.get(e)||this.queue.find(r=>r.request.callId===e)||this._completedBatch.find(r=>r.request.callId===e)}enqueue(e){this.queue.push(...e),this.emitUpdate()}dequeue(){let e=this.queue.shift();return e&&(this.activeCalls.set(e.request.callId,e),this.emitUpdate()),e}peekQueue(){return this.queue[0]}get isActive(){return this.activeCalls.size>0}get allActiveCalls(){return Array.from(this.activeCalls.values())}get activeCallCount(){return this.activeCalls.size}get queueLength(){return this.queue.length}get firstActiveCall(){return this.activeCalls.values().next().value}updateStatus(e,r,n){let o=this.activeCalls.get(e);if(!o)return;let s=this.transitionCall(o,r,n);this.activeCalls.set(e,s),this.emitUpdate()}finalizeCall(e){let r=this.activeCalls.get(e);r&&this.isTerminalCall(r)&&(this._completedBatch.push(r),this.activeCalls.delete(e),this.onTerminalCall?.(r),this.emitUpdate())}updateArgs(e,r,n){let o=this.activeCalls.get(e);!o||o.status===Be.Error||(this.activeCalls.set(e,this.patchCall(o,{request:{...o.request,args:r},invocation:n})),this.emitUpdate())}setOutcome(e,r){let n=this.activeCalls.get(e);n&&(this.activeCalls.set(e,this.patchCall(n,{outcome:r})),this.emitUpdate())}replaceActiveCallWithTailCall(e,r){this.activeCalls.has(e)&&(this.activeCalls.delete(e),this.queue.unshift(r),this.emitUpdate())}cancelAllQueued(e){if(this.queue.length!==0){for(;this.queue.length>0;){let r=this.queue.shift();if(r.status===Be.Error){this._completedBatch.push(r),this.onTerminalCall?.(r);continue}let n=this.toCancelled(r,e);this._completedBatch.push(n),this.onTerminalCall?.(n)}this.emitUpdate()}}getSnapshot(){return[...this._completedBatch,...Array.from(this.activeCalls.values()),...this.queue]}clearBatch(){this._completedBatch.length!==0&&(this._completedBatch=[],this.emitUpdate())}get completedBatch(){return[...this._completedBatch]}emitUpdate(){let e=this.getSnapshot();this.messageBus.publish({type:Li.TOOL_CALLS_UPDATE,toolCalls:e,schedulerId:this.schedulerId})}isTerminalCall(e){let{status:r}=e;return r===Be.Success||r===Be.Error||r===Be.Cancelled}transitionCall(e,r,n){switch(r){case Be.Success:{if(!Yj(n))throw new Error(`Invalid data for 'success' transition (callId: ${e.request.callId})`);return this.toSuccess(e,n)}case Be.Error:{if(!Yj(n))throw new Error(`Invalid data for 'error' transition (callId: ${e.request.callId})`);return this.toError(e,n)}case Be.AwaitingApproval:{if(!n)throw new Error(`Missing data for 'awaiting_approval' transition (callId: ${e.request.callId})`);return this.toAwaitingApproval(e,n)}case Be.Scheduled:return this.toScheduled(e);case Be.Cancelled:{if(typeof n!="string"&&!Yj(n))throw new Error(`Invalid reason (string) or response for 'cancelled' transition (callId: ${e.request.callId})`);return this.toCancelled(e,n)}case Be.Validating:return this.toValidating(e);case Be.Executing:{if(n!==void 0&&!this.isExecutingToolCallPatch(n))throw new Error(`Invalid patch for 'executing' transition (callId: ${e.request.callId})`);return this.toExecuting(e,n)}default:return r}}isExecutingToolCallPatch(e){return typeof e=="object"&&e!==null}validateHasToolAndInvocation(e,r){if(!("tool"in e&&e.tool&&"invocation"in e&&e.invocation))throw new Error(`Invalid state transition: cannot transition to ${r} without tool/invocation (callId: ${e.request.callId})`)}toSuccess(e,r){this.validateHasToolAndInvocation(e,Be.Success);let n="startTime"in e?e.startTime:void 0;return{request:e.request,tool:e.tool,invocation:e.invocation,status:Be.Success,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toError(e,r){let n="startTime"in e?e.startTime:void 0;return{request:e.request,status:Be.Error,tool:"tool"in e?e.tool:void 0,response:r,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toAwaitingApproval(e,r){this.validateHasToolAndInvocation(e,Be.AwaitingApproval);let n,o;return this.isEventDrivenApprovalData(r)?(o=r.correlationId,n=r.confirmationDetails):n=r,{request:e.request,tool:e.tool,status:Be.AwaitingApproval,correlationId:o,confirmationDetails:n,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isEventDrivenApprovalData(e){return typeof e=="object"&&e!==null&&"correlationId"in e&&"confirmationDetails"in e}toScheduled(e){return this.validateHasToolAndInvocation(e,Be.Scheduled),{request:e.request,tool:e.tool,status:Be.Scheduled,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toCancelled(e,r){this.validateHasToolAndInvocation(e,Be.Cancelled);let n="startTime"in e?e.startTime:void 0,o;if(this.isWaitingToolCall(e)){let u=e.confirmationDetails;u.type==="edit"&&"fileDiff"in u&&"fileName"in u&&"filePath"in u&&"originalContent"in u&&"newContent"in u&&(o={fileDiff:u.fileDiff,fileName:u.fileName,filePath:u.filePath,originalContent:u.originalContent,newContent:u.newContent,diffStat:u.diffStat??hXe(u.fileDiff)})}let s;if(e.status===Be.Executing&&e.liveOutput&&(s=e.liveOutput),Yj(r)){let u={...r};return u.resultDisplay||(u.resultDisplay=o??s),{request:e.request,tool:e.tool,invocation:e.invocation,status:Be.Cancelled,response:u,durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}let c=`[Operation Cancelled] Reason: ${r}`;return{request:e.request,tool:e.tool,invocation:e.invocation,status:Be.Cancelled,response:{callId:e.request.callId,responseParts:[{functionResponse:{id:e.request.callId,name:e.request.originalRequestName??e.request.name,response:{error:c}}}],resultDisplay:o??s,error:void 0,errorType:void 0,contentLength:c.length},durationMs:n?Date.now()-n:void 0,outcome:e.outcome,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}isWaitingToolCall(e){return e.status===Be.AwaitingApproval}patchCall(e,r){return{...e,...r}}toValidating(e){return this.validateHasToolAndInvocation(e,Be.Validating),{request:e.request,tool:e.tool,status:Be.Validating,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}toExecuting(e,r){this.validateHasToolAndInvocation(e,Be.Executing);let n=r,o=n?.liveOutput??("liveOutput"in e?e.liveOutput:void 0),s=n?.pid??("pid"in e?e.pid:void 0),c=n?.progressMessage??("progressMessage"in e?e.progressMessage:void 0),u=n?.progressPercent??("progressPercent"in e?e.progressPercent:void 0),d=n?.progress??("progress"in e?e.progress:void 0),l=n?.progressTotal??("progressTotal"in e?e.progressTotal:void 0);return{request:e.request,tool:e.tool,status:Be.Executing,startTime:"startTime"in e?e.startTime:void 0,outcome:e.outcome,invocation:e.invocation,liveOutput:o,pid:s,progressMessage:c,progressPercent:u,progress:d,progressTotal:l,schedulerId:e.schedulerId,approvalMode:e.approvalMode}}};import{on as Xbi}from"node:events";import{randomUUID as Zbi}from"node:crypto";async function e1i(t,e,r){if(r.aborted)throw new Error("Operation cancelled");try{for await(let[n]of Xbi(t,Li.TOOL_CONFIRMATION_RESPONSE,{signal:r})){let o=n;if(o.correlationId===e)return{outcome:o.outcome??(o.confirmed?Vt.ProceedOnce:Vt.Cancel),payload:o.payload}}}catch(n){throw r.aborted||n.name==="AbortError"?new Error("Operation cancelled"):n}throw new Error("Operation cancelled")}async function wHe(t,e,r){let{state:n,onWaitingForConfirmation:o}=r,s=t.request.callId,c=Vt.ModifyWithEditor,u;for(;c===Vt.ModifyWithEditor;){if(e.aborted)throw new Error("Operation cancelled by user");let d=n.getToolCall(s);if(!d||!("invocation"in d))throw new Error(`Tool call ${s} lost during confirmation loop`);let a=await d.invocation.shouldConfirmExecute(e,r.forcedDecision);if(!a){c=Vt.ProceedOnce;break}r.systemMessage&&(a.systemMessage=r.systemMessage),await t1i(r,a);let p=Zbi(),f=a;u=f;let g="ideConfirmation"in a?a.ideConfirmation:void 0;n.updateStatus(s,Be.AwaitingApproval,{confirmationDetails:f,correlationId:p}),o?.(!0);let y=await i1i(r.messageBus,p,e,g);if(o?.(!1),c=y.outcome,"onConfirm"in a&&typeof a.onConfirm=="function"&&await a.onConfirm(c,y.payload),c===Vt.ModifyWithEditor){let _=await r1i(r,t,e);_.error&&be.emitFeedback("error",_.error)}else y.payload&&"newContent"in y.payload&&(await n1i(r,t,y.payload,e),c=Vt.ProceedOnce)}return{outcome:c,lastDetails:u}}async function t1i(t,e){t.config.getHookSystem()&&await t.config.getHookSystem()?.fireToolNotificationEvent({...e,onConfirm:async()=>{}})}async function r1i(t,e,r){let{state:n,modifier:o,getPreferredEditor:s}=t,c=s(),u=await i4t(c,r);if(!u)return{error:e4t};let d=await o.handleModifyWithEditor(n.firstActiveCall,u,r);if(d){let l=e.tool.build(d.updatedParams);n.updateArgs(e.request.callId,d.updatedParams,l)}return{}}async function n1i(t,e,r,n){let{state:o,modifier:s}=t,c=await s.applyInlineModify(o.firstActiveCall,r,n);if(c){let u=e.tool.build(c.updatedParams);o.updateArgs(e.request.callId,c.updatedParams,u)}}async function i1i(t,e,r,n){let o=new AbortController,s=o.signal,c=()=>o.abort();r.aborted?o.abort():r.addEventListener("abort",c);try{let u=e1i(t,e,s);if(!n)return await u;let d=n.then(l=>({outcome:l.status==="accepted"?Vt.ProceedOnce:Vt.Cancel,payload:l.content?{newContent:l.content}:void 0})).catch(l=>(B.warn("Error waiting for confirmation via IDE",l),new Promise(()=>{})));return await Promise.race([u,d])}finally{r.removeEventListener("abort",c),o.abort()}}function _hr(t,e){return{errorMessage:`Tool execution denied by policy.${e?.denyMessage?` ${e.denyMessage}`:""}`,errorType:De.POLICY_VIOLATION}}async function Ehr(t,e,r){let n=t.tool instanceof yi?t.tool.serverName:void 0,o=t.tool.toolAnnotations,s=await e.getPolicyEngine().check({name:t.request.name,args:t.request.args},n,o,r),{decision:c}=s;if(c===tt.ASK_USER&&t.request.isClientInitiated&&!t.request.args?.additional_permissions)return{decision:tt.ALLOW,rule:s.rule};if(c===tt.ASK_USER&&!e.isInteractive())throw new Error(`Tool execution for "${t.tool.displayName||t.tool.name}" requires user confirmation, which is not supported in non-interactive mode.`);return{decision:c,rule:s.rule}}async function bhr(t,e,r,n,o,s){if(o1i(t,e)){n.config.setApprovalMode(Kt.AUTO_EDIT);return}let c,u,d=n.config.getApprovalMode();if(e===Vt.ProceedAlways||e===Vt.ProceedAlwaysTool||e===Vt.ProceedAlwaysServer||e===Vt.ProceedAlwaysAndSave){let l=gme.indexOf(d);l!==-1&&(u=gme.slice(l))}if(e===Vt.ProceedAlwaysAndSave&&(n.config&&n.config.isTrustedFolder()&&n.config.getWorkspacePoliciesDir()!==void 0?c="workspace":c="user"),r?.type==="mcp"){await a1i(t,e,r,o,c,u);return}await s1i(t,e,r,o,c,s,n.config,u)}function o1i(t,e){return e===Vt.ProceedAlways&&L3.has(t.name)}async function s1i(t,e,r,n,o,s,c,u){if(e===Vt.ProceedAlways||e===Vt.ProceedAlwaysAndSave){let d=s?.getPolicyUpdateOptions?.(e)||{};if(!d.commandPrefix&&r?.type==="exec")d.commandPrefix=r.rootCommands;else if(!d.argsPattern&&r?.type==="edit"){let l=c?Ho(r.filePath,c.getTargetDir()):r.filePath;d.argsPattern=Gb(l)}await n.publish({type:Li.UPDATE_POLICY,toolName:t.name,persist:e===Vt.ProceedAlwaysAndSave,persistScope:o,modes:u,...d})}}async function a1i(t,e,r,n,o,s){if(!(e===Vt.ProceedAlways||e===Vt.ProceedAlwaysTool||e===Vt.ProceedAlwaysServer||e===Vt.ProceedAlwaysAndSave))return;let u=t.name,d=e===Vt.ProceedAlwaysAndSave;e===Vt.ProceedAlwaysServer&&(u=Xv(r.serverName,"*")),await n.publish({type:Li.UPDATE_POLICY,toolName:u,mcpName:r.serverName,persist:d,persistScope:o,modes:s})}function CHe(t,e){if(!(t instanceof MXe))return;let n=(e.getMcpClientManager()?.getMcpServers()??e.getMcpServers()??{})[t.serverName];if(n)return{server_name:t.serverName,tool_name:t.serverToolName,command:n.command,args:n.args,cwd:n.cwd,url:n.url??n.httpUrl,tcp:n.tcp}}async function vhr(t,e,r,n,o,s,c,u,d){let l=t.params||{},a=!1,p=[],f=c?CHe(t,c):void 0,g=c?.getHookSystem();if(g&&!d){let _=await g.fireBeforeToolEvent(e,l,f,u);if(_?.shouldStopExecution()){let b=_.getEffectiveReason();return{llmContent:`Agent execution stopped by hook: ${b}`,returnDisplay:`Agent execution stopped by hook: ${b}`,error:{type:De.STOP_EXECUTION,message:b}}}let E=_?.getBlockingError();if(E?.blocked)return{llmContent:`Tool execution blocked: ${E.reason}`,returnDisplay:`Tool execution blocked: ${E.reason}`,error:{type:De.EXECUTION_FAILED,message:E.reason}};if(_ instanceof wA){let b=_.getModifiedToolInput();if(b){Object.assign(t.params,b),B.debug(`Tool input modified by hook for ${e}`),a=!0,p=Object.keys(b);try{t=n.build(t.params)}catch(v){return{llmContent:`Tool parameter modification by hook failed validation: ${v instanceof Error?v.message:String(v)}`,returnDisplay:"Tool parameter modification by hook failed validation.",error:{type:De.INVALID_TOOL_PARAMS,message:String(v)}}}}}}let y=await t.execute(r,o,s);if(a){let _=`