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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type { Task as SDKTask } from '@a2a-js/sdk';
import type {
  TaskStore,
  AgentExecutor,
  AgentExecutionEvent,
  RequestContext,
  ExecutionEventBus,
} from '@a2a-js/sdk/server';
import {
  GeminiEventType,
  SimpleExtensionLoader,
  type ToolCallRequestInfo,
  type Config,
  resolveToRealPath,
} from '@google/gemini-cli-core';
import { v4 as uuidv4 } from 'uuid';

import { logger } from '../utils/logger.js';
import {
  CoderAgentEvent,
  getPersistedState,
  setPersistedState,
  type StateChange,
  type AgentSettings,
  type PersistedStateMetadata,
  getContextIdFromMetadata,
  getAgentSettingsFromMetadata,
} from '../types.js';
import {
  loadConfig,
  setTargetDir,
  setIsTrusted,
  envStorage,
  cwdSymbol,
  loadEnvironment,
  type TaskEnv,
} from '../config/config.js';
import { loadSettings } from '../config/settings.js';
import { loadExtensions } from '../config/extension.js';
import { Task } from './task.js';
import { requestStorage } from '../http/requestStorage.js';
import { pushTaskStateFailed } from '../utils/executor_utils.js';

function validateWorkspacePath(workspacePath?: string): string {
  const trimmed = workspacePath?.trim();
  if (!trimmed) {
    return process.env['CODER_AGENT_WORKSPACE_PATH'] ?? process.cwd();
  }
  return resolveToRealPath(trimmed);
}

/**
 * Provides a wrapper for Task. Passes data from Task to SDKTask.
 * The idea is to use this class inside CoderAgentExecutor to replace Task.
 */
class TaskWrapper {
  task: Task;
  agentSettings: AgentSettings;

  constructor(task: Task, agentSettings: AgentSettings) {
    this.task = task;
    this.agentSettings = agentSettings;
  }

  get id() {
    return this.task.id;
  }

  toSDKTask(): SDKTask {
    const persistedState: PersistedStateMetadata = {
      _agentSettings: this.agentSettings,
      _taskState: this.task.taskState,
    };

    const sdkTask: SDKTask = {
      id: this.task.id,
      contextId: this.task.contextId,
      kind: 'task',
      status: {
        state: this.task.taskState,
        timestamp: new Date().toISOString(),
      },
      metadata: setPersistedState({}, persistedState),
      history: [],
      artifacts: [],
    };
    sdkTask.metadata!['_contextId'] = this.task.contextId;
    return sdkTask;
  }
}

/**
 * CoderAgentExecutor implements the agent's core logic for code generation.
 */
export class CoderAgentExecutor implements AgentExecutor {
  private tasks: Map<string, TaskWrapper> = new Map();
  // Track tasks with an active execution loop.
  private executingTasks = new Map<string, AbortController>();
  private activeAbortControllers = new Map<string, Set<AbortController>>();
  // Track tasks currently initializing to prevent race conditions.
  private initializingTasks = new Set<string>();
  private initializationPromises = new Map<string, Promise<TaskWrapper>>();
  // Track explicitly canceled abort controllers to handle cancellation during initialization.
  private explicitlyCanceledTasks = new Set<AbortController>();

  constructor(private taskStore?: TaskStore) {}

  private async getConfigWithEnv(
    agentSettings: AgentSettings,
    taskId: string,
    isTrusted: boolean,
    workspaceRoot: string,
  ): Promise<Config> {
    const settings = loadSettings(workspaceRoot, isTrusted);
    const extensions = loadExtensions(workspaceRoot, isTrusted);
    return loadConfig(
      settings,
      new SimpleExtensionLoader(extensions),
      taskId,
      isTrusted,
      workspaceRoot,
    );
  }

