"use strict";const T=require("vscode-uri"),Ae=require("./workspace-connection-impl-Fos0R9J1.cjs"),Te=require("path"),p=require("./logger-BN0ZR9CS.cjs"),z=require("./get-user-input-D6l3Y8vJ.cjs");require("./prompt-DKJV0_RD.cjs");const C=require("zod");require("os");const R=require("crypto");require("dedent");const u=require("./shared-types-B8BH5zz1.cjs");require("zod-stream");require("./number-coercion-Ce_kJ-2m.cjs");const w=require("./disclose-context-DDXHbF-P.cjs"),be=require("./remote-tools-discovery-DBq59ABk.cjs"),U=require("./pruning-service-DXWqhVdA.cjs"),_=require("./telemetry-C8yrvnwb.cjs"),x=require("./validate-file-modification-Bfx5eHzx.cjs"),se=require("./tool-tags-D59Uxdr-.cjs"),ke=require("./spec/tasks/index.cjs"),V=require("./index-_uSxrVd8.cjs"),j=require("./pending-changes-DJpAX0cK.cjs"),ve=require("fs"),xe=require("./cancellation-DiXZPuOm.cjs"),O=require("./session-update-utils-CNIxycOM.cjs"),v=require("@aws/codewhisperer-streaming-client"),oe=require("./q-developer-converse-CmJA6Lhm.cjs"),Ee=require("./types-Cb_u5eSG.cjs");function ne(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const s=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const A=ne(Te),Y=ne(ve),Ne=r=>typeof r=="object"&&r!==null,Oe=r=>typeof r=="object"&&r!==null&&"entries"in r,Re=r=>typeof r=="object"&&r!==null&&"type"in r&&"size"in r;class re{constructor(e,t,s){this.connection=e,this.sessionId=t,this.cwd=s}async readTextFile(e){return this.connection.readTextFile({sessionId:this.sessionId,path:this.resolvePath(e.path),line:e.line,limit:e.limit})}async writeTextFile(e){return this.connection.writeTextFile({sessionId:this.sessionId,path:this.resolvePath(e.path),content:e.content})}async stat(e){const s=await this.connection.extMethod("_kiro/fs/stat",{sessionId:this.sessionId,path:this.resolvePath(e)});if(!Re(s))throw new Error(`Invalid stat response: ${e}`);if(s.message)throw new Error(s.message);return{type:s.type}}async readDirectory(e){const s=await this.connection.extMethod("_kiro/fs/read_directory",{sessionId:this.sessionId,path:this.resolvePath(e)});if(!Oe(s))throw new Error(`Invalid readDirectory response: ${e}`);if(s.message)throw new Error(s.message);return s.entries.map(n=>({name:n.name,type:n.type}))}async exists(e){try{return await this.stat(e),!0}catch{return!1}}async delete(e){const s=await this.connection.extMethod("_kiro/fs/delete",{sessionId:this.sessionId,path:this.resolvePath(e)});if(!Ne(s))throw new Error(`Invalid delete response: ${e}`);if(s.message)throw new Error(s.message)}resolvePath(e){return e.startsWith("/")||e.startsWith("~")?e:`${this.cwd}/${e}`}}class ie{constructor(e,t){this.connection=e,this.sessionId=t}processes=new Map;terminalHandles=new Map;async startProcess(e,t,s){for(const[a,c]of this.processes)if(c.command===t&&c.cwd===s&&c.status==="running")return{terminalId:a,isReused:!0,status:"running"};const n=t.split(/\s+/),o=await this.connection.createTerminal({sessionId:this.sessionId,command:n[0],args:n.slice(1),cwd:s}),i=`term_${Date.now()}_${Math.random().toString(36).slice(2)}`;return this.processes.set(i,{command:t,cwd:s,status:"running"}),this.terminalHandles.set(i,o),{terminalId:i,isReused:!1,status:"running"}}async stopProcess(e,t){const s=this.processes.get(t),n=this.terminalHandles.get(t);s&&n&&(await n.kill(),await n.release(),s.status="stopped")}async getProcessOutput(e,t,s){const n=this.terminalHandles.get(t);if(!n)return"";const o=await n.currentOutput();return s&&s>0?o.output.split(`
`).slice(-s).join(`
`):o.output}getProcess(e){const t=this.processes.get(e);if(t)return{terminalId:e,...t}}listProcesses(){return Array.from(this.processes.entries()).map(([e,t])=>({terminalId:e,...t}))}openTerminal(e){}}function Me(r,e,t){const s=r.split(`
`),n=e.start?.line??0,o=e.start?.character??0,i=e.end?.line??s.length-1,a=e.end?.character??(s[i]?s[i].length:0),c=s.slice(0,n).join(`
`)+(n>0?`
`:"")+s[n].slice(0,o),l=(s[i]?.slice(a)??"")+(i<s.length-1?`
`+s.slice(i+1).join(`
`):"");return c+t+l}const Ue={ts:"typescript",tsx:"typescriptreact",js:"javascript",jsx:"javascriptreact",py:"python",rs:"rust",go:"go",java:"java",rb:"ruby",md:"markdown",json:"json",yaml:"yaml",yml:"yaml"};function _e(r){const e=r.split(".").pop()?.toLowerCase()??"";return Ue[e]??"plaintext"}class ae{constructor(e,t,s,n){this.persistence=e,this.fs=t,this.sessionId=s,this.workspacePaths=n}async checkpointFile(e){if(!this.persistence)return p.logger.debug("[ACPCheckpointProvider] No persistence available, returning no-op checkpoint"),{commitId:"acp-no-checkpoint",uri:e.fileUri};const t=this.toRelativePath(e.fileUri.fsPath);let s;try{s=(await this.fs.readTextFile({path:e.fileUri.fsPath})).content}catch{s=""}const n=await this.persistence.snapshotFile(this.sessionId,this.workspacePaths,t,s);p.logger.debug(`[ACPCheckpointProvider] Created snapshot ${n.snapshotId} for ${t} (${s.length} bytes)`);const o=T.URI.parse(`kiro-snapshot:///${t}?snapshotId=${n.snapshotId}&sessionId=${this.sessionId}`);return{commitId:n.snapshotId,uri:o}}toRelativePath(e){const t=[...this.workspacePaths].sort((s,n)=>n.length-s.length);for(const s of t)if(e.startsWith(s))return e.slice(s.length+1);return e}}class ce{constructor(e,t,s){this.connection=e,this.sessionId=t,this.checkpointProvider=s}async readFileWithMetadata(e){const t=e.uri.fsPath,s=await this.connection.readTextFile({sessionId:this.sessionId,path:t,line:e.range?.start.line,limit:e.range?e.range.end.line-e.range.start.line+1:void 0});return{content:{text:s.content,range:e.range??{start:{line:0,character:0},end:{line:s.content.split(`
`).length-1,character:0}}},metadata:{language:_e(t),problems:[]}}}async writeFileWithStreaming(e){const t=e.uri.fsPath,s=this.checkpointProvider;let n;if(s&&!e.skipCheckpointing)try{n=await s.checkpointFile({fileUri:e.uri,filePath:t})}catch{}const o=(async()=>{let i;if(typeof e.text=="string")i=e.text;else{const l=[];for await(const d of e.text)l.push(d);i=l.join("")}let a;if(e.range){const l=await this.connection.readTextFile({sessionId:this.sessionId,path:t});a=Me(l.content,e.range,i)}else a=i;await this.connection.writeTextFile({sessionId:this.sessionId,path:t,content:a});let c;if(s&&!e.skipCheckpointing)try{c=await s.checkpointFile({fileUri:e.uri,filePath:t})}catch{}return{endCursorPosition:{line:a.split(`
`).length-1,character:0},checkpointUri:c?.uri??e.uri}})();return{original:n?.uri,modified:e.uri,write:o}}notifyFilesCreated(){}notifyFilesDeleted(){}}class D{workspacePaths;constructor(e){this.workspacePaths=e}resolveRelativePath(e){if(A.isAbsolute(e)||e.startsWith("~"))return Promise.resolve(T.URI.file(e));if(this.workspacePaths.length===1)return Promise.resolve(T.URI.file(A.join(this.workspacePaths[0],e)));for(const t of this.workspacePaths){const s=A.basename(t),o=A.normalize(e).split(A.sep);if(o[0]===s){const i=o.slice(1).join(A.sep);return Promise.resolve(T.URI.file(A.join(t,i)))}}return Promise.resolve(T.URI.file(A.join(this.workspacePaths[0],e)))}asRelativePath(e){const t=e.path,s=[...this.workspacePaths].sort((n,o)=>o.length-n.length);for(const n of s){const o=T.URI.file(n).path;if(t.startsWith(o+"/"))return t.slice(o.length+1);if(t===o)return""}return e.fsPath}}class le{constructor(e,t){this.connection=e,this.sessionId=t}nextId=1;getOrCreateTerminal(e){const t=this.nextId++;return Promise.resolve(new Fe(this.connection,this.sessionId,t,e.cwd))}}class Fe{constructor(e,t,s,n){this.connection=e,this.sessionId=t,this.id=s,this.cwd=n}isBusy=!1;isClosed=!1;async runCommand(e,t){const s=e.split(/\s+/),n=await this.connection.createTerminal({sessionId:this.sessionId,command:s[0],args:s.slice(1),cwd:this.cwd}),o=await n.waitForExit(),i=await n.currentOutput();return await n.release(),{output:i.output,exitCode:o.exitCode??void 0,terminalId:this.id}}readOutputLines(){return""}ensureCommandRunsInCwd(e,t){return e}close(){}focus(){}}function $e(){return new w.FsWrite({validateContent:x.validateContent,getStreamingTextPadForValidation:x.getStreamingTextPadForValidation})}function qe(){return new w.FsAppend({validateContent:x.validateContent,getStreamingTextPadForValidation:x.getStreamingTextPadForValidation})}function je(){return new w.StrReplace({validateContent:x.validateContent,getStreamingTextPadForValidation:x.getStreamingTextPadForValidation})}function De(){return new w.DeleteFile({promptUser:()=>(p.logger.warn("[ACP] DeleteFile promptUser called - auto-accepting in ACP mode"),Promise.resolve("accept"))})}function de(){return new w.ListDirectory({})}function ue(){return new w.ReadFile({pruneFileContent:async(r,e,t,s,n)=>{try{const o=await U.PruningService.pruneContent({content:r,contentType:U.ContentType.Code,contextIdentifier:e,pruningReasoning:t,skipPruning:s,signal:n});return o.wasPruned?o.prunedContent:r}catch{return r}}})}function pe(){return new w.ReadMultipleFiles({pruneFileContent:async(r,e,t,s,n)=>{try{const o=await U.PruningService.pruneContent({content:r,contentType:U.ContentType.Code,contextIdentifier:e,pruningReasoning:t,skipPruning:s,signal:n});return o.wasPruned?`${o.prunedContent}

<!-- File was automatically pruned from ${o.originalLength} to ${o.prunedLength} characters (${o.reductionPercentage.toFixed(1)}% reduction) based on context: "${t}" -->`:r}catch{return r}}})}function he(){return[de(),ue(),pe(),De(),$e(),qe(),je()]}const Le=_.getMetricReporterOrNoOp(u.TelemetryNamespace.Tool,"execute-bash"),We=_.getMetricReporterOrNoOp(u.TelemetryNamespace.Tool,"control-process");function ze(r){return new w.ExecuteBash({configuredTimeout:void 0,isSingleRootWorkspace:!0},{acpToolApproval:r,recordBashToolEvent:()=>{},recordMetricTrace:e=>Le.callWithTrace(e,()=>{})})}function Be(r,e,t){return new w.ControlProcess(r,e,{isSingleRootWorkspace:!0},{acpToolApproval:t,validateFileAccess:()=>{},checkDirectoryExists:()=>Promise.resolve(!0),recordBashToolEvent:()=>{},recordMetricTrace:s=>We.callWithTrace(s,()=>{})})}function He(r,e){return new w.ListProcesses(r,e)}function Ge(r,e){return new w.GetProcessOutput(r,e)}function ge(r,e,t){return[ze(t),Be(r,e,t),He(r,e),Ge(r,e)]}function Ke(r){return new w.WebFetch({acpToolApproval:r,userAgent:"KiroACP"})}function Qe(r,e){const t=[];return e&&t.push(...e.getCachedTools()),t.push(Ke(r)),t}function L(r,e,t,s){return[...he(),...ge(r,e,t),...Qe(t,s)]}function M(r,e=!1,t){return new w.InvokeSubAgent({registry:r,generateOperationId:s=>`${s}_${R.randomUUID()}`,contextProviderRegistry:t},e)}const Ve={isToolTrusted:()=>!0,trustTool:()=>Promise.resolve(),trustWebTools:()=>Promise.resolve()};function me(r){return{mcpClient:r,toolTrustManager:Ve,awaitCommandApproval:()=>Promise.resolve("accept")}}function Ye(r){return new be.RemoteToolsDiscovery({mcpClient:r,createToolOptions:()=>me(r)})}function Je(){return new w.ReportProgress}function Xe(){return new w.SubagentResponse}function we(){return[Je(),Xe()]}function J(r){return new w.DiscloseContext(r)}function Ze(r,e){return{async findFiles(t,s,n){try{return(await r.extMethod("_kiro/search/find_files",{sessionId:e,pattern:t,exclude:s??void 0,maxResults:n})).files}catch(o){return p.logger.warn("[ACP FileSearch] extMethod call failed:",o),[]}}}}function et(r,e){return{async search(t){try{return(await r.extMethod("_kiro/search/text_search",{sessionId:e,pattern:t.pattern,caseSensitive:t.caseSensitive,includePattern:t.includePattern,excludePattern:t.excludePattern})).matches}catch(s){return p.logger.warn("[ACP GrepSearch] extMethod call failed:",s),[]}}}}class B extends z.SyncTool{constructor(e,t){super({id:e.sanitizedUniqueName,description:e.description||`Use the ${e.toolName} tool`,schema:e.inputSchema,validationSchema:C.z.object({}),tags:[`@${e.serverName}/${e.toolName}`,`@${e.serverName}`,se.ToolTags.MCP]}),this.toolConfig=e,this.getConnection=t}async handle({input:e,state:t,toolUse:s}){const n=this.getConnection(this.toolConfig.serverName);if(!n)return this.withSyncToolMessage(t,s,`MCP server "${this.toolConfig.serverName}" is not connected`,!1);try{const o={...e};delete o._meta;const i=await n.mcpClient.callTool({name:this.toolConfig.toolName,arguments:o}),a="content"in i&&Array.isArray(i.content)?i.content:[],{textResults:c,imageBase64UrlResults:l}=B.parseResponseContent(a),d=c.join(`
`);return i.isError?this.withSyncToolMessage(t,s,`MCP tool error: ${d}`,!1):this.withSyncToolMessage(t,s,d,!0,l.length>0?l:void 0)}catch(o){const i=o instanceof Error?o.message:String(o);return p.logger.error(`[MCP] [${this.toolConfig.serverName}] Tool call failed: ${i}`),this.withSyncToolMessage(t,s,`MCP tool call failed: ${i}`,!1)}}static parseResponseContent(e){const t=[],s=[];for(const n of e){if(typeof n!="object"||n===null||!("type"in n))continue;const o=n;switch(o.type){case"text":typeof o.text=="string"&&t.push(o.text);break;case"image":typeof o.mimeType=="string"&&typeof o.data=="string"&&s.push(`data:${o.mimeType};base64,${o.data}`);break;case"resource":{const i=o.resource;if(!i)break;if(typeof i.text=="string")t.push(i.text);else if(typeof i.blob=="string"){const a=i.mimeType;a?.startsWith("image/")?s.push(`data:${a};base64,${i.blob}`):a?.startsWith("text/")||a==="application/json"?t.push(Buffer.from(i.blob,"base64").toString("utf-8")):p.logger.error(`[MCP] Unsupported resource mime type: ${a}`)}break}default:p.logger.error(`[MCP] Unsupported response content type: ${String(o.type)}`);break}}return{textResults:t,imageBase64UrlResults:s}}}class tt{constructor(e,t,s,n){this.provider=e,this.persistence=t,this.sessionId=s,this.workspacePaths=n}async commitFile(e,t){const s=await this.provider.checkpointFile({fileUri:t,filePath:t.fsPath});return{commitId:s.commitId,uri:s.uri}}async getFileContentAtCommit(e,t){return this.persistence?await this.persistence.getSnapshotContent(this.sessionId,this.workspacePaths,t,e)??void 0:void 0}buildDiffUri(e,t,s){const n=e.startsWith("/")?e:"/"+e;return T.URI.from({scheme:"kiro-snapshot",path:n,query:`snapshotId=${t}&executionId=${s}`})}}class st{constructor(e,t,s,n,o){this.fs=e,this.resolver=t,this.persistence=s,this.sessionId=n,this.workspacePaths=o}async readFile(e){if(e.scheme==="kiro-snapshot"&&this.persistence){const s=new URLSearchParams(e.query).get("snapshotId"),n=e.path.startsWith("/")?e.path.substring(1):e.path;if(s){const o=await this.persistence.getSnapshotContent(this.sessionId,this.workspacePaths,s,n);return new TextEncoder().encode(o??"")}}const t=await this.fs.readTextFile({path:e.fsPath});return new TextEncoder().encode(t.content)}async writeFile(e,t){const s=new TextDecoder().decode(t);await this.fs.writeTextFile({path:e.fsPath,content:s})}async deleteFile(e){await this.fs.delete(e.fsPath)}async rename(e,t){const s=await this.readFile(e);await this.writeFile(t,s),await this.deleteFile(e)}async exists(e){if(e.scheme==="kiro-snapshot"&&this.persistence){const t=new URLSearchParams(e.query).get("snapshotId"),s=e.path.startsWith("/")?e.path.substring(1):e.path;if(t)return await this.persistence.getSnapshotContent(this.sessionId,this.workspacePaths,t,s)!==null}return this.fs.exists(e.fsPath)}async resolveWorkspacePath(e){return this.resolver.resolveRelativePath(e)}}class fe{actions=new Map;trackAction(e,t){const s=this.actions.get(e)??[],n=s.findIndex(o=>o.actionId===t.actionId);n>=0?s[n]=t:s.push(t),this.actions.set(e,s)}getExecution(e){const t=this.actions.get(e);return Promise.resolve(t?{actions:t}:void 0)}clear(e){this.actions.delete(e)}}var ot=Object.defineProperty,nt=Object.getOwnPropertyDescriptor,rt=(r,e,t,s)=>{for(var n=nt(e,t),o=r.length-1,i;o>=0;o--)(i=r[o])&&(n=i(e,t,n)||n);return n&&ot(e,t,n),n};const it=C.z.object({action:C.z.enum(["list","activate","use","readSteering","configure"]).describe('The action to perform: "list" to discover installed powers, "activate" to get documentation, "use" to execute power tools, "readSteering" for guides, "configure" to open config file'),powerName:C.z.string().optional().nullable().describe("Name of the power (required for activate, use, readSteering actions; not used for list or configure)"),serverName:C.z.string().optional().nullable().describe("Name of the MCP server within the power (REQUIRED for use action - get from toolsByServer in activate response)"),toolName:C.z.string().optional().nullable().describe("Name of the tool to execute within the power (required for use action)"),arguments:C.z.record(C.z.any()).optional().nullable().describe("Arguments object for the tool being called (use action only, get schema from activate action)"),steeringFile:C.z.string().optional().nullable().describe("Name of the steering file to read (REQUIRED for readSteering action - get from steeringFiles array in activate response, including .md extension)")}),X=_.getMetricReporterOrNoOp(u.TelemetryNamespace.Tool,"Tool.KiroPowers");function Z(r,e){return`power-${r}-${e}`}const Se=class W extends z.SyncTool{static toolId="kiroPowers";powersManager;mcpManager;homeDir;constructor(e,t,s){super({id:W.toolId,description:W.generateDescription(e),schema:it,tags:[se.ToolTags.POWERS]}),this.powersManager=e,this.mcpManager=t,this.homeDir=s}static generateDescription(e){const t=e.getInstalledPowers();let s=`Tool to manage and use Kiro Powers.

**About Powers:** Powers package documentation, workflow guides (steering files), and optionally MCP servers. When a power includes MCP servers, their tools are accessed through this interface rather than exposed directly.

`;if(t.length===0)s+=`**Currently Installed Powers:** None

No powers are installed. Use action="configure" to open the powers management panel.

`;else{s+=`**Currently Installed Powers:**

`;for(const n of t)s+=`• **${n.name}**
  ${n.description}
`,n.keywords.length>0&&(s+=`  Keywords: ${n.keywords.join(", ")}
`),n.mcpServerNames.length>0&&(s+=`  MCP Servers: ${n.mcpServerNames.join(", ")}
`),s+=`
`;s+=`**IMPORTANT: Call action="activate" with a powerName before using any power to understand its tools and parameters.**

`}return s+=`# ACTIONS:

1. **LIST** ("list") - See all installed powers
   Returns: Formatted list with names, descriptions, keywords, and MCP servers

2. **ACTIVATE** ("activate") - Get comprehensive power documentation
   Parameters: powerName (required)
   Returns: POWER.md content, available tools grouped by server with schemas, and steering file list

3. **USE** ("use") - Execute a tool from a power's MCP server
   Parameters: powerName, serverName, toolName, arguments (all required)
   **CRITICAL:** You MUST call action="activate" first to get serverName from toolsByServer

4. **READ_STEERING** ("readSteering") - Get detailed workflow guides
   Parameters: powerName, steeringFile (both required)

5. **CONFIGURE** ("configure") - Open powers management panel
   Returns: Success message indicating the panel should be opened

**CRITICAL RULES:**
- NEVER call action="use" without calling action="activate" first
- Tool names and input schemas come from the activate response
- Power names are case-sensitive`,s}async handle({input:e,state:t,toolUse:s,actionId:n}){const o=Date.now();try{let i,a;switch(e.action){case"list":i=this.handleListPowers(e,t,n,o),a=typeof i=="object"&&"formattedList"in i&&typeof i.formattedList=="string"?i.formattedList:`Found ${typeof i=="object"&&"total"in i?String(i.total):"0"} powers`;break;case"activate":if(i=await this.handleActivatePower(e,t,n,o),typeof i=="object"&&"toolsByServer"in i){const l=i;let d="";if(Object.keys(l.toolsByServer).length>0){d+=`**Available Tools by Server:**

`;for(const[g,h]of Object.entries(l.toolsByServer)){if(d+=`**Server: \`${g}\`**

`,Array.isArray(h)&&h.length>0)for(const S of h){if(d+=`• **${S.name}**`,S.description&&(d+=` - ${S.description}`),d+=`
`,S.inputSchema&&typeof S.inputSchema=="object"&&"properties"in S.inputSchema){const b=S.inputSchema;if(b.properties){d+=`  Parameters:
`;for(const[y,P]of Object.entries(b.properties)){const F=b.required?.includes(y);d+=`    - \`${y}\`${F?" (required)":" (optional)"}`,typeof P=="object"&&P!==null&&"type"in P&&typeof P.type=="string"&&(d+=`: ${P.type}`),typeof P=="object"&&P!==null&&"description"in P&&typeof P.description=="string"&&(d+=` - ${P.description}`),d+=`
`}}}d+=`
`}else d+=`  (No tools available)

`;d+=`
`}}l.steeringFiles.length>0&&(d+=`**Steering Files:** ${l.steeringFiles.join(", ")}

`),l.overview&&(d+=`---

`,d+=l.overview),a=d}else a=`No documentation available for power: ${e.powerName??"unknown"}`;break;case"use":if(i=await this.handleUsePower(e,t,n,o),typeof i=="object"&&"content"in i&&Array.isArray(i.content)){const l=i.content,d=[];for(const m of l)m&&typeof m=="object"&&"type"in m&&m.type==="text"&&"text"in m&&typeof m.text=="string"&&d.push(m.text);a=d.length>0?d.join(`
`):`Executed tool ${e.toolName??"unknown"} from power ${e.powerName??"unknown"}`}else a=`Executed tool ${e.toolName??"unknown"} from power ${e.powerName??"unknown"}`;break;case"readSteering":i=await this.handleReadSteering(e,t,n,o),a=`**Steering Guide: ${String(i.fileName)}**

${String(i.content)}`;break;case"configure":i=this.handleConfigurePower(e,t,n,o),a="Use the Powers panel in the sidebar to manage powers.";break;default:throw new Error(`Unknown action: ${"action"in e?String(e.action):"undefined"}`)}X.reportCountMetrics({[`kiroPowers_${e.action}_success`]:1});const{state:c}=this.withSyncToolMessage(t,s,a,!0);return{state:c,output:i}}catch(i){const a=i instanceof Error?i.message:String(i);p.logger.error("[KiroPowers] Error:",{action:e.action,error:a}),X.reportCountMetrics({[`kiroPowers_${e.action}_error`]:1});const{state:c}=this.withSyncToolMessage(t,s,a,!1);return{state:c,output:{success:!1,message:a}}}}createEventEmitter(e,t,s,n){return(o,i)=>{t.execution.emit({type:"AgentExecutionAction",executionId:t.execution.executionId,actionId:s,actionState:o,actionType:"kiroPower",input:{action:e.action,powerName:e.powerName,toolName:e.toolName,arguments:e.arguments},output:i,startTime:n,endTime:o===u.OperationStatus.Success||o===u.OperationStatus.Error||o===u.OperationStatus.Rejected?Date.now():void 0})}}handleListPowers(e,t,s,n){const o=this.createEventEmitter(e,t,s,n);o(u.OperationStatus.Running);const i=this.powersManager.getInstalledPowers();let a="";if(i.length===0)a=`**No powers installed**

`,a+=`You have no powers installed yet.

`,a+=`**To get started:**

`,a+=`• Use action="configure" to open the powers UI

`,a+=`• Browse and install available powers

`,a+=`• Or ask me to help you find and install a power
`;else{a+=`**Installed Powers (${i.length}):**

`;for(const l of i)a+=`• **${l.name}**
`,a+=`  ${l.description}
`,l.keywords.length>0&&(a+=`  Keywords: ${l.keywords.join(", ")} — **If you see any of these words in the user's message, strongly consider activating this power immediately!**
`),l.mcpServerNames.length>0&&(a+=`  MCP Servers: ${l.mcpServerNames.join(", ")}
`),a+=`
`;a+=`**How to use powers:**
`,a+=`1. **Activate first**: Use action="activate" with powerName to understand the power
`,a+=`2. **Then use**: Use action="use" with powerName, serverName, toolName, and arguments
`,a+=`3. **Read guides**: Use action="readSteering" for step-by-step workflows
`}const c={powers:i,total:i.length,formattedList:a};return o(u.OperationStatus.Success,{response:a}),c}async handleActivatePower(e,t,s,n){if(!e.powerName)throw new Error("powerName is required for activate action");const o=this.createEventEmitter(e,t,s,n);o(u.OperationStatus.Running);const a=this.powersManager.getInstalledPowers().find(g=>g.name===e.powerName);if(!a)throw new Error(`Power '${e.powerName}' is not installed`);const c=await this.powersManager.getPowerDocumentation(e.powerName)??"",l={};for(const g of a.mcpServerNames){const h=Z(e.powerName,g),b=this.mcpManager.getTools().filter(y=>y.serverName===h&&!y.disabled);l[g]=b.map(y=>({name:y.toolName,description:y.description,inputSchema:y.inputSchema}))}const d=await this.powersManager.getSteeringFiles(e.powerName),m={powerName:e.powerName,displayName:a.displayName??e.powerName,description:a.description,keywords:a.keywords,overview:c,steeringFiles:d,toolsByServer:l};return o(u.OperationStatus.Success,{response:JSON.stringify(m)}),m}async handleUsePower(e,t,s,n){if(!e.powerName)throw new Error("powerName is required for use action");if(!e.serverName)throw new Error('serverName is required for use action. Call action="activate" first to discover available servers from toolsByServer.');if(!e.toolName)throw new Error("toolName is required for use action");const o=this.createEventEmitter(e,t,s,n),a=this.powersManager.getInstalledPowers().find(g=>g.name===e.powerName);if(!a)throw new Error(`Power '${e.powerName}' is not installed`);if(!a.mcpServerNames.includes(e.serverName))throw new Error(`Server '${e.serverName}' not found in power '${e.powerName}'. Available servers: ${a.mcpServerNames.join(", ")}. Call action="activate" to see toolsByServer.`);const c=Z(e.powerName,e.serverName),l=this.mcpManager.getConnection(c);if(!l?.mcpClient)throw new Error(`MCP server '${c}' is not connected`);if(!await this.isPowerToolApproved(c,e.toolName)){try{await t.execution.acquireYield("kiro-powers")}catch(h){const S=`Power tool cannot proceed: ${h instanceof Error?h.message:String(h)}`;throw o(u.OperationStatus.Error,{error:S}),new Error(S)}o(u.OperationStatus.PendingAction);let g;try{const h=j.getExecutionLogger();g=await xe.abortable(h.awaitApproval(s),t.execution.abortController.signal)}catch{g=!1}finally{try{await t.execution.releaseYield("kiro-powers")}catch{}}if(!g){const h=`Tool execution denied. Tool '${e.toolName}' from power '${e.powerName}' requires your approval.`;throw o(u.OperationStatus.Rejected,{response:h}),new Error(h)}}o(u.OperationStatus.Running);const m=await l.mcpClient.callTool({name:e.toolName,arguments:e.arguments||{}},void 0,{timeout:864e5});if(m.isError&&m.content){const g=JSON.stringify(m.content).toLowerCase();if(g.includes("not enabled")||g.includes("not found")||g.includes("unknown")){const h=`Tool '${e.toolName}' does not exist on server '${c}'.

You must call action="activate" with powerName="${e.powerName}" first to learn about available tools and their parameters.`;return o(u.OperationStatus.Error,{error:h}),{content:[{type:"text",text:h}],isError:!0}}}return o(u.OperationStatus.Success,{result:m}),m}async handleReadSteering(e,t,s,n){if(!e.powerName)throw new Error("powerName is required for readSteering action");if(!e.steeringFile)throw new Error('steeringFile is required for readSteering action. Call action="activate" first to get the steeringFiles array.');if(!this.powersManager.getInstalledPowers().find(d=>d.name===e.powerName))throw new Error(`Power '${e.powerName}' is not installed`);const a=this.createEventEmitter(e,t,s,n);a(u.OperationStatus.Running);const c=await this.powersManager.getSteeringContent(e.powerName,e.steeringFile);if(!c)throw new Error(`Steering file '${e.steeringFile}' not found for power '${e.powerName}'`);const l={content:c,fileName:e.steeringFile,powerName:e.powerName};return a(u.OperationStatus.Success,{response:c,fileName:e.steeringFile}),l}handleConfigurePower(e,t,s,n){const o=this.createEventEmitter(e,t,s,n);o(u.OperationStatus.Running);const i={success:!0,message:"Use the Powers panel in the sidebar to manage powers."};return o(u.OperationStatus.Success,{response:JSON.stringify(i)}),i}async isPowerToolApproved(e,t){try{const s=A.join(this.homeDir,".kiro","settings","mcp.json");if(!Y.existsSync(s))return!1;const n=await Y.promises.readFile(s,"utf-8"),o=JSON.parse(n);if(o&&typeof o=="object"&&"powers"in o&&o.powers&&typeof o.powers=="object"&&"mcpServers"in o.powers){const a=(o.powers.mcpServers&&typeof o.powers.mcpServers=="object"?o.powers.mcpServers:{})[e];if(!a||typeof a!="object")return!1;const c="autoApprove"in a&&Array.isArray(a.autoApprove)?a.autoApprove:[];return c.includes(t)||c.includes("*")}return!1}catch{return!1}}};rt([_.Telemetry.Trace("Tool.KiroPowers")],Se.prototype,"handle");let q=Se;function at(r){const{connection:e,sessionId:t,workspacePaths:s,machineId:n="acp-client",customAgentRegistry:o,clientTools:i=[],mcpManager:a,steeringProvider:c,remoteToolsDiscovery:l,persistence:d,contextProviderRegistry:m,progressiveContextManager:g,powersManager:h,homeDir:S}=r,b=s[0]??".",y=new re(e,t,b),P=new ie(e,t),F=s.map(f=>T.URI.file(f)),Pe=new ke.NodeTaskService(y);let E=g?i.filter(f=>f.id!==w.DiscloseContext.toolId):i;h&&(E=E.filter(f=>f.id!==q.toolId));const H=()=>{if(!a)return[];const f=I=>a.getConnection(I);return a.getTools().map(I=>new B(I,f))},$=new ae(d,y,t,s),G=new fe,Ie=new j.PendingChangesService(new tt($,d,t,s),new st(y,new D(s),d,t,s),G);j.setPendingChangesService(Ie);const K=async f=>{p.logger.info(`[ACP ToolApproval] Requesting permission for toolId=${f.toolId}, operationId=${f.operationId}, sessionId=${t}`);try{const I=await e.requestPermission({sessionId:t,toolCall:{toolCallId:f.operationId,status:"pending",title:f.command??f.toolId},options:[{optionId:"accept",name:"Allow",kind:"allow_once"},{optionId:"always-accept",name:"Always allow",kind:"allow_always"},{optionId:"reject",name:"Deny",kind:"reject_once"}],_meta:{kiro:{toolId:f.toolId,...f.command&&{command:f.command}}}});if(p.logger.info(`[ACP ToolApproval] Got response: ${JSON.stringify(I.outcome)}`),I.outcome.outcome==="selected"){const k=I.outcome.optionId;return k==="accept"||k==="always-accept"?"accept":"reject"}return"reject"}catch(I){return p.logger.error("[ACP ToolApproval] requestPermission failed:",I),"reject"}},Ce={workspaceFolders:F,machineId:n,fs:y,terminalManager:new le(e,t),backgroundProcessManager:P,steeringProvider:c,taskProvider:Pe,checkpointProvider:$,fileOperationsProvider:new ce(e,t,$),workspaceResolver:new D(s),getTools:f=>{const I=[new w.FileSearch(Ze(e,t)),new w.GrepSearch(et(e,t))],k=[...L(P,t,K,l),...I,...E,...H()];o&&k.push(M(o,!1,m)),g&&k.push(J(g)),h&&a&&S&&k.push(new q(h,a,S));const N=[...V.getSpecTools(f),...L(P,t,K,l),...I,...E,...H()];o&&N.push(M(o,!0)),g&&N.push(J(g)),h&&a&&S&&N.push(new q(h,a,S));const Q=[new z.GetUserInput,new V.UpdateTaskStatus,de(),ue(),pe(),...I];return o&&Q.push(M(o,!0)),{chat:k,specAgent:N,specOrchestrator:Q,subAgent:we()}}};return{workspace:new Ae.WorkspaceConnectionImpl(Ce),executionLog:G}}function ct(r){return r>=95?"critical":r>=80?"warning":"normal"}function ee(r){return typeof r=="object"&&r!==null&&"message"in r}function lt(r){return r==="cancelled"?"aborted":r==="refusal"?"failed":"success"}const dt=new Set(["model","label","intentClassification","retry","compact","submit","userApproval","displayError","specAgent","do","ContextualHookInvoked","reportProgress"]);function te(r){switch(r){case u.OperationStatus.Running:return"in_progress";case u.OperationStatus.Success:case u.OperationStatus.Accepted:return"completed";case u.OperationStatus.Error:case u.OperationStatus.HandledError:case u.OperationStatus.Canceled:case u.OperationStatus.Rejected:return"failed";default:return"pending"}}class ut{connection;sessionId;workspacePaths;persistence;subscriptionId;sayContentByActionId=new Map;reasoningContentByActionId=new Map;fullResponse="";executionId=R.randomUUID();persistenceSuppressed=!1;emittedToolCallIds=new Set;controller;pendingPersistence=[];ownedExecutionId;pendingSummarization;constructor(e){this.connection=e.connection,this.sessionId=e.sessionId,this.workspacePaths=e.workspacePaths,this.persistence=e.persistence}subscribe(e){this.controller=e,this.subscriptionId=e.subscribeToEvents(t=>{this.handleEvent(t)})}unsubscribe(e){this.subscriptionId&&(e.unsubscribeFromEvents(this.subscriptionId),this.subscriptionId=void 0)}setOwnedExecutionId(e){this.ownedExecutionId=e}resetForNewExecution(){this.sayContentByActionId.clear(),this.reasoningContentByActionId.clear(),this.fullResponse="",this.executionId=R.randomUUID(),this.emittedToolCallIds.clear(),this.pendingPersistence=[]}getFullResponse(){return this.fullResponse}suppressPersistence(){this.persistenceSuppressed=!0}resumePersistence(){this.persistenceSuppressed=!1}async onPromptComplete(e){if(this.persistenceSuppressed)return;this.pendingPersistence.length>0&&(await Promise.allSettled(this.pendingPersistence),this.pendingPersistence=[]);const t=[];if(this.fullResponse&&t.push({id:R.randomUUID(),timestamp:new Date().toISOString(),payload:{type:"assistant",content:this.fullResponse,operationType:"Say",executionId:this.executionId}}),t.push({id:`${this.executionId}-complete`,timestamp:new Date().toISOString(),payload:{type:"session_event",category:"session_pause",context:{executionId:this.executionId,status:lt(e)}}}),t.length>0)try{await this.persistence.appendMessages(this.sessionId,this.workspacePaths,t)}catch(s){p.logger.warn("[ACPEventAdapter] Failed to persist messages",{sessionId:this.sessionId,error:s instanceof Error?s.message:String(s)})}}isOwnedEvent(e){return!this.ownedExecutionId||e.executionId===this.ownedExecutionId}handleEvent(e){switch(e.type){case"AgentExecutionBegan":if(!this.isOwnedEvent(e))return;p.logger.info(`[ACPEventAdapter] Execution began: ${e.executionId}`),this.resetForNewExecution(),this.pendingSummarization=void 0;break;case"AgentExecutionSuccess":if(!this.isOwnedEvent(e))return;p.logger.info(`[ACPEventAdapter] Execution succeeded: ${e.executionId}`);break;case"AgentExecutionFailed":if(!this.isOwnedEvent(e))return;p.logger.info(`[ACPEventAdapter] Execution failed: ${e.executionId}`);break;case"AgentExecutionAborted":if(!this.isOwnedEvent(e))return;p.logger.info(`[ACPEventAdapter] Execution aborted: ${e.executionId}`);break;case"AgentExecutionYielded":if(!this.isOwnedEvent(e))return;p.logger.info(`[ACPEventAdapter] Execution yielded: ${e.executionId}`);break;case"AgentExecutionResumed":if(!this.isOwnedEvent(e))return;p.logger.info(`[ACPEventAdapter] Execution resumed: ${e.executionId}`);break;case"AgentExecutionAction":if(!this.isOwnedEvent(e))return;this.handleActionEvent(e);break;case"AgentExecutionContextUsageUpdate":if(!this.isOwnedEvent(e))return;this.handleContextUsageUpdate(e);break;case"AgentExecutionSummarizationComplete":if(!this.isOwnedEvent(e))return;this.handleSummarizationComplete(e);break;case"AgentExecutionErrorOccurred":if(!this.isOwnedEvent(e))return;this.handleErrorOccurred(e);break}}handleActionEvent(e){if(!dt.has(e.actionType))switch(e.actionType){case"say":this.handleSayAction(e);break;case"reasoning":this.handleReasoningAction(e);break;case"steering":this.handleSteeringAction(e);break;case"invokeSubAgent":this.handleSubAgentAction(e);break;case"summarization":this.handleSummarizationAction(e);break;case"userMessage":break;case"userInput":this.handleUserInputAction(e);break;default:this.handleToolAction(e);break}}handleSayAction(e){if(ee(e.output)){const t=this.sayContentByActionId.get(e.actionId)??"",s=e.output.message.slice(t.length);s&&(this.sayContentByActionId.set(e.actionId,e.output.message),e.subExecutionId||(this.fullResponse=e.output.message),this.sendSessionUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:s},...e.subExecutionId&&{_meta:{kiro:{agentSubtaskId:e.subExecutionId}}}}))}}handleReasoningAction(e){if(ee(e.output)){const t=this.reasoningContentByActionId.get(e.actionId)??"",s=e.output.message.slice(t.length);s&&(this.reasoningContentByActionId.set(e.actionId,e.output.message),this.sendSessionUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:s},...e.subExecutionId&&{_meta:{kiro:{agentSubtaskId:e.subExecutionId}}}}))}this.persistAction(e)}handleSteeringAction(e){this.persistAction(e);const s=e.input?.documents;Array.isArray(s)&&s.length>0&&this.sendSessionUpdate({sessionUpdate:"session_info_update",_meta:{kiro:{steeringDocuments:s,...e.subExecutionId&&{agentSubtaskId:e.subExecutionId}}}})}handleSubAgentAction(e){const t=e.input,s=e.output,n=t?.subAgentName?`Sub-agent: ${t.subAgentName}`:"Sub-agent execution",o=te(e.actionState),i=s?.subExecutionId??e.actionId;e.actionState===u.OperationStatus.Running&&(this.emittedToolCallIds.has(e.actionId)?this.sendSessionUpdate({sessionUpdate:"tool_call_update",toolCallId:e.actionId,status:o,rawInput:e.input}):(this.emittedToolCallIds.add(e.actionId),this.sendSessionUpdate({sessionUpdate:"tool_call",toolCallId:e.actionId,title:n,kind:"other",rawInput:e.input,status:o,_meta:{kiro:{kind:"agent-subtask",agentSubtaskId:i}}}))),(e.actionState===u.OperationStatus.Success||e.actionState===u.OperationStatus.Error||e.actionState===u.OperationStatus.HandledError)&&(this.emittedToolCallIds.delete(e.actionId),this.sendSessionUpdate({sessionUpdate:"tool_call_update",toolCallId:e.actionId,status:e.actionState===u.OperationStatus.Success?"completed":"failed",rawOutput:e.output??e.errorMessage})),this.persistAction(e)}handleErrorOccurred(e){this.sendSessionUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:e.errorMessage}})}handleUserInputAction(e){if(e.actionState!==u.OperationStatus.PendingAction)return;const s=e.output?.questions;if(!s?.length)return;const n=s[0],o=n.options?.map(a=>({optionId:a.id,name:a.label,kind:"allow_once"}))??[];if(o.length===0)return;const i=()=>this.controller?.getExecutionsForId(e.executionId)??this.controller?.getCurrentExecution();this.sendSessionUpdate({sessionUpdate:"tool_call",toolCallId:e.actionId,title:n.question,kind:"other",status:"pending"}),(async()=>{try{const a=await this.connection.requestPermission({sessionId:this.sessionId,toolCall:{toolCallId:e.actionId,title:n.question,status:"pending"},options:o}),{outcome:c}=a;if(c.outcome==="selected"){const l=c.optionId,d=n.options?.find(m=>m.id===l)?.label??l;i()?.respondToQuestion(n.id,{type:"answered",answer:d}),this.sendSessionUpdate({sessionUpdate:"tool_call_update",toolCallId:e.actionId,status:"completed"})}else i()?.respondToQuestion(n.id,{type:"next-phase"}),this.sendSessionUpdate({sessionUpdate:"tool_call_update",toolCallId:e.actionId,status:"completed"})}catch(a){p.logger.error("[ACPEventAdapter] requestPermission for userInput failed:",a),i()?.respondToQuestion(n.id,{type:"next-phase"}),this.sendSessionUpdate({sessionUpdate:"tool_call_update",toolCallId:e.actionId,status:"failed"})}})()}handleToolAction(e){const t=te(e.actionState),s=e.subExecutionId?{_meta:{kiro:{agentSubtaskId:e.subExecutionId}}}:{},n=O.mapActionTypeToToolKind(e.actionType);if(e.actionState===u.OperationStatus.Running||e.actionState===u.OperationStatus.PendingAction)if(this.emittedToolCallIds.has(e.actionId))this.sendSessionUpdate({sessionUpdate:"tool_call_update",toolCallId:e.actionId,status:t,rawInput:e.input});else{this.emittedToolCallIds.add(e.actionId);const o=O.extractLocationsFromInput(e.input);this.sendSessionUpdate({sessionUpdate:"tool_call",toolCallId:e.actionId,title:e.actionType,kind:n,rawInput:e.input,status:t,...o.length>0&&{locations:o},...s})}else{this.emittedToolCallIds.delete(e.actionId);const o=O.extractCheckpointMeta(n,e.input);this.sendSessionUpdate({sessionUpdate:"tool_call_update",toolCallId:e.actionId,status:t,rawOutput:e.output??e.errorMessage,...o&&{_meta:{kiro:{checkpoint:o}}}})}this.persistAction(e)}persistAction(e){if(this.persistenceSuppressed)return;const t={executionId:e.executionId,actionId:e.actionId,actionType:e.actionType,actionState:e.actionState,startTime:e.startTime,endTime:e.endTime,errorMessage:e.errorMessage,input:e.input,output:e.output,subExecutionId:e.subExecutionId},s=O.actionToMessages(t,this.executionId);if(s.length===0)return;const n=this.appendMessagesQuietly(e.actionType,s);this.pendingPersistence.push(n)}async appendMessagesQuietly(e,t){try{await this.persistence.appendMessages(this.sessionId,this.workspacePaths,t)}catch(s){p.logger.warn("[ACPEventAdapter] Failed to persist action",{sessionId:this.sessionId,actionType:e,error:s instanceof Error?s.message:String(s)})}}async sendSessionUpdate(e){await this.connection.sessionUpdate({sessionId:this.sessionId,update:e})}handleContextUsageUpdate(e){const t=ct(e.contextUsagePercentage);this.sendSessionUpdate({sessionUpdate:"session_info_update",_meta:{kiro:{contextUsage:{usagePercentage:e.contextUsagePercentage,tier:t}}}})}handleSummarizationAction(e){const t=e.actionState;if(t){if(t===u.OperationStatus.Running){this.sendSessionUpdate({sessionUpdate:"session_info_update",_meta:{kiro:{summarization:{status:"running",startedAt:new Date().toISOString()}}}});return}if(t===u.OperationStatus.Error||t===u.OperationStatus.Canceled){const s=t===u.OperationStatus.Error?"error":"canceled";this.sendSessionUpdate({sessionUpdate:"session_info_update",_meta:{kiro:{summarization:{status:s,completedAt:new Date().toISOString()}}}}),this.pendingSummarization=void 0;return}if(t===u.OperationStatus.Success){const s=e.output;this.pendingSummarization={conversationSummary:s?.conversationSummary??"",truncated:s?.truncated??!1}}}}handleSummarizationComplete(e){const t=this.pendingSummarization??{conversationSummary:e.summary.conversationSummary,truncated:!1};this.sendSessionUpdate({sessionUpdate:"session_info_update",_meta:{kiro:{summarization:{status:"success",completedAt:new Date().toISOString(),summary:t}}},...e.sessionTitle?{title:e.sessionTitle}:{}}),this.pendingSummarization=void 0}}function pt(r,e,t){if(t)return;p.logger.debug(`${e}: content collection is disabled, setting x-amzn-codewhisperer-optout to true`);const s=n=>async o=>{const i=o;return i.request.headers={...i.request.headers,"x-amzn-codewhisperer-optout":"true"},n(o)};r.middlewareStack.add(s,{step:"build"})}function ht(r,e){const t=s=>async n=>{const o=n;return o.request.headers={...o.request.headers,"x-amzn-kiro-agent-mode":e},s(n)};r.middlewareStack.add(t,{step:"build"})}function ye(r,e,t="CodeWhisperer"){if(e!=="external_idp")return;p.logger.debug(`${t}: adding TokenType header for External IdP`);const s=n=>async o=>{const i=o;return i.request.headers={...i.request.headers,TokenType:"EXTERNAL_IDP"},n(o)};r.middlewareStack.add(s,{step:"build"})}const gt="https://q.us-east-1.amazonaws.com",mt="us-east-1";function wt(r,e={}){const t=e.contentCollectionEnabled??!1;return{createQDeveloperConverse:(s,n)=>{const o=e.region||r.region||mt,i=e.endpoint||gt;return new oe.QDeveloperConverse(s,n,{authProvider:r,getCodeWhispererStreamingClient:async c=>{const l=await r.getToken(),d=new v.CodeWhispererStreaming({region:o,endpoint:i,token:{token:l},retryStrategy:c,customUserAgent:e.customUserAgent});return ye(d,r.readToken()?.authMethod,"acp-q-client"),d},addPrivacyHeadersMiddleware:(c,l)=>{pt(c,l,t)},addAgentModeHeadersMiddleware:(c,l)=>{ht(c,l)},metrics:{reportCountMetrics:()=>{},reportHistogramMetrics:()=>{},createTrace:c=>({start:()=>{},success:()=>{},fail:l=>{},setAttributes:l=>{}})},qLogger:{debug:(c,...l)=>p.logger.debug(c,...l),error:(c,...l)=>p.logger.error(c,...l)},qChatLogger:{appendLine:c=>p.logger.debug("[QChat]",c),capture:()=>"",storeConversationId:()=>{},getConversationIds:()=>[]},isUsageEnabled:()=>!0,isReferenceTrackerEnabled:()=>!1,recordReferences:()=>{}})}}}const ft="https://q.us-east-1.amazonaws.com",St="us-east-1";function yt(r,e={}){const t=new oe.QClientRetryStrategy;async function s(){const n=e.region||r.region||St,o=e.endpoint||ft,i=await r.getToken(),a=new v.CodeWhispererStreaming({region:n,endpoint:o,token:{token:i},retryStrategy:t,customUserAgent:e.customUserAgent});return ye(a,r.readToken()?.authMethod,"acp-remote-mcp"),a}return{async listTools(){const o=await(await s()).send(new v.InvokeMCPCommand({jsonrpc:"2.0",id:"tools_list",method:v.MCPMethod.TOOLS_LIST,profileArn:await r.getProfileArn()}));if(o.error)throw new Error(`Failed to fetch remote tools: ${o.error.message}`);if(!o.result)throw new Error("No result returned from tools/list");const i=Ee.ListToolsResultSchema.safeParse(o.result);return i.success?{tools:i.data.tools}:(p.logger.error("[ACPRemoteMCPClient] Failed to parse tools list",JSON.stringify(i.error)),null)},async callTool(n,o,i){const c=await(await s()).send(new v.InvokeMCPCommand({jsonrpc:"2.0",id:i,method:v.MCPMethod.TOOLS_CALL,profileArn:await r.getProfileArn(),params:{name:n,arguments:o}}));return{result:c.result,error:c.error?{message:c.error.message??"",code:c.error.code??0}:void 0}}}}exports.ACPBackgroundProcessManager=ie;exports.ACPCheckpointProvider=ae;exports.ACPEventAdapter=ut;exports.ACPExecutionLogOperations=fe;exports.ACPFileOperationsProvider=ce;exports.ACPFileSystem=re;exports.ACPTerminalManager=le;exports.ACPWorkspaceResolver=D;exports.createACPQClientFactory=wt;exports.createACPRemoteMCPClient=yt;exports.createACPWorkspaceConnection=at;exports.createAcpFsTools=he;exports.createAcpInvokeSubAgentTool=M;exports.createAcpRemoteToolsDiscovery=Ye;exports.createAcpRemoteWrapperOptions=me;exports.createAcpShellTools=ge;exports.createAcpSubAgentTools=we;exports.createAcpTools=L;
//# sourceMappingURL=acp-remote-mcp-client-C3uMG7Dm.cjs.map
