@juanbenjumea/pi-agy 0.7.12 → 0.7.14

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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.14
4
+
5
+ - Keep model discovery off Pi's session-start critical path and load the MCP bridge only when needed.
6
+ - Add regression coverage confirming the extension starts without loading the bridge dependencies.
7
+ - Full 491-test suite, typecheck, and package checks pass.
8
+
9
+ ## 0.7.13
10
+
11
+ - Refresh the separate `/agy` delegation picker with every discovered concrete model ID, not just fixed aliases; preserve exact names and Gemini tier variants.
12
+ - Add explicit `/agy model=<id>` selection and native completion that preserves preceding options and following task text. Existing alias shortcuts remain available.
13
+ - Preserve concrete model IDs through confirmation, execution, quotas, receipts, and conversation resume; retain original executed targets across parked provider turns without changing native resume keys.
14
+ - Report discovery failures and distinguish last-good rosters from built-in alias fallbacks. Keep canceled and superseded discovery from replacing newer state.
15
+ - Full 490-test gate, typecheck, and package checks pass. Live discovery still requires authenticated agy.
16
+
3
17
  ## 0.7.12
4
18
 
5
19
  - Refresh the full Antigravity model catalog automatically at session startup and whenever Pi opens `/model`, using Pi's native refresh lifecycle instead of a one-time discovery probe.
package/README.md CHANGED
@@ -24,10 +24,11 @@ Useful options include:
24
24
  - `background=true` to return a handle, then use `agy_tasks` to poll, collect, or cancel
25
25
  - `context=summary|recent` to optionally pass bounded Pi conversation context (default: none)
26
26
 
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:
27
+ The `/agy` command runs tasks from Pi's TUI and can also list agents, inspect quota, diagnose setup, and select saved conversations. Its model picker refreshes the full concrete ID list from `agy models` each time it opens; alias shortcuts remain available. Discovery failures show the reason and mark cached or fallback choices as unverified. Use `model=<id>` for an exact CLI model ID; bare aliases such as `sonnet` still work. For example:
28
28
 