  private async runInIsolatedEnv<T>(
    agentSettings: AgentSettings,
    fn: (isTrusted: boolean, workspaceRoot: string) => Promise<T>,
  ): Promise<T> {
    const workspaceRoot = await setTargetDir(agentSettings);
    const isTrusted = setIsTrusted(agentSettings, workspaceRoot);

    const envVars: TaskEnv = { ...process.env };
    envVars['GEMINI_CLI_TRUST_WORKSPACE'] = isTrusted ? 'true' : 'false';
    envVars[cwdSymbol] = workspaceRoot;

    return envStorage.run(envVars, async () => {
      const loadedEnv = await loadEnvironment(isTrusted, workspaceRoot);
      Object.assign(envVars, loadedEnv);
      return fn(isTrusted, workspaceRoot);
    });
  }

  private cleanupAndEvictTask(taskId: string, expectedWrapper?: TaskWrapper) {
    const wrapper = this.tasks.get(taskId);
    if (wrapper) {
      if (expectedWrapper && wrapper !== expectedWrapper) {
        logger.info(
          `[CoderAgentExecutor] cleanupAndEvictTask: wrapper mismatch for task ${taskId}. Skipping eviction.`,
        );
        return;
      }
      wrapper.task.dispose();
      this.tasks.delete(taskId);
    }
  }

  /**
   * Reconstructs TaskWrapper from SDKTask.
   */
  async reconstruct(
    sdkTask: SDKTask,
    eventBus?: ExecutionEventBus,
  ): Promise<TaskWrapper> {
    const metadata = sdkTask.metadata || {};
    const persistedState = getPersistedState(metadata);

    if (!persistedState) {
      throw new Error(
        `Cannot reconstruct task ${sdkTask.id}: missing persisted state in metadata.`,
      );
    }

    let agentSettings: AgentSettings;
    try {
      agentSettings = {
        ...(persistedState._agentSettings ?? {}),
        workspacePath: validateWorkspacePath(
          persistedState._agentSettings?.workspacePath,
        ),
        isTrusted: false,
      };
    } catch (error) {
      logger.error(
        `[CoderAgentExecutor] Invalid workspace path in persisted state for task ${sdkTask.id}:`,
        error,
      );
      if (eventBus) {
        void pushTaskStateFailed(
          error,
          eventBus,
          sdkTask.id,
          sdkTask.contextId,
        );
      }
      throw error; // Re-throw to be caught by caller
    }

    return this.runInIsolatedEnv(
      agentSettings,
      async (isTrusted, workspaceRoot) => {
        const config = await this.getConfigWithEnv(
          agentSettings,
          sdkTask.id,
          isTrusted,
          workspaceRoot,
        );
        const contextId: string =
          getContextIdFromMetadata(metadata) || sdkTask.contextId;
        const runtimeTask = await Task.create(
          sdkTask.id,
          contextId,
          config,
          eventBus,
          agentSettings.autoExecute,
        );
        runtimeTask.taskState = persistedState._taskState;
        await runtimeTask.geminiClient.initialize();

        const wrapper = new TaskWrapper(runtimeTask, agentSettings);
        this.tasks.set(sdkTask.id, wrapper);
        logger.info(`Task ${sdkTask.id} reconstructed from store.`);
        return wrapper;
      },
    );
  }

  async createTask(
    taskId: string,
    contextId: string,
    agentSettingsInput?: AgentSettings,
    eventBus?: ExecutionEventBus,
  ): Promise<TaskWrapper> {
    const agentSettings: AgentSettings = agentSettingsInput || {
      kind: CoderAgentEvent.StateAgentSettingsEvent,
      workspacePath: process.cwd(),
    };
    return this.runInIsolatedEnv(
      agentSettings,
      async (isTrusted, workspaceRoot) => {
        const config = await this.getConfigWithEnv(
          agentSettings,
          taskId,
          isTrusted,
          workspaceRoot,
        );
        const runtimeTask = await Task.create(
          taskId,
          contextId,
          config,
          eventBus,
          agentSettings.autoExecute,
        );
        await runtimeTask.geminiClient.initialize();

        const wrapper = new TaskWrapper(runtimeTask, agentSettings);
        this.tasks.set(taskId, wrapper);
        logger.info(`New task ${taskId} created.`);
        return wrapper;
      },
    );
  }

