@uncarved/jade 0.5.0 → 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 (86) hide show
  1. package/README.md +320 -317
  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/dist/membrane.d.ts +5 -2
  7. package/dist/membrane.js +8 -3
  8. package/dist/membrane.js.map +1 -1
  9. package/dist/session.d.ts +10 -1
  10. package/dist/session.js +110 -16
  11. package/dist/session.js.map +1 -1
  12. package/package.json +6 -6
  13. package/plugins/approval/index.ts +129 -13
  14. package/plugins/approval/plugin.json +4 -1
  15. package/plugins/approval/policy.ts +127 -7
  16. package/plugins/approval/review.ts +188 -45
  17. package/plugins/ask/index.ts +29 -1
  18. package/plugins/budget/index.ts +44 -6
  19. package/plugins/budget/plugin.json +1 -2
  20. package/plugins/compact/compact.ts +153 -39
  21. package/plugins/compact/index.ts +39 -5
  22. package/plugins/compact/plugin.json +5 -2
  23. package/plugins/cost/cache.ts +114 -0
  24. package/plugins/cost/index.ts +109 -51
  25. package/plugins/cost/plugin.json +3 -2
  26. package/plugins/memory/memory.ts +51 -28
  27. package/plugins/models/configure.ts +344 -125
  28. package/plugins/models/index.ts +44 -9
  29. package/plugins/models/price.ts +291 -0
  30. package/plugins/models/provider.ts +40 -8
  31. package/plugins/models/saved.ts +20 -4
  32. package/plugins/modes/index.ts +3 -4
  33. package/plugins/prompts/prompts.ts +5 -1
  34. package/plugins/serve/index.ts +7 -0
  35. package/plugins/task/index.ts +31 -10
  36. package/plugins/task/plugin.json +5 -2
  37. package/plugins/task/subagent.ts +21 -4
  38. package/plugins/todo/index.ts +62 -1
  39. package/plugins/todo/plugin.json +1 -1
  40. package/plugins/tui/frontend.ts +31 -5
  41. package/plugins/tui/index.ts +2 -1
  42. package/plugins/tui/plugin.json +1 -1
  43. package/plugins/tui/screen.ts +17 -5
  44. package/plugins/tui/transcript.ts +518 -507
  45. package/plugins/tui/tui.ts +212 -54
  46. package/plugins/withdraw/index.ts +111 -0
  47. package/plugins/withdraw/plugin.json +8 -0
  48. package/plugins-dist/approval/index.js +103 -9
  49. package/plugins-dist/approval/plugin.json +4 -1
  50. package/plugins-dist/approval/policy.js +112 -9
  51. package/plugins-dist/approval/review.js +141 -34
  52. package/plugins-dist/ask/index.js +28 -2
  53. package/plugins-dist/budget/index.js +30 -7
  54. package/plugins-dist/budget/plugin.json +1 -2
  55. package/plugins-dist/compact/compact.js +106 -32
  56. package/plugins-dist/compact/index.js +27 -3
  57. package/plugins-dist/compact/plugin.json +6 -2
  58. package/plugins-dist/cost/cache.js +100 -0
  59. package/plugins-dist/cost/index.js +87 -38
  60. package/plugins-dist/cost/plugin.json +5 -2
  61. package/plugins-dist/memory/memory.js +51 -32
  62. package/plugins-dist/models/configure.js +285 -105
  63. package/plugins-dist/models/index.js +33 -2
  64. package/plugins-dist/models/price.js +244 -0
  65. package/plugins-dist/models/provider.js +22 -4
  66. package/plugins-dist/models/saved.js +13 -3
  67. package/plugins-dist/modes/index.js +2 -3
  68. package/plugins-dist/prompts/prompts.js +5 -1
  69. package/plugins-dist/serve/index.js +6 -0
  70. package/plugins-dist/task/index.js +25 -7
  71. package/plugins-dist/task/plugin.json +5 -2
  72. package/plugins-dist/task/subagent.js +15 -6
  73. package/plugins-dist/todo/index.js +50 -0
  74. package/plugins-dist/todo/plugin.json +1 -1
  75. package/plugins-dist/tui/frontend.js +26 -4
  76. package/plugins-dist/tui/index.js +2 -1
  77. package/plugins-dist/tui/plugin.json +2 -1
  78. package/plugins-dist/tui/screen.js +7 -3
  79. package/plugins-dist/tui/transcript.js +13 -5
  80. package/plugins-dist/tui/tui.js +197 -50
  81. package/plugins-dist/withdraw/index.js +88 -0
  82. package/plugins-dist/withdraw/plugin.json +12 -0
  83. package/src/api.ts +1 -1
  84. package/src/install.ts +5 -0
  85. package/src/membrane.ts +8 -3
  86. package/src/session.ts +124 -20
