@tencent-ai/codebuddy-code 2.142.0-dev.4fe381f.202609031343 → 2.142.0-dev.fe3dd20.202609032157
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/codebuddy-headless.js +3 -3
- package/dist/codebuddy.js +3 -3
- package/dist-server/4923.codebuddy.js +2 -2
- package/dist-server/codebuddy.js +1 -1
- package/dist-server/types/node/agent-home/agent-home-channel-events.d.ts +8 -0
- package/dist-server/types/node/agent-home/agent-home-directory-lock.d.ts +12 -0
- package/dist-server/types/node/agent-view/job-control-client.d.ts +24 -0
- package/dist-server/types/node/package.d.ts +2 -0
- package/package.json +1 -1
- package/product.cloudhosted.json +2 -2
- package/product.internal.json +2 -2
- package/product.ioa.json +2 -2
- package/product.json +2 -2
- package/product.selfhosted.json +2 -2
- package/dist-server/types/node/runtime/add-dir-middleware.d.ts +0 -13
- package/dist-server/types/node/runtime/external-uri-opener.d.ts +0 -8
- package/dist-server/types/node/runtime/file-local-storage.d.ts +0 -17
- package/dist-server/types/node/runtime/workspace-folder-manager.d.ts +0 -45
- package/dist-server/types/node/runtime/workspace.d.ts +0 -5
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";exports.ids=["4923"],exports.modules={33884(e,t,r){r.r(t),r.d(t,{buildPlaceholderAgentCard:()=>buildPlaceholderAgentCard});var o=r(48400);function buildPlaceholderAgentCard(){let{version:e}=o.PackageUtils.getCurrentPackageJson();return{name:"CodeBuddy Code",description:"CodeBuddy Code A2A inbound agent (SendMessage/GetTask/CancelTask only).",version:"string"==typeof e&&e.length>0?e:"0.0.0",provider:void 0,supportedInterfaces:[],capabilities:{streaming:!1,pushNotifications:!1,extendedAgentCard:!1,extensions:[]},securitySchemes:{},securityRequirements:[],defaultInputModes:["text"],defaultOutputModes:["text"],skills:[],signatures:[]}}},75505(e,t,r){r.r(t),r.d(t,{A2aAgentExecutor:()=>o,A2aInboundView:()=>i});let o=Symbol("A2aAgentExecutor"),i=Symbol("A2aInboundView")},4324(e,t,r){r.r(t),r.d(t,{A2aLineDispatcher:()=>A2aLineDispatcher,isA2aJsonRpcLine:()=>isA2aJsonRpcLine});var o=r(6757),i=r(477),n=r(33884);function isA2aJsonRpcLine(e){return"object"==typeof e&&null!==e&&"2.0"===e.jsonrpc}let A2aLineDispatcher=class A2aLineDispatcher{constructor(e,t,r={}){this.logger=t,this.options=r,this.sendMessageQueue=Promise.resolve();const o=new i.DefaultRequestHandler((0,n.buildPlaceholderAgentCard)(),new i.InMemoryTaskStore,e);this.transport=new i.JsonRpcTransportHandler(o),this.callContext=new i.ServerCallContext({})}isSendMessageLine(e){try{let t=JSON.parse(e);return"SendMessage"===t.method}catch{return!1}}async dispatch(e){if(this.isSendMessageLine(e)){let t=this.sendMessageQueue.then(()=>this.handle(e));return this.sendMessageQueue=t.then(()=>void 0,()=>void 0),t}return this.handle(e)}async handle(e){let t=this.checkBoundSession(e);if(t)return t;try{return await this.transport.handle(e,this.callContext)}catch(r){let t=r instanceof Error?r.message:String(r);return this.logger.error?.(`[A2aLineDispatcher] transport.handle() threw unexpectedly: ${t}`),{jsonrpc:"2.0",id:this.extractId(e),error:{code:o.A2A_ERROR_CODE.INTERNAL_ERROR,message:t}}}}checkBoundSession(e){let t;if(!this.options.boundSessionId)return;try{t=JSON.parse(e)}catch{return}if(t?.method!=="SendMessage")return;let reject=e=>(this.logger.warn?.(`[A2aLineDispatcher] rejecting SendMessage: ${e}`),{jsonrpc:"2.0",id:t?.id??null,error:{code:o.A2A_ERROR_CODE.INVALID_PARAMS,message:e}}),r=this.options.boundSessionId();if(!r)return reject("session is not established yet; send a stream-json user message first so this process is bound to a session, then retry with that contextId");let i=t?.params?.message?.contextId;if(i!==r)return reject("string"!=typeof i||0===i.length?`contextId is required and must be "${r}" in this session`:`contextId must be "${r}" in this session; got "${i}"`)}extractId(e){try{return JSON.parse(e).id??null}catch{return null}}}},61459(e,t,r){function isLoopbackAddress(e){if(!e)return!1;let t=e.trim().toLowerCase();if(!t)return!1;t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));let r=t.indexOf("%");if(r>=0&&(t=t.slice(0,r)),t.startsWith("::ffff:")){let e=t.slice(7);if(e.includes("."))return isLoopbackIpv4(e);let r=hexMappedToIpv4(e);return!!r&&isLoopbackIpv4(r)}return t.includes(":")?isLoopbackIpv6(t):isLoopbackIpv4(t)}function isLoopbackIpv4(e){let t=e.split(".");if(4!==t.length)return!1;let r=t.map(e=>/^\d{1,3}$/.test(e)?Number(e):-1);return!r.some(e=>e<0||e>255)&&127===r[0]}function isLoopbackIpv6(e){if("::1"===e)return!0;let t=expandIpv6(e);return!!t&&8===t.length&&t.slice(0,7).every(e=>0===e)&&1===t[7]}function expandIpv6(e){let t,r,o=e.indexOf("::");o>=0?(t=e.slice(0,o),r=e.slice(o+2)):(t=e,r="");let i=t?t.split(":"):[],n=r?r.split(":"):[],parseGroup=e=>{if(/^[0-9a-f]{1,4}$/.test(e))return parseInt(e,16)},s=[];for(let e of i){let t=parseGroup(e);if(void 0===t)return;s.push(t)}let a=[];for(let e of n){let t=parseGroup(e);if(void 0===t)return;a.push(t)}if(o>=0){let e=8-s.length-a.length;if(e<0)return;return[...s,...Array(e).fill(0),...a]}return 8===s.length?s:void 0}function hexMappedToIpv4(e){let t=e.split(":");if(2!==t.length)return;let r=t.map(e=>/^[0-9a-f]{1,4}$/.test(e)?parseInt(e,16):-1);if(r.some(e=>e<0||e>65535))return;let[o,i]=r;return`${o>>8&255}.${255&o}.${i>>8&255}.${255&i}`}r.r(t),r.d(t,{isLoopbackAddress:()=>isLoopbackAddress})},48678(e,t,r){r.r(t),r.d(t,{AcpToolInterceptorImpl:()=>c});var o=r(88523),i=r(70724),n=r(62279),s=r(48400),a=r(19160),l=r(71332);let c=class{constructor(){this.connection=null,this.backgroundTerminals={},this.fileContentCache=new Map}setConnection(e){this.connection=e}resolveAcpSessionId(e){return e.context.meta?.parentSessionId??e.context.id}getConnection(){if(!this.connection)throw Error("ACP connection not set. Call setConnection() first.");return this.connection}async readTextFile(e){let t=this.getConnection(),r=await t.readTextFile(e);return e.line||e.limit||this.fileContentCache.set(e.path,r.content),r}async writeTextFile(e){let t=this.getConnection(),r=await t.writeTextFile(e);return this.fileContentCache.set(e.path,e.content),r}getFileContentCache(){return Object.fromEntries(this.fileContentCache)}setCapabilities(e){this.capabilities=e}getCapabilities(){return this.capabilities}isSupportRead(){return!!this.capabilities?.fs?.readTextFile}async callRead(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path),r=await this.readTextFile({sessionId:o,path:t,line:e.offset,limit:e.limit}),i=r.content.split(/\r?\n/),n=this.formatContentWithLineNumbers(r.content,e.offset||1);return{title:`Read ${i.length} lines`,content:n,renderer:{type:"code",context:{language:s.LanguageUtils.getLanguageFromExtension(t)}}}}catch(t){let e=t instanceof Error?t.message:String(t);return{content:e,error:`Error reading file: ${e}`}}}formatContentWithLineNumbers(e,t){return e.split(/\r?\n/).map((e,r)=>{let o=(t+r).toString().padStart(4," ");return`${o}\u{2192}${e}`}).join("\n")}isSupportWrite(){return!!this.capabilities?.fs?.writeTextFile}async callWrite(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path);await this.writeTextFile({sessionId:o,path:t,content:e.content});let r=e.content.split(/\r?\n/),i=`Successfully wrote to file: ${t}`;return{title:`Wrote ${r.length} lines`,content:i,renderer:{type:"code",context:{language:s.LanguageUtils.getLanguageFromExtension(t)},value:e.content}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Write error: ${e}`)}}isSupportEdit(){return!!this.capabilities?.fs?.writeTextFile}async callEdit(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path),r=(await this.readTextFile({sessionId:o,path:t})).content,{newContent:i}=s.EditFileUtils.applyTextReplacementWithLocation(r,[{oldString:e.old_string,newString:e.new_string,replaceAll:e.replace_all}]);await this.writeTextFile({sessionId:o,path:t,content:i});let n=`Successfully edited file: ${t}`;return{title:"Edit applied",content:n,renderer:{type:"diff"}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Edit error: ${e}`)}}isSupportMultiEdit(){return!!this.capabilities?.fs?.writeTextFile}async callMultiEdit(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path),r=(await this.readTextFile({sessionId:o,path:t})).content,{newContent:i}=s.EditFileUtils.applyTextReplacementWithLocation(r,e.edits.map(e=>({oldString:e.old_string,newString:e.new_string,replaceAll:e.replace_all})));await this.writeTextFile({sessionId:o,path:t,content:i});let n=`Successfully applied ${e.edits.length} edit(s) to file: ${t}`;return{title:`Applied ${e.edits.length} edits`,content:n,renderer:{type:"diff"}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`MultiEdit error: ${e}`)}}isSupportBash(){return!!this.capabilities?.terminal}async callBash(e,t,r){let o=this.getConnection(),i=this.resolveAcpSessionId(t);try{let t=r?.toolCall?.callId;if("string"!=typeof t)throw Error("No tool call ID found");if(!o.createTerminal)throw Error("Terminal capability not available");let n=await o.createTerminal({command:e.command,sessionId:i,outputByteLimit:32e3});await o.sessionUpdate({sessionId:i,update:(0,l.withAcpTimestampMeta)({sessionUpdate:"tool_call_update",toolCallId:t,status:"in_progress",title:e.description,content:[{type:"terminal",terminalId:n.id}]})});let s=e.timeout||12e4,a=new Promise(e=>{setTimeout(async()=>{let t=this.backgroundTerminals[n.id];t&&"started"===t.status&&await n.kill(),e({status:"timedOut",exitStatus:null})},s)}),c=n.waitForExit().then(e=>({status:"exited",exitStatus:e}));if(e.run_in_background)return this.backgroundTerminals[n.id]={handle:n,lastOutput:null,status:"started"},Promise.race([c,a]).then(async({status:e,exitStatus:t})=>{let r=this.backgroundTerminals[n.id];if(!r||"started"!==r.status)return;let o=await n.currentOutput();this.backgroundTerminals[n.id]={status:e,pendingOutput:{...o,output:this.stripCommonPrefix(r.lastOutput?.output??"",o.output),exitStatus:t??o.exitStatus}},await n.release()}),{content:`Command started in background with id: ${n.id}`,renderer:{type:"text",value:`Command started in background with id: ${n.id}`}};let{status:d}=await Promise.race([c,a]),u=await n.currentOutput();await n.release();let p=this.formatToolCommandOutput(d,u);return{content:p,renderer:{type:"text",value:p}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Bash error: ${e}`)}}isSupportBashOutput(){return!!this.capabilities?.terminal}async callBashOutput(e,t,r){let o=this.backgroundTerminals[e.shell_id];if(!o)throw Error(`Unknown shell ${e.shell_id}`);if("started"===o.status){let e=await o.handle.currentOutput(),t=this.stripCommonPrefix(o.lastOutput?.output??"",e.output);o.lastOutput=e;let r=this.formatToolCommandOutput(o.status,{...e,output:t});return{content:r,renderer:{type:"text",value:r}}}{let e=this.formatToolCommandOutput(o.status,o.pendingOutput);return{content:e,renderer:{type:"text",value:e}}}}isSupportKillShell(){return!!this.capabilities?.terminal}async callKillShell(e,t,r){let o=this.backgroundTerminals[e.shell_id];if(!o)throw Error(`Unknown shell ${e.shell_id}`);switch(o.status){case"started":{await o.handle.kill();let e=await o.handle.currentOutput();return this.backgroundTerminals[o.handle.id]={status:"killed",pendingOutput:{...e,output:this.stripCommonPrefix(o.lastOutput?.output??"",e.output)}},await o.handle.release(),{content:"Command killed successfully.",renderer:{type:"text",value:"Command killed successfully."}}}case"aborted":return{content:"Command aborted by user.",renderer:{type:"text",value:"Command aborted by user."}};case"exited":return{content:"Command had already exited.",renderer:{type:"text",value:"Command had already exited."}};case"killed":return{content:"Command was already killed.",renderer:{type:"text",value:"Command was already killed."}};case"timedOut":return{content:"Command killed by timeout.",renderer:{type:"text",value:"Command killed by timeout."}};default:throw Error(`Unknown background terminal status: ${JSON.stringify(o)}`)}}isSupportAskUserQuestion(){let e=this.capabilities?._meta,t=e?.["codebuddy.ai"];return t?.question===!0}async callAskUserQuestion(e,t,r){let o=this.getConnection(),s=this.resolveAcpSessionId(t),a=r?.toolCall?.callId;if(!a)throw Error("No tool call ID found for AskUserQuestion");try{let t={sessionId:s,toolCallId:a,inputType:"question",schema:{questions:e.questions.map((e,t)=>({id:`q_${t}`,question:e.question,header:e.header,options:e.options,multiSelect:e.multiSelect}))}},r=await o.extMethod(i.ExtensionMethod.QUESTION,t);if("submitted"!==r.outcome||!r.answers)return{content:"User declined to answer questions",renderer:{type:"text"}};{let t=new Map(e.questions.map((e,t)=>[`q_${t}`,e.question])),o={};for(let[e,i]of Object.entries(r.answers))o[t.get(e)||e]=Array.isArray(i)?i.join(", "):i;return{content:Object.entries(o).map(([e,t])=>` \xb7 ${e} ${n.default.arrowRight} ${t}`).join("\n"),renderer:{type:"text"}}}}catch(t){let e=t instanceof Error?t.message:String(t);return{content:"User declined to answer questions",error:`Error asking user question: ${e}`,renderer:{type:"text"}}}}stripCommonPrefix(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return t.slice(r)}formatToolCommandOutput(e,t){let{exitStatus:r,output:o,truncated:i}=t,n="";switch(e){case"started":case"exited":r&&(r.exitCode??null)===null&&(n+="Interrupted by the user. ");break;case"killed":n+="Killed. ";break;case"timedOut":n+="Timed out. ";break;case"aborted":break;default:throw Error(`Unknown status: ${e}`)}return r?("number"==typeof r.exitCode&&(n+=`Exited with code ${r.exitCode}. `),"string"==typeof r.signal&&(n+=`Signal \`${r.signal}\`. `),n+="Final output:\n\n"):n+="New output:\n\n",n+=o,i&&(n+=`
|
|
1
|
+
"use strict";exports.ids=["4923"],exports.modules={33884(e,t,r){r.r(t),r.d(t,{buildPlaceholderAgentCard:()=>buildPlaceholderAgentCard});var o=r(48400);function buildPlaceholderAgentCard(){let{version:e}=o.PackageUtils.getCurrentPackageJson();return{name:"CodeBuddy Code",description:"CodeBuddy Code A2A inbound agent (SendMessage/GetTask/CancelTask only).",version:"string"==typeof e&&e.length>0?e:"0.0.0",provider:void 0,supportedInterfaces:[],capabilities:{streaming:!1,pushNotifications:!1,extendedAgentCard:!1,extensions:[]},securitySchemes:{},securityRequirements:[],defaultInputModes:["text"],defaultOutputModes:["text"],skills:[],signatures:[]}}},75505(e,t,r){r.r(t),r.d(t,{A2aAgentExecutor:()=>o,A2aInboundView:()=>i});let o=Symbol("A2aAgentExecutor"),i=Symbol("A2aInboundView")},4324(e,t,r){r.r(t),r.d(t,{A2aLineDispatcher:()=>A2aLineDispatcher,isA2aJsonRpcLine:()=>isA2aJsonRpcLine});var o=r(6757),i=r(477),n=r(33884);function isA2aJsonRpcLine(e){return"object"==typeof e&&null!==e&&"2.0"===e.jsonrpc}let A2aLineDispatcher=class A2aLineDispatcher{constructor(e,t,r={}){this.logger=t,this.options=r,this.sendMessageQueue=Promise.resolve();const o=new i.DefaultRequestHandler((0,n.buildPlaceholderAgentCard)(),new i.InMemoryTaskStore,e);this.transport=new i.JsonRpcTransportHandler(o),this.callContext=new i.ServerCallContext({})}isSendMessageLine(e){try{let t=JSON.parse(e);return"SendMessage"===t.method}catch{return!1}}async dispatch(e){if(this.isSendMessageLine(e)){let t=this.sendMessageQueue.then(()=>this.handle(e));return this.sendMessageQueue=t.then(()=>void 0,()=>void 0),t}return this.handle(e)}async handle(e){try{let t=this.checkBoundSession(e);if(t)return t;return await this.transport.handle(e,this.callContext)}catch(r){let t=r instanceof Error?r.message:String(r);return this.logger.error?.(`[A2aLineDispatcher] dispatch threw unexpectedly: ${t}`),{jsonrpc:"2.0",id:this.extractId(e),error:{code:o.A2A_ERROR_CODE.INTERNAL_ERROR,message:t}}}}checkBoundSession(e){let t;if(!this.options.boundSessionId)return;try{t=JSON.parse(e)}catch{return}if(t?.method!=="SendMessage")return;let reject=e=>(this.logger.warn?.(`[A2aLineDispatcher] rejecting SendMessage: ${e}`),{jsonrpc:"2.0",id:t?.id??null,error:{code:o.A2A_ERROR_CODE.INVALID_PARAMS,message:e}}),r=this.options.boundSessionId();if(!r)return reject("no session exists in this process yet; send a stream-json user message first (the session is created as soon as it is received, no need to wait for the turn to finish), then use that session id as contextId");let i=t?.params?.message?.contextId;if(i!==r)return reject("string"!=typeof i||0===i.length?`contextId is required and must be "${r}" in this session`:`contextId must be "${r}" in this session; got "${i}"`)}extractId(e){try{return JSON.parse(e).id??null}catch{return null}}}},61459(e,t,r){function isLoopbackAddress(e){if(!e)return!1;let t=e.trim().toLowerCase();if(!t)return!1;t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));let r=t.indexOf("%");if(r>=0&&(t=t.slice(0,r)),t.startsWith("::ffff:")){let e=t.slice(7);if(e.includes("."))return isLoopbackIpv4(e);let r=hexMappedToIpv4(e);return!!r&&isLoopbackIpv4(r)}return t.includes(":")?isLoopbackIpv6(t):isLoopbackIpv4(t)}function isLoopbackIpv4(e){let t=e.split(".");if(4!==t.length)return!1;let r=t.map(e=>/^\d{1,3}$/.test(e)?Number(e):-1);return!r.some(e=>e<0||e>255)&&127===r[0]}function isLoopbackIpv6(e){if("::1"===e)return!0;let t=expandIpv6(e);return!!t&&8===t.length&&t.slice(0,7).every(e=>0===e)&&1===t[7]}function expandIpv6(e){let t,r,o=e.indexOf("::");o>=0?(t=e.slice(0,o),r=e.slice(o+2)):(t=e,r="");let i=t?t.split(":"):[],n=r?r.split(":"):[],parseGroup=e=>{if(/^[0-9a-f]{1,4}$/.test(e))return parseInt(e,16)},s=[];for(let e of i){let t=parseGroup(e);if(void 0===t)return;s.push(t)}let a=[];for(let e of n){let t=parseGroup(e);if(void 0===t)return;a.push(t)}if(o>=0){let e=8-s.length-a.length;if(e<0)return;return[...s,...Array(e).fill(0),...a]}return 8===s.length?s:void 0}function hexMappedToIpv4(e){let t=e.split(":");if(2!==t.length)return;let r=t.map(e=>/^[0-9a-f]{1,4}$/.test(e)?parseInt(e,16):-1);if(r.some(e=>e<0||e>65535))return;let[o,i]=r;return`${o>>8&255}.${255&o}.${i>>8&255}.${255&i}`}r.r(t),r.d(t,{isLoopbackAddress:()=>isLoopbackAddress})},48678(e,t,r){r.r(t),r.d(t,{AcpToolInterceptorImpl:()=>c});var o=r(88523),i=r(70724),n=r(62279),s=r(48400),a=r(19160),l=r(71332);let c=class{constructor(){this.connection=null,this.backgroundTerminals={},this.fileContentCache=new Map}setConnection(e){this.connection=e}resolveAcpSessionId(e){return e.context.meta?.parentSessionId??e.context.id}getConnection(){if(!this.connection)throw Error("ACP connection not set. Call setConnection() first.");return this.connection}async readTextFile(e){let t=this.getConnection(),r=await t.readTextFile(e);return e.line||e.limit||this.fileContentCache.set(e.path,r.content),r}async writeTextFile(e){let t=this.getConnection(),r=await t.writeTextFile(e);return this.fileContentCache.set(e.path,e.content),r}getFileContentCache(){return Object.fromEntries(this.fileContentCache)}setCapabilities(e){this.capabilities=e}getCapabilities(){return this.capabilities}isSupportRead(){return!!this.capabilities?.fs?.readTextFile}async callRead(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path),r=await this.readTextFile({sessionId:o,path:t,line:e.offset,limit:e.limit}),i=r.content.split(/\r?\n/),n=this.formatContentWithLineNumbers(r.content,e.offset||1);return{title:`Read ${i.length} lines`,content:n,renderer:{type:"code",context:{language:s.LanguageUtils.getLanguageFromExtension(t)}}}}catch(t){let e=t instanceof Error?t.message:String(t);return{content:e,error:`Error reading file: ${e}`}}}formatContentWithLineNumbers(e,t){return e.split(/\r?\n/).map((e,r)=>{let o=(t+r).toString().padStart(4," ");return`${o}\u{2192}${e}`}).join("\n")}isSupportWrite(){return!!this.capabilities?.fs?.writeTextFile}async callWrite(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path);await this.writeTextFile({sessionId:o,path:t,content:e.content});let r=e.content.split(/\r?\n/),i=`Successfully wrote to file: ${t}`;return{title:`Wrote ${r.length} lines`,content:i,renderer:{type:"code",context:{language:s.LanguageUtils.getLanguageFromExtension(t)},value:e.content}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Write error: ${e}`)}}isSupportEdit(){return!!this.capabilities?.fs?.writeTextFile}async callEdit(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path),r=(await this.readTextFile({sessionId:o,path:t})).content,{newContent:i}=s.EditFileUtils.applyTextReplacementWithLocation(r,[{oldString:e.old_string,newString:e.new_string,replaceAll:e.replace_all}]);await this.writeTextFile({sessionId:o,path:t,content:i});let n=`Successfully edited file: ${t}`;return{title:"Edit applied",content:n,renderer:{type:"diff"}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Edit error: ${e}`)}}isSupportMultiEdit(){return!!this.capabilities?.fs?.writeTextFile}async callMultiEdit(e,t,r){let o=this.resolveAcpSessionId(t);try{let t=s.PathUtils.resolveFilePathToWorkDir(e.file_path),r=(await this.readTextFile({sessionId:o,path:t})).content,{newContent:i}=s.EditFileUtils.applyTextReplacementWithLocation(r,e.edits.map(e=>({oldString:e.old_string,newString:e.new_string,replaceAll:e.replace_all})));await this.writeTextFile({sessionId:o,path:t,content:i});let n=`Successfully applied ${e.edits.length} edit(s) to file: ${t}`;return{title:`Applied ${e.edits.length} edits`,content:n,renderer:{type:"diff"}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`MultiEdit error: ${e}`)}}isSupportBash(){return!!this.capabilities?.terminal}async callBash(e,t,r){let o=this.getConnection(),i=this.resolveAcpSessionId(t);try{let t=r?.toolCall?.callId;if("string"!=typeof t)throw Error("No tool call ID found");if(!o.createTerminal)throw Error("Terminal capability not available");let n=await o.createTerminal({command:e.command,sessionId:i,outputByteLimit:32e3});await o.sessionUpdate({sessionId:i,update:(0,l.withAcpTimestampMeta)({sessionUpdate:"tool_call_update",toolCallId:t,status:"in_progress",title:e.description,content:[{type:"terminal",terminalId:n.id}]})});let s=e.timeout||12e4,a=new Promise(e=>{setTimeout(async()=>{let t=this.backgroundTerminals[n.id];t&&"started"===t.status&&await n.kill(),e({status:"timedOut",exitStatus:null})},s)}),c=n.waitForExit().then(e=>({status:"exited",exitStatus:e}));if(e.run_in_background)return this.backgroundTerminals[n.id]={handle:n,lastOutput:null,status:"started"},Promise.race([c,a]).then(async({status:e,exitStatus:t})=>{let r=this.backgroundTerminals[n.id];if(!r||"started"!==r.status)return;let o=await n.currentOutput();this.backgroundTerminals[n.id]={status:e,pendingOutput:{...o,output:this.stripCommonPrefix(r.lastOutput?.output??"",o.output),exitStatus:t??o.exitStatus}},await n.release()}),{content:`Command started in background with id: ${n.id}`,renderer:{type:"text",value:`Command started in background with id: ${n.id}`}};let{status:d}=await Promise.race([c,a]),u=await n.currentOutput();await n.release();let p=this.formatToolCommandOutput(d,u);return{content:p,renderer:{type:"text",value:p}}}catch(t){let e=t instanceof Error?t.message:String(t);throw Error(`Bash error: ${e}`)}}isSupportBashOutput(){return!!this.capabilities?.terminal}async callBashOutput(e,t,r){let o=this.backgroundTerminals[e.shell_id];if(!o)throw Error(`Unknown shell ${e.shell_id}`);if("started"===o.status){let e=await o.handle.currentOutput(),t=this.stripCommonPrefix(o.lastOutput?.output??"",e.output);o.lastOutput=e;let r=this.formatToolCommandOutput(o.status,{...e,output:t});return{content:r,renderer:{type:"text",value:r}}}{let e=this.formatToolCommandOutput(o.status,o.pendingOutput);return{content:e,renderer:{type:"text",value:e}}}}isSupportKillShell(){return!!this.capabilities?.terminal}async callKillShell(e,t,r){let o=this.backgroundTerminals[e.shell_id];if(!o)throw Error(`Unknown shell ${e.shell_id}`);switch(o.status){case"started":{await o.handle.kill();let e=await o.handle.currentOutput();return this.backgroundTerminals[o.handle.id]={status:"killed",pendingOutput:{...e,output:this.stripCommonPrefix(o.lastOutput?.output??"",e.output)}},await o.handle.release(),{content:"Command killed successfully.",renderer:{type:"text",value:"Command killed successfully."}}}case"aborted":return{content:"Command aborted by user.",renderer:{type:"text",value:"Command aborted by user."}};case"exited":return{content:"Command had already exited.",renderer:{type:"text",value:"Command had already exited."}};case"killed":return{content:"Command was already killed.",renderer:{type:"text",value:"Command was already killed."}};case"timedOut":return{content:"Command killed by timeout.",renderer:{type:"text",value:"Command killed by timeout."}};default:throw Error(`Unknown background terminal status: ${JSON.stringify(o)}`)}}isSupportAskUserQuestion(){let e=this.capabilities?._meta,t=e?.["codebuddy.ai"];return t?.question===!0}async callAskUserQuestion(e,t,r){let o=this.getConnection(),s=this.resolveAcpSessionId(t),a=r?.toolCall?.callId;if(!a)throw Error("No tool call ID found for AskUserQuestion");try{let t={sessionId:s,toolCallId:a,inputType:"question",schema:{questions:e.questions.map((e,t)=>({id:`q_${t}`,question:e.question,header:e.header,options:e.options,multiSelect:e.multiSelect}))}},r=await o.extMethod(i.ExtensionMethod.QUESTION,t);if("submitted"!==r.outcome||!r.answers)return{content:"User declined to answer questions",renderer:{type:"text"}};{let t=new Map(e.questions.map((e,t)=>[`q_${t}`,e.question])),o={};for(let[e,i]of Object.entries(r.answers))o[t.get(e)||e]=Array.isArray(i)?i.join(", "):i;return{content:Object.entries(o).map(([e,t])=>` \xb7 ${e} ${n.default.arrowRight} ${t}`).join("\n"),renderer:{type:"text"}}}}catch(t){let e=t instanceof Error?t.message:String(t);return{content:"User declined to answer questions",error:`Error asking user question: ${e}`,renderer:{type:"text"}}}}stripCommonPrefix(e,t){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;return t.slice(r)}formatToolCommandOutput(e,t){let{exitStatus:r,output:o,truncated:i}=t,n="";switch(e){case"started":case"exited":r&&(r.exitCode??null)===null&&(n+="Interrupted by the user. ");break;case"killed":n+="Killed. ";break;case"timedOut":n+="Timed out. ";break;case"aborted":break;default:throw Error(`Unknown status: ${e}`)}return r?("number"==typeof r.exitCode&&(n+=`Exited with code ${r.exitCode}. `),"string"==typeof r.signal&&(n+=`Signal \`${r.signal}\`. `),n+="Final output:\n\n"):n+="New output:\n\n",n+=o,i&&(n+=`
|
|
2
2
|
|
|
3
3
|
Command output was too long, so it was truncated to ${o.length} bytes.`),n}};c=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s}([(0,o.Component)(a.AcpToolInterceptor)],c)},93321(e,t,r){r.r(t),r.d(t,{AcpViewImpl:()=>tx,mapFinishReasonToStopReason:()=>mapFinishReasonToStopReason,buildDeniedToolCallCancelledUpdate:()=>buildDeniedToolCallCancelledUpdate,resolveAcpStartTransport:()=>G.resolveAcpStartTransport,executeLocalCommandAndFlushHistory:()=>executeLocalCommandAndFlushHistory,CANCEL_BARRIER_MS:()=>tM,AcpTransportImpl:()=>tU,AcpUsagePublisherImpl:()=>tX,createTerminalId:()=>eX.createTerminalId,ACP_META_CANCEL_REASON:()=>G.ACP_META_CANCEL_REASON,AcpTransportManager:()=>G.AcpTransportManager,MCP_UI_MODEL_CONTEXT:()=>G.MCP_UI_MODEL_CONTEXT,DelegateTool:()=>G.DelegateTool,MAX_BACKGROUND_DRAIN_ROUNDS:()=>tD,AcpErrorCode:()=>e8,AcpView:()=>G.AcpView,applyAcpPromptTimestamp:()=>applyAcpPromptTimestamp,AcpTransportFactoryImpl:()=>tL,buildTerminalOutputChunk:()=>eX.buildTerminalOutputChunk,AcpAgentManager:()=>G.AcpAgentManager,AcpSecurityMiddleware:()=>tV,AcpTerminalPublisherImpl:()=>tZ,AcpServer:()=>G.AcpServer,RUN_STATE_SILENCE_LIMIT_MS:()=>tN,ACP_VIEW_NAME:()=>tO,AcpToolInterceptorImpl:()=>ta.AcpToolInterceptorImpl,AcpServerImpl:()=>tn,DelegateToolManager:()=>G.DelegateToolManager,subscribeToNewCombineEvents:()=>subscribeToNewCombineEvents,AcpBroadcastService:()=>G.AcpBroadcastService,AcpBroadcastServiceImpl:()=>to,AcpStreamManager:()=>G.AcpStreamManager,dedupeDenialToolCallIds:()=>dedupeDenialToolCallIds,AcpTransportFactory:()=>G.AcpTransportFactory,resolveResendForkPoint:()=>resolveResendForkPoint,clientSupportsTerminalOutput:()=>eX.clientSupportsTerminalOutput,AcpAgentImpl:()=>e7,shouldDeferBusyLocalCommand:()=>shouldDeferBusyLocalCommand,AcpHttpController:()=>td,AcpAgentManagerImpl:()=>te,AcpContextImpl:()=>ts,AcpAgent:()=>G.AcpAgent,isProviderFinishReasonError:()=>isProviderFinishReasonError,ACP_USAGE_CATEGORY_SNAPSHOT_SOURCES:()=>G.ACP_USAGE_CATEGORY_SNAPSHOT_SOURCES,AcpStreamManagerImpl:()=>tW,DelegateToolManagerImpl:()=>t3,isCancelBarrierActive:()=>isCancelBarrierActive,GenerationToolCreditUsageHook:()=>t1,ACP_CANCEL_REASON_SANDBOX_APPROVAL_TIMEOUT:()=>G.ACP_CANCEL_REASON_SANDBOX_APPROVAL_TIMEOUT,classifyErrorAsRequestError:()=>classifyErrorAsRequestError,buildTerminalUpdate:()=>eX.buildTerminalUpdate,AcpTransportManagerImpl:()=>tj,AcpUsagePublisher:()=>G.AcpUsagePublisher,AcpConnectionGuardImpl:()=>tH,resolveUserItemIdForResponse:()=>resolveUserItemIdForResponse,clientSupportsTerminalOutputChunk:()=>eX.clientSupportsTerminalOutputChunk,AcpTransport:()=>G.AcpTransport,AcpContext:()=>G.AcpContext,AcpToolInterceptor:()=>G.AcpToolInterceptor,ACP_META_SENSITIVE_INPUT_DECISION:()=>G.ACP_META_SENSITIVE_INPUT_DECISION,ACP_SECURITY_MIDDLEWARE_PRIORITY:()=>tK,buildPendingToolCallFailedUpdate:()=>buildPendingToolCallFailedUpdate,AcpConnectionGuard:()=>G.AcpConnectionGuard,AcpTerminalPublisher:()=>G.AcpTerminalPublisher});var o,i,n,s,a,l,c,d,u,p,g,h,m,f,y,_,w,b,v,S,A,C,E,I,T,P,R,k,O,M,D,N,$,x,j,U,L,F,B,W,q,H,G=r(71114),J=r(88523),K=r(7268),V=r(70724),Y=r(86482),z=r(9151),Q=r(79814),X=r(14480),Z=r(76982),ee=r(2721),et=r(34506),er=r(79127),eo=r(40587),ei=r(68400),en=r(40427),es=r(30694),ea=r(25682),el=r(84525),ec=r(50572),ed=r(8699),eu=r(71762),ep=r(3768);async function bindJobWorkerSession(e,t){let r=t?.jobId??(0,ep.getJobId)(),o=t?.isBroker??(0,ep.isJobBrokerProcess)();if(!r||o)return!1;let i=e.trim();if(!i)return!1;let n=t?.store;if(!n)try{n=J.ContainerUtil.get(eu.JobStore)}catch{return!1}let s=await n.read(r);return!!s&&(s.sessionId===i||(await n.patch(r,{sessionId:i}),!0))}var eg=r(48540),eh=r(63831),em=r(68238),ef=r(78290),ey=r(59458),e_=r(19028),ew=r(92522),eb=r(70541),ev=r(19472),eS=r(90666),eA=r(65380),eC=r(22800),eE=r(19585),eI=r(64383),eT=r(95955),eP=r(43465),eR=r(86045),ek=r(398),eO=r(76194),eM=r(12234),eD=r(87933),eN=r(84562),e$=r(698),ex=r(83424),ej=r(36600),eU=r(57037),eL=r(73667);eL.ToolNames.ASK_USER_QUESTION,eL.ToolNames.EXIT_PLAN_MODE;let eF="codebuddy.ai/replNestedInteraction";function isReplNestedInteraction(e){return!!(e&&"object"==typeof e&&!0===e[eF])}var eB=r(56097),eW=r(36116),eq=r(28215),eH=r(69431),eG=r(48400),eJ=r(86246);let JsonStreamParser=class JsonStreamParser{constructor(e){this.buffer="",this.parsedParams=new Map,this.completed=!1,this.onUnexpectedError=e}reportUnexpected(e,t){e instanceof SyntaxError||this.onUnexpectedError?.(e,t)}appendDelta(e){return this.completed?this.getCurrentResult():(this.buffer+=e,this.tryParse())}setComplete(e){if("string"==typeof e){this.buffer=e;try{let t=JSON.parse(e);t&&"object"==typeof t&&!Array.isArray(t)?this.updateParsedParams(t,!0):this.reportUnexpected(TypeError(`setComplete: final JSON is not an object (typeof=${typeof t})`),"setComplete")}catch(e){this.reportUnexpected(e,"setComplete")}}else this.buffer=JSON.stringify(e),this.updateParsedParams(e,!0);this.completed=!0}getCurrentResult(){let e={};return this.parsedParams.forEach((t,r)=>{e[r]=t.value}),{complete:this.completed,parameters:e,rawBuffer:this.buffer}}getBuffer(){return this.buffer}isCompleted(){return this.completed}tryParse(){let e=this.buffer.trim();if(!e||"{}"===e)return{complete:!1,parameters:{},rawBuffer:this.buffer};try{let t=JSON.parse(e);if(t&&"object"==typeof t&&!Array.isArray(t))return this.updateParsedParams(t,!0),this.completed=!0,this.getCurrentResult()}catch(r){this.reportUnexpected(r,"tryParse");let t=this.trySmartParse(e);if(t&&Object.keys(t.parsed).length>0&&(this.updateParsedParams(t.parsed,t.isComplete),t.isComplete))return this.completed=!0,this.getCurrentResult()}return{complete:!1,parameters:this.getParametersObject(),rawBuffer:this.buffer}}trySmartParse(e){let t=e.trim();if(!(t=this.tryFixMissingPrefix(t)).startsWith("{"))return;try{let e=this.tryCompleteJson(t);if(e){let r=JSON.parse(e);if(r&&"object"==typeof r&&!Array.isArray(r)){let o=e===t;return{parsed:r,isComplete:o}}}}catch(e){this.reportUnexpected(e,"trySmartParse")}let r=this.extractPartialKeyValues(t);if(r)return{parsed:r,isComplete:!1}}tryFixMissingPrefix(e){let t=e.trim();if(t.startsWith("{"))return t;if(t.startsWith('"'))return"{"+t;if(t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)"\s*:/))return'{"'+t;let r=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*"?\s*:/);if(r){let e=r[1],o=r[0].length;return'{"'+e+'":'+t.substring(o)}return t}tryCompleteJson(e){let t=e.trim(),r=0,o=0,i=!1,n=!1;for(let e=0;e<t.length;e++){let s=t[e];if("\\"===s&&!n){n=!0;continue}'"'!==s||n||(i=!i),!i&&("{"===s&&r++,"}"===s&&r--,"["===s&&o++,"]"===s&&o--),n=!1}if(0===r&&0===o&&!i)return t;let s=t;for(i&&(s+='"');o>0;)s+="]",o--;for(;r>0;)s+="}",r--;try{return JSON.parse(s),s}catch{return null}}extractPartialKeyValues(e){let t={};for(let r of this.smartSplitJson(e)){let e=r.indexOf(":");if(-1===e)continue;let o=r.substring(0,e).trim(),i=r.substring(e+1).trim(),n=o.replace(/^[{"]|"$/g,"").trim();if(!n)continue;let s=this.tryParseValue(i);void 0!==s&&(t[n]=s)}return Object.keys(t).length>0?t:void 0}tryParseValue(e){let t=e.trim();if(t)try{if(t.startsWith('"')&&!t.endsWith('"'))return this.unescapeJsonString(t.slice(1));let e=t.replace(/[,}]+$/,"");if(!e)return;return JSON.parse(e)}catch{if(t.startsWith('"'))return this.unescapeJsonString(t.slice(1).replace(/[,}]+$/,""));let e=t.match(/^(-?\d+(\.\d+)?)/);if(e)return parseFloat(e[1]);if(t.startsWith("true"))return!0;if(t.startsWith("false"))return!1;if(t.startsWith("null"))return null;return}}smartSplitJson(e){let t=[],r="",o=!1,i=!1,n=0,s=0;for(let a=0;a<e.length;a++){let l=e[a];if("\\"===l&&!i){i=!0,r+=l;continue}if('"'===l&&!i){o=!o,r+=l,i=!1;continue}if(!o){if("{"===l)n++;else if("}"===l)n--;else if("["===l)s++;else if("]"===l)s--;else if(","===l&&1===n&&0===s){t.push(r.trim()),r="",i=!1;continue}}r+=l,i=!1}return r.trim()&&t.push(r.trim()),t}unescapeJsonString(e){return e.endsWith("\\")&&!e.endsWith("\\\\")?e:e.replace(/\\([\\/"'bfnrt])/g,(e,t)=>({"\\":"\\","/":"/",'"':'"',"'":"'",b:"\b",f:"\f",n:"\n",r:"\r",t:" "})[t]||e)}updateParsedParams(e,t){for(let[r,o]of Object.entries(e))this.parsedParams.set(r,{value:o,completed:t})}getParametersObject(){let e={};return this.parsedParams.forEach((t,r)=>{e[r]=t.value}),e}};var eK=r(67971),eV=r(89277),eY=r(10618);function resolveToolManager(e){if(e.toolManager)return e.toolManager;try{return J.ContainerUtil.get(eL.ToolManager)}catch{return}}function resolveTerminalPublisher(e){if(e.terminalPublisher)return e.terminalPublisher;try{return J.ContainerUtil.get(G.AcpTerminalPublisher)}catch{return}}function resolveNotifier(e){if(e.notifier)return e.notifier;try{return J.ContainerUtil.get(eY.BackgroundTaskNotifier)}catch{return}}function findOwnedTask(e,t,r){return e.getBackgroundTasks().find(e=>e.terminalId===r&&(!e.sessionId||e.sessionId===t.id))}async function cancelBackgroundTask(e){let{session:t,terminalId:r,logger:o}=e,i=resolveToolManager(e);if(!i)return{outcome:"not_found",terminalId:r};let n=findOwnedTask(i,t,r);if(!n)return o?.info?.(`[cancelBackgroundTask] not found | terminalId=${r} | sessionId=${t.id} | \u{53EF}\u{80FD}\u{539F}\u{56E0}\u{FF1A}\u{7EC8}\u{7AEF}\u{4E0D}\u{5B58}\u{5728}\u{3001}\u{5DF2}\u{88AB} ToolManager \u{7684} TTL \u{6DD8}\u{6C70}\u{3001}\u{6216}\u{4E0D}\u{5C5E}\u{4E8E}\u{672C}\u{4F1A}\u{8BDD}`),{outcome:"not_found",terminalId:r};if("running"!==n.status&&"pending"!==n.status)return o?.info?.(`[cancelBackgroundTask] already exited | taskId=${n.id} | terminalId=${r} | status=${n.status}`),{outcome:"already_exited",terminalId:r};n.deferNotificationDrain=!0,n.endReason="cancelled-by-user";let s=await i.killBackgroundTask(n.id);if(n.terminalId)try{resolveTerminalPublisher(e)?.notifyExit(t,n.terminalId,{exitCode:null,signal:"SIGTERM"},{reason:"cancelled-by-user"})}catch(e){o?.debug?.(`[cancelBackgroundTask] notifyExit skipped: ${e?.message??e}`)}if(!s)return n.deferNotificationDrain=void 0,n.endReason=void 0,o?.warn?.(`[cancelBackgroundTask] kill failed, task still registered | taskId=${n.id} | terminalId=${r}`),{outcome:"cancel_failed",terminalId:r};try{resolveNotifier(e)?.notifyCompletion(n,t,{deferDrain:!0})}catch(e){o?.debug?.(`[cancelBackgroundTask] notifyCompletion skipped: ${e?.message??e}`)}return o?.info?.(`[cancelBackgroundTask] cancelled | taskId=${n.id} | terminalId=${r} | status=${n.status}`),{outcome:"cancelled",terminalId:r}}var ez=r(19160);function pickAcpSessionModels(e,t){return e.length>0?e:t}function buildModelCatalogKey(e,t,r){return`${e}:${r}:${JSON.stringify(t.map(e=>[e.modelId,e._meta?.credits??null]))}`}function toAcpModelInfo(e){return{modelId:e.id,name:e.name||e.id,description:[e.description,e.credits].filter(Boolean).join(" \xb7 ")||null,_meta:{supportsImages:e.supportsImages??!1,supportsReasoning:e.supportsReasoning??!1,credits:e.credits??null,maxInputTokens:e.maxInputTokens??null}}}var eQ=r(21312),eX=r(74906),eZ=r(71332);function resolveResendForkPoint(e,t){let{userMessageId:r,forkFromRequestId:o}=t;if(!r&&!o||!Array.isArray(e)||0===e.length)return{found:!1};let i=r?e.find(e=>e?.id===r):void 0;if(!i&&o&&(i=e.find(e=>e?.id===o)),!i&&o){let t=e.find(e=>e?.providerData?.conversationRequestId===o),r=t?.parentId;r&&(i=e.find(e=>e?.id===r))}return i?{found:!0,editedUserItemId:i.id,forkPoint:i.parentId}:{found:!1}}function isPreMarkerItem(e,t){return t.existingItems.has(e)||"string"==typeof e.id&&""!==e.id&&t.existingIds.has(e.id)}function isOwnPromptCandidateItem(e){if(!e||"message"!==e.type||"user"!==e.role)return!1;let t=e.providerData;return!t||!0!==t.isMeta&&!0!==t.isCompactInternal&&!t.skipRun&&"string"!=typeof t.teammateMessage?.from&&"compact"!==t.agent}function resolveUserItemIdForResponse(e,t,r){if(Array.isArray(e)&&0!==e.length){if(t){let r=e.find(e=>e&&"message"===e.type&&"user"===e.role&&e.id===t);if(r?.id)return r.id}if(r){for(let t of e)if(!(!t||isPreMarkerItem(t,r))&&isOwnPromptCandidateItem(t))return t.id;return}for(let t=e.length-1;t>=0;t--){let r=e[t];if(isOwnPromptCandidateItem(r))return r.id}}}var e0=r(19025);async function handleRollback(e,t){let{session:r}=e;if(!(t.targetMessageId||t.targetRequestId)&&"forkPointId"in t){let o=t.forkPointId??void 0;return"resend_edit"===t.reason&&e.addHistory?await (0,e0.rewindTo)(r,o,t.reason,{editedUserItemId:`root-rewind-${Date.now()}`,addHistory:e.addHistory}):await (0,e0.rewindTo)(r,o,t.reason),{applied:!0,actualForkPointId:o}}if(t.targetMessageId||t.targetRequestId){let o=await e.resolveForkPoint(r.history,{userMessageId:t.targetMessageId,forkFromRequestId:t.targetRequestId});if(!o?.found)return e.logger?.warn?.(`[Rollback] fork point not resolved: sessionId=${t.sessionId}, targetMessageId=${t.targetMessageId}, targetRequestId=${t.targetRequestId}`),{applied:!1,error:"Cannot resolve fork point"};let i=o.forkPoint;return"resend_edit"===t.reason?await (0,e0.rewindTo)(r,i,t.reason,{editedUserItemId:o.editedUserItemId,addHistory:e.addHistory}):await (0,e0.rewindTo)(r,i,t.reason),{applied:!0,actualForkPointId:i}}return{applied:!1,error:"Either forkPointId or targetMessageId is required"}}var e1=r(83457);function buildInjectHistoryItems(e){let t,r=[];for(let o of e)switch(o.role){case"user":r.push(eG.InputItemUtils.createUserMessage(o.content??"",{skipRun:!0}));break;case"assistant":{let e=eG.InputItemUtils.createAssistantMessage(o.content??"",{skipRun:!0});o.usage&&(e.providerData={...e.providerData??{},usage:o.usage}),r.push(e);break}case"tool_call":{let e;if("object"==typeof o.arguments&&null!==o.arguments)e=o.arguments;else try{e=JSON.parse(String(o.arguments??"{}"))}catch{throw Error(`Invalid JSON in tool_call arguments for tool "${o.name??"unknown"}"`)}let i=eG.InputItemUtils.createToolCallItem(o.name??"unknown",e,{skipRun:!0});t=i,r.push(i);break}case"tool_result":{let e=t??eG.InputItemUtils.createToolCallItem(o.tool_call_name??"unknown",{},{skipRun:!0});r.push(eG.InputItemUtils.createToolCallResultItem(o.output??o.content??"",e,{skipRun:!0})),t=void 0;break}default:throw Error(`Unknown role "${o.role}" in inject history message`)}return r}var e3=r(19149),e2=r(72314);async function buildWorkspaceInfoParams(){let e=J.ContainerUtil.get(e2.CwdService);return{isGitWorkspace:eG.GitUtils.isGitRepository(e.getCwd())}}async function sendWorkspaceInfoNotification(e,t,r){let o=await buildWorkspaceInfoParams();await e.extNotification(V.ExtensionMethod.COMMAND,{sessionId:t,action:"workspace_info",params:o}),r?.info?.(`[ACP Agent] workspace_info sent: sessionId=${t} isGitWorkspace=${o.isGitWorkspace}`)}let e4=new Set(["security-center-setting-disabled","session-local-environment-selected","background-automation-no-approval-ui"]);function isSandboxDisabledReason(e){return"string"==typeof e&&e4.has(e)}function normalizeSandboxDisabledReason(e){return isSandboxDisabledReason(e)?e:void 0}function formatContextWindowOption(e){return e>=1e6&&e%1e6==0?`${e/1e6}M`:e>=1e3&&e%1e3==0?`${e/1e3}K`:String(e)}function mapFinishReasonToStopReason(e){if(e)switch(e){case"content_filter":case"refusal":return"refusal";case"length":case"max_tokens":return"max_tokens";case"stop":case"end_turn":case"stop_sequence":case"tool_calls":case"tool_use":case"function_call":return"end_turn";default:return}}let e8={NetworkError:-32001,InternalError:-32002,QuotaExceeded:-32003,ModelServiceError:-32004};function isRecord(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function createAuthRequiredError(e){return eQ.RequestError.authRequired({...e??{},category:"auth"})}let e5=new Set([11140,11141,11142]);function isAuthRequiredLikeError(e,t,r,o){return!(t?.category==="custom_model_auth"||403===r&&void 0!==o&&e5.has(o))&&(e instanceof eE.AuthenticationRequiredError||e instanceof eE.AuthenticationFailedError||t?.category==="auth"||401===r||403===r)}function extractStructuredErrorData(e){if(isRecord(e)){if(isRecord(e.data)&&Object.keys(e.data).length>0)return e.data;if(isRecord(e.error)){let t=e.error;if(isRecord(t.data)&&Object.keys(t.data).length>0)return t.data}if(isRecord(e.response)){let t=e.response;if(isRecord(t.data)&&Object.keys(t.data).length>0)return t.data}}}function isCancelledMessage(e){if(!e)return!1;let t=e.toLowerCase();return"canceled"===t||"cancelled"===t||"the operation was aborted"===t||"this operation was aborted"===t}function classifyErrorAsRequestError(e){let t=e?.status??e?.response?.status,r=eG.ErrorUtils.extractBizCode(e),o=eG.ErrorUtils.getErrorMessage(e),i=o?o.replace(/Tool (.+?) not found in agent [^\s.]+\.?/g,'Tool "$1" does not exist in the current tool set.'):o,n=extractStructuredErrorData(e);if(e instanceof eQ.RequestError)return -32e3===e.code?createAuthRequiredError(n):e;let s=n?.code,a={...n??{},details:i,statusCode:t,code:"number"==typeof s&&s>=1e3?s:r};if(isAuthRequiredLikeError(e,n,t,r))return createAuthRequiredError(a);if(eG.ErrorUtils.isQuotaExhaustedError(e)||eG.ErrorUtils.isModelOverloadedError(e))return new eQ.RequestError(e8.QuotaExceeded,`Quota exceeded: ${i}`,{...a,category:"quota"});let l="number"==typeof t&&(408===t||502===t||503===t||504===t);if(eG.ErrorUtils.isStreamTimeoutError(e)||eG.ErrorUtils.isNetworkError(e)||l)return eG.ErrorUtils.isEmptyStreamError(e)?new eQ.RequestError(e8.NetworkError,`Upstream gateway returned empty stream (only placeholder chunks, no model output). The model service may be temporarily unavailable. Details: ${i}`,{...a,category:"network"}):new eQ.RequestError(e8.NetworkError,`Network error: ${i}`,{...a,category:"network"});if(eG.ErrorUtils.isRetryableModelError(e))return new eQ.RequestError(e8.ModelServiceError,`Model service error: ${i}`,{...a,category:"model_service"});if(n?.category==="cancelled"||isCancelledMessage(i))return new eQ.RequestError(e8.InternalError,"Request cancelled",{...a,category:"cancelled"});let c=a.category??"internal";return eQ.RequestError.internalError({...a,category:c})}function isProviderFinishReasonError(e){return e instanceof eQ.RequestError&&isRecord(e.data)&&"provider_finish_reason_error"===e.data.reason}function buildDeniedToolCallCancelledUpdate(e,t){let r=Date.now();return(0,eZ.withAcpTimestampMeta)({sessionId:e,update:(0,eZ.withAcpTimestampMeta)({sessionUpdate:"tool_call_update",toolCallId:t,status:"cancelled",content:[{type:"content",content:{type:"text",text:"Permission denied by user."}}],_meta:{"codebuddy.ai/toolCancelReason":"permission_denied"}},r)},r)}function dedupeDenialToolCallIds(e){let t=new Set,r=[];for(let o of e){let e=o.tool_use_id;"string"!=typeof e||0===e.length||t.has(e)||(t.add(e),r.push(e))}return r}let e6=new Set(["plugin-change","marketplace-add","marketplace-refresh","builtin-marketplace-periodic-update"]);function buildPendingToolCallFailedUpdate(e,t,r,o="tool_not_found"){let i=Date.now();return(0,eZ.withAcpTimestampMeta)({sessionId:e,update:(0,eZ.withAcpTimestampMeta)({sessionUpdate:"tool_call_update",toolCallId:t,status:"failed",content:[{type:"content",content:{type:"text",text:r}}],_meta:{"codebuddy.ai/toolFailReason":o}},i)},i)}function extractReplayUserText(e){if(e?.sessionUpdate!=="user_message_chunk")return;let t=e.content?.text;return"string"==typeof t&&t?t:void 0}let e7=class{constructor(){this.mainAgentOptIn=!1,this.replayWindowQueue=null,this.lastPushedModelCatalogKey="",this.modelCatalogPushGeneration=0,this.toolCallSentDeferreds=new Map,this.toolCallNameById=new Map,this.toolCallMemberEventById=new Map,this.handledApprovals=new WeakSet,this.activeSensitiveApprovals=new Map,this.cancelledSensitiveApprovals=new Map,this.promptEvent=new ee.Subject,this.modelChangeEvent=new ee.Subject,this.modeChangeEvent=new ee.Subject,this.displayModeEvent=new ee.Subject,this.configChangeEvent=new ee.Subject,this.cancelEvent=new ee.Subject,this.pendingCancellations=new Set,this.pendingEarlyAskSkipToolCallIds=new Set,this.handledAskToolCallIds=new Set,this.activeForwardingCleanups=new Map}consumePendingCancellation(e){let t=this.pendingCancellations.has(e);return t&&this.pendingCancellations.delete(e),t}getScopedToolCallId(e,t){return`${e}\0${t}`}addPendingEarlyAskSkipToolCallId(e,t){this.pendingEarlyAskSkipToolCallIds.add(this.getScopedToolCallId(e,t))}consumePendingEarlyAskSkipToolCallId(e,t){let r=this.getScopedToolCallId(e,t),o=this.pendingEarlyAskSkipToolCallIds.has(r);return o&&this.pendingEarlyAskSkipToolCallIds.delete(r),o}clearPendingEarlyAskSkipsForSession(e){let t=`${e}\0`;for(let e of this.pendingEarlyAskSkipToolCallIds)e.startsWith(t)&&this.pendingEarlyAskSkipToolCallIds.delete(e)}markAskToolCallHandled(e,t){let r=this.getScopedToolCallId(e,t);for(this.handledAskToolCallIds.delete(r),this.handledAskToolCallIds.add(r);this.handledAskToolCallIds.size>512;){let e=this.handledAskToolCallIds.values().next().value;if("string"!=typeof e)break;this.handledAskToolCallIds.delete(e)}}hasHandledAskToolCall(e,t){return this.handledAskToolCallIds.has(this.getScopedToolCallId(e,t))}getAskSkipAnswer(e){return{_action:e.permissionModeSubject.value===ex.PermissionMode.Plan?"skip_interview":"skip_question"}}createAbortError(e="aborted"){let t=Error(e);return t.name="AbortError",t}createSessionUpdateTimeoutError(e){let t=Error(`ACP sessionUpdate timed out after 5000ms for session ${e}`);return t.name="AcpSessionUpdateTimeoutError",t}isAbortError(e){return e instanceof Error&&"AbortError"===e.name}isSessionUpdateTimeoutError(e){return e instanceof Error&&"AcpSessionUpdateTimeoutError"===e.name}async sendPromptSessionUpdate(e,t,r){let o,i;if(r?.aborted)return!1;let n=new Promise((e,r)=>{"function"==typeof(o=setTimeout(()=>r(this.createSessionUpdateTimeoutError(t)),5e3)).unref&&o.unref()}),s=r?new Promise((e,t)=>{i=()=>t(this.createAbortError()),r.aborted?i():r.addEventListener("abort",i,{once:!0})}):void 0;try{let t=this.connection.sessionUpdate(e);return await Promise.race(s?[t,n,s]:[t,n]),!0}catch(e){if(r?.aborted||this.isAbortError(e))return!1;if(this.isSessionUpdateTimeoutError(e))return this.logger.warn?.(`[ACP Agent] Dropping sessionUpdate after timeout for session ${t}`),!1;throw e}finally{o&&clearTimeout(o),r&&i&&r.removeEventListener("abort",i)}}setConnection(e,t){this.connection=e,this.connectionId=t,J.ContainerUtil.get(G.AcpToolInterceptor).setConnection(e),J.ContainerUtil.get(G.DelegateToolManager).setConnection(e),this.setupUrlSubjectSubscription(),this.setupPendingApprovalSubscription()}getConnectionId(){return this.connectionId}tryGetAuthorizedConnection(){return this.connection??void 0}getConnection(){return this.connection}getSessionRequest(){return this.sessionRequest}getClientCapabilities(){return this.clientCapabilities}getCurrentSessionId(){return this.currentSessionId}getCurrentSession(){return this.currentSession}listPendingToolCallIds(e){return this.currentSessionId!==e?[]:Array.from(this.toolCallSentDeferreds.keys())}listPendingToolCalls(e){return this.currentSessionId!==e?[]:Array.from(this.toolCallSentDeferreds.keys()).map(e=>({toolCallId:e,toolName:this.toolCallNameById.get(e),memberEvent:this.toolCallMemberEventById.get(e)}))}notifyToolCallSent(e,t,r){if(!e)return;this.toolCallSentDeferreds.has(e)||this.toolCallSentDeferreds.set(e,new J.Deferred),"string"==typeof t&&t&&this.toolCallNameById.set(e,t),"string"==typeof r&&r&&this.toolCallMemberEventById.set(e,r);let o=this.toolCallSentDeferreds.get(e);o&&o.resolve()}notifyToolCallUpdateSent(e,t){e&&("completed"===t||"failed"===t)&&(this.toolCallSentDeferreds.delete(e),this.toolCallNameById.delete(e),this.toolCallMemberEventById.delete(e))}setSession(e){this.logger.info?.(`[ACP Agent] setSession called for session ${e.id}`);let t=this.currentSessionId;if(t&&t!==e.id){this.toolCallSentDeferreds.clear(),this.toolCallNameById.clear(),this.toolCallMemberEventById.clear();try{this.usagePublisher.unregister(t)}catch(e){this.logger.debug?.(`[ACP Agent] usagePublisher.unregister(${t}) failed: ${e?.message??e}`)}}this.currentSessionId=e.id,this.currentSession=e;try{this.usagePublisher.register(e,this.connection)}catch(t){this.logger.warn?.(`[ACP Agent] usagePublisher.register failed for session ${e.id}: ${t?.message??t}`)}this.sessionDeferred&&this.sessionDeferred.resolve(e)}setupUrlSubjectSubscription(){this.urlSubjectSubscription&&this.urlSubjectSubscription.unsubscribe(),this.urlSubjectSubscription=this.externalUriOpener.urlSubject.subscribe(e=>{this.logger.info(`[AcpAgent] External URL opened, sending auth URL notification: ${e}`);try{this.connection.extNotification(V.ExtensionMethod.AUTH_URL,{authUrl:e,provider:"external"})}catch(e){this.logger.error(`[AcpAgent] Failed to send auth URL notification: ${e}`)}})}setupPendingApprovalSubscription(){this.pendingApprovalSubscription&&this.pendingApprovalSubscription.unsubscribe(),this.pendingApprovalSubscription=this.interruptionService.pending$.subscribe(e=>{e&&this.handlePendingApprovalView(e).catch(()=>{})})}async handlePendingApprovalView(e){try{let t=await this.getRuntimeSession(e.mainSessionId),r=t?.meta?.acpConnectionId;if(!r||r!==this.connectionId)return;await this.handleToolApproval(e.item,e.mainSessionId)}catch(t){this.logger.warn?.(`[ACP Agent] handlePendingApprovalView failed for session ${e.mainSessionId}: ${t?.message??t}`)}}get agentManager(){return J.ContainerUtil.get(er.AgentManager)}get sessionManager(){return J.ContainerUtil.get(eD.SessionManager)}get interruptionService(){return J.ContainerUtil.get(eD.InterruptionService)}get mcpManager(){return J.ContainerUtil.get(eS.McpManager)}get authManager(){return J.ContainerUtil.get(Y.AuthenticationManager)}get logger(){return J.ContainerUtil.get(J.Logger)}get usagePublisher(){return J.ContainerUtil.get(G.AcpUsagePublisher)}get fileRollbackService(){return J.ContainerUtil.get(ey.FileRollbackService)}get galileoTimingHook(){try{return J.ContainerUtil.get(e_.GalileoTimingHook)}catch{return}}get metricsAggregator(){try{return J.ContainerUtil.get(e_.AgentMetricsAggregator)}catch{return}}get sessionErrorTracker(){try{return J.ContainerUtil.get(ew.SessionErrorTracker)}catch{return}}get commandManager(){return J.ContainerUtil.get(em.CommandManager)}get contextCompactSummarizer(){return J.ContainerUtil.get(ef.ContextCompactSummarizer)}get externalUriOpener(){return J.ContainerUtil.get(Q.ExternalUriOpener)}get restOperationsFactory(){return J.ContainerUtil.get(K.RestOperationsFactory)}get endpointProvider(){return J.ContainerUtil.get(ev.EndpointProvider)}get settingsManager(){return J.ContainerUtil.get(ex.SettingsManager)}get cliSettingsProvider(){return J.ContainerUtil.get(ex.CliSettingsProvider)}get askService(){return J.ContainerUtil.get(eg.AskService)}get productManager(){return J.ContainerUtil.get(z.ProductManager)}get cliRuntimeOptions(){return J.ContainerUtil.get(eh.CliRuntimeOptions)}resolveProcessDefaults(){try{return(0,eh.resolveCliProcessDefaults)(this.cliRuntimeOptions.get(),this.agentManager.getCliAgentName?.())}catch{return(0,eh.pickCliProcessDefaults)({agent:this.agentManager.getCliAgentName?.()})}}resolveProcessAgentName(){let e=this.resolveProcessDefaults();if(e.agent)return e.agent;let t=this.agentManager.getSettingsAgentName?.();return(0,ei.isShippedStandingMode)(t)?t:void 0}async getModelsInfo(e){let t;this.logger.info?.("[ACP Agent] getModelsInfo: START");let r=await this.agentManager.getInitializeMetadata(),o=this.agentManager.getDefaultAgentName()||r.defaultAgentName,i=this.isWebUiClient()&&o?this.agentManager.getModelsForContext(o):[],n=pickAcpSessionModels(i,r.models),s=i.length>0?"live":"snapshot";this.logger.info?.(`[ACP Agent] getModelsInfo: source=${s} models=${n.length} default=${o} webUi=${this.isWebUiClient()}`);let a=e.requestOptions.model||e.options.model;t=a||r.currentModelId||"default",this.logger.info?.(`[ACP Agent] getModelsInfo: sessionId=${e.id}, currentModelId=${t}, reqOptModel=${e.requestOptions.model??"<none>"}, optModel=${e.options.model??"<none>"}`);let l=n.map(e=>toAcpModelInfo(e));return this.logger.info?.(`[ACP Agent] getModelsInfo: END, returning ${l.length} models`),{availableModels:l,currentModelId:t}}async pushAvailableModelsUpdate(e){if(!this.connection||!this.isWebUiClient()||this.currentSessionId&&this.currentSessionId!==e.id)return;let t=++this.modelCatalogPushGeneration,{availableModels:r,currentModelId:o}=await this.getModelsInfo(e);if(t!==this.modelCatalogPushGeneration)return;let i=buildModelCatalogKey(e.id,r,o);if(this.lastPushedModelCatalogKey!==i)try{if(await this.connection.sessionUpdate((0,eZ.withAcpTimestampMeta)({sessionId:e.id,update:{sessionUpdate:"model_update",availableModels:r,currentModelId:o}})),t!==this.modelCatalogPushGeneration)return;this.lastPushedModelCatalogKey=i}catch(e){this.logger.warn?.(`[ACP Agent] Failed to push model catalog update: ${e}`)}}async getCurrentModelLanguageConfig(e){let t=e.requestOptions.model||e.options.model;if(!t){let e=await this.agentManager.getDefault(),r=await this.agentManager.getModel(e.name);t=r?.id}if(t)try{let e=await this.productManager.waitConfiguration();return e.models?.find(e=>e.id===t)}catch(e){this.logger.warn?.(`[ACP Agent] getCurrentModelLanguageConfig failed: ${e?.message??e}`);return}}canDisableThinking(e){return!e||!e.onlyReasoning&&e.reasoning?.canDisableThinking!==!1}getModesInfo(e){let t=(0,ea.isMinimalStandingAgent)(e),r=[{id:"default",name:"Always Ask",description:"Prompts for permission on first use of each tool"},{id:"acceptEdits",name:"Accept Edits",description:"Automatically accepts file edit permissions for the session"},...t?[]:[{id:"plan",name:"Plan",description:"Claude can analyze but not modify files or execute commands"}],{id:"auto",name:"Auto",description:"An AI classifier reviews actions that would normally prompt: safe ones are auto-approved, risky ones are denied. If the classifier is unavailable, the action falls back to a prompt (or is denied when prompts cannot be shown)"},{id:"dontAsk",name:"Don't Ask",description:"Never shows permission prompts; runs pre-approved and safe actions, denies anything that would require approval"},{id:"bypassPermissions",name:"Bypass Permissions",description:"Skips all permission prompts"},{id:"fullAccess",name:"Full Access",description:"Skips ALL permission checks including dangerous commands for all agents"},{id:"delegate",name:"Delegate",description:"Permissions managed by parent session"}],o=e.permissionModeSubject.getValue()||"default";return t&&"plan"===o&&(e.permissionModeSubject.next(ex.PermissionMode.Default),e.meta&&delete e.meta.prePlanPermissionMode,o=ex.PermissionMode.Default),{availableModes:r,currentModeId:o}}async buildMainAgentPicker(e,t){let r=await (0,en.resolveEffectiveDefaultAgentName)(t),o=await this.settingsManager?.get?.("language"),i=await (0,en.buildAgentDirectory)(this.agentManager,{defaultAgentName:r,language:"string"==typeof o?o:void 0}),n=await (0,en.resolveDisplayMainAgentName)(e,t,new Set(i.map(e=>e.name)),r);return{defaultAgentName:r,directory:i,currentAgentName:n}}async getConfigOptions(e,t){let r,o,i=await this.settingsManager.get("alwaysThinkingEnabled"),n=!1;try{let e=await this.settingsManager.list();n=!!e.sandbox?.enabled}catch(e){this.logger.warn?.(`[ACP Agent] Failed to read sandbox setting for getConfigOptions: ${e?.message??e}`)}let s={type:"select",id:"mode",name:"Permission Mode",description:"Controls how the agent requests permission before making changes",category:"mode",currentValue:e.permissionModeSubject.getValue()||"default",options:[{value:"default",name:"Always Ask",description:"Prompts for permission on first use of each tool"},{value:"acceptEdits",name:"Accept Edits",description:"Automatically accepts file edit permissions for the session"},...(0,ea.isMinimalStandingAgent)(e)?[]:[{value:"plan",name:"Plan",description:"Agent can analyze but not modify files or execute commands"}],{value:"auto",name:"Auto",description:"An AI classifier reviews actions that would normally prompt: safe ones are auto-approved, risky ones are denied. If the classifier is unavailable, the action falls back to a prompt (or is denied when prompts cannot be shown)"},{value:"dontAsk",name:"Don't Ask",description:"Does not show permission prompts; pre-approved and safe read-only actions run, everything else that would prompt is denied"},{value:"bypassPermissions",name:"Bypass Permissions",description:"Skips all permission prompts"},{value:"fullAccess",name:"Full Access",description:"Skips ALL permission checks including dangerous commands for all agents"},{value:"delegate",name:"Delegate",description:"Permissions managed by parent session"}]},{availableModels:a,currentModelId:l}=await this.getModelsInfo(e),c={type:"select",id:"model",name:"Model",description:"Select the AI model to use for this session",category:"model",currentValue:l,options:a.map(e=>({value:e.modelId,name:e.name||e.modelId,description:e.description||void 0}))},d=this.sessionManager.getOverrideThinking(e.id),u=d?.thinkingEnabled??i,p=d?.reasoningEffort,g=await this.getCurrentModelLanguageConfig(e),h=this.canDisableThinking(g),m=g?.reasoning?.supportedEfforts,f=[{value:"minimal",name:"Minimal",description:"Briefest reasoning"},{value:"low",name:"Low",description:"Light reasoning"},{value:"medium",name:"Medium",description:"Balanced reasoning"},{value:"high",name:"High",description:"Deep reasoning"},{value:"xhigh",name:"X-High",description:"Very deep reasoning"},{value:"max",name:"Max",description:"Maximum reasoning effort"}],y=m&&m.length>0?f.filter(e=>m.includes(e.value)):f,_={type:"select",id:"thought_level",name:"Deep Thinking",description:"Choose reasoning effort level for this session",category:"thought_level",currentValue:r=!1===u&&h?"disabled":!1!==u&&p?p:"enabled",options:[...h?[{value:"disabled",name:"Off",description:"Standard response without extended thinking"}]:[],...y,{value:"enabled",name:"On (default)",description:"Use the model default effort"}]},w=g?.contextWindow,b=Array.from(new Set((w?.supportedLengths??[]).filter(e=>"number"==typeof e&&Number.isSafeInteger(e)&&e>0&&(g?.maxInputTokens===void 0||e<=g.maxInputTokens)))).sort((e,t)=>e-t),v=b.length>=2?{type:"select",id:"context_window",name:"Context",description:"Choose context window budget for this session",category:"context_window",currentValue:String((0,ef.resolveEffectiveContextBudget)({overrideContextWindow:this.sessionManager.getOverrideContextWindow(e.id),contextWindow:w,maxInputTokens:g?.maxInputTokens})??b[0]),options:b.map(e=>({value:String(e),name:formatContextWindowOption(e),description:`${formatContextWindowOption(e)} context budget`}))}:void 0,S={type:"select",id:"sandbox",name:"Sandbox",description:"Run shell commands inside the sandbox-cli isolation layer",category:"sandbox",currentValue:n?"true":"false",options:[{value:"true",name:"Sandbox Environment",description:"Bash/PowerShell commands run inside the sandbox and require escalation to touch the host"},{value:"false",name:"Local Environment",description:"Commands run with full user permissions (no sandbox isolation)"}]};if((0,es.getMainAgentGateProvider)()?.isEnabledForSession(e)&&this.mainAgentOptIn&&this.isSessionOwnedByThisConnection(e)){let r=t??await this.buildMainAgentPicker(e,this.buildMainAgentDeps());o={type:"select",id:"agent",name:"Main Agent",description:"Select the agent this session runs as",category:"agent",currentValue:r.currentAgentName,options:r.directory.map(e=>({value:e.name,name:e.displayName,description:e.description}))}}return[s,c,_,...v?[v]:[],S,...o?[o]:[]]}async sendAvailableCommandsUpdate(e){try{let t=["/exit","/help","/config","/sandbox","/ide","/hooks","/theme","/rename","/agents","/model","/model:text-to-image","/model:image-to-image","/resume","/mcp","/permissions","/tasks","/plugin","/output-style","/stats","/rewind","/export","/status","/bash","/memory","/add-dir","/terminal-setup","/vim","/upgrade","/install-github-app","/migrate-installer"],r=(await this.commandManager.getAll()).filter(e=>!t.includes(e.name)).map(e=>{let t={name:e.name.startsWith("/")?e.name.substring(1):e.name,description:e.description||""};return e.argumentHint&&(t.input={hint:e.argumentHint}),t});try{let e=(await this.productManager.waitConfiguration()).skills||[],t=await (0,ej.getMergedSkillOverrides)(this.settingsManager);for(let o of e)(0,ej.resolveSkillVisibility)(o,t).menuVisible&&r.push({name:o.name,description:o.description||"",_meta:{type:"skill",source:o.source,isBuiltIn:(0,ej.isBuiltInSkill)(o)}})}catch(e){this.logger.warn?.(`Failed to load skills for available commands: ${e.message}`)}await this.connection.sessionUpdate((0,eZ.withAcpTimestampMeta)({sessionId:e,update:{sessionUpdate:"available_commands_update",availableCommands:r}}))}catch(e){this.logger.error(`Failed to send available commands update: ${e.message}`)}}async sendWorkspaceInfo(e){try{await sendWorkspaceInfoNotification(this.connection,e,this.logger)}catch(t){this.logger.warn?.(`[ACP Agent] sendWorkspaceInfo failed sessionId=${e}: ${t?.message??t}`)}}async initialize(e){this.logger.info?.("[ACP Agent] initialize() called"),this.clientCapabilities=e.clientCapabilities,this.clientInfoName=e.clientInfo?.name,J.ContainerUtil.get(G.AcpToolInterceptor).setCapabilities(e.clientCapabilities);let t=J.ContainerUtil.get(ek.HostCapabilityProvider),r=e.clientCapabilities?._meta?.["codebuddy.ai"],o=!!e.clientCapabilities?.elicitation?.form,i=r?.weixinpay?.interception===!0;o&&t.markElicitationForm(),i&&t.markWeixinpayInterception(),this.mainAgentOptIn=r?.mainAgentSupport===!0,(0,es.getMainAgentGateProvider)()?.setClientOptedIn?.(this.mainAgentOptIn,this.connectionId),await (0,es.getMainAgentGateProvider)()?.refresh().catch(e=>{this.logger.warn?.(`[ACP Agent] Failed to refresh main-agent gate: ${e instanceof Error?e.message:String(e)}`)}),J.ContainerUtil.get(eP.ReferenceService).setFileReferencesPathOnly(r?.fileReferencesPathOnly===!0);let n=this.mainAgentOptIn?this.resolveProcessDefaults():{},s={protocolVersion:eQ.PROTOCOL_VERSION,agentCapabilities:{promptCapabilities:{image:!0,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0},loadSession:!0,delegateToolsSupport:!0,mainAgentSupport:this.mainAgentOptIn&&((0,es.getMainAgentGateProvider)()?.isEnabled(this.connectionId)??!1),...n.agent||n.permissionMode?{processDefaults:n}:{}},authMethods:[{id:"iOA",name:"Login with iOA",description:null},{id:"external",name:"Login with Google/Github",description:null},{id:"internal",name:"Login with WeChat",description:null},{id:"selfhosted",name:"Login with Enterprise Domain",description:null}]};return this.logger.info?.("[ACP Agent] initialize() returning response"),s}async authenticate(e){let t={external:"external",internal:"internal",iOA:"iOA",selfhosted:"selfhosted"}[e.methodId];if(!t)throw Error(`Unsupported authentication method: ${e.methodId}`);try{await this.authManager.initialized,this.authManager.currentSessionSubject.getValue()&&(this.logger.info("User already logged in, logging out first to force re-authentication..."),await this.authManager.logout()),await this.authManager.login({type:t});let e=await this.authManager.waitAuthSession();if(!e)throw createAuthRequiredError();return{_meta:{"codebuddy.ai/userinfo":{userId:e.account.uid,userName:e.account.nickname,userNickname:e.account.nickname,enterpriseId:e.account.enterpriseId,enterpriseName:e.account.enterpriseName,enterprise:e.account.departmentFullName,authType:e.account.type??"local"}}}}catch(e){throw this.logger.error(`Authentication failed: ${e.message}`),createAuthRequiredError()}}async getUserInfo(){await this.authManager.initialized;let e=this.authManager.currentSessionSubject.getValue();if(!e)return{userInfo:void 0};let t="local";return e.account?.type&&(t=e.account.type),{userInfo:{userId:e.account?.uid??"",userName:e.account?.nickname??"",userNickname:e.account?.nickname??"",enterpriseId:e.account?.enterpriseId,enterpriseName:e.account?.enterpriseName,enterprise:e.account?.departmentFullName,authType:t,token:e.auth?.accessToken,accessToken:e.auth?.accessToken}}}async getRuntimeSession(e){if(this.currentSession?.id===e)return this.currentSession;try{let t=this.sessionManager.getCurrent();if(t?.id===e)return t}catch(e){this.logger.debug?.(`[ACP Agent] getRuntimeSession: getCurrent() failed, falling back: ${e?.message}`)}let t=this.sessionManager.sessionSubject?.value;return t?.id===e?t:this.sessionManager.get(e)}async applyRuntimeSessionModel(e,t,r){let o=await this.getRuntimeSession(e);if(!o)throw Error(`Session not found: ${e}`);let i=o.requestOptions.model||o.options.model;if(o.requestOptions.model=t,o.options.model=t,this.sessionManager.setOverrideModel(o.id,t),(0,ed.shouldSyncHostCliModel)())try{J.ContainerUtil.get(ex.CliSettingsProvider).set("model",t).catch(e=>{this.logger.warn?.(`[ACP Agent] ${r}: failed to sync CLI model setting: ${e?.message??e}`)})}catch(e){this.logger.warn?.(`[ACP Agent] ${r}: failed to access CLI settings provider: ${e?.message??e}`)}else try{await (0,ed.persistJobRespawnModel)(t)}catch(e){this.logger.warn?.(`[ACP Agent] ${r}: failed to persist job respawn model: ${e?.message??e}`)}await this.reconcileThinkingOverrideAfterModelChange(o,r),await this.reconcileContextWindowOverrideAfterModelChange(o,r),this.logger.info?.(`[ACP Agent] ${r}: applied model to runtime session ${e}: ${i||"default"} -> ${t}`)}async reconcileThinkingOverrideAfterModelChange(e,t){let r=await this.getCurrentModelLanguageConfig(e);if(this.canDisableThinking(r))return;let o=this.sessionManager.getOverrideThinking(e.id);o?.thinkingEnabled===!1&&(this.sessionManager.setOverrideThinking(e.id,{thinkingEnabled:!0,reasoningEffort:r?.reasoning?.defaultEffort??r?.reasoning?.effort}),this.logger.info?.(`[ACP Agent] ${t}: reset disabled thinking override for non-disableable model ${r?.id??"unknown"}`))}async reconcileContextWindowOverrideAfterModelChange(e,t){let r=this.sessionManager.getOverrideContextWindow(e.id);if(void 0===r)return;let o=await this.getCurrentModelLanguageConfig(e),i=Array.from(new Set((o?.contextWindow?.supportedLengths??[]).filter(e=>"number"==typeof e&&Number.isSafeInteger(e)&&e>0&&(o?.maxInputTokens===void 0||e<=o.maxInputTokens))));i.length>=2&&i.includes(r)||(this.sessionManager.setOverrideContextWindow(e.id,null),this.logger.info?.(`[ACP Agent] ${t}: cleared context_window override ${r} for model ${o?.id??"unknown"} (supported=[${i.map(String).join(", ")||"<none>"}])`))}async initializeSession(e){let t;if(await this.authManager.initialized,!this.authManager.currentSessionSubject.getValue())throw createAuthRequiredError();this.logger.info?.(`[ACP Agent] initializeSession: type=${e.type}, sessionId=${e.sessionId||"new"}`),this.sessionRequest={type:e.type,...e.sessionId&&{sessionId:e.sessionId}},this.sessionDeferred=new J.Deferred,e.mcpServers&&e.mcpServers.length>0&&(t=JSON.stringify({mcpServers:eJ.AcpUtils.convertAcpMcpServersToDynamic(e.mcpServers)}));let r=this.restOperationsFactory.create(),o=await this.endpointProvider.get(),i=`${o}/internal/agent`;this.logger.info?.(`[ACP Agent] initializeSession: sending request to ${i}`);let n=this.cliRuntimeOptions.get(),{sessionId:s,...a}=n;delete a.agent;let l="new"===e.type&&!this.currentSessionId&&"string"==typeof s&&s.length>0,c=t??n.mcpConfig,d=!0===n.strictMcpConfig;r.post(i,{...a,...l?{sessionId:s}:{},interactive:!1,acp:!0,mcpConfig:c,strictMcpConfig:d,...e.continue&&{continue:!0},...e.sessionId&&{sessionId:e.sessionId}},{headers:(0,eR.withSecurityHeader)({[K.HttpHeaders.CONTENT_TYPE]:K.MediaType.APPLICATION_JSON_UTF8,"acp-connection-id":this.connectionId||""}),proxy:!1}).catch(e=>{this.logger.error?.(`[ACP Agent] initializeSession: request failed: ${e.message}`),this.sessionDeferred&&this.sessionDeferred.reject(e)});let u=await this.sessionDeferred.promise;if(this.markWebUiAcpSession(u),await bindJobWorkerSession(u.id).catch(()=>void 0),(0,es.getMainAgentGateProvider)()?.stampHostKind(u,this.connectionId),(0,es.persistMainAgentHostKind)(u,this.sessionManager,e=>{this.logger.warn?.(`[ACP Agent] persist hostKind failed: ${e instanceof Error?e.message:String(e)}`)}),this.logger.info?.(`[ACP Agent] initializeSession: session received: ${u.id}`),"load"===e.type||"resume"===e.type){let e=await (0,ec.adoptTeamRuntimeForSession)(u,this.logger);e?.manifest.status==="paused_after_cancel"&&(0,eB.pauseTeamLeadFollowUpDispatch)(u)}let p=await this.getModelsInfo(u),g=this.getModesInfo(u),h=await this.getConfigOptions(u);return this.sessionRequest=void 0,{session:u,modelsInfo:p,modesInfo:g,configOptions:h}}async refreshProductAndTools(e){try{await J.ContainerUtil.get(eT.PluginRuntimeRefreshService).refresh("acp-host-refresh"),this.logger.info?.(`[ACP Agent] refreshProductAndTools done (${e})`)}catch(t){throw this.logger.warn?.(`[ACP Agent] refreshProductAndTools failed (${e}): ${t}`),t}}async reconcilePlugins(e){if(void 0!==e.requiredPluginIds&&(!Array.isArray(e.requiredPluginIds)||e.requiredPluginIds.some(e=>"string"!=typeof e)))throw eQ.RequestError.invalidParams("requiredPluginIds must be an array of plugin id strings");let t=e.requiredPluginIds??[],r="string"==typeof e.reason?e.reason:"acp-host",o=await J.ContainerUtil.get(eT.PluginRuntimeRefreshService).reconcileConfiguredPlugins({reason:r,requiredPluginIds:t});return{ready:o.ready,requiredPluginIds:o.requiredPluginIds,missingPluginIds:o.missingPluginIds,errors:o.errors}}async newSession(e){let t=!!e._meta?.["codebuddy.ai/continue"];this.logger.info?.(`[ACP Agent] newSession() called, continue=${t}`),t&&this.assertSessionWriterAvailable(this.sessionManager.sessionSubject?.value?.id),this.replayWindowQueue=[];try{let r,o=await this.initializeSession({type:"new",mcpServers:e.mcpServers,continue:t}),i=o.session,{modelsInfo:n,modesInfo:s,configOptions:a}=o,l=this.buildMainAgentDeps(),c=(0,es.getMainAgentGateProvider)()?.isEnabledForSession(i)??!1,d=!0;try{(0,en.assertSessionOwnedByConnection)(i,l)}catch{d=!1}if(c&&this.mainAgentOptIn&&d){if((0,en.isSessionBlank)(i)){let r=this.resolveProcessAgentName(),o=e._meta?.["codebuddy.ai/agent"],n="string"==typeof o&&o.trim().length>0?o.trim():void 0;n&&!t?await (0,en.applyUserSettableMainAgentIfBlank)(i,n,l,{overwriteExisting:!0})?this.logger.info?.(`[ACP Agent] newSession: applied main agent "${n}" to session ${i.id}`):this.logger.warn?.(`[ACP Agent] newSession: requested main agent "${n}" ignored`):await (0,en.applyUserSettableMainAgentIfBlank)(i,r,l)?this.logger.info?.(`[ACP Agent] newSession: applied process main agent "${r}" to session ${i.id}`):t||await (0,en.maybeStampConfiguredDefaultOnNewSession)(i,l)}s=this.getModesInfo(i),r=await this.buildMainAgentPicker(i,l),a=await this.getConfigOptions(i,r)}let u={sessionId:i.id,models:n,modes:s,configOptions:a};if(c&&this.mainAgentOptIn&&d){r??=await this.buildMainAgentPicker(i,l);let e=await l.getConfiguredDefaultName();Object.assign(u,{agents:r.directory,currentAgentName:r.currentAgentName,sessionBlank:(0,en.isSessionBlank)(i),...e?{defaultAgentName:e}:{}})}let p=this.isWebUiClient(),g=p&&i.history.length>0;return g&&await this.replayHistory(i),p&&(await this.sendAvailableCommandsUpdate(i.id),u.models=n=await this.getModelsInfo(i)),setTimeout(()=>{this.emitInitialSessionUpdates(i,{skipHistoryReplay:g}).catch(()=>{})},0),this.logger.info?.(`[ACP Agent] newSession() returning response: sessionId=${u.sessionId}`),u}catch(e){throw await this.flushReplayDeferred(new Set),e}}async emitInitialSessionUpdates(e,t){try{!t?.skipHistoryReplay&&e.history.length>0&&await this.replayHistory(e),await this.sendAvailableCommandsUpdate(e.id),this.sendWorkspaceInfo(e.id).catch(()=>{}),0===e.history.length&&await this.usagePublisher.publish(e.id,"new_session")}catch(e){this.logger.warn?.(`[ACP Agent] emitInitialSessionUpdates failed: ${e.message}`)}finally{await this.flushReplayDeferred(new Set)}}async loadSession(e){this.logger.info?.(`[ACP Agent] loadSession() called, sessionId=${e.sessionId}`),this.assertSessionWriterAvailable(e.sessionId);let t=this.isWebUiClient();t&&(this.replayWindowQueue=[]);try{let t,{session:r,modelsInfo:o}=await this.initializeSession({type:"load",sessionId:e.sessionId,mcpServers:e.mcpServers});r.history.length>0&&await this.replayHistory(r);let i=this.isWebUiClient()?await this.getModelsInfo(r):o;await this.sendAvailableCommandsUpdate(r.id),setTimeout(()=>this.sendAvailableCommandsUpdate(r.id),0),this.sendWorkspaceInfo(r.id).catch(()=>{});let n=(0,es.getMainAgentGateProvider)()?.isEnabledForSession(r)??!1,s=this.buildMainAgentDeps();n&&this.mainAgentOptIn&&this.isSessionOwnedByThisConnection(r)&&(t=await this.buildMainAgentPicker(r,s));let a=this.getModesInfo(r),l=await this.getConfigOptions(r,t),c={models:i,modes:a,configOptions:l};if(t){let e=await s.getConfiguredDefaultName();Object.assign(c,{agents:t.directory,currentAgentName:t.currentAgentName,sessionBlank:(0,en.isSessionBlank)(r),...e?{defaultAgentName:e}:{}})}return this.logger.info?.("[ACP Agent] loadSession() returning response"),0===r.history.length&&await this.usagePublisher.publish(r.id,"load_session"),c}finally{t&&await this.flushReplayDeferred(new Set)}}async resumeSession(e){return this.unstable_resumeSession(e)}async unstable_resumeSession(e){this.logger.info?.(`[ACP Agent] unstable_resumeSession() called, sessionId=${e.sessionId}`);let{session:t,modelsInfo:r,modesInfo:o,configOptions:i}=await this.initializeSession({type:"resume",sessionId:e.sessionId,mcpServers:e.mcpServers});return await this.sendAvailableCommandsUpdate(t.id),setTimeout(()=>this.sendAvailableCommandsUpdate(t.id),0),this.sendWorkspaceInfo(t.id).catch(()=>{}),this.logger.info?.("[ACP Agent] unstable_resumeSession() returning response"),await this.usagePublisher.publish(t.id,"resume_session"),{models:r,modes:o,configOptions:i}}async replayHistory(e){let t=await (0,e3.collectSessionReplayEvents)(e,this.logger,{showPreCompactHistory:(0,e3.isReplayShowPreCompactEnabled)(),webUiClient:this.isWebUiClient(),terminalOutputEnabled:(0,eX.clientSupportsTerminalOutput)(this.clientCapabilities),terminalOutputChunkEnabled:(0,eX.clientSupportsTerminalOutputChunk)(this.clientCapabilities),mcpUiResourceReader:async(e,t)=>{let r=await this.findMcpServer(e);return r?r.readResource({uri:t}):[]}});await (0,e3.emitSessionReplayEvents)(this.connection,t),this.logger.info?.("[ACP Agent] replayHistory: complete")}isReplayWindowActive(){return null!==this.replayWindowQueue}isWebUiClient(){return(0,e1.isWebUiAcpClientName)(this.clientInfoName)}markWebUiAcpSession(e){let t=this.isWebUiClient();if((0,e1.syncWebUiAcpSessionFlag)(e,t),t)try{J.ContainerUtil.get(eC.FollowupQueueService).watch(e)}catch{}}queueReplayDeferredSessionUpdate(e){this.replayWindowQueue??=[],this.replayWindowQueue.push(e)}async flushReplayDeferred(e){let t=this.replayWindowQueue;if(this.replayWindowQueue=null,!t||0===t.length)return;let r=this.connection;if(!r)return void this.logger.debug?.(`[ACP Agent] flushReplayDeferred: no authorized connection, dropping ${t.length} deferred broadcast(s)`);for(let{sessionId:o,update:i}of t){let t=extractReplayUserText(i);if(t&&e.has(t)){this.logger.debug?.(`[ACP Agent] flushReplayDeferred: drop deferred broadcast (replay covers it): ${JSON.stringify(t.slice(0,40))}`);continue}try{await r.sessionUpdate({sessionId:o,update:(0,eZ.withAcpTimestampMeta)(i)})}catch(e){this.logger.debug?.(`[ACP Agent] flushReplayDeferred: delivery failed: ${e}`)}}}getCodebuddyExpertId(e){let t="string"==typeof e?.expertId?e.expertId.trim():"";if(t)return t;let r=e?.expert;if(r&&"object"==typeof r&&!Array.isArray(r)){let e=r.id;if("string"==typeof e&&e.trim())return e.trim()}}applyUpstreamMeta(e,t){let r="string"==typeof t?.promptRequestId?t.promptRequestId:void 0,o=(0,eq.isValidW3CTraceId)(r)?r:void 0;o&&(e.promptRequestId=o);let i="string"==typeof t?.userId?t.userId:void 0,n="string"==typeof t?.conversationId?t.conversationId:void 0,s="string"==typeof t?.locale?t.locale:"string"==typeof t?.language?t.language:void 0,a=this.getCodebuddyExpertId(t);(i||n||s||a)&&(e.meta={...e.meta??{},...i?{"codebuddy.ai/userId":i}:{},...n?{"codebuddy.ai/conversationId":n}:{},...s?{"codebuddy.ai/locale":s}:{},...a?{"codebuddy.ai/expertId":a}:{}});let l="number"==typeof t?.clientSendTime?t.clientSendTime:void 0;l&&(e.telemetry||(e.telemetry={}),e.telemetry.clientSendTime=l);let c=this.parseTelemetryClientInfo(t?.[eD.TELEMETRY_CLIENT_INFO_META_KEY]);c&&(e.telemetryClientInfo=c),o?this.logger.info?.(`[ACP Agent] adopt upstream promptRequestId=${o} for session ${e.id}`):r&&this.logger.warn?.(`[ACP Agent] ignore invalid upstream promptRequestId=${r} for session ${e.id}`)}parseTelemetryClientInfo(e){if(!e||"object"!=typeof e)return;let t={},r=!1;for(let o of eD.TELEMETRY_CLIENT_INFO_KEYS){let i=e[o];"string"==typeof i&&""!==i&&(t[o]=i,r=!0)}return r?t:void 0}resolvePromptTracking(e,t){let r=e._meta??void 0,o=r?.["codebuddy.ai"],i=r?.["codebuddy.ai/requestId"]??o?.requestId??(0,et.uuidv7)(),n=r?.messageId??r?.["codebuddy.ai/userMessageId"]??r?.["codebuddy.ai/messageRequestId"]??o?.messageRequestId??i,s=r?.["codebuddy.ai/messageId"]??o?.messageId;return{requestId:i,messageId:"string"==typeof s&&s.trim()?s.trim():`${e.sessionId}-${n}`,messageRequestId:n}}async prompt(e){this.logger.info?.(`[ACP Agent] prompt() called for session ${e.sessionId}`);let t=await this.getRuntimeSession(e.sessionId);if(!t)throw Error(`Session not found: ${e.sessionId}`);this.currentSession!==t&&this.setSession(t),this.markWebUiAcpSession(t);let r=e._meta??void 0,o=r?.["codebuddy.ai"],i=this.getCodebuddyExpertId(o),n="string"==typeof o?.mode&&["craft","ask","plan","expert"].includes(o.mode)?o.mode:void 0;if(n&&(t.meta={...t.meta??{},"codebuddy.ai/mode":n},i||delete t.meta["codebuddy.ai/expertId"]),this.applyUpstreamMeta(t,o),o?.isAutomationBackground===!0&&(t.agentPurpose=eo.AgentPurpose.Automation,this.logger.info?.(`[ACP Agent] prompt() automation detected, set agentPurpose=${t.agentPurpose} for session ${t.id}`)),o?.isClearSession===!0)return await this.handleClearSession(t,o,r);if(o?.isCompactSession===!0)return await this.handleCompactSession(t);let s=this.resolvePromptTracking(e,t),a=Date.now();t.telemetry||(t.telemetry={}),t.telemetry.promptStartTime=a,this.sessionErrorTracker?.reset(t.id);let l=new J.Deferred;this.promptEvent.next({request:e,responseDeferred:l,tracking:s});try{let e=await l.promise;this.logger.info?.(`[ACP Agent] prompt() completed with stopReason: ${e.stopReason}`);try{let r=Date.now()-a;this.galileoTimingHook?.reportTaskTotal(r,{taskId:s.requestId,model:t.requestOptions?.model??"",agentName:t.agentName??"",agentPurpose:t.agentPurpose??""});let o=this.sessionErrorTracker?.snapshot(t.id)??{modelErrorCount:0,modelSuccessAfterErrorCount:0,toolErrorCount:0},i=e._meta?.["codebuddy.ai/errorMessage"],n=(0,eb.resolveTaskOutcome)(e.stopReason,i,o);this.sessionErrorTracker?.cleanup(t.id),this.metricsAggregator?.recordTaskOutcome(n,{model:t.requestOptions?.model??"",agentName:t.agentName??"",scene:t.meta?.["codebuddy.ai/mode"]??"",promptRequestId:t.promptRequestId??"",conversationRequestId:s.requestId,traceId:"string"==typeof e._meta?.["codebuddy.ai/traceId"]?e._meta["codebuddy.ai/traceId"]:t.traceId??"",stopReason:e.stopReason,errorCategory:(0,eb.extractCategoryFromErrorMessage)(i)??"",expertId:t.meta?.["codebuddy.ai/expertId"]??""}),e._meta||(e._meta={});let l=e._meta;l["codebuddy.ai/outcome"]||(l["codebuddy.ai/outcome"]=n)}catch{}return e}finally{await this.usagePublisher.publish(t.id,"prompt_end")}}async handleClearSession(e,t,r){let o=t.clearMessageId??`session-separator-${Date.now()}`,i=t.clearExtra,n=i&&"object"==typeof i?i:{isSessionSeparator:!0},s=(0,eZ.resolveAcpTimestamp)(r?.timestamp);this.logger.info?.(`[ACP Agent] handleClearSession: sessionId=${e.id}, messageId=${o}`);try{return await this.sessionManager.addHistory(e,[{id:o,type:"message",role:"system",content:"",timestamp:s,providerData:{skipRun:!0,isSessionSeparator:!0,separatorMessageId:o,separatorExtra:n}}]),this.connection&&await this.connection.sessionUpdate((0,eZ.withAcpTimestampMeta)({sessionId:e.id,update:{sessionUpdate:"session_info_update"},_meta:{"codebuddy.ai":{isHistoryReplay:!1,messageId:o,isSessionSeparator:!0,separatorExtra:n}}},s)),this.logger.info?.(`[ACP Agent] handleClearSession: separator written & emitted, messageId=${o}`),{stopReason:"end_turn"}}catch(e){throw this.logger.error?.("[ACP Agent] handleClearSession failed:",e),e}}async handleCompactSession(e){if(this.logger.info?.(`[ACP Agent] handleCompactSession: sessionId=${e.id}`),0===e.history.length)return this.logger.info?.(`[ACP Agent] handleCompactSession: skipped empty history, sessionId=${e.id}`),{stopReason:"end_turn"};let t=Date.now();try{if(!await this.contextCompactSummarizer.compactAndSummarize(e,{force:!0,skipContinue:!0}))throw new eQ.RequestError(e8.ModelServiceError,"\u4E0A\u4E0B\u6587\u538B\u7F29\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u6216\u65B0\u5EFA\u4F1A\u8BDD\u51CF\u5C11\u5386\u53F2\u4E0A\u4E0B\u6587\u540E\u518D\u7EE7\u7EED\u3002",{category:"model_service",reason:"compact_failed"});return this.galileoTimingHook?.reportContextCompact(Date.now()-t,{compactType:"manual",model:e.requestOptions?.model??""}),this.logger.info?.(`[ACP Agent] handleCompactSession: completed, sessionId=${e.id}`),{stopReason:"end_turn"}}catch(e){throw this.logger.error?.("[ACP Agent] handleCompactSession failed:",e),e}}consumePreMessageCompactEnd(e){if(!e.meta?.[ef.SESSION_META_PRE_MESSAGE_COMPACT_ENDED])return{ended:!1};let t=e.meta[ef.SESSION_META_PRE_MESSAGE_COMPACT_ERROR_MESSAGE];return(delete e.meta[ef.SESSION_META_PRE_MESSAGE_COMPACT_ENDED],delete e.meta[ef.SESSION_META_PRE_MESSAGE_COMPACT_ERROR_MESSAGE],"string"==typeof t)?{ended:!0,errorMessage:t}:{ended:!0}}serializePreMessageCompactFailure(e){return JSON.stringify(new eQ.RequestError(e8.ModelServiceError,e,{category:"model_service",details:e,reason:"pre_message_compact_failed"}).toErrorResponse())}createEventForwardingPromise(e,t,r){let o,i=this.activeForwardingCleanups.get(e.id);i&&(this.logger.warn?.(`[ACP Agent] createEventForwardingPromise: replacing stale forwarding subscription for session ${e.id}`),i()),this.logger.info?.(`[ACP Agent] createEventForwardingPromise: subscribing to session ${e.id}`);let n=e.resultSubject.getValue(),s=e.traceId,getPromptTraceId=()=>(e.traceId&&(s=e.traceId),s),a=new Set,getAcpUpdateMessageId=e=>{let t=e.messageId;if("string"==typeof t&&t.length>0)return t;let r=e._meta;if(!r||"object"!=typeof r||Array.isArray(r))return;let o=r["codebuddy.ai/messageId"];return"string"==typeof o&&o.length>0?o:void 0},hasStreamedAgentMessage=e=>{let t=getAcpUpdateMessageId(e);return!!(t&&a.has(t))},markStreamedAgentMessage=(e,t)=>{if("agent_message_chunk"!==e.sessionUpdate)return;let r=getAcpUpdateMessageId(e);r&&a.add(r),t&&a.add(t)},injectTrackingMeta=(r,i,n)=>{let s=e.conversationRequestId||t?.requestId,a=t?.messageRequestId||s,l="string"==typeof r.sessionUpdate?r.sessionUpdate:void 0,c=getPromptTraceId(),d={...r._meta||{}},u=!0===d["codebuddy.ai/isCompactInternal"],p="agent_message_chunk"===l||"agent_thought_chunk"===l||"tool_call"===l||"tool_call_update"===l,g=u?void 0:t?.messageId,h=p?(0,ef.withCompactGeneration)(g,e):g,m=h||n||o||e.messageId,f=p&&!!h;s&&!d["codebuddy.ai/requestId"]&&(d["codebuddy.ai/requestId"]=s),e.promptRequestId&&!d["codebuddy.ai/promptRequestId"]&&(d["codebuddy.ai/promptRequestId"]=e.promptRequestId),m&&f?d["codebuddy.ai/messageId"]=m:m&&!d["codebuddy.ai/messageId"]&&(d["codebuddy.ai/messageId"]=m),a&&!d["codebuddy.ai/messageRequestId"]&&(d["codebuddy.ai/messageRequestId"]=a),c&&!d["codebuddy.ai/traceId"]&&(d["codebuddy.ai/traceId"]=c),(0,eH.applyTurnCarrierToMeta)(d,(0,eH.turnCarrierForSession)(e));let y=e.requestOptions.model||e.options.model;y&&!d["codebuddy.ai/requestModelId"]&&(d["codebuddy.ai/requestModelId"]=y);let _=e.telemetry?.modelName;_&&!d["codebuddy.ai/requestModelName"]&&(d["codebuddy.ai/requestModelName"]=_);let w=e.meta?.responseModelId;w&&!d["codebuddy.ai/responseModelId"]&&(d["codebuddy.ai/responseModelId"]=w);let b={...r,_meta:d};return"user_message_chunk"===b.sessionUpdate&&a&&!b.messageId?b.messageId=a:f&&m?b.messageId=m:!b.messageId&&("user_message_chunk"===b.sessionUpdate&&a?b.messageId=a:("agent_message_chunk"===b.sessionUpdate||"agent_thought_chunk"===b.sessionUpdate)&&m&&(b.messageId=m)),(0,eZ.withAcpTimestampMeta)(b,i)};return new Promise((i,s)=>{let a,l,c,d="end_turn",u=new Map,p=new Map,g=new Map,h=!1,m=[],f=J.ContainerUtil.get(el.AgentTaskManager),getOwnedTeamName=()=>e.meta?.isTeamLead===!0&&"string"==typeof e.meta.teamName&&e.meta.teamName.trim().length>0?e.meta.teamName:void 0,allTeamMembersQuiescent=()=>{let e=getOwnedTeamName();if(!e)return!0;let t=(0,eB.getTeamMemberRegistry)().getAll().filter(t=>t.teamName===e);return!f.hasPendingTeamNotifications(e)&&t.every(e=>{if("in-process"===e.info.backendType)return!e.isWorking();let t=e.getAgentTask();if(!t)return!0;let r=t.status;return"completed"===r||"failed"===r||"cancelled"===r||"killed"===r})},y=J.ContainerUtil.get(eD.SessionRunStateMachine),_=null,w=null,b=["task-completed","task-failed","task-cancelled","task-killed"],tryResolvePending=()=>{if(!_||!allTeamMembersQuiescent()||e.isCompressing)return;if(void 0!==getOwnedTeamName()&&!y.isIdle(e))return void this.logger.info?.(`[ACP Agent] Team quiescent but session not idle \u{2014} deferring resolve for session ${e.id}`);this.pendingCancellations.has(e.id)&&w&&(this.logger.info?.(`[ACP Agent] Team quiescent under user cancel \u{2014} overriding stopReason to 'cancelled' for session ${e.id} (was ${w.stopReason})`),w.stopReason="cancelled",w.errorMessage=void 0,w.finishReason=void 0,w.traceId=void 0,w.promptError=void 0,this.consumePendingCancellation(e.id),e.meta?.userInitiatedAbort&&delete e.meta.userInitiatedAbort);let t=_;_=null,w=null,this.logger.info?.(`[ACP Agent] Team quiescent + session idle \u{2014} running pendingTeamResolve for session ${e.id}`),t()},teamTerminalListener=()=>{setTimeout(()=>tryResolvePending(),0)};for(let e of b)f.on(e,teamTerminalListener);let teamNotificationSettledListener=e=>{let t=getOwnedTeamName();t&&t===e&&setTimeout(()=>tryResolvePending(),0)};f.onTeamNotificationSettled(teamNotificationSettledListener),m.push(y.getChange$(e,!0).subscribe(()=>{_&&y.isIdle(e)&&setTimeout(()=>tryResolvePending(),0)}));let cleanup=()=>{if(!h){for(let e of(h=!0,m))e.unsubscribe();for(let t of(r?.signal&&c&&r.signal.removeEventListener("abort",c),this.activeForwardingCleanups.get(e.id)===cleanup&&this.activeForwardingCleanups.delete(e.id),b))f.off(t,teamTerminalListener);f.offTeamNotificationSettled(teamNotificationSettledListener),_=null,w=null,u.clear(),p.clear(),g.clear(),this.clearPendingEarlyAskSkipsForSession(e.id)}},resolveCancelledByAbort=()=>{h||(d="cancelled",this.consumePendingCancellation(e.id),e.meta?.userInitiatedAbort&&delete e.meta.userInitiatedAbort,this.logger.info?.(`[ACP Agent] Forwarding aborted for session ${e.id}; resolving prompt as cancelled`),cleanup(),i({stopReason:d,traceId:getPromptTraceId()}))},settleWhenTeamTerminal=t=>{let run=()=>{cleanup(),t.promptError?s(t.promptError):i(t)};if(allTeamMembersQuiescent()&&(void 0===getOwnedTeamName()||y.isIdle(e)))return void run();let r=[];allTeamMembersQuiescent()||r.push("team members not yet quiescent"),void 0===getOwnedTeamName()||y.isIdle(e)||r.push("session not idle (auto-dispatch run in progress)"),this.logger.info?.(`[ACP Agent] settleWhenTeamTerminal: deferring settlement for session ${e.id} \u{2014} ${r.join(", ")} (stopReason=${t.stopReason})`),_=run,w=t};m.push(e.interruptionSubject.subscribe(async t=>{t&&await this.handleToolApproval(t,e.id)})),m.push(e.phaseSubject.subscribe(t=>{if(this.connection){let o=this.logger;this.sendPromptSessionUpdate(injectTrackingMeta({sessionId:e.id,update:{sessionUpdate:"session_info_update",_meta:{"codebuddy.ai/agentPhase":t}}}),e.id,r?.signal).catch(e=>{o.warn?.("[ACP Agent] Failed to send phase update:",e)})}if(J.ContainerUtil.get(eD.SessionRunStateMachine).isIdle(e)){let t=this.consumePreMessageCompactEnd(e);if(!t.ended)return;t.errorMessage&&(d="refusal",a=this.serializePreMessageCompactFailure(t.errorMessage)),this.logger.info?.(`[ACP Agent] Resolving prompt after pre-message compact ended without running the user prompt, stopReason=${d}`),cleanup(),i({stopReason:d,errorMessage:a,finishReason:l,traceId:getPromptTraceId()})}})),m.push(e.progressSubject.subscribe(async t=>{try{this.logger.info?.(`[ACP Agent] Progress update: ${t?JSON.stringify({type:t}):"null"}`),this.connection&&await this.sendPromptSessionUpdate(injectTrackingMeta({sessionId:e.id,update:{sessionUpdate:"session_info_update",_meta:{"codebuddy.ai/progress":t?{type:t}:null}}}),e.id,r?.signal)}catch(e){this.logger.warn?.("[ACP Agent] Failed to send progress update:",e)}})),m.push(e.combineSubject.subscribe(async s=>{try{if("input"===s.type){if("function_call"===s.data.type||"function_call_result"===s.data.type||"function_call_output"===s.data.type){this.logger.info?.(`[ACP Agent] Received input event type: ${s.data.type}, callId: ${s.data.callId}`);let t=J.ContainerUtil.get(G.AcpToolInterceptor).getFileContentCache(),o=eJ.AcpUtils.convertInputItemToAcp(s.data,t,{parentToolUseId:s.parentToolUseId});if(o){let t=(0,eZ.getAcpItemTimestamp)(s.data);if(this.logger.info?.(`[ACP Agent] Converted to sessionUpdate: ${o.sessionUpdate}, toolCallId: ${o.toolCallId}`),"tool_call"===o.sessionUpdate&&o.toolCallId){this.toolCallSentDeferreds.has(o.toolCallId)||this.toolCallSentDeferreds.set(o.toolCallId,new J.Deferred);let e=eJ.AcpUtils.extractToolName(o);e&&this.toolCallNameById.set(o.toolCallId,e)}if(await this.sendPromptSessionUpdate({sessionId:e.id,update:injectTrackingMeta(o,t)},e.id,r?.signal),"tool_call"===o.sessionUpdate&&o.toolCallId){let e=this.toolCallSentDeferreds.get(o.toolCallId);e&&e.resolve()}"tool_call_update"===o.sessionUpdate&&o.toolCallId?(this.logger.info?.(`[ACP Agent] Cleaning up tool_call deferral for ${o.toolCallId}`),this.notifyToolCallUpdateSent(o.toolCallId,o.status??void 0)):"tool_call_update"!==o.sessionUpdate||o.toolCallId||this.logger.warn?.("[ACP Agent] tool_call_update missing toolCallId!")}}else if(this.isWebUiClient()&&eJ.AcpUtils.isGoalAcpHistoryItem(s.data)){let t=eJ.AcpUtils.convertHistoryItemToAcp(s.data),o=(0,eZ.getAcpItemTimestamp)(s.data);for(let i of t)await this.sendPromptSessionUpdate({sessionId:e.id,update:injectTrackingMeta(i,o)},e.id,r?.signal)}else if("message"===s.data.type&&"user"===s.data.role&&s.data.providerData?.isCompactInternal){let t=!!e.meta?.[ef.SESSION_META_COMPACT_CONTINUE_IN_PROGRESS],o=!!s.parentToolUseId,i=!!e.isCompressing;if(t||o||i)this.logger.info?.(`[ACP Agent] skip forwarding compact internal user message (sessionId=${e.id}, messageId=${s.data.id}, reason=${i?"compactInProgress":o?"sub-agent":"postCompactContinue"})`);else{let t=eJ.AcpUtils.convertHistoryItemToAcp(s.data),o=(0,eZ.getAcpItemTimestamp)(s.data);for(let i of t)await this.sendPromptSessionUpdate({sessionId:e.id,update:injectTrackingMeta(i,o)},e.id,r?.signal)}}else if("message"===s.data.type&&"assistant"===s.data.role){let t=s.data?.providerData?.model;"string"==typeof t&&t&&(e.meta||(e.meta={}),e.meta.responseModelId=t);let o=eJ.AcpUtils.convertHistoryItemToAcp(s.data),i=(0,eZ.getAcpItemTimestamp)(s.data);for(let t of o){let o=s.parentToolUseId?{...t,_meta:{...t._meta||{},"codebuddy.ai/parentToolCallId":s.parentToolUseId}}:t;if(hasStreamedAgentMessage(o)){this.logger.debug?.("[ACP Agent] skip final assistant history item already streamed");continue}let n=injectTrackingMeta(o,i);markStreamedAgentMessage(n),await this.sendPromptSessionUpdate({sessionId:e.id,update:n},e.id,r?.signal)}}}else if("model"===s.type){s.parentToolUseId||s.data?.type!=="response_started"||(o=e.messageId);let t=s.data?.event;t&&"string"==typeof t.model&&t.model&&(e.meta||(e.meta={}),e.meta.responseModelId=t.model);let i=o,n=eJ.AcpUtils.convertOpenAIEventToAcp(s.data),a=(0,eZ.getAcpItemTimestamp)(s.data);for(let t of n){let o={};s.parentToolUseId&&(o["codebuddy.ai/parentToolCallId"]=s.parentToolUseId);let n=!!e.meta?.[ef.SESSION_META_COMPACT_CONTINUE_IN_PROGRESS];if(e.isCompressing&&!n){o["codebuddy.ai/isCompactInternal"]=!0;let t=e.meta?.[ef.SESSION_META_COMPACT_TYPE];t&&(o[ef.ACP_META_COMPACT_TYPE]=t)}Object.keys(o).length>0&&(t._meta={...t._meta||{},...o});let l=t.sessionUpdate;if("tool_call_pending"===l){let n=t.toolCallId,s=t.toolName,l=t.toolCallIndex;if(n||void 0===l||(n=u.get(l)),!n||(void 0!==l&&u.set(l,n),s&&p.set(n,s),g.has(n)||g.set(n,new JsonStreamParser((e,t)=>{let r=e instanceof Error?`${e.message}${e.stack?`
|
|
4
4
|
${e.stack}`:""}`:String(e);this.logger.warn?.(`[ACP Agent] JsonStreamParser unexpected error in ${t} for ${n}: ${r}`)})),!t.toolCallId))continue;let c={sessionUpdate:"tool_call",toolCallId:n,title:s??"",kind:"other",status:"in_progress",input:{},rawInput:{},_meta:{...o,"codebuddy.ai/toolName":s}};await this.sendPromptSessionUpdate({sessionId:e.id,update:injectTrackingMeta(c,a,i)},e.id,r?.signal)}else if("tool_call_arguments_delta"===l){let n=t.toolCallId;if(!n){let e=t.toolCallIndex;if(void 0===e){this.logger.warn?.("[ACP Agent] tool_call_arguments_delta missing both toolCallId and toolCallIndex; dropping delta");continue}if(!(n=u.get(e))){this.logger.warn?.(`[ACP Agent] tool_call_arguments_delta for unknown toolCallIndex=${e}; dropping delta`);continue}}let s=t.toolName;s&&!p.has(n)&&p.set(n,s);let l=t.argumentsDelta??"",c=t.sensitiveProtection;if(!l)continue;let d=g.get(n);if(!d){let e=n;d=new JsonStreamParser((t,r)=>{let o=t instanceof Error?`${t.message}${t.stack?`
|
|
@@ -28,7 +28,7 @@ recent output: ${r}
|
|
|
28
28
|
</session>`}function cleanLine(e){return e.replace(/^[\s>*\-#`]+/,"").replace(/[`*_]/g,"").replace(/^["'\u201c\u201d]+|["'\u201c\u201d]+$/g,"").replace(/\s+/g," ").trim()}function truncate(e){return e.length<=i?e:`${e.slice(0,i-1)}\u{2026}`}},59885(e,t,r){r.r(t),r.d(t,{CLEAR_TERMINAL_SEQUENCE:()=>o,ERASE_SCREEN_SEQUENCE:()=>i,HIDE_CURSOR_SEQUENCE:()=>s,RESET_TERMINAL_SEQUENCE:()=>n,clearTerminalScreen:()=>clearTerminalScreen,eraseTerminalScreen:()=>eraseTerminalScreen,hideTerminalCursor:()=>hideTerminalCursor,releaseTerminalScreen:()=>releaseTerminalScreen});let o="\x1b[2J\x1b[3J\x1b[H",i="\x1b[2J\x1b[H",n="\x1b[?25h\x1b[0m",s="\x1b[?25l";function hideTerminalCursor(e=process.stdout){e.isTTY&&e.write(s)}function clearTerminalScreen(e=process.stdout){e.isTTY&&e.write(o)}function eraseTerminalScreen(e=process.stdout){e.isTTY&&e.write(i)}function releaseTerminalScreen(e=process.stdout){e.isTTY&&e.write(`${n}${o}`)}},57646(e,t,r){function isZeroWidth(e){return e>=768&&e<=879||e>=8203&&e<=8207||65279===e||e>=65024&&e<=65039||e>=6832&&e<=6911||e>=8400&&e<=8447}r.r(t),r.d(t,{displayWidth:()=>displayWidth,padEndToDisplayWidth:()=>padEndToDisplayWidth,truncateToDisplayWidth:()=>truncateToDisplayWidth});let o=[[4352,4447],[8986,8987],[9193,9203],[9208,9210],[9725,9726],[9748,9749],[9800,9811],[9855,9855],[9875,9875],[9889,9889],[9898,9899],[9917,9918],[9924,9925],[9934,9934],[9940,9940],[9962,9962],[9970,9971],[9973,9973],[9978,9978],[9981,9981],[9989,9989],[9994,9995],[10024,10024],[10060,10060],[10062,10062],[10067,10069],[10071,10071],[10133,10135],[10160,10160],[10175,10175],[11035,11036],[11088,11088],[11093,11093],[11904,12350],[12353,13311],[13312,19903],[19968,40959],[40960,42191],[44032,55203],[63744,64255],[65040,65049],[65072,65135],[65280,65376],[65504,65510],[126980,126980],[127183,127183],[127374,127374],[127377,127386],[127488,127743],[127744,129791],[131072,262141]];function isWide(e){for(let[t,r]of o){if(e<t)break;if(e<=r)return!0}return!1}function codePointWidth(e){return isZeroWidth(e)||e<32||e>=127&&e<160?0:isWide(e)?2:1}function displayWidth(e){let t=0;for(let r of e)t+=codePointWidth(r.codePointAt(0));return t}function truncateToDisplayWidth(e,t){if(t<=0)return"";if(displayWidth(e)<=t)return e;if(1===t)return"\u2026";let r=t-1,o=0,i="";for(let t of e){let e=codePointWidth(t.codePointAt(0));if(o+e>r)break;i+=t,o+=e}return`${i}\u{2026}`}function padEndToDisplayWidth(e,t){let r=t-displayWidth(e);return r>0?e+" ".repeat(r):e}},88206(e,t,r){r.r(t),r.d(t,{buildWorktreeGuard:()=>buildWorktreeGuard,countUnpushedCommits:()=>countUnpushedCommits});var o=r(35317);let i=(0,r(39023).promisify)(o.execFile);async function countUnpushedCommits(e){try{let{stdout:t}=await i("git",["rev-list","--count","HEAD","--not","--remotes"],{cwd:e,timeout:1e4}),r=Number(t.trim());return Number.isFinite(r)?r:void 0}catch{return}}function buildWorktreeGuard(e){return async t=>{let r=t.state.worktreePath;if(!r)return;for(let o of e.listJobs())if(o.id!==t.id&&o.state.worktreePath===r&&"number"==typeof o.state.pid&&e.isProcessRunning(o.state.pid))return`worktree is in use by session ${o.id}`;let o=await (e.countUnpushed??countUnpushedCommits)(r);if(void 0!==o&&o>0)return`worktree has ${o} unpushed commit${1===o?"":"s"} \u{2014} push them first`}}},40427(e,t,r){r.r(t),r.d(t,{MainAgentNotEnabledError:()=>MainAgentNotEnabledError,applyMainAgentToSession:()=>applyMainAgentToSession,applyUserSettableMainAgentIfBlank:()=>applyUserSettableMainAgentIfBlank,assertSessionOwnedByConnection:()=>assertSessionOwnedByConnection,buildAgentDirectory:()=>buildAgentDirectory,handleGetAgents:()=>handleGetAgents,handleSetAgent:()=>handleSetAgent,isSessionBlank:()=>c.isSessionBlank,isSessionVisibleToMainAgentRpc:()=>isSessionVisibleToMainAgentRpc,isUserSettableMainAgent:()=>isUserSettableMainAgent,maybeStampConfiguredDefaultOnNewSession:()=>maybeStampConfiguredDefaultOnNewSession,resolveDisplayMainAgentName:()=>resolveDisplayMainAgentName,resolveEffectiveDefaultAgentName:()=>resolveEffectiveDefaultAgentName,resolveRuntimeSession:()=>resolveRuntimeSession});var o=r(48400),i=r(13942),n=r(93034),s=r(68400),a=r(81998),l=r(30694),c=r(25682);let MainAgentNotEnabledError=class MainAgentNotEnabledError extends Error{constructor(){super("main-agent support is not enabled for this connection")}};function isSessionVisibleToMainAgentRpc(e,t){if(!e)return!1;let r=e.meta?.[c.MAIN_AGENT_HOST_KIND_KEY];if("unopted"===r)return!1;if(!t)return!0;let o="string"==typeof e.meta?.acpConnectionId?e.meta.acpConnectionId:void 0;return!o||o===t||"native"===r||"opted-in"===r||"native"===(0,l.getMainAgentGateProvider)()?.getHostKind(o)}function assertSessionOwnedByConnection(e,t){if(!isSessionVisibleToMainAgentRpc(e,t.connectionId))throw new MainAgentNotEnabledError}function resolveRuntimeSession(e,t,r){let o;try{o=r.sessionManager.getCurrent?.()}catch{o=void 0}return[o,r.sessionManager.sessionSubject?.value].find(t=>!!t&&t.id===e)??t}async function resolveEffectiveDefaultAgentName(e){let t=e.agentManager.getDefaultAgentName();if(!e.gateEnabled()||!e.optIn())return t;try{let r=await e.getConfiguredDefaultName();if(r&&r!==t){let o=(await e.agentManager.getAllConfigs()).find(e=>e.name===r);if(o&&isUserSettableMainAgent(o,t))return r}}catch{}return t}async function buildAgentDirectory(e,t){let r=[];for(let o of(await e.getAllConfigs())){let e=o.name;if(e)try{let l=(o.tags??[]).includes(n.CUSTOM_AGENT_TAG),c=(0,s.isShippedStandingModeAgent)(o)?(0,a.localizeBuiltinAgentMode)(e,t.language):void 0,d={name:e,displayName:c?.displayName||o.displayName||e,description:c?.description||o.description||void 0,custom:l,...o.declaredModel?{modelId:o.declaredModel}:{modelInherited:!0}};if(!isUserSettableMainAgent(o,t.defaultAgentName))continue;if(e===t.defaultAgentName||(0,i.isProductDefaultAgent)(o)||(0,s.isShippedStandingModeAgent)(o))r.push({...d,source:l?(o.tags??[]).includes(n.CustomAgentScope.USER)?"user":"project":"built-in"});else{let e=(0,i.classifyAgentSource)(o,{includeInternal:!1});if(void 0===e)continue;r.push({...d,source:e})}}catch(t){r.push({name:e,displayName:e,source:"built-in",custom:!1,broken:t instanceof Error?t.message:String(t)})}}return r}async function resolveDisplayMainAgentName(e,t,r,o){return t.gateEnabled()&&t.optIn()?(0,l.pickMainAgentName)({session:e,gateEnabled:!0,defaultAgentName:o,includeMention:!0,nameExists:e=>r.has(e),getConfiguredDefaultName:t.getConfiguredDefaultName,getLastUsedName:t.getLastUsedName}):o}async function handleGetAgents(e,t){let r,o,i;if(!t.gateEnabled()||!t.optIn())throw new MainAgentNotEnabledError;let n=await resolveEffectiveDefaultAgentName(t);try{let e=await t.getLanguage?.();r="string"==typeof e?e:void 0}catch{r=void 0}let s=await buildAgentDirectory(t.agentManager,{defaultAgentName:n,language:r}),a=new Set(s.map(e=>e.name));if(e.sessionId){let r=await t.sessionManager.get(e.sessionId);if(r){let s=resolveRuntimeSession(e.sessionId,r,t);isSessionVisibleToMainAgentRpc(s,t.connectionId)?(o=await resolveDisplayMainAgentName(s,t,a,n),i=(0,c.isSessionBlank)(s)):t.logger?.warn?.(`[MainAgent] getAgents omitted session fields for ${e.sessionId} (not visible to ${t.connectionId??"no-connection"})`)}}return{defaultAgentName:n,currentAgentName:o,sessionBlank:i,agents:s}}function isUserSettableMainAgent(e,t){return!!(0,a.isStandingMainAgentCandidate)(e,t)&&(!!(e.name===t||(0,i.isProductDefaultAgent)(e)||(0,s.isShippedStandingModeAgent)(e))||void 0!==(0,i.classifyAgentSource)(e,{includeInternal:!1}))}async function applyUserSettableMainAgentIfBlank(e,t,r,o){let i="string"==typeof t?t.trim():"";if(!i||!r.gateEnabled()||!r.optIn()||!(0,c.isSessionBlank)(e)&&!o?.overwriteExisting||(0,c.standingMainAgentName)(e)&&!o?.overwriteExisting)return!1;let n=(await r.agentManager.getAllConfigs()).find(e=>e.name===i);return!!n&&!!isUserSettableMainAgent(n,r.agentManager.getDefaultAgentName())&&(await applyMainAgentToSession(e,n,r),!0)}async function applyMainAgentToSession(e,t,r){let o;(0,c.writeStandingMainAgentKey)(e,t.name),await r.sessionManager.save(e),await applySessionAgentModel(e,t,r);try{o=r.sessionManager.getCurrent?.()}catch{o=void 0}(0,c.mirrorMainAgentOntoLiveSessions)(e,[o,r.sessionManager.sessionSubject?.value])}async function maybeStampConfiguredDefaultOnNewSession(e,t){if(!t.gateEnabled()||!t.optIn())return;let r=e.meta?.[l.MAIN_AGENT_META_KEY];if("string"==typeof r&&r.length>0)return;let o=await (0,l.resolveInheritedMainAgent)(e,Object.assign(Object.create(t.agentManager),{getConfiguredDefaultName:t.getConfiguredDefaultName,getLastUsedName:t.getLastUsedName}),{gateEnabled:!0}),i=t.agentManager.getDefaultAgentName();if(!o?.name||o.name===i)return;let n=(await t.agentManager.getAllConfigs()).find(e=>e.name===o.name);n&&isUserSettableMainAgent(n,i)&&await applyMainAgentToSession(e,n,t)}async function handleSetAgent(e,t){if(!t.gateEnabled()||!t.optIn())throw new MainAgentNotEnabledError;let{sessionId:r,agentName:i}=e;if(!r||!i)throw Error("set_agent requires sessionId and agentName");let n=await t.sessionManager.get(r);if(!n)throw Error(`Session not found: ${r}`);let s=resolveRuntimeSession(r,n,t);if(assertSessionOwnedByConnection(s,t),o.SessionUtils.isSubAgent(s)||o.SessionUtils.isTeamSession(s))throw Error("Main agent cannot be changed on subagent/team/background sessions");if(!await t.agentManager.get(i))throw Error(`Agent not found: ${i}`);let a=await t.agentManager.getAgentConfig(i);if(!a)throw Error(`Agent config not found: ${i}`);if(!isUserSettableMainAgent(a,t.agentManager.getDefaultAgentName()))throw Error(`Agent "${i}" is an internal agent and cannot be a main agent`);if(!(0,c.isSessionBlank)(s))throw Error("agent_switch_locked: session already has history, main agent cannot be changed");await applyMainAgentToSession(s,a,t);try{await t.persistLastUsedName?.(i)}catch(e){t.logger?.warn?.(`[main-agent] persist lastUsed failed: ${e instanceof Error?e.message:String(e)}`)}t.notifyConfigChanged(r,"agent",i);let{models:l,currentModelId:d}=await t.resolveModels(s);return{agentName:i,models:l,currentModelId:d,sessionBlank:(0,c.isSessionBlank)(s)}}async function applySessionAgentModel(e,t,r){let o=t.declaredModel;o&&void 0===r.sessionManager.getOverrideModel(e.id)&&void 0===e.requestOptions.model&&(e.requestOptions.model=o,e.options.model=o,r.sessionManager.setOverrideModel(e.id,o),await r.sessionManager.save(e),await r.reconcileThinking(e),r.logger?.info?.(`[MainAgent] Applied agent default model "${o}" to session ${e.id} (session-scoped, persisted)`))}},48476(e,t,r){r.r(t),r.d(t,{AgentAuthenticationStartupGate:()=>s});var o=r(88523),i=r(86482),n=r(37535);let s=class{async wait(){await (0,n.waitForStartupCredentialProtection)()}};s=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s}([(0,o.Component)(i.AuthenticationStartupGate)],s)},32422(e,t,r){r.r(t),r.d(t,{AgentAuthenticationStartupGate:()=>Y.AgentAuthenticationStartupGate,AuthenticationHttpInterceptor:()=>D,UserinfoProviderImpl:()=>T,getAuthSourceInfo:()=>getAuthSourceInfo,ApplyGroupLinkProvider:()=>z,AuthenticationSessionListener:()=>V,CliCustomTokenAuthenticationStorageImpl:()=>W,ApplyGroupLinkProviderImpl:()=>Q,ExternalAuthenticationProvider:()=>R,AuthenticationType:()=>a,CustomTokenAuthenticationStorage:()=>F,ApiKeyAuthenticationStorageImpl:()=>$,FetchInterceptor:()=>E});var o,i,n,s,a,l,c,d,u,p,g,h,m,f,y,_,w,b,v=r(88523),S=r(86482),A=r(9151),C=r(92735),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let E=class{async initialize(){let e=globalThis.fetch;this.originFetch=e;let fetchLike=async(t,r)=>{r=r||{};let o=await e(t,r);if(401===o.status&&this.matchEndPoint(t)){let e=t.toString();this.logger.warn(`[FetchInterceptor] 401 \u{2192} logout, url: ${e}`),this.authenticationManager.logout()}return o};globalThis.fetch=fetchLike}async onStop(){this.originFetch&&(globalThis.fetch=this.originFetch)}matchEndPoint(e){let t=e.toString(),r=this.productManager.getEndpoint();return t.startsWith(r)}};__decorate([(0,v.Autowired)(S.AuthenticationManager),__metadata("design:type","function"==typeof(o=void 0!==S.AuthenticationManager&&S.AuthenticationManager)?o:Object)],E.prototype,"authenticationManager",void 0),__decorate([(0,v.Autowired)(C.Logger),__metadata("design:type","function"==typeof(i=void 0!==C.Logger&&C.Logger)?i:Object)],E.prototype,"logger",void 0),__decorate([(0,v.Autowired)(A.ProductManager),__metadata("design:type","function"==typeof(n=void 0!==A.ProductManager&&A.ProductManager)?n:Object)],E.prototype,"productManager",void 0),E=__decorate([(0,v.Component)(v.ApplicationLifecycle)],E);var I=r(79814),userinfo_provider_decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s};let T=class{async provide(){let e=this.authenticationManager.currentSessionSubject.getValue();if(e?.account?.uid)return{userId:e?.account.uid??"",userName:e?.account.nickname??"",userNickname:e?.account.nickname??"",enterpriseId:e?.account.enterpriseId,token:e?.auth.accessToken??"",enterprise:e?.account?.departmentFullName}}};userinfo_provider_decorate([(0,v.Autowired)(S.AuthenticationManager),function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type","function"==typeof(s=void 0!==S.AuthenticationManager&&S.AuthenticationManager)?s:Object)],T.prototype,"authenticationManager",void 0),T=userinfo_provider_decorate([(0,v.Component)({id:I.UserinfoProvider,rebind:!0})],T),(a||(a={})).CLI_EXTERNAL_LINK="cli-external-link";var P=r(77379),enviroment_authentication_provider_decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s};let R=class extends S.ExternalLinkAuthenticationProvider{async support(e){let t=this.productManager.getCurrentConfiguration(),r=t?.authentication?.type===a.CLI_EXTERNAL_LINK;return r&&e?.type&&await this.selfProductEnvService.switch(e?.type),r}async decorateAuthUrl(e){await this.selfProductEnvService.getCurrent()===P.ProductEnviroment.IOA&&e.searchParams.set("ioa","1")}};enviroment_authentication_provider_decorate([(0,v.Autowired)(P.ProductEnvService),function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type","function"==typeof(l=void 0!==P.ProductEnvService&&P.ProductEnvService)?l:Object)],R.prototype,"selfProductEnvService",void 0),R=enviroment_authentication_provider_decorate([(0,v.Component)(S.AuthenticationProvider)],R);var k=r(7268),O=r(51147),M=r(83424),authentication_http_interceptor_decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},authentication_http_interceptor_metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let D=class{initialize(){this.restOperations.interceptors.request.use(async e=>{if(e.headers||(e.headers={}),!e.headers[O.API_KEY_HEADER]&&!process.env[M.ENV_KEY_CODEBUDDY_API_KEY_DISABLED]){let t=await this.settingsManager.get("env"),r=t?.[M.ENV_KEY_CODEBUDDY_API_KEY]||process.env[M.ENV_KEY_CODEBUDDY_API_KEY];r&&(e.headers[O.API_KEY_HEADER]=r)}return e})}};authentication_http_interceptor_decorate([(0,v.Autowired)(k.RestOperations),authentication_http_interceptor_metadata("design:type","function"==typeof(c=void 0!==k.RestOperations&&k.RestOperations)?c:Object)],D.prototype,"restOperations",void 0),authentication_http_interceptor_decorate([(0,v.Autowired)(M.SettingsManager),authentication_http_interceptor_metadata("design:type","function"==typeof(d=void 0!==M.SettingsManager&&M.SettingsManager)?d:Object)],D.prototype,"settingsManager",void 0),authentication_http_interceptor_decorate([(0,v.Autowired)(I.Notifier),authentication_http_interceptor_metadata("design:type","function"==typeof(u=void 0!==I.Notifier&&I.Notifier)?u:Object)],D.prototype,"notifier",void 0),authentication_http_interceptor_decorate([(0,v.Autowired)(v.Logger),authentication_http_interceptor_metadata("design:type","function"==typeof(p=void 0!==v.Logger&&v.Logger)?p:Object)],D.prototype,"logger",void 0),D=authentication_http_interceptor_decorate([(0,v.Component)(v.ApplicationLifecycle)],D);var N=r(2721),api_key_authentication_storage_decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},api_key_authentication_storage_metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let $=class{constructor(){this.storeSessionSubject=new N.Subject}async priority(){return await this.getApiKey()?S.AuthenticationStoragePriority.Heigh:S.AuthenticationStoragePriority.Disabled}async getApiKey(){if(process.env[M.ENV_KEY_CODEBUDDY_API_KEY_DISABLED])return;let e=await this.settingsManager.get("env");return e?.[M.ENV_KEY_CODEBUDDY_API_KEY]||process.env[M.ENV_KEY_CODEBUDDY_API_KEY]}async store(e){}async restore(){let e=await this.getApiKey();if(!e)throw Error("apiKey is undefined");let t={auth:{accessToken:e,expiresIn:0x1d1a94a1fff,expiresAt:0x1d1a94a1fff,refreshToken:"",refreshExpiresIn:0x1d1a94a1fff,refreshExpiresAt:0x1d1a94a1fff,tokenType:"ApiKey",scope:""},account:{uid:this.getUserId(e),nickname:this.getUsername(e),type:"personal",lastLogin:!0},accounts:[{uid:this.getUserId(e),nickname:this.getUsername(e),type:"personal",lastLogin:!0}]};return this.storeSessionSubject.next(t),t}async clean(){}getUserId(e){return process.env.ACC_USER_ID??`anonymous_${e.slice(-8)}`}getUsername(e){return process.env.ACC_USER_NICKNAME?process.env.ACC_USER_NICKNAME:`anonymous_${e.slice(-8)}`}};api_key_authentication_storage_decorate([(0,v.Autowired)(A.ProductManager),api_key_authentication_storage_metadata("design:type","function"==typeof(g=void 0!==A.ProductManager&&A.ProductManager)?g:Object)],$.prototype,"productManager",void 0),api_key_authentication_storage_decorate([(0,v.Autowired)(M.SettingsManager),api_key_authentication_storage_metadata("design:type","function"==typeof(h=void 0!==M.SettingsManager&&M.SettingsManager)?h:Object)],$.prototype,"settingsManager",void 0),$=api_key_authentication_storage_decorate([(0,v.Component)(S.AuthenticationStorage)],$);var x=r(73024),j=r(84570),U=r(6529),L=r(88415),custom_token_authentication_storage_decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},custom_token_authentication_storage_metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let F=Symbol("CustomTokenAuthenticationStorage"),B=["ACC_PRODUCT_CONFIG_V3","ACC_PRODUCT_CONFIG_V2"];function cleanBearerToken(e){return e.startsWith("Bearer ")?e.slice(7):e}function getAuthenticationAttributesSync(){let e=process.env[j.ENV_KEY_CODEBUDDY_AUTH_TOKEN];if(e)return{token:cleanBearerToken(e)};for(let e of B){let t=process.env[e];if(t)try{let e=JSON.parse(t);if(e.authentication?.type==="custom-token"&&e.authentication?.attributes?.token){let t=e.authentication.attributes;return{token:cleanBearerToken(t.token),enterpriseId:t.enterpriseId}}}catch{}}if((0,U.hasRegisteredDataFs)())return;for(let e of[j.SettingsScope.USER,j.SettingsScope.PROJECT,j.SettingsScope.PROJECT_LOCAL])if((0,j.isSettingScopeAllowedSync)(e))try{let t=L.PathUtils.getSettingsFilePath(e);if(!(0,x.existsSync)(t))continue;let r=(0,x.readFileSync)(t,"utf-8"),o=JSON.parse(r);if(o.env?.[j.ENV_KEY_CODEBUDDY_AUTH_TOKEN])return{token:cleanBearerToken(o.env[j.ENV_KEY_CODEBUDDY_AUTH_TOKEN])}}catch{continue}let t=process.env.ACC_PRODUCT_CONFIG_PATH;if(t)try{if((0,x.existsSync)(t)){let e=(0,x.readFileSync)(t,"utf-8"),r=JSON.parse(e);if(r.authentication?.type==="custom-token"&&r.authentication?.attributes?.token){let e=r.authentication.attributes;return{token:cleanBearerToken(e.token),enterpriseId:e.enterpriseId}}}}catch{}}function hasCustomTokenIndicatorsSync(){if(process.env[j.ENV_KEY_CODEBUDDY_AUTH_TOKEN])return!0;for(let e of B){let t=process.env[e];if(t)try{let e=JSON.parse(t);if(e.authentication?.type==="custom-token"&&e.authentication?.attributes?.token)return!0}catch{}}if((0,U.hasRegisteredDataFs)())return!1;let e=!!process.env[j.ENV_KEY_CODEBUDDY_API_KEY_HELPER_DISABLED];for(let t of[j.SettingsScope.USER,j.SettingsScope.PROJECT,j.SettingsScope.PROJECT_LOCAL])if((0,j.isSettingScopeAllowedSync)(t))try{let r=L.PathUtils.getSettingsFilePath(t);if(!(0,x.existsSync)(r))continue;let o=(0,x.readFileSync)(r,"utf-8"),i=JSON.parse(o);if(!e&&i.apiKeyHelper||i.env?.[j.ENV_KEY_CODEBUDDY_AUTH_TOKEN])return!0}catch{continue}return!1}async function hasCustomTokenInSpilledProductConfig(){let e=process.env.ACC_PRODUCT_CONFIG_PATH;if(!e)return!1;try{let t=r(91943),o=await t.readFile(e,{encoding:"utf-8"}),i=JSON.parse(o);return i.authentication?.type==="custom-token"&&!!i.authentication?.attributes?.token}catch{return!1}}let W=class extends S.CustomTokenAuthenticationStorageImpl{async priority(){if(!hasCustomTokenIndicatorsSync()&&!await hasCustomTokenInSpilledProductConfig())return S.AuthenticationStoragePriority.Disabled;let e=this.productManager.configuration.getValue();return e?.authentication?.type===A.AuthenticationType.CUSTOM_TOKEN&&e?.authentication?.attributes?.token||getAuthenticationAttributesSync()||await this.apiKeyHelperProductProvider.resolveToken()?S.AuthenticationStoragePriority.Heigh+1:S.AuthenticationStoragePriority.Disabled}async restore(){let e,t,r=getAuthenticationAttributesSync();if(r?(e=r.token,t=r.enterpriseId):(e=await this.apiKeyHelperProductProvider.resolveToken()??void 0,t=this.productManager.configuration.getValue()?.authentication?.attributes?.enterpriseId),!e)return;let o=this.tryExtractUserIDFromJWTToken(e),i=t||o?.enterpriseId,n={uid:o?.userId||this.getUserId(),nickname:o?.nickname||this.getUsername(),enterpriseId:i,type:o?.type||"personal",lastLogin:!0},s={auth:{accessToken:e,expiresIn:0x1d1a94a1fff,expiresAt:0x1d1a94a1fff,refreshToken:"",refreshExpiresIn:0x1d1a94a1fff,refreshExpiresAt:0x1d1a94a1fff,tokenType:"Bearer",scope:"",domain:o?.domain},account:n,accounts:[n]};return await this.productEnvService.switchBySession(s),this.storeSessionSubject.next(s),s}};custom_token_authentication_storage_decorate([(0,v.Autowired)(P.ProductEnvService),custom_token_authentication_storage_metadata("design:type","function"==typeof(m=void 0!==P.ProductEnvService&&P.ProductEnvService)?m:Object)],W.prototype,"productEnvService",void 0),custom_token_authentication_storage_decorate([(0,v.Autowired)(P.ApiKeyHelperProductProvider),custom_token_authentication_storage_metadata("design:type","function"==typeof(f=void 0!==P.ApiKeyHelperProductProvider&&P.ApiKeyHelperProductProvider)?f:Object)],W.prototype,"apiKeyHelperProductProvider",void 0),W=custom_token_authentication_storage_decorate([(0,v.Component)(S.AuthenticationStorage,F)],W);var q=r(34623),H=r(98463),G=r(29513),J=r(20131),K=r(31438),authentication_session_listener_decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s};let V=class{initialize(){this.logger.setContext("AuthenticationSessionListener"),this.startListening()}startListening(){this.subscription=v.ContainerUtil.get(S.AuthenticationManager).currentSessionSubject.pipe((0,q.startWith)(void 0),(0,H.pairwise)(),(0,G.filter)(([e,t])=>this.isAuthenticationSuccess(e,t))).subscribe(async([e,t])=>{try{await this.onAuthenticationSuccess(t)}catch(e){this.logger.error("\u5904\u7406\u8BA4\u8BC1\u6210\u529F\u4E8B\u4EF6\u5931\u8D25:",e)}})}isAuthenticationSuccess(e,t){return!!t&&!!t.auth?.accessToken&&(!(e&&e.auth?.accessToken)||e.auth.accessToken!==t.auth.accessToken)}async onAuthenticationSuccess(e){let t=v.ContainerUtil.get(K.SessionManager).getCurrent(),r=this.buildAuthSuccessMessage(e);this.logger.info("\u8BA4\u8BC1\u6210\u529F,\u6267\u884C Notification \u94A9\u5B50:",r);try{await v.ContainerUtil.get(K.SessionHookManager).executeNotificationHooks(t,r,J.NotificationType.AUTH_SUCCESS)}catch(e){this.logger.warn("\u6267\u884C Notification \u94A9\u5B50\u5931\u8D25:",e)}}buildAuthSuccessMessage(e){let t=e.account?.nickname||"\u672A\u77E5\u7528\u6237",r=e.account?.enterpriseName||"";return r?`auth_success: ${t} (${r})`:`auth_success: ${t}`}dispose(){this.subscription&&(this.subscription.unsubscribe(),this.subscription=void 0),this.logger.debug("AuthenticationSessionListener disposed")}};authentication_session_listener_decorate([(0,v.Autowired)(C.Logger),function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}("design:type","function"==typeof(y=void 0!==C.Logger&&C.Logger)?y:Object)],V.prototype,"logger",void 0),V=authentication_session_listener_decorate([(0,v.Component)(v.ApplicationLifecycle)],V);var Y=r(48476),apply_group_link_provider_decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},apply_group_link_provider_metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let z=Symbol("ApplyGroupLinkProvider"),Q=class{async getApplyUserGroupLink(){try{let e=await this.productManager.waitConfiguration(),t=e?.authentication?.attributes?.platform??e?.platform??"",r=e?.authentication?.attributes?.prefixPath||"",{data:{data:o}}=await this.restOperations.post(`/v2${r}/auth/state?platform=${t}`,{},{headers:{"X-No-Authorization":"true","X-No-User-Id":"true","X-No-Enterprise-Id":"true","X-No-Department-Info":"true"}})||{data:{data:void 0}};if(o?.authUrl){let e=o.authUrl,t=new URL(e);return t.searchParams.set("applyGroup","true"),t.toString()}throw Error("Failed to get apply user group link: authUrl is empty")}catch(e){throw this.logger.error(`Failed to get apply user group link: ${e}`),e}}};async function getAuthSourceInfo(){let e=v.ContainerUtil.get(j.SettingsManager),t=v.ContainerUtil.get(S.AuthenticationManager),r=await e.get("env");if(r?.[j.ENV_KEY_CODEBUDDY_AUTH_TOKEN]||process.env[j.ENV_KEY_CODEBUDDY_AUTH_TOKEN])return{type:"env",source:j.ENV_KEY_CODEBUDDY_AUTH_TOKEN};if(!process.env[j.ENV_KEY_CODEBUDDY_API_KEY_HELPER_DISABLED]){let t=await e.get("apiKeyHelper");if(t&&"string"==typeof t)return{type:"apiKeyHelper",source:t}}if(!process.env[j.ENV_KEY_CODEBUDDY_API_KEY_DISABLED]&&(r?.[j.ENV_KEY_CODEBUDDY_API_KEY]||process.env[j.ENV_KEY_CODEBUDDY_API_KEY]))return{type:"env",source:j.ENV_KEY_CODEBUDDY_API_KEY};let o=t.currentSessionSubject.getValue();return o?.account?.nickname?{type:"login",nickname:o.account.nickname,enterpriseName:o.account.enterpriseName}:{type:"none"}}apply_group_link_provider_decorate([(0,v.Autowired)(k.RestOperations),apply_group_link_provider_metadata("design:type","function"==typeof(_=void 0!==k.RestOperations&&k.RestOperations)?_:Object)],Q.prototype,"restOperations",void 0),apply_group_link_provider_decorate([(0,v.Autowired)(A.ProductManager),apply_group_link_provider_metadata("design:type","function"==typeof(w=void 0!==A.ProductManager&&A.ProductManager)?w:Object)],Q.prototype,"productManager",void 0),apply_group_link_provider_decorate([(0,v.Autowired)(C.Logger),apply_group_link_provider_metadata("design:type","function"==typeof(b=void 0!==C.Logger&&C.Logger)?b:Object)],Q.prototype,"logger",void 0),Q=apply_group_link_provider_decorate([(0,v.Component)(z)],Q)},20995(e,t,r){r.r(t),r.d(t,{CliDispatcherImpl:()=>S,redactEnvValueForLog:()=>redactEnvValueForLog});var o,i,n,s,a,l=r(88523),c=r(91943),d=r(16928),u=r(3768),p=r(6676),g=r(56788),h=r(93912),m=r(95955),f=r(56802),y=r(13945),_=r(16870),w=r(63831),b=r(98577),v=r(37535),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let S=class{constructor(){this.pluginBinPaths=[],this.prewarmArgvRewritten=!1}get startupProfiler(){return l.ContainerUtil.get(y.StartupProfiler)}init(){this.logger.setContext("CliDispatcher")}async onStart(e){if(await (0,v.waitForStartupCredentialProtection)()||this.logger.warn?.("[CredentialProtection] startup bootstrap unavailable; continuing"),(0,h.isLibraryRuntime)()){this.cliRuntimeOptions.set({}),this.logger.info?.(`[LibraryRuntime] library bootstrap pid=${process.pid}, dispatch skipped`),this.startPluginRuntimeRefresh("startup");return}this.startupProfiler.markStart(y.StartupPhase.CLI_PARSE,"CLI Parse");let t=await this.cliProvider.get(),{debug:r,print:o}=t.opts();this.startupProfiler.markEnd(y.StartupPhase.CLI_PARSE);let i=process.env.CLIENT_INFO_PRODUCT_VERSION||"unknown";this.logger.info?.(`[ColdStart] cli onStart pid=${process.pid} version=${i}`);let n=o||!process.stdout.isTTY,s=t.opts();if(this.cliRuntimeOptions.set({...s,print:n}),await this.applyPluginDirectoryEnvironment(s),this.consoleManager.interceptGlobalConsole({isDebug:r,isPrint:n}),this.isPrewarmRequested(s))return void await this.runPrewarmStandby(s);let a=t.args[0];"string"==typeof a&&t.commands.some(e=>e.name()===a||e.aliases().includes(a))||this.startPluginRuntimeRefresh("startup"),await this.dispatch()}isPrewarmRequested(e){return!0===e.prewarm}isPrewarmForceRequested(e){return!0===e.prewarmForce}async applyPluginDirectoryEnvironment(e){if(!e.pluginDir)return;let t=(Array.isArray(e.pluginDir)?e.pluginDir:[e.pluginDir]).map(e=>String(e));process.env.CODEBUDDY_PLUGIN_DIRS=t.join(d.delimiter);let r=(await Promise.all(t.map(async e=>{let t=d.resolve(e,"bin"),r=await c.stat(t).catch(()=>void 0);return r?.isDirectory()?t:void 0}))).filter(e=>!!e),o=(process.env.PATH||"").split(d.delimiter).filter(Boolean),i=new Set(this.pluginBinPaths??[]);if(0===r.length&&0===i.size)return;let n=new Set(r);this.pluginBinPaths=r,process.env.PATH=[...r,...o.filter(e=>!n.has(e)&&!i.has(e))].join(d.delimiter)}startPluginRuntimeRefresh(e){try{l.ContainerUtil.get(m.PluginRuntimeRefreshService).refresh(e).catch(t=>{this.logger?.warn?.(`[PluginRuntime] ${e} activation degraded: ${t instanceof Error?t.message:String(t)}`)})}catch(t){this.logger?.warn?.(`[PluginRuntime] ${e} activation degraded: ${t instanceof Error?t.message:String(t)}`)}}async runPrewarmStandby(e){let t,r=l.ContainerUtil.get(f.PrewarmServer),o=String(e.prewarmId??process.pid),i=this.isPrewarmForceRequested(e);this.logger.info?.(`[Prewarm] prewarm standby pid=${process.pid} prewarmId=${o} force=${i}`),i&&await this.evictExistingPrewarm(o);try{t=await r.listen(o,{force:i})}catch(e){throw e instanceof f.PrewarmIdInUseError&&(this.logger.error?.(`[Prewarm] prewarm id "${o}" \u{5DF2}\u{88AB}\u{6D3B}\u{8FDB}\u{7A0B}\u{5360}\u{7528}\u{FF08}${e.socketPath}\u{FF09}\u{3002}\u{5982}\u{9700}\u{63A5}\u{7BA1}\u{8BF7}\u{52A0} --prewarm-force\u{FF0C}\u{6216}\u{6362}\u{4E00}\u{4E2A} --prewarm-id\u{3002}`),process.stderr.write(`[Prewarm] prewarm id "${o}" \u{5DF2}\u{88AB}\u{6D3B}\u{8FDB}\u{7A0B}\u{5360}\u{7528}\u{FF08}${e.socketPath}\u{FF09}\u{3002}\u{5982}\u{9700}\u{63A5}\u{7BA1}\u{8BF7}\u{52A0} --prewarm-force\u{FF0C}\u{6216}\u{6362}\u{4E00}\u{4E2A} --prewarm-id\u{3002}
|
|
29
29
|
`),process.exit(1)),e}this.logger.info?.(`[Prewarm] standby ready, IPC at ${t}`),await this.registerPrewarmEntry(o,t);let cleanup=()=>{r.close().catch(()=>{})};process.once("SIGINT",()=>{cleanup(),process.exit(0)}),process.once("SIGTERM",()=>{cleanup(),process.exit(0)});let n=await r.waitForActivation();(0,v.configurePrewarmCredentialProtection)(n.credentialProtectionBootstrap)||this.logger.warn?.("[CredentialProtection] prewarm bootstrap unavailable; continuing"),delete n.credentialProtectionBootstrap;let s=process.cwd(),a=n.cwd;if(this.logger.info?.(`[Prewarm] activated pid=${process.pid} version=${process.env.CLIENT_INFO_PRODUCT_VERSION||"unknown"} \u{2192} prevCwd=${s}, cwd=${a??"(unchanged)"}, cwdChanged=${!!a&&a!==s}, args=${JSON.stringify(n.args??[])}`),await this.unregisterPrewarmEntry(),"ready"!==n.ackMode&&r.close().catch(()=>{}),n.cwd)try{process.chdir(n.cwd)}catch(e){throw this.logger.error?.(`[Prewarm] chdir to "${n.cwd}" failed: ${String(e)}`),e}if(n.env&&Object.keys(n.env).length>0){let e=Object.keys(n.env);for(let[e,t]of Object.entries(n.env))process.env[e]=t;for(let[t,r]of(this.logger.info?.(`[Prewarm] env merged on activate, keys=[${e.join(", ")}]`),Object.entries(n.env)))this.logger.info?.(`[Prewarm] ${t}=${redactEnvValueForLog(t,r)}`)}await this.applyPrewarmArgs(n);try{let e=l.ContainerUtil.get(f.PrewarmActivationCoordinator);await e.fireActivation(n)}catch(e){throw this.logger.error?.(`[Prewarm] activation coordinator failed: ${String(e)}`),await r.close().catch(()=>{}),e}r.markActivatePhase("dispatch"),await this.dispatch()}async evictExistingPrewarm(e){try{let t=l.ContainerUtil.get(g.SessionRegistry),r=l.ContainerUtil.get(g.DaemonProcessManager);for(let o of(await t.list({kind:"prewarm"})).filter(t=>t.meta?.prewarmId===e&&!t.manual&&t.pid>0&&t.pid!==process.pid))this.logger.warn?.(`[Prewarm] force: terminating stale prewarm pid=${o.pid} (id=${e})`),r.sendSignal(o.pid,"SIGTERM"),await r.waitForExit(o.pid,3e3)||(r.sendSignal(o.pid,"SIGKILL"),await r.waitForExit(o.pid,2e3))}catch(e){this.logger.warn?.(`[Prewarm] force eviction failed: ${String(e)}`)}}async registerPrewarmEntry(e,t){try{let r=l.ContainerUtil.get(g.SessionRegistry);await r.register({sessionId:`prewarm-${e}`,cwd:process.cwd(),startedAt:Date.now(),kind:"prewarm",meta:{prewarmId:e,socketPath:t,status:"idle"}})}catch(e){this.logger.warn?.(`[Prewarm] registry register failed: ${String(e)}`)}}async unregisterPrewarmEntry(){try{let e=l.ContainerUtil.get(g.SessionRegistry);await e.unregister()}catch(e){this.logger.warn?.(`[Prewarm] registry unregister failed: ${String(e)}`)}}stripPrewarmFlags(e){let t=new Set(["--prewarm-id"]),r=new Set(["--prewarm","--prewarm-force"]),o=[];for(let i=0;i<e.length;i++){let n=e[i];if(r.has(n))continue;let s=n.indexOf("="),a=s>=0?n.slice(0,s):n;if(t.has(a)){s<0&&i+1<e.length&&!e[i+1].startsWith("-")&&i++;continue}o.push(n)}return o}rewritePrewarmArgv(e){if(this.prewarmArgvRewritten)return;this.prewarmArgvRewritten=!0;let t=e.args??[],r=this.stripPrewarmFlags(process.argv.slice(2)),o=[...process.argv];process.argv=[process.argv[0],process.argv[1],...r,...t],this.logger.info?.(`[Prewarm] rewritePrewarmArgv: argvBefore=${JSON.stringify(o)} coldStartRest=${JSON.stringify(r)} activationArgs=${summarizeArgs(t)} argvAfter=${JSON.stringify(process.argv)}`)}async applyPrewarmArgs(e){try{this.rewritePrewarmArgv(e);let t=(await this.cliProvider.get()).opts();e.sessionId&&(t.sessionId=e.sessionId),this.cliRuntimeOptions.set({...t,print:!0===t.print||!process.stdout.isTTY}),await this.applyPluginDirectoryEnvironment(t),this.logger.info?.(`[Prewarm] applyPrewarmArgs parsed opts: sessionId=${t.sessionId??"N/A"} serve=${t.serve??!1} permissionMode=${t.permissionMode??"N/A"} model=${t.model??"N/A"} agent=${t.agent??"N/A"} systemPromptFile=${t.systemPromptFile??"N/A"} mcpConfig=${t.mcpConfig??"N/A"} strictMcpConfig=${t.strictMcpConfig??!1} settingsLen=${"string"==typeof t.settings?t.settings.length:"N/A"} allowedTools=${JSON.stringify(t.allowedTools??"N/A")} port=${t.port??"N/A"}`)}catch(e){this.logger.warn?.(`[Prewarm] applyPrewarmArgs failed: ${String(e)}`)}}async dispatch(){let e=await this.cliProvider.get(),t=e.opts();this.logger.info?.(`[Dispatch] entry opts: sessionId=${t.sessionId??"N/A"} serve=${t.serve??!1} acp=${t.acp??!1} permissionMode=${t.permissionMode??"N/A"} model=${t.model??"N/A"} agent=${t.agent??"N/A"} systemPromptFile=${t.systemPromptFile??"N/A"} mcpConfig=${t.mcpConfig??"N/A"} strictMcpConfig=${t.strictMcpConfig??!1} settingsLen=${"string"==typeof t.settings?t.settings.length:"N/A"} allowedTools=${JSON.stringify(t.allowedTools??"N/A")} port=${t.port??"N/A"} argv=${JSON.stringify(process.argv)}`);let r="stream-json"===t.inputFormat||t.acp||t.a2a,o="";r||(this.startupProfiler.markStart(y.StartupPhase.STDIN_READ,"Stdin Read"),o=await this.readAllStdin(e.commands.map(e=>e.name())),this.startupProfiler.markEnd(y.StartupPhase.STDIN_READ));let i={cli:e,pipeInput:o},n=process.argv[2];if(!g.SHORT_LIVED_COMMANDS.includes(n)&&!(0,u.isJobBrokerProcess)())try{let e,r=l.ContainerUtil.get(g.SessionRegistry),o=process.env[g.ENV_SESSION_KIND]||"interactive",i=(0,u.getJobId)();if("daemon"===o)try{e=l.ContainerUtil.get(g.DaemonProcessManager).getInheritableArgs()}catch{}await r.register({sessionId:(0,u.registrySessionIdFromCliOpts)(t,`${o}-${process.pid}`),cwd:process.cwd(),startedAt:Date.now(),kind:o,name:process.env[g.ENV_SESSION_NAME],logPath:process.env[g.ENV_SESSION_LOG],...e?{startupArgs:e}:{},...i?{meta:{jobId:i}}:{}})}catch{}await this.dispatchChain.execute(i)}async readAllStdin(e){if(process.stdin.isTTY)return this.logger.info("stdin is TTY, skipping stdin read"),"";let t=process.argv.slice(2).find(e=>!e.startsWith("-"));if(t&&e.includes(t))return this.logger.info(`stdin skipped: sub-command '${t}' does not need stdin`),"";this.logger.info("stdin is not TTY, reading stdin until EOF...");let r=[];process.stdin.setEncoding("utf8");let o=!1,i=!1,createTimeout=e=>setTimeout(()=>{i=!0,this.logger.warn(`stdin read timeout after ${e}ms (received data: ${o}), proceeding`),process.stdin.destroy()},e),n=createTimeout(500);try{for await(let e of process.stdin){if(i)break;o||(o=!0,clearTimeout(n),n=createTimeout(5e3)),r.push(e)}}catch{i||this.logger.warn("stdin read error (non-timeout)")}finally{clearTimeout(n)}return this.logger.info("finished reading stdin"),r.join("").trim()}};function summarizeArgs(e){let t=new Set(["--system-prompt","--append-system-prompt","--settings"]),r=[];for(let o=0;o<e.length;o++){let i=e[o];if(!i.startsWith("-")){r.push(`<positional:${i}>`);continue}let n=e[o+1];if(void 0===n||n.startsWith("-")){r.push(i);continue}t.has(i)?r.push(`${i}=<len=${n.length}>`):r.push(`${i}=${n}`),o++}return r.join(" ")}__decorate([(0,l.Autowired)(_.CliProvider),__metadata("design:type","function"==typeof(o=void 0!==_.CliProvider&&_.CliProvider)?o:Object)],S.prototype,"cliProvider",void 0),__decorate([(0,l.Autowired)(w.CliRuntimeOptions),__metadata("design:type","function"==typeof(i=void 0!==w.CliRuntimeOptions&&w.CliRuntimeOptions)?i:Object)],S.prototype,"cliRuntimeOptions",void 0),__decorate([(0,l.Autowired)(p.ConsoleManager),__metadata("design:type","function"==typeof(n=void 0!==p.ConsoleManager&&p.ConsoleManager)?n:Object)],S.prototype,"consoleManager",void 0),__decorate([(0,l.Autowired)(b.DispatchChain),__metadata("design:type","function"==typeof(s=void 0!==b.DispatchChain&&b.DispatchChain)?s:Object)],S.prototype,"dispatchChain",void 0),__decorate([(0,l.Autowired)(l.Logger),__metadata("design:type","function"==typeof(a=void 0!==l.Logger&&l.Logger)?a:Object)],S.prototype,"logger",void 0),__decorate([(0,l.PostConstruct)(),__metadata("design:type",Function),__metadata("design:paramtypes",[]),__metadata("design:returntype",void 0)],S.prototype,"init",null),S=__decorate([(0,l.Component)(_.CliDispatcher,l.ApplicationLifecycle)],S);let A=["_TOKEN","_API_KEY","_ACCESS_TOKEN","_SECRET","_KEY","_PASS","_PASSWORD"],C=new Set(["OPENAI_API_KEY","ANTHROPIC_API_KEY","CODEBUDDY_API_KEY","CODEBUDDY_SANDBOX_WEBHOOK_SECRET"]),E=new Set(["token","accessToken","apiKey","api_key","password","secret","Authorization","authorization"]);function isSensitiveEnvKey(e){let t=e.toUpperCase();if(C.has(t))return!0;for(let e of A)if(t.endsWith(e))return!0;return!1}function redactJsonSensitiveFields(e){if(Array.isArray(e))return e.map(redactJsonSensitiveFields);if(e&&"object"==typeof e){let t={};for(let[r,o]of Object.entries(e))E.has(r)?t[r]="string"==typeof o?`<redacted:${o.length}b>`:"<redacted>":t[r]=redactJsonSensitiveFields(o);return t}return e}function redactEnvValueForLog(e,t){if(isSensitiveEnvKey(e))return`<redacted:${t.length}b>`;let r=t.trim();if(r.startsWith("{")||r.startsWith("["))try{let e=JSON.parse(r);return JSON.stringify(redactJsonSensitiveFields(e))}catch{}return t}},79163(e,t,r){r.r(t),r.d(t,{CliExecutor:()=>$});var o,i,n,s,a,l,c,d,u=r(6757),p=r(88523),g=r(7268),h=r(92735),m=r(23785),f=r(75505),y=r(4324),_=r(10618),w=r(6676),b=r(82228),v=r(10282),S=r(43889),A=r(69866),C=r(92606),E=r(90666),I=r(86045),T=r(87933),P=r(13945),R=r(51147),k=r(91943),O=r(16928),M=r(88415);function isStdioPersistenceEnabled(){return R.BooleanUtils.isTruthy(process.env.CODEBUDDY_CODE_PERSIST_STDIO)}function resolveStdioDir(e,t){let r=process.env.CODEBUDDY_CODE_PERSIST_STDIO_DIR,o=r&&r.trim().length>0?r:M.PathUtils.getHomeProjectsDir();return(0,O.join)(o,t,e,"stdio")}function newRunStamp(){let e=new Date().toISOString().replace(/[:.]/g,"-");return`${e}-${process.pid}`}let FileChannel=class FileChannel{constructor(e){this.filePath=e,this._failedWrites=0,this.pending=Promise.resolve(),this.loggedFailures=0;const t=(0,O.join)(e,"..");this.dirReady=(0,k.mkdir)(t,{recursive:!0}).then(()=>{}).catch(()=>{})}get failedWrites(){return this._failedWrites}append(e,t){let r,o={t:new Date().toISOString(),dir:e,message:t};try{r=JSON.stringify(o)+"\n"}catch(e){this.reportFailure(e,"serialize");return}this.pending=this.pending.then(async()=>{try{await this.dirReady,await (0,k.appendFile)(this.filePath,r,"utf-8")}catch(e){this._failedWrites++,this.reportFailure(e,"write")}})}async flush(){try{await this.pending}catch{}}reportFailure(e,t){if(this.loggedFailures++,1===this.loggedFailures||this.loggedFailures%100==0)try{let{DebugLogger:o}=r(45380);o.error("StdioPersistence",`${t} failure #${this.loggedFailures} (failedWrites=${this._failedWrites})`,e).catch(()=>{})}catch{}}};function openStreamJsonChannel(e,t){let r=t??M.PathUtils.getCompressedWorkDir(),o=`${newRunStamp()}.jsonl`;return new FileChannel((0,O.join)(resolveStdioDir(e,r),o))}let StreamUtils=class StreamUtils{static isStream(e){return!!(e&&"function"==typeof e.pipe)}static async readStreamToString(e,t=65536){return await new Promise(r=>{let o=[],i=0,onData=e=>{let r=Buffer.isBuffer(e)?e:Buffer.from(e);if(i>=t)return;let n=t-i;o.push(r.length>n?r.subarray(0,n):r),i+=Math.min(r.length,n)},onEnd=()=>{cleanup(),r(Buffer.concat(o).toString("utf8"))},onError=()=>{cleanup(),r(Buffer.concat(o).toString("utf8"))},cleanup=()=>{e.off("data",onData),e.off("end",onEnd),e.off("error",onError)};e.on("data",onData),e.on("end",onEnd),e.on("error",onError)})}};var D=r(82136),N=r(49205),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};function renderMcpFirstRunStatusEventToNdjson(e){let t=(0,p.generateUUUID)(),r=new Date().toISOString();return"start"===e.kind?{type:"system",subtype:"mcp_status",event:"start",servers:[...e.servers],total_count:e.totalCount,uuid:t,__timestamp:r}:"server"===e.kind?{type:"system",subtype:"mcp_status",event:"server",name:e.name,state:e.state,error:e.error,completed:e.completed,total:e.total,uuid:t,__timestamp:r}:{type:"system",subtype:"mcp_status",event:"finish",failed:[...e.failed],timed_out:[...e.timedOut],uuid:t,__timestamp:r}}let $=class{get startupProfiler(){return p.ContainerUtil.get(P.StartupProfiler)}async ensureTraceChannelReady(){if(!process.env.DISABLE_TELEMETRY&&!process.env.DISABLE_GALILEO&&"false"!==process.env.GALILEO_ENABLE&&"1"!==process.env.GALILEO_SDK_READY)try{let e=p.ContainerUtil.get(A.GalileoService);await e.waitForReady(1e4)||"true"!==process.env.GALILEO_ENABLE||("0"===process.env.GALILEO_SDK_READY?this.logger.warn("[CliExecutor] galileo trace channel init failed; interaction spans may be lost"):this.logger.warn("[CliExecutor] galileo trace channel not ready after 10000ms; interaction spans may be lost"))}catch{}}async execute(e){this.restOperations=this.restOperationsFactory.create();let{cli:t,endpointProvider:r,path:o,baseBody:i,inputFormat:n,outputFormat:s}=e;this.logger.info("[Startup] CliExecutor: waiting for endpoint...");let a=await r.get();this.logger.info(`[Startup] CliExecutor: endpoint ready: ${a}`),await this.ensureTraceChannelReady(),this.startupProfiler.markEnd(P.StartupPhase.READY);let l=t.opts().print||!0===i.json||!process.stdout.isTTY,c=t.opts();if(c.resumeSessionAt&&!c.resume&&!c.continue)return process.stderr.write("Error: --resume-session-at requires --resume\n"),this.finalizeAndExit(1);if(c.rewindFiles&&!c.resume&&!c.continue)return process.stderr.write("Error: --rewind-files requires --resume\n"),this.finalizeAndExit(1);if(c.rewindFiles&&this.hasPromptArgument(t,i))return process.stderr.write("Error: --rewind-files is a standalone operation and cannot be used with a prompt\n"),this.finalizeAndExit(1);if(c.rewindFiles){let e=await this.rewindFilesRunner.runOneShot({userMessageId:String(c.rewindFiles),resume:c.resume,continue:c.continue,dryRun:!!c.dryRun});return e.canRewind?(process.stdout.write(`Files rewound to state at message ${String(c.rewindFiles)}
|
|
30
30
|
`),this.finalizeAndExit(0)):(process.stderr.write(`Error: ${e.error??"Unexpected error"}
|
|
31
|
-
`),this.finalizeAndExit(1))}c.resumeSessionAt&&(i.resumeSessionAt=String(c.resumeSessionAt)),"stream-json"===n?await this.executeStreamMode(a,o,i,s,!!c.a2a):await this.executeSingleRequest(a,o,i,s,l),await this.finalizeAndExit(0)}async finalizeAndExit(e){this.startupProfiler.isEnabled()&&this.consoleManager.debug(this.startupProfiler.formatReport({showAll:!0,threshold:0}),{mode:w.ConsoleOutputMode.NATIVE});try{let e=await this.stdoutWriter.flushOrStall(5e3);e.complete||this.logger.warn(`[CliExecutor] stdout flush stalled for 5000ms with no progress \u{2014} exiting with ~${e.remainingBytes} bytes undelivered (failedWrites=${this.stdoutWriter.failedWrites})`)}catch{}await this.stdoutWriter.flushPersistChannel(),this.loggerStorageService.flushSync();try{let e=p.ContainerUtil.get(_.AgentTaskManager);await e.waitForRunningTasks()}catch{}try{await new Promise(e=>setImmediate(e)),await (0,S.shutdownTelemetryBeforeExit)(2e3)}catch{}process.exit(+(0!==e))}hasPromptArgument(e,t){let r=Array.isArray(e.args)&&e.args.length>0?String(e.args[0]??""):"",o="string"==typeof t.prompt?t.prompt:"";return r.trim().length>0||o.trim().length>0}async executeSingleRequest(e,t,r,o,i){try{let n={...r,print:!0,...this.directDeliveryFields(t,o)};this.startupProfiler.markStart("http_request","HTTP Request (total)"),await this.sendRequest(e,t,n,o,i),this.startupProfiler.markEnd("http_request")}catch(e){this.startupProfiler.markEnd("http_request"),await this.writeError(e,o)}}directDeliveryFields(e,t){return"stream-json"===t&&e.includes("internal/agent")?{directDelivery:!0,deliveryId:(0,p.generateUUUID)()}:{}}extractTelemetryClientInfo(e){if(!e||"object"!=typeof e)return;let t=e[T.TELEMETRY_CLIENT_INFO_META_KEY];if(t&&"object"==typeof t)return t;let r=e._meta?.["codebuddy.ai"],o=r?.[T.TELEMETRY_CLIENT_INFO_META_KEY];return o&&"object"==typeof o?o:void 0}async executeStreamMode(e,t,r,o,i=!1){let n,s,a,l=new p.Deferred,c=!1;"stream-json"===o&&this.mcpFirstRunStatusService&&(s=this.mcpFirstRunStatusService.events$.subscribe(e=>{try{this.stdoutWriter.write(renderMcpFirstRunStatusEventToNdjson(e))}catch(e){this.logger?.warn?.(`[CliExecutor] mcp_status ndjson write failed: ${e instanceof Error?e.message:String(e)}`)}if("finish"===e.kind){try{s?.unsubscribe()}catch{}s=void 0}}));let d=isStdioPersistenceEnabled(),g=null,h=[];d&&this.stdoutWriter.armPersistPrebuffer();let _=[],activatePersistChannel=e=>{if(d&&!g){for(let t of(g=openStreamJsonChannel(e),h))g.append("in",t);h.length=0,this.stdoutWriter.attachPersistChannel(g,_),_.length=0}},w=!1,v=new p.Deferred,S=new Set,A=new AbortController,C=!1,startDrainWaitLoop=i=>{C||"stream-json"!==o||(C=!0,track((async()=>{for(;!A.signal.aborted&&!c;){let n=Date.now();try{await this.sendRequest(e,t,{...r,print:!0,drainWait:!0,sessionId:i},o,!0,A.signal)}catch(e){if(A.signal.aborted)return}let s=Date.now()-n;!(s<500)||A.signal.aborted||c||await new Promise(e=>setTimeout(e,500-s))}})()))},I=Promise.resolve(),getA2aDispatcher=()=>{if(i){if(!a)try{let e=p.ContainerUtil.get(f.A2aAgentExecutor);a=new y.A2aLineDispatcher(e,this.logger,{boundSessionId:()=>n})}catch(e){this.logger?.error?.(`[CliExecutor] --a2a set but A2A executor is unavailable: ${e instanceof Error?e.message:String(e)}`)}return a}},T=(0,m.createInterface)({input:process.stdin,crlfDelay:1/0}),processLine=async i=>{if(!i.trim())return;let s=Date.now();try{let a;try{a=JSON.parse(i)}catch{a={type:"user",content:i}}if((e=>{if(d){if(g)return g.append("in",e);h.length<4096&&h.push(e)}})(a),(0,y.isA2aJsonRpcLine)(a)){let e=getA2aDispatcher();if(!e)return void this.stdoutWriter.write({jsonrpc:"2.0",id:a?.id??null,error:{code:u.A2A_ERROR_CODE.METHOD_NOT_FOUND,message:"A2A is not enabled on this process (add --a2a)"}});let t=await e.dispatch(i);this.stdoutWriter.write(t);return}if((0,b.isControlSignalMessage)(a)){let e=a;if("control_request"===e.type){let t=e.request;if(t?.subtype==="initialize"&&!w){w=!0,I=this.controlSignalHandler.handleMessage(e).catch(e=>{this.writeError(e,o)}),await I,v.resolve({hasPrompt:t.hasPrompt});return}}this.controlSignalHandler.handleMessage(e).catch(e=>{this.writeError(e,o)});return}await I,w||(w=!0,v.resolve({hasPrompt:!0}));let l=a&&"object"==typeof a?a:void 0,c=l?.trace_id,p=l?.parent_span_id,m=this.extractTelemetryClientInfo(a),f={...r,print:!0,prompt:i,...this.directDeliveryFields(t,o),...n?{sessionId:n}:{},...c?{traceId:c}:{},...p?{parentSpanId:p}:{},...l?._meta?{_meta:l._meta}:{},...m?{telemetryClientInfo:m}:{},stdinReceivedAt:s},_=await this.sendRequest(e,t,f,o);_.sessionId&&(n=_.sessionId,startDrainWaitLoop(n),activatePersistChannel(n))}catch(e){await this.writeError(e,o)}},track=e=>{let t=e.finally(()=>{S.delete(t)});S.add(t)};if(T.on("line",e=>{track(processLine(e))}),T.on("close",()=>{c=!0,A.abort(),w||v.resolve({hasPrompt:!1});try{p.ContainerUtil.get(b.SdkPermissionClient).cancelAllPending("SDK disconnected")}catch{}try{p.ContainerUtil.get(E.SdkMcpMessageClient).cancelAllPending("SDK disconnected")}catch{}try{p.ContainerUtil.get(b.SdkElicitationClient).cancelAllPending("SDK disconnected")}catch{}l.resolve()}),T.on("error",()=>{c=!0,A.abort(),w||v.resolve({hasPrompt:!1}),l.resolve()}),r.resume){let{hasPrompt:i}=await v.promise;if(i)this.logger.info("[ResumeReplay] skipped (hasPrompt=true, SDK will send a prompt)");else{let i=Date.now();this.logger.info(`[ResumeReplay] start history replay for resume=${String(r.resume)}`);try{let s={...r,print:!0,...this.directDeliveryFields(t,o)},a=await this.sendRequest(e,t,s,o);a.sessionId&&(n=a.sessionId,activatePersistChannel(n)),this.logger.info(`[ResumeReplay] history replay completed in ${Date.now()-i}ms (sessionId=${n??"unknown"})`)}catch(e){this.logger.warn(`[ResumeReplay] history replay failed after ${Date.now()-i}ms: ${e instanceof Error?e.message:String(e)}`),await this.writeError(e,o)}}}for(await l.promise;S.size>0;)await Promise.all([...S]);try{s?.unsubscribe()}catch{}}async sendRequest(e,t,r,o,i=!0,n){let s=`${e}${t}`,a="stream-json"===o;if(a&&!0===r.directDelivery&&"string"==typeof r.deliveryId)return await this.sendDirectDeliveryRequest(s,r,r.deliveryId);let l=await this.restOperations.post(s,r,{headers:(0,I.withSecurityHeader)({[g.HttpHeaders.CONTENT_TYPE]:g.MediaType.APPLICATION_JSON_UTF8,...a?{[g.HttpHeaders.ACCEPT]:"text/event-stream"}:{}}),proxy:!1,responseType:a?"stream":void 0,...n?{signal:n}:{}});if(l.data){let e=l.headers["content-type"]||"",t=StreamUtils.isStream(l.data);if(e.includes("text/event-stream")||t)return await this.handleStreamResponse(l.data);if("object"==typeof l.data){if(i)if("stream-json"===o)process.stdout.write(JSON.stringify(l.data)+"\n");else{let e=l.data.text||l.data.message||JSON.stringify(l.data,null,2);process.stdout.write(e+"\n")}return{sessionId:l.data.sessionId}}i&&process.stdout.write(String(l.data)+"\n")}return{}}async sendDirectDeliveryRequest(e,t,r){this.deliveryLifecycle.begin(r);let o=this.restOperations.post(e,t,{headers:(0,I.withSecurityHeader)({[g.HttpHeaders.CONTENT_TYPE]:g.MediaType.APPLICATION_JSON_UTF8}),proxy:!1}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),i=await Promise.race([this.deliveryLifecycle.wait(r).then(e=>({kind:"delivered",info:e})),o.then(e=>({kind:"post",post:e}))]);if("delivered"===i.kind)return{sessionId:i.info.sessionId};let n=i.post.ok?2e3:100,s=await new Promise(e=>{let t=setTimeout(()=>e(void 0),n);t.unref?.(),this.deliveryLifecycle.wait(r).then(r=>{clearTimeout(t),e(r)}).catch(()=>{clearTimeout(t),e(void 0)})});if(this.deliveryLifecycle.abandon(r),s&&!s.error)return{sessionId:s.sessionId};if(!i.post.ok)throw i.post.error;let a=i.post.result?.data;return this.logger.warn(`[CliExecutor] direct delivery ${r} completed without view settle (post ok); sessionId=${a?.sessionId??"n/a"}`),{sessionId:a?.sessionId}}async handleStreamResponse(e){let t,r=new p.Deferred,o="";return e.on("data",e=>{try{let r=e.toString(),i=(o+=r).split("\n");for(let e of(o=i.pop()||"",i))if(e.trim())try{let r=JSON.parse(e);if(0===Object.keys(r).length)continue;this.stdoutWriter.writeLine(e),"system"===r.type&&"init"===r.subtype&&r.session_id&&(t=r.session_id)}catch{if(e.startsWith("data:")){let r=e.substring(5).trim();try{let e=JSON.parse(r);if(0===Object.keys(e).length)continue;this.stdoutWriter.writeLine(r),"system"===e.type&&"init"===e.subtype&&e.session_id&&(t=e.session_id)}catch{this.stdoutWriter.writeLine(r)}}}}catch(e){this.logger.warn(`[CliExecutor] stream data handler error (line dropped, stream kept alive): ${e instanceof Error?e.message:String(e)}`)}}),e.on("end",()=>r.resolve({sessionId:t})),e.on("error",()=>r.resolve({sessionId:t})),r.promise}async extractMessageFromData(e){if(StreamUtils.isStream(e))return await StreamUtils.readStreamToString(e);if("string"==typeof e)return e;if(Buffer.isBuffer(e))return e.toString("utf8");if("object"==typeof e){let t=e.text??e.message??e.error;if("string"==typeof t)return t;try{return JSON.stringify(e)}catch{}}}async writeError(e,t){let r;e?.isAxiosError&&e?.response&&(r=await this.extractMessageFromData(e.response.data)),r||(r=e instanceof Error?e.message:String(e)),"stream-json"===t?this.stdoutWriter.write({type:"error",error:r}):process.stderr.write(r+"\n")}};__decorate([(0,p.Autowired)(g.RestOperationsFactory),__metadata("design:type","function"==typeof(o=void 0!==g.RestOperationsFactory&&g.RestOperationsFactory)?o:Object)],$.prototype,"restOperationsFactory",void 0),__decorate([(0,p.Autowired)(h.LoggerStorageService),__metadata("design:type","function"==typeof(i=void 0!==h.LoggerStorageService&&h.LoggerStorageService)?i:Object)],$.prototype,"loggerStorageService",void 0),__decorate([(0,p.Autowired)(b.ControlSignalHandler),__metadata("design:type","function"==typeof(n=void 0!==b.ControlSignalHandler&&b.ControlSignalHandler)?n:Object)],$.prototype,"controlSignalHandler",void 0),__decorate([(0,p.Autowired)(w.ConsoleManager),__metadata("design:type","function"==typeof(s=void 0!==w.ConsoleManager&&w.ConsoleManager)?s:Object)],$.prototype,"consoleManager",void 0),__decorate([(0,p.Autowired)(h.Logger),__metadata("design:type","function"==typeof(a=void 0!==h.Logger&&h.Logger)?a:Object)],$.prototype,"logger",void 0),__decorate([(0,p.Autowired)(v.StdoutWriter),__metadata("design:type","function"==typeof(l=void 0!==v.StdoutWriter&&v.StdoutWriter)?l:Object)],$.prototype,"stdoutWriter",void 0),__decorate([(0,p.Autowired)(C.McpFirstRunStatusService),(0,p.Optional)(),__metadata("design:type",Object)],$.prototype,"mcpFirstRunStatusService",void 0),__decorate([(0,p.Autowired)(D.PrintDeliveryLifecycle),__metadata("design:type","function"==typeof(c=void 0!==D.PrintDeliveryLifecycle&&D.PrintDeliveryLifecycle)?c:Object)],$.prototype,"deliveryLifecycle",void 0),__decorate([(0,p.Autowired)(N.RewindFilesRunner),__metadata("design:type","function"==typeof(d=void 0!==N.RewindFilesRunner&&N.RewindFilesRunner)?d:Object)],$.prototype,"rewindFilesRunner",void 0),$=__decorate([(0,p.Component)()],$)},45443(e,t,r){r.r(t),r.d(t,{CliProviderImpl:()=>y});var o=r(88523),i=r(75348),n=r(79127),s=r(48400),a=r(16870);let l=s.PackageUtils.getCurrentPackageJson(),c=new i.Command;c.name("codebuddy").alias("cbc").version(l.version).description("CodeBuddy Code - starts an interactive session by default, use -p/--print for non-interactive output").argument("[prompt]","Your prompt").option("-d, --debug [filter]",'Enable debug mode with optional category filtering (e.g., "api,hooks" or "!statsig,!file")',e=>{try{let t=JSON.parse(e);if("string"==typeof t)return t;throw Error("Not a string")}catch(t){return e}},!1).addOption(new i.Option("-d2e, --debug-to-stderr","Enable debug mode (to stderr)").default(!1).hideHelp()).option("--verbose","Override verbose mode setting from config",!1).option("-p, --print","Print response and exit (useful for pipes)",!1).option("--output-format <format>",'Output format (only works with --print): "text" (default), "json" (single result), or "stream-json" (realtime streaming)',"text").option("--input-format <format>",'Input format (only works with --print): "text" (default), or "stream-json" (realtime streaming input) (choices: "text", "stream-json")',"text").option("--json-schema <schema>",'JSON Schema for structured output validation. Example: {"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}').option("--include-partial-messages","Output raw SSE incremental messages from model requests (only works with --output-format stream-json)",!1).option("-y, --dangerously-skip-permissions","Bypass permission prompts (HIGH/CRITICAL still ask). Isolated-sandbox full pass: CODEBUDDY_IS_SANDBOX=1 (process env only; high-risk).",!1).option("--permission-mode <mode>","Default permission mode for this process (TUI, --serve Web, ACP). Choices: acceptEdits, bypassPermissions, default, plan, dontAsk, auto. Does not write settings.").option("--permission-mode-before-plan <mode>","Permission mode to restore when exiting plan mode").option("--subagent-permission-mode <mode>",'Default permission mode for subagents/teammates (choices: "acceptEdits", "bypassPermissions", "default", "plan", "dontAsk", "auto"). Overrides inheritance from main session.').option("--tools <value>",'Restrict which built-in tools CodeBuddy can use. Use "" to disable all, "default" for all, or comma-separated tool names like "Bash,Edit,Read".').option("--allowedTools <tools...>",'Comma or space-separated list of tool names to allow (e.g. "Bash(git:*) Edit")').option("--disallowedTools <tools...>",'Comma or space-separated list of tool names to deny (e.g. "Bash(git:*) Edit")').option("--mcp-config <fileOrString>","Load MCP servers from a JSON file or string").option("--channels <value>","Enable specific channels (comma-separated: plugin:name@marketplace or server:configName)").option("--dangerously-load-development-channels <value>","During research preview: bypass allowlist for specific channels (development only, requires confirmation)").option("-c, --continue","Continue the most recent conversation",!1).option("-r, --resume [sessionId]","Resume a conversation - provide a session ID or interactively select a conversation to resume",!1).option("-w, --worktree [name]",'Create a git worktree and start the session in it (optionally specify a name, PR number like "#123", or PR URL)').option("--worktree-branch <branch>","Base branch for the worktree (defaults to remote default branch, requires --worktree)").option("--tmux","Create worktree in a new tmux session (requires --worktree)",!1).option("--tmux-classic","Use classic tmux mode instead of iTerm2 integration (requires --tmux)",!1).option("--model <model>","Model for the current session. Please provide the model ID.").option("--text-to-image-model <model>","Model for text-to-image generation").option("--image-to-image-model <model>","Model for image-to-image editing").option("--fallback-model <model>","Enable automatic fallback to specified model when default model is overloaded (only works with --print)").option("--add-dir <directories...>","Additional directories to allow tool access to").option("--ide","Automatically connect to IDE on startup if exactly one valid IDE is available",!1).option("-v, --version","Output the version number",!1).option("--strict-mcp-config","Only use MCP servers from --mcp-config, ignoring all other MCP configurations",!1).addOption(new i.Option("--no-plugin-management","Disable marketplace and plugin lifecycle management in this process").hideHelp()).option("--session-id <uuid>","Use a specific session ID for the conversation (supports letters, numbers, hyphens, underscores, and colons, but must start with a letter or number)").option("--no-session-persistence","Disable session persistence - sessions stay in memory and are not saved to disk").option("-H, --header <headers...>",'Custom HTTP headers for model requests (format: "Header-Key: Header-Value")').option("--serve","Start HTTP server (Web UI, REST API, ACP over HTTP SSE). Without --acp, ACP does not use stdio.",!1).option("--open","Open Web UI in browser after startup",!1).option("--port <number>","Port for HTTP server (default: auto-assign)").option("--host <string>","Host address to bind HTTP server (default: 127.0.0.1)","127.0.0.1").option("--base-path <path>","Public URL path prefix for the Web UI (e.g. /cnb-5gg-1k09dqp5v-001). Also CODEBUDDY_GATEWAY_BASE_PATH.").addOption(new i.Option("--auth <mode>",'HTTP server authentication mode (only applies with --serve). Defaults to "password"; "none" disables auth and lets any local process execute commands and read/write files through the server').choices(["password","none"])).option("--brief","Enable SendUserMessage tool for agent-to-user communication",!1).option("--acp","Start in ACP (Agent Client Protocol) mode - enables communication via stdin/stdout using ndJsonStream",!1).option("--acp-transport <transport>",'ACP transport (only works with --acp): "stdio" (default) or "streamable-http"',"stdio").addOption(new i.Option("--a2a",'Accept A2A (Agent2Agent) JSON-RPC over stdio \u2014 SendMessage/GetTask/CancelTask only. Alone: A2A owns stdio exclusively. Combined with --input-format stream-json: stdin carries both protocols, routed per line (a line with "jsonrpc" is A2A, otherwise stream-json), both driving the same session. Mutually exclusive with --acp. SDK/CloudAgent entry point, not for direct terminal use.').default(!1).hideHelp()).option("--sandbox [url]",'Run CodeBuddy in sandbox: "container" for Docker/Podman, or E2B API URL (must be complete URL like https://api.e2b.dev)').option("--sandbox-upload-dir","Upload current working directory to sandbox (E2B only)",!1).option("--sandbox-new","Force create a new sandbox (ignore cached sandbox)",!1).option("--sandbox-id <id>","Connect to specific sandbox ID").option("--sandbox-kill","Kill sandbox on exit (default: keep alive for reuse)",!1).option("--teleport <value>","Teleport to existing sandbox (format: session_{cliSessionId})").option("--max-turns <number>","Limit the number of agentic turns").option("--effort <level>","Reasoning effort level (minimal, low, medium, high, xhigh, max)").option("--autocompact <auto|tokens>",'Auto-compact window size: "auto" follows the model window, or a token count (e.g. 400000, 400k, 1m; clamped to 100k-1M)').option("--teleport <value>","Teleport to existing sandbox (format: 0010${sandboxId}${randomNumber} for e2b, 0020${sandboxId}${randomNumber} for cvm)").option("--system-prompt <prompt>","Override the system prompt for this session").option("--system-prompt-file <path>","Load system prompt from a file").option("--append-system-prompt <prompt>","Append additional content to the system prompt").option("--prompt-vars-file <path>","Load prompt template variables from a JSON file").option("--agent <agent>","Default main agent for this process (TUI, --serve Web, ACP). Overrides lastUsed for new sessions; does not write settings.").option("--agents <json>",'JSON object defining custom agents (e.g. \'{"reviewer": {"description": "Reviews code", "prompt": "You are a code reviewer"}}\')').option("--settings <file-or-json>","Path to a settings JSON file or a JSON string to load additional settings from").option("--setting-sources <sources>","Comma-separated list of setting sources to load (user, project, local). Default: user,project,local").option("--fork-session","When resuming, create a new session ID instead of reusing the original (use with --resume or --continue)").addOption(new i.Option("--resume-session-at <message id>","When resuming, only messages up to and including the assistant message with <message.id> (use with --resume in print mode)").argParser(String).hideHelp()).addOption(new i.Option("--rewind-files <user-message-id>","Restore files to state at the specified user message and exit (requires --resume)").hideHelp()).addOption(new i.Option("--dry-run","With --rewind-files, only preview the rewind; do not modify the filesystem").hideHelp()).option("--replay-user-messages","Re-emit user messages from stdin back on stdout for acknowledgment (only works with --input-format=stream-json and --output-format=stream-json)").option("--remote-control [client]","Connect to remote control service. Without args: AgentOS mode. With client type (e.g. wecom): auto-connect specified client").option("--plugin-dir <dirs...>","Load plugins from local directories (for development/testing). Can specify multiple paths.").option("--bg","Run the session in the background (detached)",!1).option("--background","Alias for --bg",!1).option("--name <name>","Name for background session (used with --bg)").option("--exec <command>","With --bg: run a shell command as a background job instead of a model session").option("--swarm","Enable swarm mode: teammates run as independent processes (tmux visualization if available, otherwise background with Web UI)",!1).addOption(new i.Option("--prewarm","Start as a prewarmed standby process: finish cold-start init then wait for IPC activation before binding to a working directory").default(!1).hideHelp()).addOption(new i.Option("--prewarm-id <id>","Identifier for the prewarm IPC endpoint (defaults to the process PID). Used to build the socket/pipe address.").hideHelp()).addOption(new i.Option("--prewarm-force","When a live prewarm process already owns the same --prewarm-id, terminate it and take over the address instead of refusing to start.").default(!1).hideHelp()).addOption(new i.Option("--teammate-mode","Mark this process as a teammate").hideHelp()).addOption(new i.Option("--team-name <name>","Team name for this teammate").hideHelp()).addOption(new i.Option("--agent-name <name>","Teammate agent name").hideHelp()).addOption(new i.Option("--agent-type <type>","Custom agent type for this teammate").hideHelp()).addOption(new i.Option("--agent-color <color>","Display color for this teammate").hideHelp()).addOption(new i.Option("--leader-endpoint <url>","Leader HTTP endpoint for Permission Bridge").hideHelp()).action(()=>{});let d=c.command("config").description("Manage configuration (eg. codebuddy config set -g theme dark)");d.command("get <key>").description("Get a config value"),d.command("set <key> <value>").description("Set a config value").option("-g, --global","Set global config"),d.command("remove <key> [values...]").alias("rm").description("Remove a config value or items from a config array").option("-g, --global","Set global config"),d.command("list").alias("ls").description("List all config values"),d.command("add <key> <values...>").description("Add items to a config array (space or comma separated)").option("-g, --global","Set global config");let u=c.command("mcp").description("Configure and manage MCP servers");u.command("add <name> <commandOrUrl> [args...]").description("Add an MCP server").option("-s, --scope <scope>","Server scope: local, project, or user","local").option("-t, --transport <transport>","Transport type: stdio, sse, or http","stdio").option("-e, --env <env...>","Environment variables (format: KEY=value)").option("-H, --header <header...>",'Custom HTTP headers for SSE and HTTP transports (format: "Header-Key: Header-Value")').addHelpText("after",'\nExample Call:\n $ codebuddy mcp add myserver --env KEY=value -- python main.py --port 8080\n\n* NOTE:\n Understanding the "\u2014-" parameter:\n The "--" (double dash) separates CodeBuddy\u2019s own CLI flags from the command and arguments that get passed to the MCP server. Everything before "--" are options for CodeBuddy, and everything after "--" is the actual command to run the MCP server.'),u.command("remove <name>").description("Remove an MCP server").option("-s, --scope <scope>","Server scope: local, project, or user"),u.command("list").alias("ls").description("List configured MCP servers"),u.command("get <name>").description("Get details about an MCP server"),u.command("add-json <name> <json>").description("Add an MCP server (stdio or SSE) with a JSON string").option("-s, --scope <scope>","Server scope: local, project, or user","local");let p=c.command("sandbox").description("Manage sandboxes");p.command("list").alias("ls").description("List all sandboxes"),p.command("info [sandboxId]").description("Show sandbox information"),p.command("kill <sandboxId>").description("Kill a running sandbox"),p.command("clean").description("Clean up stopped/expired sandboxes from state file");let g=c.command("plugin").description("Manage CodeBuddy Code plugins");g.command("validate <path>").description("Validate a plugin or marketplace manifest"),g.command("list").alias("ls").option("--json","Output as JSON").description("List installed plugins");let h=g.command("marketplace").description("Manage CodeBuddy Code marketplaces");h.command("add <source>").option("-n, --name <name>","Marketplace name").description("Add a marketplace"),h.command("list").alias("ls").description("List all marketplaces"),h.command("update <name>").description("Update a marketplace"),h.command("remove <name>").alias("rm").description("Remove a marketplace"),g.command("install <plugin>").alias("i").option("-s, --scope <scope>","Install scope: user, project, or local","user").description("Install a plugin from available marketplaces (use plugin@marketplace for specific marketplace)"),g.command("uninstall <plugin>").aliases(["remove","rm"]).option("-s, --scope <scope>","Uninstall scope: user, project, or local","user").option("--prune","Also remove auto-installed dependencies that are no longer needed").option("--keep-data","Preserve plugin data after removing the final installed scope").option("-y, --yes","Skip the --prune confirmation prompt").description("Uninstall an installed plugin"),g.command("prune").aliases(["autoremove"]).option("-s, --scope <scope>","Prune at scope: user, project, or local","user").option("--dry-run","List what would be removed without removing").option("-y, --yes","Skip the confirmation prompt").description("Remove auto-installed dependencies that are no longer needed"),g.command("enable <plugin>").option("-s, --scope <scope>","Enable scope: user, project, or local (default: auto-detect)").description("Enable a disabled plugin"),g.command("disable <plugin>").option("-s, --scope <scope>","Disable scope: user, project, or local (default: auto-detect)").description("Disable an enabled plugin"),g.command("update <plugin>").option("-s, --scope <scope>","Update scope: user, project, or local","user").description("Update a plugin to the latest version (restart required to apply)"),c.command("doctor").description("Check the health of your CodeBuddy Code auto-updater"),c.command("update").description("Check for updates and install if available"),c.command("install [target]").description("Install CodeBuddy Code native build. Use [target] to specify version (latest, or specific version)");let m=c.command("daemon").description("Manage the daemon supervisor process");m.command("start").description("Start the daemon supervisor").option("--port <number>","Port for daemon HTTP server (default: auto)").option("--host <string>","Host address to bind (default: 127.0.0.1)"),m.command("stop").description("Stop the daemon supervisor").option("--keep-workers","Leave background session workers running; stop only the daemon itself",!1),m.command("status").description("Show daemon supervisor status"),m.command("restart").description("Restart the daemon supervisor"),m.command("install").description("Register daemon as a system service (auto-start on login)").option("--port <number>","Port for daemon HTTP server").option("--permission-mode <mode>","Permission mode for daemon sessions"),m.command("uninstall").description("Remove daemon system service registration"),c.command("ps").description("List all active sessions (interactive, background, daemon)").option("--json","Output in JSON format",!1),c.command("logs <pidOrName>").description("Show logs for a background session").option("-f, --follow","Follow log output",!1),c.command("attach <pidOrName>").description("Attach to a running background session"),c.command("kill <pidOrName>").description("Terminate a background session"),c.command("stop <pidOrName>").description("Stop a background session (alias for kill)"),c.command("rm <idOrName>").description("Remove a background session from agent view (the transcript stays on your machine)"),c.command("respawn [idOrName]").description("Restart a background session with its conversation intact").option("--all","Restart every running background session (e.g. after a binary update)"),c.command("agents").description("Open agent view to dispatch and manage background sessions").option("--jobs","Print sessions as a JSON array and exit",!1).option("--all","Include completed sessions in --jobs output",!1).option("--cwd <path>","Only list sessions started under this directory").option("--model <model>","Model used for sessions dispatched from agent view").option("--permission-mode <mode>","Permission mode for sessions dispatched from agent view").option("--agent <agent>","Default main agent for dispatched sessions");let f=c.command("auto-mode").description("Inspect auto mode classifier configuration");f.command("defaults").description("Print the built-in default auto mode rules as JSON"),f.command("config").description("Print the effective auto mode config as JSON (your settings where set, defaults otherwise)"),f.command("critique").description("Get AI feedback on your custom auto mode rules"),c.command("agents").description("List configured agents grouped by source (user, project, managed, plugin, cli-arg, built-in); requires --json").option("--json","Output as JSON",!1),c.on("command:*",e=>{});let y=class{constructor(){this.CURRENTLY_SUPPORTED_PATTERN=/ Currently supported: \([^)]*\)$/}async get(){if(this.isHelpRequested()){let sigintHandler=()=>process.exit(0);process.on("SIGINT",sigintHandler),await this.updateModelOptionDescription(),process.off("SIGINT",sigintHandler)}let e=process.env.ELECTRON_RUN_AS_NODE?"node":void 0;return c.parse(process.argv,e?{from:e}:void 0),c}parseOpts(){let e=c.args;return c.parseOptions(process.argv),{arg:e,opts:c.opts()}}isHelpRequested(){let e=process.argv;return e.includes("-h")||e.includes("--help")||e.includes("help")||e.some(e=>e.endsWith("--help")||e.endsWith("-h"))}async updateModelOptionDescription(){try{let e=c.options.find(e=>"--model"===e.long);if(!e)return;let t=new Promise((e,t)=>{let r=setTimeout(()=>t(Error("timeout")),1e4);"function"==typeof r.unref&&r.unref()}),r=o.ContainerUtil.get(n.AgentManager),i=await Promise.race([r.getDefault(),t]),s=await Promise.race([r.getModels(i.name),t]);if(0===s.length)return;let a=s.map(e=>e.id).join(", ");e.description=e.description.replace(this.CURRENTLY_SUPPORTED_PATTERN,""),e.description+=` Currently supported: (${a})`}catch{}}};y=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s}([(0,o.Component)(a.CliProvider)],y)},39432(e,t,r){r.r(t),r.d(t,{CLI_VIEW_NAME:()=>i,CliViewToken:()=>o});let o=Symbol("CliView"),i="cli"},98577(e,t,r){r.r(t),r.d(t,{DispatchChain:()=>c});var o,i,n=r(88523),s=r(56604),a=r(63295),l=r(16870),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let c=class{async execute(e){try{this.shortcutManager.register(a.KEY_CODES.CTRL_C,()=>{(0,s.exitWhenInPlaceWorkersSettled)(0)})}catch{}for(let t of this.strategyProvider.sortSync())if(t.canHandle(e)&&!1!==await t.execute(e))return}};__decorate([(0,n.AutowiredProvider)(l.DispatchStrategy),__metadata("design:type","function"==typeof(o=void 0!==n.Provider&&n.Provider)?o:Object)],c.prototype,"strategyProvider",void 0),__decorate([(0,n.Autowired)(a.ShortcutManager),__metadata("design:type","function"==typeof(i=void 0!==a.ShortcutManager&&a.ShortcutManager)?i:Object)],c.prototype,"shortcutManager",void 0),c=__decorate([(0,n.Component)()],c)},48855(e,t,r){r.r(t),r.d(t,{CLI_PROCESS_PERMISSION_MODES:()=>s.CLI_PROCESS_PERMISSION_MODES,CLI_VIEW_NAME:()=>f.CLI_VIEW_NAME,CliDispatcher:()=>o.CliDispatcher,CliDispatcherImpl:()=>n.CliDispatcherImpl,CliExecutor:()=>u.CliExecutor,CliProvider:()=>o.CliProvider,CliProviderImpl:()=>i.CliProviderImpl,CliRuntimeOptions:()=>s.CliRuntimeOptions,CliViewToken:()=>f.CliViewToken,DispatchChain:()=>d.DispatchChain,DispatchStrategy:()=>o.DispatchStrategy,InteractiveExecutor:()=>g.InteractiveExecutor,LLMView:()=>a.LLMView,LLM_VIEW_NAME:()=>a.LLM_VIEW_NAME,PrintDeliveryLifecycle:()=>h.PrintDeliveryLifecycle,PrintDeliveryLifecycleImpl:()=>h.PrintDeliveryLifecycleImpl,RewindFilesRunner:()=>p.RewindFilesRunner,TuiModeService:()=>y.TuiModeService,TuiModeServiceImpl:()=>y.TuiModeServiceImpl,ViewMessageFilter:()=>m.ViewMessageFilter,ViewMessageFilterPriority:()=>m.ViewMessageFilterPriority,pickCliProcessDefaults:()=>s.pickCliProcessDefaults,redactEnvValueForLog:()=>n.redactEnvValueForLog,resolveCliProcessDefaults:()=>s.resolveCliProcessDefaults});var o=r(16870),i=r(45443),n=r(20995),s=r(63831),a=r(49253),l=r(25137),c={};for(let e in l)0>["CliRuntimeOptions","CliDispatcherImpl","default","CLI_PROCESS_PERMISSION_MODES","pickCliProcessDefaults","CliDispatcher","resolveCliProcessDefaults","LLMView","redactEnvValueForLog","CliProvider","LLM_VIEW_NAME","DispatchStrategy","CliProviderImpl"].indexOf(e)&&(c[e]=()=>l[e]);r.d(t,c);var d=r(98577),u=r(79163),p=r(49205),g=r(82573),h=r(82136),m=r(95494),f=r(39432),y=r(96287)},82573(e,t,r){r.r(t),r.d(t,{InteractiveExecutor:()=>d});var o,i,n=r(88523),s=r(7268),a=r(6676),l=r(86045),c=r(13945),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let d=class{get startupProfiler(){return n.ContainerUtil.get(c.StartupProfiler)}async execute(e){try{this.restOperations=this.restOperationsFactory.create();let{endpointProvider:t,path:r,baseBody:o}=e,i=await t.get();await this.corsService?.setup(i);let n=`${i}${r}`;this.startupProfiler.markEnd(c.StartupPhase.READY),this.startupProfiler.isEnabled()&&this.consoleManager.debug(this.startupProfiler.formatReport(),{mode:a.ConsoleOutputMode.NATIVE}),await this.restOperations.post(n,{...o,interactive:!0},{headers:(0,l.withSecurityHeader)({[s.HttpHeaders.CONTENT_TYPE]:s.MediaType.APPLICATION_JSON_UTF8}),proxy:!1})}catch(t){let e;e=t.response?.data?"string"==typeof t.response.data?t.response.data:JSON.stringify(t.response.data):t instanceof Error?t.message:String(t),process.stdout.write(`${e}
|
|
31
|
+
`),this.finalizeAndExit(1))}c.resumeSessionAt&&(i.resumeSessionAt=String(c.resumeSessionAt)),"stream-json"===n?await this.executeStreamMode(a,o,i,s,!!c.a2a):await this.executeSingleRequest(a,o,i,s,l),await this.finalizeAndExit(0)}async finalizeAndExit(e){this.startupProfiler.isEnabled()&&this.consoleManager.debug(this.startupProfiler.formatReport({showAll:!0,threshold:0}),{mode:w.ConsoleOutputMode.NATIVE});try{let e=await this.stdoutWriter.flushOrStall(5e3);e.complete||this.logger.warn(`[CliExecutor] stdout flush stalled for 5000ms with no progress \u{2014} exiting with ~${e.remainingBytes} bytes undelivered (failedWrites=${this.stdoutWriter.failedWrites})`)}catch{}await this.stdoutWriter.flushPersistChannel(),this.loggerStorageService.flushSync();try{let e=p.ContainerUtil.get(_.AgentTaskManager);await e.waitForRunningTasks()}catch{}try{await new Promise(e=>setImmediate(e)),await (0,S.shutdownTelemetryBeforeExit)(2e3)}catch{}process.exit(+(0!==e))}hasPromptArgument(e,t){let r=Array.isArray(e.args)&&e.args.length>0?String(e.args[0]??""):"",o="string"==typeof t.prompt?t.prompt:"";return r.trim().length>0||o.trim().length>0}async executeSingleRequest(e,t,r,o,i){try{let n={...r,print:!0,...this.directDeliveryFields(t,o)};this.startupProfiler.markStart("http_request","HTTP Request (total)"),await this.sendRequest(e,t,n,o,i),this.startupProfiler.markEnd("http_request")}catch(e){this.startupProfiler.markEnd("http_request"),await this.writeError(e,o)}}directDeliveryFields(e,t){return"stream-json"===t&&e.includes("internal/agent")?{directDelivery:!0,deliveryId:(0,p.generateUUUID)()}:{}}extractTelemetryClientInfo(e){if(!e||"object"!=typeof e)return;let t=e[T.TELEMETRY_CLIENT_INFO_META_KEY];if(t&&"object"==typeof t)return t;let r=e._meta?.["codebuddy.ai"],o=r?.[T.TELEMETRY_CLIENT_INFO_META_KEY];return o&&"object"==typeof o?o:void 0}async executeStreamMode(e,t,r,o,i=!1){let n,s,a,l=new p.Deferred,c=!1;"stream-json"===o&&this.mcpFirstRunStatusService&&(s=this.mcpFirstRunStatusService.events$.subscribe(e=>{try{this.stdoutWriter.write(renderMcpFirstRunStatusEventToNdjson(e))}catch(e){this.logger?.warn?.(`[CliExecutor] mcp_status ndjson write failed: ${e instanceof Error?e.message:String(e)}`)}if("finish"===e.kind){try{s?.unsubscribe()}catch{}s=void 0}}));let d=isStdioPersistenceEnabled(),g=null,h=[];d&&this.stdoutWriter.armPersistPrebuffer();let _=[],activatePersistChannel=e=>{if(d&&!g){for(let t of(g=openStreamJsonChannel(e),h))g.append("in",t);h.length=0,this.stdoutWriter.attachPersistChannel(g,_),_.length=0}},w=!1,v=new p.Deferred,S=new Set,A=new AbortController,C=!1,startDrainWaitLoop=i=>{C||"stream-json"!==o||(C=!0,track((async()=>{for(;!A.signal.aborted&&!c;){let n=Date.now();try{await this.sendRequest(e,t,{...r,print:!0,drainWait:!0,sessionId:i},o,!0,A.signal)}catch(e){if(A.signal.aborted)return}let s=Date.now()-n;!(s<500)||A.signal.aborted||c||await new Promise(e=>setTimeout(e,500-s))}})()))},I=Promise.resolve(),getA2aDispatcher=()=>{if(i){if(!a)try{let e=p.ContainerUtil.get(f.A2aAgentExecutor);a=new y.A2aLineDispatcher(e,this.logger,{boundSessionId:()=>n??p.ContainerUtil.get(T.SessionManager).sessionSubject?.getValue()?.id})}catch(e){this.logger?.error?.(`[CliExecutor] --a2a set but A2A executor is unavailable: ${e instanceof Error?e.message:String(e)}`)}return a}},P=(0,m.createInterface)({input:process.stdin,crlfDelay:1/0}),processLine=async i=>{if(!i.trim())return;let s=Date.now();try{let a;try{a=JSON.parse(i)}catch{a={type:"user",content:i}}if((e=>{if(d){if(g)return g.append("in",e);h.length<4096&&h.push(e)}})(a),(0,y.isA2aJsonRpcLine)(a)){let e=getA2aDispatcher();if(!e)return void this.stdoutWriter.write({jsonrpc:"2.0",id:a?.id??null,error:{code:u.A2A_ERROR_CODE.METHOD_NOT_FOUND,message:"A2A is not enabled on this process (add --a2a)"}});let t=await e.dispatch(i);this.stdoutWriter.write(t);return}if((0,b.isControlSignalMessage)(a)){let e=a;if("control_request"===e.type){let t=e.request;if(t?.subtype==="initialize"&&!w){w=!0,I=this.controlSignalHandler.handleMessage(e).catch(e=>{this.writeError(e,o)}),await I,v.resolve({hasPrompt:t.hasPrompt});return}}this.controlSignalHandler.handleMessage(e).catch(e=>{this.writeError(e,o)});return}await I,w||(w=!0,v.resolve({hasPrompt:!0}));let l=a&&"object"==typeof a?a:void 0,c=l?.trace_id,p=l?.parent_span_id,m=this.extractTelemetryClientInfo(a),f={...r,print:!0,prompt:i,...this.directDeliveryFields(t,o),...n?{sessionId:n}:{},...c?{traceId:c}:{},...p?{parentSpanId:p}:{},...l?._meta?{_meta:l._meta}:{},...m?{telemetryClientInfo:m}:{},stdinReceivedAt:s},_=await this.sendRequest(e,t,f,o);_.sessionId&&(n=_.sessionId,startDrainWaitLoop(n),activatePersistChannel(n))}catch(e){await this.writeError(e,o)}},track=e=>{let t=e.finally(()=>{S.delete(t)});S.add(t)};if(P.on("line",e=>{track(processLine(e))}),P.on("close",()=>{c=!0,A.abort(),w||v.resolve({hasPrompt:!1});try{p.ContainerUtil.get(b.SdkPermissionClient).cancelAllPending("SDK disconnected")}catch{}try{p.ContainerUtil.get(E.SdkMcpMessageClient).cancelAllPending("SDK disconnected")}catch{}try{p.ContainerUtil.get(b.SdkElicitationClient).cancelAllPending("SDK disconnected")}catch{}l.resolve()}),P.on("error",()=>{c=!0,A.abort(),w||v.resolve({hasPrompt:!1}),l.resolve()}),r.resume){let{hasPrompt:i}=await v.promise;if(i)this.logger.info("[ResumeReplay] skipped (hasPrompt=true, SDK will send a prompt)");else{let i=Date.now();this.logger.info(`[ResumeReplay] start history replay for resume=${String(r.resume)}`);try{let s={...r,print:!0,...this.directDeliveryFields(t,o)},a=await this.sendRequest(e,t,s,o);a.sessionId&&(n=a.sessionId,activatePersistChannel(n)),this.logger.info(`[ResumeReplay] history replay completed in ${Date.now()-i}ms (sessionId=${n??"unknown"})`)}catch(e){this.logger.warn(`[ResumeReplay] history replay failed after ${Date.now()-i}ms: ${e instanceof Error?e.message:String(e)}`),await this.writeError(e,o)}}}for(await l.promise;S.size>0;)await Promise.all([...S]);try{s?.unsubscribe()}catch{}}async sendRequest(e,t,r,o,i=!0,n){let s=`${e}${t}`,a="stream-json"===o;if(a&&!0===r.directDelivery&&"string"==typeof r.deliveryId)return await this.sendDirectDeliveryRequest(s,r,r.deliveryId);let l=await this.restOperations.post(s,r,{headers:(0,I.withSecurityHeader)({[g.HttpHeaders.CONTENT_TYPE]:g.MediaType.APPLICATION_JSON_UTF8,...a?{[g.HttpHeaders.ACCEPT]:"text/event-stream"}:{}}),proxy:!1,responseType:a?"stream":void 0,...n?{signal:n}:{}});if(l.data){let e=l.headers["content-type"]||"",t=StreamUtils.isStream(l.data);if(e.includes("text/event-stream")||t)return await this.handleStreamResponse(l.data);if("object"==typeof l.data){if(i)if("stream-json"===o)process.stdout.write(JSON.stringify(l.data)+"\n");else{let e=l.data.text||l.data.message||JSON.stringify(l.data,null,2);process.stdout.write(e+"\n")}return{sessionId:l.data.sessionId}}i&&process.stdout.write(String(l.data)+"\n")}return{}}async sendDirectDeliveryRequest(e,t,r){this.deliveryLifecycle.begin(r);let o=this.restOperations.post(e,t,{headers:(0,I.withSecurityHeader)({[g.HttpHeaders.CONTENT_TYPE]:g.MediaType.APPLICATION_JSON_UTF8}),proxy:!1}).then(e=>({ok:!0,result:e}),e=>({ok:!1,error:e})),i=await Promise.race([this.deliveryLifecycle.wait(r).then(e=>({kind:"delivered",info:e})),o.then(e=>({kind:"post",post:e}))]);if("delivered"===i.kind)return{sessionId:i.info.sessionId};let n=i.post.ok?2e3:100,s=await new Promise(e=>{let t=setTimeout(()=>e(void 0),n);t.unref?.(),this.deliveryLifecycle.wait(r).then(r=>{clearTimeout(t),e(r)}).catch(()=>{clearTimeout(t),e(void 0)})});if(this.deliveryLifecycle.abandon(r),s&&!s.error)return{sessionId:s.sessionId};if(!i.post.ok)throw i.post.error;let a=i.post.result?.data;return this.logger.warn(`[CliExecutor] direct delivery ${r} completed without view settle (post ok); sessionId=${a?.sessionId??"n/a"}`),{sessionId:a?.sessionId}}async handleStreamResponse(e){let t,r=new p.Deferred,o="";return e.on("data",e=>{try{let r=e.toString(),i=(o+=r).split("\n");for(let e of(o=i.pop()||"",i))if(e.trim())try{let r=JSON.parse(e);if(0===Object.keys(r).length)continue;this.stdoutWriter.writeLine(e),"system"===r.type&&"init"===r.subtype&&r.session_id&&(t=r.session_id)}catch{if(e.startsWith("data:")){let r=e.substring(5).trim();try{let e=JSON.parse(r);if(0===Object.keys(e).length)continue;this.stdoutWriter.writeLine(r),"system"===e.type&&"init"===e.subtype&&e.session_id&&(t=e.session_id)}catch{this.stdoutWriter.writeLine(r)}}}}catch(e){this.logger.warn(`[CliExecutor] stream data handler error (line dropped, stream kept alive): ${e instanceof Error?e.message:String(e)}`)}}),e.on("end",()=>r.resolve({sessionId:t})),e.on("error",()=>r.resolve({sessionId:t})),r.promise}async extractMessageFromData(e){if(StreamUtils.isStream(e))return await StreamUtils.readStreamToString(e);if("string"==typeof e)return e;if(Buffer.isBuffer(e))return e.toString("utf8");if("object"==typeof e){let t=e.text??e.message??e.error;if("string"==typeof t)return t;try{return JSON.stringify(e)}catch{}}}async writeError(e,t){let r;e?.isAxiosError&&e?.response&&(r=await this.extractMessageFromData(e.response.data)),r||(r=e instanceof Error?e.message:String(e)),"stream-json"===t?this.stdoutWriter.write({type:"error",error:r}):process.stderr.write(r+"\n")}};__decorate([(0,p.Autowired)(g.RestOperationsFactory),__metadata("design:type","function"==typeof(o=void 0!==g.RestOperationsFactory&&g.RestOperationsFactory)?o:Object)],$.prototype,"restOperationsFactory",void 0),__decorate([(0,p.Autowired)(h.LoggerStorageService),__metadata("design:type","function"==typeof(i=void 0!==h.LoggerStorageService&&h.LoggerStorageService)?i:Object)],$.prototype,"loggerStorageService",void 0),__decorate([(0,p.Autowired)(b.ControlSignalHandler),__metadata("design:type","function"==typeof(n=void 0!==b.ControlSignalHandler&&b.ControlSignalHandler)?n:Object)],$.prototype,"controlSignalHandler",void 0),__decorate([(0,p.Autowired)(w.ConsoleManager),__metadata("design:type","function"==typeof(s=void 0!==w.ConsoleManager&&w.ConsoleManager)?s:Object)],$.prototype,"consoleManager",void 0),__decorate([(0,p.Autowired)(h.Logger),__metadata("design:type","function"==typeof(a=void 0!==h.Logger&&h.Logger)?a:Object)],$.prototype,"logger",void 0),__decorate([(0,p.Autowired)(v.StdoutWriter),__metadata("design:type","function"==typeof(l=void 0!==v.StdoutWriter&&v.StdoutWriter)?l:Object)],$.prototype,"stdoutWriter",void 0),__decorate([(0,p.Autowired)(C.McpFirstRunStatusService),(0,p.Optional)(),__metadata("design:type",Object)],$.prototype,"mcpFirstRunStatusService",void 0),__decorate([(0,p.Autowired)(D.PrintDeliveryLifecycle),__metadata("design:type","function"==typeof(c=void 0!==D.PrintDeliveryLifecycle&&D.PrintDeliveryLifecycle)?c:Object)],$.prototype,"deliveryLifecycle",void 0),__decorate([(0,p.Autowired)(N.RewindFilesRunner),__metadata("design:type","function"==typeof(d=void 0!==N.RewindFilesRunner&&N.RewindFilesRunner)?d:Object)],$.prototype,"rewindFilesRunner",void 0),$=__decorate([(0,p.Component)()],$)},45443(e,t,r){r.r(t),r.d(t,{CliProviderImpl:()=>y});var o=r(88523),i=r(75348),n=r(79127),s=r(48400),a=r(16870);let l=s.PackageUtils.getCurrentPackageJson(),c=new i.Command;c.name("codebuddy").alias("cbc").version(l.version).description("CodeBuddy Code - starts an interactive session by default, use -p/--print for non-interactive output").argument("[prompt]","Your prompt").option("-d, --debug [filter]",'Enable debug mode with optional category filtering (e.g., "api,hooks" or "!statsig,!file")',e=>{try{let t=JSON.parse(e);if("string"==typeof t)return t;throw Error("Not a string")}catch(t){return e}},!1).addOption(new i.Option("-d2e, --debug-to-stderr","Enable debug mode (to stderr)").default(!1).hideHelp()).option("--verbose","Override verbose mode setting from config",!1).option("-p, --print","Print response and exit (useful for pipes)",!1).option("--output-format <format>",'Output format (only works with --print): "text" (default), "json" (single result), or "stream-json" (realtime streaming)',"text").option("--input-format <format>",'Input format (only works with --print): "text" (default), or "stream-json" (realtime streaming input) (choices: "text", "stream-json")',"text").option("--json-schema <schema>",'JSON Schema for structured output validation. Example: {"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}').option("--include-partial-messages","Output raw SSE incremental messages from model requests (only works with --output-format stream-json)",!1).option("-y, --dangerously-skip-permissions","Bypass permission prompts (HIGH/CRITICAL still ask). Isolated-sandbox full pass: CODEBUDDY_IS_SANDBOX=1 (process env only; high-risk).",!1).option("--permission-mode <mode>","Default permission mode for this process (TUI, --serve Web, ACP). Choices: acceptEdits, bypassPermissions, default, plan, dontAsk, auto. Does not write settings.").option("--permission-mode-before-plan <mode>","Permission mode to restore when exiting plan mode").option("--subagent-permission-mode <mode>",'Default permission mode for subagents/teammates (choices: "acceptEdits", "bypassPermissions", "default", "plan", "dontAsk", "auto"). Overrides inheritance from main session.').option("--tools <value>",'Restrict which built-in tools CodeBuddy can use. Use "" to disable all, "default" for all, or comma-separated tool names like "Bash,Edit,Read".').option("--allowedTools <tools...>",'Comma or space-separated list of tool names to allow (e.g. "Bash(git:*) Edit")').option("--disallowedTools <tools...>",'Comma or space-separated list of tool names to deny (e.g. "Bash(git:*) Edit")').option("--mcp-config <fileOrString>","Load MCP servers from a JSON file or string").option("--channels <value>","Enable specific channels (comma-separated: plugin:name@marketplace or server:configName)").option("--dangerously-load-development-channels <value>","During research preview: bypass allowlist for specific channels (development only, requires confirmation)").option("-c, --continue","Continue the most recent conversation",!1).option("-r, --resume [sessionId]","Resume a conversation - provide a session ID or interactively select a conversation to resume",!1).option("-w, --worktree [name]",'Create a git worktree and start the session in it (optionally specify a name, PR number like "#123", or PR URL)').option("--worktree-branch <branch>","Base branch for the worktree (defaults to remote default branch, requires --worktree)").option("--tmux","Create worktree in a new tmux session (requires --worktree)",!1).option("--tmux-classic","Use classic tmux mode instead of iTerm2 integration (requires --tmux)",!1).option("--model <model>","Model for the current session. Please provide the model ID.").option("--text-to-image-model <model>","Model for text-to-image generation").option("--image-to-image-model <model>","Model for image-to-image editing").option("--fallback-model <model>","Enable automatic fallback to specified model when default model is overloaded (only works with --print)").option("--add-dir <directories...>","Additional directories to allow tool access to").option("--ide","Automatically connect to IDE on startup if exactly one valid IDE is available",!1).option("-v, --version","Output the version number",!1).option("--strict-mcp-config","Only use MCP servers from --mcp-config, ignoring all other MCP configurations",!1).addOption(new i.Option("--no-plugin-management","Disable marketplace and plugin lifecycle management in this process").hideHelp()).option("--session-id <uuid>","Use a specific session ID for the conversation (supports letters, numbers, hyphens, underscores, and colons, but must start with a letter or number)").option("--no-session-persistence","Disable session persistence - sessions stay in memory and are not saved to disk").option("-H, --header <headers...>",'Custom HTTP headers for model requests (format: "Header-Key: Header-Value")').option("--serve","Start HTTP server (Web UI, REST API, ACP over HTTP SSE). Without --acp, ACP does not use stdio.",!1).option("--open","Open Web UI in browser after startup",!1).option("--port <number>","Port for HTTP server (default: auto-assign)").option("--host <string>","Host address to bind HTTP server (default: 127.0.0.1)","127.0.0.1").option("--base-path <path>","Public URL path prefix for the Web UI (e.g. /cnb-5gg-1k09dqp5v-001). Also CODEBUDDY_GATEWAY_BASE_PATH.").addOption(new i.Option("--auth <mode>",'HTTP server authentication mode (only applies with --serve). Defaults to "password"; "none" disables auth and lets any local process execute commands and read/write files through the server').choices(["password","none"])).option("--brief","Enable SendUserMessage tool for agent-to-user communication",!1).option("--acp","Start in ACP (Agent Client Protocol) mode - enables communication via stdin/stdout using ndJsonStream",!1).option("--acp-transport <transport>",'ACP transport (only works with --acp): "stdio" (default) or "streamable-http"',"stdio").addOption(new i.Option("--a2a",'Accept A2A (Agent2Agent) JSON-RPC over stdio \u2014 SendMessage/GetTask/CancelTask only. Alone: A2A owns stdio exclusively. Combined with --input-format stream-json: stdin carries both protocols, routed per line (a line with "jsonrpc" is A2A, otherwise stream-json), both driving the same session. Mutually exclusive with --acp. SDK/CloudAgent entry point, not for direct terminal use.').default(!1).hideHelp()).option("--sandbox [url]",'Run CodeBuddy in sandbox: "container" for Docker/Podman, or E2B API URL (must be complete URL like https://api.e2b.dev)').option("--sandbox-upload-dir","Upload current working directory to sandbox (E2B only)",!1).option("--sandbox-new","Force create a new sandbox (ignore cached sandbox)",!1).option("--sandbox-id <id>","Connect to specific sandbox ID").option("--sandbox-kill","Kill sandbox on exit (default: keep alive for reuse)",!1).option("--teleport <value>","Teleport to existing sandbox (format: session_{cliSessionId})").option("--max-turns <number>","Limit the number of agentic turns").option("--effort <level>","Reasoning effort level (minimal, low, medium, high, xhigh, max)").option("--autocompact <auto|tokens>",'Auto-compact window size: "auto" follows the model window, or a token count (e.g. 400000, 400k, 1m; clamped to 100k-1M)').option("--teleport <value>","Teleport to existing sandbox (format: 0010${sandboxId}${randomNumber} for e2b, 0020${sandboxId}${randomNumber} for cvm)").option("--system-prompt <prompt>","Override the system prompt for this session").option("--system-prompt-file <path>","Load system prompt from a file").option("--append-system-prompt <prompt>","Append additional content to the system prompt").option("--prompt-vars-file <path>","Load prompt template variables from a JSON file").option("--agent <agent>","Default main agent for this process (TUI, --serve Web, ACP). Overrides lastUsed for new sessions; does not write settings.").option("--agents <json>",'JSON object defining custom agents (e.g. \'{"reviewer": {"description": "Reviews code", "prompt": "You are a code reviewer"}}\')').option("--settings <file-or-json>","Path to a settings JSON file or a JSON string to load additional settings from").option("--setting-sources <sources>","Comma-separated list of setting sources to load (user, project, local). Default: user,project,local").option("--fork-session","When resuming, create a new session ID instead of reusing the original (use with --resume or --continue)").addOption(new i.Option("--resume-session-at <message id>","When resuming, only messages up to and including the assistant message with <message.id> (use with --resume in print mode)").argParser(String).hideHelp()).addOption(new i.Option("--rewind-files <user-message-id>","Restore files to state at the specified user message and exit (requires --resume)").hideHelp()).addOption(new i.Option("--dry-run","With --rewind-files, only preview the rewind; do not modify the filesystem").hideHelp()).option("--replay-user-messages","Re-emit user messages from stdin back on stdout for acknowledgment (only works with --input-format=stream-json and --output-format=stream-json)").option("--remote-control [client]","Connect to remote control service. Without args: AgentOS mode. With client type (e.g. wecom): auto-connect specified client").option("--plugin-dir <dirs...>","Load plugins from local directories (for development/testing). Can specify multiple paths.").option("--bg","Run the session in the background (detached)",!1).option("--background","Alias for --bg",!1).option("--name <name>","Name for background session (used with --bg)").option("--exec <command>","With --bg: run a shell command as a background job instead of a model session").option("--swarm","Enable swarm mode: teammates run as independent processes (tmux visualization if available, otherwise background with Web UI)",!1).addOption(new i.Option("--prewarm","Start as a prewarmed standby process: finish cold-start init then wait for IPC activation before binding to a working directory").default(!1).hideHelp()).addOption(new i.Option("--prewarm-id <id>","Identifier for the prewarm IPC endpoint (defaults to the process PID). Used to build the socket/pipe address.").hideHelp()).addOption(new i.Option("--prewarm-force","When a live prewarm process already owns the same --prewarm-id, terminate it and take over the address instead of refusing to start.").default(!1).hideHelp()).addOption(new i.Option("--teammate-mode","Mark this process as a teammate").hideHelp()).addOption(new i.Option("--team-name <name>","Team name for this teammate").hideHelp()).addOption(new i.Option("--agent-name <name>","Teammate agent name").hideHelp()).addOption(new i.Option("--agent-type <type>","Custom agent type for this teammate").hideHelp()).addOption(new i.Option("--agent-color <color>","Display color for this teammate").hideHelp()).addOption(new i.Option("--leader-endpoint <url>","Leader HTTP endpoint for Permission Bridge").hideHelp()).action(()=>{});let d=c.command("config").description("Manage configuration (eg. codebuddy config set -g theme dark)");d.command("get <key>").description("Get a config value"),d.command("set <key> <value>").description("Set a config value").option("-g, --global","Set global config"),d.command("remove <key> [values...]").alias("rm").description("Remove a config value or items from a config array").option("-g, --global","Set global config"),d.command("list").alias("ls").description("List all config values"),d.command("add <key> <values...>").description("Add items to a config array (space or comma separated)").option("-g, --global","Set global config");let u=c.command("mcp").description("Configure and manage MCP servers");u.command("add <name> <commandOrUrl> [args...]").description("Add an MCP server").option("-s, --scope <scope>","Server scope: local, project, or user","local").option("-t, --transport <transport>","Transport type: stdio, sse, or http","stdio").option("-e, --env <env...>","Environment variables (format: KEY=value)").option("-H, --header <header...>",'Custom HTTP headers for SSE and HTTP transports (format: "Header-Key: Header-Value")').addHelpText("after",'\nExample Call:\n $ codebuddy mcp add myserver --env KEY=value -- python main.py --port 8080\n\n* NOTE:\n Understanding the "\u2014-" parameter:\n The "--" (double dash) separates CodeBuddy\u2019s own CLI flags from the command and arguments that get passed to the MCP server. Everything before "--" are options for CodeBuddy, and everything after "--" is the actual command to run the MCP server.'),u.command("remove <name>").description("Remove an MCP server").option("-s, --scope <scope>","Server scope: local, project, or user"),u.command("list").alias("ls").description("List configured MCP servers"),u.command("get <name>").description("Get details about an MCP server"),u.command("add-json <name> <json>").description("Add an MCP server (stdio or SSE) with a JSON string").option("-s, --scope <scope>","Server scope: local, project, or user","local");let p=c.command("sandbox").description("Manage sandboxes");p.command("list").alias("ls").description("List all sandboxes"),p.command("info [sandboxId]").description("Show sandbox information"),p.command("kill <sandboxId>").description("Kill a running sandbox"),p.command("clean").description("Clean up stopped/expired sandboxes from state file");let g=c.command("plugin").description("Manage CodeBuddy Code plugins");g.command("validate <path>").description("Validate a plugin or marketplace manifest"),g.command("list").alias("ls").option("--json","Output as JSON").description("List installed plugins");let h=g.command("marketplace").description("Manage CodeBuddy Code marketplaces");h.command("add <source>").option("-n, --name <name>","Marketplace name").description("Add a marketplace"),h.command("list").alias("ls").description("List all marketplaces"),h.command("update <name>").description("Update a marketplace"),h.command("remove <name>").alias("rm").description("Remove a marketplace"),g.command("install <plugin>").alias("i").option("-s, --scope <scope>","Install scope: user, project, or local","user").description("Install a plugin from available marketplaces (use plugin@marketplace for specific marketplace)"),g.command("uninstall <plugin>").aliases(["remove","rm"]).option("-s, --scope <scope>","Uninstall scope: user, project, or local","user").option("--prune","Also remove auto-installed dependencies that are no longer needed").option("--keep-data","Preserve plugin data after removing the final installed scope").option("-y, --yes","Skip the --prune confirmation prompt").description("Uninstall an installed plugin"),g.command("prune").aliases(["autoremove"]).option("-s, --scope <scope>","Prune at scope: user, project, or local","user").option("--dry-run","List what would be removed without removing").option("-y, --yes","Skip the confirmation prompt").description("Remove auto-installed dependencies that are no longer needed"),g.command("enable <plugin>").option("-s, --scope <scope>","Enable scope: user, project, or local (default: auto-detect)").description("Enable a disabled plugin"),g.command("disable <plugin>").option("-s, --scope <scope>","Disable scope: user, project, or local (default: auto-detect)").description("Disable an enabled plugin"),g.command("update <plugin>").option("-s, --scope <scope>","Update scope: user, project, or local","user").description("Update a plugin to the latest version (restart required to apply)"),c.command("doctor").description("Check the health of your CodeBuddy Code auto-updater"),c.command("update").description("Check for updates and install if available"),c.command("install [target]").description("Install CodeBuddy Code native build. Use [target] to specify version (latest, or specific version)");let m=c.command("daemon").description("Manage the daemon supervisor process");m.command("start").description("Start the daemon supervisor").option("--port <number>","Port for daemon HTTP server (default: auto)").option("--host <string>","Host address to bind (default: 127.0.0.1)"),m.command("stop").description("Stop the daemon supervisor").option("--keep-workers","Leave background session workers running; stop only the daemon itself",!1),m.command("status").description("Show daemon supervisor status"),m.command("restart").description("Restart the daemon supervisor"),m.command("install").description("Register daemon as a system service (auto-start on login)").option("--port <number>","Port for daemon HTTP server").option("--permission-mode <mode>","Permission mode for daemon sessions"),m.command("uninstall").description("Remove daemon system service registration"),c.command("ps").description("List all active sessions (interactive, background, daemon)").option("--json","Output in JSON format",!1),c.command("logs <pidOrName>").description("Show logs for a background session").option("-f, --follow","Follow log output",!1),c.command("attach <pidOrName>").description("Attach to a running background session"),c.command("kill <pidOrName>").description("Terminate a background session"),c.command("stop <pidOrName>").description("Stop a background session (alias for kill)"),c.command("rm <idOrName>").description("Remove a background session from agent view (the transcript stays on your machine)"),c.command("respawn [idOrName]").description("Restart a background session with its conversation intact").option("--all","Restart every running background session (e.g. after a binary update)"),c.command("agents").description("Open agent view to dispatch and manage background sessions").option("--jobs","Print sessions as a JSON array and exit",!1).option("--all","Include completed sessions in --jobs output",!1).option("--cwd <path>","Only list sessions started under this directory").option("--model <model>","Model used for sessions dispatched from agent view").option("--permission-mode <mode>","Permission mode for sessions dispatched from agent view").option("--agent <agent>","Default main agent for dispatched sessions");let f=c.command("auto-mode").description("Inspect auto mode classifier configuration");f.command("defaults").description("Print the built-in default auto mode rules as JSON"),f.command("config").description("Print the effective auto mode config as JSON (your settings where set, defaults otherwise)"),f.command("critique").description("Get AI feedback on your custom auto mode rules"),c.command("agents").description("List configured agents grouped by source (user, project, managed, plugin, cli-arg, built-in); requires --json").option("--json","Output as JSON",!1),c.on("command:*",e=>{});let y=class{constructor(){this.CURRENTLY_SUPPORTED_PATTERN=/ Currently supported: \([^)]*\)$/}async get(){if(this.isHelpRequested()){let sigintHandler=()=>process.exit(0);process.on("SIGINT",sigintHandler),await this.updateModelOptionDescription(),process.off("SIGINT",sigintHandler)}let e=process.env.ELECTRON_RUN_AS_NODE?"node":void 0;return c.parse(process.argv,e?{from:e}:void 0),c}parseOpts(){let e=c.args;return c.parseOptions(process.argv),{arg:e,opts:c.opts()}}isHelpRequested(){let e=process.argv;return e.includes("-h")||e.includes("--help")||e.includes("help")||e.some(e=>e.endsWith("--help")||e.endsWith("-h"))}async updateModelOptionDescription(){try{let e=c.options.find(e=>"--model"===e.long);if(!e)return;let t=new Promise((e,t)=>{let r=setTimeout(()=>t(Error("timeout")),1e4);"function"==typeof r.unref&&r.unref()}),r=o.ContainerUtil.get(n.AgentManager),i=await Promise.race([r.getDefault(),t]),s=await Promise.race([r.getModels(i.name),t]);if(0===s.length)return;let a=s.map(e=>e.id).join(", ");e.description=e.description.replace(this.CURRENTLY_SUPPORTED_PATTERN,""),e.description+=` Currently supported: (${a})`}catch{}}};y=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s}([(0,o.Component)(a.CliProvider)],y)},39432(e,t,r){r.r(t),r.d(t,{CLI_VIEW_NAME:()=>i,CliViewToken:()=>o});let o=Symbol("CliView"),i="cli"},98577(e,t,r){r.r(t),r.d(t,{DispatchChain:()=>c});var o,i,n=r(88523),s=r(56604),a=r(63295),l=r(16870),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let c=class{async execute(e){try{this.shortcutManager.register(a.KEY_CODES.CTRL_C,()=>{(0,s.exitWhenInPlaceWorkersSettled)(0)})}catch{}for(let t of this.strategyProvider.sortSync())if(t.canHandle(e)&&!1!==await t.execute(e))return}};__decorate([(0,n.AutowiredProvider)(l.DispatchStrategy),__metadata("design:type","function"==typeof(o=void 0!==n.Provider&&n.Provider)?o:Object)],c.prototype,"strategyProvider",void 0),__decorate([(0,n.Autowired)(a.ShortcutManager),__metadata("design:type","function"==typeof(i=void 0!==a.ShortcutManager&&a.ShortcutManager)?i:Object)],c.prototype,"shortcutManager",void 0),c=__decorate([(0,n.Component)()],c)},48855(e,t,r){r.r(t),r.d(t,{CLI_PROCESS_PERMISSION_MODES:()=>s.CLI_PROCESS_PERMISSION_MODES,CLI_VIEW_NAME:()=>f.CLI_VIEW_NAME,CliDispatcher:()=>o.CliDispatcher,CliDispatcherImpl:()=>n.CliDispatcherImpl,CliExecutor:()=>u.CliExecutor,CliProvider:()=>o.CliProvider,CliProviderImpl:()=>i.CliProviderImpl,CliRuntimeOptions:()=>s.CliRuntimeOptions,CliViewToken:()=>f.CliViewToken,DispatchChain:()=>d.DispatchChain,DispatchStrategy:()=>o.DispatchStrategy,InteractiveExecutor:()=>g.InteractiveExecutor,LLMView:()=>a.LLMView,LLM_VIEW_NAME:()=>a.LLM_VIEW_NAME,PrintDeliveryLifecycle:()=>h.PrintDeliveryLifecycle,PrintDeliveryLifecycleImpl:()=>h.PrintDeliveryLifecycleImpl,RewindFilesRunner:()=>p.RewindFilesRunner,TuiModeService:()=>y.TuiModeService,TuiModeServiceImpl:()=>y.TuiModeServiceImpl,ViewMessageFilter:()=>m.ViewMessageFilter,ViewMessageFilterPriority:()=>m.ViewMessageFilterPriority,pickCliProcessDefaults:()=>s.pickCliProcessDefaults,redactEnvValueForLog:()=>n.redactEnvValueForLog,resolveCliProcessDefaults:()=>s.resolveCliProcessDefaults});var o=r(16870),i=r(45443),n=r(20995),s=r(63831),a=r(49253),l=r(25137),c={};for(let e in l)0>["CliRuntimeOptions","CliDispatcherImpl","default","CLI_PROCESS_PERMISSION_MODES","pickCliProcessDefaults","CliDispatcher","resolveCliProcessDefaults","LLMView","redactEnvValueForLog","CliProvider","LLM_VIEW_NAME","DispatchStrategy","CliProviderImpl"].indexOf(e)&&(c[e]=()=>l[e]);r.d(t,c);var d=r(98577),u=r(79163),p=r(49205),g=r(82573),h=r(82136),m=r(95494),f=r(39432),y=r(96287)},82573(e,t,r){r.r(t),r.d(t,{InteractiveExecutor:()=>d});var o,i,n=r(88523),s=r(7268),a=r(6676),l=r(86045),c=r(13945),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let d=class{get startupProfiler(){return n.ContainerUtil.get(c.StartupProfiler)}async execute(e){try{this.restOperations=this.restOperationsFactory.create();let{endpointProvider:t,path:r,baseBody:o}=e,i=await t.get();await this.corsService?.setup(i);let n=`${i}${r}`;this.startupProfiler.markEnd(c.StartupPhase.READY),this.startupProfiler.isEnabled()&&this.consoleManager.debug(this.startupProfiler.formatReport(),{mode:a.ConsoleOutputMode.NATIVE}),await this.restOperations.post(n,{...o,interactive:!0},{headers:(0,l.withSecurityHeader)({[s.HttpHeaders.CONTENT_TYPE]:s.MediaType.APPLICATION_JSON_UTF8}),proxy:!1})}catch(t){let e;e=t.response?.data?"string"==typeof t.response.data?t.response.data:JSON.stringify(t.response.data):t instanceof Error?t.message:String(t),process.stdout.write(`${e}
|
|
32
32
|
`),process.exit(1)}}};__decorate([(0,n.Autowired)(s.RestOperationsFactory),__metadata("design:type","function"==typeof(o=void 0!==s.RestOperationsFactory&&s.RestOperationsFactory)?o:Object)],d.prototype,"restOperationsFactory",void 0),__decorate([(0,n.Autowired)(a.ConsoleManager),__metadata("design:type","function"==typeof(i=void 0!==a.ConsoleManager&&a.ConsoleManager)?i:Object)],d.prototype,"consoleManager",void 0),__decorate([(0,n.Autowired)(l.GatewayCorsService),(0,n.Optional)(),__metadata("design:type",Object)],d.prototype,"corsService",void 0),d=__decorate([(0,n.Component)()],d)},49253(e,t,r){r.r(t),r.d(t,{LLMView:()=>X,LLM_VIEW_NAME:()=>Q});var o,i,n,s,a,l,c,d,u,p,g,h,m,f,y,_,w,b,v,S=r(88523),A=r(7268),C=r(1309),E=r(703),I=r(14913),T=r(92735),P=r(93034),R=r(35061),k=r(87933),O=r(43698),M=r(90414),D=r(48400),N=r(41720),$=r(9151),x=r(79896),j=r(71332),U=r(79127),L=r(27436),F=r(10282),B=r(16602),W=r(83424),q=r(64045),H=r(69431),G=r(36023),J=r(82136),K=r(53319);async function enrichResultWithUsage(e,t,r,o,i){if(!e||"result"!==e.type)return e;try{let t=await buildModelUsage(r,o,i);t&&Object.keys(t).length>0&&(e.modelUsage=t)}catch(e){i?.warn?.(`[ResultUsageEnrich] build modelUsage failed for session ${t.id}: ${e?.message??e}`)}try{let o=await (0,K.buildSessionUsageUpdate)(t,r,i);if(o){let t={...e._meta??{}};t[K.META_KEY_CONTEXT_USED]=o.used,o.usageByCategory&&(t[K.META_KEY_CONTEXT_USAGE_BY_CATEGORY]=o.usageByCategory),e._meta=t}}catch(e){i?.warn?.(`[ResultUsageEnrich] build context usage _meta failed for session ${t.id}: ${e?.message??e}`)}return e}async function buildModelUsage(e,t,r){let o=t.getTokenUsageByModel(),i=Object.keys(o);if(0===i.length)return;let n=await buildModelConfigMap(e,r),s={};for(let e of i){let t=o[e],r=n.get(e);s[e]={inputTokens:t.inputTokens||0,outputTokens:t.outputTokens||0,cacheReadInputTokens:t.cachedReadTokens||0,cacheCreationInputTokens:t.cachedWriteTokens||0,contextWindow:r?.contextWindow??0,maxOutputTokens:r?.maxOutputTokens??0}}return s}async function buildModelConfigMap(e,t){let r=new Map;try{let t=await e.getDefault();for(let o of(await e.getModels(t.name))){let e={contextWindow:"number"==typeof o.maxInputTokens?o.maxInputTokens:0,maxOutputTokens:"number"==typeof o.maxOutputTokens?o.maxOutputTokens:0};o.id&&r.set(o.id,e),o.modelId&&r.set(o.modelId,e)}}catch(e){t?.warn?.(`[ResultUsageEnrich] resolve model config map failed: ${e?.message??e}`)}return r}var V=r(44371),__decorate=function(e,t,r,o){var i,n=arguments.length,s=n<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,r,o);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(s=(n<3?i(s):n>3?i(t,r,s):i(t,r))||s);return n>3&&s&&Object.defineProperty(t,r,s),s},__metadata=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};let Y=o=class{constructor(){this.contentType="text/event-stream",this.priority=500,this.transformHelpers=(0,V.createStreamJsonTransformHelpers)(),this.typeGuards=this.transformHelpers.typeGuards,this.streamEventConverter=new V.StreamEventConverter,this.taskEventDedup=new Map,this.shouldRehydrateBlobRefs="true"===process.env.CODEBUDDY_REHYDRATE_IMAGE_BLOB_REFS,this.blobRefReplacer=(e,t)=>null!==t&&"object"==typeof t&&"image_blob_ref"===t.type&&"string"==typeof t.blob_id?this.rehydrateBlobRef(t):"string"==typeof t&&t.includes('"image_blob_ref"')?this.rehydrateBlobRefsInString(t):t}getTaskEventDedup(e){let t=this.taskEventDedup.get(e);return t||(t={started:new Set,notified:new Set,lastProgressToolUses:new Map,lastUpdatedStatus:new Map,workflowTimelines:new Map,workflowAgentIndex:new Map,workflowPhaseIndex:new Map,workflowRunToTask:new Map},this.taskEventDedup.set(e,t)),t}handleWorkflowEvent(e,t,r,o){try{let t="workflow_run_started"===e.kind||"workflow_run_finished"===e.kind?e.record.runId:e.runId;if(!t)return;let i=S.ContainerUtil.get(M.ToolManager).getBackgroundTasks().find(e=>e.id===t);if(!i||"Workflow"!==i.toolName)return;let n=r.workflowTimelines.get(t)??[],s=!1;switch(e.kind){case"workflow_run_started":r.workflowTimelines.has(t)||r.workflowTimelines.set(t,n);return;case"workflow_phase_started":{let o=(r.workflowPhaseIndex.get(t)??0)+1;r.workflowPhaseIndex.set(t,o),n.push({type:"workflow_phase",index:o,title:e.phase}),s=!0;break}case"workflow_agent_started":{let o=(r.workflowAgentIndex.get(t)??0)+1;r.workflowAgentIndex.set(t,o);let i={type:"workflow_agent",index:o,agentId:e.agent.key,state:"start",startedAt:e.agent.startedAt,...void 0!==e.agent.label?{label:e.agent.label}:{},...void 0!==e.agent.phase?{phaseTitle:e.agent.phase}:{},...void 0!==r.workflowPhaseIndex.get(t)?{phaseIndex:r.workflowPhaseIndex.get(t)}:{}};n.push(i),s=!0;break}case"workflow_agent_finished":{let o=e.agent.key,i=n.findIndex(e=>"workflow_agent"===e.type&&e.agentId===o&&"done"!==e.state&&"error"!==e.state&&"cached"!==e.state),a=e.agent.error?"error":"done";if(i>=0){let t=n[i];n[i]={...t,state:a,...void 0!==e.agent.tokens?{tokens:e.agent.tokens}:{},...void 0!==e.agent.endedAt?{endedAt:e.agent.endedAt}:{}}}else{let o=(r.workflowAgentIndex.get(t)??0)+1;r.workflowAgentIndex.set(t,o),n.push({type:"workflow_agent",index:o,agentId:e.agent.key,state:a,startedAt:e.agent.startedAt,...void 0!==e.agent.endedAt?{endedAt:e.agent.endedAt}:{},...void 0!==e.agent.tokens?{tokens:e.agent.tokens}:{},...void 0!==e.agent.label?{label:e.agent.label}:{},...void 0!==e.agent.phase?{phaseTitle:e.agent.phase}:{}})}s=!0;break}case"workflow_agent_cached":{let o=(r.workflowAgentIndex.get(t)??0)+1;r.workflowAgentIndex.set(t,o),n.push({type:"workflow_agent",index:o,agentId:e.agent.key,state:"cached",startedAt:e.agent.startedAt,...void 0!==e.agent.endedAt?{endedAt:e.agent.endedAt}:{},...void 0!==e.agent.tokens?{tokens:e.agent.tokens}:{},...void 0!==e.agent.label?{label:e.agent.label}:{},...void 0!==e.agent.phase?{phaseTitle:e.agent.phase}:{}}),s=!0;break}case"workflow_phase_finished":case"workflow_run_finished":return}s&&(r.workflowTimelines.set(t,n),o(i))}catch(e){this.logger.warn?.("[StreamJsonView] handleWorkflowEvent failed:",e)}}init(){this.logger.setContext("StreamJsonView")}static resolveResultGate(e,t){return(0,k.getResultInterceptorGate)(e)??t}static isDuplicateResult(e,t){return(!e||!e.__cancelNudge)&&e===t}async render(e,t){let r=this.createOutputChannel(e);r.begin();let i=e.resultSubject.value,n=i.currentAgent,s=n.model.toString(),a=S.ContainerUtil.get(W.SettingsManager),l=await a.get("permissions")||{},c=e.permissionModeSubject.value||l?.defaultMode||W.PermissionMode.Default,d=new S.Deferred;if(!e.meta?.systemInitEmitted){let t=await this.createSystemMessage(e,n,s,c,i);r.next(t)}this.logger.info("inputSubscription");let u=e.progressSubject?.subscribe(t=>{try{let o="string"==typeof t&&("compacting"===t||t.includes("Compacting context")),i=void 0===t;if(!o&&!i)return;let n={type:"system",subtype:"status",status:o?"compacting":null,uuid:(0,S.generateUUUID)(),session_id:e.id};r.next(n)}catch(e){this.logger.warn?.("[StreamJsonView] Failed to forward progress status:",e)}}),p=this.getTaskEventDedup(e.id),emitTaskEvent=t=>{try{let o="completed"===t.status||"failed"===t.status||"killed"===t.status||"cancelled"===t.status;if(("running"===t.status||o)&&!p.started.has(t.id)){p.started.add(t.id);let o={type:"system",subtype:"task_started",task_id:t.id,...t.toolUseId?{tool_use_id:t.toolUseId}:{},description:t.description||t.title,task_type:"Workflow"===t.toolName?"local_workflow":t.toolName,..."Workflow"===t.toolName&&t.title?{workflow_name:t.title}:{},uuid:(0,S.generateUUUID)(),session_id:e.id};r.next(o),"Workflow"===t.toolName&&p.workflowRunToTask.set(t.id,t.id)}if(p.lastUpdatedStatus.get(t.id)!==t.status){p.lastUpdatedStatus.set(t.id,t.status);let i="cancelled"===t.status?"killed":t.status,n={status:i};o&&t.endTime&&(n.end_time=t.endTime);let s={type:"system",subtype:"task_updated",task_id:t.id,patch:n,status:i,uuid:(0,S.generateUUUID)(),session_id:e.id};r.next(s)}if("Workflow"===t.toolName){let o=p.workflowTimelines.get(t.id);if(o&&o.length>0){let i={type:"system",subtype:"task_progress",task_id:t.id,...t.toolUseId?{tool_use_id:t.toolUseId}:{},description:t.description||t.title,usage:this.buildTaskUsage(t),workflow_progress:o.slice(),uuid:(0,S.generateUUUID)(),session_id:e.id};r.next(i)}}else if(!o&&t.usage){let o=p.lastProgressToolUses.get(t.id)??-1;if(t.usage.toolUses>o){p.lastProgressToolUses.set(t.id,t.usage.toolUses);let o={type:"system",subtype:"task_progress",task_id:t.id,...t.toolUseId?{tool_use_id:t.toolUseId}:{},description:t.description||t.title,usage:this.buildTaskUsage(t),...t.lastToolName?{last_tool_name:t.lastToolName}:{},uuid:(0,S.generateUUUID)(),session_id:e.id};r.next(o)}}if(o&&!p.notified.has(t.id)){p.notified.add(t.id);let o="completed"===t.status?"completed":"failed"===t.status?"failed":"stopped",i={type:"system",subtype:"task_notification",task_id:t.id,...t.toolUseId?{tool_use_id:t.toolUseId}:{},status:o,summary:this.buildTaskEventSummary(t),...t.outputFilePath?{output_file:t.outputFilePath}:{},...t.outputStderrPath?{output_stderr_file:t.outputStderrPath}:{},...t.usage?{usage:this.buildTaskUsage(t)}:{},uuid:(0,S.generateUUUID)(),session_id:e.id};r.next(i)}}catch(e){this.logger.warn?.("[StreamJsonView] Failed to forward background task event:",e)}};try{for(let t of S.ContainerUtil.get(M.ToolManager).getBackgroundTasks())t.sessionId&&t.sessionId!==e.id||emitTaskEvent(t)}catch{}let g=e.backgroundTaskSubject?.subscribe({next:emitTaskEvent,complete:()=>this.taskEventDedup.delete(e.id)}),h=this.workflowProgressEmitter&&"function"==typeof this.workflowProgressEmitter.on?this.workflowProgressEmitter.on(t=>this.handleWorkflowEvent(t,e,p,emitTaskEvent)):void 0,m=!1,f=!1,y=null,_=null,w=null,flushPendingFilterable=()=>{if(!w)return;let e=w.writes;for(let t of(w=null,e))r.next(t)},b=e.combineSubject.subscribe(async t=>{if("model"===t.type){if(e.options.includePartialMessages){let o=t.data;for(let i of this.convertToClaudeStreamEvent(o))if(i){let o={type:"stream_event",event:i,session_id:e.id,parent_tool_use_id:t.parentToolUseId??null,uuid:(0,S.generateUUUID)()};r.next(o)}}}else if("input"===t.type){let o=t.data,n=o.providerData,s=n?.messageId;if(n?.contentFilterNotice){w&&w.messageId===s?w=null:flushPendingFilterable();let t=this.transformAgentInputItemToMessage(o,e,i);t&&r.next(t);return}if("file-history-snapshot"===o.type){flushPendingFilterable(),r.next(o);return}let a=this.extractAiTitleItem(o);if(a){flushPendingFilterable();let t={type:"ai-title",id:a.id,aiTitle:a.aiTitle,session_id:a.sessionId??e.id,providerData:a.providerData};r.next(t);return}let l=this.extractTopicItem(o);if(l){flushPendingFilterable();let t={type:"topic",id:l.id,topic:l.topic,session_id:e.id,providerData:l.providerData};r.next(t);return}let c=this.transformAgentInputItemToMessage(o,e,i);if(c){let i=t.parentToolUseId;if("message"===o.type&&"user"===c.type){if(flushPendingFilterable(),e.options.replayUserMessages&&D.InputItemUtils.isLiveStreamUserMessageItem(o)){let e={...c,isReplay:!0,...i&&{parent_tool_use_id:i}};r.next(e)}}else{let e=i&&("user"===c.type||"assistant"===c.type)?{...c,parent_tool_use_id:i}:c;"reasoning"===o.type||"message"===o.type&&"assistant"===c.type?(w&&w.messageId!==s&&flushPendingFilterable(),w||(w={messageId:s,writes:[]}),w.writes.push(e)):(flushPendingFilterable(),r.next(e))}}}else if("interrupt_result"===t.type){flushPendingFilterable();let t=e.permissionDenials?.map(e=>e.tool_name).join(", ")||"unknown",o=await this.createErrorResultMessage(e,Error(`Permission denied for tool(s): ${t}`));r.next(o),r.done(),r.end(),b.unsubscribe(),u?.unsubscribe(),g?.unsubscribe();try{h?.()}catch{}f=!0,d.resolve()}else if("result"===t.type){flushPendingFilterable();let n=t.data||i;if(!n||!D.RunResultUtils.isStream(n))return;if(m){if(o.isDuplicateResult(n,_))return;y=t;return}m=!0,_=n;let s=o.resolveResultGate(n,e.interceptorGate);this.completionWaiter&&await this.completionWaiter.waitForCompletion(e);let a=null;n.completed.catch(e=>{a=e}).finally(async()=>{if(s){let t=await s.completed,r=!!n.__cancelNudge;if(t&&!r){if(m=!1,_=null,y){let t=y;y=null,e.combineSubject.next(t)}return}}try{if(a)throw a;let t=N.ResultMessageUtils.findLastAssistantMessage(e.history);if(t&&D.InputItemUtils.isUserInterrupted(t)){let t=N.ResultMessageUtils.findLastCompletedAssistantMessage(e.history),o=await this.createResultMessage(e,t);r.next(o)}else{let t,o=n.state._lastTurnResponse;if(o?.output?.length)for(let r=o.output.length-1;r>=0;r--){let i=o.output[r],s=this.transformAgentInputItemToMessage(i,e,n);if(this.isCompleted(i,s)){t=i;break}}if(t||(t=N.ResultMessageUtils.findLastCompletedAssistantMessage(e.history)),!t&&void 0===e.structuredOutput){let e=JSON.stringify(n.state._currentStep?.type),t=n.state._modelResponses?.length,r=n.state._generatedItems?.length,o=n.state._originalInput?.length;throw this.logger.warn(`[StreamJsonView] _lastTurnResponse is empty. step=${e}, responses=${t}, items=${r}, input=${o}, isStream=${D.RunResultUtils.isStream(n)}, completedError=${a}`),Error("No response received from model")}let i=await this.createResultMessage(e,t);r.next(i)}}catch(o){this.logger.error(`Failed to create result message: ${D.ErrorUtils.getErrorMessage(o)}`);let t=await this.createErrorResultMessage(e,o);r.next(t)}try{let t=S.ContainerUtil.get(q.TerminalTitleUpdater),r=S.ContainerUtil.get(B.SessionTitleService),o=[t.getPendingTopicPromise(e.id),r.getPendingTitlePromise(e.id)].filter(e=>!!e);o.length>0&&await Promise.race([Promise.all(o),new Promise(e=>setTimeout(e,5e3))])}catch(e){this.logger.warn(`Failed to wait for title generation: ${D.ErrorUtils.getErrorMessage(e)}`)}r.done(),r.end(),b.unsubscribe(),u?.unsubscribe(),g?.unsubscribe();try{h?.()}catch{}f=!0,d.resolve()})}});return D.RunResultUtils.isStream(i)&&i.completed.then(()=>null,()=>null).then(()=>new Promise(e=>setTimeout(e,0))).then(()=>{f||m||e.combineSubject.next({type:"result",data:i})}),d.promise}support({viewName:e}){return Promise.resolve(!1)}renderEvent(e,t,r,o){return`event: ${e}
|
|
33
33
|
data: ${this.serializePayload(t,r,o)}
|
|
34
34
|
|