  getTask(taskId: string): TaskWrapper | undefined {
    return this.tasks.get(taskId);
  }

  getAllTasks(): TaskWrapper[] {
    return Array.from(this.tasks.values());
  }

  cancelTask = async (
    taskId: string,
    eventBus: ExecutionEventBus,
  ): Promise<void> => {
    logger.info(
      `[CoderAgentExecutor] Received cancel request for task ${taskId}`,
    );

    const abortControllers = this.activeAbortControllers.get(taskId);
    if (abortControllers && abortControllers.size > 0) {
      logger.info(
        `[CoderAgentExecutor] Aborting ${abortControllers.size} active execution loop(s) for task ${taskId}.`,
      );
      // Abort first to ensure loops are stopped.
      for (const controller of Array.from(abortControllers)) {
        this.explicitlyCanceledTasks.add(controller);
        controller.abort();
      }

      // Then, attempt to update state and persist.
      const wrapper = this.tasks.get(taskId);
      if (wrapper) {
        const { task } = wrapper;
        task.cancelPendingTools('Task canceled by user request.');
        task.setTaskStateAndPublishUpdate(
          'canceled',
          { kind: CoderAgentEvent.StateChangeEvent },
          'Task canceled by user request.',
          undefined,
          true,
        );
        this.cleanupAndEvictTask(taskId, wrapper);
        try {
          await this.taskStore?.save(wrapper.toSDKTask());
          logger.info(
            `[CoderAgentExecutor] Task ${taskId} state CANCELED saved during active abort.`,
          );
        } catch (saveError) {
          logger.error(
            `[CoderAgentExecutor] Failed to save task ${taskId} state during active abort:`,
            saveError,
          );
        }
      }
      return;
    }

    // If there is no active execution loop, the task is idle.
    // We can clean it up directly.
    logger.info(
      `[CoderAgentExecutor] No active execution for task ${taskId}. Cleaning up directly.`,
    );
    const wrapper = this.tasks.get(taskId);

    if (!wrapper) {
      logger.warn(
        `[CoderAgentExecutor] Task ${taskId} not found for cancellation.`,
      );
      eventBus.publish({
        kind: 'status-update',
        taskId,
        contextId: uuidv4(),
        status: {
          state: 'failed',
          message: {
            kind: 'message',
            role: 'agent',
            parts: [{ kind: 'text', text: `Task ${taskId} not found.` }],
            messageId: uuidv4(),
            taskId,
          },
        },
        final: true,
      });
      return;
    }

    const { task } = wrapper;

    if (task.taskState === 'canceled' || task.taskState === 'failed') {
      logger.info(
        `[CoderAgentExecutor] Task ${taskId} is already in a final state: ${task.taskState}. No action needed for cancellation.`,
      );
      eventBus.publish({
        kind: 'status-update',
        taskId,
        contextId: task.contextId,
        status: {
          state: task.taskState,
          message: {
            kind: 'message',
            role: 'agent',
            parts: [
              {
                kind: 'text',
                text: `Task ${taskId} is already ${task.taskState}.`,
              },
            ],
            messageId: uuidv4(),
            taskId,
          },
        },
        final: true,
      });
      return;
    }

    try {
      logger.info(
        `[CoderAgentExecutor] Initiating cancellation for task ${taskId}.`,
      );
      task.cancelPendingTools('Task canceled by user request.');

      const stateChange: StateChange = {
        kind: CoderAgentEvent.StateChangeEvent,
      };
      task.setTaskStateAndPublishUpdate(
        'canceled',
        stateChange,
        'Task canceled by user request.',
        undefined,
        true,
      );
      logger.info(
        `[CoderAgentExecutor] Task ${taskId} cancellation processed. Saving state.`,
      );
      // Cleanup listener subscriptions and evict synchronously before async save
      this.cleanupAndEvictTask(taskId, wrapper);

      await this.taskStore?.save(wrapper.toSDKTask());
      logger.info(`[CoderAgentExecutor] Task ${taskId} state CANCELED saved.`);
    } catch (error) {
      const errorMessage =
        error instanceof Error ? error.message : 'Unknown error';
      logger.error(
        `[CoderAgentExecutor] Error during task cancellation for ${taskId}: ${errorMessage}`,
        error,
      );
      eventBus.publish({
        kind: 'status-update',
        taskId,
        contextId: task.contextId,
        status: {
          state: 'failed',
          message: {
            kind: 'message',
            role: 'agent',
            parts: [
              {
                kind: 'text',
                text: `Failed to process cancellation for task ${taskId}: ${errorMessage}`,
              },
            ],
            messageId: uuidv4(),
            taskId,
          },
        },
        final: true,
      });
    }
  };

