@juanbenjumea/pi-agy 0.7.8 → 0.7.11

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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.11
4
+
5
+ - Preserve exclusive provider-turn ownership across tool suspension, resumption, and terminal delivery; reject competing turns before they alter bridge tools.
6
+ - Retain terminal responses received while awaiting Pi tools for exactly one continuation, with bounded abandonment and safe process reuse.
7
+ - Reclaim orphaned bridge calls, suspended state, staged images, and unpolled escalation results on completion or abandonment, including races before suspension publication.
8
+ - Add lifecycle and real-loopback/fake-process regression coverage; 455 tests, typecheck, and package checks pass.
9
+
10
+ ## 0.7.10
11
+
12
+ - Harden process-tree cancellation, provider tool forwarding, bridge reconnection, terminal response handling, and cancelled resumes.
13
+ - Bound bridge request complexity and refresh the MCP dependency floor and qualified Pi development dependencies.
14
+ - Derive delegation model aliases and tool schemas from one definition; normalize conversation selection while preserving resume behavior.
15
+ - Keep completed background polling compact; retrieve full results with `agy_tasks collect`.
16
+ - Expand regression coverage to 414 tests; typecheck and package checks pass.
17
+
18
+ ## 0.7.9
19
+
20
+ - Rewrite the README as a concise overview of agy task delegation and the Antigravity provider, retaining installation, configuration, and development essentials.
21
+
3
22
  ## 0.7.8
4
23
 
5
24
  - Improve agy provider cache behavior: stabilize prompt prefixes, cap recent resume context, key preflight and verification caches by working directory, and bucket print timeouts for identical arguments.
package/README.md CHANGED
@@ -1,292 +1,80 @@
1
1
  # @juanbenjumea/pi-agy
2
2
 
3
- Antigravity (agy) provider and delegation for Pi: `/model` picker integration,
4
- persistent driver with loopback MCP tool bridge, background tasks, quota awareness,
5
- repo verification, and trustworthy diff summaries.
3
+ Use Google's Antigravity CLI (`agy`) from Pi. This package adds two ways to work:
6
4
 
7
- Pi can delegate scoped tasks to the Antigravity CLI (`agy`) or use Antigravity
8
- as the primary `/model` provider for interactive chat with a full loopback MCP tool bridge.
5
+ - **Delegate a task** to `agy` with Pi tools such as `agy_execute`, or the `/agy` command.
6
+ - **Use agy as a Pi model provider** through `antigravity/*` in `/model`, with an optional bridge to Pi tools.
9
7
 
