@juanbenjumea/pi-agy 0.7.7 → 0.7.9

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