@juanbenjumea/pi-agy 0.7.14 → 0.7.16

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,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.16
4
+
5
+ - Derive `--effort` support from the catalog instead of a vendor pattern. The previous `/^gpt-oss-/` rule emitted exactly the argv agy rejects: `--model gpt-oss-120b-medium --effort high` fails with "conflicts with --effort=high", while `claude-opus-5-5` accepts the flag. A tier-qualified id now never receives `--effort`, and a base slug only receives a tier its catalog lists.
6
+ - Collapse every family with two or more effort tiers into one picker entry with a thinking-level toggle, rather than only `gemini-*` families. The catalog decides, so `claude-*` bases stop appearing as separate per-tier entries.
7
+ - Treat `xhigh` and `max` as effort tiers. `gemini-4-neon-xhigh` and `gemini-4-hydrogen-xhigh` previously did not match the tier suffix and appeared as standalone models instead of a fourth stop in their family's toggle.
8
+ - Offer `xhigh` and `max` through `agy_execute`'s `effort` parameter, matching `agy --effort`.
9
+ - Cache the last observed model roster so a cold process can answer `getModels()`; the bridge's `agy_model_catalog` tool reads the same cache instead of reporting an empty catalog when live discovery fails. Pi resolves `enabledModels` during startup, so an undiscovered provider reported `No models match pattern "antigravity/<id>"` for an existing model. The cache stores only ids `agy models` returned, is written atomically, and degrades to the previous empty start when unreadable.
10
+
11
+ ## 0.7.15
12
+
13
+ - Resolve every model alias against the live `agy models` catalog; no production path ships a model id, a per-family regex, or a fallback roster, so a renamed or new family needs no package update. An unresolvable alias now fails with the alias name, the exact recovery, and the discovered-catalog requirement instead of launching a stale id.
14
+ - Match aliases structurally (family, optional trailing tier) and let a family that ships no tier variants answer its tier aliases with its top id, so a flagship named without a tier still serves `pro`. A tier-aware family keeps failing loudly for a retired tier instead of substituting a neighbour, and `xhigh` counts as a tier.
15
+ - Report native provider usage: validate `agy` token counts, difference the cumulative `result.usage` of a persistent child so consecutive turns are not double-counted, and normalize to Pi's `Usage` shape (`cache_read` excluded from input, thinking reported as reasoning).
16
+ - Stream agy thinking into Pi's TUI as thinking blocks and deltas, separate from tool/step progress.
17
+ - Send only the new transcript delta to a resumed agy conversation instead of replaying the whole prompt.
18
+ - Deny agy's shadowed built-in tools through a session `--settings` document when the Pi bridge owns the same capability.
19
+ - Batch parallel bridged MCP tool calls inside a short window so Pi answers them in one turn instead of one turn per call. Live verification shows agy's tool loop is serial (two calls arrived across two sequential phases), so this window is insurance rather than observed traffic; the batching behaviour itself is covered by deterministic driver tests.
20
+ - Verify the deny document live: with `--dangerously-skip-permissions` in force, `permissions.deny` still blocks agy's built-in shell tool (`Permission denied ... Matches user-configured deny rule`), while an identical request without the document creates its file. Both controls are in `npm run test:bridge`.
21
+ - Add `npm run test:provider`, an opt-in two-turn live check that keeps one child alive across turns and
22
+ asserts native usage is reported per turn instead of cumulatively; verified against agy 1.5.13
23
+ (`input 10420 / total 10421`, then `input 2119 + cache_read 8376 / total 10496` on reuse).
24
+ - Full 510-test suite, typecheck, live smoke against an authenticated agy CLI, and package checks pass.
25
+
3
26
  ## 0.7.14
4
27
 
5
28
  - Keep model discovery off Pi's session-start critical path and load the MCP bridge only when needed.
package/README.md CHANGED
@@ -24,7 +24,7 @@ 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. 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:
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 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
@@ -34,11 +34,17 @@ The `/agy` command runs tasks from Pi's TUI and can also list agents, inspect qu
34
34
  /agy doctor