10
- Enhanced fork of [`@bacnh85/pi-agy`](https://github.com/bacnh85/pi-extensions/tree/main/pi-agy).
11
-
12
- ## Install
8
+ Install with:
13
9
 
14
10
  ```bash
15
11
  pi install npm:@juanbenjumea/pi-agy
16
12
  ```
17
13
 
18
- Requires Node.js >= 20.3.
19
-
20
- ## What's different from upstream 0.3.1
21
-
22
- | Feature | Upstream | This fork |
23
- |---------|----------|-----------|
24
- | Live progress | Final text only | `stream-json` → Pi `onUpdate` cards |
25
- | Model aliases | Hardcoded ids | Live `agy models` catalog (newest stable generation wins; preview/experimental ignored), static map fallback |
26
- | Conversation resume | None | `conversation_id`, `continue`, session store with task summaries and custom-agent identity, `/agy sessions` picker, `agy_history` discovery tool — runs that time out or are cancelled are recorded too |
27
- | Verify injection | `npm test` only | `just ci` first, then `npm test`/`uv run pytest` |
28
- | Post-write summary | None | Appends `git diff --stat` for newly-dirty files only; pre-existing dirt (including renames and unstaged edits) is listed separately and never misattributed |
29
- | Preflight | Every call | Health/model checks cached 5 min per process; model quotas refresh every minute |
30
- | Quota discovery | None | Read-only `/usage` probe exposes model-specific remaining quota and reset times to agents |
31
- | Custom agents | None | Read-only `agy_agents` / `/agy agents` discovery plus validated `agent` / `agent=name` selection via `--agent` |
32
- | Subagent visibility | None | Native stream progress plus a capped per-run roster in result details/receipts; observations never claim live lifecycle control |
33
- | Concurrency | Unlocked | Per-directory lock (in-process + filesystem, symlink-aware), lock wait counts against the timeout |
34
- | Transient failures | Fatal | One retry when agy fails before doing any work |
35
- | Cancellation | Direct child only | Full process-tree kill on cancel/timeout via detached process groups; a fully delivered result is preserved |
36
- | Primary-model picker | None | `antigravity/*` provider with live catalog, persistent driver, MCP tool bridge, and image staging (see below) |
37
- | Background runs | Blocking only | `background=true` detaches with a handle; `agy_tasks` polls, collects, and cancels under the same timeout and lock |
38
-
39
- Auth is unchanged: existing `agy` OAuth (`~/.gemini/oauth_creds.json`).
40
-
41
- ## Antigravity provider (`/model` picker)
42
-
43
- This package also registers an `antigravity` provider, so agy-backed models
44
- appear in Pi's global `/model` picker as `antigravity/<id>` (for example
45
- `antigravity/gemini-3-8-flash`). Model entries are discovered from live
46
- `agy models` output at startup (refreshed in the background, no `/reload`
47
- needed); when discovery fails, a fallback catalog keeps the picker populated
48
- and selection yields a clear runtime error instead of an empty list.
49
-
50
- Gemini bases with multiple effort tiers expose Pi's thinking-level toggle,
51
- which is sent as agy `--effort` (clamped to tiers the base accepts — Pro has
52
- no medium). Fixed-thinking families (Claude, GPT-OSS) keep agy's exact slug
53
- and never receive `--effort`.
54
-
55
- Attached images are staged as files under a process-stable 0700 root
56
- (passed as `--add-dir` so sandboxed turns can open them) and referenced by
57
- path in the turn prompt, so agy opens them with its file tools; images on
58
- tool results ride the delivery the same way. Capped at the 8 newest images /
59
- 8 MiB each with strict base64 validation — failures degrade to omitted notes.
60
- Each staging has a dispose handle owned by its turn (suspensions carry
61
- theirs forward); terminal settle, stale-cancel, abandonment, and session
62
- shutdown all reclaim.
63
-
64
- Each turn runs on a persistent `agy --input-format stream-json` driver
65
- process (one per working directory) with the transcript rendered as text.
66
- The process is reused across turns — follow-ups skip cold start and re-auth —
67
- and recycled when the model, effort, permissions, or conversation drifts; idle
68
- processes are reaped after five minutes and everything is disposed on session
69
- shutdown. Completed turns are recorded to the same session store as
70
- delegation runs, so `/agy sessions` can resume them. Provider turns take the
71
- same per-directory lock as delegation runs (lock waits count against the turn
72
- timeout), so a provider turn never races `agy_execute` in the same directory.
73
-
74
- Read-only tool bridge: provider turns also get an extra `--add-dir`
75
- carrying a localhost MCP server (`pi-agy-tools`) that exposes Pi-side
76
- context agy cannot see otherwise — `agy_sessions_list`, `agy_quota_report`,
77
- `agy_model_catalog`, and `activate_skill` (which dynamically lists and injects
78
- Pi Agent Skills from `~/.pi/agent/skills`, `~/.agents/skills`, and `.pi/skills`).
79
- The server binds 127.0.0.1 with a per-process shared secret, serves only reads,
80
- and never touches your global agy config. Set `"providerBridge": false` in
81
- `agy-config.json` to run provider turns plain.
82
-
83
- Mutating tool bridge: agy turns can also call Pi tools directly. The bridge
84
- parks the MCP call, the provider emits a real shadow `toolCall`, and Pi
85
- executes it with normal permissions, approvals, and diff review; the next
86
- turn's `toolResult` completes the parked call and agy continues. Only active
87
- non-builtin tools are exposed (`agy_*` and `AskAntigravity` excluded — no
88
- recursive delegation); the catalog refreshes per turn and the driver recycles
89
- when it changes so agy always sees a fresh tool list. Long calls over 20 seconds
90
- early-ack with `STILL RUNNING` and a `callId` so agy can poll via
91
- `bridge_poll_result`, completely avoiding agy's ~180-second MCP client timeout.
92
- Suspended turns hold the agy child with timers off, re-arm on resume, and are
93
- abandoned loudly on cancel, teardown, or a 30-minute stall cap.
94
-
95
- Do not install `@estebanforge/pi-antigravity-bridge` alongside this package:
96
- both register the `antigravity` provider id and an `/agy` command.
14
+ Requires Node.js >= 20.3 and an installed, authenticated `agy` CLI. Existing agy OAuth credentials are used; this package does not manage authentication.
97
15
 
98
- ## Timeouts & cancellation
16
+ ## Delegate tasks
99
17
 