@@ -1,6 +1,7 @@
1
1
  import { readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { hasProvider, parseTokens } from "./config.js";
3
3
  import { contextWindow } from "./context.js";
4
+ import { CURRENCIES, formatRates, formatRulePrices, formatWhen, parseRates, parseRulePrices, parseWhen, priceSummary, symbol } from "./price.js";
4
5
  import { EFFORTS, fallbacksFromEnv, isBuiltinKind, isOfficialAnthropic, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, thinkingFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
5
6
  import { MODEL_SETTINGS, readSavedServices, updateEnvFile, writeSavedServices } from "./saved.js";
6
7
  const PROVIDERS = [
@@ -76,8 +77,12 @@ function describeService(service) {
76
77
  } catch {}
77
78
  return [i.kind, host].filter(Boolean).join(" · ");
78
79
  }
79
- function otherModels(services, currentId, currentModel) {
80
- return [...services.filter((s) => serviceId(s.env) === currentId), ...services.filter((s) => serviceId(s.env) !== currentId)].flatMap((s) => s.models.filter((m) => !(serviceId(s.env) === currentId && m.name === currentModel)).map((m) => ({ service: s, model: m })));
80
+ const groupOf = (s) => s.name ?? describeService(s);
81
+ const byName = (a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" });
82
+ const sortedServices = (services) => [...services].sort((a, b) => byName(groupOf(a), groupOf(b)));
83
+ function allModels(services, currentId, currentModel, current) {
84
+ const list = sortedServices(services).flatMap((s) => [...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 })));
85
+ return list.some((e) => e.current) ? list : [current(), ...list];
81
86
  }
82
87
  const ANTHROPIC_DEFAULT_MAX_TOKENS = 64000;
83
88
  const shorten = (text, max = 40) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
@@ -122,9 +127,12 @@ export function configurator(opts) {
122
127
  return sid !== undefined && (sid === id || replacing !== undefined && sid === replacing);
123
128
  });
124
129
  const models = old.flatMap((s) => s.models).filter((m, i, list) => m.name !== model && list.findIndex((x) => x.name === m.name) === i);
130
+ const price = old.flatMap((s) => s.models).find((m) => m.name === model)?.price;
131
+ const name = old.find((s) => s.name)?.name;
125
132
  const service = {
133
+ ...name ? { name } : {},
126
134
  env: { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind },
127
- models: [{ name: model, settings: pick(env, MODEL_SETTINGS) }, ...models]
135
+ models: [{ name: model, settings: pick(env, MODEL_SETTINGS), ...price ? { price } : {} }, ...models]
128
136
  };
129
137
  await writeSavedServices(modelsFile, [service, ...all.filter((s) => !old.includes(s))]);
130
138
  }
@@ -145,7 +153,7 @@ export function configurator(opts) {
145
153
  report(`Model: ${info.model} (${info.kind}${info.baseURL ? `, ${info.baseURL}` : ""}). Saved to ${envFile}.`);
146
154
  return true;
147
155
  }
148
- function useSaved(s, m) {
156
+ function useSaved(s, m, replacing) {
149
157
  const kind = providerKind(s.env);
150
158
  if (!isBuiltinKind(kind)) {
151
159
  report(`The saved service ${describeService(s)} is not one of the built-in providers.`);
@@ -158,21 +166,33 @@ export function configurator(opts) {
158
166
  updates[k] = m.settings[k];
159
167
  updates.JADE_PROVIDER = kind;
160
168
  updates[MODEL_KEY[kind]] = m.name;
161
- return applyConfig(updates);
169
+ return applyConfig(updates, replacing);
170
+ }
171
+ async function useModel(serviceEnv, kind, model, from, replacing) {
172
+ const saved = from?.models.find((m) => m.name === model);
173
+ if (from && saved)
174
+ return useSaved({ ...from, env: { ...from.env, ...pick(serviceEnv, serviceKeys(kind)) } }, saved, replacing);
175
+ const updates = { ...pick(serviceEnv, serviceKeys(kind)), JADE_PROVIDER: kind, [MODEL_KEY[kind]]: model };
176
+ for (const k of MODEL_SETTINGS)
177
+ updates[k] = undefined;
178
+ if (kind !== "anthropic" && ui.interactive) {
179
+ 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);
180
+ if (max === undefined || !tokensInput("Output limit", max))
181
+ return false;
182
+ if (max)
183
+ updates.JADE_MAX_TOKENS = max;
184
+ }
185
+ return applyConfig(updates, replacing);
162
186
  }
163
187
  async function switchModel(model) {
164
188
  const env = opts.env();
165
- const id = serviceId(env);
166
- const service = (await savedServices()).find((s) => serviceId(s.env) === id);
167
- const saved = service?.models.find((m) => m.name === model);
168
- if (service && saved)
169
- return useSaved(service, saved);
170
189
  const kind = providerKind(env);
171
190
  if (!isBuiltinKind(kind)) {
172
191
  report(`JADE_PROVIDER must be one of ${PROVIDERS.map((p) => p.kind).join(", ")}; set the model in ${envFile}.`);
173
192
  return false;
174
193
  }
175
- return applyConfig({ [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined });
194
+ const id = serviceId(env);
195
+ return useModel(env, kind, model, (await savedServices()).find((s) => serviceId(s.env) === id));
176
196
  }
177
197
  async function chooseModel(env, current, saved = []) {
178
198
  const models = await listModels(env, opts.fetch);
@@ -181,7 +201,7 @@ export function configurator(opts) {
181
201
  const OTHER = "\x00other";
182
202
  const picked = await ui.select({
183
203
  title: "Choose a model",
184
- 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 }]
204
+ 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 }]
185
205
  }, opts.signal);
186
206
  if (picked === BACK)
187
207
  return;
@@ -196,7 +216,7 @@ export function configurator(opts) {
196
216
  const currentId = hasProvider(env) ? serviceId(env) : undefined;
197
217
  const kindName = await ui.select({
198
218
  title: "Which service should jade use?",
199
- options: PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.kind === current?.kind ? `${p.hint} · current` : p.hint }))
219
+ options: PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.hint, ...p.kind === current?.kind ? { current: true } : {} }))
200
220
  }, opts.signal);
