@uncarved/jade 0.5.1 → 0.5.2

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 (78) hide show
  1. package/README.md +14 -11
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/install.js +5 -0
  5. package/dist/install.js.map +1 -1
  6. package/package.json +6 -6
  7. package/plugins/approval/index.ts +129 -13
  8. package/plugins/approval/plugin.json +4 -1
  9. package/plugins/approval/policy.ts +127 -7
  10. package/plugins/approval/review.ts +188 -45
  11. package/plugins/ask/index.ts +29 -1
  12. package/plugins/budget/index.ts +44 -6
  13. package/plugins/budget/plugin.json +1 -2
  14. package/plugins/compact/compact.ts +153 -39
  15. package/plugins/compact/index.ts +39 -5
  16. package/plugins/compact/plugin.json +5 -2
  17. package/plugins/cost/cache.ts +114 -0
  18. package/plugins/cost/index.ts +109 -51
  19. package/plugins/cost/plugin.json +3 -2
  20. package/plugins/memory/memory.ts +51 -28
  21. package/plugins/models/configure.ts +344 -125
  22. package/plugins/models/index.ts +44 -9
  23. package/plugins/models/price.ts +291 -0
  24. package/plugins/models/provider.ts +40 -8
  25. package/plugins/models/saved.ts +20 -4
  26. package/plugins/modes/index.ts +3 -4
  27. package/plugins/prompts/prompts.ts +5 -1
  28. package/plugins/task/index.ts +31 -10
  29. package/plugins/task/plugin.json +5 -2
  30. package/plugins/task/subagent.ts +21 -4
  31. package/plugins/todo/index.ts +62 -1
  32. package/plugins/todo/plugin.json +1 -1
  33. package/plugins/tui/frontend.ts +31 -5
  34. package/plugins/tui/index.ts +2 -1
  35. package/plugins/tui/plugin.json +1 -1
  36. package/plugins/tui/screen.ts +17 -5
  37. package/plugins/tui/transcript.ts +518 -507
  38. package/plugins/tui/tui.ts +212 -54
  39. package/plugins/withdraw/index.ts +111 -0
  40. package/plugins/withdraw/plugin.json +8 -0
  41. package/plugins-dist/approval/index.js +103 -9
  42. package/plugins-dist/approval/plugin.json +4 -1
  43. package/plugins-dist/approval/policy.js +112 -9
  44. package/plugins-dist/approval/review.js +141 -34
  45. package/plugins-dist/ask/index.js +28 -2
  46. package/plugins-dist/budget/index.js +30 -7
  47. package/plugins-dist/budget/plugin.json +1 -2
  48. package/plugins-dist/compact/compact.js +106 -32
  49. package/plugins-dist/compact/index.js +27 -3
  50. package/plugins-dist/compact/plugin.json +6 -2
  51. package/plugins-dist/cost/cache.js +100 -0
  52. package/plugins-dist/cost/index.js +87 -38
  53. package/plugins-dist/cost/plugin.json +5 -2
  54. package/plugins-dist/memory/memory.js +51 -32
  55. package/plugins-dist/models/configure.js +285 -105
  56. package/plugins-dist/models/index.js +33 -2
  57. package/plugins-dist/models/price.js +244 -0
  58. package/plugins-dist/models/provider.js +22 -4
  59. package/plugins-dist/models/saved.js +13 -3
  60. package/plugins-dist/modes/index.js +2 -3
  61. package/plugins-dist/prompts/prompts.js +5 -1
  62. package/plugins-dist/task/index.js +25 -7
  63. package/plugins-dist/task/plugin.json +5 -2
  64. package/plugins-dist/task/subagent.js +15 -6
  65. package/plugins-dist/todo/index.js +50 -0
  66. package/plugins-dist/todo/plugin.json +1 -1
  67. package/plugins-dist/tui/frontend.js +26 -4
  68. package/plugins-dist/tui/index.js +2 -1
  69. package/plugins-dist/tui/plugin.json +2 -1
  70. package/plugins-dist/tui/screen.js +7 -3
  71. package/plugins-dist/tui/transcript.js +13 -5
  72. package/plugins-dist/tui/tui.js +197 -50
  73. package/plugins-dist/tui/vendor.js +1388 -1088
  74. package/plugins-dist/withdraw/index.js +88 -0
  75. package/plugins-dist/withdraw/plugin.json +12 -0
  76. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  77. package/src/api.ts +1 -1
  78. package/src/install.ts +5 -0
@@ -1,12 +1,15 @@
1
- // /model:选服务、填地址和密钥、选模型、改输出上限、思考力度、上下文窗口、限速和能不能看图。
1
+ // /model:选服务、填地址和密钥、选模型、改输出上限、思考力度、上下文窗口、限速、能不能看图和单价。
2
2
  // 配置写进 $JADE_HOME/.env;用过的服务和模型记在 $JADE_HOME/models.json 里(saved.ts),可以直接切回去。
3
3
  //
4
- // 从旧 jade 的 ui/configure.ts 移植。省掉了旧 jade 的"插件提供的模型服务"(新的 jade 还没有这种服务),
5
- // 其余流程一样。
4
+ // 主菜单按服务分组列出全部模型,回车就切换;设置、单价、服务的名字、删除在 "Manage models…" 里。
5
+ // 新加的模型一律从默认设置开始,不沿用当前模型的。
6
+ //
7
+ // 从旧 jade 的 ui/configure.ts 移植。省掉了旧 jade 的"插件提供的模型服务"(新的 jade 还没有这种服务)。
6
8
 
7
9
  import { readFile, rm, writeFile } from "node:fs/promises";
8
10
  import { hasProvider, parseTokens } from "./config.ts";
9
11
  import { contextWindow } from "./context.ts";
