pi-dent-agent 0.2.5 → 0.2.6

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.
@@ -54,14 +54,19 @@ export interface AdapterDependencies {
54
54
  }
55
55
 
56
56
  /**
57
- * One request under Section 4: method `GET`, `accept: application/json` and
58
- * `user-agent: pi-dent-purse` added by the transport. The allowlist is bound into the transport.
57
+ * One request under Section 4: `accept: application/json` and `user-agent: pi-dent-purse`
58
+ * added by the transport; method `GET` unless the request names `POST` with its spec's
59
+ * verbatim `body`. The allowlist is bound into the transport.
59
60
  */
60
61
  export interface TransportRequest {
61
62
  /** An `https:` URL without userinfo whose origin is in the bound allowlist, else `internal`. */
62
63
  url: string;
63
64
  /** Only the headers the adapter spec lists (Sections 3–4). */
64
65
  headers?: Record<string, string>;
66
+ /** `POST` only, and only where the adapter spec states the request's body verbatim. */
67
+ method?: "POST";
68
+ /** The verbatim body of a `POST` request; a body without `method` is refused. */
69
+ body?: string;
65
70
  /** Body cap in bytes of a 2xx body (Section 4). */
66
71
  bodyCap: number;
67
72
  /** The refresh's abort signal: aborted means `deadline`; the 8-second expiry is `timeout`. */
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The Antigravity adapter (specs/adapter-antigravity.md): the Cloud Code Assist quota summary,
3
+ * plan, and credits read with the Google account's OAuth credential. The module performs no
4
+ * I/O; transport, credentials, and clock arrive as dependencies (adapter-contract.md Section
5
+ * 2). `run` never rejects.
6
+ */
7
+
8
+ import type { Adapter, AdapterDependencies, InventoryModel } from "../adapter.ts";
9
+ import {
10
+ cleanVendorString,
11
+ finiteNumber,
12
+ type AdapterFailure,
13
+ type AdapterResult,
14
+ type Facet,
15
+ type LimitWindowCapture,
16
+ } from "../state.ts";
17
+
18
+ /** Provider origin and host allowlist (Section 1). */
19
+ const PROVIDER_ORIGIN = "https://daily-cloudcode-pa.googleapis.com";
20
+ const HOST_ALLOWLIST: readonly string[] = [
21
+ PROVIDER_ORIGIN,
22
+ "https://daily-cloudcode-pa.sandbox.googleapis.com",
23
+ "https://cloudcode-pa.googleapis.com",
24
+ ];
25
+
26
+ /** The usage endpoints (Sections 3–4). */
27
+ const QUOTA_URL = `${PROVIDER_ORIGIN}/v1internal:retrieveUserQuotaSummary`;
28
+ const ASSIST_URL = `${PROVIDER_ORIGIN}/v1internal:loadCodeAssist`;
29
+
30
+ /** The verbatim request bodies and user agent (Sections 3–4). */
31
+ const QUOTA_BODY = "{}";
32
+ const ASSIST_BODY =
33
+ '{"metadata":{"ideType":"ANTIGRAVITY","platform":"PLATFORM_UNSPECIFIED","pluginType":"GEMINI"}}';
34
+ const USER_AGENT =
35
+ "antigravity/cli/1.5.5 (aidev_client; os_type=linux; arch=amd64; cl=982146307; auth_method=consumer)";
36
+
37
+ /** Body cap, 1 MiB (Section 1). */
38
+ const BODY_CAP = 1024 * 1024;
39
+
40
+ /** The credential the host stores for the provider (Section 2). */
41
+ interface AntigravityCredential {
42
+ token: string;
43
+ projectId: string;
44
+ }
45
+
46
+ const TOKEN_PATTERN = /^[\x21-\x7e]+$/u;
47
+
48
+ /** The credential of the `apiKey` blob, or `null` when it is not one (Section 2). */
49
+ function parseCredential(apiKey: string): AntigravityCredential | null {
50
+ let parsed: unknown;
51
+ try {
52
+ parsed = JSON.parse(apiKey);
53
+ } catch {
54
+ return null;
55
+ }
56
+ const object = asRecord(parsed);
57
+ if (object === null) return null;
58
+ const token = object["token"];
59
+ const projectId = object["projectId"];
60
+ if (typeof token !== "string" || !TOKEN_PATTERN.test(token)) return null;
61
+ if (typeof projectId !== "string" || !TOKEN_PATTERN.test(projectId)) return null;
62
+ return { token, projectId };
63
+ }
64
+
65
+ /** A JSON object, else `null` (untrusted vendor data). */
66
+ function asRecord(value: unknown): Record<string, unknown> | null {
67
+ return typeof value === "object" && value !== null && !Array.isArray(value)
68
+ ? Object.fromEntries(Object.entries(value))
69
+ : null;
70
+ }
71
+
72
+ /** The string at `key` of a JSON object, else `null` (untrusted vendor data). */
73
+ function stringAt(object: Record<string, unknown>, key: string): string | null {
74
+ const value = object[key];
75
+ return typeof value === "string" ? value : null;
76
+ }
77
+
78
+ /** The array at `key` of a JSON object, else `null` (untrusted vendor data). */
79
+ function arrayAt(object: Record<string, unknown>, key: string): readonly unknown[] | null {
80
+ const value = object[key];
81
+ return Array.isArray(value) ? value : null;
82
+ }
83
+
84
+ /** The epoch milliseconds of an RFC 3339 date-time, else `null` (Section 3). */
85
+ function epochOf(value: unknown): number | null {
86
+ if (typeof value !== "string") return null;
87
+ const ms = Date.parse(value);
88
+ return Number.isFinite(ms) ? ms : null;
89
+ }
90
+
91
+ /** One response: the object body, or the failure that replaces it. */
92
+ interface Response {
93
+ body: Record<string, unknown> | null;
94
+ failure?: AdapterFailure;
95
+ }
96
+
97
+ async function post(
98
+ deps: AdapterDependencies,
99
+ url: string,
100
+ token: string,
101
+ body: string,
102
+ signal: AbortSignal,
103
+ ): Promise<Response> {
104
+ const outcome = await deps.transport({
105
+ url,
106
+ method: "POST",
107
+ headers: {
108
+ authorization: `Bearer ${token}`,
109
+ "content-type": "application/json",
110
+ "user-agent": USER_AGENT,
111
+ },
112
+ body,
113
+ bodyCap: BODY_CAP,
114
+ signal,
115
+ });
116
+ if ("reason" in outcome) {
117
+ return {
118
+ body: null,
119
+ failure:
120
+ outcome.retryAfter === undefined
121
+ ? { reason: outcome.reason }
122
+ : { reason: outcome.reason, retryAfter: outcome.retryAfter },
123
+ };
124
+ }
125
+ let parsed: unknown;
126
+ try {
127
+ parsed = JSON.parse(outcome.body);
128
+ } catch {
129
+ return { body: null, failure: { reason: "bad-response" } };
130
+ }
131
+ const object = asRecord(parsed);
132
+ return object === null ? { body: null, failure: { reason: "bad-response" } } : { body: object };
133
+ }
134
+
135
+ const FIVE_HOUR_SECONDS = 18000;
136
+ const WEEKLY_SECONDS = 604800;
137
+
138
+ interface GroupScope {
139
+ tag: string | null;
140
+ models: string[] | null;
141
+ }
142
+
143
+ /** Derives the compact group tag and matching inventory models from `group.displayName` (Section 3). */
144
+ function groupScope(
145
+ rawDisplayName: string | null,
146
+ inventory: readonly InventoryModel[],
147
+ ): GroupScope {
148
+ const cleaned = cleanVendorString(rawDisplayName);
149
+ if (cleaned === null) return { tag: null, models: null };
150
+ const stripped = cleaned
151
+ .toLowerCase()
152
+ .replace(/\s+models?$/u, "")
153
+ .trim();
154
+ const families = stripped
155
+ .split(/\s+and\s+/u)
156
+ .map((part) => part.trim())
157
+ .filter((part) => part !== "");
158
+ if (families.length === 0) return { tag: null, models: null };
159
+ const tag = families.join("/");
160
+ const needles = families.map((family) => family.replace(/\s+/gu, "-"));
161
+ const matched = inventory
162
+ .filter((model) => {
163
+ const lower = model.id.toLowerCase();
164
+ return needles.some((needle) => lower.includes(needle));
165
+ })
166
+ .map((model) => model.id);
167
+ return { tag, models: matched };
168
+ }
169
+
170
+ /** Recognizes 5h and 7d durations from a bucket's cleaned display name (Section 3). */
171
+ function bucketDuration(
172
+ displayName: string | null,
173
+ ): { token: "5h" | "7d"; seconds: number } | null {
174
+ if (displayName === null) return null;
175
+ const lower = displayName.toLowerCase();
176
+ if (
177
+ lower.includes("five hour") ||
178
+ lower.includes("5 hour") ||
179
+ lower.includes("5-hour") ||
180
+ /(?:^|[^a-z0-9])5h(?:$|[^a-z0-9])/u.test(lower)
181
+ ) {
182
+ return { token: "5h", seconds: FIVE_HOUR_SECONDS };
183
+ }
184
+ if (
185
+ lower.includes("weekly") ||
186
+ lower.includes("seven day") ||
187
+ lower.includes("7 day") ||
188
+ lower.includes("7-day") ||
189
+ /(?:^|[^a-z0-9])7d(?:$|[^a-z0-9])/u.test(lower)
190
+ ) {
191
+ return { token: "7d", seconds: WEEKLY_SECONDS };
192
+ }
193
+ return null;
194
+ }
195
+
196
+ /** The quota pools' windows (Section 3). */
197
+ function quotaWindows(
198
+ body: Record<string, unknown> | null,
199
+ inventory: readonly InventoryModel[],
200
+ ): LimitWindowCapture[] {
201
+ if (body === null) return [];
202
+ const windows = new Map<string, LimitWindowCapture>();
203
+ for (const group of arrayAt(body, "groups") ?? []) {
204
+ const groupObject = asRecord(group);
205
+ if (groupObject === null) continue;
206
+ const scope = groupScope(stringAt(groupObject, "displayName"), inventory);
207
+ for (const bucket of arrayAt(groupObject, "buckets") ?? []) {
208
+ const bucketObject = asRecord(bucket);
209
+ if (bucketObject === null) continue;
210
+ const bucketId = cleanVendorString(stringAt(bucketObject, "bucketId"));
211
+ const displayName = cleanVendorString(stringAt(bucketObject, "displayName"));
212
+ const fraction = finiteNumber(bucketObject["remainingFraction"]);
213
+ // A fraction outside [0, 1] carries no honest percentage (Section 3).
214
+ if (fraction === null || fraction < 0 || fraction > 1) continue;
215
+ const id = bucketId ?? displayName;
216
+ if (id === null || windows.has(id)) continue;
217
+ const duration = bucketDuration(displayName);
218
+ const label =
219
+ duration === null
220
+ ? (displayName ?? id)
221
+ : scope.tag === null
222
+ ? duration.token
223
+ : `${duration.token} ${scope.tag}`;
224
+ windows.set(id, {
225
+ id,
226
+ label,
227
+ unit: "percent",
228
+ used: null,
229
+ limit: null,
230
+ percent: Math.round((1 - fraction) * 1000) / 10,
231
+ resetsAt: epochOf(bucketObject["resetTime"]),
232
+ windowSeconds: duration === null ? null : duration.seconds,
233
+ models: scope.models,
234
+ source: "endpoint",
235
+ });
236
+ }
237
+ }
238
+ return [...windows.values()];
239
+ }
240
+
241
+ /** The plan name, first that applies (Section 4). */
242
+ function planName(body: Record<string, unknown> | null): string | null {
243
+ if (body === null) return null;
244
+ const paid = asRecord(body["paidTier"]);
245
+ const current = asRecord(body["currentTier"]);
246
+ const names = [
247
+ paid === null ? null : cleanVendorString(stringAt(paid, "name")),
248
+ paid === null ? null : cleanVendorString(stringAt(paid, "id")),
249
+ current === null ? null : cleanVendorString(stringAt(current, "name")),
250
+ current === null ? null : cleanVendorString(stringAt(current, "id")),
251
+ ];
252
+ return names.find((name) => name !== null) ?? null;
253
+ }
254
+
255
+ /** The credit windows of the first credits array present (Section 4). */
256
+ function creditWindows(body: Record<string, unknown> | null): LimitWindowCapture[] {
257
+ if (body === null) return [];
258
+ const paid = asRecord(body["paidTier"]);
259
+ const current = asRecord(body["currentTier"]);
260
+ const credits =
261
+ (paid === null ? null : arrayAt(paid, "availableCredits")) ??
262
+ (current === null ? null : arrayAt(current, "availableCredits")) ??
263
+ arrayAt(body, "availableCredits");
264
+ if (credits === null) return [];
265
+ const windows: LimitWindowCapture[] = [];
266
+ const seen = new Set<string>();
267
+ for (const credit of credits) {
268
+ const creditObject = asRecord(credit);
269
+ if (creditObject === null) continue;
270
+ const amount = finiteNumber(creditObject["creditAmount"]);
271
+ if (amount === null) continue;
272
+ const type = cleanVendorString(stringAt(creditObject, "creditType"));
273
+ const id = type === null ? "credits" : `credits:${type}`;
274
+ if (seen.has(id)) continue;
275
+ seen.add(id);
276
+ windows.push({
277
+ id,
278
+ label: "credits",
279
+ unit: "credits",
280
+ used: null,
281
+ limit: amount,
282
+ percent: null,
283
+ resetsAt: null,
284
+ windowSeconds: null,
285
+ models: null,
286
+ source: "endpoint",
287
+ });
288
+ }
289
+ return windows;
290
+ }
291
+
292
+ async function refresh(deps: AdapterDependencies, signal: AbortSignal): Promise<AdapterResult> {
293
+ const credentials = await deps.credentials();
294
+ if (credentials === undefined) return { reason: "no-credentials" };
295
+ if (!credentials.oauth) return { reason: "unsupported-auth" };
296
+ const credential = parseCredential(credentials.apiKey);
297
+ if (credential === null) return { reason: "unsupported-auth" };
298
+ const { token } = credential;
299
+
300
+ // Sections 3–4: the issue order, quota summary before plan.
301
+ const summary = await post(deps, QUOTA_URL, token, QUOTA_BODY, signal);
302
+ const assist = await post(deps, ASSIST_URL, token, ASSIST_BODY, signal);
303
+ const firstFailure = summary.failure ?? assist.failure;
304
+
305
+ let limits: Facet<LimitWindowCapture[]>;
306
+ if (summary.failure === undefined) {
307
+ const windows = [...quotaWindows(summary.body, deps.inventory), ...creditWindows(assist.body)];
308
+ limits =
309
+ windows.length === 0
310
+ ? { state: "unavailable", reason: "empty-response" }
311
+ : { state: "known", value: windows };
312
+ } else {
313
+ limits = { state: "unavailable", reason: summary.failure.reason };
314
+ }
315
+
316
+ let plan: Facet<string>;
317
+ if (assist.failure === undefined) {
318
+ const name = planName(assist.body);
319
+ plan =
320
+ name === null
321
+ ? { state: "unavailable", reason: "empty-response" }
322
+ : { state: "known", value: name };
323
+ } else {
324
+ plan = { state: "unavailable", reason: assist.failure.reason };
325
+ }
326
+
327
+ return firstFailure === undefined
328
+ ? { facets: { plan, limits } }
329
+ : { facets: { plan, limits }, firstFailure };
330
+ }
331
+
332
+ async function run(deps: AdapterDependencies, signal: AbortSignal): Promise<AdapterResult> {
333
+ try {
334
+ return await refresh(deps, signal);
335
+ } catch {
336
+ return { reason: "internal" };
337
+ }
338
+ }
339
+
340
+ export const antigravity: Adapter = {
341
+ id: "antigravity",
342
+ providerOrigin: PROVIDER_ORIGIN,
343
+ hostAllowlist: HOST_ALLOWLIST,
344
+ exposedFacets: ["plan", "limits"],
345
+ freshnessSeconds: 300,
346
+ run,
347
+ };
@@ -4,6 +4,7 @@
4
4
  */
5
5
 
6
6
  import type { Adapter } from "../adapter.ts";
7
+ import { antigravity } from "./antigravity.ts";
7
8
  import { amd } from "./amd.ts";
8
9
  import { anthropic } from "./anthropic.ts";
9
10
  import { deepseek } from "./deepseek.ts";
@@ -14,5 +15,8 @@ import { zai } from "./zai.ts";
14
15
 
15
16
  /** The adapters by provider id; pass to `createRefresher({ adapters: ADAPTERS })`. */
16
17
  export const ADAPTERS: ReadonlyMap<string, Adapter> = new Map(
17
- [amd, anthropic, deepseek, exa, google, openaiCodex, zai].map((adapter) => [adapter.id, adapter]),
18
+ [antigravity, amd, anthropic, deepseek, exa, google, openaiCodex, zai].map((adapter) => [
19
+ adapter.id,
20
+ adapter,
21
+ ]),
18
22
  );
@@ -149,7 +149,7 @@ async function readBody(response: Response, cap: number, signal: AbortSignal): P
149
149
  }