201
221
  if (!kindName || !isBuiltinKind(kindName))
202
222
  return false;
@@ -228,27 +248,34 @@ export function configurator(opts) {
228
248
  return false;
229
249
  const key = answer || known;
230
250
  const serviceEnv = { JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL, [KEY_KEY[kind]]: key };
231
- const target = services.find((s) => serviceId(s.env) === serviceId(serviceEnv));
251
+ const rekeyed = same && sameAddress(env) && currentId !== undefined && key !== env[KEY_KEY[kind]];
252
+ const target = services.find((s) => serviceId(s.env) === serviceId(serviceEnv)) ?? (rekeyed ? services.find((s) => serviceId(s.env) === currentId) : undefined);
232
253
  const model = await chooseModel({ ...env, ...serviceEnv }, same ? current?.model : undefined, target?.models.map((m) => m.name));
233
254
  if (!model)
234
255
  return false;
235
- const saved = target?.models.find((m) => m.name === model);
236
- if (target && saved)
237
- return useSaved({ ...target, env: { ...target.env, ...pick(serviceEnv, serviceKeys(kind)) } }, saved);
238
- const updates = { ...serviceEnv, [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined };
239
- const sameService = same && sameAddress(env);
240
- if (!sameService)
241
- for (const k of MODEL_SETTINGS)
242
- updates[k] = undefined;
243
- if (kind !== "anthropic" && !(sameService && env.JADE_MAX_TOKENS)) {
244
- 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);
245
- if (max === undefined || !tokensInput("Output limit", max))
246
- return false;
247
- if (max)
248
- updates.JADE_MAX_TOKENS = max;
249
- }
250
- const rekeyed = sameService && currentId !== undefined && key !== env[KEY_KEY[kind]];
251
- return applyConfig(updates, rekeyed ? currentId : undefined);
256
+ return useModel(serviceEnv, kind, model, target, rekeyed ? currentId : undefined);
257
+ }
258
+ async function addModel() {
259
+ const currentId = serviceId(opts.env());
260
+ const services = sortedServices(await savedServices());
261
+ const where = await ui.select({
262
+ title: "Add a model from",
263
+ options: [
264
+ ...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 } : {} })),
265
+ { label: "Another service…", value: "provider", hint: "a new base URL or API key" },
266
+ { label: "Back", value: "back" }
267
+ ]
268
+ }, opts.signal);
269
+ if (where === "provider")
270
+ return configureProvider();
271
+ const s = where?.startsWith("service:") ? services[Number(where.slice(8))] : undefined;
272
+ if (!s)
273
+ return false;
274
+ const kind = providerKind(s.env);
275
+ if (!isBuiltinKind(kind))
276
+ return false;
277
+ const model = await chooseModel(s.env, undefined, s.models.map((m) => m.name));
278
+ return model ? useModel(s.env, kind, model, s) : false;
252
279
  }
253
280
  async function configureSettings(target) {
254
281
  const { title, kind, model, baseURL } = target;
@@ -266,11 +293,16 @@ export function configurator(opts) {
266
293
  ...kind === "anthropic" ? [{ label: "Server-side fallback", value: "fallbacks", hint: fallbacksHint(env, baseURL) }] : [],
267
294
  ...kind === "anthropic" ? [{ label: "Send thinking settings", value: "thinking", hint: thinkingSetting(env) === false ? "off" : `on${env.JADE_THINKING ? "" : " (default)"}` }] : [],
268
295
  ...kind === "openai-compat" ? [{ label: "Extra request body", value: "extra", hint: env.OPENAI_COMPAT_EXTRA_BODY ? shorten(env.OPENAI_COMPAT_EXTRA_BODY) : "none" }] : [],
296
+ { label: "Price", value: "price", hint: priceSummary(await target.readPrice()) },
269
297
  { label: "Back", value: "back" }
270
298
  ]
271
299
  }, opts.signal);