12
+ import { CURRENCIES, formatRates, formatRulePrices, formatWhen, parseRates, parseRulePrices, parseWhen, priceSummary, symbol, type Currency, type ModelPrice, type PriceRule } from "./price.ts";
10
13
  import { EFFORTS, fallbacksFromEnv, isBuiltinKind, isOfficialAnthropic, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, thinkingFromEnv, URL_KEY, visionFromEnv, type ProviderKind } from "./provider.ts";
11
14
  import { MODEL_SETTINGS, readSavedServices, updateEnvFile, writeSavedServices, type Env, type SavedModel, type SavedService } from "./saved.ts";
12
15
  import type { UI } from "@uncarved/jade-api";
@@ -117,11 +120,29 @@ function describeService(service: SavedService): string {
117
120
  return [i.kind, host].filter(Boolean).join(" · ");
118
121
  }
119
122
 
120
- /** 保存过的、不是当前的模型,按服务分组:当前服务的在前 */
121
- function otherModels(services: SavedService[], currentId: string | undefined, currentModel: string): { service: SavedService; model: SavedModel }[] {
122
- return [...services.filter((s) => serviceId(s.env) === currentId), ...services.filter((s) => serviceId(s.env) !== currentId)].flatMap((s) =>
123
- s.models.filter((m) => !(serviceId(s.env) === currentId && m.name === currentModel)).map((m) => ({ service: s, model: m })),
123
+ /** 分组的标题:用户起的名字,否则类型和主机名 */
124
+ const groupOf = (s: SavedService) => s.name ?? describeService(s);
125
+
126
+ const byName = (a: string, b: string) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
127
+
128
+ /** 按名字排好的服务 */
129
+ const sortedServices = (services: SavedService[]) => [...services].sort((a, b) => byName(groupOf(a), groupOf(b)));
130
+
131
+ interface Entry {
132
+ service: SavedService;
133
+ model: SavedModel;
134
+ current: boolean;
135
+ }
136
+
137
+ /**
138
+ * 保存过的全部模型:服务按名字排,同一个服务的模型按名字排,顺序不随最近用过哪个变。
139
+ * 当前的模型不在 models.json 里时(不是内置的服务)单独放在最前
140
+ */
141
+ function allModels(services: SavedService[], currentId: string | undefined, currentModel: string | undefined, current: () => Entry): Entry[] {
142
+ const list = sortedServices(services).flatMap((s) =>
143
+ [...s.models].sort((a, b) => byName(a.name, b.name)).map((m) => ({ service: s, model: m, current: currentId !== undefined && serviceId(s.env) === currentId && m.name === currentModel })),
124
144
  );
145
+ return list.some((e) => e.current) ? list : [current(), ...list];
125
146
  }
126
147
 
127
148
  /** Claude 不设输出上限时用的值:和 @uncarved/provider-anthropic 里的默认值一致(不从那里导入:加载它的 SDK 要一百多毫秒) */
@@ -183,9 +204,13 @@ export function configurator(opts: ConfigureOptions): Configure {
183
204
  return sid !== undefined && (sid === id || (replacing !== undefined && sid === replacing));
184
205
  });
185
206
  const models = old.flatMap((s) => s.models).filter((m, i, list) => m.name !== model && list.findIndex((x) => x.name === m.name) === i);
207
+ // 单价和服务的名字不在 .env 里:从原来那份带过来
208
+ const price = old.flatMap((s) => s.models).find((m) => m.name === model)?.price;
209
+ const name = old.find((s) => s.name)?.name;
186
210
  const service: SavedService = {
211
+ ...(name ? { name } : {}),
187
212
  env: { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind },
188
- models: [{ name: model, settings: pick(env, MODEL_SETTINGS) }, ...models],
213
+ models: [{ name: model, settings: pick(env, MODEL_SETTINGS), ...(price ? { price } : {}) }, ...models],
189
214
  };
190
215
  await writeSavedServices(modelsFile, [service, ...all.filter((s) => !old.includes(s))]);
191
216
  }
@@ -210,7 +235,7 @@ export function configurator(opts: ConfigureOptions): Configure {
210
235
  }
211
236
 
212
237
  /** 换成保存过的服务 s 上的模型 m:服务的变量和模型的设置写进 .env,模型没设的设置删掉 */
