@opensumi/cli-engine 3.9.1-next-1788150617.0 → 3.9.1-next-1788263965.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39434,10 +39434,10 @@ Source session id: ${N.sourceSessionId}
39434
39434
  Digest source: ${N.digestSource}`}async function x(N,L){let B=N.getSessions(),K=w(B,L);if(K||(B=await N.getSessionsByAcp(),K=w(B,L)),!!K)return m(K)>0?K:await N.loadSessionModel(I(K))||K}function k(N){return{name:"acp_chat",description:"ACP chat session state, permission status, and safe chat UI controls",defaultLoaded:!0,tools:[{name:"acp_chat_get_session_state",description:"Get the active ACP chat session state without returning user prompts or assistant response content.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const L=(0,v.tryGetService)(N,r.IChatInternalService);if(!L)return(0,v.serviceUnavailableResult)("IChatInternalService");const B=(0,v.tryGetService)(N,_.AcpPermissionBridgeService);try{const K=L.sessionModel;return K?(0,v.successResult)({active:!0,session:S(K,B)}):(0,v.successResult)({active:!1,session:null})}catch(K){return(0,v.errorResult)((0,v.classifyError)(K),K)}}},{name:"acp_chat_get_permission_state",description:"Get ACP permission dialog counts and active session id. Does not approve, reject, or expose permission content.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const L=(0,v.tryGetService)(N,_.AcpPermissionBridgeService);if(!L)return(0,v.serviceUnavailableResult)("AcpPermissionBridgeService");try{return(0,v.successResult)({activeDialogCount:L.getActiveDialogCount(),activeSessionId:L.getActiveSession(),pendingCountExcludingActive:L.getPendingCountExcludingActive()})}catch(B){return(0,v.errorResult)((0,v.classifyError)(B),B)}}},{name:"acp_chat_show_chat_view",description:"Show the ACP chat view panel in the IDE.",riskLevel:"ui",inputSchema:{type:"object",properties:{}},execute:async()=>{const L=(0,v.tryGetService)(N,n.ChatServiceToken);if(!L)return(0,v.serviceUnavailableResult)("ChatService");try{return L.showChatView(),(0,v.successResult)({shown:!0})}catch(B){return(0,v.errorResult)((0,v.classifyError)(B),B)}}},{name:"acp_chat_list_sessions",description:"List ACP chat sessions newest first as metadata only. Does not return prompts, responses, or tool-call contents.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{}},execute:async()=>{const L=(0,v.tryGetService)(N,r.IChatInternalService);if(!L)return(0,v.serviceUnavailableResult)("IChatInternalService");const B=(0,v.tryGetService)(N,_.AcpPermissionBridgeService);try{const K=await L.getSessionsByAcp(),W=y(K);return(0,v.successResult)({sessions:W.map(U=>S(U,B)),total:K.length})}catch(K){return(0,v.errorResult)((0,v.classifyError)(K),K)}}},{name:"acp_chat_get_available_commands",description:"Get available ACP slash commands for the active chat session.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{}},execute:async()=>{const L=(0,v.tryGetService)(N,r.IChatInternalService);if(!L)return(0,v.serviceUnavailableResult)("IChatInternalService");try{const B=L.getAvailableCommands();return(0,v.successResult)({commands:B.map(K=>({name:K.name,description:K.description||""})),total:B.length})}catch(B){return(0,v.errorResult)((0,v.classifyError)(B),B)}}},{name:"acp_chat_prepare_session_digest",description:"Prepare a bounded background digest for another ACP chat session. Returns only digest metadata and a short preview; the full digest stays in the browser relay store.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{sourceSessionId:{type:"string",description:"ACP session id to summarize. Accepts either acp:<id> or raw <id>."},maxSourceChars:{type:"number",description:"Maximum source characters used by the background summarizer. Default 12000, cap 30000."},maxDigestChars:{type:"number",description:"Maximum digest characters stored for relay. Default 2000, cap 6000."}},required:["sourceSessionId"],additionalProperties:!1},execute:async L=>{var B,K,W,U,G,j;const Y=typeof L.sourceSessionId=="string"?L.sourceSessionId:"";if(!Y)return(0,v.errorResult)("INVALID_INPUT",new Error("sourceSessionId is required"));const z=(0,v.tryGetService)(N,r.IChatInternalService);if(!z)return(0,v.serviceUnavailableResult)("IChatInternalService");const V=(0,v.tryGetService)(N,c.AcpChatRelaySummaryProvider);if(!V)return(0,v.serviceUnavailableResult)("AcpChatRelaySummaryProvider");const $=(0,v.tryGetService)(N,o.AcpChatRelayStore);if(!$)return(0,v.serviceUnavailableResult)("AcpChatRelayStore");const H=(0,v.tryGetService)(N,n.ILogger);try{const Q=Date.now();(B=H?.log)===null||B===void 0||B.call(H,`[WebMCP][acp_chat] prepareSessionDigest start \u2014 requestedSourceSessionId=${g(Y)}, maxSourceChars=${(K=L.maxSourceChars)!==null&&K!==void 0?K:"default"}, maxDigestChars=${(W=L.maxDigestChars)!==null&&W!==void 0?W:"default"}`);const Z=await x(z,Y);if(!Z)return(U=H?.warn)===null||U===void 0||U.call(H,`[WebMCP][acp_chat] prepareSessionDigest miss \u2014 requestedSourceSessionId=${g(Y)}, reason=session_not_found, durationMs=${Date.now()-Q}`),(0,v.errorResult)("FILE_NOT_FOUND",new Error(`ACP session "${Y}" not found`));const te=await V.prepareSessionDigest(Z,{maxSourceChars:L.maxSourceChars,maxDigestChars:L.maxDigestChars}),ie=I(Z),ce=$.put({sourceSessionId:ie,sourceTitle:T(Z),digestSource:te.digestSource,digest:te.digest,sourceChars:te.sourceChars,digestChars:te.digestChars,sourceTruncated:te.sourceTruncated});return(G=H?.log)===null||G===void 0||G.call(H,`[WebMCP][acp_chat] prepareSessionDigest \u2014 sourceSessionId=${g(ie)}, digestId=${ce.digestId}, digestSource=${te.digestSource}, historyMessages=${m(Z)}, memorySummaries=${h(Z)}, sourceChars=${te.sourceChars}, digestChars=${te.digestChars}, sourceTruncated=${te.sourceTruncated}, expiresInMs=${ce.expiresAt-ce.createdAt}, durationMs=${Date.now()-Q}`),(0,v.successResult)({digestId:ce.digestId,sourceSessionId:ie,sourceTitle:ce.sourceTitle,digestSource:ce.digestSource,preview:R(ce.digest,p),digestChars:ce.digestChars,sourceChars:ce.sourceChars,sourceTruncated:ce.sourceTruncated,expiresAt:ce.expiresAt})}catch(Q){return(j=H?.warn)===null||j===void 0||j.call(H,`[WebMCP][acp_chat] prepareSessionDigest error \u2014 requestedSourceSessionId=${g(Y)}, errorName=${Q instanceof Error?Q.name:typeof Q}`),(0,v.errorResult)((0,v.classifyError)(Q),Q)}}},{name:"acp_chat_post_prepared_relay",description:"Post a previously prepared ACP chat digest to a target ACP session after explicit user permission.",riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{digestId:{type:"string",description:"Digest id returned by acp_chat_prepare_session_digest."},targetSessionId:{type:"string",description:"ACP session id to receive the relay message. Accepts either acp:<id> or raw <id>."}},required:["digestId","targetSessionId"],additionalProperties:!1},execute:async L=>{var B,K,W,U,G,j,Y,z,V,$,H,Q,Z;const te=typeof L.digestId=="string"?L.digestId:"",ie=typeof L.targetSessionId=="string"?L.targetSessionId:"";if(!te||!ie)return(0,v.errorResult)("INVALID_INPUT",new Error("digestId and targetSessionId are required"));const ce=(0,v.tryGetService)(N,r.IChatInternalService);if(!ce)return(0,v.serviceUnavailableResult)("IChatInternalService");const me=(0,v.tryGetService)(N,n.ChatServiceToken);if(!me)return(0,v.serviceUnavailableResult)("ChatService");const q=(0,v.tryGetService)(N,_.AcpPermissionBridgeService);if(!q)return(0,v.serviceUnavailableResult)("AcpPermissionBridgeService");const be=(0,v.tryGetService)(N,o.AcpChatRelayStore);if(!be)return(0,v.serviceUnavailableResult)("AcpChatRelayStore");const fe=(0,v.tryGetService)(N,n.ILogger);try{const ne=Date.now();(B=fe?.log)===null||B===void 0||B.call(fe,`[WebMCP][acp_chat] postPreparedRelay start \u2014 digestId=${te}, requestedTargetSessionId=${g(ie)}`);const ge=be.get(te);if(!ge)return(K=fe?.warn)===null||K===void 0||K.call(fe,`[WebMCP][acp_chat] postPreparedRelay miss \u2014 digestId=${te}, requestedTargetSessionId=${g(ie)}, reason=digest_not_found_or_expired, durationMs=${Date.now()-ne}`),(0,v.errorResult)("FILE_NOT_FOUND",new Error(`Relay digest "${te}" not found or expired`));if(!ge.digest)return(W=fe?.warn)===null||W===void 0||W.call(fe,`[WebMCP][acp_chat] postPreparedRelay miss \u2014 digestId=${te}, sourceSessionId=${g(ge.sourceSessionId)}, reason=empty_digest, durationMs=${Date.now()-ne}`),(0,v.errorResult)("INVALID_INPUT",new Error(`Relay digest "${te}" is empty`));let Oe=ce.getSessions(),Pe=w(Oe,ie);if(Pe||(Oe=await ce.getSessionsByAcp(),Pe=w(Oe,ie)),!Pe)return(U=fe?.warn)===null||U===void 0||U.call(fe,`[WebMCP][acp_chat] postPreparedRelay miss \u2014 digestId=${te}, sourceSessionId=${g(ge.sourceSessionId)}, requestedTargetSessionId=${g(ie)}, reason=target_session_not_found, durationMs=${Date.now()-ne}`),(0,v.errorResult)("FILE_NOT_FOUND",new Error(`Target ACP session "${ie}" not found`));const Me=(G=ce.sessionModel)===null||G===void 0?void 0:G.sessionId,ke=I(Pe),De=!E(Me,ke),pe=O({sourceSessionId:ge.sourceSessionId,sourceTitle:ge.sourceTitle,digest:R(ge.digest,a),digestSource:ge.digestSource}),Ie=`${g(Me)||"acp_chat"}:relay:${(0,n.uuid)(8)}`,Ae=Date.now();(j=fe?.log)===null||j===void 0||j.call(fe,`[WebMCP][acp_chat] postPreparedRelay permission request \u2014 digestId=${te}, requestId=${Ie}, sourceSessionId=${g(ge.sourceSessionId)}, targetSessionId=${g(ke)}, digestChars=${ge.digestChars}, switchedSession=${De}`);const xe=await q.showPermissionDialog({requestId:Ie,sessionId:g(Me)||g(ke)||"acp_chat",title:"Forward ACP chat digest",kind:"write",content:[`Source: ${ge.sourceTitle||ge.sourceSessionId}`,`Target: ${T(Pe)} (${ke})`,`Digest chars: ${ge.digestChars}`,`Temporary session switch: ${De?"yes":"no"}`,"",R(ge.digest,f)].join(`
39435
39435
  `),options:[{optionId:"allow_once",name:"Allow Once",kind:"allow_once"},{optionId:"reject",name:"Reject",kind:"reject_once"}]});if((Y=fe?.log)===null||Y===void 0||Y.call(fe,`[WebMCP][acp_chat] postPreparedRelay permission result \u2014 digestId=${te}, requestId=${Ie}, decision=${xe.type}, optionId=${"optionId"in xe?xe.optionId:""}, durationMs=${Date.now()-Ae}`),xe.type!=="allow")return(z=fe?.warn)===null||z===void 0||z.call(fe,`[WebMCP][acp_chat] postPreparedRelay denied \u2014 digestId=${te}, requestId=${Ie}, decision=${xe.type}, durationMs=${Date.now()-ne}`),{success:!1,error:"PERMISSION_DENIED",details:`Relay rejected or cancelled: ${xe.type}`};try{De&&((V=fe?.log)===null||V===void 0||V.call(fe,`[WebMCP][acp_chat] postPreparedRelay session switch \u2014 digestId=${te}, fromSessionId=${g(Me)}, toSessionId=${g(ke)}`),await ce.activateSession(ke));const _e={message:pe,immediate:!0};me.sendMessage(_e),($=fe?.log)===null||$===void 0||$.call(fe,`[WebMCP][acp_chat] postPreparedRelay message sent \u2014 digestId=${te}, targetSessionId=${g(ke)}, messageChars=${pe.length}`),be.delete(te)}finally{De&&Me&&(await ce.activateSession(Me),(H=fe?.log)===null||H===void 0||H.call(fe,`[WebMCP][acp_chat] postPreparedRelay session restored \u2014 digestId=${te}, restoredSessionId=${g(Me)}`))}return(Q=fe?.log)===null||Q===void 0||Q.call(fe,`[WebMCP][acp_chat] postPreparedRelay \u2014 digestId=${te}, sourceSessionId=${g(ge.sourceSessionId)}, targetSessionId=${g(ke)}, digestSource=${ge.digestSource}, digestChars=${ge.digestChars}, switchedSession=${De}, durationMs=${Date.now()-ne}`),(0,v.successResult)({posted:!0,digestId:te,sourceSessionId:ge.sourceSessionId,targetSessionId:ke,digestChars:ge.digestChars,switchedSession:De})}catch(ne){return(Z=fe?.warn)===null||Z===void 0||Z.call(fe,`[WebMCP][acp_chat] postPreparedRelay error \u2014 digestId=${te}, requestedTargetSessionId=${g(ie)}, errorName=${ne instanceof Error?ne.name:typeof ne}`),(0,v.errorResult)((0,v.classifyError)(ne),ne)}}},{name:"acp_chat_read_session_messages",description:"Read bounded recent user/assistant message previews from an ACP session. Full-profile debug fallback only.",riskLevel:"read",profiles:["full"],inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"ACP session id to read. Accepts either acp:<id> or raw <id>."},maxMessages:{type:"number",description:"Maximum recent messages to return. Default 10, cap 30."},maxChars:{type:"number",description:"Maximum total preview characters. Default 4000, cap 12000."},sinceRequestId:{type:"string",description:"Optional request id lower bound. Messages before this request id are skipped."}},required:["sessionId"],additionalProperties:!1},execute:async L=>{const B=typeof L.sessionId=="string"?L.sessionId:"";if(!B)return(0,v.errorResult)("INVALID_INPUT",new Error("sessionId is required"));const K=(0,v.tryGetService)(N,r.IChatInternalService);if(!K)return(0,v.serviceUnavailableResult)("IChatInternalService");try{const W=await x(K,B);if(!W)return(0,v.errorResult)("FILE_NOT_FOUND",new Error(`ACP session "${B}" not found`));const U=D(L.maxMessages,u,s),G=D(L.maxChars,l,d),j=typeof L.sinceRequestId=="string"?L.sinceRequestId:void 0;let Y=M(W);if(j){const Q=Y.findIndex(Z=>Z.requestId===j);Q>=0&&(Y=Y.slice(Q+1))}let z=0,V=Y.length>U;const $=[],H=Y.slice(-U);for(const Q of H){const Z=Math.max(G-z,0);if(Z<=0){V=!0;break}const te=R(Q.content||"",Z);z+=te.length;const ie=te.length<(Q.content||"").length;ie&&(V=!0),$.push({role:Q.role===1?"user":"assistant",contentPreview:te,chars:(Q.content||"").length,truncated:ie})}return(0,v.successResult)({sessionId:I(W),title:T(W),requestCount:b(W),historyMessageCount:m(W),messages:$,truncated:V})}catch(W){return(0,v.errorResult)((0,v.classifyError)(W),W)}}},{name:"acp_chat_set_session_mode",description:"Switch the active ACP session mode. This changes agent behavior and is only available in the full WebMCP profile.",riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{modeId:{type:"string",description:"ACP session mode id, for example agent or chat."}},required:["modeId"],additionalProperties:!1},execute:async L=>{const B=typeof L.modeId=="string"?L.modeId:"";if(!B)return(0,v.errorResult)("INVALID_INPUT",new Error("modeId is required"));const K=(0,v.tryGetService)(N,r.IChatInternalService);if(!K)return(0,v.serviceUnavailableResult)("IChatInternalService");try{return await K.setSessionMode(B),(0,v.successResult)({modeId:B})}catch(W){return(0,v.errorResult)((0,v.classifyError)(W),W)}}}]}}},32815:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createDiagnosticsGroup=d;const n=e(43718),r=e(54414),o=e(55126),c=e(51500),_=e(67741),v=100,p=500;function f(g,E,m){return Math.min(Math.max(Number(g)||E,1),m)}function a(g){if(typeof g!="string"||g==="all")return;const E=g.toLowerCase();if(E==="error")return n.MarkerSeverity.Error;if(E==="warning")return n.MarkerSeverity.Warning;if(E==="info")return n.MarkerSeverity.Info;if(E==="hint")return n.MarkerSeverity.Hint}function u(g){return g===n.MarkerSeverity.Error?"error":g===n.MarkerSeverity.Warning?"warning":g===n.MarkerSeverity.Info?"info":"hint"}function s(g){return{errors:Number(g.errors)||0,warnings:Number(g.warnings)||0,infos:Number(g.infos)||0,unknowns:Number(g.unknowns)||0}}function l(g,E){if(E.startsWith("file://"))return E;if(E.startsWith("/"))return n.URI.file(E).toString();const m=g?.tryGetRoots()[0];if(!m)return n.URI.file(E).toString();const h=n.URI.parse(m.uri).codeUri.fsPath;return n.URI.file(`${h}/${E}`.replace(/\/+/g,"/")).toString()}function d(g){return{name:"diagnostics",description:"IDE diagnostics and problem navigation",defaultLoaded:!0,tools:[{name:"diagnostics_list",description:"List current IDE diagnostics. Use this after edits or validation commands to inspect errors and warnings.",riskLevel:"read",inputSchema:{type:"object",properties:{path:{type:"string",description:"Optional file path or file URI to filter diagnostics."},severity:{type:"string",enum:["all","error","warning","info","hint"],description:"Optional severity filter. Defaults to all."},maxResults:{type:"number",description:"Maximum diagnostics to return. Defaults to 100, capped at 500."}}},execute:async E=>{const m=(0,_.tryGetService)(g,o.IMarkerService);if(!m)return(0,_.serviceUnavailableResult)("IMarkerService");const h=(0,_.tryGetService)(g,c.IWorkspaceService);try{const b=f(E.maxResults,v,p),A=typeof E.path=="string"&&E.path?l(h,E.path):void 0,y=m.getManager().getMarkers({resource:A,severities:a(E.severity),take:b}),S=y.map(w=>({type:w.type,uri:w.resource,path:n.URI.parse(w.resource).codeUri.fsPath,severity:u(w.severity),message:w.message,source:w.source,code:w.code,startLine:w.startLineNumber,startColumn:w.startColumn,endLine:w.endLineNumber,endColumn:w.endColumn}));return(0,_.successResult)({diagnostics:S,stats:s(m.getManager().getStats()),total:S.length,truncated:y.length>=b})}catch(b){return(0,_.errorResult)((0,_.classifyError)(b),b)}}},{name:"diagnostics_get_stats",description:"Get diagnostic counts by severity for the current workspace.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const E=(0,_.tryGetService)(g,o.IMarkerService);if(!E)return(0,_.serviceUnavailableResult)("IMarkerService");try{return(0,_.successResult)(s(E.getManager().getStats()))}catch(m){return(0,_.errorResult)((0,_.classifyError)(m),m)}}},{name:"diagnostics_open",description:"Open a file and reveal the given diagnostic location.",riskLevel:"ui",inputSchema:{type:"object",properties:{path:{type:"string",description:"File path or file URI to open."},line:{type:"number",description:"Line number to reveal, 1-based."},column:{type:"number",description:"Column number to reveal, 1-based. Defaults to 1."}},required:["path","line"]},execute:async E=>{const m=typeof E.path=="string"?E.path:"",h=Number(E.line);if(!m||!h||h<1)return(0,_.errorResult)("INVALID_INPUT",new Error("path and positive line are required"));const b=(0,_.tryGetService)(g,c.IWorkspaceService),A=(0,_.tryGetService)(g,r.WorkbenchEditorService);if(!A)return(0,_.serviceUnavailableResult)("WorkbenchEditorService");try{const y=n.URI.parse(l(b,m)),S=Math.max(Number(E.column)||1,1);return await A.open(y,{range:{startLineNumber:h,startColumn:S,endLineNumber:h,endColumn:S},revealRangeInCenter:!0}),(0,_.successResult)({path:y.codeUri.fsPath,line:h,column:S,opened:!0})}catch(y){return(0,_.errorResult)((0,_.classifyError)(y),y)}}}]}}},74296:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createEditorGroup=E;const n=e(41869),r=e(43718),o=e(54414),c=e(96689),_=e(14951),v=e(67741),p=e(21727);function f(m){const h=m.currentEditor;if(!h)return null;const b=h.currentUri,A=h.getSelections(),y=A&&A.length>0?A[0]:null;return{path:b?b.codeUri.fsPath:null,uri:b?b.toString():null,selection:y?{startLine:y.selectionStartLineNumber,startCol:y.selectionStartColumn,endLine:y.positionLineNumber,endCol:y.positionColumn}:null}}function a(m,h){if(h.startsWith("file://"))return r.URI.parse(h);if(h.startsWith("/"))return r.URI.file(h);const b=(0,v.tryGetService)(m,n.AppConfig),A=b?.workspaceDir;return r.URI.file(A?`${A}/${h}`.replace(/\/+/g,"/"):h)}function u(m){return(0,v.errorResult)("INVALID_INPUT",new Error(m))}async function s(m,h,b){const A=(0,v.tryGetService)(m,n.AppConfig);if(!A||!A.workspaceDir)return{ok:!1,result:(0,v.serviceUnavailableResult)("AppConfig")};const y=(0,v.tryGetService)(m,_.IFileServiceClient);if(!y)return{ok:!1,result:(0,v.serviceUnavailableResult)("IFileServiceClient")};const S=(0,p.resolveWorkspaceFilePath)(A.workspaceDir,h);if(!S.ok)return{ok:!1,result:u(S.message)};const w=b==="write"?await(0,p.validateWritableWorkspaceTarget)(y,A.workspaceDir,S.value):await(0,p.validateWorkspacePathAccess)(y,A.workspaceDir,S.value);return w.ok?{ok:!0,uri:r.URI.file(S.value.absolutePath),absolutePath:S.value.absolutePath}:{ok:!1,result:u(w.message)}}function l(m,h,b){return Math.min(Math.max(Number(m)||h,1),b)}async function d(m,h,b){const A=(0,v.tryGetService)(m,c.IEditorDocumentModelService);if(!A)return null;const y=A.getModelReference(h,"webmcp");if(y)try{return await b(y.instance)}finally{y.dispose()}const S=await A.createModelReference(h,"webmcp");try{return await b(S.instance)}finally{S.dispose()}}function g(m,h,b){const A=m.split(/\r?\n/),y=h.split(/\r?\n/);let S=0;for(;S<A.length&&S<y.length&&A[S]===y[S];)S++;let w=0;for(;w+S<A.length&&w+S<y.length&&A[A.length-1-w]===y[y.length-1-w];)w++;const T=A.slice(S,A.length-w),I=y.slice(S,y.length-w),D=[`@@ -${S+1},${T.length} +${S+1},${I.length} @@`,...T.map(R=>`-${R}`),...I.map(R=>`+${R}`)];return{diff:D.slice(0,b).join(`
39436
39436
  `),truncated:D.length>b}}function E(m){return{name:"editor",description:"\u7F16\u8F91\u5668\u64CD\u4F5C\uFF08\u6253\u5F00\u3001\u5173\u95ED\u3001\u8DF3\u8F6C\u3001\u683C\u5F0F\u5316\u7B49\uFF09",defaultLoaded:!0,tools:[{name:"editor_open",description:"Open a file in the editor. Optionally specify a line and column to scroll to. Returns the editor info for the opened file.",riskLevel:"ui",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute or workspace-relative path of the file to open."},line:{type:"number",description:"The line number to scroll to (1-based)."},column:{type:"number",description:"The column number to scroll to (1-based)."}},required:["path"]},execute:async h=>{const b=h.path;if(!b)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required"));const A=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!A)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const y=r.URI.file(b),S={},w=h.line,T=h.column;w!==void 0&&(S.range={startLineNumber:w,startColumn:T??1,endLineNumber:w,endColumn:T??1},S.revealRangeInCenter=!0),await A.open(y,S);const I=f(A);return(0,v.successResult)({path:b,editor:I})}catch(y){return(0,v.errorResult)((0,v.classifyError)(y),y)}}},{name:"editor_close",description:"Close the editor tab for the given file path.",riskLevel:"ui",profiles:["interactive","full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute or workspace-relative path of the file to close."}},required:["path"]},execute:async h=>{const b=h.path;if(!b)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required"));const A=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!A)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const y=r.URI.file(b);return await A.close(y),(0,v.successResult)({path:b,closed:!0})}catch(y){return(0,v.errorResult)((0,v.classifyError)(y),y)}}},{name:"editor_get_active",description:"Get information about the currently active editor, including file path and selection range.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const h=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!h)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const b=f(h);return b?(0,v.successResult)({...b,active:!0}):(0,v.successResult)({path:null,selection:null,active:!1})}catch(b){return(0,v.errorResult)((0,v.classifyError)(b),b)}}},{name:"editor_list_open_files",description:"List files currently opened in editor groups, including dirty and active state.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{var h,b;const A=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!A)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");const y=(0,v.tryGetService)(m,c.IEditorDocumentModelService);try{const S=(b=(h=A.currentEditor)===null||h===void 0?void 0:h.currentUri)===null||b===void 0?void 0:b.toString(),w=A.editorGroups.flatMap((T,I)=>T.resources.map(D=>{const R=y?.getModelReference(D.uri,"webmcp");try{const M=R?.instance;return{uri:D.uri.toString(),path:D.uri.codeUri.fsPath,name:D.name,groupIndex:I,active:D.uri.toString()===S,dirty:!!M?.dirty,languageId:M?.languageId}}finally{R?.dispose()}}));return(0,v.successResult)({files:w,total:w.length})}catch(S){return(0,v.errorResult)((0,v.classifyError)(S),S)}}},{name:"editor_get_selection",description:"Get the active editor selection range and selected text.",riskLevel:"read",inputSchema:{type:"object",properties:{maxChars:{type:"number",description:"Maximum selected characters to return. Defaults to 20000, capped at 100000."}}},execute:async h=>{var b,A,y;const S=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!S)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const w=S.currentEditor,T=w?.currentUri,I=(b=w?.getSelections())===null||b===void 0?void 0:b[0];if(!w||!T||!I)return(0,v.successResult)({active:!1,selection:null,text:""});const D=l(h.maxChars,2e4,1e5),R=(y=(A=w.currentDocumentModel)===null||A===void 0?void 0:A.getText({startLineNumber:I.selectionStartLineNumber,startColumn:I.selectionStartColumn,endLineNumber:I.positionLineNumber,endColumn:I.positionColumn}))!==null&&y!==void 0?y:"";return(0,v.successResult)({active:!0,uri:T.toString(),path:T.codeUri.fsPath,selection:{startLine:I.selectionStartLineNumber,startColumn:I.selectionStartColumn,endLine:I.positionLineNumber,endColumn:I.positionColumn},text:R.slice(0,D),truncated:R.length>D})}catch(w){return(0,v.errorResult)((0,v.classifyError)(w),w)}}},{name:"editor_read_buffer",description:"Read an editor buffer, including unsaved content. Defaults to the active editor.",riskLevel:"read",inputSchema:{type:"object",properties:{path:{type:"string",description:"Optional file path or file URI. Defaults to the active editor."},maxChars:{type:"number",description:"Maximum characters to return. Defaults to 100000, capped at 500000."}}},execute:async h=>{var b;const A=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!A)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const y=typeof h.path=="string"&&h.path?a(m,h.path):(b=A.currentEditor)===null||b===void 0?void 0:b.currentUri;if(!y)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required when no active editor exists"));const S=l(h.maxChars,1e5,5e5),w=await d(m,y,T=>{const I=T.getText();return{uri:y.toString(),path:y.codeUri.fsPath,languageId:T.languageId,dirty:T.dirty,text:I.slice(0,S),size:I.length,truncated:I.length>S}});return w?(0,v.successResult)(w):(0,v.serviceUnavailableResult)("IEditorDocumentModelService")}catch(y){return(0,v.errorResult)((0,v.classifyError)(y),y)}}},{name:"editor_read_range_from_buffer",description:"Read a line range from an editor buffer, including unsaved content.",riskLevel:"read",inputSchema:{type:"object",properties:{path:{type:"string",description:"Optional file path or file URI. Defaults to the active editor."},startLine:{type:"number",description:"Start line, 1-based."},endLine:{type:"number",description:"End line, 1-based. Defaults to startLine."},maxChars:{type:"number",description:"Maximum characters to return. Defaults to 50000, capped at 200000."}},required:["startLine"]},execute:async h=>{var b;const A=Number(h.startLine),y=Number(h.endLine)||A;if(!A||A<1||y<A)return(0,v.errorResult)("INVALID_INPUT",new Error("valid startLine and endLine are required"));const S=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!S)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const w=typeof h.path=="string"&&h.path?a(m,h.path):(b=S.currentEditor)===null||b===void 0?void 0:b.currentUri;if(!w)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required when no active editor exists"));const T=l(h.maxChars,5e4,2e5),I=await d(m,w,D=>{const R=D.getMonacoModel().getLineCount();if(A>R)return{uri:w.toString(),path:w.codeUri.fsPath,startLine:A,endLine:R,lineCount:R,text:"",truncated:!1};const M=Math.min(y,R),O=D.getText({startLineNumber:A,startColumn:1,endLineNumber:M,endColumn:D.getMonacoModel().getLineMaxColumn(M)});return{uri:w.toString(),path:w.codeUri.fsPath,startLine:A,endLine:M,lineCount:R,text:O.slice(0,T),truncated:O.length>T}});return I?(0,v.successResult)(I):(0,v.serviceUnavailableResult)("IEditorDocumentModelService")}catch(w){return(0,v.errorResult)((0,v.classifyError)(w),w)}}},{name:"editor_list_dirty_files",description:"List unsaved editor buffers.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const h=(0,v.tryGetService)(m,c.IEditorDocumentModelService);if(!h)return(0,v.serviceUnavailableResult)("IEditorDocumentModelService");try{const b=h.getAllModels().filter(A=>A.dirty).map(A=>({uri:A.uri.toString(),path:A.uri.codeUri.fsPath,languageId:A.languageId,savable:A.savable,readonly:A.readonly}));return(0,v.successResult)({files:b,total:b.length})}catch(b){return(0,v.errorResult)((0,v.classifyError)(b),b)}}},{name:"editor_get_dirty_diff",description:"Return a compact diff between disk content and an unsaved editor buffer.",riskLevel:"read",inputSchema:{type:"object",properties:{path:{type:"string",description:"Optional file path or file URI. Defaults to the active editor."},maxLines:{type:"number",description:"Maximum diff lines to return. Defaults to 200, capped at 1000."}}},execute:async h=>{var b;const A=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!A)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");const y=(0,v.tryGetService)(m,_.IFileServiceClient);if(!y)return(0,v.serviceUnavailableResult)("IFileServiceClient");try{const S=typeof h.path=="string"&&h.path?a(m,h.path):(b=A.currentEditor)===null||b===void 0?void 0:b.currentUri;if(!S)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required when no active editor exists"));const w=l(h.maxLines,200,1e3),I=await y.getFileStat(S.toString())?(await y.readFile(S.toString())).content.toString():"",D=await d(m,S,R=>{const M=R.getText(),{diff:O,truncated:x}=g(I,M,w);return{uri:S.toString(),path:S.codeUri.fsPath,dirty:R.dirty,diff:O,truncated:x}});return D?(0,v.successResult)(D):(0,v.serviceUnavailableResult)("IEditorDocumentModelService")}catch(S){return(0,v.errorResult)((0,v.classifyError)(S),S)}}},{name:"editor_set_selection",description:"Set the selection range in the editor. Opens the file first if it is not already open, then sets the selection to the specified line range.",riskLevel:"ui",inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute or workspace-relative path of the file."},startLine:{type:"number",description:"The start line of the selection (1-based)."},endLine:{type:"number",description:"The end line of the selection (1-based). Defaults to startLine if omitted."}},required:["path","startLine"]},execute:async h=>{var b;const A=h.path,y=h.startLine,S=(b=h.endLine)!==null&&b!==void 0?b:y;if(!A)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required"));if(!y||y<1)return(0,v.errorResult)("INVALID_INPUT",new Error("startLine must be a positive number"));const w=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!w)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const T=r.URI.file(A);return await w.open(T,{range:{startLineNumber:y,startColumn:1,endLineNumber:S,endColumn:1},revealRangeInCenter:!0}),(0,v.successResult)({path:A,startLine:y,endLine:S})}catch(T){return(0,v.errorResult)((0,v.classifyError)(T),T)}}},{name:"editor_format",description:"Format the document at the given path using the editor format command.",riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute or workspace-relative path of the file to format."}},required:["path"]},execute:async h=>{const b=h.path;if(!b)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required"));const A=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!A)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");const y=(0,v.tryGetService)(m,r.CommandService);if(!y)return(0,v.serviceUnavailableResult)("CommandService");try{const S=await s(m,b,"write");if(!S.ok)return S.result;const w=S.uri;return await A.open(w,{focus:!0}),await y.executeCommand("editor.action.formatDocument"),(0,v.successResult)({path:S.absolutePath,formatted:!0})}catch(S){return(0,v.errorResult)((0,v.classifyError)(S),S)}}},{name:"editor_fold",description:"Fold code at the specified line in the editor. Opens the file first if needed.",riskLevel:"ui",profiles:["interactive","full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute or workspace-relative path of the file."},startLine:{type:"number",description:"The line number at which to fold code (1-based)."}},required:["path","startLine"]},execute:async h=>{const b=h.path,A=h.startLine;if(!b)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required"));if(!A||A<1)return(0,v.errorResult)("INVALID_INPUT",new Error("startLine must be a positive number"));const y=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!y)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");const S=(0,v.tryGetService)(m,r.CommandService);if(!S)return(0,v.serviceUnavailableResult)("CommandService");try{const w=r.URI.file(b);return await y.open(w,{focus:!0}),await S.executeCommand("editor.fold",A),(0,v.successResult)({path:b,startLine:A,folded:!0})}catch(w){return(0,v.errorResult)((0,v.classifyError)(w),w)}}},{name:"editor_unfold",description:"Unfold code at the specified line in the editor. Opens the file first if needed.",riskLevel:"ui",profiles:["interactive","full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute or workspace-relative path of the file."},startLine:{type:"number",description:"The line number at which to unfold code (1-based)."}},required:["path","startLine"]},execute:async h=>{const b=h.path,A=h.startLine;if(!b)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required"));if(!A||A<1)return(0,v.errorResult)("INVALID_INPUT",new Error("startLine must be a positive number"));const y=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!y)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");const S=(0,v.tryGetService)(m,r.CommandService);if(!S)return(0,v.serviceUnavailableResult)("CommandService");try{const w=r.URI.file(b);return await y.open(w,{focus:!0}),await S.executeCommand("editor.unfold",A),(0,v.successResult)({path:b,startLine:A,unfolded:!0})}catch(w){return(0,v.errorResult)((0,v.classifyError)(w),w)}}},{name:"editor_save",description:"Save the file at the given path.",riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The absolute or workspace-relative path of the file to save."}},required:["path"]},execute:async h=>{const b=h.path;if(!b)return(0,v.errorResult)("INVALID_INPUT",new Error("path is required"));const A=(0,v.tryGetService)(m,o.WorkbenchEditorService);if(!A)return(0,v.serviceUnavailableResult)("WorkbenchEditorService");try{const y=await s(m,b,"write");return y.ok?A.editorGroups.some(T=>T.resources.some(I=>I.uri.isEqual(y.uri)))?await A.save(y.uri)?(0,v.successResult)({path:y.absolutePath,saved:!0}):(0,v.errorResult)("FILE_NOT_FOUND",new Error(`Editor not found for path: ${b}`)):(0,v.errorResult)("INVALID_INPUT",new Error(`Editor is not open for path: ${b}`)):y.result}catch(y){return(0,v.errorResult)((0,v.classifyError)(y),y)}}}]}}},21727:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.resolveWorkspaceFilePath=u,t.validateWorkspaceFileStat=s,t.validateWorkspacePathAccess=l,t.validateWritableWorkspaceTarget=d;const n=e(43718),r=/^[a-zA-Z][a-zA-Z0-9+.-]*:/,o=/^[a-zA-Z]:[\\/]/,c=/^[a-zA-Z]:(?![\\/])/,_=/^(?:\\\\|\/\/)[^\\/]+[\\/][^\\/]+/;function v(g){return o.test(g)||c.test(g)||g.includes("\\")}function p(g,E){return v(g)||v(E)?n.path.win32:n.path.posix}function f(g){return r.test(g)&&!o.test(g)&&!c.test(g)}function a(g,E,m){const h=g.relative(E,m);return h===""||!h.startsWith("..")&&!g.isAbsolute(h)}function u(g,E){if(typeof E!="string"||!E.trim())return{ok:!1,message:"path is required"};if(!g)return{ok:!1,message:"workspaceDir is required"};const m=E.trim();if(f(m))return{ok:!1,message:"URI paths are not supported; pass a workspace-relative path or workspace-local absolute path"};if(c.test(m))return{ok:!1,message:"Windows drive-relative paths are not supported"};const h=p(g,m),b=h.resolve(g),y=h.isAbsolute(m)||_.test(m)?h.resolve(m):h.resolve(b,m);return a(h,b,y)?{ok:!0,value:{absolutePath:y,uri:n.URI.file(y).toString(),pathModule:h}}:{ok:!1,message:"Path is outside of the workspace"}}function s(g,E,m){if(!E)return{ok:!1,message:"File stat is required"};if(!E.isSymbolicLink)return{ok:!0,value:{absolutePath:n.URI.parse(E.uri).codeUri.fsPath,uri:E.uri,pathModule:m}};if(!E.realUri)return{ok:!1,message:"Cannot verify symbolic link target"};const h=n.URI.parse(E.realUri).codeUri.fsPath,b=m.resolve(g),A=m.resolve(h);return a(m,b,A)?{ok:!0,value:{absolutePath:A,uri:E.realUri,pathModule:m}}:{ok:!1,message:"Symbolic link target is outside of the workspace"}}async function l(g,E,m){const h=m.pathModule.resolve(E);let b=m.absolutePath;for(;a(m.pathModule,h,b);){const A=await g.getFileStat(n.URI.file(b).toString());if(A?.isSymbolicLink){const S=s(E,A,m.pathModule);if(!S.ok)return S}if(b===h)break;const y=m.pathModule.dirname(b);if(y===b)break;b=y}return{ok:!0,value:m}}async function d(g,E,m){const h=await g.getFileStat(m.uri);if(h)return s(E,h,m.pathModule);const b=m.pathModule.resolve(E);let A=m.pathModule.dirname(m.absolutePath);for(;a(m.pathModule,b,A);){const y=await g.getFileStat(n.URI.file(A).toString());if(y)return s(E,y,m.pathModule);const S=m.pathModule.dirname(A);if(S===A)break;A=S}return{ok:!1,message:"Cannot verify writable target parent inside workspace"}}},59805:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createFileGroup=p;const n=e(41869),r=e(14951),o=e(67741),c=e(21727);function _(f){return(0,o.errorResult)("INVALID_INPUT",new Error(f))}function v(f,a,u){var s;const l=(s=f[a])!==null&&s!==void 0?s:u?f[u]:void 0;return typeof l=="string"?l:""}function p(f){return{name:"file",description:"\u6587\u4EF6\u8BFB\u5199\u548C\u7BA1\u7406\u64CD\u4F5C",defaultLoaded:!0,tools:[{name:"file_get_workspace_root",description:"Get the absolute path of the current workspace root directory. Use this to understand the base path for relative file operations.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{}},execute:async()=>{const a=(0,o.tryGetService)(f,n.AppConfig);if(!a)return(0,o.serviceUnavailableResult)("AppConfig");try{return(0,o.successResult)({workspaceRoot:a.workspaceDir})}catch(u){return(0,o.errorResult)((0,o.classifyError)(u),u)}}},{name:"file_read",description:"Read the contents of a file. Returns the file content as text. Use relative paths from the workspace root.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The relative path of the file to read, from the workspace root."}},required:["path"]},execute:async a=>{const u=a.path;if(!u)return(0,o.errorResult)("INVALID_INPUT",new Error("path is required"));const s=(0,o.tryGetService)(f,n.AppConfig);if(!s||!s.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const l=(0,o.tryGetService)(f,r.IFileServiceClient);if(!l)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const d=(0,c.resolveWorkspaceFilePath)(s.workspaceDir,u);if(!d.ok)return _(d.message);const g=await(0,c.validateWorkspacePathAccess)(l,s.workspaceDir,d.value);if(!g.ok)return _(g.message);const E=d.value.uri,m=await l.getFileStat(E);if(!m)return(0,o.errorResult)("FILE_NOT_FOUND",new Error(`File not found: ${u}`));const h=(0,c.validateWorkspaceFileStat)(s.workspaceDir,m,d.value.pathModule);if(!h.ok)return _(h.message);if(m.isDirectory)return(0,o.errorResult)("IS_DIRECTORY",new Error(`Path is a directory, not a file: ${u}`));const A=(await l.readFile(E)).content.toString();return(0,o.successResult)({path:u,content:A,size:A.length})}catch(d){return(0,o.errorResult)((0,o.classifyError)(d),d)}}},{name:"file_write",description:"Write content to a file. Creates the file if it does not exist, overwrites if it does. Creates parent directories automatically.",riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The relative path of the file to write, from the workspace root."},content:{type:"string",description:"The content to write to the file."}},required:["path","content"]},execute:async a=>{const u=a.path,s=a.content;if(!u||s===void 0)return(0,o.errorResult)("INVALID_INPUT",new Error("path and content are required"));const l=(0,o.tryGetService)(f,n.AppConfig);if(!l||!l.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const d=(0,o.tryGetService)(f,r.IFileServiceClient);if(!d)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const g=(0,c.resolveWorkspaceFilePath)(l.workspaceDir,u);if(!g.ok)return _(g.message);const E=await(0,c.validateWritableWorkspaceTarget)(d,l.workspaceDir,g.value);if(!E.ok)return _(E.message);const m=g.value.uri,h=await d.getFileStat(m);return h?await d.setContent(h,s):await d.createFile(m,{content:s}),(0,o.successResult)({path:u,written:!0,size:s.length})}catch(g){return(0,o.errorResult)((0,o.classifyError)(g),g)}}},{name:"file_list",description:'List the contents of a directory. Returns an array of file/directory entries with metadata. Use "." for the workspace root.',riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{path:{type:"string",description:'The relative path of the directory to list, from the workspace root. Use "." for workspace root.'}},required:["path"]},execute:async a=>{const u=a.path;if(!u)return(0,o.errorResult)("INVALID_INPUT",new Error("path is required"));const s=(0,o.tryGetService)(f,n.AppConfig);if(!s||!s.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const l=(0,o.tryGetService)(f,r.IFileServiceClient);if(!l)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const d=(0,c.resolveWorkspaceFilePath)(s.workspaceDir,u);if(!d.ok)return _(d.message);const g=await(0,c.validateWorkspacePathAccess)(l,s.workspaceDir,d.value);if(!g.ok)return _(g.message);const E=d.value.uri,m=await l.getFileStat(E,!0);if(!m)return(0,o.errorResult)("FILE_NOT_FOUND",new Error(`Directory not found: ${u}`));const h=(0,c.validateWorkspaceFileStat)(s.workspaceDir,m,d.value.pathModule);if(!h.ok)return _(h.message);if(!m.isDirectory)return(0,o.errorResult)("NOT_A_DIRECTORY",new Error(`Path is a file, not a directory: ${u}`));const b=(m.children||[]).map(A=>({name:A.uri?A.uri.split("/").pop():"unknown",isDirectory:A.isDirectory,size:A.size}));return(0,o.successResult)({path:u,entries:b,total:b.length})}catch(d){return(0,o.errorResult)((0,o.classifyError)(d),d)}}},{name:"file_stat",description:"Get metadata about a file or directory. Returns size, isDirectory, lastModified, and other stat info.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The relative path of the file or directory, from the workspace root."}},required:["path"]},execute:async a=>{const u=a.path;if(!u)return(0,o.errorResult)("INVALID_INPUT",new Error("path is required"));const s=(0,o.tryGetService)(f,n.AppConfig);if(!s||!s.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const l=(0,o.tryGetService)(f,r.IFileServiceClient);if(!l)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const d=(0,c.resolveWorkspaceFilePath)(s.workspaceDir,u);if(!d.ok)return _(d.message);const g=await(0,c.validateWorkspacePathAccess)(l,s.workspaceDir,d.value);if(!g.ok)return _(g.message);const E=d.value.uri,m=await l.getFileStat(E);if(!m)return(0,o.errorResult)("FILE_NOT_FOUND",new Error(`Path not found: ${u}`));const h=(0,c.validateWorkspaceFileStat)(s.workspaceDir,m,d.value.pathModule);return h.ok?(0,o.successResult)({path:u,isDirectory:m.isDirectory,size:m.size,lastModified:m.lastModification,isReadonly:m.readonly}):_(h.message)}catch(d){return(0,o.errorResult)((0,o.classifyError)(d),d)}}},{name:"file_exists",description:"Check whether a file or directory exists at the given path. Returns true or false.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The relative path to check, from the workspace root."}},required:["path"]},execute:async a=>{const u=a.path;if(!u)return(0,o.errorResult)("INVALID_INPUT",new Error("path is required"));const s=(0,o.tryGetService)(f,n.AppConfig);if(!s||!s.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const l=(0,o.tryGetService)(f,r.IFileServiceClient);if(!l)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const d=(0,c.resolveWorkspaceFilePath)(s.workspaceDir,u);if(!d.ok)return _(d.message);const g=await(0,c.validateWorkspacePathAccess)(l,s.workspaceDir,d.value);if(!g.ok)return _(g.message);const E=await l.getFileStat(d.value.uri);if(E){const h=(0,c.validateWorkspaceFileStat)(s.workspaceDir,E,d.value.pathModule);if(!h.ok)return _(h.message)}const m=!!E;return(0,o.successResult)({path:u,exists:m})}catch(d){return(0,o.errorResult)((0,o.classifyError)(d),d)}}},{name:"file_create",description:'Create a new file with optional content. Use "type: directory" to create a folder instead.',riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The relative path to create, from the workspace root."},type:{type:"string",enum:["file","directory"],description:'Whether to create a "file" or "directory". Defaults to "file".'},content:{type:"string",description:'Initial file content. Ignored when type is "directory".'}},required:["path"]},execute:async a=>{const u=a.path,s=a.type||"file",l=typeof a.content=="string"?a.content:void 0;if(!u)return(0,o.errorResult)("INVALID_INPUT",new Error("path is required"));const d=(0,o.tryGetService)(f,n.AppConfig);if(!d||!d.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const g=(0,o.tryGetService)(f,r.IFileServiceClient);if(!g)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const E=(0,c.resolveWorkspaceFilePath)(d.workspaceDir,u);if(!E.ok)return _(E.message);const m=await(0,c.validateWritableWorkspaceTarget)(g,d.workspaceDir,E.value);if(!m.ok)return _(m.message);const h=E.value.uri;return await g.getFileStat(h)?(0,o.errorResult)("FILE_EXISTS",new Error(`Path already exists: ${u}`)):(s==="directory"?await g.createFolder(h):await g.createFile(h,{content:l}),(0,o.successResult)({path:u,type:s,created:!0}))}catch(E){return(0,o.errorResult)((0,o.classifyError)(E),E)}}},{name:"file_delete",description:"Delete a file or directory. Use recursive: true to delete a directory and its contents.",riskLevel:"destructive",profiles:["full"],inputSchema:{type:"object",properties:{path:{type:"string",description:"The relative path to delete, from the workspace root."},recursive:{type:"boolean",description:"Whether to delete a directory and all its contents. Required for directories."}},required:["path"]},execute:async a=>{var u;const s=a.path,l=(u=a.recursive)!==null&&u!==void 0?u:!1;if(!s)return(0,o.errorResult)("INVALID_INPUT",new Error("path is required"));const d=(0,o.tryGetService)(f,n.AppConfig);if(!d||!d.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const g=(0,o.tryGetService)(f,r.IFileServiceClient);if(!g)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const E=(0,c.resolveWorkspaceFilePath)(d.workspaceDir,s);if(!E.ok)return _(E.message);const m=await(0,c.validateWorkspacePathAccess)(g,d.workspaceDir,E.value);if(!m.ok)return _(m.message);const h=E.value.uri,b=await g.getFileStat(h);if(!b)return(0,o.errorResult)("FILE_NOT_FOUND",new Error(`Path not found: ${s}`));const A=(0,c.validateWorkspaceFileStat)(d.workspaceDir,b,E.value.pathModule);return A.ok?b.isDirectory&&!l?(0,o.errorResult)("IS_DIRECTORY",new Error("Path is a directory. Use recursive: true to delete directories.")):(await g.delete(h),(0,o.successResult)({path:s,deleted:!0})):_(A.message)}catch(E){return(0,o.errorResult)((0,o.classifyError)(E),E)}}},{name:"file_move",description:"Move or rename a file or directory from source to destination.",riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{sourcePath:{type:"string",description:"The relative source path to move, from the workspace root."},targetPath:{type:"string",description:"The relative destination path to move to, from the workspace root."}},required:["sourcePath","targetPath"]},execute:async a=>{const u=v(a,"sourcePath","source"),s=v(a,"targetPath","destination");if(!u||!s)return(0,o.errorResult)("INVALID_INPUT",new Error("sourcePath and targetPath are required"));const l=(0,o.tryGetService)(f,n.AppConfig);if(!l||!l.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const d=(0,o.tryGetService)(f,r.IFileServiceClient);if(!d)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const g=(0,c.resolveWorkspaceFilePath)(l.workspaceDir,u);if(!g.ok)return _(g.message);const E=await(0,c.validateWorkspacePathAccess)(d,l.workspaceDir,g.value);if(!E.ok)return _(E.message);const m=(0,c.resolveWorkspaceFilePath)(l.workspaceDir,s);if(!m.ok)return _(m.message);const h=g.value.uri,b=m.value.uri,A=await d.getFileStat(h);if(!A)return(0,o.errorResult)("FILE_NOT_FOUND",new Error(`Source not found: ${u}`));const y=(0,c.validateWorkspaceFileStat)(l.workspaceDir,A,g.value.pathModule);if(!y.ok)return _(y.message);const S=await(0,c.validateWritableWorkspaceTarget)(d,l.workspaceDir,m.value);return S.ok?(await d.move(h,b),(0,o.successResult)({source:u,destination:s,moved:!0})):_(S.message)}catch(g){return(0,o.errorResult)((0,o.classifyError)(g),g)}}},{name:"file_copy",description:"Copy a file or directory from source to destination.",riskLevel:"write",profiles:["full"],inputSchema:{type:"object",properties:{sourcePath:{type:"string",description:"The relative source path to copy, from the workspace root."},targetPath:{type:"string",description:"The relative destination path to copy to, from the workspace root."}},required:["sourcePath","targetPath"]},execute:async a=>{const u=v(a,"sourcePath","source"),s=v(a,"targetPath","destination");if(!u||!s)return(0,o.errorResult)("INVALID_INPUT",new Error("sourcePath and targetPath are required"));const l=(0,o.tryGetService)(f,n.AppConfig);if(!l||!l.workspaceDir)return(0,o.serviceUnavailableResult)("AppConfig");const d=(0,o.tryGetService)(f,r.IFileServiceClient);if(!d)return(0,o.serviceUnavailableResult)("IFileServiceClient");try{const g=(0,c.resolveWorkspaceFilePath)(l.workspaceDir,u);if(!g.ok)return _(g.message);const E=await(0,c.validateWorkspacePathAccess)(d,l.workspaceDir,g.value);if(!E.ok)return _(E.message);const m=(0,c.resolveWorkspaceFilePath)(l.workspaceDir,s);if(!m.ok)return _(m.message);const h=g.value.uri,b=m.value.uri,A=await d.getFileStat(h);if(!A)return(0,o.errorResult)("FILE_NOT_FOUND",new Error(`Source not found: ${u}`));const y=(0,c.validateWorkspaceFileStat)(l.workspaceDir,A,g.value.pathModule);if(!y.ok)return _(y.message);const S=await(0,c.validateWritableWorkspaceTarget)(d,l.workspaceDir,m.value);return S.ok?(await d.copy(h,b),(0,o.successResult)({source:u,destination:s,copied:!0})):_(S.message)}catch(g){return(0,o.errorResult)((0,o.classifyError)(g),g)}}}]}}},13682:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createOpenSumiMcpGroup=o;const n=e(43718),r=e(67741);function o(c){return{name:"opensumi_mcp",description:"OpenSumi built-in MCP transport discovery",defaultLoaded:!0,tools:[{name:"opensumi_get_mcp_server_connection",description:"Start the built-in opensumi-ide MCP server and return a local Streamable HTTP connection descriptor. Use redactedUrl for logs.",riskLevel:"read",inputSchema:{type:"object",properties:{},additionalProperties:!1},execute:async()=>{const _=(0,r.tryGetService)(c,n.AIBackSerivcePath);if(!_?.getOpenSumiMcpServerConnection)return(0,r.serviceUnavailableResult)("AIBackService.getOpenSumiMcpServerConnection");try{return(0,r.successResult)(await _.getOpenSumiMcpServerConnection())}catch(v){return(0,r.errorResult)((0,r.classifyError)(v),v)}}}]}}},38583:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createSearchGroup=A;const n=e(79240),r=e(43718),o=e(87863),c=e(23950),_=e(84660),v=e(52925),p=e(51500),f=e(67741),a=20,u=100,s=50,l=200,d=1e4;function g(y){return y.tryGetRoots().map(S=>r.URI.parse(S.uri).codeUri.fsPath)}function E(y){if(Array.isArray(y))return y.filter(S=>typeof S=="string"&&S.length>0)}function m(y,S,w){return Math.min(Math.max(Number(y)||S,1),w)}function h(y,S){return new Promise(w=>{let T=!1,I;const D=M=>{T||(T=!0,I?.dispose(),clearTimeout(R),w({timedOut:M}))},R=setTimeout(()=>D(!0),S);I=y.onDidChange(()=>{y.isSearching||D(!1)}),y.isSearching||D(!1)})}function b(y,S){return Array.from(y.entries()).flatMap(([T,I])=>{const D=r.URI.parse(T).codeUri.fsPath;return I.map(R=>{var M,O;return{uri:T,path:D,line:R.line,matchStart:R.matchStart,matchLength:R.matchLength,lineText:(O=(M=R.lineText)!==null&&M!==void 0?M:R.renderLineText)!==null&&O!==void 0?O:""}})}).slice(0,S)}function A(y){return{name:"search",description:"Workspace file, text, and symbol search",defaultLoaded:!0,tools:[{name:"search_files",description:"Search workspace files by fuzzy filename or path. Prefer this before reading files when the exact path is unknown.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{query:{type:"string",description:"Filename or path fragment to search for."},maxResults:{type:"number",description:"Maximum number of files to return. Defaults to 20, capped at 100."},includePatterns:{type:"array",items:{type:"string"},description:"Optional glob patterns to include."},excludePatterns:{type:"array",items:{type:"string"},description:"Optional glob patterns to exclude."}},required:["query"]},execute:async S=>{var w;const T=typeof S.query=="string"?S.query.trim():"";if(!T)return(0,f.errorResult)("INVALID_INPUT",new Error("query is required"));const I=(0,f.tryGetService)(y,p.IWorkspaceService);if(!I)return(0,f.serviceUnavailableResult)("IWorkspaceService");const D=(0,f.tryGetService)(y,_.FileSearchServicePath);if(!D)return(0,f.serviceUnavailableResult)("FileSearchServicePath");try{const R=g(I),M=m(S.maxResults,a,u),O=(0,n.getValidateInput)(T.replace(/\s/g,"")),x=await D.find(O,{rootUris:R,excludePatterns:[...Object.keys(o.defaultFilesWatcherExcludes),...(w=E(S.excludePatterns))!==null&&w!==void 0?w:[]],includePatterns:E(S.includePatterns),limit:M,useGitIgnore:!0,noIgnoreParent:!0,fuzzyMatch:!0});return(0,f.successResult)({query:T,files:x.slice(0,M).map(k=>({path:k})),total:x.length,truncated:x.length>M})}catch(R){return(0,f.errorResult)((0,f.classifyError)(R),R)}}},{name:"search_text",description:"Search text across workspace files. Returns matching file path, line, column, and a shortened line preview.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{query:{type:"string",description:"Text or regular expression to search for."},maxResults:{type:"number",description:"Maximum number of matches to return. Defaults to 50, capped at 200."},include:{type:"array",items:{type:"string"},description:"Optional glob patterns to include."},exclude:{type:"array",items:{type:"string"},description:"Optional glob patterns to exclude."},matchCase:{type:"boolean",description:"Whether matching is case-sensitive."},matchWholeWord:{type:"boolean",description:"Whether to match whole words only."},useRegExp:{type:"boolean",description:"Whether query is a regular expression."},includeIgnored:{type:"boolean",description:"Whether to include gitignored and hidden files."}},required:["query"]},execute:async S=>{const w=typeof S.query=="string"?S.query:"";if(!w)return(0,f.errorResult)("INVALID_INPUT",new Error("query is required"));const T=(0,f.tryGetService)(y,v.IContentSearchClientService);if(!T)return(0,f.serviceUnavailableResult)("IContentSearchClientService");try{const I=m(S.maxResults,s,l),D=new r.CancellationTokenSource;T.cleanSearchResults(),await T.doSearch(w,{...T.UIState,isMatchCase:!!S.matchCase,isWholeWord:!!S.matchWholeWord,isUseRegexp:!!S.useRegExp,isIncludeIgnored:!!S.includeIgnored,include:E(S.include),exclude:E(S.exclude),maxResults:I},D.token);const{timedOut:R}=await h(T,d);R&&D.cancel();const M=b(T.searchResults,I);return(0,f.successResult)({query:w,matches:M,total:T.resultTotal.resultNum,fileTotal:T.resultTotal.fileNum,truncated:T.resultTotal.resultNum>M.length,timedOut:R,searchState:v.SEARCH_STATE[T.searchState],error:T.searchError||void 0})}catch(I){return(0,f.errorResult)((0,f.classifyError)(I),I)}}},{name:"search_symbols",description:"Search workspace symbols through registered language providers.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{query:{type:"string",description:"Symbol name or partial name to search for."},maxResults:{type:"number",description:"Maximum number of symbols to return. Defaults to 50, capped at 200."}},required:["query"]},execute:async S=>{const w=typeof S.query=="string"?S.query.trim():"";if(!w)return(0,f.errorResult)("INVALID_INPUT",new Error("query is required"));const T=(0,f.tryGetService)(y,c.ILanguageService);if(!T)return(0,f.serviceUnavailableResult)("ILanguageService");try{const I=m(S.maxResults,s,l),D=await Promise.all(T.workspaceSymbolProviders.map(M=>Promise.resolve(M.provideWorkspaceSymbols({query:w},r.CancellationToken.None)).catch(()=>[]))),R=D.flat().slice(0,I).map(M=>({name:M.name,kind:M.kind,containerName:M.containerName,uri:M.location.uri,path:r.URI.parse(M.location.uri).codeUri.fsPath,range:M.location.range}));return(0,f.successResult)({query:w,symbols:R,total:D.reduce((M,O)=>M+O.length,0),truncated:D.reduce((M,O)=>M+O.length,0)>R.length})}catch(I){return(0,f.errorResult)((0,f.classifyError)(I),I)}}}]}}},96743:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createTerminalGroup=g;const n=e(26405),r=e(78453),o=e(7473),c=e(67741),_=120,v=1e3,p=6e4;function f(E,m,h){return Math.min(Math.max(Number(E)||m,1),h)}function a(E){return E.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,"")}function u(E,m){var h;return m?E.clients.get(m):(h=E.activeClient)!==null&&h!==void 0?h:Array.from(E.clients.values()).find(b=>b.id)}function s(E,m){var h,b;const A=f(m.maxLines,_,v),y=E.term.buffer.active,S=y.length,w=(typeof m.cursor=="string",Number(m.cursor)),T=Number.isFinite(w)?Math.min(Math.max(w,0),S):Math.max(S-A,0),I=Math.min(T+A,S),D=m.stripAnsi!==!1,R=[];for(let M=T;M<I;M++){const O=(b=(h=y.getLine(M))===null||h===void 0?void 0:h.translateToString(!0))!==null&&b!==void 0?b:"";R.push(D?a(O):O)}return{terminalId:E.id,cursor:String(I),lines:R,totalBufferLines:S,truncated:I<S}}function l(E){const m=E.toLowerCase();return{enter:"\r","ctrl-c":"","ctrl-d":"",escape:"\x1B",tab:" ",up:"\x1B[A",down:"\x1B[B",right:"\x1B[C",left:"\x1B[D"}[m]}function d(E){return new Promise(m=>setTimeout(m,E))}function g(E){return{name:"terminal",description:"\u7EC8\u7AEF\u64CD\u4F5C",defaultLoaded:!0,tools:[{name:"terminal_list",description:"List all open terminal sessions. Returns an array of terminal info objects including id, name, and isActive. Use this to discover existing terminals before sending commands.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const m=(0,c.tryGetService)(E,r.ITerminalApiService);if(!m)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{const h=m.terminals;return(0,c.successResult)(h.map(b=>({id:b.id,name:b.name,isActive:b.isActive})))}catch(h){return(0,c.errorResult)("EXECUTION_ERROR",h)}}},{name:"terminal_get_active",description:"Get the active IDE terminal session.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const m=(0,c.tryGetService)(E,o.ITerminalController);if(!m)return(0,c.serviceUnavailableResult)("ITerminalController");try{const h=u(m);return h?(0,c.successResult)({active:!0,terminal:{id:h.id,name:h.name,ready:h.ready,cwd:h.launchConfig.cwd}}):(0,c.successResult)({active:!1,terminal:null})}catch(h){return(0,c.errorResult)("EXECUTION_ERROR",h)}}},{name:"terminal_read_output",description:"Read recent output lines from an IDE terminal.",riskLevel:"read",inputSchema:{type:"object",properties:{id:{type:"string",description:"Optional terminal session ID. Defaults to the active terminal."},maxLines:{type:"number",description:"Maximum lines to return. Defaults to 120, capped at 1000."},stripAnsi:{type:"boolean",description:"Whether to strip ANSI escape sequences. Defaults to true."}}},execute:async m=>{const h=(0,c.tryGetService)(E,o.ITerminalController);if(!h)return(0,c.serviceUnavailableResult)("ITerminalController");try{const b=u(h,m.id);return b?(0,c.successResult)(s(b,{maxLines:m.maxLines,stripAnsi:m.stripAnsi})):(0,c.errorResult)("INVALID_INPUT",new Error("terminal not found"))}catch(b){return(0,c.errorResult)("EXECUTION_ERROR",b)}}},{name:"terminal_tail",description:"Read output lines after a cursor from an IDE terminal.",riskLevel:"read",inputSchema:{type:"object",properties:{id:{type:"string",description:"Terminal session ID."},cursor:{type:"string",description:"Cursor returned by readOutput or tail."},maxLines:{type:"number",description:"Maximum lines to return. Defaults to 120, capped at 1000."},stripAnsi:{type:"boolean",description:"Whether to strip ANSI escape sequences. Defaults to true."}},required:["id"]},execute:async m=>{const h=(0,c.tryGetService)(E,o.ITerminalController);if(!h)return(0,c.serviceUnavailableResult)("ITerminalController");try{const b=u(h,m.id);return b?(0,c.successResult)(s(b,{cursor:m.cursor,maxLines:m.maxLines,stripAnsi:m.stripAnsi})):(0,c.errorResult)("INVALID_INPUT",new Error("terminal not found"))}catch(b){return(0,c.errorResult)("EXECUTION_ERROR",b)}}},{name:"terminal_get_process_info",description:"Get process metadata for an IDE terminal.",riskLevel:"read",inputSchema:{type:"object",properties:{id:{type:"string",description:"Optional terminal session ID. Defaults to the active terminal."}}},execute:async m=>{const h=(0,c.tryGetService)(E,o.ITerminalController);if(!h)return(0,c.serviceUnavailableResult)("ITerminalController");const b=(0,c.tryGetService)(E,r.ITerminalApiService);if(!b)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{const A=u(h,m.id);if(!A)return(0,c.errorResult)("INVALID_INPUT",new Error("terminal not found"));const y=await b.getProcessId(A.id);return(0,c.successResult)({terminalId:A.id,name:A.name,pid:y??null,cwd:A.launchConfig.cwd,executable:A.launchConfig.executable,ready:A.ready})}catch(A){return(0,c.errorResult)("EXECUTION_ERROR",A)}}},{name:"terminal_create",description:"Create a new terminal session. Optionally specify a shell path or working directory. Returns the terminal id. Use this to open a new terminal for running commands.",riskLevel:"shell",profiles:["interactive","full"],inputSchema:{type:"object",properties:{name:{type:"string",description:"Display name for the terminal."},cwd:{type:"string",description:"Working directory for the new terminal. Defaults to workspace root."},shellPath:{type:"string",description:'Shell executable path (e.g. "/bin/bash", "/bin/zsh"). Defaults to system default.'}}},execute:async m=>{const h=(0,c.tryGetService)(E,o.ITerminalController);if(!h)return(0,c.serviceUnavailableResult)("ITerminalController");try{await h.viewReady.promise;const b=await h.createTerminal({config:m.shellPath?{executable:m.shellPath}:void 0,cwd:m.cwd});return(0,c.successResult)({id:b.id,name:b.name})}catch(b){return(0,c.errorResult)("EXECUTION_ERROR",b)}}},{name:"terminal_execute_command",description:"Send a text command to a specific terminal session identified by id. The text is typed into the terminal as-is. To execute the command, include a trailing newline (\\n). Get valid ids from terminal_list.",riskLevel:"shell",profiles:["interactive","full"],inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID. Get valid IDs from terminal_list."},command:{type:"string",description:'The text to send to the terminal. Append "\\n" to execute the command.'}},required:["id","command"]},execute:async m=>{const h=m.id,b=m.command;if(!h||!b)return(0,c.errorResult)("EXECUTION_ERROR",new Error("id and command are required"));const A=(0,c.tryGetService)(E,r.ITerminalApiService);if(!A)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return A.sendText(h,b),(0,c.successResult)({terminalId:h,commandLength:b.length,sent:!0})}catch(y){return(0,c.errorResult)("EXECUTION_ERROR",y)}}},{name:"terminal_send_text",description:"Type text into an IDE terminal without pressing Enter.",riskLevel:"shell",profiles:["interactive","full"],inputSchema:{type:"object",properties:{id:{type:"string",description:"Terminal session ID."},text:{type:"string",description:"Text to type. It is not logged or returned."}},required:["id","text"]},execute:async m=>{const h=m.id,b=m.text;if(!h||typeof b!="string")return(0,c.errorResult)("INVALID_INPUT",new Error("id and text are required"));const A=(0,c.tryGetService)(E,r.ITerminalApiService);if(!A)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return A.sendText(h,b,!1),(0,c.successResult)({terminalId:h,charCount:b.length,sent:!0})}catch(y){return(0,c.errorResult)("EXECUTION_ERROR",y)}}},{name:"terminal_send_control",description:"Send an allowlisted control key to an IDE terminal.",riskLevel:"shell",profiles:["interactive","full"],inputSchema:{type:"object",properties:{id:{type:"string",description:"Terminal session ID."},key:{type:"string",enum:["enter","ctrl-c","ctrl-d","escape","tab","up","down","left","right"],description:"Control key to send."}},required:["id","key"]},execute:async m=>{const h=m.id,b=m.key,A=typeof b=="string"?l(b):void 0;if(!h||!A)return(0,c.errorResult)("INVALID_INPUT",new Error("valid id and key are required"));const y=(0,c.tryGetService)(E,r.ITerminalApiService);if(!y)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return y.sendText(h,A,!1),(0,c.successResult)({terminalId:h,key:b,sent:!0})}catch(S){return(0,c.errorResult)("EXECUTION_ERROR",S)}}},{name:"terminal_run_command",description:"Type a command into an IDE terminal and press Enter.",riskLevel:"shell",profiles:["interactive","full"],inputSchema:{type:"object",properties:{id:{type:"string",description:"Terminal session ID."},command:{type:"string",description:"Command text. It is not logged or returned."}},required:["id","command"]},execute:async m=>{const h=m.id,b=m.command;if(!h||!b)return(0,c.errorResult)("INVALID_INPUT",new Error("id and command are required"));const A=(0,c.tryGetService)(E,r.ITerminalApiService);if(!A)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return A.sendText(h,b,!0),(0,c.successResult)({terminalId:h,commandLength:b.length,sent:!0})}catch(y){return(0,c.errorResult)("EXECUTION_ERROR",y)}}},{name:"terminal_wait_for_pattern",description:"Wait until terminal output contains a string or regular expression.",riskLevel:"read",profiles:["default","interactive","full"],inputSchema:{type:"object",properties:{id:{type:"string",description:"Terminal session ID."},pattern:{type:"string",description:"String or regular expression to wait for."},useRegExp:{type:"boolean",description:"Whether pattern is a regular expression."},timeoutMs:{type:"number",description:"Timeout in milliseconds. Defaults to 10000, capped at 60000."},pollIntervalMs:{type:"number",description:"Polling interval in milliseconds. Defaults to 500."}},required:["id","pattern"]},execute:async m=>{const h=m.id,b=m.pattern;if(!h||!b)return(0,c.errorResult)("INVALID_INPUT",new Error("id and pattern are required"));const A=(0,c.tryGetService)(E,o.ITerminalController);if(!A)return(0,c.serviceUnavailableResult)("ITerminalController");try{const y=u(A,h);if(!y)return(0,c.errorResult)("INVALID_INPUT",new Error("terminal not found"));const S=f(m.timeoutMs,1e4,p),w=f(m.pollIntervalMs,500,5e3),T=m.useRegExp?new RegExp(b):null,I=Date.now();for(;Date.now()-I<S;){const D=s(y,{maxLines:_}).lines.join(`
39437
- `);if(T?T.test(D):D.includes(b))return(0,c.successResult)({terminalId:h,matched:!0,elapsedMs:Date.now()-I});await d(w)}return(0,c.successResult)({terminalId:h,matched:!1,timedOut:!0,elapsedMs:Date.now()-I})}catch(y){return(0,c.errorResult)("EXECUTION_ERROR",y)}}},{name:"terminal_show",description:"Show/focus a specific terminal session in the terminal panel. Use this to bring a terminal into view.",riskLevel:"ui",inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID to show. Get valid IDs from terminal_list."}},required:["id"]},execute:async m=>{const h=m.id;if(!h)return(0,c.errorResult)("EXECUTION_ERROR",new Error("id is required"));const b=(0,c.tryGetService)(E,r.ITerminalApiService);if(!b)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return b.showTerm(h),(0,c.successResult)({terminalId:h})}catch(A){return(0,c.errorResult)("EXECUTION_ERROR",A)}}},{name:"terminal_get_process_id",description:"Get the OS process ID (PID) of the shell process running in a terminal session. Returns null if the process has exited.",riskLevel:"read",inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID. Get valid IDs from terminal_list."}},required:["id"]},execute:async m=>{const h=m.id;if(!h)return(0,c.errorResult)("EXECUTION_ERROR",new Error("id is required"));const b=(0,c.tryGetService)(E,r.ITerminalApiService);if(!b)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{const A=await b.getProcessId(h);return(0,c.successResult)({terminalId:h,pid:A??null})}catch(A){return(0,c.errorResult)("EXECUTION_ERROR",A)}}},{name:"terminal_dispose",description:"Close/kill a terminal session and its underlying shell process. Use this to clean up terminals that are no longer needed.",riskLevel:"destructive",profiles:["full"],inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID to close. Get valid IDs from terminal_list."}},required:["id"]},execute:async m=>{const h=m.id;if(!h)return(0,c.errorResult)("INVALID_INPUT",new Error("id is required"));const b=(0,c.tryGetService)(E,o.ITerminalController);if(!b)return(0,c.serviceUnavailableResult)("ITerminalController");const A=(0,c.tryGetService)(E,r.ITerminalApiService);if(!A)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return u(b,h)?(A.removeTerm(h),(0,c.successResult)({terminalId:h,disposed:!0})):(0,c.errorResult)("INVALID_INPUT",new Error("terminal not found"))}catch(y){return(0,c.errorResult)("EXECUTION_ERROR",y)}}},{name:"terminal_resize",description:"Resize a terminal session to the specified number of columns (width) and rows (height).",riskLevel:"ui",inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID. Get valid IDs from terminal_list."},cols:{type:"number",description:"Number of columns (character width) for the terminal."},rows:{type:"number",description:"Number of rows (character height) for the terminal."}},required:["id","cols","rows"]},execute:async m=>{const h=m.id,b=m.cols,A=m.rows;if(!h||!b||!A)return(0,c.errorResult)("EXECUTION_ERROR",new Error("id, cols, and rows are required"));const y=(0,c.tryGetService)(E,n.ITerminalService);if(!y)return(0,c.serviceUnavailableResult)("ITerminalService");try{return await y.resize(h,b,A),(0,c.successResult)({terminalId:h,cols:b,rows:A})}catch(S){return(0,c.errorResult)("EXECUTION_ERROR",S)}}},{name:"terminal_get_os",description:'Get the operating system type of the terminal backend (e.g. "Linux", "macOS", "Windows"). Useful for writing platform-specific commands.',riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const m=(0,c.tryGetService)(E,n.ITerminalService);if(!m)return(0,c.serviceUnavailableResult)("ITerminalService");try{const h=await m.getOS();return(0,c.successResult)({os:h})}catch(h){return(0,c.errorResult)("EXECUTION_ERROR",h)}}},{name:"terminal_get_profiles",description:"Get the list of available terminal shell profiles (e.g. bash, zsh, PowerShell). Use the profile name with terminal_create to open a specific shell.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{autoDetect:{type:"boolean",description:"Whether to auto-detect available shells. Defaults to true."}}},execute:async m=>{var h;const b=(0,c.tryGetService)(E,n.ITerminalService);if(!b)return(0,c.serviceUnavailableResult)("ITerminalService");try{const A=(h=m.autoDetect)!==null&&h!==void 0?h:!0,y=await b.getProfiles(A);return(0,c.successResult)(y.map(S=>({profileName:S.profileName,path:S.path,isAutoDetected:S.isAutoDetected})))}catch(A){return(0,c.errorResult)("EXECUTION_ERROR",A)}}},{name:"terminal_show_panel",description:"Show/open the terminal panel in the IDE. Use this to ensure the terminal panel is visible before interacting with terminals.",riskLevel:"ui",inputSchema:{type:"object",properties:{}},execute:async()=>{const m=(0,c.tryGetService)(E,o.ITerminalController);if(!m)return(0,c.serviceUnavailableResult)("ITerminalController");try{return m.showTerminalPanel(),(0,c.successResult)({status:"shown"})}catch(h){return(0,c.errorResult)("EXECUTION_ERROR",h)}}}]}}},68840:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createWorkspaceGroup=p;const n=e(41869),r=e(43718),o=e(54414),c=e(51500),_=e(67741);function v(f){return r.URI.parse(f).codeUri.fsPath}function p(f){return{name:"workspace",description:"Workspace context and open editor state",defaultLoaded:!0,tools:[{name:"workspace_get_info",description:"Get workspace metadata, including root folders, workspace name, multi-root state, and the configured workspace directory.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{var a;const u=(0,_.tryGetService)(f,c.IWorkspaceService);if(!u)return(0,_.serviceUnavailableResult)("IWorkspaceService");const s=(0,_.tryGetService)(f,n.AppConfig);try{await u.whenReady;const l=u.tryGetRoots().map(d=>({uri:d.uri,path:v(d.uri),name:u.getWorkspaceName(r.URI.parse(d.uri))}));return(0,_.successResult)({workspaceDir:(a=s?.workspaceDir)!==null&&a!==void 0?a:null,roots:l,rootCount:l.length,isMultiRootWorkspaceOpened:u.isMultiRootWorkspaceOpened,isMultiRootWorkspaceEnabled:u.isMultiRootWorkspaceEnabled})}catch(l){return(0,_.errorResult)((0,_.classifyError)(l),l)}}},{name:"workspace_list_open_files",description:"List files currently opened in editor groups. Use this to understand the user visible editing context.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{var a,u;const s=(0,_.tryGetService)(f,o.WorkbenchEditorService);if(!s)return(0,_.serviceUnavailableResult)("WorkbenchEditorService");try{const l=(u=(a=s.currentEditor)===null||a===void 0?void 0:a.currentUri)===null||u===void 0?void 0:u.toString(),d=s.editorGroups.flatMap((g,E)=>g.resources.map(m=>({uri:m.uri.toString(),path:m.uri.codeUri.fsPath,name:m.name,groupIndex:E,active:m.uri.toString()===l})));return(0,_.successResult)({files:d,total:d.length})}catch(l){return(0,_.errorResult)((0,_.classifyError)(l),l)}}},{name:"workspace_list_recent_workspaces",description:"List recently used workspaces known to the IDE.",riskLevel:"read",inputSchema:{type:"object",properties:{maxResults:{type:"number",description:"Maximum number of recent workspaces to return. Defaults to 10, capped at 50."}}},execute:async a=>{const u=(0,_.tryGetService)(f,c.IWorkspaceService);if(!u)return(0,_.serviceUnavailableResult)("IWorkspaceService");try{const s=Math.min(Math.max(Number(a.maxResults)||10,1),50),l=await u.getMostRecentlyUsedWorkspaces();return(0,_.successResult)({workspaces:l.slice(0,s),total:l.length})}catch(s){return(0,_.errorResult)((0,_.classifyError)(s),s)}}}]}}},80945:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getWebMcpModelContextToolDefinitions=c,t.registerWebMcpModelContextTools=_;const n=e(99763),r=e(87854),o=new WeakMap;function c(v,p){const{defaultLoadedOnly:f=!0,includeAllTools:a=!1}=p??{},u=v.getGroupDefinitions({...p,includeAllTools:a}).filter(l=>!f||l.defaultLoaded).flatMap(l=>l.tools.filter(d=>{var g;return(0,r.canExposeWebMcpTool)(d,(g=l.profile)!==null&&g!==void 0?g:"default")}).map(d=>({group:l.name,name:d.name,description:d.description,inputSchema:d.inputSchema}))),s=new Set;return u.filter(l=>s.has(l.name)?!1:(s.add(l.name),!0))}function _(v,p){var f,a;(0,n.ensureModelContext)();const u=navigator.modelContext,s=(f=o.get(u))!==null&&f!==void 0?f:new Set;o.set(u,s),(a=u.getTools)===null||a===void 0||a.call(u).forEach(g=>s.add(g.name));const l=[],d=c(v,p).filter(g=>s.has(g.name)?!1:(s.add(g.name),l.push(g.name),!0)).map(g=>u.registerTool({name:g.name,description:g.description,inputSchema:g.inputSchema,execute:E=>v.executeTool(g.group,g.name,E??{})}));return{dispose:()=>{d.forEach(g=>g.dispose()),l.forEach(g=>s.delete(g))}}}},67741:(P,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tryGetService=e,t.classifyError=n,t.safeErrorMessage=o,t.successResult=c,t.errorResult=_,t.serviceUnavailableResult=v;function e(p,f){try{return p.get(f)}catch{return null}}function n(p){if(p instanceof Error){const f=p.message.toLowerCase();if(f.includes("timeout")||f.includes("timed out"))return"RPC_TIMEOUT";if(f.includes("permission")||f.includes("forbidden"))return"PERMISSION_DENIED";if(f.includes("abort"))return"ABORTED";if(f.includes("not found")||f.includes("enoent"))return"FILE_NOT_FOUND";if(f.includes("already exists")||f.includes("eexist"))return"FILE_EXISTS";if(f.includes("di")||f.includes("injector"))return"DI_ERROR"}return"EXECUTION_ERROR"}const r=[/(?:token|key|secret|password|auth)["\s]*[:=]\s*["']?[^"'`\s,}]+/gi,/sk-[a-zA-Z0-9]{20,}/g,/ghp_[a-zA-Z0-9]{30,}/g];function o(p,f=200){let a=p instanceof Error?p.message:String(p);for(const u of r)a=a.replace(u,"[REDACTED]");return a.length>f?a.slice(0,f)+"...":a}function c(p){return{success:!0,result:p}}function _(p,f){return{success:!1,error:p,details:o(f)}}function v(p){return{success:!1,error:"SERVICE_UNAVAILABLE",details:`Service ${p} is not available`}}},77659:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AINativeContextKey=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(50394);let _=class{get contextKeyService(){return this._contextKeyService}constructor(p){this._contextKeyService=this.globalContextKeyService.createScoped(p),this.inlineChatIsVisible=c.InlineChatIsVisible.bind(this._contextKeyService),this.inlineCompletionIsTrigger=c.InlineCompletionIsTrigger.bind(this._contextKeyService),this.inlineHintWidgetIsVisible=c.InlineHintWidgetIsVisible.bind(this._contextKeyService),this.inlineInputWidgetIsVisible=c.InlineInputWidgetIsVisible.bind(this._contextKeyService),this.inlineInputWidgetIsStreaming=c.InlineInputWidgetIsStreaming.bind(this._contextKeyService),this.inlineDiffPartialEditsIsVisible=c.InlineDiffPartialEditsIsVisible.bind(this._contextKeyService),this.codeEditsIsVisible=c.CodeEditsIsVisible.bind(this._contextKeyService)}};t.AINativeContextKey=_,n.__decorate([(0,r.Autowired)(o.IContextKeyService),n.__metadata("design:type",Object)],_.prototype,"globalContextKeyService",void 0),t.AINativeContextKey=_=n.__decorate([(0,r.Injectable)(),n.__param(0,(0,r.Optional)()),n.__metadata("design:paramtypes",[Object])],_)},32016:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AINativeBrowserContribution=t.INLINE_DIFF_MANAGER_WIDGET_ID=void 0;const n=e(85608),r=n.__importDefault(e(14041)),o=e(76003),c=e(41869),_=e(57925),v=e(50394),p=e(1149),f=e(93899),a=e(97222),u=e(43718),s=e(82353),l=e(54414),d=e(57517),g=e(51553),E=e(63067),m=e(72665),h=e(46507),b=e(97682),A=e(68415),y=e(96640),S=e(19413),w=e(46044),T=e(64811),I=e(69820),D=e(75334),R=e(29212),M=e(46572),O=e(5871),x=e(3504),k=e(32815),N=e(74296),L=e(59805),B=e(13682),K=e(38583),W=e(96743),U=e(68840),G=e(80945),j=e(44279),Y=e(87540),z=e(98987),V=e(61282),$=e(42995),H=e(51081),Q=e(29770),Z=e(59347),te=e(4457),ie=e(76154),ce=e(15764),me=e(28524),q=e(57987),be=e(49601),fe=e(79559),ne=e(57232),ge=e(72991),Oe=e(71863),Pe=e(7511),Me=e(42911),ke=e(72801),De=e(87817),pe=e(48590),Ie=e(79169),Ae=e(4972),xe=e(82983),_e=e(73974),re=e(33108),le=e(77633),Se=e(51221),Ee=e(2281),Ne=e(31031),Ye=e(95608),Ve=e(38890),mt=e(77886),_t=e(89060),Ot=e(74353),nt=e(22169),yt=e(90058);t.INLINE_DIFF_MANAGER_WIDGET_ID="inline-diff-manager-widget";const rt=()=>{const ct=(0,c.useInjectable)(u.ChatViewRegistryToken).getActiveChatView();return ct?r.default.createElement(ct.component):null};let Xe=class{constructor(){this.registerFeature()}registerMultiDiffSourceResolver(ct){return ct.registerResolver(this.chatMultiDiffResolver)}registerEditorDocumentModelContentProvider(ct){ct.registerEditorDocumentModelContentProvider(this.chatEditResourceProvider)}async initialize(){this.panelLayoutService.initialize();const{supportsChatAssistant:ct,supportsAgentMode:Tt}=this.aiNativeConfigService.capabilities;ct&&(c.ComponentRegistryImpl.addLayoutModule(this.appConfig.layoutConfig,S.AI_CHAT_VIEW_ID,S.AI_CHAT_CONTAINER_ID),c.ComponentRegistryImpl.addLayoutModule(this.appConfig.layoutConfig,s.DESIGN_MENU_BAR_RIGHT,S.AI_CHAT_LOGO_AVATAR_ID),this.chatProxyService.registerDefaultAgent(),Tt||(this.chatInternalService.init(),this.chatManagerService.init()))}registerEditorExtensionContribution(ct){const{supportsInlineChat:Tt,supportsInlineCompletion:Qt,supportsProblemFix:dn,supportsCodeAction:Kn}=this.aiNativeConfigService.capabilities;ct(Ve.InlineDiffController.ID,new y.SyncDescriptor(Ve.InlineDiffController,[this.injector]),b.EditorContributionInstantiation.Lazy),Kn&&ct(yt.SumiLightBulbWidget.ID,yt.SumiLightBulbWidget,b.EditorContributionInstantiation.Lazy),Tt&&(ct(Se.InlineChatEditorController.ID,new y.SyncDescriptor(Se.InlineChatEditorController,[this.injector]),b.EditorContributionInstantiation.BeforeFirstInteraction),this.inlineInputService.getInteractiveInputHandler()&&(ct(mt.InlineHintController.ID,new y.SyncDescriptor(mt.InlineHintController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender),ct(_t.InlineInputController.ID,new y.SyncDescriptor(_t.InlineInputController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender))),Qt&&(ct(Pe.IntelligentCompletionsController.ID,new y.SyncDescriptor(Pe.IntelligentCompletionsController,[this.injector]),b.EditorContributionInstantiation.Eager),ct(ge.InlineCompletionsController.ID,new y.SyncDescriptor(ge.InlineCompletionsController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender)),dn&&ct(Me.ProblemFixController.ID,new y.SyncDescriptor(Me.ProblemFixController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender)}onReconnect(){const{supportsMCP:ct}=this.aiNativeConfigService.capabilities;ct&&this.initMCPServers()}onDidStart(){this.registerWebMcpSurface(),(0,u.runWhenIdle)(()=>{const{supportsAgentMode:ct,supportsRenameSuggestions:Tt,supportsInlineChat:Qt,supportsMCP:dn,supportsCustomLLMSettings:Kn}=this.aiNativeConfigService.capabilities,fn=this.preferenceService.getValid(c.AINativeSettingSectionsId.ChatVisibleType);fn==="always"?this.commandService.executeCommand(_.AI_CHAT_VISIBLE.id,!0):fn==="never"&&this.commandService.executeCommand(_.AI_CHAT_VISIBLE.id,!1),Tt&&this.renameSingleHandler.load(),Qt&&this.codeActionSingleHandler.load(),Kn&&(this.preferenceService.onSpecificPreferenceChange(c.AINativeSettingSectionsId.LLMModelSelection,qt=>{const Rn=this.getModelByName(qt.newValue),zt=Rn?Object.keys(Rn):[],st=zt.length?zt[0]:"",$e=this.preferenceSchemaProvider.getPreferenceProperty(c.AINativeSettingSectionsId.ModelID);this.preferenceSchemaProvider.setSchema({properties:{[c.AINativeSettingSectionsId.ModelID]:{...$e,default:st,defaultValue:st,enum:zt.length?zt:void 0}}},!0),this.preferenceService.set(c.AINativeSettingSectionsId.ModelID,st,qt.scope),this.preferenceSettings.setEnumLabels(c.AINativeSettingSectionsId.ModelID,zt.reduce((Le,Fe)=>({...Le,[Fe]:Fe}),{}))}),this.preferenceService.onSpecificPreferenceChange(c.AINativeSettingSectionsId.ModelID,qt=>{const Rn=this.preferenceService.get(c.AINativeSettingSectionsId.LLMModelSelection);if(!Rn)return;const zt=this.getModelByName(Rn);zt&&zt[qt.newValue]&&(this.preferenceService.set(c.AINativeSettingSectionsId.MaxTokens,zt[qt.newValue].maxTokens,qt.scope),this.preferenceService.set(c.AINativeSettingSectionsId.ContextWindow,zt[qt.newValue].contextWindow,qt.scope))})),dn&&this.initMCPServers(),ct&&this.warmUpDefaultAcpPool()})}onStop(){var ct;(ct=this.webMcpModelContextDisposable)===null||ct===void 0||ct.dispose()}warmUpDefaultAcpPool(){const ct=this.aiBackService.warmUpAgentPool,Tt=this.acpConfigProvider.resolvePrewarmConfig;!ct||!Tt||Tt.call(this.acpConfigProvider).then(async Qt=>{Qt&&await ct.call(this.aiBackService,Qt)},Qt=>{this.logger.warn("[AINative] Failed to resolve ACP pool warmup config",Qt)}).catch(Qt=>{this.logger.warn("[AINative] Failed to warm up ACP agent pool",Qt)})}registerWebMcpSurface(){if(this.webMcpModelContextDisposable)return;const ct=this.injector.get(u.WebMcpGroupRegistryToken);ct.registerGroup((0,B.createOpenSumiMcpGroup)(this.injector)),ct.registerGroup((0,U.createWorkspaceGroup)(this.injector)),ct.registerGroup((0,K.createSearchGroup)(this.injector)),ct.registerGroup((0,k.createDiagnosticsGroup)(this.injector)),ct.registerGroup((0,L.createFileGroup)(this.injector)),ct.registerGroup((0,W.createTerminalGroup)(this.injector)),ct.registerGroup((0,N.createEditorGroup)(this.injector)),ct.registerGroup((0,x.createAcpChatGroup)(this.injector)),this.webMcpModelContextDisposable=(0,G.registerWebMcpModelContextTools)(ct)}async initMCPServers(){var ct,Tt;const Qt=await this.storageProvider(u.STORAGE_NAMESPACE.CHAT);let dn=Qt.get(T.MCPServersDisabledKey,[]);const Kn=this.preferenceService.get(c.AINativeSettingSectionsId.MCPServers,[]);let fn=this.preferenceService.resolve("mcp",{mcpServers:{}},void 0);if(fn.scope===u.PreferenceScope.Default&&Kn.length>0){const zt={mcpServers:{}},st=new Set;Kn.forEach($e=>{$e.type===I.MCP_SERVER_TYPE.SSE?zt.mcpServers[$e.name]={url:$e.serverHost}:$e.type===I.MCP_SERVER_TYPE.STDIO&&(zt.mcpServers[$e.name]={command:$e.command,args:$e.args,env:$e.env}),$e.enabled||st.add($e.name)}),!((ct=Kn.find($e=>$e.name===S.BUILTIN_MCP_SERVER_NAME))===null||ct===void 0)&&ct.enabled||st.add(S.BUILTIN_MCP_SERVER_NAME),await this.preferenceService.set("mcp",zt,u.PreferenceScope.Workspace),fn=this.preferenceService.resolve("mcp",{mcpServers:{}},void 0),dn=Array.from(st),Qt.set(T.MCPServersDisabledKey,dn)}const qt=(Tt=fn.value)===null||Tt===void 0?void 0:Tt.mcpServers,Rn=this.preferenceService.get(c.AINativeSettingSectionsId.WebMcpEnabled,!0);if(this.sumiMCPServerBackendProxy.$initBuiltinMCPServer(!dn.includes(S.BUILTIN_MCP_SERVER_NAME)&&Rn!==!1),qt&&Object.keys(qt).length>0){const zt=(await Promise.all(Object.keys(qt).map(async st=>await this.mcpConfigService.getServerConfigByName(st)))).filter(st=>st!==void 0);await this.sumiMCPServerBackendProxy.$initExternalMCPServers(zt)}this.mcpConfigService.fireMCPServersChange(!0)}getModelByName(ct){switch(ct){case"deepseek":return S.deepSeekModels;case"anthropic":return S.anthropicModels;case"openai":return S.openAiNativeModels;default:return}}registerFeature(){this.contributions.getContributions().forEach(ct=>{var Tt,Qt,dn,Kn,fn,qt,Rn,zt,st;(Tt=ct.registerInlineChatFeature)===null||Tt===void 0||Tt.call(ct,this.inlineChatFeatureRegistry),(Qt=ct.registerChatFeature)===null||Qt===void 0||Qt.call(ct,this.chatFeatureRegistry),(dn=ct.registerResolveConflictFeature)===null||dn===void 0||dn.call(ct,this.resolveConflictRegistry),(Kn=ct.registerRenameProvider)===null||Kn===void 0||Kn.call(ct,this.renameCandidatesProviderRegistry),(fn=ct.registerChatRender)===null||fn===void 0||fn.call(ct,this.chatRenderRegistry),(qt=ct.registerTerminalProvider)===null||qt===void 0||qt.call(ct,this.terminalProviderRegistry),(Rn=ct.registerIntelligentCompletionFeature)===null||Rn===void 0||Rn.call(ct,this.intelligentCompletionsRegistry),(zt=ct.registerProblemFixFeature)===null||zt===void 0||zt.call(ct,this.problemFixProviderRegistry),(st=ct.registerChatAgentPromptProvider)===null||st===void 0||st.call(ct)}),this.registerDefaultInputs(),this.registerChatViews(),this.aiNativeConfigService.capabilities.supportsChatAssistant&&this.inlineChatFeatureRegistry.registerEditorInlineChat({id:"ai-chat",name:"Chat",title:"Add to Chat",renderType:"button"},{execute:async(ct,Tt)=>{const Qt=ct.getModel();if(!Qt)return;const dn=Qt.uri,[Kn,fn]=[Tt.selectionStartLineNumber,Tt.positionLineNumber].sort((qt,Rn)=>qt-Rn);this.llmContextService.addFileToContext(new u.URI(dn.toString()),[Kn,fn],!0),this.chatService.sendMessage({message:"",immediate:!1})}}),this.mcpServerContributions.getContributions().forEach(ct=>{ct.registerMCPServer(this.mcpServerRegistry)})}registerDefaultInputs(){this.chatInputRegistry.registerChatInput({id:"acp-mention-input",component:M.AcpChatMentionInput,capabilities:["restore-draft","focus","expand","images","mentions","paste","rich-queued-edit"],queuedTurnEditor:O.AcpQueuedTurnEditor,priority:200,when:()=>this.aiNativeConfigService.capabilities.supportsAgentMode}),this.chatInputRegistry.registerChatInput({id:"acp-chat-input",component:R.AcpChatInput,capabilities:["restore-draft","focus","expand"],priority:150,when:()=>this.aiNativeConfigService.capabilities.supportsAgentMode}),this.chatInputRegistry.registerChatInput({id:"mention-input",component:be.ChatMentionInput,priority:100,when:()=>this.aiNativeConfigService.capabilities.supportsMCP}),this.chatInputRegistry.registerChatInput({id:"chat-input",component:q.ChatInput,priority:50})}registerChatViews(){this.chatViewRegistry.registerChatView({id:"acp-chat-view",component:ce.AIChatViewACP,priority:200,when:()=>this.aiNativeConfigService.capabilities.supportsAgentMode}),this.chatViewRegistry.registerChatView({id:"default-chat-view",component:ie.AIChatView,priority:50})}registerSetting(ct){ct.registerSettingGroup({id:c.AI_NATIVE_SETTING_GROUP_ID,title:u.AI_NATIVE_SETTING_GROUP_TITLE,iconClass:(0,c.getIcon)("magic-wand")}),ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.chat.title"),preferences:[{id:c.AINativeSettingSectionsId.ChatVisibleType,localized:"preference.ai.native.chat.visible.type"},{id:c.AINativeSettingSectionsId.PanelLayout,localized:"preference.ai.native.panelLayout"}]}),ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.interface.quick.title"),preferences:[{id:c.AINativeSettingSectionsId.InterfaceQuickNavigationEnabled,localized:"preference.ai.native.interface.quick.navigation"}]}),this.aiNativeConfigService.capabilities.supportsInlineCompletion&&(ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.intelligentCompletions.title"),preferences:[{id:c.AINativeSettingSectionsId.IntelligentCompletionsCacheEnabled,localized:"preference.ai.native.intelligentCompletions.cache.enabled"},{id:c.AINativeSettingSectionsId.IntelligentCompletionsDebounceTime,localized:"preference.ai.native.intelligentCompletions.debounceTime"},{id:c.AINativeSettingSectionsId.IntelligentCompletionsPromptEngineeringEnabled,localized:"preference.ai.native.intelligentCompletions.promptEngineering.enabled"},{id:c.AINativeSettingSectionsId.IntelligentCompletionsAlwaysVisible,localized:"preference.ai.native.intelligentCompletions.alwaysVisible"}]}),ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.codeEdits.title"),preferences:[{id:c.AINativeSettingSectionsId.CodeEditsLintErrors,localized:"preference.ai.native.codeEdits.lintErrors"},{id:c.AINativeSettingSectionsId.CodeEditsLineChange,localized:"preference.ai.native.codeEdits.lineChange"},{id:c.AINativeSettingSectionsId.CodeEditsTyping,localized:"preference.ai.native.codeEdits.typing"},{id:c.AINativeSettingSectionsId.CodeEditsRenderType,localized:"preference.ai.native.codeEdits.renderType"},{id:c.AINativeSettingSectionsId.SystemPrompt,localized:"preference.ai.native.chat.system.prompt"}]})),this.aiNativeConfigService.capabilities.supportsCustomLLMSettings&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.llm.apiSettings.title"),preferences:[{id:c.AINativeSettingSectionsId.LLMModelSelection,localized:"preference.ai.native.llm.model.selection"},{id:c.AINativeSettingSectionsId.ModelID,localized:"preference.ai.native.llm.model.id"},{id:c.AINativeSettingSectionsId.DeepseekApiKey,localized:"preference.ai.native.deepseek.apiKey"},{id:c.AINativeSettingSectionsId.AnthropicApiKey,localized:"preference.ai.native.anthropic.apiKey"},{id:c.AINativeSettingSectionsId.OpenaiApiKey,localized:"preference.ai.native.openai.apiKey"},{id:c.AINativeSettingSectionsId.OpenaiBaseURL,localized:"preference.ai.native.openai.baseURL"},{id:c.AINativeSettingSectionsId.MaxTokens,localized:"preference.ai.native.maxTokens"},{id:c.AINativeSettingSectionsId.ContextWindow,localized:"preference.ai.native.contextWindow"}]}),this.aiNativeConfigService.capabilities.supportsMCP&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.mcp.settings.title"),preferences:[{id:c.AINativeSettingSectionsId.MCPServers,localized:"preference.ai.native.mcp.servers"},{id:c.AINativeSettingSectionsId.TerminalAutoRun,localized:"ai.native.terminal.autorun"}]}),this.aiNativeConfigService.capabilities.supportsAgentMode&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.agent.configs.title"),preferences:[{id:c.AINativeSettingSectionsId.AgentConfigs,localized:"preference.ai.native.agent.configs"},{id:c.AINativeSettingSectionsId.DefaultAgentType,localized:"preference.ai.native.agent.defaultType"},{id:c.AINativeSettingSectionsId.AcpThreadPoolSize,localized:"preference.ai-native.acp.threadPoolSize"},{id:c.AINativeSettingSectionsId.AcpDeliveryMode,localized:"preference.ai-native.acp.deliveryMode"}]}),this.aiNativeConfigService.capabilities.supportsInlineChat&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.inlineChat.title"),preferences:[{id:c.AINativeSettingSectionsId.InlineChatAutoVisible,localized:"preference.ai.native.inlineChat.auto.visible"},{id:c.AINativeSettingSectionsId.InlineChatCodeActionEnabled,localized:"preference.ai.native.inlineChat.codeAction.enabled"},{id:c.AINativeSettingSectionsId.InlineDiffPreviewMode,localized:"preference.ai.native.inlineDiff.preview.mode"}]})}registerEditorFeature(ct){ct.registerEditorFeatureContribution({contribute:Tt=>{const{monacoEditor:Qt}=Tt;return this.codeActionSingleHandler.mountEditor(Tt.monacoEditor),Qt.onDidScrollChange(()=>{this.ctxMenuRenderer.visible&&this.ctxMenuRenderer.hide(!0)})}})}registerEditorComponent(ct){ct.registerEditorSideWidget({id:t.INLINE_DIFF_MANAGER_WIDGET_ID,component:Ye.InlineDiffManager,displaysOnResource:Tt=>{var Qt;return!!(this.aiNativeConfigService.capabilities.supportsMCP&&(!((Qt=this.applyService.getUriCodeBlocks(Tt.uri))===null||Qt===void 0)&&Qt.filter(dn=>dn.status==="pending").length))}})}registerCommands(ct){(0,pe.registerAgenticWorkbenchRevealCommandInterceptors)(ct,this.panelLayoutService,this.mainLayoutService),ct.registerCommand(j.AI_CHAT_INPUT_TOGGLE_EXPANDED,{execute:()=>{var Tt,Qt;return(Qt=(Tt=this.chatInputRegistry.getActiveInputHandle())===null||Tt===void 0?void 0:Tt.toggleExpanded)===null||Qt===void 0?void 0:Qt.call(Tt)}}),ct.registerCommand({...Y.AI_CHAT_NEW_CHAT,enablement:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == classic`},{execute:()=>{const Tt=this.chatInputRegistry.preserveActiveDraft()||this.aiChatService.getInputDraft();this.aiChatService.updateInputDraft(Tt),this.panelLayoutService.showAIChatView("classic"),this.aiChatService.enterDraftSession(),this.chatInputRegistry.restoreActiveDraft(Tt),this.focusChatInputAfterReveal()}}),ct.registerCommand({...Y.AI_CHAT_NEW_TASK,enablement:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == agentic`},{execute:async Tt=>{const Qt=this.chatInputRegistry.preserveActiveDraft()||this.aiChatService.getInputDraft();this.aiChatService.updateInputDraft(Qt),this.panelLayoutService.showAIChatView("agentic");const dn=await this.agenticWorkspaceSwitchService.launchHeaderTask(Tt);if(dn.status==="launched"){this.chatInputRegistry.restoreActiveDraft(Qt),this.focusChatInputAfterReveal();return}if(dn.status==="no-agent"){const Kn=(0,c.localize)("aiNative.chat.agentSelector.configureAgents","Agent Configurations");await this.messageService.warning((0,c.localize)("aiNative.chat.newTask.noAgent","No ACP Agent available"),[Kn],!0)===Kn&&(await this.preferenceService.set(c.AINativeSettingSectionsId.AgentConfigs,(0,me.getAvailableAgentConfigs)(this.preferenceService),u.PreferenceScope.User),await this.commandService.executeCommand(c.COMMON_COMMANDS.OPEN_PREFERENCES.id,c.AINativeSettingSectionsId.AgentConfigs));return}if(dn.status==="project-unavailable"||dn.status==="no-project"){await this.messageService.warning((0,c.localize)("aiNative.chat.newTask.workspaceUnavailable","Workspace Target unavailable"));return}dn.status==="failed"&&await this.messageService.warning((0,c.localize)("aiNative.chat.newTask.failed","Failed to create a new Task"))}}),ct.registerCommand(_.AI_INLINE_CHAT_VISIBLE,{execute:Tt=>{this.aiInlineChatService._onInlineChatVisible.fire(Tt)}}),ct.registerCommand(_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE,{execute:async Tt=>{var Qt;if(!Tt){this.inlineInputService.hide();return}this.commandService.executeCommand(_.AI_INLINE_CHAT_VISIBLE.id,!1);const dn=this.workbenchEditorService.currentCodeEditor;if(!dn)return;const Kn=dn.monacoEditor.getPosition();if(!Kn)return;const fn=dn.monacoEditor.getSelection();if(Kn?((Qt=dn.monacoEditor.getModel())===null||Qt===void 0?void 0:Qt.getLineLength(Kn.lineNumber))===0:!1){this.inlineInputService.visibleByPosition(Kn);return}if(fn&&!fn.isEmpty()){this.inlineInputService.visibleBySelection(fn);return}this.inlineInputService.visibleByNearestCodeBlock(Kn,dn.monacoEditor)}}),ct.registerCommand(_.AI_INLINE_CHAT_INTERACTIVE_INPUT_CANCEL,{execute:()=>{var Tt;const Qt=this.workbenchEditorService.currentCodeEditor;Qt&&((Tt=_t.InlineInputController.get(Qt.monacoEditor))===null||Tt===void 0||Tt.cancelToken())}}),ct.registerCommand(_.AI_INLINE_COMPLETION_REPORTER,{execute:(Tt,Qt,dn,Kn)=>{this.aiCompletionsService.report({sessionId:Qt,accept:dn,relationId:Tt,code:Kn})}}),ct.registerCommand(_.AI_CHAT_VISIBLE,{execute:Tt=>{if(Tt===!1){this.panelLayoutService.hideAIChatView();return}this.panelLayoutService.showAIChatView()}}),ct.registerCommand(_.AI_PANEL_LAYOUT_SET,{execute:Tt=>this.panelLayoutService.setLayoutMode(Tt)}),ct.registerCommand(_.AI_PANEL_LAYOUT_GET,{execute:()=>this.panelLayoutService.getLayoutMode()}),ct.registerCommand(_.AI_PANEL_LAYOUT_TOGGLE,{execute:()=>this.panelLayoutService.toggleLayoutMode()}),ct.registerCommand(_.AI_AGENTIC_WORKBENCH_TOGGLE,{execute:Tt=>this.panelLayoutService.toggleAgenticWorkbenchVisibility(Tt)}),ct.registerCommand(_.AI_AGENTIC_WORKBENCH_IS_VISIBLE,{execute:()=>this.panelLayoutService.isAgenticWorkbenchVisible()}),ct.registerCommand(_.AI_INLINE_COMPLETION_VISIBLE,{execute:async Tt=>{Tt||(this.aiCompletionsService.hideStatusBarItem(),this.aiInlineCompletionsProvider.setVisibleCompletion(!1),this.aiInlineCompletionsProvider.cancelRequest())}}),ct.registerCommand(_.AI_INLINE_DIFF_PARTIAL_EDIT,{execute:Tt=>{this.inlineStreamDiffService.launchAcceptDiscardPartialEdit(Tt)}}),ct.afterExecuteCommand(A.HideInlineCompletion.ID,()=>{this.commandService.executeCommand(_.AI_INLINE_COMPLETION_VISIBLE.id,!1)})}focusChatInputAfterReveal(){const ct=(Tt=0)=>{this.chatInputRegistry.focusActiveInput(),!(this.chatInputRegistry.isActiveInputFocused()!==!1||Tt>=60)&&c.fastdom.measureAtNextFrame(()=>ct(Tt+1))};ct()}registerMenus(ct){ct.registerMenuItem(f.MenuId.MenubarViewMenu,{submenu:Ie.AI_PANEL_LAYOUT_MENU,label:"Panel Layout",group:"5_panel"}),ct.registerMenuItem(Ie.AI_PANEL_LAYOUT_MENU,{command:{id:_.AI_PANEL_LAYOUT_SET.id,label:"Classic"},group:"navigation",extraTailArgs:["classic"],toggledWhen:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == classic`}),ct.registerMenuItem(Ie.AI_PANEL_LAYOUT_MENU,{command:{id:_.AI_PANEL_LAYOUT_SET.id,label:"Agent"},group:"navigation",extraTailArgs:["agentic"],toggledWhen:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == agentic`})}registerRenderer(ct){const Tt={isLatter:!0};this.designLayoutConfig.supportExternalChatPanel?ct.registerSlotRenderer(S.AI_CHAT_VIEW_ID,Ae.AIChatTabRendererWithTab,Tt):ct.registerSlotRenderer(S.AI_CHAT_VIEW_ID,Ae.AIChatTabRenderer,Tt),this.designLayoutConfig.useMergeRightWithLeftPanel&&(ct.registerSlotRenderer(c.SlotLocation.view,Ae.AILeftTabRenderer,Object.assign({},Tt,{isLatter:!1})),ct.registerSlotRenderer(c.SlotLocation.extendView,Ae.AIRightTabRenderer,Tt))}registerComponent(ct){ct.register(S.AI_CHAT_CONTAINER_ID,[],{component:rt,title:(0,c.localize)("aiNative.chat.ai.assistant.name"),iconClass:(0,c.getIcon)("magic-wand"),containerId:S.AI_CHAT_CONTAINER_ID}),ct.register(S.AI_MENU_BAR_DEBUG_TOOLBAR,{id:S.AI_MENU_BAR_DEBUG_TOOLBAR,component:De.AIRunToolbar}),ct.register(S.AI_CHAT_LOGO_AVATAR_ID,{id:S.AI_CHAT_LOGO_AVATAR_ID,component:xe.AIChatLogoAvatar})}registerKeybindings(ct){this.aiNativeConfigService.capabilities.supportsAgentMode&&(ct.registerKeybinding({command:Y.AI_CHAT_NEW_CHAT.id,keybinding:"ctrlcmd+alt+n",when:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == classic`},c.KeybindingScope.USER),ct.registerKeybinding({command:Y.AI_CHAT_NEW_TASK.id,keybinding:"ctrlcmd+alt+n",when:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == agentic`},c.KeybindingScope.USER)),this.aiNativeConfigService.capabilities.supportsInlineChat&&(ct.registerKeybinding({command:_.AI_INLINE_CHAT_VISIBLE.id,keybinding:"ctrlcmd+i",when:"editorTextFocus",args:!0,priority:0},c.KeybindingScope.USER),ct.registerKeybinding({command:_.AI_INLINE_CHAT_VISIBLE.id,keybinding:"esc",args:!1,when:`editorFocus && ${v.InlineChatIsVisible.raw}`}),this.inlineInputService.getInteractiveInputHandler()&&(ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE.id,keybinding:this.aiNativeConfigService.inlineChat.inputKeybinding,args:!0,priority:0,when:`editorFocus && (${v.InlineChatIsVisible.raw} || inlineSuggestionVisible)`},c.KeybindingScope.USER),ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE.id,keybinding:"esc",args:!1,priority:0,when:`editorFocus && ${v.InlineInputWidgetIsVisible.raw}`}),ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_CANCEL.id,keybinding:"esc",priority:1,when:`editorFocus && ${v.InlineInputWidgetIsStreaming.raw}`}),ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE.id,keybinding:this.aiNativeConfigService.inlineChat.inputKeybinding,args:!0,priority:0,when:`editorFocus && ${v.InlineHintWidgetIsVisible.raw} && ${v.InlineChatIsVisible.not}`},c.KeybindingScope.USER))),ct.registerKeybinding({command:_.AI_INLINE_DIFF_PARTIAL_EDIT.id,keybinding:"ctrl+y",args:!0,priority:100,when:`editorTextFocus && ${v.InlineDiffPartialEditsIsVisible.raw}`}),ct.registerKeybinding({command:_.AI_INLINE_DIFF_PARTIAL_EDIT.id,keybinding:"ctrl+n",args:!1,priority:100,when:`editorTextFocus && ${v.InlineDiffPartialEditsIsVisible.raw}`})}};t.AINativeBrowserContribution=Xe,n.__decorate([(0,o.Autowired)(c.AppConfig),n.__metadata("design:type",Object)],Xe.prototype,"appConfig",void 0),n.__decorate([(0,o.Autowired)(o.INJECTOR_TOKEN),n.__metadata("design:type",o.Injector)],Xe.prototype,"injector",void 0),n.__decorate([(0,o.Autowired)(a.IBrowserCtxMenu),n.__metadata("design:type",a.IBrowserCtxMenu)],Xe.prototype,"ctxMenuRenderer",void 0),n.__decorate([(0,o.Autowired)(le.AINativeCoreContribution),n.__metadata("design:type",Object)],Xe.prototype,"contributions",void 0),n.__decorate([(0,o.Autowired)(le.MCPServerContribution),n.__metadata("design:type",Object)],Xe.prototype,"mcpServerContributions",void 0),n.__decorate([(0,o.Autowired)(le.TokenMCPServerRegistry),n.__metadata("design:type",Object)],Xe.prototype,"mcpServerRegistry",void 0),n.__decorate([(0,o.Autowired)(u.InlineChatFeatureRegistryToken),n.__metadata("design:type",Ee.InlineChatFeatureRegistry)],Xe.prototype,"inlineChatFeatureRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ChatFeatureRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatFeatureRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ChatRenderRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatRenderRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ChatInputRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatInputRegistry",void 0),n.__decorate([(0,o.Autowired)(S.IChatInternalService),n.__metadata("design:type",te.AcpChatInternalService)],Xe.prototype,"aiChatService",void 0),n.__decorate([(0,o.Autowired)(u.ChatViewRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatViewRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ResolveConflictRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"resolveConflictRegistry",void 0),n.__decorate([(0,o.Autowired)(u.RenameCandidatesProviderRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"renameCandidatesProviderRegistry",void 0),n.__decorate([(0,o.Autowired)(u.TerminalRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"terminalProviderRegistry",void 0),n.__decorate([(0,o.Autowired)(u.IntelligentCompletionsRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"intelligentCompletionsRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ProblemFixRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"problemFixProviderRegistry",void 0),n.__decorate([(0,o.Autowired)(c.AINativeConfigService),n.__metadata("design:type",c.AINativeConfigService)],Xe.prototype,"aiNativeConfigService",void 0),n.__decorate([(0,o.Autowired)(u.AIBackSerivcePath),n.__metadata("design:type",Object)],Xe.prototype,"aiBackService",void 0),n.__decorate([(0,o.Autowired)(u.IACPConfigProvider),n.__metadata("design:type",Object)],Xe.prototype,"acpConfigProvider",void 0),n.__decorate([(0,o.Autowired)(u.ILogger),n.__metadata("design:type",Object)],Xe.prototype,"logger",void 0),n.__decorate([(0,o.Autowired)(p.DesignLayoutConfig),n.__metadata("design:type",p.DesignLayoutConfig)],Xe.prototype,"designLayoutConfig",void 0),n.__decorate([(0,o.Autowired)(Ie.AIPanelLayoutService),n.__metadata("design:type",Ie.AIPanelLayoutService)],Xe.prototype,"panelLayoutService",void 0),n.__decorate([(0,o.Autowired)(D.AgenticWorkspaceSwitchService),n.__metadata("design:type",D.AgenticWorkspaceSwitchService)],Xe.prototype,"agenticWorkspaceSwitchService",void 0),n.__decorate([(0,o.Autowired)(m.IMessageService),n.__metadata("design:type",Object)],Xe.prototype,"messageService",void 0),n.__decorate([(0,o.Autowired)(Oe.AICompletionsService),n.__metadata("design:type",Oe.AICompletionsService)],Xe.prototype,"aiCompletionsService",void 0),n.__decorate([(0,o.Autowired)(ne.AIInlineCompletionsProvider),n.__metadata("design:type",ne.AIInlineCompletionsProvider)],Xe.prototype,"aiInlineCompletionsProvider",void 0),n.__decorate([(0,o.Autowired)(u.CommandService),n.__metadata("design:type",Object)],Xe.prototype,"commandService",void 0),n.__decorate([(0,o.Autowired)(c.PreferenceSchemaProvider),n.__metadata("design:type",c.PreferenceSchemaProvider)],Xe.prototype,"preferenceSchemaProvider",void 0),n.__decorate([(0,o.Autowired)(c.IPreferenceSettingsService),n.__metadata("design:type",Object)],Xe.prototype,"preferenceSettings",void 0),n.__decorate([(0,o.Autowired)(c.PreferenceService),n.__metadata("design:type",Object)],Xe.prototype,"preferenceService",void 0),n.__decorate([(0,o.Autowired)(S.ChatProxyServiceToken),n.__metadata("design:type",H.ChatProxyService)],Xe.prototype,"chatProxyService",void 0),n.__decorate([(0,o.Autowired)(c.IAIInlineChatService),n.__metadata("design:type",Ne.InlineChatService)],Xe.prototype,"aiInlineChatService",void 0),n.__decorate([(0,o.Autowired)(Ot.InlineInputService),n.__metadata("design:type",Ot.InlineInputService)],Xe.prototype,"inlineInputService",void 0),n.__decorate([(0,o.Autowired)(nt.InlineStreamDiffService),n.__metadata("design:type",nt.InlineStreamDiffService)],Xe.prototype,"inlineStreamDiffService",void 0),n.__decorate([(0,o.Autowired)(ke.RenameSingleHandler),n.__metadata("design:type",ke.RenameSingleHandler)],Xe.prototype,"renameSingleHandler",void 0),n.__decorate([(0,o.Autowired)(fe.CodeActionSingleHandler),n.__metadata("design:type",fe.CodeActionSingleHandler)],Xe.prototype,"codeActionSingleHandler",void 0),n.__decorate([(0,o.Autowired)(S.SumiMCPServerProxyServicePath),n.__metadata("design:type",Object)],Xe.prototype,"sumiMCPServerBackendProxy",void 0),n.__decorate([(0,o.Autowired)(u.MCPConfigServiceToken),n.__metadata("design:type",re.MCPConfigService)],Xe.prototype,"mcpConfigService",void 0),n.__decorate([(0,o.Autowired)(l.WorkbenchEditorService),n.__metadata("design:type",g.WorkbenchEditorServiceImpl)],Xe.prototype,"workbenchEditorService",void 0),n.__decorate([(0,o.Autowired)(E.IMainLayoutService),n.__metadata("design:type",Object)],Xe.prototype,"mainLayoutService",void 0),n.__decorate([(0,o.Autowired)(S.IChatManagerService),n.__metadata("design:type",V.ChatManagerService)],Xe.prototype,"chatManagerService",void 0),n.__decorate([(0,o.Autowired)(S.IChatInternalService),n.__metadata("design:type",Z.ChatInternalService)],Xe.prototype,"chatInternalService",void 0),n.__decorate([(0,o.Autowired)(_e.BaseApplyService),n.__metadata("design:type",_e.BaseApplyService)],Xe.prototype,"applyService",void 0),n.__decorate([(0,o.Autowired)(u.StorageProvider),n.__metadata("design:type",Function)],Xe.prototype,"storageProvider",void 0),n.__decorate([(0,o.Autowired)(u.ChatServiceToken),n.__metadata("design:type",Q.ChatService)],Xe.prototype,"chatService",void 0),n.__decorate([(0,o.Autowired)(w.LLMContextServiceToken),n.__metadata("design:type",Object)],Xe.prototype,"llmContextService",void 0),n.__decorate([(0,o.Autowired)(),n.__metadata("design:type",z.ChatEditSchemeDocumentProvider)],Xe.prototype,"chatEditResourceProvider",void 0),n.__decorate([(0,o.Autowired)(),n.__metadata("design:type",$.ChatMultiDiffResolver)],Xe.prototype,"chatMultiDiffResolver",void 0),t.AINativeBrowserContribution=Xe=n.__decorate([(0,c.Domain)(c.ClientAppContribution,d.BrowserEditorContribution,c.CommandContribution,h.SettingContribution,c.KeybindingContribution,c.ComponentContribution,c.SlotRendererContribution,f.MenuContribution,c.MonacoContribution,d.MultiDiffSourceContribution),n.__metadata("design:paramtypes",[])],Xe)},77852:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AcpQueuedTurns=void 0,t.getAcpQueuedTurnPreview=f;const n=e(85608),r=n.__importStar(e(14041)),o=e(41869),c=e(81878),_=e(70392),v=e(98864),p=n.__importDefault(e(77256));function f(s){return(0,v.cleanAttachedTextWrapper)(s).replace(/<br\s*\/?>/gi," ").replace(/<\/(div|p|li|section)>/gi," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/\s+/g," ").trim()||(0,o.localize)("aiNative.chat.queue.emptyPreview","Empty message")}function a(s){switch(s){case"manual-stop":return(0,o.localize)("aiNative.chat.queue.pauseReason.manualStop","Stopped");case"agent-error":return(0,o.localize)("aiNative.chat.queue.pauseReason.agentError","Agent error");case"start-failed":return(0,o.localize)("aiNative.chat.queue.pauseReason.startFailed","Could not start");case"cancel-failed":return(0,o.localize)("aiNative.chat.queue.pauseReason.cancelFailed","Could not stop");default:return}}const u=({snapshot:s,expanded:l,disabled:d=!1,capabilities:g,QueuedEditor:E,onToggleExpanded:m,onResume:h,onClear:b,onBeginEdit:A,onCommitEdit:y,onCancelEdit:S,onDelete:w,onImmediateSend:T,onEditorReady:I,onOpenCapacitySettings:D})=>{var R,M;if(s.initialStartPending)return r.createElement("div",{className:p.default.queued_turns_status,"data-testid":"acp-task-launch-status",role:"status"},r.createElement("span",null,(0,o.localize)("aiNative.chat.acp.startingTask","Starting task\u2026")));if(s.entries.length===0&&s.phase!=="paused")return null;const O=g.includes("rich-queued-edit")&&!!E,x=!!s.editingTurnId,k=s.entries.length===1?(0,o.localize)("aiNative.chat.queue.one","1 Queued Turn"):_.strings.format((0,o.localize)("aiNative.chat.queue.many","{0} Queued Turns"),s.entries.length),N=a(s.pauseReason),L=((R=s.pauseError)===null||R===void 0?void 0:R.name)==="ACP_THREAD_POOL_SATURATED",B=(M=s.pauseError)===null||M===void 0?void 0:M.limit;return r.createElement("section",{className:p.default.queued_turns,"aria-label":(0,o.localize)("aiNative.chat.queue.ariaLabel","Queued turns")},r.createElement("div",{className:p.default.queued_turns_header},r.createElement("button",{"aria-expanded":l,"aria-label":(0,o.localize)("aiNative.chat.queue.toggleAriaLabel","Toggle queued turns"),className:p.default.queued_turns_summary,"data-testid":"acp-queued-turns-summary",disabled:d||x,onClick:m,title:d||x?(0,o.localize)("aiNative.chat.queue.finishEditBeforeCollapse","Finish editing before collapsing"):void 0,type:"button"},r.createElement(c.Icon,{className:p.default.queued_turns_disclosure,iconClass:(0,o.getIcon)(l?"arrow-down":"arrow-right")}),r.createElement("span",null,k)),r.createElement("div",{className:p.default.queued_turns_header_actions},s.phase==="paused"&&!L&&r.createElement("div",{className:p.default.queued_turns_status,"data-testid":"acp-queued-turn-status",role:"status"},r.createElement("span",null,(0,o.localize)("aiNative.chat.queue.paused","Paused")),N&&r.createElement("span",{className:p.default.queued_turns_pause_reason},N),s.canResume&&r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.resumeAriaLabel","Resume queued turns"),className:p.default.queued_turns_resume,"data-testid":"acp-queued-turn-resume",disabled:d,onClick:h,type:"button"},(0,o.localize)("aiNative.chat.queue.resume","Resume Queue"))),s.entries.length>0&&r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.clearAriaLabel","Clear queued turns"),className:p.default.queued_turns_clear,disabled:d,onClick:b,type:"button"},(0,o.localize)("aiNative.chat.queue.clearAll","Clear All")))),s.phase==="paused"&&L&&r.createElement("div",{className:p.default.queued_turns_status,"data-testid":"acp-capacity-error",role:"alert"},r.createElement("span",null,B?_.strings.format((0,o.localize)("aiNative.chat.acp.capacityFull.withLimit","The Agent task capacity limit ({0}) has been reached, and no reusable Agent is currently available. Your task draft and unsent content have been preserved. Wait for a running task to finish and try again, or increase the ACP process limit in Settings."),B):(0,o.localize)("aiNative.chat.acp.capacityFull","The Agent task capacity limit has been reached, and no reusable Agent is currently available. Your task draft and unsent content have been preserved. Wait for a running task to finish and try again, or increase the ACP process limit in Settings.")),r.createElement("button",{"data-testid":"acp-capacity-retry",disabled:d,onClick:h,type:"button"},(0,o.localize)("aiNative.chat.acp.capacityRetry","Retry")),D&&r.createElement("button",{"data-testid":"acp-capacity-open-settings",disabled:d,onClick:D,type:"button"},(0,o.localize)("aiNative.chat.acp.capacityOpenSettings","Open Settings"))),l&&r.createElement("div",{className:p.default.queued_turns_list},s.entries.map((K,W)=>{const U=O&&s.editingTurnId===K.id;return r.createElement("div",{className:U?p.default.queued_turn_editing:p.default.queued_turn,"data-testid":"acp-queued-turn",key:K.id},U&&E?r.createElement("div",{className:p.default.queued_turn_editor,"data-testid":"acp-queued-turn-editor"},r.createElement(E,{turn:K,onSave:G=>d?void 0:y(K.id,G,!1),onCancel:()=>{d||S(K.id)},onImmediateSend:G=>d?void 0:y(K.id,G,!0),onReady:I,disabled:d,immediateSendDisabled:d||s.phase==="cancelling-for-immediate"})):r.createElement(r.Fragment,null,r.createElement("div",{className:p.default.queued_turn_index},W+1),r.createElement("div",{className:p.default.queued_turn_preview,"data-testid":"acp-queued-turn-preview"},f(K.message)),r.createElement("div",{className:p.default.queued_turn_actions},O&&r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.editAriaLabel","Edit queued turn"),"data-testid":"acp-queued-turn-edit",disabled:d,onClick:()=>A(K.id),type:"button"},(0,o.localize)("aiNative.chat.queue.edit","Edit")),r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.deleteAriaLabel","Delete queued turn"),"data-testid":"acp-queued-turn-delete",disabled:d,onClick:()=>w(K.id),type:"button"},(0,o.localize)("aiNative.chat.queue.delete","Delete")),r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.immediateAriaLabel","Send queued turn immediately"),"data-testid":"acp-queued-turn-immediate",disabled:d||s.phase==="cancelling-for-immediate",onClick:()=>T(K.id),type:"button"},(0,o.localize)("aiNative.chat.queue.immediate","Immediate Send")))))})))};t.AcpQueuedTurns=u},10929:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgenticChatHeaderMaximizeAction=void 0;const n=e(85608),r=n.__importDefault(e(14041)),o=e(41869),c=e(89195),_=e(79169),v=n.__importDefault(e(77256)),p=({id:f="ai-chat-header-maximize"})=>{const a=(0,o.useInjectable)(_.AIPanelLayoutService),[u,s]=r.default.useState(()=>a.getLayoutMode()),[l,d]=r.default.useState(()=>a.isAgenticWorkbenchVisible()!==!1),g=r.default.useCallback(()=>{const b=a.isAgenticWorkbenchVisible();d(typeof b=="boolean"?b:!0)},[a]);r.default.useEffect(()=>{s(a.getLayoutMode()),g();const b=a.onDidChangePanelLayout(A=>{s(A),g()});return()=>{b.dispose()}},[a,g]),r.default.useEffect(()=>{const b=a.onDidChangeAgenticWorkbenchVisibility(A=>{d(A)});return()=>{b.dispose()}},[a]);const E=r.default.useCallback(()=>{const b=a.toggleAgenticWorkbenchVisibility(!l);typeof b=="boolean"&&d(b)},[l,a]);if(u!=="agentic")return null;const m=(0,o.localize)(l?"aiNative.chat.expand.fullescreen":"aiNative.chat.expand.unfullscreen"),h=(0,o.getIcon)(l?"fullescreen":"unfullscreen");return r.default.createElement("div",{id:f,"data-workbench-visible":String(l)},r.default.createElement(c.EnhanceIcon,{wrapperClassName:v.default.action_btn,className:h,onClick:E,tabIndex:0,role:"button",ariaLabel:m,ariaPressed:!l}))};t.AgenticChatHeaderMaximizeAction=p},89705:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAgenticChatPanelTitle=w,t.AgenticChatPanelHeader=I,t.AgenticChatHeaderNewSessionMenu=D;const n=e(85608),r=n.__importDefault(e(53373)),o=n.__importDefault(e(14041)),c=e(41869),_=e(43718),v=e(27284),p=e(70392),f=e(51500),a=e(19413),u=e(98864),s=e(29993),l=e(20450),d=e(70004),g=e(79169),E=e(10929),m=n.__importDefault(e(77256)),h=e(28524),b=100,A={"claude-agent-acp":{label:"Claude",title:"Claude Code ACP"},qwen:{label:"Qwen",title:"Qwen"}};function y(R){const M=(0,h.getAvailableAgentConfigs)(R);return Object.entries(M).map(([O,x])=>{const k=A[O];return{value:O,label:k?.label||x.description||O,title:k?.title||S(O,x)}})}function S(R,M){return M.command?`${R} \xB7 ${M.command}`:R}function w(R,M=!1){if(M&&R?.title)return R.title.slice(0,b);const x=[...R?.history.getMessages()||[]].find(N=>N.role===1);return(x?(0,u.cleanAttachedTextWrapper)(x.content).slice(0,b):"")||(0,c.localize)("aiNative.chat.ai.assistant.name")}function T({onExecutionContextChange:R,sessionModel:M}){const O=(0,c.useInjectable)(a.IChatInternalService),x=(0,c.useInjectable)(s.AgenticTaskRegistryService),k=(0,c.useInjectable)(f.IWorkspaceService),[N,L]=o.default.useState(),[B,K]=o.default.useState(),W=o.default.useRef(0),U=o.default.useCallback(async()=>{var G;const j=++W.current,Y=k.workspace,z=(G=M?.requests)===null||G===void 0?void 0:G.at(-1),V=O.getActiveAgenticTaskTarget(M?.sessionId);try{const $=Y?.uri?_.URI.parse(Y.uri):void 0,H=$?.scheme==="file"&&Y?.isDirectory!==!1?{id:$.toString(),workspaceUri:$.toString(),workspacePath:$.codeUri.fsPath,joinedAt:0,availability:"available"}:void 0,Q=await x.listProjects(),Z=V?Q.find(ie=>ie.workspacePath===V.cwd):void 0,te=H?await x.getProject(H.id):void 0;if(j!==W.current)return;L(Z||te||H),R(Z&&Z.workspacePath!==H?.workspacePath?Z:void 0),K(V?.agentId||z?.message.agentId||O.getActiveAgenticTaskAgentId(M?.sessionId))}catch{j===W.current&&(L(void 0),R(void 0),K(void 0))}},[O,R,x,M,k]);return o.default.useEffect(()=>{U();const G=x.onDidChange(()=>void U()),j=k.onWorkspaceChanged(()=>void U()),Y=k.onWorkspaceLocationChanged(()=>void U());return()=>{W.current+=1,G.dispose(),j.dispose(),Y.dispose()}},[U,x,k]),o.default.createElement(d.AgenticTaskLaunchMenu,{project:N,preferredAgentId:B,variant:"chat-header"})}function I({onCloseTaskDraft:R,preferSessionTitle:M=!1,sessionModel:O}){var x;const k=(0,c.useInjectable)(a.IChatInternalService),N=(0,c.useInjectable)(c.PreferenceService),L=(0,c.useInjectable)(g.AIPanelLayoutService),[B,K]=o.default.useState(()=>L.getLayoutMode()),[W,U]=o.default.useState(()=>w(O,M)),[G,j]=o.default.useState(),Y=o.default.useRef(0),z=k.isActiveAgenticTaskDraft(),V=O?.title,$=k.getActiveAgenticTaskTarget(),H=$?.agentId,Q=H?((x=(0,h.getAvailableAgentConfigs)(N)[H])===null||x===void 0?void 0:x.description)||H:"",Z=$?_.URI.file($.cwd).displayName:"",te=o.default.useCallback(async()=>{++Y.current===Y.current&&U(z?(0,c.localize)("aiNative.chat.agenticTask.draft.title","New Session"):w(O,M))},[z,M,O,V]);return o.default.useEffect(()=>{K(L.getLayoutMode());const ie=L.onDidChangePanelLayout(ce=>{K(ce)});return()=>ie.dispose()},[L]),o.default.useEffect(()=>{te();const ie=O?.history.onMessageChange(()=>void te());return()=>{Y.current+=1,ie?.dispose()}},[te,O]),B!=="agentic"?null:o.default.createElement("div",{className:m.default.agentic_chat_panel_header,"data-testid":"agentic-chat-panel-header"},o.default.createElement("div",{className:m.default.agentic_chat_panel_title,"data-testid":"agentic-chat-panel-header-title",title:W},W),z&&o.default.createElement("div",{className:m.default.agentic_task_draft_context,"data-testid":"agentic-task-draft-context"},p.strings.format((0,c.localize)("aiNative.chat.agenticTask.draft.context","Using {0}"),Q),Z&&` \xB7 ${Z}`),G&&o.default.createElement("div",{"aria-label":p.strings.format((0,c.localize)("aiNative.chat.agenticTask.workingDirectory","Agent working directory: {0}"),G.workspacePath),className:m.default.agentic_task_execution_context,"data-testid":"agentic-task-execution-context",title:G.workspacePath},p.strings.format((0,c.localize)("aiNative.chat.agenticTask.workingDirectory","Agent working directory: {0}"),(0,l.getAgenticProjectDisplayLabel)(G))),o.default.createElement("div",{className:m.default.agentic_chat_panel_actions},z&&R&&o.default.createElement("button",{"aria-label":(0,c.localize)("aiNative.operate.close.title","Close"),className:m.default.agentic_task_draft_close,"data-testid":"agentic-task-draft-close",onClick:R,title:(0,c.localize)("aiNative.operate.close.title","Close"),type:"button"},o.default.createElement("span",{"aria-hidden":"true",className:"codicon codicon-close"})),o.default.createElement(T,{onExecutionContextChange:j,sessionModel:O}),o.default.createElement(E.AgenticChatHeaderMaximizeAction,{id:"agentic-chat-panel-header-maximize"})))}function D(){const R=(0,c.useInjectable)(a.IChatInternalService),M=(0,c.useInjectable)(c.PreferenceService),O=(0,c.useInjectable)(_.CommandService),[x,k]=o.default.useState(()=>y(M)),[N,L]=o.default.useState(()=>(0,h.getDefaultAgentType)(M)),[B,K]=o.default.useState(!1),[W,U]=o.default.useState(!1),G=o.default.useRef(void 0),j=o.default.useCallback(()=>{k(y(M)),L((0,h.getDefaultAgentType)(M))},[M]);o.default.useEffect(()=>{var Z,te;const ie=(Z=M.onSpecificPreferenceChange)===null||Z===void 0?void 0:Z.call(M,v.AINativeSettingSectionsId.DefaultAgentType,j),ce=(te=M.onSpecificPreferenceChange)===null||te===void 0?void 0:te.call(M,v.AINativeSettingSectionsId.AgentConfigs,j);return()=>{ie?.dispose(),ce?.dispose()}},[M,j]);const Y=o.default.useCallback(()=>{B||(G.current&&(window.clearTimeout(G.current),G.current=void 0),U(!0))},[B]),z=o.default.useCallback(()=>{G.current=window.setTimeout(()=>{U(!1),G.current=void 0},120)},[]);o.default.useEffect(()=>()=>{G.current&&window.clearTimeout(G.current)},[]);const V=o.default.useCallback(async Z=>{U(!1),K(!0);try{L(Z),await M.set(v.AINativeSettingSectionsId.DefaultAgentType,Z,_.PreferenceScope.User),R.enterDraftSession()}finally{K(!1)}},[R,M]),$=o.default.useCallback(async()=>{U(!1);try{await M.set(v.AINativeSettingSectionsId.AgentConfigs,(0,h.getAvailableAgentConfigs)(M),_.PreferenceScope.User)}finally{O.executeCommand(c.COMMON_COMMANDS.OPEN_PREFERENCES.id,v.AINativeSettingSectionsId.AgentConfigs)}},[O,M]),H=x.find(Z=>Z.value===N)||x[0],Q=(0,c.localize)("aiNative.operate.newChat.title");return o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu_group},o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu_container,onMouseEnter:Y,onMouseLeave:z},o.default.createElement("button",{"aria-disabled":B,"aria-expanded":W,"aria-haspopup":"menu","aria-label":Q,className:m.default.agentic_chat_new_session_button,"data-testid":"agentic-chat-new-session-button",disabled:B,onClick:Y,title:H?`${Q} \xB7 ${H.title}`:Q,type:"button"},o.default.createElement("span",{className:"codicon codicon-add"})),W&&o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu,"data-testid":"agentic-chat-new-session-menu",role:"menu"},x.map(Z=>{const te=Z.value===N;return o.default.createElement("button",{className:(0,r.default)(m.default.agentic_chat_new_session_menu_item,te&&m.default.agentic_chat_new_session_menu_item_selected),"data-testid":`agentic-chat-new-session-agent-${Z.value}`,key:Z.value,onClick:()=>V(Z.value),role:"menuitem",title:Z.title,type:"button"},o.default.createElement("span",{className:m.default.agentic_chat_new_session_menu_item_label},Z.label),te&&o.default.createElement("span",{className:(0,r.default)(m.default.agentic_chat_new_session_menu_item_check,(0,c.getIcon)("check"))}))}),o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu_separator}),o.default.createElement("button",{className:m.default.agentic_chat_new_session_menu_item,"data-testid":"agentic-chat-agent-config-menu-item",onClick:$,role:"menuitem",type:"button"},(0,c.localize)("aiNative.chat.agentSelector.configureAgents","Agent \u914D\u7F6E")))))}},17996:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgenticVirtualMessageList=void 0;const r=e(85608).__importStar(e(14041)),o=e(68392),c=e(89892),_=new Map,v={bottom:480,top:480};function p(u,s){const l=_.get(u);if(!l||l.kind==="bottom")return s.length>0?{index:s.length-1,align:"end"}:0;const d=s.findIndex(g=>g.id===l.messageId);return d>=0?{index:d,align:"start",offset:-l.offset}:0}function f(u){const s=_.get(u);return!s||s.kind==="bottom"}function a({className:u,messages:s,renderMessage:l,sessionId:d},g){var E;const m=r.useRef(null),h=r.useRef(null),b=r.useRef(0),A=r.useRef(!0),y=r.useRef(!1),S=r.useRef(!1),w=r.useRef(),T=r.useRef(s);T.current=s;const I=r.useCallback(()=>{var N;T.current.length!==0&&((N=m.current)===null||N===void 0||N.scrollToIndex({index:T.current.length-1,align:"end"}))},[]),D=r.useCallback(()=>{var N;const L=h.current,B=L?.getBoundingClientRect(),K=Array.from(L?.querySelectorAll("[data-message-id]")||[]),W=(N=T.current[T.current.length-1])===null||N===void 0?void 0:N.id,U=K.some(z=>z.dataset.messageId===W&&(!B||z.getBoundingClientRect().top<B.bottom));if(y.current||A.current||S.current||U){_.set(d,{kind:"bottom"});return}const G=K.find(z=>!B||z.getBoundingClientRect().bottom>B.top),j=G?.dataset.messageId;if(G&&j&&B){_.set(d,{kind:"message",messageId:j,offset:G.getBoundingClientRect().top-B.top});return}const Y=T.current[b.current];Y&&_.set(d,{kind:"message",messageId:Y.id,offset:0})},[d]);r.useEffect(()=>D,[D]),r.useImperativeHandle(g,()=>({maintainBottom:()=>{var N;A.current&&((N=m.current)===null||N===void 0||N.autoscrollToBottom())},scrollToBottom:(N="auto")=>{var L;T.current.length!==0&&((L=m.current)===null||L===void 0||L.scrollToIndex({index:T.current.length-1,align:"end",behavior:N}))}}),[]);const R=s.length>0,M=(E=s[0])===null||E===void 0?void 0:E.id,O=r.useRef();(!O.current||O.current.sessionId!==d||O.current.firstMessageId!==M)&&(O.current={firstMessageId:M,location:p(d,s),sessionId:d});const x=O.current.location;r.useEffect(()=>{if(!R)return;y.current=f(d),y.current&&(A.current=!1);const N=requestAnimationFrame(()=>{var L;(L=m.current)===null||L===void 0||L.scrollToIndex(x),y.current&&I()});return()=>{cancelAnimationFrame(N),w.current!==void 0&&(cancelAnimationFrame(w.current),w.current=void 0)}},[M,R,x,I,d]);const k=r.useCallback((N,L)=>{const B=l(L);return r.createElement("div",{"data-message-id":L.id,"data-message-role":B?.position==="right"?"user":"assistant","data-testid":"agentic-message-row",style:{display:"flow-root"}},r.createElement(o.MessageBox,{...B}))},[l]);return r.createElement("div",{className:`rce-container-mlist ${u||""}`,"data-testid":"agentic-virtual-message-list",style:{height:"100%",minHeight:0,overflow:"hidden"}},r.createElement(c.Virtuoso,{key:`${d}:${M||"empty"}`,ref:m,className:"rce-mlist",style:{display:"block",height:"100%",minHeight:0,overflow:"auto",position:"relative"},data:s,computeItemKey:(N,L)=>L.id,defaultItemHeight:96,increaseViewportBy:v,initialTopMostItemIndex:x,overscan:{main:160,reverse:160},followOutput:N=>N?"auto":!1,atBottomStateChange:N=>{A.current=N,N&&(y.current=!1,_.set(d,{kind:"bottom"}))},rangeChanged:N=>{b.current=N.startIndex,S.current=N.endIndex>=T.current.length-1,y.current&&!A.current&&w.current===void 0&&(w.current=requestAnimationFrame(()=>{w.current=void 0,I()}))},scrollerRef:N=>{h.current=N instanceof HTMLElement?N:null},itemContent:k}))}t.AgenticVirtualMessageList=r.forwardRef(a)},41046:(P,t,e)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AcpChatAgent=void 0;const r=e(85608),o=e(76003),c=e(41869),_=e(43718),v=e(27284),p=e(9447),f=e(72665),a=e(93062),u=e(19413),s=e(33108),l=e(61282),d=e(11735);let g=n=class{constructor(){this.id=n.AGENT_ID}get metadata(){return{systemPrompt:this.preferenceService.get(v.AINativeSettingSectionsId.SystemPrompt,"")}}set metadata(m){}async getRequestOptions(){const m=this.preferenceService.get(v.AINativeSettingSectionsId.LLMModelSelection),h=this.preferenceService.get(v.AINativeSettingSectionsId.ModelID);let b="",A="";m==="deepseek"?b=this.preferenceService.get(v.AINativeSettingSectionsId.DeepseekApiKey,""):m==="openai"?b=this.preferenceService.get(v.AINativeSettingSectionsId.OpenaiApiKey,""):m==="anthropic"?b=this.preferenceService.get(v.AINativeSettingSectionsId.AnthropicApiKey,""):(b=this.preferenceService.get(v.AINativeSettingSectionsId.OpenaiApiKey,""),A=this.preferenceService.get(v.AINativeSettingSectionsId.OpenaiBaseURL,""));const y=this.preferenceService.get(v.AINativeSettingSectionsId.MaxTokens),S=this.chatAgentService.getAgent(n.AGENT_ID),w=await this.mcpConfigService.getDisabledTools();return this.logger.log(`[ACP Chat] getRequestOptions: model=${m}, modelId=${h}, apiKey=${b?b.slice(0,8)+"***":"(empty)"}, baseURL=${A}, maxTokens=${y}`),{clientId:this.applicationService.clientId,model:m,modelId:h,apiKey:b,baseURL:A,maxTokens:y,system:S?.metadata.systemPrompt,disabledTools:w}}async invoke(m,h,b,A){var y,S,w,T;const I=new _.Deferred,{message:D,command:R}=m;this.logger.log(`[ACP Chat] invoke start \u2014 rawSessionId=${m.sessionId}, requestId=${m.requestId}, command=${R||"(empty)"}, messageChars=${D.length}, images=${(S=(y=m.images)===null||y===void 0?void 0:y.length)!==null&&S!==void 0?S:0}, historyMessages=${b.length}`);let M=D;if(R){const k=this.chatFeatureRegistry.getSlashCommandHandler(R);if(k&&k.providerPrompt){const N=this.monacoCommandRegistry.getActiveCodeEditor();M=await k.providerPrompt(D,N),this.logger.log(`[ACP Chat] invoke slash prompt resolved \u2014 requestId=${m.requestId}, command=${R}, promptChars=${M.length}`)}}if(R){const k=this.chatFeatureRegistry.getSlashCommandHandler(R);if(k?.invoke)return this.logger.log(`[ACP Chat] invoke custom slash handler \u2014 requestId=${m.requestId}, command=${R}, promptChars=${M.length}`),h({kind:"requestAccepted",sessionId:m.sessionId}),await k.invoke(M,h,A),I.resolve(),{}}let O=m.sessionId;O.startsWith("acp:")&&(O=O.substring(4));const x=b[b.length-1];this.logger.log(`[ACP Chat] invoke normalized \u2014 sessionId=${O}, requestId=${m.requestId}, promptChars=${M.length}, lastMessageRole=${(w=x?.role)!==null&&w!==void 0?w:"(empty)"}`);try{const k=m.sessionId.startsWith("acp:")?m.sessionId:`acp:${m.sessionId}`,N=(T=this.chatManagerService.getSession(k))===null||T===void 0?void 0:T.acpTarget,L=N&&this.configProvider.resolveConfigForTarget?await this.configProvider.resolveConfigForTarget(N):await this.configProvider.resolveConfig();this.logger.log(`[ACP Chat] invoke: sessionId=${O}, config=${JSON.stringify(L)}`);const B=this.preferenceService.get(v.AINativeSettingSectionsId.AcpDeliveryMode,"stream"),K={requestId:m.requestId,sessionId:O,history:[x],images:m.images,acpDeliveryMode:B,...await this.getRequestOptions(),agentSessionConfig:L};this.logger.log(`[ACP Chat] invoking aiBackService.requestStream: agentSessionConfig=${!!K.agentSessionConfig}, apiKey=${K.apiKey?K.apiKey.slice(0,8)+"***":"(empty)"}`);const W=await this.aiBackService.requestStream(M,K,A);this.logger.log(`[ACP Chat] requestStream opened \u2014 sessionId=${O}, requestId=${m.requestId}, historyMessages=${K.history.length}`),h({kind:"requestAccepted",sessionId:O});let U=0,G=!1;(0,a.listenReadable)(W,{onData:j=>{var Y;U+=1;const z=j.kind;j.kind==="threadStatus"?(this.logger.log(`[ACP Chat] stream data \u2014 sessionId=${O}, requestId=${m.requestId}, kind=threadStatus, status=${j.threadStatus}`),this.handleThreadStatusUpdate(j.threadStatus,j.sessionId),h({kind:"safeProgress",content:this.getThreadStatusSafeProgress(j.threadStatus)})):j.kind==="sessionState"?(this.logger.log(`[ACP Chat] stream data \u2014 sessionId=${O}, requestId=${m.requestId}, kind=sessionState, currentModeId=${(Y=j.currentModeId)!==null&&Y!==void 0?Y:"(empty)"}`),this.handleSessionStateUpdate(j,O)):((!G||z!=="content"&&z!=="markdownContent"&&z!=="reasoning")&&(this.logger.log(`[ACP Chat] stream data \u2014 sessionId=${O}, requestId=${m.requestId}, kind=${z}, count=${U}`),G=!0),h(j))},onEnd:()=>{this.logger.log(`[ACP Chat] stream end \u2014 sessionId=${O}, requestId=${m.requestId}, dataCount=${U}`),I.resolve()},onError:j=>{this.logger.error(`[ACP Chat] stream error \u2014 sessionId=${O}, requestId=${m.requestId}, error=${j.message}`),this.messageService.error(j.message),this.aiReporter.end(O+"_"+m.requestId,{message:j.message,success:!1,command:R}),I.reject(j)}}),await I.promise}catch(k){const N=k instanceof Error?k.message:String(k);return this.logger.error(`[ACP Chat] invoke error \u2014 sessionId=${O}, requestId=${m.requestId}, error=${N}`),this.messageService.error(N),{errorDetails:{message:N}}}return{}}handleThreadStatusUpdate(m,h){const b=h.startsWith("acp:")?h:`acp:${h}`,A=this.chatManagerService.getSession(b);A&&A.setThreadStatus(m)}getThreadStatusSafeProgress(m){switch(m){case"working":return(0,_.localize)("aiNative.chat.safeProgress.agentWorking");case"stopping":return(0,_.localize)("aiNative.chat.safeProgress.agentStopping");case"auth_required":return(0,_.localize)("aiNative.chat.safeProgress.authRequired");case"errored":return(0,_.localize)("aiNative.chat.safeProgress.errored");case"disconnected":return(0,_.localize)("aiNative.chat.safeProgress.disconnected");case"idle":case"awaiting_prompt":default:return""}}handleSessionStateUpdate(m,h){var b;const A=this.chatManagerService;(b=A.applySessionStateUpdate)===null||b===void 0||b.call(A,m.sessionId||h,{currentModeId:m.currentModeId,currentModelId:m.currentModelId,configOptions:m.configOptions,availableCommands:m.availableCommands,title:m.title,updatedAt:m.updatedAt})}async provideSlashCommands(){return this.chatFeatureRegistry.getAllSlashCommand().map(m=>({...m,name:m.name,description:m.description||""}))}async provideChatWelcomeMessage(){}};t.AcpChatAgent=g,g.AGENT_ID="Default_Chat_Agent",r.__decorate([(0,o.Autowired)(u.IChatAgentService),r.__metadata("design:type",Object)],g.prototype,"chatAgentService",void 0),r.__decorate([(0,o.Autowired)(_.AIBackSerivcePath),r.__metadata("design:type",Object)],g.prototype,"aiBackService",void 0),r.__decorate([(0,o.Autowired)(c.PreferenceService),r.__metadata("design:type",Object)],g.prototype,"preferenceService",void 0),r.__decorate([(0,o.Autowired)(_.IApplicationService),r.__metadata("design:type",Object)],g.prototype,"applicationService",void 0),r.__decorate([(0,o.Autowired)(p.MonacoCommandRegistry),r.__metadata("design:type",p.MonacoCommandRegistry)],g.prototype,"monacoCommandRegistry",void 0),r.__decorate([(0,o.Autowired)(_.ChatFeatureRegistryToken),r.__metadata("design:type",d.ChatFeatureRegistry)],g.prototype,"chatFeatureRegistry",void 0),r.__decorate([(0,o.Autowired)(_.IAIReporter),r.__metadata("design:type",Object)],g.prototype,"aiReporter",void 0),r.__decorate([(0,o.Autowired)(f.IMessageService),r.__metadata("design:type",Object)],g.prototype,"messageService",void 0),r.__decorate([(0,o.Autowired)(_.MCPConfigServiceToken),r.__metadata("design:type",s.MCPConfigService)],g.prototype,"mcpConfigService",void 0),r.__decorate([(0,o.Autowired)(_.IACPConfigProvider),r.__metadata("design:type",Object)],g.prototype,"configProvider",void 0),r.__decorate([(0,o.Autowired)(c.ILogger),r.__metadata("design:type",Object)],g.prototype,"logger",void 0),r.__decorate([(0,o.Autowired)(u.IChatManagerService),r.__metadata("design:type",l.ChatManagerService)],g.prototype,"chatManagerService",void 0),t.AcpChatAgent=g=n=r.__decorate([(0,o.Injectable)()],g)},44279:(P,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AI_CHAT_INPUT_TOGGLE_EXPANDED=void 0,t.AI_CHAT_INPUT_TOGGLE_EXPANDED={id:"ai.chat.input.toggleExpanded",label:"Toggle Chat Input Expansion"}},5811:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AcpQueuedTurnModule=void 0;const n=e(43718),r=e(4835);class o{constructor(_){this.port=_,this.processing="auto",this.entries=[],this.canFastTrack=!1,this.nextTurnId=1,this.sessionEpoch=0,this.intentVersion=0,this.pendingInitialStart=!1,this.hasPendingActivation=!1,this.operationTail=Promise.resolve(),this.onDidChangeEmitter=new n.Emitter,this.onDidChange=this.onDidChangeEmitter.event}get snapshot(){const _=this.getPhase();return{activeSessionId:this.activeSessionId,phase:_,entries:[...this.entries],editingTurnId:this.editingTurnId,pauseReason:this.pauseReason,pauseError:this.pauseError,canResume:_==="paused"&&this.entries.length>0,canFastTrack:this.canFastTrack&&_==="generating"&&this.entries.length>0&&this.entries[0].id!==this.editingTurnId,initialStartPending:this.pendingInitialStart}}activate(_){const v=this.hasPendingActivation?this.pendingActivationId:this.activeSessionId;if(_!==v){if(this.pendingInitialStart){this.pendingActivationId=_,this.hasPendingActivation=!0;return}this.applyActivation(_)}}deactivate(){this.sessionEpoch+=1,this.intentVersion+=1,this.activeSessionId=void 0,this.processing="auto",this.entries=[],this.editingTurnId=void 0,this.reservedTurn=void 0,this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.activeDelivery=void 0,this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.pendingInitialStart=!1,this.cancelledInitialStartTurnId=void 0,this.initialStartCancellation=void 0,this.hasPendingActivation=!1,this.pendingActivationId=void 0}submit(_,v="normal"){if(!(0,r.hasAcpChatSendPayload)(_))return Promise.resolve({accepted:!1,reason:"empty-content"});const p=this.sessionEpoch,f=this.activeSessionId,a=this.copyDraft(_);if(v==="immediate"){const u=this.createQueuedTurn(a);return this.entries.push(u),this.fireDidChange(),this.sendImmediately(u.id).then(s=>this.withQueuedDraftDisposition(u,s))}if(this.processing==="paused"&&this.activeDelivery){const u=this.createQueuedTurn(a);return this.entries.unshift(u),this.sendImmediately(u.id).then(s=>this.withQueuedDraftDisposition(u,s))}return this.serialize(async()=>{if(!this.isCapturedSessionActive(p,f))return{accepted:!1,reason:"stale-session"};if(this.processing==="paused"&&!this.activeDelivery){const s=this.createQueuedTurn(a);return this.withQueuedDraftDisposition(s,await this.startReservedTurn(s,!0))}if(this.entries.length>0||this.port.getStatus(this.activeSessionId)==="generating"||this.activeDelivery)return this.entries.push(this.createQueuedTurn(a)),this.canFastTrack=this.processing==="auto",this.processing!=="paused"&&(this.pauseReason=void 0,this.pauseError=void 0),this.fireDidChange(),{accepted:!0,outcome:"queued"};const u=this.createQueuedTurn(a);return this.withQueuedDraftDisposition(u,await this.startReservedTurn(u,!0))})}resume(){const _=this.intentVersion;return this.serialize(async()=>{if(this.processing!=="paused"||!this.activeDelivery&&this.entries.length===0)return{accepted:!1,reason:"turn-not-found"};if(_!==this.intentVersion)return{accepted:!1,reason:"turn-not-found"};if(this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.fireDidChange(),this.activeDelivery)return{accepted:!0,outcome:"resumed"};if(_!==this.intentVersion)return{accepted:!0,outcome:"resumed"};const v=await this.startNextQueuedTurnIfReady();return v.accepted?{accepted:!0,outcome:"resumed"}:v})}replaceFailedStartDraft(_){const v=this.entries[0];return this.processing!=="paused"||this.pauseReason!=="start-failed"||!v||!(0,r.hasAcpChatSendPayload)(_)?!1:(this.entries[0]={...this.copyDraft(_),id:v.id},this.fireDidChange(),!0)}stop(){const _=this.sessionEpoch,v=this.activeSessionId,p=++this.intentVersion;return this.processing="paused",this.pauseReason="manual-stop",this.pauseError=void 0,this.canFastTrack=!1,this.cancelledInitialStartTurnId=void 0,this.initialStartCancellation=void 0,this.fireDidChange(),this.serialize(async()=>{if(!this.isCapturedSessionActive(_,v))return{accepted:!1,reason:"stale-session"};const f=v??this.activeSessionId;try{await this.port.ensureCurrentCancelled(f)}catch{return this.isResolvedSessionActive(_,f)?(p===this.intentVersion&&(this.processing="paused",this.pauseReason="cancel-failed",this.pauseError=void 0,this.fireDidChange()),{accepted:!1,reason:"cancel-failed"}):{accepted:!1,reason:"stale-session"}}return this.isResolvedSessionActive(_,f)?(this.activeDelivery=void 0,p===this.intentVersion&&(this.processing="paused",this.pauseReason="manual-stop",this.pauseError=void 0,this.canFastTrack=!1),this.fireDidChange(),{accepted:!0,outcome:"stopped"}):{accepted:!1,reason:"stale-session"}})}cancelInitialStart(){if(!this.pendingInitialStart||!this.reservedTurn||!this.port.cancelPendingStart)return Promise.resolve({accepted:!1,reason:"turn-not-found"});if(this.initialStartCancellation)return this.initialStartCancellation;this.cancelledInitialStartTurnId=this.reservedTurn.id,this.fireDidChange();const _=this.port.cancelPendingStart(this.activeSessionId).then(()=>this.whenSettled()).then(()=>({accepted:!0,outcome:"stopped"})).catch(()=>(this.cancelledInitialStartTurnId=void 0,this.fireDidChange(),{accepted:!1,reason:"cancel-failed"})).finally(()=>{this.initialStartCancellation===_&&(this.initialStartCancellation=void 0)});return this.initialStartCancellation=_,_}sendImmediately(_){return this.sendImmediatelyInternal(_,!1)}sendImmediatelyInternal(_,v){const p=this.sessionEpoch,f=this.activeSessionId;if(this.editingTurnId===_&&!v)return Promise.resolve({accepted:!1,reason:"another-turn-is-editing"});if(this.processing==="absorbing-cancel"||this.immediateReservation)return Promise.resolve({accepted:!1,reason:"turn-not-found"});const a=this.entries.findIndex(({id:l})=>l===_);if(a===-1)return Promise.resolve({accepted:!1,reason:"turn-not-found"});const[u]=this.entries.splice(a,1),s=++this.intentVersion;return this.immediateReservation=u,this.immediateReservationIndex=a,this.processing="absorbing-cancel",this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.fireDidChange(),this.serialize(async()=>{const l=await this.cancelForImmediateAndStart(u,a,p,f,s);return l.accepted&&v&&this.editingTurnId===_&&(this.editingTurnId=void 0,this.fireDidChange()),l})}beginEdit(_){return this.entries.some(({id:v})=>v===_)?this.editingTurnId&&this.editingTurnId!==_?{accepted:!1,reason:"another-turn-is-editing"}:(this.editingTurnId=_,this.fireDidChange(),{accepted:!0,outcome:"updated"}):{accepted:!1,reason:"turn-not-found"}}commitEdit(_,v,p=!1){if(p){if(this.processing==="absorbing-cancel"||this.immediateReservation)return Promise.resolve({accepted:!1,reason:"turn-not-found"});if(!(0,r.hasAcpChatSendPayload)(v))return Promise.resolve({accepted:!1,reason:"empty-content"});const a=this.entries.findIndex(({id:u})=>u===_);return a===-1||this.editingTurnId!==_?Promise.resolve({accepted:!1,reason:"turn-not-found"}):(this.entries[a]={...this.copyDraft(v),id:_},this.fireDidChange(),this.sendImmediatelyInternal(_,!0))}const f=this.intentVersion;return this.serialize(async()=>{if(!(0,r.hasAcpChatSendPayload)(v))return{accepted:!1,reason:"empty-content"};const a=this.entries.findIndex(({id:u})=>u===_);return a===-1||this.editingTurnId!==_?{accepted:!1,reason:"turn-not-found"}:(this.entries[a]={...this.copyDraft(v),id:_},this.editingTurnId=void 0,f===this.intentVersion&&this.processing==="paused"&&(this.processing="auto",this.pauseReason=void 0),this.fireDidChange(),f===this.intentVersion&&await this.startNextQueuedTurnIfReady(),{accepted:!0,outcome:"updated"})})}cancelEdit(_){const v=this.intentVersion;return this.serialize(async()=>this.editingTurnId!==_||!this.entries.some(({id:p})=>p===_)?{accepted:!1,reason:"turn-not-found"}:(this.editingTurnId=void 0,v===this.intentVersion&&this.processing==="paused"&&(this.processing="auto",this.pauseReason=void 0),this.fireDidChange(),v===this.intentVersion&&await this.startNextQueuedTurnIfReady(),{accepted:!0,outcome:"updated"}))}remove(_){const v=this.intentVersion;return this.serialize(async()=>{const p=this.entries.findIndex(({id:f})=>f===_);return p===-1?{accepted:!1,reason:"turn-not-found"}:(this.entries.splice(p,1),this.editingTurnId===_&&(this.editingTurnId=void 0),v===this.intentVersion&&this.processing==="paused"&&(this.processing="auto",this.pauseReason=void 0),this.fireDidChange(),v===this.intentVersion&&await this.startNextQueuedTurnIfReady(),{accepted:!0,outcome:"removed"})})}takeBackLast(){const _=this.entries.pop();if(_)return this.editingTurnId===_.id&&(this.editingTurnId=void 0),this.canFastTrack=!1,this.fireDidChange(),_}fastTrack(){const _=this.entries[0];return!this.canFastTrack||!_||_.id===this.editingTurnId?Promise.resolve({accepted:!1,reason:"turn-not-found"}):(this.canFastTrack=!1,this.sendImmediately(_.id))}invalidateFastTrack(){this.canFastTrack&&(this.canFastTrack=!1,this.fireDidChange())}clear(){this.intentVersion+=1,this.entries=[],this.editingTurnId=void 0,this.reservedTurn=void 0,this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.fireDidChange()}serialize(_){const v=this.operationTail.then(_,_);return this.operationTail=v.then(()=>{},()=>{}),v}whenSettled(){return this.operationTail.then(()=>this.operationTail)}dispose(){this.onDidChangeEmitter.dispose()}applyActivation(_){this.sessionEpoch+=1,this.intentVersion+=1,this.activeSessionId=_,this.processing="auto",this.entries=[],this.editingTurnId=void 0,this.reservedTurn=void 0,this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.activeDelivery=void 0,this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.cancelledInitialStartTurnId=void 0,this.initialStartCancellation=void 0,this.hasPendingActivation=!1,this.pendingActivationId=void 0,this.fireDidChange()}async startReservedTurn(_,v){const p=this.sessionEpoch,f=this.activeSessionId,a=this.intentVersion,{id:u,...s}=_;this.reservedTurn=_,this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.pendingInitialStart=f===void 0,this.fireDidChange();let l;try{l=await this.port.start(f,s)}catch(g){const E=this.takePendingActivation();return this.pendingInitialStart=!1,this.cancelledInitialStartTurnId===_.id?(this.cancelledInitialStartTurnId=void 0,this.reservedTurn=void 0,this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.fireDidChange(),{accepted:!1,reason:"start-cancelled"}):p!==this.sessionEpoch?{accepted:!1,reason:"stale-session"}:E.pending?(this.applyActivation(E.sessionId),{accepted:!1,reason:"stale-session"}):(this.reservedTurn===_&&v&&this.entries.unshift(_),this.reservedTurn=void 0,a===this.intentVersion&&(this.processing="paused",this.pauseReason="start-failed",this.pauseError={name:g instanceof Error?g.name:void 0,message:g instanceof Error?g.message:String(g),limit:g&&typeof g=="object"&&typeof g.limit=="number"?g.limit:void 0}),this.fireDidChange(),{accepted:!1,reason:"start-failed"})}this.pendingInitialStart=!1;const d=this.takePendingActivation();if(this.watchOutcome(p,l),p!==this.sessionEpoch)return{accepted:!1,reason:"stale-session"};if(d.pending&&d.sessionId!==l.sessionId)return this.applyActivation(d.sessionId),{accepted:!1,reason:"stale-session"};if(f===void 0)this.activeSessionId=l.sessionId;else if(l.sessionId!==f)return this.reservedTurn=void 0,{accepted:!1,reason:"stale-session"};return this.reservedTurn=void 0,this.activeDelivery={epoch:p,id:l.id},a===this.intentVersion&&(this.processing="auto"),this.fireDidChange(),{accepted:!0,outcome:"started"}}async cancelForImmediateAndStart(_,v,p,f,a){if(!this.isCapturedSessionActive(p,f))return{accepted:!1,reason:"stale-session"};const u=f??this.activeSessionId;if(a!==this.intentVersion)return this.immediateReservation===_&&(this.entries.splice(Math.min(v,this.entries.length),0,_),this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.fireDidChange()),{accepted:!1,reason:"turn-not-found"};try{await this.port.ensureCurrentCancelled(u)}catch{return this.isResolvedSessionActive(p,u)?this.immediateReservation!==_?{accepted:!1,reason:"turn-not-found"}:(this.entries.unshift(_),this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.processing="paused",this.pauseReason="cancel-failed",this.fireDidChange(),{accepted:!1,reason:"cancel-failed"}):{accepted:!1,reason:"stale-session"}}return this.isResolvedSessionActive(p,u)?(this.activeDelivery=void 0,a!==this.intentVersion?(this.immediateReservation===_&&(this.entries.splice(Math.min(v,this.entries.length),0,_),this.immediateReservation=void 0,this.immediateReservationIndex=void 0),this.fireDidChange(),{accepted:!1,reason:"turn-not-found"}):this.immediateReservation!==_?(this.fireDidChange(),{accepted:!1,reason:"turn-not-found"}):(this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.processing="auto",this.pauseReason=void 0,this.startReservedTurn(_,!0))):{accepted:!1,reason:"stale-session"}}watchOutcome(_,v){v.outcome.then(p=>{this.serialize(()=>this.handleOutcome(_,v.id,p))},()=>{this.serialize(()=>this.handleOutcome(_,v.id,"agent-error"))})}async handleOutcome(_,v,p){var f,a;if(!(_!==this.sessionEpoch||((f=this.activeDelivery)===null||f===void 0?void 0:f.epoch)!==_||this.activeDelivery.id!==v)){if(this.activeDelivery=void 0,this.processing==="paused"){this.fireDidChange();return}if(p!=="completed"){this.processing="paused",this.pauseReason=p,this.canFastTrack=!1,this.fireDidChange();return}if(this.pauseReason=void 0,((a=this.entries[0])===null||a===void 0?void 0:a.id)===this.editingTurnId){this.fireDidChange();return}await this.startNextQueuedTurnIfReady()}}async startNextQueuedTurnIfReady(){var _;if(this.activeDelivery||this.reservedTurn||this.processing!=="auto"||((_=this.entries[0])===null||_===void 0?void 0:_.id)===this.editingTurnId)return{accepted:!0,outcome:"updated"};const v=this.entries.shift();return v?this.startReservedTurn(v,!0):(this.fireDidChange(),{accepted:!0,outcome:"updated"})}getPhase(){return this.processing==="absorbing-cancel"?"cancelling-for-immediate":this.processing==="paused"?"paused":this.activeDelivery||this.reservedTurn||this.port.getStatus(this.activeSessionId)==="generating"?"generating":"idle"}createQueuedTurn(_){return{...this.copyDraft(_),id:`queued-turn-${this.nextTurnId++}`}}copyDraft(_){return{..._,images:_.images?[..._.images]:void 0}}withQueuedDraftDisposition(_,v){return!v.accepted&&this.entries.some(({id:p})=>p===_.id)?{...v,draftDisposition:"queued"}:v}takePendingActivation(){const _=this.hasPendingActivation,v=this.pendingActivationId;return this.hasPendingActivation=!1,this.pendingActivationId=void 0,{pending:_,sessionId:v}}isCapturedSessionActive(_,v){return _===this.sessionEpoch&&(v===void 0||v===this.activeSessionId)}isResolvedSessionActive(_,v){return _===this.sessionEpoch&&v===this.activeSessionId}fireDidChange(){this.onDidChangeEmitter.fire(this.snapshot)}}t.AcpQueuedTurnModule=o},87540:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AI_CHAT_NEW_TASK=t.AI_CHAT_NEW_CHAT=void 0;const n=e(43718);t.AI_CHAT_NEW_CHAT={id:"ai.chat.newChat",label:(0,n.localize)("aiNative.command.newChat","AI Chat: New Chat")},t.AI_CHAT_NEW_TASK={id:"ai.chat.newTask",label:(0,n.localize)("aiNative.command.newTask","Agent: New Session")}},17354:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ACPSessionProvider=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(43718),_=e(72665),v=e(70392),p=e(90684),f=e(29993),a=e(28524),u=e(26093),s="Default_Chat_Agent";function l(m){return/^(?:[A-Za-z]:[\\/]|[\\/])/.test(m)}function d(m){return!!m&&typeof m=="object"&&m.name===c.ACP_THREAD_POOL_SATURATED_ERROR_NAME}function g(m){var h;const b=typeof m.message=="string"?(h=m.message.match(/\bThread pool is full \((\d+)\)/))===null||h===void 0?void 0:h[1]:void 0,A=b?v.strings.format((0,c.localize)("aiNative.chat.acp.threadPoolSaturated.withLimit","ACP concurrent tasks have reached the configured limit of {0}. Switch to or stop an active task, then try again."),b):(0,c.localize)("aiNative.chat.acp.threadPoolSaturated","ACP concurrent tasks have reached the configured limit. Switch to or stop an active task, then try again."),y=new Error(A);return y.name=c.ACP_THREAD_POOL_SATURATED_ERROR_NAME,b&&(y.limit=Number(b)),y}let E=class{constructor(){this.id="ACPSessionProvider",this.loadedSessionMap=new Map,this.loadedSessionsResult=null,this.loadingSessionsPromise=null,this.didRetryEmptySessionsResult=!1,this.agentSessionCatalog=[],this.agentSessionTargets=new Map,this.agentSessionRefreshRequested=!1}canHandle(h){return h.startsWith("acp")}async createSession(h){var b;if(!(!((b=this.aiBackService)===null||b===void 0)&&b.createSession))throw new Error("aiBackService.createSession is not available");try{const A=h?.acpTarget&&this.configProvider.resolveConfigForTarget?await this.configProvider.resolveConfigForTarget(h.acpTarget):await this.configProvider.resolveConfig(),y=await(h?.operationId?this.aiBackService.createSession(A,h.operationId):this.aiBackService.createSession(A));if(!y?.sessionId)throw new Error("createSession did not return a valid sessionId");const S=`acp:${y.sessionId}`,w=Date.now(),T={sessionId:S,createdAt:w,modelId:y.currentModelId,agentModes:y.modes,currentModeId:y.currentModeId,agentModels:y.models,configOptions:y.configOptions,history:{additional:{},messages:[]},requests:[],title:"",extension:{availableCommands:y.availableCommands||[],acpTarget:{agentId:A.agentId,cwd:A.cwd}}};return this.loadedSessionMap.set(S,T),this.agentSessionTargets.set(S,{agentId:A.agentId,cwd:A.cwd}),T}catch(A){throw d(A)?g(A):A}}getAgentSessions(){return this.agentSessionCatalog.map(h=>({...h}))}refreshAgentSessions(){return this.agentSessionRefreshRequested=!0,this.agentSessionRefreshPromise||(this.agentSessionRefreshPromise=this.drainAgentSessionRefreshes().finally(()=>{this.agentSessionRefreshPromise=void 0})),this.agentSessionRefreshPromise}async drainAgentSessionRefreshes(){let h=[];do this.agentSessionRefreshRequested=!1,h=await this.doRefreshAgentSessions();while(this.agentSessionRefreshRequested);return h}async doRefreshAgentSessions(){var h;if(!(!((h=this.aiBackService)===null||h===void 0)&&h.listSessions)||!this.configProvider.resolveConfigForTarget)return this.agentSessionCatalog=[],this.agentSessionTargets.clear(),[];const b=(await this.agenticTaskRegistry.listProjects()).filter(R=>R.availability==="available"&&l(R.workspacePath)),A=new Set(b.map(R=>R.workspacePath)),y=Object.keys((0,a.getAvailableAgentConfigs)(this.preferenceService)),S=[],w=new Map;for(const R of y){const M=new Map;let O=!1;for(const[x,k]of b.entries())try{const N=await this.configProvider.resolveConfigForTarget({agentId:R,cwd:k.workspacePath}),L=await this.aiBackService.listSessions(N);for(const B of L?.sessions||[]){if(!B?.sessionId||!l(B.cwd)||!A.has(B.cwd))continue;const K=`acp:${B.sessionId}`,W={sessionId:K,agentSessionId:B.sessionId,agentId:R,cwd:B.cwd,title:B.title||void 0,updatedAt:B.updatedAt||void 0},U=M.get(K);(!U||this.toTimestamp(W.updatedAt)>=this.toTimestamp(U.updatedAt))&&M.set(K,W)}}catch(N){O=!0,this.logger.warn(`[ACP Chat][Session Catalog] list failed \u2014 agentId=${R}, projectOrdinal=${x}, errorType=${N instanceof Error?N.name:typeof N}`);break}if(!O)for(const x of M.values())S.push(x),w.set(x.sessionId,{agentId:x.agentId,cwd:x.cwd})}const T=new Map;for(const R of S){const M=T.get(R.agentSessionId)||new Set;M.add(R.agentId),T.set(R.agentSessionId,M)}const I=new Set(Array.from(T.entries()).filter(([,R])=>R.size>1).map(([R])=>R));if(I.size>0){const R=Math.max(...Array.from(I,M=>{var O;return((O=T.get(M))===null||O===void 0?void 0:O.size)||0}));this.logger.warn(`[ACP Chat][Session Catalog] excluded cross-Agent Session ID collisions \u2014 count=${I.size}, agentCount=${R}`)}const D=S.filter(R=>!I.has(R.agentSessionId));for(const R of I)w.delete(`acp:${R}`);return D.sort((R,M)=>this.toTimestamp(M.updatedAt)-this.toTimestamp(R.updatedAt)),this.agentSessionCatalog=D,this.agentSessionTargets=w,this.getAgentSessions()}toTimestamp(h){const b=h?Date.parse(h):0;return Number.isFinite(b)?b:0}async loadSessions(){if(Array.isArray(this.loadedSessionsResult))return this.loadedSessionsResult;if(this.loadingSessionsPromise)return this.loadingSessionsPromise;this.loadingSessionsPromise=this.doLoadSessions();try{return await this.loadingSessionsPromise}finally{this.loadingSessionsPromise=null}}async doLoadSessions(){var h,b;if(!(!((h=this.aiBackService)===null||h===void 0)&&h.listSessions))return this.loadedSessionsResult=[],this.loadedSessionsResult;try{const A=await this.configProvider.resolveConfig(),y=await this.aiBackService.listSessions(A);if(!(!((b=y?.sessions)===null||b===void 0)&&b.length))return this.didRetryEmptySessionsResult?(this.loadedSessionsResult=[],this.loadedSessionsResult):(this.didRetryEmptySessionsResult=!0,[]);const S=y.sessions.slice(0,20).reverse().map(w=>({...w,sessionId:`acp:${w.sessionId}`,history:{additional:{},messages:[]},requests:[],title:w.title}));return this.loadedSessionsResult=S,this.didRetryEmptySessionsResult=!1,this.loadedSessionsResult}catch(A){return this.messageService.error(A.message),[]}}async loadSession(h){var b,A;if(!h||!(!((b=this.aiBackService)===null||b===void 0)&&b.loadAgentSession))return;const y=h.startsWith("acp:")?h.slice(4):h;try{const S=await this.resolveSessionConfig(h),w=await this.aiBackService.loadAgentSession(S,y);if(!w)return;const T=this.convertAgentSessionToModel(h,w),I=this.agentSessionTargets.get(h);return I&&(T.extension={...T.extension,availableCommands:((A=T.extension)===null||A===void 0?void 0:A.availableCommands)||[],acpTarget:{...I},metadataOnly:!1}),this.loadedSessionMap.set(h,T),T}catch(S){throw S}}async attachSession(h){var b;if(!h||!(!((b=this.aiBackService)===null||b===void 0)&&b.attachSession))return;const A=h.startsWith("acp:")?h.slice(4):h;return this.aiBackService.attachSession(A)}async cancelSession(h){var b;if(!h||!(!((b=this.aiBackService)===null||b===void 0)&&b.cancelSession))return;const A=h.startsWith("acp:")?h.slice(4):h;await this.aiBackService.cancelSession(A)}async disposeSession(h,b=!1){var A;if(!h||!(!((A=this.aiBackService)===null||A===void 0)&&A.disposeSession))return;const y=h.startsWith("acp:")?h.slice(4):h;b?await this.aiBackService.disposeSession(y,!0):await this.aiBackService.disposeSession(y)}restoreSessionSnapshot(h,b){if(b.historyUpdates.length!==0)return this.convertAgentSessionToModel(h,{sessionId:b.sessionId,modes:b.modes,currentModeId:b.currentModeId,models:b.models,currentModelId:b.currentModelId,configOptions:b.configOptions,availableCommands:b.availableCommands,threadStatus:b.threadStatus,historyUpdates:b.historyUpdates,messages:[]})}async resolveSessionConfig(h){const b=this.agentSessionTargets.get(h);return b&&this.configProvider.resolveConfigForTarget?this.configProvider.resolveConfigForTarget(b):this.configProvider.resolveConfig()}convertAgentSessionToModel(h,b){var A;const y=b.historyUpdates;if(y?.length)return this.convertHistoryUpdatesToModel(h,{...b,historyUpdates:y});const w=b.messages.filter((I,D)=>!(I.content.includes("<command-name>")||I.content.includes("<local-command-stdout>"))).map((I,D)=>({id:`${h}-msg-${D}`,role:I.role==="user"?1:2,content:I.content,order:D,timestamp:I.timestamp}));return{sessionId:h,createdAt:(A=w[0])===null||A===void 0?void 0:A.timestamp,modelId:b.currentModelId,agentModes:b.modes,currentModeId:b.currentModeId,agentModels:b.models,configOptions:b.configOptions,extension:b.availableCommands?{availableCommands:b.availableCommands}:void 0,history:{additional:{},messages:w},requests:[]}}convertHistoryUpdatesToModel(h,b){var A,y,S,w,T,I;const D=[];let R;const M=()=>(R||(R={userContent:"",assistantContent:"",responseParts:[],toolCalls:new Map}),R),O=()=>{R&&(R.userContent||R.responseParts.length>0)&&D.push(R),R=void 0},x=(B,K)=>{const W=B.responseParts[B.responseParts.length-1];W?.kind==="markdownContent"?B.responseParts[B.responseParts.length-1]={kind:"markdownContent",content:new p.MarkdownString(W.content.value+K,W.content)}:B.responseParts.push({kind:"markdownContent",content:new p.MarkdownString(K)}),B.assistantContent+=K},k=(B,K)=>{const W=B.responseParts[B.responseParts.length-1];W?.kind==="reasoning"?W.content+=K:B.responseParts.push({kind:"reasoning",content:K.replace(/^<think>/,"")})};for(const B of b.historyUpdates){const K=B.update;if(K)switch(K.sessionUpdate){case"user_message_chunk":{const W=((A=K.content)===null||A===void 0?void 0:A.type)==="text"?K.content.text:"";if(!W)break;R&&(R.assistantContent||R.responseParts.length>0)&&O(),M().userContent+=W;break}case"agent_message_chunk":{const W=((y=K.content)===null||y===void 0?void 0:y.type)==="text"?K.content.text:"";W&&x(M(),W);break}case"agent_thought_chunk":{const W=((S=K.content)===null||S===void 0?void 0:S.type)==="text"?K.content.text:"";W&&k(M(),W);break}case"tool_call":{const W=M(),U={id:K.toolCallId||"",type:"function",function:{name:K.title||K.toolCallId||"",arguments:JSON.stringify((w=K.rawInput)!==null&&w!==void 0?w:{})},state:"streaming-start"};W.toolCalls.set(U.id,U),W.responseParts.push({kind:"toolCall",content:U});break}case"tool_call_update":{const U=M().toolCalls.get(K.toolCallId);if(!U)break;if(K.rawInput!==void 0&&(U.function.arguments=JSON.stringify(K.rawInput)),K.status==="in_progress"){U.state="streaming";break}if(K.status!=="completed"&&K.status!=="failed")break;if(K.rawOutput!==void 0)U.result=typeof K.rawOutput=="string"?K.rawOutput:JSON.stringify(K.rawOutput),U.state="result";else if(Array.isArray(K.content)){const G=K.content.find(j=>j?.type==="diff");G?.path&&(U.result=`Modified ${G.path}`,U.state="result")}else K.status==="failed"?(U.result="Tool failed",U.state="result"):U.state="complete";break}case"plan":{const W=(I=(T=K.plan)===null||T===void 0?void 0:T.entries)!==null&&I!==void 0?I:K.entries;Array.isArray(W)&&W.length>0&&x(M(),`${W.map(U=>U.completed||U.status==="completed"?`- [x] ${U.content}`:`- [ ] ${U.content}`).join(`
39437
+ `);if(T?T.test(D):D.includes(b))return(0,c.successResult)({terminalId:h,matched:!0,elapsedMs:Date.now()-I});await d(w)}return(0,c.successResult)({terminalId:h,matched:!1,timedOut:!0,elapsedMs:Date.now()-I})}catch(y){return(0,c.errorResult)("EXECUTION_ERROR",y)}}},{name:"terminal_show",description:"Show/focus a specific terminal session in the terminal panel. Use this to bring a terminal into view.",riskLevel:"ui",inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID to show. Get valid IDs from terminal_list."}},required:["id"]},execute:async m=>{const h=m.id;if(!h)return(0,c.errorResult)("EXECUTION_ERROR",new Error("id is required"));const b=(0,c.tryGetService)(E,r.ITerminalApiService);if(!b)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return b.showTerm(h),(0,c.successResult)({terminalId:h})}catch(A){return(0,c.errorResult)("EXECUTION_ERROR",A)}}},{name:"terminal_get_process_id",description:"Get the OS process ID (PID) of the shell process running in a terminal session. Returns null if the process has exited.",riskLevel:"read",inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID. Get valid IDs from terminal_list."}},required:["id"]},execute:async m=>{const h=m.id;if(!h)return(0,c.errorResult)("EXECUTION_ERROR",new Error("id is required"));const b=(0,c.tryGetService)(E,r.ITerminalApiService);if(!b)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{const A=await b.getProcessId(h);return(0,c.successResult)({terminalId:h,pid:A??null})}catch(A){return(0,c.errorResult)("EXECUTION_ERROR",A)}}},{name:"terminal_dispose",description:"Close/kill a terminal session and its underlying shell process. Use this to clean up terminals that are no longer needed.",riskLevel:"destructive",profiles:["full"],inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID to close. Get valid IDs from terminal_list."}},required:["id"]},execute:async m=>{const h=m.id;if(!h)return(0,c.errorResult)("INVALID_INPUT",new Error("id is required"));const b=(0,c.tryGetService)(E,o.ITerminalController);if(!b)return(0,c.serviceUnavailableResult)("ITerminalController");const A=(0,c.tryGetService)(E,r.ITerminalApiService);if(!A)return(0,c.serviceUnavailableResult)("ITerminalApiService");try{return u(b,h)?(A.removeTerm(h),(0,c.successResult)({terminalId:h,disposed:!0})):(0,c.errorResult)("INVALID_INPUT",new Error("terminal not found"))}catch(y){return(0,c.errorResult)("EXECUTION_ERROR",y)}}},{name:"terminal_resize",description:"Resize a terminal session to the specified number of columns (width) and rows (height).",riskLevel:"ui",inputSchema:{type:"object",properties:{id:{type:"string",description:"The terminal session ID. Get valid IDs from terminal_list."},cols:{type:"number",description:"Number of columns (character width) for the terminal."},rows:{type:"number",description:"Number of rows (character height) for the terminal."}},required:["id","cols","rows"]},execute:async m=>{const h=m.id,b=m.cols,A=m.rows;if(!h||!b||!A)return(0,c.errorResult)("EXECUTION_ERROR",new Error("id, cols, and rows are required"));const y=(0,c.tryGetService)(E,n.ITerminalService);if(!y)return(0,c.serviceUnavailableResult)("ITerminalService");try{return await y.resize(h,b,A),(0,c.successResult)({terminalId:h,cols:b,rows:A})}catch(S){return(0,c.errorResult)("EXECUTION_ERROR",S)}}},{name:"terminal_get_os",description:'Get the operating system type of the terminal backend (e.g. "Linux", "macOS", "Windows"). Useful for writing platform-specific commands.',riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{const m=(0,c.tryGetService)(E,n.ITerminalService);if(!m)return(0,c.serviceUnavailableResult)("ITerminalService");try{const h=await m.getOS();return(0,c.successResult)({os:h})}catch(h){return(0,c.errorResult)("EXECUTION_ERROR",h)}}},{name:"terminal_get_profiles",description:"Get the list of available terminal shell profiles (e.g. bash, zsh, PowerShell). Use the profile name with terminal_create to open a specific shell.",riskLevel:"read",profiles:["interactive","full"],inputSchema:{type:"object",properties:{autoDetect:{type:"boolean",description:"Whether to auto-detect available shells. Defaults to true."}}},execute:async m=>{var h;const b=(0,c.tryGetService)(E,n.ITerminalService);if(!b)return(0,c.serviceUnavailableResult)("ITerminalService");try{const A=(h=m.autoDetect)!==null&&h!==void 0?h:!0,y=await b.getProfiles(A);return(0,c.successResult)(y.map(S=>({profileName:S.profileName,path:S.path,isAutoDetected:S.isAutoDetected})))}catch(A){return(0,c.errorResult)("EXECUTION_ERROR",A)}}},{name:"terminal_show_panel",description:"Show/open the terminal panel in the IDE. Use this to ensure the terminal panel is visible before interacting with terminals.",riskLevel:"ui",inputSchema:{type:"object",properties:{}},execute:async()=>{const m=(0,c.tryGetService)(E,o.ITerminalController);if(!m)return(0,c.serviceUnavailableResult)("ITerminalController");try{return m.showTerminalPanel(),(0,c.successResult)({status:"shown"})}catch(h){return(0,c.errorResult)("EXECUTION_ERROR",h)}}}]}}},68840:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.createWorkspaceGroup=p;const n=e(41869),r=e(43718),o=e(54414),c=e(51500),_=e(67741);function v(f){return r.URI.parse(f).codeUri.fsPath}function p(f){return{name:"workspace",description:"Workspace context and open editor state",defaultLoaded:!0,tools:[{name:"workspace_get_info",description:"Get workspace metadata, including root folders, workspace name, multi-root state, and the configured workspace directory.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{var a;const u=(0,_.tryGetService)(f,c.IWorkspaceService);if(!u)return(0,_.serviceUnavailableResult)("IWorkspaceService");const s=(0,_.tryGetService)(f,n.AppConfig);try{await u.whenReady;const l=u.tryGetRoots().map(d=>({uri:d.uri,path:v(d.uri),name:u.getWorkspaceName(r.URI.parse(d.uri))}));return(0,_.successResult)({workspaceDir:(a=s?.workspaceDir)!==null&&a!==void 0?a:null,roots:l,rootCount:l.length,isMultiRootWorkspaceOpened:u.isMultiRootWorkspaceOpened,isMultiRootWorkspaceEnabled:u.isMultiRootWorkspaceEnabled})}catch(l){return(0,_.errorResult)((0,_.classifyError)(l),l)}}},{name:"workspace_list_open_files",description:"List files currently opened in editor groups. Use this to understand the user visible editing context.",riskLevel:"read",inputSchema:{type:"object",properties:{}},execute:async()=>{var a,u;const s=(0,_.tryGetService)(f,o.WorkbenchEditorService);if(!s)return(0,_.serviceUnavailableResult)("WorkbenchEditorService");try{const l=(u=(a=s.currentEditor)===null||a===void 0?void 0:a.currentUri)===null||u===void 0?void 0:u.toString(),d=s.editorGroups.flatMap((g,E)=>g.resources.map(m=>({uri:m.uri.toString(),path:m.uri.codeUri.fsPath,name:m.name,groupIndex:E,active:m.uri.toString()===l})));return(0,_.successResult)({files:d,total:d.length})}catch(l){return(0,_.errorResult)((0,_.classifyError)(l),l)}}},{name:"workspace_list_recent_workspaces",description:"List recently used workspaces known to the IDE.",riskLevel:"read",inputSchema:{type:"object",properties:{maxResults:{type:"number",description:"Maximum number of recent workspaces to return. Defaults to 10, capped at 50."}}},execute:async a=>{const u=(0,_.tryGetService)(f,c.IWorkspaceService);if(!u)return(0,_.serviceUnavailableResult)("IWorkspaceService");try{const s=Math.min(Math.max(Number(a.maxResults)||10,1),50),l=await u.getMostRecentlyUsedWorkspaces();return(0,_.successResult)({workspaces:l.slice(0,s),total:l.length})}catch(s){return(0,_.errorResult)((0,_.classifyError)(s),s)}}}]}}},80945:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getWebMcpModelContextToolDefinitions=c,t.registerWebMcpModelContextTools=_;const n=e(99763),r=e(87854),o=new WeakMap;function c(v,p){const{defaultLoadedOnly:f=!0,includeAllTools:a=!1}=p??{},u=v.getGroupDefinitions({...p,includeAllTools:a}).filter(l=>!f||l.defaultLoaded).flatMap(l=>l.tools.filter(d=>{var g;return(0,r.canExposeWebMcpTool)(d,(g=l.profile)!==null&&g!==void 0?g:"default")}).map(d=>({group:l.name,name:d.name,description:d.description,inputSchema:d.inputSchema}))),s=new Set;return u.filter(l=>s.has(l.name)?!1:(s.add(l.name),!0))}function _(v,p){var f,a;(0,n.ensureModelContext)();const u=navigator.modelContext,s=(f=o.get(u))!==null&&f!==void 0?f:new Set;o.set(u,s),(a=u.getTools)===null||a===void 0||a.call(u).forEach(g=>s.add(g.name));const l=[],d=c(v,p).filter(g=>s.has(g.name)?!1:(s.add(g.name),l.push(g.name),!0)).map(g=>u.registerTool({name:g.name,description:g.description,inputSchema:g.inputSchema,execute:E=>v.executeTool(g.group,g.name,E??{})}));return{dispose:()=>{d.forEach(g=>g.dispose()),l.forEach(g=>s.delete(g))}}}},67741:(P,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.tryGetService=e,t.classifyError=n,t.safeErrorMessage=o,t.successResult=c,t.errorResult=_,t.serviceUnavailableResult=v;function e(p,f){try{return p.get(f)}catch{return null}}function n(p){if(p instanceof Error){const f=p.message.toLowerCase();if(f.includes("timeout")||f.includes("timed out"))return"RPC_TIMEOUT";if(f.includes("permission")||f.includes("forbidden"))return"PERMISSION_DENIED";if(f.includes("abort"))return"ABORTED";if(f.includes("not found")||f.includes("enoent"))return"FILE_NOT_FOUND";if(f.includes("already exists")||f.includes("eexist"))return"FILE_EXISTS";if(f.includes("di")||f.includes("injector"))return"DI_ERROR"}return"EXECUTION_ERROR"}const r=[/(?:token|key|secret|password|auth)["\s]*[:=]\s*["']?[^"'`\s,}]+/gi,/sk-[a-zA-Z0-9]{20,}/g,/ghp_[a-zA-Z0-9]{30,}/g];function o(p,f=200){let a=p instanceof Error?p.message:String(p);for(const u of r)a=a.replace(u,"[REDACTED]");return a.length>f?a.slice(0,f)+"...":a}function c(p){return{success:!0,result:p}}function _(p,f){return{success:!1,error:p,details:o(f)}}function v(p){return{success:!1,error:"SERVICE_UNAVAILABLE",details:`Service ${p} is not available`}}},77659:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AINativeContextKey=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(50394);let _=class{get contextKeyService(){return this._contextKeyService}constructor(p){this._contextKeyService=this.globalContextKeyService.createScoped(p),this.inlineChatIsVisible=c.InlineChatIsVisible.bind(this._contextKeyService),this.inlineCompletionIsTrigger=c.InlineCompletionIsTrigger.bind(this._contextKeyService),this.inlineHintWidgetIsVisible=c.InlineHintWidgetIsVisible.bind(this._contextKeyService),this.inlineInputWidgetIsVisible=c.InlineInputWidgetIsVisible.bind(this._contextKeyService),this.inlineInputWidgetIsStreaming=c.InlineInputWidgetIsStreaming.bind(this._contextKeyService),this.inlineDiffPartialEditsIsVisible=c.InlineDiffPartialEditsIsVisible.bind(this._contextKeyService),this.codeEditsIsVisible=c.CodeEditsIsVisible.bind(this._contextKeyService)}};t.AINativeContextKey=_,n.__decorate([(0,r.Autowired)(o.IContextKeyService),n.__metadata("design:type",Object)],_.prototype,"globalContextKeyService",void 0),t.AINativeContextKey=_=n.__decorate([(0,r.Injectable)(),n.__param(0,(0,r.Optional)()),n.__metadata("design:paramtypes",[Object])],_)},32016:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AINativeBrowserContribution=t.INLINE_DIFF_MANAGER_WIDGET_ID=void 0;const n=e(85608),r=n.__importDefault(e(14041)),o=e(76003),c=e(41869),_=e(57925),v=e(50394),p=e(1149),f=e(93899),a=e(97222),u=e(43718),s=e(82353),l=e(54414),d=e(57517),g=e(51553),E=e(63067),m=e(72665),h=e(46507),b=e(97682),A=e(68415),y=e(96640),S=e(19413),w=e(46044),T=e(64811),I=e(69820),D=e(75334),R=e(29212),M=e(46572),O=e(5871),x=e(3504),k=e(32815),N=e(74296),L=e(59805),B=e(13682),K=e(38583),W=e(96743),U=e(68840),G=e(80945),j=e(44279),Y=e(87540),z=e(98987),V=e(61282),$=e(42995),H=e(51081),Q=e(29770),Z=e(59347),te=e(4457),ie=e(76154),ce=e(15764),me=e(28524),q=e(57987),be=e(49601),fe=e(79559),ne=e(57232),ge=e(72991),Oe=e(71863),Pe=e(7511),Me=e(42911),ke=e(72801),De=e(87817),pe=e(48590),Ie=e(79169),Ae=e(4972),xe=e(82983),_e=e(73974),re=e(33108),le=e(77633),Se=e(51221),Ee=e(2281),Ne=e(31031),Ye=e(95608),Ve=e(38890),mt=e(77886),_t=e(89060),Ot=e(74353),nt=e(22169),yt=e(90058);t.INLINE_DIFF_MANAGER_WIDGET_ID="inline-diff-manager-widget";const rt=()=>{const ct=(0,c.useInjectable)(u.ChatViewRegistryToken).getActiveChatView();return ct?r.default.createElement(ct.component):null};let Xe=class{constructor(){this.registerFeature()}registerMultiDiffSourceResolver(ct){return ct.registerResolver(this.chatMultiDiffResolver)}registerEditorDocumentModelContentProvider(ct){ct.registerEditorDocumentModelContentProvider(this.chatEditResourceProvider)}async initialize(){this.panelLayoutService.initialize();const{supportsChatAssistant:ct,supportsAgentMode:Tt}=this.aiNativeConfigService.capabilities;ct&&(c.ComponentRegistryImpl.addLayoutModule(this.appConfig.layoutConfig,S.AI_CHAT_VIEW_ID,S.AI_CHAT_CONTAINER_ID),c.ComponentRegistryImpl.addLayoutModule(this.appConfig.layoutConfig,s.DESIGN_MENU_BAR_RIGHT,S.AI_CHAT_LOGO_AVATAR_ID),this.chatProxyService.registerDefaultAgent(),Tt||(this.chatInternalService.init(),this.chatManagerService.init()))}registerEditorExtensionContribution(ct){const{supportsInlineChat:Tt,supportsInlineCompletion:Qt,supportsProblemFix:dn,supportsCodeAction:Kn}=this.aiNativeConfigService.capabilities;ct(Ve.InlineDiffController.ID,new y.SyncDescriptor(Ve.InlineDiffController,[this.injector]),b.EditorContributionInstantiation.Lazy),Kn&&ct(yt.SumiLightBulbWidget.ID,yt.SumiLightBulbWidget,b.EditorContributionInstantiation.Lazy),Tt&&(ct(Se.InlineChatEditorController.ID,new y.SyncDescriptor(Se.InlineChatEditorController,[this.injector]),b.EditorContributionInstantiation.BeforeFirstInteraction),this.inlineInputService.getInteractiveInputHandler()&&(ct(mt.InlineHintController.ID,new y.SyncDescriptor(mt.InlineHintController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender),ct(_t.InlineInputController.ID,new y.SyncDescriptor(_t.InlineInputController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender))),Qt&&(ct(Pe.IntelligentCompletionsController.ID,new y.SyncDescriptor(Pe.IntelligentCompletionsController,[this.injector]),b.EditorContributionInstantiation.Eager),ct(ge.InlineCompletionsController.ID,new y.SyncDescriptor(ge.InlineCompletionsController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender)),dn&&ct(Me.ProblemFixController.ID,new y.SyncDescriptor(Me.ProblemFixController,[this.injector]),b.EditorContributionInstantiation.AfterFirstRender)}onReconnect(){const{supportsMCP:ct}=this.aiNativeConfigService.capabilities;ct&&this.initMCPServers()}onDidStart(){this.registerWebMcpSurface(),(0,u.runWhenIdle)(()=>{const{supportsAgentMode:ct,supportsRenameSuggestions:Tt,supportsInlineChat:Qt,supportsMCP:dn,supportsCustomLLMSettings:Kn}=this.aiNativeConfigService.capabilities,fn=this.preferenceService.getValid(c.AINativeSettingSectionsId.ChatVisibleType);fn==="always"?this.commandService.executeCommand(_.AI_CHAT_VISIBLE.id,!0):fn==="never"&&this.commandService.executeCommand(_.AI_CHAT_VISIBLE.id,!1),Tt&&this.renameSingleHandler.load(),Qt&&this.codeActionSingleHandler.load(),Kn&&(this.preferenceService.onSpecificPreferenceChange(c.AINativeSettingSectionsId.LLMModelSelection,qt=>{const Rn=this.getModelByName(qt.newValue),zt=Rn?Object.keys(Rn):[],st=zt.length?zt[0]:"",$e=this.preferenceSchemaProvider.getPreferenceProperty(c.AINativeSettingSectionsId.ModelID);this.preferenceSchemaProvider.setSchema({properties:{[c.AINativeSettingSectionsId.ModelID]:{...$e,default:st,defaultValue:st,enum:zt.length?zt:void 0}}},!0),this.preferenceService.set(c.AINativeSettingSectionsId.ModelID,st,qt.scope),this.preferenceSettings.setEnumLabels(c.AINativeSettingSectionsId.ModelID,zt.reduce((Le,Fe)=>({...Le,[Fe]:Fe}),{}))}),this.preferenceService.onSpecificPreferenceChange(c.AINativeSettingSectionsId.ModelID,qt=>{const Rn=this.preferenceService.get(c.AINativeSettingSectionsId.LLMModelSelection);if(!Rn)return;const zt=this.getModelByName(Rn);zt&&zt[qt.newValue]&&(this.preferenceService.set(c.AINativeSettingSectionsId.MaxTokens,zt[qt.newValue].maxTokens,qt.scope),this.preferenceService.set(c.AINativeSettingSectionsId.ContextWindow,zt[qt.newValue].contextWindow,qt.scope))})),dn&&this.initMCPServers(),ct&&this.warmUpDefaultAcpPool()})}onStop(){var ct;(ct=this.webMcpModelContextDisposable)===null||ct===void 0||ct.dispose()}warmUpDefaultAcpPool(){const ct=this.aiBackService.warmUpAgentPool,Tt=this.acpConfigProvider.resolvePrewarmConfig;!ct||!Tt||Tt.call(this.acpConfigProvider).then(async Qt=>{Qt&&await ct.call(this.aiBackService,Qt)},Qt=>{this.logger.warn("[AINative] Failed to resolve ACP pool warmup config",Qt)}).catch(Qt=>{this.logger.warn("[AINative] Failed to warm up ACP agent pool",Qt)})}registerWebMcpSurface(){if(this.webMcpModelContextDisposable)return;const ct=this.injector.get(u.WebMcpGroupRegistryToken);ct.registerGroup((0,B.createOpenSumiMcpGroup)(this.injector)),ct.registerGroup((0,U.createWorkspaceGroup)(this.injector)),ct.registerGroup((0,K.createSearchGroup)(this.injector)),ct.registerGroup((0,k.createDiagnosticsGroup)(this.injector)),ct.registerGroup((0,L.createFileGroup)(this.injector)),ct.registerGroup((0,W.createTerminalGroup)(this.injector)),ct.registerGroup((0,N.createEditorGroup)(this.injector)),ct.registerGroup((0,x.createAcpChatGroup)(this.injector)),this.webMcpModelContextDisposable=(0,G.registerWebMcpModelContextTools)(ct)}async initMCPServers(){var ct,Tt;const Qt=await this.storageProvider(u.STORAGE_NAMESPACE.CHAT);let dn=Qt.get(T.MCPServersDisabledKey,[]);const Kn=this.preferenceService.get(c.AINativeSettingSectionsId.MCPServers,[]);let fn=this.preferenceService.resolve("mcp",{mcpServers:{}},void 0);if(fn.scope===u.PreferenceScope.Default&&Kn.length>0){const zt={mcpServers:{}},st=new Set;Kn.forEach($e=>{$e.type===I.MCP_SERVER_TYPE.SSE?zt.mcpServers[$e.name]={url:$e.serverHost}:$e.type===I.MCP_SERVER_TYPE.STDIO&&(zt.mcpServers[$e.name]={command:$e.command,args:$e.args,env:$e.env}),$e.enabled||st.add($e.name)}),!((ct=Kn.find($e=>$e.name===S.BUILTIN_MCP_SERVER_NAME))===null||ct===void 0)&&ct.enabled||st.add(S.BUILTIN_MCP_SERVER_NAME),await this.preferenceService.set("mcp",zt,u.PreferenceScope.Workspace),fn=this.preferenceService.resolve("mcp",{mcpServers:{}},void 0),dn=Array.from(st),Qt.set(T.MCPServersDisabledKey,dn)}const qt=(Tt=fn.value)===null||Tt===void 0?void 0:Tt.mcpServers,Rn=this.preferenceService.get(c.AINativeSettingSectionsId.WebMcpEnabled,!0);if(this.sumiMCPServerBackendProxy.$initBuiltinMCPServer(!dn.includes(S.BUILTIN_MCP_SERVER_NAME)&&Rn!==!1),qt&&Object.keys(qt).length>0){const zt=(await Promise.all(Object.keys(qt).map(async st=>await this.mcpConfigService.getServerConfigByName(st)))).filter(st=>st!==void 0);await this.sumiMCPServerBackendProxy.$initExternalMCPServers(zt)}this.mcpConfigService.fireMCPServersChange(!0)}getModelByName(ct){switch(ct){case"deepseek":return S.deepSeekModels;case"anthropic":return S.anthropicModels;case"openai":return S.openAiNativeModels;default:return}}registerFeature(){this.contributions.getContributions().forEach(ct=>{var Tt,Qt,dn,Kn,fn,qt,Rn,zt,st;(Tt=ct.registerInlineChatFeature)===null||Tt===void 0||Tt.call(ct,this.inlineChatFeatureRegistry),(Qt=ct.registerChatFeature)===null||Qt===void 0||Qt.call(ct,this.chatFeatureRegistry),(dn=ct.registerResolveConflictFeature)===null||dn===void 0||dn.call(ct,this.resolveConflictRegistry),(Kn=ct.registerRenameProvider)===null||Kn===void 0||Kn.call(ct,this.renameCandidatesProviderRegistry),(fn=ct.registerChatRender)===null||fn===void 0||fn.call(ct,this.chatRenderRegistry),(qt=ct.registerTerminalProvider)===null||qt===void 0||qt.call(ct,this.terminalProviderRegistry),(Rn=ct.registerIntelligentCompletionFeature)===null||Rn===void 0||Rn.call(ct,this.intelligentCompletionsRegistry),(zt=ct.registerProblemFixFeature)===null||zt===void 0||zt.call(ct,this.problemFixProviderRegistry),(st=ct.registerChatAgentPromptProvider)===null||st===void 0||st.call(ct)}),this.registerDefaultInputs(),this.registerChatViews(),this.aiNativeConfigService.capabilities.supportsChatAssistant&&this.inlineChatFeatureRegistry.registerEditorInlineChat({id:"ai-chat",name:"Chat",title:"Add to Chat",renderType:"button"},{execute:async(ct,Tt)=>{const Qt=ct.getModel();if(!Qt)return;const dn=Qt.uri,[Kn,fn]=[Tt.selectionStartLineNumber,Tt.positionLineNumber].sort((qt,Rn)=>qt-Rn);this.llmContextService.addFileToContext(new u.URI(dn.toString()),[Kn,fn],!0),this.chatService.sendMessage({message:"",immediate:!1})}}),this.mcpServerContributions.getContributions().forEach(ct=>{ct.registerMCPServer(this.mcpServerRegistry)})}registerDefaultInputs(){this.chatInputRegistry.registerChatInput({id:"acp-mention-input",component:M.AcpChatMentionInput,capabilities:["restore-draft","focus","expand","images","mentions","paste","rich-queued-edit"],queuedTurnEditor:O.AcpQueuedTurnEditor,priority:200,when:()=>this.aiNativeConfigService.capabilities.supportsAgentMode}),this.chatInputRegistry.registerChatInput({id:"acp-chat-input",component:R.AcpChatInput,capabilities:["restore-draft","focus","expand"],priority:150,when:()=>this.aiNativeConfigService.capabilities.supportsAgentMode}),this.chatInputRegistry.registerChatInput({id:"mention-input",component:be.ChatMentionInput,priority:100,when:()=>this.aiNativeConfigService.capabilities.supportsMCP}),this.chatInputRegistry.registerChatInput({id:"chat-input",component:q.ChatInput,priority:50})}registerChatViews(){this.chatViewRegistry.registerChatView({id:"acp-chat-view",component:ce.AIChatViewACP,priority:200,when:()=>this.aiNativeConfigService.capabilities.supportsAgentMode}),this.chatViewRegistry.registerChatView({id:"default-chat-view",component:ie.AIChatView,priority:50})}registerSetting(ct){ct.registerSettingGroup({id:c.AI_NATIVE_SETTING_GROUP_ID,title:u.AI_NATIVE_SETTING_GROUP_TITLE,iconClass:(0,c.getIcon)("magic-wand")}),ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.chat.title"),preferences:[{id:c.AINativeSettingSectionsId.ChatVisibleType,localized:"preference.ai.native.chat.visible.type"},{id:c.AINativeSettingSectionsId.PanelLayout,localized:"preference.ai.native.panelLayout"}]}),ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.interface.quick.title"),preferences:[{id:c.AINativeSettingSectionsId.InterfaceQuickNavigationEnabled,localized:"preference.ai.native.interface.quick.navigation"}]}),this.aiNativeConfigService.capabilities.supportsInlineCompletion&&(ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.intelligentCompletions.title"),preferences:[{id:c.AINativeSettingSectionsId.IntelligentCompletionsCacheEnabled,localized:"preference.ai.native.intelligentCompletions.cache.enabled"},{id:c.AINativeSettingSectionsId.IntelligentCompletionsDebounceTime,localized:"preference.ai.native.intelligentCompletions.debounceTime"},{id:c.AINativeSettingSectionsId.IntelligentCompletionsPromptEngineeringEnabled,localized:"preference.ai.native.intelligentCompletions.promptEngineering.enabled"},{id:c.AINativeSettingSectionsId.IntelligentCompletionsAlwaysVisible,localized:"preference.ai.native.intelligentCompletions.alwaysVisible"}]}),ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.codeEdits.title"),preferences:[{id:c.AINativeSettingSectionsId.CodeEditsLintErrors,localized:"preference.ai.native.codeEdits.lintErrors"},{id:c.AINativeSettingSectionsId.CodeEditsLineChange,localized:"preference.ai.native.codeEdits.lineChange"},{id:c.AINativeSettingSectionsId.CodeEditsTyping,localized:"preference.ai.native.codeEdits.typing"},{id:c.AINativeSettingSectionsId.CodeEditsRenderType,localized:"preference.ai.native.codeEdits.renderType"},{id:c.AINativeSettingSectionsId.SystemPrompt,localized:"preference.ai.native.chat.system.prompt"}]})),this.aiNativeConfigService.capabilities.supportsCustomLLMSettings&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.llm.apiSettings.title"),preferences:[{id:c.AINativeSettingSectionsId.LLMModelSelection,localized:"preference.ai.native.llm.model.selection"},{id:c.AINativeSettingSectionsId.ModelID,localized:"preference.ai.native.llm.model.id"},{id:c.AINativeSettingSectionsId.DeepseekApiKey,localized:"preference.ai.native.deepseek.apiKey"},{id:c.AINativeSettingSectionsId.AnthropicApiKey,localized:"preference.ai.native.anthropic.apiKey"},{id:c.AINativeSettingSectionsId.OpenaiApiKey,localized:"preference.ai.native.openai.apiKey"},{id:c.AINativeSettingSectionsId.OpenaiBaseURL,localized:"preference.ai.native.openai.baseURL"},{id:c.AINativeSettingSectionsId.MaxTokens,localized:"preference.ai.native.maxTokens"},{id:c.AINativeSettingSectionsId.ContextWindow,localized:"preference.ai.native.contextWindow"}]}),this.aiNativeConfigService.capabilities.supportsMCP&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.mcp.settings.title"),preferences:[{id:c.AINativeSettingSectionsId.MCPServers,localized:"preference.ai.native.mcp.servers"},{id:c.AINativeSettingSectionsId.TerminalAutoRun,localized:"ai.native.terminal.autorun"}]}),this.aiNativeConfigService.capabilities.supportsAgentMode&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.agent.configs.title"),preferences:[{id:c.AINativeSettingSectionsId.AgentConfigs,localized:"preference.ai.native.agent.configs"},{id:c.AINativeSettingSectionsId.DefaultAgentType,localized:"preference.ai.native.agent.defaultType"},{id:c.AINativeSettingSectionsId.AcpThreadPoolSize,localized:"preference.ai-native.acp.threadPoolSize"},{id:c.AINativeSettingSectionsId.AcpDeliveryMode,localized:"preference.ai-native.acp.deliveryMode"}]}),this.aiNativeConfigService.capabilities.supportsInlineChat&&ct.registerSettingSection(c.AI_NATIVE_SETTING_GROUP_ID,{title:(0,c.localize)("preference.ai.native.inlineChat.title"),preferences:[{id:c.AINativeSettingSectionsId.InlineChatAutoVisible,localized:"preference.ai.native.inlineChat.auto.visible"},{id:c.AINativeSettingSectionsId.InlineChatCodeActionEnabled,localized:"preference.ai.native.inlineChat.codeAction.enabled"},{id:c.AINativeSettingSectionsId.InlineDiffPreviewMode,localized:"preference.ai.native.inlineDiff.preview.mode"}]})}registerEditorFeature(ct){ct.registerEditorFeatureContribution({contribute:Tt=>{const{monacoEditor:Qt}=Tt;return this.codeActionSingleHandler.mountEditor(Tt.monacoEditor),Qt.onDidScrollChange(()=>{this.ctxMenuRenderer.visible&&this.ctxMenuRenderer.hide(!0)})}})}registerEditorComponent(ct){ct.registerEditorSideWidget({id:t.INLINE_DIFF_MANAGER_WIDGET_ID,component:Ye.InlineDiffManager,displaysOnResource:Tt=>{var Qt;return!!(this.aiNativeConfigService.capabilities.supportsMCP&&(!((Qt=this.applyService.getUriCodeBlocks(Tt.uri))===null||Qt===void 0)&&Qt.filter(dn=>dn.status==="pending").length))}})}registerCommands(ct){(0,pe.registerAgenticWorkbenchRevealCommandInterceptors)(ct,this.panelLayoutService,this.mainLayoutService),ct.registerCommand(j.AI_CHAT_INPUT_TOGGLE_EXPANDED,{execute:()=>{var Tt,Qt;return(Qt=(Tt=this.chatInputRegistry.getActiveInputHandle())===null||Tt===void 0?void 0:Tt.toggleExpanded)===null||Qt===void 0?void 0:Qt.call(Tt)}}),ct.registerCommand({...Y.AI_CHAT_NEW_CHAT,enablement:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == classic`},{execute:()=>{const Tt=this.chatInputRegistry.preserveActiveDraft()||this.aiChatService.getInputDraft();this.aiChatService.updateInputDraft(Tt),this.panelLayoutService.showAIChatView("classic"),this.aiChatService.enterDraftSession(),this.chatInputRegistry.restoreActiveDraft(Tt),this.focusChatInputAfterReveal()}}),ct.registerCommand({...Y.AI_CHAT_NEW_TASK,enablement:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == agentic`},{execute:async Tt=>{const Qt=this.chatInputRegistry.preserveActiveDraft()||this.aiChatService.getInputDraft();this.aiChatService.updateInputDraft(Qt),this.panelLayoutService.showAIChatView("agentic");const dn=await this.agenticWorkspaceSwitchService.launchHeaderTask(Tt);if(dn.status==="launched"){this.chatInputRegistry.restoreActiveDraft(Qt),this.focusChatInputAfterReveal();return}if(dn.status==="no-agent"){const Kn=(0,c.localize)("aiNative.chat.agentSelector.configureAgents","Agent Configurations");await this.messageService.warning((0,c.localize)("aiNative.chat.newTask.noAgent","No ACP Agent available"),[Kn],!0)===Kn&&(await this.preferenceService.set(c.AINativeSettingSectionsId.AgentConfigs,(0,me.getAvailableAgentConfigs)(this.preferenceService),u.PreferenceScope.User),await this.commandService.executeCommand(c.COMMON_COMMANDS.OPEN_PREFERENCES.id,c.AINativeSettingSectionsId.AgentConfigs));return}if(dn.status==="project-unavailable"||dn.status==="no-project"){await this.messageService.warning((0,c.localize)("aiNative.chat.newTask.workspaceUnavailable","Workspace Target unavailable"));return}dn.status==="failed"&&await this.messageService.warning((0,c.localize)("aiNative.chat.newTask.failed","Failed to create a new Task"))}}),ct.registerCommand(_.AI_INLINE_CHAT_VISIBLE,{execute:Tt=>{this.aiInlineChatService._onInlineChatVisible.fire(Tt)}}),ct.registerCommand(_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE,{execute:async Tt=>{var Qt;if(!Tt){this.inlineInputService.hide();return}this.commandService.executeCommand(_.AI_INLINE_CHAT_VISIBLE.id,!1);const dn=this.workbenchEditorService.currentCodeEditor;if(!dn)return;const Kn=dn.monacoEditor.getPosition();if(!Kn)return;const fn=dn.monacoEditor.getSelection();if(Kn?((Qt=dn.monacoEditor.getModel())===null||Qt===void 0?void 0:Qt.getLineLength(Kn.lineNumber))===0:!1){this.inlineInputService.visibleByPosition(Kn);return}if(fn&&!fn.isEmpty()){this.inlineInputService.visibleBySelection(fn);return}this.inlineInputService.visibleByNearestCodeBlock(Kn,dn.monacoEditor)}}),ct.registerCommand(_.AI_INLINE_CHAT_INTERACTIVE_INPUT_CANCEL,{execute:()=>{var Tt;const Qt=this.workbenchEditorService.currentCodeEditor;Qt&&((Tt=_t.InlineInputController.get(Qt.monacoEditor))===null||Tt===void 0||Tt.cancelToken())}}),ct.registerCommand(_.AI_INLINE_COMPLETION_REPORTER,{execute:(Tt,Qt,dn,Kn)=>{this.aiCompletionsService.report({sessionId:Qt,accept:dn,relationId:Tt,code:Kn})}}),ct.registerCommand(_.AI_CHAT_VISIBLE,{execute:Tt=>{if(Tt===!1){this.panelLayoutService.hideAIChatView();return}this.panelLayoutService.showAIChatView()}}),ct.registerCommand(_.AI_PANEL_LAYOUT_SET,{execute:Tt=>this.panelLayoutService.setLayoutMode(Tt)}),ct.registerCommand(_.AI_PANEL_LAYOUT_GET,{execute:()=>this.panelLayoutService.getLayoutMode()}),ct.registerCommand(_.AI_PANEL_LAYOUT_TOGGLE,{execute:()=>this.panelLayoutService.toggleLayoutMode()}),ct.registerCommand(_.AI_AGENTIC_WORKBENCH_TOGGLE,{execute:Tt=>this.panelLayoutService.toggleAgenticWorkbenchVisibility(Tt)}),ct.registerCommand(_.AI_AGENTIC_WORKBENCH_IS_VISIBLE,{execute:()=>this.panelLayoutService.isAgenticWorkbenchVisible()}),ct.registerCommand(_.AI_INLINE_COMPLETION_VISIBLE,{execute:async Tt=>{Tt||(this.aiCompletionsService.hideStatusBarItem(),this.aiInlineCompletionsProvider.setVisibleCompletion(!1),this.aiInlineCompletionsProvider.cancelRequest())}}),ct.registerCommand(_.AI_INLINE_DIFF_PARTIAL_EDIT,{execute:Tt=>{this.inlineStreamDiffService.launchAcceptDiscardPartialEdit(Tt)}}),ct.afterExecuteCommand(A.HideInlineCompletion.ID,()=>{this.commandService.executeCommand(_.AI_INLINE_COMPLETION_VISIBLE.id,!1)})}focusChatInputAfterReveal(){const ct=(Tt=0)=>{this.chatInputRegistry.focusActiveInput(),!(this.chatInputRegistry.isActiveInputFocused()!==!1||Tt>=60)&&c.fastdom.measureAtNextFrame(()=>ct(Tt+1))};ct()}registerMenus(ct){ct.registerMenuItem(f.MenuId.MenubarViewMenu,{submenu:Ie.AI_PANEL_LAYOUT_MENU,label:"Panel Layout",group:"5_panel"}),ct.registerMenuItem(Ie.AI_PANEL_LAYOUT_MENU,{command:{id:_.AI_PANEL_LAYOUT_SET.id,label:"Classic"},group:"navigation",extraTailArgs:["classic"],toggledWhen:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == classic`}),ct.registerMenuItem(Ie.AI_PANEL_LAYOUT_MENU,{command:{id:_.AI_PANEL_LAYOUT_SET.id,label:"Agent"},group:"navigation",extraTailArgs:["agentic"],toggledWhen:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == agentic`})}registerRenderer(ct){const Tt={isLatter:!0};this.designLayoutConfig.supportExternalChatPanel?ct.registerSlotRenderer(S.AI_CHAT_VIEW_ID,Ae.AIChatTabRendererWithTab,Tt):ct.registerSlotRenderer(S.AI_CHAT_VIEW_ID,Ae.AIChatTabRenderer,Tt),this.designLayoutConfig.useMergeRightWithLeftPanel&&(ct.registerSlotRenderer(c.SlotLocation.view,Ae.AILeftTabRenderer,Object.assign({},Tt,{isLatter:!1})),ct.registerSlotRenderer(c.SlotLocation.extendView,Ae.AIRightTabRenderer,Tt))}registerComponent(ct){ct.register(S.AI_CHAT_CONTAINER_ID,[],{component:rt,title:(0,c.localize)("aiNative.chat.ai.assistant.name"),iconClass:(0,c.getIcon)("magic-wand"),containerId:S.AI_CHAT_CONTAINER_ID}),ct.register(S.AI_MENU_BAR_DEBUG_TOOLBAR,{id:S.AI_MENU_BAR_DEBUG_TOOLBAR,component:De.AIRunToolbar}),ct.register(S.AI_CHAT_LOGO_AVATAR_ID,{id:S.AI_CHAT_LOGO_AVATAR_ID,component:xe.AIChatLogoAvatar})}registerKeybindings(ct){this.aiNativeConfigService.capabilities.supportsAgentMode&&(ct.registerKeybinding({command:Y.AI_CHAT_NEW_CHAT.id,keybinding:"ctrlcmd+alt+n",when:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == classic`},c.KeybindingScope.USER),ct.registerKeybinding({command:Y.AI_CHAT_NEW_TASK.id,keybinding:"ctrlcmd+alt+n",when:`${Ie.AI_PANEL_LAYOUT_CONTEXT} == agentic`},c.KeybindingScope.USER)),this.aiNativeConfigService.capabilities.supportsInlineChat&&(ct.registerKeybinding({command:_.AI_INLINE_CHAT_VISIBLE.id,keybinding:"ctrlcmd+i",when:"editorTextFocus",args:!0,priority:0},c.KeybindingScope.USER),ct.registerKeybinding({command:_.AI_INLINE_CHAT_VISIBLE.id,keybinding:"esc",args:!1,when:`editorFocus && ${v.InlineChatIsVisible.raw}`}),this.inlineInputService.getInteractiveInputHandler()&&(ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE.id,keybinding:this.aiNativeConfigService.inlineChat.inputKeybinding,args:!0,priority:0,when:`editorFocus && (${v.InlineChatIsVisible.raw} || inlineSuggestionVisible)`},c.KeybindingScope.USER),ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE.id,keybinding:"esc",args:!1,priority:0,when:`editorFocus && ${v.InlineInputWidgetIsVisible.raw}`}),ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_CANCEL.id,keybinding:"esc",priority:1,when:`editorFocus && ${v.InlineInputWidgetIsStreaming.raw}`}),ct.registerKeybinding({command:_.AI_INLINE_CHAT_INTERACTIVE_INPUT_VISIBLE.id,keybinding:this.aiNativeConfigService.inlineChat.inputKeybinding,args:!0,priority:0,when:`editorFocus && ${v.InlineHintWidgetIsVisible.raw} && ${v.InlineChatIsVisible.not}`},c.KeybindingScope.USER))),ct.registerKeybinding({command:_.AI_INLINE_DIFF_PARTIAL_EDIT.id,keybinding:"ctrl+y",args:!0,priority:100,when:`editorTextFocus && ${v.InlineDiffPartialEditsIsVisible.raw}`}),ct.registerKeybinding({command:_.AI_INLINE_DIFF_PARTIAL_EDIT.id,keybinding:"ctrl+n",args:!1,priority:100,when:`editorTextFocus && ${v.InlineDiffPartialEditsIsVisible.raw}`})}};t.AINativeBrowserContribution=Xe,n.__decorate([(0,o.Autowired)(c.AppConfig),n.__metadata("design:type",Object)],Xe.prototype,"appConfig",void 0),n.__decorate([(0,o.Autowired)(o.INJECTOR_TOKEN),n.__metadata("design:type",o.Injector)],Xe.prototype,"injector",void 0),n.__decorate([(0,o.Autowired)(a.IBrowserCtxMenu),n.__metadata("design:type",a.IBrowserCtxMenu)],Xe.prototype,"ctxMenuRenderer",void 0),n.__decorate([(0,o.Autowired)(le.AINativeCoreContribution),n.__metadata("design:type",Object)],Xe.prototype,"contributions",void 0),n.__decorate([(0,o.Autowired)(le.MCPServerContribution),n.__metadata("design:type",Object)],Xe.prototype,"mcpServerContributions",void 0),n.__decorate([(0,o.Autowired)(le.TokenMCPServerRegistry),n.__metadata("design:type",Object)],Xe.prototype,"mcpServerRegistry",void 0),n.__decorate([(0,o.Autowired)(u.InlineChatFeatureRegistryToken),n.__metadata("design:type",Ee.InlineChatFeatureRegistry)],Xe.prototype,"inlineChatFeatureRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ChatFeatureRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatFeatureRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ChatRenderRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatRenderRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ChatInputRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatInputRegistry",void 0),n.__decorate([(0,o.Autowired)(S.IChatInternalService),n.__metadata("design:type",te.AcpChatInternalService)],Xe.prototype,"aiChatService",void 0),n.__decorate([(0,o.Autowired)(u.ChatViewRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"chatViewRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ResolveConflictRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"resolveConflictRegistry",void 0),n.__decorate([(0,o.Autowired)(u.RenameCandidatesProviderRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"renameCandidatesProviderRegistry",void 0),n.__decorate([(0,o.Autowired)(u.TerminalRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"terminalProviderRegistry",void 0),n.__decorate([(0,o.Autowired)(u.IntelligentCompletionsRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"intelligentCompletionsRegistry",void 0),n.__decorate([(0,o.Autowired)(u.ProblemFixRegistryToken),n.__metadata("design:type",Object)],Xe.prototype,"problemFixProviderRegistry",void 0),n.__decorate([(0,o.Autowired)(c.AINativeConfigService),n.__metadata("design:type",c.AINativeConfigService)],Xe.prototype,"aiNativeConfigService",void 0),n.__decorate([(0,o.Autowired)(u.AIBackSerivcePath),n.__metadata("design:type",Object)],Xe.prototype,"aiBackService",void 0),n.__decorate([(0,o.Autowired)(u.IACPConfigProvider),n.__metadata("design:type",Object)],Xe.prototype,"acpConfigProvider",void 0),n.__decorate([(0,o.Autowired)(u.ILogger),n.__metadata("design:type",Object)],Xe.prototype,"logger",void 0),n.__decorate([(0,o.Autowired)(p.DesignLayoutConfig),n.__metadata("design:type",p.DesignLayoutConfig)],Xe.prototype,"designLayoutConfig",void 0),n.__decorate([(0,o.Autowired)(Ie.AIPanelLayoutService),n.__metadata("design:type",Ie.AIPanelLayoutService)],Xe.prototype,"panelLayoutService",void 0),n.__decorate([(0,o.Autowired)(D.AgenticWorkspaceSwitchService),n.__metadata("design:type",D.AgenticWorkspaceSwitchService)],Xe.prototype,"agenticWorkspaceSwitchService",void 0),n.__decorate([(0,o.Autowired)(m.IMessageService),n.__metadata("design:type",Object)],Xe.prototype,"messageService",void 0),n.__decorate([(0,o.Autowired)(Oe.AICompletionsService),n.__metadata("design:type",Oe.AICompletionsService)],Xe.prototype,"aiCompletionsService",void 0),n.__decorate([(0,o.Autowired)(ne.AIInlineCompletionsProvider),n.__metadata("design:type",ne.AIInlineCompletionsProvider)],Xe.prototype,"aiInlineCompletionsProvider",void 0),n.__decorate([(0,o.Autowired)(u.CommandService),n.__metadata("design:type",Object)],Xe.prototype,"commandService",void 0),n.__decorate([(0,o.Autowired)(c.PreferenceSchemaProvider),n.__metadata("design:type",c.PreferenceSchemaProvider)],Xe.prototype,"preferenceSchemaProvider",void 0),n.__decorate([(0,o.Autowired)(c.IPreferenceSettingsService),n.__metadata("design:type",Object)],Xe.prototype,"preferenceSettings",void 0),n.__decorate([(0,o.Autowired)(c.PreferenceService),n.__metadata("design:type",Object)],Xe.prototype,"preferenceService",void 0),n.__decorate([(0,o.Autowired)(S.ChatProxyServiceToken),n.__metadata("design:type",H.ChatProxyService)],Xe.prototype,"chatProxyService",void 0),n.__decorate([(0,o.Autowired)(c.IAIInlineChatService),n.__metadata("design:type",Ne.InlineChatService)],Xe.prototype,"aiInlineChatService",void 0),n.__decorate([(0,o.Autowired)(Ot.InlineInputService),n.__metadata("design:type",Ot.InlineInputService)],Xe.prototype,"inlineInputService",void 0),n.__decorate([(0,o.Autowired)(nt.InlineStreamDiffService),n.__metadata("design:type",nt.InlineStreamDiffService)],Xe.prototype,"inlineStreamDiffService",void 0),n.__decorate([(0,o.Autowired)(ke.RenameSingleHandler),n.__metadata("design:type",ke.RenameSingleHandler)],Xe.prototype,"renameSingleHandler",void 0),n.__decorate([(0,o.Autowired)(fe.CodeActionSingleHandler),n.__metadata("design:type",fe.CodeActionSingleHandler)],Xe.prototype,"codeActionSingleHandler",void 0),n.__decorate([(0,o.Autowired)(S.SumiMCPServerProxyServicePath),n.__metadata("design:type",Object)],Xe.prototype,"sumiMCPServerBackendProxy",void 0),n.__decorate([(0,o.Autowired)(u.MCPConfigServiceToken),n.__metadata("design:type",re.MCPConfigService)],Xe.prototype,"mcpConfigService",void 0),n.__decorate([(0,o.Autowired)(l.WorkbenchEditorService),n.__metadata("design:type",g.WorkbenchEditorServiceImpl)],Xe.prototype,"workbenchEditorService",void 0),n.__decorate([(0,o.Autowired)(E.IMainLayoutService),n.__metadata("design:type",Object)],Xe.prototype,"mainLayoutService",void 0),n.__decorate([(0,o.Autowired)(S.IChatManagerService),n.__metadata("design:type",V.ChatManagerService)],Xe.prototype,"chatManagerService",void 0),n.__decorate([(0,o.Autowired)(S.IChatInternalService),n.__metadata("design:type",Z.ChatInternalService)],Xe.prototype,"chatInternalService",void 0),n.__decorate([(0,o.Autowired)(_e.BaseApplyService),n.__metadata("design:type",_e.BaseApplyService)],Xe.prototype,"applyService",void 0),n.__decorate([(0,o.Autowired)(u.StorageProvider),n.__metadata("design:type",Function)],Xe.prototype,"storageProvider",void 0),n.__decorate([(0,o.Autowired)(u.ChatServiceToken),n.__metadata("design:type",Q.ChatService)],Xe.prototype,"chatService",void 0),n.__decorate([(0,o.Autowired)(w.LLMContextServiceToken),n.__metadata("design:type",Object)],Xe.prototype,"llmContextService",void 0),n.__decorate([(0,o.Autowired)(),n.__metadata("design:type",z.ChatEditSchemeDocumentProvider)],Xe.prototype,"chatEditResourceProvider",void 0),n.__decorate([(0,o.Autowired)(),n.__metadata("design:type",$.ChatMultiDiffResolver)],Xe.prototype,"chatMultiDiffResolver",void 0),t.AINativeBrowserContribution=Xe=n.__decorate([(0,c.Domain)(c.ClientAppContribution,d.BrowserEditorContribution,c.CommandContribution,h.SettingContribution,c.KeybindingContribution,c.ComponentContribution,c.SlotRendererContribution,f.MenuContribution,c.MonacoContribution,d.MultiDiffSourceContribution),n.__metadata("design:paramtypes",[])],Xe)},77852:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AcpQueuedTurns=void 0,t.getAcpQueuedTurnPreview=f;const n=e(85608),r=n.__importStar(e(14041)),o=e(41869),c=e(81878),_=e(70392),v=e(98864),p=n.__importDefault(e(77256));function f(s){return(0,v.cleanAttachedTextWrapper)(s).replace(/<br\s*\/?>/gi," ").replace(/<\/(div|p|li|section)>/gi," ").replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/\s+/g," ").trim()||(0,o.localize)("aiNative.chat.queue.emptyPreview","Empty message")}function a(s){switch(s){case"manual-stop":return(0,o.localize)("aiNative.chat.queue.pauseReason.manualStop","Stopped");case"agent-error":return(0,o.localize)("aiNative.chat.queue.pauseReason.agentError","Agent error");case"start-failed":return(0,o.localize)("aiNative.chat.queue.pauseReason.startFailed","Could not start");case"cancel-failed":return(0,o.localize)("aiNative.chat.queue.pauseReason.cancelFailed","Could not stop");default:return}}const u=({snapshot:s,expanded:l,disabled:d=!1,capabilities:g,QueuedEditor:E,onToggleExpanded:m,onResume:h,onClear:b,onBeginEdit:A,onCommitEdit:y,onCancelEdit:S,onDelete:w,onImmediateSend:T,onEditorReady:I,onOpenCapacitySettings:D})=>{var R,M;if(s.initialStartPending)return r.createElement("div",{className:p.default.queued_turns_status,"data-testid":"acp-task-launch-status",role:"status"},r.createElement("span",null,(0,o.localize)("aiNative.chat.acp.startingTask","Starting task\u2026")));if(s.entries.length===0&&s.phase!=="paused")return null;const O=g.includes("rich-queued-edit")&&!!E,x=!!s.editingTurnId,k=s.entries.length===1?(0,o.localize)("aiNative.chat.queue.one","1 Queued Turn"):_.strings.format((0,o.localize)("aiNative.chat.queue.many","{0} Queued Turns"),s.entries.length),N=a(s.pauseReason),L=((R=s.pauseError)===null||R===void 0?void 0:R.name)==="ACP_THREAD_POOL_SATURATED",B=(M=s.pauseError)===null||M===void 0?void 0:M.limit;return r.createElement("section",{className:p.default.queued_turns,"aria-label":(0,o.localize)("aiNative.chat.queue.ariaLabel","Queued turns")},r.createElement("div",{className:p.default.queued_turns_header},r.createElement("button",{"aria-expanded":l,"aria-label":(0,o.localize)("aiNative.chat.queue.toggleAriaLabel","Toggle queued turns"),className:p.default.queued_turns_summary,"data-testid":"acp-queued-turns-summary",disabled:d||x,onClick:m,title:d||x?(0,o.localize)("aiNative.chat.queue.finishEditBeforeCollapse","Finish editing before collapsing"):void 0,type:"button"},r.createElement(c.Icon,{className:p.default.queued_turns_disclosure,iconClass:(0,o.getIcon)(l?"arrow-down":"arrow-right")}),r.createElement("span",null,k)),r.createElement("div",{className:p.default.queued_turns_header_actions},s.phase==="paused"&&!L&&r.createElement("div",{className:p.default.queued_turns_status,"data-testid":"acp-queued-turn-status",role:"status"},r.createElement("span",null,(0,o.localize)("aiNative.chat.queue.paused","Paused")),N&&r.createElement("span",{className:p.default.queued_turns_pause_reason},N),s.canResume&&r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.resumeAriaLabel","Resume queued turns"),className:p.default.queued_turns_resume,"data-testid":"acp-queued-turn-resume",disabled:d,onClick:h,type:"button"},(0,o.localize)("aiNative.chat.queue.resume","Resume Queue"))),s.entries.length>0&&r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.clearAriaLabel","Clear queued turns"),className:p.default.queued_turns_clear,disabled:d,onClick:b,type:"button"},(0,o.localize)("aiNative.chat.queue.clearAll","Clear All")))),s.phase==="paused"&&L&&r.createElement("div",{className:p.default.queued_turns_status,"data-testid":"acp-capacity-error",role:"alert"},r.createElement("span",null,B?_.strings.format((0,o.localize)("aiNative.chat.acp.capacityFull.withLimit","The Agent task capacity limit ({0}) has been reached, and no reusable Agent is currently available. Your task draft and unsent content have been preserved. Wait for a running task to finish and try again, or increase the ACP process limit in Settings."),B):(0,o.localize)("aiNative.chat.acp.capacityFull","The Agent task capacity limit has been reached, and no reusable Agent is currently available. Your task draft and unsent content have been preserved. Wait for a running task to finish and try again, or increase the ACP process limit in Settings.")),r.createElement("button",{"data-testid":"acp-capacity-retry",disabled:d,onClick:h,type:"button"},(0,o.localize)("aiNative.chat.acp.capacityRetry","Retry")),D&&r.createElement("button",{"data-testid":"acp-capacity-open-settings",disabled:d,onClick:D,type:"button"},(0,o.localize)("aiNative.chat.acp.capacityOpenSettings","Open Settings"))),l&&r.createElement("div",{className:p.default.queued_turns_list},s.entries.map((K,W)=>{const U=O&&s.editingTurnId===K.id;return r.createElement("div",{className:U?p.default.queued_turn_editing:p.default.queued_turn,"data-testid":"acp-queued-turn",key:K.id},U&&E?r.createElement("div",{className:p.default.queued_turn_editor,"data-testid":"acp-queued-turn-editor"},r.createElement(E,{turn:K,onSave:G=>d?void 0:y(K.id,G,!1),onCancel:()=>{d||S(K.id)},onImmediateSend:G=>d?void 0:y(K.id,G,!0),onReady:I,disabled:d,immediateSendDisabled:d||s.phase==="cancelling-for-immediate"})):r.createElement(r.Fragment,null,r.createElement("div",{className:p.default.queued_turn_index},W+1),r.createElement("div",{className:p.default.queued_turn_preview,"data-testid":"acp-queued-turn-preview"},f(K.message)),r.createElement("div",{className:p.default.queued_turn_actions},O&&r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.editAriaLabel","Edit queued turn"),"data-testid":"acp-queued-turn-edit",disabled:d,onClick:()=>A(K.id),type:"button"},(0,o.localize)("aiNative.chat.queue.edit","Edit")),r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.deleteAriaLabel","Delete queued turn"),"data-testid":"acp-queued-turn-delete",disabled:d,onClick:()=>w(K.id),type:"button"},(0,o.localize)("aiNative.chat.queue.delete","Delete")),r.createElement("button",{"aria-label":(0,o.localize)("aiNative.chat.queue.immediateAriaLabel","Send queued turn immediately"),"data-testid":"acp-queued-turn-immediate",disabled:d||s.phase==="cancelling-for-immediate",onClick:()=>T(K.id),type:"button"},(0,o.localize)("aiNative.chat.queue.immediate","Immediate Send")))))})))};t.AcpQueuedTurns=u},10929:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgenticChatHeaderMaximizeAction=void 0;const n=e(85608),r=n.__importDefault(e(14041)),o=e(41869),c=e(89195),_=e(79169),v=n.__importDefault(e(77256)),p=({id:f="ai-chat-header-maximize"})=>{const a=(0,o.useInjectable)(_.AIPanelLayoutService),[u,s]=r.default.useState(()=>a.getLayoutMode()),[l,d]=r.default.useState(()=>a.isAgenticWorkbenchVisible()!==!1),g=r.default.useCallback(()=>{const b=a.isAgenticWorkbenchVisible();d(typeof b=="boolean"?b:!0)},[a]);r.default.useEffect(()=>{s(a.getLayoutMode()),g();const b=a.onDidChangePanelLayout(A=>{s(A),g()});return()=>{b.dispose()}},[a,g]),r.default.useEffect(()=>{const b=a.onDidChangeAgenticWorkbenchVisibility(A=>{d(A)});return()=>{b.dispose()}},[a]);const E=r.default.useCallback(()=>{const b=a.toggleAgenticWorkbenchVisibility(!l);typeof b=="boolean"&&d(b)},[l,a]);if(u!=="agentic")return null;const m=(0,o.localize)(l?"aiNative.chat.expand.fullescreen":"aiNative.chat.expand.unfullscreen"),h=(0,o.getIcon)(l?"fullescreen":"unfullscreen");return r.default.createElement("div",{id:f,"data-workbench-visible":String(l)},r.default.createElement(c.EnhanceIcon,{wrapperClassName:v.default.action_btn,className:h,onClick:E,tabIndex:0,role:"button",ariaLabel:m,ariaPressed:!l}))};t.AgenticChatHeaderMaximizeAction=p},89705:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getAgenticChatPanelTitle=w,t.AgenticChatPanelHeader=I,t.AgenticChatHeaderNewSessionMenu=D;const n=e(85608),r=n.__importDefault(e(53373)),o=n.__importDefault(e(14041)),c=e(41869),_=e(43718),v=e(27284),p=e(70392),f=e(51500),a=e(19413),u=e(98864),s=e(29993),l=e(20450),d=e(70004),g=e(79169),E=e(10929),m=n.__importDefault(e(77256)),h=e(28524),b=100,A={"claude-agent-acp":{label:"Claude",title:"Claude Code ACP"},qwen:{label:"Qwen",title:"Qwen"}};function y(R){const M=(0,h.getAvailableAgentConfigs)(R);return Object.entries(M).map(([O,x])=>{const k=A[O];return{value:O,label:k?.label||x.description||O,title:k?.title||S(O,x)}})}function S(R,M){return M.command?`${R} \xB7 ${M.command}`:R}function w(R,M=!1){if(M&&R?.title)return R.title.slice(0,b);const x=[...R?.history.getMessages()||[]].find(N=>N.role===1);return(x?(0,u.cleanAttachedTextWrapper)(x.content).slice(0,b):"")||(0,c.localize)("aiNative.chat.ai.assistant.name")}function T({onExecutionContextChange:R,sessionModel:M}){const O=(0,c.useInjectable)(a.IChatInternalService),x=(0,c.useInjectable)(s.AgenticTaskRegistryService),k=(0,c.useInjectable)(f.IWorkspaceService),[N,L]=o.default.useState(),[B,K]=o.default.useState(),W=o.default.useRef(0),U=o.default.useCallback(async()=>{var G;const j=++W.current,Y=k.workspace,z=(G=M?.requests)===null||G===void 0?void 0:G.at(-1),V=O.getActiveAgenticTaskTarget(M?.sessionId);try{const $=Y?.uri?_.URI.parse(Y.uri):void 0,H=$?.scheme==="file"&&Y?.isDirectory!==!1?{id:$.toString(),workspaceUri:$.toString(),workspacePath:$.codeUri.fsPath,joinedAt:0,availability:"available"}:void 0,Q=await x.listProjects(),Z=V?Q.find(ie=>ie.workspacePath===V.cwd):void 0,te=H?await x.getProject(H.id):void 0;if(j!==W.current)return;L(Z||te||H),R(Z&&Z.workspacePath!==H?.workspacePath?Z:void 0),K(V?.agentId||z?.message.agentId||O.getActiveAgenticTaskAgentId(M?.sessionId))}catch{j===W.current&&(L(void 0),R(void 0),K(void 0))}},[O,R,x,M,k]);return o.default.useEffect(()=>{U();const G=x.onDidChange(()=>void U()),j=k.onWorkspaceChanged(()=>void U()),Y=k.onWorkspaceLocationChanged(()=>void U());return()=>{W.current+=1,G.dispose(),j.dispose(),Y.dispose()}},[U,x,k]),o.default.createElement(d.AgenticTaskLaunchMenu,{project:N,preferredAgentId:B,variant:"chat-header"})}function I({onCloseTaskDraft:R,preferSessionTitle:M=!1,sessionModel:O}){var x;const k=(0,c.useInjectable)(a.IChatInternalService),N=(0,c.useInjectable)(c.PreferenceService),L=(0,c.useInjectable)(g.AIPanelLayoutService),[B,K]=o.default.useState(()=>L.getLayoutMode()),[W,U]=o.default.useState(()=>w(O,M)),[G,j]=o.default.useState(),Y=o.default.useRef(0),z=k.isActiveAgenticTaskDraft(),V=O?.title,$=k.getActiveAgenticTaskTarget(),H=$?.agentId,Q=H?((x=(0,h.getAvailableAgentConfigs)(N)[H])===null||x===void 0?void 0:x.description)||H:"",Z=$?_.URI.file($.cwd).displayName:"",te=o.default.useCallback(async()=>{++Y.current===Y.current&&U(z?(0,c.localize)("aiNative.chat.agenticTask.draft.title","New Session"):w(O,M))},[z,M,O,V]);return o.default.useEffect(()=>{K(L.getLayoutMode());const ie=L.onDidChangePanelLayout(ce=>{K(ce)});return()=>ie.dispose()},[L]),o.default.useEffect(()=>{te();const ie=O?.history.onMessageChange(()=>void te());return()=>{Y.current+=1,ie?.dispose()}},[te,O]),B!=="agentic"?null:o.default.createElement("div",{className:m.default.agentic_chat_panel_header,"data-testid":"agentic-chat-panel-header"},o.default.createElement("div",{className:m.default.agentic_chat_panel_title,"data-testid":"agentic-chat-panel-header-title",title:W},W),z&&o.default.createElement("div",{className:m.default.agentic_task_draft_context,"data-testid":"agentic-task-draft-context"},p.strings.format((0,c.localize)("aiNative.chat.agenticTask.draft.context","Using {0}"),Q),Z&&` \xB7 ${Z}`),G&&o.default.createElement("div",{"aria-label":p.strings.format((0,c.localize)("aiNative.chat.agenticTask.workingDirectory","Agent working directory: {0}"),G.workspacePath),className:m.default.agentic_task_execution_context,"data-testid":"agentic-task-execution-context",title:G.workspacePath},p.strings.format((0,c.localize)("aiNative.chat.agenticTask.workingDirectory","Agent working directory: {0}"),(0,l.getAgenticProjectDisplayLabel)(G))),o.default.createElement("div",{className:m.default.agentic_chat_panel_actions},z&&R&&o.default.createElement("button",{"aria-label":(0,c.localize)("aiNative.operate.close.title","Close"),className:m.default.agentic_task_draft_close,"data-testid":"agentic-task-draft-close",onClick:R,title:(0,c.localize)("aiNative.operate.close.title","Close"),type:"button"},o.default.createElement("span",{"aria-hidden":"true",className:"codicon codicon-close"})),o.default.createElement(T,{onExecutionContextChange:j,sessionModel:O}),o.default.createElement(E.AgenticChatHeaderMaximizeAction,{id:"agentic-chat-panel-header-maximize"})))}function D(){const R=(0,c.useInjectable)(a.IChatInternalService),M=(0,c.useInjectable)(c.PreferenceService),O=(0,c.useInjectable)(_.CommandService),[x,k]=o.default.useState(()=>y(M)),[N,L]=o.default.useState(()=>(0,h.getDefaultAgentType)(M)),[B,K]=o.default.useState(!1),[W,U]=o.default.useState(!1),G=o.default.useRef(void 0),j=o.default.useCallback(()=>{k(y(M)),L((0,h.getDefaultAgentType)(M))},[M]);o.default.useEffect(()=>{var Z,te;const ie=(Z=M.onSpecificPreferenceChange)===null||Z===void 0?void 0:Z.call(M,v.AINativeSettingSectionsId.DefaultAgentType,j),ce=(te=M.onSpecificPreferenceChange)===null||te===void 0?void 0:te.call(M,v.AINativeSettingSectionsId.AgentConfigs,j);return()=>{ie?.dispose(),ce?.dispose()}},[M,j]);const Y=o.default.useCallback(()=>{B||(G.current&&(window.clearTimeout(G.current),G.current=void 0),U(!0))},[B]),z=o.default.useCallback(()=>{G.current=window.setTimeout(()=>{U(!1),G.current=void 0},120)},[]);o.default.useEffect(()=>()=>{G.current&&window.clearTimeout(G.current)},[]);const V=o.default.useCallback(async Z=>{U(!1),K(!0);try{L(Z),await M.set(v.AINativeSettingSectionsId.DefaultAgentType,Z,_.PreferenceScope.User),R.enterDraftSession()}finally{K(!1)}},[R,M]),$=o.default.useCallback(async()=>{U(!1);try{await M.set(v.AINativeSettingSectionsId.AgentConfigs,(0,h.getAvailableAgentConfigs)(M),_.PreferenceScope.User)}finally{O.executeCommand(c.COMMON_COMMANDS.OPEN_PREFERENCES.id,v.AINativeSettingSectionsId.AgentConfigs)}},[O,M]),H=x.find(Z=>Z.value===N)||x[0],Q=(0,c.localize)("aiNative.operate.newChat.title");return o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu_group},o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu_container,onMouseEnter:Y,onMouseLeave:z},o.default.createElement("button",{"aria-disabled":B,"aria-expanded":W,"aria-haspopup":"menu","aria-label":Q,className:m.default.agentic_chat_new_session_button,"data-testid":"agentic-chat-new-session-button",disabled:B,onClick:Y,title:H?`${Q} \xB7 ${H.title}`:Q,type:"button"},o.default.createElement("span",{className:"codicon codicon-add"})),W&&o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu,"data-testid":"agentic-chat-new-session-menu",role:"menu"},x.map(Z=>{const te=Z.value===N;return o.default.createElement("button",{className:(0,r.default)(m.default.agentic_chat_new_session_menu_item,te&&m.default.agentic_chat_new_session_menu_item_selected),"data-testid":`agentic-chat-new-session-agent-${Z.value}`,key:Z.value,onClick:()=>V(Z.value),role:"menuitem",title:Z.title,type:"button"},o.default.createElement("span",{className:m.default.agentic_chat_new_session_menu_item_label},Z.label),te&&o.default.createElement("span",{className:(0,r.default)(m.default.agentic_chat_new_session_menu_item_check,(0,c.getIcon)("check"))}))}),o.default.createElement("div",{className:m.default.agentic_chat_new_session_menu_separator}),o.default.createElement("button",{className:m.default.agentic_chat_new_session_menu_item,"data-testid":"agentic-chat-agent-config-menu-item",onClick:$,role:"menuitem",type:"button"},(0,c.localize)("aiNative.chat.agentSelector.configureAgents","Agent \u914D\u7F6E")))))}},17996:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgenticVirtualMessageList=void 0;const r=e(85608).__importStar(e(14041)),o=e(68392),c=e(89892),_=new Map,v={bottom:480,top:480};function p(u,s){const l=_.get(u);if(!l||l.kind==="bottom")return s.length>0?{index:s.length-1,align:"end"}:0;const d=s.findIndex(g=>g.id===l.messageId);return d>=0?{index:d,align:"start",offset:-l.offset}:0}function f(u){const s=_.get(u);return!s||s.kind==="bottom"}function a({className:u,messages:s,renderMessage:l,sessionId:d},g){var E;const m=r.useRef(null),h=r.useRef(null),b=r.useRef(0),A=r.useRef(!0),y=r.useRef(!1),S=r.useRef(!1),w=r.useRef(),T=r.useRef(s);T.current=s;const I=r.useCallback(()=>{var N;T.current.length!==0&&((N=m.current)===null||N===void 0||N.scrollToIndex({index:T.current.length-1,align:"end"}))},[]),D=r.useCallback(()=>{var N;const L=h.current,B=L?.getBoundingClientRect(),K=Array.from(L?.querySelectorAll("[data-message-id]")||[]),W=(N=T.current[T.current.length-1])===null||N===void 0?void 0:N.id,U=K.some(z=>z.dataset.messageId===W&&(!B||z.getBoundingClientRect().top<B.bottom));if(y.current||A.current||S.current||U){_.set(d,{kind:"bottom"});return}const G=K.find(z=>!B||z.getBoundingClientRect().bottom>B.top),j=G?.dataset.messageId;if(G&&j&&B){_.set(d,{kind:"message",messageId:j,offset:G.getBoundingClientRect().top-B.top});return}const Y=T.current[b.current];Y&&_.set(d,{kind:"message",messageId:Y.id,offset:0})},[d]);r.useEffect(()=>D,[D]),r.useImperativeHandle(g,()=>({maintainBottom:()=>{var N;A.current&&((N=m.current)===null||N===void 0||N.autoscrollToBottom())},scrollToBottom:(N="auto")=>{var L;T.current.length!==0&&((L=m.current)===null||L===void 0||L.scrollToIndex({index:T.current.length-1,align:"end",behavior:N}))}}),[]);const R=s.length>0,M=(E=s[0])===null||E===void 0?void 0:E.id,O=r.useRef();(!O.current||O.current.sessionId!==d||O.current.firstMessageId!==M)&&(O.current={firstMessageId:M,location:p(d,s),sessionId:d});const x=O.current.location;r.useEffect(()=>{if(!R)return;y.current=f(d),y.current&&(A.current=!1);const N=requestAnimationFrame(()=>{var L;(L=m.current)===null||L===void 0||L.scrollToIndex(x),y.current&&I()});return()=>{cancelAnimationFrame(N),w.current!==void 0&&(cancelAnimationFrame(w.current),w.current=void 0)}},[M,R,x,I,d]);const k=r.useCallback((N,L)=>{const B=l(L);return r.createElement("div",{"data-message-id":L.id,"data-message-role":B?.position==="right"?"user":"assistant","data-testid":"agentic-message-row",style:{display:"flow-root"}},r.createElement(o.MessageBox,{...B}))},[l]);return r.createElement("div",{className:`rce-container-mlist ${u||""}`,"data-testid":"agentic-virtual-message-list",style:{height:"100%",minHeight:0,overflow:"hidden"}},r.createElement(c.Virtuoso,{key:`${d}:${M||"empty"}`,ref:m,className:"rce-mlist",style:{display:"block",height:"100%",minHeight:0,overflow:"auto",position:"relative"},data:s,computeItemKey:(N,L)=>L.id,defaultItemHeight:96,increaseViewportBy:v,initialTopMostItemIndex:x,overscan:{main:160,reverse:160},followOutput:N=>N?"auto":!1,atBottomStateChange:N=>{A.current=N,N&&(y.current=!1,_.set(d,{kind:"bottom"}))},rangeChanged:N=>{b.current=N.startIndex,S.current=N.endIndex>=T.current.length-1,y.current&&!A.current&&w.current===void 0&&(w.current=requestAnimationFrame(()=>{w.current=void 0,I()}))},scrollerRef:N=>{h.current=N instanceof HTMLElement?N:null},itemContent:k}))}t.AgenticVirtualMessageList=r.forwardRef(a)},41046:(P,t,e)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.AcpChatAgent=void 0;const r=e(85608),o=e(76003),c=e(41869),_=e(43718),v=e(27284),p=e(9447),f=e(72665),a=e(93062),u=e(19413),s=e(33108),l=e(61282),d=e(11735);let g=n=class{constructor(){this.id=n.AGENT_ID}get metadata(){return{systemPrompt:this.preferenceService.get(v.AINativeSettingSectionsId.SystemPrompt,"")}}set metadata(m){}async getRequestOptions(){const m=this.preferenceService.get(v.AINativeSettingSectionsId.LLMModelSelection),h=this.preferenceService.get(v.AINativeSettingSectionsId.ModelID);let b="",A="";m==="deepseek"?b=this.preferenceService.get(v.AINativeSettingSectionsId.DeepseekApiKey,""):m==="openai"?b=this.preferenceService.get(v.AINativeSettingSectionsId.OpenaiApiKey,""):m==="anthropic"?b=this.preferenceService.get(v.AINativeSettingSectionsId.AnthropicApiKey,""):(b=this.preferenceService.get(v.AINativeSettingSectionsId.OpenaiApiKey,""),A=this.preferenceService.get(v.AINativeSettingSectionsId.OpenaiBaseURL,""));const y=this.preferenceService.get(v.AINativeSettingSectionsId.MaxTokens),S=this.chatAgentService.getAgent(n.AGENT_ID),w=await this.mcpConfigService.getDisabledTools();return this.logger.log(`[ACP Chat] getRequestOptions: model=${m}, modelId=${h}, apiKey=${b?b.slice(0,8)+"***":"(empty)"}, baseURL=${A}, maxTokens=${y}`),{clientId:this.applicationService.clientId,model:m,modelId:h,apiKey:b,baseURL:A,maxTokens:y,system:S?.metadata.systemPrompt,disabledTools:w}}async invoke(m,h,b,A){var y,S,w,T;const I=new _.Deferred,{message:D,command:R}=m;this.logger.log(`[ACP Chat] invoke start \u2014 rawSessionId=${m.sessionId}, requestId=${m.requestId}, command=${R||"(empty)"}, messageChars=${D.length}, images=${(S=(y=m.images)===null||y===void 0?void 0:y.length)!==null&&S!==void 0?S:0}, historyMessages=${b.length}`);let M=D;if(R){const k=this.chatFeatureRegistry.getSlashCommandHandler(R);if(k&&k.providerPrompt){const N=this.monacoCommandRegistry.getActiveCodeEditor();M=await k.providerPrompt(D,N),this.logger.log(`[ACP Chat] invoke slash prompt resolved \u2014 requestId=${m.requestId}, command=${R}, promptChars=${M.length}`)}}if(R){const k=this.chatFeatureRegistry.getSlashCommandHandler(R);if(k?.invoke)return this.logger.log(`[ACP Chat] invoke custom slash handler \u2014 requestId=${m.requestId}, command=${R}, promptChars=${M.length}`),h({kind:"requestAccepted",sessionId:m.sessionId}),await k.invoke(M,h,A),I.resolve(),{}}let O=m.sessionId;O.startsWith("acp:")&&(O=O.substring(4));const x=b[b.length-1];this.logger.log(`[ACP Chat] invoke normalized \u2014 sessionId=${O}, requestId=${m.requestId}, promptChars=${M.length}, lastMessageRole=${(w=x?.role)!==null&&w!==void 0?w:"(empty)"}`);try{const k=m.sessionId.startsWith("acp:")?m.sessionId:`acp:${m.sessionId}`,N=(T=this.chatManagerService.getSession(k))===null||T===void 0?void 0:T.acpTarget,L=N&&this.configProvider.resolveConfigForTarget?await this.configProvider.resolveConfigForTarget(N):await this.configProvider.resolveConfig();this.logger.log(`[ACP Chat] invoke: sessionId=${O}, config=${JSON.stringify(L)}`);const B=this.preferenceService.get(v.AINativeSettingSectionsId.AcpDeliveryMode,"stream"),K={requestId:m.requestId,sessionId:O,history:[x],images:m.images,acpDeliveryMode:B,...await this.getRequestOptions(),agentSessionConfig:L};this.logger.log(`[ACP Chat] invoking aiBackService.requestStream: agentSessionConfig=${!!K.agentSessionConfig}, apiKey=${K.apiKey?K.apiKey.slice(0,8)+"***":"(empty)"}`);const W=await this.aiBackService.requestStream(M,K,A);this.logger.log(`[ACP Chat] requestStream opened \u2014 sessionId=${O}, requestId=${m.requestId}, historyMessages=${K.history.length}`),h({kind:"requestAccepted",sessionId:O});let U=0,G=!1;(0,a.listenReadable)(W,{onData:j=>{var Y;U+=1;const z=j.kind;j.kind==="threadStatus"?(this.logger.log(`[ACP Chat] stream data \u2014 sessionId=${O}, requestId=${m.requestId}, kind=threadStatus, status=${j.threadStatus}`),this.handleThreadStatusUpdate(j.threadStatus,j.sessionId),h({kind:"safeProgress",content:this.getThreadStatusSafeProgress(j.threadStatus)})):j.kind==="sessionState"?(this.logger.log(`[ACP Chat] stream data \u2014 sessionId=${O}, requestId=${m.requestId}, kind=sessionState, currentModeId=${(Y=j.currentModeId)!==null&&Y!==void 0?Y:"(empty)"}`),this.handleSessionStateUpdate(j,O)):((!G||z!=="content"&&z!=="markdownContent"&&z!=="reasoning")&&(this.logger.log(`[ACP Chat] stream data \u2014 sessionId=${O}, requestId=${m.requestId}, kind=${z}, count=${U}`),G=!0),h(j))},onEnd:()=>{this.logger.log(`[ACP Chat] stream end \u2014 sessionId=${O}, requestId=${m.requestId}, dataCount=${U}`),I.resolve()},onError:j=>{this.logger.error(`[ACP Chat] stream error \u2014 sessionId=${O}, requestId=${m.requestId}, error=${j.message}`),this.messageService.error(j.message),this.aiReporter.end(O+"_"+m.requestId,{message:j.message,success:!1,command:R}),I.reject(j)}}),await I.promise}catch(k){const N=k instanceof Error?k.message:String(k);return this.logger.error(`[ACP Chat] invoke error \u2014 sessionId=${O}, requestId=${m.requestId}, error=${N}`),this.messageService.error(N),{errorDetails:{message:N}}}return{}}handleThreadStatusUpdate(m,h){const b=h.startsWith("acp:")?h:`acp:${h}`,A=this.chatManagerService.getSession(b);A&&A.setThreadStatus(m)}getThreadStatusSafeProgress(m){switch(m){case"working":return(0,_.localize)("aiNative.chat.safeProgress.agentWorking");case"stopping":return(0,_.localize)("aiNative.chat.safeProgress.agentStopping");case"auth_required":return(0,_.localize)("aiNative.chat.safeProgress.authRequired");case"errored":return(0,_.localize)("aiNative.chat.safeProgress.errored");case"disconnected":return(0,_.localize)("aiNative.chat.safeProgress.disconnected");case"idle":case"awaiting_prompt":default:return""}}handleSessionStateUpdate(m,h){var b;const A=this.chatManagerService;(b=A.applySessionStateUpdate)===null||b===void 0||b.call(A,m.sessionId||h,{currentModeId:m.currentModeId,currentModelId:m.currentModelId,configOptions:m.configOptions,availableCommands:m.availableCommands,title:m.title,updatedAt:m.updatedAt})}async provideSlashCommands(){return this.chatFeatureRegistry.getAllSlashCommand().map(m=>({...m,name:m.name,description:m.description||""}))}async provideChatWelcomeMessage(){}};t.AcpChatAgent=g,g.AGENT_ID="Default_Chat_Agent",r.__decorate([(0,o.Autowired)(u.IChatAgentService),r.__metadata("design:type",Object)],g.prototype,"chatAgentService",void 0),r.__decorate([(0,o.Autowired)(_.AIBackSerivcePath),r.__metadata("design:type",Object)],g.prototype,"aiBackService",void 0),r.__decorate([(0,o.Autowired)(c.PreferenceService),r.__metadata("design:type",Object)],g.prototype,"preferenceService",void 0),r.__decorate([(0,o.Autowired)(_.IApplicationService),r.__metadata("design:type",Object)],g.prototype,"applicationService",void 0),r.__decorate([(0,o.Autowired)(p.MonacoCommandRegistry),r.__metadata("design:type",p.MonacoCommandRegistry)],g.prototype,"monacoCommandRegistry",void 0),r.__decorate([(0,o.Autowired)(_.ChatFeatureRegistryToken),r.__metadata("design:type",d.ChatFeatureRegistry)],g.prototype,"chatFeatureRegistry",void 0),r.__decorate([(0,o.Autowired)(_.IAIReporter),r.__metadata("design:type",Object)],g.prototype,"aiReporter",void 0),r.__decorate([(0,o.Autowired)(f.IMessageService),r.__metadata("design:type",Object)],g.prototype,"messageService",void 0),r.__decorate([(0,o.Autowired)(_.MCPConfigServiceToken),r.__metadata("design:type",s.MCPConfigService)],g.prototype,"mcpConfigService",void 0),r.__decorate([(0,o.Autowired)(_.IACPConfigProvider),r.__metadata("design:type",Object)],g.prototype,"configProvider",void 0),r.__decorate([(0,o.Autowired)(c.ILogger),r.__metadata("design:type",Object)],g.prototype,"logger",void 0),r.__decorate([(0,o.Autowired)(u.IChatManagerService),r.__metadata("design:type",l.ChatManagerService)],g.prototype,"chatManagerService",void 0),t.AcpChatAgent=g=n=r.__decorate([(0,o.Injectable)()],g)},44279:(P,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AI_CHAT_INPUT_TOGGLE_EXPANDED=void 0,t.AI_CHAT_INPUT_TOGGLE_EXPANDED={id:"ai.chat.input.toggleExpanded",label:"Toggle Chat Input Expansion"}},5811:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AcpQueuedTurnModule=void 0;const n=e(43718),r=e(4835);class o{constructor(_){this.port=_,this.processing="auto",this.entries=[],this.canFastTrack=!1,this.nextTurnId=1,this.sessionEpoch=0,this.intentVersion=0,this.pendingInitialStart=!1,this.hasPendingActivation=!1,this.operationTail=Promise.resolve(),this.onDidChangeEmitter=new n.Emitter,this.onDidChange=this.onDidChangeEmitter.event}get snapshot(){const _=this.getPhase();return{activeSessionId:this.activeSessionId,phase:_,entries:[...this.entries],editingTurnId:this.editingTurnId,pauseReason:this.pauseReason,pauseError:this.pauseError,canResume:_==="paused"&&this.entries.length>0,canFastTrack:this.canFastTrack&&_==="generating"&&this.entries.length>0&&this.entries[0].id!==this.editingTurnId,initialStartPending:this.pendingInitialStart}}activate(_){const v=this.hasPendingActivation?this.pendingActivationId:this.activeSessionId;if(_!==v){if(this.pendingInitialStart){this.pendingActivationId=_,this.hasPendingActivation=!0;return}this.applyActivation(_)}}deactivate(){this.sessionEpoch+=1,this.intentVersion+=1,this.activeSessionId=void 0,this.processing="auto",this.entries=[],this.editingTurnId=void 0,this.reservedTurn=void 0,this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.activeDelivery=void 0,this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.pendingInitialStart=!1,this.cancelledInitialStartTurnId=void 0,this.initialStartCancellation=void 0,this.hasPendingActivation=!1,this.pendingActivationId=void 0}submit(_,v="normal"){if(!(0,r.hasAcpChatSendPayload)(_))return Promise.resolve({accepted:!1,reason:"empty-content"});const p=this.sessionEpoch,f=this.activeSessionId,a=this.copyDraft(_);if(v==="immediate"){const u=this.createQueuedTurn(a);return this.entries.push(u),this.fireDidChange(),this.sendImmediately(u.id).then(s=>this.withQueuedDraftDisposition(u,s))}if(this.processing==="paused"&&this.activeDelivery){const u=this.createQueuedTurn(a);return this.entries.unshift(u),this.sendImmediately(u.id).then(s=>this.withQueuedDraftDisposition(u,s))}return this.serialize(async()=>{if(!this.isCapturedSessionActive(p,f))return{accepted:!1,reason:"stale-session"};if(this.processing==="paused"&&!this.activeDelivery){const s=this.createQueuedTurn(a);return this.withQueuedDraftDisposition(s,await this.startReservedTurn(s,!0))}if(this.entries.length>0||this.port.getStatus(this.activeSessionId)==="generating"||this.activeDelivery)return this.entries.push(this.createQueuedTurn(a)),this.canFastTrack=this.processing==="auto",this.processing!=="paused"&&(this.pauseReason=void 0,this.pauseError=void 0),this.fireDidChange(),{accepted:!0,outcome:"queued"};const u=this.createQueuedTurn(a);return this.withQueuedDraftDisposition(u,await this.startReservedTurn(u,!0))})}resume(){const _=this.intentVersion;return this.serialize(async()=>{if(this.processing!=="paused"||!this.activeDelivery&&this.entries.length===0)return{accepted:!1,reason:"turn-not-found"};if(_!==this.intentVersion)return{accepted:!1,reason:"turn-not-found"};if(this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.fireDidChange(),this.activeDelivery)return{accepted:!0,outcome:"resumed"};if(_!==this.intentVersion)return{accepted:!0,outcome:"resumed"};const v=await this.startNextQueuedTurnIfReady();return v.accepted?{accepted:!0,outcome:"resumed"}:v})}replaceFailedStartDraft(_){const v=this.entries[0];return this.processing!=="paused"||this.pauseReason!=="start-failed"||!v||!(0,r.hasAcpChatSendPayload)(_)?!1:(this.entries[0]={...this.copyDraft(_),id:v.id},this.fireDidChange(),!0)}stop(){const _=this.sessionEpoch,v=this.activeSessionId,p=++this.intentVersion;return this.processing="paused",this.pauseReason="manual-stop",this.pauseError=void 0,this.canFastTrack=!1,this.cancelledInitialStartTurnId=void 0,this.initialStartCancellation=void 0,this.fireDidChange(),this.serialize(async()=>{if(!this.isCapturedSessionActive(_,v))return{accepted:!1,reason:"stale-session"};const f=v??this.activeSessionId;try{await this.port.ensureCurrentCancelled(f)}catch{return this.isResolvedSessionActive(_,f)?(p===this.intentVersion&&(this.processing="paused",this.pauseReason="cancel-failed",this.pauseError=void 0,this.fireDidChange()),{accepted:!1,reason:"cancel-failed"}):{accepted:!1,reason:"stale-session"}}return this.isResolvedSessionActive(_,f)?(this.activeDelivery=void 0,p===this.intentVersion&&(this.processing="paused",this.pauseReason="manual-stop",this.pauseError=void 0,this.canFastTrack=!1),this.fireDidChange(),{accepted:!0,outcome:"stopped"}):{accepted:!1,reason:"stale-session"}})}cancelInitialStart(){if(!this.pendingInitialStart||!this.reservedTurn||!this.port.cancelPendingStart)return Promise.resolve({accepted:!1,reason:"turn-not-found"});if(this.initialStartCancellation)return this.initialStartCancellation;this.cancelledInitialStartTurnId=this.reservedTurn.id,this.fireDidChange();const _=this.port.cancelPendingStart(this.activeSessionId).then(()=>this.whenSettled()).then(()=>({accepted:!0,outcome:"stopped"})).catch(()=>(this.cancelledInitialStartTurnId=void 0,this.fireDidChange(),{accepted:!1,reason:"cancel-failed"})).finally(()=>{this.initialStartCancellation===_&&(this.initialStartCancellation=void 0)});return this.initialStartCancellation=_,_}sendImmediately(_){return this.sendImmediatelyInternal(_,!1)}sendImmediatelyInternal(_,v){const p=this.sessionEpoch,f=this.activeSessionId;if(this.editingTurnId===_&&!v)return Promise.resolve({accepted:!1,reason:"another-turn-is-editing"});if(this.processing==="absorbing-cancel"||this.immediateReservation)return Promise.resolve({accepted:!1,reason:"turn-not-found"});const a=this.entries.findIndex(({id:l})=>l===_);if(a===-1)return Promise.resolve({accepted:!1,reason:"turn-not-found"});const[u]=this.entries.splice(a,1),s=++this.intentVersion;return this.immediateReservation=u,this.immediateReservationIndex=a,this.processing="absorbing-cancel",this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.fireDidChange(),this.serialize(async()=>{const l=await this.cancelForImmediateAndStart(u,a,p,f,s);return l.accepted&&v&&this.editingTurnId===_&&(this.editingTurnId=void 0,this.fireDidChange()),l})}beginEdit(_){return this.entries.some(({id:v})=>v===_)?this.editingTurnId&&this.editingTurnId!==_?{accepted:!1,reason:"another-turn-is-editing"}:(this.editingTurnId=_,this.fireDidChange(),{accepted:!0,outcome:"updated"}):{accepted:!1,reason:"turn-not-found"}}commitEdit(_,v,p=!1){if(p){if(this.processing==="absorbing-cancel"||this.immediateReservation)return Promise.resolve({accepted:!1,reason:"turn-not-found"});if(!(0,r.hasAcpChatSendPayload)(v))return Promise.resolve({accepted:!1,reason:"empty-content"});const a=this.entries.findIndex(({id:u})=>u===_);return a===-1||this.editingTurnId!==_?Promise.resolve({accepted:!1,reason:"turn-not-found"}):(this.entries[a]={...this.copyDraft(v),id:_},this.fireDidChange(),this.sendImmediatelyInternal(_,!0))}const f=this.intentVersion;return this.serialize(async()=>{if(!(0,r.hasAcpChatSendPayload)(v))return{accepted:!1,reason:"empty-content"};const a=this.entries.findIndex(({id:u})=>u===_);return a===-1||this.editingTurnId!==_?{accepted:!1,reason:"turn-not-found"}:(this.entries[a]={...this.copyDraft(v),id:_},this.editingTurnId=void 0,f===this.intentVersion&&this.processing==="paused"&&(this.processing="auto",this.pauseReason=void 0),this.fireDidChange(),f===this.intentVersion&&await this.startNextQueuedTurnIfReady(),{accepted:!0,outcome:"updated"})})}cancelEdit(_){const v=this.intentVersion;return this.serialize(async()=>this.editingTurnId!==_||!this.entries.some(({id:p})=>p===_)?{accepted:!1,reason:"turn-not-found"}:(this.editingTurnId=void 0,v===this.intentVersion&&this.processing==="paused"&&(this.processing="auto",this.pauseReason=void 0),this.fireDidChange(),v===this.intentVersion&&await this.startNextQueuedTurnIfReady(),{accepted:!0,outcome:"updated"}))}remove(_){const v=this.intentVersion;return this.serialize(async()=>{const p=this.entries.findIndex(({id:f})=>f===_);return p===-1?{accepted:!1,reason:"turn-not-found"}:(this.entries.splice(p,1),this.editingTurnId===_&&(this.editingTurnId=void 0),v===this.intentVersion&&this.processing==="paused"&&(this.processing="auto",this.pauseReason=void 0),this.fireDidChange(),v===this.intentVersion&&await this.startNextQueuedTurnIfReady(),{accepted:!0,outcome:"removed"})})}takeBackLast(){const _=this.entries.pop();if(_)return this.editingTurnId===_.id&&(this.editingTurnId=void 0),this.canFastTrack=!1,this.fireDidChange(),_}fastTrack(){const _=this.entries[0];return!this.canFastTrack||!_||_.id===this.editingTurnId?Promise.resolve({accepted:!1,reason:"turn-not-found"}):(this.canFastTrack=!1,this.sendImmediately(_.id))}invalidateFastTrack(){this.canFastTrack&&(this.canFastTrack=!1,this.fireDidChange())}clear(){this.intentVersion+=1,this.entries=[],this.editingTurnId=void 0,this.reservedTurn=void 0,this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.fireDidChange()}serialize(_){const v=this.operationTail.then(_,_);return this.operationTail=v.then(()=>{},()=>{}),v}whenSettled(){return this.operationTail.then(()=>this.operationTail)}dispose(){this.onDidChangeEmitter.dispose()}applyActivation(_){this.sessionEpoch+=1,this.intentVersion+=1,this.activeSessionId=_,this.processing="auto",this.entries=[],this.editingTurnId=void 0,this.reservedTurn=void 0,this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.activeDelivery=void 0,this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.cancelledInitialStartTurnId=void 0,this.initialStartCancellation=void 0,this.hasPendingActivation=!1,this.pendingActivationId=void 0,this.fireDidChange()}async startReservedTurn(_,v){const p=this.sessionEpoch,f=this.activeSessionId,a=this.intentVersion,{id:u,...s}=_;this.reservedTurn=_,this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.canFastTrack=!1,this.pendingInitialStart=f===void 0,this.fireDidChange();let l;try{l=await this.port.start(f,s)}catch(g){const E=this.takePendingActivation();return this.pendingInitialStart=!1,this.cancelledInitialStartTurnId===_.id?(this.cancelledInitialStartTurnId=void 0,this.reservedTurn=void 0,this.processing="auto",this.pauseReason=void 0,this.pauseError=void 0,this.fireDidChange(),{accepted:!1,reason:"start-cancelled"}):p!==this.sessionEpoch?{accepted:!1,reason:"stale-session"}:E.pending?(this.applyActivation(E.sessionId),{accepted:!1,reason:"stale-session"}):(this.reservedTurn===_&&v&&this.entries.unshift(_),this.reservedTurn=void 0,a===this.intentVersion&&(this.processing="paused",this.pauseReason="start-failed",this.pauseError={name:g instanceof Error?g.name:void 0,message:g instanceof Error?g.message:String(g),limit:g&&typeof g=="object"&&typeof g.limit=="number"?g.limit:void 0}),this.fireDidChange(),{accepted:!1,reason:"start-failed"})}this.pendingInitialStart=!1;const d=this.takePendingActivation();if(this.watchOutcome(p,l),p!==this.sessionEpoch)return{accepted:!1,reason:"stale-session"};if(d.pending&&d.sessionId!==l.sessionId)return this.applyActivation(d.sessionId),{accepted:!1,reason:"stale-session"};if(f===void 0)this.activeSessionId=l.sessionId;else if(l.sessionId!==f)return this.reservedTurn=void 0,{accepted:!1,reason:"stale-session"};return this.reservedTurn=void 0,this.activeDelivery={epoch:p,id:l.id},a===this.intentVersion&&(this.processing="auto"),this.fireDidChange(),{accepted:!0,outcome:"started"}}async cancelForImmediateAndStart(_,v,p,f,a){if(!this.isCapturedSessionActive(p,f))return{accepted:!1,reason:"stale-session"};const u=f??this.activeSessionId;if(a!==this.intentVersion)return this.immediateReservation===_&&(this.entries.splice(Math.min(v,this.entries.length),0,_),this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.fireDidChange()),{accepted:!1,reason:"turn-not-found"};try{await this.port.ensureCurrentCancelled(u)}catch{return this.isResolvedSessionActive(p,u)?this.immediateReservation!==_?{accepted:!1,reason:"turn-not-found"}:(this.entries.unshift(_),this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.processing="paused",this.pauseReason="cancel-failed",this.fireDidChange(),{accepted:!1,reason:"cancel-failed"}):{accepted:!1,reason:"stale-session"}}return this.isResolvedSessionActive(p,u)?(this.activeDelivery=void 0,a!==this.intentVersion?(this.immediateReservation===_&&(this.entries.splice(Math.min(v,this.entries.length),0,_),this.immediateReservation=void 0,this.immediateReservationIndex=void 0),this.fireDidChange(),{accepted:!1,reason:"turn-not-found"}):this.immediateReservation!==_?(this.fireDidChange(),{accepted:!1,reason:"turn-not-found"}):(this.immediateReservation=void 0,this.immediateReservationIndex=void 0,this.processing="auto",this.pauseReason=void 0,this.startReservedTurn(_,!0))):{accepted:!1,reason:"stale-session"}}watchOutcome(_,v){v.outcome.then(p=>{this.serialize(()=>this.handleOutcome(_,v.id,p))},()=>{this.serialize(()=>this.handleOutcome(_,v.id,"agent-error"))})}async handleOutcome(_,v,p){var f,a;if(!(_!==this.sessionEpoch||((f=this.activeDelivery)===null||f===void 0?void 0:f.epoch)!==_||this.activeDelivery.id!==v)){if(this.activeDelivery=void 0,this.processing==="paused"){this.fireDidChange();return}if(p!=="completed"){this.processing="paused",this.pauseReason=p,this.canFastTrack=!1,this.fireDidChange();return}if(this.pauseReason=void 0,((a=this.entries[0])===null||a===void 0?void 0:a.id)===this.editingTurnId){this.fireDidChange();return}await this.startNextQueuedTurnIfReady()}}async startNextQueuedTurnIfReady(){var _;if(this.activeDelivery||this.reservedTurn||this.processing!=="auto"||((_=this.entries[0])===null||_===void 0?void 0:_.id)===this.editingTurnId)return{accepted:!0,outcome:"updated"};const v=this.entries.shift();return v?this.startReservedTurn(v,!0):(this.fireDidChange(),{accepted:!0,outcome:"updated"})}getPhase(){return this.processing==="absorbing-cancel"?"cancelling-for-immediate":this.processing==="paused"?"paused":this.activeDelivery||this.reservedTurn||this.port.getStatus(this.activeSessionId)==="generating"?"generating":"idle"}createQueuedTurn(_){return{...this.copyDraft(_),id:`queued-turn-${this.nextTurnId++}`}}copyDraft(_){return{..._,images:_.images?[..._.images]:void 0}}withQueuedDraftDisposition(_,v){return!v.accepted&&this.entries.some(({id:p})=>p===_.id)?{...v,draftDisposition:"queued"}:v}takePendingActivation(){const _=this.hasPendingActivation,v=this.pendingActivationId;return this.hasPendingActivation=!1,this.pendingActivationId=void 0,{pending:_,sessionId:v}}isCapturedSessionActive(_,v){return _===this.sessionEpoch&&(v===void 0||v===this.activeSessionId)}isResolvedSessionActive(_,v){return _===this.sessionEpoch&&v===this.activeSessionId}fireDidChange(){this.onDidChangeEmitter.fire(this.snapshot)}}t.AcpQueuedTurnModule=o},87540:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AI_CHAT_NEW_TASK=t.AI_CHAT_NEW_CHAT=void 0;const n=e(43718);t.AI_CHAT_NEW_CHAT={id:"ai.chat.newChat",label:(0,n.localize)("aiNative.command.newChat","AI Chat: New Chat")},t.AI_CHAT_NEW_TASK={id:"ai.chat.newTask",label:(0,n.localize)("aiNative.command.newTask","Agent: New Session")}},17354:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ACPSessionProvider=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(43718),_=e(72665),v=e(70392),p=e(90684),f=e(29993),a=e(28524),u=e(26093),s="Default_Chat_Agent",l=/^\s*<opensumi_mcp_usage_hint\b[^>]*>[\s\S]*?<\/opensumi_mcp_usage_hint>\s*/;function d(b){return b.replace(l,"")}function g(b){return/^(?:[A-Za-z]:[\\/]|[\\/])/.test(b)}function E(b){return!!b&&typeof b=="object"&&b.name===c.ACP_THREAD_POOL_SATURATED_ERROR_NAME}function m(b){var A;const y=typeof b.message=="string"?(A=b.message.match(/\bThread pool is full \((\d+)\)/))===null||A===void 0?void 0:A[1]:void 0,S=y?v.strings.format((0,c.localize)("aiNative.chat.acp.threadPoolSaturated.withLimit","ACP concurrent tasks have reached the configured limit of {0}. Switch to or stop an active task, then try again."),y):(0,c.localize)("aiNative.chat.acp.threadPoolSaturated","ACP concurrent tasks have reached the configured limit. Switch to or stop an active task, then try again."),w=new Error(S);return w.name=c.ACP_THREAD_POOL_SATURATED_ERROR_NAME,y&&(w.limit=Number(y)),w}let h=class{constructor(){this.id="ACPSessionProvider",this.loadedSessionMap=new Map,this.loadedSessionsResult=null,this.loadingSessionsPromise=null,this.didRetryEmptySessionsResult=!1,this.agentSessionCatalog=[],this.agentSessionTargets=new Map,this.agentSessionRefreshRequested=!1}canHandle(A){return A.startsWith("acp")}async createSession(A){var y;if(!(!((y=this.aiBackService)===null||y===void 0)&&y.createSession))throw new Error("aiBackService.createSession is not available");try{const S=A?.acpTarget&&this.configProvider.resolveConfigForTarget?await this.configProvider.resolveConfigForTarget(A.acpTarget):await this.configProvider.resolveConfig(),w=await(A?.operationId?this.aiBackService.createSession(S,A.operationId):this.aiBackService.createSession(S));if(!w?.sessionId)throw new Error("createSession did not return a valid sessionId");const T=`acp:${w.sessionId}`,I=Date.now(),D={sessionId:T,createdAt:I,modelId:w.currentModelId,agentModes:w.modes,currentModeId:w.currentModeId,agentModels:w.models,configOptions:w.configOptions,history:{additional:{},messages:[]},requests:[],title:"",extension:{availableCommands:w.availableCommands||[],acpTarget:{agentId:S.agentId,cwd:S.cwd}}};return this.loadedSessionMap.set(T,D),this.agentSessionTargets.set(T,{agentId:S.agentId,cwd:S.cwd}),D}catch(S){throw E(S)?m(S):S}}getAgentSessions(){return this.agentSessionCatalog.map(A=>({...A}))}refreshAgentSessions(){return this.agentSessionRefreshRequested=!0,this.agentSessionRefreshPromise||(this.agentSessionRefreshPromise=this.drainAgentSessionRefreshes().finally(()=>{this.agentSessionRefreshPromise=void 0})),this.agentSessionRefreshPromise}async drainAgentSessionRefreshes(){let A=[];do this.agentSessionRefreshRequested=!1,A=await this.doRefreshAgentSessions();while(this.agentSessionRefreshRequested);return A}async doRefreshAgentSessions(){var A;if(!(!((A=this.aiBackService)===null||A===void 0)&&A.listSessions)||!this.configProvider.resolveConfigForTarget)return this.agentSessionCatalog=[],this.agentSessionTargets.clear(),[];const y=(await this.agenticTaskRegistry.listProjects()).filter(O=>O.availability==="available"&&g(O.workspacePath)),S=new Set(y.map(O=>O.workspacePath)),w=Object.keys((0,a.getAvailableAgentConfigs)(this.preferenceService)),T=[],I=new Map;for(const O of w){const x=new Map;let k=!1;for(const[N,L]of y.entries())try{const B=await this.configProvider.resolveConfigForTarget({agentId:O,cwd:L.workspacePath}),K=await this.aiBackService.listSessions(B);for(const W of K?.sessions||[]){if(!W?.sessionId||!g(W.cwd)||!S.has(W.cwd))continue;const U=`acp:${W.sessionId}`,G={sessionId:U,agentSessionId:W.sessionId,agentId:O,cwd:W.cwd,title:W.title||void 0,updatedAt:W.updatedAt||void 0},j=x.get(U);(!j||this.toTimestamp(G.updatedAt)>=this.toTimestamp(j.updatedAt))&&x.set(U,G)}}catch(B){k=!0,this.logger.warn(`[ACP Chat][Session Catalog] list failed \u2014 agentId=${O}, projectOrdinal=${N}, errorType=${B instanceof Error?B.name:typeof B}`);break}if(!k)for(const N of x.values())T.push(N),I.set(N.sessionId,{agentId:N.agentId,cwd:N.cwd})}const D=new Map;for(const O of T){const x=D.get(O.agentSessionId)||new Set;x.add(O.agentId),D.set(O.agentSessionId,x)}const R=new Set(Array.from(D.entries()).filter(([,O])=>O.size>1).map(([O])=>O));if(R.size>0){const O=Math.max(...Array.from(R,x=>{var k;return((k=D.get(x))===null||k===void 0?void 0:k.size)||0}));this.logger.warn(`[ACP Chat][Session Catalog] excluded cross-Agent Session ID collisions \u2014 count=${R.size}, agentCount=${O}`)}const M=T.filter(O=>!R.has(O.agentSessionId));for(const O of R)I.delete(`acp:${O}`);return M.sort((O,x)=>this.toTimestamp(x.updatedAt)-this.toTimestamp(O.updatedAt)),this.agentSessionCatalog=M,this.agentSessionTargets=I,this.getAgentSessions()}toTimestamp(A){const y=A?Date.parse(A):0;return Number.isFinite(y)?y:0}async loadSessions(){if(Array.isArray(this.loadedSessionsResult))return this.loadedSessionsResult;if(this.loadingSessionsPromise)return this.loadingSessionsPromise;this.loadingSessionsPromise=this.doLoadSessions();try{return await this.loadingSessionsPromise}finally{this.loadingSessionsPromise=null}}async doLoadSessions(){var A,y;if(!(!((A=this.aiBackService)===null||A===void 0)&&A.listSessions))return this.loadedSessionsResult=[],this.loadedSessionsResult;try{const S=await this.configProvider.resolveConfig(),w=await this.aiBackService.listSessions(S);if(!(!((y=w?.sessions)===null||y===void 0)&&y.length))return this.didRetryEmptySessionsResult?(this.loadedSessionsResult=[],this.loadedSessionsResult):(this.didRetryEmptySessionsResult=!0,[]);const T=w.sessions.slice(0,20).reverse().map(I=>({...I,sessionId:`acp:${I.sessionId}`,history:{additional:{},messages:[]},requests:[],title:I.title}));return this.loadedSessionsResult=T,this.didRetryEmptySessionsResult=!1,this.loadedSessionsResult}catch(S){return this.messageService.error(S.message),[]}}async loadSession(A){var y,S;if(!A||!(!((y=this.aiBackService)===null||y===void 0)&&y.loadAgentSession))return;const w=A.startsWith("acp:")?A.slice(4):A;try{const T=await this.resolveSessionConfig(A),I=await this.aiBackService.loadAgentSession(T,w);if(!I)return;console.log("[ACP Chat][session/load] Agent history updates:",I.historyUpdates||[]);const D=this.convertAgentSessionToModel(A,I),R=this.agentSessionTargets.get(A);return R&&(D.extension={...D.extension,availableCommands:((S=D.extension)===null||S===void 0?void 0:S.availableCommands)||[],acpTarget:{...R},metadataOnly:!1}),this.loadedSessionMap.set(A,D),D}catch(T){throw T}}async attachSession(A){var y;if(!A||!(!((y=this.aiBackService)===null||y===void 0)&&y.attachSession))return;const S=A.startsWith("acp:")?A.slice(4):A;return this.aiBackService.attachSession(S)}async cancelSession(A){var y;if(!A||!(!((y=this.aiBackService)===null||y===void 0)&&y.cancelSession))return;const S=A.startsWith("acp:")?A.slice(4):A;await this.aiBackService.cancelSession(S)}async disposeSession(A,y=!1){var S;if(!A||!(!((S=this.aiBackService)===null||S===void 0)&&S.disposeSession))return;const w=A.startsWith("acp:")?A.slice(4):A;y?await this.aiBackService.disposeSession(w,!0):await this.aiBackService.disposeSession(w)}restoreSessionSnapshot(A,y){if(y.historyUpdates.length!==0)return this.convertAgentSessionToModel(A,{sessionId:y.sessionId,modes:y.modes,currentModeId:y.currentModeId,models:y.models,currentModelId:y.currentModelId,configOptions:y.configOptions,availableCommands:y.availableCommands,threadStatus:y.threadStatus,historyUpdates:y.historyUpdates,messages:[]})}async resolveSessionConfig(A){const y=this.agentSessionTargets.get(A);return y&&this.configProvider.resolveConfigForTarget?this.configProvider.resolveConfigForTarget(y):this.configProvider.resolveConfig()}convertAgentSessionToModel(A,y){var S;const w=y.historyUpdates;if(w?.length)return this.convertHistoryUpdatesToModel(A,{...y,historyUpdates:w});const I=y.messages.filter(R=>!(R.content.includes("<command-name>")||R.content.includes("<local-command-stdout>"))).map(R=>R.role==="user"?{...R,content:d(R.content)}:R).filter(R=>R.role!=="user"||!!R.content).map((R,M)=>({id:`${A}-msg-${M}`,role:R.role==="user"?1:2,content:R.content,order:M,timestamp:R.timestamp}));return{sessionId:A,createdAt:(S=I[0])===null||S===void 0?void 0:S.timestamp,modelId:y.currentModelId,agentModes:y.modes,currentModeId:y.currentModeId,agentModels:y.models,configOptions:y.configOptions,extension:y.availableCommands?{availableCommands:y.availableCommands}:void 0,history:{additional:{},messages:I},requests:[]}}convertHistoryUpdatesToModel(A,y){var S,w,T,I,D,R;const M=[];let O;const x=()=>(O||(O={userContent:"",assistantContent:"",responseParts:[],toolCalls:new Map}),O),k=()=>{O&&(O.userContent=d(O.userContent),(O.userContent||O.responseParts.length>0)&&M.push(O)),O=void 0},N=(W,U)=>{const G=W.responseParts[W.responseParts.length-1];G?.kind==="markdownContent"?W.responseParts[W.responseParts.length-1]={kind:"markdownContent",content:new p.MarkdownString(G.content.value+U,G.content)}:W.responseParts.push({kind:"markdownContent",content:new p.MarkdownString(U)}),W.assistantContent+=U},L=(W,U)=>{const G=W.responseParts[W.responseParts.length-1];G?.kind==="reasoning"?G.content+=U:W.responseParts.push({kind:"reasoning",content:U.replace(/^<think>/,"")})};for(const W of y.historyUpdates){const U=W.update;if(U)switch(U.sessionUpdate){case"user_message_chunk":{const G=((S=U.content)===null||S===void 0?void 0:S.type)==="text"?U.content.text:"";if(!G)break;const j=typeof U.messageId=="string"?U.messageId:void 0,Y=O?.userMessageId&&j&&O.userMessageId!==j;O&&(O.assistantContent||O.responseParts.length>0||Y)&&k();const z=x();z.userMessageId=z.userMessageId||j,z.userContent+=G;break}case"agent_message_chunk":{const G=((w=U.content)===null||w===void 0?void 0:w.type)==="text"?U.content.text:"";if(G){const j=typeof U.messageId=="string"?U.messageId:void 0;O?.assistantMessageId&&j&&O.assistantMessageId!==j&&k();const Y=x();Y.assistantMessageId=Y.assistantMessageId||j,N(Y,G)}break}case"agent_thought_chunk":{const G=((T=U.content)===null||T===void 0?void 0:T.type)==="text"?U.content.text:"";G&&L(x(),G);break}case"tool_call":{const G=x(),j={id:U.toolCallId||"",type:"function",function:{name:U.title||U.toolCallId||"",arguments:JSON.stringify((I=U.rawInput)!==null&&I!==void 0?I:{})},state:"streaming-start"};G.toolCalls.set(j.id,j),G.responseParts.push({kind:"toolCall",content:j});break}case"tool_call_update":{const j=x().toolCalls.get(U.toolCallId);if(!j)break;if(U.rawInput!==void 0&&(j.function.arguments=JSON.stringify(U.rawInput)),U.status==="in_progress"){j.state="streaming";break}if(U.status!=="completed"&&U.status!=="failed")break;if(U.rawOutput!==void 0)j.result=typeof U.rawOutput=="string"?U.rawOutput:JSON.stringify(U.rawOutput),j.state="result";else if(Array.isArray(U.content)){const Y=U.content.find(z=>z?.type==="diff");Y?.path&&(j.result=`Modified ${Y.path}`,j.state="result")}else U.status==="failed"?(j.result="Tool failed",j.state="result"):j.state="complete";break}case"plan":{const G=(R=(D=U.plan)===null||D===void 0?void 0:D.entries)!==null&&R!==void 0?R:U.entries;Array.isArray(G)&&G.length>0&&N(x(),`${G.map(j=>j.completed||j.status==="completed"?`- [x] ${j.content}`:`- [ ] ${j.content}`).join(`
39438
39438
  `)}
39439
39439
 
39440
- `);break}default:break}}O();const N=[],L=[];return D.forEach((B,K)=>{const W=`${h}-restored-relation-${K}`,U=`${h}-restored-request-${K}`;N.push({id:`${h}-restored-user-${K}`,role:1,content:B.userContent,order:N.length,relationId:W,agentId:s,agentCommand:"",images:[]}),N.push({id:`${h}-restored-assistant-${K}`,role:2,content:B.assistantContent,order:N.length,relationId:W,requestId:U,agentId:s,agentCommand:"",images:[]}),L.push({requestId:U,message:{prompt:B.userContent,agentId:s,command:"",images:[]},response:{isComplete:K<D.length-1||!(0,u.isAcpResponsePending)(b.threadStatus),isCanceled:!1,responseText:B.assistantContent,responseContents:B.responseParts,responseParts:B.responseParts,errorDetails:void 0,followups:void 0}})}),{sessionId:h,createdAt:void 0,modelId:b.currentModelId,agentModes:b.modes,currentModeId:b.currentModeId,agentModels:b.models,configOptions:b.configOptions,extension:b.availableCommands?{availableCommands:b.availableCommands}:void 0,history:{additional:{},messages:N},requests:L}}async saveSessions(h){}};t.ACPSessionProvider=E,n.__decorate([(0,r.Autowired)(c.AIBackSerivcePath),n.__metadata("design:type",Object)],E.prototype,"aiBackService",void 0),n.__decorate([(0,r.Autowired)(c.IACPConfigProvider),n.__metadata("design:type",Object)],E.prototype,"configProvider",void 0),n.__decorate([(0,r.Autowired)(_.IMessageService),n.__metadata("design:type",Object)],E.prototype,"messageService",void 0),n.__decorate([(0,r.Autowired)(o.PreferenceService),n.__metadata("design:type",Object)],E.prototype,"preferenceService",void 0),n.__decorate([(0,r.Autowired)(o.ILogger),n.__metadata("design:type",Object)],E.prototype,"logger",void 0),n.__decorate([(0,r.Autowired)(f.AgenticTaskRegistryService),n.__metadata("design:type",f.AgenticTaskRegistryService)],E.prototype,"agenticTaskRegistry",void 0),t.ACPSessionProvider=E=n.__decorate([(0,c.Domain)(u.SessionProviderDomain),(0,r.Injectable)()],E)},84244:(P,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgenticConversationViewModelCache=void 0,t.createAgenticConversationViewModel=r,t.updateAgenticConversationViewModel=c,t.isAgenticConversationViewModelCurrent=_;const e=5,n=5e3;function r(p,f){return c(p,f)}function o(p,f){return JSON.stringify(p)===JSON.stringify(f)}function c(p,f,a){if(a?.sessionId===p&&_(a,f))return a;const u=a?.sessionId===p?new Map(a.messages.map(s=>[s.id,s])):new Map;return{sessionId:p,messages:f.map(s=>{const l=u.get(s.id);return l&&o(l,s)?l:JSON.parse(JSON.stringify(s))})}}function _(p,f){return p.messages.length!==f.length?!1:p.messages.every((a,u)=>o(a,f[u]))}class v{constructor(f={}){var a,u;this.entries=new Map,this.protectedSessionIds=new Set,this.messageCount=0,this.maxConversations=(a=f.maxConversations)!==null&&a!==void 0?a:e,this.maxMessages=(u=f.maxMessages)!==null&&u!==void 0?u:n}has(f){return this.entries.has(f)}get(f){const a=this.entries.get(f);if(a)return this.entries.delete(f),this.entries.set(f,a),a}set(f){const a=this.entries.get(f.sessionId);return a&&(this.entries.delete(f.sessionId),this.messageCount-=a.messages.length),this.entries.set(f.sessionId,f),this.messageCount+=f.messages.length,this.evict(f.sessionId),this.entries.has(f.sessionId)}delete(f){const a=this.entries.get(f);return a?(this.entries.delete(f),this.messageCount-=a.messages.length,!0):!1}protect(f){this.protectedSessionIds=new Set(f),this.evict()}evict(f){for(;this.entries.size>this.maxConversations||this.messageCount>this.maxMessages;){const u=Array.from(this.entries.keys()).find(s=>!this.protectedSessionIds.has(s));if(!u){f&&this.entries.has(f)&&this.delete(f);return}this.delete(u)}}}t.AgenticConversationViewModelCache=v},96366:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApplyService=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(92323),_=e(57517),v=e(20868),p=e(79865),f=e(19413),a=e(73974),u=e(51081);function s(d){return d.title.toLowerCase().includes("all")}let l=class extends a.BaseApplyService{async postApplyHandler(g){const E=g.getModel();if(!E)return Promise.resolve();const m=p.languageFeaturesService.codeActionProvider.ordered(E);if(!m)return Promise.resolve();const[h]=m,b=E.getFullModelRange(),A={trigger:v.CodeActionTriggerType.Auto},y=new o.CancellationTokenSource,S=await h.provideCodeActions(E,b,A,y.token),w=S?.actions.filter(s)||[];if(w.length===0)return Promise.resolve();await Promise.allSettled(w.map(async T=>{if(T.command)try{await this.commandService.executeCommand(T.command.id,...T.command.arguments||[])}catch{}}))}async doApply(g){const E=new o.URI(o.path.join(this.appConfig.workspaceDir,g.relativePath)),h=(await this.modelService.createModelReference(E)).instance.getMonacoModel().getValue();return{stream:await this.aiBackService.requestStream(`Merge all changes from the <update> snippet into the <code> below.
39440
+ `);break}default:break}}k();const B=[],K=[];return M.forEach((W,U)=>{const G=W.assistantMessageId||W.userMessageId||String(U),j=`${A}-restored-relation-${G}`,Y=`${A}-restored-request-${G}`;W.userContent&&B.push({id:`${A}-restored-user-${W.userMessageId||U}`,role:1,content:W.userContent,order:B.length,relationId:j,agentId:s,agentCommand:"",images:[]}),B.push({id:`${A}-restored-assistant-${W.assistantMessageId||U}`,role:2,content:W.assistantContent,order:B.length,relationId:j,requestId:Y,agentId:s,agentCommand:"",images:[]}),K.push({requestId:Y,message:{prompt:W.userContent,agentId:s,command:"",images:[]},response:{isComplete:U<M.length-1||!(0,u.isAcpResponsePending)(y.threadStatus),isCanceled:!1,responseText:W.assistantContent,responseContents:W.responseParts,responseParts:W.responseParts,errorDetails:void 0,followups:void 0}})}),{sessionId:A,createdAt:void 0,modelId:y.currentModelId,agentModes:y.modes,currentModeId:y.currentModeId,agentModels:y.models,configOptions:y.configOptions,extension:y.availableCommands?{availableCommands:y.availableCommands}:void 0,history:{additional:{},messages:B},requests:K}}async saveSessions(A){}};t.ACPSessionProvider=h,n.__decorate([(0,r.Autowired)(c.AIBackSerivcePath),n.__metadata("design:type",Object)],h.prototype,"aiBackService",void 0),n.__decorate([(0,r.Autowired)(c.IACPConfigProvider),n.__metadata("design:type",Object)],h.prototype,"configProvider",void 0),n.__decorate([(0,r.Autowired)(_.IMessageService),n.__metadata("design:type",Object)],h.prototype,"messageService",void 0),n.__decorate([(0,r.Autowired)(o.PreferenceService),n.__metadata("design:type",Object)],h.prototype,"preferenceService",void 0),n.__decorate([(0,r.Autowired)(o.ILogger),n.__metadata("design:type",Object)],h.prototype,"logger",void 0),n.__decorate([(0,r.Autowired)(f.AgenticTaskRegistryService),n.__metadata("design:type",f.AgenticTaskRegistryService)],h.prototype,"agenticTaskRegistry",void 0),t.ACPSessionProvider=h=n.__decorate([(0,c.Domain)(u.SessionProviderDomain),(0,r.Injectable)()],h)},84244:(P,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AgenticConversationViewModelCache=void 0,t.createAgenticConversationViewModel=r,t.updateAgenticConversationViewModel=c,t.isAgenticConversationViewModelCurrent=_;const e=5,n=5e3;function r(p,f){return c(p,f)}function o(p,f){return JSON.stringify(p)===JSON.stringify(f)}function c(p,f,a){if(a?.sessionId===p&&_(a,f))return a;const u=a?.sessionId===p?new Map(a.messages.map(s=>[s.id,s])):new Map;return{sessionId:p,messages:f.map(s=>{const l=u.get(s.id);return l&&o(l,s)?l:JSON.parse(JSON.stringify(s))})}}function _(p,f){return p.messages.length!==f.length?!1:p.messages.every((a,u)=>o(a,f[u]))}class v{constructor(f={}){var a,u;this.entries=new Map,this.protectedSessionIds=new Set,this.messageCount=0,this.maxConversations=(a=f.maxConversations)!==null&&a!==void 0?a:e,this.maxMessages=(u=f.maxMessages)!==null&&u!==void 0?u:n}has(f){return this.entries.has(f)}get(f){const a=this.entries.get(f);if(a)return this.entries.delete(f),this.entries.set(f,a),a}set(f){const a=this.entries.get(f.sessionId);return a&&(this.entries.delete(f.sessionId),this.messageCount-=a.messages.length),this.entries.set(f.sessionId,f),this.messageCount+=f.messages.length,this.evict(f.sessionId),this.entries.has(f.sessionId)}delete(f){const a=this.entries.get(f);return a?(this.entries.delete(f),this.messageCount-=a.messages.length,!0):!1}protect(f){this.protectedSessionIds=new Set(f),this.evict()}evict(f){for(;this.entries.size>this.maxConversations||this.messageCount>this.maxMessages;){const u=Array.from(this.entries.keys()).find(s=>!this.protectedSessionIds.has(s));if(!u){f&&this.entries.has(f)&&this.delete(f);return}this.delete(u)}}}t.AgenticConversationViewModelCache=v},96366:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ApplyService=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(92323),_=e(57517),v=e(20868),p=e(79865),f=e(19413),a=e(73974),u=e(51081);function s(d){return d.title.toLowerCase().includes("all")}let l=class extends a.BaseApplyService{async postApplyHandler(g){const E=g.getModel();if(!E)return Promise.resolve();const m=p.languageFeaturesService.codeActionProvider.ordered(E);if(!m)return Promise.resolve();const[h]=m,b=E.getFullModelRange(),A={trigger:v.CodeActionTriggerType.Auto},y=new o.CancellationTokenSource,S=await h.provideCodeActions(E,b,A,y.token),w=S?.actions.filter(s)||[];if(w.length===0)return Promise.resolve();await Promise.allSettled(w.map(async T=>{if(T.command)try{await this.commandService.executeCommand(T.command.id,...T.command.arguments||[])}catch{}}))}async doApply(g){const E=new o.URI(o.path.join(this.appConfig.workspaceDir,g.relativePath)),h=(await this.modelService.createModelReference(E)).instance.getMonacoModel().getValue();return{stream:await this.aiBackService.requestStream(`Merge all changes from the <update> snippet into the <code> below.
39441
39441
  - Preserve the code's structure, order, comments, and indentation exactly.
39442
39442
  - Output only the updated code, enclosed within <updated-code> and </updated-code> tags.
39443
39443
  - Do not include any additional text, explanations, placeholders, ellipses, or code fences.
@@ -39449,7 +39449,7 @@ Digest source: ${N.digestSource}`}async function x(N,L){let B=N.getSessions(),K=
39449
39449
  User's intention: ${g.instructions}
39450
39450
  `:""}
39451
39451
  Provide the complete updated code.
39452
- `,{...await this.chatProxyService.getRequestOptions(),trimTexts:["<updated-code>","</updated-code>"],system:"You are a coding assistant that helps merge code updates, ensuring every modification is fully integrated."})}}};t.ApplyService=l,n.__decorate([(0,r.Autowired)(c.CommandService),n.__metadata("design:type",Object)],l.prototype,"commandService",void 0),n.__decorate([(0,r.Autowired)(_.IEditorDocumentModelService),n.__metadata("design:type",Object)],l.prototype,"modelService",void 0),n.__decorate([(0,r.Autowired)(o.AIBackSerivcePath),n.__metadata("design:type",Object)],l.prototype,"aiBackService",void 0),n.__decorate([(0,r.Autowired)(f.ChatProxyServiceToken),n.__metadata("design:type",u.ChatProxyService)],l.prototype,"chatProxyService",void 0),t.ApplyService=l=n.__decorate([(0,r.Injectable)()],l)},74055:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatAgentService=void 0;const n=e(85608),r=n.__importDefault(e(66652)),o=e(76003),c=e(43718),_=e(46044),v=e(73307),p=e(29770);let f=class extends c.Disposable{constructor(){super(),this.agents=new Map,this.initialUserMessageMap=new Map,this.shouldUpdateContext=!1,this._onDidChangeAgents=new c.Emitter,this.onDidChangeAgents=this._onDidChangeAgents.event,this._onDidSendMessage=new c.Emitter,this.onDidSendMessage=this._onDidSendMessage.event,this.addDispose(this._onDidChangeAgents),this.addDispose(this.llmContextService.onDidContextFilesChangeEvent(u=>{u.version!==this.contextVersion&&(this.contextVersion=u.version,this.shouldUpdateContext=!0)}))}registerAgent(u){if(this.agents.has(u.id))throw new Error(`Already registered an agent with id ${u.id}`);return this.agents.set(u.id,{agent:u,commands:[]}),this._onDidChangeAgents.fire(),(0,c.toDisposable)(()=>{this.agents.delete(u.id)&&this._onDidChangeAgents.fire()})}async updateAgent(u,s){const l=this.agents.get(u);if(!l)throw new Error(`No agent with id ${u} registered`);l.agent.metadata={...l.agent.metadata,...s},l.commands=await l.agent.provideSlashCommands(c.CancellationToken.None),s.isDefault&&(this.defaultAgentId=u);const d=await l.agent.provideChatWelcomeMessage(c.CancellationToken.None);if(d){const{content:g,sampleQuestions:E}=d;this.chatFeatureRegistry.registerWelcome(g,E)}this._onDidChangeAgents.fire()}getAgents(){return Array.from(this.agents.values(),u=>u.agent)}hasAgent(u){return this.agents.has(u)}getDefaultAgentId(){return this.defaultAgentId}getAgent(u){const s=this.agents.get(u);return s?.agent}async invokeAgent(u,s,l,d,g){const E=Date.now();this.logger.log(`[ChatAgentService] invokeAgent start \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, messageChars=${s.message.length}, historyMessages=${d.length}, regenerate=${!!s.regenerate}`);const m=this.agents.get(u);if(!m)throw this.logger.error(`[ChatAgentService] invokeAgent missing agent \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, registeredAgents=${Array.from(this.agents.keys()).join(",")||"(empty)"}`),new Error(`No agent with id ${u},this.agents ${this.agents}`);if(this.initialUserMessageMap.has(s.sessionId))this.shouldUpdateContext||s.regenerate||d.length===0?(this.logger.log(`[ChatAgentService] invokeAgent context enhance refresh \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, shouldUpdateContext=${this.shouldUpdateContext}, regenerate=${!!s.regenerate}, historyMessages=${d.length}`),s.message=await this.provideContextMessage(s.message,s.sessionId),this.shouldUpdateContext=!1):this.logger.log(`[ChatAgentService] invokeAgent context enhance skipped \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}`);else{this.logger.log(`[ChatAgentService] invokeAgent context enhance initial \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}`),this.initialUserMessageMap.set(s.sessionId,s.message);const b=s.message;s.message=await this.provideContextMessage(b,s.sessionId)}this.logger.log(`[ChatAgentService] invokeAgent calling agent \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, enhancedMessageChars=${s.message.length}`);const h=await m.agent.invoke(s,l,d,g);return this.logger.log(`[ChatAgentService] invokeAgent done \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, elapsedMs=${Date.now()-E}`),h}async provideContextMessage(u,s){const l=Date.now();this.logger.log(`[ChatAgentService] provideContextMessage serialize start \u2014 sessionId=${s}, messageChars=${u.length}`);const d=await this.llmContextService.serialize();this.logger.log(`[ChatAgentService] provideContextMessage serialize done \u2014 sessionId=${s}, elapsedMs=${Date.now()-l}, contextChars=${JSON.stringify(d).length}`);const g=await this.promptProvider.provideContextPrompt(d,u);return this.logger.log(`[ChatAgentService] provideContextMessage prompt done \u2014 sessionId=${s}, elapsedMs=${Date.now()-l}, fullMessageChars=${g.length}`),this.aiReporter.send({msgType:c.AIServiceType.Chat,actionType:c.ActionTypeEnum.ContextEnhance,actionSource:c.ActionSourceEnum.Chat,sessionId:s,message:g}),this.logger.log(`[ChatAgentService] provideContextMessage reporter sent \u2014 sessionId=${s}, elapsedMs=${Date.now()-l}`),g}populateChatInput(u,s){this.aiChatService.sendMessage({...s,agentId:u,immediate:!1})}getCommands(){return(0,r.default)(Array.from(this.agents.values(),({agent:u,commands:s})=>s.map(l=>({...l,agentId:u.id}))))}async getFollowups(u,s,l){const d=this.agents.get(u);if(!d)throw new Error(`No agent with id ${u}`);return d.agent.provideFollowups?d.agent.provideFollowups(s,l):[]}async getSampleQuestions(u,s){const l=this.agents.get(u);if(!l)throw new Error(`No agent with id ${u}`);return l.agent.provideSampleQuestions?l.agent.provideSampleQuestions(s):[]}async getAllSampleQuestions(){const u=await Promise.all(Array.from(this.agents.values()).map(async({agent:s})=>{try{return await this.getSampleQuestions(s.id,c.CancellationToken.None)}catch(l){return this.logger.error(l),[]}}));return(0,r.default)(u)}sendMessage(u){this._onDidSendMessage.fire(u)}parseMessage(u,s){var l;const d={agentId:"",command:"",message:u};let g=s;const E=this.getAgents(),m=new RegExp(`^@(${E.map(b=>b.id).join("|")})(?:\\s+|$)`,"i"),h=d.message.match(m);if(h){const b=E.find(A=>A.id.toLowerCase()===h[1].toLowerCase());if(!b)return d;g=b.id,d.agentId=g,d.message=d.message.replace(h[0],"")}if(g){const b=(l=this.agents.get(g))===null||l===void 0?void 0:l.commands;if(b?.length){const A=new RegExp(`^/\\s?(${b.map(S=>S.name).join("|")})(?:\\s+|$)`,"i"),y=d.message.match(A);if(y){const S=b.find(w=>w.name.toLowerCase()===y[1].toLowerCase());if(!S)return d;d.command=S.name,d.message=d.message.replace(y[0],"")}}}return d}};t.ChatAgentService=f,n.__decorate([(0,o.Autowired)(c.ILogger),n.__metadata("design:type",Object)],f.prototype,"logger",void 0),n.__decorate([(0,o.Autowired)(c.IAIReporter),n.__metadata("design:type",Object)],f.prototype,"aiReporter",void 0),n.__decorate([(0,o.Autowired)(_.LLMContextServiceToken),n.__metadata("design:type",Object)],f.prototype,"llmContextService",void 0),n.__decorate([(0,o.Autowired)(v.ChatAgentPromptProvider),n.__metadata("design:type",Object)],f.prototype,"promptProvider",void 0),n.__decorate([(0,o.Autowired)(c.ChatServiceToken),n.__metadata("design:type",p.ChatService)],f.prototype,"aiChatService",void 0),n.__decorate([(0,o.Autowired)(c.ChatFeatureRegistryToken),n.__metadata("design:type",Object)],f.prototype,"chatFeatureRegistry",void 0),t.ChatAgentService=f=n.__decorate([(0,o.Injectable)(),n.__metadata("design:paramtypes",[])],f)},84543:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatAgentViewService=void 0;const n=e(85608),r=e(76003),o=e(43718),c=e(19413),_=e(51081);let v=class{constructor(){this.componentsMap=new Map,this.componentsDeferredMap=new Map}registerChatComponent(f){return this.componentsMap.set(f.id,f),this.componentsDeferredMap.has(f.id)&&(this.componentsDeferredMap.get(f.id).resolve(f),this.componentsDeferredMap.delete(f.id)),{dispose:()=>{this.componentsMap.get(f.id)===f&&(this.componentsMap.delete(f.id),this.componentsDeferredMap.delete(f.id))}}}getChatComponent(f){return this.componentsMap.has(f)?this.componentsMap.get(f):(this.componentsDeferredMap.has(f)||this.componentsDeferredMap.set(f,new o.Deferred),null)}getChatComponentDeferred(f){return this.componentsDeferredMap.get(f)||null}getRenderAgents(){return this.chatAgentService.getAgents().filter(f=>f.id!==_.ChatProxyService.AGENT_ID)}};t.ChatAgentViewService=v,n.__decorate([(0,r.Autowired)(c.IChatAgentService),n.__metadata("design:type",Object)],v.prototype,"chatAgentService",void 0),t.ChatAgentViewService=v=n.__decorate([(0,r.Injectable)()],v)},98987:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatEditSchemeDocumentProvider=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(54414),_=e(96689),v=e(73974);let p=class{constructor(){this._onDidChangeContent=new o.Emitter,this.onDidChangeContent=this._onDidChangeContent.event}handlesScheme(a){return a===v.BaseApplyService.CHAT_EDITING_SOURCE_RESOLVER_SCHEME}async provideEditorDocumentModelContent(a,u){const{id:s,side:l}=a.getParsedQuery(),d=this.baseApplyService.getSessionCodeBlocks(),g=d?.find(m=>m.toolCallId===s);return(l==="left"?g?.originalCode:g?.updatedCode)||""}isReadonly(a){return!0}onDidDisposeModel(){}};t.ChatEditSchemeDocumentProvider=p,n.__decorate([(0,r.Autowired)(_.IEditorDocumentModelService),n.__metadata("design:type",Object)],p.prototype,"editorDocumentModelService",void 0),n.__decorate([(0,r.Autowired)(c.WorkbenchEditorService),n.__metadata("design:type",c.WorkbenchEditorService)],p.prototype,"workbenchEditorService",void 0),n.__decorate([(0,r.Autowired)(o.AppConfig),n.__metadata("design:type",Object)],p.prototype,"appConfig",void 0),n.__decorate([(0,r.Autowired)(o.IApplicationService),n.__metadata("design:type",Object)],p.prototype,"applicationService",void 0),n.__decorate([(0,r.Autowired)(v.BaseApplyService),n.__metadata("design:type",v.BaseApplyService)],p.prototype,"baseApplyService",void 0),n.__decorate([(0,r.Autowired)(o.PreferenceService),n.__metadata("design:type",Object)],p.prototype,"preferenceService",void 0),t.ChatEditSchemeDocumentProvider=p=n.__decorate([(0,r.Injectable)()],p)},75641:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatInputFooterRegistry=t.FooterButtonPosition=t.ChatInputFooterRegistryToken=void 0;const n=e(85608),r=e(76003),o=e(43718);Object.defineProperty(t,"ChatInputFooterRegistryToken",{enumerable:!0,get:function(){return o.ChatInputFooterRegistryToken}}),Object.defineProperty(t,"FooterButtonPosition",{enumerable:!0,get:function(){return o.FooterButtonPosition}});let c=class extends o.Disposable{constructor(){super(...arguments),this.contributions=[],this.onDidChangeEmitter=new o.Emitter,this.onDidChange=this.onDidChangeEmitter.event}registerFooterItem(v,p){var f,a;const u=this.contributions.findIndex(d=>d.id===v);u!==-1&&this.contributions.splice(u,1);const s={id:v,...p,order:(f=p.order)!==null&&f!==void 0?f:100,position:(a=p.position)!==null&&a!==void 0?a:o.FooterButtonPosition.LEFT};this.contributions.push(s),this.contributions.sort((d,g)=>{var E,m;return((E=d.order)!==null&&E!==void 0?E:0)-((m=g.order)!==null&&m!==void 0?m:0)});const l=o.Disposable.create(()=>{const d=this.contributions.indexOf(s);d!==-1&&(this.contributions.splice(d,1),this.onDidChangeEmitter.fire())});return this.addDispose(l),this.onDidChangeEmitter.fire(),l}getItems(){return this.contributions.filter(v=>!v.visible||v.visible())}};t.ChatInputFooterRegistry=c,t.ChatInputFooterRegistry=c=n.__decorate([(0,r.Injectable)()],c)},36940:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AcpChatManagerService=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(43718),_=e(98864),v=e(90336),p=e(44260),f=e(61282),a=e(42033),u=e(26093),s=e(79329),l=20,d=100,g="New Session",E="acpSessionDisplayTitleOverrides",m=["OpenSumi exposes IDE capabilities","The user's OS version","The rules section has","For requests to create an OpenSumi IDE"];let h=class extends f.ChatManagerService{constructor(){super(),this.mainProvider=null,this.localFallbackActive=!1,this.acpSessionDisplayTitleOverrides={},this.ownedBackendSessions=new Set,this.sessionDisposeRequests=new Map,this.sessionLoadGenerations=new Map,this.sessionLifecycleOperations=new Map,this.shouldFailBddAttachment=(0,v.createAcpAttachmentFailureFixture)(),this.agentSessionCatalog=[],this.metadataOnlySessionIds=new Set,this.agentSessionMetadataRevision=0,this.agentSessionMetadataUpdates=new Map,this.onDidApplySessionStateEmitter=this.registerDispose(new c.Emitter),this.onDidApplySessionState=this.onDidApplySessionStateEmitter.event,this.onDidChangeAgentSessionCatalogEmitter=this.registerDispose(new c.Emitter),this.onDidChangeAgentSessionCatalog=this.onDidChangeAgentSessionCatalogEmitter.event;const A=this.aiNativeConfig.capabilities.supportsAgentMode?"acp":"local",S=this.sessionProviderRegistry.getAllProviders().filter(w=>w.canHandle(A))[0];this.mainProvider=S}useAcpProviderWhenAvailable(){var A;const y=(A=this.mainProvider)===null||A===void 0?void 0:A.canHandle;this.localFallbackActive||!this.aiNativeConfig.capabilities.supportsAgentMode||typeof y!="function"||y.call(this.mainProvider,"acp")||(this.mainProvider=this.sessionProviderRegistry.getAllProviders().find(S=>S.canHandle("acp"))||null)}async init(){await this.initDisplayTitleOverrides(),await this.loadSessionList()}async initDisplayTitleOverrides(){try{this.acpTitleStorage=await this.acpStorageProvider(c.STORAGE_NAMESPACE.CHAT),this.acpSessionDisplayTitleOverrides=this.acpTitleStorage.get(E,{})||{}}catch{this.acpTitleStorage=void 0,this.acpSessionDisplayTitleOverrides={}}}persistDisplayTitleOverrides(){var A;(A=this.acpTitleStorage)===null||A===void 0||A.set(E,this.acpSessionDisplayTitleOverrides)}getDisplayTitleOverride(A){return this.acpSessionDisplayTitleOverrides[A]}peekSession(A){const y=this.sessionModels;return y.peek?y.peek(A):y.get(A)}getSession(A){return this.aiNativeConfig.capabilities.supportsAgentMode?this.peekSession(A):super.getSession(A)}setSessionPreservingOrder(A,y){const S=this.sessionModels,w=S.has(A)&&S.keys?Array.from(S.keys()):void 0;if(this.sessionModels.set(A,y),!w)return;const T=w.map(I=>[I,I===A?y:this.peekSession(I)]).filter(I=>!!I[1]);this.sessionModels.clear(),T.forEach(([I,D])=>{this.sessionModels.set(I,D)})}setDisplayTitleOverride(A,y){var S;const w=this.createDisplayTitle(y);w&&(this.acpSessionDisplayTitleOverrides={...this.acpSessionDisplayTitleOverrides,[A]:w},(S=this.peekSession(A))===null||S===void 0||S.setTitle(w),this.persistDisplayTitleOverrides())}removeDisplayTitleOverride(A){if(!this.acpSessionDisplayTitleOverrides[A])return;const y={...this.acpSessionDisplayTitleOverrides};delete y[A],this.acpSessionDisplayTitleOverrides=y,this.persistDisplayTitleOverrides()}extractUserMessageFromAcpPrompt(A){var y;const S=A.match(/(?:^|\n)\s*---\s*(?:\n+|\s+)([\s\S]*)$/);return((y=S?.[1])===null||y===void 0?void 0:y.trim())||void 0}createDisplayTitle(A){if(!A)return"";const y=this.extractUserMessageFromAcpPrompt(A)||A;return(0,_.cleanAttachedTextWrapper)(y).trim().slice(0,d)}isLikelyAcpContextTitle(A){return A?m.some(y=>A.trim().startsWith(y)):!1}createFallbackSessionTitle(A){return`Session ${(A.startsWith("acp:")?A.slice(4):A).slice(0,8)}`}resolveTitleFromMessages(A){const y=A.history.messages.find(S=>S.role===1)||A.history.messages[0];return this.createDisplayTitle(y?.content)}resolveAcpSessionTitle(A){var y;const S=(y=this.agentSessionMetadataUpdates.get(A.sessionId))===null||y===void 0?void 0:y.title;if(S)return this.createDisplayTitle(S);const w=this.getDisplayTitleOverride(A.sessionId);if(w)return w;const T=this.extractUserMessageFromAcpPrompt(A.title||"");if(T)return this.createDisplayTitle(T);const I=this.createDisplayTitle(A.title);if(I&&!this.isLikelyAcpContextTitle(A.title))return I;const D=this.resolveTitleFromMessages(A);return D||(A.title&&this.isLikelyAcpContextTitle(A.title)?this.createFallbackSessionTitle(A.sessionId):g)}getExistingTitleForLoadedSession(A,y){const S=this.getDisplayTitleOverride(A);if(S)return S;const w=y?.title;if(w&&!this.isLikelyAcpContextTitle(w))return w}isEmptyDefaultSession(A){return A.title===g&&A.history.getMessages().length===0&&A.requests.length===0}moveEmptyDefaultSessionsToEnd(A){A.forEach(y=>{const S=this.peekSession(y);!S||!this.isEmptyDefaultSession(S)||(this.sessionModels.delete(y),this.sessionModels.set(y,S))})}async loadSessionList(){if(this.useAcpProviderWhenAvailable(),!this.mainProvider){await this.storageInitEmitter.fireAndAwait();return}try{const y=(await this.mainProvider.loadSessions()).slice(-l),S=new Set(this.sessionModels.keys()),w=y.filter(I=>!S.has(I.sessionId)),T=l-S.size;T>0&&this.fromAcpJSON(w.slice(-T)).forEach(D=>{this.sessionModels.set(D.sessionId,D)}),this.moveEmptyDefaultSessionsToEnd(S)}catch{this.sessionModels.clear()}await this.storageInitEmitter.fireAndAwait()}getAgentSessionCatalog(){return this.agentSessionCatalog.map(A=>({...A}))}async refreshAgentSessionCatalog(){var A;if(this.useAcpProviderWhenAvailable(),!(!((A=this.mainProvider)===null||A===void 0)&&A.refreshAgentSessions))return this.agentSessionCatalog=[],[];const y=this.agentSessionMetadataRevision,w=(await this.mainProvider.refreshAgentSessions()).map(D=>{const R=this.agentSessionMetadataUpdates.get(D.sessionId);return!R||R.revision<=y?D:{...D,...R.title!==void 0?{title:R.title||void 0}:{},...R.updatedAt!==void 0?{updatedAt:R.updatedAt||void 0}:{}}}),T=new Set(w.map(D=>D.sessionId)),I=new Map;for(const D of w){if(this.peekSession(D.sessionId)&&!this.metadataOnlySessionIds.has(D.sessionId))continue;const M=D.updatedAt?Date.parse(D.updatedAt):void 0,[O]=this.fromAcpJSON([{sessionId:D.sessionId,createdAt:Number.isFinite(M)?M:void 0,history:{additional:{},messages:[]},requests:[],title:D.title||"",extension:{availableCommands:[],acpTarget:{agentId:D.agentId,cwd:D.cwd},metadataOnly:!0,updatedAt:D.updatedAt}}]);O&&I.set(D.sessionId,O)}for(const D of this.metadataOnlySessionIds)T.has(D)||this.sessionModels.delete(D);for(const[D,R]of I)this.sessionModels.set(D,R);return this.metadataOnlySessionIds=new Set(I.keys()),this.agentSessionCatalog=w.map(D=>({...D})),this.onDidChangeAgentSessionCatalogEmitter.fire(this.getAgentSessionCatalog()),this.getAgentSessionCatalog()}getSessions(){return Array.from(this.sessionModels.values())}getAvailableCommands(A){var y;return((y=this.availableCommandsBySession)===null||y===void 0?void 0:y.get(A))||[]}getAvailableCommandsBySession(){return this.availableCommandsBySession||(this.availableCommandsBySession=new Map),this.availableCommandsBySession}async startSession(A){var y,S;if(this.useAcpProviderWhenAvailable(),this.aiNativeConfig.capabilities.supportsAgentMode&&(!((y=this.mainProvider)===null||y===void 0)&&y.createSession)){const T=await this.mainProvider.createSession(A),I=this.fromAcpJSON([T]);if(I.length>0){const D=I[0];return!((S=T.extension)===null||S===void 0)&&S.availableCommands&&this.getAvailableCommandsBySession().set(D.sessionId,T.extension.availableCommands),this.ownedBackendSessions.add(D.sessionId),this.sessionModels.set(D.sessionId,D),this.listenSession(D),D}}const w=new a.ChatModel(this.chatFeatureRegistry);return this.sessionModels.set(w.sessionId,w),this.listenSession(w),w}async loadSession(A){const y=(this.sessionLoadGenerations.get(A)||0)+1;this.sessionLoadGenerations.set(A,y);let S=Promise.resolve("ready");return await this.enqueueSessionLifecycle(A,async()=>{var w,T;if(this.useAcpProviderWhenAvailable(),this.aiNativeConfig.capabilities.supportsAgentMode){const I=this.peekSession(A),D=!!(!((T=(w=I?.history)===null||w===void 0?void 0:w.getMessages())===null||T===void 0)&&T.length);if(this.mainProvider&&A){let R=!1;if(!D&&this.mainProvider.loadSession){const M=await this.mainProvider.loadSession(A);M&&(R=!0,this.ownedBackendSessions.add(A),this.restoreLoadedSession(A,M,I))}S=(async()=>{var M,O;if(this.shouldFailBddAttachment())throw new Error("BDD attachment transport unavailable");const x=await((O=(M=this.mainProvider)===null||M===void 0?void 0:M.attachSession)===null||O===void 0?void 0:O.call(M,A));return this.sessionLoadGenerations.get(A)!==y||!this.peekSession(A)?(x?.end(),"failed"):(x&&this.observeSessionAttachment(A,x),R&&this.ownedBackendSessions.add(A),"ready")})().catch(M=>(this.logger.error(`[ACP Chat][Manager] attach session failed after restoring history \u2014 errorType=${M instanceof Error?M.name:typeof M}`),"failed"))}}}),{liveReady:S}}enqueueSessionLifecycle(A,y){const w=(this.sessionLifecycleOperations.get(A)||Promise.resolve()).catch(()=>{}).then(y),T=w.then(()=>{},()=>{});return this.sessionLifecycleOperations.set(A,T),T.then(()=>{this.sessionLifecycleOperations.get(A)===T&&this.sessionLifecycleOperations.delete(A)}),w}restoreLoadedSession(A,y,S){var w,T,I;const D=this.getExistingTitleForLoadedSession(A,S),R=D&&(!y.title||this.isLikelyAcpContextTitle(y.title))?{...y,title:D}:y,M={...R,extension:R.extension?{...R.extension,acpTarget:(w=R.extension.acpTarget)!==null&&w!==void 0?w:S?.acpTarget}:S?.acpTarget?{availableCommands:[],acpTarget:S.acpTarget}:void 0},[O]=this.fromAcpJSON([M]);O&&(!((T=y.extension)===null||T===void 0)&&T.availableCommands&&this.getAvailableCommandsBySession().set(A,y.extension.availableCommands),this.setSessionPreservingOrder(A,O),this.metadataOnlySessionIds.delete(A),this.listenSession(O),S&&S!==O&&((I=this.onDidApplySessionStateEmitter)===null||I===void 0||I.fire({sessionId:A,model:O,modelReplaced:!0})),!S&&O.title&&O.title!==g&&!this.isLikelyAcpContextTitle(O.title)&&this.setDisplayTitleOverride(A,O.title))}getSessionAttachments(){return this.sessionAttachments||(this.sessionAttachments=new Map),this.sessionAttachments}observeSessionAttachment(A,y){const S=this.getSessionAttachments(),w=S.get(A);w&&(w.disposables.forEach(M=>M.dispose()),w.stream.end());const T=M=>{const O=this.getSession(A);if(O&&(O.setThreadStatus(M),!(0,u.isAcpResponsePending)(M))){const x=O.requests[O.requests.length-1];x&&!x.response.isComplete&&x.response.complete()}},I=[],D=()=>{var M;((M=S.get(A))===null||M===void 0?void 0:M.stream)===y&&S.delete(A),I.splice(0).forEach(O=>O.dispose())},R=M=>{var O;const x=M();((O=S.get(A))===null||O===void 0?void 0:O.stream)!==y?x.dispose():I.push(x)};S.set(A,{stream:y,disposables:I}),R(()=>y.onData(M=>{var O,x;if(M.kind==="sessionSnapshot"){const L=(x=(O=this.mainProvider)===null||O===void 0?void 0:O.restoreSessionSnapshot)===null||x===void 0?void 0:x.call(O,A,M);L&&this.restoreLoadedSession(A,L,this.peekSession(A)),T(M.threadStatus),this.applySessionStateUpdate(A,{currentModeId:M.currentModeId,currentModelId:M.currentModelId,configOptions:M.configOptions,availableCommands:M.availableCommands});return}if(M.kind==="threadStatus"){T(M.threadStatus);return}if(M.kind==="sessionState"){this.applySessionStateUpdate(A,M);return}const k=this.getSession(A),N=k?.requests[k.requests.length-1];k&&N&&!N.response.isComplete&&k.acceptResponseProgress(N,M)})),R(()=>y.onEnd(D)),R(()=>y.onError(D))}createRequest(A,y,S,w,T){var I,D,R,M;const O=this.getSession(A),x=this.aiNativeConfig.capabilities.supportsAgentMode&&!this.getDisplayTitleOverride(A)&&O&&(O.history.getMessages().length===0&&O.requests.length===0||this.isLikelyAcpContextTitle(O.title));this.logger.log(`[ACP Chat][Manager] createRequest start \u2014 sessionId=${A}, agentId=${S||"(empty)"}, command=${w||"(empty)"}, messageChars=${y.length}, images=${(I=T?.length)!==null&&I!==void 0?I:0}, existingRequests=${(D=O?.requests.length)!==null&&D!==void 0?D:0}, historyMessages=${(R=O?.history.getMessages().length)!==null&&R!==void 0?R:0}`);const k=super.createRequest(A,y,S,w,T);return this.logger.log(`[ACP Chat][Manager] createRequest ${k?"done":"skipped"} \u2014 sessionId=${A}, requestId=${(M=k?.requestId)!==null&&M!==void 0?M:"(empty)"}`),k&&x&&this.setDisplayTitleOverride(A,y),k}async sendRequest(A,y,S,w){var T,I;this.logger.log(`[ACP Chat][Manager] sendRequest start \u2014 sessionId=${A}, requestId=${y.requestId}, regenerate=${S}, agentId=${y.message.agentId}, command=${y.message.command||"(empty)"}, messageChars=${y.message.prompt.length}, images=${(I=(T=y.message.images)===null||T===void 0?void 0:T.length)!==null&&I!==void 0?I:0}`);try{await super.sendRequest(A,y,S,w),this.logger.log(`[ACP Chat][Manager] sendRequest done \u2014 sessionId=${A}, requestId=${y.requestId}`)}catch(D){const R=D instanceof Error?D.message:String(D);throw this.logger.error(`[ACP Chat][Manager] sendRequest error \u2014 sessionId=${A}, requestId=${y.requestId}, error=${R}`),D}}cancelRequest(A){var y;if(super.cancelRequest(A))return!0;const w=this.getSession(A);return!w||!(0,u.isAcpCancellationAllowed)(w.threadStatus)||!(!((y=this.mainProvider)===null||y===void 0)&&y.cancelSession)?!1:(this.mainProvider.cancelSession(A).catch(T=>{const I=T instanceof Error?T.message:String(T);this.logger.error(`[ACP Chat][Manager] cancel attached session failed \u2014 sessionId=${A}, error=${I}`)}),!0)}shouldValidateModelChange(A){return!A.startsWith("acp:")}clearSession(A){var y;super.clearSession(A),(y=this.availableCommandsBySession)===null||y===void 0||y.delete(A),this.removeDisplayTitleOverride(A)}async disposeSession(A,y=!1){const S=this.sessionLoadGenerations.get(A)||0,w=this.sessionDisposeRequests.get(A);if(w?.generation===S)return w.promise;const I=this.enqueueSessionLifecycle(A,async()=>{var D,R,M,O,x,k;const N=(D=this.sessionAttachments)===null||D===void 0?void 0:D.get(A);if(N&&((R=this.sessionAttachments)===null||R===void 0||R.delete(A),N.disposables.forEach(L=>L.dispose()),N.stream.end()),!y&&!this.ownedBackendSessions.has(A)){this.getSession(A)&&this.clearSession(A);return}try{y?await((O=(M=this.mainProvider)===null||M===void 0?void 0:M.disposeSession)===null||O===void 0?void 0:O.call(M,A,!0)):await((k=(x=this.mainProvider)===null||x===void 0?void 0:x.disposeSession)===null||k===void 0?void 0:k.call(x,A)),this.ownedBackendSessions.delete(A)}finally{this.getSession(A)&&this.clearSession(A)}}).finally(()=>{var D;((D=this.sessionDisposeRequests.get(A))===null||D===void 0?void 0:D.promise)===I&&this.sessionDisposeRequests.delete(A)});return this.sessionDisposeRequests.set(A,{generation:S,promise:I}),I}applySessionStateUpdate(A,y){const S=A.startsWith("acp:")?A:`acp:${A}`;this.applyAgentSessionMetadataUpdate(S,y.title,y.updatedAt);const w=this.getSession(S);if(!w)return;const T=w.currentModeId;let I=!1;y.currentModeId!==void 0&&w.currentModeId!==y.currentModeId&&(w.currentModeId=y.currentModeId,I=!0),y.currentModelId!==void 0&&w.modelId!==y.currentModelId&&(w.modelId=y.currentModelId,I=!0),y.configOptions!==void 0&&(w.configOptions=y.configOptions,I=!0),y.availableCommands!==void 0&&(this.getAvailableCommandsBySession().set(S,y.availableCommands),I=!0),y.title!==void 0&&w.title!==(y.title||"")&&(w.setTitle(y.title||""),I=!0),I&&this.onDidApplySessionStateEmitter.fire({sessionId:S,model:w,previousModeId:T,currentModeId:w.currentModeId,availableCommands:y.availableCommands})}applyAgentSessionMetadataUpdate(A,y,S){if(y===void 0&&S===void 0)return;const w=this.agentSessionMetadataUpdates.get(A);this.agentSessionMetadataUpdates.set(A,{revision:++this.agentSessionMetadataRevision,...y!==void 0?{title:y}:w?.title!==void 0?{title:w.title}:{},...S!==void 0?{updatedAt:S}:w?.updatedAt!==void 0?{updatedAt:w.updatedAt}:{}});const T=this.agentSessionCatalog.findIndex(R=>R.sessionId===A);if(T===-1)return;const D={...this.agentSessionCatalog[T],...y!==void 0?{title:y||void 0}:{},...S!==void 0?{updatedAt:S||void 0}:{}};this.agentSessionCatalog=this.agentSessionCatalog.map((R,M)=>M===T?D:R),this.onDidChangeAgentSessionCatalogEmitter.fire(this.getAgentSessionCatalog())}fallbackToLocal(){const A=this.sessionProviderRegistry.getProvider("local");A&&(this.localFallbackActive=!0,this.mainProvider=A,this.sessionModels.clear(),this.loadSessionList())}toSessionData(A){return{sessionId:A.sessionId,createdAt:A.createdAt,modelId:A.modelId,history:A.history.toJSON(),title:A.title,requests:A.getRequests().map(y=>({requestId:y.requestId,message:y.message,response:{isCanceled:y.response.isCanceled,isComplete:y.response.isComplete,responseText:y.response.responseText,responseContents:y.response.responseContents,responseParts:y.response.responseParts,errorDetails:y.response.errorDetails,followups:y.response.followups}}))}}fromAcpJSON(A){return A.filter(y=>y.history.messages.length>0||y.sessionId.startsWith("acp:")).map(y=>{var S;const w=new a.ChatModel(this.chatFeatureRegistry,{sessionId:y.sessionId,createdAt:y.createdAt,history:new p.MsgHistoryManager(this.chatFeatureRegistry,y.history),modelId:y.modelId,title:this.resolveAcpSessionTitle(y),agentModes:y.agentModes,currentModeId:y.currentModeId,agentModels:y.agentModels,configOptions:y.configOptions,acpTarget:(S=y.extension)===null||S===void 0?void 0:S.acpTarget}),T=y.requests.map(I=>{var D;return new a.ChatRequestModel(I.requestId,w,I.message,new a.ChatResponseModel(I.requestId,w,I.message.agentId,{responseContents:I.response.responseContents,isComplete:(D=I.response.isComplete)!==null&&D!==void 0?D:!0,responseText:I.response.responseText,responseParts:I.response.responseParts,errorDetails:I.response.errorDetails,followups:I.response.followups,isCanceled:I.response.isCanceled}))});return w.restoreRequests(T),w})}async saveSessions(){var A;if(!(!((A=this.mainProvider)===null||A===void 0)&&A.saveSessions))return;const y=this.getSessions().map(S=>this.toSessionData(S));await this.mainProvider.saveSessions(y)}dispose(){var A,y;(A=this.sessionAttachments)===null||A===void 0||A.forEach(({stream:S,disposables:w})=>{w.forEach(T=>T.dispose()),S.end()}),(y=this.sessionAttachments)===null||y===void 0||y.clear(),super.dispose()}};t.AcpChatManagerService=h,n.__decorate([(0,r.Autowired)(o.AINativeConfigService),n.__metadata("design:type",o.AINativeConfigService)],h.prototype,"aiNativeConfig",void 0),n.__decorate([(0,r.Autowired)(o.ILogger),n.__metadata("design:type",Object)],h.prototype,"logger",void 0),n.__decorate([(0,r.Autowired)(s.ISessionProviderRegistry),n.__metadata("design:type",Object)],h.prototype,"sessionProviderRegistry",void 0),n.__decorate([(0,r.Autowired)(c.StorageProvider),n.__metadata("design:type",Function)],h.prototype,"acpStorageProvider",void 0),n.__decorate([(0,c.debounce)(1e3),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[]),n.__metadata("design:returntype",Promise)],h.prototype,"saveSessions",null),t.AcpChatManagerService=h=n.__decorate([(0,r.Injectable)(),n.__metadata("design:paramtypes",[])],h)},61282:(P,t,e)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ChatManagerService=void 0;const r=e(85608),o=e(76003),c=e(41869),_=e(43718),v=e(65677),p=e(19413),f=e(44260),a=e(42033),u=e(11735),s=20;function l(E){return E instanceof Error?E.message:String(E)}class d extends _.LRUCache{disposeKey(m){const h=this.get(m);h&&h.dispose(),this.delete(m)}dispose(){this.forEach(m=>{m.dispose()}),this.clear()}}let g=class extends _.Disposable{fromJSON(m){return m.filter(h=>h.history.messages.length>0).map(h=>{const b=new a.ChatModel(this.chatFeatureRegistry,{sessionId:h.sessionId,createdAt:h.createdAt,history:new f.MsgHistoryManager(this.chatFeatureRegistry,h.history),modelId:h.modelId}),A=h.requests.map(y=>new a.ChatRequestModel(y.requestId,b,y.message,new a.ChatResponseModel(y.requestId,b,y.message.agentId,{responseContents:y.response.responseContents,isComplete:!0,responseText:y.response.responseText,responseParts:y.response.responseParts,errorDetails:y.response.errorDetails,followups:y.response.followups,isCanceled:y.response.isCanceled})));return b.restoreRequests(A),b})}constructor(){super(),this.sessionModels=this.registerDispose(new d(s)),n.set(this,this.registerDispose(new _.DisposableMap)),this.storageInitEmitter=new _.Emitter,this.onStorageInit=this.storageInitEmitter.event}async init(){this._chatStorage=await this.storageProvider(_.STORAGE_NAMESPACE.CHAT);const m=this._chatStorage.get("sessionModels",[]);this.fromJSON(m).forEach(b=>{this.sessionModels.set(b.sessionId,b),this.listenSession(b)}),await this.storageInitEmitter.fireAndAwait()}getSessions(){return Array.from(this.sessionModels.values())}async startSession(){const m=new a.ChatModel(this.chatFeatureRegistry);return this.sessionModels.set(m.sessionId,m),this.listenSession(m),m}getSession(m){return this.sessionModels.get(m)}clearSession(m){var h;if(!this.sessionModels.get(m))throw new Error(`Unknown session: ${m}`);this.sessionModels.disposeKey(m),(h=r.__classPrivateFieldGet(this,n,"f").get(m))===null||h===void 0||h.cancel(),r.__classPrivateFieldGet(this,n,"f").disposeKey(m),this.saveSessions()}createRequest(m,h,b,A,y){const S=this.getSession(m);if(!S)throw new Error(`Unknown session: ${m}`);if(!r.__classPrivateFieldGet(this,n,"f").has(m))return S.addRequest({prompt:h,agentId:b,command:A,images:y})}async sendRequest(m,h,b,A){var y,S;const w=Date.now();this.logger.log(`[ChatManagerService] sendRequest enter \u2014 sessionId=${m}, requestId=${h.requestId}, agentId=${h.message.agentId}, command=${h.message.command||"(empty)"}, regenerate=${!!b}`);const T=this.getSession(m);if(!T)throw this.logger.error(`[ChatManagerService] sendRequest missing model \u2014 sessionId=${m}, requestId=${h.requestId}`),new Error(`Unknown session: ${m}`);this.logger.log(`[ChatManagerService] sendRequest model resolved \u2014 sessionId=${m}, requestId=${h.requestId}, requests=${T.requests.length}, historyMessages=${T.history.getMessages().length}`);const I=T.modelId,D=this.preferenceService.get(_.AINativeSettingSectionsId.ModelID);if(this.logger.log(`[ChatManagerService] sendRequest model preference \u2014 sessionId=${m}, requestId=${h.requestId}, savedModelId=${I||"(empty)"}, currentModelId=${D||"(empty)"}`),!I)T.modelId=D;else{if(I!==D&&this.shouldValidateModelChange(m,T))throw this.logger.error(`[ChatManagerService] sendRequest model changed \u2014 sessionId=${m}, requestId=${h.requestId}, savedModelId=${I||"(empty)"}, currentModelId=${D||"(empty)"}`),new Error("Model changed unexpectedly");I!==D&&this.logger.log(`[ChatManagerService] sendRequest model change allowed \u2014 sessionId=${m}, requestId=${h.requestId}, savedModelId=${I||"(empty)"}, currentModelId=${D||"(empty)"}`)}const R=new _.CancellationTokenSource,M=R.token;r.__classPrivateFieldGet(this,n,"f").set(T.sessionId,R),this.logger.log(`[ChatManagerService] sendRequest pending registered \u2014 sessionId=${m}, requestId=${h.requestId}`);const O=M.onCancellationRequested(()=>{this.logger.log(`[ChatManagerService] sendRequest cancellation requested \u2014 sessionId=${m}, requestId=${h.requestId}`),h.response.cancel()}),x=this.preferenceService.get(_.AINativeSettingSectionsId.ContextWindow);this.logger.log(`[ChatManagerService] sendRequest history start \u2014 sessionId=${m}, requestId=${h.requestId}, contextWindow=${x}`);const k=T.getMessageHistory(x);this.logger.log(`[ChatManagerService] sendRequest history done \u2014 sessionId=${m}, requestId=${h.requestId}, historyMessages=${k.length}`);try{const N=K=>{if(!M.isCancellationRequested){if(K.kind==="requestAccepted"){A?.();return}T.acceptResponseProgress(h,K)}};this.logger.log(`[ChatManagerService] sendRequest progress callback ready \u2014 sessionId=${m}, requestId=${h.requestId}`);const L={sessionId:m,requestId:h.requestId,message:h.message.prompt,command:h.message.command,images:h.message.images,regenerate:b};this.logger.log(`[ChatManagerService] sendRequest invokeAgent before \u2014 sessionId=${m}, requestId=${h.requestId}, agentId=${h.message.agentId}, messageChars=${L.message.length}, historyMessages=${k.length}, chatAgentService=${((S=(y=this.chatAgentService)===null||y===void 0?void 0:y.constructor)===null||S===void 0?void 0:S.name)||"(unknown)"}`);const B=await this.chatAgentService.invokeAgent(h.message.agentId,L,N,k,M);if(this.logger.log(`[ChatManagerService] sendRequest invokeAgent after \u2014 sessionId=${m}, requestId=${h.requestId}, elapsedMs=${Date.now()-w}, hasErrorDetails=${!!B.errorDetails}`),!M.isCancellationRequested){if(B.errorDetails){h.response.setErrorDetails(B.errorDetails),h.response.complete();return}this.chatAgentService.getFollowups(h.message.agentId,m,_.CancellationToken.None).then(W=>{h.response.setFollowups(W),h.response.complete()})}}catch(N){const L=l(N);this.logger.error(`[ChatManagerService] sendRequest error \u2014 sessionId=${m}, requestId=${h.requestId}, error=${L}`),M.isCancellationRequested||(h.response.setErrorDetails({message:L}),h.response.complete())}finally{this.logger.log(`[ChatManagerService] sendRequest cleanup \u2014 sessionId=${m}, requestId=${h.requestId}, elapsedMs=${Date.now()-w}, canceled=${M.isCancellationRequested}`),O.dispose(),r.__classPrivateFieldGet(this,n,"f").disposeKey(T.sessionId),this.saveSessions()}}shouldValidateModelChange(m,h){return!0}listenSession(m){this.addDispose(m.history.onMessageAdditionalChange(()=>{this.saveSessions()}))}saveSessions(){this._chatStorage.set("sessionModels",this.getSessions())}cancelRequest(m){const h=r.__classPrivateFieldGet(this,n,"f").get(m);return h?.cancel(),r.__classPrivateFieldGet(this,n,"f").disposeKey(m),this.saveSessions(),!!h}};t.ChatManagerService=g,n=new WeakMap,r.__decorate([(0,o.Autowired)(o.INJECTOR_TOKEN),r.__metadata("design:type",o.Injector)],g.prototype,"injector",void 0),r.__decorate([(0,o.Autowired)(p.IChatAgentService),r.__metadata("design:type",Object)],g.prototype,"chatAgentService",void 0),r.__decorate([(0,o.Autowired)(_.ILogger),r.__metadata("design:type",Object)],g.prototype,"logger",void 0),r.__decorate([(0,o.Autowired)(_.StorageProvider),r.__metadata("design:type",Function)],g.prototype,"storageProvider",void 0),r.__decorate([(0,o.Autowired)(c.PreferenceService),r.__metadata("design:type",Object)],g.prototype,"preferenceService",void 0),r.__decorate([(0,o.Autowired)(v.ChatFeatureRegistryToken),r.__metadata("design:type",u.ChatFeatureRegistry)],g.prototype,"chatFeatureRegistry",void 0),r.__decorate([(0,_.debounce)(1e3),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",void 0)],g.prototype,"saveSessions",null),t.ChatManagerService=g=r.__decorate([(0,o.Injectable)(),r.__metadata("design:paramtypes",[])],g)},42033:(P,t,e)=>{"use strict";var n,r,o,c,_,v,p,f,a,u,s,l,d,g,E,m,h,b,A,y,S,w,T,I,D;Object.defineProperty(t,"__esModule",{value:!0}),t.ChatSlashCommandItemModel=t.ChatWelcomeMessageModel=t.ChatModel=t.ChatRequestModel=t.ChatResponseModel=void 0;const R=e(85608),M=e(76003),O=e(43718),x=e(90684),k=e(19413),N=e(44260);class L extends O.Disposable{get responseParts(){return R.__classPrivateFieldGet(this,r,"f")}get responseContents(){return R.__classPrivateFieldGet(this,o,"f")}get isComplete(){return R.__classPrivateFieldGet(this,c,"f")}get isCanceled(){return R.__classPrivateFieldGet(this,_,"f")}get requestId(){return R.__classPrivateFieldGet(this,v,"f")}get responseText(){return R.__classPrivateFieldGet(this,p,"f")}get safeProgress(){return R.__classPrivateFieldGet(this,f,"f")}get errorDetails(){return R.__classPrivateFieldGet(this,a,"f")}get followups(){return R.__classPrivateFieldGet(this,u,"f")}get onDidChange(){return R.__classPrivateFieldGet(this,s,"f").event}constructor(j,Y,z,V){super(),n.add(this),this.session=Y,this.agentId=z,r.set(this,[]),o.set(this,[]),c.set(this,!1),_.set(this,!1),v.set(this,void 0),p.set(this,""),f.set(this,void 0),a.set(this,void 0),u.set(this,void 0),s.set(this,this.registerDispose(new O.Emitter)),R.__classPrivateFieldSet(this,v,j,"f"),V&&(R.__classPrivateFieldSet(this,o,V.responseContents,"f"),R.__classPrivateFieldSet(this,r,V.responseParts||[],"f"),R.__classPrivateFieldSet(this,p,V.responseText,"f"),R.__classPrivateFieldSet(this,c,V.isComplete,"f"),R.__classPrivateFieldSet(this,_,V.isCanceled,"f"),R.__classPrivateFieldSet(this,a,V.errorDetails,"f"),R.__classPrivateFieldSet(this,u,V.followups,"f"))}updateContent(j,Y){var z;const V=R.__classPrivateFieldGet(this,r,"f").length-1;if(j.kind==="content"||j.kind==="markdownContent"){const $=R.__classPrivateFieldGet(this,r,"f")[V];!$||$.kind!=="markdownContent"?j.kind==="content"?R.__classPrivateFieldGet(this,r,"f").push({content:new x.MarkdownString(j.content),kind:"markdownContent"}):R.__classPrivateFieldGet(this,r,"f").push(j):j.kind==="markdownContent"?R.__classPrivateFieldGet(this,r,"f")[V]={content:new x.MarkdownString($.content.value+j.content.value),kind:"markdownContent"}:R.__classPrivateFieldGet(this,r,"f")[V]={content:new x.MarkdownString($.content.value+j.content,$.content),kind:"markdownContent"},R.__classPrivateFieldGet(this,n,"m",l).call(this)}else if(j.kind==="reasoning"){const $=R.__classPrivateFieldGet(this,r,"f")[V];!$||$.kind!=="reasoning"?R.__classPrivateFieldGet(this,r,"f").push({content:j.content.replace(/^<think>/,""),kind:"reasoning"}):R.__classPrivateFieldGet(this,r,"f")[V]={content:$.content+j.content,kind:"reasoning"},R.__classPrivateFieldGet(this,n,"m",l).call(this)}else if(j.kind==="asyncContent"){const $=R.__classPrivateFieldGet(this,r,"f").push(j)-1;R.__classPrivateFieldGet(this,n,"m",l).call(this),(z=j.resolvedContent)===null||z===void 0||z.then(H=>{typeof H=="string"?R.__classPrivateFieldGet(this,r,"f")[$]={content:new x.MarkdownString(H),kind:"markdownContent"}:(0,x.isMarkdownString)(H)?R.__classPrivateFieldGet(this,r,"f")[$]={content:H,kind:"markdownContent"}:R.__classPrivateFieldGet(this,r,"f")[$]=H,R.__classPrivateFieldGet(this,n,"m",l).call(this,Y)})}else if(j.kind==="treeData"||j.kind==="component")R.__classPrivateFieldGet(this,r,"f").push(j),R.__classPrivateFieldGet(this,n,"m",l).call(this,Y);else if(j.kind==="toolCall"){const $=R.__classPrivateFieldGet(this,r,"f").findIndex(H=>H.kind==="toolCall"&&H.content.id===j.content.id);$!==-1?R.__classPrivateFieldGet(this,r,"f")[$]={kind:"toolCall",content:{...j.content}}:R.__classPrivateFieldGet(this,r,"f").push(j),R.__classPrivateFieldGet(this,n,"m",l).call(this,Y)}}updateSafeProgress(j){var Y;const z=j?.content.trim()?j:void 0;((Y=R.__classPrivateFieldGet(this,f,"f"))===null||Y===void 0?void 0:Y.content)!==z?.content&&(R.__classPrivateFieldSet(this,f,z,"f"),R.__classPrivateFieldGet(this,s,"f").fire())}complete(){R.__classPrivateFieldSet(this,c,!0,"f"),R.__classPrivateFieldSet(this,f,void 0,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}cancel(){R.__classPrivateFieldSet(this,c,!0,"f"),R.__classPrivateFieldSet(this,_,!0,"f"),R.__classPrivateFieldSet(this,f,void 0,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}reset(){R.__classPrivateFieldSet(this,o,[],"f"),R.__classPrivateFieldSet(this,r,[],"f"),R.__classPrivateFieldSet(this,p,"","f"),R.__classPrivateFieldSet(this,f,void 0,"f"),R.__classPrivateFieldSet(this,_,!1,"f"),R.__classPrivateFieldSet(this,c,!1,"f"),R.__classPrivateFieldSet(this,a,void 0,"f"),R.__classPrivateFieldSet(this,u,void 0,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}setErrorDetails(j){R.__classPrivateFieldSet(this,a,j,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}setFollowups(j){R.__classPrivateFieldSet(this,u,j,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}toJSON(){return{isCanceled:this.isCanceled,responseContents:this.responseContents,responseText:this.responseText,responseParts:this.responseParts,errorDetails:this.errorDetails,followups:this.followups}}}t.ChatResponseModel=L,r=new WeakMap,o=new WeakMap,c=new WeakMap,_=new WeakMap,v=new WeakMap,p=new WeakMap,f=new WeakMap,a=new WeakMap,u=new WeakMap,s=new WeakMap,n=new WeakSet,l=function(j){R.__classPrivateFieldSet(this,p,R.__classPrivateFieldGet(this,r,"f").map(z=>z.kind==="asyncContent"?z.content:z.kind==="treeData"||z.kind==="component"?"":z.kind==="toolCall"?z.content.function.name:z.kind==="reasoning"?"":z.content.value).join(`
39452
+ `,{...await this.chatProxyService.getRequestOptions(),trimTexts:["<updated-code>","</updated-code>"],system:"You are a coding assistant that helps merge code updates, ensuring every modification is fully integrated."})}}};t.ApplyService=l,n.__decorate([(0,r.Autowired)(c.CommandService),n.__metadata("design:type",Object)],l.prototype,"commandService",void 0),n.__decorate([(0,r.Autowired)(_.IEditorDocumentModelService),n.__metadata("design:type",Object)],l.prototype,"modelService",void 0),n.__decorate([(0,r.Autowired)(o.AIBackSerivcePath),n.__metadata("design:type",Object)],l.prototype,"aiBackService",void 0),n.__decorate([(0,r.Autowired)(f.ChatProxyServiceToken),n.__metadata("design:type",u.ChatProxyService)],l.prototype,"chatProxyService",void 0),t.ApplyService=l=n.__decorate([(0,r.Injectable)()],l)},74055:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatAgentService=void 0;const n=e(85608),r=n.__importDefault(e(66652)),o=e(76003),c=e(43718),_=e(46044),v=e(73307),p=e(29770);let f=class extends c.Disposable{constructor(){super(),this.agents=new Map,this.initialUserMessageMap=new Map,this.shouldUpdateContext=!1,this._onDidChangeAgents=new c.Emitter,this.onDidChangeAgents=this._onDidChangeAgents.event,this._onDidSendMessage=new c.Emitter,this.onDidSendMessage=this._onDidSendMessage.event,this.addDispose(this._onDidChangeAgents),this.addDispose(this.llmContextService.onDidContextFilesChangeEvent(u=>{u.version!==this.contextVersion&&(this.contextVersion=u.version,this.shouldUpdateContext=!0)}))}registerAgent(u){if(this.agents.has(u.id))throw new Error(`Already registered an agent with id ${u.id}`);return this.agents.set(u.id,{agent:u,commands:[]}),this._onDidChangeAgents.fire(),(0,c.toDisposable)(()=>{this.agents.delete(u.id)&&this._onDidChangeAgents.fire()})}async updateAgent(u,s){const l=this.agents.get(u);if(!l)throw new Error(`No agent with id ${u} registered`);l.agent.metadata={...l.agent.metadata,...s},l.commands=await l.agent.provideSlashCommands(c.CancellationToken.None),s.isDefault&&(this.defaultAgentId=u);const d=await l.agent.provideChatWelcomeMessage(c.CancellationToken.None);if(d){const{content:g,sampleQuestions:E}=d;this.chatFeatureRegistry.registerWelcome(g,E)}this._onDidChangeAgents.fire()}getAgents(){return Array.from(this.agents.values(),u=>u.agent)}hasAgent(u){return this.agents.has(u)}getDefaultAgentId(){return this.defaultAgentId}getAgent(u){const s=this.agents.get(u);return s?.agent}async invokeAgent(u,s,l,d,g){const E=Date.now();this.logger.log(`[ChatAgentService] invokeAgent start \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, messageChars=${s.message.length}, historyMessages=${d.length}, regenerate=${!!s.regenerate}`);const m=this.agents.get(u);if(!m)throw this.logger.error(`[ChatAgentService] invokeAgent missing agent \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, registeredAgents=${Array.from(this.agents.keys()).join(",")||"(empty)"}`),new Error(`No agent with id ${u},this.agents ${this.agents}`);if(this.initialUserMessageMap.has(s.sessionId))this.shouldUpdateContext||s.regenerate||d.length===0?(this.logger.log(`[ChatAgentService] invokeAgent context enhance refresh \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, shouldUpdateContext=${this.shouldUpdateContext}, regenerate=${!!s.regenerate}, historyMessages=${d.length}`),s.message=await this.provideContextMessage(s.message,s.sessionId),this.shouldUpdateContext=!1):this.logger.log(`[ChatAgentService] invokeAgent context enhance skipped \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}`);else{this.logger.log(`[ChatAgentService] invokeAgent context enhance initial \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}`),this.initialUserMessageMap.set(s.sessionId,s.message);const b=s.message;s.message=await this.provideContextMessage(b,s.sessionId)}this.logger.log(`[ChatAgentService] invokeAgent calling agent \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, enhancedMessageChars=${s.message.length}`);const h=await m.agent.invoke(s,l,d,g);return this.logger.log(`[ChatAgentService] invokeAgent done \u2014 agentId=${u}, sessionId=${s.sessionId}, requestId=${s.requestId}, elapsedMs=${Date.now()-E}`),h}async provideContextMessage(u,s){const l=Date.now();this.logger.log(`[ChatAgentService] provideContextMessage serialize start \u2014 sessionId=${s}, messageChars=${u.length}`);const d=await this.llmContextService.serialize();this.logger.log(`[ChatAgentService] provideContextMessage serialize done \u2014 sessionId=${s}, elapsedMs=${Date.now()-l}, contextChars=${JSON.stringify(d).length}`);const g=await this.promptProvider.provideContextPrompt(d,u);return this.logger.log(`[ChatAgentService] provideContextMessage prompt done \u2014 sessionId=${s}, elapsedMs=${Date.now()-l}, fullMessageChars=${g.length}`),this.aiReporter.send({msgType:c.AIServiceType.Chat,actionType:c.ActionTypeEnum.ContextEnhance,actionSource:c.ActionSourceEnum.Chat,sessionId:s,message:g}),this.logger.log(`[ChatAgentService] provideContextMessage reporter sent \u2014 sessionId=${s}, elapsedMs=${Date.now()-l}`),g}populateChatInput(u,s){this.aiChatService.sendMessage({...s,agentId:u,immediate:!1})}getCommands(){return(0,r.default)(Array.from(this.agents.values(),({agent:u,commands:s})=>s.map(l=>({...l,agentId:u.id}))))}async getFollowups(u,s,l){const d=this.agents.get(u);if(!d)throw new Error(`No agent with id ${u}`);return d.agent.provideFollowups?d.agent.provideFollowups(s,l):[]}async getSampleQuestions(u,s){const l=this.agents.get(u);if(!l)throw new Error(`No agent with id ${u}`);return l.agent.provideSampleQuestions?l.agent.provideSampleQuestions(s):[]}async getAllSampleQuestions(){const u=await Promise.all(Array.from(this.agents.values()).map(async({agent:s})=>{try{return await this.getSampleQuestions(s.id,c.CancellationToken.None)}catch(l){return this.logger.error(l),[]}}));return(0,r.default)(u)}sendMessage(u){this._onDidSendMessage.fire(u)}parseMessage(u,s){var l;const d={agentId:"",command:"",message:u};let g=s;const E=this.getAgents(),m=new RegExp(`^@(${E.map(b=>b.id).join("|")})(?:\\s+|$)`,"i"),h=d.message.match(m);if(h){const b=E.find(A=>A.id.toLowerCase()===h[1].toLowerCase());if(!b)return d;g=b.id,d.agentId=g,d.message=d.message.replace(h[0],"")}if(g){const b=(l=this.agents.get(g))===null||l===void 0?void 0:l.commands;if(b?.length){const A=new RegExp(`^/\\s?(${b.map(S=>S.name).join("|")})(?:\\s+|$)`,"i"),y=d.message.match(A);if(y){const S=b.find(w=>w.name.toLowerCase()===y[1].toLowerCase());if(!S)return d;d.command=S.name,d.message=d.message.replace(y[0],"")}}}return d}};t.ChatAgentService=f,n.__decorate([(0,o.Autowired)(c.ILogger),n.__metadata("design:type",Object)],f.prototype,"logger",void 0),n.__decorate([(0,o.Autowired)(c.IAIReporter),n.__metadata("design:type",Object)],f.prototype,"aiReporter",void 0),n.__decorate([(0,o.Autowired)(_.LLMContextServiceToken),n.__metadata("design:type",Object)],f.prototype,"llmContextService",void 0),n.__decorate([(0,o.Autowired)(v.ChatAgentPromptProvider),n.__metadata("design:type",Object)],f.prototype,"promptProvider",void 0),n.__decorate([(0,o.Autowired)(c.ChatServiceToken),n.__metadata("design:type",p.ChatService)],f.prototype,"aiChatService",void 0),n.__decorate([(0,o.Autowired)(c.ChatFeatureRegistryToken),n.__metadata("design:type",Object)],f.prototype,"chatFeatureRegistry",void 0),t.ChatAgentService=f=n.__decorate([(0,o.Injectable)(),n.__metadata("design:paramtypes",[])],f)},84543:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatAgentViewService=void 0;const n=e(85608),r=e(76003),o=e(43718),c=e(19413),_=e(51081);let v=class{constructor(){this.componentsMap=new Map,this.componentsDeferredMap=new Map}registerChatComponent(f){return this.componentsMap.set(f.id,f),this.componentsDeferredMap.has(f.id)&&(this.componentsDeferredMap.get(f.id).resolve(f),this.componentsDeferredMap.delete(f.id)),{dispose:()=>{this.componentsMap.get(f.id)===f&&(this.componentsMap.delete(f.id),this.componentsDeferredMap.delete(f.id))}}}getChatComponent(f){return this.componentsMap.has(f)?this.componentsMap.get(f):(this.componentsDeferredMap.has(f)||this.componentsDeferredMap.set(f,new o.Deferred),null)}getChatComponentDeferred(f){return this.componentsDeferredMap.get(f)||null}getRenderAgents(){return this.chatAgentService.getAgents().filter(f=>f.id!==_.ChatProxyService.AGENT_ID)}};t.ChatAgentViewService=v,n.__decorate([(0,r.Autowired)(c.IChatAgentService),n.__metadata("design:type",Object)],v.prototype,"chatAgentService",void 0),t.ChatAgentViewService=v=n.__decorate([(0,r.Injectable)()],v)},98987:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatEditSchemeDocumentProvider=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(54414),_=e(96689),v=e(73974);let p=class{constructor(){this._onDidChangeContent=new o.Emitter,this.onDidChangeContent=this._onDidChangeContent.event}handlesScheme(a){return a===v.BaseApplyService.CHAT_EDITING_SOURCE_RESOLVER_SCHEME}async provideEditorDocumentModelContent(a,u){const{id:s,side:l}=a.getParsedQuery(),d=this.baseApplyService.getSessionCodeBlocks(),g=d?.find(m=>m.toolCallId===s);return(l==="left"?g?.originalCode:g?.updatedCode)||""}isReadonly(a){return!0}onDidDisposeModel(){}};t.ChatEditSchemeDocumentProvider=p,n.__decorate([(0,r.Autowired)(_.IEditorDocumentModelService),n.__metadata("design:type",Object)],p.prototype,"editorDocumentModelService",void 0),n.__decorate([(0,r.Autowired)(c.WorkbenchEditorService),n.__metadata("design:type",c.WorkbenchEditorService)],p.prototype,"workbenchEditorService",void 0),n.__decorate([(0,r.Autowired)(o.AppConfig),n.__metadata("design:type",Object)],p.prototype,"appConfig",void 0),n.__decorate([(0,r.Autowired)(o.IApplicationService),n.__metadata("design:type",Object)],p.prototype,"applicationService",void 0),n.__decorate([(0,r.Autowired)(v.BaseApplyService),n.__metadata("design:type",v.BaseApplyService)],p.prototype,"baseApplyService",void 0),n.__decorate([(0,r.Autowired)(o.PreferenceService),n.__metadata("design:type",Object)],p.prototype,"preferenceService",void 0),t.ChatEditSchemeDocumentProvider=p=n.__decorate([(0,r.Injectable)()],p)},75641:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ChatInputFooterRegistry=t.FooterButtonPosition=t.ChatInputFooterRegistryToken=void 0;const n=e(85608),r=e(76003),o=e(43718);Object.defineProperty(t,"ChatInputFooterRegistryToken",{enumerable:!0,get:function(){return o.ChatInputFooterRegistryToken}}),Object.defineProperty(t,"FooterButtonPosition",{enumerable:!0,get:function(){return o.FooterButtonPosition}});let c=class extends o.Disposable{constructor(){super(...arguments),this.contributions=[],this.onDidChangeEmitter=new o.Emitter,this.onDidChange=this.onDidChangeEmitter.event}registerFooterItem(v,p){var f,a;const u=this.contributions.findIndex(d=>d.id===v);u!==-1&&this.contributions.splice(u,1);const s={id:v,...p,order:(f=p.order)!==null&&f!==void 0?f:100,position:(a=p.position)!==null&&a!==void 0?a:o.FooterButtonPosition.LEFT};this.contributions.push(s),this.contributions.sort((d,g)=>{var E,m;return((E=d.order)!==null&&E!==void 0?E:0)-((m=g.order)!==null&&m!==void 0?m:0)});const l=o.Disposable.create(()=>{const d=this.contributions.indexOf(s);d!==-1&&(this.contributions.splice(d,1),this.onDidChangeEmitter.fire())});return this.addDispose(l),this.onDidChangeEmitter.fire(),l}getItems(){return this.contributions.filter(v=>!v.visible||v.visible())}};t.ChatInputFooterRegistry=c,t.ChatInputFooterRegistry=c=n.__decorate([(0,r.Injectable)()],c)},36940:(P,t,e)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.AcpChatManagerService=void 0;const n=e(85608),r=e(76003),o=e(41869),c=e(43718),_=e(98864),v=e(90336),p=e(44260),f=e(61282),a=e(42033),u=e(26093),s=e(79329),l=20,d=100,g="New Session",E="acpSessionDisplayTitleOverrides",m=["OpenSumi exposes IDE capabilities","The user's OS version","The rules section has","For requests to create an OpenSumi IDE"];let h=class extends f.ChatManagerService{constructor(){super(),this.mainProvider=null,this.localFallbackActive=!1,this.acpSessionDisplayTitleOverrides={},this.ownedBackendSessions=new Set,this.sessionDisposeRequests=new Map,this.sessionLoadGenerations=new Map,this.sessionLifecycleOperations=new Map,this.shouldFailBddAttachment=(0,v.createAcpAttachmentFailureFixture)(),this.agentSessionCatalog=[],this.metadataOnlySessionIds=new Set,this.agentSessionMetadataRevision=0,this.agentSessionMetadataUpdates=new Map,this.onDidApplySessionStateEmitter=this.registerDispose(new c.Emitter),this.onDidApplySessionState=this.onDidApplySessionStateEmitter.event,this.onDidChangeAgentSessionCatalogEmitter=this.registerDispose(new c.Emitter),this.onDidChangeAgentSessionCatalog=this.onDidChangeAgentSessionCatalogEmitter.event;const A=this.aiNativeConfig.capabilities.supportsAgentMode?"acp":"local",S=this.sessionProviderRegistry.getAllProviders().filter(w=>w.canHandle(A))[0];this.mainProvider=S}useAcpProviderWhenAvailable(){var A;const y=(A=this.mainProvider)===null||A===void 0?void 0:A.canHandle;this.localFallbackActive||!this.aiNativeConfig.capabilities.supportsAgentMode||typeof y!="function"||y.call(this.mainProvider,"acp")||(this.mainProvider=this.sessionProviderRegistry.getAllProviders().find(S=>S.canHandle("acp"))||null)}async init(){await this.initDisplayTitleOverrides(),await this.loadSessionList()}async initDisplayTitleOverrides(){try{this.acpTitleStorage=await this.acpStorageProvider(c.STORAGE_NAMESPACE.CHAT),this.acpSessionDisplayTitleOverrides=this.acpTitleStorage.get(E,{})||{}}catch{this.acpTitleStorage=void 0,this.acpSessionDisplayTitleOverrides={}}}persistDisplayTitleOverrides(){var A;(A=this.acpTitleStorage)===null||A===void 0||A.set(E,this.acpSessionDisplayTitleOverrides)}getDisplayTitleOverride(A){return this.acpSessionDisplayTitleOverrides[A]}peekSession(A){const y=this.sessionModels;return y.peek?y.peek(A):y.get(A)}getSession(A){return this.aiNativeConfig.capabilities.supportsAgentMode?this.peekSession(A):super.getSession(A)}setSessionPreservingOrder(A,y){const S=this.sessionModels,w=S.has(A)&&S.keys?Array.from(S.keys()):void 0;if(this.sessionModels.set(A,y),!w)return;const T=w.map(I=>[I,I===A?y:this.peekSession(I)]).filter(I=>!!I[1]);this.sessionModels.clear(),T.forEach(([I,D])=>{this.sessionModels.set(I,D)})}setDisplayTitleOverride(A,y){var S;const w=this.createDisplayTitle(y);w&&(this.acpSessionDisplayTitleOverrides={...this.acpSessionDisplayTitleOverrides,[A]:w},(S=this.peekSession(A))===null||S===void 0||S.setTitle(w),this.persistDisplayTitleOverrides())}removeDisplayTitleOverride(A){if(!this.acpSessionDisplayTitleOverrides[A])return;const y={...this.acpSessionDisplayTitleOverrides};delete y[A],this.acpSessionDisplayTitleOverrides=y,this.persistDisplayTitleOverrides()}extractUserMessageFromAcpPrompt(A){var y;const S=A.match(/(?:^|\n)\s*---\s*(?:\n+|\s+)([\s\S]*)$/);return((y=S?.[1])===null||y===void 0?void 0:y.trim())||void 0}createDisplayTitle(A){if(!A)return"";const y=this.extractUserMessageFromAcpPrompt(A)||A;return(0,_.cleanAttachedTextWrapper)(y).trim().slice(0,d)}isLikelyAcpContextTitle(A){return A?m.some(y=>A.trim().startsWith(y)):!1}createFallbackSessionTitle(A){return`Session ${(A.startsWith("acp:")?A.slice(4):A).slice(0,8)}`}resolveTitleFromMessages(A){const y=A.history.messages.find(S=>S.role===1)||A.history.messages[0];return this.createDisplayTitle(y?.content)}resolveAcpSessionTitle(A){var y;const S=(y=this.agentSessionMetadataUpdates.get(A.sessionId))===null||y===void 0?void 0:y.title;if(S)return this.createDisplayTitle(S);const w=this.getDisplayTitleOverride(A.sessionId);if(w)return w;const T=this.extractUserMessageFromAcpPrompt(A.title||"");if(T)return this.createDisplayTitle(T);const I=this.createDisplayTitle(A.title);if(I&&!this.isLikelyAcpContextTitle(A.title))return I;const D=this.resolveTitleFromMessages(A);return D||(A.title&&this.isLikelyAcpContextTitle(A.title)?this.createFallbackSessionTitle(A.sessionId):g)}getExistingTitleForLoadedSession(A,y){const S=this.getDisplayTitleOverride(A);if(S)return S;const w=y?.title;if(w&&!this.isLikelyAcpContextTitle(w))return w}isEmptyDefaultSession(A){return A.title===g&&A.history.getMessages().length===0&&A.requests.length===0}moveEmptyDefaultSessionsToEnd(A){A.forEach(y=>{const S=this.peekSession(y);!S||!this.isEmptyDefaultSession(S)||(this.sessionModels.delete(y),this.sessionModels.set(y,S))})}async loadSessionList(){if(this.useAcpProviderWhenAvailable(),!this.mainProvider){await this.storageInitEmitter.fireAndAwait();return}try{const y=(await this.mainProvider.loadSessions()).slice(-l),S=new Set(this.sessionModels.keys()),w=y.filter(I=>!S.has(I.sessionId)),T=l-S.size;T>0&&this.fromAcpJSON(w.slice(-T)).forEach(D=>{this.sessionModels.set(D.sessionId,D)}),this.moveEmptyDefaultSessionsToEnd(S)}catch{this.sessionModels.clear()}await this.storageInitEmitter.fireAndAwait()}getAgentSessionCatalog(){return this.agentSessionCatalog.map(A=>({...A}))}async refreshAgentSessionCatalog(){var A;if(this.useAcpProviderWhenAvailable(),!(!((A=this.mainProvider)===null||A===void 0)&&A.refreshAgentSessions))return this.agentSessionCatalog=[],[];const y=this.agentSessionMetadataRevision,w=(await this.mainProvider.refreshAgentSessions()).map(D=>{const R=this.agentSessionMetadataUpdates.get(D.sessionId);return!R||R.revision<=y?D:{...D,...R.title!==void 0?{title:R.title||void 0}:{},...R.updatedAt!==void 0?{updatedAt:R.updatedAt||void 0}:{}}}),T=new Set(w.map(D=>D.sessionId)),I=new Map;for(const D of w){if(this.peekSession(D.sessionId)&&!this.metadataOnlySessionIds.has(D.sessionId))continue;const M=D.updatedAt?Date.parse(D.updatedAt):void 0,[O]=this.fromAcpJSON([{sessionId:D.sessionId,createdAt:Number.isFinite(M)?M:void 0,history:{additional:{},messages:[]},requests:[],title:D.title||"",extension:{availableCommands:[],acpTarget:{agentId:D.agentId,cwd:D.cwd},metadataOnly:!0,updatedAt:D.updatedAt}}]);O&&I.set(D.sessionId,O)}for(const D of this.metadataOnlySessionIds)T.has(D)||this.sessionModels.delete(D);for(const[D,R]of I)this.sessionModels.set(D,R);return this.metadataOnlySessionIds=new Set(I.keys()),this.agentSessionCatalog=w.map(D=>({...D})),this.onDidChangeAgentSessionCatalogEmitter.fire(this.getAgentSessionCatalog()),this.getAgentSessionCatalog()}getSessions(){return Array.from(this.sessionModels.values())}getAvailableCommands(A){var y;return((y=this.availableCommandsBySession)===null||y===void 0?void 0:y.get(A))||[]}getAvailableCommandsBySession(){return this.availableCommandsBySession||(this.availableCommandsBySession=new Map),this.availableCommandsBySession}async startSession(A){var y,S;if(this.useAcpProviderWhenAvailable(),this.aiNativeConfig.capabilities.supportsAgentMode&&(!((y=this.mainProvider)===null||y===void 0)&&y.createSession)){const T=await this.mainProvider.createSession(A),I=this.fromAcpJSON([T]);if(I.length>0){const D=I[0];return!((S=T.extension)===null||S===void 0)&&S.availableCommands&&this.getAvailableCommandsBySession().set(D.sessionId,T.extension.availableCommands),this.ownedBackendSessions.add(D.sessionId),this.sessionModels.set(D.sessionId,D),this.listenSession(D),D}}const w=new a.ChatModel(this.chatFeatureRegistry);return this.sessionModels.set(w.sessionId,w),this.listenSession(w),w}async loadSession(A){const y=(this.sessionLoadGenerations.get(A)||0)+1;this.sessionLoadGenerations.set(A,y);let S=Promise.resolve("ready");return await this.enqueueSessionLifecycle(A,async()=>{var w,T;if(this.useAcpProviderWhenAvailable(),this.aiNativeConfig.capabilities.supportsAgentMode){const I=this.peekSession(A),D=!!(!((T=(w=I?.history)===null||w===void 0?void 0:w.getMessages())===null||T===void 0)&&T.length);if(this.mainProvider&&A){let R=!1;if(!D&&this.mainProvider.loadSession){const M=await this.mainProvider.loadSession(A);M&&(R=!0,this.ownedBackendSessions.add(A),this.restoreLoadedSession(A,M,I))}S=(async()=>{var M,O;if(this.shouldFailBddAttachment())throw new Error("BDD attachment transport unavailable");const x=await((O=(M=this.mainProvider)===null||M===void 0?void 0:M.attachSession)===null||O===void 0?void 0:O.call(M,A));return this.sessionLoadGenerations.get(A)!==y||!this.peekSession(A)?(x?.end(),"failed"):(x&&this.observeSessionAttachment(A,x),R&&this.ownedBackendSessions.add(A),"ready")})().catch(M=>(this.logger.error(`[ACP Chat][Manager] attach session failed after restoring history \u2014 errorType=${M instanceof Error?M.name:typeof M}`),"failed"))}}}),{liveReady:S}}enqueueSessionLifecycle(A,y){const w=(this.sessionLifecycleOperations.get(A)||Promise.resolve()).catch(()=>{}).then(y),T=w.then(()=>{},()=>{});return this.sessionLifecycleOperations.set(A,T),T.then(()=>{this.sessionLifecycleOperations.get(A)===T&&this.sessionLifecycleOperations.delete(A)}),w}restoreLoadedSession(A,y,S){var w,T,I;const D=this.preserveExistingUsersWhenSnapshotOmitsThem(y,S),R=this.getExistingTitleForLoadedSession(A,S),M=R&&(!D.title||this.isLikelyAcpContextTitle(D.title))?{...D,title:R}:D,O={...M,extension:M.extension?{...M.extension,acpTarget:(w=M.extension.acpTarget)!==null&&w!==void 0?w:S?.acpTarget}:S?.acpTarget?{availableCommands:[],acpTarget:S.acpTarget}:void 0},[x]=this.fromAcpJSON([O]);x&&(!((T=y.extension)===null||T===void 0)&&T.availableCommands&&this.getAvailableCommandsBySession().set(A,y.extension.availableCommands),this.setSessionPreservingOrder(A,x),this.metadataOnlySessionIds.delete(A),this.listenSession(x),S&&S!==x&&((I=this.onDidApplySessionStateEmitter)===null||I===void 0||I.fire({sessionId:A,model:x,modelReplaced:!0})),!S&&x.title&&x.title!==g&&!this.isLikelyAcpContextTitle(x.title)&&this.setDisplayTitleOverride(A,x.title))}preserveExistingUsersWhenSnapshotOmitsThem(A,y){const S=A.history.messages;if(!y||S.some(K=>K.role===1))return A;const w=y.history.getMessages();if(!w.some(K=>K.role===1))return A;const T=()=>{const K=this.toSessionData(y);return{...A,history:{...A.history,messages:K.history.messages.map(W=>({...W}))},requests:K.requests}},I=w.filter(K=>K.role===1),D=new Set(S.map(K=>K.relationId).filter(K=>!!K)),R=new Map,M=I.filter(K=>!K.relationId);I.forEach(K=>{if(!K.relationId)return;const W=R.get(K.relationId)||[];W.push(K),R.set(K.relationId,W)});const O=I.length===1&&M.length===1&&S.length===1&&A.requests.length===1;if(!O&&M.length>0||Array.from(R.keys()).some(K=>!D.has(K)))return T();const x=new Set,k=S.flatMap(K=>{const W=K.relationId?R.get(K.relationId):void 0;return W&&K.relationId&&!x.has(K.relationId)?(x.add(K.relationId),[...W.map(U=>({...U})),{...K}]):O?[{...M[0]},{...K}]:[{...K}]}),N=y.requests,L=new Map(N.map(K=>[K.requestId,K])),B=N.length===1&&A.requests.length===1;return{...A,history:{...A.history,messages:k.map((K,W)=>({...K,order:W}))},requests:A.requests.map(K=>{const W=L.get(K.requestId)||(B?N[0]:void 0);return K.message.prompt||!W?.message.prompt?K:{...K,message:{...K.message,prompt:W.message.prompt}}})}}getSessionAttachments(){return this.sessionAttachments||(this.sessionAttachments=new Map),this.sessionAttachments}observeSessionAttachment(A,y){const S=this.getSessionAttachments(),w=S.get(A);w&&(w.disposables.forEach(M=>M.dispose()),w.stream.end());const T=M=>{const O=this.getSession(A);if(O&&(O.setThreadStatus(M),!(0,u.isAcpResponsePending)(M))){const x=O.requests[O.requests.length-1];x&&!x.response.isComplete&&x.response.complete()}},I=[],D=()=>{var M;((M=S.get(A))===null||M===void 0?void 0:M.stream)===y&&S.delete(A),I.splice(0).forEach(O=>O.dispose())},R=M=>{var O;const x=M();((O=S.get(A))===null||O===void 0?void 0:O.stream)!==y?x.dispose():I.push(x)};S.set(A,{stream:y,disposables:I}),R(()=>y.onData(M=>{var O,x;if(M.kind==="sessionSnapshot"){const L=(x=(O=this.mainProvider)===null||O===void 0?void 0:O.restoreSessionSnapshot)===null||x===void 0?void 0:x.call(O,A,M);L&&this.restoreLoadedSession(A,L,this.peekSession(A)),T(M.threadStatus),this.applySessionStateUpdate(A,{currentModeId:M.currentModeId,currentModelId:M.currentModelId,configOptions:M.configOptions,availableCommands:M.availableCommands});return}if(M.kind==="threadStatus"){T(M.threadStatus);return}if(M.kind==="sessionState"){this.applySessionStateUpdate(A,M);return}const k=this.getSession(A),N=k?.requests[k.requests.length-1];k&&N&&!N.response.isComplete&&k.acceptResponseProgress(N,M)})),R(()=>y.onEnd(D)),R(()=>y.onError(D))}createRequest(A,y,S,w,T){var I,D,R,M;const O=this.getSession(A),x=this.aiNativeConfig.capabilities.supportsAgentMode&&!this.getDisplayTitleOverride(A)&&O&&(O.history.getMessages().length===0&&O.requests.length===0||this.isLikelyAcpContextTitle(O.title));this.logger.log(`[ACP Chat][Manager] createRequest start \u2014 sessionId=${A}, agentId=${S||"(empty)"}, command=${w||"(empty)"}, messageChars=${y.length}, images=${(I=T?.length)!==null&&I!==void 0?I:0}, existingRequests=${(D=O?.requests.length)!==null&&D!==void 0?D:0}, historyMessages=${(R=O?.history.getMessages().length)!==null&&R!==void 0?R:0}`);const k=super.createRequest(A,y,S,w,T);return this.logger.log(`[ACP Chat][Manager] createRequest ${k?"done":"skipped"} \u2014 sessionId=${A}, requestId=${(M=k?.requestId)!==null&&M!==void 0?M:"(empty)"}`),k&&x&&this.setDisplayTitleOverride(A,y),k}async sendRequest(A,y,S,w){var T,I;this.logger.log(`[ACP Chat][Manager] sendRequest start \u2014 sessionId=${A}, requestId=${y.requestId}, regenerate=${S}, agentId=${y.message.agentId}, command=${y.message.command||"(empty)"}, messageChars=${y.message.prompt.length}, images=${(I=(T=y.message.images)===null||T===void 0?void 0:T.length)!==null&&I!==void 0?I:0}`);try{await super.sendRequest(A,y,S,w),this.logger.log(`[ACP Chat][Manager] sendRequest done \u2014 sessionId=${A}, requestId=${y.requestId}`)}catch(D){const R=D instanceof Error?D.message:String(D);throw this.logger.error(`[ACP Chat][Manager] sendRequest error \u2014 sessionId=${A}, requestId=${y.requestId}, error=${R}`),D}}cancelRequest(A){var y;if(super.cancelRequest(A))return!0;const w=this.getSession(A);return!w||!(0,u.isAcpCancellationAllowed)(w.threadStatus)||!(!((y=this.mainProvider)===null||y===void 0)&&y.cancelSession)?!1:(this.mainProvider.cancelSession(A).catch(T=>{const I=T instanceof Error?T.message:String(T);this.logger.error(`[ACP Chat][Manager] cancel attached session failed \u2014 sessionId=${A}, error=${I}`)}),!0)}shouldValidateModelChange(A){return!A.startsWith("acp:")}clearSession(A){var y;super.clearSession(A),(y=this.availableCommandsBySession)===null||y===void 0||y.delete(A),this.removeDisplayTitleOverride(A)}async disposeSession(A,y=!1){const S=this.sessionLoadGenerations.get(A)||0,w=this.sessionDisposeRequests.get(A);if(w?.generation===S)return w.promise;const I=this.enqueueSessionLifecycle(A,async()=>{var D,R,M,O,x,k;const N=(D=this.sessionAttachments)===null||D===void 0?void 0:D.get(A);if(N&&((R=this.sessionAttachments)===null||R===void 0||R.delete(A),N.disposables.forEach(L=>L.dispose()),N.stream.end()),!y&&!this.ownedBackendSessions.has(A)){this.getSession(A)&&this.clearSession(A);return}try{y?await((O=(M=this.mainProvider)===null||M===void 0?void 0:M.disposeSession)===null||O===void 0?void 0:O.call(M,A,!0)):await((k=(x=this.mainProvider)===null||x===void 0?void 0:x.disposeSession)===null||k===void 0?void 0:k.call(x,A)),this.ownedBackendSessions.delete(A)}finally{this.getSession(A)&&this.clearSession(A)}}).finally(()=>{var D;((D=this.sessionDisposeRequests.get(A))===null||D===void 0?void 0:D.promise)===I&&this.sessionDisposeRequests.delete(A)});return this.sessionDisposeRequests.set(A,{generation:S,promise:I}),I}applySessionStateUpdate(A,y){const S=A.startsWith("acp:")?A:`acp:${A}`;this.applyAgentSessionMetadataUpdate(S,y.title,y.updatedAt);const w=this.getSession(S);if(!w)return;const T=w.currentModeId;let I=!1;y.currentModeId!==void 0&&w.currentModeId!==y.currentModeId&&(w.currentModeId=y.currentModeId,I=!0),y.currentModelId!==void 0&&w.modelId!==y.currentModelId&&(w.modelId=y.currentModelId,I=!0),y.configOptions!==void 0&&(w.configOptions=y.configOptions,I=!0),y.availableCommands!==void 0&&(this.getAvailableCommandsBySession().set(S,y.availableCommands),I=!0),y.title!==void 0&&w.title!==(y.title||"")&&(w.setTitle(y.title||""),I=!0),I&&this.onDidApplySessionStateEmitter.fire({sessionId:S,model:w,previousModeId:T,currentModeId:w.currentModeId,availableCommands:y.availableCommands})}applyAgentSessionMetadataUpdate(A,y,S){if(y===void 0&&S===void 0)return;const w=this.agentSessionMetadataUpdates.get(A);this.agentSessionMetadataUpdates.set(A,{revision:++this.agentSessionMetadataRevision,...y!==void 0?{title:y}:w?.title!==void 0?{title:w.title}:{},...S!==void 0?{updatedAt:S}:w?.updatedAt!==void 0?{updatedAt:w.updatedAt}:{}});const T=this.agentSessionCatalog.findIndex(R=>R.sessionId===A);if(T===-1)return;const D={...this.agentSessionCatalog[T],...y!==void 0?{title:y||void 0}:{},...S!==void 0?{updatedAt:S||void 0}:{}};this.agentSessionCatalog=this.agentSessionCatalog.map((R,M)=>M===T?D:R),this.onDidChangeAgentSessionCatalogEmitter.fire(this.getAgentSessionCatalog())}fallbackToLocal(){const A=this.sessionProviderRegistry.getProvider("local");A&&(this.localFallbackActive=!0,this.mainProvider=A,this.sessionModels.clear(),this.loadSessionList())}toSessionData(A){return{sessionId:A.sessionId,createdAt:A.createdAt,modelId:A.modelId,history:A.history.toJSON(),title:A.title,requests:A.getRequests().map(y=>({requestId:y.requestId,message:y.message,response:{isCanceled:y.response.isCanceled,isComplete:y.response.isComplete,responseText:y.response.responseText,responseContents:y.response.responseContents,responseParts:y.response.responseParts,errorDetails:y.response.errorDetails,followups:y.response.followups}}))}}fromAcpJSON(A){return A.filter(y=>y.history.messages.length>0||y.sessionId.startsWith("acp:")).map(y=>{var S;const w=new a.ChatModel(this.chatFeatureRegistry,{sessionId:y.sessionId,createdAt:y.createdAt,history:new p.MsgHistoryManager(this.chatFeatureRegistry,y.history),modelId:y.modelId,title:this.resolveAcpSessionTitle(y),agentModes:y.agentModes,currentModeId:y.currentModeId,agentModels:y.agentModels,configOptions:y.configOptions,acpTarget:(S=y.extension)===null||S===void 0?void 0:S.acpTarget}),T=y.requests.map(I=>{var D;return new a.ChatRequestModel(I.requestId,w,I.message,new a.ChatResponseModel(I.requestId,w,I.message.agentId,{responseContents:I.response.responseContents,isComplete:(D=I.response.isComplete)!==null&&D!==void 0?D:!0,responseText:I.response.responseText,responseParts:I.response.responseParts,errorDetails:I.response.errorDetails,followups:I.response.followups,isCanceled:I.response.isCanceled}))});return w.restoreRequests(T),w})}async saveSessions(){var A;if(!(!((A=this.mainProvider)===null||A===void 0)&&A.saveSessions))return;const y=this.getSessions().map(S=>this.toSessionData(S));await this.mainProvider.saveSessions(y)}dispose(){var A,y;(A=this.sessionAttachments)===null||A===void 0||A.forEach(({stream:S,disposables:w})=>{w.forEach(T=>T.dispose()),S.end()}),(y=this.sessionAttachments)===null||y===void 0||y.clear(),super.dispose()}};t.AcpChatManagerService=h,n.__decorate([(0,r.Autowired)(o.AINativeConfigService),n.__metadata("design:type",o.AINativeConfigService)],h.prototype,"aiNativeConfig",void 0),n.__decorate([(0,r.Autowired)(o.ILogger),n.__metadata("design:type",Object)],h.prototype,"logger",void 0),n.__decorate([(0,r.Autowired)(s.ISessionProviderRegistry),n.__metadata("design:type",Object)],h.prototype,"sessionProviderRegistry",void 0),n.__decorate([(0,r.Autowired)(c.StorageProvider),n.__metadata("design:type",Function)],h.prototype,"acpStorageProvider",void 0),n.__decorate([(0,c.debounce)(1e3),n.__metadata("design:type",Function),n.__metadata("design:paramtypes",[]),n.__metadata("design:returntype",Promise)],h.prototype,"saveSessions",null),t.AcpChatManagerService=h=n.__decorate([(0,r.Injectable)(),n.__metadata("design:paramtypes",[])],h)},61282:(P,t,e)=>{"use strict";var n;Object.defineProperty(t,"__esModule",{value:!0}),t.ChatManagerService=void 0;const r=e(85608),o=e(76003),c=e(41869),_=e(43718),v=e(65677),p=e(19413),f=e(44260),a=e(42033),u=e(11735),s=20;function l(E){return E instanceof Error?E.message:String(E)}class d extends _.LRUCache{disposeKey(m){const h=this.get(m);h&&h.dispose(),this.delete(m)}dispose(){this.forEach(m=>{m.dispose()}),this.clear()}}let g=class extends _.Disposable{fromJSON(m){return m.filter(h=>h.history.messages.length>0).map(h=>{const b=new a.ChatModel(this.chatFeatureRegistry,{sessionId:h.sessionId,createdAt:h.createdAt,history:new f.MsgHistoryManager(this.chatFeatureRegistry,h.history),modelId:h.modelId}),A=h.requests.map(y=>new a.ChatRequestModel(y.requestId,b,y.message,new a.ChatResponseModel(y.requestId,b,y.message.agentId,{responseContents:y.response.responseContents,isComplete:!0,responseText:y.response.responseText,responseParts:y.response.responseParts,errorDetails:y.response.errorDetails,followups:y.response.followups,isCanceled:y.response.isCanceled})));return b.restoreRequests(A),b})}constructor(){super(),this.sessionModels=this.registerDispose(new d(s)),n.set(this,this.registerDispose(new _.DisposableMap)),this.storageInitEmitter=new _.Emitter,this.onStorageInit=this.storageInitEmitter.event}async init(){this._chatStorage=await this.storageProvider(_.STORAGE_NAMESPACE.CHAT);const m=this._chatStorage.get("sessionModels",[]);this.fromJSON(m).forEach(b=>{this.sessionModels.set(b.sessionId,b),this.listenSession(b)}),await this.storageInitEmitter.fireAndAwait()}getSessions(){return Array.from(this.sessionModels.values())}async startSession(){const m=new a.ChatModel(this.chatFeatureRegistry);return this.sessionModels.set(m.sessionId,m),this.listenSession(m),m}getSession(m){return this.sessionModels.get(m)}clearSession(m){var h;if(!this.sessionModels.get(m))throw new Error(`Unknown session: ${m}`);this.sessionModels.disposeKey(m),(h=r.__classPrivateFieldGet(this,n,"f").get(m))===null||h===void 0||h.cancel(),r.__classPrivateFieldGet(this,n,"f").disposeKey(m),this.saveSessions()}createRequest(m,h,b,A,y){const S=this.getSession(m);if(!S)throw new Error(`Unknown session: ${m}`);if(!r.__classPrivateFieldGet(this,n,"f").has(m))return S.addRequest({prompt:h,agentId:b,command:A,images:y})}async sendRequest(m,h,b,A){var y,S;const w=Date.now();this.logger.log(`[ChatManagerService] sendRequest enter \u2014 sessionId=${m}, requestId=${h.requestId}, agentId=${h.message.agentId}, command=${h.message.command||"(empty)"}, regenerate=${!!b}`);const T=this.getSession(m);if(!T)throw this.logger.error(`[ChatManagerService] sendRequest missing model \u2014 sessionId=${m}, requestId=${h.requestId}`),new Error(`Unknown session: ${m}`);this.logger.log(`[ChatManagerService] sendRequest model resolved \u2014 sessionId=${m}, requestId=${h.requestId}, requests=${T.requests.length}, historyMessages=${T.history.getMessages().length}`);const I=T.modelId,D=this.preferenceService.get(_.AINativeSettingSectionsId.ModelID);if(this.logger.log(`[ChatManagerService] sendRequest model preference \u2014 sessionId=${m}, requestId=${h.requestId}, savedModelId=${I||"(empty)"}, currentModelId=${D||"(empty)"}`),!I)T.modelId=D;else{if(I!==D&&this.shouldValidateModelChange(m,T))throw this.logger.error(`[ChatManagerService] sendRequest model changed \u2014 sessionId=${m}, requestId=${h.requestId}, savedModelId=${I||"(empty)"}, currentModelId=${D||"(empty)"}`),new Error("Model changed unexpectedly");I!==D&&this.logger.log(`[ChatManagerService] sendRequest model change allowed \u2014 sessionId=${m}, requestId=${h.requestId}, savedModelId=${I||"(empty)"}, currentModelId=${D||"(empty)"}`)}const R=new _.CancellationTokenSource,M=R.token;r.__classPrivateFieldGet(this,n,"f").set(T.sessionId,R),this.logger.log(`[ChatManagerService] sendRequest pending registered \u2014 sessionId=${m}, requestId=${h.requestId}`);const O=M.onCancellationRequested(()=>{this.logger.log(`[ChatManagerService] sendRequest cancellation requested \u2014 sessionId=${m}, requestId=${h.requestId}`),h.response.cancel()}),x=this.preferenceService.get(_.AINativeSettingSectionsId.ContextWindow);this.logger.log(`[ChatManagerService] sendRequest history start \u2014 sessionId=${m}, requestId=${h.requestId}, contextWindow=${x}`);const k=T.getMessageHistory(x);this.logger.log(`[ChatManagerService] sendRequest history done \u2014 sessionId=${m}, requestId=${h.requestId}, historyMessages=${k.length}`);try{const N=K=>{if(!M.isCancellationRequested){if(K.kind==="requestAccepted"){A?.();return}T.acceptResponseProgress(h,K)}};this.logger.log(`[ChatManagerService] sendRequest progress callback ready \u2014 sessionId=${m}, requestId=${h.requestId}`);const L={sessionId:m,requestId:h.requestId,message:h.message.prompt,command:h.message.command,images:h.message.images,regenerate:b};this.logger.log(`[ChatManagerService] sendRequest invokeAgent before \u2014 sessionId=${m}, requestId=${h.requestId}, agentId=${h.message.agentId}, messageChars=${L.message.length}, historyMessages=${k.length}, chatAgentService=${((S=(y=this.chatAgentService)===null||y===void 0?void 0:y.constructor)===null||S===void 0?void 0:S.name)||"(unknown)"}`);const B=await this.chatAgentService.invokeAgent(h.message.agentId,L,N,k,M);if(this.logger.log(`[ChatManagerService] sendRequest invokeAgent after \u2014 sessionId=${m}, requestId=${h.requestId}, elapsedMs=${Date.now()-w}, hasErrorDetails=${!!B.errorDetails}`),!M.isCancellationRequested){if(B.errorDetails){h.response.setErrorDetails(B.errorDetails),h.response.complete();return}this.chatAgentService.getFollowups(h.message.agentId,m,_.CancellationToken.None).then(W=>{h.response.setFollowups(W),h.response.complete()})}}catch(N){const L=l(N);this.logger.error(`[ChatManagerService] sendRequest error \u2014 sessionId=${m}, requestId=${h.requestId}, error=${L}`),M.isCancellationRequested||(h.response.setErrorDetails({message:L}),h.response.complete())}finally{this.logger.log(`[ChatManagerService] sendRequest cleanup \u2014 sessionId=${m}, requestId=${h.requestId}, elapsedMs=${Date.now()-w}, canceled=${M.isCancellationRequested}`),O.dispose(),r.__classPrivateFieldGet(this,n,"f").disposeKey(T.sessionId),this.saveSessions()}}shouldValidateModelChange(m,h){return!0}listenSession(m){this.addDispose(m.history.onMessageAdditionalChange(()=>{this.saveSessions()}))}saveSessions(){this._chatStorage.set("sessionModels",this.getSessions())}cancelRequest(m){const h=r.__classPrivateFieldGet(this,n,"f").get(m);return h?.cancel(),r.__classPrivateFieldGet(this,n,"f").disposeKey(m),this.saveSessions(),!!h}};t.ChatManagerService=g,n=new WeakMap,r.__decorate([(0,o.Autowired)(o.INJECTOR_TOKEN),r.__metadata("design:type",o.Injector)],g.prototype,"injector",void 0),r.__decorate([(0,o.Autowired)(p.IChatAgentService),r.__metadata("design:type",Object)],g.prototype,"chatAgentService",void 0),r.__decorate([(0,o.Autowired)(_.ILogger),r.__metadata("design:type",Object)],g.prototype,"logger",void 0),r.__decorate([(0,o.Autowired)(_.StorageProvider),r.__metadata("design:type",Function)],g.prototype,"storageProvider",void 0),r.__decorate([(0,o.Autowired)(c.PreferenceService),r.__metadata("design:type",Object)],g.prototype,"preferenceService",void 0),r.__decorate([(0,o.Autowired)(v.ChatFeatureRegistryToken),r.__metadata("design:type",u.ChatFeatureRegistry)],g.prototype,"chatFeatureRegistry",void 0),r.__decorate([(0,_.debounce)(1e3),r.__metadata("design:type",Function),r.__metadata("design:paramtypes",[]),r.__metadata("design:returntype",void 0)],g.prototype,"saveSessions",null),t.ChatManagerService=g=r.__decorate([(0,o.Injectable)(),r.__metadata("design:paramtypes",[])],g)},42033:(P,t,e)=>{"use strict";var n,r,o,c,_,v,p,f,a,u,s,l,d,g,E,m,h,b,A,y,S,w,T,I,D;Object.defineProperty(t,"__esModule",{value:!0}),t.ChatSlashCommandItemModel=t.ChatWelcomeMessageModel=t.ChatModel=t.ChatRequestModel=t.ChatResponseModel=void 0;const R=e(85608),M=e(76003),O=e(43718),x=e(90684),k=e(19413),N=e(44260);class L extends O.Disposable{get responseParts(){return R.__classPrivateFieldGet(this,r,"f")}get responseContents(){return R.__classPrivateFieldGet(this,o,"f")}get isComplete(){return R.__classPrivateFieldGet(this,c,"f")}get isCanceled(){return R.__classPrivateFieldGet(this,_,"f")}get requestId(){return R.__classPrivateFieldGet(this,v,"f")}get responseText(){return R.__classPrivateFieldGet(this,p,"f")}get safeProgress(){return R.__classPrivateFieldGet(this,f,"f")}get errorDetails(){return R.__classPrivateFieldGet(this,a,"f")}get followups(){return R.__classPrivateFieldGet(this,u,"f")}get onDidChange(){return R.__classPrivateFieldGet(this,s,"f").event}constructor(j,Y,z,V){super(),n.add(this),this.session=Y,this.agentId=z,r.set(this,[]),o.set(this,[]),c.set(this,!1),_.set(this,!1),v.set(this,void 0),p.set(this,""),f.set(this,void 0),a.set(this,void 0),u.set(this,void 0),s.set(this,this.registerDispose(new O.Emitter)),R.__classPrivateFieldSet(this,v,j,"f"),V&&(R.__classPrivateFieldSet(this,o,V.responseContents,"f"),R.__classPrivateFieldSet(this,r,V.responseParts||[],"f"),R.__classPrivateFieldSet(this,p,V.responseText,"f"),R.__classPrivateFieldSet(this,c,V.isComplete,"f"),R.__classPrivateFieldSet(this,_,V.isCanceled,"f"),R.__classPrivateFieldSet(this,a,V.errorDetails,"f"),R.__classPrivateFieldSet(this,u,V.followups,"f"))}updateContent(j,Y){var z;const V=R.__classPrivateFieldGet(this,r,"f").length-1;if(j.kind==="content"||j.kind==="markdownContent"){const $=R.__classPrivateFieldGet(this,r,"f")[V];!$||$.kind!=="markdownContent"?j.kind==="content"?R.__classPrivateFieldGet(this,r,"f").push({content:new x.MarkdownString(j.content),kind:"markdownContent"}):R.__classPrivateFieldGet(this,r,"f").push(j):j.kind==="markdownContent"?R.__classPrivateFieldGet(this,r,"f")[V]={content:new x.MarkdownString($.content.value+j.content.value),kind:"markdownContent"}:R.__classPrivateFieldGet(this,r,"f")[V]={content:new x.MarkdownString($.content.value+j.content,$.content),kind:"markdownContent"},R.__classPrivateFieldGet(this,n,"m",l).call(this)}else if(j.kind==="reasoning"){const $=R.__classPrivateFieldGet(this,r,"f")[V];!$||$.kind!=="reasoning"?R.__classPrivateFieldGet(this,r,"f").push({content:j.content.replace(/^<think>/,""),kind:"reasoning"}):R.__classPrivateFieldGet(this,r,"f")[V]={content:$.content+j.content,kind:"reasoning"},R.__classPrivateFieldGet(this,n,"m",l).call(this)}else if(j.kind==="asyncContent"){const $=R.__classPrivateFieldGet(this,r,"f").push(j)-1;R.__classPrivateFieldGet(this,n,"m",l).call(this),(z=j.resolvedContent)===null||z===void 0||z.then(H=>{typeof H=="string"?R.__classPrivateFieldGet(this,r,"f")[$]={content:new x.MarkdownString(H),kind:"markdownContent"}:(0,x.isMarkdownString)(H)?R.__classPrivateFieldGet(this,r,"f")[$]={content:H,kind:"markdownContent"}:R.__classPrivateFieldGet(this,r,"f")[$]=H,R.__classPrivateFieldGet(this,n,"m",l).call(this,Y)})}else if(j.kind==="treeData"||j.kind==="component")R.__classPrivateFieldGet(this,r,"f").push(j),R.__classPrivateFieldGet(this,n,"m",l).call(this,Y);else if(j.kind==="toolCall"){const $=R.__classPrivateFieldGet(this,r,"f").findIndex(H=>H.kind==="toolCall"&&H.content.id===j.content.id);$!==-1?R.__classPrivateFieldGet(this,r,"f")[$]={kind:"toolCall",content:{...j.content}}:R.__classPrivateFieldGet(this,r,"f").push(j),R.__classPrivateFieldGet(this,n,"m",l).call(this,Y)}}updateSafeProgress(j){var Y;const z=j?.content.trim()?j:void 0;((Y=R.__classPrivateFieldGet(this,f,"f"))===null||Y===void 0?void 0:Y.content)!==z?.content&&(R.__classPrivateFieldSet(this,f,z,"f"),R.__classPrivateFieldGet(this,s,"f").fire())}complete(){R.__classPrivateFieldSet(this,c,!0,"f"),R.__classPrivateFieldSet(this,f,void 0,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}cancel(){R.__classPrivateFieldSet(this,c,!0,"f"),R.__classPrivateFieldSet(this,_,!0,"f"),R.__classPrivateFieldSet(this,f,void 0,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}reset(){R.__classPrivateFieldSet(this,o,[],"f"),R.__classPrivateFieldSet(this,r,[],"f"),R.__classPrivateFieldSet(this,p,"","f"),R.__classPrivateFieldSet(this,f,void 0,"f"),R.__classPrivateFieldSet(this,_,!1,"f"),R.__classPrivateFieldSet(this,c,!1,"f"),R.__classPrivateFieldSet(this,a,void 0,"f"),R.__classPrivateFieldSet(this,u,void 0,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}setErrorDetails(j){R.__classPrivateFieldSet(this,a,j,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}setFollowups(j){R.__classPrivateFieldSet(this,u,j,"f"),R.__classPrivateFieldGet(this,s,"f").fire()}toJSON(){return{isCanceled:this.isCanceled,responseContents:this.responseContents,responseText:this.responseText,responseParts:this.responseParts,errorDetails:this.errorDetails,followups:this.followups}}}t.ChatResponseModel=L,r=new WeakMap,o=new WeakMap,c=new WeakMap,_=new WeakMap,v=new WeakMap,p=new WeakMap,f=new WeakMap,a=new WeakMap,u=new WeakMap,s=new WeakMap,n=new WeakSet,l=function(j){R.__classPrivateFieldSet(this,p,R.__classPrivateFieldGet(this,r,"f").map(z=>z.kind==="asyncContent"?z.content:z.kind==="treeData"||z.kind==="component"?"":z.kind==="toolCall"?z.content.function.name:z.kind==="reasoning"?"":z.content.value).join(`
39453
39453
 
39454
39454
  `),"f");const Y=[];for(const z of R.__classPrivateFieldGet(this,r,"f")){const V=Y[Y.length-1];z.kind==="markdownContent"&&V?.kind==="markdownContent"?Y[Y.length-1]={content:new x.MarkdownString(V.content.value+z.content.value,{isTrusted:V.content.isTrusted}),kind:"markdownContent"}:Y.push(z)}R.__classPrivateFieldSet(this,o,Y,"f"),j||R.__classPrivateFieldGet(this,s,"f").fire()};class B{get requestId(){return R.__classPrivateFieldGet(this,d,"f")}constructor(j,Y,z,V){this.session=Y,this.message=z,this.response=V,d.set(this,void 0),R.__classPrivateFieldSet(this,d,j,"f")}toJSON(){return{requestId:this.requestId,message:this.message,response:this.response}}}t.ChatRequestModel=B,d=new WeakMap;class K extends O.Disposable{constructor(j,Y){var z,V,$,H,Q,Z,te;super(),this.chatFeatureRegistry=j,this.requestIdPool=0,g.set(this,void 0),E.set(this,void 0),m.set(this,void 0),h.set(this,new Map),b.set(this,0),A.set(this,void 0),y.set(this,[]),S.set(this,void 0),w.set(this,[]),T.set(this,[]),I.set(this,"idle"),this._onThreadStatusChange=new O.Emitter,this.onThreadStatusChange=this._onThreadStatusChange.event,R.__classPrivateFieldSet(this,E,(z=Y?.sessionId)!==null&&z!==void 0?z:(0,O.uuid)(),"f"),R.__classPrivateFieldSet(this,m,(V=Y?.createdAt)!==null&&V!==void 0?V:Date.now(),"f"),this.history=($=Y?.history)!==null&&$!==void 0?$:new N.MsgHistoryManager(this.chatFeatureRegistry),R.__classPrivateFieldSet(this,A,Y?.modelId,"f"),R.__classPrivateFieldSet(this,g,(H=Y?.title)!==null&&H!==void 0?H:"","f"),R.__classPrivateFieldSet(this,y,(Q=Y?.agentModes)!==null&&Q!==void 0?Q:[],"f"),R.__classPrivateFieldSet(this,S,Y?.currentModeId,"f"),R.__classPrivateFieldSet(this,w,(Z=Y?.agentModels)!==null&&Z!==void 0?Z:[],"f"),R.__classPrivateFieldSet(this,T,(te=Y?.configOptions)!==null&&te!==void 0?te:[],"f"),this.acpTarget=Y?.acpTarget}get title(){return R.__classPrivateFieldGet(this,g,"f")}setTitle(j){R.__classPrivateFieldSet(this,g,j,"f")}get sessionId(){return R.__classPrivateFieldGet(this,E,"f")}get createdAt(){return R.__classPrivateFieldGet(this,m,"f")}get requests(){return Array.from(R.__classPrivateFieldGet(this,h,"f").values())}restoreRequests(j){R.__classPrivateFieldSet(this,h,new Map(j.map(Y=>[Y.requestId,Y])),"f"),this.requestIdPool=j.length}get slicedMessageCount(){return R.__classPrivateFieldGet(this,b,"f")}get modelId(){return R.__classPrivateFieldGet(this,A,"f")}set modelId(j){R.__classPrivateFieldSet(this,A,j,"f")}get agentModes(){return R.__classPrivateFieldGet(this,y,"f")}set agentModes(j){R.__classPrivateFieldSet(this,y,j??[],"f")}get currentModeId(){return R.__classPrivateFieldGet(this,S,"f")}set currentModeId(j){R.__classPrivateFieldSet(this,S,j,"f")}get agentModels(){return R.__classPrivateFieldGet(this,w,"f")}set agentModels(j){R.__classPrivateFieldSet(this,w,j??[],"f")}get configOptions(){return R.__classPrivateFieldGet(this,T,"f")}set configOptions(j){R.__classPrivateFieldSet(this,T,j??[],"f")}get threadStatus(){return R.__classPrivateFieldGet(this,I,"f")}setThreadStatus(j){R.__classPrivateFieldGet(this,I,"f")!==j&&(R.__classPrivateFieldSet(this,I,j,"f"),this._onThreadStatusChange.fire(j))}processMemorySummaries(){const j=this.history.getMemorySummaries();if(j.length===0)return[];const Y=j.map(z=>{try{const V=JSON.parse(z.content);return V.memory||V.content||z.content}catch{return z.content}}).filter(z=>z&&z!=="no_memory_needed").filter((z,V,$)=>$.indexOf(z)===V);return Y.length>0?[{role:"system",content:`\u4EE5\u4E0B\u662F\u4E4B\u524D\u5BF9\u8BDD\u7684\u603B\u7ED3\uFF1A
39455
39455
  `+Y.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opensumi/cli-engine",
3
- "version": "3.9.1-next-1788150617.0",
3
+ "version": "3.9.1-next-1788263965.0",
4
4
  "description": "Integration engine runtime for opensumi-cli and opensumi extension",
5
5
  "license": "MIT",
6
6
  "files": [
@@ -26,14 +26,14 @@
26
26
  "dependencies": {
27
27
  "@koa/cors": "^5.0.0",
28
28
  "@opensumi/di": "^1.8.0",
29
- "@opensumi/ide-core-browser": "3.9.1-next-1788150617.0",
30
- "@opensumi/ide-core-common": "3.9.1-next-1788150617.0",
31
- "@opensumi/ide-core-node": "3.9.1-next-1788150617.0",
32
- "@opensumi/ide-express-file-server": "3.9.1-next-1788150617.0",
33
- "@opensumi/ide-extension": "3.9.1-next-1788150617.0",
34
- "@opensumi/ide-i18n": "3.9.1-next-1788150617.0",
35
- "@opensumi/ide-main-layout": "3.9.1-next-1788150617.0",
36
- "@opensumi/ide-startup": "3.9.1-next-1788150617.0",
29
+ "@opensumi/ide-core-browser": "3.9.1-next-1788263965.0",
30
+ "@opensumi/ide-core-common": "3.9.1-next-1788263965.0",
31
+ "@opensumi/ide-core-node": "3.9.1-next-1788263965.0",
32
+ "@opensumi/ide-express-file-server": "3.9.1-next-1788263965.0",
33
+ "@opensumi/ide-extension": "3.9.1-next-1788263965.0",
34
+ "@opensumi/ide-i18n": "3.9.1-next-1788263965.0",
35
+ "@opensumi/ide-main-layout": "3.9.1-next-1788263965.0",
36
+ "@opensumi/ide-startup": "3.9.1-next-1788263965.0",
37
37
  "chalk": "^4.1.2",
38
38
  "ejs": "^3.1.7",
39
39
  "ip": "^1.1.8",
@@ -72,5 +72,5 @@
72
72
  "webpack": "^5.90.0",
73
73
  "webpack-cli": "^5.1.4"
74
74
  },
75
- "gitHead": "0ebb1920a1ebb0cb2e21ee67d4904a9d80527e55"
75
+ "gitHead": "dd6615ecf24b8ccaca8615e4ed17b94f95b12239"
76
76
  }