@juanbenjumea/pi-agy 0.6.11 → 0.7.1

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.
@@ -0,0 +1,101 @@
1
+ /**
2
+ * `/agy` command-line argument parsing.
3
+ *
4
+ * Split out of `extensions/commands.ts`: pure tokenizer with no pi APIs, so
5
+ * the grammar is testable without a TUI harness. `commands.ts` re-exports the
6
+ * parser for its existing test importers.
7
+ */
8
+
9
+ import { normalizeAgyAgentName, type AgyModel } from "./cli.js";
10
+ import type { AgyContextMode } from "./context.js";
11
+
12
+ export const MODEL_ALIASES: Record<string, AgyModel> = {
13
+ flash: "flash-medium",
14
+ "flash-low": "flash-low",
15
+ "flash-medium": "flash-medium",
16
+ "flash-high": "flash-high",
17
+ pro: "pro-high",
18
+ "pro-low": "pro-low",
19
+ "pro-high": "pro-high",
20
+ sonnet: "sonnet",
21
+ opus: "opus",
22
+ "gpt-oss": "gpt-oss",
23
+ };
24
+
25
+ export const MODEL_KEYS = Object.keys(MODEL_ALIASES);
26
+
27
+ export const MODE_KEYS = ["accept-edits", "plan", "sandbox"] as const;
28
+
29
+ export const DEFAULT_TIMEOUT_MS = 300_000;
30
+ export const MAX_TIMEOUT_MS = 600_000;
31
+
32
+ export interface AgyCommandArgs {
33
+ mode?: "plan" | "accept-edits" | "sandbox";
34
+ model?: AgyModel;
35
+ agent?: string;
36
+ prompt?: string;
37
+ continue?: boolean;
38
+ timeout_ms?: number;
39
+ context?: AgyContextMode;
40
+ error?: string;
41
+ }
42
+
43
+ /**
44
+ * Parse `/agy [mode] [model] [agent=name] [continue] [timeout=10m] <prompt>` — leading
45
+ * option tokens are consumed in any order; the remainder is the prompt.
46
+ */
47
+ export function parseAgyCommandArgs(args: string): AgyCommandArgs {
48
+ let rest = args.trim();
49
+ const parsed: AgyCommandArgs = {};
50
+
51
+ while (rest) {
52
+ const token = readToken(rest);
53
+ if (!token) break;
54
+ const value = token.value.toLowerCase();
55
+
56
+ const timeout = parseTimeoutToken(token.value);
57
+ if (MODE_KEYS.includes(value as (typeof MODE_KEYS)[number])) {
58
+ parsed.mode = value as AgyCommandArgs["mode"];
59
+ } else if (MODEL_ALIASES[value]) {
60
+ parsed.model = MODEL_ALIASES[value];
61
+ } else if (value === "continue") {
62
+ parsed.continue = true;
63
+ } else if (value.startsWith("agent=")) {
64
+ try {
65
+ parsed.agent = normalizeAgyAgentName(token.value.slice("agent=".length));
66
+ } catch (error) {
67
+ parsed.error = error instanceof Error ? error.message : String(error);
68
+ }
69
+ } else if (value.startsWith("context=")) {
70
+ const context = value.slice("context=".length);
71
+ if (context === "none" || context === "summary" || context === "recent") {
72
+ parsed.context = context;
73
+ } else {
74
+ parsed.error = `unknown context mode '${context || "(empty)"}'`;
75
+ }
76
+ } else if (timeout !== undefined) {
77
+ parsed.timeout_ms = timeout;
78
+ } else {
79
+ break;
80
+ }
81
+ rest = rest.slice(token.end).trimStart();
82
+ }
83
+
84
+ if (rest) parsed.prompt = rest;
85
+ return parsed;
86
+ }
87
+
88
+ /** `timeout=10m`, `timeout=90s`, `timeout=1500ms`; a bare number means minutes. */
89
+ function parseTimeoutToken(token: string): number | undefined {
90
+ const match = /^timeout=(\d+(?:\.\d+)?)(ms|s|m)?$/i.exec(token);
91
+ if (!match) return undefined;
92
+ const amount = Number.parseFloat(match[1]);
93
+ const unit = (match[2] ?? "m").toLowerCase();
94
+ const ms = unit === "ms" ? amount : unit === "s" ? amount * 1_000 : amount * 60_000;
95
+ return Math.min(Math.max(Math.round(ms), 1_000), MAX_TIMEOUT_MS);
96
+ }
97
+
98
+ function readToken(value: string): { value: string; end: number } | undefined {
99
+ const match = /^\S+/.exec(value);
100
+ return match ? { value: match[0], end: match[0].length } : undefined;
101
+ }
@@ -1,5 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
- import { readFile } from "node:fs/promises";
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { promisify } from "node:util";
@@ -47,6 +47,12 @@ export interface AgyConfig {
47
47
  * command you control — the config file is user-owned.
48
48
  */
49
49
  defaultModelCommand?: string;
50
+ /**
51
+ * Expose Pi-side read-only context (sessions, quota, model catalog) to
52
+ * provider agy turns over a localhost MCP bridge injected via an extra
53
+ * `--add-dir`. Default `true`. Set `false` to run provider turns plain.
54
+ */
55
+ providerBridge?: boolean;
50
56
  }