213
- function useSaved(s: SavedService, m: SavedModel): Promise<boolean> {
238
+ function useSaved(s: SavedService, m: SavedModel, replacing?: string): Promise<boolean> {
214
239
  const kind = providerKind(s.env);
215
240
  if (!isBuiltinKind(kind)) {
216
241
  report(`The saved service ${describeService(s)} is not one of the built-in providers.`);
@@ -221,25 +246,38 @@ export function configurator(opts: ConfigureOptions): Configure {
221
246
  for (const k of MODEL_SETTINGS) updates[k] = m.settings[k];
222
247
  updates.JADE_PROVIDER = kind;
223
248
  updates[MODEL_KEY[kind]] = m.name;
224
- return applyConfig(updates);
249
+ return applyConfig(updates, replacing);
225
250
  }
226
251
 
227
252
  /**
228
- * 在当前的服务上换成 model:用过的带上它自己的设置;新的模型沿用输出上限、思考力度和额外请求参数,
229
- * 上下文窗口不沿用(不同模型差别很大),按模型名推断
253
+ * 换成服务 serviceEnv 上的 model。from 下保存过这个模型时带上它自己的设置;新的模型一律从默认设置开始
254
+ * (思考力度、额外请求参数各服务写法不同,限速、上下文窗口跟着模型走,沿用别的模型的容易错),
255
+ * 只问输出上限:Claude 以外的服务常常默认只给 4096 个输出 token,带思考的模型很容易用完。
256
+ * replacing:换了密钥的那个服务原来的 id
230
257
  */
258
+ async function useModel(serviceEnv: Env, kind: ProviderKind, model: string, from?: SavedService, replacing?: string): Promise<boolean> {
259
+ const saved = from?.models.find((m) => m.name === model);
260
+ if (from && saved) return useSaved({ ...from, env: { ...from.env, ...pick(serviceEnv, serviceKeys(kind)) } }, saved, replacing);
261
+ const updates: Env = { ...pick(serviceEnv, serviceKeys(kind)), JADE_PROVIDER: kind, [MODEL_KEY[kind]]: model };
262
+ for (const k of MODEL_SETTINGS) updates[k] = undefined;
263
+ if (kind !== "anthropic" && ui.interactive) {
264
+ const max = await ui.input({ title: "Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", initial: "32K" }, opts.signal);
265
+ if (max === undefined || !tokensInput("Output limit", max)) return false;
266
+ if (max) updates.JADE_MAX_TOKENS = max;
267
+ }
268
+ return applyConfig(updates, replacing);
269
+ }
270
+
271
+ /** 在当前的服务上换成 model(/model <name>,名字不是保存过的模型) */
231
272
  async function switchModel(model: string): Promise<boolean> {
232
273
  const env = opts.env();
233
- const id = serviceId(env);
234
- const service = (await savedServices()).find((s) => serviceId(s.env) === id);
235
- const saved = service?.models.find((m) => m.name === model);
236
- if (service && saved) return useSaved(service, saved);
237
274
  const kind = providerKind(env);
238
275
  if (!isBuiltinKind(kind)) {
239
276
  report(`JADE_PROVIDER must be one of ${PROVIDERS.map((p) => p.kind).join(", ")}; set the model in ${envFile}.`);
240
277
  return false;
241
278
  }
242
- return applyConfig({ [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined });
279
+ const id = serviceId(env);
280
+ return useModel(env, kind, model, (await savedServices()).find((s) => serviceId(s.env) === id));
243
281
  }
244
282
 
245
283
  /** 选模型:服务能列出模型时从列表里选,否则手动输入。选 Back 和取消一样返回 undefined */
@@ -251,7 +289,7 @@ export function configurator(opts: ConfigureOptions): Configure {
251
289
  const picked = await ui.select(
252
290
  {
253
291
  title: "Choose a model",
254
- options: [...models.map((m) => ({ label: m, value: m, ...(m === current ? { hint: "current" } : saved.includes(m) ? { hint: "saved" } : {}) })), { label: "Enter a name…", value: OTHER }, { label: "Back", value: BACK }],
292
+ options: [...models.map((m) => ({ label: m, value: m, ...(m === current ? { current: true } : saved.includes(m) ? { hint: "saved" } : {}) })), { label: "Enter a name…", value: OTHER }, { label: "Back", value: BACK }],
255
293
  },
256
294
  opts.signal,
257
295
  );
@@ -268,7 +306,7 @@ export function configurator(opts: ConfigureOptions): Configure {
268
306
  const kindName = await ui.select(
269
307
  {
270
308
  title: "Which service should jade use?",
271
- options: PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.kind === current?.kind ? `${p.hint} · current` : p.hint })),
309
+ options: PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.hint, ...(p.kind === current?.kind ? { current: true } : {}) })),
272
310
  },
273
311
  opts.signal,
274
312
  );
@@ -308,29 +346,36 @@ export function configurator(opts: ConfigureOptions): Configure {
308
346
  const key = answer || known;
309
347
 
310
348
  const serviceEnv: Env = { JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL, [KEY_KEY[kind]]: key };
311
- const target = services.find((s) => serviceId(s.env) === serviceId(serviceEnv));
349
+ // 同一个地址只换了密钥:原来的服务下的模型(带着各自的设置和单价)归到新的密钥下
350
+ const rekeyed = same && sameAddress(env) && currentId !== undefined && key !== env[KEY_KEY[kind]];
351
+ const target = services.find((s) => serviceId(s.env) === serviceId(serviceEnv)) ?? (rekeyed ? services.find((s) => serviceId(s.env) === currentId) : undefined);
312
352
  const model = await chooseModel({ ...env, ...serviceEnv }, same ? current?.model : undefined, target?.models.map((m) => m.name));
313
353
  if (!model) return false;
354
+ return useModel(serviceEnv, kind, model, target, rekeyed ? currentId : undefined);
355
+ }
314
356
 