272
300
  if (action === undefined || action === "back")
273
301
  return;
302
+ if (action === "price") {
303
+ await configurePrice(target);
304
+ continue;
305
+ }
274
306
  if (action === "max") {
275
307
  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);
276
308
  if (max !== undefined && tokensInput("Output limit", max))
@@ -279,7 +311,7 @@ export function configurator(opts) {
279
311
  const DEFAULT = "\x00default";
280
312
  const effort = await ui.select({
281
313
  title: "Reasoning effort",
282
- options: [...efforts.map((e) => ({ label: e, value: e, ...e === env.JADE_EFFORT ? { hint: "current" } : {} })), { label: "Default", value: DEFAULT, hint: kind === "anthropic" ? "high" : "service default" }]
314
+ options: [...efforts.map((e) => ({ label: e, value: e, ...e === env.JADE_EFFORT ? { current: true } : {} })), { label: "Default", value: DEFAULT, hint: kind === "anthropic" ? "high" : "service default" }]
283
315
  }, opts.signal);
284
316
  if (effort !== undefined)
285
317
  await target.update({ JADE_EFFORT: effort === DEFAULT ? undefined : effort });
@@ -355,67 +387,243 @@ export function configurator(opts) {
355
387
  }
356
388
  }
357
389
  }
358
- async function writeSavedModel(service, model, settings) {
390
+ async function editSaved(service, fn) {
359
391
  const id = serviceId(service.env);
360
392
  const all = await readSavedServices(modelsFile);
361
- const mine = id === undefined ? undefined : all.find((s) => serviceId(s.env) === id);
362
- if (!mine) {
393
+ const i = id === undefined ? -1 : all.findIndex((s) => serviceId(s.env) === id);
394
+ if (i === -1) {
363
395
  report(`Not saved: ${describeService(service)} is no longer in ${modelsFile}.`);
364
396
  return false;
365
397
  }
366
- const mineIndex = all.indexOf(mine);
367
- const modelIndex = mine.models.findIndex((m) => m.name === model.name);
368
- const merged = { ...mine.models[modelIndex]?.settings ?? model.settings, ...pick(settings, MODEL_SETTINGS), ...blank(settings, MODEL_SETTINGS) };
369
- const next = { name: model.name, settings: Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined && v !== "")) };
370
- const models = modelIndex === -1 ? [next, ...mine.models] : [...mine.models.slice(0, modelIndex), next, ...mine.models.slice(modelIndex + 1)];
371
- await writeSavedServices(modelsFile, [...all.slice(0, mineIndex), { ...mine, models }, ...all.slice(mineIndex + 1)]);
372
- report(`Settings for ${model.name} (${describeService(mine)}) saved to ${modelsFile}.`);
398
+ await writeSavedServices(modelsFile, [...all.slice(0, i), fn(all[i]), ...all.slice(i + 1)]);
373
399
  return true;
374
400
  }