150
150
 
151
151
  /**
152
- * The transport (Section 4) bound to one adapter's host allowlist: one `GET`, the request
152
+ * The transport (Section 4) bound to one adapter's host allowlist: one request, the request
153
153
  * deadline, the body cap, and the status mapping; never a redirect, never a failure that
154
154
  * rejects.
155
155
  */
@@ -167,6 +167,12 @@ export function createTransport(
167
167
 
168
168
  const cap = request.bodyCap;
169
169
  if (!Number.isFinite(cap) || cap < 0) return failure("internal");
170
+ // Section 4: a body goes only with `POST`, and `POST` always carries one.
171
+ const method = request.method === undefined ? "GET" : request.method;
172
+ const requestBody = request.body;
173
+ if (method === "POST" ? typeof requestBody !== "string" : requestBody !== undefined) {
174
+ return failure("internal");
175
+ }
170
176
  if (request.signal.aborted) return failure("deadline");
171
177
 
172
178
  const controller = new AbortController();
@@ -188,20 +194,22 @@ export function createTransport(
188
194
  try {
189
195
  headers = new Headers(request.headers);
190
196
  headers.set("accept", ACCEPT_HEADER);
191
- headers.set("user-agent", USER_AGENT_HEADER);
197
+ if (!headers.has("user-agent")) headers.set("user-agent", USER_AGENT_HEADER);
192
198
  } catch {
193
199
  return failure("internal");
194
200
  }
195
201
 
202
+ const init: RequestInit = {
203
+ method,
204
+ headers,
205
+ // Never follow: a 3xx is the answer to report.
206
+ redirect: "manual",
207
+ signal: controller.signal,
208
+ };
209
+ if (requestBody !== undefined) init.body = requestBody;
196
210
  let response: Response;
197
211
  try {
198
- response = await fetchFunction(request.url, {
199
- method: "GET",
200
- headers,
201
- // Never follow: a 3xx is the answer to report.
202
- redirect: "manual",
203
- signal: controller.signal,
204
- });
212
+ response = await fetchFunction(request.url, init);
205
213
  } catch {
206
214
  return failure(cause ?? "network");
207
215
  }
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "pi-dent-purse",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "A pi extension that collects per-provider LLM billing state and serves it to other extensions and the user",
5
5
  "keywords": [
6
6
  "billing",
7
7
  "pi-extension",
8
8
  "pi-package"
9
9
  ],
10
- "license": "MIT",
11
- "author": "Chris B <dralban68@protonmail.com>",
12
10
  "homepage": "https://github.com/dralban68/pi-dent-purse#readme",
13
11
  "bugs": "https://github.com/dralban68/pi-dent-purse/issues",
12
+ "license": "MIT",
13
+ "author": "Chris B <dralban68@protonmail.com>",
14
14
  "repository": {
15
15
  "type": "git",
16
16
  "url": "git+https://github.com/dralban68/pi-dent-purse.git"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-dent-agent",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "A generic coding agent as a pi extension: Bash, Task, Agent, Fleet, Script, Search, Markdown and more tools, with billing and terms extensions bundled",
5
5
  "keywords": [
6
6
  "coding-agent",
@@ -35,7 +35,7 @@
35
35
  "jszip": "^3.10.2",
36
36
  "pi-anthropic-oauth": "0.3.9",
37
37
  "pi-dent-markdown": "0.1.0",
38
- "pi-dent-purse": "0.1.0",
38
+ "pi-dent-purse": "0.2.0",
39
39
  "pi-dent-terms": "0.1.0",
40
40
  "pi-mcp-adapter": "7.0.1",
41
41
  "pi-web-access": "0.47.0",