pi-agy-acp 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,7 +20,11 @@ import type {
20
20
  AcpToolCallMeta,
21
21
  } from './acp-process.ts'
22
22
  import type { BridgeTool, BridgeToolResult } from './mcp-bridge.ts'
23
- import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './history.ts'
23
+ import {
24
+ AGENT_TOOL_PREFIX,
25
+ CALL_TOOL_NAME,
26
+ MCP_SERVER_NAME,
27
+ } from './history.ts'
24
28
  import { AsyncQueue, deferred, type Deferred } from './util.ts'
25
29
 
26
30
  /** Agent-side transport retry notice streamed as message text, e.g. `⚠ API error (attempt 1): …`. */
@@ -133,8 +137,15 @@ export type TurnEvent =
133
137
  | { kind: 'done'; result: AcpPromptResult }
134
138
  | { kind: 'error'; error: Error }
135
139
 
140
+ /** Bound on buffered text/thought chars accumulated while a tool call is relayed. */
141
+ const MAX_RELAY_BUFFER_CHARS = 65_536
142
+
136
143
  /** One running ACP prompt turn. */
137
144
  export class AcpTurn {
145
+ readonly cancellation = new AbortController()
146
+ /** First interruption wins; prompt completion is committed only after the step drains. */
147
+ private terminal: { kind: 'cancelled' } | { kind: 'failed'; error: Error } | undefined
148
+ releaseSignal: (() => void) | undefined
138
149
  readonly startedAt = performance.now()
139
150
  readonly events = new AsyncQueue<TurnEvent>()
140
151
  /** Calls handed to Pi whose results have not arrived yet. */
@@ -143,6 +154,8 @@ export class AcpTurn {
143
154
  readonly calls = new Map<string, ParkedCall>()
144
155
  /** Pi steps this turn has ended with `tool-calls`. */
145
156
  toolSteps = 0
157
+ /** Tool steps completed inside the active `session/prompt` segment. */
158
+ segmentToolSteps = 0
146
159
  /** Long-decode continuations sent in this turn. */
147
160
  continuations = 0
148
161
  /** The agent ended the prompt. */
@@ -150,8 +163,13 @@ export class AcpTurn {
150
163
  /** Settles after the current prompt's result or error has been queued. */
151
164
  promptSettled: Promise<void> = Promise.resolve()
152
165
  usage?: AcpPromptResult['usage']
153
- /** A parked call was answered with a still-running notice and the agent has not resumed waiting yet. */
154
- relaying = false
166
+ /** Latest positive single-call context occupancy reported via `usage_update.used`. */
167
+ contextUsed?: number
168
+ /** Relayed call ids whose results the agent has not yet re-awaited via `pi_await_result`. */
169
+ readonly relayedCalls = new Set<string>()
170
+ /** Bounded output buffered while one or more calls are relayed. */
171
+ private relayBuffer: Array<Extract<TurnEvent, { kind: 'text' | 'thought' }>> = []
172
+ private relayBufferChars = 0
155
173
  /** The turn produced visible text or a tool call. */
156
174
  produced = false
157
175
  /** Agent-side transport retry notices dropped from the output. */
@@ -184,11 +202,70 @@ export class AcpTurn {
184
202
  return call
185
203
  }
186
204
 
205
+ get isRelaying(): boolean {
206
+ return this.relayedCalls.size > 0
207
+ }
208
+
209
+ /** Record that `callId` timed out into a relay notice and awaits `pi_await_result`. */
210
+ markRelayed(callId: string): void {
211
+ this.relayedCalls.add(callId)
212
+ }
213
+
214
+ /** Clear one relayed call when `pi_await_result` resumes it, flushing buffered output once all relays clear. */
215
+ resumeRelay(callId: string): void {
216
+ if (this.relayedCalls.delete(callId) && this.relayedCalls.size === 0) {
217
+ for (const event of this.relayBuffer) this.events.push(event)
218
+ this.clearRelayBuffer()
219
+ const held = this.recoverNoticeHold()
220
+ if (held.length > 0) this.events.push({ kind: 'text', text: held })
221
+ }
222
+ }
223
+
224
+ /** Release all relay tracking and buffered output. */
225
+ clearRelay(): void {
226
+ this.relayedCalls.clear()
227
+ this.clearRelayBuffer()
228
+ }
229
+
230
+ private clearRelayBuffer(): void {
231
+ this.relayBuffer.length = 0
232
+ this.relayBufferChars = 0
233
+ }
234
+
235
+ private emitOrBuffer(
236
+ event: Extract<TurnEvent, { kind: 'text' | 'thought' }>,
237
+ ): void {
238
+ if (!this.isRelaying) {
239
+ this.events.push(event)
240
+ return
241
+ }
242
+ const remaining = MAX_RELAY_BUFFER_CHARS - this.relayBufferChars
243
+ if (remaining <= 0) return
244
+ const text =
245
+ event.text.length <= remaining ? event.text : event.text.slice(0, remaining)
246
+ this.relayBufferChars += text.length
247
+ const tail = this.relayBuffer[this.relayBuffer.length - 1]
248
+ if (tail !== undefined && tail.kind === event.kind) {
249
+ tail.text += text
250
+ } else {
251
+ this.relayBuffer.push({ kind: event.kind, text })
252
+ }
253
+ }
254
+
187
255
  /**
188
256
  * Route one ACP session update into the event queue.
189
257
  * @param update - the agent notification.
190
258
  */
191
259
  onUpdate(update: AcpSessionUpdate): void {
260
+ if (
261
+ update.sessionUpdate === 'usage_update' &&
262
+ typeof update.used === 'number' &&
263
+ Number.isFinite(update.used) &&
264
+ update.used > 0
265
+ ) {
266
+ this.contextUsed = update.used
267
+ return
268
+ }
192
269
  const text =
193
270
  update.content?.type === 'text' ? (update.content.text ?? '') : ''
194
271
  if (update.sessionUpdate === 'agent_message_chunk' && text.length > 0) {
@@ -197,10 +274,8 @@ export class AcpTurn {
197
274
  }
198
275
  if (update.sessionUpdate === 'agent_thought_chunk') {
199
276
  const held = this.recoverNoticeHold()
200
- if (held.length > 0 && !this.relaying)
201
- this.events.push({ kind: 'text', text: held })
202
- if (text.length > 0 && !this.relaying)
203
- this.events.push({ kind: 'thought', text })
277
+ if (held.length > 0) this.emitOrBuffer({ kind: 'text', text: held })
278
+ if (text.length > 0) this.emitOrBuffer({ kind: 'thought', text })
204
279
  }
205
280
  }
206
281
 
@@ -220,7 +295,7 @@ export class AcpTurn {
220
295
  this.retryNotices++
221
296
  return
222
297
  }
223
- if (!this.relaying) this.events.push({ kind: 'text', text: combined })
298
+ this.emitOrBuffer({ kind: 'text', text: combined })
224
299
  }
225
300
 
226
301
  /**
@@ -236,7 +311,7 @@ export class AcpTurn {
236
311
  this.retryNotices++
237
312
  return ''
238
313
  }
239
- return this.relaying ? '' : held
314
+ return held
240
315
  }
241
316
 
242
317
  /**
@@ -244,6 +319,37 @@ export class AcpTurn {
244
319
  * @param reason - message delivered to the agent.
245
320
  */
246
321
  abandon(reason: string): void {
322
+ this.terminal ??= { kind: 'cancelled' }
323
+ if (this.terminal.kind === 'cancelled') this.cancellation.abort()
324
+ this.clearRelay()
325
+ this.settleCalls(reason)
326
+ }
327
+
328
+ /** End transport ownership without misreporting a process failure as cancellation. */
329
+ fail(error: Error): void {
330
+ this.terminal ??= { kind: 'failed', error }
331
+ this.clearRelay()
332
+ this.events.push({ kind: 'error', error })
333
+ this.settleCalls(error.message)
334
+ }
335
+
336
+ /** Guard both async-generator boundaries before emission, accounting, or drain. */
337
+ guard(chunk: StreamChunk | undefined, signal?: AbortSignal): StreamChunk | undefined {
338
+ if (signal?.aborted) this.abandon('The harness cancelled this request.')
339
+ if (this.terminal?.kind === 'failed') throw this.terminal.error
340
+ if (this.terminal?.kind === 'cancelled') return {
341
+ type: 'finish',
342
+ reason: {
343
+ kind: 'aborted',
344
+ failure: { message: 'Request aborted', code: 'ABORTED' },
345
+ },
346
+ }
347
+ return chunk
348
+ }
349
+
350
+ private settleCalls(reason: string): void {
351
+ this.releaseSignal?.()
352
+ this.releaseSignal = undefined
247
353
  for (const call of this.calls.values()) {
248
354
  call.result.resolve({
249
355
  content: [{ type: 'text', text: reason }],
@@ -266,39 +372,90 @@ export interface PumpHost {
266
372
  cancel(): void
267
373
  }
268
374
 
375
+ /** Optional single-call context occupancy inputs for {@link toTokenUsage}. */
376
+ export interface TokenUsageOptions {
377
+ /** Latest single-call context occupancy reported via `usage_update.used`. */
378
+ contextTokens?: number
379
+ /** Final `session/prompt` segment's usage when the turn spanned `max_tokens` continuations. */
380
+ lastSegmentUsage?: AcpPromptResult['usage']
381
+ }
382
+
383
+ function accumulateRawUsage(
384
+ prior: AcpPromptResult['usage'],
385
+ next: AcpPromptResult['usage'],
386
+ ): AcpPromptResult['usage'] {
387
+ if (prior === undefined) return next
388
+ if (next === undefined) return prior
389
+ const add = (a?: number, b?: number): number | undefined =>
390
+ a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0)
391
+ return {
392
+ inputTokens: add(prior.inputTokens, next.inputTokens),
393
+ outputTokens: add(prior.outputTokens, next.outputTokens),
394
+ cachedReadTokens: add(prior.cachedReadTokens, next.cachedReadTokens),
395
+ cachedWriteTokens: add(prior.cachedWriteTokens, next.cachedWriteTokens),
396
+ thoughtTokens: add(prior.thoughtTokens, next.thoughtTokens),
397
+ totalTokens: add(prior.totalTokens, next.totalTokens),
398
+ }
399
+ }
400
+
269
401
  /**
270
- * Map one completed prompt or step sample to Pi token usage. When a single
271
- * sample spanned `calls` internal model steps (tool rounds or continuations),
272
- * prompt buckets are normalized by `calls` so Pi's native ContextMeter reflects
273
- * single-request context occupancy rather than the multi-step sum.
402
+ * Map accumulated ACP turn usage into Pi token usage.
403
+ *
404
+ * Consumption buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
405
+ * `cacheWriteTokens`, `reasoningTokens`) stay unscaled cumulative turn totals
406
+ * because intermediate `toolUse` steps emit zero usage and Pi sums those
407
+ * buckets across steps for session accounting and flat pricing overrides.
408
+ *
409
+ * `totalTokens` feeds Pi's `calculateContextTokens` / ContextMeter / compaction
410
+ * threshold as final-call context occupancy: when `options.contextTokens`
411
+ * (from live `usage_update.used`) is positive, it is used directly; otherwise
412
+ * final-segment prompt buckets are normalized by `calls` and added to final-
413
+ * segment output tokens.
274
414
  *
275
415
  * `agy acp` reports `inputTokens` as uncached input only, disjoint from
276
- * `cachedReadTokens` and `cachedWriteTokens`, so every bucket is kept as
277
- * reported and the total is their sum.
278
- * @param usage - the agent's step or turn usage.
279
- * @param calls - model calls executed inside this sample (>= 1).
416
+ * `cachedReadTokens` and `cachedWriteTokens`.
417
+ * @param usage - accumulated turn usage.
418
+ * @param calls - model calls inside the final `session/prompt` segment (>= 1).
419
+ * @param options - optional live `usage_update` count and final segment usage.
280
420
  * @returns Pi usage.
281
421
  */
282
422
  export function toTokenUsage(
283
423
  usage: AcpPromptResult['usage'],
284
424
  calls = 1,
425
+ options?: TokenUsageOptions,
285
426
  ): TokenUsage | undefined {
286
427
  if (usage === undefined) return undefined
287
- const scale = Math.max(1, calls)
288
- const input = Math.max(0, Math.round((usage.inputTokens ?? 0) / scale))
289
- const cacheRead = Math.max(
290
- 0,
291
- Math.round((usage.cachedReadTokens ?? 0) / scale),
292
- )
293
- const cacheWrite = Math.max(
294
- 0,
295
- Math.round((usage.cachedWriteTokens ?? 0) / scale),
296
- )
297
- const output = Math.max(0, usage.outputTokens ?? 0)
428
+ const input = Math.max(0, Math.round(usage.inputTokens ?? 0))
429
+ const cacheRead = Math.max(0, Math.round(usage.cachedReadTokens ?? 0))
430
+ const cacheWrite = Math.max(0, Math.round(usage.cachedWriteTokens ?? 0))
431
+ const output = Math.max(0, Math.round(usage.outputTokens ?? 0))
298
432
  const reasoning =
299
433
  usage.thoughtTokens !== undefined && usage.thoughtTokens > 0
300
- ? Math.min(output, usage.thoughtTokens)
434
+ ? Math.min(output, Math.round(usage.thoughtTokens))
301
435
  : undefined
436
+ const liveContext = options?.contextTokens
437
+ let totalTokens: number
438
+ if (
439
+ typeof liveContext === 'number' &&
440
+ Number.isFinite(liveContext) &&
441
+ liveContext > 0
442
+ ) {
443
+ totalTokens = Math.round(liveContext)
444
+ } else {
445
+ const seg = options?.lastSegmentUsage ?? usage
446
+ const scale = Math.max(1, calls)
447
+ const segPrompt = Math.max(
448
+ 0,
449
+ Math.round(
450
+ ((seg.inputTokens ?? 0) +
451
+ (seg.cachedReadTokens ?? 0) +
452
+ (seg.cachedWriteTokens ?? 0)) /
453
+ scale,
454
+ ),
455
+ )
456
+ const segOutput = Math.max(0, Math.round(seg.outputTokens ?? 0))
457
+ totalTokens = segPrompt + segOutput
458
+ }
302
459
  return {
303
460
  inputTokens: input,
304
461
  outputTokens: output,
@@ -309,7 +466,7 @@ export function toTokenUsage(
309
466
  ...(reasoning !== undefined && reasoning > 0
310
467
  ? { reasoningTokens: reasoning }
311
468
  : {}),
312
- totalTokens: input + cacheRead + cacheWrite + output,
469
+ totalTokens,
313
470
  }
314
471
  }
315
472
 
@@ -324,6 +481,45 @@ export async function* pumpStep(
324
481
  turn: AcpTurn,
325
482
  host: PumpHost,
326
483
  signal: AbortSignal | undefined,
484
+ ): AsyncGenerator<StreamChunk> {
485
+ const cancel = () => turn.abandon('The harness cancelled this request.')
486
+ signal?.addEventListener('abort', cancel, { once: true })
487
+ if (signal?.aborted) cancel()
488
+ const chunks = stepChunks(turn, host, signal)
489
+ try {
490
+ // Real ACP exit can land behind a queued park, or while a consumer holds block-start.
491
+ for (;;) {
492
+ const interrupted = turn.guard(undefined, signal)
493
+ if (interrupted !== undefined) {
494
+ host.cancel()
495
+ yield interrupted
496
+ return
497
+ }
498
+ const next = await chunks.next()
499
+ const chunk = turn.guard(next.value, signal)
500
+ const aborted = chunk?.type === 'finish' && chunk.reason.kind === 'aborted'
501
+ if (aborted) host.cancel()
502
+ if (chunk !== undefined) yield chunk
503
+ if (aborted) return
504
+ if (next.done) return
505
+ }
506
+ } catch (error) {
507
+ turn.fail(error instanceof Error ? error : new Error(String(error)))
508
+ const interrupted = turn.guard(undefined, signal)
509
+ if (interrupted !== undefined) {
510
+ host.cancel()
511
+ yield interrupted
512
+ }
513
+ } finally {
514
+ signal?.removeEventListener('abort', cancel)
515
+ await chunks.return(undefined)
516
+ }
517
+ }
518
+
519
+ async function* stepChunks(
520
+ turn: AcpTurn,
521
+ host: PumpHost,
522
+ signal: AbortSignal | undefined,
327
523
  ): AsyncGenerator<StreamChunk> {
328
524
  let index = 0
329
525
  let open:
@@ -353,21 +549,9 @@ export async function* pumpStep(
353
549
  }
354
550
 
355
551
  for (;;) {
356
- const ready = await turn.events.wait(signal)
357
- if (!ready) {
358
- host.cancel()
359
- turn.abandon('The harness cancelled this request.')
360
- yield* close()
361
- yield {
362
- type: 'finish',
363
- reason: {
364
- kind: 'aborted',
365
- failure: { message: 'Request aborted', code: 'ABORTED' },
366
- },
367
- }
368
- return
369
- }
370
- if (turn.events.peek()?.kind !== 'text') {
552
+ await turn.events.wait(signal)
553
+ if (turn.guard(undefined, signal) !== undefined) return
554
+ if (!turn.isRelaying && turn.events.peek()?.kind !== 'text') {
371
555
  const held = turn.recoverNoticeHold()
372
556
  if (held.length > 0) {
373
557
  turn.produced = true
@@ -394,6 +578,7 @@ export async function* pumpStep(
394
578
  turn.events.shift()
395
579
  batch.push(next.call)
396
580
  }
581
+ if (turn.guard(undefined, signal) !== undefined) return
397
582
  for (const call of batch) {
398
583
  const blockIndex = index++
399
584
  turn.pendingCalls.set(call.id, call)
@@ -421,33 +606,48 @@ export async function* pumpStep(
421
606
  }
422
607
  }
423
608
  turn.toolSteps++
609
+ turn.segmentToolSteps++
424
610
  yield { type: 'finish', reason: { kind: 'tool-calls' } }
425
611
  return
426
612
  }
427
613
  case 'done': {
614
+ turn.usage = accumulateRawUsage(turn.usage, event.result.usage)
428
615
  const stop = event.result.stopReason
429
616
  if (
430
617
  stop === 'max_tokens' &&
431
618
  turn.continuations < host.maxContinuations
432
619
  ) {
433
620
  turn.continuations++
621
+ turn.segmentToolSteps = 0
622
+ turn.contextUsed = undefined
434
623
  turn.promptSettled = host.continuePrompt().then(
435
624
  (result) => turn.events.push({ kind: 'done', result }),
436
625
  (error: unknown) =>
437
- turn.events.push({
438
- kind: 'error',
439
- error:
440
- error instanceof Error ? error : new Error(String(error)),
441
- }),
626
+ turn.fail(error instanceof Error ? error : new Error(String(error))),
442
627
  )
443
628
  break
444
629
  }
445
630
  turn.finished = true
446
631
  yield* close()
447
- const calls = turn.toolSteps + turn.continuations + 1
448
- turn.usage = event.result.usage
449
- const usage = toTokenUsage(event.result.usage, calls)
632
+ const segmentCalls =
633
+ event.result.usage !== undefined
634
+ ? turn.segmentToolSteps + 1
635
+ : turn.toolSteps + turn.continuations + 1
636
+ const usage = toTokenUsage(turn.usage, segmentCalls, {
637
+ contextTokens: turn.contextUsed,
638
+ lastSegmentUsage: event.result.usage ?? turn.usage,
639
+ })
450
640
  if (usage !== undefined) yield { type: 'usage', usage }
641
+ if (
642
+ turn.isRelaying &&
643
+ (stop === 'end_turn' || stop === 'max_tokens')
644
+ ) {
645
+ turn.clearRelay()
646
+ throw new LlmError(
647
+ 'Antigravity ended the turn before retrieving relayed tool result(s)',
648
+ 'PROVIDER_ERROR',
649
+ )
650
+ }
451
651
  if (stop === 'end_turn' && !turn.produced) {
452
652
  throw new LlmError(
453
653
  'Antigravity ended the turn without visible output',
@@ -501,8 +701,9 @@ export async function* pumpStep(
501
701
  }
502
702
  case 'error':
503
703
  turn.finished = true
504
- yield* close()
505
- throw event.error
704
+ turn.fail(event.error)
705
+ turn.guard(undefined, signal)
706
+ return
506
707
  }
507
708
  }
508
709
  }
@@ -538,8 +739,31 @@ function nonEmpty(value: unknown): string | undefined {
538
739
  }
539
740
 
540
741
  /**
541
- * Extract the structured `(serverName, toolName)` an agent claimed in one
542
- * permission request: top-level `mcpServerName`/`mcpToolName` or `_meta`.
742
+ * Resolve one explicit metadata field across candidate aliases, flagging when
743
+ * any two non-empty candidates disagree.
744
+ */
745
+ function reconcileCandidates(values: readonly unknown[]): {
746
+ value?: string
747
+ conflict: boolean
748
+ } {
749
+ let value: string | undefined
750
+ let conflict = false
751
+ for (const raw of values) {
752
+ const candidate = nonEmpty(raw)
753
+ if (candidate === undefined) continue
754
+ if (value === undefined) value = candidate
755
+ else if (value !== candidate) conflict = true
756
+ }
757
+ return { ...(value !== undefined ? { value } : {}), conflict }
758
+ }
759
+
760
+ /**
761
+ * Extract tool identity `(serverName, toolName)` from `session/update`
762
+ * (`recordReportedToolCall`) or `session/request_permission` (`answerPermission`).
763
+ * Reads top-level `mcpServerName`/`mcpToolName` or `_meta`, and reconciles flat
764
+ * `name` (`mcp_<server>_<tool>`). Non-Pi flat names map to a `non-pi:<name>`
765
+ * server sentinel, and contradictions across explicit fields or `name` set
766
+ * `conflict: true`. Returns `{}` only when no identity fields are present.
543
767
  * `title` and `rawInput` are deliberately not consulted.
544
768
  */
545
769
  export function structuredToolMeta(
@@ -547,21 +771,49 @@ export function structuredToolMeta(
547
771
  ): {
548
772
  serverName?: string
549
773
  toolName?: string
774
+ conflict?: boolean
550
775
  } {
551
776
  const meta: AcpToolCallMeta | undefined = toolCall?._meta
552
- const serverName =
553
- nonEmpty(toolCall?.mcpServerName) ??
554
- nonEmpty(meta?.mcpServerName) ??
555
- nonEmpty(meta?.serverName) ??
556
- nonEmpty(meta?.server)
557
- const toolName =
558
- nonEmpty(toolCall?.mcpToolName) ??
559
- nonEmpty(meta?.mcpToolName) ??
560
- nonEmpty(meta?.toolName) ??
561
- nonEmpty(meta?.tool)
777
+ const server = reconcileCandidates([
778
+ toolCall?.mcpServerName,
779
+ meta?.mcpServerName,
780
+ meta?.serverName,
781
+ meta?.server,
782
+ ])
783
+ const tool = reconcileCandidates([
784
+ toolCall?.mcpToolName,
785
+ meta?.mcpToolName,
786
+ meta?.toolName,
787
+ meta?.tool,
788
+ ])
789
+ const explicitServer = server.value
790
+ const explicitTool = tool.value
791
+ const flat = nonEmpty(toolCall?.name)
792
+ if (flat === undefined) {
793
+ const conflict = server.conflict || tool.conflict
794
+ return {
795
+ ...(explicitServer !== undefined ? { serverName: explicitServer } : {}),
796
+ ...(explicitTool !== undefined ? { toolName: explicitTool } : {}),
797
+ ...(conflict ? { conflict: true } : {}),
798
+ }
799
+ }
800
+ const candidateServer = explicitServer ?? MCP_SERVER_NAME
801
+ const prefix = `mcp_${candidateServer}_`
802
+ const hasPrefixedTool =
803
+ flat.startsWith(prefix) && flat.length > prefix.length
804
+ const flatServer = hasPrefixedTool ? candidateServer : `non-pi:${flat}`
805
+ const flatTool = hasPrefixedTool ? flat.slice(prefix.length) : flat
806
+ const hasExplicit = explicitServer !== undefined || explicitTool !== undefined
807
+ const conflict =
808
+ server.conflict ||
809
+ tool.conflict ||
810
+ (hasExplicit &&
811
+ (!hasPrefixedTool ||
812
+ (explicitTool !== undefined && explicitTool !== flatTool)))
562
813
  return {
563
- ...(serverName !== undefined ? { serverName } : {}),
564
- ...(toolName !== undefined ? { toolName } : {}),
814
+ serverName: explicitServer ?? flatServer,
815
+ toolName: explicitTool ?? flatTool,
816
+ ...(conflict ? { conflict: true } : {}),
565
817
  }
566
818
  }
567
819
 
@@ -585,11 +837,15 @@ export function recordReportedToolCall(
585
837
  return
586
838
  if (typeof update.toolCallId !== 'string' || update.toolCallId.length === 0)
587
839
  return
588
- const { serverName, toolName } = structuredToolMeta(update)
840
+ const {
841
+ serverName,
842
+ toolName,
843
+ conflict: metaConflict,
844
+ } = structuredToolMeta(update)
589
845
  const kind = typeof update.kind === 'string' ? update.kind : undefined
590
846
  const existing = conv.reportedToolCalls.get(update.toolCallId)
591
847
  const merged: ReportedToolCall = existing === undefined ? {} : { ...existing }
592
- let conflict = false
848
+ let conflict = metaConflict === true
593
849
  if (kind !== undefined) {
594
850
  if (merged.kind !== undefined && merged.kind !== kind) conflict = true
595
851
  else merged.kind = kind