401
+ const editSavedModel = (service, fallback, fn) => editSaved(service, (s) => {
402
+ const i = s.models.findIndex((m) => m.name === fallback.name);
403
+ const next = fn(s.models[i] ?? fallback);
404
+ return { ...s, models: i === -1 ? [next, ...s.models] : [...s.models.slice(0, i), next, ...s.models.slice(i + 1)] };
405
+ });
406
+ async function writeSavedModel(service, model, settings) {
407
+ const ok = await editSavedModel(service, model, (m) => {
408
+ const merged = { ...m.settings, ...pick(settings, MODEL_SETTINGS), ...blank(settings, MODEL_SETTINGS) };
409
+ return { ...m, settings: Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined && v !== "")) };
410
+ });
411
+ if (ok)
412
+ report(`Settings for ${model.name} (${groupOf(service)}) saved to ${modelsFile}.`);
413
+ return ok;
414
+ }
415
+ async function writePrice(service, model, price) {
416
+ const ok = await editSavedModel(service, model, ({ price: _old, ...m }) => price ? { ...m, price } : m);
417
+ if (ok)
418
+ report(price ? `Price of ${model.name}: ${priceSummary(price)}.` : `Removed the price of ${model.name}.`);
419
+ return ok;
420
+ }
421
+ async function savedModel(service, fallback) {
422
+ const id = serviceId(service.env);
423
+ const mine = id === undefined ? undefined : (await readSavedServices(modelsFile)).find((s) => serviceId(s.env) === id);
424
+ return mine?.models.find((m) => m.name === fallback.name) ?? fallback;
425
+ }
426
+ function ruleHint(rule, currency) {
427
+ if (rule.scale !== undefined)
428
+ return `${formatRulePrices(rule)} of the base price`;
429
+ const s = symbol(currency);
430
+ const names = { input: "in", output: "out", cacheRead: "cache read", cacheWrite: "cache write" };
431
+ return Object.keys(names).flatMap((k) => rule[k] === undefined ? [] : [`${names[k]} ${s}${rule[k]}`]).join(" · ");
432
+ }
433
+ const WHEN_TITLE = "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";
434
+ 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)';
435
+ async function askRule(rule) {
436
+ const whenText = await ui.input({ title: WHEN_TITLE, initial: rule ? formatWhen(rule) : "", placeholder: "00:30-08:30 UTC+8" }, opts.signal);
437
+ if (whenText === undefined)
438
+ return;
439
+ let when;
440
+ try {
441
+ when = parseWhen(whenText);
442
+ } catch (err) {
443
+ report(errorText(err));
444
+ return;
445
+ }
446
+ if (Object.keys(when).length === 0) {
447
+ report("Write when the price applies, for example 00:30-08:30 or sat,sun.");
448
+ return;
449
+ }
450
+ const pricesText = await ui.input({ title: RULE_PRICE_TITLE, initial: rule ? formatRulePrices(rule) : "", placeholder: "50%" }, opts.signal);
451
+ if (pricesText === undefined)
452
+ return;
453
+ try {
454
+ return { ...when, ...parseRulePrices(pricesText) };
455
+ } catch (err) {
456
+ report(errorText(err));
457
+ return;
458
+ }
459
+ }
460
+ async function configurePrice(target) {
461
+ while (true) {
462
+ const p = await target.readPrice();
463
+ const rules = p?.rules ?? [];
464
+ const action = await ui.select({
465
+ title: `Price of ${target.title} per million tokens`,
466
+ options: [
467
+ { label: "Base price", value: "base", hint: p ? `${symbol(p.currency)} ${formatRates(p)} (input output cache-read cache-write)` : "not set" },
468
+ ...p ? [{ label: "Currency", value: "currency", hint: `${p.currency} (${symbol(p.currency)})` }] : [],
469
+ ...rules.map((r, i) => ({ label: formatWhen(r), value: `rule:${i}`, hint: ruleHint(r, p.currency), group: "Time-based prices (the first that matches applies)" })),
470
+ ...p ? [{ label: "Add a time-based price…", value: "add", hint: "off-peak, weekend or promotional prices" }] : [],
471
+ ...p ? [{ label: "Remove the price", value: "clear" }] : [],
472
+ { label: "Back", value: "back" }
473
+ ]
474
+ }, opts.signal);
475
+ if (action === undefined || action === "back")
476
+ return;
477
+ if (action === "base") {
478
+ const currency = p?.currency ?? await chooseCurrency();
479
+ if (!currency)
480
+ continue;
481
+ const text = await ui.input({
482
+ 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" : ""})`,
483
+ initial: p ? formatRates(p) : ""
484
+ }, opts.signal);
485
+ if (text === undefined)
486
+ continue;
487
+ if (!text.trim()) {
488
+ if (p)
489
+ await target.writePrice(undefined);
490
+ continue;
491
+ }
492
+ try {
493
+ const r = parseRates(text, false);
494
+ const { cacheRead: _r, cacheWrite: _w, ...rest } = p ?? { currency, input: 0, output: 0 };
495
+ await target.writePrice({ ...rest, currency, input: r.input, output: r.output, ...r.cacheRead !== undefined ? { cacheRead: r.cacheRead } : {}, ...r.cacheWrite !== undefined ? { cacheWrite: r.cacheWrite } : {} });
496
+ } catch (err) {
497
+ report(errorText(err));
498
+ }
499
+ } else if (action === "currency" && p) {
500
+ const currency = await chooseCurrency(p.currency);
501
+ if (currency && currency !== p.currency)
502
+ await target.writePrice({ ...p, currency });
503
+ } else if (action === "add" && p) {
504
+ const rule = await askRule();
505
+ if (rule)
506
+ await target.writePrice({ ...p, rules: [...rules, rule] });
507
+ } else if (action === "clear" && p) {
508
+ await target.writePrice(undefined);
509
+ } else if (action.startsWith("rule:") && p) {
510
+ const i = Number(action.slice(5));
511
+ const rule = rules[i];
512
+ if (!rule)
513
+ continue;
514
+ const what = await ui.select({
515
+ title: `${formatWhen(rule)}: ${ruleHint(rule, p.currency)}`,
516
+ options: [
517
+ { label: "Edit…", value: "edit" },
518
+ ...i > 0 ? [{ label: "Move up", value: "up", hint: "rules higher up win" }] : [],
519
+ { label: "Remove", value: "remove" },
520
+ { label: "Back", value: "back" }
521
+ ]
522
+ }, opts.signal);
523
+ const next = [...rules];
524
+ if (what === "edit") {
525
+ const edited = await askRule(rule);
526
+ if (!edited)
527
+ continue;
528
+ next[i] = edited;
529
+ } else if (what === "up")
530
+ next.splice(i - 1, 2, rule, rules[i - 1]);
531
+ else if (what === "remove")
532
+ next.splice(i, 1);
533
+ else
534
+ continue;
535
+ const { rules: _old, ...rest } = p;
536
+ await target.writePrice(next.length ? { ...rest, rules: next } : rest);
537
+ }
538
+ }
539
+ }
540
+ async function chooseCurrency(current) {
541
+ return ui.select({
542
+ title: "Currency of the prices",
543
+ options: CURRENCIES.map((c) => ({ label: c, value: c, hint: symbol(c), ...c === current ? { current: true } : {} }))
544
+ }, opts.signal);
545
+ }
375
546
  async function forgetModel(service, model) {
376
547
  const id = serviceId(service.env);
377
548
  if (!id)
378
549
  return;
379
550
  const rest = (await readSavedServices(modelsFile)).map((s) => serviceId(s.env) === id ? { ...s, models: s.models.filter((m) => m.name !== model.name) } : s).filter((s) => s.models.length > 0);
380
551
  await writeSavedServices(modelsFile, rest);
381
- report(`Removed ${model.name} (${describeService(service)}).`);
552
+ report(`Removed ${model.name} (${groupOf(service)}).`);
553
+ }
554
+ async function renameService(service) {
555
+ const text = await ui.input({ title: `Name for this service, e.g. DeepSeek (empty for ${describeService(service)})`, initial: service.name ?? "" }, opts.signal);
556
+ if (text === undefined)
557
+ return;
558
+ const name = text.trim();
559
+ if (await editSaved(service, ({ name: _old, ...s }) => name ? { name, ...s } : s))
560
+ report(name ? `Renamed ${describeService(service)} to ${name}.` : `${describeService(service)} has no name now.`);
382
561
  }
