pi-agy-acp 0.2.6 → 0.2.8

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.
@@ -19,38 +19,59 @@ import type {
19
19
  AcpPermissionRequest,
20
20
  AcpToolCallMeta,
21
21
  } from './acp-process.ts'
22
- import type {
23
- BridgeCallRequest,
24
- BridgeTool,
25
- BridgeToolResult,
26
- } from './mcp-bridge.ts'
27
22
  import {
28
23
  AGENT_TOOL_PREFIX,
29
- CALL_TOOL_NAME,
24
+ AWAIT_TOOL_NAME,
30
25
  MCP_SERVER_NAME,
31
- } from './history.ts'
32
- import { AsyncQueue, deferred, type Deferred } from './util.ts'
26
+ type BridgeCallRequest,
27
+ type BridgeToolResult,
28
+ } from './mcp-bridge.ts'
29
+ import { AsyncQueue, deferred, isRecord, type Deferred } from './util.ts'
33
30
 
34
31
  /** Agent-side transport retry notice streamed as message text, e.g. `⚠ API error (attempt 1): …`. */
35
- const AGENT_RETRY_NOTICE = /^\s*⚠\s*API error \(attempt \d+\)/
36
- /** Discarded-attempt prefix agy 1.5.23+ emits on retryable generation failures (`%s\n%s\nRetries remaining: %d`). */
37
- const DISCARDED_ATTEMPT_PREFIX = 'a response attempt was discarded'
38
- /** Standalone retry guidance agy 1.5.23+ pairs with combined reasoning+output limit discards. */
39
- const REASONING_OUTPUT_LIMIT_TAIL =
40
- 'please keep your reasoning and response shorter'
41
- /** Internal retry notice agy emits when an upstream stream is interrupted mid-turn. */
42
- const STREAM_INTERRUPTED =
43
- 'the stream was interrupted. please continue the task you were working on.'
44
- /** Internal retry notice agy emits when a model response contains neither text nor tool calls. */
45
- const EMPTY_MODEL_OUTPUT =
46
- 'model output error: model output must contain either output text or tool calls, these cannot both be empty, please try again'
47
- const EMPTY_MODEL_OUTPUT_BODY =
48
- 'model output must contain either output text or tool calls, these cannot both be empty, please try again'
49
- /** Generic retry notice prefix paired with a trailing `Retries remaining: <N>`. */
50
- const PROBLEM_RETRY_PREFIX = 'there was a problem'
32
+ const TRANSPORT_RETRY_NOTICE_RE = /^\s*⚠\s*API error \(attempt \d+\)/
51
33
  /** Cap on held characters while waiting for `Retries remaining: <N>` after a generic retry prefix. */
52
34
  const MAX_PROBLEM_NOTICE_CHARS = 512
53
35
 
36
+ /** Prefix-matched retry notices that require a trailing positive `Retries remaining: <N>`. */
37
+ const RETRY_PREFIX_NOTICES = [
38
+ {
39
+ prefix: 'there was a problem',
40
+ pattern: /^there was a problem\b/,
41
+ minHoldPrefix: 'there was',
42
+ },
43
+ {
44
+ prefix: 'a response attempt was discarded',
45
+ pattern: /^a response attempt was discarded\b/,
46
+ minHoldPrefix: 'a response attempt',
47
+ },
48
+ ] as const
49
+
50
+ /** Full-line internal retry and output-cap notices with an optional `Retries remaining: <N>` footer. */
51
+ const EXACT_RETRY_NOTICES: readonly {
52
+ readonly text: string
53
+ readonly minHoldPrefix: string
54
+ readonly stripPeriods?: boolean
55
+ }[] = [
56
+ {
57
+ text: 'please keep your reasoning and response shorter',
58
+ minHoldPrefix: 'please keep your reasoning',
59
+ stripPeriods: true,
60
+ },
61
+ {
62
+ text: 'the stream was interrupted. please continue the task you were working on.',
63
+ minHoldPrefix: 'the stream',
64
+ },
65
+ {
66
+ text: 'model output error: model output must contain either output text or tool calls, these cannot both be empty, please try again',
67
+ minHoldPrefix: 'model output',
68
+ },
69
+ {
70
+ text: 'model output must contain either output text or tool calls, these cannot both be empty, please try again',
71
+ minHoldPrefix: 'model output',
72
+ },
73
+ ]
74
+
54
75
  /** Collapse agy's warning mark, line-leading `Error:`, and line breaks so notices match across chunks. */