315
- // 用过的模型带上它自己的设置
316
- const saved = target?.models.find((m) => m.name === model);
317
- if (target && saved) return useSaved({ ...target, env: { ...target.env, ...pick(serviceEnv, serviceKeys(kind)) } }, saved);
318
-
319
- const updates: Env = { ...serviceEnv, [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined };
320
- // 换了服务的新模型从新服务的默认值开始:思考力度、额外请求参数各服务写法不同,限速、输出上限、
321
- // 能不能看图也是跟着服务和模型走的,沿用当前的容易错(例如免费服务的限速带到付费服务上)。
322
- // 同一个服务(只换了密钥)照旧沿用
323
- const sameService = same && sameAddress(env);
324
- if (!sameService) for (const k of MODEL_SETTINGS) updates[k] = undefined;
325
- // 其他服务常常默认只给 4096 个输出 token,带思考的模型很容易用完
326
- if (kind !== "anthropic" && !(sameService && env.JADE_MAX_TOKENS)) {
327
- const max = await ui.input({ title: "Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", initial: "32K" }, opts.signal);
328
- if (max === undefined || !tokensInput("Output limit", max)) return false;
329
- if (max) updates.JADE_MAX_TOKENS = max;
330
- }
331
- // 同一个地址只换了密钥:原来的服务下的模型归到新的密钥下
332
- const rekeyed = sameService && currentId !== undefined && key !== env[KEY_KEY[kind]];
333
- return applyConfig(updates, rekeyed ? currentId : undefined);
357
+ /** 加一个模型:选一个保存过的服务(或者新的服务),再选模型。加好了(成了当前的模型)返回 true */
358
+ async function addModel(): Promise<boolean> {
359
+ const currentId = serviceId(opts.env());
360
+ const services = sortedServices(await savedServices());
361
+ const where = await ui.select(
362
+ {
363
+ title: "Add a model from",
364
+ options: [
365
+ ...services.map((s, i) => ({ label: groupOf(s), value: `service:${i}`, hint: `${s.name ? `${describeService(s)} · ` : ""}${s.models.length} saved`, ...(serviceId(s.env) === currentId ? { current: true } : {}) })),
366
+ { label: "Another service…", value: "provider", hint: "a new base URL or API key" },
367
+ { label: "Back", value: "back" },
368
+ ],
369
+ },
370
+ opts.signal,
371
+ );
372
+ if (where === "provider") return configureProvider();
373
+ const s = where?.startsWith("service:") ? services[Number(where.slice(8))] : undefined;
374
+ if (!s) return false;
375
+ const kind = providerKind(s.env);
376
+ if (!isBuiltinKind(kind)) return false;
377
+ const model = await chooseModel(s.env, undefined, s.models.map((m) => m.name));
378
+ return model ? useModel(s.env, kind, model, s) : false;
334
379
  }
335
380
 
336
381
  /** 要配置设置的模型:title 和 kind 是显示和按服务取值用的,read 读这个模型现在的设置变量,update 写回改动 */
@@ -342,6 +387,9 @@ export function configurator(opts: ConfigureOptions): Configure {
342
387
  baseURL: string | undefined;
343
388
  read(): Promise<Env>;
344
389
  update(settings: Env): Promise<boolean>;
390
+ /** 单价只存在 models.json 里,当前的模型也一样 */
391
+ readPrice(): Promise<ModelPrice | undefined>;
392
+ writePrice(price: ModelPrice | undefined): Promise<boolean>;
345
393
  }
346
394
 
347
395
  /**
@@ -365,12 +413,17 @@ export function configurator(opts: ConfigureOptions): Configure {
365
413
  ...(kind === "anthropic" ? [{ label: "Server-side fallback", value: "fallbacks", hint: fallbacksHint(env, baseURL) }] : []),
366
414
  ...(kind === "anthropic" ? [{ label: "Send thinking settings", value: "thinking", hint: thinkingSetting(env) === false ? "off" : `on${env.JADE_THINKING ? "" : " (default)"}` }] : []),
367
415
  ...(kind === "openai-compat" ? [{ label: "Extra request body", value: "extra", hint: env.OPENAI_COMPAT_EXTRA_BODY ? shorten(env.OPENAI_COMPAT_EXTRA_BODY) : "none" }] : []),
416
+ { label: "Price", value: "price", hint: priceSummary(await target.readPrice()) },
368
417
  { label: "Back", value: "back" },
369
418
  ],
370
419
  },
371
420
  opts.signal,
372
421
  );
373
422
  if (action === undefined || action === "back") return;
423
+ if (action === "price") {
424
+ await configurePrice(target);
425
+ continue;
426
+ }
374
427
  // 每一项里按 Esc 或者输入有误:什么都不改,回到这个菜单
375
428
  if (action === "max") {
376
429
  const max = await ui.input({ title: "Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", initial: env.JADE_MAX_TOKENS ?? "32K" }, opts.signal);
@@ -380,7 +433,7 @@ export function configurator(opts: ConfigureOptions): Configure {
380
433
  const effort = await ui.select(
381
434
  {
382
435
  title: "Reasoning effort",
383
- options: [...efforts.map((e) => ({ label: e, value: e, ...(e === env.JADE_EFFORT ? { hint: "current" } : {}) })), { label: "Default", value: DEFAULT, hint: kind === "anthropic" ? "high" : "service default" }],
436
+ options: [...efforts.map((e) => ({ label: e, value: e, ...(e === env.JADE_EFFORT ? { current: true } : {}) })), { label: "Default", value: DEFAULT, hint: kind === "anthropic" ? "high" : "service default" }],
384
437
  },
385
438
  opts.signal,
386
439
  );
@@ -464,26 +517,185 @@ export function configurator(opts: ConfigureOptions): Configure {
464
517
  }
465
518
  }
466
519
 
467
- /** 把模型的设置写进 models.json 里那一个模型;.env 不变(当前用的还是原来的模型)。改回默认值的设置从 settings 里删掉 */
468
- async function writeSavedModel(service: SavedService, model: SavedModel, settings: Env): Promise<boolean> {
520
+ /**
521
+ * 改 models.json 里服务 service 的那一份(在文件里现在的内容上改:菜单打开之后 models.json 可能被别的会话改过)。
522
+ * 找不到这个服务时报告并返回 false
523
+ */
524
+ async function editSaved(service: SavedService, fn: (s: SavedService) => SavedService): Promise<boolean> {
469
525
  const id = serviceId(service.env);
470
526
  const all = await readSavedServices(modelsFile);
471
- const mine = id === undefined ? undefined : all.find((s) => serviceId(s.env) === id);
472
- if (!mine) {
527
+ const i = id === undefined ? -1 : all.findIndex((s) => serviceId(s.env) === id);
528
+ if (i === -1) {
473
529
  report(`Not saved: ${describeService(service)} is no longer in ${modelsFile}.`);
474
530
  return false;
475
531
  }
476
- const mineIndex = all.indexOf(mine);
477
- const modelIndex = mine.models.findIndex((m) => m.name === model.name);
478
- // 在文件里现在的设置上改:菜单打开之后 models.json 可能被别的会话改过
479
- const merged: Env = { ...(mine.models[modelIndex]?.settings ?? model.settings), ...pick(settings, MODEL_SETTINGS), ...blank(settings, MODEL_SETTINGS) };
480
- const next: SavedModel = { name: model.name, settings: Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined && v !== "")) as Record<string, string> };
481
- const models = modelIndex === -1 ? [next, ...mine.models] : [...mine.models.slice(0, modelIndex), next, ...mine.models.slice(modelIndex + 1)];
482
- await writeSavedServices(modelsFile, [...all.slice(0, mineIndex), { ...mine, models }, ...all.slice(mineIndex + 1)]);
483
- report(`Settings for ${model.name} (${describeService(mine)}) saved to ${modelsFile}.`);
532
+ await writeSavedServices(modelsFile, [...all.slice(0, i), fn(all[i]!), ...all.slice(i + 1)]);
484
533
  return true;
485
534
  }
486
535
 
536
+ /** 改 models.json 里服务 service 下的模型 name;文件里还没有这个模型时以 fallback 为底加上 */
537
+ const editSavedModel = (service: SavedService, fallback: SavedModel, fn: (m: SavedModel) => SavedModel) =>
538
+ editSaved(service, (s) => {
539
+ const i = s.models.findIndex((m) => m.name === fallback.name);
540
+ const next = fn(s.models[i] ?? fallback);
541
+ return { ...s, models: i === -1 ? [next, ...s.models] : [...s.models.slice(0, i), next, ...s.models.slice(i + 1)] };
542
+ });
543
+
544
+ /** 把模型的设置写进 models.json 里那一个模型;.env 不变(当前用的还是原来的模型)。改回默认值的设置从 settings 里删掉 */
545
+ async function writeSavedModel(service: SavedService, model: SavedModel, settings: Env): Promise<boolean> {
546
+ const ok = await editSavedModel(service, model, (m) => {
547
+ const merged: Env = { ...m.settings, ...pick(settings, MODEL_SETTINGS), ...blank(settings, MODEL_SETTINGS) };
548
+ return { ...m, settings: Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined && v !== "")) as Record<string, string> };
549
+ });
550
+ if (ok) report(`Settings for ${model.name} (${groupOf(service)}) saved to ${modelsFile}.`);
551
+ return ok;
552
+ }
553
+
554
+ /** 把模型的单价写进 models.json;undefined 删掉 */
555
+ async function writePrice(service: SavedService, model: SavedModel, price: ModelPrice | undefined): Promise<boolean> {
556
+ const ok = await editSavedModel(service, model, ({ price: _old, ...m }) => (price ? { ...m, price } : m));
557
+ if (ok) report(price ? `Price of ${model.name}: ${priceSummary(price)}.` : `Removed the price of ${model.name}.`);
558
+ return ok;
559
+ }
560
+
561
+ /** 保存过的模型在 models.json 里现在的样子;找不到时用 fallback 那份 */
562
+ async function savedModel(service: SavedService, fallback: SavedModel): Promise<SavedModel> {
563
+ const id = serviceId(service.env);
564
+ const mine = id === undefined ? undefined : (await readSavedServices(modelsFile)).find((s) => serviceId(s.env) === id);
565
+ return mine?.models.find((m) => m.name === fallback.name) ?? fallback;
566
+ }
567
+
568
+ /** 规则的价格在菜单里的样子:"50% of the base price",或者 "in ¥0.5 · out ¥2" */
569
+ function ruleHint(rule: PriceRule, currency: Currency): string {
570
+ if (rule.scale !== undefined) return `${formatRulePrices(rule)} of the base price`;
571
+ const s = symbol(currency);
572
+ const names = { input: "in", output: "out", cacheRead: "cache read", cacheWrite: "cache write" } as const;
573
+ return (Object.keys(names) as (keyof typeof names)[]).flatMap((k) => (rule[k] === undefined ? [] : [`${names[k]} ${s}${rule[k]}`])).join(" · ");
574
+ }
575
+
576
+ const WHEN_TITLE =
577
+ "When it applies: times like 00:30-08:30 (may cross midnight; several like 09:00-12:00,14:00-18:00), days like mon-fri or sat,sun, dates like 2026-12-01..2026-12-31, and a time zone like UTC+8 or Asia/Shanghai (default: this computer's). Any of them, in any order";
578
+ const RULE_PRICE_TITLE = 'Price at those times: a share of the base price like 50%, or input output [cache read] [cache write] per million tokens ("-" keeps the base price)';
579
+
580
+ /** 问一条规则的时间和价格(编辑时预填 rule 的);Esc 或写错时 undefined */
581
+ async function askRule(rule?: PriceRule): Promise<PriceRule | undefined> {
582
+ const whenText = await ui.input({ title: WHEN_TITLE, initial: rule ? formatWhen(rule) : "", placeholder: "00:30-08:30 UTC+8" }, opts.signal);
583
+ if (whenText === undefined) return undefined;
584
+ let when: PriceRule;
585
+ try {
586
+ when = parseWhen(whenText);
587
+ } catch (err) {
588
+ report(errorText(err));
589
+ return undefined;
590
+ }
591
+ if (Object.keys(when).length === 0) {
592
+ report("Write when the price applies, for example 00:30-08:30 or sat,sun.");
593
+ return undefined;
594
+ }
595
+ const pricesText = await ui.input({ title: RULE_PRICE_TITLE, initial: rule ? formatRulePrices(rule) : "", placeholder: "50%" }, opts.signal);
596
+ if (pricesText === undefined) return undefined;
597
+ try {
598
+ return { ...when, ...parseRulePrices(pricesText) };
599
+ } catch (err) {
600
+ report(errorText(err));
601
+ return undefined;
602
+ }
603
+ }
604
+
605
+ /**
606
+ * 一个模型的单价:货币、基础价和按时间的规则(从上往下第一条符合的算数)。
607
+ * 改完一项回到这个菜单;Back 或 Esc 离开
608
+ */
609
+ async function configurePrice(target: SettingsTarget) {
610
+ while (true) {
611
+ const p = await target.readPrice();
612
+ const rules = p?.rules ?? [];
613
+ const action = await ui.select(
614
+ {
615
+ title: `Price of ${target.title} per million tokens`,
616
+ options: [
617
+ { label: "Base price", value: "base", hint: p ? `${symbol(p.currency)} ${formatRates(p)} (input output cache-read cache-write)` : "not set" },
618
+ ...(p ? [{ label: "Currency", value: "currency", hint: `${p.currency} (${symbol(p.currency)})` }] : []),
619
+ ...rules.map((r, i) => ({ label: formatWhen(r), value: `rule:${i}`, hint: ruleHint(r, p!.currency), group: "Time-based prices (the first that matches applies)" })),
620
+ ...(p ? [{ label: "Add a time-based price…", value: "add", hint: "off-peak, weekend or promotional prices" }] : []),
621
+ ...(p ? [{ label: "Remove the price", value: "clear" }] : []),
622
+ { label: "Back", value: "back" },
623
+ ],
624
+ },
625
+ opts.signal,
626
+ );
627
+ if (action === undefined || action === "back") return;
628
+ if (action === "base") {
629
+ // 第一次填时先选货币
630
+ const currency = p?.currency ?? (await chooseCurrency());
631
+ if (!currency) continue;
632
+ const text = await ui.input(
633
+ {
634
+ title: `Price per million tokens in ${currency}: input output [cache read] [cache write], e.g. 3 15 0.3 3.75 (cache prices default to the input price${p ? "; empty removes the price" : ""})`,
635
+ initial: p ? formatRates(p) : "",
636
+ },
637
+ opts.signal,
638
+ );
639
+ if (text === undefined) continue;
640
+ if (!text.trim()) {
641
+ if (p) await target.writePrice(undefined);
642
+ continue;
643
+ }
644
+ try {
645
+ const r = parseRates(text, false);
646
+ const { cacheRead: _r, cacheWrite: _w, ...rest } = p ?? { currency, input: 0, output: 0 };
647
+ await target.writePrice({ ...rest, currency, input: r.input!, output: r.output!, ...(r.cacheRead !== undefined ? { cacheRead: r.cacheRead } : {}), ...(r.cacheWrite !== undefined ? { cacheWrite: r.cacheWrite } : {}) });
648
+ } catch (err) {
649
+ report(errorText(err));
650
+ }
651
+ } else if (action === "currency" && p) {
652
+ const currency = await chooseCurrency(p.currency);
653
+ if (currency && currency !== p.currency) await target.writePrice({ ...p, currency });
654
+ } else if (action === "add" && p) {
655
+ const rule = await askRule();
656
+ if (rule) await target.writePrice({ ...p, rules: [...rules, rule] });
657
+ } else if (action === "clear" && p) {
658
+ await target.writePrice(undefined);
659
+ } else if (action.startsWith("rule:") && p) {
660
+ const i = Number(action.slice(5));
661
+ const rule = rules[i];
662
+ if (!rule) continue;
663
+ const what = await ui.select(
664
+ {
665
+ title: `${formatWhen(rule)}: ${ruleHint(rule, p.currency)}`,
666
+ options: [
667
+ { label: "Edit…", value: "edit" },
668
+ ...(i > 0 ? [{ label: "Move up", value: "up", hint: "rules higher up win" }] : []),
669
+ { label: "Remove", value: "remove" },
670
+ { label: "Back", value: "back" },
671
+ ],
672
+ },
673
+ opts.signal,
674
+ );
675
+ const next = [...rules];
676
+ if (what === "edit") {
677
+ const edited = await askRule(rule);
678
+ if (!edited) continue;
679
+ next[i] = edited;
680
+ } else if (what === "up") next.splice(i - 1, 2, rule, rules[i - 1]!);
681
+ else if (what === "remove") next.splice(i, 1);
682
+ else continue;
683
+ const { rules: _old, ...rest } = p;
684
+ await target.writePrice(next.length ? { ...rest, rules: next } : rest);
685
+ }
686
+ }
687
+ }
688
+
689
+ async function chooseCurrency(current?: Currency): Promise<Currency | undefined> {
690
+ return ui.select(
691
+ {
692
+ title: "Currency of the prices",
693
+ options: CURRENCIES.map((c) => ({ label: c, value: c, hint: symbol(c), ...(c === current ? { current: true } : {}) })),
694
+ },
695
+ opts.signal,
696
+ );
697
+ }
698
+
487
699
  /** 把保存过的模型从 models.json 里删掉;服务下没有模型了就连服务(和它的密钥)一起删掉 */
