@juanbenjumea/pi-agy 0.7.9 → 0.7.12

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,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.12
4
+
5
+ - Refresh the full Antigravity model catalog automatically at session startup and whenever Pi opens `/model`, using Pi's native refresh lifecycle instead of a one-time discovery probe.
6
+ - Discover nonhyphen IDs such as `argon` and new model generations without hardcoded catalog updates; preserve exact CLI names and existing Gemini effort grouping.
7
+ - Retain the last good catalog on discovery failures and retry on the next picker opening; reject canceled, superseded, and shutdown refresh results.
8
+ - Add real Pi runtime and model-picker integration regressions. Full 465-test gate, typecheck, and package checks pass; live discovery still requires an authenticated agy CLI.
9
+
10
+ ## 0.7.11
11
+
12
+ - Preserve exclusive provider-turn ownership across tool suspension, resumption, and terminal delivery; reject competing turns before they alter bridge tools.
13
+ - Retain terminal responses received while awaiting Pi tools for exactly one continuation, with bounded abandonment and safe process reuse.
14
+ - Reclaim orphaned bridge calls, suspended state, staged images, and unpolled escalation results on completion or abandonment, including races before suspension publication.
15
+ - Add lifecycle and real-loopback/fake-process regression coverage; 455 tests, typecheck, and package checks pass.
16
+
17
+ ## 0.7.10
18
+
19
+ - Harden process-tree cancellation, provider tool forwarding, bridge reconnection, terminal response handling, and cancelled resumes.
20
+ - Bound bridge request complexity and refresh the MCP dependency floor and qualified Pi development dependencies.
21
+ - Derive delegation model aliases and tool schemas from one definition; normalize conversation selection while preserving resume behavior.
22
+ - Keep completed background polling compact; retrieve full results with `agy_tasks collect`.
23
+ - Expand regression coverage to 414 tests; typecheck and package checks pass.
24
+
3
25
  ## 0.7.9
4
26
 
5
27
  - Rewrite the README as a concise overview of agy task delegation and the Antigravity provider, retaining installation, configuration, and development essentials.
package/README.md CHANGED
@@ -37,12 +37,20 @@ In `accept-edits` mode, Pi confirms before writes. agy's own permission behavior
37
37
 
38
38
  ## Use agy as a Pi model
39
39
 
40
- The package registers an `antigravity` provider. Select discovered models as `antigravity/<model>` in Pi's `/model` picker. Models are discovered from `agy models`, with a fallback catalog if discovery fails. Gemini thinking levels map to agy's supported effort tiers.
40
+ The package registers an `antigravity` provider. Select discovered models as `antigravity/<model>` in Pi's `/model` picker. Models refresh automatically from `agy models` at session startup and whenever Pi opens the model picker (Pi 1.5.2 native refresh). New model names need no package update. Failed discovery keeps the last good catalog, or the synchronous fallback before the first success; reopen `/model` after signing in to retry. Cache-only refreshes never run the CLI. Gemini thinking levels map to agy's supported effort tiers.
41
41
 
42
42
  Provider turns use a persistent agy process per working directory and can stage attached images for agy to read. By default, an MCP bridge gives agy read-only Pi context and lets it call active Pi tools through Pi's normal permission and approval flow. Set `"providerBridge": false` in `agy-config.json` to disable the bridge.
43
43
 
44
44
  Do not install `@estebanforge/pi-antigravity-bridge` alongside this package: both register the `antigravity` provider and `/agy` command.
45
45
 
46
+ ### Bridge input limits
47
+
48
+ Authenticated bridge POSTs retain a **1 MiB UTF-8 body cap** and allow at most **10,000 object properties plus array elements** across the entire parsed JSON-RPC body, including metadata, with at most **64 container levels** (root container = level 1). Scalar string content counts toward bytes, not structural elements. Overly wide/deep requests return HTTP **413** before SDK validation, session allocation or tool parking; oversized byte streams retain the existing connection-close behavior. Authentication and localhost Host checks happen first, but authentication alone is not a complexity budget.
49
+
50
+ The bridge uses the SDK's low-level `Server`, not the high-level `McpServer` tool validator, so it enforces these local structural limits rather than relying on `maxToolInputElements`. These are defensive input bounds, not a guarantee against all resource exhaustion.
51
+
52
+ The SDK dependency floor is `^1.32.2`; the repository lock qualifies SDK 1.32.2, Zod 4.6.7 and body-parser 2.4.0. A library consumer resolves its own dependency graph: the SDK still permits older Zod through `^3.25 || ^4.0`, and overrides in this package would not enforce a consumer's resolutions. Audit the actual consumer tree; a patched repository lock is not a universal downstream security guarantee.
53
+
46
54
  ## Configuration
