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66
67
68
69
70
71
72
73
74
75
76
77
78
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
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview LocalSubagentProtocol — wraps LocalAgentExecutor behind the
 * AgentProtocol interface, translating SubagentActivityEvent callbacks into
 * AgentEvents and exposing the executor result via getResult().
 *
 * Pattern mirrors LegacyAgentProtocol, but the loop body runs
 * LocalAgentExecutor instead of GeminiClient.sendMessageStream().
 */

import { randomUUID } from 'node:crypto';
import type { AgentLoopContext } from '../config/agent-loop-context.js';
import { AgentSession } from '../agent/agent-session.js';
import type {
  AgentProtocol,
  AgentSend,
  AgentEvent,
  StreamEndReason,
  Unsubscribe,
  ContentPart,
} from '../agent/types.js';
import { LocalAgentExecutor } from './local-executor.js';
import {
  AgentTerminateMode,
  type LocalAgentDefinition,
  type AgentInputs,
  type OutputObject,
  type SubagentActivityEvent,
} from './types.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function isAbortLikeError(err: unknown): boolean {
  return err instanceof Error && err.name === 'AbortError';
}

function mapTerminateMode(mode: AgentTerminateMode): StreamEndReason {
  switch (mode) {
    case AgentTerminateMode.GOAL:
      return 'completed';
    case AgentTerminateMode.TIMEOUT:
      return 'max_time';
    case AgentTerminateMode.MAX_TURNS:
      return 'max_turns';
    case AgentTerminateMode.ABORTED:
      return 'aborted';
    case AgentTerminateMode.ERROR:
    case AgentTerminateMode.ERROR_NO_COMPLETE_TASK_CALL:
      return 'failed';
    default: {
      void (mode satisfies never);
      return 'failed';
    }
  }
}

// ---------------------------------------------------------------------------
// LocalSubagentProtocol
// ---------------------------------------------------------------------------

class LocalSubagentProtocol implements AgentProtocol {
  private _events: AgentEvent[] = [];
  private _subscribers = new Set<(event: AgentEvent) => void>();
  private _streamId: string = randomUUID();
  private _eventCounter = 0;
  private _agentStartEmitted = false;
  private _agentEndEmitted = false;
  private _activeStreamId: string | undefined;
  private _abortController = new AbortController();

  // Result promise wiring — re-created per stream in _beginNewStream()
  private _resultResolve!: (output: OutputObject) => void;
  private _resultReject!: (err: unknown) => void;
  private _resultPromise: Promise<OutputObject> | undefined;

  // Buffered config from send({update})
  private _bufferedConfig: Record<string, unknown> = {};

  constructor(
    private readonly definition: LocalAgentDefinition,
    private readonly context: AgentLoopContext,
    // Required for API parity across protocol constructors (local, remote, legacy)
    _messageBus: MessageBus,
    private readonly _rawActivityCallback?: (
      activity: SubagentActivityEvent,
    ) => void,
  ) {}

  // ---------------------------------------------------------------------------
  // AgentProtocol interface
  // ---------------------------------------------------------------------------

  get events(): readonly AgentEvent[] {
    return this._events;
  }

  subscribe(callback: (event: AgentEvent) => void): Unsubscribe {
    this._subscribers.add(callback);
    return () => {
      this._subscribers.delete(callback);
    };
  }

  async send(payload: AgentSend): Promise<{ streamId: string | null }> {
    if ('update' in payload && payload.update) {
      // Buffer config for use when message send arrives
      if (payload.update.config) {
        this._bufferedConfig = {
          ...this._bufferedConfig,
          ...payload.update.config,
        };
      }
      return { streamId: null };
    }

    if ('message' in payload && payload.message) {
      if (this._activeStreamId) {
        throw new Error(
          'LocalSubagentProtocol.send() cannot be called while a stream is active.',
        );
      }

      // Extract query text from the message ContentParts
      const queryText = payload.message.content
        .filter((p): p is ContentPart & { type: 'text' } => p.type === 'text')
        .map((p) => p.text)
        .join('');

      // Only include 'query' in params when the message text is non-empty,
      // so that callers that pass all fields via update.config are not affected.
      const params: AgentInputs = {
        ...this._bufferedConfig,
        ...(queryText.length > 0 ? { query: queryText } : {}),
      };
      this._bufferedConfig = {};

      this._beginNewStream();
      const streamId = this._streamId;

      // Schedule execution in a macrotask so send() resolves before agent_start
      setTimeout(() => {
        void this._runExecutionInBackground(params);
      }, 0);

      return { streamId };
    }

    // action and elicitations are not supported
    return { streamId: null };
  }

