pi-agy-acp 0.2.0 → 0.2.2
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.
- package/CHANGELOG.md +26 -0
- package/README.md +4 -5
- package/docs/development.md +44 -12
- package/docs/reference.md +45 -35
- package/index.ts +19 -8
- package/package.json +1 -1
- package/src/acp-process.ts +48 -4
- package/src/catalog.ts +219 -51
- package/src/config.ts +1 -1
- package/src/conversation.ts +379 -35
- package/src/format.ts +76 -25
- package/src/host.ts +257 -20
- package/src/jsonrpc.ts +38 -4
- package/src/mcp-bridge.ts +26 -2
- package/src/pi-stream.ts +2 -2
- package/src/preflight.ts +356 -309
- package/src/quota.ts +202 -36
- package/src/runtime.ts +417 -139
- package/src/session-db.ts +670 -0
package/src/conversation.ts
CHANGED
|
@@ -19,7 +19,11 @@ import type {
|
|
|
19
19
|
AcpPermissionRequest,
|
|
20
20
|
AcpToolCallMeta,
|
|
21
21
|
} from './acp-process.ts'
|
|
22
|
-
import type {
|
|
22
|
+
import type {
|
|
23
|
+
BridgeCallRequest,
|
|
24
|
+
BridgeTool,
|
|
25
|
+
BridgeToolResult,
|
|
26
|
+
} from './mcp-bridge.ts'
|
|
23
27
|
import {
|
|
24
28
|
AGENT_TOOL_PREFIX,
|
|
25
29
|
CALL_TOOL_NAME,
|
|
@@ -35,39 +39,67 @@ const OUTPUT_LIMIT_HEAD =
|
|
|
35
39
|
/** Second sentence of that same notice. */
|
|
36
40
|
const OUTPUT_LIMIT_TAIL =
|
|
37
41
|
'please continue from where you left off, keeping your response shorter'
|
|
42
|
+
/** Internal retry notice agy emits when an upstream stream is interrupted mid-turn. */
|
|
43
|
+
const STREAM_INTERRUPTED =
|
|
44
|
+
'the stream was interrupted. please continue the task you were working on.'
|
|
45
|
+
/** Internal retry notice agy emits when a model response contains neither text nor tool calls. */
|
|
46
|
+
const EMPTY_MODEL_OUTPUT =
|
|
47
|
+
'model output error: model output must contain either output text or tool calls, these cannot both be empty, please try again'
|
|
48
|
+
const EMPTY_MODEL_OUTPUT_BODY =
|
|
49
|
+
'model output must contain either output text or tool calls, these cannot both be empty, please try again'
|
|
50
|
+
/** Generic retry notice prefix paired with a trailing `Retries remaining: <N>`. */
|
|
51
|
+
const PROBLEM_RETRY_PREFIX = 'there was a problem'
|
|
52
|
+
/** Cap on held characters while waiting for `Retries remaining: <N>` after `There was a problem`. */
|
|
53
|
+
const MAX_PROBLEM_NOTICE_CHARS = 512
|
|
38
54
|
|
|
39
|
-
/** Collapse agy's warning mark and line breaks so
|
|
55
|
+
/** Collapse agy's warning mark, line-leading `Error:`, and line breaks so notices match across chunks. */
|
|
40
56
|
function noticeText(raw: string): string {
|
|
41
57
|
return raw
|
|
42
58
|
.replace(/⚠/g, ' ')
|
|
43
|
-
.replace(
|
|
59
|
+
.replace(/(?:^|\n)\s*error:\s*/gi, ' ')
|
|
44
60
|
.replace(/\s+/g, ' ')
|
|
45
61
|
.trim()
|
|
46
62
|
.toLowerCase()
|
|
47
63
|
}
|
|
48
64
|
|
|
49
65
|
/**
|
|
50
|
-
* Classify text against agy's output-cap continuation
|
|
51
|
-
* `drop` is only
|
|
66
|
+
* Classify text against agy's internal retry and output-cap continuation notices.
|
|
67
|
+
* `drop` is only an internal notice, `hold` is still a prefix of one, `emit` is model text.
|
|
52
68
|
*/
|
|
53
69
|
export function classifyOutputLimitNotice(
|
|
54
70
|
raw: string,
|
|
55
71
|
): 'drop' | 'hold' | 'emit' {
|
|
56
72
|
const text = noticeText(raw)
|
|
57
|
-
if (text.length === 0) return 'emit'
|
|
73
|
+
if (text.length === 0) return raw.includes('⚠') ? 'hold' : 'emit'
|
|
74
|
+
// Terminal exhaustion (`Retries remaining: 0`) must surface immediately instead of being dropped or held.
|
|
75
|
+
if (/\bretries remaining:\s*0+$/i.test(text)) return 'emit'
|
|
76
|
+
if (/^there was a problem\b/.test(text)) {
|
|
77
|
+
if (/\bretries remaining:\s*[1-9]\d*$/.test(text)) return 'drop'
|
|
78
|
+
return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
|
|
79
|
+
}
|
|
80
|
+
if (PROBLEM_RETRY_PREFIX.startsWith(text) && text.startsWith('there was'))
|
|
81
|
+
return 'hold'
|
|
58
82
|
const stripped = text.replace(/\s*retries remaining:\s*\d*\s*$/i, '').trim()
|
|
59
83
|
const retry = text.slice(stripped.length).trim()
|
|
60
84
|
if (retry.length > 0 && !/^retries remaining:\s*\d*$/i.test(retry))
|
|
61
85
|
return 'emit'
|
|
62
|
-
if (stripped.length === 0)
|
|
63
|
-
|
|
86
|
+
if (stripped.length === 0) {
|
|
87
|
+
if (/^retries remaining:\s*[1-9]\d*$/i.test(text)) return 'drop'
|
|
88
|
+
return /^retries remaining:\s*$/i.test(text) ? 'hold' : 'emit'
|
|
89
|
+
}
|
|
64
90
|
const full = `${OUTPUT_LIMIT_HEAD} ${OUTPUT_LIMIT_TAIL}`
|
|
65
91
|
if (
|
|
66
92
|
stripped === full ||
|
|
67
93
|
stripped === OUTPUT_LIMIT_HEAD ||
|
|
68
|
-
stripped === OUTPUT_LIMIT_TAIL
|
|
69
|
-
|
|
70
|
-
|
|
94
|
+
stripped === OUTPUT_LIMIT_TAIL ||
|
|
95
|
+
stripped === STREAM_INTERRUPTED ||
|
|
96
|
+
stripped === EMPTY_MODEL_OUTPUT ||
|
|
97
|
+
stripped === EMPTY_MODEL_OUTPUT_BODY
|
|
98
|
+
) {
|
|
99
|
+
if (retry.length === 0 || /^retries remaining:\s*[1-9]\d*$/i.test(retry))
|
|
100
|
+
return 'drop'
|
|
101
|
+
return /^retries remaining:\s*$/i.test(retry) ? 'hold' : 'emit'
|
|
102
|
+
}
|
|
71
103
|
if (full.startsWith(stripped) && stripped.startsWith('your previous'))
|
|
72
104
|
return 'hold'
|
|
73
105
|
if (
|
|
@@ -75,6 +107,17 @@ export function classifyOutputLimitNotice(
|
|
|
75
107
|
stripped.startsWith('please continue from where you left off')
|
|
76
108
|
)
|
|
77
109
|
return 'hold'
|
|
110
|
+
if (
|
|
111
|
+
STREAM_INTERRUPTED.startsWith(stripped) &&
|
|
112
|
+
stripped.startsWith('the stream')
|
|
113
|
+
)
|
|
114
|
+
return 'hold'
|
|
115
|
+
if (
|
|
116
|
+
(EMPTY_MODEL_OUTPUT.startsWith(stripped) ||
|
|
117
|
+
EMPTY_MODEL_OUTPUT_BODY.startsWith(stripped)) &&
|
|
118
|
+
stripped.startsWith('model output')
|
|
119
|
+
)
|
|
120
|
+
return 'hold'
|
|
78
121
|
if ('retries remaining:'.startsWith(text) && text.startsWith('retries'))
|
|
79
122
|
return 'hold'
|
|
80
123
|
return 'emit'
|
|
@@ -140,6 +183,13 @@ export type TurnEvent =
|
|
|
140
183
|
/** Bound on buffered text/thought chars accumulated while a tool call is relayed. */
|
|
141
184
|
const MAX_RELAY_BUFFER_CHARS = 65_536
|
|
142
185
|
|
|
186
|
+
type RelayState = 'waiting' | 'unawaited' | 'notified'
|
|
187
|
+
|
|
188
|
+
interface RelayEntry {
|
|
189
|
+
state: RelayState
|
|
190
|
+
resolved: boolean
|
|
191
|
+
}
|
|
192
|
+
|
|
143
193
|
/** One running ACP prompt turn. */
|
|
144
194
|
export class AcpTurn {
|
|
145
195
|
readonly cancellation = new AbortController()
|
|
@@ -160,13 +210,25 @@ export class AcpTurn {
|
|
|
160
210
|
continuations = 0
|
|
161
211
|
/** The agent ended the prompt. */
|
|
162
212
|
finished = false
|
|
213
|
+
/** True while an ACP `session/prompt` RPC for this turn has not yet settled. */
|
|
214
|
+
private promptActive = false
|
|
163
215
|
/** Settles after the current prompt's result or error has been queued. */
|
|
164
216
|
promptSettled: Promise<void> = Promise.resolve()
|
|
165
217
|
usage?: AcpPromptResult['usage']
|
|
166
218
|
/** Latest positive single-call context occupancy reported via `usage_update.used`. */
|
|
167
219
|
contextUsed?: number
|
|
168
|
-
/**
|
|
169
|
-
|
|
220
|
+
/** Fallback single-call context occupancy decoded from same-turn `gen_metadata` (`estimated_tokens_used`). */
|
|
221
|
+
estimatedContextUsed?: number
|
|
222
|
+
/** Lower `gen_metadata.idx` bound owned by the active turn segment, or `null` when unobservable. */
|
|
223
|
+
metaFloorIdx: number | null = 0
|
|
224
|
+
/** Highest `steps.idx` already persisted before the active prompt segment started, or `null` when unobservable. */
|
|
225
|
+
lastStepIdx: number | null = -1
|
|
226
|
+
/** Per-call relay lifecycle: waiting (gating `relayBuffer`) -> unawaited -> notified. */
|
|
227
|
+
private readonly relays = new Map<string, RelayEntry>()
|
|
228
|
+
/** Per-call MCP delivery ownership: absent (idle), waiting (active MCP handler), or delivered (committed). */
|
|
229
|
+
private readonly callDelivery = new Map<string, 'waiting' | 'delivered'>()
|
|
230
|
+
/** Tool deltas and steering text deferred until an active MCP call returns a real result. */
|
|
231
|
+
private readonly pendingSuffix: string[] = []
|
|
170
232
|
/** Bounded output buffered while one or more calls are relayed. */
|
|
171
233
|
private relayBuffer: Array<Extract<TurnEvent, { kind: 'text' | 'thought' }>> = []
|
|
172
234
|
private relayBufferChars = 0
|
|
@@ -184,6 +246,41 @@ export class AcpTurn {
|
|
|
184
246
|
this.turnTag = turnTag
|
|
185
247
|
}
|
|
186
248
|
|
|
249
|
+
/** Authoritative liveness of the underlying ACP `session/prompt` RPC. */
|
|
250
|
+
get isPromptActive(): boolean {
|
|
251
|
+
return this.promptActive && !this.finished && this.terminal === undefined
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Bind one ACP `session/prompt` RPC promise to this turn's lifecycle.
|
|
256
|
+
* Clears `promptActive` the instant the RPC settles so tool-result delivery
|
|
257
|
+
* never has to guess liveness from the head of `events`.
|
|
258
|
+
*/
|
|
259
|
+
bindPrompt(
|
|
260
|
+
promise: Promise<AcpPromptResult>,
|
|
261
|
+
options?: {
|
|
262
|
+
mapError?: (error: unknown) => Error
|
|
263
|
+
},
|
|
264
|
+
): void {
|
|
265
|
+
this.promptActive = true
|
|
266
|
+
this.promptSettled = promise.then(
|
|
267
|
+
(result) => {
|
|
268
|
+
this.promptActive = false
|
|
269
|
+
this.events.push({ kind: 'done', result })
|
|
270
|
+
},
|
|
271
|
+
(error: unknown) => {
|
|
272
|
+
this.promptActive = false
|
|
273
|
+
this.fail(
|
|
274
|
+
options?.mapError !== undefined
|
|
275
|
+
? options.mapError(error)
|
|
276
|
+
: error instanceof Error
|
|
277
|
+
? error
|
|
278
|
+
: new Error(String(error)),
|
|
279
|
+
)
|
|
280
|
+
},
|
|
281
|
+
)
|
|
282
|
+
}
|
|
283
|
+
|
|
187
284
|
/**
|
|
188
285
|
* Register one agent tool call.
|
|
189
286
|
* @param name - Pi tool name.
|
|
@@ -191,6 +288,10 @@ export class AcpTurn {
|
|
|
191
288
|
* @returns the parked call.
|
|
192
289
|
*/
|
|
193
290
|
park(name: string, args: Record<string, unknown>): ParkedCall {
|
|
291
|
+
// A new tool call means the agent moved on instead of only waiting on relayed call(s):
|
|
292
|
+
// flush buffered thought/text in chronological order before queueing the new call so
|
|
293
|
+
// subsequent steps stream live instead of accumulating in relayBuffer.
|
|
294
|
+
this.releaseRelayWait()
|
|
194
295
|
const call: ParkedCall = {
|
|
195
296
|
id: `agy_${this.turnTag}_${++this.nextCall}`,
|
|
196
297
|
name,
|
|
@@ -202,29 +303,253 @@ export class AcpTurn {
|
|
|
202
303
|
return call
|
|
203
304
|
}
|
|
204
305
|
|
|
306
|
+
/** Park one Pi tool call and wait for its result, relaying if it outlives `relayAfterMs`. */
|
|
307
|
+
invokeTool(
|
|
308
|
+
name: string,
|
|
309
|
+
args: Record<string, unknown>,
|
|
310
|
+
relayAfterMs: number,
|
|
311
|
+
signal: AbortSignal,
|
|
312
|
+
commit?: BridgeCallRequest['commit'],
|
|
313
|
+
): Promise<BridgeToolResult> {
|
|
314
|
+
return this.awaitCall(this.park(name, args), relayAfterMs, signal, commit)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Resume waiting on a previously parked call via `pi_await_result`, or return undefined if unknown. */
|
|
318
|
+
awaitRelayedCall(
|
|
319
|
+
callId: string,
|
|
320
|
+
relayAfterMs: number,
|
|
321
|
+
signal: AbortSignal,
|
|
322
|
+
commit?: BridgeCallRequest['commit'],
|
|
323
|
+
): Promise<BridgeToolResult> | undefined {
|
|
324
|
+
const call = this.calls.get(callId)
|
|
325
|
+
if (call === undefined) return undefined
|
|
326
|
+
const status = this.callDelivery.get(callId)
|
|
327
|
+
if (status === 'delivered') {
|
|
328
|
+
return Promise.resolve({
|
|
329
|
+
content: [
|
|
330
|
+
{
|
|
331
|
+
type: 'text',
|
|
332
|
+
text: `Tool call ${callId} result was already delivered.`,
|
|
333
|
+
},
|
|
334
|
+
],
|
|
335
|
+
})
|
|
336
|
+
}
|
|
337
|
+
if (status === 'waiting') {
|
|
338
|
+
return Promise.resolve({
|
|
339
|
+
content: [
|
|
340
|
+
{
|
|
341
|
+
type: 'text',
|
|
342
|
+
text: `Tool call ${callId} is already being awaited.`,
|
|
343
|
+
},
|
|
344
|
+
],
|
|
345
|
+
isError: true,
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
if (signal.aborted) {
|
|
349
|
+
return Promise.resolve({
|
|
350
|
+
content: [{ type: 'text', text: 'The tool call was cancelled.' }],
|
|
351
|
+
isError: true,
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
this.resumeRelay(callId)
|
|
355
|
+
return this.awaitCall(call, relayAfterMs, signal, commit)
|
|
356
|
+
}
|
|
357
|
+
|
|
205
358
|
get isRelaying(): boolean {
|
|
206
|
-
|
|
359
|
+
for (const entry of this.relays.values()) {
|
|
360
|
+
if (entry.state === 'waiting') return true
|
|
361
|
+
}
|
|
362
|
+
return false
|
|
207
363
|
}
|
|
208
364
|
|
|
209
365
|
/** Record that `callId` timed out into a relay notice and awaits `pi_await_result`. */
|
|
210
366
|
markRelayed(callId: string): void {
|
|
211
|
-
this.
|
|
367
|
+
const prev = this.relays.get(callId)
|
|
368
|
+
this.relays.set(callId, {
|
|
369
|
+
state: 'waiting',
|
|
370
|
+
resolved: prev?.resolved ?? false,
|
|
371
|
+
})
|
|
212
372
|
}
|
|
213
373
|
|
|
214
|
-
/** Clear one relayed call when `pi_await_result` resumes it, flushing buffered output once all
|
|
374
|
+
/** Clear one relayed call when `pi_await_result` resumes it, flushing buffered output once all waits clear. */
|
|
215
375
|
resumeRelay(callId: string): void {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
376
|
+
const wasWaiting = this.relays.get(callId)?.state === 'waiting'
|
|
377
|
+
this.relays.delete(callId)
|
|
378
|
+
if (wasWaiting && !this.isRelaying) this.flushRelayBuffer()
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Deliver Pi's tool results for the currently pending batch.
|
|
383
|
+
* When the ACP prompt is still active, resolves the parked calls and defers any
|
|
384
|
+
* harness suffix onto the next delivered MCP result; otherwise returns the
|
|
385
|
+
* pending batch and combined suffix so the owner can open a continuation prompt.
|
|
386
|
+
*/
|
|
387
|
+
deliverToolResults(
|
|
388
|
+
results: ReadonlyMap<string, BridgeToolResult>,
|
|
389
|
+
suffix: string,
|
|
390
|
+
):
|
|
391
|
+
| { resumed: true }
|
|
392
|
+
| { resumed: false; pending: ParkedCall[]; suffix: string } {
|
|
393
|
+
const pending = [...this.pendingCalls.values()]
|
|
394
|
+
this.pendingCalls.clear()
|
|
395
|
+
if (!this.isPromptActive) {
|
|
396
|
+
const carried = this.consumePendingSuffix()
|
|
397
|
+
return {
|
|
398
|
+
resumed: false,
|
|
399
|
+
pending,
|
|
400
|
+
suffix: [carried, suffix].filter(Boolean).join('\n\n'),
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (suffix.length > 0) this.pendingSuffix.push(suffix)
|
|
404
|
+
for (const call of pending) {
|
|
405
|
+
const result = results.get(call.id)
|
|
406
|
+
if (result === undefined) continue
|
|
407
|
+
const entry = this.relays.get(call.id)
|
|
408
|
+
if (entry !== undefined) entry.resolved = true
|
|
409
|
+
call.result.resolve(result)
|
|
410
|
+
}
|
|
411
|
+
return { resumed: true }
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Finalize relay tracking when the prompt finishes with `stop`.
|
|
416
|
+
* Always clears relay state and reports whether completion is clean (`ok`),
|
|
417
|
+
* has unretrieved relayed calls (`note`), or ended prematurely while still
|
|
418
|
+
* actively waiting on relayed calls (`premature`).
|
|
419
|
+
*/
|
|
420
|
+
settleOnDone(
|
|
421
|
+
stop: AcpPromptResult['stopReason'],
|
|
422
|
+
):
|
|
423
|
+
| { kind: 'ok' }
|
|
424
|
+
| { kind: 'note'; ids: string[] }
|
|
425
|
+
| { kind: 'premature' } {
|
|
426
|
+
if (stop !== 'end_turn' && stop !== 'max_tokens') {
|
|
427
|
+
this.clearRelay()
|
|
428
|
+
return { kind: 'ok' }
|
|
429
|
+
}
|
|
430
|
+
if (this.isRelaying) {
|
|
431
|
+
this.clearRelay()
|
|
432
|
+
return { kind: 'premature' }
|
|
433
|
+
}
|
|
434
|
+
const ids = [...this.relays.keys()]
|
|
435
|
+
this.clearRelay()
|
|
436
|
+
return ids.length > 0 ? { kind: 'note', ids } : { kind: 'ok' }
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
private async awaitCall(
|
|
440
|
+
call: ParkedCall,
|
|
441
|
+
relayAfterMs: number,
|
|
442
|
+
signal: AbortSignal,
|
|
443
|
+
commit?: BridgeCallRequest['commit'],
|
|
444
|
+
): Promise<BridgeToolResult> {
|
|
445
|
+
this.callDelivery.set(call.id, 'waiting')
|
|
446
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
447
|
+
const relay = new Promise<'relay'>((resolve) => {
|
|
448
|
+
timer = setTimeout(() => resolve('relay'), relayAfterMs)
|
|
449
|
+
})
|
|
450
|
+
let onAbort: (() => void) | undefined
|
|
451
|
+
const aborted = new Promise<'aborted'>((resolve) => {
|
|
452
|
+
if (signal.aborted) resolve('aborted')
|
|
453
|
+
else {
|
|
454
|
+
onAbort = () => resolve('aborted')
|
|
455
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
456
|
+
}
|
|
457
|
+
})
|
|
458
|
+
try {
|
|
459
|
+
const outcome = await Promise.race([call.result.promise, relay, aborted])
|
|
460
|
+
// Check signal.aborted first to close the same-tick Promise.race tie where
|
|
461
|
+
// call.result.promise precedes aborted.
|
|
462
|
+
if (signal.aborted || outcome === 'aborted') {
|
|
463
|
+
return {
|
|
464
|
+
content: [{ type: 'text', text: 'The tool call was cancelled.' }],
|
|
465
|
+
isError: true,
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
if (outcome === 'relay') {
|
|
469
|
+
this.markRelayed(call.id)
|
|
470
|
+
return relayNotice(call)
|
|
471
|
+
}
|
|
472
|
+
return commit !== undefined
|
|
473
|
+
? commit(() => this.deliverCallResult(call.id, outcome))
|
|
474
|
+
: this.deliverCallResult(call.id, outcome)
|
|
475
|
+
} finally {
|
|
476
|
+
if (this.callDelivery.get(call.id) === 'waiting')
|
|
477
|
+
this.callDelivery.delete(call.id)
|
|
478
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
479
|
+
if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
private consumePendingSuffix(): string {
|
|
484
|
+
if (this.pendingSuffix.length === 0) return ''
|
|
485
|
+
const combined = this.pendingSuffix.join('\n\n')
|
|
486
|
+
this.pendingSuffix.length = 0
|
|
487
|
+
return combined
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Finalize one real tool result immediately before returning it over MCP:
|
|
492
|
+
* release any stale relay buffer wait (e.g. when a parallel sibling was never re-awaited)
|
|
493
|
+
* and attach deferred harness suffixes plus a one-time completion update for resolved unretrieved relays.
|
|
494
|
+
*/
|
|
495
|
+
private deliverCallResult(
|
|
496
|
+
callId: string,
|
|
497
|
+
result: BridgeToolResult,
|
|
498
|
+
): BridgeToolResult {
|
|
499
|
+
this.callDelivery.set(callId, 'delivered')
|
|
500
|
+
this.relays.delete(callId)
|
|
501
|
+
this.releaseRelayWait()
|
|
502
|
+
const notes: string[] = []
|
|
503
|
+
const suffix = this.consumePendingSuffix()
|
|
504
|
+
if (suffix.length > 0) notes.push(suffix)
|
|
505
|
+
const completedLines: string[] = []
|
|
506
|
+
for (const [id, entry] of this.relays) {
|
|
507
|
+
if (entry.state !== 'unawaited' || !entry.resolved) continue
|
|
508
|
+
entry.state = 'notified'
|
|
509
|
+
const completed = this.calls.get(id)
|
|
510
|
+
if (completed === undefined) continue
|
|
511
|
+
completedLines.push(
|
|
512
|
+
`[tool completed: ${completed.id} (${completed.name}) — call ${AGENT_TOOL_PREFIX}${AWAIT_TOOL_NAME} with {"call_id":"${completed.id}"} to read its result]`,
|
|
513
|
+
)
|
|
514
|
+
}
|
|
515
|
+
if (completedLines.length > 0) {
|
|
516
|
+
notes.push(
|
|
517
|
+
`<harness_relay_update>\n${completedLines.join('\n')}\n</harness_relay_update>`,
|
|
518
|
+
)
|
|
519
|
+
}
|
|
520
|
+
if (notes.length === 0) return result
|
|
521
|
+
return {
|
|
522
|
+
...result,
|
|
523
|
+
content: [
|
|
524
|
+
...result.content,
|
|
525
|
+
{ type: 'text', text: `\n\n${notes.join('\n\n')}` },
|
|
526
|
+
],
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** Release all relay tracking, deferred suffixes, and buffered output. */
|
|
531
|
+
private clearRelay(): void {
|
|
532
|
+
this.relays.clear()
|
|
533
|
+
this.pendingSuffix.length = 0
|
|
534
|
+
this.clearRelayBuffer()
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
private releaseRelayWait(): void {
|
|
538
|
+
let released = false
|
|
539
|
+
for (const entry of this.relays.values()) {
|
|
540
|
+
if (entry.state === 'waiting') {
|
|
541
|
+
entry.state = 'unawaited'
|
|
542
|
+
released = true
|
|
543
|
+
}
|
|
221
544
|
}
|
|
545
|
+
if (released) this.flushRelayBuffer()
|
|
222
546
|
}
|
|
223
547
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
this.relayedCalls.clear()
|
|
548
|
+
private flushRelayBuffer(): void {
|
|
549
|
+
for (const event of this.relayBuffer) this.events.push(event)
|
|
227
550
|
this.clearRelayBuffer()
|
|
551
|
+
const held = this.recoverNoticeHold()
|
|
552
|
+
if (held.length > 0) this.events.push({ kind: 'text', text: held })
|
|
228
553
|
}
|
|
229
554
|
|
|
230
555
|
private clearRelayBuffer(): void {
|
|
@@ -285,13 +610,18 @@ export class AcpTurn {
|
|
|
285
610
|
*/
|
|
286
611
|
private consumeMessage(text: string): void {
|
|
287
612
|
const combined = this.noticeHold + text
|
|
613
|
+
if (AGENT_RETRY_NOTICE.test(combined)) {
|
|
614
|
+
this.noticeHold = ''
|
|
615
|
+
this.retryNotices++
|
|
616
|
+
return
|
|
617
|
+
}
|
|
288
618
|
const kind = classifyOutputLimitNotice(combined)
|
|
289
619
|
if (kind === 'hold') {
|
|
290
620
|
this.noticeHold = combined
|
|
291
621
|
return
|
|
292
622
|
}
|
|
293
623
|
this.noticeHold = ''
|
|
294
|
-
if (kind === 'drop'
|
|
624
|
+
if (kind === 'drop') {
|
|
295
625
|
this.retryNotices++
|
|
296
626
|
return
|
|
297
627
|
}
|
|
@@ -376,6 +706,8 @@ export interface PumpHost {
|
|
|
376
706
|
export interface TokenUsageOptions {
|
|
377
707
|
/** Latest single-call context occupancy reported via `usage_update.used`. */
|
|
378
708
|
contextTokens?: number
|
|
709
|
+
/** Fallback single-call context occupancy decoded from same-turn `gen_metadata` (`estimated_tokens_used`). */
|
|
710
|
+
estimatedContextTokens?: number
|
|
379
711
|
/** Final `session/prompt` segment's usage when the turn spanned `max_tokens` continuations. */
|
|
380
712
|
lastSegmentUsage?: AcpPromptResult['usage']
|
|
381
713
|
}
|
|
@@ -434,6 +766,7 @@ export function toTokenUsage(
|
|
|
434
766
|
? Math.min(output, Math.round(usage.thoughtTokens))
|
|
435
767
|
: undefined
|
|
436
768
|
const liveContext = options?.contextTokens
|
|
769
|
+
const estimatedContext = options?.estimatedContextTokens
|
|
437
770
|
let totalTokens: number
|
|
438
771
|
if (
|
|
439
772
|
typeof liveContext === 'number' &&
|
|
@@ -441,6 +774,12 @@ export function toTokenUsage(
|
|
|
441
774
|
liveContext > 0
|
|
442
775
|
) {
|
|
443
776
|
totalTokens = Math.round(liveContext)
|
|
777
|
+
} else if (
|
|
778
|
+
typeof estimatedContext === 'number' &&
|
|
779
|
+
Number.isFinite(estimatedContext) &&
|
|
780
|
+
estimatedContext > 0
|
|
781
|
+
) {
|
|
782
|
+
totalTokens = Math.round(estimatedContext)
|
|
444
783
|
} else {
|
|
445
784
|
const seg = options?.lastSegmentUsage ?? usage
|
|
446
785
|
const scale = Math.max(1, calls)
|
|
@@ -615,18 +954,26 @@ async function* stepChunks(
|
|
|
615
954
|
const stop = event.result.stopReason
|
|
616
955
|
if (
|
|
617
956
|
stop === 'max_tokens' &&
|
|
957
|
+
!turn.isRelaying &&
|
|
618
958
|
turn.continuations < host.maxContinuations
|
|
619
959
|
) {
|
|
620
960
|
turn.continuations++
|
|
621
961
|
turn.segmentToolSteps = 0
|
|
622
962
|
turn.contextUsed = undefined
|
|
623
|
-
turn.
|
|
624
|
-
|
|
625
|
-
(error: unknown) =>
|
|
626
|
-
turn.fail(error instanceof Error ? error : new Error(String(error))),
|
|
627
|
-
)
|
|
963
|
+
turn.estimatedContextUsed = undefined
|
|
964
|
+
turn.bindPrompt(host.continuePrompt())
|
|
628
965
|
break
|
|
629
966
|
}
|
|
967
|
+
const relayOutcome = turn.settleOnDone(stop)
|
|
968
|
+
if (relayOutcome.kind === 'note') {
|
|
969
|
+
const prefix =
|
|
970
|
+
open?.type === 'text' && open.text.length > 0 ? '\n\n' : ''
|
|
971
|
+
turn.produced = true
|
|
972
|
+
yield* append(
|
|
973
|
+
'text',
|
|
974
|
+
`${prefix}[Antigravity ended the turn without retrieving the result of long-running tool call(s) ${relayOutcome.ids.join(', ')}; this reply may not reflect that result.]`,
|
|
975
|
+
)
|
|
976
|
+
}
|
|
630
977
|
turn.finished = true
|
|
631
978
|
yield* close()
|
|
632
979
|
const segmentCalls =
|
|
@@ -635,14 +982,11 @@ async function* stepChunks(
|
|
|
635
982
|
: turn.toolSteps + turn.continuations + 1
|
|
636
983
|
const usage = toTokenUsage(turn.usage, segmentCalls, {
|
|
637
984
|
contextTokens: turn.contextUsed,
|
|
985
|
+
estimatedContextTokens: turn.estimatedContextUsed,
|
|
638
986
|
lastSegmentUsage: event.result.usage ?? turn.usage,
|
|
639
987
|
})
|
|
640
988
|
if (usage !== undefined) yield { type: 'usage', usage }
|
|
641
|
-
if (
|
|
642
|
-
turn.isRelaying &&
|
|
643
|
-
(stop === 'end_turn' || stop === 'max_tokens')
|
|
644
|
-
) {
|
|
645
|
-
turn.clearRelay()
|
|
989
|
+
if (relayOutcome.kind === 'premature') {
|
|
646
990
|
throw new LlmError(
|
|
647
991
|
'Antigravity ended the turn before retrieving relayed tool result(s)',
|
|
648
992
|
'PROVIDER_ERROR',
|