pi-agy-acp 0.1.4 → 0.2.1
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 +24 -0
- package/README.md +4 -5
- package/docs/development.md +33 -10
- package/docs/reference.md +37 -29
- package/index.ts +23 -8
- package/package.json +1 -1
- package/src/acp-process.ts +33 -3
- package/src/catalog.ts +249 -41
- package/src/config.ts +1 -1
- package/src/conversation.ts +326 -32
- package/src/format.ts +16 -7
- package/src/host.ts +120 -18
- package/src/pi-stream.ts +2 -2
- package/src/preflight.ts +385 -34
- package/src/quota.ts +163 -16
- package/src/runtime.ts +244 -105
package/src/conversation.ts
CHANGED
|
@@ -35,37 +35,60 @@ const OUTPUT_LIMIT_HEAD =
|
|
|
35
35
|
/** Second sentence of that same notice. */
|
|
36
36
|
const OUTPUT_LIMIT_TAIL =
|
|
37
37
|
'please continue from where you left off, keeping your response shorter'
|
|
38
|
+
/** Internal retry notice agy emits when an upstream stream is interrupted mid-turn. */
|
|
39
|
+
const STREAM_INTERRUPTED =
|
|
40
|
+
'the stream was interrupted. please continue the task you were working on.'
|
|
41
|
+
/** Internal retry notice agy emits when a model response contains neither text nor tool calls. */
|
|
42
|
+
const EMPTY_MODEL_OUTPUT =
|
|
43
|
+
'model output error: model output must contain either output text or tool calls, these cannot both be empty, please try again'
|
|
44
|
+
const EMPTY_MODEL_OUTPUT_BODY =
|
|
45
|
+
'model output must contain either output text or tool calls, these cannot both be empty, please try again'
|
|
46
|
+
/** Generic retry notice prefix paired with a trailing `Retries remaining: <N>`. */
|
|
47
|
+
const PROBLEM_RETRY_PREFIX = 'there was a problem'
|
|
48
|
+
/** Cap on held characters while waiting for `Retries remaining: <N>` after `There was a problem`. */
|
|
49
|
+
const MAX_PROBLEM_NOTICE_CHARS = 512
|
|
38
50
|
|
|
39
|
-
/** Collapse agy's warning mark and line breaks so
|
|
51
|
+
/** Collapse agy's warning mark, line-leading `Error:`, and line breaks so notices match across chunks. */
|
|
40
52
|
function noticeText(raw: string): string {
|
|
41
53
|
return raw
|
|
42
54
|
.replace(/⚠/g, ' ')
|
|
43
|
-
.replace(
|
|
55
|
+
.replace(/(?:^|\n)\s*error:\s*/gi, ' ')
|
|
44
56
|
.replace(/\s+/g, ' ')
|
|
45
57
|
.trim()
|
|
46
58
|
.toLowerCase()
|
|
47
59
|
}
|
|
48
60
|
|
|
49
61
|
/**
|
|
50
|
-
* Classify text against agy's output-cap continuation
|
|
51
|
-
* `drop` is only
|
|
62
|
+
* Classify text against agy's internal retry and output-cap continuation notices.
|
|
63
|
+
* `drop` is only an internal notice, `hold` is still a prefix of one, `emit` is model text.
|
|
52
64
|
*/
|
|
53
65
|
export function classifyOutputLimitNotice(
|
|
54
66
|
raw: string,
|
|
55
67
|
): 'drop' | 'hold' | 'emit' {
|
|
56
68
|
const text = noticeText(raw)
|
|
57
|
-
if (text.length === 0) return 'emit'
|
|
69
|
+
if (text.length === 0) return raw.includes('⚠') ? 'hold' : 'emit'
|
|
70
|
+
if (/^there was a problem\b/.test(text)) {
|
|
71
|
+
if (/\bretries remaining:\s*\d+$/.test(text)) return 'drop'
|
|
72
|
+
return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
|
|
73
|
+
}
|
|
74
|
+
if (PROBLEM_RETRY_PREFIX.startsWith(text) && text.startsWith('there was'))
|
|
75
|
+
return 'hold'
|
|
58
76
|
const stripped = text.replace(/\s*retries remaining:\s*\d*\s*$/i, '').trim()
|
|
59
77
|
const retry = text.slice(stripped.length).trim()
|
|
60
78
|
if (retry.length > 0 && !/^retries remaining:\s*\d*$/i.test(retry))
|
|
61
79
|
return 'emit'
|
|
62
|
-
if (stripped.length === 0)
|
|
63
|
-
|
|
80
|
+
if (stripped.length === 0) {
|
|
81
|
+
if (/^retries remaining:\s*\d+$/i.test(text)) return 'drop'
|
|
82
|
+
return /^retries remaining:\s*$/i.test(text) ? 'hold' : 'emit'
|
|
83
|
+
}
|
|
64
84
|
const full = `${OUTPUT_LIMIT_HEAD} ${OUTPUT_LIMIT_TAIL}`
|
|
65
85
|
if (
|
|
66
86
|
stripped === full ||
|
|
67
87
|
stripped === OUTPUT_LIMIT_HEAD ||
|
|
68
|
-
stripped === OUTPUT_LIMIT_TAIL
|
|
88
|
+
stripped === OUTPUT_LIMIT_TAIL ||
|
|
89
|
+
stripped === STREAM_INTERRUPTED ||
|
|
90
|
+
stripped === EMPTY_MODEL_OUTPUT ||
|
|
91
|
+
stripped === EMPTY_MODEL_OUTPUT_BODY
|
|
69
92
|
)
|
|
70
93
|
return 'drop'
|
|
71
94
|
if (full.startsWith(stripped) && stripped.startsWith('your previous'))
|
|
@@ -75,6 +98,17 @@ export function classifyOutputLimitNotice(
|
|
|
75
98
|
stripped.startsWith('please continue from where you left off')
|
|
76
99
|
)
|
|
77
100
|
return 'hold'
|
|
101
|
+
if (
|
|
102
|
+
STREAM_INTERRUPTED.startsWith(stripped) &&
|
|
103
|
+
stripped.startsWith('the stream')
|
|
104
|
+
)
|
|
105
|
+
return 'hold'
|
|
106
|
+
if (
|
|
107
|
+
(EMPTY_MODEL_OUTPUT.startsWith(stripped) ||
|
|
108
|
+
EMPTY_MODEL_OUTPUT_BODY.startsWith(stripped)) &&
|
|
109
|
+
stripped.startsWith('model output')
|
|
110
|
+
)
|
|
111
|
+
return 'hold'
|
|
78
112
|
if ('retries remaining:'.startsWith(text) && text.startsWith('retries'))
|
|
79
113
|
return 'hold'
|
|
80
114
|
return 'emit'
|
|
@@ -140,6 +174,13 @@ export type TurnEvent =
|
|
|
140
174
|
/** Bound on buffered text/thought chars accumulated while a tool call is relayed. */
|
|
141
175
|
const MAX_RELAY_BUFFER_CHARS = 65_536
|
|
142
176
|
|
|
177
|
+
type RelayState = 'waiting' | 'unawaited' | 'notified'
|
|
178
|
+
|
|
179
|
+
interface RelayEntry {
|
|
180
|
+
state: RelayState
|
|
181
|
+
resolved: boolean
|
|
182
|
+
}
|
|
183
|
+
|
|
143
184
|
/** One running ACP prompt turn. */
|
|
144
185
|
export class AcpTurn {
|
|
145
186
|
readonly cancellation = new AbortController()
|
|
@@ -160,13 +201,21 @@ export class AcpTurn {
|
|
|
160
201
|
continuations = 0
|
|
161
202
|
/** The agent ended the prompt. */
|
|
162
203
|
finished = false
|
|
204
|
+
/** True while an ACP `session/prompt` RPC for this turn has not yet settled. */
|
|
205
|
+
private promptActive = false
|
|
163
206
|
/** Settles after the current prompt's result or error has been queued. */
|
|
164
207
|
promptSettled: Promise<void> = Promise.resolve()
|
|
165
208
|
usage?: AcpPromptResult['usage']
|
|
166
209
|
/** Latest positive single-call context occupancy reported via `usage_update.used`. */
|
|
167
210
|
contextUsed?: number
|
|
168
|
-
/**
|
|
169
|
-
|
|
211
|
+
/** Fallback single-call context occupancy decoded from same-turn `gen_metadata` (`estimated_tokens_used`). */
|
|
212
|
+
estimatedContextUsed?: number
|
|
213
|
+
/** Lower `gen_metadata.idx` bound owned by the active turn segment, or `null` when unobservable. */
|
|
214
|
+
metaFloorIdx: number | null = 0
|
|
215
|
+
/** Per-call relay lifecycle: waiting (gating `relayBuffer`) -> unawaited -> notified. */
|
|
216
|
+
private readonly relays = new Map<string, RelayEntry>()
|
|
217
|
+
/** Tool deltas and steering text deferred until an active MCP call returns a real result. */
|
|
218
|
+
private readonly pendingSuffix: string[] = []
|
|
170
219
|
/** Bounded output buffered while one or more calls are relayed. */
|
|
171
220
|
private relayBuffer: Array<Extract<TurnEvent, { kind: 'text' | 'thought' }>> = []
|
|
172
221
|
private relayBufferChars = 0
|
|
@@ -184,6 +233,44 @@ export class AcpTurn {
|
|
|
184
233
|
this.turnTag = turnTag
|
|
185
234
|
}
|
|
186
235
|
|
|
236
|
+
/** Authoritative liveness of the underlying ACP `session/prompt` RPC. */
|
|
237
|
+
get isPromptActive(): boolean {
|
|
238
|
+
return this.promptActive && !this.finished && this.terminal === undefined
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Bind one ACP `session/prompt` RPC promise to this turn's lifecycle.
|
|
243
|
+
* Clears `promptActive` the instant the RPC settles so tool-result delivery
|
|
244
|
+
* never has to guess liveness from the head of `events`.
|
|
245
|
+
*/
|
|
246
|
+
bindPrompt(
|
|
247
|
+
promise: Promise<AcpPromptResult>,
|
|
248
|
+
options?: {
|
|
249
|
+
onSettled?: () => void
|
|
250
|
+
mapError?: (error: unknown) => Error
|
|
251
|
+
},
|
|
252
|
+
): void {
|
|
253
|
+
this.promptActive = true
|
|
254
|
+
this.promptSettled = promise.then(
|
|
255
|
+
(result) => {
|
|
256
|
+
this.promptActive = false
|
|
257
|
+
options?.onSettled?.()
|
|
258
|
+
this.events.push({ kind: 'done', result })
|
|
259
|
+
},
|
|
260
|
+
(error: unknown) => {
|
|
261
|
+
this.promptActive = false
|
|
262
|
+
options?.onSettled?.()
|
|
263
|
+
this.fail(
|
|
264
|
+
options?.mapError !== undefined
|
|
265
|
+
? options.mapError(error)
|
|
266
|
+
: error instanceof Error
|
|
267
|
+
? error
|
|
268
|
+
: new Error(String(error)),
|
|
269
|
+
)
|
|
270
|
+
},
|
|
271
|
+
)
|
|
272
|
+
}
|
|
273
|
+
|
|
187
274
|
/**
|
|
188
275
|
* Register one agent tool call.
|
|
189
276
|
* @param name - Pi tool name.
|
|
@@ -191,6 +278,10 @@ export class AcpTurn {
|
|
|
191
278
|
* @returns the parked call.
|
|
192
279
|
*/
|
|
193
280
|
park(name: string, args: Record<string, unknown>): ParkedCall {
|
|
281
|
+
// A new tool call means the agent moved on instead of only waiting on relayed call(s):
|
|
282
|
+
// flush buffered thought/text in chronological order before queueing the new call so
|
|
283
|
+
// subsequent steps stream live instead of accumulating in relayBuffer.
|
|
284
|
+
this.releaseRelayWait()
|
|
194
285
|
const call: ParkedCall = {
|
|
195
286
|
id: `agy_${this.turnTag}_${++this.nextCall}`,
|
|
196
287
|
name,
|
|
@@ -202,29 +293,214 @@ export class AcpTurn {
|
|
|
202
293
|
return call
|
|
203
294
|
}
|
|
204
295
|
|
|
296
|
+
/** Park one Pi tool call and wait for its result, relaying if it outlives `relayAfterMs`. */
|
|
297
|
+
invokeTool(
|
|
298
|
+
name: string,
|
|
299
|
+
args: Record<string, unknown>,
|
|
300
|
+
relayAfterMs: number,
|
|
301
|
+
signal: AbortSignal,
|
|
302
|
+
): Promise<BridgeToolResult> {
|
|
303
|
+
return this.awaitCall(this.park(name, args), relayAfterMs, signal)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Resume waiting on a previously parked call via `pi_await_result`, or return undefined if unknown. */
|
|
307
|
+
awaitRelayedCall(
|
|
308
|
+
callId: string,
|
|
309
|
+
relayAfterMs: number,
|
|
310
|
+
signal: AbortSignal,
|
|
311
|
+
): Promise<BridgeToolResult> | undefined {
|
|
312
|
+
const call = this.calls.get(callId)
|
|
313
|
+
if (call === undefined) return undefined
|
|
314
|
+
this.resumeRelay(callId)
|
|
315
|
+
return this.awaitCall(call, relayAfterMs, signal)
|
|
316
|
+
}
|
|
317
|
+
|
|
205
318
|
get isRelaying(): boolean {
|
|
206
|
-
|
|
319
|
+
for (const entry of this.relays.values()) {
|
|
320
|
+
if (entry.state === 'waiting') return true
|
|
321
|
+
}
|
|
322
|
+
return false
|
|
207
323
|
}
|
|
208
324
|
|
|
209
325
|
/** Record that `callId` timed out into a relay notice and awaits `pi_await_result`. */
|
|
210
326
|
markRelayed(callId: string): void {
|
|
211
|
-
this.
|
|
327
|
+
const prev = this.relays.get(callId)
|
|
328
|
+
this.relays.set(callId, {
|
|
329
|
+
state: 'waiting',
|
|
330
|
+
resolved: prev?.resolved ?? false,
|
|
331
|
+
})
|
|
212
332
|
}
|
|
213
333
|
|
|
214
|
-
/** Clear one relayed call when `pi_await_result` resumes it, flushing buffered output once all
|
|
334
|
+
/** Clear one relayed call when `pi_await_result` resumes it, flushing buffered output once all waits clear. */
|
|
215
335
|
resumeRelay(callId: string): void {
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
336
|
+
const wasWaiting = this.relays.get(callId)?.state === 'waiting'
|
|
337
|
+
this.relays.delete(callId)
|
|
338
|
+
if (wasWaiting && !this.isRelaying) this.flushRelayBuffer()
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Deliver Pi's tool results for the currently pending batch.
|
|
343
|
+
* When the ACP prompt is still active, resolves the parked calls and defers any
|
|
344
|
+
* harness suffix onto the next delivered MCP result; otherwise returns the
|
|
345
|
+
* pending batch and combined suffix so the owner can open a continuation prompt.
|
|
346
|
+
*/
|
|
347
|
+
deliverToolResults(
|
|
348
|
+
results: ReadonlyMap<string, BridgeToolResult>,
|
|
349
|
+
suffix: string,
|
|
350
|
+
):
|
|
351
|
+
| { resumed: true }
|
|
352
|
+
| { resumed: false; pending: ParkedCall[]; suffix: string } {
|
|
353
|
+
const pending = [...this.pendingCalls.values()]
|
|
354
|
+
this.pendingCalls.clear()
|
|
355
|
+
if (!this.isPromptActive) {
|
|
356
|
+
const carried = this.consumePendingSuffix()
|
|
357
|
+
return {
|
|
358
|
+
resumed: false,
|
|
359
|
+
pending,
|
|
360
|
+
suffix: [carried, suffix].filter(Boolean).join('\n\n'),
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
if (suffix.length > 0) this.pendingSuffix.push(suffix)
|
|
364
|
+
for (const call of pending) {
|
|
365
|
+
const result = results.get(call.id)
|
|
366
|
+
if (result === undefined) continue
|
|
367
|
+
const entry = this.relays.get(call.id)
|
|
368
|
+
if (entry !== undefined) entry.resolved = true
|
|
369
|
+
call.result.resolve(result)
|
|
370
|
+
}
|
|
371
|
+
return { resumed: true }
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Finalize relay tracking when the prompt finishes with `stop`.
|
|
376
|
+
* Always clears relay state and reports whether completion is clean (`ok`),
|
|
377
|
+
* has unretrieved relayed calls (`note`), or ended prematurely while still
|
|
378
|
+
* actively waiting on relayed calls (`premature`).
|
|
379
|
+
*/
|
|
380
|
+
settleOnDone(
|
|
381
|
+
stop: AcpPromptResult['stopReason'],
|
|
382
|
+
):
|
|
383
|
+
| { kind: 'ok' }
|
|
384
|
+
| { kind: 'note'; ids: string[] }
|
|
385
|
+
| { kind: 'premature' } {
|
|
386
|
+
if (stop !== 'end_turn' && stop !== 'max_tokens') {
|
|
387
|
+
this.clearRelay()
|
|
388
|
+
return { kind: 'ok' }
|
|
389
|
+
}
|
|
390
|
+
if (this.isRelaying) {
|
|
391
|
+
this.clearRelay()
|
|
392
|
+
return { kind: 'premature' }
|
|
393
|
+
}
|
|
394
|
+
const ids = [...this.relays.keys()]
|
|
395
|
+
this.clearRelay()
|
|
396
|
+
return ids.length > 0 ? { kind: 'note', ids } : { kind: 'ok' }
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
private async awaitCall(
|
|
400
|
+
call: ParkedCall,
|
|
401
|
+
relayAfterMs: number,
|
|
402
|
+
signal: AbortSignal,
|
|
403
|
+
): Promise<BridgeToolResult> {
|
|
404
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
405
|
+
const relay = new Promise<'relay'>((resolve) => {
|
|
406
|
+
timer = setTimeout(() => resolve('relay'), relayAfterMs)
|
|
407
|
+
})
|
|
408
|
+
let onAbort: (() => void) | undefined
|
|
409
|
+
const aborted = new Promise<'aborted'>((resolve) => {
|
|
410
|
+
if (signal.aborted) resolve('aborted')
|
|
411
|
+
else {
|
|
412
|
+
onAbort = () => resolve('aborted')
|
|
413
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
414
|
+
}
|
|
415
|
+
})
|
|
416
|
+
try {
|
|
417
|
+
const outcome = await Promise.race([call.result.promise, relay, aborted])
|
|
418
|
+
if (outcome === 'relay') {
|
|
419
|
+
this.markRelayed(call.id)
|
|
420
|
+
return relayNotice(call)
|
|
421
|
+
}
|
|
422
|
+
if (outcome === 'aborted') {
|
|
423
|
+
return {
|
|
424
|
+
content: [{ type: 'text', text: 'The tool call was cancelled.' }],
|
|
425
|
+
isError: true,
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return this.deliverCallResult(call.id, outcome)
|
|
429
|
+
} finally {
|
|
430
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
431
|
+
if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
private consumePendingSuffix(): string {
|
|
436
|
+
if (this.pendingSuffix.length === 0) return ''
|
|
437
|
+
const combined = this.pendingSuffix.join('\n\n')
|
|
438
|
+
this.pendingSuffix.length = 0
|
|
439
|
+
return combined
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/**
|
|
443
|
+
* Finalize one real tool result immediately before returning it over MCP:
|
|
444
|
+
* release any stale relay buffer wait (e.g. when a parallel sibling was never re-awaited)
|
|
445
|
+
* and attach deferred harness suffixes plus a one-time completion update for resolved unretrieved relays.
|
|
446
|
+
*/
|
|
447
|
+
private deliverCallResult(
|
|
448
|
+
callId: string,
|
|
449
|
+
result: BridgeToolResult,
|
|
450
|
+
): BridgeToolResult {
|
|
451
|
+
this.relays.delete(callId)
|
|
452
|
+
this.releaseRelayWait()
|
|
453
|
+
const notes: string[] = []
|
|
454
|
+
const suffix = this.consumePendingSuffix()
|
|
455
|
+
if (suffix.length > 0) notes.push(suffix)
|
|
456
|
+
const completedLines: string[] = []
|
|
457
|
+
for (const [id, entry] of this.relays) {
|
|
458
|
+
if (entry.state !== 'unawaited' || !entry.resolved) continue
|
|
459
|
+
entry.state = 'notified'
|
|
460
|
+
const completed = this.calls.get(id)
|
|
461
|
+
if (completed === undefined) continue
|
|
462
|
+
completedLines.push(
|
|
463
|
+
`[tool completed: ${completed.id} (${completed.name}) — call ${AGENT_TOOL_PREFIX}${AWAIT_TOOL_NAME} with {"call_id":"${completed.id}"} to read its result]`,
|
|
464
|
+
)
|
|
221
465
|
}
|
|
466
|
+
if (completedLines.length > 0) {
|
|
467
|
+
notes.push(
|
|
468
|
+
`<harness_relay_update>\n${completedLines.join('\n')}\n</harness_relay_update>`,
|
|
469
|
+
)
|
|
470
|
+
}
|
|
471
|
+
if (notes.length === 0) return result
|
|
472
|
+
return {
|
|
473
|
+
...result,
|
|
474
|
+
content: [
|
|
475
|
+
...result.content,
|
|
476
|
+
{ type: 'text', text: `\n\n${notes.join('\n\n')}` },
|
|
477
|
+
],
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Release all relay tracking, deferred suffixes, and buffered output. */
|
|
482
|
+
private clearRelay(): void {
|
|
483
|
+
this.relays.clear()
|
|
484
|
+
this.pendingSuffix.length = 0
|
|
485
|
+
this.clearRelayBuffer()
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
private releaseRelayWait(): void {
|
|
489
|
+
let released = false
|
|
490
|
+
for (const entry of this.relays.values()) {
|
|
491
|
+
if (entry.state === 'waiting') {
|
|
492
|
+
entry.state = 'unawaited'
|
|
493
|
+
released = true
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (released) this.flushRelayBuffer()
|
|
222
497
|
}
|
|
223
498
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
this.relayedCalls.clear()
|
|
499
|
+
private flushRelayBuffer(): void {
|
|
500
|
+
for (const event of this.relayBuffer) this.events.push(event)
|
|
227
501
|
this.clearRelayBuffer()
|
|
502
|
+
const held = this.recoverNoticeHold()
|
|
503
|
+
if (held.length > 0) this.events.push({ kind: 'text', text: held })
|
|
228
504
|
}
|
|
229
505
|
|
|
230
506
|
private clearRelayBuffer(): void {
|
|
@@ -285,13 +561,18 @@ export class AcpTurn {
|
|
|
285
561
|
*/
|
|
286
562
|
private consumeMessage(text: string): void {
|
|
287
563
|
const combined = this.noticeHold + text
|
|
564
|
+
if (AGENT_RETRY_NOTICE.test(combined)) {
|
|
565
|
+
this.noticeHold = ''
|
|
566
|
+
this.retryNotices++
|
|
567
|
+
return
|
|
568
|
+
}
|
|
288
569
|
const kind = classifyOutputLimitNotice(combined)
|
|
289
570
|
if (kind === 'hold') {
|
|
290
571
|
this.noticeHold = combined
|
|
291
572
|
return
|
|
292
573
|
}
|
|
293
574
|
this.noticeHold = ''
|
|
294
|
-
if (kind === 'drop'
|
|
575
|
+
if (kind === 'drop') {
|
|
295
576
|
this.retryNotices++
|
|
296
577
|
return
|
|
297
578
|
}
|
|
@@ -376,6 +657,8 @@ export interface PumpHost {
|
|
|
376
657
|
export interface TokenUsageOptions {
|
|
377
658
|
/** Latest single-call context occupancy reported via `usage_update.used`. */
|
|
378
659
|
contextTokens?: number
|
|
660
|
+
/** Fallback single-call context occupancy decoded from same-turn `gen_metadata` (`estimated_tokens_used`). */
|
|
661
|
+
estimatedContextTokens?: number
|
|
379
662
|
/** Final `session/prompt` segment's usage when the turn spanned `max_tokens` continuations. */
|
|
380
663
|
lastSegmentUsage?: AcpPromptResult['usage']
|
|
381
664
|
}
|
|
@@ -434,6 +717,7 @@ export function toTokenUsage(
|
|
|
434
717
|
? Math.min(output, Math.round(usage.thoughtTokens))
|
|
435
718
|
: undefined
|
|
436
719
|
const liveContext = options?.contextTokens
|
|
720
|
+
const estimatedContext = options?.estimatedContextTokens
|
|
437
721
|
let totalTokens: number
|
|
438
722
|
if (
|
|
439
723
|
typeof liveContext === 'number' &&
|
|
@@ -441,6 +725,12 @@ export function toTokenUsage(
|
|
|
441
725
|
liveContext > 0
|
|
442
726
|
) {
|
|
443
727
|
totalTokens = Math.round(liveContext)
|
|
728
|
+
} else if (
|
|
729
|
+
typeof estimatedContext === 'number' &&
|
|
730
|
+
Number.isFinite(estimatedContext) &&
|
|
731
|
+
estimatedContext > 0
|
|
732
|
+
) {
|
|
733
|
+
totalTokens = Math.round(estimatedContext)
|
|
444
734
|
} else {
|
|
445
735
|
const seg = options?.lastSegmentUsage ?? usage
|
|
446
736
|
const scale = Math.max(1, calls)
|
|
@@ -620,13 +910,20 @@ async function* stepChunks(
|
|
|
620
910
|
turn.continuations++
|
|
621
911
|
turn.segmentToolSteps = 0
|
|
622
912
|
turn.contextUsed = undefined
|
|
623
|
-
turn.
|
|
624
|
-
|
|
625
|
-
(error: unknown) =>
|
|
626
|
-
turn.fail(error instanceof Error ? error : new Error(String(error))),
|
|
627
|
-
)
|
|
913
|
+
turn.estimatedContextUsed = undefined
|
|
914
|
+
turn.bindPrompt(host.continuePrompt())
|
|
628
915
|
break
|
|
629
916
|
}
|
|
917
|
+
const relayOutcome = turn.settleOnDone(stop)
|
|
918
|
+
if (relayOutcome.kind === 'note') {
|
|
919
|
+
const prefix =
|
|
920
|
+
open?.type === 'text' && open.text.length > 0 ? '\n\n' : ''
|
|
921
|
+
turn.produced = true
|
|
922
|
+
yield* append(
|
|
923
|
+
'text',
|
|
924
|
+
`${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.]`,
|
|
925
|
+
)
|
|
926
|
+
}
|
|
630
927
|
turn.finished = true
|
|
631
928
|
yield* close()
|
|
632
929
|
const segmentCalls =
|
|
@@ -635,14 +932,11 @@ async function* stepChunks(
|
|
|
635
932
|
: turn.toolSteps + turn.continuations + 1
|
|
636
933
|
const usage = toTokenUsage(turn.usage, segmentCalls, {
|
|
637
934
|
contextTokens: turn.contextUsed,
|
|
935
|
+
estimatedContextTokens: turn.estimatedContextUsed,
|
|
638
936
|
lastSegmentUsage: event.result.usage ?? turn.usage,
|
|
639
937
|
})
|
|
640
938
|
if (usage !== undefined) yield { type: 'usage', usage }
|
|
641
|
-
if (
|
|
642
|
-
turn.isRelaying &&
|
|
643
|
-
(stop === 'end_turn' || stop === 'max_tokens')
|
|
644
|
-
) {
|
|
645
|
-
turn.clearRelay()
|
|
939
|
+
if (relayOutcome.kind === 'premature') {
|
|
646
940
|
throw new LlmError(
|
|
647
941
|
'Antigravity ended the turn before retrieving relayed tool result(s)',
|
|
648
942
|
'PROVIDER_ERROR',
|
package/src/format.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { asEffort, type Effort, type QuotaDisplay } from './config.ts'
|
|
1
|
+
import { asEffort, EFFORTS, type Effort, type QuotaDisplay } from './config.ts'
|
|
2
2
|
import type {
|
|
3
3
|
AccountInfo,
|
|
4
4
|
QuotaSnapshot,
|
|
@@ -33,10 +33,16 @@ export interface QuotaModelRef {
|
|
|
33
33
|
const EXPLICIT_MEMBERS_PREFIX = /^\s*models within this group:\s*/i
|
|
34
34
|
const CLAUSE_SPLIT = /[,;\n/|&+]+|\b(?:and|or)\b/i
|
|
35
35
|
const ID_DATE_SUFFIX = /[-_](?:20\d{2}[-_]\d{2}[-_]\d{2}|20\d{6})$/i
|
|
36
|
+
const EFFORT_PATTERN = EFFORTS.join('|')
|
|
36
37
|
// Effort or thinking-mode suffixes in model IDs (`-thinking`) and `/usage` labels (`(Thinking)`).
|
|
37
|
-
const ID_QUALIFIER_SUFFIX =
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
const ID_QUALIFIER_SUFFIX = new RegExp(
|
|
39
|
+
`[-_](?:(${EFFORT_PATTERN})(?:-effort)?|(thinking))$`,
|
|
40
|
+
'i',
|
|
41
|
+
)
|
|
42
|
+
const GROUP_QUALIFIER_SUFFIX = new RegExp(
|
|
43
|
+
`\\s*\\((${EFFORT_PATTERN}|thinking)\\)(?=\\s*(?:models?|groups?)?[\\s.!?)]*$)`,
|
|
44
|
+
'i',
|
|
45
|
+
)
|
|
40
46
|
const SPECIFIER = /^\d+(?:\.\d+)*b?$/
|
|
41
47
|
const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
|
|
42
48
|
const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
|
|
@@ -127,7 +133,7 @@ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
|
127
133
|
}
|
|
128
134
|
const idQual = ID_QUALIFIER_SUFFIX.exec(text)
|
|
129
135
|
if (idQual) {
|
|
130
|
-
const nextEffort = asEffort(idQual[1]!.toLowerCase())
|
|
136
|
+
const nextEffort = asEffort((idQual[1] ?? idQual[2])!.toLowerCase())
|
|
131
137
|
if (nextEffort) {
|
|
132
138
|
if (effort && effort !== nextEffort) effortConflict = true
|
|
133
139
|
effort = nextEffort
|
|
@@ -447,7 +453,7 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
|
|
|
447
453
|
` Home: ${status.home}`,
|
|
448
454
|
...(account ? [` Account: ${account}`] : []),
|
|
449
455
|
` Sessions: ${status.liveSessions} live · ${status.activeTurns} active turn(s)`,
|
|
450
|
-
` Context: ${Math.round(status.contextWindow / 1024)}K tokens · default effort: ${status.defaultEffort} (${status.efforts.join(', ')})`,
|
|
456
|
+
` Context: ${status.contextWindow ? `${Math.round(status.contextWindow / 1024)}K tokens` : 'dynamic (unprobed)'} · default effort: ${status.defaultEffort}${status.efforts.length > 0 ? ` (${status.efforts.join(', ')})` : ''}`,
|
|
451
457
|
' Models:',
|
|
452
458
|
]
|
|
453
459
|
if (status.models.length === 0) lines.push(' No models available.')
|
|
@@ -458,7 +464,10 @@ export function formatStatus(status: RuntimeStatus): FormattedNotice {
|
|
|
458
464
|
: model.fixedEffort
|
|
459
465
|
? `[${model.fixedEffort}] (fixed)`
|
|
460
466
|
: 'no effort selector'
|
|
461
|
-
|
|
467
|
+
const ctx = model.contextWindow
|
|
468
|
+
? ` · ${Math.round(model.contextWindow / 1024)}K`
|
|
469
|
+
: ''
|
|
470
|
+
lines.push(` ${model.id} (${model.name}) — ${efforts}${ctx}`)
|
|
462
471
|
}
|
|
463
472
|
if (status.lastTurn) {
|
|
464
473
|
const turn = status.lastTurn
|