100
- `timeout_ms` (default 5m, max 10m) is a hard parent-side deadline — lock
101
- waits, preflight probes, and post-run summaries all count against it. When
102
- it fires, the full agy process group is killed so nested tools cannot
103
- outlive the run. agy's own `--print-timeout` is set five seconds later because
104
- agy 1.1.28+ returns partial output with exit code 0 when that internal timer
105
- fires; Pi therefore remains the authoritative timeout owner. Terminal result
106
- envelopes also fail closed: when agy supplies a status, only `SUCCESS` and `OK`
107
- are accepted, even if a failed result carries an empty response and exits 0.
18
+ `agy_execute` runs a task in `plan`, `accept-edits`, or `sandbox` mode. It streams progress and returns the result, quota details when available, and a summary of newly changed files. Runs are serialized per working directory; timeouts and cancellations stop the agy process tree.
108
19
 
109
- Active tool updates show bounded intent (for example a tool action or async
110
- threshold) but never echo full command lines, which may contain secrets.
111
- Subagent spawn steps likewise produce bounded progress and a final per-run
112
- observation roster (maximum 32). An `active at last event` entry describes the
113
- last stream record only; it does not claim that a controllable process remains live.
114
- Background commands are intentionally not detached or managed out-of-band:
115
- agy exposes no reliable headless task lifecycle or task-to-process ownership,
116
- so timeout/cancellation still kills the full process tree and prevents work from
117
- continuing after the directory lock is released.
20
+ Useful options include:
118
21
 
119
- The deadline never discards finished work:
22
+ - `model` and `agent` to select a model or configured agy agent
23
+ - `conversation_id`, `continue`, and `new_session` to resume work
24
+ - `background=true` to return a handle, then use `agy_tasks` to poll, collect, or cancel
25
+ - `context=summary|recent` to optionally pass bounded Pi conversation context (default: none)
120
26
 
121
- - A response that fully arrived before the kill is returned with an
122
- explanatory note instead of being thrown away — even if cancellation or
123
- the deadline landed between delivery and process exit.
124
- - Post-run steps cut short by the deadline (the accept-edits diff summary)
125
- are skipped with a note rather than failing the run.
126
- - The conversation id is recorded on timeout and cancellation, so the run
127
- stays resumable via `conversation_id`, `/agy continue`, or `/agy sessions`.
128
- Timeout errors distinguish ids successfully recorded for `/agy continue` or
129
- `/agy sessions` from ids merely observed when local persistence failed; the
130
- latter can still be resumed by passing `conversation_id` explicitly.
27
+ The `/agy` command runs tasks from Pi's TUI and can also list agents, inspect quota, diagnose setup, and select saved conversations. For example:
131
28
 
132
- ## Tool params (new)
133
-
134
- | Param | Description |
135
- |-------|-------------|
136
- | `background` | Return immediately with a task handle instead of waiting; poll with `agy_tasks status` and collect the result. The run keeps its `timeout_ms` deadline; cancel via `agy_tasks`. |
137
- | `conversation_id` | Resume agy conversation by ID |
138
- | `continue` | `--continue` most recent conversation |
139
- | `new_session` | Force fresh session; set `false` to reuse last ID for dir |
140
- | `effort` | Reasoning effort via `--effort` where supported; `gpt-oss` accepts it, while Claude thinking models reject it and Gemini aliases already encode it |
141
- | `agent` | Optional configured custom agy agent name; discover names with `agy_agents` |
142
- | `stream` | Use `stream-json` (default `true`) |
143
- | `context` | Optional Pi history handoff: `none` (default), `summary`, or `recent` |
144
- | `mode` | `accept-edits` by default; use `plan` for exploration/review |
145
-
146
- `agy_execute` refreshes quota information before each run (best effort) and
147
- returns it in `details.quota`/`details.quota_status` and the response when
148
- the CLI exposes structured model records. Use the separate `agy_usage` tool
149
- when choosing a model before execution. If the selected model is explicitly
150
- reported as exhausted, the run stops before spending another agent turn and
151
- reports the reset information. When no model is explicitly requested, an exhausted
152
- quota-balanced default automatically falls back to the first reported available
153
- model family. Explicit model selections fail clearly instead of silently
154
- switching models.
155
- Use `agy_usage` with `model` (for example `model=sonnet`) for a targeted
156
- `available`/`exhausted`/`unknown` status. Older agy versions that do not support
157
- headless `/usage` continue without failing the task. The extension requires
158
- agy 1.1.11+ before invoking `/usage`; older versions are refused safely because
159
- that command could otherwise consume model quota as a prompt.
160
-
161
- When agy emits `subagent` stream steps, `agy_execute` returns a capped,
162
- control-safe `details.subagents` list and appends the same observed summary to
163
- tool content. Native rendering deduplicates that synthetic appendix and shows
164
- compact/expanded roster metadata. Conversation ids and log URIs from nested
165
- subagents are deliberately not exposed as lifecycle handles.
29
+ ```text
30
+ /agy plan flash investigate the failing tests
31
+ /agy continue fix the remaining issues
32
+ /agy sessions
33
+ /agy doctor
34
+ ```
166
35
 