35
35
  ```
36
36
 
37
+ Aliases are resolved against the live catalog instead of a shipped table: an alias names a family and optionally a tier (`sonnet`, `flash-low`, `pro-high`), and it matches an id whose hyphen-separated tokens appear contiguously, with a tier only as the id's trailing tokens. A family that ships no tier variants at all answers its tier aliases with its top id, so a flagship named without a tier still serves `pro`. A tier the vendor retires stops resolving and fails with an actionable message rather than quietly substituting a neighbour; the executed concrete id is always reported in the run receipt.
38
+
37
39
  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.
38
40
 
39
41
  ## Use agy as a Pi model
40
42
 
41
- The package registers an `antigravity` provider. Select discovered models as `antigravity/<model>` in Pi's `/model` picker. Models refresh automatically from `agy models` at session startup and whenever Pi opens the model picker (Pi 1.5.2 native refresh). New model names need no package update. Failed discovery keeps the last good catalog, or the synchronous fallback before the first success; reopen `/model` after signing in to retry. Cache-only refreshes never run the CLI. Gemini thinking levels map to agy's supported effort tiers.
43
+ The package registers an `antigravity` provider. Select discovered models as `antigravity/<model>` in Pi's `/model` picker. Models refresh automatically from `agy models` at session startup and whenever Pi opens the model picker (Pi 1.5.2 native refresh). New model names need no package update. Failed discovery keeps the last good catalog; before the first successful discovery the picker is empty rather than a stale built-in list, and `/agy doctor` reports why. Reopen `/model` after signing in to retry. Cache-only refreshes never run the CLI.
44
+
45
+ The last observed roster is also cached in `agy-provider-models.json` next to `agy-config.json`. That file holds only ids `agy models` actually returned, and it exists because Pi resolves configured model scopes at startup: without it, a configured `antigravity/<id>` reports `No models match pattern` for a model that plainly exists, since the provider simply had not discovered anything yet.
46
+
47
+ A family that ships several effort tiers appears as one picker entry with a thinking-level toggle, including `xhigh` and `max` where agy offers them, and `--effort` carries the chosen tier. Families with a single tier, or none, keep agy's exact qualified id and never receive `--effort` — agy rejects that combination as a conflict.
42
48
 
43
49
  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.
44
50
 
@@ -73,10 +79,16 @@ Development tests are qualified against the exact Pi SDK fixture version 1.5.2,
73
79
  ```bash
74
80
  npm test
75
81
  npm run typecheck
