@juanbenjumea/pi-agy 0.5.0

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 ADDED
@@ -0,0 +1,76 @@
1
+ # Changelog
2
+
3
+ ## 0.5.0
4
+
5
+ - 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.
6
+ - First standalone release as `@juanbenjumea/pi-agy` (extracted from dotfiles `pi/packages/pi-agy`).
7
+ - Terminate the full agy process tree (not just the direct child) on cancel/timeout via detached process groups.
8
+ - Attribute post-run git summaries to newly-dirty files only; pre-existing dirt is listed separately and shown in accept-edits confirmation.
9
+ - Serialize same-directory runs across Pi processes with filesystem locks and symlink-canonicalized paths; heartbeat long-held locks so they are never mistaken for stale, and release only locks still owned.
10
+ - Bound streamed JSONL records and accumulated responses; discard oversized records with a warning (pure `appendStreamChunk` helper with behavioral tests).
11
+ - Ignore preview/experimental model ids in live catalog resolution unless `PI_AGY_ALLOW_PREVIEW=1`.
12
+ - Ship a publishable `LICENSE`, add `typecheck`/`pack:check` scripts, and verify the packed tarball contents.
13
+ - Add `tests/regression.test.ts`: fake-agy cancel/timeout/malformed-JSONL integration, a grandchild file-write proof that tree-kill stops nested writers, preview filtering, stream bounds, baseline diff attribution, symlink lock sharing, and artifact checks.
14
+ - Split the monolithic `tests/cli.test.ts` into focused suites (`cli-args`, `verify`, `stream`, `postflight`, `execution`, `command`, `config`, `sessions`, `balance`, `lock`) sharing a `tests/helpers.ts` fake-agy harness.
15
+ - Document `PI_AGY_ALLOW_PREVIEW=1` as the explicit opt-in for preview/experimental model ids.
16
+ - Normalize equivalent working-directory paths before locking so concurrent calls cannot bypass serialization.
17
+
18
+ - Normalize equivalent working-directory paths before locking so concurrent calls cannot bypass serialization.
19
+ - Sanitize `agy-config.json`; malformed permission settings fail closed instead of enabling bypasses.
20
+ - Persist the effective fallback model so session history and quota balancing remain accurate.
21
+ - Distinguish delegation timeouts from user cancellation, preserve JSON-shaped response text, and bound postflight git commands.
22
+ - Use stable response-generation progress instead of forwarding raw token fragments to the TUI.
23
+ - Preserve recoverable conversation IDs across failed runs, propagate postflight cancellation, refuse to overwrite corrupt session stores while letting reads degrade gracefully so tasks are never blocked by bookkeeping.
24
+ - Recognize configured `flash`/`pro` shorthands and distinguish subprocess timeouts from transient failures.
25
+ - Make session-store writes cancellation-aware and clean up partially acquired locks.
26
+ - Reject conflicting conversation selectors and invalid empty/timeout execution inputs early (missing prompts fail with a clear error, not a TypeError).
27
+ - Parse unterminated final stream records before handling process failures so retry safety sees real agy activity and terminal progress is preserved.
28
+ - Enforce `timeout_ms` across setup, preflight, and the agy process instead of adding an unconditional grace period.
29
+ - Preserve legacy `tier` selection in execution details and when configured default-model commands are present.
30
+ - Serialize session-store writes across independent Pi processes and ignore malformed history entries safely.
31
+ - Refresh model aliases from the live `agy models` catalog during preflight; newest generation wins, static map stays as fallback.
32
+ - Count per-directory lock wait toward the call timeout so queued runs cannot silently exceed their budget.
33
+ - Retry once when agy fails with a transient error (rate limit, network) before emitting any progress.
34
+ - Add an `effort` tool parameter passed through to `--effort`.
35
+ - Pass `--disable-slash-commands` so task text never triggers agy slash/skill expansion.
36
+ - Add optional `agy-config.json` with `skipPermissions`, `defaultModel`, and `defaultModelCommand` (quota/usage-aware default resolution); record `permissions_skipped` in tool details.
37
+ - `/agy continue`, `/agy timeout=10m`, and `/agy sessions` conversation picker; status updates throttled.
38
+ - Session store keeps up to 10 recent conversations per directory.
39
+ - Bound verify-command detection at the repository root; recognize `.justfile`, check the `just` binary, and add `uv run pytest` detection.
40
+ - Accumulate stream-json results regardless of whether a progress callback is attached.
41
+
42
+ ## Post-review fixes prior to 0.5.0 (sonnet cross-review of b87019f + c65bb4a)
43
+
44
+ - Parse only stdout when refreshing the model catalog — stderr diagnostics can no longer pollute alias resolution.
45
+ - Numeric-aware model comparison so `claude-sonnet-4-10` sorts above `claude-sonnet-4-6`.
46
+ - Retry eligibility now requires real agy activity (tool steps / model responses); session-start chatter no longer suppresses the transient retry.
47
+ - The timeout budget starts before config/default-model resolution so a slow resolver cannot eat into it unaccounted.
48
+ - `agy-default-model.sh` no longer double-counts the latest conversation when the store has both legacy `last_*` fields and `history` entries.
49
+ - Cover extension registration and `/agy` argument completions in tests.
50
+
51
+ - Keep sandbox runs behind agy permission checks instead of bypassing them.
52
+ - Make streamed result statuses visible in progress updates.
53
+ - Preserve clean successful responses when agy emits stderr diagnostics.
54
+ - Allow queued calls to cancel without blocking later runs in the same directory.
55
+ - Accept explicit `/agy accept-edits ...` mode prefixes.
56
+ - Preserve multiline prompt formatting in `/agy` command arguments.
57
+ - Include staged files in postflight change summaries and preserve response endings when truncating output.
58
+ - Serialize session-store updates, write atomically, and keep conversation IDs in a private file.
59
+ - Resolve the Agy session store from `PI_CODING_AGENT_DIR` instead of always using `~/.pi/agent`.
60
+ - Detect `Justfile`, package `ci` scripts, and npm/pnpm/yarn/bun runners for verification.
61
+ - Ignore non-object JSON lines in streamed agy output safely.
62
+ - Keep direct `agy_execute` calls implementation-oriented with `accept-edits` as the default; use `plan` explicitly for review.
63
+
64
+ ## 0.4.0
65
+
66
+ - Fork from `@bacnh85/pi-agy` 0.3.1 into dotfiles local package.
67
+ - Stream agy progress via `--output-format stream-json` and Pi `onUpdate`.
68
+ - Add `conversation_id`, `continue`, `new_session` for multi-turn handoffs.
69
+ - Persist last conversation per workspace in `~/.pi/agent/agy-sessions.json`.
70
+ - Detect `just ci` for verify-loop injection (falls back to `npm test`).
71
+ - Append git diff summary after `accept-edits`.
72
+ - Cache preflight health/connectivity checks for 5 minutes.
73
+ - Serialize concurrent calls per working directory.
74
+ - Add human-callable `/agy [plan|sandbox] [model] <prompt>` TUI command with model autocomplete.
75
+ - `/agy` wizard UX: interactive mode select, model select with descriptions, multi-line task editor, accept-edits confirmation.
76
+ - `/agy` executes agy directly after confirmation: progress uses the status bar and the final response is notified without a second LLM turn.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Juan Benjumea
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,114 @@
1
+ # @juanbenjumea/pi-agy
2
+
3
+ Enhanced fork of [`@bacnh85/pi-agy`](https://github.com/bacnh85/pi-extensions/tree/main/pi-agy).
4
+
5
+ Delegates bulk work to the Antigravity CLI (`agy`) while Pi stays the conductor.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pi install npm:@juanbenjumea/pi-agy
11
+ ```
12
+
13
+ ## What's different from upstream 0.3.1
14
+
15
+ | Feature | Upstream | This fork |
16
+ |---------|----------|-----------|
17
+ | Live progress | Final text only | `stream-json` → Pi `onUpdate` cards |
18
+ | Model aliases | Hardcoded ids | Live `agy models` catalog (newest stable generation wins; preview/experimental ignored), static map fallback |
19
+ | Conversation resume | None | `conversation_id`, `continue`, session store, `/agy sessions` picker |
20
+ | Verify injection | `npm test` only | `just ci` first, then `npm test`/`uv run pytest` |
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 |
23
+ | Concurrency | Unlocked | Per-directory lock (in-process + filesystem, symlink-aware), lock wait counts against the timeout |
24
+ | Transient failures | Fatal | One retry when agy fails before doing any work |
25
+ | Cancellation | Direct child only | Full process-tree kill on cancel/timeout via detached process groups |
26
+
27
+ Auth is unchanged: existing `agy` OAuth (`~/.gemini/oauth_creds.json`).
28
+
29
+ ## Tool params (new)
30
+
31
+ | Param | Description |
32
+ |-------|-------------|
33
+ | `conversation_id` | Resume agy conversation by ID |
34
+ | `continue` | `--continue` most recent conversation |
35
+ | `new_session` | Force fresh session; set `false` to reuse last ID for dir |
36
+ | `effort` | Reasoning effort via `--effort` (low/medium/high); mostly useful for `sonnet`/`opus`/`gpt-oss` since Gemini aliases encode effort in the model id |
37
+ | `stream` | Use `stream-json` (default `true`) |
38
+ | `mode` | `accept-edits` by default; use `plan` for exploration/review |
39
+
40
+ ## Human-callable `/agy` command
41
+
42
+ Run agy directly from the Pi TUI — fast path when fully specified, wizard otherwise:
43
+
44
+ ```
45
+ /agy flash fix git conflicts # fully specified → runs immediately
46
+ /agy plan sonnet review the diff # mode + model + prompt
47
+ /agy plan # wizard: model select → task editor
48
+ /agy # wizard: mode → model → task editor
49
+ /agy continue fix the tests # continue this directory's last conversation
50
+ /agy timeout=10m sonnet big task # raise the run cap (also 90s / 1500ms; bare = minutes)
51
+ /agy sessions # pick a recorded conversation to resume
52
+ ```
53
+
54
+ Leading option tokens (`plan`, a model alias, `continue`, `timeout=…`) are
55
+ consumed in any order; the remainder is the prompt. `/agy continue` reuses the
56
+ last model when the session store recorded one. `timeout=` caps at 10m.
57
+
58
+ First token optional: `accept-edits` / `plan` / `sandbox` mode prefix, then a
59
+ model alias (`flash`, `pro`, `sonnet`, `opus`, `gpt-oss`, …), then the prompt.
60
+ The interactive wizard and direct `agy_execute` calls default to
61
+ `accept-edits`; the wizard confirms before writing. Use `plan` explicitly for
62
+ exploration/review. Sandbox runs do not bypass agy permission checks.
63
+
64
+ Missing pieces open interactive dialogs (mode select, model select with
65
+ descriptions, multi-line task editor). `accept-edits` asks for confirmation
66
+ before writing. The command then runs agy directly with the selected parameters;
67
+ progress is shown in the (throttled) status bar and the final response is
68
+ notified — no second LLM turn or custom TUI surface.
69
+
70
+ ## Config
71
+
72
+ Optional `$PI_CODING_AGENT_DIR/agy-config.json` (default
73
+ `~/.pi/agent/agy-config.json`):
74
+
75
+ ```json
76
+ {
77
+ "skipPermissions": true,
78
+ "defaultModel": "flash-medium"
79
+ }
80
+ ```
81
+
82
+ - `skipPermissions` (default `true`) — pass `--dangerously-skip-permissions`
83
+ for `accept-edits` runs. Set `false` to leave agy's own permission checks in
84
+ place; note print mode has no interactive approval path, so restricted
85
+ operations may fail instead of prompting.
86
+ - `defaultModel` — alias used when `agy_execute` omits `model`/`tier`.
87
+ - `defaultModelCommand` — shell command whose stdout sets the default alias
88
+ when `defaultModel` is unset (an explicit `defaultModel` always wins).
89
+ Must print one valid alias; failures and invalid output fall back to the
90
+ built-in default. Result cached ~5 min per process. Escape hatch for
91
+ custom resolvers; prefer `quotaBalancing` below.
92
+ - `quotaBalancing` — steer the default across agy's quota families by
93
+ recent usage balance: when the Gemini group (flash/pro) carried ≥75% of
94
+ the last 24h of recorded conversations (min 3), the default flips to
95
+ `sonnet` so routine delegation rests the hot group. Tune with
96
+ `AGY_DEFAULT_MODEL_WINDOW_HOURS`, `AGY_DEFAULT_MODEL_MIN_SESSIONS`, and
97
+ `AGY_DEFAULT_MODEL_GEMINI_SHARE`. Missing/corrupt stores mean no signal.
98
+
99
+ Tool results record `permissions_skipped` in `details` for auditability.
100
+
101
+ Live catalog resolution ignores preview/experimental model ids so an
102
+ unstable entry can never silently become the default. Set
103
+ `PI_AGY_ALLOW_PREVIEW=1` to opt into preview ids explicitly.
104
+
105
+ ## Development
106
+
107
+ ```bash
108
+ npm test
109
+ npm run typecheck
110
+ ```
111
+
112
+ ## License
113
+
114
+ MIT
@@ -0,0 +1,343 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { isAgyModel, resolveAgyModelId, type AgyModel } from "./lib/cli.js";
4
+ import { executeAgyTask } from "./lib/execute.js";
5
+ import { truncate } from "./lib/output.js";
6
+ import { describePreRunDirt } from "./lib/postflight.js";
7
+ import { getHistory, getSession } from "./lib/sessions.js";
8
+
9
+ const MODEL_ALIASES: Record<string, AgyModel> = {
10
+ flash: "flash-medium",
11
+ "flash-low": "flash-low",
12
+ "flash-medium": "flash-medium",
13
+ "flash-high": "flash-high",
14
+ pro: "pro-high",
15
+ "pro-low": "pro-low",
16
+ "pro-high": "pro-high",
17
+ sonnet: "sonnet",
18
+ opus: "opus",
19
+ "gpt-oss": "gpt-oss",
20
+ };
21
+
22
+ const MODEL_KEYS = Object.keys(MODEL_ALIASES);
23
+
24
+ const MODEL_OPTIONS = [
25
+ "flash — fast, cheap (Gemini Flash medium)",
26
+ "flash-low — trivial / high-volume",
27
+ "flash-high — harder agentic work",
28
+ "pro — deep reasoning (Gemini Pro high)",
29
+ "pro-low — pro, lighter reasoning",
30
+ "pro-high — max Gemini reasoning",
31
+ "sonnet — Claude default (review/code)",
32
+ "opus — Claude hard problems",
33
+ "gpt-oss — open-model alternative",
34
+ ];
35
+
36
+ const MODE_OPTIONS = [
37
+ "accept-edits — writes files (default)",
38
+ "plan — exploration, no edits",
39
+ "sandbox — isolated preview",
40
+ ];
41
+
42
+ const MODE_KEYS = ["accept-edits", "plan", "sandbox"] as const;
43
+
44
+ const DEFAULT_TIMEOUT_MS = 300_000;
45
+ const MAX_TIMEOUT_MS = 600_000;
46
+
47
+ export interface AgyCommandArgs {
48
+ mode?: "plan" | "accept-edits" | "sandbox";
49
+ model?: AgyModel;
50
+ prompt?: string;
51
+ continue?: boolean;
52
+ timeout_ms?: number;
53
+ }
54
+
55
+ /**
56
+ * Parse `/agy [mode] [model] [continue] [timeout=10m] <prompt>` — leading
57
+ * option tokens are consumed in any order; the remainder is the prompt.
58
+ */
59
+ export function parseAgyCommandArgs(args: string): AgyCommandArgs {
60
+ let rest = args.trim();
61
+ const parsed: AgyCommandArgs = {};
62
+
63
+ while (rest) {
64
+ const token = readToken(rest);
65
+ if (!token) break;
66
+ const value = token.value.toLowerCase();
67
+
68
+ const timeout = parseTimeoutToken(token.value);
69
+ if (MODE_KEYS.includes(value as (typeof MODE_KEYS)[number])) {
70
+ parsed.mode = value as AgyCommandArgs["mode"];
71
+ } else if (MODEL_ALIASES[value]) {
72
+ parsed.model = MODEL_ALIASES[value];
73
+ } else if (value === "continue") {
74
+ parsed.continue = true;
75
+ } else if (timeout !== undefined) {
76
+ parsed.timeout_ms = timeout;
77
+ } else {
78
+ break;
79
+ }
80
+ rest = rest.slice(token.end).trimStart();
81
+ }
82
+
83
+ if (rest) parsed.prompt = rest;
84
+ return parsed;
85
+ }
86
+
87
+ /** `timeout=10m`, `timeout=90s`, `timeout=1500ms`; a bare number means minutes. */
88
+ function parseTimeoutToken(token: string): number | undefined {
89
+ const match = /^timeout=(\d+(?:\.\d+)?)(ms|s|m)?$/i.exec(token);
90
+ if (!match) return undefined;
91
+ const amount = Number.parseFloat(match[1]);
92
+ const unit = (match[2] ?? "m").toLowerCase();
93
+ const ms = unit === "ms" ? amount : unit === "s" ? amount * 1_000 : amount * 60_000;
94
+ return Math.min(Math.max(Math.round(ms), 1_000), MAX_TIMEOUT_MS);
95
+ }
96
+
97
+ function readToken(value: string): { value: string; end: number } | undefined {
98
+ const match = /^\S+/.exec(value);
99
+ return match ? { value: match[0], end: match[0].length } : undefined;
100
+ }
101
+
102
+ interface InteractiveRun {
103
+ mode: "plan" | "accept-edits" | "sandbox";
104
+ model: AgyModel;
105
+ prompt: string;
106
+ conversation_id?: string;
107
+ continue?: boolean;
108
+ timeout_ms?: number;
109
+ }
110
+
111
+ /**
112
+ * Register the human-callable `/agy` command. Missing parts are filled with
113
+ * dialogs, write-capable runs are confirmed, and agy executes directly — the
114
+ * confirmed parameters stay authoritative with no second LLM turn.
115
+ */
116
+ export function registerAgyCommand(pi: ExtensionAPI): void {
117
+ pi.registerCommand("agy", {
118
+ description:
119
+ "Run agy directly: /agy [mode] [model] [continue] [timeout=10m] <prompt>, or /agy sessions to resume a prior conversation.",
120
+ getArgumentCompletions: (prefix: string) => {
121
+ const tokens = prefix.trim().split(/\s+/).filter(Boolean);
122
+ const p = prefix.toLowerCase();
123
+
124
+ if (tokens.length === 1 && MODE_KEYS.includes(tokens[0] as (typeof MODE_KEYS)[number])) {
125
+ return [
126
+ ...MODEL_KEYS.map((k) => ({ value: k, label: k })),
127
+ { value: "continue", label: "continue" },
128
+ ];
129
+ }
130
+ if (tokens.length <= 1) {
131
+ const modes = MODE_KEYS.filter((m) => m.startsWith(tokens[0] ?? ""));
132
+ const models = MODEL_KEYS.filter((k) => k.startsWith(p));
133
+ const extras = ["continue", "sessions"].filter((k) => k.startsWith(p));
134
+ return [
135
+ ...modes.map((m) => ({ value: m, label: m })),
136
+ ...models.map((m) => ({ value: m, label: m })),
137
+ ...extras.map((k) => ({ value: k, label: k })),
138
+ ];
139
+ }
140
+ return null;
141
+ },
142
+ handler: async (args, ctx) => {
143
+ if (ctx.mode !== "tui") {
144
+ ctx.ui.notify("/agy requires interactive (TUI) mode", "error");
145
+ return;
146
+ }
147
+
148
+ if (args.trim().toLowerCase() === "sessions") {
149
+ await runSessionsPicker(ctx);
150
+ return;
151
+ }
152
+
153
+ const parsed = parseAgyCommandArgs(args);
154
+
155
+ let mode: InteractiveRun["mode"] | undefined = parsed.mode;
156
+ if (!mode) {
157
+ const pick = await ctx.ui.select("agy mode", MODE_OPTIONS);
158
+ if (!pick) {
159
+ ctx.ui.notify("agy: cancelled", "info");
160
+ return;
161
+ }
162
+ mode = optionKey(pick) as InteractiveRun["mode"];
163
+ }
164
+
165
+ let model = parsed.model;
166
+ if (!model && parsed.continue) {
167
+ const prior = await getSession(ctx.cwd);
168
+ if (prior?.last_model && isAgyModel(prior.last_model)) model = prior.last_model;
169
+ }
170
+ if (!model) {
171
+ const pick = await ctx.ui.select("agy model", MODEL_OPTIONS);
172
+ if (!pick) {
173
+ ctx.ui.notify("agy: cancelled", "info");
174
+ return;
175
+ }
176
+ model = MODEL_ALIASES[optionKey(pick)] ?? "flash-medium";
177
+ }
178
+
179
+ let prompt = parsed.prompt;
180
+ if (!prompt) {
181
+ const text = await ctx.ui.editor("agy task", "");
182
+ if (!text?.trim()) {
183
+ ctx.ui.notify("agy: cancelled (empty task)", "info");
184
+ return;
185
+ }
186
+ prompt = text.trim();
187
+ }
188
+
189
+ await executeConfirmedRun(ctx, {
190
+ mode,
191
+ model,
192
+ prompt,
193
+ continue: parsed.continue,
194
+ timeout_ms: parsed.timeout_ms,
195
+ });
196
+ },
197
+ });
198
+ }
199
+
200
+ /** `/agy sessions` — pick a recorded conversation and resume it with a follow-up. */
201
+ async function runSessionsPicker(ctx: ExtensionCommandContext): Promise<void> {
202
+ const history = await getHistory(ctx.cwd);
203
+ if (history.length === 0) {
204
+ ctx.ui.notify("agy: no recorded conversations for this directory", "info");
205
+ return;
206
+ }
207
+
208
+ const options = history.map((entry, index) => {
209
+ const id = entry.conversation_id.slice(0, 8);
210
+ const model = entry.model ?? "unknown model";
211
+ return `${index + 1}. ${model} · ${describeWhen(entry.updated_at)} · ${id}…`;
212
+ });
213
+ const pick = await ctx.ui.select("resume agy conversation", options);
214
+ if (!pick) {
215
+ ctx.ui.notify("agy: cancelled", "info");
216
+ return;
217
+ }
218
+ const entry = history[options.indexOf(pick)];
219
+ if (!entry) {
220
+ ctx.ui.notify("agy: cancelled", "info");
221
+ return;
222
+ }
223
+
224
+ const modePick = await ctx.ui.select("agy mode", MODE_OPTIONS);
225
+ if (!modePick) {
226
+ ctx.ui.notify("agy: cancelled", "info");
227
+ return;
228
+ }
229
+ const mode = optionKey(modePick) as InteractiveRun["mode"];
230
+
231
+ const text = await ctx.ui.editor("agy follow-up task", "");
232
+ if (!text?.trim()) {
233
+ ctx.ui.notify("agy: cancelled (empty task)", "info");
234
+ return;
235
+ }
236
+
237
+ await executeConfirmedRun(ctx, {
238
+ mode,
239
+ model: isAgyModel(entry.model) ? entry.model : "flash-medium",
240
+ prompt: text.trim(),
241
+ conversation_id: entry.conversation_id,
242
+ });
243
+ }
244
+
245
+ async function executeConfirmedRun(ctx: ExtensionCommandContext, run: InteractiveRun): Promise<void> {
246
+ const cwd = ctx.cwd;
247
+
248
+ if (run.mode === "accept-edits") {
249
+ const dirt = await describePreRunDirt(cwd, ctx.signal).catch(() => null);
250
+ const dirtLine = dirt ? `\nworkspace: ${dirt}` : "";
251
+ const warning =
252
+ dirt && dirt !== "clean"
253
+ ? `\n\nWarning: uncommitted changes already exist — the result summary only attributes newly-dirty files to agy.`
254
+ : "";
255
+ const ok = await ctx.ui.confirm(
256
+ "Run agy (accept-edits)?",
257
+ `model: ${run.model} (${resolveAgyModelId(run.model)})\ndir: ${cwd}${dirtLine}\n\ntask: ${run.prompt.slice(0, 200)}${run.prompt.length > 200 ? "…" : ""}\n\nThis grants agy permission to modify files and run commands.${warning}`,
258
+ );
259
+ if (!ok) {
260
+ ctx.ui.notify("agy: cancelled", "info");
261
+ return;
262
+ }
263
+ }
264
+
265
+ // Execute directly so the confirmed parameters cannot be changed by
266
+ // a second LLM turn and the command works even when tools are limited.
267
+ const status = createStatusThrottler(ctx);
268
+ try {
269
+ await ctx.waitForIdle();
270
+ status(`starting (${run.model} · ${run.mode})`);
271
+ const result = await executeAgyTask(
272
+ {
273
+ prompt: run.prompt,
274
+ model: run.model,
275
+ mode: run.mode,
276
+ dir: cwd,
277
+ timeout_ms: run.timeout_ms ?? DEFAULT_TIMEOUT_MS,
278
+ conversation_id: run.conversation_id,
279
+ continue: run.continue,
280
+ new_session: run.conversation_id || run.continue ? false : true,
281
+ stream: true,
282
+ },
283
+ ctx.signal,
284
+ (progress) => status(progress),
285
+ );
286
+ status(undefined);
287
+ ctx.ui.notify(truncate(result.text || "(empty response)", 4000), "info");
288
+ } catch (error) {
289
+ status(undefined);
290
+ const message = error instanceof Error ? error.message : String(error);
291
+ ctx.ui.notify(`agy failed: ${message}`, "error");
292
+ }
293
+ }
294
+
295
+ /** Coalesce status-bar updates so per-token deltas do not churn the TUI. */
296
+ function createStatusThrottler(ctx: ExtensionCommandContext, intervalMs = 300) {
297
+ let lastEmit = 0;
298
+ let timer: ReturnType<typeof setTimeout> | undefined;
299
+ let pending: string | undefined;
300
+
301
+ const emit = (text: string) => {
302
+ lastEmit = Date.now();
303
+ ctx.ui.setStatus("agy", text.slice(0, 200));
304
+ };
305
+
306
+ return (text: string | undefined): void => {
307
+ if (text === undefined) {
308
+ if (timer !== undefined) clearTimeout(timer);
309
+ timer = undefined;
310
+ pending = undefined;
311
+ ctx.ui.setStatus("agy", undefined);
312
+ return;
313
+ }
314
+ const now = Date.now();
315
+ if (now - lastEmit >= intervalMs) {
316
+ emit(text);
317
+ return;
318
+ }
319
+ pending = text;
320
+ if (timer === undefined) {
321
+ timer = setTimeout(() => {
322
+ timer = undefined;
323
+ if (pending !== undefined) emit(pending);
324
+ pending = undefined;
325
+ }, intervalMs - (now - lastEmit));
326
+ }
327
+ };
328
+ }
329
+
330
+ function describeWhen(iso: string): string {
331
+ const ms = Date.now() - Date.parse(iso);
332
+ if (!Number.isFinite(ms)) return "unknown age";
333
+ const minutes = Math.round(ms / 60_000);
334
+ if (minutes < 1) return "just now";
335
+ if (minutes < 60) return `${minutes}m ago`;
336
+ const hours = Math.round(minutes / 60);
337
+ if (hours < 24) return `${hours}h ago`;
338
+ return `${Math.round(hours / 24)}d ago`;
339
+ }
340
+
341
+ function optionKey(option: string): string {
342
+ return option.split(" — ")[0] ?? option;
343
+ }