pi-agy-acp 0.1.3 → 0.1.4

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.
@@ -20,7 +20,11 @@ import type {
20
20
  AcpToolCallMeta,
21
21
  } from './acp-process.ts'
22
22
  import type { BridgeTool, BridgeToolResult } from './mcp-bridge.ts'
23
- import { AGENT_TOOL_PREFIX, CALL_TOOL_NAME } from './history.ts'
23
+ import {
24
+ AGENT_TOOL_PREFIX,
25
+ CALL_TOOL_NAME,
26
+ MCP_SERVER_NAME,
27
+ } from './history.ts'
24
28
  import { AsyncQueue, deferred, type Deferred } from './util.ts'
25
29
 
26
30
  /** Agent-side transport retry notice streamed as message text, e.g. `⚠ API error (attempt 1): …`. */
@@ -150,6 +154,8 @@ export class AcpTurn {
150
154
  readonly calls = new Map<string, ParkedCall>()
151
155
  /** Pi steps this turn has ended with `tool-calls`. */
152
156
  toolSteps = 0
157
+ /** Tool steps completed inside the active `session/prompt` segment. */
158
+ segmentToolSteps = 0
153
159
  /** Long-decode continuations sent in this turn. */
154
160
  continuations = 0
155
161
  /** The agent ended the prompt. */
@@ -157,6 +163,8 @@ export class AcpTurn {
157
163
  /** Settles after the current prompt's result or error has been queued. */
158
164
  promptSettled: Promise<void> = Promise.resolve()
159
165
  usage?: AcpPromptResult['usage']
166
+ /** Latest positive single-call context occupancy reported via `usage_update.used`. */
167
+ contextUsed?: number
160
168
  /** Relayed call ids whose results the agent has not yet re-awaited via `pi_await_result`. */
161
169
  readonly relayedCalls = new Set<string>()
162
170
  /** Bounded output buffered while one or more calls are relayed. */
@@ -249,6 +257,15 @@ export class AcpTurn {
249
257
  * @param update - the agent notification.
250
258
  */
251
259
  onUpdate(update: AcpSessionUpdate): void {
260
+ if (
261
+ update.sessionUpdate === 'usage_update' &&
262
+ typeof update.used === 'number' &&
263
+ Number.isFinite(update.used) &&
264
+ update.used > 0
265
+ ) {
266
+ this.contextUsed = update.used
267
+ return
268
+ }
252
269
  const text =
253
270
  update.content?.type === 'text' ? (update.content.text ?? '') : ''
254
271
  if (update.sessionUpdate === 'agent_message_chunk' && text.length > 0) {
@@ -355,39 +372,90 @@ export interface PumpHost {
355
372
  cancel(): void
356
373
  }
357
374
 
375
+ /** Optional single-call context occupancy inputs for {@link toTokenUsage}. */
376
+ export interface TokenUsageOptions {
377
+ /** Latest single-call context occupancy reported via `usage_update.used`. */
378
+ contextTokens?: number
379
+ /** Final `session/prompt` segment's usage when the turn spanned `max_tokens` continuations. */
380
+ lastSegmentUsage?: AcpPromptResult['usage']
381
+ }
382
+
383
+ function accumulateRawUsage(
384
+ prior: AcpPromptResult['usage'],
385
+ next: AcpPromptResult['usage'],
386
+ ): AcpPromptResult['usage'] {
387
+ if (prior === undefined) return next
388
+ if (next === undefined) return prior
389
+ const add = (a?: number, b?: number): number | undefined =>
390
+ a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0)
391
+ return {
392
+ inputTokens: add(prior.inputTokens, next.inputTokens),
393
+ outputTokens: add(prior.outputTokens, next.outputTokens),
394
+ cachedReadTokens: add(prior.cachedReadTokens, next.cachedReadTokens),
395
+ cachedWriteTokens: add(prior.cachedWriteTokens, next.cachedWriteTokens),
396
+ thoughtTokens: add(prior.thoughtTokens, next.thoughtTokens),
397
+ totalTokens: add(prior.totalTokens, next.totalTokens),
398
+ }
399
+ }
400
+
358
401
  /**
359
- * Map one completed prompt or step sample to Pi token usage. When a single
360
- * sample spanned `calls` internal model steps (tool rounds or continuations),
361
- * prompt buckets are normalized by `calls` so Pi's native ContextMeter reflects
362
- * single-request context occupancy rather than the multi-step sum.
402
+ * Map accumulated ACP turn usage into Pi token usage.
403
+ *
404
+ * Consumption buckets (`inputTokens`, `outputTokens`, `cacheReadTokens`,
405
+ * `cacheWriteTokens`, `reasoningTokens`) stay unscaled cumulative turn totals
406
+ * because intermediate `toolUse` steps emit zero usage and Pi sums those
407
+ * buckets across steps for session accounting and flat pricing overrides.
408
+ *
409
+ * `totalTokens` feeds Pi's `calculateContextTokens` / ContextMeter / compaction
410
+ * threshold as final-call context occupancy: when `options.contextTokens`
411
+ * (from live `usage_update.used`) is positive, it is used directly; otherwise
412
+ * final-segment prompt buckets are normalized by `calls` and added to final-
413
+ * segment output tokens.
363
414
  *
364
415
  * `agy acp` reports `inputTokens` as uncached input only, disjoint from
365
- * `cachedReadTokens` and `cachedWriteTokens`, so every bucket is kept as
366
- * reported and the total is their sum.
367
- * @param usage - the agent's step or turn usage.
368
- * @param calls - model calls executed inside this sample (>= 1).
416
+ * `cachedReadTokens` and `cachedWriteTokens`.
417
+ * @param usage - accumulated turn usage.
418
+ * @param calls - model calls inside the final `session/prompt` segment (>= 1).
419
+ * @param options - optional live `usage_update` count and final segment usage.
369
420
  * @returns Pi usage.
370
421
  */
371
422
  export function toTokenUsage(
372
423
  usage: AcpPromptResult['usage'],
373
424
  calls = 1,
425
+ options?: TokenUsageOptions,
374
426
  ): TokenUsage | undefined {
375
427
  if (usage === undefined) return undefined
376
- const scale = Math.max(1, calls)
377
- const input = Math.max(0, Math.round((usage.inputTokens ?? 0) / scale))
378
- const cacheRead = Math.max(
379
- 0,
380
- Math.round((usage.cachedReadTokens ?? 0) / scale),
381
- )
382
- const cacheWrite = Math.max(
383
- 0,
384
- Math.round((usage.cachedWriteTokens ?? 0) / scale),
385
- )
386
- const output = Math.max(0, usage.outputTokens ?? 0)
428
+ const input = Math.max(0, Math.round(usage.inputTokens ?? 0))
429
+ const cacheRead = Math.max(0, Math.round(usage.cachedReadTokens ?? 0))
430
+ const cacheWrite = Math.max(0, Math.round(usage.cachedWriteTokens ?? 0))
431
+ const output = Math.max(0, Math.round(usage.outputTokens ?? 0))
387
432
  const reasoning =
388
433
  usage.thoughtTokens !== undefined && usage.thoughtTokens > 0
389
- ? Math.min(output, usage.thoughtTokens)
434
+ ? Math.min(output, Math.round(usage.thoughtTokens))
390
435
  : undefined
436
+ const liveContext = options?.contextTokens
437
+ let totalTokens: number
438
+ if (
439
+ typeof liveContext === 'number' &&
440
+ Number.isFinite(liveContext) &&
441
+ liveContext > 0
442
+ ) {
443
+ totalTokens = Math.round(liveContext)
444
+ } else {
445
+ const seg = options?.lastSegmentUsage ?? usage
446
+ const scale = Math.max(1, calls)
447
+ const segPrompt = Math.max(
448
+ 0,
449
+ Math.round(
450
+ ((seg.inputTokens ?? 0) +
451
+ (seg.cachedReadTokens ?? 0) +
452
+ (seg.cachedWriteTokens ?? 0)) /
453
+ scale,
454
+ ),
455
+ )
456
+ const segOutput = Math.max(0, Math.round(seg.outputTokens ?? 0))
457
+ totalTokens = segPrompt + segOutput
458
+ }
391
459
  return {
392
460
  inputTokens: input,
393
461
  outputTokens: output,
@@ -398,7 +466,7 @@ export function toTokenUsage(
398
466
  ...(reasoning !== undefined && reasoning > 0
399
467
  ? { reasoningTokens: reasoning }
400
468
  : {}),
401
- totalTokens: input + cacheRead + cacheWrite + output,
469
+ totalTokens,
402
470
  }
403
471
  }
404
472
 
@@ -538,16 +606,20 @@ async function* stepChunks(
538
606
  }
539
607
  }
540
608
  turn.toolSteps++
609
+ turn.segmentToolSteps++
541
610
  yield { type: 'finish', reason: { kind: 'tool-calls' } }
542
611
  return
543
612
  }
544
613
  case 'done': {
614
+ turn.usage = accumulateRawUsage(turn.usage, event.result.usage)
545
615
  const stop = event.result.stopReason
546
616
  if (
547
617
  stop === 'max_tokens' &&
548
618
  turn.continuations < host.maxContinuations
549
619
  ) {
550
620
  turn.continuations++
621
+ turn.segmentToolSteps = 0
622
+ turn.contextUsed = undefined
551
623
  turn.promptSettled = host.continuePrompt().then(
552
624
  (result) => turn.events.push({ kind: 'done', result }),
553
625
  (error: unknown) =>
@@ -557,9 +629,14 @@ async function* stepChunks(
557
629
  }
558
630
  turn.finished = true
559
631
  yield* close()
560
- const calls = turn.toolSteps + turn.continuations + 1
561
- turn.usage = event.result.usage
562
- const usage = toTokenUsage(event.result.usage, calls)
632
+ const segmentCalls =
633
+ event.result.usage !== undefined
634
+ ? turn.segmentToolSteps + 1
635
+ : turn.toolSteps + turn.continuations + 1
636
+ const usage = toTokenUsage(turn.usage, segmentCalls, {
637
+ contextTokens: turn.contextUsed,
638
+ lastSegmentUsage: event.result.usage ?? turn.usage,
639
+ })
563
640
  if (usage !== undefined) yield { type: 'usage', usage }
564
641
  if (
565
642
  turn.isRelaying &&
@@ -662,8 +739,31 @@ function nonEmpty(value: unknown): string | undefined {
662
739
  }
663
740
 
664
741
  /**
665
- * Extract the structured `(serverName, toolName)` an agent claimed in one
666
- * permission request: top-level `mcpServerName`/`mcpToolName` or `_meta`.
742
+ * Resolve one explicit metadata field across candidate aliases, flagging when
743
+ * any two non-empty candidates disagree.
744
+ */
745
+ function reconcileCandidates(values: readonly unknown[]): {
746
+ value?: string
747
+ conflict: boolean
748
+ } {
749
+ let value: string | undefined
750
+ let conflict = false
751
+ for (const raw of values) {
752
+ const candidate = nonEmpty(raw)
753
+ if (candidate === undefined) continue
754
+ if (value === undefined) value = candidate
755
+ else if (value !== candidate) conflict = true
756
+ }
757
+ return { ...(value !== undefined ? { value } : {}), conflict }
758
+ }
759
+
760
+ /**
761
+ * Extract tool identity `(serverName, toolName)` from `session/update`
762
+ * (`recordReportedToolCall`) or `session/request_permission` (`answerPermission`).
763
+ * Reads top-level `mcpServerName`/`mcpToolName` or `_meta`, and reconciles flat
764
+ * `name` (`mcp_<server>_<tool>`). Non-Pi flat names map to a `non-pi:<name>`
765
+ * server sentinel, and contradictions across explicit fields or `name` set
766
+ * `conflict: true`. Returns `{}` only when no identity fields are present.
667
767
  * `title` and `rawInput` are deliberately not consulted.
668
768
  */
669
769
  export function structuredToolMeta(
@@ -671,21 +771,49 @@ export function structuredToolMeta(
671
771
  ): {
672
772
  serverName?: string
673
773
  toolName?: string
774
+ conflict?: boolean
674
775
  } {
675
776
  const meta: AcpToolCallMeta | undefined = toolCall?._meta
676
- const serverName =
677
- nonEmpty(toolCall?.mcpServerName) ??
678
- nonEmpty(meta?.mcpServerName) ??
679
- nonEmpty(meta?.serverName) ??
680
- nonEmpty(meta?.server)
681
- const toolName =
682
- nonEmpty(toolCall?.mcpToolName) ??
683
- nonEmpty(meta?.mcpToolName) ??
684
- nonEmpty(meta?.toolName) ??
685
- nonEmpty(meta?.tool)
777
+ const server = reconcileCandidates([
778
+ toolCall?.mcpServerName,
779
+ meta?.mcpServerName,
780
+ meta?.serverName,
781
+ meta?.server,
782
+ ])
783
+ const tool = reconcileCandidates([
784
+ toolCall?.mcpToolName,
785
+ meta?.mcpToolName,
786
+ meta?.toolName,
787
+ meta?.tool,
788
+ ])
789
+ const explicitServer = server.value
790
+ const explicitTool = tool.value
791
+ const flat = nonEmpty(toolCall?.name)
792
+ if (flat === undefined) {
793
+ const conflict = server.conflict || tool.conflict
794
+ return {
795
+ ...(explicitServer !== undefined ? { serverName: explicitServer } : {}),
796
+ ...(explicitTool !== undefined ? { toolName: explicitTool } : {}),
797
+ ...(conflict ? { conflict: true } : {}),
798
+ }
799
+ }
800
+ const candidateServer = explicitServer ?? MCP_SERVER_NAME
801
+ const prefix = `mcp_${candidateServer}_`
802
+ const hasPrefixedTool =
803
+ flat.startsWith(prefix) && flat.length > prefix.length
804
+ const flatServer = hasPrefixedTool ? candidateServer : `non-pi:${flat}`
805
+ const flatTool = hasPrefixedTool ? flat.slice(prefix.length) : flat
806
+ const hasExplicit = explicitServer !== undefined || explicitTool !== undefined
807
+ const conflict =
808
+ server.conflict ||
809
+ tool.conflict ||
810
+ (hasExplicit &&
811
+ (!hasPrefixedTool ||
812
+ (explicitTool !== undefined && explicitTool !== flatTool)))
686
813
  return {
687
- ...(serverName !== undefined ? { serverName } : {}),
688
- ...(toolName !== undefined ? { toolName } : {}),
814
+ serverName: explicitServer ?? flatServer,
815
+ toolName: explicitTool ?? flatTool,
816
+ ...(conflict ? { conflict: true } : {}),
689
817
  }
690
818
  }
691
819
 
@@ -709,11 +837,15 @@ export function recordReportedToolCall(
709
837
  return
710
838
  if (typeof update.toolCallId !== 'string' || update.toolCallId.length === 0)
711
839
  return
712
- const { serverName, toolName } = structuredToolMeta(update)
840
+ const {
841
+ serverName,
842
+ toolName,
843
+ conflict: metaConflict,
844
+ } = structuredToolMeta(update)
713
845
  const kind = typeof update.kind === 'string' ? update.kind : undefined
714
846
  const existing = conv.reportedToolCalls.get(update.toolCallId)
715
847
  const merged: ReportedToolCall = existing === undefined ? {} : { ...existing }
716
- let conflict = false
848
+ let conflict = metaConflict === true
717
849
  if (kind !== undefined) {
718
850
  if (merged.kind !== undefined && merged.kind !== kind) conflict = true
719
851
  else merged.kind = kind
package/src/format.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { QuotaDisplay } from './config.ts'
1
+ import { asEffort, type Effort, type QuotaDisplay } from './config.ts'
2
2
  import type {
3
3
  AccountInfo,
4
4
  QuotaSnapshot,
@@ -22,21 +22,319 @@ function formatAccount(account?: AccountInfo): string {
22
22
  return [account?.email, account?.plan].filter(Boolean).join(' · ')
23
23
  }
24
24
 
25
- /** Lowest known window for the model family; unknown groups fall back conservatively. */
25
+ /** Active model identity from Pi (`id` plus optional display `name` for `/usage` labels such as `Orchestrator (Carbon)`). */
26
+ export interface QuotaModelRef {
27
+ readonly id: string
28
+ readonly name?: string
29
+ }
30
+
31
+ // `agy` `/usage` prefixes closed, exhaustive member lists with "Models within this group:";
32
+ // unprefixed descriptions are free-form prose notes.
33
+ const EXPLICIT_MEMBERS_PREFIX = /^\s*models within this group:\s*/i
34
+ const CLAUSE_SPLIT = /[,;\n/|&+]+|\b(?:and|or)\b/i
35
+ const ID_DATE_SUFFIX = /[-_](?:20\d{2}[-_]\d{2}[-_]\d{2}|20\d{6})$/i
36
+ // Effort or thinking-mode suffixes in model IDs (`-thinking`) and `/usage` labels (`(Thinking)`).
37
+ const ID_QUALIFIER_SUFFIX = /[-_](low|medium|high|thinking)$/i
38
+ const GROUP_QUALIFIER_SUFFIX =
39
+ /\s*\((low|medium|high|thinking)\)(?=\s*(?:models?|groups?)?[\s.!?)]*$)/i
40
+ const SPECIFIER = /^\d+(?:\.\d+)*b?$/
41
+ const VENDOR_TOKENS = new Set(['google', 'anthropic', 'openai'])
42
+ const FAMILY_TOKENS = new Set(['gemini', 'claude', 'gpt'])
43
+ const GROUP_NOISE_TOKENS = new Set(['model', 'models', 'group', 'groups'])
44
+ const GENERIC_GROUP_TOKENS = new Set([
45
+ ...VENDOR_TOKENS,
46
+ ...FAMILY_TOKENS,
47
+ ...GROUP_NOISE_TOKENS,
48
+ 'all',
49
+ 'other',
50
+ 'default',
51
+ 'general',
52
+ ])
53
+
54
+ /**
55
+ * Tokenize into lowercase words, dotted versions, and `<n>b` parameter sizes.
56
+ * Hyphens between digits become dots only for 1-2 digit version segments (`5-5` -> `5.5`),
57
+ * preserving parameter sizes (`3-8b`, `120b`) and dates stripped beforehand.
58
+ */
59
+ function normalizeTokens(text: string): string[] {
60
+ return (
61
+ text
62
+ .toLowerCase()
63
+ .replace(/(?<=\d)-(?=\d{1,2}(?![a-z0-9.]))/g, '.')
64
+ .match(/[a-z0-9]+(?:\.[0-9]+)*(?:b(?![a-z0-9]))?/g) ?? []
65
+ )
66
+ }
67
+
68
+ interface ParsedPhrase {
69
+ readonly head: string | undefined
70
+ readonly words: readonly string[]
71
+ readonly specs: readonly string[]
72
+ readonly effort: Effort | undefined
73
+ readonly thinking: boolean
74
+ readonly effortConflict: boolean
75
+ readonly tokenCount: number
76
+ readonly canonical: string
77
+ }
78
+
79
+ function buildPhrase(
80
+ tokens: readonly string[],
81
+ effort?: Effort,
82
+ thinking = false,
83
+ effortConflict = false,
84
+ ): ParsedPhrase {
85
+ const words: string[] = []
86
+ const specs: string[] = []
87
+ for (const token of tokens) {
88
+ if (SPECIFIER.test(token)) specs.push(token)
89
+ else words.push(token)
90
+ }
91
+ return {
92
+ head: tokens[0],
93
+ words,
94
+ specs,
95
+ effort,
96
+ thinking,
97
+ effortConflict,
98
+ tokenCount: tokens.length,
99
+ canonical: `${words.join(' ')}|${specs.join(' ')}`,
100
+ }
101
+ }
102
+
103
+ function parseClause(raw: string, stripNoise = false): ParsedPhrase {
104
+ let text = raw.trim().replace(/[.!?]+$/, '')
105
+ let effort: Effort | undefined
106
+ let thinking = false
107
+ let effortConflict = false
108
+ while (text.length > 0) {
109
+ const withoutDate = text.replace(ID_DATE_SUFFIX, '')
110
+ if (withoutDate !== text) {
111
+ text = withoutDate
112
+ continue
113
+ }
114
+ const groupQual = GROUP_QUALIFIER_SUFFIX.exec(text)
115
+ if (groupQual) {
116
+ const nextEffort = asEffort(groupQual[1]!.toLowerCase())
117
+ if (nextEffort) {
118
+ if (effort && effort !== nextEffort) effortConflict = true
119
+ effort = nextEffort
120
+ } else {
121
+ thinking = true
122
+ }
123
+ text =
124
+ text.slice(0, groupQual.index) +
125
+ text.slice(groupQual.index + groupQual[0].length)
126
+ continue
127
+ }
128
+ const idQual = ID_QUALIFIER_SUFFIX.exec(text)
129
+ if (idQual) {
130
+ const nextEffort = asEffort(idQual[1]!.toLowerCase())
131
+ if (nextEffort) {
132
+ if (effort && effort !== nextEffort) effortConflict = true
133
+ effort = nextEffort
134
+ } else {
135
+ thinking = true
136
+ }
137
+ text = text.slice(0, idQual.index)
138
+ continue
139
+ }
140
+ break
141
+ }
142
+ const baseTokens = normalizeTokens(text)
143
+ const fallback = baseTokens.length === 0
144
+ const tokens = [...(fallback ? normalizeTokens(raw) : baseTokens)]
145
+ while (tokens.length >= 2 && VENDOR_TOKENS.has(tokens[0]!)) tokens.shift()
146
+ const cleaned = stripNoise
147
+ ? (() => {
148
+ const stripped = tokens.filter((t) => !GROUP_NOISE_TOKENS.has(t))
149
+ return stripped.length >= 2 ? stripped : tokens
150
+ })()
151
+ : tokens
152
+ return buildPhrase(
153
+ cleaned,
154
+ fallback ? undefined : effort,
155
+ fallback ? false : thinking,
156
+ !fallback && effortConflict,
157
+ )
158
+ }
159
+
160
+ function parseGroupPhrases(
161
+ text: string,
162
+ excludeGeneric: boolean,
163
+ ): ParsedPhrase[] {
164
+ const phrases: ParsedPhrase[] = []
165
+ for (const part of text.split(CLAUSE_SPLIT)) {
166
+ if (
167
+ excludeGeneric &&
168
+ normalizeTokens(part).every((token) => GENERIC_GROUP_TOKENS.has(token))
169
+ )
170
+ continue
171
+ const phrase = parseClause(part, true)
172
+ if (phrase.tokenCount > 0 && !phrase.effortConflict) phrases.push(phrase)
173
+ }
174
+ return phrases
175
+ }
176
+
177
+ function buildModelCandidates(id: string, name?: string): ParsedPhrase[] {
178
+ const idPhrase = parseClause(id)
179
+ const namePhrase = name ? parseClause(name) : undefined
180
+ if (
181
+ idPhrase.effortConflict ||
182
+ namePhrase?.effortConflict ||
183
+ (idPhrase.effort &&
184
+ namePhrase?.effort &&
185
+ idPhrase.effort !== namePhrase.effort)
186
+ )
187
+ return []
188
+ const effort = idPhrase.effort ?? namePhrase?.effort
189
+ const thinking = idPhrase.thinking || Boolean(namePhrase?.thinking)
190
+ const seen = new Set<string>()
191
+ const out: ParsedPhrase[] = []
192
+ for (const candidate of [idPhrase, namePhrase]) {
193
+ if (!candidate || candidate.tokenCount === 0) continue
194
+ const phrase = { ...candidate, effort, thinking }
195
+ const key = `${phrase.canonical}#${phrase.effort ?? ''}#${phrase.thinking ? 't' : ''}`
196
+ if (!seen.has(key)) {
197
+ seen.add(key)
198
+ out.push(phrase)
199
+ }
200
+ }
201
+ return out
202
+ }
203
+
204
+ const isExactPhrase = (groupPhrase: ParsedPhrase, modelPhrase: ParsedPhrase) =>
205
+ groupPhrase.canonical === modelPhrase.canonical
206
+
207
+ /**
208
+ * True for a subfamily without version/size (`GPT-OSS`, `Gemini Flash`) or a
209
+ * single-version generation line (`Gemini 4`, `Gemini 3.8`) matching the model.
210
+ */
211
+ function isBroaderVariant(
212
+ groupPhrase: ParsedPhrase,
213
+ modelPhrase: ParsedPhrase,
214
+ ): boolean {
215
+ if (
216
+ groupPhrase.tokenCount < 2 ||
217
+ !groupPhrase.head ||
218
+ groupPhrase.head !== modelPhrase.head
219
+ )
220
+ return false
221
+ if (groupPhrase.words.length >= 2 && groupPhrase.specs.length === 0)
222
+ return groupPhrase.words.join(' ') === modelPhrase.words.join(' ')
223
+ const modelVersions = modelPhrase.specs.filter((s) => !s.endsWith('b'))
224
+ return (
225
+ groupPhrase.words.length === 1 &&
226
+ groupPhrase.specs.length === 1 &&
227
+ !groupPhrase.specs[0]!.endsWith('b') &&
228
+ modelVersions.length === 1 &&
229
+ modelVersions[0] === groupPhrase.specs[0]
230
+ )
231
+ }
232
+
233
+ function extractFamily(text?: string): string | undefined {
234
+ const head = text
235
+ ? normalizeTokens(text).find((token) => !VENDOR_TOKENS.has(token))
236
+ : undefined
237
+ return head && FAMILY_TOKENS.has(head) ? head : undefined
238
+ }
239
+
240
+ function isGenericFamilyGroup(group: QuotaGroup, family: string): boolean {
241
+ if (EXPLICIT_MEMBERS_PREFIX.test(group.description)) return false
242
+ return group.name.split(CLAUSE_SPLIT).some((clause) => {
243
+ const tokens = normalizeTokens(clause)
244
+ return (
245
+ tokens.includes(family) &&
246
+ tokens.every((token) => GENERIC_GROUP_TOKENS.has(token))
247
+ )
248
+ })
249
+ }
250
+
251
+ const matchGroup = (
252
+ phrases: readonly ParsedPhrase[],
253
+ candidates: readonly ParsedPhrase[],
254
+ relation: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
255
+ qualOk: (g: ParsedPhrase, m: ParsedPhrase) => boolean,
256
+ ) => phrases.some((p) => candidates.some((c) => qualOk(p, c) && relation(p, c)))
257
+
258
+ function selectQuotaGroups(
259
+ snapshot: QuotaSnapshot,
260
+ model?: QuotaModelRef,
261
+ ): QuotaGroup[] {
262
+ if (!model) return []
263
+ const candidates = buildModelCandidates(model.id, model.name)
264
+ if (candidates.length === 0) return []
265
+
266
+ const indexed = snapshot.groups.map((group) => {
267
+ const explicit = EXPLICIT_MEMBERS_PREFIX.test(group.description)
268
+ const raw = explicit
269
+ ? group.description.replace(EXPLICIT_MEMBERS_PREFIX, '')
270
+ : group.name
271
+ return { group, explicit, phrases: parseGroupPhrases(raw, !explicit) }
272
+ })
273
+
274
+ // Without an effort qualifier (`low`/`medium`/`high`) on the model reference, any matching
275
+ // effort-capped pool makes group ownership depend on unknown active effort; return unknown.
276
+ const omittedEffort = (g: ParsedPhrase, m: ParsedPhrase) =>
277
+ g.effort !== undefined && m.effort === undefined
278
+ if (
279
+ indexed.some(
280
+ (entry) =>
281
+ matchGroup(entry.phrases, candidates, isExactPhrase, omittedEffort) ||
282
+ matchGroup(entry.phrases, candidates, isBroaderVariant, omittedEffort),
283
+ )
284
+ )
285
+ return []
286
+
287
+ const compatQual = (g: ParsedPhrase, m: ParsedPhrase) =>
288
+ (g.effort === undefined || g.effort === m.effort) &&
289
+ (!g.thinking || m.thinking || m.effort !== undefined)
290
+
291
+ const authoritative: (typeof indexed)[number][] = []
292
+ const variantOnly: (typeof indexed)[number][] = []
293
+ for (const entry of indexed) {
294
+ const exact = matchGroup(entry.phrases, candidates, isExactPhrase, compatQual)
295
+ const variant = matchGroup(
296
+ entry.phrases,
297
+ candidates,
298
+ isBroaderVariant,
299
+ compatQual,
300
+ )
301
+ if (exact || (entry.explicit && variant)) authoritative.push(entry)
302
+ else if (variant) variantOnly.push(entry)
303
+ }
304
+ if (authoritative.length > 0) {
305
+ return [
306
+ ...authoritative,
307
+ ...(variantOnly.length === 1 ? variantOnly : []),
308
+ ].map((e) => e.group)
309
+ }
310
+ if (variantOnly.length === 1) return [variantOnly[0]!.group]
311
+ if (variantOnly.length > 1) return []
312
+
313
+ const thinkingQual = (g: ParsedPhrase, m: ParsedPhrase) =>
314
+ g.thinking && !m.thinking && g.effort === undefined && m.effort === undefined
315
+ const thinkingMatches = indexed.filter(
316
+ (entry) =>
317
+ matchGroup(entry.phrases, candidates, isExactPhrase, thinkingQual) ||
318
+ matchGroup(entry.phrases, candidates, isBroaderVariant, thinkingQual),
319
+ )
320
+ if (thinkingMatches.length === 1) return [thinkingMatches[0]!.group]
321
+ if (thinkingMatches.length > 1) return []
322
+
323
+ const family = extractFamily(model.id) ?? extractFamily(model.name)
324
+ if (!family) return []
325
+ const generic = indexed.filter(
326
+ (entry) => !entry.explicit && isGenericFamilyGroup(entry.group, family),
327
+ )
328
+ return generic.length === 1 ? [generic[0]!.group] : []
329
+ }
330
+
331
+ /** Lowest known window across the model's governing quota group(s); returns undefined when unknown or ambiguous. */
26
332
  export function quotaForModel(
27
333
  snapshot: QuotaSnapshot,
28
- model?: string,
334
+ model?: QuotaModelRef,
29
335
  ): { group: QuotaGroup; bucket: QuotaBucket; fraction: number } | undefined {
30
336
  if (snapshot.status !== 'ok') return undefined
31
- const family = /^(gemini|claude|gpt)(?:-|$)/i.exec(model ?? '')?.[1]
32
- const matched = family
33
- ? snapshot.groups.filter((group) =>
34
- new RegExp(`\\b${family}\\b`, 'i').test(
35
- `${group.name} ${group.description}`,
36
- ),
37
- )
38
- : []
39
- const groups = matched.length > 0 ? matched : snapshot.groups
337
+ const groups = selectQuotaGroups(snapshot, model)
40
338
  let lowest: ReturnType<typeof quotaForModel>
41
339
  for (const group of groups) {
42
340
  for (const bucket of group.buckets) {
@@ -59,7 +357,7 @@ export function displayFraction(
59
357
 
60
358
  export function formatQuotaStatus(
61
359
  snapshot: QuotaSnapshot,
62
- model?: string,
360
+ model?: QuotaModelRef,
63
361
  display: QuotaDisplay = 'used',
64
362
  ): string | undefined {
65
363
  const quota = quotaForModel(snapshot, model)
@@ -97,10 +395,11 @@ export function formatQuota(
97
395
  }
98
396
  for (const group of snapshot.groups) {
99
397
  lines.push('', ` ${group.name || 'Unnamed model group'}`)
100
- if (group.description) {
101
- lines.push(
102
- ` ${group.description.replace(/^Models within this group:\s*/i, '')}`,
103
- )
398
+ const description = group.description
399
+ .replace(EXPLICIT_MEMBERS_PREFIX, '')
400
+ .trim()
401
+ if (description) {
402
+ lines.push(` ${description}`)
104
403
  }
105
404
  if (group.buckets.length === 0)
106
405
  lines.push(' No quota windows available.')