82
+ npm run test:live # read-only, no inference
83
+ npm run test:bridge # billable: deny-rule and park-path evidence
76
84
  ```
77
85
 
78
86
  With an installed agy CLI, `npm run test:live` runs read-only integration checks without starting an inference turn.
79
87
 
88
+ `npm run test:bridge` covers the two behaviours that need a real child on the loopback bridge: that the `--settings` deny document actually stops agy's built-in shell tool (proven with a positive control, so a passing run cannot be the model declining to act), and how many bridged calls a single turn produces. Note that agy's tool loop is serial — it issues one call, waits, then issues the next — so the park micro-batch never sees concurrent calls in practice and stays covered by deterministic driver tests instead.
89
+
90
+ `npm run test:provider` is the one deliberately billable check: it spends two short turns on a budget alias of your choosing (`npm run test:provider -- <model-id>`), keeps the child alive between them, and asserts streamed text, the conversation id, native usage, and that a reused process reports the second turn as a delta rather than the session's cumulative counters. It runs without agy's permission bypass, so a tool call would be escalated rather than silently executed.
91
+
80
92
  ## License
81
93
 
82
94
  MIT
@@ -28,6 +28,10 @@ import {
28
28
  toProviderModelDef,
29
29
  type AgyProviderModelEntry,
30
30
  } from "./lib/provider-models.js";
31
+ import {
32
+ loadProviderCatalogCache,
33
+ saveProviderCatalogCache,
34
+ } from "./lib/provider-catalog-store.js";
31
35
  import { runPreflightCommand } from "./lib/spawn.js";
32
36
 
33
37
  export { truncate } from "./lib/output.js";
@@ -45,10 +49,28 @@ export { truncate } from "./lib/output.js";
45
49
  function registerAgyProvider(pi: ExtensionAPI): void {
46
50
  if (typeof pi.registerProvider !== "function") return;
47
51
  // Keep one handler and catalog array for conversation/driver continuity.
48
- // Only a generation-checked publication may mutate these entries.
49
- const entries: AgyProviderModelEntry[] = [...FALLBACK_PROVIDER_MODELS];
52
+ // Only a generation-checked publication may mutate these entries. Start from
53
+ // the last roster this machine actually observed: Pi resolves configured
54
+ // model scopes during startup, and an empty catalog there reports a real
55
+ // model as "No models match pattern" before discovery can answer.
56
+ const cached = loadProviderCatalogCache();
57
+ const entries: AgyProviderModelEntry[] = [
58
+ ...(cached.length > 0 ? cached : FALLBACK_PROVIDER_MODELS),
59
+ ];
50
60
  const shutdown = new AbortController();
51
- pi.on?.("session_shutdown", () => { shutdown.abort(); });
61
+ let activeUi: { setStatus?: (key: string, text: string | undefined) => void } | undefined;
62
+ const setLiveStatus = (label: string | undefined): void => {
63
+ try {
64
+ activeUi?.setStatus?.(AGY_PROVIDER_ID, label);
65
+ } catch {
66
+ // Status updates are best effort and must never disrupt a turn.
67
+ }
68
+ };
69
+ pi.on?.("session_shutdown", () => {
70
+ setLiveStatus(undefined);
71
+ activeUi = undefined;
72
+ shutdown.abort();
73
+ });
52
74
  const streamSimple = createAgyStreamSimple(
53
75
  {
54
76
  createStream: () => {
@@ -65,7 +87,7 @@ function registerAgyProvider(pi: ExtensionAPI): void {
65
87
  getSystemPrompt: (messages) =>
66
88
  getCurrentSystemPrompt(messages as unknown as Parameters<typeof getCurrentSystemPrompt>[0]),
67
89
  },
68
- { entries },
90
+ { entries, onActivity: setLiveStatus },
69
91
  );
70
92
  const baseUrl = "agy-provider://antigravity";
71
93
  const modelDefinitions = (catalog: readonly AgyProviderModelEntry[]): Model<any>[] =>
@@ -106,7 +128,12 @@ function registerAgyProvider(pi: ExtensionAPI): void {
106
128
  signal.throwIfAborted();
107
129
  const live = parseProviderCatalog(raw);
108
130
  if (live.length === 0) throw new Error("agy models returned no usable models");
109
- if (areProviderCatalogsEqual(entries, live)) return;
131
+ if (areProviderCatalogsEqual(entries, live)) {
132
+ // Same roster, possibly only now confirmed on disk (first run after an
133
+ // older version, or a cache cleared by hand).
134
+ saveProviderCatalogCache(live);
135
+ return;
136
+ }
110
137
  const definitions = modelDefinitions(live);
111
138
  await context.publish({
112
139
  update: () => {
@@ -117,6 +144,7 @@ function registerAgyProvider(pi: ExtensionAPI): void {
117
144
  models = definitions;
118
145
  },
119
146
  });
147
+ saveProviderCatalogCache(live);
120
148
  },
121
149
  stream: (model, context, options) => stream(model, context, options as SimpleStreamOptions),
122
150
  streamSimple: stream,
@@ -129,6 +157,9 @@ function registerAgyProvider(pi: ExtensionAPI): void {
129
157
  return;
130
158
  }
131
159
  pi.on?.("session_start", (_event, ctx) => {
160
+ if (ctx.hasUI && typeof ctx.ui?.setStatus === "function") {
161
+ activeUi = ctx.ui;
162
+ }
132
163
  const signal = AbortSignal.any([shutdown.signal, AbortSignal.timeout(10_000)]);
133
164
  // Keep provider discovery off Pi's session-start critical path. The model
134
165
  // picker also refreshes on demand, so startup can use the cached catalog.
@@ -8,8 +8,13 @@
8
8
 
9
9
  import { validateModelSelector } from "./model-selection.js";
10
10
 
11
- import { getModelCatalog, normalizeAgyAgentName } from "./inspect.js";
12
- import type { AgyModel, AgyOptions } from "./cli.js";
11
+ import {
12
+ effortTiersForModelId,
13
+ getModelCatalog,
14
+ namesEffortTierInId,
15
+ normalizeAgyAgentName,
16
+ } from "./inspect.js";
17
+ import type { AgyEffort, AgyModel, AgyOptions } from "./cli.js";
13
18
 
14
19
  // agy >= 1.1.28 returns partial output with exit 0 when its own print timeout
15
20
  // fires. Keep that timeout behind Pi's hard parent deadline (and its 2s kill
@@ -20,18 +25,11 @@ const PRINT_TIMEOUT_BUFFER_MS = 5_000;
20
25
  // unbucketed value it replaces (Pi's hard kill still governs the run).
21
26
  const PRINT_TIMEOUT_BUCKET_S = 30;
22
27
 
23
- // Static fallback for when `agy models` output is unavailable. The live
24
- // catalog (updated during preflight) overrides these per alias.
25
- const MODEL_MAP: Record<AgyModel, string> = {
26
- "flash-low": "gemini-3.8-flash-low",
27
- "flash-medium": "gemini-3.8-flash-medium",
28
- "flash-high": "gemini-3.8-flash-high",
29
- "pro-low": "gemini-3.1-pro-low",
30
- "pro-high": "gemini-3.1-pro-high",
31
- sonnet: "claude-sonnet-4-6",
32
- opus: "claude-opus-4-6-thinking",
33
- "gpt-oss": "gpt-oss-120b-medium",
34
- };
28
+ /**
29
+ * Alias selected when the caller names nothing. Deliberately an alias: a
30
+ * concrete id here would be a hardcoded model name that goes stale silently.
31
+ */
32
+ const DEFAULT_MODEL_ALIAS: AgyModel = "flash-medium";
35
33
 
36
34
  const TIER_MAP: Record<NonNullable<AgyOptions["tier"]>, AgyModel> = {
37
35
  flash: "flash-high",
@@ -47,19 +45,55 @@ export function resolveAgyModelAlias(
47
45
  return model ?? (tier ? TIER_MAP[tier] : undefined);
48
46
  }
49
47
 
50
- /** Resolve a model alias to a concrete agy model id, preferring the live catalog. */
51
- export function resolveAgyModelId(model?: AgyModel, tier?: AgyOptions["tier"]): string {
52
- const alias = resolveAgyModelAlias(model, tier) ?? "flash-medium";
53
- return getModelCatalog()[alias] ?? MODEL_MAP[alias];
48
+ /**
49
+ * Resolve a model alias to a concrete agy model id from the live catalog.
50
+ *
51
+ * Returns `undefined` when the catalog was never observed or the vendor no
52
+ * longer ships a matching id. No id is ever invented: a fabricated fallback
53
+ * turns a retired tier into a runtime failure far from its cause.
54
+ */
55
+ export function resolveAgyModelId(model?: AgyModel, tier?: AgyOptions["tier"]): string | undefined {
56
+ const alias = resolveAgyModelAlias(model, tier) ?? DEFAULT_MODEL_ALIAS;
57
+ return getModelCatalog()[alias];
58
+ }
59
+
60
+ /**
61
+ * Same resolution for argv and prompt paths, where an absent id is fatal.
62
+ * The message names the alias and the exact recovery, so a stale catalog is
63
+ * never mistaken for a bad request.
64
+ */
65
+ export function requireAgyModelId(model?: AgyModel, tier?: AgyOptions["tier"]): string {
66
+ const alias = resolveAgyModelAlias(model, tier) ?? DEFAULT_MODEL_ALIAS;
67
+ const id = resolveAgyModelId(model, tier);
68
+ if (id) return id;
69
+ throw new Error(
70
+ `agy model alias "${alias}" matches nothing in the current catalog; run \`agy models\` (sign in if needed) or pass model=<exact id>`,
71
+ );
72
+ }
73
+
74
+ /**
75
+ * Effort capability is a catalog fact, never a vendor-name rule.
76
+ *
77
+ * agy rejects `--effort` for a tier-qualified id ("--model …-medium conflicts
78
+ * with --effort=high") and for a family that ships no tiers ("--effort is not
79
+ * supported"), and accepts it for a base slug whose catalog lists the tier
80
+ * asked for. The `/^gpt-oss-/` rule this replaces was wrong in exactly the
81
+ * observed way: `gpt-oss-120b-medium` conflicts, while `claude-opus-5-5`
82
+ * accepts `--effort`. Verified against agy 1.5.13.
83
+ */
84
+ export function supportsAgyEffortId(id: string, effort?: AgyEffort): boolean {
85
+ const tiers = effortTiersForModelId(id);
86
+ if (tiers.length === 0) return false;
87
+ return effort === undefined || tiers.includes(effort);
54
88
  }