47
55
 
48
56
  Optional file: `$PI_CODING_AGENT_DIR/agy-config.json` (default `~/.pi/agent/agy-config.json`). For example:
@@ -59,6 +67,8 @@ Optional file: `$PI_CODING_AGENT_DIR/agy-config.json` (default `~/.pi/agent/agy-
59
67
 
60
68
  ## Development
61
69
 
70
+ Development tests are qualified against the exact Pi SDK fixture version 1.5.2, which requires Node >=22.19.0; qualification ran on Node 22.23.4. The resolved development graph is qualified; embedded Undici is not independently attested.
71
+
62
72
  ```bash
63
73
  npm test
64
74
  npm run typecheck
@@ -8,6 +8,7 @@ import { describeWhen, truncate } from "./lib/output.js";
8
8
  import { buildAcceptEditsConfirm } from "./lib/confirm.js";
9
9
  import { AGY_RUN_ENTRY_TYPE, type AgyRunReceipt } from "./lib/render.js";
10
10
  import { getHistory } from "./lib/sessions.js";
11
+ import { normalizeConversationSelection, type ConversationSelection } from "./lib/request.js";
11
12
 
12
13
  export interface InteractiveRun {
13
14
  mode: "plan" | "accept-edits" | "sandbox";
@@ -83,11 +84,23 @@ export async function executeConfirmedRun(
83
84
  run: InteractiveRun,
84
85
  ): Promise<void> {
85
86
  const cwd = ctx.cwd;
87
+ let selection: ConversationSelection;
88
+ try {
89
+ selection = normalizeConversationSelection(run);
90
+ } catch (error) {
91
+ if (ctx.signal?.aborted) {
92
+ ctx.ui.notify("agy: cancelled", "info");
93
+ } else {
94
+ const message = error instanceof Error ? error.message : String(error);
95
+ ctx.ui.notify(`agy failed: ${message}`, "error");
96
+ }
97
+ return;
98
+ }
86
99
  await ctx.waitForIdle();
87
100
  const requestedContextMode = run.context ?? "none";
88
101
  const contextMode = effectiveResumeContextMode(
89
102
  requestedContextMode,
90
- Boolean(run.conversation_id || run.continue),
103
+ selection.kind !== "new",
91
104
  );
92
105
  const contextText =
93
106
  contextMode === "none"
@@ -127,7 +140,7 @@ export async function executeConfirmedRun(
127
140
  timeout_ms: run.timeout_ms ?? DEFAULT_TIMEOUT_MS,
128
141
  conversation_id: run.conversation_id,
129
142
  continue: run.continue,
130
- new_session: run.conversation_id || run.continue ? false : true,
143
+ new_session: selection.kind === "new",
131
144
  stream: true,
132
145
  context: contextMode,
133
146
  context_text: contextText,
@@ -6,8 +6,8 @@ import {
6
6
  type AssistantMessageEvent,
7
7
  type AssistantMessageEventStream,
8
8
  type Model,
9
+ type Provider,
9
10
  type SimpleStreamOptions,
10
- type TranscriptContext,
11
11
  } from "@earendil-works/pi-ai";
12
12
  import { registerAgyCommand } from "./commands.js";
13
13
  import { closeProviderDrivers } from "./lib/provider.js";
@@ -36,20 +36,19 @@ export { truncate } from "./lib/output.js";
36
36
  * Register agy-backed models in Pi's global `/model` picker as
37
37
  * `antigravity/*`.
38
38
  *
39
- * Registers synchronously with the fallback catalog so provider setup can
40
- * never break extension load (or the delegation tools below); then refreshes
41
- * from live `agy models` in the background and re-registers when the catalog
42
- * changed — applied immediately, no `/reload` required. Refresh failures keep
43
- * the fallback. Do not install `@estebanforge/pi-antigravity-bridge`
44
- * alongside this package: both register the `antigravity` provider id and an
45
- * `/agy` command.
39
+ * Registers a synchronous fallback and lets Pi refresh the catalog whenever
40
+ * its model picker opens. Both picker definitions and turn resolution are
41
+ * published atomically through Pi's generation-checked native refresh API.
42
+ * Do not install `@estebanforge/pi-antigravity-bridge` alongside this package:
43
+ * both register the `antigravity` provider id and an `/agy` command.
46
44
  */
47
45
  function registerAgyProvider(pi: ExtensionAPI): void {
48
46
  if (typeof pi.registerProvider !== "function") return;
49
- // Shared mutable catalog: the turn handler closes over this array, so a
50
- // background refresh updates picker models without losing conversation
51
- // continuity or re-creating the handler.
47
+ // Keep one handler and catalog array for conversation/driver continuity.
48
+ // Only a generation-checked publication may mutate these entries.
52
49
  const entries: AgyProviderModelEntry[] = [...FALLBACK_PROVIDER_MODELS];
50
+ const shutdown = new AbortController();
51
+ pi.on?.("session_shutdown", () => { shutdown.abort(); });
53
52
  const streamSimple = createAgyStreamSimple(
54
53
  {
55
54
  createStream: () => {
@@ -68,58 +67,76 @@ function registerAgyProvider(pi: ExtensionAPI): void {
68
67
  },
69
68
  { entries },
70
69
  );
71
- const register = (): void => {
72
- pi.registerProvider(AGY_PROVIDER_ID, {
73
- name: "Antigravity (agy)",
74
- baseUrl: "agy-provider://antigravity",
75
- apiKey: "not-used",
70
+ const baseUrl = "agy-provider://antigravity";
71
+ const modelDefinitions = (catalog: readonly AgyProviderModelEntry[]): Model<any>[] =>
72
+ catalog.map((entry) => ({
73
+ ...toProviderModelDef(entry),
76
74
  api: AGY_PROVIDER_API,
77
- models: entries.map((entry) => ({
78
- ...toProviderModelDef(entry),
79
- api: AGY_PROVIDER_API,
80
- })),
81
- streamSimple: (
82
- model: Model<any>,
83
- context: TranscriptContext,
84
- options?: SimpleStreamOptions,
85
- ): AssistantMessageEventStream =>
86
- streamSimple(
87
- { id: model.id },
88
- context.messages as unknown as ProviderTranscriptMessage[],
89
- options
90
- ? {
91
- signal: options.signal,
92
- reasoning: options.reasoning,
93
- tools: getCurrentTools(context.messages) as unknown as ProviderToolSource[],
94
- }
95
- : undefined,
96
- ) as unknown as AssistantMessageEventStream,
97
- });
75
+ provider: AGY_PROVIDER_ID,
76
+ baseUrl,
77
+ }));
78
+ let models = modelDefinitions(entries);
79
+ const stream: Provider["streamSimple"] = (model, context, options) =>
80
+ streamSimple(
81
+ { id: model.id },
82
+ context.messages as unknown as ProviderTranscriptMessage[],
83
+ {
84
+ signal: options?.signal,
85
+ reasoning: options?.reasoning,
86
+ tools: getCurrentTools(context.messages) as unknown as ProviderToolSource[],
87
+ },
88
+ ) as unknown as AssistantMessageEventStream;
89
+ const provider: Provider = {
90
+ id: AGY_PROVIDER_ID,
91
+ name: "Antigravity (agy)",
92
+ baseUrl,
93
+ // agy owns authentication. Pi must regard this ambient CLI provider as
94
+ // configured so refresh can recover after the user signs in to agy.
95
+ auth: { apiKey: { name: "Antigravity CLI", resolve: async () => ({ auth: { apiKey: "not-used" } }) } },
96
+ getModels: () => models,
97
+ async refreshModels(context) {
98
+ const signal = AbortSignal.any([context.signal, shutdown.signal]);
99
+ signal.throwIfAborted();
100
+ // Native refresh first calls a cache-only phase, even for network
101
+ // refreshes. Never launch agy (which can contact its server) there.
102
+ if (!context.allowNetwork) return;
103
+ const raw = await runPreflightCommand(
104
+ ["models"], process.cwd(), signal, "agy provider model discovery", true,
105
+ );
106
+ signal.throwIfAborted();
107
+ const live = parseProviderCatalog(raw);
108
+ if (live.length === 0) throw new Error("agy models returned no usable models");
109
+ if (areProviderCatalogsEqual(entries, live)) return;
110
+ const definitions = modelDefinitions(live);
111
+ await context.publish({
112
+ update: () => {
113
+ // Pi checks its generation/signal immediately before this callback;
114
+ // session shutdown also invalidates a still-live runtime's refresh.
115
+ signal.throwIfAborted();
116
+ entries.splice(0, entries.length, ...live);
117
+ models = definitions;
118
+ },
119
+ });
120
+ },
121
+ stream: (model, context, options) => stream(model, context, options as SimpleStreamOptions),
122
+ streamSimple: stream,
98
123
  };
99
124
  try {
100
- register();
125
+ pi.registerProvider(provider);
101
126
  } catch {
102
127
  // Provider setup is additive; delegation tools must survive it.
128
+ shutdown.abort();
103
129
  return;
104
130
  }
105
- void (async () => {
106
- try {
107
- const raw = await runPreflightCommand(
108
- ["models"],
109
- process.cwd(),
110
- undefined,
111
- "agy provider model discovery",
112
- true,
113
- );
114
- const live = parseProviderCatalog(raw);
115
- if (live.length === 0) return;
116
- if (areProviderCatalogsEqual(entries, live)) return;
117
- entries.splice(0, entries.length, ...live);
118
- register();
119
- } catch {
120
- // Refresh failures keep the fallback catalog.
131
+ pi.on?.("session_start", async (_event, ctx) => {
132
+ const signal = AbortSignal.any([shutdown.signal, AbortSignal.timeout(10_000)]);
133
+ const result = await ctx.modelRegistry.refresh({
134
+ providers: [AGY_PROVIDER_ID], allowNetwork: true, signal,
135
+ });
136
+ if (!signal.aborted && result.errors.has(AGY_PROVIDER_ID)) {
137
+ ctx.ui.notify("Could not refresh Antigravity models; showing cached models. Reopen /model to retry.", "warning");
121
138
  }
122
- })();
139
+ });
123
140
  }
124
141
 
125
142
  export default function piAgyExtension(pi: ExtensionAPI) {
@@ -0,0 +1,37 @@
1
+ /** Limits for the complete parsed bridge request, including JSON-RPC metadata. */
2
+ export const MAX_BRIDGE_INPUT_ELEMENTS = 10_000;
3
+ export const MAX_BRIDGE_INPUT_DEPTH = 64;
4
+
5
+ /**
6
+ * Bounds structure before SDK validation. Input must come from JSON.parse:
7
+ * this is not schema validation or a walker for arbitrary JS accessors/proxies.
8
+ * Count object properties and array slots; only containers contribute depth.
9
+ * The root container has depth 1. Strings remain subject to the byte reader.
10
+ */
11
+ export function isBridgeInputWithinBudget(value: unknown): boolean {
12
+ if (value === null || typeof value !== "object") return true;
13
+ const pending: Array<{ node: object; depth: number }> = [{ node: value, depth: 1 }];
14
+ let elements = 0;
15
+ while (pending.length > 0) {
16
+ const { node, depth } = pending.pop()!;
17
+ const array = Array.isArray(node);
18
+ if (array) {
19
+ // Refuse wide arrays before reading or queuing any of their children.
20
+ elements += node.length;
21
+ if (elements > MAX_BRIDGE_INPUT_ELEMENTS) return false;
22
+ }
23
+ // Do not allocate Object.entries/values or flatten all descendants.
24
+ for (const key in node) {
25
+ if (!Object.hasOwn(node, key)) continue;
26
+ if (!array && ++elements > MAX_BRIDGE_INPUT_ELEMENTS) return false;
27
+ const child = (node as Record<string, unknown>)[key];
28
+ if (child !== null && typeof child === "object") {
29
+ if (depth >= MAX_BRIDGE_INPUT_DEPTH) return false;
30
+ // Every queued child is charged to an already-counted property/slot:
31
+ // the worklist cannot exceed the finite element budget.
32
+ pending.push({ node: child, depth: depth + 1 });
33
+ }
34
+ }
35
+ }
36
+ return true;
37
+ }
@@ -1,17 +1,7 @@
1
1
  export { detectVerifyCommand, detectVerifyCommandFromPackageJson } from "./verify.js";
2
2
  export { parseJsonResponse } from "./parse.js";
3
3
 
4
- export type AgyModel =
5
- | "flash-low"
6
- | "flash-medium"
7
- | "flash-high"
8
- | "pro-low"
9
- | "pro-high"
10
- | "sonnet"
11
- | "opus"
12
- | "gpt-oss";
13
-
14
- export const AGY_MODEL_ALIASES: readonly AgyModel[] = [
4
+ export const AGY_MODEL_ALIASES = [
15
5
  "flash-low",
16
6
  "flash-medium",
17
7
  "flash-high",
@@ -20,7 +10,9 @@ export const AGY_MODEL_ALIASES: readonly AgyModel[] = [
20
10
  "sonnet",
21
11
  "opus",
22
12
  "gpt-oss",
23
- ];
13
+ ] as const;
14
+
15
+ export type AgyModel = typeof AGY_MODEL_ALIASES[number];
24
16
 
25
17
  export function isAgyModel(value: unknown): value is AgyModel {
26
18
  return typeof value === "string" && (AGY_MODEL_ALIASES as readonly string[]).includes(value);
@@ -35,6 +35,7 @@ import {
35
35
  } from "./postflight.js";
36
36
  import { resetPreflightCache, runPreflight } from "./preflight.js";
37
37
  import { getHistory, getSession, saveSession, conversationSummary } from "./sessions.js";
38
+ import { normalizeConversationSelection } from "./request.js";
38
39
 
39
40
  export type AgyMode = "plan" | "accept-edits" | "sandbox";
40
41
 
@@ -92,6 +93,7 @@ export async function executeAgyTask(
92
93
  onProgress?: (message: string) => void,
93
94
  ): Promise<AgyExecutionResult> {
94
95
  validateAgyExecutionOptions(options);
96
+ const selection = normalizeConversationSelection(options);
95
97
  let agent = normalizeAgyAgentName(options.agent);
96
98
  const startedAt = Date.now();
97
99
  const budgetController = new AbortController();
@@ -123,17 +125,18 @@ export async function executeAgyTask(
123
125
  throw new Error(`Working directory is not a directory: ${options.dir}`);
124
126
  }
125
127
 
126
- let conversationId = options.conversation_id;
127
- const resumesLatest = options.continue || options.new_session === false;
128
+ let conversationId = selection.kind === "resume" ? selection.id : undefined;
129
+ // Explicit IDs with new_session=false historically inherit the latest
130
+ // agent too. This lookup policy is separate from the selected CLI ID.
131
+ const resumesLatest = selection.kind === "latest" || options.new_session === false;
128
132
  const prior =
129
133
  (!conversationId && options.new_session !== true) || (!agent && resumesLatest)
130
134
  ? await getSession(options.dir)
131
135
  : undefined;
132
136
  if (
133
- !conversationId &&
134
- !options.continue &&
135
- prior?.last_conversation_id &&
136
- options.new_session === false
137
+ selection.kind === "latest" &&
138
+ selection.source === "recorded" &&
139
+ prior?.last_conversation_id
137
140
  ) {
138
141
  conversationId = prior.last_conversation_id;
139
142
  }
@@ -227,7 +230,7 @@ export async function executeAgyTask(
227
230
  dir: options.dir,
228
231
  timeout_ms: runTimeoutMs,
229
232
  conversation_id: conversationId,
230
- continue: options.continue,
233
+ continue: selection.kind === "latest" && selection.source === "cli",
231
234
  stream: options.stream ?? true,
232
235
  skipPermissions,
233
236
  },
@@ -354,12 +357,7 @@ export function validateAgyExecutionOptions(options: AgyExecutionOptions): void
354
357
  if (!Number.isFinite(options.timeout_ms) || options.timeout_ms <= 0) {
355
358
  throw new Error("agy timeout_ms must be a positive finite number");
356
359
  }
357
- if (options.continue && options.conversation_id) {
358
- throw new Error("agy cannot use --continue and --conversation together");
359
- }
360
- if (options.new_session === true && (options.continue || options.conversation_id)) {
361
- throw new Error("agy new_session cannot be combined with a conversation to resume");
362
- }
360
+ normalizeConversationSelection(options);
363
361
  }
364
362
 
365
363
  function remainingBudget(startedAt: number, timeoutMs: number): number {