383
- async function pickModelAction(o, isCurrent) {
384
- const kind = providerKind(o.service.env);
385
- const read = isCurrent ? async () => pick(opts.env(), MODEL_SETTINGS) : () => savedSettings(o.service, o.model);
562
+ function entryOption(e, value, env) {
563
+ const settings = e.current ? pick(env, MODEL_SETTINGS) : e.model.settings;
564
+ const kind = providerKind(e.service.env);
565
+ const parts = [settingsSummary(settings, kind, contextWindow(e.model.name, settings)), e.model.price ? priceSummary(e.model.price) : ""];
566
+ return { label: e.model.name, value, hint: parts.filter(Boolean).join(" · "), group: groupOf(e.service), ...e.current ? { current: true } : {} };
567
+ }
568
+ async function entries() {
569
+ const env = opts.env();
570
+ const kind = providerKind(env);
571
+ const info = providerInfo(env);
572
+ return allModels(await savedServices(), serviceId(env), info.model, () => ({
573
+ service: { env: isBuiltinKind(kind) ? { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind } : { JADE_PROVIDER: kind }, models: [] },
574
+ model: { name: info.model, settings: pick(env, MODEL_SETTINGS) },
575
+ current: true
576
+ }));
577
+ }
578
+ async function pickModelAction(e) {
579
+ const kind = providerKind(e.service.env);
580
+ const read = e.current ? async () => pick(opts.env(), MODEL_SETTINGS) : async () => (await savedModel(e.service, e.model)).settings;
581
+ const saved = serviceId(e.service.env) !== undefined && e.service.models.length > 0;
386
582
  while (true) {
387
583
  const settings = await read();
584
+ const model = await savedModel(e.service, e.model);
585
+ const service = (await savedServices()).find((s) => serviceId(s.env) === serviceId(e.service.env)) ?? e.service;
388
586
  const action = await ui.select({
389
- title: o.model.name,
587
+ title: `${e.model.name} (${groupOf(service)})`,
390
588
  options: [
391
- ...isCurrent ? [] : [{ label: "Switch to it", value: "switch", hint: serviceId(o.service.env) === serviceId(opts.env()) ? "this service" : describeService(o.service) }],
392
- { label: "Settings…", value: "settings", hint: settingsSummary(settings, kind, contextWindow(o.model.name, settings)) },
393
- ...isCurrent ? [] : [{ label: "Remove", value: "forget" }],
589
+ { label: "Settings…", value: "settings", hint: [settingsSummary(settings, kind, contextWindow(e.model.name, settings)), model.price ? priceSummary(model.price) : ""].filter(Boolean).join(" · ") },
590
+ ...saved ? [{ label: "Service name…", value: "rename", hint: service.name ?? `not set (${describeService(service)})` }] : [],
591
+ ...e.current ? [] : [{ label: "Remove", value: "forget" }],
394
592
  { label: "Back", value: "back" }
395
593
  ]
396
594
  }, opts.signal);
397
595
  if (action === "settings") {
398
596
  await configureSettings({
399
- title: o.model.name,
597
+ title: e.model.name,
400
598
  kind,
401
- model: o.model.name,
402
- baseURL: providerInfo(o.service.env).baseURL,
599
+ model: e.model.name,
600
+ baseURL: providerInfo(e.service.env).baseURL,
403
601
  read,
404
- update: (updates) => isCurrent ? applyConfig(updates) : writeSavedModel(o.service, o.model, updates)
602
+ update: (updates) => e.current ? applyConfig(updates) : writeSavedModel(e.service, e.model, updates),
603
+ readPrice: async () => saved ? (await savedModel(e.service, e.model)).price : undefined,
604
+ 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))
405
605
  });
406
606
  continue;
407
607
  }
408
- if (action === "switch")
409
- await useSaved(o.service, { ...o.model, settings });
410
- else if (action === "forget")
411
- await forgetModel(o.service, o.model);
608
+ if (action === "rename") {
609
+ await renameService(service);
610
+ continue;
611
+ }
612
+ if (action === "forget")
613
+ await forgetModel(e.service, e.model);
412
614
  return;
413
615
  }