55
89
 
56
90
  /**
57
- * Gemini aliases already select a low/medium/high model variant. Claude's
58
- * thinking models also reject --effort; keep the flag for model families that
59
- * expose it without turning a valid tool call into an argument error.
91
+ * Tier-suffixed aliases already select a low/medium/high variant, so an alias
92
+ * asking for effort of its own has nothing to add.
60
93
  */
61
94
  export function supportsAgyEffort(model?: AgyModel, tier?: AgyOptions["tier"]): boolean {
62
- return resolveAgyModelId(model, tier).startsWith("gpt-oss-");
95
+ const id = resolveAgyModelId(model, tier);
96
+ return id !== undefined && supportsAgyEffortId(id);
63
97
  }
64
98
 
65
99
  export function buildAgyArgs(options: AgyOptions): string[] {
@@ -68,7 +102,7 @@ export function buildAgyArgs(options: AgyOptions): string[] {
68
102
  }
69
103
 
70
104
  validateModelSelector(options);
71
- const model = options.model_id ?? resolveAgyModelId(options.model, options.tier);
105
+ const model = options.model_id ?? requireAgyModelId(options.model, options.tier);
72
106
  const agent = normalizeAgyAgentName(options.agent);
73
107
  const unbucketedSec = Math.ceil((options.timeout_ms + PRINT_TIMEOUT_BUFFER_MS) / 1000);
74
108
  const timeoutSec = Math.ceil(unbucketedSec / PRINT_TIMEOUT_BUCKET_S) * PRINT_TIMEOUT_BUCKET_S;
@@ -77,6 +111,14 @@ export function buildAgyArgs(options: AgyOptions): string[] {
77
111
  const skipPermissions = options.skipPermissions ?? true;
78
112
  const useStream = options.stream ?? true;
79
113
  const structured = mode !== "accept-edits" || useStream;
114
+ // An exact id only needs the one check agy reports on its own terms (`--model
115
+ // …-medium conflicts with --effort`): it names its tier, so no effort can be
116
+ // layered on. Catalog coverage is unnecessary there, and an unsupported tier
117
+ // is left to agy's precise "available: …" error. An alias resolves through
118
+ // the catalog and may only send a tier that catalog offers.
119
+ const effortCapable = options.model_id
120
+ ? !namesEffortTierInId(options.model_id)
121
+ : supportsAgyEffort(options.model, options.tier);
80
122
 
81
123
  const args = [
82
124
  "--model",
@@ -89,9 +131,7 @@ export function buildAgyArgs(options: AgyOptions): string[] {
89
131
  "--disable-slash-commands",
90
132
  ...(mode === "sandbox" ? ["--sandbox"] : ["--mode", mode]),
91
133
  ...(writes && skipPermissions ? ["--dangerously-skip-permissions"] : []),
92
- ...(options.effort && (options.model_id ? options.model_id.startsWith("gpt-oss-") : supportsAgyEffort(options.model, options.tier))
93
- ? ["--effort", options.effort]
94
- : []),
134
+ ...(options.effort && effortCapable ? ["--effort", options.effort] : []),
95
135
  ...(agent ? ["--agent", agent] : []),
96
136
  ];
97
137
 
@@ -19,7 +19,8 @@ export function isAgyModel(value: unknown): value is AgyModel {
19
19
  return typeof value === "string" && (AGY_MODEL_ALIASES as readonly string[]).includes(value);
20
20
  }
21
21
 
22
- export type AgyEffort = "low" | "medium" | "high";
22
+ /** Reasoning-effort values `agy --effort` documents. */
23
+ export type AgyEffort = "low" | "medium" | "high" | "xhigh" | "max";
23
24
 
24
25
  export type { AgyQuotaEntry, AgyUsageSnapshot } from "./usage.js";
25
26
 
@@ -42,11 +43,14 @@ export {
42
43
  checkAgyConnectivity,
43
44
  checkAgyHealth,
44
45
  checkAgyUsage,
46
+ effortTiersForModelId,
45
47
  getModelCatalog,
46
48
  inspectAgyAgents,
49
+ inspectAgyModelIds,
47
50
  inspectAgyModels,
48
51
  inspectAgyVersion,
49
52
  isStableModelId,
53
+ namesEffortTierInId,
50
54
  normalizeAgyAgentName,
51
55
  parseAgyAgents,
52
56
  parseModelCatalog,
@@ -57,9 +61,11 @@ export { isTransientAgyFailure } from "./retry.js";
57
61
  export {
58
62
  buildAgyArgs,
59
63
  buildAgyPrompt,
64
+ requireAgyModelId,
60
65
  resolveAgyModelAlias,
61
66
  resolveAgyModelId,
62
67
  supportsAgyEffort,
68
+ supportsAgyEffortId,
63
69
  } from "./args.js";
64
70
 
65
71
  export { findAgyQuotaEntries, formatAgyUsage, isAgyQuotaExhausted, parseAgyUsage } from "./usage.js";
@@ -11,6 +11,7 @@ import {
11
11
  isAgyQuotaExhausted,
12
12
  isTransientAgyFailure,
13
13
  normalizeAgyAgentName,
14
+ requireAgyModelId,
14
15
  resolveAgyModelAlias,
15
16
  resolveAgyModelId,
16
17
  spawnAgyStream,
@@ -177,7 +178,7 @@ export async function executeAgyTask(
177
178
  const run = await runWithTransientRetry(async (trackProgress) => {
178
179
  const remainingMs = remainingBudget(startedAt, options.timeout_ms);
179
180
  quota = await runPreflight(options.dir, abortSignal, remainingMs);
180
- const selectedModelId = options.model_id ?? resolveAgyModelId(model, options.tier);
181
+ const selectedModelId = options.model_id ?? requireAgyModelId(model, options.tier);
181
182
  const selectedQuotas = findAgyQuotaEntries(quota, selectedModelId);
182
183
  quotaStatus = quota
183
184
  ? selectedQuotas.length === 0
@@ -192,7 +193,7 @@ export async function executeAgyTask(
192
193
  : undefined;
193
194
  if (fallback) {
194
195
  onProgress?.(
195
- `agy: ${selectedModelId} quota exhausted; falling back to ${resolveAgyModelId(fallback)}…`,
196
+ `agy: ${selectedModelId} quota exhausted; falling back to ${resolveAgyModelId(fallback) ?? fallback}…`,
196
197
  );
197
198
  model = fallback;
198
199
  effectiveModel = fallback;
@@ -387,7 +388,10 @@ function findAvailableFallbackModel(
387
388
  if (!snapshot) return undefined;
388
389
  return FALLBACK_MODELS.find((candidate) => {
389
390
  if (candidate === current) return false;
390
- const entries = findAgyQuotaEntries(snapshot, resolveAgyModelId(candidate));
391
+ // An alias with no catalog match cannot be run, so it cannot be the fallback.
392
+ const id = resolveAgyModelId(candidate);
393
+ if (!id) return false;
394
+ const entries = findAgyQuotaEntries(snapshot, id);
391
395
  return entries.length > 0 && entries.every((entry) => !isAgyQuotaExhausted(entry));
392
396
  });
393
397
  }
@@ -10,20 +10,121 @@ import { parseAgyModelIds, type AgyModelId } from "./provider-models.js";
10
10
  import { compareModelIds } from "./model-sort.js";
11
11
  import { runPreflightCommand } from "./spawn.js";
12
12
  import { parseAgyUsage, usageError, type AgyUsageSnapshot } from "./usage.js";
13
- import type { AgyModel } from "./cli.js";
14
-
15
- /** alias → pattern matching concrete model ids in `agy models` output. */
16
- const UNSTABLE_SUFFIX = "(?:-(?:preview|experimental|beta|alpha|rc\\d*|snapshot|next))*";
17
- const CATALOG_PATTERNS: Record<AgyModel, RegExp> = {
18
- "flash-low": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-low${UNSTABLE_SUFFIX}$`),
19
- "flash-medium": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-medium${UNSTABLE_SUFFIX}$`),
20
- "flash-high": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-high${UNSTABLE_SUFFIX}$`),
21
- "pro-low": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-pro-low${UNSTABLE_SUFFIX}$`),
22
- "pro-high": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-pro-high${UNSTABLE_SUFFIX}$`),
23
- sonnet: /^claude-sonnet-[\w.-]+$/,
24
- opus: /^claude-opus-[\w.-]+$/,
25
- "gpt-oss": /^gpt-oss-[\w.-]+$/,
26
- };
13
+ import { AGY_MODEL_ALIASES, type AgyModel } from "./cli.js";
14
+
15
+ /**
16
+ * Alias matching is structural, never a literal model name.
17
+ *
18
+ * An alias is `family` or `family-<effort>` (see `AGY_MODEL_ALIASES`). It
19
+ * matches an `agy models` id when the alias's hyphen-separated tokens appear
20
+ * contiguously in the id — and, for an effort alias, only as the id's trailing
21
+ * tokens. `…-flash-low` therefore matches `flash-low` but not `flash-medium`,
22
+ * and a tier the vendor retires stops matching instead of resolving to an
23
+ * invented id. New families and renames resolve with no code change.
24
+ */
25
+ const EFFORT_TOKENS: readonly string[] = ["low", "medium", "high", "xhigh", "max"];
26
+
27
+ /**
28
+ * Release-channel qualifiers that may trail an id (`…-flash-medium-preview`).
29
+ * Structural, not model-specific: these describe maturity, not a family, and
30
+ * stripping them lets a preview catalog resolve while `isStableModelId` still
31
+ * keeps such ids out of the default catalog.
32
+ */
33
+ const QUALIFIER_TOKENS: readonly string[] = ["preview", "experimental", "beta", "alpha", "snapshot", "next"];
34
+
35
+ export type AgyModelAliasMatcher = (alias: AgyModel, id: string) => boolean;
36
+
37
+ function findTokenRun(haystack: readonly string[], needle: readonly string[]): number {
38
+ if (needle.length === 0 || needle.length > haystack.length) return -1;
39
+ const last = haystack.length - needle.length;
40
+ for (let start = 0; start <= last; start++) {
41
+ let matched = true;
42
+ for (let offset = 0; offset < needle.length; offset++) {
43
+ if (haystack[start + offset] !== needle[offset]) {
44
+ matched = false;
45
+ break;
46
+ }
47
+ }
48
+ if (matched) return start;
49
+ }
50
+ return -1;
51
+ }
52
+
53
+ function aliasTokens(alias: string): string[] {
54
+ return alias.toLowerCase().split("-").filter(Boolean);
55
+ }
56
+
57
+ /** Class tokens of an effort alias (`flash-low` -> `flash`), else undefined. */
58
+ function classTokensOf(alias: string): string[] | undefined {
59
+ const tokens = aliasTokens(alias);
60
+ if (tokens.length < 2) return undefined;
61
+ if (!EFFORT_TOKENS.includes(tokens[tokens.length - 1])) return undefined;
62
+ return tokens.slice(0, -1);
63
+ }
64
+
65
+ /** Does this catalog id satisfy the alias? Pure token comparison. */
66
+ export function aliasMatchesModelId(alias: string, id: string): boolean {
67
+ const tokens = aliasTokens(alias);
68
+ const idTokens = id.toLowerCase().split("-").filter(Boolean);
69
+ if (tokens.length === 0) return false;
70
+ const namesEffort = EFFORT_TOKENS.includes(tokens[tokens.length - 1]);
71
+ const start = findTokenRun(idTokens, tokens);
72
+ if (start === -1) return false;
73
+ if (!namesEffort) return true;
74
+ // An effort alias pins the tier: only release-channel qualifiers may follow,
75
+ // so `…-flash-medium-preview` is still flash-medium and `…-flash-medium-x` is not.
76
+ const trailing = idTokens.slice(start + tokens.length);
77
+ return trailing.every((token) => QUALIFIER_TOKENS.includes(token));
78
+ }
79
+
80
+ /**
81
+ * Class-level match used only when a family ships no effort variants at all.
82
+ *
83
+ * Vendors do move effort out of the id: a `…-pro-orchestrator-neon` flagship
84
+ * carries no tier token, so every `pro-*` alias would stop resolving and a
85
+ * legacy `tier: "pro"` would fail for a model that plainly exists. Such a
86
+ * family answers its tier aliases with its top id instead. A family that does
87
+ * ship variants never reaches this path, so a retired tier still fails loudly
88
+ * rather than silently upgrading.
89
+ */
90
+ function classMatchesModelId(classTokens: readonly string[], id: string): boolean {
91
+ const idTokens = id.toLowerCase().split("-").filter(Boolean);
92
+ return findTokenRun(idTokens, classTokens) !== -1;
93
+ }
94
+
95
+ /** Does this concrete id already name its tier (`…-flash-low`)? */
96
+ export function namesEffortTierInId(id: string): boolean {
97
+ const idTokens = id.toLowerCase().split("-").filter(Boolean);
98
+ return idTokens.length > 0 && EFFORT_TOKENS.includes(idTokens[idTokens.length - 1]!);
99
+ }
100
+
101
+ /**
102
+ * Effort tiers agy accepts on a base slug, derived from the live catalog.
103
+ *
104
+ * agy's own error text defines the rule: `--effort T` is accepted for a base
105
+ * `B` exactly when the catalog carries `B-T` ("has no \"high\" effort
106
+ * (available: low, medium, high)"), is a **conflict** for a tier-qualified id
107
+ * ("--model …-medium conflicts with --effort=high"), and is **unsupported**
108
+ * for a family that ships no tiers. A tier-qualified id therefore answers
109
+ * with no tiers at all, and no vendor name is consulted. Verified against
110
+ * agy 1.5.13.
111
+ */
112
+ export function effortTiersForModelId(
113
+ baseId: string,
114
+ ids: readonly string[] = Object.values(modelCatalog),
115
+ ): string[] {
116
+ if (namesEffortTierInId(baseId)) return [];
117
+ const prefix = `${baseId}-`;
118
+ const tiers = new Set<string>();
119
+ for (const id of ids) {
120
+ if (!id.startsWith(prefix)) continue;
121
+ const suffix = id.slice(prefix.length).toLowerCase();
122
+ if (EFFORT_TOKENS.includes(suffix)) tiers.add(suffix);
123
+ }
124
+ return [...tiers].sort(
125
+ (left, right) => EFFORT_TOKENS.indexOf(left) - EFFORT_TOKENS.indexOf(right),
126
+ );
127
+ }
27
128
 
28
129
  export type AgyModelCatalog = Partial<Record<AgyModel, string>>;
29
130
 
@@ -44,17 +145,40 @@ export function isStableModelId(id: string): boolean {
44
145
  */
45
146
  export function parseModelCatalog(output: string, allowPreview = false): AgyModelCatalog {
46
147
  const allow = allowPreview || process.env.PI_AGY_ALLOW_PREVIEW === "1";
47
- const found: AgyModelCatalog = {};
148
+ const ids: string[] = [];
48
149
  for (const line of output.split("\n")) {
49
150
  const id = line.trim().split(/\s+/)[0] ?? "";
50
151
  if (!id) continue;
51
152
  if (!allow && !isStableModelId(id)) continue;
52
- for (const [alias, pattern] of Object.entries(CATALOG_PATTERNS) as Array<[AgyModel, RegExp]>) {
53
- if (pattern.test(id) && compareModelIds(id, found[alias] ?? "") > 0) {
153
+ ids.push(id);
154
+ }
155
+
156
+ const found: AgyModelCatalog = {};
157
+ const unanswered: AgyModel[] = [];
158
+ for (const alias of AGY_MODEL_ALIASES) {
159
+ for (const id of ids) {
160
+ // A catalog line that is just the alias name is the CLI's own shortcut,
161
+ // not a concrete model: letting it win would shadow the real family id.
162
+ if (id === alias) continue;
163
+ if (aliasMatchesModelId(alias, id) && compareModelIds(id, found[alias] ?? "") > 0) {
54
164
  found[alias] = id;
55
165
  }
56
166
  }
167
+ if (found[alias] === undefined) unanswered.push(alias);
57
168
  }
169
+
170
+ for (const alias of unanswered) {
171
+ const classTokens = classTokensOf(alias);
172
+ if (!classTokens) continue;
173
+ const candidates = ids.filter((id) => classMatchesModelId(classTokens, id));
174
+ // A class that ships any effort variant is tier-aware: its aliases must
175
+ // match the requested tier or fail, never fall back to another tier.
176
+ if (candidates.length === 0 || candidates.some(namesEffortTierInId)) continue;
177
+ for (const id of candidates) {
178
+ if (compareModelIds(id, found[alias] ?? "") > 0) found[alias] = id;
179
+ }
180
+ }
181
+
58
182
  return found;
59
183
  }
60
184
 
@@ -5,16 +5,24 @@
5
5
  * catalog state, so it can be tested and reasoned about in isolation.
6
6
  */
7
7
 
8
+ /**
9
+ * Dotted version segment following the leading family token, e.g.
10
+ * `acme-3.8-thing` -> `3.8`. Family-agnostic on purpose: naming one vendor
11
+ * here would freeze ordering to that vendor's id shape.
12
+ */
13
+ const DOTTED_VERSION_RE = /^[a-z][a-z0-9]*-(\d+(?:\.\d+)+)/i;
14
+
8
15
  /**
9
16
  * Order model ids so the newest-looking id wins catalog resolution.
10
17
  * Returns a negative/zero/positive number like `Array.prototype.sort` expects.
11
18
  */
12
19
  export function compareModelIds(a: string, b: string): number {
13
20
  if (!b) return 1;
14
- const versionA = /^gemini-(\d+(?:\.\d+)*)-/.exec(a)?.[1];
15
- const versionB = /^gemini-(\d+(?:\.\d+)*)-/.exec(b)?.[1];
21
+ const versionA = DOTTED_VERSION_RE.exec(a)?.[1];
22
+ const versionB = DOTTED_VERSION_RE.exec(b)?.[1];
16
23
  if (versionA && versionB) return compareDottedVersions(versionA, versionB);
17
- // Numeric-aware compare so claude-sonnet-4-10 sorts above claude-sonnet-4-6.
24
+ // Numeric-aware compare so `x-4-10` sorts above `x-4-6` and a dotted id
25
+ // still outranks a hyphenated lower generation.
18
26
  return compareNatural(a, b);
19
27
  }
20
28