@punch-bot/cli 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +44 -7
  2. package/README.md +2 -2
  3. package/dist/bundle/chunks/{anthropic-messages-DA6M7CRN.js → anthropic-messages-BUUFZMRE.js} +3 -3
  4. package/dist/bundle/chunks/{azure-openai-responses-IJO5RNR3.js → azure-openai-responses-WZ4GZHD2.js} +1 -1
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +1 -1
  6. package/dist/bundle/chunks/{chunk-JHYQSLCR.js → chunk-6WNF4BLC.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-FLX3SJDL.js → chunk-6YKFJ7FQ.js} +92 -60
  8. package/dist/bundle/chunks/{chunk-5OD3Y36V.js → chunk-BYHXHV4K.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-5HTGPCR7.js → chunk-OWCYH5W2.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-FJPXW4TE.js → chunk-YGGF2ZM6.js} +1 -1
  11. package/dist/bundle/chunks/{google-generative-ai-JSIIVUNP.js → google-generative-ai-S2KXX5PQ.js} +1 -1
  12. package/dist/bundle/chunks/{google-vertex-BZ3ID54S.js → google-vertex-LQOUTFJN.js} +1 -1
  13. package/dist/bundle/chunks/{mistral-conversations-RMNTDYQK.js → mistral-conversations-VNJYBSRF.js} +1 -1
  14. package/dist/bundle/chunks/{openai-codex-responses-O3P3UWDP.js → openai-codex-responses-E6BLZPYJ.js} +1 -1
  15. package/dist/bundle/chunks/{openai-completions-G4BKSHGH.js → openai-completions-LUDIAWSG.js} +1 -1
  16. package/dist/bundle/chunks/{openai-responses-377V6EDU.js → openai-responses-IOCBEIVC.js} +1 -1
  17. package/dist/bundle/chunks/{virtual-modules-FOSN3OT2.js → virtual-modules-GZVZPCK3.js} +1 -1
  18. package/dist/bundle/cli-runtime.js +1 -1
  19. package/dist/bundle/index.js +1 -1
  20. package/dist/bundle/rpc-entry.js +1 -1
  21. package/dist/cli/args.js +4 -4
  22. package/dist/cli/args.js.map +1 -1
  23. package/dist/cli/credential-print.d.ts.map +1 -1
  24. package/dist/cli/credential-print.js +4 -4
  25. package/dist/cli/credential-print.js.map +1 -1
  26. package/dist/core/agent-session-services.d.ts +0 -1
  27. package/dist/core/agent-session-services.d.ts.map +1 -1
  28. package/dist/core/agent-session-services.js +0 -1
  29. package/dist/core/agent-session-services.js.map +1 -1
  30. package/dist/core/model-resolver.d.ts +67 -25
  31. package/dist/core/model-resolver.d.ts.map +1 -1
  32. package/dist/core/model-resolver.js +378 -193
  33. package/dist/core/model-resolver.js.map +1 -1
  34. package/dist/core/model-runtime.d.ts +4 -0
  35. package/dist/core/model-runtime.d.ts.map +1 -1
  36. package/dist/core/model-runtime.js +7 -2
  37. package/dist/core/model-runtime.js.map +1 -1
  38. package/dist/core/model-suffix-variants.d.ts +14 -0
  39. package/dist/core/model-suffix-variants.d.ts.map +1 -0
  40. package/dist/core/model-suffix-variants.js +27 -0
  41. package/dist/core/model-suffix-variants.js.map +1 -0
  42. package/dist/core/sdk.d.ts +0 -2
  43. package/dist/core/sdk.d.ts.map +1 -1
  44. package/dist/core/sdk.js +6 -22
  45. package/dist/core/sdk.js.map +1 -1
  46. package/dist/extensions/punch/auth.d.ts +2 -1
  47. package/dist/extensions/punch/auth.d.ts.map +1 -1
  48. package/dist/extensions/punch/auth.js +5 -1
  49. package/dist/extensions/punch/auth.js.map +1 -1
  50. package/dist/extensions/punch/index.d.ts.map +1 -1
  51. package/dist/extensions/punch/index.js +2 -1
  52. package/dist/extensions/punch/index.js.map +1 -1
  53. package/dist/extensions/punch/server.d.ts +3 -0
  54. package/dist/extensions/punch/server.d.ts.map +1 -1
  55. package/dist/extensions/punch/server.js +41 -3
  56. package/dist/extensions/punch/server.js.map +1 -1
  57. package/dist/extensions/punch/todo-store.d.ts +15 -0
  58. package/dist/extensions/punch/todo-store.d.ts.map +1 -0
  59. package/dist/extensions/punch/todo-store.js +208 -0
  60. package/dist/extensions/punch/todo-store.js.map +1 -0
  61. package/dist/extensions/punch/todos.d.ts +7 -3
  62. package/dist/extensions/punch/todos.d.ts.map +1 -1
  63. package/dist/extensions/punch/todos.js +40 -17
  64. package/dist/extensions/punch/todos.js.map +1 -1
  65. package/dist/main.d.ts.map +1 -1
  66. package/dist/main.js +9 -8
  67. package/dist/main.js.map +1 -1
  68. package/dist/modes/rpc/rpc-client.d.ts +4 -0
  69. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  70. package/dist/modes/rpc/rpc-client.js +7 -0
  71. package/dist/modes/rpc/rpc-client.js.map +1 -1
  72. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  73. package/dist/modes/rpc/rpc-mode.js +14 -2
  74. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  75. package/dist/modes/rpc/rpc-types.d.ts +11 -0
  76. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  77. package/dist/modes/rpc/rpc-types.js.map +1 -1
  78. package/docs/cli.md +5 -5
  79. package/docs/docs.json +4 -0
  80. package/docs/punch-todos.md +24 -0
  81. package/docs/rpc-commands.md +30 -2
  82. package/docs/rpc.md +1 -1
  83. package/docs/settings.md +2 -2
  84. package/docs/usage.md +2 -2
  85. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  86. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  87. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  88. package/examples/extensions/gondolin/package-lock.json +2 -2
  89. package/examples/extensions/gondolin/package.json +1 -1
  90. package/examples/extensions/sandbox/package-lock.json +2 -2
  91. package/examples/extensions/sandbox/package.json +1 -1
  92. package/examples/extensions/with-deps/package-lock.json +2 -2
  93. package/examples/extensions/with-deps/package.json +1 -1
  94. package/npm-shrinkwrap.json +21 -21
  95. package/package.json +17 -7
  96. package/src/extensions/punch/sqlite-bun.mjs +1 -0
  97. package/src/extensions/punch/sqlite-driver.d.mts +15 -0
  98. package/src/extensions/punch/sqlite-node.mjs +1 -0
