omp-alamode 0.0.0-stage → 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.
@@ -0,0 +1,714 @@
1
+ /**
2
+ * Read-only usage knowledge for the model context.
3
+ *
4
+ * This module deliberately owns no state and has no side effects beyond asking
5
+ * the host for its cached, normalized provider-usage reports. It never reads
6
+ * credentials, account identities, usage history, or raw provider payloads.
7
+ */
8
+ import type { ContextUsage, ExtensionContext, UsageStatistics } from "@oh-my-pi/pi-coding-agent";
9
+ import type { UsageAmount, UsageLimit, UsageReport, UsageUnit } from "@oh-my-pi/pi-ai";
10
+
11
+ /** Host quota reports are cached for five minutes; older snapshots cannot claim current allowance. */
12
+ const REPORT_MAX_AGE_MS = 5 * 60_000;
13
+ const MAX_TIMESTAMP_MS = 8_640_000_000_000_000;
14
+ const MAX_LABEL_LENGTH = 80;
15
+ const NEAR_LIMIT_FRACTION = 0.25;
16
+ const TIGHT_LIMIT_FRACTION = 0.1;
17
+
18
+ const amountFormat = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });
19
+
20
+ interface RemainingAllowance {
21
+ fraction?: number;
22
+ amount?: number;
23
+ limit?: number;
24
+ overLimit: boolean;
25
+ invalidLimit: boolean;
26
+ }
27
+
28
+ interface ContextKnowledge {
29
+ line: string;
30
+ remainingFraction?: number;
31
+ headroomTokens?: number;
32
+ }
33
+
34
+ interface SessionKnowledge {
35
+ line: string;
36
+ }
37
+
38
+ interface SnapshotFreshness {
39
+ stale: boolean;
40
+ description: string;
41
+ }
42
+
43
+ interface UsagePressure {
44
+ source: "context" | "provider";
45
+ fraction: number;
46
+ label: string;
47
+ resetsAt?: number;
48
+ exhausted: boolean;
49
+ headroomTokens?: number;
50
+ }
51
+
52
+ interface SnapshotKnowledge {
53
+ line: string;
54
+ candidates: UsagePressure[];
55
+ }
56
+
57
+ function isFiniteNumber(value: unknown): value is number {
58
+ return typeof value === "number" && Number.isFinite(value);
59
+ }
60
+
61
+ function nonNegativeNumber(value: unknown): number | undefined {
62
+ return isFiniteNumber(value) && value >= 0 ? value : undefined;
63
+ }
64
+
65
+ function timestampValue(value: unknown): number | undefined {
66
+ return isFiniteNumber(value) && value > 0 && value <= MAX_TIMESTAMP_MS ? value : undefined;
67
+ }
68
+
69
+ function clamp01(value: number): number {
70
+ return Math.min(1, Math.max(0, value));
71
+ }
72
+
73
+ /** Keep provider-authored text from introducing line breaks or unbounded payloads. */
74
+ function cleanText(value: unknown, fallback: string): string {
75
+ if (typeof value !== "string") return fallback;
76
+ const cleaned = value
77
+ .replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ")
78
+ .replace(/\s+/g, " ")
79
+ .trim();
80
+ if (!cleaned) return fallback;
81
+ return cleaned.length > MAX_LABEL_LENGTH ? `${cleaned.slice(0, MAX_LABEL_LENGTH - 3)}...` : cleaned;
82
+ }
83
+
84
+ function formatNumber(value: number): string {
85
+ return amountFormat.format(value);
86
+ }
87
+
88
+ function formatPercentValue(percent: number): string {
89
+ const rounded = Math.round(percent * 10) / 10;
90
+ return Number.isInteger(rounded) ? `${rounded}%` : `${rounded.toFixed(1)}%`;
91
+ }
92
+
93
+ function formatPercent(fraction: number): string {
94
+ if (fraction >= 1) return "100%";
95
+ if (fraction <= 0) return "0%";
96
+ const percent = fraction * 100;
97
+ if (percent < 0.1) return "<0.1%";
98
+ const rounded = Math.round(percent * 10) / 10;
99
+ if (rounded >= 100) return "99.9%";
100
+ return Number.isInteger(rounded) ? `${rounded}%` : `${rounded.toFixed(1)}%`;
101
+ }
102
+
103
+ function formatDuration(ms: number): string {
104
+ const seconds = Math.max(0, Math.round(ms / 1000));
105
+ if (seconds < 60) return `${seconds}s`;
106
+ const minutes = Math.floor(seconds / 60);
107
+ if (minutes < 60) return seconds % 60 === 0 ? `${minutes}m` : `${minutes}m ${seconds % 60}s`;
108
+ const hours = Math.floor(minutes / 60);
109
+ if (hours < 48) return minutes % 60 === 0 ? `${hours}h` : `${hours}h ${minutes % 60}m`;
110
+ const days = Math.floor(hours / 24);
111
+ return hours % 24 === 0 ? `${days}d` : `${days}d ${hours % 24}h`;
112
+ }
113
+
114
+ function formatUsd(value: number): string {
115
+ return `${value < 0 ? "-" : ""}$${Math.abs(value).toFixed(6)}`;
116
+ }
117
+
118
+ function formatQuantity(value: number, unit: UsageUnit | undefined): { value: string; unit: string } {
119
+ switch (unit) {
120
+ case "percent":
121
+ return { value: formatPercentValue(value), unit: "" };
122
+ case "usd":
123
+ return { value: `${value < 0 ? "-" : ""}$${formatNumber(Math.abs(value))}`, unit: "" };
124
+ case "tokens":
125
+ return { value: formatNumber(value), unit: "tokens" };
126
+ case "requests":
127
+ return { value: formatNumber(value), unit: "requests" };
128
+ case "credits":
129
+ return { value: formatNumber(value), unit: "credits" };
130
+ case "minutes":
131
+ return { value: formatNumber(value), unit: "minutes" };
132
+ case "bytes":
133
+ return { value: formatNumber(value), unit: "bytes" };
134
+ default:
135
+ return { value: formatNumber(value), unit: "units (unit type unknown)" };
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Resolve remaining allowance from whichever fields the host populated.
141
+ * Precedence follows the host usage UI: explicit remaining fraction, explicit
142
+ * used fraction, remaining/limit, used/limit, then percent-unit used. Only
143
+ * observed values are used; missing data stays missing.
144
+ */
145
+ function resolveRemaining(amount: UsageAmount | undefined): RemainingAllowance {
146
+ if (!amount) return { overLimit: false, invalidLimit: false };
147
+ const rawLimit = amount.limit;
148
+ const invalidLimit = rawLimit !== undefined && (!isFiniteNumber(rawLimit) || rawLimit <= 0);
149
+ const limit = !invalidLimit && isFiniteNumber(rawLimit) && rawLimit > 0 ? rawLimit : undefined;
150
+ const remaining = nonNegativeNumber(amount.remaining);
151
+ const used = nonNegativeNumber(amount.used);
152
+ const remainingFraction = isFiniteNumber(amount.remainingFraction) ? amount.remainingFraction : undefined;
153
+ const usedFraction = isFiniteNumber(amount.usedFraction) ? amount.usedFraction : undefined;
154
+
155
+ let fraction: number | undefined;
156
+ if (!invalidLimit) {
157
+ if (remainingFraction !== undefined) fraction = clamp01(remainingFraction);
158
+ else if (usedFraction !== undefined) fraction = clamp01(1 - usedFraction);
159
+ else if (remaining !== undefined && limit !== undefined) fraction = clamp01(remaining / limit);
160
+ else if (used !== undefined && limit !== undefined) fraction = clamp01(1 - used / limit);
161
+ else if (amount.unit === "percent" && used !== undefined) fraction = clamp01(1 - used / 100);
162
+ else if (amount.unit === "percent" && remaining !== undefined) fraction = clamp01(remaining / 100);
163
+ else if (remaining === 0) fraction = 0;
164
+ }
165
+
166
+ const overLimit =
167
+ !invalidLimit &&
168
+ ((usedFraction !== undefined && usedFraction > 1) ||
169
+ (used !== undefined && limit !== undefined && used > limit));
170
+
171
+ let remainingAmount = invalidLimit ? undefined : remaining;
172
+ if (remainingAmount === undefined && fraction !== undefined && limit !== undefined) {
173
+ remainingAmount = fraction * limit;
174
+ }
175
+ if (remainingAmount !== undefined && limit !== undefined) {
176
+ remainingAmount = Math.min(remainingAmount, limit);
177
+ }
178
+ if (overLimit) {
179
+ fraction = 0;
180
+ if (limit !== undefined) remainingAmount = 0;
181
+ }
182
+
183
+ return { fraction, amount: remainingAmount, limit, overLimit, invalidLimit };
184
+ }
185
+
186
+ function describeRemaining(
187
+ remaining: RemainingAllowance,
188
+ unit: UsageUnit | undefined,
189
+ status: unknown,
190
+ ): string {
191
+ if (remaining.invalidLimit) return "invalid reported limit; remaining unknown";
192
+ if (remaining.fraction === undefined && remaining.amount === undefined) {
193
+ switch (status) {
194
+ case "exhausted":
195
+ return "provider status exhausted; remaining amount unknown";
196
+ case "warning":
197
+ return "provider status warning; remaining amount unknown";
198
+ case "unknown":
199
+ return "provider status unknown; remaining amount unknown";
200
+ default:
201
+ return "remaining amount unknown";
202
+ }
203
+ }
204
+
205
+ let percentText: string | undefined;
206
+ let absoluteText: string | undefined;
207
+ if (remaining.fraction !== undefined) percentText = `${formatPercent(remaining.fraction)} left`;
208
+ if (remaining.amount !== undefined && unit !== "percent") {
209
+ const remainingQuantity = formatQuantity(remaining.amount, unit);
210
+ if (remaining.limit !== undefined) {
211
+ const limitQuantity = formatQuantity(remaining.limit, unit);
212
+ const unitSuffix = limitQuantity.unit ? ` ${limitQuantity.unit}` : "";
213
+ absoluteText = `${remainingQuantity.value} of ${limitQuantity.value}${unitSuffix} left`;
214
+ } else {
215
+ const unitSuffix = remainingQuantity.unit ? ` ${remainingQuantity.unit}` : "";
216
+ absoluteText = `${remainingQuantity.value}${unitSuffix} left`;
217
+ }
218
+ }
219
+
220
+ let text: string;
221
+ if (percentText && absoluteText) text = `${percentText} (${absoluteText})`;
222
+ else if (percentText) text = `${percentText} (absolute amount not reported)`;
223
+ else if (absoluteText) text = `${absoluteText} (fraction not reported)`;
224
+ else text = "remaining amount unknown";
225
+ if (remaining.overLimit) text += " — over limit";
226
+ return text;
227
+ }
228
+
229
+ function limitTitle(limit: UsageLimit): string {
230
+ const label = cleanText(limit.label, cleanText(limit.id, "limit"));
231
+ const windowLabel = cleanText(
232
+ limit.window?.label,
233
+ cleanText(limit.scope?.windowId, limit.window ? cleanText(limit.window.id, "") : ""),
234
+ );
235
+ if (windowLabel && !label.toLowerCase().includes(windowLabel.toLowerCase())) {
236
+ return `${label} (${windowLabel})`;
237
+ }
238
+ return label;
239
+ }
240
+
241
+ function describeReset(limit: UsageLimit, now: number): string {
242
+ const resetsAt = timestampValue(limit.window?.resetsAt);
243
+ if (resetsAt === undefined) return "reset time not reported";
244
+ const iso = new Date(resetsAt).toISOString();
245
+ const resetLabel = cleanText(limit.window?.resetLabel, "resets");
246
+ if (resetsAt > now) return `${resetLabel} in ${formatDuration(resetsAt - now)} (${iso})`;
247
+ if (resetsAt === now) return `resets now (${iso})`;
248
+ return `reset ${formatDuration(now - resetsAt)} ago (${iso})`;
249
+ }
250
+
251
+ function describePastReset(resetsAt: number, now: number): string {
252
+ const iso = new Date(resetsAt).toISOString();
253
+ return resetsAt === now ? `window reset at ${iso} (now)` : `window reset ${formatDuration(now - resetsAt)} ago (${iso})`;
254
+ }
255
+
256
+ function describeRecordedReset(limit: UsageLimit, now: number): string {
257
+ const resetsAt = timestampValue(limit.window?.resetsAt);
258
+ if (resetsAt === undefined) return "recorded reset time not reported";
259
+ const iso = new Date(resetsAt).toISOString();
260
+ if (resetsAt > now) return `recorded reset at ${iso} (in ${formatDuration(resetsAt - now)})`;
261
+ if (resetsAt === now) return `recorded reset at ${iso} (now)`;
262
+ return `recorded reset at ${iso} (${formatDuration(now - resetsAt)} ago)`;
263
+ }
264
+
265
+ function assessFreshness(report: UsageReport, now: number): SnapshotFreshness {
266
+ const fetchedAt = timestampValue(report.fetchedAt);
267
+ if (fetchedAt === undefined) return { stale: true, description: "report time missing" };
268
+ if (fetchedAt > now) return { stale: true, description: "report timestamp is in the future" };
269
+ const ageMs = Math.max(0, now - fetchedAt);
270
+ const ageText = ageMs < 5_000 ? "just now" : `${formatDuration(ageMs)} old`;
271
+ if (ageMs > REPORT_MAX_AGE_MS) return { stale: true, description: `report ${ageText}, stale` };
272
+ return { stale: false, description: `report ${ageText}` };
273
+ }
274
+
275
+ function limitMatchesModel(limit: UsageLimit, provider: string, modelId: string): boolean {
276
+ const scope = limit.scope;
277
+ if (!scope || typeof scope !== "object") return true;
278
+ if (scope.shared === true) return true;
279
+ const scopedModel = typeof scope.modelId === "string" ? scope.modelId.trim() : "";
280
+ if (!scopedModel) return true;
281
+ if (!modelId) return false;
282
+ return scopedModel === modelId || scopedModel === `${provider}/${modelId}`;
283
+ }
284
+
285
+ function describeSnapshot(
286
+ report: UsageReport,
287
+ index: number,
288
+ total: number,
289
+ provider: string,
290
+ modelId: string,
291
+ now: number,
292
+ ): SnapshotKnowledge {
293
+ const freshness = assessFreshness(report, now);
294
+ const allLimits = Array.isArray(report.limits) ? report.limits : [];
295
+ const limits: UsageLimit[] = [];
296
+ let omitted = 0;
297
+ for (const limit of allLimits) {
298
+ if (limitMatchesModel(limit, provider, modelId)) limits.push(limit);
299
+ else omitted += 1;
300
+ }
301
+ const omittedSuffix =
302
+ omitted > 0 ? ` | ${formatNumber(omitted)} other-model limit${omitted === 1 ? "" : "s"} omitted` : "";
303
+
304
+ if (freshness.stale) {
305
+ const parts = limits.map(limit => `${limitTitle(limit)} — ${describeRecordedReset(limit, now)}`);
306
+ const body =
307
+ parts.length > 0
308
+ ? parts.join(" | ")
309
+ : allLimits.length === 0
310
+ ? "no limit windows reported"
311
+ : "no limits for the current model";
312
+ return {
313
+ line: `- account snapshot ${formatNumber(index)} of ${formatNumber(total)} (${freshness.description}; current allowance unknown; not used for advice): ${body}${omittedSuffix}`,
314
+ candidates: [],
315
+ };
316
+ }
317
+
318
+ const candidates: UsagePressure[] = [];
319
+ const parts: string[] = [];
320
+ for (const limit of limits) {
321
+ const resetsAt = timestampValue(limit.window?.resetsAt);
322
+ if (resetsAt !== undefined && resetsAt <= now) {
323
+ parts.push(`${limitTitle(limit)} — current allowance unknown: ${describePastReset(resetsAt, now)}`);
324
+ continue;
325
+ }
326
+
327
+ const remaining = resolveRemaining(limit.amount);
328
+ const dataKnown = remaining.fraction !== undefined || remaining.amount !== undefined;
329
+ if (limit.status === "unknown") {
330
+ const text = dataKnown
331
+ ? `recorded ${describeRemaining(remaining, limit.amount?.unit, limit.status)}; provider status unknown, current usability unknown, not used for advice`
332
+ : `${describeRemaining(remaining, limit.amount?.unit, limit.status)}; not used for advice`;
333
+ parts.push(`${limitTitle(limit)} — ${text}, ${describeReset(limit, now)}`);
334
+ continue;
335
+ }
336
+ if (limit.status === "exhausted") {
337
+ const text = dataKnown
338
+ ? `recorded ${describeRemaining(remaining, limit.amount?.unit, limit.status)}; provider status exhausted, not used as spendable headroom`
339
+ : "provider status exhausted; remaining unknown";
340
+ parts.push(`${limitTitle(limit)} — ${text}, ${describeReset(limit, now)}`);
341
+ candidates.push({
342
+ source: "provider",
343
+ fraction: 0,
344
+ label: limitTitle(limit),
345
+ resetsAt,
346
+ exhausted: true,
347
+ });
348
+ continue;
349
+ }
350
+
351
+ const amountText = describeRemaining(remaining, limit.amount?.unit, limit.status);
352
+ const suffix = dataKnown && limit.status === "warning" ? "; provider status warning" : "";
353
+ parts.push(`${limitTitle(limit)} — ${amountText}${suffix}, ${describeReset(limit, now)}`);
354
+
355
+ if (remaining.fraction !== undefined) {
356
+ candidates.push({
357
+ source: "provider",
358
+ fraction: remaining.fraction,
359
+ label: limitTitle(limit),
360
+ resetsAt,
361
+ exhausted: remaining.fraction === 0,
362
+ });
363
+ }
364
+ }
365
+
366
+ let body: string;
367
+ if (parts.length > 0) body = parts.join(" | ");
368
+ else if (allLimits.length === 0) body = "no limit windows reported; current allowance unknown";
369
+ else body = "no limits for the current model; current allowance unknown";
370
+
371
+ return {
372
+ line: `- account snapshot ${formatNumber(index)} of ${formatNumber(total)} (${freshness.description}): ${body}${omittedSuffix}`,
373
+ candidates,
374
+ };
375
+ }
376
+
377
+ function readContextKnowledge(ctx: ExtensionContext): ContextKnowledge {
378
+ let usage: ContextUsage | undefined;
379
+ try {
380
+ usage = ctx.getContextUsage();
381
+ } catch {
382
+ return { line: "Context: unknown (host context usage unavailable)" };
383
+ }
384
+ if (!usage) return { line: "Context: unknown (host returned no context usage)" };
385
+
386
+ const tokens = nonNegativeNumber(usage.tokens);
387
+ const contextWindow = isFiniteNumber(usage.contextWindow) && usage.contextWindow > 0 ? usage.contextWindow : undefined;
388
+ const percent = nonNegativeNumber(usage.percent);
389
+
390
+ if (tokens !== undefined && contextWindow !== undefined) {
391
+ const usedPercent = (tokens / contextWindow) * 100;
392
+ const headroomTokens = Math.max(0, contextWindow - tokens);
393
+ const remainingFraction = clamp01(headroomTokens / contextWindow);
394
+ const overWindow = usedPercent > 100;
395
+ return {
396
+ line: `Context: ${formatNumber(tokens)} / ${formatNumber(contextWindow)} tokens used (${formatPercentValue(usedPercent)}${overWindow ? ", over window" : ""}); ${formatNumber(headroomTokens)} tokens (${formatPercent(remainingFraction)}) headroom`,
397
+ remainingFraction,
398
+ headroomTokens,
399
+ };
400
+ }
401
+
402
+ if (tokens !== undefined) {
403
+ const percentText = percent !== undefined ? ` (${formatPercentValue(percent)})` : "";
404
+ return {
405
+ line: `Context: ${formatNumber(tokens)} tokens used${percentText}; context window and token headroom unknown`,
406
+ };
407
+ }
408
+
409
+ if (percent !== undefined) {
410
+ const remainingFraction = clamp01(1 - percent / 100);
411
+ return {
412
+ line: `Context: ${formatPercentValue(percent)} used (token counts not reported); ${formatPercent(remainingFraction)} headroom, token headroom unknown`,
413
+ remainingFraction,
414
+ };
415
+ }
416
+
417
+ return { line: "Context: unknown (host reported no token counts)" };
418
+ }
419
+
420
+ function readSessionKnowledge(ctx: ExtensionContext): SessionKnowledge {
421
+ let raw: UsageStatistics | undefined;
422
+ try {
423
+ raw = ctx.sessionManager.getUsageStatistics();
424
+ } catch {
425
+ return { line: "Session: unknown (host statistics unavailable)" };
426
+ }
427
+ if (!raw) return { line: "Session: unknown (host returned no statistics)" };
428
+
429
+ const input = nonNegativeNumber(raw.input);
430
+ const output = nonNegativeNumber(raw.output);
431
+ const cacheRead = nonNegativeNumber(raw.cacheRead);
432
+ const cacheWrite = nonNegativeNumber(raw.cacheWrite);
433
+ const totalTokens = nonNegativeNumber(raw.totalTokens);
434
+ const premiumRequests = nonNegativeNumber(raw.premiumRequests);
435
+ const cost = nonNegativeNumber(raw.cost);
436
+ const subagentCost = nonNegativeNumber(raw.subagentCost);
437
+
438
+ if (
439
+ input === undefined &&
440
+ output === undefined &&
441
+ cacheRead === undefined &&
442
+ cacheWrite === undefined &&
443
+ totalTokens === undefined &&
444
+ cost === undefined
445
+ ) {
446
+ return { line: "Session: unknown (no counters reported)" };
447
+ }
448
+
449
+ const parts: string[] = [];
450
+ parts.push(totalTokens !== undefined ? `${formatNumber(totalTokens)} tokens total` : "total tokens unknown");
451
+ parts.push(
452
+ [
453
+ `input ${input !== undefined ? formatNumber(input) : "unknown"}`,
454
+ `output ${output !== undefined ? formatNumber(output) : "unknown"}`,
455
+ `cache read ${cacheRead !== undefined ? formatNumber(cacheRead) : "unknown"}`,
456
+ `cache write ${cacheWrite !== undefined ? formatNumber(cacheWrite) : "unknown"}`,
457
+ ].join("; "),
458
+ );
459
+ parts.push(
460
+ cost !== undefined
461
+ ? `cost ${formatUsd(cost)}${subagentCost !== undefined && subagentCost > 0 ? ` (includes ${formatUsd(subagentCost)} subagent spend)` : ""}`
462
+ : "cost unknown",
463
+ );
464
+ parts.push(
465
+ premiumRequests !== undefined
466
+ ? `${formatNumber(premiumRequests)} premium request${premiumRequests === 1 ? "" : "s"}`
467
+ : "premium requests unknown",
468
+ );
469
+
470
+ return { line: `Session: ${parts.join("; ")}` };
471
+ }
472
+
473
+ function pressureLabel(pressure: UsagePressure): string {
474
+ return pressure.source === "context" ? "context" : `reported provider window "${pressure.label}"`;
475
+ }
476
+
477
+ function describePressureAdvice(pressure: UsagePressure, now: number, snapshotCount: number): string {
478
+ const percent = formatPercent(pressure.fraction);
479
+ if (pressure.source === "context") {
480
+ if (pressure.fraction <= 0) {
481
+ return "Context has no reported headroom; compact or start a fresh session before adding more, preserving user requirements and unresolved work first.";
482
+ }
483
+ if (pressure.fraction <= TIGHT_LIMIT_FRACTION) {
484
+ const headroom =
485
+ pressure.headroomTokens !== undefined ? ` (${formatNumber(pressure.headroomTokens)} tokens)` : "";
486
+ return `Context headroom is ${percent}${headroom}; compact or start a fresh session before adding large content, preserving user requirements and unresolved work first.`;
487
+ }
488
+ return `Context headroom is ${percent}; keep additions small and consider compacting soon, preserving user requirements and unresolved work first.`;
489
+ }
490
+
491
+ const label = `reported provider window "${pressure.label}"`;
492
+ const across = snapshotCount > 1 ? " across reported account snapshots (active account unknown)" : "";
493
+ if (pressure.exhausted) {
494
+ const subject =
495
+ snapshotCount > 1
496
+ ? `A reported account snapshot has an exhausted provider window "${pressure.label}"`
497
+ : `The ${label} is exhausted`;
498
+ return `${subject}; stop non-essential provider calls until a reset is observed. Do not assume a reset restored quota.`;
499
+ }
500
+ if (pressure.resetsAt !== undefined) {
501
+ const untilReset = pressure.resetsAt - now;
502
+ if (untilReset > 0 && untilReset <= 15 * 60_000) {
503
+ return `The tightest ${label} has ${percent} left and a reported reset in ${formatDuration(untilReset)}; prefer short work and re-check after the reset rather than assuming it succeeded.`;
504
+ }
505
+ }
506
+ if (pressure.fraction <= TIGHT_LIMIT_FRACTION) {
507
+ return `The tightest ${label} has ${percent} left${across}; prioritize required work, defer optional or large calls, and do not assume more quota than reported. Model/account switching is the operator's decision.`;
508
+ }
509
+ return `${label[0]!.toUpperCase()}${label.slice(1)} has ${percent} left${across}; budget remaining calls and prefer required work.`;
510
+ }
511
+
512
+ function buildAdvice(
513
+ pressures: readonly UsagePressure[],
514
+ contextKnown: boolean,
515
+ providerKnown: boolean,
516
+ snapshotCount: number,
517
+ now: number,
518
+ ): string {
519
+ if (!contextKnown && !providerKnown) {
520
+ return "Advice: No current provider-quota or context headroom is known; do not assume that missing, stale, or past-reset data restores allowance.";
521
+ }
522
+
523
+ const sorted = [...pressures].sort((left, right) => left.fraction - right.fraction);
524
+ const context = sorted.find(pressure => pressure.source === "context");
525
+ const provider = sorted.find(pressure => pressure.source === "provider");
526
+ const selected = [context, provider]
527
+ .filter((pressure): pressure is UsagePressure => pressure !== undefined)
528
+ .sort((left, right) => left.fraction - right.fraction);
529
+ const clauses: string[] = [];
530
+
531
+ const tight = selected.filter(pressure => pressure.fraction <= NEAR_LIMIT_FRACTION);
532
+ if (tight.length === 0 && selected.length > 0) {
533
+ const tightest = selected[0]!;
534
+ const qualifier =
535
+ tightest.source === "provider" && snapshotCount > 1
536
+ ? " across reported account snapshots (active account unknown)"
537
+ : "";
538
+ clauses.push(
539
+ `Known limits have headroom (tightest: ${pressureLabel(tightest)} at ${formatPercent(tightest.fraction)} left${qualifier}); no immediate usage pressure.`,
540
+ );
541
+ } else {
542
+ for (const pressure of tight) clauses.push(describePressureAdvice(pressure, now, snapshotCount));
543
+ for (const pressure of selected.filter(candidate => candidate.fraction > NEAR_LIMIT_FRACTION)) {
544
+ const label = pressureLabel(pressure);
545
+ const qualifier =
546
+ pressure.source === "provider" && snapshotCount > 1 ? " in one reported account snapshot" : "";
547
+ clauses.push(
548
+ `${label[0]!.toUpperCase()}${label.slice(1)} still has ${formatPercent(pressure.fraction)} headroom${qualifier}.`,
549
+ );
550
+ }
551
+ }
552
+
553
+ if (!providerKnown && contextKnown) {
554
+ clauses.push("Provider quota for the current model is unknown; do not assume provider headroom.");
555
+ }
556
+ if (!contextKnown && providerKnown) {
557
+ clauses.push("Context headroom is unknown; do not assume context space.");
558
+ }
559
+ return `Advice: ${clauses.join(" ")}`;
560
+ }
561
+
562
+ function readModel(ctx: ExtensionContext): { label: string; provider: string; modelId: string } {
563
+ const rawModel = ctx.model;
564
+ const provider = typeof rawModel?.provider === "string" ? rawModel.provider.trim() : "";
565
+ const modelId = typeof rawModel?.id === "string" ? rawModel.id.trim() : "";
566
+ const providerText = cleanText(provider, "unknown provider");
567
+ const modelText = cleanText(modelId, "unknown model");
568
+
569
+ if (provider && modelId) return { label: `${providerText}/${modelText}`, provider, modelId };
570
+ if (provider) return { label: `${providerText} (model id unknown)`, provider, modelId };
571
+ if (modelId) return { label: `${modelText} (provider unknown)`, provider, modelId };
572
+ return { label: "unknown (no active model)", provider, modelId };
573
+ }
574
+
575
+ async function readProviderQuota(
576
+ ctx: ExtensionContext,
577
+ provider: string,
578
+ modelId: string,
579
+ now: number,
580
+ ): Promise<{ lines: string[]; candidates: UsagePressure[]; snapshotCount: number }> {
581
+ const providerLabel = cleanText(provider, "unknown provider");
582
+ if (!provider || !modelId) {
583
+ return {
584
+ lines: ["Provider quota: unknown (no active model/provider; no provider read attempted)"],
585
+ candidates: [],
586
+ snapshotCount: 0,
587
+ };
588
+ }
589
+
590
+ let rawReports: UsageReport[] | null = null;
591
+ try {
592
+ const registry = ctx.modelRegistry;
593
+ const usage = registry?.authStorage?.usage;
594
+ if (!usage || typeof usage.reports !== "function") {
595
+ return {
596
+ lines: [`Provider quota (${providerLabel}): unknown (host usage API unavailable)`],
597
+ candidates: [],
598
+ snapshotCount: 0,
599
+ };
600
+ }
601
+
602
+ const options: {
603
+ provider: string;
604
+ baseUrlResolver?: (provider: string) => string | undefined;
605
+ } = { provider };
606
+ if (registry && typeof registry.getProviderBaseUrl === "function") {
607
+ const getBaseUrl = registry.getProviderBaseUrl.bind(registry);
608
+ options.baseUrlResolver = candidateProvider => {
609
+ try {
610
+ return getBaseUrl(candidateProvider);
611
+ } catch {
612
+ return undefined;
613
+ }
614
+ };
615
+ }
616
+ rawReports = await usage.reports(options);
617
+ } catch {
618
+ return {
619
+ lines: [`Provider quota (${providerLabel}): unknown (read failed; error details withheld)`],
620
+ candidates: [],
621
+ snapshotCount: 0,
622
+ };
623
+ }
624
+
625
+ if (rawReports === null) {
626
+ return {
627
+ lines: [`Provider quota (${providerLabel}): unknown (host returned no current report)`],
628
+ candidates: [],
629
+ snapshotCount: 0,
630
+ };
631
+ }
632
+ if (!Array.isArray(rawReports)) {
633
+ return {
634
+ lines: [`Provider quota (${providerLabel}): unknown (host returned an invalid report)`],
635
+ candidates: [],
636
+ snapshotCount: 0,
637
+ };
638
+ }
639
+
640
+ const reports = rawReports.filter(
641
+ (report): report is UsageReport =>
642
+ report !== null && typeof report === "object" && report.provider === provider,
643
+ );
644
+ if (reports.length === 0) {
645
+ return {
646
+ lines: [`Provider quota (${providerLabel}): unknown (no account snapshots reported)`],
647
+ candidates: [],
648
+ snapshotCount: 0,
649
+ };
650
+ }
651
+
652
+ const sorted = [...reports].sort(
653
+ (left, right) => (timestampValue(right.fetchedAt) ?? 0) - (timestampValue(left.fetchedAt) ?? 0),
654
+ );
655
+ const lines = [
656
+ `Provider quota (${providerLabel}), ${formatNumber(sorted.length)} account snapshot${sorted.length === 1 ? "" : "s"}; active account unknown; values not summed:`,
657
+ ];
658
+ const candidates: UsagePressure[] = [];
659
+ for (let index = 0; index < sorted.length; index += 1) {
660
+ const snapshot = describeSnapshot(sorted[index]!, index + 1, sorted.length, provider, modelId, now);
661
+ lines.push(snapshot.line);
662
+ candidates.push(...snapshot.candidates);
663
+ }
664
+
665
+ return { lines, candidates, snapshotCount: sorted.length };
666
+ }
667
+
668
+ /**
669
+ * Build compact, factual usage knowledge for the current model context.
670
+ *
671
+ * Reads only public host surfaces: context usage, session usage statistics, and
672
+ * cached provider quota reports. Provider quota is treated as a per-account
673
+ * snapshot, not active-account truth; snapshots older than five minutes or
674
+ * past their reset window are reported as unknown rather than as current
675
+ * allowance. No state is persisted and no automatic model/account change is
676
+ * suggested.
677
+ */
678
+ export async function getUsageKnowledge(ctx: ExtensionContext, nowInput?: number): Promise<string> {
679
+ const now =
680
+ typeof nowInput === "number" && Number.isFinite(nowInput) && nowInput > 0 ? nowInput : Date.now();
681
+ const model = readModel(ctx);
682
+ const context = readContextKnowledge(ctx);
683
+ const session = readSessionKnowledge(ctx);
684
+ const quota = await readProviderQuota(ctx, model.provider, model.modelId, now);
685
+
686
+ const contextKnown = context.remainingFraction !== undefined;
687
+ const providerKnown = quota.candidates.length > 0;
688
+ const contextPressure: UsagePressure[] =
689
+ context.remainingFraction !== undefined
690
+ ? [
691
+ {
692
+ source: "context",
693
+ fraction: context.remainingFraction,
694
+ label: "context",
695
+ exhausted: context.remainingFraction === 0,
696
+ headroomTokens: context.headroomTokens,
697
+ },
698
+ ]
699
+ : [];
700
+ const pressures = [...contextPressure, ...quota.candidates];
701
+
702
+ const scope =
703
+ "Scope: Provider quota rows are per-account snapshots from the host usage cache; the active account is unknown, so they are not necessarily this session's account, and values are never summed. Model-specific windows for other models are omitted; shared and account-wide windows are retained. Session token/cost counters are local to this session, not provider quota; cost includes subagent spend. Quota data over 5 minutes old or past a window reset is reported as unknown current allowance.";
704
+
705
+ return [
706
+ "Usage awareness (session-scoped, read-only)",
707
+ `Model: ${model.label}`,
708
+ session.line,
709
+ context.line,
710
+ ...quota.lines,
711
+ scope,
712
+ buildAdvice(pressures, contextKnown, providerKnown, quota.snapshotCount, now),
713
+ ].join("\n");
714
+ }