51
57
 
52
58
  export function getDefaultConfigPath(): string {
@@ -79,6 +85,12 @@ export async function loadAgyConfig(
79
85
  // A malformed permission setting must never silently enable bypasses.
80
86
  config.skipPermissions = false;
81
87
  }
88
+ if (typeof record.providerBridge === "boolean") {
89
+ config.providerBridge = record.providerBridge;
90
+ } else if ("providerBridge" in record) {
91
+ // A malformed bridge setting must never silently open new surface.
92
+ config.providerBridge = false;
93
+ }
82
94
  return config;
83
95
  }
84
96
  } catch {
@@ -87,6 +99,29 @@ export async function loadAgyConfig(
87
99
  return {};
88
100
  }
89
101
 
102
+ /**
103
+ * Persist config overrides, preserving unknown keys. Malformed existing
104
+ * files are replaced (the caller just made an explicit choice).
105
+ */
106
+ export async function saveAgyConfig(
107
+ patch: Partial<AgyConfig>,
108
+ configPath = getDefaultConfigPath(),
109
+ ): Promise<void> {
110
+ let base: Record<string, unknown> = {};
111
+ try {
112
+ const parsed: unknown = JSON.parse(await readFile(configPath, { encoding: "utf8" }));
113
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
114
+ base = parsed as Record<string, unknown>;
115
+ }
116
+ } catch {
117
+ // Missing or corrupt: start fresh with the patch.
118
+ }
119
+ await mkdir(path.dirname(configPath), { recursive: true });
120
+ await writeFile(configPath, JSON.stringify({ ...base, ...patch }, null, 2) + "\n", {
121
+ encoding: "utf8",
122
+ });
123
+ }
124
+
90
125
  const cachedCommandAliases = new Map<string, { at: number; alias?: AgyModel }>();
91
126
 
92
127
  /**
@@ -0,0 +1,43 @@
1
+ /**
2
+ * accept-edits confirmation dialog text.
3
+ *
4
+ * Shared by the `/agy` command (commands.ts) and the `agy_execute` tool
5
+ * (index.ts): one pre-run summary builder so the two approval paths can never
6
+ * drift apart. Pure text — callers fetch `dirt` and pass everything in.
7
+ */
8
+
9
+ export interface AcceptEditsConfirmInput {
10
+ /** Pre-rendered model line, e.g. `flash-medium (gemini-3.8-flash-medium)`. */
11
+ modelLabel: string;
12
+ agent?: string;
13
+ cwd: string;
14
+ prompt: string;
15
+ contextMode: string;
16
+ contextText?: string;
17
+ /** Pre-run workspace dirt, or null when the check was skipped or failed. */
18
+ dirt: string | null;
19
+ }
20
+
21
+ export function buildAcceptEditsConfirm(input: AcceptEditsConfirmInput): {
22
+ title: string;
23
+ body: string;
24
+ } {
25
+ const { modelLabel, agent, cwd, prompt, contextMode, contextText, dirt } = input;
26
+ const dirtLine = dirt ? `\nworkspace: ${dirt}` : "";
27
+ const agentLine = agent ? `\nagent: ${agent}` : "";
28
+ const contextLine =
29
+ contextMode === "none"
30
+ ? "\ncontext: none"
31
+ : contextText
32
+ ? `\ncontext: ${contextMode} (${contextText.length.toLocaleString()} chars; text-only)`
33
+ : `\ncontext: ${contextMode} (0 chars; no eligible text)`;
34
+ const warning =
35
+ dirt && dirt !== "clean"
36
+ ? `\n\nWarning: uncommitted changes already exist — the result summary only attributes newly-dirty files to agy.`
37
+ : "";
38
+ const excerpt = prompt.slice(0, 200) + (prompt.length > 200 ? "…" : "");
39
+ return {
40
+ title: "Run agy (accept-edits)?",
41
+ body: `model: ${modelLabel}${agentLine}\ndir: ${cwd}${dirtLine}${contextLine}\n\ntask: ${excerpt}\n\nThis grants agy permission to modify files and run commands.${warning}`,
42
+ };
43
+ }
@@ -12,6 +12,7 @@ import {
12
12
  } from "./cli.js";
