pi-dent-agent 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -23,6 +23,7 @@ import { runFleetCommand } from "./lib/fleet-command.ts";
23
23
  import { recapRuntime } from "./lib/recap.ts";
24
24
  import { renderRecapEntry } from "./lib/recap-render.ts";
25
25
  import { appendPluginContext, renderPluginCommand } from "./lib/plugins.ts";
26
+ import { PluginUiController } from "./lib/plugin-ui.ts";
26
27
  import { type Diagnostic, errorMessage, isPlainObject } from "./lib/util.ts";
27
28
  import { rebuildInterruptedTasks } from "./lib/task-rebuild.ts";
28
29
  import {
@@ -282,6 +283,7 @@ export default function (pi: ExtensionAPI) {
282
283
  // Section 2).
283
284
  const questions = askUserRuntime();
284
285
  const recap = recapRuntime(boot.config, (data) => pi.appendEntry("pi-dent-recap", data));
286
+ const pluginUi = new PluginUiController(boot.pluginIndex);
285
287
  let taskWidget: TaskWidgetHandle | undefined;
286
288
  // Feeds for an RPC client (task.md Section 4.1, fleet-tool.md Section 6).
287
289
  let taskFeed: FeedHandle | undefined;
@@ -688,6 +690,11 @@ export default function (pi: ExtensionAPI) {
688
690
  }
689
691
  shutdownStep("ending owned tasks", () => engine.registry.end(), reportShutdown);
690
692
  shutdownStep("cancelling owned task runs", () => engine.cancelAll(), reportShutdown);
693
+ shutdownStep(
694
+ "cancelling plugin UI calls",
695
+ () => pluginUi.cancelAll("Session ended"),
696
+ reportShutdown,
697
+ );
691
698
  // The Search tool's continuations of catch-up end with the boot window
692
699
  // (search-tool.md Section 2.2).
693
700
  shutdownStep("stopping Search", () => search.stop(), reportShutdown);
@@ -899,6 +906,17 @@ export default function (pi: ExtensionAPI) {
899
906
  }
900
907
  }
901
908
 
909
+ pi.registerCommand("dent-ui", {
910
+ description: "Run and cancel plugin UI script calls",
911
+ handler: async (args, ctx) => {
912
+ if (ctx.mode !== "rpc") return;
913
+ pluginUi.handleCommand(args, {
914
+ cwd: ctx.cwd ?? currentHost?.cwd() ?? process.cwd(),
915
+ setWidget: (key, lines) => ctx.ui.setWidget(key, lines),
916
+ });
917
+ },
918
+ });
919
+
902
920
  pi.registerCommand("dent", {
903
921
  description: "Confirm the pi-dent extension is loaded",
904
922
  handler: async (_args, ctx) => {
@@ -0,0 +1,237 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { bundledAliases } from "./bundled.ts";
3
+ import type { PluginEntry } from "./plugins.ts";
4
+ import { resolvePluginScriptPath } from "./plugins.ts";
5
+ import { runScript, type ScriptRunHandle, type ScriptRunResult } from "./script-runner.ts";
6
+ import { errorCode, errorMessage, isPlainObject } from "./util.ts";
7
+
8
+ /**
9
+ * Plugin UI protocol controller (specs/plugin-ui.md): handles `/dent-ui run`
10
+ * and `/dent-ui cancel`, executes plugin scripts with `dent.ui.send` and no
11
+ * time limit or tool functions, and emits `message` and `reply` records on the
12
+ * `pi-dent-ui` widget feed.
13
+ */
14
+
15
+ export const PLUGIN_UI_WIDGET_KEY = "pi-dent-ui";
16
+ export const PLUGIN_UI_PROTOCOL = "ui/1";
17
+ export const PLUGIN_UI_PAYLOAD_CAP_BYTES = 262_144;
18
+
19
+ export interface PluginUiCommandContext {
20
+ cwd: string;
21
+ setWidget(key: string, lines: string[] | undefined): void;
22
+ extraEnv?: Record<string, string>;
23
+ }
24
+
25
+ interface ActiveUiCall {
26
+ handle: ScriptRunHandle;
27
+ cancelReason?: string;
28
+ }
29
+
30
+ function formatThrownError(
31
+ error: { name: string; message: string; stack: string } | undefined,
32
+ ): string {
33
+ if (!error) return "Script threw an error";
34
+ return error.message === "" ? error.name : `${error.name}: ${error.message}`;
35
+ }
36
+
37
+ export class PluginUiController {
38
+ private readonly pluginIndex: ReadonlyMap<string, PluginEntry>;
39
+ private readonly active = new Map<string, ActiveUiCall>();
40
+
41
+ constructor(pluginIndex: ReadonlyMap<string, PluginEntry>) {
42
+ this.pluginIndex = pluginIndex;
43
+ }
44
+
45
+ /** Number of UI calls currently executing. */
46
+ activeCount(): number {
47
+ return this.active.size;
48
+ }
49
+
50
+ /** Handle one `/dent-ui <args>` command (specs/plugin-ui.md Sections 1-3). */
51
+ handleCommand(args: string, ctx: PluginUiCommandContext): void {
52
+ const trimmed = args.trim();
53
+ if (trimmed === "") return;
54
+ const space = trimmed.search(/\s/);
55
+ const subcommand = space === -1 ? trimmed : trimmed.slice(0, space);
56
+ const payload = space === -1 ? "" : trimmed.slice(space).trim();
57
+ if (subcommand === "run") {
58
+ this.handleRun(payload, ctx);
59
+ } else if (subcommand === "cancel") {
60
+ this.handleCancel(payload);
61
+ }
62
+ }
63
+
64
+ /** Cancel every executing UI call (specs/plugin-ui.md Section 6). */
65
+ cancelAll(reason = "Session ended"): void {
66
+ for (const entry of this.active.values()) {
67
+ entry.cancelReason = reason;
68
+ entry.handle.cancel("killed");
69
+ }
70
+ }
71
+
72
+ private handleRun(rawJson: string, ctx: PluginUiCommandContext): void {
73
+ let parsed: unknown;
74
+ try {
75
+ parsed = JSON.parse(rawJson);
76
+ } catch {
77
+ return;
78
+ }
79
+ if (!isPlainObject(parsed) || typeof parsed.id !== "string" || parsed.id === "") {
80
+ return;
81
+ }
82
+ const id = parsed.id;
83
+ const emitLine = (line: string): void => {
84
+ try {
85
+ ctx.setWidget(PLUGIN_UI_WIDGET_KEY, [line]);
86
+ } catch {
87
+ // Widget update failures are unreported per specs/AGENTS.md.
88
+ }
89
+ };
90
+ const emitMessageJson = (dataJson: string): void => {
91
+ emitLine(
92
+ `{"piDent":${JSON.stringify(PLUGIN_UI_PROTOCOL)},"type":"message","id":${JSON.stringify(id)},"data":${dataJson}}`,
93
+ );
94
+ };
95
+ const emitReplyOkJson = (valueJson: string): void => {
96
+ emitLine(
97
+ `{"piDent":${JSON.stringify(PLUGIN_UI_PROTOCOL)},"type":"reply","id":${JSON.stringify(id)},"ok":true,"value":${valueJson}}`,
98
+ );
99
+ };
100
+ const emitReplyError = (error: string): void => {
101
+ emitLine(
102
+ JSON.stringify({
103
+ piDent: PLUGIN_UI_PROTOCOL,
104
+ type: "reply",
105
+ id,
106
+ ok: false,
107
+ error,
108
+ }),
109
+ );
110
+ };
111
+
112
+ if (this.active.has(id)) {
113
+ emitReplyError(`UI call "${id}" is already running`);
114
+ return;
115
+ }
116
+ if (typeof parsed.namespace !== "string" || parsed.namespace === "") {
117
+ emitReplyError("Invalid plugin namespace");
118
+ return;
119
+ }
120
+ const plugin = this.pluginIndex.get(parsed.namespace);
121
+ if (!plugin) {
122
+ emitReplyError(`Unknown plugin "${parsed.namespace}"`);
123
+ return;
124
+ }
125
+ if (typeof parsed.root !== "string" || parsed.root !== plugin.root) {
126
+ emitReplyError(`Plugin "${parsed.namespace}" root mismatch`);
127
+ return;
128
+ }
129
+ if (typeof parsed.path !== "string" || parsed.path.trim() === "") {
130
+ emitReplyError("Invalid script path");
131
+ return;
132
+ }
133
+ const resolved = resolvePluginScriptPath(plugin.root, parsed.path);
134
+ if ("error" in resolved) {
135
+ emitReplyError(`plugin "${parsed.namespace}": ${resolved.error}`);
136
+ return;
137
+ }
138
+ let code: string;
139
+ try {
140
+ code = readFileSync(resolved.path, "utf8");
141
+ } catch (error) {
142
+ const codeName = errorCode(error);
143
+ emitReplyError(
144
+ codeName === "ENOENT"
145
+ ? `plugin "${parsed.namespace}": missing script ${resolved.path}`
146
+ : `plugin "${parsed.namespace}": failed to read ${resolved.path}: ${codeName ?? errorMessage(error)}`,
147
+ );
148
+ return;
149
+ }
150
+
151
+ const data = parsed.data === undefined ? null : parsed.data;
152
+ let handle: ScriptRunHandle;
153
+ try {
154
+ handle = runScript({
155
+ code,
156
+ filename: resolved.path,
157
+ cwd: ctx.cwd,
158
+ input: { ui: data },
159
+ aliases: bundledAliases(),
160
+ uiCall: true,
161
+ ...(ctx.extraEnv && Object.keys(ctx.extraEnv).length > 0 ? { extraEnv: ctx.extraEnv } : {}),
162
+ onUiMessage: (dataJson) => {
163
+ emitMessageJson(dataJson);
164
+ },
165
+ });
166
+ } catch (error) {
167
+ emitReplyError(`Failed to start script: ${errorMessage(error)}`);
168
+ return;
169
+ }
170
+
171
+ const entry: ActiveUiCall = { handle };
172
+ this.active.set(id, entry);
173
+
174
+ void handle.promise
175
+ .then((result) => {
176
+ this.active.delete(id);
177
+ this.emitSettlementReply(result, entry, emitReplyOkJson, emitReplyError);
178
+ })
179
+ .catch((error: unknown) => {
180
+ this.active.delete(id);
181
+ emitReplyError(errorMessage(error));
182
+ });
183
+ }
184
+
185
+ private emitSettlementReply(
186
+ result: ScriptRunResult,
187
+ entry: ActiveUiCall,
188
+ emitOkJson: (valueJson: string) => void,
189
+ emitError: (error: string) => void,
190
+ ): void {
191
+ switch (result.exitReason) {
192
+ case "ok":
193
+ if (result.uiReturn?.ok === true) {
194
+ emitOkJson(result.uiReturn.json);
195
+ } else if (result.uiReturn?.ok === false) {
196
+ emitError(result.uiReturn.error);
197
+ } else {
198
+ emitOkJson("null");
199
+ }
200
+ return;
201
+ case "exit-called":
202
+ if ((result.exitCode ?? 0) === 0) {
203
+ emitOkJson("null");
204
+ } else {
205
+ emitError(`Script exited with code ${result.exitCode}`);
206
+ }
207
+ return;
208
+ case "threw":
209
+ emitError(formatThrownError(result.error));
210
+ return;
211
+ case "killed":
212
+ case "aborted":
213
+ emitError(entry.cancelReason ?? "UI call was cancelled");
214
+ return;
215
+ case "timeout":
216
+ emitError("UI call timed out");
217
+ return;
218
+ }
219
+ }
220
+
221
+ private handleCancel(rawJson: string): void {
222
+ let parsed: unknown;
223
+ try {
224
+ parsed = JSON.parse(rawJson);
225
+ } catch {
226
+ return;
227
+ }
228
+ if (!isPlainObject(parsed) || !Array.isArray(parsed.ids)) return;
229
+ for (const id of parsed.ids) {
230
+ if (typeof id !== "string") continue;
231
+ const entry = this.active.get(id);
232
+ if (!entry) continue;
233
+ entry.cancelReason = "UI call was cancelled";
234
+ entry.handle.cancel("killed");
235
+ }
236
+ }
237
+ }
@@ -4,7 +4,7 @@ import type { ToolCallReply } from "./script-tool-calls.ts";
4
4
  import { toolDeclarations } from "./script-tool-types.ts";
5
5
  import { applySessionTmp } from "./session-tmp.ts";
6
6
  import { killTreeWindows, prefixBytes, signalGroup } from "./tool-common.ts";
7
- import { errorCode, errorMessage } from "./util.ts";
7
+ import { errorCode, errorMessage, isPlainObject } from "./util.ts";
8
8
  import { typeStrippingOptions } from "./worker-options.ts";
9
9
 
10
10
  /**
@@ -92,8 +92,15 @@ export interface ScriptRunRequest {
92
92
  extraEnv?: Record<string, string>;
93
93
  /** The tool functions (Section 10); absent binds none. */
94
94
  tools?: ScriptRunTools;
95
+ /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
96
+ uiCall?: boolean;
97
+ /** Fired with each validated UI message JSON payload before settlement. */
98
+ onUiMessage?: (json: string) => void;
95
99
  }
96
100
 
101
+ /** Pre-validated return outcome of a plugin UI call (specs/plugin-ui.md Section 5). */
102
+ export type UiReturnOutcome = { ok: true; json: string } | { ok: false; error: string };
103
+
97
104
  /** The tool functions of a run (Section 10.3). */
98
105
  export interface ScriptRunTools {
99
106
  /** Bound tool names, in declaration order. */
@@ -119,6 +126,8 @@ export interface ScriptRunResult {
119
126
  exitCode?: number;
120
127
  durationMs: number;
121
128
  error?: { name: string; message: string; stack: string };
129
+ /** Pre-validated return outcome of a plugin UI call (specs/plugin-ui.md Section 5). */
130
+ uiReturn?: UiReturnOutcome;
122
131
  }
123
132
 
124
133
  export interface ScriptRunHandle {
@@ -133,6 +142,18 @@ export interface ScriptRunHandle {
133
142
  stderrLine: (line: string) => boolean;
134
143
  }
135
144
 
145
+ /** Parse a worker's `uiReturn` payload without type assertions. */
146
+ function parseUiReturn(value: unknown): UiReturnOutcome | undefined {
147
+ if (!isPlainObject(value)) return undefined;
148
+ if (value.ok === true && typeof value.json === "string") {
149
+ return { ok: true, json: value.json };
150
+ }
151
+ if (value.ok === false && typeof value.error === "string") {
152
+ return { ok: false, error: value.error };
153
+ }
154
+ return undefined;
155
+ }
156
+
136
157
  /** Signal one spawned child by its process ID (Windows: its tree with taskkill /T /F). */
137
158
  function signalChild(pid: number, signal: NodeJS.Signals): void {
138
159
  if (process.platform === "win32") {
@@ -296,6 +317,7 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
296
317
  aliases: req.aliases,
297
318
  toolNames: req.tools?.names ?? [],
298
319
  toolTypes: req.tools?.declarations ?? toolDeclarations({ bound: [], unbound: [] }),
320
+ uiCall: req.uiCall === true,
299
321
  },
300
322
  env: workerEnv,
301
323
  });
@@ -335,6 +357,9 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
335
357
  case "tool-call":
336
358
  if (!settled) startNestedCall(msg.id, String(msg.name), msg.args);
337
359
  break;
360
+ case "ui-message":
361
+ if (!settled && typeof msg.json === "string") req.onUiMessage?.(msg.json);
362
+ break;
338
363
  case "exit-called":
339
364
  settle({ exitReason: "exit-called", exitCode: msg.code ?? 0 });
340
365
  break;
@@ -350,15 +375,18 @@ export function runScript(req: ScriptRunRequest): ScriptRunHandle {
350
375
  },
351
376
  });
352
377
  break;
353
- case "result":
378
+ case "result": {
379
+ const uiReturn = parseUiReturn(msg.uiReturn);
354
380
  settle({
355
381
  exitReason: "ok",
356
382
  returnValue: msg.returnValue,
357
383
  rendered: msg.rendered,
358
384
  render: msg.render,
359
385
  json: msg.json,
386
+ ...(uiReturn === undefined ? {} : { uiReturn }),
360
387
  });
361
388
  break;
389
+ }
362
390
  }
363
391
  });