  async execute(
    requestContext: RequestContext,
    eventBus: ExecutionEventBus,
  ): Promise<void> {
    const userMessage = requestContext.userMessage;
    const sdkTask = requestContext.task;

    const taskId = sdkTask?.id || userMessage.taskId || uuidv4();
    const contextId: string =
      userMessage.contextId ||
      sdkTask?.contextId ||
      getContextIdFromMetadata(sdkTask?.metadata) ||
      uuidv4();

    let agentSettings: AgentSettings;
    try {
      const existingWrapper = this.tasks.get(taskId);
      if (existingWrapper) {
        agentSettings = existingWrapper.agentSettings;
      } else if (sdkTask) {
        const persistedState = getPersistedState(sdkTask.metadata || {});
        agentSettings = {
          kind: CoderAgentEvent.StateAgentSettingsEvent,
          ...(persistedState?._agentSettings ?? {}),
          workspacePath: validateWorkspacePath(
            persistedState?._agentSettings?.workspacePath,
          ),
          isTrusted: false,
        };
      } else {
        const rawAgentSettings = getAgentSettingsFromMetadata(
          userMessage.metadata,
        );
        agentSettings = {
          kind: CoderAgentEvent.StateAgentSettingsEvent,
          ...(rawAgentSettings || {}),
          workspacePath: validateWorkspacePath(rawAgentSettings?.workspacePath),
          isTrusted: false,
        };
      }
    } catch (error) {
      logger.error(
        `[CoderAgentExecutor] Invalid workspace path during execution setup for task ${taskId}:`,
        error,
      );
      if (eventBus) {
        void pushTaskStateFailed(error, eventBus, taskId, contextId);
      }
      throw error;
    }

    return this.runInIsolatedEnv(agentSettings, async () => {
      try {
        logger.info(
          `[CoderAgentExecutor] Executing for taskId: ${taskId}, contextId: ${contextId}`,
        );
        logger.info(
          `[CoderAgentExecutor] userMessage: ${JSON.stringify(userMessage)}`,
        );
        eventBus.on('event', (event: AgentExecutionEvent) =>
          logger.info('[EventBus event]: ', event),
        );

        const store = requestStorage.getStore();
        if (!store) {
          logger.error(
            '[CoderAgentExecutor] Could not get request from async local storage. Cancellation on socket close will not be handled for this request.',
          );
        }

        const abortController = new AbortController();
        const abortSignal = abortController.signal;

        if (!this.activeAbortControllers.has(taskId)) {
          this.activeAbortControllers.set(taskId, new Set());
        }
        this.activeAbortControllers.get(taskId)!.add(abortController);

        let proceedToMainLoop = false;
        let wrapper: TaskWrapper | undefined;
        let isPrimaryExecution = false;

        try {
          if (store) {
            const socket = store.req.socket;
            const onSocketEnd = () => {
              logger.info(
                `[CoderAgentExecutor] Socket ended for message ${userMessage.messageId} (task ${taskId}). Aborting execution loop.`,
              );
              if (!abortController.signal.aborted) {
                abortController.abort();
              }
              socket.removeListener('end', onSocketEnd);
            };
            socket.on('end', onSocketEnd);
            socket.once('close', () =>
              socket.removeListener('end', onSocketEnd),
            );
            abortSignal.addEventListener('abort', () =>
              socket.removeListener('end', onSocketEnd),
            );
            logger.info(
              `[CoderAgentExecutor] Socket close handler set up for task ${taskId}.`,
            );
          }

          // Check if the task is currently initializing
          if (this.initializingTasks.has(taskId)) {
            logger.info(
              `[CoderAgentExecutor] Task ${taskId} is currently initializing. Waiting for initialization to complete.`,
            );
            const initPromise = this.initializationPromises.get(taskId);
            if (initPromise) {
              try {
                wrapper = await initPromise;
              } catch {
                logger.error(
                  `[CoderAgentExecutor] Failed to wait for task ${taskId} initialization.`,
                );
                return;
              }
            }
          }

          if (!wrapper) {
            this.initializingTasks.add(taskId);
            const initPromise = (async () => {
              let initializedWrapper: TaskWrapper | undefined;
              initializedWrapper = this.tasks.get(taskId);

              if (initializedWrapper) {
                initializedWrapper.task.eventBus = eventBus;
                logger.info(
                  `[CoderAgentExecutor] Task ${taskId} found in memory cache.`,
                );
              } else if (sdkTask) {
                logger.info(
                  `[CoderAgentExecutor] Task ${taskId} found in TaskStore. Reconstructing...`,
                );
                try {
                  initializedWrapper = await this.reconstruct(
                    sdkTask,
                    eventBus,
                  );
                } catch (e) {
                  logger.error(
                    `[CoderAgentExecutor] Aborting execution due to failed task reconstruction for task ${taskId}:`,
                    e,
                  );
                  throw e;
                }
              } else {
                initializedWrapper = await this.createTask(
                  taskId,
                  contextId,
                  agentSettings,
                  eventBus,
                );
                const newTaskSDK = initializedWrapper.toSDKTask();
                eventBus.publish({
                  ...newTaskSDK,
                  kind: 'task',
                  status: {
                    state: 'submitted',
                    timestamp: new Date().toISOString(),
                  },
                  history: [userMessage],
                });
                try {
                  await this.taskStore?.save(newTaskSDK);
                  logger.info(
                    `[CoderAgentExecutor] New task ${taskId} saved to store.`,
                  );
                } catch (saveError) {
                  logger.error(
                    `[CoderAgentExecutor] Failed to save new task ${taskId} to store:`,
                    saveError,
                  );
                }
              }
              return initializedWrapper;
            })();

            this.initializationPromises.set(taskId, initPromise);

            try {
              wrapper = await initPromise;
            } catch {
              // Error is already handled/logged inside the promise
              return;
            } finally {
              this.initializingTasks.delete(taskId);
              this.initializationPromises.delete(taskId);
            }
          }

          if (!wrapper) {
            logger.error(
              `[CoderAgentExecutor] Task ${taskId} is unexpectedly undefined after load/create.`,
            );
            return;
          }

          const currentTask = wrapper.task;

          if (
            ['canceled', 'failed', 'completed'].includes(currentTask.taskState)
          ) {
            logger.info(
              `[CoderAgentExecutor] Re-activating task ${taskId} from terminal state ${currentTask.taskState}.`,
            );
            currentTask.taskState = 'submitted';
          }

          if (abortSignal.aborted) {
            logger.warn(
              `[CoderAgentExecutor] Task ${taskId} was aborted during initialization.`,
            );
            const isExplicitCancel =
              this.explicitlyCanceledTasks.has(abortController);
            const finalState = isExplicitCancel ? 'canceled' : 'input-required';
            const message = isExplicitCancel
              ? 'Task canceled by user request.'
              : 'Execution aborted by client.';
            currentTask.setTaskStateAndPublishUpdate(
              finalState,
              { kind: CoderAgentEvent.StateChangeEvent },
              message,
              undefined,
              true,
            );
            try {
              await this.taskStore?.save(wrapper.toSDKTask());
            } catch (saveError) {
              logger.error(
                `[CoderAgentExecutor] Failed to save task ${taskId} state:`,
                saveError,
              );
            }
            if (isExplicitCancel) {
              this.cleanupAndEvictTask(taskId, wrapper);
            }
            return;
          }

          const activeController = this.executingTasks.get(taskId);
          if (activeController && !activeController.signal.aborted) {
            logger.info(
              `[CoderAgentExecutor] Task ${taskId} has a pending execution. Processing message and yielding.`,
            );
            currentTask.eventBus = eventBus;
            try {
              for await (const _ of currentTask.acceptUserMessage(
                requestContext,
                abortController.signal,
              )) {
                logger.info(
                  `[CoderAgentExecutor] Processing user message ${userMessage.messageId} in secondary execution loop for task ${taskId}.`,
                );
              }
            } catch (error) {
              if (!abortController.signal.aborted) {
                throw error;
              }
              logger.info(
                `[CoderAgentExecutor] Secondary execution loop for task ${taskId} was aborted.`,
              );
            }
            return;
          }

          isPrimaryExecution = true;

          proceedToMainLoop = true;
        } finally {
          this.explicitlyCanceledTasks.delete(abortController);
          if (!proceedToMainLoop) {
            const controllers = this.activeAbortControllers.get(taskId);
            if (controllers) {
              controllers.delete(abortController);
              if (controllers.size === 0) {
                this.activeAbortControllers.delete(taskId);
              }
            }
          }
        }

        const currentTask = wrapper.task;
        try {
          logger.info(
            `[CoderAgentExecutor] Starting main execution for message ${userMessage.messageId} for task ${taskId}.`,
          );
          this.executingTasks.set(taskId, abortController);

          let agentTurnActive = true;
          logger.info(
            `[CoderAgentExecutor] Task ${taskId}: Processing user turn.`,
          );
          let agentEvents = currentTask.acceptUserMessage(
            requestContext,
            abortSignal,
          );

          while (agentTurnActive) {
            if (abortSignal.aborted) {
              logger.info(
                `[CoderAgentExecutor] Task ${taskId} aborted before turn. Exiting loop.`,
              );
              throw new Error('Execution aborted');
            }
            logger.info(
              `[CoderAgentExecutor] Task ${taskId}: Processing agent turn (LLM stream).`,
            );
            const toolCallRequests: ToolCallRequestInfo[] = [];
            for await (const event of agentEvents) {
              if (abortSignal.aborted) {
                logger.warn(
                  `[CoderAgentExecutor] Task ${taskId}: Abort signal received during agent event processing.`,
                );
                throw new Error('Execution aborted');
              }
              if (event.type === GeminiEventType.ToolCallRequest) {
                toolCallRequests.push(event.value);
                continue;
              }
              await currentTask.acceptAgentMessage(event);
            }

            if (abortSignal.aborted) throw new Error('Execution aborted');

            if (toolCallRequests.length > 0) {
              logger.info(
                `[CoderAgentExecutor] Task ${taskId}: Found ${toolCallRequests.length} tool call requests. Scheduling as a batch.`,
              );
              await currentTask.scheduleToolCalls(
                toolCallRequests,
                abortSignal,
              );
            }

            logger.info(
              `[CoderAgentExecutor] Task ${taskId}: Waiting for pending tools if any.`,
            );
            await currentTask.waitForPendingTools();
            logger.info(
              `[CoderAgentExecutor] Task ${taskId}: All pending tools completed or none were pending.`,
            );

            if (abortSignal.aborted) throw new Error('Execution aborted');

            if (currentTask.hasPendingTools) {
              logger.info(
                `[CoderAgentExecutor] Task ${taskId}: There are still ${currentTask.pendingToolsCount} pending tools waiting for approval. Yielding to user.`,
              );
              agentTurnActive = false;
            } else {
              const completedTools = currentTask.getAndClearCompletedTools();

              if (completedTools.length > 0) {
                if (
                  completedTools.every((tool) => tool.status === 'cancelled')
                ) {
                  logger.info(
                    `[CoderAgentExecutor] Task ${taskId}: All tool calls were cancelled. Updating history and ending agent turn.`,
                  );
                  currentTask.addToolResponsesToHistory(completedTools);
                  agentTurnActive = false;
                  const stateChange: StateChange = {
                    kind: CoderAgentEvent.StateChangeEvent,
                  };
                  currentTask.setTaskStateAndPublishUpdate(
                    'input-required',
                    stateChange,
                    undefined,
                    undefined,
                    true,
                  );
                } else {
                  logger.info(
                    `[CoderAgentExecutor] Task ${taskId}: Found ${completedTools.length} completed tool calls. Sending results back to LLM.`,
                  );

                  agentEvents = currentTask.sendCompletedToolsToLlm(
                    completedTools,
                    abortSignal,
                  );
                }
              } else {
                logger.info(
                  `[CoderAgentExecutor] Task ${taskId}: No more tool calls to process. Ending agent turn.`,
                );
                agentTurnActive = false;
              }
            }
          }

          logger.info(
            `[CoderAgentExecutor] Task ${taskId}: Agent turn finished, setting to input-required.`,
          );
          const stateChange: StateChange = {
            kind: CoderAgentEvent.StateChangeEvent,
          };
          currentTask.setTaskStateAndPublishUpdate(
            'input-required',
            stateChange,
            undefined,
            undefined,
            true,
          );
        } catch (error) {
          if (abortSignal.aborted) {
            logger.warn(
              `[CoderAgentExecutor] Task ${taskId} execution aborted.`,
            );
            currentTask.cancelPendingTools('Execution aborted');
            if (
              currentTask.taskState !== 'canceled' &&
              currentTask.taskState !== 'failed'
            ) {
              currentTask.setTaskStateAndPublishUpdate(
                'input-required',
                { kind: CoderAgentEvent.StateChangeEvent },
                'Execution aborted by client.',
                undefined,
                true,
              );
            }
          } else {
            const errorMessage =
              error instanceof Error ? error.message : 'Agent execution error';
            logger.error(
              `[CoderAgentExecutor] Error executing agent for task ${taskId}:`,
              error,
            );
            currentTask.cancelPendingTools(errorMessage);
            if (currentTask.taskState !== 'failed') {
              const stateChange: StateChange = {
                kind: CoderAgentEvent.StateChangeEvent,
              };
              currentTask.setTaskStateAndPublishUpdate(
                'failed',
                stateChange,
                errorMessage,
                undefined,
                true,
              );
            }
          }
        } finally {
          if (isPrimaryExecution) {
            const controllers = this.activeAbortControllers.get(taskId);
            if (controllers) {
              controllers.delete(abortController);
              if (controllers.size === 0) {
                this.activeAbortControllers.delete(taskId);
              }
            }
            if (this.executingTasks.get(taskId) === abortController) {
              this.executingTasks.delete(taskId);
            }
            if (
              ['canceled', 'failed', 'completed'].includes(
                currentTask.taskState,
              )
            ) {
              this.cleanupAndEvictTask(taskId, wrapper);
            }
            logger.info(
              `[CoderAgentExecutor] Saving final state for task ${taskId}.`,
            );
            try {
              await this.taskStore?.save(wrapper.toSDKTask());
              logger.info(`[CoderAgentExecutor] Task ${taskId} state saved.`);
            } catch (saveError) {
              logger.error(
                `[CoderAgentExecutor] Failed to save task ${taskId} state in finally block:`,
                saveError,
              );
            }
          }
        }
      } catch (error) {
        logger.error(
          `[CoderAgentExecutor] Failed to execute task ${taskId}:`,
          error,
        );
        void pushTaskStateFailed(error, eventBus, taskId, contextId);
        throw error;
      }
    }).catch((error) => {
      logger.error(
        `[CoderAgentExecutor] Failed to initialize isolated environment for task ${taskId}:`,
        error,
      );
      if (eventBus) {
        void pushTaskStateFailed(error, eventBus, taskId, contextId);
      }
      throw error;
    });
  }
}