@juanbenjumea/pi-agy 0.5.0 → 0.5.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.2
4
+
5
+ - Deliver large streamed result records intact: the per-record bound now fits a maximum-size response (1M chars with worst-case JSON escaping) instead of discarding records over 256 KB mid-stream.
6
+ - Mark responses served from the raw stdout fallback when the 64 KB capture bound truncated them.
7
+ - Record both sides of pre-existing staged renames/copies in the git baseline so they are never attributed to agy as newly-dirty files.
8
+ - Require Node.js >= 20.3.0 (`AbortSignal.any`).
9
+ - Name the failing check in preflight exit-code errors (health, connectivity, version, usage) instead of a hardcoded connectivity hint.
10
+ - Validate the `agy_usage` working directory before spawning so a bad `dir` is not misreported as a missing Antigravity CLI installation.
11
+ - Document that `new_session: false` resumes the last recorded conversation in the tool schema the model sees.
12
+ - Stop caching negative `just` binary probes mid-session; installing `just` is now picked up without a restart.
13
+ - Offer `timeout=10m` in `/agy` argument completions.
14
+ - Document the irreducible stale-lock recovery race in both lock implementations.
15
+
16
+ ## 0.5.1
17
+
18
+ - Add an `agy_usage` tool and `/agy usage` command for model-specific quota and reset discovery.
19
+ - Refresh read-only agy usage data before executions and include the snapshot in results when available; unsupported older CLIs remain best effort.
20
+ - Refresh quota data every minute while retaining five-minute health/model preflight caching.
21
+ - Fix release-candidate model ids such as `rc1` being treated as stable.
22
+ - Honor the documented `quotaBalancing` config flag when loading `agy-config.json`.
23
+ - Fail fast with reset details when usage explicitly reports the selected model is exhausted, including secondary windows such as weekly limits.
24
+ - Accept JSONL quota output from noisy agy CLI versions that support native headless usage.
25
+ - Ignore malformed streamed metadata instead of allowing subprocess JSON to corrupt results.
26
+ - Make stream bounds UTF-8 byte-accurate and decode split multibyte stdout safely.
27
+ - Include available model alternatives when failing fast on an exhausted quota.
28
+ - Normalize explicit percentage quota fields correctly, including fractional percentages.
29
+ - Match quota records across model aliases and human-readable thinking labels without conflating low/medium/high tiers.
30
+ - Add structured `quota_status` metadata (`available`, `exhausted`, or `unknown`) to targeted quota checks, echoed in the readable tool text.
31
+ - Preserve bounded quota-probe failure reasons for troubleshooting instead of reporting only generic unavailability.
32
+ - Add `quota_status` to successful execution details for machine-readable model availability.
33
+ - Match grouped Gemini and Claude/GPT quota pools to concrete model selections without crossing families, preserving nested window names.
34
+ - Recognize grouped/family fields, snake-case exhaustion flags, and relative reset durations.
35
+ - Retry failed quota probes after five seconds while caching successful snapshots for one minute.
36
+ - Refuse to invoke `/usage` on agy versions older than 1.1.11, where it could be interpreted as a model prompt.
37
+ - Group all quota windows for a targeted model at the top of its report.
38
+ - Parse plain-text quota records when a version-gated native usage command returns text, extracting model percentages, requests, tokens, quota windows, and reset hints where possible.
39
+
3
40
  ## 0.5.0
4
41
 
5
42
  - Fold quota-aware default-model steering into the extension (`quotaBalancing` config + `AGY_DEFAULT_MODEL_*` env tuning); the external `agy-default-model.sh` wrapper is gone.
package/README.md CHANGED
@@ -19,7 +19,8 @@ pi install npm:@juanbenjumea/pi-agy
19
19
  | Conversation resume | None | `conversation_id`, `continue`, session store, `/agy sessions` picker |
20
20
  | Verify injection | `npm test` only | `just ci` first, then `npm test`/`uv run pytest` |
21
21
  | Post-write summary | None | Appends `git diff --stat` for newly-dirty files only; pre-existing dirt is listed separately |
22
- | Preflight | Every call | Cached 5 min per process; also refreshes the model catalog |
22
+ | Preflight | Every call | Health/model checks cached 5 min per process; model quotas refresh every minute |
23
+ | Quota discovery | None | Read-only `/usage` probe exposes model-specific remaining quota and reset times to agents |
23
24
  | Concurrency | Unlocked | Per-directory lock (in-process + filesystem, symlink-aware), lock wait counts against the timeout |
24
25
  | Transient failures | Fatal | One retry when agy fails before doing any work |
25
26
  | Cancellation | Direct child only | Full process-tree kill on cancel/timeout via detached process groups |
@@ -37,6 +38,18 @@ Auth is unchanged: existing `agy` OAuth (`~/.gemini/oauth_creds.json`).
37
38
  | `stream` | Use `stream-json` (default `true`) |
38
39
  | `mode` | `accept-edits` by default; use `plan` for exploration/review |
39
40
 
41
+ `agy_execute` refreshes quota information before each run (best effort) and
42
+ returns it in `details.quota`/`details.quota_status` and the response when
43
+ the CLI exposes structured model records. Use the separate `agy_usage` tool
44
+ when choosing a model before execution. If the selected model is explicitly
45
+ reported as exhausted, the run stops before spending another agent turn and
46
+ reports the reset information.
47
+ Use `agy_usage` with `model` (for example `model=sonnet`) for a targeted
48
+ `available`/`exhausted`/`unknown` status. Older agy versions that do not support
49
+ headless `/usage` continue without failing the task. The extension requires
50
+ agy 1.1.11+ before invoking `/usage`; older versions are refused safely because
51
+ that command could otherwise consume model quota as a prompt.
52
+
40
53
  ## Human-callable `/agy` command
41
54
 
42
55
  Run agy directly from the Pi TUI — fast path when fully specified, wizard otherwise:
@@ -49,6 +62,7 @@ Run agy directly from the Pi TUI — fast path when fully specified, wizard othe
49
62
  /agy continue fix the tests # continue this directory's last conversation
50
63
  /agy timeout=10m sonnet big task # raise the run cap (also 90s / 1500ms; bare = minutes)
51
64
  /agy sessions # pick a recorded conversation to resume
