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49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview RemoteSubagentProtocol — wraps A2A remote agent streaming
 * behind the AgentProtocol interface.
 *
 * Pattern mirrors LocalSubagentProtocol and LegacyAgentProtocol, but the loop
 * body drives A2AClientManager instead of LocalAgentExecutor.
 */

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 type { ToolResult } from '../tools/tools.js';
import {
  DEFAULT_QUERY_STRING,
  type RemoteAgentDefinition,
  type SubagentProgress,
  SubagentState,
  getRemoteAgentTargetUrl,
  getAgentCardLoadOptions,
} from './types.js';
import { A2AResultReassembler, extractIdsFromResponse } from './a2aUtils.js';
import type { AuthenticationHandler } from '@a2a-js/sdk/client';
import { A2AAuthProviderFactory } from './auth-provider/factory.js';
import { A2AAgentError } from './a2a-errors.js';
import { debugLogger } from '../utils/debugLogger.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';

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

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

// ---------------------------------------------------------------------------
// RemoteSubagentProtocol
// ---------------------------------------------------------------------------

class RemoteSubagentProtocol 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();

  // A2A conversation state — persists across sends within this session instance
  private contextId: string | undefined;
  private taskId: string | undefined;
  private authHandler: AuthenticationHandler | undefined;

  // Agent display name (for SubagentProgress construction)
  private readonly _agentName: string;

  // Latest SubagentProgress — updated per chunk, used for error recovery
  private _latestProgress: SubagentProgress | undefined;

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

  constructor(
    private readonly definition: RemoteAgentDefinition,
    private readonly context: AgentLoopContext,
    // Required for API parity across protocol constructors (local, remote, legacy)
    _messageBus: MessageBus,
    initialState?: { contextId?: string; taskId?: string },
  ) {
    this._agentName = definition.displayName ?? definition.name;
    if (initialState) {
      this.contextId = initialState.contextId;
      this.taskId = initialState.taskId;
    }
  }

  /**
   * Returns the current A2A conversation state.
   * Used by the invocation layer to persist state across invocations.
   */
  getSessionState(): { contextId?: string; taskId?: string } {
    return { contextId: this.contextId, taskId: this.taskId };
  }

  // ---------------------------------------------------------------------------
  // 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 ('message' in payload && payload.message) {
      if (this._activeStreamId) {
        throw new Error(
          'RemoteSubagentProtocol.send() cannot be called while a stream is active.',
        );
      }

      const query =
        payload.message.content
          .filter((p): p is ContentPart & { type: 'text' } => p.type === 'text')
          .map((p) => p.text)
          .join('') || DEFAULT_QUERY_STRING;

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

      setTimeout(() => {
        void this._runStreamInBackground(query);
      }, 0);

      return { streamId };
    }

    // update/action/elicitations not used for remote agents
    return { streamId: null };
  }

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

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

  getResult(): Promise<ToolResult> {
    if (!this._resultPromise) {
      return Promise.reject(new Error('No active or completed stream'));
    }
    return this._resultPromise;
  }

  getLatestProgress(): SubagentProgress | undefined {
    return this._latestProgress;
  }

  // ---------------------------------------------------------------------------
  // Core: A2A streaming
  // ---------------------------------------------------------------------------

  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<ToolResult>((resolve, reject) => {
      this._resultResolve = resolve;
      this._resultReject = reject;
    });
  }

  private async _runStreamInBackground(query: string): Promise<void> {
    this._ensureAgentStart();
    try {
      await this._runStream(query);
    } 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({
          llmContent: [{ text: '' }],
          returnDisplay: '',
        });
      } else {
        this._emitErrorAndAgentEnd(err);
        this._resultReject(err);
      }
    } finally {
      this._clearActiveStream();
    }
  }

  private async _runStream(query: string): Promise<void> {
    const clientManager = this.context.config.getA2AClientManager();
    if (!clientManager) {
      throw new Error(
        `RemoteSubagentProtocol: A2AClientManager not available for '${this.definition.name}'.`,
      );
    }

    const authHandler = await this._getAuthHandler();
    if (!clientManager.getClient(this.definition.name)) {
      await clientManager.loadAgent(
        this.definition.name,
        getAgentCardLoadOptions(this.definition),
        authHandler,
      );
    }

    const reassembler = new A2AResultReassembler();
    let prevText = '';

    const stream = clientManager.sendMessageStream(
      this.definition.name,
      query,
      {
        contextId: this.contextId,
        taskId: this.taskId,
        signal: this._abortController.signal,
      },
    );

    for await (const chunk of stream) {
      reassembler.update(chunk);

      const {
        contextId: newContextId,
        taskId: newTaskId,
        clearTaskId,
      } = extractIdsFromResponse(chunk);
      if (newContextId) this.contextId = newContextId;
      this.taskId = clearTaskId ? undefined : (newTaskId ?? this.taskId);

      const currentText = reassembler.toString();

      // Update latest progress snapshot (for invocation's error recovery)
      this._latestProgress = {
        isSubagentProgress: true,
        agentName: this._agentName,
        state: SubagentState.RUNNING,
        recentActivity: reassembler.toActivityItems(),
        result: currentText,
      };

      // Emit delta as a message event
      const delta = currentText.slice(prevText.length);
      if (delta) {
        this._emit([
          this._makeEvent('message', {
            role: 'agent',
            content: [{ type: 'text', text: delta }],
          }),
        ]);
        prevText = currentText;
      }
    }

    const finalOutput = reassembler.toString();
    debugLogger.debug(
      `[RemoteSubagentProtocol] ${this.definition.name} finished, output length: ${finalOutput.length}`,
    );

    const finalProgress: SubagentProgress = {
      isSubagentProgress: true,
      agentName: this._agentName,
      state: SubagentState.COMPLETED,
      result: finalOutput,
      recentActivity: reassembler.toActivityItems(),
    };
    this._latestProgress = finalProgress;

    this._finishStream('completed');

    this._resultResolve({
      llmContent: [{ text: finalOutput }],
      returnDisplay: finalProgress,
    });
  }

  private async _getAuthHandler(): Promise<AuthenticationHandler | undefined> {
    if (this.authHandler) return this.authHandler;
    if (!this.definition.auth) return undefined;

    const targetUrl = getRemoteAgentTargetUrl(this.definition);
    const provider = await A2AAuthProviderFactory.create({
      authConfig: this.definition.auth,
      agentName: this.definition.name,
      targetUrl,
      agentCardUrl: this.definition.agentCardUrl,
    });
    if (!provider) {
      throw new Error(
        `Failed to create auth provider for agent '${this.definition.name}'`,
      );
    }
    this.authHandler = provider;
    return this.authHandler;
  }

  // ---------------------------------------------------------------------------
  // Internal helpers
  // ---------------------------------------------------------------------------

  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 = this._formatError(err);
    this._ensureAgentStart();

    const meta: Record<string, unknown> = {};
    if (err instanceof Error) {
      meta['errorName'] = err.constructor.name;
      meta['stack'] = err.stack;
    }

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

  private _formatError(error: unknown): string {
    if (error instanceof A2AAgentError) {
      return error.userMessage;
    }
    return `Error calling remote agent: ${error instanceof Error ? error.message : String(error)}`;
  }

  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 RemoteSubagentSession extends AgentSession {
  private readonly _remoteProtocol: RemoteSubagentProtocol;

  constructor(
    definition: RemoteAgentDefinition,
    context: AgentLoopContext,
    messageBus: MessageBus,
    initialState?: { contextId?: string; taskId?: string },
  ) {
    const protocol = new RemoteSubagentProtocol(
      definition,
      context,
      messageBus,
      initialState,
    );
    super(protocol);
    this._remoteProtocol = protocol;
  }

  /**
   * Returns the ToolResult once the remote agent stream completes.
   * Used by RemoteAgentInvocation to return the result.
   */
  getResult(): Promise<ToolResult> {
    return this._remoteProtocol.getResult();
  }

  /**
   * Returns the most recent SubagentProgress snapshot, updated per streaming
   * chunk. Useful for constructing error progress when getResult() rejects.
   */
  getLatestProgress(): SubagentProgress | undefined {
    return this._remoteProtocol.getLatestProgress();
  }

  /**
   * Returns the current A2A conversation state (contextId/taskId).
   * Used by the invocation layer to persist state across invocations.
   */
  getSessionState(): { contextId?: string; taskId?: string } {
    return this._remoteProtocol.getSessionState();
  }

  /**
   * Convenience: start execution with a query string.
   * Equivalent to send({message: {content: [{type:'text', text: query}]}}).
   */
  async startWithQuery(query: string): Promise<{ streamId: string | null }> {
    return this.send({
      message: { content: [{ type: 'text', text: query }] },
    });
  }
}