  async abort(): Promise<void> {
    this._abortController.abort();
  }

  // ---------------------------------------------------------------------------
  // Protocol-specific: result access
  // ---------------------------------------------------------------------------

  /**
   * Resolves when the executor completes, with the raw OutputObject.
   * Used by LocalSubagentInvocation to build the ToolResult.
   */
  getResult(): Promise<OutputObject> {
    if (!this._resultPromise) {
      return Promise.reject(new Error('No active or completed stream'));
    }
    return this._resultPromise;
  }

  // ---------------------------------------------------------------------------
  // Core: execution
  // ---------------------------------------------------------------------------

  private _beginNewStream(): void {
    this._streamId = randomUUID();
    this._eventCounter = 0;
    this._abortController = new AbortController();
    this._agentStartEmitted = false;
    this._agentEndEmitted = false;
    this._activeStreamId = this._streamId;
    this._resultPromise = new Promise<OutputObject>((resolve, reject) => {
      this._resultResolve = resolve;
      this._resultReject = reject;
    });
  }

  private async _runExecutionInBackground(params: AgentInputs): Promise<void> {
    this._ensureAgentStart();
    try {
      await this._runExecution(params);
    } catch (err: unknown) {
      if (this._abortController.signal.aborted || isAbortLikeError(err)) {
        this._ensureAgentEnd('aborted');
        // Abort resolves with an empty result — partial output is intentionally
        // dropped since the caller requested cancellation.
        this._resultResolve({
          result: '',
          terminate_reason: AgentTerminateMode.ABORTED,
        });
      } else {
        this._emitErrorAndAgentEnd(err);
        this._resultReject(err);
      }
    } finally {
      this._clearActiveStream();
    }
  }

  private async _runExecution(params: AgentInputs): Promise<void> {
    const signal = this._abortController.signal;

    const onActivity = (activity: SubagentActivityEvent): void => {
      // Forward raw activity to invocation-level callback (for rich SubagentProgress display)
      this._rawActivityCallback?.(activity);
      this._emit(this._translateActivity(activity));
    };

    const executor = await LocalAgentExecutor.create(
      this.definition,
      this.context,
      onActivity,
    );

    const output = await executor.run(params, signal);

    if (
      output.terminate_reason === AgentTerminateMode.ABORTED ||
      signal.aborted
    ) {
      this._finishStream('aborted');
    } else {
      this._finishStream(mapTerminateMode(output.terminate_reason));
    }

    this._resultResolve(output);
  }

  // ---------------------------------------------------------------------------
  // Activity → AgentEvent translation
  // ---------------------------------------------------------------------------

  private _translateActivity(activity: SubagentActivityEvent): AgentEvent[] {
    switch (activity.type) {
      case 'THOUGHT_CHUNK': {
        const rawText = activity.data['text'];
        const text = String(rawText ?? '');
        return [
          this._makeEvent('message', {
            role: 'agent',
            content: [{ type: 'thought', thought: text }],
          }),
        ];
      }
      case 'TOOL_CALL_START': {
        const rawCallId = activity.data['callId'];
        const callId = String(rawCallId ?? randomUUID());
        const rawName = activity.data['name'];
        const name = String(rawName ?? 'unknown');
        const rawArgs = activity.data['args'];
        const args: Record<string, unknown> =
          rawArgs !== null &&
          typeof rawArgs === 'object' &&
          !Array.isArray(rawArgs)
            ? // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
              (rawArgs as Record<string, unknown>)
            : {};
        return [
          this._makeEvent('tool_request', {
            requestId: callId,
            name,
            args,
          }),
        ];
      }
      case 'TOOL_CALL_END': {
        const rawId = activity.data['id'];
        const requestId = String(rawId ?? randomUUID());
        const rawName = activity.data['name'];
        const name = String(rawName ?? 'unknown');
        const rawOutput = activity.data['output'];
        const output = String(rawOutput ?? '');
        return [
          this._makeEvent('tool_response', {
            requestId,
            name,
            content: [{ type: 'text', text: output }],
          }),
        ];
      }
      case 'ERROR': {
        const rawError = activity.data['error'];
        const errorMsg = String(rawError ?? 'Unknown error');
        return [
          this._makeEvent('error', {
            status: 'INTERNAL',
            message: errorMsg,
            fatal: false,
          }),
        ];
      }
      default: {
        void (activity.type satisfies never);
        return [];
      }
    }
  }