55
76
  function noticeText(raw: string): string {
56
77
  return raw
@@ -62,22 +83,25 @@ function noticeText(raw: string): string {
62
83
  }
63
84
 
64
85
  /**
65
- * Classify text against agy's internal retry and output-cap continuation notices.
86
+ * Classify text against agy's internal transport, retry, and output-cap notices.
66
87
  * `drop` is only an internal notice, `hold` is still a prefix of one, `emit` is model text.
67
88
  */
68
- export function classifyOutputLimitNotice(
89
+ export function classifyAgentRetryNotice(
69
90
  raw: string,
70
91
  ): 'drop' | 'hold' | 'emit' {
92
+ if (TRANSPORT_RETRY_NOTICE_RE.test(raw)) return 'drop'
71
93
  const text = noticeText(raw)
72
94
  if (text.length === 0) return raw.includes('⚠') ? 'hold' : 'emit'
73
95
  // Terminal exhaustion (`Retries remaining: 0`) must surface immediately instead of being dropped or held.
74
96
  if (/\bretries remaining:\s*0+$/i.test(text)) return 'emit'
75
- if (/^there was a problem\b/.test(text)) {
76
- if (/\bretries remaining:\s*[1-9]\d*$/.test(text)) return 'drop'
77
- return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
97
+ for (const notice of RETRY_PREFIX_NOTICES) {
98
+ if (notice.pattern.test(text)) {
99
+ if (/\bretries remaining:\s*[1-9]\d*$/.test(text)) return 'drop'
100
+ return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
101
+ }
102
+ if (notice.prefix.startsWith(text) && text.startsWith(notice.minHoldPrefix))
103
+ return 'hold'
78
104
  }
79
- if (PROBLEM_RETRY_PREFIX.startsWith(text) && text.startsWith('there was'))
80
- return 'hold'
81
105
  const stripped = text.replace(/\s*retries remaining:\s*\d*\s*$/i, '').trim()
82
106
  const retry = text.slice(stripped.length).trim()
83
107
  if (retry.length > 0 && !/^retries remaining:\s*\d*$/i.test(retry))
@@ -87,87 +111,27 @@ export function classifyOutputLimitNotice(
87
111
  return /^retries remaining:\s*$/i.test(text) ? 'hold' : 'emit'
88
112
  }
89
113
  const normalized = stripped.replace(/\./g, '').replace(/\s+/g, ' ').trim()
90
- if (
91
- normalized === REASONING_OUTPUT_LIMIT_TAIL ||
92
- stripped === STREAM_INTERRUPTED ||
93
- stripped === EMPTY_MODEL_OUTPUT ||
94
- stripped === EMPTY_MODEL_OUTPUT_BODY
95
- ) {
96
- if (retry.length === 0 || /^retries remaining:\s*[1-9]\d*$/i.test(retry))
97
- return 'drop'
98
- return /^retries remaining:\s*$/i.test(retry) ? 'hold' : 'emit'
114
+ for (const notice of EXACT_RETRY_NOTICES) {
115
+ const candidate = notice.stripPeriods ? normalized : stripped
116
+ if (candidate === notice.text) {
117
+ if (retry.length === 0 || /^retries remaining:\s*[1-9]\d*$/i.test(retry))
118
+ return 'drop'
119
+ return /^retries remaining:\s*$/i.test(retry) ? 'hold' : 'emit'
120
+ }
99
121
  }
100
- if (/^a response attempt was discarded\b/.test(text)) {
101
- if (/\bretries remaining:\s*[1-9]\d*$/.test(text)) return 'drop'
102
- return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
122
+ for (const notice of EXACT_RETRY_NOTICES) {
123
+ const candidate = notice.stripPeriods ? normalized : stripped
124
+ if (
125
+ notice.text.startsWith(candidate) &&
126
+ candidate.startsWith(notice.minHoldPrefix)
127
+ )
128
+ return 'hold'
103
129
  }
104
- if (
105
- DISCARDED_ATTEMPT_PREFIX.startsWith(text) &&
106
- text.startsWith('a response attempt')
107
- )
108
- return 'hold'
109
- if (
110
- REASONING_OUTPUT_LIMIT_TAIL.startsWith(normalized) &&
111
- normalized.startsWith('please keep your reasoning')
112
- )
113
- return 'hold'
114
- if (
115
- STREAM_INTERRUPTED.startsWith(stripped) &&
116
- stripped.startsWith('the stream')
117
- )
118
- return 'hold'
119
- if (
120
- (EMPTY_MODEL_OUTPUT.startsWith(stripped) ||
121
- EMPTY_MODEL_OUTPUT_BODY.startsWith(stripped)) &&
122
- stripped.startsWith('model output')
123
- )
124
- return 'hold'
125
130
  if ('retries remaining:'.startsWith(text) && text.startsWith('retries'))
126
131
  return 'hold'
127
132
  return 'emit'
128
133
  }
129
134
 
130
- /** Tool the agent calls to keep waiting on a relayed Pi tool result. */
131
- export const AWAIT_TOOL_NAME = 'pi_await_result'
132
-
133
- /** MCP descriptor of {@link AWAIT_TOOL_NAME}. */
134
- export const AWAIT_TOOL: BridgeTool = {
135
- name: AWAIT_TOOL_NAME,
136
- description:
137
- 'Wait for the result of a harness tool call that reported it is still running. Call this only when a tool result tells you to, passing the call_id it gave.',
138
- inputSchema: {
139
- type: 'object',
140
- properties: {
141
- call_id: {
142
- type: 'string',
143
- description: 'The call id from the still-running notice.',
144
- },
145
- },
146
- required: ['call_id'],
147
- },
148
- }
149
-
150
- /** MCP descriptor of {@link CALL_TOOL_NAME} (~340B, stays below agy's lazy cutoff). */
151
- export const CALL_TOOL: BridgeTool = {
152
- name: CALL_TOOL_NAME,
153
- description:
154
- 'Invoke any harness tool by exact name when mcp_pi_<name> is absent from your direct tool declarations.',
155
- inputSchema: {
156
- type: 'object',
157
- properties: {
158
- name: {
159
- type: 'string',
160
- description: 'Exact Pi tool name without mcp_pi_ prefix.',
161
- },
162
- arguments: {
163
- type: 'object',
164
- description: 'Arguments object matching that tool schema.',
165
- },
166
- },
167
- required: ['name'],
168
- },
169
- }
170
-
171
135
  /** One tool call the agent issued and Pi has to run. */
172
136
  export interface ParkedCall {
173
137
  readonly id: string
@@ -189,9 +153,15 @@ const MAX_RELAY_BUFFER_CHARS = 65_536
189
153
 
190
154
  type RelayState = 'waiting' | 'unawaited' | 'notified'
191
155
 
192
- interface RelayEntry {
193
- state: RelayState
194
- resolved: boolean
156
+ /** Cohesive per-call lifecycle state owned by one {@link AcpTurn}. */
157
+ export interface ToolCallEntry {
158
+ readonly call: ParkedCall
159
+ /** Handed to Pi in a `tool-calls` step; awaiting Pi's tool result message. */
160
+ pending: boolean
161
+ /** MCP delivery ownership: idle (no active handler), waiting (active MCP handler), or delivered (committed). */
162
+ delivery: 'idle' | 'waiting' | 'delivered'
163
+ /** Relay lifecycle: waiting (gating `relayBuffer`) -> unawaited -> notified, or undefined when not relayed. */
164
+ relay: { state: RelayState; resolved: boolean } | undefined
195
165
  }
196
166
 
197
167
  /** One running ACP prompt turn. */
@@ -202,10 +172,8 @@ export class AcpTurn {
202
172
  releaseSignal: (() => void) | undefined
203
173
  readonly startedAt = performance.now()
204
174
  readonly events = new AsyncQueue<TurnEvent>()
205
- /** Calls handed to Pi whose results have not arrived yet. */
206
- readonly pendingCalls = new Map<string, ParkedCall>()
207
- /** Calls the agent issued during this turn. */
208
- readonly calls = new Map<string, ParkedCall>()
175
+ /** Calls the agent issued during this turn together with their pending, delivery, and relay state. */
176
+ readonly calls = new Map<string, ToolCallEntry>()
209
177
  /** Pi steps this turn has ended with `tool-calls`. */
210
178
  toolSteps = 0
211
179
  /** Tool steps completed inside the active `session/prompt` segment. */
@@ -220,17 +188,13 @@ export class AcpTurn {
220
188
  promptSettled: Promise<void> = Promise.resolve()
221
189
  usage?: AcpPromptResult['usage']
222
190
  /** Latest positive single-call context occupancy reported via `usage_update.used`. */
223
- contextUsed?: number
191
+ contextTokens?: number
224
192
  /** Fallback single-call context occupancy decoded from same-turn `gen_metadata` (`estimated_tokens_used`). */
225
- estimatedContextUsed?: number
193
+ estimatedContextTokens?: number
226
194
  /** Lower `gen_metadata.idx` bound owned by the active turn segment, or `null` when unobservable. */
227
195
  metaFloorIdx: number | null = 0
228
196
  /** Highest `steps.idx` already persisted before the active prompt segment started, or `null` when unobservable. */
229
197
  lastStepIdx: number | null = -1
230
- /** Per-call relay lifecycle: waiting (gating `relayBuffer`) -> unawaited -> notified. */
231
- private readonly relays = new Map<string, RelayEntry>()
232
- /** Per-call MCP delivery ownership: absent (idle), waiting (active MCP handler), or delivered (committed). */
233
- private readonly callDelivery = new Map<string, 'waiting' | 'delivered'>()
234
198
  /** Tool deltas and steering text deferred until an active MCP call returns a real result. */
235
199
  private readonly pendingSuffix: string[] = []
236
200
  /** Bounded output buffered while one or more calls are relayed. */
@@ -250,6 +214,26 @@ export class AcpTurn {
250
214
  this.turnTag = turnTag
251
215
  }
252
216
 
217
+ /** Number of tool calls handed to Pi whose results have not arrived yet. */
218
+ get pendingCallCount(): number {
219
+ let count = 0
220
+ for (const entry of this.calls.values()) {
221
+ if (entry.pending) count++
222
+ }
223
+ return count
224
+ }
225
+
226
+ /** Whether `callId` was handed to Pi and still awaits its tool result. */
227
+ isPendingCall(callId: string): boolean {
228
+ return this.calls.get(callId)?.pending === true
229
+ }
230
+
231
+ /** Mark one parked call as handed off to Pi for execution. */
232
+ markPending(callId: string): void {
233
+ const entry = this.calls.get(callId)
234
+ if (entry !== undefined) entry.pending = true
235
+ }
236
+
253
237
  /** Authoritative liveness of the underlying ACP `session/prompt` RPC. */
254
238
  get isPromptActive(): boolean {
255
239
  return this.promptActive && !this.finished && this.terminal === undefined
@@ -302,7 +286,12 @@ export class AcpTurn {
302
286
  argumentsJson: JSON.stringify(args),
303
287
  result: deferred<BridgeToolResult>(),
304
288
  }
305
- this.calls.set(call.id, call)
289
+ this.calls.set(call.id, {
290
+ call,
291
+ pending: false,
292
+ delivery: 'idle',
293
+ relay: undefined,
294
+ })
306
295
  this.events.push({ kind: 'park', call })
307
296
  return call
308
297
  }
@@ -315,7 +304,13 @@ export class AcpTurn {
315
304
  signal: AbortSignal,
316
305
  commit?: BridgeCallRequest['commit'],
317
306
  ): Promise<BridgeToolResult> {
318
- return this.awaitCall(this.park(name, args), relayAfterMs, signal, commit)
307
+ const call = this.park(name, args)
308
+ return this.awaitCall(
309
+ this.calls.get(call.id) as ToolCallEntry,
310
+ relayAfterMs,
311
+ signal,
312
+ commit,
313
+ )
319
314
  }
320
315
 
321
316
  /** Resume waiting on a previously parked call via `pi_await_result`, or return undefined if unknown. */
@@ -325,10 +320,9 @@ export class AcpTurn {
325
320
  signal: AbortSignal,
326
321
  commit?: BridgeCallRequest['commit'],
327
322
  ): Promise<BridgeToolResult> | undefined {
328
- const call = this.calls.get(callId)
329
- if (call === undefined) return undefined
330
- const status = this.callDelivery.get(callId)
331
- if (status === 'delivered') {
323
+ const entry = this.calls.get(callId)
324
+ if (entry === undefined) return undefined
325
+ if (entry.delivery === 'delivered') {
332
326
  return Promise.resolve({
333
327
  content: [
334
328
  {
@@ -338,7 +332,7 @@ export class AcpTurn {
338
332
  ],
339
333
  })
340
334
  }
341
- if (status === 'waiting') {
335
+ if (entry.delivery === 'waiting') {
342
336
  return Promise.resolve({
343
337
  content: [
344
338
  {
@@ -356,29 +350,32 @@ export class AcpTurn {
356
350
  })
357
351
  }
358
352
  this.resumeRelay(callId)
359
- return this.awaitCall(call, relayAfterMs, signal, commit)
353
+ return this.awaitCall(entry, relayAfterMs, signal, commit)
360
354
  }
361
355
 
362
356
  get isRelaying(): boolean {
363
- for (const entry of this.relays.values()) {
364
- if (entry.state === 'waiting') return true
357
+ for (const entry of this.calls.values()) {
358
+ if (entry.relay?.state === 'waiting') return true
365
359
  }
366
360
  return false
367
361
  }
368
362
 
369
363
  /** Record that `callId` timed out into a relay notice and awaits `pi_await_result`. */
370
364
  markRelayed(callId: string): void {
371
- const prev = this.relays.get(callId)
372
- this.relays.set(callId, {
365
+ const entry = this.calls.get(callId)
366
+ if (entry === undefined) return
367
+ entry.relay = {
373
368
  state: 'waiting',
374
- resolved: prev?.resolved ?? false,
375
- })
369
+ resolved: entry.relay?.resolved ?? false,
370
+ }
376
371
  }
377
372
 
378
373
  /** Clear one relayed call when `pi_await_result` resumes it, flushing buffered output once all waits clear. */
379
374
  resumeRelay(callId: string): void {
380
- const wasWaiting = this.relays.get(callId)?.state === 'waiting'
381
- this.relays.delete(callId)
375
+ const entry = this.calls.get(callId)
376
+ if (entry === undefined) return
377
+ const wasWaiting = entry.relay?.state === 'waiting'
378
+ entry.relay = undefined
382
379
  if (wasWaiting && !this.isRelaying) this.flushRelayBuffer()
383
380
  }
384
381
 
@@ -394,8 +391,12 @@ export class AcpTurn {
394
391
  ):
395
392
  | { resumed: true }
396
393
  | { resumed: false; pending: ParkedCall[]; suffix: string } {
397
- const pending = [...this.pendingCalls.values()]
398
- this.pendingCalls.clear()
394
+ const pending: ParkedCall[] = []
395
+ for (const entry of this.calls.values()) {
396
+ if (!entry.pending) continue
397
+ entry.pending = false
398
+ pending.push(entry.call)
399
+ }
399
400
  if (!this.isPromptActive) {
400
401
  const carried = this.consumePendingSuffix()
401
402
  return {
@@ -408,8 +409,8 @@ export class AcpTurn {
408
409
  for (const call of pending) {
409
410
  const result = results.get(call.id)
410
411
  if (result === undefined) continue
411
- const entry = this.relays.get(call.id)
412
- if (entry !== undefined) entry.resolved = true
412
+ const entry = this.calls.get(call.id)
413
+ if (entry?.relay !== undefined) entry.relay.resolved = true
413
414
  call.result.resolve(result)
414
415
  }
415
416
  return { resumed: true }
@@ -435,18 +436,22 @@ export class AcpTurn {
435
436
  this.clearRelay()
436
437
  return { kind: 'premature' }
437
438
  }
438
- const ids = [...this.relays.keys()]
439
+ const ids: string[] = []
440
+ for (const [id, entry] of this.calls) {
441
+ if (entry.relay !== undefined) ids.push(id)
442
+ }
439
443
  this.clearRelay()
440
444
  return ids.length > 0 ? { kind: 'note', ids } : { kind: 'ok' }
441
445
  }
442
446
 
443
447
  private async awaitCall(
444
- call: ParkedCall,
448
+ entry: ToolCallEntry,
445
449
  relayAfterMs: number,
446
450
  signal: AbortSignal,
447
451
  commit?: BridgeCallRequest['commit'],
448
452
  ): Promise<BridgeToolResult> {
449
- this.callDelivery.set(call.id, 'waiting')
453
+ const { call } = entry
454
+ entry.delivery = 'waiting'
450
455
  let timer: ReturnType<typeof setTimeout> | undefined
451
456
  const relay = new Promise<'relay'>((resolve) => {
452
457
  timer = setTimeout(() => resolve('relay'), relayAfterMs)
@@ -474,11 +479,10 @@ export class AcpTurn {
474
479
  return relayNotice(call)
475
480
  }
476
481
  return commit !== undefined
477
- ? commit(() => this.deliverCallResult(call.id, outcome))
478
- : this.deliverCallResult(call.id, outcome)
482
+ ? commit(() => this.deliverCallResult(entry, outcome))
483
+ : this.deliverCallResult(entry, outcome)
479
484
  } finally {
480
- if (this.callDelivery.get(call.id) === 'waiting')
481
- this.callDelivery.delete(call.id)
485
+ if (entry.delivery === 'waiting') entry.delivery = 'idle'
482
486
  if (timer !== undefined) clearTimeout(timer)
483
487
  if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
484
488
  }
@@ -497,23 +501,21 @@ export class AcpTurn {
497
501
  * and attach deferred harness suffixes plus a one-time completion update for resolved unretrieved relays.
498
502
  */
499
503
  private deliverCallResult(
500
- callId: string,
504
+ entry: ToolCallEntry,
501
505
  result: BridgeToolResult,
502
506
  ): BridgeToolResult {
503
- this.callDelivery.set(callId, 'delivered')
504
- this.relays.delete(callId)
507
+ entry.delivery = 'delivered'
508
+ entry.relay = undefined
505
509
  this.releaseRelayWait()
506
510
  const notes: string[] = []
507
511
  const suffix = this.consumePendingSuffix()
508
512
  if (suffix.length > 0) notes.push(suffix)
509
513
  const completedLines: string[] = []
510
- for (const [id, entry] of this.relays) {
511
- if (entry.state !== 'unawaited' || !entry.resolved) continue
512
- entry.state = 'notified'
513
- const completed = this.calls.get(id)
514
- if (completed === undefined) continue
514
+ for (const other of this.calls.values()) {
515
+ if (other.relay?.state !== 'unawaited' || !other.relay.resolved) continue
516
+ other.relay.state = 'notified'
515
517
  completedLines.push(
516
- `[tool completed: ${completed.id} (${completed.name}) — call ${AGENT_TOOL_PREFIX}${AWAIT_TOOL_NAME} with {"call_id":"${completed.id}"} to read its result]`,
518
+ `[tool completed: ${other.call.id} (${other.call.name}) — call ${AGENT_TOOL_PREFIX}${AWAIT_TOOL_NAME} with {"call_id":"${other.call.id}"} to read its result]`,
517
519
  )
518
520
  }
519
521
  if (completedLines.length > 0) {
@@ -533,16 +535,16 @@ export class AcpTurn {
533
535
 
534
536
  /** Release all relay tracking, deferred suffixes, and buffered output. */
535
537
  private clearRelay(): void {
536
- this.relays.clear()
538
+ for (const entry of this.calls.values()) entry.relay = undefined
537
539
  this.pendingSuffix.length = 0
538
540
  this.clearRelayBuffer()
539
541
  }
540
542
 
541
543
  private releaseRelayWait(): void {
542
544
  let released = false
543
- for (const entry of this.relays.values()) {
544
- if (entry.state === 'waiting') {
545
- entry.state = 'unawaited'
545
+ for (const entry of this.calls.values()) {
546
+ if (entry.relay?.state === 'waiting') {
547
+ entry.relay.state = 'unawaited'
546
548
  released = true
547
549
  }
548
550
  }
@@ -592,7 +594,7 @@ export class AcpTurn {
592
594
  Number.isFinite(update.used) &&
593
595
  update.used > 0
594
596
  ) {
595
- this.contextUsed = update.used
597
+ this.contextTokens = update.used
596
598
  return
597
599
  }
598
600
  const text =
@@ -614,12 +616,7 @@ export class AcpTurn {
614
616
  */
615
617
  private consumeMessage(text: string): void {
616
618
  const combined = this.noticeHold + text
617
- if (AGENT_RETRY_NOTICE.test(combined)) {
618
- this.noticeHold = ''
619
- this.retryNotices++
620
- return
621
- }
622
- const kind = classifyOutputLimitNotice(combined)
619
+ const kind = classifyAgentRetryNotice(combined)
623
620
  if (kind === 'hold') {
624
621
  this.noticeHold = combined
625
622
  return
@@ -641,7 +638,7 @@ export class AcpTurn {
641
638
  if (this.noticeHold.length === 0) return ''
642
639
  const held = this.noticeHold
643
640
  this.noticeHold = ''
644
- if (classifyOutputLimitNotice(held) === 'drop') {
641
+ if (classifyAgentRetryNotice(held) === 'drop') {
645
642
  this.retryNotices++
646
643
  return ''
647
644
  }
@@ -684,13 +681,13 @@ export class AcpTurn {
684
681
  private settleCalls(reason: string): void {
685
682
  this.releaseSignal?.()
686
683
  this.releaseSignal = undefined
687
- for (const call of this.calls.values()) {
688
- call.result.resolve({
684
+ for (const entry of this.calls.values()) {
685
+ entry.pending = false
686
+ entry.call.result.resolve({
689
687
  content: [{ type: 'text', text: reason }],
690
688
  isError: true,
691
689
  })
692
690
  }
693
- this.pendingCalls.clear()
694
691
  }
695
692
  }
696
693
 
@@ -978,7 +975,7 @@ async function* stepChunks(
978
975
  if (turn.guard(undefined, signal) !== undefined) return
979
976
  for (const call of batch) {
980
977
  const blockIndex = index++
981
- turn.pendingCalls.set(call.id, call)
978
+ turn.markPending(call.id)
982
979
  yield {
983
980
  type: 'block-start',
984
981
  index: blockIndex,
@@ -1017,8 +1014,8 @@ async function* stepChunks(
1017
1014
  ) {
1018
1015
  turn.continuations++
1019
1016
  turn.segmentToolSteps = 0
1020
- turn.contextUsed = undefined
1021
- turn.estimatedContextUsed = undefined
1017
+ turn.contextTokens = undefined
1018
+ turn.estimatedContextTokens = undefined
1022
1019
  turn.bindPrompt(host.continuePrompt())
1023
1020
  break
1024
1021
  }
@@ -1039,8 +1036,8 @@ async function* stepChunks(
1039
1036
  ? turn.segmentToolSteps + 1
1040
1037
  : turn.toolSteps + turn.continuations + 1
1041
1038
  const usage = toTokenUsage(turn.usage, segmentCalls, {
1042
- contextTokens: turn.contextUsed,
1043
- estimatedContextTokens: turn.estimatedContextUsed,
1039
+ contextTokens: turn.contextTokens,
1040
+ estimatedContextTokens: turn.estimatedContextTokens,
1044
1041
  lastSegmentUsage: event.result.usage ?? turn.usage,
1045
1042
  })
1046
1043
  if (usage !== undefined) yield { type: 'usage', usage }
@@ -1273,6 +1270,6 @@ export function isEmptyInput(rawInput: unknown): boolean {
1273
1270
  if (rawInput === undefined || rawInput === null) return true
1274
1271
  if (typeof rawInput === 'string') return rawInput.trim().length === 0
1275
1272
  if (Array.isArray(rawInput)) return rawInput.length === 0
1276
- if (typeof rawInput === 'object') return Object.keys(rawInput).length === 0
1273
+ if (isRecord(rawInput)) return Object.keys(rawInput).length === 0
1277
1274
  return false
1278
1275
  }