167
- Context handoff is opt-in and text-only. `summary` sends up to 12,000
168
- characters from the latest durable summaries and four conversational messages;
169
- `recent` sends up to 40,000 characters from the recent conversational tail.
170
- Both exclude Pi system prompts, thinking, tool arguments, tool results, images,
171
- and custom extension messages. The current delegated task is appended after the
172
- reference context and remains authoritative.
36
+ In `accept-edits` mode, Pi confirms before writes. agy's own permission behavior is controlled by its configuration and the package's `agy-config.json` settings below.
173
37
 
174
- The `agy_agents` tool runs the read-only `agy agents` subcommand and returns
175
- configured custom-agent names without spending a model turn. Pass an exact
176
- name as `agy_execute agent`; initial selection is always explicit, while known
177
- conversation resumes restore their recorded agent.
38
+ ## Use agy as a Pi model
178
39
 
179
- The `agy_history` tool lists recorded conversations for a directory — ids,
180
- models, custom agents, ages, and one-line task summaries — so agents can find a
181
- `conversation_id` to resume; `/agy sessions` offers the same in the TUI
182
- picker. Summaries are stored locally (first ~80 chars of each prompt), and a
183
- recorded custom agent is restored when that conversation resumes.
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.
184
41
 
185
- The `agy_tasks` tool manages background runs started with
186
- `agy_execute background=true`: `list` shows tasks per directory, `status`
187
- polls state and recent progress, `collect` returns the terminal result and
188
- frees the record, and `cancel` aborts a live run. Background runs keep their
189
- `timeout_ms` deadline, serialize on the per-directory lock like foreground
190
- runs, and are recorded to the session store on completion so nothing is lost
191
- when a payload goes uncollected; session shutdown aborts anything still live.
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.
192
43
 
193
- ## Human-callable `/agy` command
44
+ Do not install `@estebanforge/pi-antigravity-bridge` alongside this package: both register the `antigravity` provider and `/agy` command.
194
45
 
195
- Run agy directly from the Pi TUI — fast path when fully specified, wizard otherwise:
46
+ ### Bridge input limits
196
47
 
197
- ```
198
- /agy flash fix git conflicts # fully specified → runs immediately
199
- /agy plan sonnet review the diff # mode + model + prompt
200
- /agy agents # list configured custom agents (read-only)
201
- /agy plan agent=gsd-debugger investigate the crash
202
- /agy context=summary plan sonnet review our earlier decision
203
- /agy plan # wizard: model select → task editor
204
- /agy # wizard: mode → model → task editor
205
- /agy continue fix the tests # continue this directory's last conversation
206
- /agy timeout=10m sonnet big task # raise the run cap (also 90s / 1500ms; bare = minutes)
207
- /agy sessions # pick a recorded conversation to resume
208
- /agy doctor # diagnose CLI, models, agents, quota, config, sessions, lock, provider, and repo gate
209
- /agy usage # inspect model quotas and reset times
210
- /agy bridge [on|off] # inspect or toggle the provider MCP bridge (takes effect next turn)
211
- ```
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.
212
49
 
213
- Leading option tokens (`plan`, a model alias, `agent=name`, `continue`,
214
- `context=summary`, `context=recent`, `timeout=…`) are consumed in any order;
215
- the remainder is the prompt. `/agy continue` reuses the last model and custom
216
- agent when the session store recorded them. `timeout=` caps at 10m.
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.
217
51
 
218
- First token optional: `accept-edits` / `plan` / `sandbox` mode prefix, then a
219
- model alias (`flash`, `pro`, `sonnet`, `opus`, `gpt-oss`, …), then the prompt.
220
- The interactive wizard and direct `agy_execute` calls default to
221
- `accept-edits`; the wizard confirms before writing. Use `plan` explicitly for
222
- exploration/review. Sandbox runs do not bypass agy permission checks.
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.
223
53
 
224
- `/agy doctor` performs no inference and spends no model tokens. It reports the
225
- installed CLI version, discoverable stable model aliases, optional custom-agent
226
- discovery, quota support, active config, recorded sessions, workspace lock state,
227
- provider runtime state (driver turns/reuses/recycles, bridge tool count,
228
- suspended turns awaiting Pi tools, live image staging), and detected
229
- verification gate.
54
+ ## Configuration
230
55
 