  // ---------------------------------------------------------------------------
  // Internal helpers (mirrors LegacyAgentProtocol)
  // ---------------------------------------------------------------------------

  private _emit(events: AgentEvent[]): void {
    if (events.length === 0) return;
    const subscribers = [...this._subscribers];
    for (const event of events) {
      this._events.push(event);
      if (event.type === 'agent_end') {
        this._agentEndEmitted = true;
      }
      for (const sub of subscribers) {
        sub(event);
      }
    }
  }

  private _clearActiveStream(): void {
    this._activeStreamId = undefined;
  }

  private _ensureAgentStart(): void {
    if (!this._agentStartEmitted) {
      this._agentStartEmitted = true;
      this._emit([this._makeEvent('agent_start', {})]);
    }
  }

  private _ensureAgentEnd(reason: StreamEndReason = 'completed'): void {
    if (!this._agentEndEmitted && this._agentStartEmitted) {
      this._emit([this._makeEvent('agent_end', { reason })]);
    }
  }

  private _finishStream(reason: StreamEndReason): void {
    this._ensureAgentEnd(reason);
    this._clearActiveStream();
  }

  private _emitErrorAndAgentEnd(err: unknown): void {
    const message = err instanceof Error ? err.message : String(err);
    this._ensureAgentStart();

    const meta: Record<string, unknown> = {};
    if (err instanceof Error) {
      meta['errorName'] = err.constructor.name;
      meta['stack'] = err.stack;
      if ('exitCode' in err && typeof err.exitCode === 'number') {
        meta['exitCode'] = err.exitCode;
      }
      if ('code' in err) {
        meta['code'] = err.code;
      }
      if ('status' in err) {
        meta['status'] = err.status;
      }
    }

    this._emit([
      this._makeEvent('error', {
        status: 'INTERNAL',
        message,
        fatal: true,
        ...(Object.keys(meta).length > 0 ? { _meta: meta } : {}),
      }),
    ]);
    this._ensureAgentEnd('failed');
  }

  private _nextEventFields() {
    return {
      id: `${this._streamId}-${this._eventCounter++}`,
      timestamp: new Date().toISOString(),
      streamId: this._streamId,
    };
  }

  private _makeEvent<T extends AgentEvent['type']>(
    type: T,
    payload: Omit<AgentEvent<T>, 'id' | 'timestamp' | 'streamId' | 'type'>,
  ): AgentEvent {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
    return {
      ...this._nextEventFields(),
      type,
      ...payload,
    } as AgentEvent;
  }
}

// ---------------------------------------------------------------------------
// Public export
// ---------------------------------------------------------------------------

export class LocalSubagentSession extends AgentSession {
  private readonly _localProtocol: LocalSubagentProtocol;

  constructor(
    definition: LocalAgentDefinition,
    context: AgentLoopContext,
    messageBus: MessageBus,
    rawActivityCallback?: (activity: SubagentActivityEvent) => void,
  ) {
    const protocol = new LocalSubagentProtocol(
      definition,
      context,
      messageBus,
      rawActivityCallback,
    );
    super(protocol);
    this._localProtocol = protocol;
  }

  /**
   * Returns the raw executor OutputObject once execution completes.
   * Used by LocalSubagentInvocation to build the ToolResult.
   */
  getResult(): Promise<OutputObject> {
    return this._localProtocol.getResult();
  }
}