13
13
  import { getDefaultConfigPath } from "./config.js";
14
14
  import { canonicalDir, getDirLockPath } from "./lock.js";
15
+ import { getProviderStatus } from "./provider.js";
15
16
  import { getDefaultStorePath, getHistory } from "./sessions.js";
16
17
  import { detectVerifyCommand } from "./verify.js";
17
18
 
@@ -107,6 +108,8 @@ export async function runAgyDoctor(
107
108
 
108
109
  checks.push(await configCheck(signal));
109
110
  throwIfCancelled(signal);
111
+ checks.push(providerCheck(resolvedCwd));
112
+ throwIfCancelled(signal);
110
113
  checks.push(await sessionsCheck(resolvedCwd, signal));
111
114
  throwIfCancelled(signal);
112
115
  checks.push(await lockCheck(resolvedCwd));
@@ -136,7 +139,7 @@ export async function runAgyDoctor(
136
139
  };
137
140
  }
138
141
 
139
- export function formatAgyDoctorReport(cwd: string, checks: AgyDoctorCheck[]): string {
142
+ function formatAgyDoctorReport(cwd: string, checks: AgyDoctorCheck[]): string {
140
143
  const icon: Record<AgyDoctorStatus, string> = {
141
144
  ok: "✓",
142
145
  info: "•",
@@ -300,6 +303,39 @@ async function lockCheck(cwd: string): Promise<AgyDoctorCheck> {
300
303
  }
301
304
  }
302
305
 
306
+ /** Provider runtime state: driver, bridge, suspensions, staging. Never throws. */
307
+ function providerCheck(cwd: string): AgyDoctorCheck {
308
+ try {
309
+ const status = getProviderStatus(cwd);
310
+ const parts: string[] = [];
311
+ if (status.driver) {
312
+ const stats = status.driver;
313
+ parts.push(
314
+ `driver ${stats.state} · ${stats.turns} turn${stats.turns === 1 ? "" : "s"}` +
315
+ ` (${stats.reuses} reuse${stats.reuses === 1 ? "" : "s"}, ${stats.recycles} recycle${stats.recycles === 1 ? "" : "s"}` +
316
+ `${stats.lastRecycleReason ? `: ${stats.lastRecycleReason}` : ""})`,
317
+ );
318
+ } else {
319
+ parts.push("driver idle (no provider turns yet)");
320
+ }
321
+ parts.push(status.bridge ? `bridge ${status.bridge.toolCount} tools` : "bridge off");
322
+ if (status.suspended.length > 0) {
323
+ const names = status.suspended.map((entry) => entry.toolName).join(", ");
324
+ parts.push(`${status.suspended.length} suspended awaiting Pi tools (${names})`);
325
+ }
326
+ if (status.stagedImages > 0) {
327
+ parts.push(`${status.stagedImages} staged image dirs live`);
328
+ }
329
+ return {
330
+ name: "Provider",
331
+ status: status.driver ? "ok" : "info",
332
+ detail: parts.join(" · "),
333
+ };
334
+ } catch (error) {
335
+ return { name: "Provider", status: "warn", detail: errorMessage(error) };
336
+ }
337
+ }
338
+
303
339
  function throwIfCancelled(signal?: AbortSignal): void {
304
340
  if (signal?.aborted) throw new Error("agy doctor was cancelled");
305
341
  }
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Capability inspection: version, health, models, connectivity, agents, and
3
+ * usage checks against the agy CLI, plus the live model-catalog state they
4
+ * feed. Split out of `lib/cli.ts`; `cli.ts` re-exports the public surface
5
+ * so existing importers are untouched.
6
+ */
7
+
8
+ import { compareModelIds } from "./model-sort.js";
9
+ import { runPreflightCommand } from "./spawn.js";
10
+ import { parseAgyUsage, usageError, type AgyUsageSnapshot } from "./usage.js";
11
+ import type { AgyModel } from "./cli.js";
12
+
13
+ /** alias → pattern matching concrete model ids in `agy models` output. */
14
+ const UNSTABLE_SUFFIX = "(?:-(?:preview|experimental|beta|alpha|rc\\d*|snapshot|next))*";
15
+ const CATALOG_PATTERNS: Record<AgyModel, RegExp> = {
16
+ "flash-low": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-low${UNSTABLE_SUFFIX}$`),
17
+ "flash-medium": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-medium${UNSTABLE_SUFFIX}$`),
18
+ "flash-high": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-flash-high${UNSTABLE_SUFFIX}$`),
19
+ "pro-low": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-pro-low${UNSTABLE_SUFFIX}$`),
20
+ "pro-high": new RegExp(`^gemini-\\d+(?:\\.\\d+)*-pro-high${UNSTABLE_SUFFIX}$`),
21
+ sonnet: /^claude-sonnet-[\w.-]+$/,
22
+ opus: /^claude-opus-[\w.-]+$/,
23
+ "gpt-oss": /^gpt-oss-[\w.-]+$/,
24
+ };
25
+
26
+ export type AgyModelCatalog = Partial<Record<AgyModel, string>>;
27
+
28
+ const UNSTABLE_MODEL_PATTERN =
29
+ /(?:^|[-_.])(?:preview|experimental|beta|alpha|rc\d*|snapshot|next)(?:$|[-_.])/i;
30
+
31
+ let modelCatalog: AgyModelCatalog = {};
32
+
33
+ export function isStableModelId(id: string): boolean {
34
+ return !UNSTABLE_MODEL_PATTERN.test(id);
35
+ }
36
+
37
+ /**
38
+ * Parse `agy models` output into alias → concrete model id. Newer model
39
+ * generations win over older ones so aliases track the latest catalog.
40
+ * Preview/experimental ids are ignored unless `allowPreview` is set, so an
41
+ * unstable catalog entry can never silently become the default model.
42
+ */
43
+ export function parseModelCatalog(output: string, allowPreview = false): AgyModelCatalog {
44
+ const allow = allowPreview || process.env.PI_AGY_ALLOW_PREVIEW === "1";
45
+ const found: AgyModelCatalog = {};
46
+ for (const line of output.split("\n")) {
47
+ const id = line.trim().split(/\s+/)[0] ?? "";
48
+ if (!id) continue;
49
+ if (!allow && !isStableModelId(id)) continue;
50
+ for (const [alias, pattern] of Object.entries(CATALOG_PATTERNS) as Array<[AgyModel, RegExp]>) {
51
+ if (pattern.test(id) && compareModelIds(id, found[alias] ?? "") > 0) {
52
+ found[alias] = id;
53
+ }
54
+ }
55
+ }
56
+ return found;
57
+ }
58
+
59
+ /** Merge freshly observed catalog entries over the in-process catalog. */
60
+ export function updateModelCatalog(catalog: AgyModelCatalog): void {
61
+ modelCatalog = { ...modelCatalog, ...catalog };
62
+ }
63
+
64
+ export function getModelCatalog(): AgyModelCatalog {
65
+ return { ...modelCatalog };
66
+ }
67
+
68
+ /** Test helper — drop in-process catalog state. */
69
+ export function resetModelCatalog(): void {
70
+ modelCatalog = {};
71
+ }
72
+
73
+ export async function inspectAgyVersion(
74
+ cwd: string,
75
+ signal?: AbortSignal,
76
+ timeoutMs?: number,
77
+ ): Promise<string> {
78
+ return (
79
+ await runPreflightCommand(
80
+ ["--version"],
81
+ cwd,
82
+ signal,
83
+ "agy health check",
84
+ true,
85
+ timeoutMs,
86
+ )
87
+ ).trim();
88
+ }
89
+
90
+ export async function checkAgyHealth(
91
+ cwd: string,
92
+ signal?: AbortSignal,
93
+ timeoutMs?: number,
94
+ ): Promise<void> {
95
+ await inspectAgyVersion(cwd, signal, timeoutMs);
96
+ }
97
+
98
+ export async function inspectAgyModels(
99
+ cwd: string,
100
+ signal?: AbortSignal,
101
+ timeoutMs?: number,
102
+ ): Promise<AgyModelCatalog> {
103
+ const output = await runPreflightCommand(
104
+ ["models"],
105
+ cwd,
106
+ signal,
107
+ "agy connectivity check",
108
+ true,
109
+ timeoutMs,
110
+ );
111
+ const catalog = parseModelCatalog(output);
112
+ if (Object.keys(catalog).length > 0) updateModelCatalog(catalog);
113
+ return catalog;
114
+ }
115
+
116
+ export async function checkAgyConnectivity(
117
+ cwd: string,
118
+ signal?: AbortSignal,
119
+ timeoutMs?: number,
120
+ ): Promise<void> {
121
+ await inspectAgyModels(cwd, signal, timeoutMs);
122
+ }
123
+
124
+ /** List configured custom agents without spending a model turn. */
125
+ export async function inspectAgyAgents(
126
+ cwd: string,
127
+ signal?: AbortSignal,
128
+ timeoutMs?: number,
129
+ ): Promise<string[]> {
130
+ const output = await runPreflightCommand(
131
+ ["agents"],
132
+ cwd,
133
+ signal,
134
+ "agy agents check",
135
+ true,
136
+ timeoutMs,
137
+ );
138
+ return parseAgyAgents(output);
139
+ }
140
+
141
+ /**
142
+ * Refresh model-specific quotas without spending a model turn. Newer agy
143
+ * versions answer read-only `/usage` in print mode; older versions may not,
144
+ * so unsupported usage reporting is deliberately best effort.
145
+ */
146
+ const MIN_NATIVE_USAGE_VERSION = [1, 1, 11] as const;
147
+
148
+ export async function checkAgyUsage(
149
+ cwd: string,
150
+ signal?: AbortSignal,
151
+ timeoutMs?: number,
152
+ ): Promise<AgyUsageSnapshot | undefined> {
153
+ let versionOutput: string;
154
+ try {
155
+ versionOutput = await runPreflightCommand(
156
+ ["--version"],
157
+ cwd,
158
+ signal,
159
+ "agy version check",
160
+ true,
161
+ timeoutMs,
162
+ );
163
+ } catch (error) {
164
+ if (signal?.aborted) throw error;
165
+ const message = error instanceof Error ? error.message : String(error);
166
+ return usageError(`could not verify native usage support: ${message}`);
167
+ }
168
+
169
+ const version = parseAgyVersion(versionOutput);
170
+ if (!version) {
171
+ return usageError("could not verify native usage support; refusing to run /usage blindly");
172
+ }
173
+ if (compareVersions(version, MIN_NATIVE_USAGE_VERSION) < 0) {
174
+ return usageError(
175
+ `headless /usage requires agy >= ${MIN_NATIVE_USAGE_VERSION.join(".")} (detected ${version.join(".")})`,
176
+ );
177
+ }
178
+
179
+ try {
180
+ const output = await runPreflightCommand(
181
+ ["--output-format", "json", "-p", "/usage"],
182
+ cwd,
183
+ signal,
184
+ "agy usage check",
185
+ true,
186
+ timeoutMs,
187
+ );
188
+ return parseAgyUsage(output);
189
+ } catch (error) {
190
+ if (signal?.aborted) throw error;
191
+ const message = error instanceof Error ? error.message : String(error);
192
+ return usageError(message);
193
+ }
194
+ }
195
+
196
+ function parseAgyVersion(output: string): [number, number, number] | undefined {
197
+ const match = /(?:^|\s)v?(\d+)\.(\d+)\.(\d+)(?:\s|$)/m.exec(output);
198
+ return match
199
+ ? [Number(match[1]), Number(match[2]), Number(match[3])]
200
+ : undefined;
201
+ }
202
+
203
+ function compareVersions(left: readonly number[], right: readonly number[]): number {
204
+ for (let index = 0; index < 3; index++) {
205
+ if (left[index] !== right[index]) return left[index] < right[index] ? -1 : 1;
206
+ }
207
+ return 0;
208
+ }
209
+
210
+ const MAX_AGENT_NAME_LENGTH = 128;
211
+ const MAX_AGENT_COUNT = 200;
212
+
213
+ export function normalizeAgyAgentName(value?: string): string | undefined {
214
+ if (value === undefined) return undefined;
215
+ const agent = value.trim();
216
+ if (!agent) throw new Error("agy agent must not be empty");
217
+ if (/[\x00-\x1f\x7f]/.test(agent)) {
218
+ throw new Error("agy agent must not contain control characters");
219
+ }
220
+ if (agent.length > MAX_AGENT_NAME_LENGTH) {
221
+ throw new Error(`agy agent must be at most ${MAX_AGENT_NAME_LENGTH} characters`);
222
+ }
223
+ return agent;
224
+ }
225
+
226
+ /** Parse the intentionally simple, line-oriented output of `agy agents`. */
227
+ export function parseAgyAgents(output: string): string[] {
228
+ const agents: string[] = [];
229
+ for (const raw of output.split(/\r?\n/)) {
230
+ const line = raw.trim();
231
+ if (
232
+ !line ||
233
+ /^available\s+agents:?$/i.test(line) ||
234
+ /^name\s+/i.test(line) ||
235
+ /^(?:no|zero)\s+(?:custom\s+)?agents?\b/i.test(line)
236
+ ) {
237
+ continue;
238
+ }
239
+ const candidate = line
240
+ .split(/\t|\s{2,}/, 1)[0]
241
+ ?.replace(/^[-*]\s*/, "")
242
+ .trim();
243
+ try {
244
+ const agent = normalizeAgyAgentName(candidate);
245
+ if (agent && !agents.includes(agent)) {
246
+ agents.push(agent);
247
+ if (agents.length >= MAX_AGENT_COUNT) break;
248
+ }
249
+ } catch {
250
+ // Ignore malformed diagnostics and overlong names from CLI output.
251
+ }
252
+ }
253
+ return agents;
254
+ }
@@ -42,7 +42,7 @@ export function getDirLockPath(canonical: string): string {
42
42
  }
