pi-dent-purse 0.2.0 → 0.2.2

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.
@@ -1,7 +1,7 @@
1
1
  /**
2
- * The Exa adapter (specs/adapter-exa.md): the team's credits balance (Section 2) and the spend
3
- * of its API keys over the last 30 days (Section 3), read with an Exa team service key. It is a
4
- * tool provider (adapter-contract.md Section 1): no provider origin, credential from the
2
+ * The Exa adapter (specs/adapter-exa.md): the team's credits balance (specs/adapter-exa.md#balance) and the spend
3
+ * of its API keys over the last 30 days (specs/adapter-exa.md#limits), read with an Exa team service key. It is a
4
+ * tool provider (specs/adapter-contract.md#adapters): no provider origin, credential from the
5
5
  * `PURSE_EXA_SERVICE_KEY` environment variable. The adapter performs no I/O of its own: every
6
6
  * request goes through the injected transport, and `run` never rejects.
7
7
  */
@@ -21,34 +21,34 @@ import {
21
21
  type LimitWindowCapture,
22
22
  } from "../state.ts";
23
23
 
24
- /** The credential variable (Section 1); config-file.md Section 3 owns its name. */
24
+ /** The credential variable (specs/adapter-exa.md#constants); specs/config-file.md#environment owns its name. */
25
25
  const CREDENTIAL_VARIABLE = "PURSE_EXA_SERVICE_KEY";
26
26
 
27
- /** The only origin the adapter contacts (Section 1). */
27
+ /** The only origin the adapter contacts (specs/adapter-exa.md#constants). */
28
28
  const ADMIN_ORIGIN = "https://admin-api.exa.ai";
29
29
 
30
- /** The credits and key list endpoints (Sections 2–3). */
30
+ /** The credits and key list endpoints (specs/adapter-exa.md#balance, specs/adapter-exa.md#limits). */
31
31
  const CREDITS_URL = `${ADMIN_ORIGIN}/team-management/credits`;
32
32
  const KEYS_URL = `${ADMIN_ORIGIN}/team-management/api-keys`;
33
33
 
34
- /** Body caps in bytes, one per endpoint (Section 1). */
34
+ /** Body caps in bytes, one per endpoint (specs/adapter-exa.md#constants). */
35
35
  const CREDITS_BODY_CAP = 16 * 1024;
36
36
  const KEYS_BODY_CAP = 256 * 1024;
37
37
  const USAGE_BODY_CAP = 64 * 1024;
38
38
 
39
- /** Freshness period, 900 seconds (Section 1). */
39
+ /** Freshness period, 900 seconds (specs/adapter-exa.md#constants). */
40
40
  const FRESHNESS_SECONDS = 900;
41
41
 
42
- /** The spend window, 30 days in seconds (Section 3). */
42
+ /** The spend window, 30 days in seconds (specs/adapter-exa.md#limits). */
43
43
  const SPEND_WINDOW_SECONDS = 2_592_000;
44
44
 
45
- /** Most elements the key list may hold (Section 3). */
45
+ /** Most elements the key list may hold (specs/adapter-exa.md#limits). */
46
46
  const MAX_KEYS = 32;
47
47
 
48
- /** Most key usage requests in flight at a time (Section 3). */
48
+ /** Most key usage requests in flight at a time (specs/adapter-exa.md#limits). */
49
49
  const MAX_IN_FLIGHT = 4;
50
50
 
51
- /** A `publicId` as the vendor sends it (Section 3). */
51
+ /** A `publicId` as the vendor sends it (specs/adapter-exa.md#limits). */
52
52
  const PUBLIC_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
53
53
 
54
54
  /** A JSON object, excluding `null` and arrays. */
@@ -61,7 +61,7 @@ function arrayOf(value: unknown): readonly unknown[] | null {
61
61
  return Array.isArray(value) ? value : null;
62
62
  }
63
63
 