488
700
  async function forgetModel(service: SavedService, model: SavedModel): Promise<void> {
489
701
  const id = serviceId(service.env);
@@ -492,30 +704,58 @@ export function configurator(opts: ConfigureOptions): Configure {
492
704
  .map((s) => (serviceId(s.env) === id ? { ...s, models: s.models.filter((m) => m.name !== model.name) } : s))
493
705
  .filter((s) => s.models.length > 0);
494
706
  await writeSavedServices(modelsFile, rest);
495
- report(`Removed ${model.name} (${describeService(service)}).`);
707
+ report(`Removed ${model.name} (${groupOf(service)}).`);
708
+ }
709
+
710
+ /** 给服务起名字(/model 里按它分组);空的回到默认的类型和主机名 */
711
+ async function renameService(service: SavedService): Promise<void> {
712
+ const text = await ui.input({ title: `Name for this service, e.g. DeepSeek (empty for ${describeService(service)})`, initial: service.name ?? "" }, opts.signal);
713
+ if (text === undefined) return;
714
+ const name = text.trim();
715
+ if (await editSaved(service, ({ name: _old, ...s }) => (name ? { name, ...s } : s))) report(name ? `Renamed ${describeService(service)} to ${name}.` : `${describeService(service)} has no name now.`);
716
+ }
717
+
718
+ /** 主菜单和管理菜单里一个模型的选项:分组是它的服务 */
719
+ function entryOption(e: Entry, value: string, env: Env) {
720
+ const settings = e.current ? pick(env, MODEL_SETTINGS) : e.model.settings;
721
+ const kind = providerKind(e.service.env);
722
+ const parts = [settingsSummary(settings, kind, contextWindow(e.model.name, settings)), e.model.price ? priceSummary(e.model.price) : ""];
723
+ return { label: e.model.name, value, hint: parts.filter(Boolean).join(" · "), group: groupOf(e.service), ...(e.current ? { current: true } : {}) };
724
+ }
725
+
726
+ /** 全部模型(当前的那个的设置以 .env 为准) */
727
+ async function entries(): Promise<Entry[]> {
728
+ const env = opts.env();
729
+ const kind = providerKind(env);
730
+ const info = providerInfo(env);
731
+ return allModels(await savedServices(), serviceId(env), info.model, () => ({
732
+ service: { env: isBuiltinKind(kind) ? { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind } : { JADE_PROVIDER: kind }, models: [] },
733
+ model: { name: info.model, settings: pick(env, MODEL_SETTINGS) },
734
+ current: true,
735
+ }));
496
736
  }
497
737
 
498
738
  /**
499
- * 选中主菜单里一个模型后:切换、配置它(不用先切到它)、把它删掉或返回主菜单。
500
- * 当前的模型只能配置(切换没意义;删掉了下次进 /model 又会被记回来)。从设置里出来回到这个菜单;
501
- * 切换、删除、Back 或 Esc 回到主菜单
739
+ * 管理菜单里选中一个模型后:设置(含单价)、服务的名字、删掉它。当前的模型不能删(删掉了下次进 /model 又会被记回来)。
740
+ * 从设置里出来回到这个菜单;删除、Back 或 Esc 回到管理菜单
502
741
  */
503
- async function pickModelAction(o: { service: SavedService; model: SavedModel }, isCurrent: boolean): Promise<void> {
504
- const kind = providerKind(o.service.env);
742
+ async function pickModelAction(e: Entry): Promise<void> {
743
+ const kind = providerKind(e.service.env);
505
744
  // 当前的模型改 .env 就好——applyConfig 里的 remember 会把改完的 .env 写回 models.json;
506
- // 其他保存过的模型只改 models.json 里的那一个
507
- const read = isCurrent ? async () => pick(opts.env(), MODEL_SETTINGS) : () => savedSettings(o.service, o.model);
745
+ // 其他保存过的模型只改 models.json 里的那一个。单价都只在 models.json 里
746
+ const read = e.current ? async () => pick(opts.env(), MODEL_SETTINGS) : async () => (await savedModel(e.service, e.model)).settings;
747
+ const saved = serviceId(e.service.env) !== undefined && e.service.models.length > 0;
508
748
  while (true) {
509
749
  const settings = await read();
750
+ const model = await savedModel(e.service, e.model);
751
+ const service = (await savedServices()).find((s) => serviceId(s.env) === serviceId(e.service.env)) ?? e.service;
510
752
  const action = await ui.select(
511
753
  {
512
- title: o.model.name,
754
+ title: `${e.model.name} (${groupOf(service)})`,
513
755
  options: [
514
- ...(isCurrent
515
- ? []
516
- : [{ label: "Switch to it", value: "switch", hint: serviceId(o.service.env) === serviceId(opts.env()) ? "this service" : describeService(o.service) }]),
517
- { label: "Settings…", value: "settings", hint: settingsSummary(settings, kind, contextWindow(o.model.name, settings)) },
518
- ...(isCurrent ? [] : [{ label: "Remove", value: "forget" }]),
756
+ { label: "Settings…", value: "settings", hint: [settingsSummary(settings, kind, contextWindow(e.model.name, settings)), model.price ? priceSummary(model.price) : ""].filter(Boolean).join(" · ") },
757
+ ...(saved ? [{ label: "Service name…", value: "rename", hint: service.name ?? `not set (${describeService(service)})` }] : []),
758
+ ...(e.current ? [] : [{ label: "Remove", value: "forget" }]),
519
759
  { label: "Back", value: "back" },
520
760
  ],
521
761
  },
@@ -523,27 +763,39 @@ export function configurator(opts: ConfigureOptions): Configure {
523
763
  );
524
764
  if (action === "settings") {
525
765
  await configureSettings({
526
- title: o.model.name,
766
+ title: e.model.name,
527
767
  kind,
528
- model: o.model.name,
529
- baseURL: providerInfo(o.service.env).baseURL,
768
+ model: e.model.name,
769
+ baseURL: providerInfo(e.service.env).baseURL,
530
770
  read,
531
- update: (updates) => (isCurrent ? applyConfig(updates) : writeSavedModel(o.service, o.model, updates)),
771
+ update: (updates) => (e.current ? applyConfig(updates) : writeSavedModel(e.service, e.model, updates)),
772
+ readPrice: async () => (saved ? (await savedModel(e.service, e.model)).price : undefined),
773
+ writePrice: (price) => (saved ? writePrice(e.service, e.model, price) : (report(`${e.model.name} is not saved in ${modelsFile}, so it cannot have a price.`), Promise.resolve(false))),
532
774
  });
533
775
  continue;
534
776
  }
535
- // 用刚读到的设置切换:在这个菜单里改过的也带上
536
- if (action === "switch") await useSaved(o.service, { ...o.model, settings });
537
- else if (action === "forget") await forgetModel(o.service, o.model);
777
+ if (action === "rename") {
778
+ await renameService(service);
779
+ continue;
780
+ }
781
+ if (action === "forget") await forgetModel(e.service, e.model);
538
782
  return;
539
783
  }
540
784
  }
541
785
 
542
- /** 保存过的模型在 models.json 里现在的设置;找不到时用 fallback 那份 */
543
- async function savedSettings(service: SavedService, fallback: SavedModel): Promise<Record<string, string>> {
544
- const id = serviceId(service.env);
545
- const mine = id === undefined ? undefined : (await readSavedServices(modelsFile)).find((s) => serviceId(s.env) === id);
546
- return mine?.models.find((m) => m.name === fallback.name)?.settings ?? fallback.settings;
786
+ /** 管理菜单:和主菜单一样分组列出全部模型,选中一个改它的设置、单价、服务的名字或删掉它。Back 或 Esc 回到主菜单 */
787
+ async function manageModels(): Promise<void> {
788
+ while (true) {
789
+ const env = opts.env();
790
+ const list = await entries();
791
+ const action = await ui.select(
792
+ { title: "Manage models", options: [...list.map((e, i) => entryOption(e, `model:${i}`, env)), { label: "Back", value: "back" }] },
793
+ opts.signal,
794
+ );
795
+ const e = action?.startsWith("model:") ? list[Number(action.slice(6))] : undefined;
796
+ if (!e) return;
797
+ await pickModelAction(e);
798
+ }
547
799
  }
548
800
 
549
801
  async function configureModel(arg: string | undefined) {
@@ -554,67 +806,34 @@ export function configurator(opts: ConfigureOptions): Configure {
554
806
  await remember().catch(() => {});
555
807
  if (arg) {
556
808
  // 保存过的模型按名字切换(当前服务的优先),否则换当前服务的模型
557
- const saved = otherModels(await savedServices(), serviceId(env), providerInfo(env).model).find((o) => o.model.name === arg);
809
+ const list = (await entries()).filter((e) => !e.current && e.model.name === arg);
810
+ const saved = list.find((e) => serviceId(e.service.env) === serviceId(env)) ?? list[0];
558
811
  return void (await (saved ? useSaved(saved.service, saved.model) : switchModel(arg)));
559
812
  }
560
- // 主菜单循环:保存过的模型全部直接列出(当前的在最前,然后是同一服务的),选中出一个子菜单
561
- // (切换 / 设置 / 删除 / 返回);配置某个模型、把它删掉都不用先切到它,做完回到主菜单再选。
562
- // 每一轮都重读当前配置:切换、配置之后模型和它的设置可能都变了
813
+ // 主菜单:保存过的模型按服务分组全部列出,回车就切换到它(选当前的什么都不做),然后结束 /model。
814
+ // 加模型、管理模型做完回到这里;每一轮都重读:配置之后模型和它的设置可能都变了
563
815
  while (true) {
564
816
  const env = opts.env();
565
- const id = serviceId(env);
566
- const kind = providerKind(env);
567
- const kindKnown = isBuiltinKind(kind);
568
- const info = providerInfo(env);
569
- const here = describeService({ env: kindKnown ? pick(env, serviceKeys(kind as ProviderKind)) : {}, models: [] });
570
- const services = await savedServices();
571
- const multi = services.length > 1;
572
- const others = otherModels(services, id, info.model);
817
+ const list = await entries();
573
818
  const action = await ui.select(
574
819
  {
575
820
  title: "Switch model",
576
821
  options: [
577
- {
578
- label: info.model,
579
- value: "current",
580
- hint: `${multi ? `${here} · ` : ""}current · ${settingsSummary(env, info.kind, contextWindow(info.model, env))}`,
581
- },
582
- ...others.map((o, i) => ({
583
- label: o.model.name,
584
- value: `saved:${i}`,
585
- hint: `${multi ? `${describeService(o.service)} · ` : ""}${settingsSummary(o.model.settings, providerKind(o.service.env), contextWindow(o.model.name, o.model.settings))}`,
586
- })),
587
- { label: "Add a model…", value: "add", hint: "from this service or another one" },
822
+ ...list.map((e, i) => entryOption(e, `model:${i}`, env)),
823
+ { label: "Add a model…", value: "add", hint: "from a saved service or a new one" },
824
+ { label: "Manage models…", value: "manage", hint: "settings, prices, service names, remove" },
588
825
  ],
589
826
  },
590
827
  opts.signal,
591
828
  );
592
829
  if (action === undefined) return; // Esc:整个 /model 结束
593
- if (action === "current") {
594
- const service = { env: kindKnown ? { ...pick(env, serviceKeys(kind as ProviderKind)), JADE_PROVIDER: kind } : { JADE_PROVIDER: kind }, models: [] };
595
- await pickModelAction({ service, model: { name: info.model, settings: pick(env, MODEL_SETTINGS) } }, true);
596
- } else if (action.startsWith("saved:")) {
597
- const o = others[Number(action.slice(6))];
598
- if (o) await pickModelAction(o, false);
599
- } else if (action === "add") {
600
- const where = await ui.select(
601
- {
602
- title: "Add a model from",
603
- options: [
604
- { label: "This service", value: "model", hint: here },
605
- { label: "Another service…", value: "provider", hint: "or change this one's base URL / API key" },
606
- { label: "Back", value: "back" },
607
- ],
608
- },
609
- opts.signal,
610
- );
611
- // 做完、Back、Esc 或没填完,都回到主菜单
612
- if (where === "model") {
613
- const saved = services.find((s) => serviceId(s.env) === id)?.models.map((m) => m.name);
614
- const model = await chooseModel(env, info.model, saved);
615
- if (model && model !== info.model) await switchModel(model);
616
- } else if (where === "provider") await configureProvider();
830
+ if (action.startsWith("model:")) {
831
+ const e = list[Number(action.slice(6))];
832
+ if (e && !e.current) await useSaved(e.service, e.model);
833
+ return;
617
834
  }
835
+ if (action === "add" && (await addModel())) return;
836
+ if (action === "manage") await manageModels();
618
837
  }
619
838
  }
620
839