pi-agy-acp 0.2.1 → 0.2.3
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 +16 -0
- package/README.md +11 -7
- package/docs/architecture.md +262 -0
- package/docs/development.md +68 -156
- package/docs/reference.md +151 -128
- package/docs/releasing.md +56 -0
- package/index.ts +87 -22
- package/package.json +1 -1
- package/src/acp-process.ts +15 -1
- package/src/catalog.ts +66 -48
- package/src/config.ts +1 -1
- package/src/conversation.ts +66 -16
- package/src/format.ts +68 -23
- package/src/host.ts +148 -13
- package/src/jsonrpc.ts +38 -4
- package/src/mcp-bridge.ts +26 -2
- package/src/preflight.ts +296 -371
- package/src/quota.ts +39 -20
- package/src/runtime.ts +549 -244
- package/src/session-db.ts +670 -0
package/src/catalog.ts
CHANGED
|
@@ -114,11 +114,11 @@ export class ModelCatalog {
|
|
|
114
114
|
private supportsImageInput: boolean | undefined
|
|
115
115
|
/** Latest `availableModels` snapshot, kept for later option updates. */
|
|
116
116
|
private available: readonly AvailableModel[] | undefined
|
|
117
|
-
/**
|
|
118
|
-
private
|
|
119
|
-
/**
|
|
120
|
-
private
|
|
121
|
-
/** Whether a live ACP session has reported the catalog. */
|
|
117
|
+
/** Current on-disk `agy` binary fingerprint, if resolved. */
|
|
118
|
+
private currentFingerprint: string | undefined
|
|
119
|
+
/** Fingerprint of the `agy` binary that produced the cached catalog. */
|
|
120
|
+
private observedFingerprint: string | undefined
|
|
121
|
+
/** Whether a live ACP session has reported the catalog in this process. */
|
|
122
122
|
observed = false
|
|
123
123
|
private readonly cachePath: string
|
|
124
124
|
|
|
@@ -128,10 +128,22 @@ export class ModelCatalog {
|
|
|
128
128
|
*/
|
|
129
129
|
constructor(cachePath: string, binaryFingerprint?: string) {
|
|
130
130
|
this.cachePath = cachePath
|
|
131
|
+
this.currentFingerprint = binaryFingerprint
|
|
131
132
|
this.models = this.load(binaryFingerprint) ?? []
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Whether disk-cached models match the current `agy` binary fingerprint. */
|
|
136
|
+
hasFreshCache(): boolean {
|
|
137
|
+
return (
|
|
138
|
+
this.models.length > 0 &&
|
|
139
|
+
(this.currentFingerprint === undefined ||
|
|
140
|
+
this.observedFingerprint === this.currentFingerprint)
|
|
141
|
+
)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Whether the catalog is current without probing ACP. */
|
|
145
|
+
isCurrent(): boolean {
|
|
146
|
+
return this.observed || this.hasFreshCache()
|
|
135
147
|
}
|
|
136
148
|
|
|
137
149
|
/** Input modalities advertised to Pi, derived from `initialize` `promptCapabilities.image`. */
|
|
@@ -160,20 +172,15 @@ export class ModelCatalog {
|
|
|
160
172
|
* @returns whether cached context windows were invalidated.
|
|
161
173
|
*/
|
|
162
174
|
syncBinaryFingerprint(fingerprint: string | undefined): boolean {
|
|
163
|
-
if (!fingerprint) return false
|
|
164
|
-
|
|
175
|
+
if (!fingerprint || this.currentFingerprint === fingerprint) return false
|
|
176
|
+
this.currentFingerprint = fingerprint
|
|
177
|
+
if (this.observedFingerprint === fingerprint) return false
|
|
165
178
|
const hadContextWindows = this.contextWindows.size > 0
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
if (
|
|
170
|
-
|
|
171
|
-
this.observed = false
|
|
172
|
-
this.fingerprintDirty = true
|
|
173
|
-
this.save()
|
|
174
|
-
return hadContextWindows
|
|
175
|
-
}
|
|
176
|
-
return false
|
|
179
|
+
this.contextWindows.clear()
|
|
180
|
+
this.observed = false
|
|
181
|
+
// Persist cleared contextWindows while keeping observedFingerprint intact until live ACP re-observes.
|
|
182
|
+
if (hadContextWindows) this.save()
|
|
183
|
+
return hadContextWindows
|
|
177
184
|
}
|
|
178
185
|
|
|
179
186
|
/**
|
|
@@ -285,13 +292,14 @@ export class ModelCatalog {
|
|
|
285
292
|
(o) => o.id === 'thought_level' || o.category === 'thought_level',
|
|
286
293
|
)
|
|
287
294
|
const beforeEfforts = JSON.stringify(this.efforts)
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
+
const levelEfforts =
|
|
296
|
+
levelOption?.options !== undefined
|
|
297
|
+
? flattenConfigOptions(levelOption.options)
|
|
298
|
+
.map((o) => o.value)
|
|
299
|
+
.filter((v): v is Effort =>
|
|
300
|
+
(EFFORTS as readonly string[]).includes(v),
|
|
301
|
+
)
|
|
302
|
+
: []
|
|
295
303
|
const modelEntries = flattenConfigOptions(modelOption?.options)
|
|
296
304
|
const next =
|
|
297
305
|
modelEntries.length > 0
|
|
@@ -303,19 +311,37 @@ export class ModelCatalog {
|
|
|
303
311
|
this.observed = true
|
|
304
312
|
const changed = JSON.stringify(next) !== JSON.stringify(this.models)
|
|
305
313
|
if (changed) this.models = next
|
|
314
|
+
const fingerprintChanged =
|
|
315
|
+
modelEntries.length > 0 &&
|
|
316
|
+
this.currentFingerprint !== undefined &&
|
|
317
|
+
this.observedFingerprint !== this.currentFingerprint
|
|
318
|
+
if (fingerprintChanged) this.observedFingerprint = this.currentFingerprint
|
|
319
|
+
let prunedChanged = false
|
|
320
|
+
if (modelEntries.length > 0) {
|
|
321
|
+
const activeIds = new Set(this.models.map((m) => m.id))
|
|
322
|
+
for (const id of [...this.byModel.keys()]) {
|
|
323
|
+
if (!activeIds.has(id)) {
|
|
324
|
+
this.byModel.delete(id)
|
|
325
|
+
prunedChanged = true
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
306
329
|
const derivedChanged = this.deriveEfforts()
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
330
|
+
const union = new Set<Effort>(levelEfforts)
|
|
331
|
+
for (const model of this.models) {
|
|
332
|
+
const values = this.byModel.get(model.id)
|
|
333
|
+
if (values !== undefined) {
|
|
310
334
|
for (const effort of values) union.add(effort)
|
|
311
335
|
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
336
|
+
}
|
|
337
|
+
if (union.size > 0) {
|
|
338
|
+
this.efforts = EFFORTS.filter((e) => union.has(e))
|
|
315
339
|
}
|
|
316
340
|
const effortsChanged =
|
|
317
|
-
|
|
318
|
-
|
|
341
|
+
prunedChanged ||
|
|
342
|
+
derivedChanged ||
|
|
343
|
+
beforeEfforts !== JSON.stringify(this.efforts)
|
|
344
|
+
if (changed || effortsChanged || tierChanged || fingerprintChanged)
|
|
319
345
|
this.save()
|
|
320
346
|
return changed || effortsChanged
|
|
321
347
|
}
|
|
@@ -350,11 +376,7 @@ export class ModelCatalog {
|
|
|
350
376
|
}
|
|
351
377
|
continue
|
|
352
378
|
}
|
|
353
|
-
const present = this.available.some(
|
|
354
|
-
(entry) =>
|
|
355
|
-
entry.modelId === model.id ||
|
|
356
|
-
entry.modelId.startsWith(`${model.id}-`),
|
|
357
|
-
)
|
|
379
|
+
const present = this.available.some((entry) => entry.modelId === model.id)
|
|
358
380
|
if (!present) continue
|
|
359
381
|
const prevEfforts = this.effortsFor(model.id)
|
|
360
382
|
if (this.byModel.get(model.id)?.length !== 0) {
|
|
@@ -385,8 +407,8 @@ export class ModelCatalog {
|
|
|
385
407
|
...(this.supportsImageInput !== undefined
|
|
386
408
|
? { supportsImage: this.supportsImageInput }
|
|
387
409
|
: {}),
|
|
388
|
-
...(this.
|
|
389
|
-
? { binaryFingerprint: this.
|
|
410
|
+
...(this.observedFingerprint !== undefined
|
|
411
|
+
? { binaryFingerprint: this.observedFingerprint }
|
|
390
412
|
: {}),
|
|
391
413
|
},
|
|
392
414
|
null,
|
|
@@ -394,7 +416,6 @@ export class ModelCatalog {
|
|
|
394
416
|
)}\n`,
|
|
395
417
|
)
|
|
396
418
|
renameSync(tempPath, this.cachePath)
|
|
397
|
-
this.fingerprintDirty = false
|
|
398
419
|
} catch (_cacheWrite) {
|
|
399
420
|
try {
|
|
400
421
|
unlinkSync(tempPath)
|
|
@@ -426,10 +447,7 @@ export class ModelCatalog {
|
|
|
426
447
|
const fingerprintMatches =
|
|
427
448
|
expectedFingerprint === undefined ||
|
|
428
449
|
storedFingerprint === expectedFingerprint
|
|
429
|
-
this.
|
|
430
|
-
? (storedFingerprint ?? expectedFingerprint)
|
|
431
|
-
: expectedFingerprint
|
|
432
|
-
this.fingerprintDirty = !fingerprintMatches
|
|
450
|
+
this.observedFingerprint = storedFingerprint
|
|
433
451
|
this.tierInfo = normalizeTier(parsed.tier)
|
|
434
452
|
if (typeof parsed.supportsImage === 'boolean') {
|
|
435
453
|
this.supportsImageInput = parsed.supportsImage
|
package/src/config.ts
CHANGED
|
@@ -33,7 +33,7 @@ export interface Config {
|
|
|
33
33
|
defaultEffort: Effort
|
|
34
34
|
/** Maximum concurrent ACP sessions kept alive across conversations, subagents, and auxiliary calls. */
|
|
35
35
|
maxLiveSessions: number
|
|
36
|
-
/** Idle time after which an
|
|
36
|
+
/** Idle time after which inactive ACP sessions and an otherwise idle ACP process are closed. */
|
|
37
37
|
idleSessionTtlMs: number
|
|
38
38
|
/** Window that groups parallel tool calls into one Pi step. */
|
|
39
39
|
parkSettleMs: number
|
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,
|
|
@@ -67,8 +71,10 @@ export function classifyOutputLimitNotice(
|
|
|
67
71
|
): 'drop' | 'hold' | 'emit' {
|
|
68
72
|
const text = noticeText(raw)
|
|
69
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'
|
|
70
76
|
if (/^there was a problem\b/.test(text)) {
|
|
71
|
-
if (/\bretries remaining:\s
|
|
77
|
+
if (/\bretries remaining:\s*[1-9]\d*$/.test(text)) return 'drop'
|
|
72
78
|
return text.length <= MAX_PROBLEM_NOTICE_CHARS ? 'hold' : 'emit'
|
|
73
79
|
}
|
|
74
80
|
if (PROBLEM_RETRY_PREFIX.startsWith(text) && text.startsWith('there was'))
|
|
@@ -78,7 +84,7 @@ export function classifyOutputLimitNotice(
|
|
|
78
84
|
if (retry.length > 0 && !/^retries remaining:\s*\d*$/i.test(retry))
|
|
79
85
|
return 'emit'
|
|
80
86
|
if (stripped.length === 0) {
|
|
81
|
-
if (/^retries remaining:\s
|
|
87
|
+
if (/^retries remaining:\s*[1-9]\d*$/i.test(text)) return 'drop'
|
|
82
88
|
return /^retries remaining:\s*$/i.test(text) ? 'hold' : 'emit'
|
|
83
89
|
}
|
|
84
90
|
const full = `${OUTPUT_LIMIT_HEAD} ${OUTPUT_LIMIT_TAIL}`
|
|
@@ -89,8 +95,11 @@ export function classifyOutputLimitNotice(
|
|
|
89
95
|
stripped === STREAM_INTERRUPTED ||
|
|
90
96
|
stripped === EMPTY_MODEL_OUTPUT ||
|
|
91
97
|
stripped === EMPTY_MODEL_OUTPUT_BODY
|
|
92
|
-
)
|
|
93
|
-
|
|
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
|
+
}
|
|
94
103
|
if (full.startsWith(stripped) && stripped.startsWith('your previous'))
|
|
95
104
|
return 'hold'
|
|
96
105
|
if (
|
|
@@ -212,8 +221,12 @@ export class AcpTurn {
|
|
|
212
221
|
estimatedContextUsed?: number
|
|
213
222
|
/** Lower `gen_metadata.idx` bound owned by the active turn segment, or `null` when unobservable. */
|
|
214
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
|
|
215
226
|
/** Per-call relay lifecycle: waiting (gating `relayBuffer`) -> unawaited -> notified. */
|
|
216
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'>()
|
|
217
230
|
/** Tool deltas and steering text deferred until an active MCP call returns a real result. */
|
|
218
231
|
private readonly pendingSuffix: string[] = []
|
|
219
232
|
/** Bounded output buffered while one or more calls are relayed. */
|
|
@@ -246,7 +259,6 @@ export class AcpTurn {
|
|
|
246
259
|
bindPrompt(
|
|
247
260
|
promise: Promise<AcpPromptResult>,
|
|
248
261
|
options?: {
|
|
249
|
-
onSettled?: () => void
|
|
250
262
|
mapError?: (error: unknown) => Error
|
|
251
263
|
},
|
|
252
264
|
): void {
|
|
@@ -254,12 +266,10 @@ export class AcpTurn {
|
|
|
254
266
|
this.promptSettled = promise.then(
|
|
255
267
|
(result) => {
|
|
256
268
|
this.promptActive = false
|
|
257
|
-
options?.onSettled?.()
|
|
258
269
|
this.events.push({ kind: 'done', result })
|
|
259
270
|
},
|
|
260
271
|
(error: unknown) => {
|
|
261
272
|
this.promptActive = false
|
|
262
|
-
options?.onSettled?.()
|
|
263
273
|
this.fail(
|
|
264
274
|
options?.mapError !== undefined
|
|
265
275
|
? options.mapError(error)
|
|
@@ -299,8 +309,9 @@ export class AcpTurn {
|
|
|
299
309
|
args: Record<string, unknown>,
|
|
300
310
|
relayAfterMs: number,
|
|
301
311
|
signal: AbortSignal,
|
|
312
|
+
commit?: BridgeCallRequest['commit'],
|
|
302
313
|
): Promise<BridgeToolResult> {
|
|
303
|
-
return this.awaitCall(this.park(name, args), relayAfterMs, signal)
|
|
314
|
+
return this.awaitCall(this.park(name, args), relayAfterMs, signal, commit)
|
|
304
315
|
}
|
|
305
316
|
|
|
306
317
|
/** Resume waiting on a previously parked call via `pi_await_result`, or return undefined if unknown. */
|
|
@@ -308,11 +319,40 @@ export class AcpTurn {
|
|
|
308
319
|
callId: string,
|
|
309
320
|
relayAfterMs: number,
|
|
310
321
|
signal: AbortSignal,
|
|
322
|
+
commit?: BridgeCallRequest['commit'],
|
|
311
323
|
): Promise<BridgeToolResult> | undefined {
|
|
312
324
|
const call = this.calls.get(callId)
|
|
313
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
|
+
}
|
|
314
354
|
this.resumeRelay(callId)
|
|
315
|
-
return this.awaitCall(call, relayAfterMs, signal)
|
|
355
|
+
return this.awaitCall(call, relayAfterMs, signal, commit)
|
|
316
356
|
}
|
|
317
357
|
|
|
318
358
|
get isRelaying(): boolean {
|
|
@@ -400,7 +440,9 @@ export class AcpTurn {
|
|
|
400
440
|
call: ParkedCall,
|
|
401
441
|
relayAfterMs: number,
|
|
402
442
|
signal: AbortSignal,
|
|
443
|
+
commit?: BridgeCallRequest['commit'],
|
|
403
444
|
): Promise<BridgeToolResult> {
|
|
445
|
+
this.callDelivery.set(call.id, 'waiting')
|
|
404
446
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
405
447
|
const relay = new Promise<'relay'>((resolve) => {
|
|
406
448
|
timer = setTimeout(() => resolve('relay'), relayAfterMs)
|
|
@@ -415,18 +457,24 @@ export class AcpTurn {
|
|
|
415
457
|
})
|
|
416
458
|
try {
|
|
417
459
|
const outcome = await Promise.race([call.result.promise, relay, aborted])
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
}
|
|
422
|
-
if (outcome === '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') {
|
|
423
463
|
return {
|
|
424
464
|
content: [{ type: 'text', text: 'The tool call was cancelled.' }],
|
|
425
465
|
isError: true,
|
|
426
466
|
}
|
|
427
467
|
}
|
|
428
|
-
|
|
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)
|
|
429
475
|
} finally {
|
|
476
|
+
if (this.callDelivery.get(call.id) === 'waiting')
|
|
477
|
+
this.callDelivery.delete(call.id)
|
|
430
478
|
if (timer !== undefined) clearTimeout(timer)
|
|
431
479
|
if (onAbort !== undefined) signal.removeEventListener('abort', onAbort)
|
|
432
480
|
}
|
|
@@ -448,6 +496,7 @@ export class AcpTurn {
|
|
|
448
496
|
callId: string,
|
|
449
497
|
result: BridgeToolResult,
|
|
450
498
|
): BridgeToolResult {
|
|
499
|
+
this.callDelivery.set(callId, 'delivered')
|
|
451
500
|
this.relays.delete(callId)
|
|
452
501
|
this.releaseRelayWait()
|
|
453
502
|
const notes: string[] = []
|
|
@@ -905,6 +954,7 @@ async function* stepChunks(
|
|
|
905
954
|
const stop = event.result.stopReason
|
|
906
955
|
if (
|
|
907
956
|
stop === 'max_tokens' &&
|
|
957
|
+
!turn.isRelaying &&
|
|
908
958
|
turn.continuations < host.maxContinuations
|
|
909
959
|
) {
|
|
910
960
|
turn.continuations++
|
package/src/format.ts
CHANGED
|
@@ -33,16 +33,28 @@ 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
|
-
|
|
36
|
+
type EffortQualifier = Effort | 'extra-low'
|
|
37
|
+
|
|
38
|
+
// Keep longest qualifiers first (`extra[-_]low` before `low`) so compound suffixes match whole.
|
|
39
|
+
const EFFORT_QUALIFIER_PATTERN = [
|
|
40
|
+
'extra[-_]low',
|
|
41
|
+
...[...EFFORTS].sort((a, b) => b.length - a.length),
|
|
42
|
+
].join('|')
|
|
37
43
|
// Effort or thinking-mode suffixes in model IDs (`-thinking`) and `/usage` labels (`(Thinking)`).
|
|
38
44
|
const ID_QUALIFIER_SUFFIX = new RegExp(
|
|
39
|
-
`[-_](?:(${
|
|
45
|
+
`[-_](?:(${EFFORT_QUALIFIER_PATTERN})(?:[-_]effort)?|(thinking))$`,
|
|
40
46
|
'i',
|
|
41
47
|
)
|
|
42
48
|
const GROUP_QUALIFIER_SUFFIX = new RegExp(
|
|
43
|
-
`\\s*\\((${
|
|
49
|
+
`\\s*\\((${EFFORT_QUALIFIER_PATTERN}|thinking)\\)(?=\\s*(?:models?|groups?)?[\\s.!?)]*$)`,
|
|
44
50
|
'i',
|
|
45
51
|
)
|
|
52
|
+
|
|
53
|
+
function parseEffortQualifier(raw: string): EffortQualifier | undefined {
|
|
54
|
+
const normalized = raw.toLowerCase().replace(/_/g, '-')
|
|
55
|
+
if (normalized === 'extra-low') return 'extra-low'
|
|
56
|
+
return asEffort(normalized)
|
|
57
|
+
}
|
|
46
58
|
const SPECIFIER = /^\d+(?:\.\d+)*b?$/
|
|
47
59
|
const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
|
|
48
60
|
const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
|
|
@@ -75,7 +87,7 @@ interface ParsedPhrase {
|
|
|
75
87
|
readonly head: string | undefined
|
|
76
88
|
readonly words: readonly string[]
|
|
77
89
|
readonly specs: readonly string[]
|
|
78
|
-
readonly effort:
|
|
90
|
+
readonly effort: EffortQualifier | undefined
|
|
79
91
|
readonly thinking: boolean
|
|
80
92
|
readonly effortConflict: boolean
|
|
81
93
|
readonly tokenCount: number
|
|
@@ -84,7 +96,7 @@ interface ParsedPhrase {
|
|
|
84
96
|
|
|
85
97
|
function buildPhrase(
|
|
86
98
|
tokens: readonly string[],
|
|
87
|
-
effort?:
|
|
99
|
+
effort?: EffortQualifier,
|
|
88
100
|
thinking = false,
|
|
89
101
|
effortConflict = false,
|
|
90
102
|
): ParsedPhrase {
|
|
@@ -108,9 +120,21 @@ function buildPhrase(
|
|
|
108
120
|
|
|
109
121
|
function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
110
122
|
let text = raw.trim().replace(/[.!?]+$/, '')
|
|
111
|
-
let effort:
|
|
123
|
+
let effort: EffortQualifier | undefined
|
|
112
124
|
let thinking = false
|
|
113
125
|
let effortConflict = false
|
|
126
|
+
const applyQualifier = (rawQualifier: string) => {
|
|
127
|
+
const token = rawQualifier.toLowerCase()
|
|
128
|
+
if (token === 'thinking') {
|
|
129
|
+
thinking = true
|
|
130
|
+
return
|
|
131
|
+
}
|
|
132
|
+
const nextEffort = parseEffortQualifier(token)
|
|
133
|
+
if (nextEffort) {
|
|
134
|
+
if (effort && effort !== nextEffort) effortConflict = true
|
|
135
|
+
effort = nextEffort
|
|
136
|
+
}
|
|
137
|
+
}
|
|
114
138
|
while (text.length > 0) {
|
|
115
139
|
const withoutDate = text.replace(ID_DATE_SUFFIX, '')
|
|
116
140
|
if (withoutDate !== text) {
|
|
@@ -119,13 +143,7 @@ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
|
119
143
|
}
|
|
120
144
|
const groupQual = GROUP_QUALIFIER_SUFFIX.exec(text)
|
|
121
145
|
if (groupQual) {
|
|
122
|
-
|
|
123
|
-
if (nextEffort) {
|
|
124
|
-
if (effort && effort !== nextEffort) effortConflict = true
|
|
125
|
-
effort = nextEffort
|
|
126
|
-
} else {
|
|
127
|
-
thinking = true
|
|
128
|
-
}
|
|
146
|
+
applyQualifier(groupQual[1]!)
|
|
129
147
|
text =
|
|
130
148
|
text.slice(0, groupQual.index) +
|
|
131
149
|
text.slice(groupQual.index + groupQual[0].length)
|
|
@@ -133,13 +151,7 @@ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
|
133
151
|
}
|
|
134
152
|
const idQual = ID_QUALIFIER_SUFFIX.exec(text)
|
|
135
153
|
if (idQual) {
|
|
136
|
-
|
|
137
|
-
if (nextEffort) {
|
|
138
|
-
if (effort && effort !== nextEffort) effortConflict = true
|
|
139
|
-
effort = nextEffort
|
|
140
|
-
} else {
|
|
141
|
-
thinking = true
|
|
142
|
-
}
|
|
154
|
+
applyQualifier((idQual[1] ?? idQual[2])!)
|
|
143
155
|
text = text.slice(0, idQual.index)
|
|
144
156
|
continue
|
|
145
157
|
}
|
|
@@ -371,6 +383,38 @@ export function formatQuotaStatus(
|
|
|
371
383
|
return `AGY ${Math.round(displayFraction(quota.fraction, display) * 100)}%`
|
|
372
384
|
}
|
|
373
385
|
|
|
386
|
+
const WINDOW_DURATION = /^(\d+)([mhdw])$/
|
|
387
|
+
const WINDOW_UNIT_SECONDS: Record<string, number> = {
|
|
388
|
+
m: 60,
|
|
389
|
+
h: 3600,
|
|
390
|
+
d: 86400,
|
|
391
|
+
w: 7 * 86400,
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function windowSeconds(window: string): number | undefined {
|
|
395
|
+
const normalized = window.trim().toLowerCase()
|
|
396
|
+
if (normalized === 'weekly') return 7 * 86400
|
|
397
|
+
if (normalized === 'daily') return 86400
|
|
398
|
+
const match = WINDOW_DURATION.exec(normalized)
|
|
399
|
+
if (!match) return undefined
|
|
400
|
+
const count = Number(match[1])
|
|
401
|
+
const unit = WINDOW_UNIT_SECONDS[match[2]!]
|
|
402
|
+
return count > 0 && unit !== undefined ? count * unit : undefined
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function isUntouchedRollingReset(
|
|
406
|
+
bucket: QuotaBucket,
|
|
407
|
+
fraction: number | undefined,
|
|
408
|
+
now: number,
|
|
409
|
+
): boolean {
|
|
410
|
+
if (fraction === undefined || fraction < 1) return false
|
|
411
|
+
const resetMs = Date.parse(bucket.resetTime)
|
|
412
|
+
if (!Number.isFinite(resetMs)) return false
|
|
413
|
+
const windowSecs = windowSeconds(bucket.window)
|
|
414
|
+
if (windowSecs === undefined) return false
|
|
415
|
+
return Math.abs((resetMs - now) / 1000 - windowSecs) <= 60
|
|
416
|
+
}
|
|
417
|
+
|
|
374
418
|
function resetCountdown(resetTime: string, now: number): string {
|
|
375
419
|
const reset = Date.parse(resetTime)
|
|
376
420
|
if (!Number.isFinite(reset)) return 'reset time unavailable'
|
|
@@ -423,9 +467,10 @@ export function formatQuota(
|
|
|
423
467
|
bucket.id ||
|
|
424
468
|
'quota'
|
|
425
469
|
).padEnd(7)
|
|
426
|
-
const reset =
|
|
427
|
-
|
|
428
|
-
|
|
470
|
+
const reset =
|
|
471
|
+
bucket.resetTime && !isUntouchedRollingReset(bucket, fraction, now)
|
|
472
|
+
? ` · ${resetCountdown(bucket.resetTime, now)}`
|
|
473
|
+
: ''
|
|
429
474
|
lines.push(` ${label} [${bar}] ${percent.padStart(4)}${reset}`)
|
|
430
475
|
if (fraction !== undefined) {
|
|
431
476
|
if (fraction <= 0.05) level = 'error'
|