64
- /** A body that is a JSON object, else `null` (Section 1). */
64
+ /** A body that is a JSON object, else `null` (specs/adapter-exa.md#constants). */
65
65
  function parseObject(body: string): Record<string, unknown> | null {
66
66
  let parsed: unknown;
67
67
  try {
@@ -72,14 +72,14 @@ function parseObject(body: string): Record<string, unknown> | null {
72
72
  return isRecord(parsed) ? parsed : null;
73
73
  }
74
74
 
75
- /** A transport failure as a result failure (adapter-contract.md Section 2). */
75
+ /** A transport failure as a result failure (specs/adapter-contract.md#boundary). */
76
76
  function failureOf(failure: TransportFailure): AdapterFailure {
77
77
  return failure.retryAfter === undefined
78
78
  ? { reason: failure.reason }
79
79
  : { reason: failure.reason, retryAfter: failure.retryAfter };
80
80
  }
81
81
 
82
- /** One GET of Sections 2–3, carrying only the credential header (Section 1). */
82
+ /** One GET of specs/adapter-exa.md#balance, specs/adapter-exa.md#limits, carrying only the credential header (specs/adapter-exa.md#constants). */
83
83
  function get(
84
84
  deps: AdapterDependencies,
85
85
  url: string,
@@ -90,7 +90,7 @@ function get(
90
90
  return deps.transport({ url, headers: { "x-api-key": apiKey }, bodyCap, signal });
91
91
  }
92
92
 
93
- /** The credits body as one balance item, or the request's failure (Section 2). */
93
+ /** The credits body as one balance item, or the request's failure (specs/adapter-exa.md#balance). */
94
94
  function balanceOutcome(
95
95
  outcome: TransportOutcome,
96
96
  ): { item: BalanceItemCapture } | { failure: AdapterFailure } {
@@ -101,7 +101,7 @@ function balanceOutcome(
101
101
  return { item: { amount, currency: "USD", currencyAssumed: false, gatesUsage: true } };
102
102
  }
103
103
 
104
- /** The distinct `publicId`s of the key list in body order, or its failure (Section 3). */
104
+ /** The distinct `publicId`s of the key list in body order, or its failure (specs/adapter-exa.md#limits). */
105
105
  function keyListOutcome(
106
106
  outcome: TransportOutcome,
107
107
  ): { publicIds: string[] } | { failure: AdapterFailure } {
@@ -124,7 +124,7 @@ function keyListOutcome(
124
124
  return { publicIds };
125
125
  }
126
126
 
127
- /** A usage body's `total_cost_usd`, or the request's failure (Section 3). */
127
+ /** A usage body's `total_cost_usd`, or the request's failure (specs/adapter-exa.md#limits). */
128
128
  function usageOutcome(outcome: TransportOutcome): { cost: number } | { failure: AdapterFailure } {
129
129
  if ("reason" in outcome) return { failure: failureOf(outcome) };
130
130
  const body = parseObject(outcome.body);
@@ -133,7 +133,7 @@ function usageOutcome(outcome: TransportOutcome): { cost: number } | { failure:
133
133
  return { cost };
134
134
  }
135
135
 
136
- /** `epochMs` as `YYYY-MM-DDTHH:MM:SSZ` in UTC, seconds rounded down (Section 3). */
136
+ /** `epochMs` as `YYYY-MM-DDTHH:MM:SSZ` in UTC, seconds rounded down (specs/adapter-exa.md#limits). */
137
137
  function rfc3339(epochMs: number): string {
138
138
  const time = new Date(epochMs);
139
139
  const pad = (value: number, width: number): string => String(value).padStart(width, "0");
@@ -148,12 +148,12 @@ function rfc3339(epochMs: number): string {
148
148
  return `${date}T${clock}Z`;
149
149
  }
150
150
 
151
- /** A sum of money rounded to two decimals (Section 3). */
151
+ /** A sum of money rounded to two decimals (specs/adapter-exa.md#limits). */
152
152
  function roundToCents(value: number): number {
153
153
  return Math.round(value * 100) / 100;
154
154
  }
155
155
 
156
- /** The single spend window (Section 3). */
156
+ /** The single spend window (specs/adapter-exa.md#limits). */
157
157
  function spendWindow(used: number): LimitWindowCapture {
158
158
  return {
159
159
  id: "spend-30d",
@@ -171,7 +171,7 @@ function spendWindow(used: number): LimitWindowCapture {
171
171
  }
172
172
 
173
173
  /**
174
- * The keys' spend over the window (Section 3): one usage request per public id, in key list
174
+ * The keys' spend over the window (specs/adapter-exa.md#limits): one usage request per public id, in key list
175
175
  * order, at most 4 in flight, and no request issued once one has failed. The failure returned
176
176
  * is the first in issue order; the cost is the sum rounded to two decimals.
177
177
  */
@@ -223,12 +223,12 @@ async function spend(
223
223
 
224
224
  /** One refresh: the credits and key list requests, then the key usage requests. */
225
225
  async function refresh(deps: AdapterDependencies, signal: AbortSignal): Promise<AdapterResult> {
226
- // Section 3: the window ends at the clock's time at the start of `run`.
226
+ // specs/adapter-exa.md#limits: the window ends at the clock's time at the start of `run`.
227
227
  const endMs = deps.clock();
228
228
  const end = rfc3339(endMs);
229
229
  const start = rfc3339(endMs - SPEND_WINDOW_SECONDS * 1000);
230
230
 
231
- // adapter-contract.md Section 3 checks ran before `run`; any credential is accepted.
231
+ // specs/adapter-contract.md#credentials checks ran before `run`; any credential is accepted.
232
232
  const credentials = await deps.credentials();
233
233
  if (credentials === undefined) return { reason: "no-credentials" };
234
234
  const apiKey = credentials.apiKey;
@@ -280,7 +280,7 @@ async function run(deps: AdapterDependencies, signal: AbortSignal): Promise<Adap
280
280
  }
281
281
 
282
282
  /**
283
- * The Exa adapter (Section 1): id `exa`, a tool provider with no provider origin, credential
283
+ * The Exa adapter (specs/adapter-exa.md#constants): id `exa`, a tool provider with no provider origin, credential
284
284
  * variable `PURSE_EXA_SERVICE_KEY`, host allowlist `https://admin-api.exa.ai`, freshness period
285
285
  * 900 seconds, exposed facets `balance` and `limits`.
286
286
  */
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * Google adapter (specs/adapter-google.md): the usage tier and the quota limit windows of the
3
- * Gemini API key's cloud project. Sections 2–6 run in order: access token from `gcloud`, cloud
3
+ * Gemini API key's cloud project. specs/adapter-google.md#access-token, specs/adapter-google.md#cloud-project, specs/adapter-google.md#quota-metadata, specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage run in order: access token from `gcloud`, cloud
4
4
  * project from configuration, store or the API Keys API, quota metadata from Cloud Quotas,
5
5
  * metric types and one limit series request per `/limit` type from Cloud Monitoring, one
6
6
  * daily usage request per family with a `day` window, and the estimated spend of a paid tier
7
- * from the month's token counts (Section 7).
7
+ * from the month's token counts (specs/adapter-google.md#estimated-spend).
8
8
  * Shared behavior is owned by specs/adapter-contract.md.
9
9
  *
10
10
  * The adapter performs no I/O itself: every request goes through `deps.transport` and every
@@ -25,23 +25,23 @@ import {
25
25
  type LimitWindowCapture,
26
26
  } from "../state.ts";
27
27
 
28
- /** Provider origin (Section 1): the Gemini API. */
28
+ /** Provider origin (specs/adapter-google.md#constants): the Gemini API. */
29
29
  const PROVIDER_ORIGIN = "https://generativelanguage.googleapis.com";
30
30
 
31
- /** Host origins the adapter may contact (Section 1). */
31
+ /** Host origins the adapter may contact (specs/adapter-google.md#constants). */
32
32
  const API_KEYS_ORIGIN = "https://apikeys.googleapis.com";
33
33
  const CLOUD_QUOTAS_ORIGIN = "https://cloudquotas.googleapis.com";
34
34
  const MONITORING_ORIGIN = "https://monitoring.googleapis.com";
35
35
  const HOST_ALLOWLIST: readonly string[] = [API_KEYS_ORIGIN, CLOUD_QUOTAS_ORIGIN, MONITORING_ORIGIN];
36
36
 
37
- /** Freshness period in seconds (Section 1). */
37
+ /** Freshness period in seconds (specs/adapter-google.md#constants). */
38
38
  const FRESHNESS_SECONDS = 300;
39
39
 
40
- /** Body cap in bytes of a 2xx response body (Section 1). */
40
+ /** Body cap in bytes of a 2xx response body (specs/adapter-google.md#constants). */
41
41
  const API_KEYS_BODY_CAP = 16 * 1024;
42
42
  const DEFAULT_BODY_CAP = 1024 * 1024;
43
43
 
44
- /** The one `gcloud` invocation (Section 2). */
44
+ /** The one `gcloud` invocation (specs/adapter-google.md#access-token). */
45
45
  const GCLOUD_COMMAND = "gcloud";
46
46
  const GCLOUD_ARGS: readonly string[] = [
47
47
  "auth",
@@ -52,10 +52,10 @@ const GCLOUD_ARGS: readonly string[] = [
52
52
  const GCLOUD_DEADLINE_MS = 10_000;
53
53
  const GCLOUD_OUTPUT_CAP = 8 * 1024;
54
54
 
55
- /** A trimmed access token: 1–4096 characters of the URL-safe token alphabet (Section 2). */
55
+ /** A trimmed access token: 1–4096 characters of the URL-safe token alphabet (specs/adapter-google.md#access-token). */
56
56
  const ACCESS_TOKEN_PATTERN = /^[A-Za-z0-9._~+/=-]{1,4096}$/;
57
57
 
58
- /** The quota service and the metric-type shape of its series (Sections 4–6). */
58
+ /** The quota service and the metric-type shape of its series (specs/adapter-google.md#quota-metadata, specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage). */
59
59
  const QUOTA_SERVICE = "generativelanguage.googleapis.com";
60
60
  const QUOTA_METRIC_PREFIX = `${QUOTA_SERVICE}/quota/`;
61
61
  const DESCRIPTOR_FILTER = `metric.type = starts_with("${QUOTA_METRIC_PREFIX}")`;
@@ -67,7 +67,7 @@ const USAGE_ALIGNER = "ALIGN_SUM";
67
67
  const LIMIT_LOOKBACK_MS = 25 * 3_600_000;
68
68
  const MIN_USAGE_ALIGNMENT_SECONDS = 60;
69
69
 
70
- /** The estimated spend window and its token metric types (Section 7). */
70
+ /** The estimated spend window and its token metric types (specs/adapter-google.md#estimated-spend). */
71
71
  const OUTPUT_TOKEN_TYPE = `${QUOTA_SERVICE}/generate_content_usage_output_token_count`;
72
72
  const USAGE_SUFFIX = "/usage";
73
73
  const INPUT_TOKEN_FAMILY = "input_token_count";
@@ -76,23 +76,23 @@ const SPEND_LABEL = "spend est/month";
76
76
  const SPEND_CURRENCY = "USD";
77
77
  const TOKENS_PER_RATE = 1_000_000;
78
78
 
79
- /** Paging and metadata caching (Section 4, "at most 5 pages"). */
79
+ /** Paging and metadata caching (specs/adapter-google.md#quota-metadata, "at most 5 pages"). */
80
80
  const MAX_PAGES = 5;
81
81
  const QUOTA_INFOS_PAGE_SIZE = 200;
82
82
  const METADATA_TTL_SECONDS = 86_400;
83
83
 
84
- /** The window lengths of the two known intervals and the unlimited sentinel (Sections 5–6). */
84
+ /** The window lengths of the two known intervals and the unlimited sentinel (specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage). */
85
85
  const DAY_SECONDS = 86_400;
86
86
  const MINUTE_SECONDS = 60;
87
87
  const UNLIMITED = -1;
88
88
 
89
- /** The cloud project's parent in a `keys:lookupKey` response (Section 3). */
89
+ /** The cloud project's parent in a `keys:lookupKey` response (specs/adapter-google.md#cloud-project). */
90
90
  const PROJECT_PARENT_PATTERN = /^projects\/([^/]+)\/locations\//;
91
91
 
92
- /** A cloud project id or number (Section 3; config-file.md Section 2, `project`). */
92
+ /** A cloud project id or number (specs/adapter-google.md#cloud-project; specs/config-file.md#keys, `project`). */
93
93
  const PROJECT_PATTERN = /^(?:[a-z][a-z0-9-]{4,28}[a-z0-9]|[0-9]{1,20})$/;
94
94
 
95
- /** The time zone of the day windows' midnight (Sections 5–6). */
95
+ /** The time zone of the day windows' midnight (specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage). */
96
96
  const LA_TIME_ZONE = "America/Los_Angeles";
97
97
 
98
98
  const FREE_TIER = "Free tier";
@@ -110,7 +110,7 @@ interface CivilDate {
110
110
  day: number;
111
111
  }
112
112
 
113
- /** The first failed request or command of one run (adapter-contract.md Section 2). */
113
+ /** The first failed request or command of one run (specs/adapter-contract.md#boundary). */
114
114
  interface Tally {
115
115
  firstFailure: AdapterFailure | undefined;
116
116
  }
@@ -125,7 +125,7 @@ interface RunContext {
125
125
  readonly tally: Tally;
126
126
  }
127
127
 
128
- /** Outcome of a step that either yields a value or is a whole failure (Sections 2–5). */
128
+ /** Outcome of a step that either yields a value or is a whole failure (specs/adapter-google.md#access-token, specs/adapter-google.md#cloud-project, specs/adapter-google.md#quota-metadata, specs/adapter-google.md#active-limits). */
129
129
  type StepResult<T> = { ok: true; value: T } | { ok: false; failure: AdapterFailure };
130
130
 
131
131
  /** Outcome of one request: the parsed body, or the failure plus the response's status. */
@@ -133,11 +133,11 @@ type RequestOutcome =
133
133
  | { ok: true; body: unknown }
134
134
  | { ok: false; failure: AdapterFailure; status: number | undefined };
135
135
 
136
- /** The `limit_name` and `model` labels a series carries (Section 5). */
136
+ /** The `limit_name` and `model` labels a series carries (specs/adapter-google.md#active-limits). */
137
137
  interface SeriesLabels {
138
- /** Cleaned, for the returned window (billing-state.md Section 7). */
138
+ /** Cleaned, for the returned window (specs/billing-state.md#content-restrictions). */
139
139
  quotaId: string | null;
140
- /** As sent by the vendor, compared with the quota metadata's `quotaId` (Section 5). */
140
+ /** As sent by the vendor, compared with the quota metadata's `quotaId` (specs/adapter-google.md#active-limits). */
141
141
  rawQuotaId: string | null;
142
142
  /** Cleaned; `null` when absent. */
143
143
  model: string | null;
@@ -145,13 +145,13 @@ interface SeriesLabels {
145
145
  rawModel: string | null;
146
146
  }
147
147
 
148
- /** One `timeSeries[]` object (Section 5). */
148
+ /** One `timeSeries[]` object (specs/adapter-google.md#active-limits). */
149
149
  interface QuotaSeries extends SeriesLabels {
150
150
  family: string;
151
151
  value: number;
152
152
  }
153
153
 
154
- /** A `day` window waiting for its `used` from Section 6. */
154
+ /** A `day` window waiting for its `used` from specs/adapter-google.md#daily-usage. */
155
155
  interface DayWindow {
156
156
  window: LimitWindowCapture;
157
157
  family: string;
@@ -161,11 +161,11 @@ interface DayWindow {
161
161
 
162
162
  /**
163
163
  * The quota metadata: the `refreshInterval` per `quotaId` (`null` when the vendor sent no
164
- * string), or `null` when the metadata is absent (Section 4).
164
+ * string), or `null` when the metadata is absent (specs/adapter-google.md#quota-metadata).
165
165
  */
166
166
  type QuotaMetadata = ReadonlyMap<string, string | null>;
167
167
 
168
- /** The spend cap in USD of a usage tier, `null` when it has no fixed one (Section 7). */
168
+ /** The spend cap in USD of a usage tier, `null` when it has no fixed one (specs/adapter-google.md#estimated-spend). */
169
169
  const SPEND_CAPS: Readonly<Record<string, number>> = { [PAID_TIER_1]: 250, [PAID_TIER_2]: 2000 };
170
170
 
171
171
  const LA_PARTS_FORMATTER = new Intl.DateTimeFormat("en-US", {
@@ -200,12 +200,12 @@ function stringAt(object: Record<string, unknown>, key: string): string | null {
200
200
  return typeof value === "string" ? value : null;
201
201
  }
202
202
 
203
- /** An RFC 3339 timestamp for a moment in time (Sections 5–6). */
203
+ /** An RFC 3339 timestamp for a moment in time (specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage). */
204
204
  function rfc3339(ms: number): string {
205
205
  return new Date(ms).toISOString();
206
206
  }
207
207
 
208
- /** The civil date and time of `ms` in `America/Los_Angeles` (Sections 5–6). */
208
+ /** The civil date and time of `ms` in `America/Los_Angeles` (specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage). */
209
209
  function losAngelesParts(ms: number): CivilDate & { hour: number; minute: number; second: number } {
210
210
  const parts = LA_PARTS_FORMATTER.formatToParts(ms);
211
211
  const read = (type: string): number => {
@@ -222,7 +222,7 @@ function losAngelesParts(ms: number): CivilDate & { hour: number; minute: number
222
222
  };
223
223
  }
224
224
 
225
- /** The instant of a calendar date's midnight in `America/Los_Angeles` (Sections 5–6). */
225
+ /** The instant of a calendar date's midnight in `America/Los_Angeles` (specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage). */
226
226
  function losAngelesMidnight(date: CivilDate): number {
227
227
  const target = Date.UTC(date.year, date.month - 1, date.day);
228
228
  let instant = target;
@@ -243,12 +243,12 @@ function losAngelesMidnight(date: CivilDate): number {
243
243
  return instant;
244
244
  }
245
245
 
246
- /** The latest midnight in `America/Los_Angeles` at or before `ms` (Section 6). */
246
+ /** The latest midnight in `America/Los_Angeles` at or before `ms` (specs/adapter-google.md#daily-usage). */
247
247
  function latestLosAngelesMidnight(ms: number): number {
248
248
  return losAngelesMidnight(losAngelesParts(ms));
249
249
  }
250
250
 
251
- /** The next midnight in `America/Los_Angeles` after `ms` (Section 5). */
251
+ /** The next midnight in `America/Los_Angeles` after `ms` (specs/adapter-google.md#active-limits). */
252
252
  function nextLosAngelesMidnight(ms: number): number {
253
253
  const date = losAngelesParts(ms);
254
254
  const tomorrow = new Date(Date.UTC(date.year, date.month - 1, date.day + 1));
@@ -259,13 +259,13 @@ function nextLosAngelesMidnight(ms: number): number {
259
259
  });
260
260
  }
261
261
 
262
- /** The latest month start in `America/Los_Angeles` at or before `ms` (Section 7). */
262
+ /** The latest month start in `America/Los_Angeles` at or before `ms` (specs/adapter-google.md#estimated-spend). */
263
263
  function latestLosAngelesMonthStart(ms: number): number {
264
264
  const date = losAngelesParts(ms);
265
265
  return losAngelesMidnight({ year: date.year, month: date.month, day: 1 });
266
266
  }
267
267
 
268
- /** The next month start in `America/Los_Angeles` after `ms` (Section 7). */
268
+ /** The next month start in `America/Los_Angeles` after `ms` (specs/adapter-google.md#estimated-spend). */
269
269
  function nextLosAngelesMonthStart(ms: number): number {
270
270
  const date = losAngelesParts(ms);
271
271
  const next = new Date(Date.UTC(date.year, date.month, 1));
@@ -276,17 +276,17 @@ function nextLosAngelesMonthStart(ms: number): number {
276
276
  });
277
277
  }
278
278
 
279
- /** The hex SHA-256 digest of a string (Section 3). */
279
+ /** The hex SHA-256 digest of a string (specs/adapter-google.md#cloud-project). */
280
280
  function sha256Hex(value: string): string {
281
281
  return createHash("sha256").update(value, "utf8").digest("hex");
282
282
  }
283
283
 
284
- /** The store key of the metric types of a cloud project (Section 5). */
284
+ /** The store key of the metric types of a cloud project (specs/adapter-google.md#active-limits). */
285
285
  function metricTypesKey(project: string): string {
286
286
  return `google-metric-types:${sha256Hex(project)}`;
287
287
  }
288
288
 
289
- /** The store key of the quota metadata of a cloud project (Section 4). */
289
+ /** The store key of the quota metadata of a cloud project (specs/adapter-google.md#quota-metadata). */
290
290
  function metadataKey(project: string): string {
291
291
  return `google-quota-metadata:${sha256Hex(project)}`;
292
292
  }
@@ -297,9 +297,9 @@ function record(tally: Tally, failure?: AdapterFailure): void {
297
297
  }
298
298
 
299
299
  /**
300
- * One `GET` with the access token (Sections 2, 4). The transport has already mapped the
300
+ * One `GET` with the access token (specs/adapter-google.md#access-token, specs/adapter-google.md#quota-metadata). The transport has already mapped the
301
301
  * status; `status` stays inside the adapter, and response text and other headers never leave
302
- * it (adapter-contract.md Section 4).
302
+ * it (specs/adapter-contract.md#transport).
303
303
  */
304
304
  async function requestJson(
305
305
  context: RunContext,
@@ -331,7 +331,7 @@ async function requestJson(
331
331
 
332
332
  /**
333
333
  * One paged `GET`: the body of each page, following `nextPageToken` as `pageToken` for at
334
- * most 5 pages (Section 1). A failed page fails the request.
334
+ * most 5 pages (specs/adapter-google.md#constants). A failed page fails the request.
335
335
  */
336
336
  async function requestPages(
337
337
  context: RunContext,
@@ -353,7 +353,7 @@ async function requestPages(
353
353
  return { ok: true, bodies };
354
354
  }
355
355
 
356
- /** Section 2: the access token, or the whole failure the command's outcome maps to. */
356
+ /** specs/adapter-google.md#access-token: the access token, or the whole failure the command's outcome maps to. */
357
357
  async function readAccessToken(
358
358
  commandRunner: CommandRunner,
359
359
  signal: AbortSignal,
@@ -393,7 +393,7 @@ async function readAccessToken(
393
393
  }
394
394
 
395
395
  /**
396
- * Section 3: the `project` configuration, else the store item keyed by the API key's digest,
396
+ * specs/adapter-google.md#cloud-project: the `project` configuration, else the store item keyed by the API key's digest,
397
397
  * else `keys:lookupKey`.
398
398
  */
399
399
  async function resolveProject(context: RunContext): Promise<StepResult<string>> {
@@ -427,7 +427,7 @@ async function resolveProject(context: RunContext): Promise<StepResult<string>>
427
427
  }
428
428
 
429
429
  /**
430
- * Section 4: the quota metadata, or `null` when absent. The result is cached for 86400
430
+ * specs/adapter-google.md#quota-metadata: the quota metadata, or `null` when absent. The result is cached for 86400
431
431
  * seconds; a failure is not a whole failure.
432
432
  */
433
433
  async function readQuotaMetadata(
@@ -473,13 +473,13 @@ function storedMetadata(value: unknown): QuotaMetadata | null {
473
473
  return metadata;
474
474
  }
475
475
 
476
- /** A label from `metric.labels` (Section 5). */
476
+ /** A label from `metric.labels` (specs/adapter-google.md#active-limits). */
477
477
  function metricLabel(item: Record<string, unknown>, name: string): string | null {
478
478
  const labels = asRecord(asRecord(item["metric"])?.["labels"]);
479
479
  return labels === null ? null : stringAt(labels, name);
480
480
  }
481
481
 
482
- /** The finite value of one Monitoring point, else `null` (Section 5). */
482
+ /** The finite value of one Monitoring point, else `null` (specs/adapter-google.md#active-limits). */
483
483
  function pointValue(point: unknown): number | null {
484
484
  const object = asRecord(point);
485
485
  if (object === null) return null;
@@ -493,7 +493,7 @@ function pointValue(point: unknown): number | null {
493
493
  return finiteNumber(value["doubleValue"]);
494
494
  }
495
495
 
496
- /** The labels of one series, cleaned for output (Section 5, billing-state.md Section 7). */
496
+ /** The labels of one series, cleaned for output (specs/adapter-google.md#active-limits, specs/billing-state.md#content-restrictions). */
497
497
  function seriesLabels(item: Record<string, unknown>): SeriesLabels {
498
498
  const rawQuotaId = metricLabel(item, "limit_name");
499
499
  const rawModel = metricLabel(item, "model");
@@ -505,7 +505,7 @@ function seriesLabels(item: Record<string, unknown>): SeriesLabels {
505
505
  };
506
506
  }
507
507
 
508
- /** Section 5: the metric types, from the store or the metric descriptors. */
508
+ /** specs/adapter-google.md#active-limits: the metric types, from the store or the metric descriptors. */
509
509
  async function readMetricTypes(
510
510
  context: RunContext,
511
511
  project: string,
@@ -534,14 +534,14 @@ async function readMetricTypes(
534
534
  return { ok: true, value: types };
535
535
  }
536
536
 
537
- /** The family of a limit type, else `null` (Section 5). */
537
+ /** The family of a limit type, else `null` (specs/adapter-google.md#active-limits). */
538
538
  function limitFamily(type: string): string | null {
539
539
  if (!type.startsWith(QUOTA_METRIC_PREFIX) || !type.endsWith(LIMIT_SUFFIX)) return null;
540
540
  const family = type.slice(QUOTA_METRIC_PREFIX.length, type.length - LIMIT_SUFFIX.length);
541
541
  return family === "" ? null : family;
542
542
  }
543
543
 
544
- /** The time-series request URL of one metric type (Sections 5–6). */
544
+ /** The time-series request URL of one metric type (specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage). */
545
545
  function timeSeriesUrl(
546
546
  project: string,
547
547
  type: string,
@@ -560,7 +560,7 @@ function timeSeriesUrl(
560
560
  }
561
561
 
562
562
  /**
563
- * Section 5: the valid series of one limit type's request, or its failure. A series needs a
563
+ * specs/adapter-google.md#active-limits: the valid series of one limit type's request, or its failure. A series needs a
564
564
  * quota id and a finite value.
565
565
  */
566
566
  async function readLimitSeries(
@@ -596,7 +596,7 @@ async function readLimitSeries(
596
596
  }
597
597
 
598
598
  /**
599
- * Section 5: the usage tier, from the families of the series that survived the value check.
599
+ * specs/adapter-google.md#active-limits: the usage tier, from the families of the series that survived the value check.
600
600
  */
601
601
  function usageTier(series: readonly QuotaSeries[]): string {
602
602
  const families = series.map((entry) => entry.family);
@@ -606,7 +606,7 @@ function usageTier(series: readonly QuotaSeries[]): string {
606
606
  return FREE_TIER;
607
607
  }
608
608
 
609
- /** Section 4: the interval a quota id resets in. */
609
+ /** specs/adapter-google.md#quota-metadata: the interval a quota id resets in. */
610
610
  function quotaInterval(quotaId: string, metadata: QuotaMetadata | null): QuotaInterval {
611
611
  if (metadata !== null && metadata.has(quotaId)) {
612
612
  const refreshInterval = metadata.get(quotaId);
@@ -619,28 +619,28 @@ function quotaInterval(quotaId: string, metadata: QuotaMetadata | null): QuotaIn
619
619
  return null;
620
620
  }
621
621
 
622
- /** The last part of a window's `label` (Section 5). */
622
+ /** The last part of a window's `label` (specs/adapter-google.md#active-limits). */
623
623
  function intervalLabel(interval: QuotaInterval): "day" | "min" | "?" {
624
624
  if (interval === "day") return "day";
625
625
  if (interval === "minute") return "min";
626
626
  return "?";
627
627
  }
628
628
 
629
- /** A window's `windowSeconds` (Section 5). */
629
+ /** A window's `windowSeconds` (specs/adapter-google.md#active-limits). */
630
630
  function windowSeconds(interval: QuotaInterval): number | null {
631
631
  if (interval === "day") return DAY_SECONDS;
632
632
  if (interval === "minute") return MINUTE_SECONDS;
633
633
  return null;
634
634
  }
635
635
 
636
- /** The key that pairs a usage series with a day window of its family (Section 6). */
636
+ /** The key that pairs a usage series with a day window of its family (specs/adapter-google.md#daily-usage). */
637
637
  function usageKey(quotaId: string, model: string | null): string {
638
638
  return JSON.stringify([quotaId, model]);
639
639
  }
640
640
 
641
641
  /**
642
- * Section 5: one window per remaining series with a value other than `-1`, and the `day`
643
- * windows that need their `used` from Section 6.
642
+ * specs/adapter-google.md#active-limits: one window per remaining series with a value other than `-1`, and the `day`
643
+ * windows that need their `used` from specs/adapter-google.md#daily-usage.
644
644
  */
645
645
  function buildWindows(
646
646
  series: readonly QuotaSeries[],
@@ -684,7 +684,7 @@ function buildWindows(
684
684
  }
685
685
 
686
686
  /**
687
- * Section 6: one request per family; fills each of the family's `day` windows' `used` with the
687
+ * specs/adapter-google.md#daily-usage: one request per family; fills each of the family's `day` windows' `used` with the
688
688
  * sum of its matching series' finite point values, `0` when the request succeeded without one.
689
689
  * A failure is not a whole failure.
690
690
  */
@@ -732,7 +732,7 @@ async function fillDailyUsage(
732
732
  );
733
733
  }
734
734
 
735
- /** The family of an input-token usage type of a paid tier, else `null` (Section 7). */
735
+ /** The family of an input-token usage type of a paid tier, else `null` (specs/adapter-google.md#estimated-spend). */
736
736
  function spendInputFamily(type: string): string | null {
737
737
  if (!type.startsWith(QUOTA_METRIC_PREFIX) || !type.endsWith(USAGE_SUFFIX)) return null;
738
738
  const family = type.slice(QUOTA_METRIC_PREFIX.length, type.length - USAGE_SUFFIX.length);
@@ -740,7 +740,7 @@ function spendInputFamily(type: string): string | null {
740
740
  }
741
741
 
742
742
  /**
743
- * Section 7: the series totals of one month-to-date request as `[quota id, model, total]`, or
743
+ * specs/adapter-google.md#estimated-spend: the series totals of one month-to-date request as `[quota id, model, total]`, or
744
744
  * `null` when the request failed. A series without a model is skipped.
745
745
  */
746
746
  async function readMonthTotals(
@@ -781,7 +781,7 @@ async function readMonthTotals(
781
781
  }
782
782
 
783
783
  /**
784
- * Section 7: the estimated spend window of a paid tier. `used` is `null` when a request
784
+ * specs/adapter-google.md#estimated-spend: the estimated spend window of a paid tier. `used` is `null` when a request
785
785
  * failed, a token-bearing model is outside the inventory, or a token-bearing rate is
786
786
  * unknown; a failure is not a whole failure.
787
787
  */
@@ -857,7 +857,7 @@ async function spendWindow(
857
857
  };
858
858
  }
859
859
 
860
- /** A successful run's result (adapter-contract.md Section 2). */
860
+ /** A successful run's result (specs/adapter-contract.md#boundary). */
861
861
  function successResult(tally: Tally, facets: CaptureFacets): AdapterResult {
862
862
  return {
863
863
  facets,
@@ -865,15 +865,15 @@ function successResult(tally: Tally, facets: CaptureFacets): AdapterResult {
865
865
  };
866
866
  }
867
867
 
868
- /** A facet that is `unavailable` with the spec's reason (Section 5). */
868
+ /** A facet that is `unavailable` with the spec's reason (specs/adapter-google.md#active-limits). */
869
869
  function unavailable(reason: "empty-response"): Facet<never> {
870
870
  return { state: "unavailable", reason };
871
871
  }
872
872
 
873
- /** Sections 2–7, in order. */
873
+ /** specs/adapter-google.md#access-token, specs/adapter-google.md#cloud-project, specs/adapter-google.md#quota-metadata, specs/adapter-google.md#active-limits, specs/adapter-google.md#daily-usage, specs/adapter-google.md#estimated-spend, in order. */
874
874
  async function runRefresh(deps: AdapterDependencies, signal: AbortSignal): Promise<AdapterResult> {
875
875
  const now = deps.clock();
876
- // adapter-contract.md Section 3 checks ran before `run`.
876
+ // specs/adapter-contract.md#credentials checks ran before `run`.
877
877
  const credentials = await deps.credentials();
878
878
  if (credentials === undefined) return { reason: "no-credentials" };
879
879
  const apiKey = credentials.apiKey;
@@ -891,7 +891,7 @@ async function runRefresh(deps: AdapterDependencies, signal: AbortSignal): Promi
891
891
  const metricTypes = await readMetricTypes(context, project.value);
892
892
  if (!metricTypes.ok) return metricTypes.failure;
893
893
 
894
- // Ascending by UTF-16 code units, each type once (Section 5).
894
+ // Ascending by UTF-16 code units, each type once (specs/adapter-google.md#active-limits).
895
895
  const limitTypes: [string, string][] = [];
896
896
  for (const type of [...new Set(metricTypes.value)].toSorted()) {
897
897
  const family = limitFamily(type);
@@ -939,7 +939,7 @@ async function runRefresh(deps: AdapterDependencies, signal: AbortSignal): Promi
939
939
  }
940
940
 
941
941
  /**
942
- * The Google adapter (Section 1): Gemini API key limits and usage tier through Google Cloud
942
+ * The Google adapter (specs/adapter-google.md#constants): Gemini API key limits and usage tier through Google Cloud
943
943
  * APIs, authorized by a `gcloud` access token. The transport and the command runner are the
944
944
  * only ways out; an unexpected exception is a whole failure with `internal`.
945
945
  */
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The header helpers the adapters share when they read the headers of inference responses
3
- * (adapter-anthropic.md Section 4, adapter-amd.md Section 2). No logic beyond parsing one value.
3
+ * (specs/adapter-anthropic.md#header-observations, specs/adapter-amd.md#header-observations). No logic beyond parsing one value.
4
4
  */
5
5
 
6
6
  import { finiteNumber } from "../state.ts";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The adapters of specs/adapter-contract.md Section 1, keyed by provider id. Every provider not
2
+ * The adapters of specs/adapter-contract.md#adapters, keyed by provider id. Every provider not
3
3
  * listed here has no adapter.
4
4
  */
5
5