"use strict";const m=require("./shared-types-B8BH5zz1.cjs"),R=require("./telemetry-C8yrvnwb.cjs"),ie=require("./token-monitor-uGAwbC-8.cjs"),h=require("./context-chat-message-CcL2Y-yV.cjs"),I=require("./sub-agent-CYzSed7z.cjs"),O=require("@langchain/langgraph"),l=require("./logger-BN0ZR9CS.cjs"),Y=require("./message-parts-tGBL83L3.cjs"),re=require("./intent-detection-service-DP1cQxy7.cjs"),pe=require("./model-config-Clqxmxf5.cjs"),Le=require("./orchestrator-prompt-Bv2Dqt8x.cjs"),D=require("./spec-platform-B-vK5eNN.cjs"),H=require("./config-constants-CzjFv-yC.cjs"),_=require("./disclose-context-DDXHbF-P.cjs"),fe=require("./cancellation-DiXZPuOm.cjs"),qe=require("./model-provider-TqxgiEyN.cjs"),$e=require("./stream-BfNQDS2Z.cjs");require("./base-DYJSEa-Z.cjs");require("uuid");require("./string-CNIv5GMJ.cjs");const He=require("./get-user-input-D6l3Y8vJ.cjs");require("zod-stream");require("./number-coercion-Ce_kJ-2m.cjs");const Ge=require("./errors-S60ZSV73.cjs"),se=require("./actions-DW6bU0WB.cjs"),We=require("./execution-log-controller-DT7jtyqR.cjs"),P=require("./pending-changes-DJpAX0cK.cjs"),je=require("./autonomy-mode-bjOTo5IP.cjs"),he=require("./hooks-CP-1kO8-.cjs"),Ye=require("crypto");var Se=(e=>(e.MockedAgent="mocked-agent",e.ChatAgent="chat-agent",e.SpecGeneration="spec-generation",e.SubAgent="sub-agent",e))(Se||{});const Qe=20,ae=15,Ke=7,ce=10;function Ve(e){const t=e.messages.filter(o=>o.role!=="bot");if(t.length<ae)return;let n=0;for(let o=1;o<=Qe;o++){const r=t.at(-o);if(!r||!te(r))return;if(xe(r)&&n++,n>=ae)return{failureMessage:"Multiple recent messages contain tool failures. You need to analyze what is failing and change your approach completely.",userMessage:`I've encountered repeated tool failures (${n} recent failures) and need guidance on how to proceed.`,userQuestion:`I've been encountering repeated failures and would like your input.

Before I continue exploring more alternatives, please let me know how you'd like me to proceed — I can either keep iterating with different approaches, or switch to alternative methods if you provide more detailed instructions.`,choiceMessages:{cancel:"User has chosen to cancel the current task due to repeated failures.","keep-iterating":"User wants you to to keep iterating. Please continue.","provide-guidance":'User provided specific guidance: "{guidanceText}". Please incorporate this guidance.'}}}}function te(e){return e.entries.some(t=>t.type==="toolUseResponse")}function xe(e){return e.entries.some(t=>t.type==="toolUseResponse"&&!t.success)}function ue(e){const{id:t,...n}=e;return n}function Be(e,t){const n=new Set;for(const o of e){const r=ue(o);for(const i of t){const s=ue(i);JSON.stringify(r)===JSON.stringify(s)&&n.add(o)}}return n}function Ze(e){const t=e.messages.filter(o=>o.role!=="bot");if(t.length<ce)return;let n;for(let o=1;o<=ce;o++){const r=t.at(-o);if(!r||!te(r))return;const i=new Set(r.entries.filter(s=>s.type==="toolUseResponse"));if(!n)n=i;else{const s=Be(n,i);if(s.size===0)return;n=s}}return{failureMessage:"The same tool is being used repeatedly in consecutive attempts. You may be stuck in a loop and should try a completely different approach.",userMessage:"I'm potentially stuck in a loop - the same tool has been used repeatedly.",userQuestion:`I've been using the same tool repeatedly. This might indicate I'm stuck in a loop.

What would you like me to do?`,choiceMessages:{cancel:"User has chosen to cancel the current task due to repetitive tool usage. Please acknowledge the cancellation and stop the current approach.","keep-iterating":"I asked for your input due to repetitive tool usage and you chose to keep iterating. Please continue with your current approach.","provide-guidance":'User provided specific guidance: "{guidanceText}". Please incorporate this guidance and try a different approach.'}}}function le(e,t="",n=Ke){const o=e.messages.filter(s=>s.role!=="bot");if(o.length<n)return;let r;for(let s=1;s<=n;s++){const c=o.at(-s);if(!c||!te(c)||!xe(c))return;const a=new Set(c.entries.filter(u=>u.type==="toolUseResponse"&&!u.success).map(u=>u.name).filter(u=>u.startsWith(t)));if(r||(r=a),new Set([...r].filter(u=>a.has(u))).size===0)return}const i=Array.from(r||[]);return{failureMessage:"The same tool is failing repeatedly in consecutive attempts. You are stuck in a failure loop and must try a completely different approach.",userMessage:`I'm stuck in a failure loop - the same tool(s) have failed ${n} consecutive times.`,userQuestion:`I've been trying to use "${i.join(", ")}" but it's failed ${n} times in a row. I'm clearly stuck in a loop.

What would you like me to do?`,choiceMessages:{cancel:"User has chosen to cancel the current task due to repeated failures. Please acknowledge the cancellation and stop the current approach.","keep-iterating":"I asked for your input due to repeated failures and you chose to keep iterating. Please continue with your current approach.","provide-guidance":'User provided specific guidance: "{guidanceText}". Please incorporate this guidance and try a different approach.'}}}const Ie=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"FailureDetection"),Je=3,Te=Ie.wrapTrace("FailureDetectionNode",Xe);function Xe(e){if(e.skipFailureIntervention)return{interventionResult:void 0};l.logger.debug("[FailureDetectionNode] Checking message-based failure patterns");const t=le(e.context),n=le(e.context,"mcp",Je),o=Ze(e.context),r=Ve(e.context),i=t||r||n||o;return Ie.reportCountMetrics({ToolLoopDetected:t?1:0,MCPToolLoopDetected:n?1:0,RepetitiveToolDetected:o?1:0,FailureHistoryDetected:r?1:0,AnyFailureDetected:i?1:0}),{interventionResult:i}}function Ee(e){return e.interventionResult?"USER_INTERVENTION":"MODEL_INVOKE"}const we=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"UserIntervention"),ye=we.wrapTrace("UserInterventionNode",et);async function et(e){if(l.logger.info("[UserInterventionNode] Processing user intervention for detected failures"),!e.interventionResult)return l.logger.debug("[UserInterventionNode] No intervention result found, continuing normally"),e;const t=e.interventionResult.failureMessage;l.logger.info(`[UserInterventionNode] Intervention triggered: ${t}`);let n=!1,o;try{const i={id:`failure-intervention-${Date.now()}`,question:e.interventionResult.userQuestion,options:[{id:"cancel",label:"Cancel"},{id:"keep-iterating",label:"Keep Iterating"}],response:void 0};e.execution.addQuestion(i),e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:`failure-intervention-prompt-${Date.now()}`,actionState:m.OperationStatus.PendingAction,actionType:"userInput",output:{questions:[i],reason:"failure-intervention"}}),await e.execution.acquireYield("user-intervention"),n=!0;const s=await fe.abortable(e.execution.waitForAllQuestions(),e.execution.abortController.signal),c=Object.values(s).find(a=>a.id.includes("failure-intervention"));return!c||!c.response?(l.logger.warn("[UserInterventionNode] No failure intervention response found after waiting"),o={...e,interventionResult:void 0},o):(o=tt(e,c),o)}catch(r){if(r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")))throw l.logger.debug("[UserInterventionNode] Execution was aborted during user intervention"),r;l.logger.error("[UserInterventionNode] Failed during user intervention, continuing with automatic guidance:",r);const i=e.interventionResult.choiceMessages["keep-iterating"],s=e.context.withExtendedMessage(h.ContextChatMessage.fromHuman().withText(i));return o={...e,context:s,interventionResult:void 0},o}finally{if(n)try{await e.execution.releaseYield("user-intervention")}catch{}}}function tt(e,t){if(!e.interventionResult)return l.logger.error("[UserInterventionNode] processUserResponse called without interventionResult"),{...e,interventionResult:void 0};let n,o;if(t.response&&t.response.type==="answered"){const s=t.response.answer;s==="cancel"||s==="keep-iterating"?(n=s,o=void 0):(n="provide-guidance",o=s)}else n="keep-iterating",o=void 0;l.logger.info(`[UserInterventionNode] User selected: ${n}`),we.reportCountMetrics({UserInterventionCompleted:1,[`UserChoice_${n.replace("-","_")}`]:1});let r=e.context,i;return n==="provide-guidance"&&o?i=e.interventionResult.choiceMessages["provide-guidance"].replace("{guidanceText}",o):i=e.interventionResult.choiceMessages[n]||e.interventionResult.choiceMessages["keep-iterating"],r=r.withExtendedMessage(h.ContextChatMessage.fromHuman().withText(i)),e.execution.removeQuestion(t.id),e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:`failure-intervention-${Date.now()}`,actionState:m.OperationStatus.Success,actionType:"print",input:{message:`User intervention: ${n}${o?` - ${o}`:""}`},output:{userChoice:n,guidanceProvided:n==="provide_guidance",guidanceText:o}}),{...e,context:r,interventionResult:void 0,skipFailureIntervention:n==="keep-iterating"?!0:e.skipFailureIntervention}}const F=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"SummarizationDetection"),ve=F.wrapTrace("SummarizationDetectionNode",nt);function nt(e){const t=e.context.messages.at(-1),n=t?.role==="tool";if(!e.contextUsagePercentage||e.needsSummarization||e.summarizationComplete||e.execution.simulatedTurnMessage?.includes("summarizing"))return F.reportCountMetrics({SummarizationNotNeeded:1}),{summarizationResult:void 0};let r=e.contextUsagePercentage;if(n&&e.contextUsagePercentage!==void 0){const a=t.entries.filter(d=>d.type==="toolUseResponse").map(d=>d.message||"").join(`
`);a&&(r=Y.estimateProjectedUsage(e.contextUsagePercentage,a,e.execution.model.modelId,e.execution.model.maxInputTokens))}const i=Y.decideContextAction(r??e.contextUsagePercentage??0),s=e.context.messages.length,c=e.context.messages.filter(a=>a.role==="human"&&!a.forcedRole&&a.entries.some(d=>d.type==="text")).length;return i.type==="truncate"?(l.logger.warn(`[SummarizationDetectionNode] CRITICAL: Projected usage ${i.projectedUsage.toFixed(1)}% > 95%, triggering immediate truncation`),F.reportCountMetrics({SummarizationTriggered:1,SummarizationCriticalTruncation:1,MessageCount:s,UserMessageCount:c}),{summarizationResult:{shouldSummarize:!0,shouldTruncate:!0,contextUsagePercentage:i.projectedUsage,projectedUsage:i.projectedUsage}}):i.type==="summarize"?(l.logger.info(`[SummarizationDetectionNode] Projected usage ${i.projectedUsage.toFixed(1)}% > 80%, triggering summarization`),F.reportCountMetrics({SummarizationTriggered:1,SummarizationCriticalTruncation:0,SummarizationTriggeredWithToolResponse:n?1:0,MessageCount:s,UserMessageCount:c}),{summarizationResult:{shouldSummarize:!0,shouldTruncate:!1,contextUsagePercentage:i.projectedUsage,projectedUsage:i.projectedUsage}}):(F.reportCountMetrics({SummarizationNotNeeded:1}),{summarizationResult:void 0})}function ot(e){const t=e.context.messages.at(-1);return e.summarizationResult?.shouldSummarize?"SUMMARIZATION_NODE":e.summarizationComplete?(l.logger.info("[SummarizationDetectionRouter] Summarization complete - routing to END"),O.END):t?.role==="tool"?"FAILURE_DETECTION":e.execution.hasQueuedUserMessage()?(l.logger.info("[SummarizationDetectionRouter] Queued user message found - routing to MODEL_INVOKE"),"MODEL_INVOKE"):"USER_HOOK_AGENT_STOP"}const C=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"Summarization");function Ae(e){const t=[];let n=0;const o=1e4,r=["<EnvironmentContext>","<steering-reminder>","## Included Rules","<ADDITIONAL_INSTRUCTIONS>","Previous conversation summary:","## CONVERSATION SUMMARY","CONTEXT TRANSFER:","[SYSTEM NOTE: This is an automated summarization request",`METADATA:
The previous conversation had`,`INSTRUCTIONS:
Continue working until the user query`];for(let i=e.length-1;i>=0;i--){const s=e[i];if(s.role==="human"&&!s.forcedRole){for(const c of s.entries)if(c.type==="text"&&"text"in c){const a=c.text.trim();if(r.some(u=>a.includes(u)))continue;if(a&&n+a.length+2<=o)t.push(a),n+=a.length+2;else if(n>=o)break}if(n>=o)break}}return t.length===0?"":`

USER QUERIES(most recent first):
`+t.map((i,s)=>`${s+1}. ${i}`).join(`
`)}function it(e){const t=[];for(const n of e)for(const o of n.entries){if(n.role==="human"&&o.type==="text"&&"text"in o&&t.push(`User message: ${o.text}
`),n.role==="bot"&&o.type==="text"&&"text"in o&&t.push(`Assistant message: ${o.text}
`),n.role==="bot"&&o.type==="toolUse"&&"name"in o&&"args"in o){const r=Object.keys(o.args).length>0?JSON.stringify(o.args):"no args";t.push(`Tool: ${o.name||"unknown"} - ${r}
`)}if(n.role==="tool"&&o.type==="toolUseResponse"&&"success"in o){const r=o.success?"SUCCESS":"FAILED";let i="";const s="name"in o?o.name:void 0;s===_.ReadFile.id||s===_.ReadMultipleFiles.id||s==="executeBash"||s==="executePwsh"||s==="grepSearch"||s===_.WebFetch.id||s&&s.startsWith("mcp_")?i=" - Tool response contents truncated for brevity":"message"in o&&o.message&&(i=` - ${o.message}`),t.push(`ToolResult: ${r}${i}
`)}}return t.join(`
`)}function rt(){return`You are preparing a summary for a new agent instance who will pick up this conversation.

Organize the summary by TASKS/REQUESTS. For each distinct task or request the user made:

For each task:
- SHORT DESCRIPTION: Brief description of the task/request
- STATUS: done | in-progress | not-started | abandoned
  * Use "in-progress" if ANY work remains, even if partially implemented
  * The most recent task should almost always be "in-progress"
  * Only use "done" if the conversation moved to a completely different task
  * Use "abandoned" when an approach was tried and explicitly discarded (note why in DETAILS)
- USER QUERIES: Which user queries relate to this task (reference by number)
- DETAILS: Additional context, decisions made, current state
  * Distinguish between what was discussed vs what was actually implemented
  * If only a partial fix or workaround was implemented, state explicitly what's missing
  * Pay extra close attention to the last file that was edited - the agent may have been cut off in the middle of edits
- NEXT STEPS: If status is "in-progress", list specific remaining work:
  * Exact files that need changes
  * Specific methods/functions that need to be added or modified
  * Any validation, error handling, or edge cases not yet addressed
- FILEPATHS: Files related to this specific task

After all tasks, include:
- USER CORRECTIONS AND INSTRUCTIONS: Specific instructions or corrections the user gave that apply across tasks

You can specify filepaths of files the new agent should read on initialization. Focus especially on files relevant to IN PROGRESS tasks, as the new agent will need to continue working on those.

If there are files the new agent should read, list them at the end Files to read section

Example format:
TASK 1: Implement user authentication
- STATUS: done
- USER QUERIES: 1 ("Add login endpoint"), 2 ("Hash passwords")
- DETAILS: Completed login endpoint with bcrypt hashing. Tested with 'npm test auth'.
- FILEPATHS: src/auth/login.ts, src/models/user.ts

TASK 2: Add error handling
- STATUS: in-progress
- USER QUERIES: 3 ("Add validation middleware")
- DETAILS: Created basic structure but still need error response formatting.
- NEXT STEPS:
  * Add error response formatting in src/middleware/validation.ts
  * Integrate middleware with routes in src/routes/index.ts
- FILEPATHS: src/middleware/validation.ts, src/routes/index.ts

USER CORRECTIONS AND INSTRUCTIONS:
- Use bcrypt for password hashing
- Run 'npm test auth' to test, not full suite

Files to read
- src/middleware/validation.ts
- src/routes/index.ts
`}function Re(){return`[SYSTEM NOTE: This is an automated summarization request due to context limit]

IMPORTANT: Context limit reached. You MUST create a structured summary.

Format your response using markdown syntax for better readability:
- Use ## for task headers (e.g., "## TASK 1: Description")
- Use **bold** for field labels (e.g., "**STATUS**:", "**DETAILS**:")
- Use \`code\` formatting for file paths
- Use bullet lists with - for items

${rt()}

Review the conversation history above and create a comprehensive summary.`}function st(e){if(e instanceof Ge.ContextWindowExceededError)return!0;if(e instanceof Error){const t=e.message.toLowerCase();return t.includes("input is too long")||t.includes("context")&&t.includes("exceeded")}return!1}async function de(e,t,n){const o=n!==void 0?`(projected: ${n}%)`:"(fallback from normal path)";l.logger.warn(`[SummarizationNode] Using truncation summarization ${o}`);const r=it(e.context.messages.filter(g=>!g.forcedRole));l.logger.info(`[SummarizationNode] Extracted ${r.length} characters of conversation data for summarization`);const i=`${Re()}

CONVERSATION DATA TO SUMMARIZE:
${r}`,a=(await qe.loadModel(e.execution.model.provider,e.execution.model.modelId,e.execution.getAgentMode(),{forceRefresh:!0}).invoke([new $e.HumanMessage(i)])).content,d=Ae(e.context.messages.filter(g=>!g.forcedRole)),u=a+(d||"");return l.logger.info("[SummarizationNode] Truncation summarization complete"),e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:t,actionType:"summarization",actionState:m.OperationStatus.Success,endTime:Date.now(),output:{content:u,conversationSummary:u,truncated:!0}}),e.execution.emit({type:"AgentExecutionSummarizationComplete",executionId:e.execution.executionId,chatSessionId:e.execution.chatSessionId,summary:{conversationSummary:u},sessionTitle:"Context Truncated"}),{state:{summarizationComplete:!0,needsSummarization:!1,summarizationResult:void 0},summarySize:u.length}}const Me=C.wrapTrace("SummarizationNode",at);async function at(e){if(l.logger.info("[SummarizationNode] Starting direct summarization"),!e.summarizationResult||!e.summarizationResult.shouldSummarize)return l.logger.debug("[SummarizationNode] No summarization result found, continuing normally"),e;const t=Date.now(),n=h.getId();e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:n,actionType:"summarization",actionState:m.OperationStatus.Running,startTime:Date.now()});try{if(e.summarizationResult.shouldTruncate){l.logger.warn(`[SummarizationNode] Critical overflow detected - using separate LLM call for summarization (projected: ${e.summarizationResult.projectedUsage}%)`);const{state:f,summarySize:x}=await de(e,n,e.summarizationResult.projectedUsage),T=Date.now()-t;return l.logger.info(`[SummarizationNode] Truncation summarization metrics: summarySize=${x} chars, latencyMs=${T}`),C.reportCountMetrics({SummarizationSuccess:1,SummarizationWithTruncation:1,SummarySize:x,LatencyMs:T}),f}l.logger.info("[SummarizationNode] Sending summarization prompt as new message");const o=Re();e.context.messages[e.context.messages.length-1].role!=="bot"&&(e.context=e.context.withNewMessage(h.ContextChatMessage.fromAI().withText("Understood. The conversation is getting too long. I will request summarization of our conversation and continue.").withForcedRole())),e.context=e.context.withNewMessage(h.ContextChatMessage.fromHuman().withText(o).withForcedRole()),e.execution.saveState(e),l.logger.info("[SummarizationNode] Invoking model to generate summary");const i=e.execution.workspace.getChatTools(),{responseStream:s}=await e.execution.modelStream2(e.context,i),c=[];for await(const f of s)"content"in f&&typeof f.content=="string"&&c.push(f.content);const a=c.join(""),d=Ae(e.context.messages.filter(f=>!f.forcedRole)),u=a+(d||"");l.logger.info("[SummarizationNode] Summarization complete"),e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:n,actionType:"summarization",actionState:m.OperationStatus.Success,endTime:Date.now(),output:{content:u,conversationSummary:u}}),e.execution.emit({type:"AgentExecutionSummarizationComplete",executionId:e.execution.executionId,chatSessionId:e.execution.chatSessionId,summary:{conversationSummary:u},sessionTitle:"Conversation Summary"});const g=Date.now()-t;return l.logger.info(`[SummarizationNode] Normal summarization metrics: summarySize=${u.length} chars, latencyMs=${g}`),C.reportCountMetrics({SummarizationSuccess:1,SummarySize:u.length,LatencyMs:g}),{summarizationComplete:!0,needsSummarization:!1,summarizationResult:void 0}}catch(o){if(He.isAbortError(o))throw l.logger.info("[SummarizationNode] Summarization was cancelled by user"),e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:n,actionType:"summarization",actionState:m.OperationStatus.Canceled,endTime:Date.now()}),C.reportCountMetrics({SummarizationCanceled:1}),o;if(st(o)){l.logger.warn("[SummarizationNode] Normal summarization failed with context limit error, falling back to truncation strategy",o);try{const{state:r,summarySize:i}=await de(e,n),s=Date.now()-t;return l.logger.info(`[SummarizationNode] Fallback truncation summarization metrics: summarySize=${i} chars, latencyMs=${s}`),C.reportCountMetrics({SummarizationSuccess:1,SummarizationWithTruncation:1,SummarizationFallbackToTruncation:1,SummarySize:i,LatencyMs:s}),r}catch(r){return l.logger.error("[SummarizationNode] Truncation fallback also failed",r),e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:n,actionType:"summarization",actionState:m.OperationStatus.Error,endTime:Date.now()}),C.reportCountMetrics({SummarizationError:1,SummarizationTruncationFallbackError:1}),{needsSummarization:!1,summarizationResult:void 0}}}return l.logger.error("[SummarizationNode] Summarization failed",o),e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:n,actionType:"summarization",actionState:m.OperationStatus.Error,endTime:Date.now()}),C.reportCountMetrics({SummarizationError:1}),{needsSummarization:!1,summarizationResult:void 0}}}async function Ne(e){try{const t=await We.getExecutionLogController().getExecution(e);if(!t?.actions)return l.logger.warn(`[TurnApproval] No actions array found for execution: ${e}`),[];const n=t.actions.filter(s=>(se.isFileChangeAction(s)||se.isSemanticRenameAction(s))&&s.actionState===m.OperationStatus.PendingAction),o=P.getExecutionLogger(),r=o.filterAwaitingUserDecision?o.filterAwaitingUserDecision(n.map(({actionId:s})=>s)):n.map(({actionId:s})=>s);return n.filter(({actionId:s})=>r.includes(s))}catch(t){return l.logger.warn(`[TurnApproval] Error querying execution log for ${e}:`,t),[]}}function Ce(e,t){const n=e.filter(s=>s.type==="toolUse");if(n.some(s=>s.name==="semanticRename"))return{skip:!1,currentFile:void 0};let o;for(const s of n){const c=s.args,a=c?.path||c?.file||c?.targetFile;if(a){if(o===void 0)o=a;else if(a!==o){o=void 0;break}}}const r=t?.[0];return{skip:!!(o&&o===r),currentFile:o}}async function Oe(e){const t=P.generateOperationId(`turn_approval_${Date.now()}`);await e.execution.acquireYield("turn-approval");const n=(o,r)=>({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:t,actionState:o,actionType:"userApproval",...r&&{errorMessage:r}});try{e.execution.emit(n(m.OperationStatus.PendingAction));let o;try{o=await fe.abortable(P.getExecutionLogger().awaitApproval(t),e.execution.abortController.signal)}catch{o=!1}if(o){try{await P.getPendingChangesService().applyPendingChanges({executionId:e.execution.executionId},i=>e.execution.emit({type:"AgentExecutionAction",...i}))}catch(r){return l.logger.error("[TurnApproval] Failed to apply pending changes:",r),e.execution.emit(n(m.OperationStatus.Error,r instanceof Error?r.message:String(r))),e.execution.abort(),{approved:!1,state:e}}e.execution.emit(n(m.OperationStatus.Success))}else{try{await P.getPendingChangesService().restorePendingChanges({executionId:e.execution.executionId},i=>e.execution.emit({type:"AgentExecutionAction",...i}))}catch(r){return l.logger.error("[TurnApproval] Failed to restore pending changes:",r),e.execution.emit(n(m.OperationStatus.Error,r instanceof Error?r.message:String(r))),e.execution.abort(),{approved:!1,state:e}}e.execution.emit(n(m.OperationStatus.Rejected)),e.execution.abort()}return{approved:o,state:e}}finally{try{await e.execution.releaseYield("turn-approval")}catch{}}}const A=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"UserHookNode"),ke=A.wrapTrace("UserHookNode",ct);async function ct(e,t){let n=e;for(const o of t)try{const r=await ut(n,o);if("shouldRestartGraph"in r&&r.shouldRestartGraph)return r;n=r}catch{switch(o){case m.IDEListenableEvent.UserPrompt:A.reportCountMetrics({userPromptFailed:1},{Operation:"kiroAgent.hooks.contextualFailures"});break;case m.IDEListenableEvent.AgentStop:A.reportCountMetrics({agentStopFailed:1},{Operation:"kiroAgent.hooks.contextualFailures"});break;default:A.reportCountMetrics({unknownTriggerFailed:1},{Operation:"kiroAgent.hooks.contextualFailures"});break}}return n}async function ut(e,t){const n=await he.extractHooks(t,e);if(n.length===0)return e;const o=lt(e,t),{state:r,userPromptText:i}=await dt(n,e,o);switch(t){case m.IDEListenableEvent.UserPrompt:return A.reportCountMetrics({userPromptTriggered:n.length},{Operation:"kiroAgent.hooks.contextualTriggers"}),gt(r,i,o.userPromptMessage);case m.IDEListenableEvent.AgentStop:{if(A.reportCountMetrics({agentStopTriggered:n.length},{Operation:"kiroAgent.hooks.contextualTriggers"}),i.trim()!==""){const c=h.ContextChatMessage.fromHuman().withText(i);return{...r,context:r.context.withNewMessage(c),shouldRestartGraph:!0}}return r}default:return r}}function lt(e,t){const n=e.context.messages.at(-1),r=[...e.context.messages].reverse().find(u=>{if(u.role!=="human")return!1;const g=u.entries[0];return g.type==="text"&&g.text.trim()!==""})?.entries[0],i=r?.type==="text"?r.text:"",s=i.indexOf("<ADDITIONAL_INSTRUCTIONS>"),c=s!==-1?i.substring(0,s).trim():i,a=n?.entries[0],d=a?.type==="text"?a.text:"";switch(t){case m.IDEListenableEvent.UserPrompt:return{userPromptMessage:n,cleanUserPrompt:c,startingPromptText:d};case m.IDEListenableEvent.AgentStop:return{cleanUserPrompt:"",startingPromptText:""};default:throw new Error(`Unsupported trigger type: ${t}`)}}async function dt(e,t,n){let o=n.startingPromptText,r=t;for(const i of e)try{i.action.type==="askAgent"?o=mt(r,i,o):r=await he.executeHookAction(i,r,n.cleanUserPrompt)}catch{i.action.type==="askAgent"?A.reportCountMetrics({askAgentActionFailed:1}):A.reportCountMetrics({runCommandActionFailed:1})}return{state:r,userPromptText:o}}function mt(e,t,n){t.name&&e.execution.emit({type:"AgentExecutionAction",executionId:e.execution.executionId,actionId:Ye.randomUUID(),actionState:m.OperationStatus.Success,actionType:"ContextualHookInvoked",input:{name:t.name,hookId:t.id,hookActionType:"askAgent"}});const o=t.action.type==="askAgent"?t.action.prompt:"";return n?`${n}

<ADDITIONAL_INSTRUCTIONS>
${o}
</ADDITIONAL_INSTRUCTIONS>`:o}function gt(e,t,n){const o=n?.entries[0];return o?.type==="text"&&o.text!==t&&(o.text=t),n&&(e.context=e.context.withNewMessage(n)),e}const pt=10,U="MODEL_INVOKE",Q="Setup",G="Cleanup",K="ImplicitRules",N="FAILURE_DETECTION",V="USER_INTERVENTION",B="TURN_APPROVAL_CHECK",Z="SUMMARIZATION_DETECTION",W="SUMMARIZATION_NODE",z="AGENT_STOP_HOOKS",b="SystemPrompt",ft=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"SpecAgentGraph");function Ue({stateDefinition:e=I.AgentGraphState,getAvailableTools:t,name:n,iterationLimit:o=pt,promptBuilder:r}){let i=new O.StateGraph(e);i=i.addNode(Q,a=>{l.logger.info(`[Tool agent ${n}] setup node`);let d=a.context;if(r){const u=new h.ContextChatMessage("human",[],b).withText(r(a)).withForcedRole();d.getMessageById(b)?d=d.withReplacedMessageById(b,u):d=d.withNewMessage(u)}return{...a,agentIterationLimit:o,context:d}}),i=i.addNode(U,async a=>{l.logger.info("[AgentIterator] Invoking agent"),a=await I.populateMatchedSteering(a),a.execution.state=a;let d=a.context;const u=a.execution.consumeQueuedUserMessage();if(u){l.logger.info("[SpecAgent] Appending queued user message to context");const M=h.ContextChatMessage.fromHuman().withText(u);d=d.withNewMessage(M)}const g=t(),{responseStream:f}=await a.execution.modelStream2(d,g),x={...a,context:d},T=await I.processChunkStream(x,f,g,ft);return T.execution.state=T,T}),i=i.addNode(K,Fe),i=i.addNode(N,Te),i=i.addNode(V,ye),i=i.addNode(B,async a=>{if(a.execution.autonomyMode!==je.AutonomyMode.Supervised||(await Ne(a.execution.executionId)).length===0)return a;const g=a.context.messages.findLast(M=>M.role==="bot")?.entries??[],{skip:f,currentFile:x}=Ce(g,a.lastTurnToolFiles);if(f&&x)return{...a,lastTurnToolFiles:[x]};const{state:T}=await Oe(a);return{...T,lastTurnToolFiles:x?[x]:void 0}}),i=i.addNode(Z,ve),i=i.addNode(W,Me),i=i.addNode(z,async a=>{if(a.execution.skipHooks)return a;if(a.onAgentStopHooksExecuted)return a.shouldRestartGraph=!1,a;{const d=await ke(a,[m.IDEListenableEvent.AgentStop]),u={...a,...d,onAgentStopHooksExecuted:!0};return u.execution.state=u,u}}),i=i.addNode(G,a=>(l.logger.info(`[Tool agent ${n}] cleanup node - resetting state values`),{...a,agentIterationNumber:0}));const s=a=>a.summarizationResult?.shouldSummarize?W:a.context.messages.at(-1)?.role==="tool"?N:a.execution.hasQueuedUserMessage()?(l.logger.info("[SpecAgent] Queued user message found - routing to MODEL_INVOKE"),U):z,c=a=>a.shouldRestartGraph?N:G;return i=i.addEdge(O.START,Q),i=i.addEdge(Q,K),i=i.addEdge(K,N),i=i.addConditionalEdges(N,Ee,[V,U]),i=i.addEdge(V,U),i=i.addEdge(U,B),i=i.addEdge(B,Z),i=i.addConditionalEdges(Z,s,[W,N,z,U]),i=i.addEdge(W,z),i=i.addConditionalEdges(z,c,[G,N]),i=i.addEdge(G,O.END),i.compile()}const L="tooluse_wsfiles";async function De(e,t){if(e=Array.from(new Set(e)),e.length===0)return[];const n={id:L,args:{paths:e},name:"readMultipleFiles",success:!0};let o=h.ContextChatMessage.fromTool(L);for(const r of e){const i=await h.serializeFile({type:"file",path:r},t);o=o.withDocument({document:{type:"file",path:r,staticContent:i}})}return[h.ContextChatMessage.fromAI(L+"__toolUse").withToolUse(n),o.withToolUseResponse(n)]}const ht=e=>{const t=pe.isExperimentsFeatureEnabled("requirementAnalyzer");return Le.getOrchestratorSystemPrompt(e,{requirementAnalyzerEnabled:t})},ne="ActionPhase",oe="SteeringNode";let E=new O.StateGraph(I.AgentGraphState);E=E.addNode(ne,e=>Ue({getAvailableTools:()=>{const t=pe.isExperimentsFeatureEnabled("mergeVibeSpec"),n=e.execution.agentModeOverride==="spec",o=t&&!n,r=o?e.execution.workspace.getSpecAgentTools():e.execution.workspace.getSpecOrchestratorTools();return l.logger.info("[SPEC_GRAPH] Tool selection:",{toolCount:r.length,toolIds:r.map(i=>i.id),isMergeVibeSpecEnabled:t,isSpecOrchestratorMode:n,useFullTools:o,agentModeOverride:e.execution.agentModeOverride}),r},name:"Action",iterationLimit:1e3}));E=E.addNode(oe,I.populateMatchedSteering);E=E.addEdge(O.START,oe);E=E.addEdge(oe,ne);E=E.addEdge(ne,O.END);const ze=E.compile();class Pe{rules=[];setRules(t){this.rules=[...t]}addRule(t){this.rules.push(t)}clearRules(){this.rules=[]}getRules(){return[...this.rules]}getCombinedRulesContent(){return this.rules.length===0?"":`<implicit-rules>## Implicit Rules
`+this.rules.join(`

`)+"</implicit-rules>"}}const me=`Focus on creating a new spec file or identifying an existing spec to update. 
If starting a new spec, first present the entry point choice to the user (Start with Requirements or Start with Design). 
Do not create any spec files until the user has made their choice.
If working with an existing spec, review the current spec files and suggest improvements if needed. 
Do not make direct code changes yet. First establish or review the spec file that will guide our implementation.`,St=`You are working on the requirements document. 
Make sure the requirements include clear user stories and acceptance criteria. 
If following the requirements-first workflow (no design.md exists yet), proceed to create design.md.
If following the design-first workflow (design.md already exists), proceed to create tasks.md.`,xt=`You are working on the design document. 

IMPORTANT: If you just created the design document in this same turn, do NOT ask for review yet. Wait for the user to see it first.

Check if requirements.md exists in the same directory:
- If requirements.md does NOT exist (design-first workflow): Proceed to create requirements.md based on the design.
- If requirements.md exists (requirements-first workflow): Proceed to create tasks.md.`,It=`You are working on the implementation plan. 
Ensure each task is actionable, references specific requirements, and focuses only on coding activities. 
Inform the user that the spec is complete and they can begin implementing the tasks by opening the tasks.md file.`;function j(e,t){return typeof e=="string"&&e.includes(t)}function Tt(e,t){const n=[];return e.name===_.ReadFile.id&&typeof e.args=="object"&&typeof e.args.path=="string"?n.push(e.args.path):e.name===_.ReadMultipleFiles.id&&typeof e.args=="object"&&Array.isArray(e.args.paths)&&n.push(...e.args.paths),n.length===0?!1:n.some(o=>j(o,t))}function Et(e,t){return typeof e.args!="object"?!1:e.name==="fsWrite"&&e.args.path&&j(e.args.path,t)||e.name==="fsAppend"&&e.args.path&&j(e.args.path,t)?!0:e.name==="strReplace"&&e.args.operations&&Array.isArray(e.args.operations)?e.args.operations.some(n=>n.path&&j(n.path,t)):!1}function wt(e){return e.name==="taskStatus"}function yt(e){return e.some(t=>t.entries.some(n=>n.type==="toolUse"&&wt(n)))}function J(e,t){let n=!1;return e.forEach(o=>{o.entries.some(i=>i.type==="toolUse"&&Tt(i,t))&&(n=!0)}),{wasAccessed:n}}function X(e,t){let n=-1,o=!1;return e.forEach((r,i)=>{r.entries.some(c=>c.type==="toolUse"&&Et(c,t))&&(n=i,o=!0)}),{lastWriteIndex:n,wasWritten:o}}function vt(e){const t=e.context.messages,n=J(t,"requirements.md"),o=J(t,"design.md"),r=J(t,"tasks.md"),i=X(t,"requirements.md"),s=X(t,"design.md"),c=X(t,"tasks.md");if(c.wasWritten||s.wasWritten||i.wasWritten){const a=Math.max(c.lastWriteIndex,s.lastWriteIndex,i.lastWriteIndex);if(a===c.lastWriteIndex&&c.wasWritten)return"implementation_plan";if(a===s.lastWriteIndex&&s.wasWritten)return"design";if(a===i.lastWriteIndex&&i.wasWritten)return"requirements"}return r.wasAccessed?"implementation_plan":o.wasAccessed?"design":n.wasAccessed?"requirements":"initial"}const w=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"SpecImplicitRules");function Fe(e){const t=new Pe,n=vt(e),o=e.context.messages,r=yt(o);if(w.reportCountMetrics({phaseDetection:1,[`phase.${n}`]:1}),r){w.reportCountMetrics({noRulesAdded:1,taskStatusUsedSkip:1});const s=e.context.withImplicitRules(t);return Promise.resolve({...e,context:s})}switch(n){case"initial":{t.addRule(me),w.reportCountMetrics({ruleAdded:1,"rule.initial":1});break}case"requirements":t.addRule(St),w.reportCountMetrics({ruleAdded:1,"rule.requirements":1});break;case"design":t.addRule(xt),w.reportCountMetrics({ruleAdded:1,"rule.design":1});break;case"implementation_plan":t.addRule(It),w.reportCountMetrics({ruleAdded:1,"rule.implementationPlan":1});break;default:e.context.messages.filter(s=>s.role==="human").length<=5?(t.addRule(me),w.reportCountMetrics({ruleAdded:1,"rule.initial":1})):w.reportCountMetrics({noRulesAdded:1})}w.reportCountMetrics({totalRulesAdded:t.getRules().length});const i=e.context.withImplicitRules(t);return Promise.resolve({...e,context:i})}var At=Object.defineProperty,Rt=Object.getOwnPropertyDescriptor,Mt=(e,t,n,o)=>{for(var r=Rt(t,n),i=e.length-1,s;i>=0;i--)(s=e[i])&&(r=s(t,n,r)||r);return r&&At(t,n,r),r};const ge=1e3,Nt=1e4,Ct=R.getMetricReporterOrNoOp(m.TelemetryNamespace.Agent,"SpecGenerationGraph");function ee(e){return"messages"in e}class _e extends I.ExecutionDefinition{constructor(t){let n="Spec Generation";if(ee(t.input)){const o=[...t.input.messages].reverse().find(r=>r.role==="user");if(o)if(typeof o.content=="string")n=o.content;else{const{entireMessage:r}=Y.parseMessagePartArray(o.content);n=r}}else n=t.input.prompt??t.input.userPrompt??n;super({type:Se.SpecGeneration,...t,title:t.input.title??t.title??"Generate Spec",titlePrompt:n})}async build(t){return ee(t.input)?this.buildFromMessages(t):this.buildFromPrompt(t)}async buildFromMessages(t){const{input:n,inputDocuments:o,chatSessionId:r,workspace:i}=t,s=n.messages.slice().reverse().find(p=>p.role==="user"),a=n.messagesFromExecutionId.some(p=>p.messageId===I.FILE_TREE_MESSAGE_ID),d=D.mapSpecContextItemToContextDocuments(n.context??[]).files,u=o.filter(p=>p.type==="file").map(p=>p.path),g=[...d.map(p=>p.path),...u],f=this.getSystemPromptMessages(i);if(a||f.push(...await I.getFileTreeContext({expandedPaths:[`${H.PRODUCT_CONFIG_DIRECTORY}/${H.SPECS_DIRECTORY}`,...g],target:500,workspace:i})),n.messagesFromExecutionId.length>0&&f.push(...n.messagesFromExecutionId),s){let p=h.ContextChatMessage.fromHuman();if(typeof s.content=="string")p=p.withText(s.content);else{const{entireMessage:k,imageBase64Urls:q,documentAttachments:$}=Y.parseMessagePartArray(s.content);p=p.withText(k),q.length>0&&(p=p.withImages(q.map(v=>({image:v})))),$.length>0&&(p=p.withDocumentAttachments($.map(v=>({data:v.data,name:v.name,mimeType:v.mimeType}))))}f.push(p.withEnvironmentInfo())}f.at(-1)?.role==="bot"&&f.push(h.ContextChatMessage.fromHuman().withText("Now follow the instruction."));const x=D.getSpecPlatformProvider(),T=x.loadOpenEditorFiles(),M=x.loadCurrentFile()||"",y=t.getFastModelClient("intent-classification");return{inputParams:this.input,agentIterationLimit:ge,continuationId:this.preservedContinuationId??I.createContinuationId(),context:f.reduce((p,k)=>p.withNewMessage(k),ie.ModelContext.empty()),chatSessionId:r,specTaskId:n.taskId,intentDetectionService:new re.IntentDetectionService(y.modelId,y.modelClient),openFiles:T,activeFile:M}}async buildFromPrompt(t){const{input:n,imageBase64Urls:o,documentAttachments:r,inputDocuments:i,workspace:s,chatSessionId:c}=t,{previousMessages:a}=n,d=D.mapSpecContextItemToContextDocuments(n.context??[]).files,u=i.filter(S=>S.type==="file").map(S=>S.path),g=this.getSystemPromptMessages(s),f=[...d.map(S=>S.path),...u];a?.some(S=>S.messageId===I.FILE_TREE_MESSAGE_ID)||g.push(...await I.getFileTreeContext({expandedPaths:[`${H.PRODUCT_CONFIG_DIRECTORY}/${H.SPECS_DIRECTORY}`,...f],target:500,workspace:s})),a?.some(S=>S.messageId===L)||g.push(...await De(f,s)),a&&g.push(h.ContextChatMessage.fromAI().withText("Understood."),...a);const M=n.prompt??n.userPrompt??"";let y=h.ContextChatMessage.fromHuman().withText(M).withEnvironmentInfo();o.length!==0&&(y=y.withImages(o.map(S=>({image:S})))),r.length>0&&(y=y.withDocumentAttachments(r.map(S=>({data:S.data,name:S.name,mimeType:S.mimeType})))),g.push(y),g.at(-1)?.role==="bot"&&g.push(h.ContextChatMessage.fromHuman().withText("Now follow the instruction."));const p=g.reduce((S,be)=>S.withNewMessage(be),ie.ModelContext.empty()),k=D.getSpecPlatformProvider(),q=k.loadOpenEditorFiles(),$=k.loadCurrentFile()||"",v=t.getFastModelClient("intent-classification");return{inputParams:this.input,agentIterationLimit:ge,context:p,chatSessionId:c,continuationId:this.preservedContinuationId??I.createContinuationId(),specTaskId:n.taskId,intentDetectionService:new re.IntentDetectionService(v.modelId,v.modelClient),openFiles:q,activeFile:$}}getSystemPromptMessages(t){return[new h.ContextChatMessage("human",[],b).withText("# Additional Instructions").withText(ht(t).format({machineId:D.getSpecPlatformProvider().getMachineId()})).withForcedRole(),h.ContextChatMessage.fromAI().withText("I will follow these instructions.").withForcedRole()]}async invoke(t){return await ze.invoke(await t.getState(),{recursionLimit:Nt,signal:t.abortController.signal}),{status:I.AgentStopReason.Success,executionId:t.executionId,result:{}}}}Mt([Ct.Trace()],_e.prototype,"invoke");exports.ImplicitRules=Pe;exports.OPEN_FILES_MESSAGE_ID=L;exports.SYSTEM_PROMPT_MESSAGE_ID=b;exports.SpecGenerationDefinition=_e;exports.SpecGenerationGraph=ze;exports.createSpecAgent=Ue;exports.failureDetectionNode=Te;exports.failureDetectionRouter=Ee;exports.getOpenFilesContext=De;exports.getPendingFileActions=Ne;exports.isMessagesInput=ee;exports.manageSpecImplicitRules=Fe;exports.shouldSkipTurnApproval=Ce;exports.summarizationDetectionNode=ve;exports.summarizationDetectionRouter=ot;exports.summarizationNode=Me;exports.userHookNode=ke;exports.userInterventionNode=ye;exports.yieldForTurnApproval=Oe;
//# sourceMappingURL=index-DBXhCZBu.cjs.map