@@ -6,6 +6,7 @@ import chalk from "chalk";
6
6
  import { minimatch } from "minimatch";
7
7
  import { isValidThinkingLevel } from "../cli/args.js";
8
8
  import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
9
+ import { findModelOrSuffixVariant } from "./model-suffix-variants.js";
9
10
  /** Default chat model IDs for providers with built-in chat models. */
10
11
  export const defaultModelPerProvider = {
11
12
  "amazon-bedrock": "us.anthropic.claude-opus-4-6-v1",
@@ -45,237 +46,418 @@ export const defaultModelPerProvider = {
45
46
  "qwen-token-plan": "qwen3.7-max",
46
47
  "qwen-token-plan-cn": "qwen3.7-max",
47
48
  "qwen-token-plan-individual": "qwen3.8-max",
48
- xiaomi: "mimo-v2.5-pro",
49
- "xiaomi-token-plan-cn": "mimo-v2.5-pro",
50
- "xiaomi-token-plan-ams": "mimo-v2.5-pro",
51
- "xiaomi-token-plan-sgp": "mimo-v2.5-pro",
49
+ xiaomi: "mimo-v2.6-pro",
50
+ "xiaomi-token-plan-cn": "mimo-v2.6-pro",
51
+ "xiaomi-token-plan-ams": "mimo-v2.6-pro",
52
+ "xiaomi-token-plan-sgp": "mimo-v2.6-pro",
52
53
  };
53
- export function resolveModelScopeFromModels(patterns, models, options) {
54
- const availableModels = [...models];
55
- const catalogModels = options?.catalogModels ?? availableModels;
56
- const catalogProviderNames = [...new Set(catalogModels.map((model) => model.provider))];
54
+ function splitThinkingSuffix(text) {
55
+ const colonIndex = text.lastIndexOf(":");
56
+ const suffix = text.substring(colonIndex + 1);
57
+ if (colonIndex === -1 || !isValidThinkingLevel(suffix))
58
+ return undefined;
59
+ return { base: text.substring(0, colonIndex), thinkingLevel: suffix };
60
+ }
61
+ function splitProviderPrefix(text, models) {
62
+ const slashIndex = text.indexOf("/");
63
+ if (slashIndex === -1)
64
+ return undefined;
65
+ const prefix = text.substring(0, slashIndex).trim().toLowerCase();
66
+ const modelText = text.substring(slashIndex + 1).trim();
67
+ if (!prefix || !modelText)
68
+ return undefined;
69
+ const provider = models.find((model) => model.provider.toLowerCase() === prefix)?.provider;
70
+ return provider ? { provider, modelText } : undefined;
71
+ }
72
+ /**
73
+ * `usable` only breaks ties between providers, so a unique match resolves even without credentials
74
+ * (`--api-key` first-time setup).
75
+ */
76
+ export function resolveModelReference(request, models, usable) {
77
+ const text = request.text.trim();
78
+ if (!text)
79
+ return { status: "not-found" };
80
+ const constraint = request.provider?.toLowerCase();
81
+ const pool = constraint ? models.filter((model) => model.provider.toLowerCase() === constraint) : models;
82
+ const result = resolveText(text, request, pool, usable);
83
+ if (result.status !== "not-found")
84
+ return result;
85
+ const split = splitProviderPrefix(text, pool);
86
+ const anchor = constraint ? pool[0] : pool.find((model) => model.provider === split?.provider);
87
+ if (!anchor)
88
+ return result;
89
+ const modelText = split?.modelText ?? text;
90
+ const suffix = request.thinkingSuffix === "none" ? undefined : splitThinkingSuffix(modelText);
91
+ return {
92
+ status: "not-found",
93
+ target: {
94
+ provider: anchor.provider,
95
+ providerModels: [anchor, ...pool.filter((model) => model.provider === anchor.provider && model !== anchor)],
96
+ modelText,
97
+ modelId: suffix?.base ?? modelText,
98
+ thinkingLevel: suffix?.thinkingLevel,
99
+ },
100
+ };
101
+ }
102
+ /** Exact `provider/id` or bare id lookup without thinking suffixes or fuzzy matching. */
103
+ export function findExactModelReferenceMatch(modelReference, models) {
104
+ const result = resolveModelReference({ text: modelReference, thinkingSuffix: "none", fuzzy: false }, models, () => true);
105
+ return result.status === "resolved" ? result.model : undefined;
106
+ }
107
+ function resolveText(text, request, pool, usable) {
108
+ const reference = selectReference(text, pool, request.fuzzy, usable);
109
+ if (reference)
110
+ return reference;
111
+ if (request.fuzzy) {
112
+ const fuzzy = selectFuzzy(text, fuzzyMatches(text, pool), usable);
113
+ if (fuzzy)
114
+ return fuzzy;
115
+ }
116
+ if (request.thinkingSuffix === "none")
117
+ return { status: "not-found" };
118
+ const thinking = splitThinkingSuffix(text);
119
+ if (thinking) {
120
+ const inner = resolveText(thinking.base, request, pool, usable);
121
+ if (inner.status === "not-found")
122
+ return inner;
123
+ // Only use this thinking level if no warning from inner recursion
124
+ return { ...inner, thinkingLevel: inner.warning ? undefined : thinking.thinkingLevel };
125
+ }
126
+ // Keep an invalid suffix as part of the id and fail, rather than resolve a different model
127
+ if (request.thinkingSuffix === "strict")
128
+ return { status: "not-found" };
129
+ const colonIndex = text.lastIndexOf(":");
130
+ if (colonIndex === -1)
131
+ return { status: "not-found" };
132
+ const suffix = text.substring(colonIndex + 1);
133
+ const inner = resolveText(text.substring(0, colonIndex), request, pool, usable);
134
+ if (inner.status === "not-found")
135
+ return inner;
136
+ return {
137
+ ...inner,
138
+ thinkingLevel: undefined,
139
+ warning: `Invalid thinking level "${suffix}" in pattern "${text}". Using default instead.`,
140
+ };
141
+ }
142
+ /**
143
+ * `provider/rest` is only a hint: the whole text may also be a model id on another provider, such as
144
+ * gateway id `zai/glm-5` or commandcode id `xiaomi/mimo-v2.5-pro`. The named provider wins when usable,
145
+ * since that is what the syntax usually means; otherwise a sole usable raw match wins, since the named
146
+ * provider could not serve the request. An unusable named match is still preferred over unusable raw
147
+ * matches, so `--api-key` can set up the named provider.
148
+ */
149
+ function selectReference(text, pool, fuzzy, usable) {
150
+ const lowerText = text.toLowerCase();
151
+ const raw = pool.filter((model) => model.id.toLowerCase() === lowerText);
152
+ const split = splitProviderPrefix(text, pool);
153
+ let named;
154
+ let namedPartially = false;
155
+ if (split) {
156
+ const providerModels = pool.filter((model) => model.provider === split.provider);
157
+ const lowerModelText = split.modelText.toLowerCase();
158
+ // The provider's own literal id (OpenRouter's `openrouter/free`) beats its fuzzy matches
159
+ named =
160
+ providerModels.find((model) => model.id.toLowerCase() === lowerModelText) ??
161
+ raw.find((model) => model.provider === split.provider);
162
+ if (!named && fuzzy) {
163
+ named = bestFuzzyMatch(split.modelText, fuzzyMatches(split.modelText, providerModels));
164
+ namedPartially = named !== undefined;
165
+ }
166
+ }
167
+ const resolved = (model) => model === named && namedPartially ? { status: "resolved", model, partial: true } : { status: "resolved", model };
168
+ const others = raw.filter((model) => model !== named);
169
+ const candidates = named ? [named, ...others] : others;
170
+ if (candidates.length === 0)
171
+ return undefined;
172
+ // Within one provider, the literal id (OpenRouter's `openrouter/fusion`) beats the prefix-stripped `fusion`
173
+ if (new Set(candidates.map((model) => model.provider)).size === 1)
174
+ return resolved(raw[0] ?? candidates[0]);
175
+ if (named && usable(named.provider))
176
+ return resolved(named);
177
+ const usableOthers = others.filter((model) => usable(model.provider));
178
+ if (usableOthers.length === 1)
179
+ return resolved(usableOthers[0]);
180
+ if (usableOthers.length === 0 && named)
181
+ return resolved(named);
182
+ return { status: "ambiguous", candidates, usableCount: usableOthers.length };
183
+ }
184
+ function fuzzyMatches(text, models) {
185
+ const lowerText = text.toLowerCase();
186
+ return models.filter((model) => model.id.toLowerCase().includes(lowerText) || model.name?.toLowerCase().includes(lowerText));
187
+ }
188
+ function selectFuzzy(text, matches, usable) {
189
+ if (matches.length === 0)
190
+ return undefined;
191
+ const multipleProviders = new Set(matches.map((model) => model.provider)).size > 1;
192
+ const usableMatches = multipleProviders ? matches.filter((model) => usable(model.provider)) : [];
193
+ const pool = usableMatches.length > 0 ? usableMatches : matches;
194
+ const best = bestFuzzyMatch(text, pool);
195
+ if (!best)
196
+ return undefined;
197
+ // The same id on several providers would otherwise be decided by catalog order
198
+ const tied = pool.filter((model) => model.id === best.id);
199
+ if (new Set(tied.map((model) => model.provider)).size === 1)
200
+ return { status: "resolved", model: best, partial: true };
201
+ return {
202
+ status: "ambiguous",
203
+ candidates: tied,
204
+ usableCount: usableMatches.length > 0 ? tied.length : 0,
205
+ };
206
+ }
207
+ /**
208
+ * Rank partial matches, each rule applied to the models left by the previous one:
209
+ * 1. A base id beats its catalog variants: `gemini-2.5-pro` matches `google/gemini-2.5-pro`, not
210
+ * `google/gemini-2.5-pro:batch`. Typing the variant's full id still selects it.
211
+ * 2. An id ending in the text at a separator beats one that continues it: `sonnet-5` matches
212
+ * `claude-sonnet-5`, not `claude-sonnet-5.5`.
213
+ * 3. Aliases (`claude-sonnet-4-5`) beat dated versions (`claude-sonnet-4-5-20250929`), then the latest id wins.
214
+ */
215
+ function bestFuzzyMatch(text, matches) {
216
+ const keys = new Set(matches.map((model) => `${model.provider}/${model.id}`));
217
+ const bases = matches.filter((model) => {
218
+ const colon = model.id.lastIndexOf(":");
219
+ return colon === -1 || !keys.has(`${model.provider}/${model.id.slice(0, colon)}`);
220
+ });
221
+ const lowerText = text.toLowerCase();
222
+ const closest = bases.filter((model) => endsAtSeparator(model.id.toLowerCase(), lowerText));
223
+ const ranked = closest.length > 0 ? closest : bases;
224
+ const aliases = ranked.filter((model) => isAlias(model.id));
225
+ return [...(aliases.length > 0 ? aliases : ranked)].sort((a, b) => b.id.localeCompare(a.id))[0];
226
+ }
227
+ function endsAtSeparator(id, text) {
228
+ if (!id.endsWith(text))
229
+ return false;
230
+ const before = id[id.length - text.length - 1];
231
+ return before === undefined || "/-_.:".includes(before);
232
+ }
233
+ function isAlias(id) {
234
+ return id.endsWith("-latest") || !/-\d{8}$/.test(id);
235
+ }
236
+ /** Describe a partial match, so a client sees which model a short or misspelled id selected. */
237
+ function partialMatchWarning(text, model) {
238
+ return `No exact match for "${text}". Using ${model.provider}/${model.id}.`;
239
+ }
240
+ /**
241
+ * A custom id `<catalog id>:<suffix>` (OpenRouter's `:nitro` routing, for example) keeps the catalog model's
242
+ * metadata. Other custom ids copy the provider's default model.
243
+ */
244
+ function buildFallbackModel(providerModels, modelId) {
245
+ const variant = findModelOrSuffixVariant(modelId, (id) => providerModels.find((model) => model.id === id));
246
+ if (variant)
247
+ return variant;
248
+ const defaultId = defaultModelPerProvider[providerModels[0].provider];
249
+ const baseModel = defaultId
250
+ ? (providerModels.find((m) => m.id === defaultId) ?? providerModels[0])
251
+ : providerModels[0];
252
+ return {
253
+ ...baseModel,
254
+ id: modelId,
255
+ name: modelId,
256
+ };
257
+ }
258
+ /**
259
+ * Resolve scope patterns (`--models`, `enabledModels`) to models with optional thinking levels.
260
+ *
261
+ * Every model in `models` is usable, so credentials cannot choose between providers offering the same
262
+ * id. All of them are added, with a warning so the user can pick one with `provider/id`.
263
+ */
264
+ export function resolveModelScopeFromModels(patterns, models) {
57
265
  const scopedModels = [];
58
266
  const diagnostics = [];
59
- const addModel = (model, thinkingLevel) => {
60
- if (!scopedModels.find((sm) => modelsAreEqual(sm.model, model))) {
267
+ const add = (model, thinkingLevel) => {
268
+ if (!scopedModels.some((scoped) => modelsAreEqual(scoped.model, model))) {
61
269
  scopedModels.push({ model, thinkingLevel });
62
270
  }
63
271
  };
272
+ const noMatch = (pattern) => diagnostics.push({ type: "warning", code: "no-match", message: `No models match pattern "${pattern}"`, pattern });
273
+ const ambiguous = (pattern, candidates) => {
274
+ const providers = [...new Set(candidates.map((m) => m.provider))].sort((a, b) => a.localeCompare(b));
275
+ diagnostics.push({
276
+ type: "warning",
277
+ code: "ambiguous",
278
+ message: `Pattern "${pattern}" matches several providers: ${providers.join(", ")}. Use provider/id to choose one.`,
279
+ pattern,
280
+ });
281
+ };
64
282
  for (const pattern of patterns) {
65
- const exact = resolveExactModelReference(pattern, catalogModels);
66
- // An ambiguous literal ID is reported as-is and never retried as a glob.
67
- if (!exact.model &&
68
- !exact.ambiguous &&
69
- (pattern.includes("*") || pattern.includes("?") || pattern.includes("["))) {
70
- // Extract optional thinking level suffix (e.g., "provider/*:high")
71
- const colonIdx = pattern.lastIndexOf(":");
72
- let globPattern = pattern;
73
- let thinkingLevel;
74
- if (colonIdx !== -1) {
75
- const suffix = pattern.substring(colonIdx + 1);
76
- if (isValidThinkingLevel(suffix)) {
77
- thinkingLevel = suffix;
78
- globPattern = pattern.substring(0, colonIdx);
79
- }
80
- }
81
- // "*sonnet*" matches bare IDs, but "openrouter/*" only matches that provider.
82
- const slash = globPattern.indexOf("/");
83
- const prefix = slash === -1 ? undefined : globPattern.slice(0, slash);
84
- const prefixProviders = prefix === undefined ? [] : matchProviderNames(catalogProviderNames, prefix);
85
- if (prefix !== undefined && prefixProviders.length > 1) {
86
- diagnostics.push({
87
- type: "warning",
88
- code: "no-match",
89
- message: `Provider "${prefix}" is ambiguous: ${prefixProviders.sort().join(", ")}.`,
90
- pattern,
91
- });
283
+ // Check if pattern contains glob characters
284
+ if (pattern.includes("*") || pattern.includes("?") || pattern.includes("[")) {
285
+ // A literal id such as `model[1m]:high` wins before `:high` is read as a thinking level
286
+ const literal = resolveModelReference({ text: pattern, thinkingSuffix: "none", fuzzy: false }, models, () => true);
287
+ if (literal.status === "resolved") {
288
+ add(literal.model, undefined);
92
289
  continue;
93
290
  }
94
- const [provider] = prefixProviders;
95
- const matchingModels = provider === undefined
96
- ? availableModels.filter((m) => minimatch(`${m.provider}/${m.id}`, globPattern, { nocase: true }) ||
97
- minimatch(m.id, globPattern, { nocase: true }))
98
- : availableModels.filter((m) => m.provider === provider && minimatch(m.id, globPattern.slice(slash + 1), { nocase: true }));
99
- if (matchingModels.length === 0) {
100
- diagnostics.push({
101
- type: "warning",
102
- code: "no-match",
103
- message: `No models match pattern "${pattern}"`,
104
- pattern,
105
- });
291
+ // Extract optional thinking level suffix (e.g., "provider/*:high")
292
+ const thinking = splitThinkingSuffix(pattern);
293
+ const globPattern = thinking?.base ?? pattern;
294
+ const thinkingLevel = thinking?.thinkingLevel;
295
+ // Ids such as `bracketed-model[1m]` are not globs
296
+ const exact = resolveModelReference({ text: globPattern, thinkingSuffix: "none", fuzzy: false }, models, () => true);
297
+ let matches = [];
298
+ if (exact.status === "resolved")
299
+ matches = [exact.model];
300
+ else if (exact.status === "ambiguous") {
301
+ matches = exact.candidates;
302
+ ambiguous(pattern, matches);
303
+ }
304
+ else {
305
+ // A glob naming a provider (`anthropic/*`) only matches that provider's ids, not gateway ids such as
306
+ // OpenRouter's `anthropic/claude-sonnet-5`. Other globs match "provider/modelId" or just the model id,
307
+ // so "*sonnet*" matches without requiring "anthropic/*sonnet*".
308
+ const slash = globPattern.indexOf("/");
309
+ const prefix = slash === -1 ? undefined : globPattern.slice(0, slash).toLowerCase();
310
+ const namedProvider = prefix !== undefined && models.some((m) => m.provider.toLowerCase() === prefix);
311
+ matches = models.filter((m) => namedProvider
312
+ ? m.provider.toLowerCase() === prefix &&
313
+ minimatch(m.id, globPattern.slice(slash + 1), { nocase: true })
314
+ : minimatch(`${m.provider}/${m.id}`, globPattern, { nocase: true }) ||
315
+ minimatch(m.id, globPattern, { nocase: true }));
106
316
  }
107
- for (const model of matchingModels)
108
- addModel(model, thinkingLevel);
317
+ if (matches.length === 0)
318
+ noMatch(pattern);
319
+ for (const model of matches)
320
+ add(model, thinkingLevel);
109
321
  continue;
110
322
  }
111
- const model = exact.model;
112
- if (!model) {
113
- diagnostics.push({ type: "warning", code: "no-match", message: exact.error ?? "", pattern });
323
+ // `provider/<catalog id>:<suffix>` (OpenRouter's `:nitro`) selects that variant, before the lenient
324
+ // fallback below would drop the suffix as an invalid thinking level and select the base model
325
+ const exact = resolveModelReference({ text: pattern, thinkingSuffix: "strict", fuzzy: false }, models, () => true);
326
+ if (exact.status === "not-found" && exact.target) {
327
+ const { target } = exact;
328
+ const variant = findModelOrSuffixVariant(target.modelId, (id) => target.providerModels.find((model) => model.id === id));
329
+ if (variant) {
330
+ add(variant, target.thinkingLevel);
331
+ continue;
332
+ }
333
+ }
334
+ const result = resolveModelReference({ text: pattern, thinkingSuffix: "lenient", fuzzy: true }, models, () => true);
335
+ if (result.status === "not-found") {
336
+ noMatch(pattern);
114
337
  continue;
115
338
  }
116
- if (!availableModels.some((available) => modelsAreEqual(available, model))) {
339
+ if (result.warning) {
340
+ diagnostics.push({ type: "warning", code: "invalid-thinking-level", message: result.warning, pattern });
341
+ }
342
+ if (result.status === "resolved" && result.partial) {
117
343
  diagnostics.push({
118
344
  type: "warning",
119
- code: "no-match",
120
- message: `Model "${model.provider}/${model.id}" is unavailable. Configure authentication for its provider.`,
345
+ code: "partial-match",
346
+ message: partialMatchWarning(pattern, result.model),
121
347
  pattern,
122
348
  });
123
- continue;
124
349
  }
125
- addModel(model, exact.thinkingLevel);
350
+ if (result.status === "ambiguous")
351
+ ambiguous(pattern, result.candidates);
352
+ const matches = result.status === "resolved" ? [result.model] : result.candidates;
353
+ for (const model of matches)
354
+ add(model, result.thinkingLevel);
126
355
  }
127
356
  return { scopedModels, diagnostics };
128
357
  }
129
358
  export async function resolveModelScopeWithDiagnostics(patterns, modelRuntime, options) {
130
- return resolveModelScopeFromModels(patterns, await modelRuntime.getAvailable(undefined, options), {
131
- // Authentication must not change provider inference or hide ambiguous IDs.
132
- catalogModels: modelRuntime.getModels(),
133
- });
359
+ return resolveModelScopeFromModels(patterns, await modelRuntime.getAvailable(undefined, options));
360
+ }
361
+ export async function resolveModelScope(patterns, modelRuntime, options) {
362
+ const { scopedModels, diagnostics } = await resolveModelScopeWithDiagnostics(patterns, modelRuntime, options);
363
+ for (const diagnostic of diagnostics) {
364
+ console.warn(chalk.yellow(`Warning: ${diagnostic.message}`));
365
+ }
366
+ return scopedModels;
134
367
  }
135
368
  /**
136
- * Return the provider names that match `name`. An exact-case match wins. Otherwise
137
- * every case-insensitive match is returned, so callers must treat more than one as ambiguous.
369
+ * Resolve a single model from CLI flags.
370
+ *
371
+ * Supports:
372
+ * - --provider <provider> --model <pattern>
373
+ * - --model <provider>/<pattern>
374
+ * - Fuzzy matching (same rules as model scoping: exact id, then partial id/name), with a warning
375
+ *
376
+ * Note: This does not apply the thinking level by itself, but it may *parse* and
377
+ * return a thinking level from "<pattern>:<thinking>" so the caller can apply it.
138
378
  */
139
- function matchProviderNames(providerNames, name) {
140
- const exact = providerNames.filter((provider) => provider === name);
141
- return exact.length > 0 ? exact : providerNames.filter((provider) => provider.toLowerCase() === name.toLowerCase());
142
- }
143
- function resolveExactModelReference(reference, models, cliProvider) {
144
- const providerNames = [...new Set(models.map((model) => model.provider))];
145
- const cliMatches = cliProvider === undefined ? [] : matchProviderNames(providerNames, cliProvider);
146
- if (cliProvider !== undefined && cliMatches.length === 0) {
379
+ export function resolveCliModel(options) {
380
+ const { cliProvider, cliModel, cliThinking, inlineApiKey, modelRuntime } = options;
381
+ // An empty --model is an error, not a request for the default model.
382
+ if (cliModel === undefined) {
383
+ return { model: undefined, warning: undefined, error: undefined };
384
+ }
385
+ // Important: use *all* models here, not just models with pre-configured auth.
386
+ // This allows "--api-key" to be used for first-time setup.
387
+ const models = [...modelRuntime.getModels()];
388
+ if (models.length === 0) {
147
389
  return {
148
390
  model: undefined,
149
391
  warning: undefined,
150
- error: `Unknown provider "${cliProvider}". Use --list-models to see available providers.`,
392
+ error: "No models available. Check your installation or add models to models.json.",
151
393
  };
152
394
  }
153
- if (cliProvider !== undefined && cliMatches.length > 1) {
395
+ const provider = cliProvider
396
+ ? models.find((m) => m.provider.toLowerCase() === cliProvider.toLowerCase())?.provider
397
+ : undefined;
398
+ if (cliProvider && !provider) {
154
399
  return {
155
400
  model: undefined,
156
401
  warning: undefined,
157
- error: `Provider "${cliProvider}" is ambiguous: ${cliMatches.sort().join(", ")}.`,
402
+ error: `Unknown provider "${cliProvider}". Use --list-models to see available providers/models.`,
158
403
  };
159
404
  }
160
- let provider = cliMatches.length === 1 ? cliMatches[0] : undefined;
161
- let modelId = reference;
162
- const literalId = cliProvider === undefined ? undefined : reference;
163
- if (provider === undefined) {
164
- const slash = modelId.indexOf("/");
165
- // An ambiguous prefix is not a provider; it stays part of the model ID.
166
- const prefixMatches = slash === -1 ? [] : matchProviderNames(providerNames, modelId.slice(0, slash));
167
- if (prefixMatches.length === 1) {
168
- provider = prefixMatches[0];
169
- modelId = modelId.slice(slash + 1);
170
- }
171
- }
172
- else if (modelId.toLowerCase().startsWith(`${provider.toLowerCase()}/`)) {
173
- modelId = modelId.slice(provider.length + 1);
174
- }
175
- const candidates = provider === undefined ? models : models.filter((model) => model.provider === provider);
176
- // An exact-case ID wins; otherwise accept IDs that differ only in case.
177
- const findMatches = (id) => {
178
- const matches = candidates.filter((model) => model.id === id);
179
- return matches.length > 0 ? matches : candidates.filter((model) => model.id.toLowerCase() === id.toLowerCase());
180
- };
181
- // With --provider, the raw ID may itself start with that provider name
182
- // (for example OpenRouter's openrouter/fusion).
183
- const ids = literalId === undefined || literalId === modelId ? [modelId] : [literalId, modelId];
184
- let matches = ids.map(findMatches).find((matches) => matches.length > 0) ?? [];
185
- let thinkingLevel;
186
- // A literal catalog ID takes precedence, including IDs ending in :high.
187
- // Strip at most one thinking suffix, and only resolve the remaining ID exactly.
188
- if (matches.length === 0) {
189
- for (const id of ids) {
190
- const colon = id.lastIndexOf(":");
191
- const suffix = id.slice(colon + 1);
192
- if (colon !== -1 && isValidThinkingLevel(suffix)) {
193
- matches = findMatches(id.slice(0, colon));
194
- if (matches.length > 0) {
195
- thinkingLevel = suffix;
196
- break;
197
- }
198
- }
199
- }
405
+ const result = resolveModelReference({ text: cliModel, provider, thinkingSuffix: "strict", fuzzy: true }, models,
406
+ // An inline key goes to whichever provider is selected, so stored credentials must not choose it
407
+ inlineApiKey ? () => false : (providerId) => modelRuntime.hasConfiguredAuth(providerId));
408
+ if (result.status === "resolved") {
409
+ const warning = result.partial ? partialMatchWarning(cliModel, result.model) : result.warning;
410
+ return { model: result.model, thinkingLevel: result.thinkingLevel, warning, error: undefined };
200
411
  }
201
- if (matches.length === 1) {
202
- return { model: matches[0], thinkingLevel, warning: undefined, error: undefined };
412
+ if (result.status === "ambiguous") {
413
+ const matches = result.candidates
414
+ .map((m) => `${m.provider}/${m.id}`)
415
+ .sort((a, b) => a.localeCompare(b))
416
+ .join(", ");
417
+ const authHint = inlineApiKey
418
+ ? "--api-key does not choose a provider."
419
+ : result.usableCount === 0
420
+ ? "No matching provider is authenticated."
421
+ : "More than one matching provider is authenticated.";
422
+ return {
423
+ model: undefined,
424
+ warning: undefined,
425
+ error: `Model "${cliModel}" is ambiguous across providers: ${matches}. ${authHint} Use --provider or provider/model.`,
426
+ };
203
427
  }
204
- const display = provider === undefined ? reference : `${provider}/${modelId}`;
205
- return {
206
- model: undefined,
207
- warning: undefined,
208
- ambiguous: matches.length > 1,
209
- error: matches.length > 1
210
- ? `Model "${display}" is ambiguous: ${matches
211
- .map((model) => `${model.provider}/${model.id}`)
212
- .sort()
213
- .join(", ")}. Use --provider or provider/model.`
214
- : `Model "${display}" not found. Use --list-models or define the exact model in models.json.`,
215
- };
216
- }
217
- /**
218
- * Resolve a single model from CLI flags.
219
- *
220
- * Supports:
221
- * - --provider <provider> --model <id>
222
- * - --model <provider>/<id>
223
- *
224
- * The ID must name one catalog model exactly. Case is ignored only when that
225
- * leaves a single match. There is no partial matching or custom-model fallback.
226
- *
227
- * Note: This does not apply the thinking level by itself, but it may *parse* and
228
- * return a thinking level from "<id>:<thinking>" so the caller can apply it.
229
- */
230
- export function resolveCliModel(options) {
231
- const { cliProvider, cliModel, modelRuntime } = options;
232
- if (cliModel === undefined) {
233
- return { model: undefined, warning: undefined, error: undefined };
428
+ const { target } = result;
429
+ if (!target) {
430
+ return {
431
+ model: undefined,
432
+ warning: undefined,
433
+ error: `Model "${cliModel}" not found. Use --list-models to see available models.`,
434
+ };
234
435
  }
235
- // Use all models, not only authenticated ones, so --api-key works for first-time setup.
236
- const resolved = resolveExactModelReference(cliModel, modelRuntime.getModels(), cliProvider);
237
- // Copy fields explicitly so the internal `ambiguous` flag does not leak.
436
+ // Use the thinking level suffix only when --thinking is not explicitly provided; otherwise it
437
+ // stays part of the custom model id.
438
+ // e.g. "zai-org/GLM-5.1-FP8:high" → modelId="zai-org/GLM-5.1-FP8", fallbackThinking="high"
439
+ const modelId = cliThinking ? target.modelText : target.modelId;
440
+ const fallbackThinking = cliThinking ? undefined : target.thinkingLevel;
441
+ const fallbackModel = buildFallbackModel(target.providerModels, modelId);
442
+ const requestedThinking = cliThinking ?? fallbackThinking;
238
443
  return {
239
- model: resolved.model,
240
- thinkingLevel: resolved.thinkingLevel,
241
- warning: resolved.warning,
242
- error: resolved.error,
444
+ model: requestedThinking && requestedThinking !== "off" ? { ...fallbackModel, reasoning: true } : fallbackModel,
445
+ thinkingLevel: fallbackThinking,
446
+ warning: `Model "${modelId}" not found for provider "${target.provider}". Using custom model id.`,
447
+ error: undefined,
243
448
  };
244
449
  }
245
450
  /**
246
451
  * Find the initial model to use based on priority:
247
- * 1. CLI args (provider + model)
248
- * 2. First model from scoped models (if not continuing/resuming)
249
- * 3. Restored from session (if continuing/resuming)
250
- * 4. Saved default from settings
251
- * 5. First available model with valid API key
452
+ * 1. First model from scoped models (if not continuing/resuming)
453
+ * 2. Saved default from settings
454
+ * 3. First available model with valid API key
252
455
  */
253
456
  export async function findInitialModel(options) {
254
- const { cliProvider, cliModel, scopedModels, isContinuing, defaultProvider, defaultModelId, defaultThinkingLevel, modelThinkingLevels, modelRuntime, strictModelSelection = true, } = options;
457
+ const { scopedModels, isContinuing, defaultProvider, defaultModelId, defaultThinkingLevel, modelThinkingLevels, modelRuntime, } = options;
255
458
  let model;
256
459
  let thinkingLevel = DEFAULT_THINKING_LEVEL;
257
- // 1. CLI args take priority
258
- if (cliModel !== undefined) {
259
- const resolved = resolveCliModel({
260
- cliProvider,
261
- cliModel,
262
- modelRuntime,
263
- });
264
- if (resolved.error) {
265
- if (strictModelSelection)
266
- throw new Error(resolved.error);
267
- console.error(chalk.red(resolved.error));
268
- process.exit(1);
269
- }
270
- if (resolved.model) {
271
- return {
272
- model: resolved.model,
273
- thinkingLevel: resolved.thinkingLevel ?? DEFAULT_THINKING_LEVEL,
274
- fallbackMessage: undefined,
275
- };
276
- }
277
- }
278
- // 2. Use first model from scoped models (skip if continuing/resuming)
460
+ // 1. Use first model from scoped models (skip if continuing/resuming)
279
461
  if (scopedModels.length > 0 && !isContinuing) {
280
462
  const scopedModel = scopedModels[0];
281
463
  const perModel = modelThinkingLevels?.[`${scopedModel.model.provider}/${scopedModel.model.id}`];
@@ -285,12 +467,10 @@ export async function findInitialModel(options) {
285
467
  fallbackMessage: undefined,
286
468
  };
287
469
  }
288
- // 3. Try saved default from settings if auth is configured.
470
+ // 2. Try saved default from settings if auth is configured.
471
+ let defaultMiss;
289
472
  if (defaultProvider && defaultModelId) {
290
473
  const found = modelRuntime.getModel(defaultProvider, defaultModelId);
291
- if (strictModelSelection && (!found || !modelRuntime.hasConfiguredAuth(defaultProvider))) {
292
- throw new Error(`Could not select default model ${defaultProvider}/${defaultModelId}: ${found ? "no auth configured" : "model not found; define the exact model in models.json"}.`);
293
- }
294
474
  if (found && modelRuntime.hasConfiguredAuth(found.provider)) {
295
475
  model = found;
296
476
  const perModel = modelThinkingLevels?.[`${defaultProvider}/${defaultModelId}`];
@@ -302,22 +482,27 @@ export async function findInitialModel(options) {
302
482
  }
303
483
  return { model, thinkingLevel, fallbackMessage: undefined };
304
484
  }
485
+ defaultMiss = `Could not select default model ${defaultProvider}/${defaultModelId} (${found ? "no auth configured" : "model not found"})`;
305
486
  }
306
- // 4. Try first available model with valid API key
487
+ const fallback = (match) => ({
488
+ model: match,
489
+ thinkingLevel: DEFAULT_THINKING_LEVEL,
490
+ fallbackMessage: defaultMiss && `${defaultMiss}. Using ${match.provider}/${match.id}.`,
491
+ });
492
+ // 3. Try first available model with valid API key
307
493
  const availableModels = [...modelRuntime.getAvailableSnapshot()];
308
494
  if (availableModels.length > 0) {
309
495
  // Try to find a default model from known providers
310
496
  for (const provider of Object.keys(defaultModelPerProvider)) {
311
497
  const defaultId = defaultModelPerProvider[provider];
312
498
  const match = availableModels.find((m) => m.provider === provider && m.id === defaultId);
313
- if (match) {
314
- return { model: match, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };
315
- }
499
+ if (match)
500
+ return fallback(match);
316
501
  }
317
502
  // If no default found, use first available
318
- return { model: availableModels[0], thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };
503
+ return fallback(availableModels[0]);
319
504
  }
320
- // 5. No model found
505
+ // 4. No model found
321
506
  return { model: undefined, thinkingLevel: DEFAULT_THINKING_LEVEL, fallbackMessage: undefined };
322
507
  }
323
508
  /**