65
+ /agy usage # inspect model quotas and reset times
52
66
  ```
53
67
 
54
68
  Leading option tokens (`plan`, a model alias, `continue`, `timeout=…`) are
@@ -65,7 +79,8 @@ Missing pieces open interactive dialogs (mode select, model select with
65
79
  descriptions, multi-line task editor). `accept-edits` asks for confirmation
66
80
  before writing. The command then runs agy directly with the selected parameters;
67
81
  progress is shown in the (throttled) status bar and the final response is
68
- notified — no second LLM turn or custom TUI surface.
82
+ notified — no second LLM turn or custom TUI surface. `/agy usage` performs the
83
+ same read-only quota check without starting a model turn.
69
84
 
70
85
  ## Config
71
86
 
@@ -1,6 +1,12 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
- import { isAgyModel, resolveAgyModelId, type AgyModel } from "./lib/cli.js";
3
+ import {
4
+ checkAgyUsage,
5
+ formatAgyUsage,
6
+ isAgyModel,
7
+ resolveAgyModelId,
8
+ type AgyModel,
9
+ } from "./lib/cli.js";
4
10
  import { executeAgyTask } from "./lib/execute.js";
5
11
  import { truncate } from "./lib/output.js";
6
12
  import { describePreRunDirt } from "./lib/postflight.js";
@@ -116,21 +122,43 @@ interface InteractiveRun {
116
122
  export function registerAgyCommand(pi: ExtensionAPI): void {
117
123
  pi.registerCommand("agy", {
118
124
  description:
119
- "Run agy directly: /agy [mode] [model] [continue] [timeout=10m] <prompt>, or /agy sessions to resume a prior conversation.",
125
+ "Run agy directly: /agy [mode] [model] [continue] [timeout=10m] <prompt>; use /agy usage to inspect model quotas.",
120
126
  getArgumentCompletions: (prefix: string) => {
121
127
  const tokens = prefix.trim().split(/\s+/).filter(Boolean);
122
128
  const p = prefix.toLowerCase();
123
129
 
124
- if (tokens.length === 1 && MODE_KEYS.includes(tokens[0] as (typeof MODE_KEYS)[number])) {
130
+ if (
131
+ tokens.length === 1 &&
132
+ (MODE_KEYS.includes(tokens[0] as (typeof MODE_KEYS)[number]) ||
133
+ tokens[0] === "usage" ||
134
+ tokens[0] === "quota")
135
+ ) {
125
136
  return [
126
137
  ...MODEL_KEYS.map((k) => ({ value: k, label: k })),
127
- { value: "continue", label: "continue" },
138
+ ...(tokens[0] === "usage" || tokens[0] === "quota"
139
+ ? []
140
+ : [
141
+ { value: "continue", label: "continue" },
142
+ { value: "timeout=10m", label: "timeout=10m" },
143
+ ]),
128
144
  ];
129
145
  }
146
+ if (
147
+ tokens.length === 2 &&
148
+ (tokens[0] === "usage" || tokens[0] === "quota")
149
+ ) {
150
+ const partial = prefix.endsWith(" ") ? "" : tokens[1].toLowerCase();
151
+ return MODEL_KEYS.filter((key) => key.startsWith(partial)).map((key) => ({
152
+ value: key,
153
+ label: key,
154
+ }));
155
+ }
130
156
  if (tokens.length <= 1) {
131
157
  const modes = MODE_KEYS.filter((m) => m.startsWith(tokens[0] ?? ""));
132
158
  const models = MODEL_KEYS.filter((k) => k.startsWith(p));
133
- const extras = ["continue", "sessions"].filter((k) => k.startsWith(p));
159
+ const extras = ["continue", "sessions", "usage", "quota", "timeout=10m"].filter((k) =>
160
+ k.startsWith(p),
161
+ );
134
162
  return [
135
163
  ...modes.map((m) => ({ value: m, label: m })),
136
164
  ...models.map((m) => ({ value: m, label: m })),
@@ -145,10 +173,21 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
145
173
  return;
146
174
  }
147
175
 
148
- if (args.trim().toLowerCase() === "sessions") {
176
+ const command = args.trim().toLowerCase();
177
+ if (command === "sessions") {
149
178
  await runSessionsPicker(ctx);
150
179
  return;
151
180
  }
181
+ const usageMatch = /^(?:usage|quota)(?:\s+(\S+))?$/.exec(command);
182
+ if (usageMatch) {
183
+ const requestedModel = usageMatch[1] ? MODEL_ALIASES[usageMatch[1]] : undefined;
184
+ if (usageMatch[1] && !requestedModel) {
185
+ ctx.ui.notify(`agy: unknown model alias '${usageMatch[1]}'`, "error");
186
+ return;
187
+ }
188
+ await showUsage(ctx, requestedModel);
189
+ return;
190
+ }
152
191
 
153
192
  const parsed = parseAgyCommandArgs(args);
154
193
 
@@ -197,6 +236,22 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
197
236
  });
198
237
  }
199
238
 
239
+ /** `/agy usage` — show model quotas without starting an agent turn. */
240
+ async function showUsage(
241
+ ctx: ExtensionCommandContext,
242
+ model?: AgyModel,
243
+ ): Promise<void> {
244
+ try {
245
+ await ctx.waitForIdle();
246
+ const snapshot = await checkAgyUsage(ctx.cwd, ctx.signal);
247
+ const report = formatAgyUsage(snapshot, model ? resolveAgyModelId(model) : undefined);
248
+ ctx.ui.notify(report ?? "agy quota information is unavailable in this CLI version", report ? "info" : "warning");
249
+ } catch (error) {
250
+ const message = error instanceof Error ? error.message : String(error);
251
+ ctx.ui.notify(`agy usage check failed: ${message}`, "error");
252
+ }
253
+ }
254
+
200
255
  /** `/agy sessions` — pick a recorded conversation and resume it with a follow-up. */
201
256
  async function runSessionsPicker(ctx: ExtensionCommandContext): Promise<void> {
202
257
  const history = await getHistory(ctx.cwd);
@@ -339,5 +394,5 @@ function describeWhen(iso: string): string {
339
394
  }
340
395
 
341
396
  function optionKey(option: string): string {
342
- return option.split(" — ")[0] ?? option;
397
+ return option.split(" — ")[0];
343
398
  }
@@ -1,8 +1,17 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "@sinclair/typebox";
3
+ import { stat } from "node:fs/promises";
3
4
  import * as path from "node:path";
4
5
 
5
- import { resolveAgyModelAlias, resolveAgyModelId, type AgyModel } from "./lib/cli.js";
6
+ import {
7
+ checkAgyUsage,
8
+ findAgyQuotaEntries,
9
+ formatAgyUsage,
10
+ isAgyQuotaExhausted,
11
+ resolveAgyModelAlias,
12
+ resolveAgyModelId,
13
+ type AgyModel,
14
+ } from "./lib/cli.js";
6
15
  import { describePreRunDirt } from "./lib/postflight.js";
7
16
  import { registerAgyCommand } from "./commands.js";
8
17
  import {
@@ -40,6 +49,7 @@ export default function piAgyExtension(pi: ExtensionAPI) {
40
49
  "Use gpt-oss when an open-model alternative is specifically desired.",
41
50
  "For consequential work, use one family to produce and the opposite family to cross-review in mode=plan; do not spend both quota groups on trivial tasks.",
42
51
  "Reuse conversation_id or continue=true for multi-step plan→implement→review handoffs.",
52
+ "Use agy_usage before choosing a model when quota availability matters; agy_execute also refreshes and returns a quota snapshot.",
43
53
  "Batch related work, prefer digest output for non-write calls, and avoid parallel agy_execute calls within one shared-quota group or directory.",
44
54
  "Always review the git diff and run just ci (or the project gate) after agy_execute with mode=accept-edits.",
45
55
  "Never use agy for irreversible production changes.",
@@ -113,7 +123,8 @@ export default function piAgyExtension(pi: ExtensionAPI) {
113
123
  ),
114
124
  new_session: Type.Optional(
115
125
  Type.Boolean({
116
- description: "Force a fresh agy conversation (default when no conversation_id/continue).",
126
+ description:
127
+ "Force a fresh agy conversation (default when no conversation_id/continue). Explicit false resumes the last recorded conversation for the directory.",
117
128
  }),
118
129
  ),
119
130
  stream: Type.Optional(
@@ -183,4 +194,76 @@ export default function piAgyExtension(pi: ExtensionAPI) {
183
194
  };
184
195
  },
185
196
  });
197
+
198
+ pi.registerTool({
199
+ name: "agy_usage",
200
+ label: "Antigravity Quota",
201
+ description:
202
+ "Read the current model-specific Antigravity quota and reset information without spending a model turn.",
203
+ promptSnippet: "Inspect Antigravity model quotas before choosing a model",
204
+ parameters: Type.Object({
205
+ model: Type.Optional(
206
+ Type.Union(
207
+ [
208
+ Type.Literal("flash-low"),
209
+ Type.Literal("flash-medium"),
210
+ Type.Literal("flash-high"),
211
+ Type.Literal("pro-low"),
212
+ Type.Literal("pro-high"),
213
+ Type.Literal("sonnet"),
214
+ Type.Literal("opus"),
215
+ Type.Literal("gpt-oss"),
216
+ ],
217
+ { description: "Optional model alias to place first in the report." },
218
+ ),
219
+ ),
220
+ dir: Type.Optional(
221
+ Type.String({
222
+ description: "Working directory used for the agy CLI check. Defaults to current project root.",
223
+ }),
224
+ ),
225
+ }),
226
+
227
+ async execute(_toolCallId, params, signal, _onUpdate, ctx) {
228
+ const cwd = params.dir ? path.resolve(ctx.cwd, params.dir) : ctx.cwd;
229
+ if (params.dir) {
230
+ // Validate the override before spawning so a bad dir is not
231
+ // misreported as a missing Antigravity CLI installation.
232
+ try {
233
+ const info = await stat(cwd);
234
+ if (!info.isDirectory()) throw new Error(`Working directory is not a directory: ${cwd}`);
235
+ } catch (error) {
236
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
237
+ throw new Error(`Working directory does not exist: ${cwd}`);
238
+ }
239
+ throw error;
240
+ }
241
+ }
242
+ const quota = await checkAgyUsage(cwd, signal);
243
+ const selectedModel = params.model ? resolveAgyModelId(params.model) : undefined;
244
+ const selectedEntries = selectedModel ? findAgyQuotaEntries(quota, selectedModel) : [];
245
+ const quotaStatus = selectedModel
246
+ ? selectedEntries.length === 0
247
+ ? "unknown"
248
+ : selectedEntries.some((entry) => isAgyQuotaExhausted(entry))
249
+ ? "exhausted"
250
+ : "available"
251
+ : undefined;
252
+ const quotaReport =
253
+ formatAgyUsage(quota, selectedModel) ??
254
+ "agy quota information is unavailable in this CLI version or account configuration";
255
+ const report = quotaStatus
256
+ ? `selected model ${selectedModel}: ${quotaStatus}\n\n${quotaReport}`
257
+ : quotaReport;
258
+ return {
259
+ content: [{ type: "text", text: report }],
260
+ details: {
261
+ cwd,
262
+ selected_model: selectedModel,
263
+ quota_status: quotaStatus,
264
+ quota,
265
+ },
266
+ };
267
+ },
268
+ });
186
269
  }
@@ -3,6 +3,7 @@ import { createRequire } from "node:module";
3
3
  const _require = createRequire(import.meta.url);
4
4
 
5
5
  import type { ChildProcess } from "node:child_process";
6
+ import { StringDecoder } from "node:string_decoder";
6
7
  import { readFile } from "node:fs/promises";
7
8
  import * as path from "node:path";
8
9
 
@@ -49,6 +50,24 @@ export function isAgyModel(value: unknown): value is AgyModel {
49
50
 
50
51
  export type AgyEffort = "low" | "medium" | "high";
51
52
 
53
+ /** A normalized model quota entry returned by agy's read-only usage command. */
54
+ export interface AgyQuotaEntry {
55
+ model: string;
56
+ window?: string;
57
+ remaining_fraction?: number;
58
+ remaining_requests?: number;
59
+ remaining_tokens?: number;
60
+ reset_at?: string;
61
+ }
62
+
63
+ /** Best-effort quota snapshot; agy versions may expose different JSON shapes. */
64
+ export interface AgyUsageSnapshot {
65
+ fetched_at: string;
66
+ models: AgyQuotaEntry[];
67
+ raw_summary?: string;
68
+ error?: string;
69
+ }
70
+
52
71
  export interface AgyOptions {
53
72
  prompt: string;
54
73
  model?: AgyModel;
@@ -68,7 +87,8 @@ const PREFLIGHT_TIMEOUT_MS = 10_000;
68
87
  // stream-json path accumulates results incrementally and is not capped by it.
69
88
  const MAX_CAPTURE_BYTES = 64 * 1024;
70
89
  // Preview/experimental model ids must never win catalog resolution implicitly.
71
- const UNSTABLE_MODEL_PATTERN = /(?:preview|experimental|beta|alpha|\brc\b|snapshot|\bnext\b)/i;
90
+ const UNSTABLE_MODEL_PATTERN =
91
+ /(?:^|[-_.])(?:preview|experimental|beta|alpha|rc\d*|snapshot|next)(?:$|[-_.])/i;
72
92
 
73
93
  // Static fallback for when `agy models` output is unavailable. The live
74
94
  // catalog (updated during preflight) overrides these per alias.
@@ -295,6 +315,438 @@ export async function checkAgyConnectivity(
295
315
  if (Object.keys(catalog).length > 0) updateModelCatalog(catalog);
296
316
  }
297
317
 
318
+ /**
319
+ * Refresh model-specific quotas without spending a model turn. Newer agy
320
+ * versions answer read-only `/usage` in print mode; older versions may not,
321
+ * so unsupported usage reporting is deliberately best effort.
322
+ */
323
+ const MIN_NATIVE_USAGE_VERSION = [1, 1, 11] as const;
324
+
325
+ export async function checkAgyUsage(
326
+ cwd: string,
327
+ signal?: AbortSignal,
328
+ timeoutMs?: number,
329
+ ): Promise<AgyUsageSnapshot | undefined> {
330
+ let versionOutput: string;
331
+ try {
332
+ versionOutput = await runPreflightCommand(
333
+ ["--version"],
334
+ cwd,
335
+ signal,
336
+ "agy version check",
337
+ true,
338
+ timeoutMs,
339
+ );
340
+ } catch (error) {
341
+ if (signal?.aborted) throw error;
342
+ const message = error instanceof Error ? error.message : String(error);
343
+ return usageError(`could not verify native usage support: ${message}`);
344
+ }
345
+
346
+ const version = parseAgyVersion(versionOutput);
347
+ if (!version) {
348
+ return usageError("could not verify native usage support; refusing to run /usage blindly");
349
+ }
350
+ if (compareVersions(version, MIN_NATIVE_USAGE_VERSION) < 0) {
351
+ return usageError(
352
+ `headless /usage requires agy >= ${MIN_NATIVE_USAGE_VERSION.join(".")} (detected ${version.join(".")})`,
353
+ );
354
+ }
355
+
356
+ try {
357
+ const output = await runPreflightCommand(
358
+ ["--output-format", "json", "-p", "/usage"],
359
+ cwd,
360
+ signal,
361
+ "agy usage check",
362
+ true,
363
+ timeoutMs,
364
+ );
365
+ return parseAgyUsage(output);
366
+ } catch (error) {
367
+ if (signal?.aborted) throw error;
368
+ const message = error instanceof Error ? error.message : String(error);
369
+ return usageError(message);
370
+ }
371
+ }
372
+
373
+ function parseAgyVersion(output: string): [number, number, number] | undefined {
374
+ const match = /(?:^|\s)v?(\d+)\.(\d+)\.(\d+)(?:\s|$)/m.exec(output);
375
+ return match
376
+ ? [Number(match[1]), Number(match[2]), Number(match[3])]
377
+ : undefined;
378
+ }
379
+
380
+ function compareVersions(left: readonly number[], right: readonly number[]): number {
381
+ for (let index = 0; index < 3; index++) {
382
+ if (left[index] !== right[index]) return left[index] < right[index] ? -1 : 1;
383
+ }
384
+ return 0;
385
+ }
386
+
387
+ function usageError(message: string): AgyUsageSnapshot {
388
+ return {
389
+ fetched_at: new Date().toISOString(),
390
+ models: [],
391
+ error: message.slice(0, 2_000),
392
+ };
393
+ }
394
+
395
+ const MAX_USAGE_SUMMARY_CHARS = 12_000;
396
+ const MODEL_FIELD_KEYS = [
397
+ "model",
398
+ "model_id",
399
+ "modelId",
400
+ "model_name",
401
+ "modelName",
402
+ "displayName",
403
+ "label",
404
+ "group",
405
+ "family",
406
+ "pool",
407
+ ];
408
+ const REMAINING_FRACTION_KEYS = [
409
+ "remainingFraction",
410
+ "remaining_fraction",
411
+ "fractionRemaining",
412
+ ];
413
+ const REMAINING_PERCENT_KEYS = ["remainingPercent", "remaining_percent"];
414
+ const REMAINING_REQUEST_KEYS = ["remainingRequests", "remaining_requests", "requestsRemaining"];
415
+ const REMAINING_TOKEN_KEYS = ["remainingTokens", "remaining_tokens", "tokensRemaining"];
416
+ const WINDOW_KEYS = ["window", "period", "quotaWindow", "duration"];
417
+ const RELATIVE_RESET_KEYS = ["resetsInSeconds", "resetAfterSeconds", "reset_after_seconds"];
418
+ const RESET_KEYS = [
419
+ "resetAt",
420
+ "reset_at",
421
+ "resetTime",
422
+ "reset_time",
423
+ "reset_timestamp",
424
+ "quotaResetTime",
425
+ "nextReset",
426
+ ];
427
+
428
+ /** Normalize both documented and version-specific usage payloads. */
429
+ export function parseAgyUsage(output: string): AgyUsageSnapshot | undefined {
430
+ const raw = output.trim();
431
+ if (!raw) return undefined;
432
+
433
+ let parsed: unknown;
434
+ try {
435
+ parsed = JSON.parse(raw);
436
+ } catch {
437
+ const plainTextSnapshot = parsePlainTextUsage(raw);
438
+ if (plainTextSnapshot) return plainTextSnapshot;
439
+ const jsonLines = raw
440
+ .split("\n")
441
+ .map((line) => {
442
+ try {
443
+ return JSON.parse(line);
444
+ } catch {
445
+ return undefined;
446
+ }
447
+ })
448
+ .filter((line): line is unknown => line !== undefined);
449
+ if (jsonLines.length > 0) {
450
+ const lineSnapshot = parseAgyUsage(JSON.stringify(jsonLines));
451
+ if (lineSnapshot?.models.length) return lineSnapshot;
452
+ }
453
+ return {
454
+ fetched_at: new Date().toISOString(),
455
+ models: [],
456
+ raw_summary: raw.slice(0, MAX_USAGE_SUMMARY_CHARS),
457
+ };
458
+ }
459
+
460
+ const entries = new Map<string, AgyQuotaEntry>();
461
+ const visit = (value: unknown, hintedModel?: string, hintedWindow?: string): void => {
462
+ if (Array.isArray(value)) {
463
+ for (const item of value) visit(item, hintedModel, hintedWindow);
464
+ return;
465
+ }
466
+ if (!isRecord(value)) return;
467
+
468
+ const model = findModelName(value) ?? hintedModel;
469
+ const entry = model ? readQuotaEntry(model, value, hintedWindow) : undefined;
470
+ if (entry) {
471
+ const key = `${entry.model.toLowerCase()}\u0000${entry.window?.toLowerCase() ?? ""}`;
472
+ entries.set(key, mergeQuotaEntries(entries.get(key), entry));
473
+ }
474
+
475
+ for (const [key, child] of Object.entries(value)) {
476
+ visit(
477
+ child,
478
+ model ?? (looksLikeModelName(key) ? key : undefined),
479
+ hintedWindow ?? quotaWindowName(key),
480
+ );
481
+ }
482
+ };
483
+ visit(parsed);
484
+
485
+ if (entries.size === 0 && isRunEnvelope(parsed)) return undefined;
486
+
487
+ const snapshot: AgyUsageSnapshot = {
488
+ fetched_at: new Date().toISOString(),
489
+ models: [...entries.values()].sort((a, b) => a.model.localeCompare(b.model)),
490
+ };
491
+ if (snapshot.models.length === 0) {
492
+ snapshot.raw_summary = JSON.stringify(parsed).slice(0, MAX_USAGE_SUMMARY_CHARS);
493
+ }
494
+ return snapshot;
495
+ }
496
+
497
+ function parsePlainTextUsage(raw: string): AgyUsageSnapshot | undefined {
498
+ const models: AgyQuotaEntry[] = [];
499
+ for (const line of raw.split("\n")) {
500
+ const match = /^\s*[-*]?\s*((?:gemini|claude|gpt(?:[- ]?oss))[^:\t—]+?)\s*(?::|\t|\s+—\s+|\s+-\s+)(.+)$/i.exec(line);
501
+ if (!match) continue;
502
+ let model = match[1].trim();
503
+ const values = match[2];
504
+ const modelWindowMatch = /\s*\((five[- ]hour|weekly|daily|monthly)\)\s*$/i.exec(model);
505
+ if (modelWindowMatch) model = model.slice(0, modelWindowMatch.index).trim();
506
+ const percentMatch = /(\d+(?:\.\d+)?)\s*%/.exec(values);
507
+ const requestMatch = /(\d[\d,]*)\s+(?:requests?|reqs?)\s*(?:left|remaining)?/i.exec(values);
508
+ const tokenMatch = /(\d[\d,]*)\s+tokens?\s*(?:left|remaining)?/i.exec(values);
509
+ const resetMatch = /\breset(?:s| at)?\s*(?:in|at)?\s+(.+)$/i.exec(values);
510
+ const windowMatch = /\b(five[- ]hour|weekly|daily|monthly)\b/i.exec(values);
511
+ const entry: AgyQuotaEntry = {
512
+ model,
513
+ window: modelWindowMatch?.[1] ?? windowMatch?.[1],
514
+ remaining_fraction: percentMatch ? Number(percentMatch[1]) / 100 : undefined,
515
+ remaining_requests: requestMatch ? Number(requestMatch[1].replace(/,/g, "")) : undefined,
516
+ remaining_tokens: tokenMatch ? Number(tokenMatch[1].replace(/,/g, "")) : undefined,
517
+ reset_at: resetMatch?.[1]?.trim(),
518
+ };
519
+ if (
520
+ entry.remaining_fraction !== undefined ||
521
+ entry.remaining_requests !== undefined ||
522
+ entry.remaining_tokens !== undefined ||
523
+ entry.reset_at ||
524
+ /\bexhausted\b/i.test(values)
525
+ ) {
526
+ if (/\bexhausted\b/i.test(values)) entry.remaining_fraction = 0;
527
+ models.push(entry);
528
+ }
529
+ }
530
+ return models.length
531
+ ? { fetched_at: new Date().toISOString(), models }
532
+ : undefined;
533
+ }
534
+
535
+ function isRunEnvelope(value: unknown): boolean {
536
+ if (!isRecord(value)) return false;
537
+ return value.event === "result" || isRecord(value.result);
538
+ }
539
+
540
+ /** Return true when a quota record explicitly says the model is exhausted. */
541
+ export function isAgyQuotaExhausted(entry: AgyQuotaEntry | undefined): boolean {
542
+ if (!entry) return false;
543
+ return (
544
+ (entry.remaining_fraction !== undefined && entry.remaining_fraction <= 0) ||
545
+ (entry.remaining_requests !== undefined && entry.remaining_requests <= 0) ||
546
+ (entry.remaining_tokens !== undefined && entry.remaining_tokens <= 0)
547
+ );
548
+ }
549
+
550
+ /** Find quota windows that correspond to a concrete agy model id or label. */
551
+ export function findAgyQuotaEntries(
552
+ snapshot: AgyUsageSnapshot | undefined,
553
+ selectedModel: string,
554
+ ): AgyQuotaEntry[] {
555
+ if (!snapshot) return [];
556
+ return snapshot.models.filter((entry) => quotaModelsMatch(entry.model, selectedModel));
557
+ }
558
+
559
+ function quotaModelsMatch(left: string, right: string): boolean {
560
+ const normalize = (value: string) =>
561
+ value
562
+ .toLowerCase()
563
+ .replace(/\bthinking\b/g, "")
564
+ .replace(/[^a-z0-9]/g, "");
565
+ const leftNormalized = normalize(left);
566
+ const rightNormalized = normalize(right);
567
+ if (leftNormalized === rightNormalized) return true;
568
+
569
+ const leftGroup = quotaModelGroup(leftNormalized);
570
+ const rightGroup = quotaModelGroup(rightNormalized);
571
+ if (leftGroup && leftGroup === rightGroup && (isQuotaGroup(leftNormalized) || isQuotaGroup(rightNormalized))) {
572
+ return true;
573
+ }
574
+
575
+ const leftTier = /(low|medium|high)$/.exec(leftNormalized)?.[1];
576
+ const rightTier = /(low|medium|high)$/.exec(rightNormalized)?.[1];
577
+ if (leftTier && rightTier) return false;
578
+ const leftBase = leftTier ? leftNormalized.slice(0, -leftTier.length) : leftNormalized;
579
+ const rightBase = rightTier ? rightNormalized.slice(0, -rightTier.length) : rightNormalized;
580
+ return leftBase === rightBase;
581
+ }
582
+
583
+ function quotaModelGroup(normalized: string): "gemini" | "claude-gpt" | undefined {
584
+ if (normalized.startsWith("gemini")) return "gemini";
585
+ if (normalized.startsWith("claude") || normalized.startsWith("gptoss")) return "claude-gpt";
586
+ return undefined;
587
+ }
588
+
589
+ function isQuotaGroup(normalized: string): boolean {
590
+ return /^(?:gemini(?:models)?|claude(?:andgpt)?models?|gptossmodels?)$/.test(normalized);
591
+ }
592
+
593
+ /** Format a compact, agent-readable quota report for tool results and TUI status. */
594
+ export function formatAgyUsage(
595
+ snapshot: AgyUsageSnapshot | undefined,
596
+ selectedModel?: string,
597
+ ): string | undefined {
598
+ if (!snapshot) return undefined;
599
+ if (snapshot.models.length === 0) {
600
+ if (snapshot.error) return `agy quota unavailable: ${snapshot.error}`;
601
+ return snapshot.raw_summary ? `agy quota snapshot: ${snapshot.raw_summary}` : undefined;
602
+ }
603
+
604
+ const selectedEntries = selectedModel ? findAgyQuotaEntries(snapshot, selectedModel) : [];
605
+ const selectedSet = new Set(selectedEntries);
606
+ const ordered = selectedEntries.length
607
+ ? [...selectedEntries, ...snapshot.models.filter((entry) => !selectedSet.has(entry))]
608
+ : snapshot.models;
609
+ const lines = ordered.map((entry) => {
610
+ const values: string[] = [];
611
+ if (entry.window) values.push(`${entry.window} window`);
612
+ if (entry.remaining_fraction !== undefined) {
613
+ const percent = entry.remaining_fraction <= 1
614
+ ? entry.remaining_fraction * 100
615
+ : entry.remaining_fraction;
616
+ values.push(`${formatNumber(percent)}% remaining`);
617
+ }
618
+ if (entry.remaining_requests !== undefined) {
619
+ values.push(`${formatNumber(entry.remaining_requests)} requests left`);
620
+ }
621
+ if (entry.remaining_tokens !== undefined) {
622
+ values.push(`${formatNumber(entry.remaining_tokens)} tokens left`);
623
+ }
624
+ if (entry.reset_at) values.push(`resets ${entry.reset_at}`);
625
+ return `- ${entry.model}: ${values.join(", ") || "quota reported without remaining amount"}`;
626
+ });
627
+ return `agy model quota (refreshed ${snapshot.fetched_at}):\n${lines.join("\n")}`;
628
+ }
629
+
630
+ function isRecord(value: unknown): value is Record<string, unknown> {
631
+ return typeof value === "object" && value !== null && !Array.isArray(value);
632
+ }
633
+
634
+ function findModelName(value: Record<string, unknown>): string | undefined {
635
+ for (const key of MODEL_FIELD_KEYS) {
636
+ const candidate = value[key];
637
+ if (typeof candidate === "string" && looksLikeModelName(candidate)) return candidate;
638
+ }
639
+ return undefined;
640
+ }
641
+
642
+ function looksLikeModelName(value: string): boolean {
643
+ return /(?:gemini|claude|gpt[-_ ]?oss|flash|pro|sonnet|opus)/i.test(value);
644
+ }
645
+
646
+ function readQuotaEntry(
647
+ model: string,
648
+ value: Record<string, unknown>,
649
+ hintedWindow?: string,
650
+ ): AgyQuotaEntry | undefined {
651
+ const window = readString(value, WINDOW_KEYS) ?? hintedWindow;
652
+ const fraction = readNumber(value, REMAINING_FRACTION_KEYS);
653
+ const percent = readNumber(value, REMAINING_PERCENT_KEYS);
654
+ const normalizedFraction = fraction ?? (percent !== undefined ? percent / 100 : undefined);
655
+ const requests = readNumber(value, REMAINING_REQUEST_KEYS);
656
+ const tokens = readNumber(value, REMAINING_TOKEN_KEYS);
657
+ const reset = readReset(value, RESET_KEYS, RELATIVE_RESET_KEYS);
658
+ const exhausted =
659
+ value.exhausted === true || value.isExhausted === true || value.is_exhausted === true;
660
+ if (
661
+ normalizedFraction === undefined &&
662
+ requests === undefined &&
663
+ tokens === undefined &&
664
+ !reset &&
665
+ !exhausted
666
+ ) {
667
+ return undefined;
668
+ }
669
+ return {
670
+ model,
671
+ window,
672
+ remaining_fraction: exhausted ? 0 : normalizedFraction,
673
+ remaining_requests: requests,
674
+ remaining_tokens: tokens,
675
+ reset_at: reset,
676
+ };
677
+ }
678
+
679
+ function quotaWindowName(value: string): string | undefined {
680
+ const normalized = value.toLowerCase().replace(/[^a-z0-9]/g, "");
681
+ if (normalized === "weekly") return "weekly";
682
+ if (normalized === "daily") return "daily";
683
+ if (normalized === "monthly") return "monthly";
684
+ if (normalized === "fivehour" || normalized === "5h") return "five-hour";
685
+ return undefined;
686
+ }
687
+
688
+ function mergeQuotaEntries(existing: AgyQuotaEntry | undefined, next: AgyQuotaEntry): AgyQuotaEntry {
689
+ return {
690
+ model: existing?.model ?? next.model,
691
+ window: existing?.window ?? next.window,
692
+ remaining_fraction: next.remaining_fraction ?? existing?.remaining_fraction,
693
+ remaining_requests: next.remaining_requests ?? existing?.remaining_requests,
694
+ remaining_tokens: next.remaining_tokens ?? existing?.remaining_tokens,
695
+ reset_at: next.reset_at ?? existing?.reset_at,
696
+ };
697
+ }
698
+
699
+ function readNumber(value: Record<string, unknown>, keys: string[]): number | undefined {
700
+ for (const key of keys) {
701
+ const candidate = value[key];
702
+ const number = typeof candidate === "number" ? candidate : typeof candidate === "string" ? Number(candidate) : NaN;
703
+ if (Number.isFinite(number)) return number;
704
+ }
705
+ return undefined;
706
+ }
707
+
708
+ function readString(value: Record<string, unknown>, keys: string[]): string | undefined {
709
+ for (const key of keys) {
710
+ const candidate = value[key];
711
+ if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
712
+ }
713
+ return undefined;
714
+ }
715
+
716
+ function readReset(
717
+ value: Record<string, unknown>,
718
+ keys: string[],
719
+ relativeKeys: string[],
720
+ ): string | undefined {
721
+ for (const key of relativeKeys) {
722
+ const seconds = readNumber(value, [key]);
723
+ if (seconds !== undefined && seconds >= 0) return `in ${formatDuration(seconds)}`;
724
+ }
725
+ for (const key of keys) {
726
+ const candidate = value[key];
727
+ if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
728
+ if (typeof candidate === "number" && Number.isFinite(candidate)) {
729
+ const milliseconds = candidate < 1e12 ? candidate * 1000 : candidate;
730
+ const date = new Date(milliseconds);
731
+ if (Number.isFinite(date.getTime())) return date.toISOString();
732
+ }
733
+ }
734
+ return undefined;
735
+ }
736
+
737
+ function formatDuration(seconds: number): string {
738
+ if (seconds < 60) return `${Math.round(seconds)}s`;
739
+ const minutes = Math.round(seconds / 60);
740
+ if (minutes < 60) return `${minutes}m`;
741
+ const hours = Math.round(minutes / 60);
742
+ if (hours < 24) return `${hours}h`;
743
+ return `${Math.round(hours / 24)}d`;
744
+ }
745
+
746
+ function formatNumber(value: number): string {
747
+ return Number.isInteger(value) ? String(value) : value.toFixed(1).replace(/\.0$/, "");
748
+ }
749
+
298
750
  /**
299
751
  * Terminate a spawned agy process and any tools it started. Node's `signal`
300
752
  * and `timeout` spawn options only kill the direct child, so cancel/timeout
@@ -409,11 +861,17 @@ async function runPreflightCommand(
409
861
  } else {
410
862
  const msg = Buffer.concat(stderr).toString("utf8").trim();
411
863
  const status = `exit ${code}`;
864
+ // A failing --version probe usually means the CLI is present but
865
+ // not authenticated; every failure names the check that failed.
412
866
  const authHint =
413
867
  args[0] === "--version"
414
- ? "Antigravity CLI is not authenticated or not working"
415
- : "agy connectivity check failed";
416
- reject(new Error(`${authHint} (${status}). ${msg || "Run 'agy' interactively to authenticate."}`));
868
+ ? " — Antigravity CLI is not authenticated or not working"
869
+ : "";
870
+ reject(
871
+ new Error(
872
+ `${label} failed${authHint} (${status}). ${msg || "Run 'agy' interactively to authenticate."}`,
873
+ ),
874
+ );
417
875
  }
418
876
  });
419
877
  });
@@ -483,16 +941,27 @@ function spawnAgyInternal(
483
941
  const stderr: Buffer[] = [];
484
942
  let stdoutBytes = 0;
485
943
  let stderrBytes = 0;
944
+ let stdoutTruncated = false;
486
945
  let lineBuffer = "";
487
946
  let runResult: AgyRunResult = { response: "" };
947
+ const decoder = new StringDecoder("utf8");
488
948
 
489
- child.stdout.on("data", (d: Buffer) => {
490
- stdoutBytes = appendBounded(stdout, stdoutBytes, d);
491
- const chunk = appendStreamChunk(lineBuffer, d.toString("utf8"), onProgress);
949
+ const processStdoutText = (text: string): void => {
950
+ if (!text) return;
951
+ const chunk = appendStreamChunk(lineBuffer, text, onProgress);
492
952
  lineBuffer = chunk.lineBuffer;
493
953
  for (const line of chunk.lines) {
494
954
  runResult = processStreamLine(line, runResult, onProgress);
495
955
  }
956
+ };
957
+
958
+ child.stdout.on("data", (d: Buffer) => {
959
+ const before = stdoutBytes;
960
+ stdoutBytes = appendBounded(stdout, stdoutBytes, d);
961
+ // The raw buffer is only a fallback; flag overflow so a verbatim
962
+ // response is never served as silently truncated text.
963
+ if (before + d.length > stdoutBytes) stdoutTruncated = true;
964
+ processStdoutText(decoder.write(d));
496
965
  });
497
966
 
498
967
  child.stderr.on("data", (d: Buffer) => {
@@ -527,6 +996,9 @@ function spawnAgyInternal(
527
996
  const out = Buffer.concat(stdout).toString("utf8");
528
997
  const err = Buffer.concat(stderr).toString("utf8");
529
998
 
999
+ // Flush a partial UTF-8 sequence before handling the final record.
1000
+ processStdoutText(decoder.end());
1001
+
530
1002
  // JSONL producers normally terminate every record with a newline, but
531
1003
  // process failures can leave the final record unterminated. Parse it
532
1004
  // before handling the exit code so retry logic sees real activity and
@@ -554,7 +1026,13 @@ function spawnAgyInternal(
554
1026
 
555
1027
  // agy writes diagnostics to stderr even on successful runs. Keep it
556
1028
  // out of the response so JSON/stream parsing remains deterministic.
557
- resolve(finalizeRunResult(out, runResult));
1029
+ const finalized = finalizeRunResult(out, runResult);
1030
+ // Only responses served verbatim from the bounded raw capture can be
1031
+ // incomplete; anything parsed from a record was delivered in full.
1032
+ if (stdoutTruncated && !finalized.response_complete) {
1033
+ finalized.response += `\n\n(raw stdout capture was truncated at the ${MAX_CAPTURE_BYTES / 1024} KB fallback bound)`;
1034
+ }
1035
+ resolve(finalized);
558
1036
  });
559
1037
  });
560
1038
  });
@@ -70,6 +70,9 @@ export async function loadAgyConfig(
70
70
  if (typeof record.defaultModelCommand === "string") {
71
71
  config.defaultModelCommand = record.defaultModelCommand;
72
72
  }
73
+ if (typeof record.quotaBalancing === "boolean") {
74
+ config.quotaBalancing = record.quotaBalancing;
75
+ }
73
76
  if (typeof record.skipPermissions === "boolean") {
74
77
  config.skipPermissions = record.skipPermissions;
75
78
  } else if ("skipPermissions" in record) {
@@ -3,12 +3,17 @@ import { stat } from "node:fs/promises";
3
3
  import {
4
4
  buildAgyPrompt,
5
5
  detectVerifyCommand,
6
+ findAgyQuotaEntries,
7
+ formatAgyUsage,
6
8
  getAgyConversationId,
9
+ isAgyQuotaExhausted,
7
10
  isTransientAgyFailure,
8
11
  resolveAgyModelAlias,
12
+ resolveAgyModelId,
9
13
  spawnAgyStream,
10
14
  type AgyEffort,
11
15
  type AgyModel,
16
+ type AgyUsageSnapshot,
12
17
  } from "./cli.js";
13
18
  import { loadAgyConfig, resolveDefaultModel } from "./config.js";
14
19
  import type { AgyUsage } from "./stream.js";
@@ -50,6 +55,9 @@ export interface AgyExecutionDetails {
50
55
  duration_seconds?: number;
51
56
  changed_files?: string[];
52
57
  preexisting_files?: string[];
58
+ /** Model-specific quota information refreshed before the run, when supported. */
59
+ quota?: AgyUsageSnapshot;
60
+ quota_status?: "available" | "unknown";
53
61
  }
54
62
 
55
63
  export interface AgyExecutionResult {
@@ -120,9 +128,36 @@ export async function executeAgyTask(
120
128
  verifyCmd,
121
129
  );
122
130
 
131
+ let quota: AgyUsageSnapshot | undefined;
132
+ let quotaStatus: "available" | "unknown" | undefined;
123
133
  const run = await runWithTransientRetry(async (trackProgress) => {
124
134
  const remainingMs = remainingBudget(startedAt, options.timeout_ms);
125
- await runPreflight(options.dir, abortSignal, remainingMs);
135
+ quota = await runPreflight(options.dir, abortSignal, remainingMs);
136
+ const selectedModelId = resolveAgyModelId(model, options.tier);
137
+ const selectedQuotas = findAgyQuotaEntries(quota, selectedModelId);
138
+ quotaStatus = quota
139
+ ? selectedQuotas.length === 0
140
+ ? "unknown"
141
+ : "available"
142
+ : undefined;
143
+ const quotaSummary = quota ? formatAgyUsage(quota, selectedModelId) : undefined;
144
+ if (quotaSummary) onProgress?.(quotaSummary);
145
+ if (selectedQuotas.some((entry) => isAgyQuotaExhausted(entry))) {
146
+ const quotaEntries = quota?.models ?? [];
147
+ const alternatives = [...new Set(quotaEntries.map((entry) => entry.model))]
148
+ .filter((candidate) => candidate.toLowerCase() !== selectedModelId.toLowerCase())
149
+ .filter((candidate) =>
150
+ quotaEntries
151
+ .filter((entry) => entry.model === candidate)
152
+ .every((entry) => !isAgyQuotaExhausted(entry)),
153
+ );
154
+ const alternativeText = alternatives.length
155
+ ? ` Available reported alternatives: ${alternatives.join(", ")}.`
156
+ : " No available alternative was reported.";
157
+ throw new Error(
158
+ `agy quota exhausted for ${selectedModelId}; choose another model or run agy_usage first.${alternativeText}\n${quotaSummary ?? ""}`,
159
+ );
160
+ }
126
161
  const runTimeoutMs = remainingBudget(startedAt, options.timeout_ms);
127
162
  // Emitted via onProgress directly: progress tracking (and therefore
128
163
  // retry eligibility) must only reflect activity from agy itself.
@@ -159,6 +194,10 @@ export async function executeAgyTask(
159
194
  remainingBudget(startedAt, options.timeout_ms);
160
195
 
161
196
  let text = run.response;
197
+ const quotaSummary = quota?.models.length
198
+ ? formatAgyUsage(quota, resolveAgyModelId(model, options.tier))
199
+ : undefined;
200
+ if (quotaSummary) text = `${text}\n\n## agy quota snapshot\n${quotaSummary}`;
162
201
  let changedFiles: string[] | undefined;