414
616
  }
415
- async function savedSettings(service, fallback) {
416
- const id = serviceId(service.env);
417
- const mine = id === undefined ? undefined : (await readSavedServices(modelsFile)).find((s) => serviceId(s.env) === id);
418
- return mine?.models.find((m) => m.name === fallback.name)?.settings ?? fallback.settings;
617
+ async function manageModels() {
618
+ while (true) {
619
+ const env = opts.env();
620
+ const list = await entries();
621
+ const action = await ui.select({ title: "Manage models", options: [...list.map((e, i) => entryOption(e, `model:${i}`, env)), { label: "Back", value: "back" }] }, opts.signal);
622
+ const e = action?.startsWith("model:") ? list[Number(action.slice(6))] : undefined;
623
+ if (!e)
624
+ return;
625
+ await pickModelAction(e);
626
+ }
419
627
  }
420
628
  async function configureModel(arg) {
421
629
  const env = opts.env();
@@ -423,61 +631,33 @@ export function configurator(opts) {
423
631
  return void await configureProvider();
424
632
  await remember().catch(() => {});
425
633
  if (arg) {
426
- const saved = otherModels(await savedServices(), serviceId(env), providerInfo(env).model).find((o) => o.model.name === arg);
634
+ const list = (await entries()).filter((e) => !e.current && e.model.name === arg);
635
+ const saved = list.find((e) => serviceId(e.service.env) === serviceId(env)) ?? list[0];
427
636
  return void await (saved ? useSaved(saved.service, saved.model) : switchModel(arg));
428
637
  }
429
638
  while (true) {
430
639
  const env = opts.env();
431
- const id = serviceId(env);
432
- const kind = providerKind(env);
433
- const kindKnown = isBuiltinKind(kind);
434
- const info = providerInfo(env);
435
- const here = describeService({ env: kindKnown ? pick(env, serviceKeys(kind)) : {}, models: [] });
436
- const services = await savedServices();
437
- const multi = services.length > 1;
438
- const others = otherModels(services, id, info.model);
640
+ const list = await entries();
439
641
  const action = await ui.select({
440
642
  title: "Switch model",
441
643
  options: [
442
- {
443
- label: info.model,
444
- value: "current",
445
- hint: `${multi ? `${here} · ` : ""}current · ${settingsSummary(env, info.kind, contextWindow(info.model, env))}`
446
- },
447
- ...others.map((o, i) => ({
448
- label: o.model.name,
449
- value: `saved:${i}`,
450
- hint: `${multi ? `${describeService(o.service)} · ` : ""}${settingsSummary(o.model.settings, providerKind(o.service.env), contextWindow(o.model.name, o.model.settings))}`
451
- })),
452
- { label: "Add a model…", value: "add", hint: "from this service or another one" }
644
+ ...list.map((e, i) => entryOption(e, `model:${i}`, env)),
645
+ { label: "Add a model…", value: "add", hint: "from a saved service or a new one" },
646
+ { label: "Manage models…", value: "manage", hint: "settings, prices, service names, remove" }
453
647
  ]
454
648
  }, opts.signal);
455
649
  if (action === undefined)
456
650
  return;
457
- if (action === "current") {
458
- const service = { env: kindKnown ? { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind } : { JADE_PROVIDER: kind }, models: [] };
459
- await pickModelAction({ service, model: { name: info.model, settings: pick(env, MODEL_SETTINGS) } }, true);
460
- } else if (action.startsWith("saved:")) {
461
- const o = others[Number(action.slice(6))];
462
- if (o)
463
- await pickModelAction(o, false);
464
- } else if (action === "add") {
465
- const where = await ui.select({
466
- title: "Add a model from",
467
- options: [
468
- { label: "This service", value: "model", hint: here },
469
- { label: "Another service…", value: "provider", hint: "or change this one's base URL / API key" },
470
- { label: "Back", value: "back" }
471
- ]
472
- }, opts.signal);
473
- if (where === "model") {
474
- const saved = services.find((s) => serviceId(s.env) === id)?.models.map((m) => m.name);
475
- const model = await chooseModel(env, info.model, saved);
476
- if (model && model !== info.model)
477
- await switchModel(model);
478
- } else if (where === "provider")
479
- await configureProvider();
651
+ if (action.startsWith("model:")) {
652
+ const e = list[Number(action.slice(6))];
653
+ if (e && !e.current)
654
+ await useSaved(e.service, e.model);
655
+ return;
480
656
  }
657
+ if (action === "add" && await addModel())
658
+ return;
659
+ if (action === "manage")
660
+ await manageModels();
481
661
  }
482
662
  }
483
663
  return { provider: configureProvider, model: configureModel };
@@ -1,10 +1,12 @@
1
+ import { readFileSync, statSync } from "node:fs";
1
2
  import path from "node:path";
2
3
  import { definePlugin } from "@uncarved/jade-api";
3
4
  import { contextWindow } from "./context.js";
4
5
  import { envWithFile, hasProvider, parseTokens } from "./config.js";
5
6
  import { configurator } from "./configure.js";
6
- import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry } from "./provider.js";
7
- import { MODEL_SETTINGS, readSavedServices } from "./saved.js";
7
+ import { isBuiltinKind, KEY_KEY, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry } from "./provider.js";
8
+ import { priceAt } from "./price.js";
9
+ import { MODEL_SETTINGS, parseSavedServices, readSavedServices } from "./saved.js";
8
10
  let setup;
9
11
  let hinted = false;
10
12
  const countdowns = new Map;
@@ -96,6 +98,24 @@ export default definePlugin({
96
98
  delete snapshot[k];
97
99
  return cachedBuild(snapshot);
98
100
  };
101
+ let priced;
102
+ const savedNow = () => {
103
+ let mtime;
104
+ try {
105
+ mtime = statSync(modelsFile).mtimeMs;
106
+ } catch {
107
+ return [];
108
+ }
109
+ if (priced?.mtime !== mtime)
110
+ priced = { mtime, services: parseSavedServices(readFileSync(modelsFile, "utf8")) };
111
+ return priced.services;
112
+ };
113
+ const price = (name, at) => {
114
+ const services = savedNow();
115
+ const here = hasProvider(env) ? services.find((s) => isBuiltinKind(providerKind(s.env)) && sameService(s.env, env)) : undefined;
116
+ const m = [...here ? [here] : [], ...services].flatMap((s) => s.models).find((x) => x.name === name && x.price);
117
+ return m?.price ? priceAt(m.price, at) : undefined;
118
+ };
99
119
  const current = (request, options) => provider().then((p) => p.complete(request, options));
100
120
  const complete = (request, { model, ...options }) => model ? saved(model).then((p) => p.complete(request, options)) : current(request, options);
101
121
  ctx.provide("provider@1", { id: "jade/models", complete: current });
@@ -124,6 +144,7 @@ export default definePlugin({
124
144
  };
125
145
  },
126
146
  complete,
147
+ price,
127
148
  list: () => listModels(env),
128
149
  async saved() {
129
150
  const names = (await readSavedServices(modelsFile)).flatMap((s) => isBuiltinKind(providerKind(s.env)) ? s.models.map((m) => m.name) : []);
@@ -290,6 +311,16 @@ export default definePlugin({
290
311
  });
291
312
  }
292
313
  });
314
+ function sameService(a, b) {
315
+ try {
316
+ const x = providerInfo(a);
317
+ const y = providerInfo(b);
318
+ const kind = providerKind(a);
319
+ return isBuiltinKind(kind) && x.kind === y.kind && (x.baseURL ?? "") === (y.baseURL ?? "") && a[KEY_KEY[kind]] === b[KEY_KEY[kind]];
320
+ } catch {
321
+ return false;
322
+ }
323
+ }
293
324
  function via(kind, baseURL) {
294
325
  const host = baseURL ? safeHost(baseURL) : undefined;
295
326
  if (kind === "anthropic")