231
- Missing pieces open interactive dialogs (mode select, model select with
232
- descriptions, multi-line task editor). `accept-edits` asks for confirmation
233
- before writing. The command then runs agy directly with the selected parameters;
234
- progress is shown in the throttled status bar and a durable, expandable receipt
235
- is appended to Pi's transcript. Receipts are TUI-only custom entries: they are
236
- not sent to the primary model, and context handoff excludes them. Stored task
237
- text is capped at 500 characters and result text at 8,000 characters. Stripped-down
238
- hosts fall back to a normal notification. `/agy usage` performs the same read-only
239
- quota check without starting a model turn; `/agy agents` likewise lists custom
240
- agents without inference.
241
-
242
- ## Config
243
-
244
- Optional `$PI_CODING_AGENT_DIR/agy-config.json` (default
245
- `~/.pi/agent/agy-config.json`):
56
+ Optional file: `$PI_CODING_AGENT_DIR/agy-config.json` (default `~/.pi/agent/agy-config.json`). For example:
246
57
 
247
58
  ```json
248
59
  {
60
+ "defaultModel": "flash-medium",
249
61
  "skipPermissions": true,
250
- "defaultModel": "flash-medium"
62
+ "providerBridge": true
251
63
  }
252
64
  ```
253
65
 
254
- - `skipPermissions` (default `true`) — pass `--dangerously-skip-permissions`
255
- for `accept-edits` runs. Set `false` to leave agy's own permission checks in
256
- place; note print mode has no interactive approval path, so restricted
257
- operations may be reported as `denied_actions` instead of prompting. The
258
- extension rejects a denied run with no response and visibly warns when agy
259
- returns an explanatory response alongside denied actions.
260
- - `defaultModel` — alias used when `agy_execute` omits `model`/`tier`.
261
- - `defaultModelCommand` — shell command whose stdout sets the default alias
262
- when `defaultModel` is unset (an explicit `defaultModel` always wins).
263
- Must print one valid alias; failures and invalid output fall back to the
264
- built-in default. Result cached ~5 min per process. Escape hatch for
265
- custom resolvers; prefer `quotaBalancing` below.
266
- - `quotaBalancing` — steer the default across agy's quota families by
267
- recent usage balance: when the Gemini group (flash/pro) carried ≥75% of
268
- the last 24h of recorded conversations (min 3), the default flips to
269
- `sonnet` so routine delegation rests the hot group. Tune with
270
- `AGY_DEFAULT_MODEL_WINDOW_HOURS`, `AGY_DEFAULT_MODEL_MIN_SESSIONS`, and
271
- `AGY_DEFAULT_MODEL_GEMINI_SHARE`. Missing/corrupt stores mean no signal.
272
-
273
- Tool results record `permissions_skipped` in `details` for auditability.
274
-
275
- Live catalog resolution ignores preview/experimental model ids so an
276
- unstable entry can never silently become the default. Set
277
- `PI_AGY_ALLOW_PREVIEW=1` to opt into preview ids explicitly.
66
+ `defaultModel` sets the default for delegated tasks. `skipPermissions` controls agy's permission-bypass flag for `accept-edits` runs; set it to `false` to retain agy's checks. `providerBridge` toggles the provider's Pi-tool bridge.
278
67
 
279
68
  ## Development
280
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
+
281
72
  ```bash
282
73
  npm test
283
74
  npm run typecheck
284
75
  ```
285
76
 
286
- With an installed, authenticated `agy`, run `npm run test:live` to verify the
287
- CLI version, stable model catalog, custom-agent roster, quota schema, and doctor
288
- integration against the real binary. The smoke uses read-only commands only and
289
- does not start an inference turn or spend model tokens.
77
+ With an installed agy CLI, `npm run test:live` runs read-only integration checks without starting an inference turn.
290
78
 
291
79
  ## License
292
80
 
@@ -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,
@@ -86,13 +86,11 @@ function registerAgyProvider(pi: ExtensionAPI): void {
86
86
  streamSimple(
87
87
  { id: model.id },
88
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,
89
+ {
90
+ signal: options?.signal,
91
+ reasoning: options?.reasoning,
92
+ tools: getCurrentTools(context.messages) as unknown as ProviderToolSource[],
93
+ },
96
94
  ) as unknown as AssistantMessageEventStream,
97
95
  });
98
96
  };
@@ -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 {