163
202
  let preexistingFiles: string[] | undefined;
164
203
  if (options.mode === "accept-edits") {
@@ -186,6 +225,8 @@ export async function executeAgyTask(
186
225
  duration_seconds: run.duration_seconds,
187
226
  changed_files: changedFiles,
188
227
  preexisting_files: preexistingFiles,
228
+ quota,
229
+ quota_status: quotaStatus,
189
230
  },
190
231
  };
191
232
  },
@@ -67,6 +67,12 @@ async function withFileLock<T>(
67
67
  try {
68
68
  const lockStat = await statFile(lockPath);
69
69
  if (Date.now() - lockStat.mtimeMs > LOCK_STALE_MS) {
70
+ // Stale recovery has an irreducible stat→rm race: another process
71
+ // can recover the same stale lock in between and install a fresh
72
+ // one that this rm then deletes, briefly admitting two holders.
73
+ // The heartbeat keeps live locks fresh, the owner check on release
74
+ // limits the damage, and the window is a single await wide — an
75
+ // accepted cost for a best-effort agent-serialization lock.
70
76
  await rm(lockPath, { recursive: true, force: true });
71
77
  continue;
72
78
  }
@@ -25,9 +25,23 @@ export async function captureGitBaseline(cwd: string, signal?: AbortSignal): Pro
25
25
  for (const line of stdout.split("\n")) {
26
26
  const trimmed = line.trim();
27
27
  if (!trimmed) continue;
28
- // Porcelain v1: XY <path>[ -> <orig>]. Keep the raw path token(s).
28
+ // Porcelain v1: XY <path>[ -> <orig>]. Rename/copy entries print
29
+ // `ORIG -> NEW` while `diff --name-only` reports only NEW, so record
30
+ // both sides — otherwise a pre-existing rename looks newly-dirty
31
+ // after the run and is misattributed to agy.
32
+ const status = trimmed.slice(0, 2);
29
33
  const file = trimmed.slice(3).trim();
30
- if (file) dirtyFiles.add(file);
34
+ if (!file) continue;
35
+ const isRenameOrCopy = status.includes("R") || status.includes("C");
36
+ const arrow = file.indexOf(" -> ");
37
+ if (isRenameOrCopy && arrow !== -1) {
38
+ const orig = file.slice(0, arrow).trim();
39
+ const renamed = file.slice(arrow + " -> ".length).trim();
40
+ if (orig) dirtyFiles.add(orig);
41
+ if (renamed) dirtyFiles.add(renamed);
42
+ } else {
43
+ dirtyFiles.add(file);
44
+ }
31
45
  }
32
46
  return { dirtyFiles, unavailable: false };
33
47
  } catch {
@@ -1,26 +1,51 @@
1
- import { checkAgyConnectivity, checkAgyHealth } from "./cli.js";
1
+ import {
2
+ checkAgyConnectivity,
3
+ checkAgyHealth,
4
+ checkAgyUsage,
5
+ type AgyUsageSnapshot,
6
+ } from "./cli.js";
2
7
 
3
8
  const TTL_MS = 5 * 60 * 1000;
9
+ const USAGE_TTL_MS = 60 * 1000;
10
+ const USAGE_FAILURE_TTL_MS = 5 * 1000;
4
11
  let cachedAt = 0;
12
+ let cachedUsageAt = 0;
13
+ let cachedUsage: AgyUsageSnapshot | undefined;
5
14
 
6
- /** Run agy health/connectivity checks, cached for a few minutes per process. */
15
+ /** Run cached health/model checks and a shorter-lived model quota refresh. */
7
16
  export async function runPreflight(
8
17
  cwd: string,
9
18
  signal?: AbortSignal,
10
19
  timeoutMs?: number,
11
- ): Promise<void> {
12
- if (cachedAt && Date.now() - cachedAt < TTL_MS) return;
20
+ ): Promise<AgyUsageSnapshot | undefined> {
21
+ const now = Date.now();
22
+ const healthFresh = cachedAt > 0 && now - cachedAt < TTL_MS;
23
+ const usageTtl = cachedUsage?.error || !cachedUsage ? USAGE_FAILURE_TTL_MS : USAGE_TTL_MS;
24
+ const usageFresh = cachedUsageAt > 0 && now - cachedUsageAt < usageTtl;
25
+ if (healthFresh && usageFresh) return cachedUsage;
13
26
  if (timeoutMs !== undefined && timeoutMs <= 0) {
14
27
  throw new Error("agy timed out before preflight");
15
28
  }
16
- await Promise.all([
17
- checkAgyHealth(cwd, signal, timeoutMs),
18
- checkAgyConnectivity(cwd, signal, timeoutMs),
19
- ]);
20
- cachedAt = Date.now();
29
+
30
+ const health = healthFresh
31
+ ? Promise.resolve()
32
+ : Promise.all([
33
+ checkAgyHealth(cwd, signal, timeoutMs),
34
+ checkAgyConnectivity(cwd, signal, timeoutMs),
35
+ ]).then(() => undefined);
36
+ const usage = usageFresh ? Promise.resolve(cachedUsage) : checkAgyUsage(cwd, signal, timeoutMs);
37
+ const [, refreshedUsage] = await Promise.all([health, usage]);
38
+ if (!healthFresh) cachedAt = Date.now();
39
+ if (!usageFresh) {
40
+ cachedUsage = refreshedUsage;
41
+ cachedUsageAt = Date.now();
42
+ }
43
+ return cachedUsage;
21
44
  }
22
45
 
23
46
  /** Test helper — reset the in-process cache. */
24
47
  export function resetPreflightCache(): void {
25
48
  cachedAt = 0;
49
+ cachedUsageAt = 0;
50
+ cachedUsage = undefined;
26
51
  }
@@ -174,6 +174,9 @@ export function createSessionStore(
174
174
  try {
175
175
  const lockStat = await statFile(lockPath);
176
176
  if (Date.now() - lockStat.mtimeMs > LOCK_STALE_MS) {
177
+ // Same irreducible stat→rm race as the dir lock in lock.ts; the
178
+ // critical section here is a single fast read-modify-write, so
179
+ // the 30 s staleness margin dwarfs the window. Accepted cost.
177
180
  await rm(lockPath, { recursive: true, force: true });
178
181
  continue;
179
182
  }
@@ -94,10 +94,13 @@ export function formatStepProgress(parsed: AgyStreamLine): string | null {
94
94
  }
95
95
 
96
96
  export const MAX_RESPONSE_CHARS = 1_000_000;
97
- // A single JSONL record without a newline is almost certainly a runaway or
98
- // hostile producer. Discard it with a warning instead of growing memory
99
- // without bound.
100
- export const MAX_STREAM_LINE_BYTES = 256 * 1024;
97
+ // One JSONL record is bounded at the largest legitimate result event:
98
+ // MAX_RESPONSE_CHARS with worst-case JSON escaping (\uXXXX = 6 bytes per
99
+ // char) plus envelope headroom. A record that grows past this is either
100
+ // malfunctioning or hostile, so it is discarded with a warning — the bound
101
+ // applies equally to terminated records and to an unterminated buffer,
102
+ // because a legitimate large result is itself unterminated while it streams.
103
+ export const MAX_STREAM_LINE_BYTES = 8 * 1024 * 1024;
101
104
 
102
105
  export interface StreamChunk {
103
106
  /** Complete newline-terminated records ready to parse. */
@@ -120,7 +123,7 @@ export function appendStreamChunk(
120
123
  onProgress?.("agy: warning — discarded oversized stream record", "status");
121
124
  const combined = lineBuffer + chunk;
122
125
  if (!combined.includes("\n")) {
123
- if (combined.length > MAX_STREAM_LINE_BYTES) {
126
+ if (Buffer.byteLength(combined, "utf8") > MAX_STREAM_LINE_BYTES) {
124
127
  warn();
125
128
  return { lines: [], lineBuffer: "" };
126
129
  }
@@ -128,13 +131,13 @@ export function appendStreamChunk(
128
131
  }
129
132
  const parts = combined.split("\n");
130
133
  let remainder = parts.pop() ?? "";
131
- if (remainder.length > MAX_STREAM_LINE_BYTES) {
134
+ if (Buffer.byteLength(remainder, "utf8") > MAX_STREAM_LINE_BYTES) {
132
135
  warn();
133
136
  remainder = "";
134
137
  }
135
138
  const lines: string[] = [];
136
139
  for (const line of parts) {
137
- if (line.length > MAX_STREAM_LINE_BYTES) {
140
+ if (Buffer.byteLength(line, "utf8") > MAX_STREAM_LINE_BYTES) {
138
141
  warn();
139
142
  continue;
140
143
  }
@@ -146,23 +149,29 @@ export function appendStreamChunk(
146
149
  export function accumulateRunResult(parsed: AgyStreamLine, current: AgyRunResult): AgyRunResult {
147
150
  const next = { ...current };
148
151
 
149
- if (parsed.conversation_id) next.conversation_id = parsed.conversation_id;
150
- if (parsed.init && parsed.conversation_id) next.conversation_id = parsed.conversation_id;
152
+ if (typeof parsed.conversation_id === "string") next.conversation_id = parsed.conversation_id;
151
153
 
152
154
  const step = parsed.step_update;
153
- if (step?.conversation_id) next.conversation_id = step.conversation_id;
155
+ if (typeof step?.conversation_id === "string") next.conversation_id = step.conversation_id;
154
156
 
155
157
  if (parsed.result) {
156
- if (parsed.result.conversation_id) next.conversation_id = parsed.result.conversation_id;
157
- if (parsed.result.response != null) {
158
+ if (typeof parsed.result.conversation_id === "string") {
159
+ next.conversation_id = parsed.result.conversation_id;
160
+ }
161
+ if (typeof parsed.result.response === "string") {
158
162
  next.response =
159
163
  parsed.result.response.length > MAX_RESPONSE_CHARS
160
164
  ? parsed.result.response.slice(0, MAX_RESPONSE_CHARS) + "\n\n(response truncated)"
161
165
  : parsed.result.response;
162
166
  next.response_complete = true;
163
167
  }
164
- if (parsed.result.usage) next.usage = parsed.result.usage;
165
- if (parsed.result.duration_seconds != null) {
168
+ if (typeof parsed.result.usage === "object" && parsed.result.usage !== null) {
169
+ next.usage = parsed.result.usage;
170
+ }
171
+ if (
172
+ typeof parsed.result.duration_seconds === "number" &&
173
+ Number.isFinite(parsed.result.duration_seconds)
174
+ ) {
166
175
  next.duration_seconds = parsed.result.duration_seconds;
167
176
  }
168
177
  }
@@ -76,15 +76,17 @@ async function hasJustCi(cwd: string): Promise<boolean> {
76
76
  let justBinaryProbe: Promise<boolean> | undefined;
77
77
 
78
78
  async function justBinaryAvailable(): Promise<boolean> {
79
- justBinaryProbe ??= (async () => {
80
- try {
81
- await execFileAsync("just", ["--version"], { timeout: 5_000 });
82
- return true;
83
- } catch {
84
- return false;
85
- }
86
- })();
87
- return justBinaryProbe;
79
+ // Cache only while positive: `just` may be installed mid-session, and a
80
+ // failed probe is cheap (ENOENT fails without actually spawning a process).
81
+ if (!justBinaryProbe) {
82
+ justBinaryProbe = execFileAsync("just", ["--version"], { timeout: 5_000 }).then(
83
+ () => true,
84
+ () => false,
85
+ );
86
+ }
87
+ const available = await justBinaryProbe;
88
+ if (!available) justBinaryProbe = undefined;
89
+ return available;
88
90
  }
89
91
 
90
92
  /** Python projects: `uv run pytest` when pyproject uses uv and references pytest. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanbenjumea/pi-agy",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Enhanced Antigravity CLI (agy) bridge for Pi — streaming progress, conversation continuity, repo-aware verify, and diff summaries.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -53,6 +53,6 @@
53
53
  "typescript": "^5.0.0"
54
54
  },
55
55
  "engines": {
56
- "node": ">=20.0.0"
56
+ "node": ">=20.3.0"
57
57
  }
58
58
  }
@@ -9,8 +9,9 @@ license: MIT
9
9
 
10
10
  # agy-delegate
11
11
 
12
- Use the `agy_execute` tool to offload large scaffolding, repetitive refactors,
13
- or exhaustive test generation via the Antigravity CLI.
12
+ Use the `agy_usage` tool to inspect model-specific quota and reset times when
13
+ availability matters, then use `agy_execute` to offload large scaffolding,
14
+ repetitive refactors, or exhaustive test generation via the Antigravity CLI.
14
15
 
15
16
  ## Prerequisites
16
17
 
@@ -41,6 +42,7 @@ agy_execute prompt="Generate exhaustive unit tests for src/auth/" model=flash-lo
41
42
  agy_execute prompt="Plan the migration to ESM" model=sonnet mode=plan digest=true
42
43
  agy_execute prompt="Implement the approved plan" conversation_id=<id> mode=accept-edits
43
44
  agy_execute prompt="Adversarial review the diff" model=opus effort=high mode=plan
45
+ agy_usage
44
46
  ```
45
47
 
46
48
  ## Modes
@@ -68,6 +70,7 @@ agy_execute prompt="Adversarial review the diff" model=opus effort=high mode=pla
68
70
 
69
71
  ## Enhancements over upstream pi-agy
70
72
 
73
+ - **Quota discovery** — `agy_usage` and `/agy usage` report model-specific remaining quota and reset times; executions refresh quota snapshots and return machine-readable `quota_status` as well.
71
74
  - **Streaming progress** — live tool steps via `stream-json` and Pi `onUpdate`.
72
75
  - **Conversation continuity** — `conversation_id`, `continue`, session store under `$PI_CODING_AGENT_DIR/agy-sessions.json` (or `~/.pi/agent/agy-sessions.json` by default).
73
76
  - **Repo-aware verify** — prefers `just ci` when a justfile defines `ci:`.