364
392
 
@@ -30,6 +30,8 @@ interface ScriptWorkerData {
30
30
  toolNames: string[];
31
31
  /** The tool declarations (Section 10.2). */
32
32
  toolTypes: string;
33
+ /** Whether this run is a plugin UI call (specs/plugin-ui.md). */
34
+ uiCall?: boolean;
33
35
  }
34
36
 
35
37
  const port = parentPort;
@@ -209,7 +211,41 @@ const toolFunction =
209
211
  const scriptTools: Record<string, unknown> = Object.freeze(
210
212
  Object.fromEntries(data.toolNames.map((name) => [name, toolFunction(name)])),
211
213
  );
212
- const scriptDent = Object.freeze({ toolTypes: (): string => data.toolTypes });
214
+ const UI_PAYLOAD_CAP_BYTES = 262_144;
215
+ const serializeUiJson = (value: unknown, label: string): string => {
216
+ if (!isJsonCompatible(value)) {
217
+ throw new Error(`${label} must be a JSON value`);
218
+ }
219
+ let json: string | undefined;
220
+ try {
221
+ json = JSON.stringify(value);
222
+ } catch {
223
+ throw new Error(`${label} must be a JSON value`);
224
+ }
225
+ if (typeof json !== "string") {
226
+ throw new Error(`${label} must be a JSON value`);
227
+ }
228
+ if (Buffer.byteLength(json, "utf8") > UI_PAYLOAD_CAP_BYTES) {
229
+ throw new Error(`${label} exceeds ${UI_PAYLOAD_CAP_BYTES} bytes`);
230
+ }
231
+ return json;
232
+ };
233
+ const sendUiMessage = (payload: unknown): void => {
234
+ const json = serializeUiJson(payload, "UI message data");
235
+ if (exitCalled) return;
236
+ try {
237
+ port.postMessage({ type: "ui-message", json });
238
+ } catch {
239
+ // Port closed.
240
+ }
241
+ };
242
+ const scriptDent =
243
+ data.uiCall === true
244
+ ? Object.freeze({
245
+ toolTypes: (): string => data.toolTypes,
246
+ ui: Object.freeze({ send: sendUiMessage }),
247
+ })
248
+ : Object.freeze({ toolTypes: (): string => data.toolTypes });
213
249
  Object.defineProperty(globalThis, "tools", {
214
250
  value: scriptTools,
215
251
  writable: true,
@@ -1057,6 +1093,31 @@ void (async () => {
1057
1093
  // A script that caught the exit's error reaches its own end; its run already
1058
1094
  // settled as exit-called, so there is no result to report.
1059
1095
  if (exitCalled) return;
1096
+ // Plugin UI calls classify the raw return value before structured cloning,
1097
+ // so non-cloneable values (functions, symbols) are never turned into strings
1098
+ // and `undefined` maps to `null` (specs/plugin-ui.md Section 5).
1099
+ if (data.uiCall === true) {
1100
+ const rawExported: unknown = mod?.default;
1101
+ let uiReturn: { ok: true; json: string } | { ok: false; error: string };
1102
+ if (rawExported === undefined) {
1103
+ uiReturn = { ok: true, json: "null" };
1104
+ } else {
1105
+ try {
1106
+ uiReturn = { ok: true, json: serializeUiJson(rawExported, "Return value") };
1107
+ } catch (err) {
1108
+ uiReturn = {
1109
+ ok: false,
1110
+ error: err instanceof Error ? err.message : String(err),
1111
+ };
1112
+ }
1113
+ }
1114
+ try {
1115
+ port.postMessage({ type: "result", uiReturn });
1116
+ } catch {
1117
+ // Port closed.
1118
+ }
1119
+ return;
1120
+ }
1060
1121
  // Section 4: a return value that cannot be structured-cloned degrades, without
1061
1122
  // failing the run, to the `<non-cloneable: <error>>` marker string. The check
1062
1123
  // happens here, where the original value still exists. A value that clones
@@ -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.7",
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",