pi-agy-acp 0.2.7 → 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.
- package/CHANGELOG.md +7 -0
- package/docs/architecture.md +34 -21
- package/docs/development.md +3 -3
- package/index.ts +65 -45
- package/package.json +1 -1
- package/src/acp-process.ts +13 -27
- package/src/catalog.ts +59 -33
- package/src/config.ts +3 -5
- package/src/conversation.ts +172 -175
- package/src/format.ts +9 -355
- package/src/history.ts +59 -48
- package/src/host.ts +2 -2
- package/src/mcp-bridge.ts +53 -12
- package/src/pi-stream.ts +5 -8
- package/src/preflight.ts +1 -3
- package/src/protocol.ts +18 -3
- package/src/quota.ts +377 -41
- package/src/runtime.ts +270 -242
- package/src/session-db.ts +24 -5
- package/src/util.ts +5 -0
package/src/pi-stream.ts
CHANGED
|
@@ -17,11 +17,12 @@ import type {
|
|
|
17
17
|
import type {
|
|
18
18
|
ContentBlock,
|
|
19
19
|
GenerateOptions,
|
|
20
|
+
LlmErrorCode,
|
|
20
21
|
RequestMessage,
|
|
21
22
|
StreamChunk,
|
|
22
23
|
} from './protocol.ts'
|
|
23
24
|
import { LlmError } from './protocol.ts'
|
|
24
|
-
import { digest } from './util.ts'
|
|
25
|
+
import { digest, isRecord } from './util.ts'
|
|
25
26
|
|
|
26
27
|
export function requestMessages(messages: Message[]): RequestMessage[] {
|
|
27
28
|
let leadingSystem = true
|
|
@@ -83,7 +84,7 @@ export function requestMessages(messages: Message[]): RequestMessage[] {
|
|
|
83
84
|
|
|
84
85
|
function errorMessage(
|
|
85
86
|
message: string | undefined,
|
|
86
|
-
code?:
|
|
87
|
+
code?: LlmErrorCode,
|
|
87
88
|
): string | undefined {
|
|
88
89
|
if (
|
|
89
90
|
code === 'CONTEXT_WINDOW_EXCEEDED' &&
|
|
@@ -151,17 +152,13 @@ export function streamPi(
|
|
|
151
152
|
// the original tools; passing `tools: []` explicitly disables them.
|
|
152
153
|
const replacement = await options.onPayload?.(request, model)
|
|
153
154
|
if (replacement !== undefined) {
|
|
154
|
-
if (
|
|
155
|
-
replacement === null ||
|
|
156
|
-
typeof replacement !== 'object' ||
|
|
157
|
-
Array.isArray(replacement)
|
|
158
|
-
) {
|
|
155
|
+
if (!isRecord(replacement)) {
|
|
159
156
|
throw new LlmError(
|
|
160
157
|
'onPayload must return a payload object or undefined',
|
|
161
158
|
'INVALID_PAYLOAD',
|
|
162
159
|
)
|
|
163
160
|
}
|
|
164
|
-
const candidate = replacement
|
|
161
|
+
const candidate = replacement
|
|
165
162
|
if (
|
|
166
163
|
typeof candidate.model !== 'string' ||
|
|
167
164
|
candidate.model.trim().length === 0
|
package/src/preflight.ts
CHANGED
|
@@ -29,8 +29,6 @@ import { readJson } from './config.ts'
|
|
|
29
29
|
import { removeArtifacts } from './session-db.ts'
|
|
30
30
|
import { atomicWriteFile } from './util.ts'
|
|
31
31
|
|
|
32
|
-
export { atomicWriteFile }
|
|
33
|
-
|
|
34
32
|
/** Agent id installed in the isolated home. */
|
|
35
33
|
export const BRIDGE_AGENT = 'pi-bridge'
|
|
36
34
|
/** Minimum official CLI version supported (`agy 1.5.23+`). */
|
|
@@ -496,7 +494,7 @@ export function prepareHome(
|
|
|
496
494
|
syncOAuthToken(home, userHome, env)
|
|
497
495
|
} catch (error) {
|
|
498
496
|
onWarn?.(
|
|
499
|
-
`
|
|
497
|
+
`OAuth token sync skipped: ${error instanceof Error ? error.message : String(error)}`,
|
|
500
498
|
)
|
|
501
499
|
}
|
|
502
500
|
const settingsPath = join(appData, 'settings.json')
|
package/src/protocol.ts
CHANGED
|
@@ -33,6 +33,21 @@ export interface TokenUsage {
|
|
|
33
33
|
reasoningTokens?: number
|
|
34
34
|
totalTokens: number
|
|
35
35
|
}
|
|
36
|
+
export type LlmErrorCode =
|
|
37
|
+
| 'ABORTED'
|
|
38
|
+
| 'AUTH'
|
|
39
|
+
| 'CONTEXT_WINDOW_EXCEEDED'
|
|
40
|
+
| 'EMPTY_RESPONSE'
|
|
41
|
+
| 'INVALID_PAYLOAD'
|
|
42
|
+
| 'INVALID_REQUEST'
|
|
43
|
+
| 'PROVIDER_ERROR'
|
|
44
|
+
| 'QUOTA'
|
|
45
|
+
| 'RATE_LIMIT'
|
|
46
|
+
| 'REFUSAL'
|
|
47
|
+
| 'SERVER'
|
|
48
|
+
| 'TIMEOUT'
|
|
49
|
+
| 'TRANSPORT'
|
|
50
|
+
| 'UNKNOWN_MODEL'
|
|
36
51
|
export type StreamChunk =
|
|
37
52
|
| {
|
|
38
53
|
type: 'block-start'
|
|
@@ -53,12 +68,12 @@ export type StreamChunk =
|
|
|
53
68
|
type: 'finish'
|
|
54
69
|
reason: {
|
|
55
70
|
kind: 'stop' | 'tool-calls' | 'max-tokens' | 'aborted' | 'error'
|
|
56
|
-
failure?: { message: string; code:
|
|
71
|
+
failure?: { message: string; code: LlmErrorCode }
|
|
57
72
|
}
|
|
58
73
|
}
|
|
59
74
|
export class LlmError extends Error {
|
|
60
|
-
readonly code:
|
|
61
|
-
constructor(message: string, code:
|
|
75
|
+
readonly code: LlmErrorCode
|
|
76
|
+
constructor(message: string, code: LlmErrorCode, options?: ErrorOptions) {
|
|
62
77
|
super(message, options)
|
|
63
78
|
this.code = code
|
|
64
79
|
}
|
package/src/quota.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Plan quota read through the official CLI's local `agy usage` command,
|
|
3
|
-
*
|
|
2
|
+
* Plan quota read through the official CLI's local `agy usage` command, login-log
|
|
3
|
+
* email lookup, and model-to-group quota matching without starting a
|
|
4
4
|
* conversation or sending a model request.
|
|
5
5
|
* @module pi-agy-acp/quota
|
|
6
6
|
*/
|
|
@@ -15,7 +15,9 @@ import {
|
|
|
15
15
|
statSync,
|
|
16
16
|
} from 'node:fs'
|
|
17
17
|
import { isAbsolute, join, relative } from 'node:path'
|
|
18
|
+
import { asEffort, EFFORTS, type Effort } from './config.ts'
|
|
18
19
|
import type { CommandRunner } from './preflight.ts'
|
|
20
|
+
import { isRecord } from './util.ts'
|
|
19
21
|
|
|
20
22
|
/** Best-effort identity from local logs and ACP subscription metadata. */
|
|
21
23
|
export interface AccountInfo {
|
|
@@ -195,23 +197,21 @@ export interface QuotaSnapshot {
|
|
|
195
197
|
}
|
|
196
198
|
|
|
197
199
|
function parseBucket(raw: unknown): QuotaBucket | undefined {
|
|
198
|
-
if (
|
|
199
|
-
|
|
200
|
-
const
|
|
201
|
-
|
|
202
|
-
const id = String(bucket.id ?? '').trim()
|
|
203
|
-
const window = String(bucket.window ?? '').trim()
|
|
200
|
+
if (!isRecord(raw)) return undefined
|
|
201
|
+
if (raw.disabled === true) return undefined
|
|
202
|
+
const id = String(raw.id ?? '').trim()
|
|
203
|
+
const window = String(raw.window ?? '').trim()
|
|
204
204
|
if (id.length === 0 || window.length === 0) return undefined
|
|
205
205
|
return {
|
|
206
206
|
id,
|
|
207
|
-
name: String(
|
|
207
|
+
name: String(raw.name ?? ''),
|
|
208
208
|
window,
|
|
209
209
|
remainingFraction:
|
|
210
|
-
typeof
|
|
211
|
-
Number.isFinite(
|
|
212
|
-
?
|
|
210
|
+
typeof raw.remaining_fraction === 'number' &&
|
|
211
|
+
Number.isFinite(raw.remaining_fraction)
|
|
212
|
+
? raw.remaining_fraction
|
|
213
213
|
: undefined,
|
|
214
|
-
resetTime: String(
|
|
214
|
+
resetTime: String(raw.reset_time ?? ''),
|
|
215
215
|
}
|
|
216
216
|
}
|
|
217
217
|
|
|
@@ -222,39 +222,375 @@ function parseBucket(raw: unknown): QuotaBucket | undefined {
|
|
|
222
222
|
*/
|
|
223
223
|
export function parseUsage(stdout: string): QuotaGroup[] {
|
|
224
224
|
const parsed: unknown = JSON.parse(stdout)
|
|
225
|
-
const command =
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
: undefined
|
|
229
|
-
const data =
|
|
230
|
-
command !== null && typeof command === 'object' && !Array.isArray(command)
|
|
231
|
-
? (command as { data?: unknown }).data
|
|
232
|
-
: undefined
|
|
233
|
-
const groups =
|
|
234
|
-
data !== null && typeof data === 'object' && !Array.isArray(data)
|
|
235
|
-
? (data as { groups?: unknown }).groups
|
|
236
|
-
: undefined
|
|
225
|
+
const command = isRecord(parsed) ? parsed.command : undefined
|
|
226
|
+
const data = isRecord(command) ? command.data : undefined
|
|
227
|
+
const groups = isRecord(data) ? data.groups : undefined
|
|
237
228
|
if (!Array.isArray(groups))
|
|
238
229
|
throw new Error('agy usage returned no quota groups')
|
|
239
|
-
return groups
|
|
240
|
-
.
|
|
241
|
-
|
|
242
|
-
|
|
230
|
+
return groups.filter(isRecord).map((group) => ({
|
|
231
|
+
name: String(group.name ?? ''),
|
|
232
|
+
description: String(group.description ?? ''),
|
|
233
|
+
buckets: (Array.isArray(group.buckets) ? group.buckets : [])
|
|
234
|
+
.map(parseBucket)
|
|
235
|
+
.filter((bucket): bucket is QuotaBucket => bucket !== undefined),
|
|
236
|
+
}))
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Clamp a finite fraction to `0..1`, returning `undefined` otherwise. */
|
|
240
|
+
export function clampFraction(value: number | undefined): number | undefined {
|
|
241
|
+
return typeof value === 'number' && Number.isFinite(value)
|
|
242
|
+
? Math.max(0, Math.min(1, value))
|
|
243
|
+
: undefined
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Active model identity from Pi (`id` plus optional display `name` for `agy usage` labels such as `Orchestrator (Carbon)`). */
|
|
247
|
+
export interface QuotaModelRef {
|
|
248
|
+
readonly id: string
|
|
249
|
+
readonly name?: string
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// `agy usage` prefixes closed, exhaustive member lists with "Models within this group:";
|
|
253
|
+
// unprefixed descriptions are free-form prose notes.
|
|
254
|
+
export const EXPLICIT_MEMBERS_PREFIX = /^\s*models within this group:\s*/i
|
|
255
|
+
const CLAUSE_SPLIT = /[,;\n/|&+]+|\b(?:and|or)\b/i
|
|
256
|
+
const ID_DATE_SUFFIX = /[-_](?:20\d{2}[-_]\d{2}[-_]\d{2}|20\d{6})$/i
|
|
257
|
+
type EffortQualifier = Effort | 'extra-low'
|
|
258
|
+
|
|
259
|
+
// Keep longest qualifiers first (`extra[-_]low` before `low`) so compound suffixes match whole.
|
|
260
|
+
const EFFORT_QUALIFIER_PATTERN = [
|
|
261
|
+
'extra[-_]low',
|
|
262
|
+
...[...EFFORTS].sort((a, b) => b.length - a.length),
|
|
263
|
+
].join('|')
|
|
264
|
+
// Effort or thinking-mode suffixes in model IDs (`-thinking`) and `agy usage` labels (`(Thinking)`).
|
|
265
|
+
const ID_QUALIFIER_SUFFIX = new RegExp(
|
|
266
|
+
`[-_](?:(${EFFORT_QUALIFIER_PATTERN})(?:[-_]effort)?|(thinking))$`,
|
|
267
|
+
'i',
|
|
268
|
+
)
|
|
269
|
+
const GROUP_QUALIFIER_SUFFIX = new RegExp(
|
|
270
|
+
`\\s*\\((${EFFORT_QUALIFIER_PATTERN}|thinking)\\)(?=\\s*(?:models?|groups?)?[\\s.!?)]*$)`,
|
|
271
|
+
'i',
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
function parseEffortQualifier(raw: string): EffortQualifier | undefined {
|
|
275
|
+
const normalized = raw.toLowerCase().replace(/_/g, '-')
|
|
276
|
+
if (normalized === 'extra-low') return 'extra-low'
|
|
277
|
+
return asEffort(normalized)
|
|
278
|
+
}
|
|
279
|
+
const SPECIFIER = /^\d+(?:\.\d+)*b?$/
|
|
280
|
+
const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
|
|
281
|
+
const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
|
|
282
|
+
const GROUP_NOISE_TOKENS = new Set(['model', 'models', 'group', 'groups'])
|
|
283
|
+
const GENERIC_GROUP_TOKENS = new Set([
|
|
284
|
+
...VENDOR_TOKENS,
|
|
285
|
+
...FAMILY_TOKENS,
|
|
286
|
+
...GROUP_NOISE_TOKENS,
|
|
287
|
+
'all',
|
|
288
|
+
'other',
|
|
289
|
+
'default',
|
|
290
|
+
'general',
|
|
291
|
+
])
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Tokenize into lowercase words, dotted versions, and `<n>b` parameter sizes.
|
|
295
|
+
* Hyphens between digits become dots only for 1-2 digit version segments (`5-5` -> `5.5`),
|
|
296
|
+
* preserving parameter sizes (`3-8b`, `120b`) and dates stripped beforehand.
|
|
297
|
+
*/
|
|
298
|
+
function normalizeTokens(text: string): string[] {
|
|
299
|
+
return (
|
|
300
|
+
text
|
|
301
|
+
.toLowerCase()
|
|
302
|
+
.replace(/(?<=\d)-(?=\d{1,2}(?![a-z0-9.]))/g, '.')
|
|
303
|
+
.match(/[a-z0-9]+(?:\.[0-9]+)*(?:b(?![a-z0-9]))?/g) ?? []
|
|
304
|
+
)
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
interface ParsedPhrase {
|
|
308
|
+
readonly head: string | undefined
|
|
309
|
+
readonly words: readonly string[]
|
|
310
|
+
readonly specs: readonly string[]
|
|
311
|
+
readonly effort: EffortQualifier | undefined
|
|
312
|
+
readonly thinking: boolean
|
|
313
|
+
readonly effortConflict: boolean
|
|
314
|
+
readonly tokenCount: number
|
|
315
|
+
readonly canonical: string
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function buildPhrase(
|
|
319
|
+
tokens: readonly string[],
|
|
320
|
+
effort?: EffortQualifier,
|
|
321
|
+
thinking = false,
|
|
322
|
+
effortConflict = false,
|
|
323
|
+
): ParsedPhrase {
|
|
324
|
+
const words: string[] = []
|
|
325
|
+
const specs: string[] = []
|
|
326
|
+
for (const token of tokens) {
|
|
327
|
+
if (SPECIFIER.test(token)) specs.push(token)
|
|
328
|
+
else words.push(token)
|
|
329
|
+
}
|
|
330
|
+
return {
|
|
331
|
+
head: tokens[0],
|
|
332
|
+
words,
|
|
333
|
+
specs,
|
|
334
|
+
effort,
|
|
335
|
+
thinking,
|
|
336
|
+
effortConflict,
|
|
337
|
+
tokenCount: tokens.length,
|
|
338
|
+
canonical: `${words.join(' ')}|${specs.join(' ')}`,
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function parseClause(raw: string, stripNoise = false): ParsedPhrase {
|
|
343
|
+
let text = raw.trim().replace(/[.!?]+$/, '')
|
|
344
|
+
let effort: EffortQualifier | undefined
|
|
345
|
+
let thinking = false
|
|
346
|
+
let effortConflict = false
|
|
347
|
+
const applyQualifier = (rawQualifier: string) => {
|
|
348
|
+
const token = rawQualifier.toLowerCase()
|
|
349
|
+
if (token === 'thinking') {
|
|
350
|
+
thinking = true
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
const nextEffort = parseEffortQualifier(token)
|
|
354
|
+
if (nextEffort) {
|
|
355
|
+
if (effort && effort !== nextEffort) effortConflict = true
|
|
356
|
+
effort = nextEffort
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
while (text.length > 0) {
|
|
360
|
+
const withoutDate = text.replace(ID_DATE_SUFFIX, '')
|
|
361
|
+
if (withoutDate !== text) {
|
|
362
|
+
text = withoutDate
|
|
363
|
+
continue
|
|
364
|
+
}
|
|
365
|
+
const groupQual = GROUP_QUALIFIER_SUFFIX.exec(text)
|
|
366
|
+
if (groupQual) {
|
|
367
|
+
applyQualifier(groupQual[1]!)
|
|
368
|
+
text =
|
|
369
|
+
text.slice(0, groupQual.index) +
|
|
370
|
+
text.slice(groupQual.index + groupQual[0].length)
|
|
371
|
+
continue
|
|
372
|
+
}
|
|
373
|
+
const idQual = ID_QUALIFIER_SUFFIX.exec(text)
|
|
374
|
+
if (idQual) {
|
|
375
|
+
applyQualifier((idQual[1] ?? idQual[2])!)
|
|
376
|
+
text = text.slice(0, idQual.index)
|
|
377
|
+
continue
|
|
378
|
+
}
|
|
379
|
+
break
|
|
380
|
+
}
|
|
381
|
+
const baseTokens = normalizeTokens(text)
|
|
382
|
+
const fallback = baseTokens.length === 0
|
|
383
|
+
const tokens = [...(fallback ? normalizeTokens(raw) : baseTokens)]
|
|
384
|
+
while (tokens.length >= 2 && VENDOR_TOKENS.has(tokens[0]!)) tokens.shift()
|
|
385
|
+
const cleaned = stripNoise
|
|
386
|
+
? (() => {
|
|
387
|
+
const stripped = tokens.filter((t) => !GROUP_NOISE_TOKENS.has(t))
|
|
388
|
+
return stripped.length >= 2 ? stripped : tokens
|
|
389
|
+
})()
|
|
390
|
+
: tokens
|
|
391
|
+
return buildPhrase(
|
|
392
|
+
cleaned,
|
|
393
|
+
fallback ? undefined : effort,
|
|
394
|
+
fallback ? false : thinking,
|
|
395
|
+
!fallback && effortConflict,
|
|
396
|
+
)
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
function parseGroupPhrases(
|
|
400
|
+
text: string,
|
|
401
|
+
excludeGeneric: boolean,
|
|
402
|
+
): ParsedPhrase[] {
|
|
403
|
+
const phrases: ParsedPhrase[] = []
|
|
404
|
+
for (const part of text.split(CLAUSE_SPLIT)) {
|
|
405
|
+
if (
|
|
406
|
+
excludeGeneric &&
|
|
407
|
+
normalizeTokens(part).every((token) => GENERIC_GROUP_TOKENS.has(token))
|
|
408
|
+
)
|
|
409
|
+
continue
|
|
410
|
+
const phrase = parseClause(part, true)
|
|
411
|
+
if (phrase.tokenCount > 0 && !phrase.effortConflict) phrases.push(phrase)
|
|
412
|
+
}
|
|
413
|
+
return phrases
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function buildModelCandidates(id: string, name?: string): ParsedPhrase[] {
|
|
417
|
+
const idPhrase = parseClause(id)
|
|
418
|
+
const namePhrase = name ? parseClause(name) : undefined
|
|
419
|
+
if (
|
|
420
|
+
idPhrase.effortConflict ||
|
|
421
|
+
namePhrase?.effortConflict ||
|
|
422
|
+
(idPhrase.effort &&
|
|
423
|
+
namePhrase?.effort &&
|
|
424
|
+
idPhrase.effort !== namePhrase.effort)
|
|
425
|
+
)
|
|
426
|
+
return []
|
|
427
|
+
const effort = idPhrase.effort ?? namePhrase?.effort
|
|
428
|
+
const thinking = idPhrase.thinking || Boolean(namePhrase?.thinking)
|
|
429
|
+
const seen = new Set<string>()
|
|
430
|
+
const out: ParsedPhrase[] = []
|
|
431
|
+
for (const candidate of [idPhrase, namePhrase]) {
|
|
432
|
+
if (!candidate || candidate.tokenCount === 0) continue
|
|
433
|
+
const phrase = { ...candidate, effort, thinking }
|
|
434
|
+
const key = `${phrase.canonical}#${phrase.effort ?? ''}#${phrase.thinking ? 't' : ''}`
|
|
435
|
+
if (!seen.has(key)) {
|
|
436
|
+
seen.add(key)
|
|
437
|
+
out.push(phrase)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
return out
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const isExactPhrase = (groupPhrase: ParsedPhrase, modelPhrase: ParsedPhrase) =>
|
|
444
|
+
groupPhrase.canonical === modelPhrase.canonical
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* True for a subfamily without version/size (`GPT-OSS`, `Gemini Flash`) or a
|
|
448
|
+
* single-version generation line (`Gemini 4`, `Gemini 3.8`) matching the model.
|
|
449
|
+
*/
|
|
450
|
+
function isBroaderVariant(
|
|
451
|
+
groupPhrase: ParsedPhrase,
|
|
452
|
+
modelPhrase: ParsedPhrase,
|
|
453
|
+
): boolean {
|
|
454
|
+
if (
|
|
455
|
+
groupPhrase.tokenCount < 2 ||
|
|
456
|
+
!groupPhrase.head ||
|
|
457
|
+
groupPhrase.head !== modelPhrase.head
|
|
458
|
+
)
|
|
459
|
+
return false
|
|
460
|
+
if (groupPhrase.words.length >= 2 && groupPhrase.specs.length === 0)
|
|
461
|
+
return groupPhrase.words.join(' ') === modelPhrase.words.join(' ')
|
|
462
|
+
const modelVersions = modelPhrase.specs.filter((s) => !s.endsWith('b'))
|
|
463
|
+
return (
|
|
464
|
+
groupPhrase.words.length === 1 &&
|
|
465
|
+
groupPhrase.specs.length === 1 &&
|
|
466
|
+
!groupPhrase.specs[0]!.endsWith('b') &&
|
|
467
|
+
modelVersions.length === 1 &&
|
|
468
|
+
modelVersions[0] === groupPhrase.specs[0]
|
|
469
|
+
)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function extractFamily(text?: string): string | undefined {
|
|
473
|
+
const head = text
|
|
474
|
+
? normalizeTokens(text).find((token) => !VENDOR_TOKENS.has(token))
|
|
475
|
+
: undefined
|
|
476
|
+
return head && FAMILY_TOKENS.has(head) ? head : undefined
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function isGenericFamilyGroup(group: QuotaGroup, family: string): boolean {
|
|
480
|
+
if (EXPLICIT_MEMBERS_PREFIX.test(group.description)) return false
|
|
481
|
+
return group.name.split(CLAUSE_SPLIT).some((clause) => {
|
|
482
|
+
const tokens = normalizeTokens(clause)
|
|
483
|
+
return (
|
|
484
|
+
tokens.includes(family) &&
|
|
485
|
+
tokens.every((token) => GENERIC_GROUP_TOKENS.has(token))
|
|
243
486
|
)
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
487
|
+
})
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
const matchGroup = (
|
|
491
|
+
phrases: readonly ParsedPhrase[],
|
|
492
|
+
candidates: readonly ParsedPhrase[],
|
|
493
|
+
relation: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
|
|
494
|
+
qualOk: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
|
|
495
|
+
) => phrases.some((p) => candidates.some((c) => qualOk(p, c) && relation(p, c)))
|
|
496
|
+
|
|
497
|
+
function selectQuotaGroups(
|
|
498
|
+
snapshot: QuotaSnapshot,
|
|
499
|
+
model?: QuotaModelRef,
|
|
500
|
+
): QuotaGroup[] {
|
|
501
|
+
if (!model) return []
|
|
502
|
+
const candidates = buildModelCandidates(model.id, model.name)
|
|
503
|
+
if (candidates.length === 0) return []
|
|
504
|
+
|
|
505
|
+
const indexed = snapshot.groups.map((group) => {
|
|
506
|
+
const explicit = EXPLICIT_MEMBERS_PREFIX.test(group.description)
|
|
507
|
+
const raw = explicit
|
|
508
|
+
? group.description.replace(EXPLICIT_MEMBERS_PREFIX, '')
|
|
509
|
+
: group.name
|
|
510
|
+
return { group, explicit, phrases: parseGroupPhrases(raw, !explicit) }
|
|
511
|
+
})
|
|
512
|
+
|
|
513
|
+
// Without an effort qualifier (`low`/`medium`/`high`) on the model reference, any matching
|
|
514
|
+
// effort-capped pool makes group ownership depend on unknown active effort; return unknown.
|
|
515
|
+
const omittedEffort = (g: ParsedPhrase, m: ParsedPhrase) =>
|
|
516
|
+
g.effort !== undefined && m.effort === undefined
|
|
517
|
+
if (
|
|
518
|
+
indexed.some(
|
|
519
|
+
(entry) =>
|
|
520
|
+
matchGroup(entry.phrases, candidates, isExactPhrase, omittedEffort) ||
|
|
521
|
+
matchGroup(entry.phrases, candidates, isBroaderVariant, omittedEffort),
|
|
522
|
+
)
|
|
523
|
+
)
|
|
524
|
+
return []
|
|
525
|
+
|
|
526
|
+
const compatQual = (g: ParsedPhrase, m: ParsedPhrase) =>
|
|
527
|
+
(g.effort === undefined || g.effort === m.effort) &&
|
|
528
|
+
(!g.thinking || m.thinking || m.effort !== undefined)
|
|
529
|
+
|
|
530
|
+
const authoritative: (typeof indexed)[number][] = []
|
|
531
|
+
const variantOnly: (typeof indexed)[number][] = []
|
|
532
|
+
for (const entry of indexed) {
|
|
533
|
+
const exact = matchGroup(entry.phrases, candidates, isExactPhrase, compatQual)
|
|
534
|
+
const variant = matchGroup(
|
|
535
|
+
entry.phrases,
|
|
536
|
+
candidates,
|
|
537
|
+
isBroaderVariant,
|
|
538
|
+
compatQual,
|
|
539
|
+
)
|
|
540
|
+
if (exact || (entry.explicit && variant)) authoritative.push(entry)
|
|
541
|
+
else if (variant) variantOnly.push(entry)
|
|
542
|
+
}
|
|
543
|
+
if (authoritative.length > 0) {
|
|
544
|
+
return [
|
|
545
|
+
...authoritative,
|
|
546
|
+
...(variantOnly.length === 1 ? variantOnly : []),
|
|
547
|
+
].map((e) => e.group)
|
|
548
|
+
}
|
|
549
|
+
if (variantOnly.length === 1) return [variantOnly[0]!.group]
|
|
550
|
+
if (variantOnly.length > 1) return []
|
|
551
|
+
|
|
552
|
+
const thinkingQual = (g: ParsedPhrase, m: ParsedPhrase) =>
|
|
553
|
+
g.thinking && !m.thinking && g.effort === undefined && m.effort === undefined
|
|
554
|
+
const thinkingMatches = indexed.filter(
|
|
555
|
+
(entry) =>
|
|
556
|
+
matchGroup(entry.phrases, candidates, isExactPhrase, thinkingQual) ||
|
|
557
|
+
matchGroup(entry.phrases, candidates, isBroaderVariant, thinkingQual),
|
|
558
|
+
)
|
|
559
|
+
if (thinkingMatches.length === 1) return [thinkingMatches[0]!.group]
|
|
560
|
+
if (thinkingMatches.length > 1) return []
|
|
561
|
+
|
|
562
|
+
const family = extractFamily(model.id) ?? extractFamily(model.name)
|
|
563
|
+
if (!family) return []
|
|
564
|
+
const generic = indexed.filter(
|
|
565
|
+
(entry) => !entry.explicit && isGenericFamilyGroup(entry.group, family),
|
|
566
|
+
)
|
|
567
|
+
return generic.length === 1 ? [generic[0]!.group] : []
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** Lowest known window across the model's governing quota group(s); returns undefined when unknown or ambiguous. */
|
|
571
|
+
export function quotaForModel(
|
|
572
|
+
snapshot: QuotaSnapshot,
|
|
573
|
+
model?: QuotaModelRef,
|
|
574
|
+
): { group: QuotaGroup; bucket: QuotaBucket; fraction: number } | undefined {
|
|
575
|
+
if (snapshot.status !== 'ok') return undefined
|
|
576
|
+
const groups = selectQuotaGroups(snapshot, model)
|
|
577
|
+
let lowest: ReturnType<typeof quotaForModel>
|
|
578
|
+
for (const group of groups) {
|
|
579
|
+
for (const bucket of group.buckets) {
|
|
580
|
+
const fraction = clampFraction(bucket.remainingFraction)
|
|
581
|
+
if (fraction === undefined) continue
|
|
582
|
+
if (!lowest || fraction < lowest.fraction)
|
|
583
|
+
lowest = { group, bucket, fraction }
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return lowest
|
|
251
587
|
}
|
|
252
588
|
|
|
253
589
|
/** Cached quota reader with request coalescing. */
|
|
254
590
|
export class QuotaReader {
|
|
255
591
|
private cached: QuotaSnapshot | undefined
|
|
256
592
|
// Monotonic `performance.now()` starts near 0, so `-Infinity` guarantees an empty cache is never fresh.
|
|
257
|
-
private
|
|
593
|
+
private cachedAtMs = -Infinity
|
|
258
594
|
private inflight: Promise<QuotaSnapshot> | undefined
|
|
259
595
|
private readonly binary: () => string
|
|
260
596
|
private readonly run: CommandRunner
|
|
@@ -282,7 +618,7 @@ export class QuotaReader {
|
|
|
282
618
|
/** Fresh successful data only; never starts a command. */
|
|
283
619
|
peek(): QuotaSnapshot | undefined {
|
|
284
620
|
return this.cached?.status === 'ok' &&
|
|
285
|
-
this.now() - this.
|
|
621
|
+
this.now() - this.cachedAtMs < this.ttlMs
|
|
286
622
|
? this.cached
|
|
287
623
|
: undefined
|
|
288
624
|
}
|
|
@@ -296,7 +632,7 @@ export class QuotaReader {
|
|
|
296
632
|
if (
|
|
297
633
|
!force &&
|
|
298
634
|
this.cached !== undefined &&
|
|
299
|
-
this.now() - this.
|
|
635
|
+
this.now() - this.cachedAtMs < this.ttlMs
|
|
300
636
|
)
|
|
301
637
|
return this.cached
|
|
302
638
|
this.inflight ??= this.fetch().finally(() => {
|
|
@@ -339,7 +675,7 @@ export class QuotaReader {
|
|
|
339
675
|
groups: parseUsage(result.stdout),
|
|
340
676
|
}
|
|
341
677
|
this.cached = snapshot
|
|
342
|
-
this.
|
|
678
|
+
this.cachedAtMs = this.now()
|
|
343
679
|
return snapshot
|
|
344
680
|
} catch (error) {
|
|
345
681
|
const snapshot: QuotaSnapshot = {
|
|
@@ -350,7 +686,7 @@ export class QuotaReader {
|
|
|
350
686
|
}
|
|
351
687
|
// Apply the same TTL to failures so settled events cannot hammer an unavailable CLI.
|
|
352
688
|
this.cached = snapshot
|
|
353
|
-
this.
|
|
689
|
+
this.cachedAtMs = this.now()
|
|
354
690
|
return snapshot
|
|
355
691
|
}
|
|
356
692
|
}
|