43
43
 
44
44
  /** Refresh a held lock so the stale-lock recovery cannot steal it mid-run. */
45
- export async function touchDirLock(lockPath: string): Promise<void> {
45
+ async function touchDirLock(lockPath: string): Promise<void> {
46
46
  const now = new Date();
47
47
  await utimes(lockPath, now, now);
48
48
  }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Model-id ordering for catalog resolution.
3
+ *
4
+ * Split out of `lib/cli.ts`: pure string comparison with no process or
5
+ * catalog state, so it can be tested and reasoned about in isolation.
6
+ */
7
+
8
+ /**
9
+ * Order model ids so the newest-looking id wins catalog resolution.
10
+ * Returns a negative/zero/positive number like `Array.prototype.sort` expects.
11
+ */
12
+ export function compareModelIds(a: string, b: string): number {
13
+ if (!b) return 1;
14
+ const versionA = /^gemini-(\d+(?:\.\d+)*)-/.exec(a)?.[1];
15
+ const versionB = /^gemini-(\d+(?:\.\d+)*)-/.exec(b)?.[1];
16
+ if (versionA && versionB) return compareDottedVersions(versionA, versionB);
17
+ // Numeric-aware compare so claude-sonnet-4-10 sorts above claude-sonnet-4-6.
18
+ return compareNatural(a, b);
19
+ }
20
+
21
+ function compareNatural(a: string, b: string): number {
22
+ const sa = a.split(/(\d+)/);
23
+ const sb = b.split(/(\d+)/);
24
+ for (let i = 0; i < Math.max(sa.length, sb.length); i++) {
25
+ const pa = sa[i] ?? "";
26
+ const pb = sb[i] ?? "";
27
+ if (pa === pb) continue;
28
+ if (/^\d+$/.test(pa) && /^\d+$/.test(pb)) {
29
+ const na = Number(pa);
30
+ const nb = Number(pb);
31
+ if (na !== nb) return na < nb ? -1 : 1;
32
+ }
33
+ return pa < pb ? -1 : 1;
34
+ }
35
+ return 0;
36
+ }
37
+
38
+ function compareDottedVersions(a: string, b: string): number {
39
+ const pa = a.split(".").map(Number);
40
+ const pb = b.split(".").map(Number);
41
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
42
+ const delta = (pa[i] ?? 0) - (pb[i] ?? 0);
43
+ if (delta !== 0) return delta;
44
+ }
45
+ return 0;
46
+ }