29
29
  ```text
30
30
  /agy plan flash investigate the failing tests
31
+ /agy plan model=argon investigate the failing tests
31
32
  /agy continue fix the remaining issues
32
33
  /agy sessions
33
34
  /agy doctor
@@ -1,5 +1,6 @@
1
+ import { storedModelSelection, type AgyModelSelection } from "./lib/model-selection.js";
1
2
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
- import { isAgyModel, resolveAgyModelId, type AgyModel } from "./lib/cli.js";
3
+ import { resolveAgyModelId } from "./lib/cli.js";
3
4
  import { buildAgyContextFromEntries, effectiveResumeContextMode, type AgyContextMode } from "./lib/context.js";
4
5
  import { describePreRunDirt } from "./lib/postflight.js";
5
6
  import { DEFAULT_TIMEOUT_MS } from "./lib/command-args.js";
@@ -10,9 +11,8 @@ import { AGY_RUN_ENTRY_TYPE, type AgyRunReceipt } from "./lib/render.js";
10
11
  import { getHistory } from "./lib/sessions.js";
11
12
  import { normalizeConversationSelection, type ConversationSelection } from "./lib/request.js";
12
13
 
13
- export interface InteractiveRun {
14
+ export type InteractiveRun = AgyModelSelection & {
14
15
  mode: "plan" | "accept-edits" | "sandbox";
15
- model: AgyModel;
16
16
  agent?: string;
17
17
  prompt: string;
18
18
  conversation_id?: string;
@@ -40,7 +40,7 @@ export async function runSessionsPicker(
40
40
 
41
41
  const options = history.map((entry, index) => {
42
42
  const id = entry.conversation_id.slice(0, 8);
43
- const model = entry.model ?? "unknown model";
43
+ const model = entry.raw_model_id ?? entry.model ?? "unknown model";
44
44
  const agent = entry.agent ? ` · agent ${entry.agent}` : "";
45
45
  const summary = entry.summary ? `${entry.summary.slice(0, 50)} · ` : "";
46
46
  return `${index + 1}. ${summary}${model}${agent} · ${describeWhen(entry.updated_at)} · ${id}…`;
@@ -69,9 +69,14 @@ export async function runSessionsPicker(
69
69
  return;
70
70
  }
71
71
 
72
+ const modelSelection = storedModelSelection(entry.model, entry.raw_model_id);
73
+ if (!modelSelection) {
74
+ ctx.ui.notify("agy: recorded model is missing, invalid, or ambiguous; resume with an explicit model=<id> using /agy continue", "error");
75
+ return;
76
+ }
72
77
  await executeConfirmedRun(pi, ctx, {
73
78
  mode,
74
- model: isAgyModel(entry.model) ? entry.model : "flash-medium",
79
+ ...modelSelection,
75
80
  agent: entry.agent,
76
81
  prompt: text.trim(),
77
82
  conversation_id: entry.conversation_id,
@@ -110,7 +115,7 @@ export async function executeConfirmedRun(
110
115
  if (run.mode === "accept-edits") {
111
116
  const dirt = await describePreRunDirt(cwd, ctx.signal).catch(() => null);
112
117
  const { title, body } = buildAcceptEditsConfirm({
113
- modelLabel: `${run.model} (${resolveAgyModelId(run.model)})`,
118
+ modelLabel: run.model_id ?? `${run.model} (${resolveAgyModelId(run.model)})`,
114
119
  agent: run.agent,
115
120
  cwd,
116
121
  prompt: run.prompt,
@@ -129,11 +134,11 @@ export async function executeConfirmedRun(
129
134
  // a second LLM turn and the command works even when tools are limited.
130
135
  const status = createStatusThrottler(ctx);
131
136
  try {
132
- status(`starting (${run.model} · ${run.mode}${run.agent ? ` · agent ${run.agent}` : ""})`);
137
+ status(`starting (${run.model_id ?? run.model} · ${run.mode}${run.agent ? ` · agent ${run.agent}` : ""})`);
133
138
  const result = await executeAgyTask(
134
139
  {
135
140
  prompt: run.prompt,
136
- model: run.model,
141
+ ...(run.model_id ? { model_id: run.model_id } : { model: run.model, tier: run.tier }),
137
142
  agent: run.agent,
138
143
  mode: run.mode,
139
144
  dir: cwd,
@@ -1,25 +1,21 @@
1
- import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
1
+ import path from "node:path";
2
+ import { inspectAgyModelIds } from "./lib/inspect.js";
3
+ import { storedModelSelection, type AgyModelSelection } from "./lib/model-selection.js";
4
+ import type { AgyModelId } from "./lib/provider-models.js";
5
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
6
 
3
7
  import {
4
- inspectAgyModels,
5
- isAgyModel,
8
+ parseModelCatalog,
9
+ updateModelCatalog,
6
10
  normalizeAgyAgentName,
7
11
  resolveAgyModelId,
8
12
  } from "./lib/cli.js";
9
- import { truncate } from "./lib/output.js";
10
13
  import { AGY_RUN_ENTRY_TYPE, renderAgyRunReceipt } from "./lib/render.js";
11
14
  import { getSession } from "./lib/sessions.js";
12
15
 
13
16
  import { MODEL_ALIASES, MODEL_KEYS, MODE_KEYS, parseAgyCommandArgs } from "./lib/command-args.js";
14
17
  import { executeConfirmedRun, MODE_OPTIONS, optionKey, runSessionsPicker, type InteractiveRun } from "./command-run.js";
15
18
  import { showAgents, showBridge, showDoctor, showUsage } from "./command-info.js";
16
- import { buildAcceptEditsConfirm } from "./lib/confirm.js";
17
-
18
- function modelOptions(): string[] {
19
- return Object.keys(MODEL_ALIASES).map((alias) =>
20
- `${alias} — ${resolveAgyModelId(MODEL_ALIASES[alias])}`,
21
- );
22
- }
23
19
 
24
20
  export { parseAgyCommandArgs, type AgyCommandArgs } from "./lib/command-args.js";
25
21
 
@@ -29,14 +25,25 @@ export { parseAgyCommandArgs, type AgyCommandArgs } from "./lib/command-args.js"
29
25
  * confirmed parameters stay authoritative with no second LLM turn.
30
26
  */
31
27
  export function registerAgyCommand(pi: ExtensionAPI): void {
28
+ const rosters = new Map<string, { ids?: AgyModelId[]; request: number }>();
29
+ let completionCwd: string | undefined;
32
30
  pi.registerEntryRenderer?.(AGY_RUN_ENTRY_TYPE, (entry, options, theme) =>
33
31
  renderAgyRunReceipt(entry.data, options, theme),
34
32
  );
35
33
 
36
34
  pi.registerCommand("agy", {
37
35
  description:
38
- "Run agy directly: /agy [mode] [model] [agent=name] [continue] [context=summary|recent] [timeout=10m] <prompt>; use /agy agents to list custom agents.",
36
+ "Run agy directly: /agy [mode] [model|model=id] [agent=name] [continue] [context=summary|recent] [timeout=10m] <prompt>; use /agy agents to list custom agents.",
39
37
  getArgumentCompletions: (prefix: string) => {
38
+ const exactPrefix = /(?:^|\s)model=(\S*)$/.exec(prefix);
39
+ if (exactPrefix) {
40
+ // Pi replaces the whole argument prefix with item.value, not just
41
+ // the current token. Preserve every preceding option and separator.
42
+ const beforeId = prefix.slice(0, prefix.length - exactPrefix[1].length);
43
+ return (rosters.get(completionCwd ?? "")?.ids ?? [])
44
+ .filter(id => id.startsWith(exactPrefix[1]))
45
+ .map(id => ({ value: `${beforeId}${id}`, label: `${id} (last successful discovery)` }));
46
+ }
40
47
  const tokens = prefix.trim().split(/\s+/).filter(Boolean);
41
48
  const p = prefix.toLowerCase();
42
49
 
@@ -51,6 +58,7 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
51
58
  ...(tokens[0] === "usage" || tokens[0] === "quota"
52
59
  ? []
53
60
  : [
61
+ { value: "model=", label: "model=" },
54
62
  { value: "agent=", label: "agent=" },
55
63
  { value: "continue", label: "continue" },
56
64
  { value: "timeout=10m", label: "timeout=10m" },
@@ -82,6 +90,7 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
82
90
  "context=summary",
83
91
  "context=recent",
84
92
  "timeout=10m",
93
+ "model=",
85
94
  ].filter((k) => k.startsWith(p));
86
95
  return [
87
96
  ...modes.map((m) => ({ value: m, label: m })),
@@ -92,6 +101,7 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
92
101
  return null;
93
102
  },
94
103
  handler: async (args, ctx) => {
104
+ completionCwd = path.resolve(ctx.cwd);
95
105
  if (ctx.mode !== "tui") {
96
106
  ctx.ui.notify("/agy requires interactive (TUI) mode", "error");
97
107
  return;
@@ -152,33 +162,56 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
152
162
  mode = optionKey(pick) as InteractiveRun["mode"];
153
163
  }
154
164
 
155
- let model = parsed.model;
165
+ let modelSelection: AgyModelSelection | undefined = parsed.model_id
166
+ ? { model_id: parsed.model_id }
167
+ : parsed.model ? { model: parsed.model } : undefined;
156
168
  let agent = parsed.agent;
157
- if (parsed.continue && (!model || !agent)) {
169
+ if (parsed.continue && (!modelSelection || !agent)) {
158
170
  const prior = await getSession(ctx.cwd);
159
- if (!model && prior?.last_model && isAgyModel(prior.last_model)) model = prior.last_model;
171
+ if (!modelSelection) modelSelection = storedModelSelection(prior?.last_model, prior?.last_raw_model_id);
160
172
  if (!agent && prior?.last_agent) {
161
- try {
162
- agent = normalizeAgyAgentName(prior.last_agent);
163
- } catch {
173
+ try { agent = normalizeAgyAgentName(prior.last_agent); } catch {
164
174
  // Ignore malformed legacy session metadata.
165
175
  }
166
176
  }
167
177
  }
168
- if (!model) {
169
- // Refresh once when opening the picker so labels show the concrete IDs
170
- // exposed by this account, while retaining the stable alias interface.
178
+ if (!modelSelection) {
179
+ const key = path.resolve(ctx.cwd);
180
+ let state = rosters.get(key);
181
+ if (!state) {
182
+ state = { request: 0 };
183
+ rosters.set(key, state);
184
+ }
185
+ const request = ++state.request;
186
+ let live = false;
171
187
  try {
172
- await inspectAgyModels(ctx.cwd, ctx.signal);
173
- } catch {
174
- // Keep the picker usable with the built-in fallback aliases.
188
+ const ids = await inspectAgyModelIds(ctx.cwd, ctx.signal);
189
+ if (ctx.signal?.aborted || state.request !== request) return;
190
+ updateModelCatalog(parseModelCatalog(ids.join("\n")));
191
+ state.ids = ids;
192
+ live = true;
193
+ } catch (error) {
194
+ if (ctx.signal?.aborted || state.request !== request) return;
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ ctx.ui.notify(`agy model discovery failed: ${message}. ${state.ids ? "Using last successful roster; availability is unverified." : "Using built-in alias fallback; availability is unverified."}`, "warning");
175
197
  }
176
- const pick = await ctx.ui.select("agy model", modelOptions());
177
- if (!pick) {
198
+ const choices: Array<{ label: string; selection: AgyModelSelection }> = [
199
+ ...(state.ids ?? []).map(id => ({ label: id, selection: { model_id: id } })),
200
+ ...Object.entries(MODEL_ALIASES).map(([alias, model]) => ({
201
+ label: `${alias} — alias shortcut (${resolveAgyModelId(model)}; availability unverified)`,
202
+ selection: { model },
203
+ })),
204
+ ];
205
+ const title = live ? "agy model (discovered IDs; alias shortcuts below)"
206
+ : state.ids ? "agy model (last successful roster; availability unverified)"
207
+ : "agy model (built-in alias fallback; availability unverified)";
208
+ const pick = await ctx.ui.select(title, choices.map(choice => choice.label));
209
+ if (ctx.signal?.aborted || state.request !== request) return;
210
+ modelSelection = choices.find(choice => choice.label === pick)?.selection;
211
+ if (!modelSelection) {
178
212
  ctx.ui.notify("agy: cancelled", "info");
179
213
  return;
180
214
  }
181
- model = MODEL_ALIASES[optionKey(pick)] ?? "flash-medium";
182
215
  }
183
216
 
184
217
  let prompt = parsed.prompt;
@@ -193,7 +226,7 @@ export function registerAgyCommand(pi: ExtensionAPI): void {
193
226
 
194
227
  await executeConfirmedRun(pi, ctx, {
195
228
  mode,
196
- model,
229
+ ...modelSelection,
197
230
  agent,
198
231
  prompt,
199
232
  continue: parsed.continue,
@@ -128,14 +128,21 @@ function registerAgyProvider(pi: ExtensionAPI): void {
128
128
  shutdown.abort();
129
129
  return;
130
130
  }
131
- pi.on?.("session_start", async (_event, ctx) => {
131
+ pi.on?.("session_start", (_event, ctx) => {
132
132
  const signal = AbortSignal.any([shutdown.signal, AbortSignal.timeout(10_000)]);
133
- const result = await ctx.modelRegistry.refresh({
133
+ // Keep provider discovery off Pi's session-start critical path. The model
134
+ // picker also refreshes on demand, so startup can use the cached catalog.
135
+ void ctx.modelRegistry.refresh({
134
136
  providers: [AGY_PROVIDER_ID], allowNetwork: true, signal,
137
+ }).then((result) => {
138
+ if (!signal.aborted && result.errors.has(AGY_PROVIDER_ID)) {
139
+ ctx.ui.notify("Could not refresh Antigravity models; showing cached models. Reopen /model to retry.", "warning");
140
+ }
141
+ }).catch(() => {
142
+ if (!signal.aborted) {
143
+ ctx.ui.notify("Could not refresh Antigravity models; showing cached models. Reopen /model to retry.", "warning");
144
+ }
135
145
  });
136
- if (!signal.aborted && result.errors.has(AGY_PROVIDER_ID)) {
137
- ctx.ui.notify("Could not refresh Antigravity models; showing cached models. Reopen /model to retry.", "warning");
138
- }
139
146
  });
140
147
  }
141
148
 
@@ -6,6 +6,8 @@
6
6
  * `cli.ts` re-exports the public surface so existing importers are untouched.
7
7
  */
8
8
 
9
+ import { validateModelSelector } from "./model-selection.js";
10
+
9
11
  import { getModelCatalog, normalizeAgyAgentName } from "./inspect.js";
10
12
  import type { AgyModel, AgyOptions } from "./cli.js";
11
13
 
@@ -65,7 +67,8 @@ export function buildAgyArgs(options: AgyOptions): string[] {
65
67
  throw new Error("agy cannot use --continue and --conversation together");
66
68
  }
67
69
 
68
- const model = resolveAgyModelId(options.model, options.tier);
70
+ validateModelSelector(options);
71
+ const model = options.model_id ?? resolveAgyModelId(options.model, options.tier);
69
72
  const agent = normalizeAgyAgentName(options.agent);
70
73
  const unbucketedSec = Math.ceil((options.timeout_ms + PRINT_TIMEOUT_BUFFER_MS) / 1000);
71
74
  const timeoutSec = Math.ceil(unbucketedSec / PRINT_TIMEOUT_BUCKET_S) * PRINT_TIMEOUT_BUCKET_S;
@@ -86,7 +89,7 @@ export function buildAgyArgs(options: AgyOptions): string[] {
86
89
  "--disable-slash-commands",
87
90
  ...(mode === "sandbox" ? ["--sandbox"] : ["--mode", mode]),
88
91
  ...(writes && skipPermissions ? ["--dangerously-skip-permissions"] : []),
89
- ...(options.effort && supportsAgyEffort(options.model, options.tier)
92
+ ...(options.effort && (options.model_id ? options.model_id.startsWith("gpt-oss-") : supportsAgyEffort(options.model, options.tier))
90
93
  ? ["--effort", options.effort]
91
94
  : []),
92
95
  ...(agent ? ["--agent", agent] : []),
@@ -1,3 +1,4 @@
1
+ import type { AgyModelSelector } from "./model-selection.js";
1
2
  export { detectVerifyCommand, detectVerifyCommandFromPackageJson } from "./verify.js";
2
3
  export { parseJsonResponse } from "./parse.js";
3
4
 
@@ -22,10 +23,8 @@ export type AgyEffort = "low" | "medium" | "high";
22
23
 
23
24
  export type { AgyQuotaEntry, AgyUsageSnapshot } from "./usage.js";
24
25
 
25
- export interface AgyOptions {
26
+ export type AgyOptions = AgyModelSelector & {
26
27
  prompt: string;
27
- model?: AgyModel;
28
- tier?: "flash" | "flash-lo" | "pro";
29
28
  effort?: AgyEffort;
30
29
  /** Optional custom agent name passed to `agy --agent`. */
31
30
  agent?: string;
@@ -6,6 +6,8 @@
6
6
  * parser for its existing test importers.
7
7
  */
8
8
 
9
+ import { validateAgyModelId, type AgyModelId } from "./provider-models.js";
10
+
9
11
  import { normalizeAgyAgentName, type AgyModel } from "./cli.js";
10
12
  import type { AgyContextMode } from "./context.js";
11
13
 
@@ -32,6 +34,7 @@ export const MAX_TIMEOUT_MS = 600_000;
32
34
  export interface AgyCommandArgs {
33
35
  mode?: "plan" | "accept-edits" | "sandbox";
34
36
  model?: AgyModel;
37
+ model_id?: AgyModelId;
35
38
  agent?: string;
36
39
  prompt?: string;
37
40
  continue?: boolean;
@@ -56,8 +59,16 @@ export function parseAgyCommandArgs(args: string): AgyCommandArgs {
56
59
  const timeout = parseTimeoutToken(token.value);
57
60
  if (MODE_KEYS.includes(value as (typeof MODE_KEYS)[number])) {
58
61
  parsed.mode = value as AgyCommandArgs["mode"];
59
- } else if (MODEL_ALIASES[value]) {
62
+ } else if (Object.hasOwn(MODEL_ALIASES, value)) {
63
+ if (parsed.model_id !== undefined) parsed.error = "model and model= cannot be combined";
60
64
  parsed.model = MODEL_ALIASES[value];
65
+ } else if (value.startsWith("model=")) {
66
+ try {
67
+ if (parsed.model !== undefined || parsed.model_id !== undefined) throw new Error("model= cannot be combined with another model selector");
68
+ parsed.model_id = validateAgyModelId(token.value.slice("model=".length));
69
+ } catch (error) {
70
+ parsed.error = error instanceof Error ? error.message : String(error);
71
+ }
61
72
  } else if (value === "continue") {
62
73
  parsed.continue = true;
63
74
  } else if (value.startsWith("agent=")) {
@@ -1,3 +1,5 @@
1
+ import { validateModelSelector, type AgyModelSelector } from "./model-selection.js";
2
+ import type { AgyModelId } from "./provider-models.js";
1
3
  import { stat } from "node:fs/promises";
2
4
 
3
5
  import {
@@ -39,10 +41,8 @@ import { normalizeConversationSelection } from "./request.js";
39
41
 
40
42
  export type AgyMode = "plan" | "accept-edits" | "sandbox";
41
43
 
42
- export interface AgyExecutionOptions {
44
+ export type AgyExecutionOptions = AgyModelSelector & {
43
45
  prompt: string;
44
- model?: AgyModel;
45
- tier?: "flash" | "flash-lo" | "pro";
46
46
  effort?: AgyEffort;
47
47
  agent?: string;
48
48
  mode: AgyMode;
@@ -60,7 +60,7 @@ export interface AgyExecutionOptions {
60
60
 
61
61
  export interface AgyExecutionDetails {
62
62
  mode: AgyMode;
63
- model: AgyModel | "flash-medium";
63
+ model: AgyModel | AgyModelId;
64
64
  dir: string;
65
65
  conversation_id?: string;
66
66
  verify_cmd: string | null;
@@ -104,17 +104,17 @@ export async function executeAgyTask(
104
104
  () => budgetController.abort(),
105
105
  Math.max(options.timeout_ms, 0),
106
106
  );
107
- let effectiveModel: AgyModel | "flash-medium" = "flash-medium";
107
+ let effectiveModel: AgyModel | AgyModelId = "flash-medium";
108
108
 
109
109
  try {
110
110
  const config = await loadAgyConfig(undefined, abortSignal);
111
111
  // Explicit model → legacy tier → configured default → flash-medium.
112
112
  const selectedModel = resolveAgyModelAlias(options.model, options.tier);
113
- const resolvedModel = selectedModel ?? (await resolveDefaultModel(config, abortSignal));
113
+ const resolvedModel = selectedModel ?? (options.model_id ? undefined : await resolveDefaultModel(config, abortSignal));
114
114
  let model: AgyModel = resolvedModel ?? "flash-medium";
115
- effectiveModel = model;
115
+ effectiveModel = options.model_id ?? model;
116
116
  const autoModelSelection =
117
- !selectedModel && !config.defaultModel && !config.defaultModelCommand;
117
+ !options.model_id && !selectedModel && !config.defaultModel && !config.defaultModelCommand;
118
118
  const skipPermissions = config.skipPermissions !== false;
119
119
 
120
120
  return await withDirLock(
@@ -177,7 +177,7 @@ export async function executeAgyTask(
177
177
  const run = await runWithTransientRetry(async (trackProgress) => {
178
178
  const remainingMs = remainingBudget(startedAt, options.timeout_ms);
179
179
  quota = await runPreflight(options.dir, abortSignal, remainingMs);
180
- const selectedModelId = resolveAgyModelId(model, options.tier);
180
+ const selectedModelId = options.model_id ?? resolveAgyModelId(model, options.tier);
181
181
  const selectedQuotas = findAgyQuotaEntries(quota, selectedModelId);
182
182
  quotaStatus = quota
183
183
  ? selectedQuotas.length === 0
@@ -223,7 +223,7 @@ export async function executeAgyTask(
223
223
  return spawnAgyStream(
224
224
  {
225
225
  prompt: finalPrompt,
226
- model,
226
+ ...(options.model_id ? { model_id: options.model_id } : { model }),
227
227
  effort: options.effort,
228
228
  agent,
229
229
  mode: options.mode,
@@ -250,6 +250,7 @@ export async function executeAgyTask(
250
250
  AbortSignal.timeout(10_000),
251
251
  conversationSummary(options.prompt),
252
252
  agent,
253
+ options.model_id,
253
254
  );
254
255
  } catch (error) {
255
256
  const reason = error instanceof Error ? error.message : String(error);
@@ -264,7 +265,7 @@ export async function executeAgyTask(
264
265
  const subagentSummary = formatAgySubagentObservations(run.subagents);
265
266
  if (subagentSummary) text = `${text}\n\n## ${subagentSummary}`;
266
267
  const quotaSummary = quota?.models.length
267
- ? formatAgyUsage(quota, resolveAgyModelId(model, options.tier))
268
+ ? formatAgyUsage(quota, options.model_id ?? resolveAgyModelId(model, options.tier))
268
269
  : undefined;
269
270
  if (quotaSummary) text = `${text}\n\n## agy quota snapshot\n${quotaSummary}`;
270
271
  let changedFiles: string[] | undefined;
@@ -331,6 +332,7 @@ export async function executeAgyTask(
331
332
  AbortSignal.timeout(10_000),
332
333
  conversationSummary(options.prompt),
333
334
  agent,
335
+ options.model_id,
334
336
  );
335
337
  conversationPersisted = true;
336
338
  } catch {
@@ -353,6 +355,7 @@ export async function executeAgyTask(
353
355
 
354
356
  export function validateAgyExecutionOptions(options: AgyExecutionOptions): void {
355
357
  if (!options.prompt?.trim()) throw new Error("agy prompt must not be empty");
358
+ validateModelSelector(options);
356
359
  normalizeAgyAgentName(options.agent);
357
360
  if (!Number.isFinite(options.timeout_ms) || options.timeout_ms <= 0) {
358
361
  throw new Error("agy timeout_ms must be a positive finite number");
@@ -5,6 +5,8 @@
5
5
  * so existing importers are untouched.
6
6
  */
7
7
 
8
+ import { parseAgyModelIds, type AgyModelId } from "./provider-models.js";
9
+
8
10
  import { compareModelIds } from "./model-sort.js";
9
11
  import { runPreflightCommand } from "./spawn.js";
10
12
  import { parseAgyUsage, usageError, type AgyUsageSnapshot } from "./usage.js";
@@ -113,6 +115,18 @@ export async function inspectAgyModels(
113
115
  return catalog;
114
116
  }
115
117
 
118
+ /** Raw delegation roster; successful empty/malformed output is not availability. */
119
+ export async function inspectAgyModelIds(
120
+ cwd: string, signal?: AbortSignal, timeoutMs?: number,
121
+ ): Promise<AgyModelId[]> {
122
+ const output = await runPreflightCommand(
123
+ ["models"], cwd, signal, "agy model discovery", true, timeoutMs,
124
+ );
125
+ const ids = parseAgyModelIds(output);
126
+ if (!ids.length) throw new Error("agy models returned no valid model IDs");
127
+ return ids;
128
+ }
129
+
116
130
  export async function checkAgyConnectivity(
117
131
  cwd: string,
118
132
  signal?: AbortSignal,
@@ -0,0 +1,31 @@
1
+ import { isAgyModel, type AgyModel } from "./cli.js";
2
+ import { validateAgyModelId, type AgyModelId } from "./provider-models.js";
3
+
4
+ /** Keep closed aliases exhaustive; concrete IDs are a separate, exclusive selector. */
5
+ export type AgyModelSelector =
6
+ | { model?: AgyModel; tier?: "flash" | "flash-lo" | "pro"; model_id?: never }
7
+ | { model_id: AgyModelId; model?: never; tier?: never };
8
+
9
+ /** Interactive runs always have an explicit selection; executor callers may use defaults. */
10
+ export type AgyModelSelection = AgyModelSelector & ({ model: AgyModel } | { model_id: AgyModelId });
11
+
12
+ export function validateModelSelector(selection: AgyModelSelector): void {
13
+ if (selection.model_id !== undefined) {
14
+ validateAgyModelId(selection.model_id);
15
+ if (selection.model !== undefined || selection.tier !== undefined) {
16
+ throw new Error("agy model_id cannot be combined with model or tier");
17
+ }
18
+ }
19
+ }
20
+
21
+ /** Legacy provider keys may be slugified: never guess a distorted hyphenated ID. */
22
+ export function storedModelSelection(value: unknown, rawModelId?: unknown): AgyModelSelection | undefined {
23
+ try {
24
+ if (rawModelId !== undefined) return { model_id: validateAgyModelId(rawModelId) };
25
+ if (isAgyModel(value)) return { model: value };
26
+ const id = validateAgyModelId(value);
27
+ // Dots cannot come from Pi slugification; bare IDs survive it unchanged.
28
+ if (id.includes(".") || !id.includes("-")) return { model_id: id };
29
+ } catch { /* Missing or malformed legacy metadata requires explicit selection. */ }
30
+ return undefined;
31
+ }
@@ -35,6 +35,7 @@ import {
35
35
 
36
36
  import { getDefaultConfigPath } from "./config.js";
37
37
  import { isBridgeInputWithinBudget } from "./bridge-input-budget.js";
38
+ import type { BridgeToolDef } from "./provider-tools.js";
38
39
  import { checkAgyUsage, formatAgyUsage } from "./cli.js";
39
40
  import {
40
41
  FALLBACK_PROVIDER_MODELS,
@@ -180,16 +181,6 @@ export interface McpBridgeHandle {
180
181
  describe: () => { configDir: string; url: string; toolCount: number; pendingResults: number };
181
182
  }
182
183
 
183
- /** A Pi tool projected for agy: MCP-safe advertised name, real Pi identity. */
184
- export interface BridgeToolDef {
185
- /** MCP-safe name as advertised to agy. */
186
- name: string;
187
- /** Real Pi tool name (invoked via shadow toolUse). */
188
- piName: string;
189
- description: string;
190
- inputSchema: Record<string, unknown>;
191
- }
192
-
193
184
  export interface BridgePark {
194
185
  callId: string;
195
186
  /** Real Pi tool name. */
@@ -204,15 +195,6 @@ export interface BridgeToolResult {
204
195
 
205
196
  export type BridgeParkHandler = (park: BridgePark) => boolean;
206
197
 
207
- /** MCP tool names: [a-zA-Z0-9_-]{1,64}. Pi names are sanitized into that. */
208
- export function toSafeBridgeName(name: string): string {
209
- const safe = name
210
- .replace(/[^a-zA-Z0-9_-]+/g, "_")
211
- .replace(/^_+|_+$/g, "")
212
- .slice(0, 64);
213
- return safe || "tool";
214
- }
215
-
216
198
  interface CatalogCache {
217
199
  raw: string;
218
200
  at: number;
@@ -49,6 +49,28 @@ const MODEL_LINE_RE = /^[A-Za-z0-9][A-Za-z0-9._]*-[A-Za-z0-9._-]*$/;
49
49
  const NONHYPHEN_MODEL_ID_RE = /^[a-z0-9](?:[a-z0-9._]*[a-z0-9_])?$/;
50
50
  const NON_MODEL_TOKEN_RE = /^(?:id|model|models|name|label|status|available|fetching|loading|error|warning|info|auth|authentication|unauthorized|forbidden|login|success)$/;
51
51
 
52
+ /** Exact CLI IDs, validated with the same token rules used by native discovery. */
53
+ declare const agyModelId: unique symbol;
54
+ export type AgyModelId = string & { readonly [agyModelId]: true };
55
+
56
+ export function isAgyModelId(value: unknown): value is AgyModelId {
57
+ return typeof value === "string" && !/[\s\x00-\x1f\x7f-\x9f]/.test(value) && (
58
+ MODEL_LINE_RE.test(value) ||
59
+ (NONHYPHEN_MODEL_ID_RE.test(value) && !NON_MODEL_TOKEN_RE.test(value))
60
+ );
61
+ }
62
+
63
+ export function validateAgyModelId(value: unknown): AgyModelId {
64
+ if (!isAgyModelId(value)) throw new Error("agy model ID must be a nonempty CLI ID without whitespace or leading flags");
65
+ return value;
66
+ }
67
+
68
+ /** Preserve full first-column IDs and tiers; never slugify or group delegation IDs. */
69
+ export function parseAgyModelIds(raw: string): AgyModelId[] {
70
+ const ids = raw.split("\n").map(line => line.trim().split(/\s+/)[0]);
71
+ return [...new Set(ids.filter(isAgyModelId))];
72
+ }
73
+
52
74
  /**
53
75
  * Families verified to accept base-slug + `--effort`. Only these collapse to
54
76
  * a base entry with a thinking toggle; every other family keeps agy's exact
@@ -146,12 +168,7 @@ export function thinkingMapForEfforts(
146
168
  */
147
169
  export function parseProviderCatalog(raw: string): AgyProviderModelEntry[] {
148
170
  const groups = new Map<string, { lines: string[]; tiers: Set<AgyProviderEffort> }>();
149
- for (const line of raw.split("\n")) {
150
- const slug = line.trim().split(/\s+/)[0] ?? "";
151
- if (
152
- !MODEL_LINE_RE.test(slug) &&
153
- (!NONHYPHEN_MODEL_ID_RE.test(slug) || NON_MODEL_TOKEN_RE.test(slug))
154
- ) continue;
171
+ for (const slug of parseAgyModelIds(raw)) {
155
172
  const match = TIER_RE.exec(slug);
156
173
  const base = match ? match[1] : slug;
157
174
  const tier = match ? (match[2] as AgyProviderEffort) : null;
@@ -1,4 +1,19 @@
1
- import { toSafeBridgeName, type BridgeToolDef } from "./provider-mcp.js";
1
+ /** A Pi tool projected for agy: MCP-safe advertised name, real Pi identity. */
2
+ export interface BridgeToolDef {
3
+ name: string;
4
+ piName: string;
5
+ description: string;
6
+ inputSchema: Record<string, unknown>;
7
+ }
8
+
9
+ /** MCP tool names: [a-zA-Z0-9_-]{1,64}. Pi names are sanitized into that. */
10
+ function toSafeBridgeName(name: string): string {
11
+ const safe = name
12
+ .replace(/[^a-zA-Z0-9_-]+/g, "_")
13
+ .replace(/^_+|_+$/g, "")
14
+ .slice(0, 64);
15
+ return safe || "tool";
16
+ }
2
17
 
3
18
  /** Pi tool source shape (structural subset of Pi's ToolInfo). */
4
19
  export interface ProviderToolSource {
@@ -42,15 +42,14 @@ export {
42
42
  } from "./provider-prompt.js";
43
43
 
44
44
  import { withDirLock } from "./lock.js";
45
- import {
46
- startMcpBridge,
47
- type BridgeToolDef,
48
- type McpBridgeHandle,
49
- } from "./provider-mcp.js";
45
+ import type { McpBridgeHandle } from "./provider-mcp.js";
46
+ import type { BridgeToolDef } from "./provider-tools.js";
50
47
  import { getSession, saveSession } from "./sessions.js";
51
48
  import { AgyProviderDriver, PROVIDER_TURN_TIMEOUT_MS } from "./provider-driver.js";
52
49
  import {
53
50
  toProviderEffort,
51
+ validateAgyModelId,
52
+ type AgyModelId,
54
53
  type AgyProviderEffort,
55
54
  type AgyProviderModelEntry,
56
55
  type AgyThinkingLevel,
@@ -301,6 +300,8 @@ async function ensureProviderBridge(dir: string): Promise<McpBridgeHandle | unde
301
300
  try {
302
301
  const config = await loadAgyConfig();
303
302
  if (config.providerBridge !== false) {
303
+ // Keep the bridge and its MCP SDK off the extension startup path.
304
+ const { startMcpBridge } = await import("./provider-mcp.js");
304
305
  handle = await startMcpBridge(dir);
305
306
  }
306
307
  } catch {
@@ -521,6 +522,8 @@ function hasUserMessageAfterToolCall(messages: ProviderTranscriptMessage[], tool
521
522
  }
522
523
 
523
524
  interface SuspendedTurn {
525
+ /** Original executed selector, retained across reasoning/catalog changes and re-parks. */
526
+ rawModelId: AgyModelId;
524
527
  runner: ProviderTurnRunner;
525
528
  ownership?: ProviderTurnOwnership;
526
529
  toolCallId: string;
@@ -679,7 +682,9 @@ export function createAgyStreamSimple(
679
682
  const prior = suspendedByDir.get(skey);
680
683
  const bodies = prior ? collectParkedDeliveries(messages, prior.toolCallId) : [];
681
684
  let end: ProviderRunEnd;
685
+ let executedRawModelId: AgyModelId;
682
686
  if (prior && bodies.length > 0) {
687
+ executedRawModelId = prior.rawModelId;
683
688
  prior.ownership?.assertValid();
684
689
  suspendedByDir.delete(skey);
685
690
  // Images riding on the delivered tool results are staged too:
@@ -751,6 +756,11 @@ export function createAgyStreamSimple(
751
756
  const staged = await stageImages(collectImageBlocks(messages));
752
757
  pendingImageCleanups.push(staged.cleanup);
753
758
  const prompt = renderProviderPrompt(messages, systemPrompt || undefined, staged.paths);
759
+ // Capture before execution: later invocations can resolve a different
760
+ // profile while this child remains parked on its original target.
761
+ executedRawModelId = validateAgyModelId(
762
+ turnModel.effort ? `${turnModel.full}-${turnModel.effort}` : turnModel.full,
763
+ );
754
764
  end = await runner.run({
755
765
  fullModel: turnModel.full,
756
766
  effort: turnModel.effort,
@@ -788,6 +798,7 @@ export function createAgyStreamSimple(
788
798
  end.ownership?.assertValid();
789
799
  suspendedByDir.set(skey, {
790
800
  runner, ownership: end.ownership, toolCallId, park: end.park,
801
+ rawModelId: executedRawModelId,
791
802
  modelId: model.id, imageCleanups: pendingImageCleanups,
792
803
  });
793
804
  output.content.push(toolCall);
@@ -837,7 +848,10 @@ export function createAgyStreamSimple(
837
848
  // Preserve a delegation-recorded agent: provider turns must not
838
849
  // wipe the agent that /agy continue would otherwise restore.
839
850
  const prior = await getSession(dir).catch(() => undefined);
840
- await saveSession(dir, result.conversationId, model.id, undefined, summary, prior?.last_agent);
851
+ // Native resume still keys on model.id. Delegation needs the exact
852
+ // CLI ID, including the concrete Gemini tier represented by the
853
+ // catalog's base + effort pair (never the normalized Pi ID).
854
+ await saveSession(dir, result.conversationId, model.id, undefined, summary, prior?.last_agent, executedRawModelId);
841
855
  } catch {
842
856
  // Recording failures must never fail a completed turn.
843
857
  }
@@ -1,3 +1,4 @@
1
+ import { isAgyModelId, validateAgyModelId, type AgyModelId } from "./provider-models.js";
1
2
  import {
2
3
  chmod,
3
4
  mkdir,
@@ -16,6 +17,8 @@ import { randomUUID } from "node:crypto";
16
17
  export interface AgyConversationEntry {
17
18
  conversation_id: string;
18
19
  model?: string;
20
+ /** Exact delegation CLI ID; model remains the alias or native provider resume key. */
21
+ raw_model_id?: AgyModelId;
19
22
  agent?: string;
20
23
  updated_at: string;
21
24
  /** Short task excerpt so humans and agents can tell conversations apart. */
@@ -25,6 +28,7 @@ export interface AgyConversationEntry {
25
28
  export interface AgySessionRecord {
26
29
  last_conversation_id?: string;
27
30
  last_model?: string;
31
+ last_raw_model_id?: AgyModelId;
28
32
  last_agent?: string;
29
33
  updated_at?: string;
30
34
  /** Recent conversations for the directory, most recent first. */
@@ -72,6 +76,7 @@ export interface AgySessionStore {
72
76
  signal?: AbortSignal,
73
77
  summary?: string,
74
78
  agent?: string,
79
+ rawModelId?: AgyModelId,
75
80
  ): Promise<void>;
76
81
  }
77
82
 
@@ -155,7 +160,8 @@ export function createSessionStore(
155
160
  (entry) =>
156
161
  entry &&
157
162
  typeof entry.conversation_id === "string" &&
158
- typeof entry.updated_at === "string",
163
+ typeof entry.updated_at === "string" &&
164
+ (entry.raw_model_id === undefined || isAgyModelId(entry.raw_model_id)),
159
165
  )
160
166
  .map((entry) => {
161
167
  const normalized: AgyConversationEntry = {
@@ -163,6 +169,7 @@ export function createSessionStore(
163
169
  updated_at: entry.updated_at,
164
170
  };
165
171
  if (typeof entry.model === "string") normalized.model = entry.model;
172
+ if (entry.raw_model_id !== undefined) normalized.raw_model_id = entry.raw_model_id;
166
173
  if (typeof entry.agent === "string") {
167
174
  const agent = entry.agent.trim();
168
175
  if (agent && agent.length <= 128 && !/[\x00-\x1f\x7f]/.test(agent)) {
@@ -255,7 +262,9 @@ export function createSessionStore(
255
262
  signal?: AbortSignal,
256
263
  summary?: string,
257
264
  agent?: string,
265
+ rawModelId?: AgyModelId,
258
266
  ): Promise<void> {
267
+ if (rawModelId !== undefined) validateAgyModelId(rawModelId);
259
268
  const operation = waitForMutation(signal).then(() =>
260
269
  withStoreLock(async () => {
261
270
  const store = await loadStore(signal);
@@ -265,10 +274,11 @@ export function createSessionStore(
265
274
  store[key] = {
266
275
  last_conversation_id: conversationId,
267
276
  last_model: model,
277
+ ...(rawModelId ? { last_raw_model_id: rawModelId } : {}),
268
278
  last_agent: agent,
269
279
  updated_at: updatedAt,
270
280
  history: [
271
- { conversation_id: conversationId, model, agent, updated_at: updatedAt, summary },
281
+ { conversation_id: conversationId, model, ...(rawModelId ? { raw_model_id: rawModelId } : {}), agent, updated_at: updatedAt, summary },
272
282
  ...(Array.isArray(record.history) ? record.history : []).filter(
273
283
  (entry) =>
274
284
  entry &&
@@ -307,6 +317,7 @@ export function saveSession(
307
317
  signal?: AbortSignal,
308
318
  summary?: string,
309
319
  agent?: string,
320
+ rawModelId?: AgyModelId,
310
321
  ): Promise<void> {
311
- return defaultStore.saveSession(dir, conversationId, model, signal, summary, agent);
322
+ return defaultStore.saveSession(dir, conversationId, model, signal, summary, agent, rawModelId);
312
323
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@juanbenjumea/pi-agy",
3
- "version": "0.7.12",
3
+ "version": "0.7.14",
4
4
  "description": "Antigravity (agy) provider and delegation for Pi — /model picker, background tasks, loopback MCP tool bridge, quota awareness, and repo verification.",
5
5
  "type": "module",
6
6
  "license": "MIT",