@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
@@ -4,6 +4,7 @@
4
4
  // /model 改了配置之后不用重开会话:provider@1 给核心的是一个转发到当前 provider 的壳(设计第 10 节),
5
5
  // 下一次请求就用新的。
6
6
 
7
+ import { readFileSync, statSync } from "node:fs";
7
8
  import path from "node:path";
8
9
  import type { ModelRequest, ModelResponse, Provider } from "uncarved";
9
10
  import { definePlugin, type Notice, type UI, type Updater } from "@uncarved/jade-api";
@@ -11,8 +12,9 @@ import type { Commands, Models } from "@uncarved/jade-api/services";
11
12
  import { contextWindow } from "./context.ts";
12
13
  import { envWithFile, hasProvider, parseTokens } from "./config.ts";
13
14
  import { configurator } from "./configure.ts";
14
- import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry, type RetriedResponse, type RetryOptions } from "./provider.ts";
15
- import { MODEL_SETTINGS, readSavedServices, type Env } from "./saved.ts";
15
+ import { isBuiltinKind, KEY_KEY, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry, type RetriedResponse, type RetryingProvider, type RetryOptions } from "./provider.ts";
16
+ import { priceAt } from "./price.ts";
17
+ import { MODEL_SETTINGS, parseSavedServices, readSavedServices, type Env, type SavedService } from "./saved.ts";
16
18
 
17
19
  /** 进程级的配置交给会话里的提示用:有没有配好模型、有没有 /model、.env 在哪 */
18
20
  let setup: { configured(): boolean; command: boolean; envFile: string } | undefined;
@@ -62,9 +64,9 @@ export default definePlugin({
62
64
  " OPENAI_COMPAT_BASE_URL=... and OPENAI_COMPAT_MODEL=... (an OpenAI-compatible service)",
63
65
  );
64
66
 
65
- let made: Promise<Provider> | undefined;
67
+ let made: Promise<RetryingProvider> | undefined;
66
68
  // 用创建时的这份配置:之后换了配置,新的一份自己建 provider
67
- const build = (snapshot: Env): Promise<Provider> => {
69
+ const build = (snapshot: Env): Promise<RetryingProvider> => {
68
70
  return (async () => {
69
71
  const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui()?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
70
72
  return withRetry(await providerFromEnv(snapshot, { "user-agent": userAgent() }), {
@@ -80,7 +82,7 @@ export default definePlugin({
80
82
  };
81
83
 
82
84
  // 第一次用时才创建:配置写错时错误出现在这一轮里,而不是让插件激活失败、连会话都打不开
83
- const provider = (): Promise<Provider> => {
85
+ const provider = (): Promise<RetryingProvider> => {
84
86
  if (!hasProvider(env)) return Promise.reject(notConfigured());
85
87
  if (made) return made;
86
88
  const p = build(env);
@@ -93,8 +95,8 @@ export default definePlugin({
93
95
  };
94
96
 
95
97
  /** 保存过的模型的 provider,按配置缓存:models.json 里的密钥或设置改了就另建一份 */
96
- const savedProviders = new Map<string, Promise<Provider>>();
97
- const cachedBuild = (snapshot: Env): Promise<Provider> => {
98
+ const savedProviders = new Map<string, Promise<RetryingProvider>>();
99
+ const cachedBuild = (snapshot: Env): Promise<RetryingProvider> => {
98
100
  const key = JSON.stringify(snapshot);
99
101
  const cached = savedProviders.get(key);
100
102
  if (cached) return cached;
@@ -104,7 +106,7 @@ export default definePlugin({
104
106
  p.catch(() => savedProviders.delete(key));
105
107
  return p;
106
108
  };
107
- const saved = async (name: string): Promise<Provider> => {
109
+ const saved = async (name: string): Promise<RetryingProvider> => {
108
110
  for (const s of await readSavedServices(modelsFile)) {
109
111
  const m = s.models.find((x) => x.name === name);
110
112
  const kind = providerKind(s.env);
@@ -122,7 +124,27 @@ export default definePlugin({
122
124
  return cachedBuild(snapshot);
123
125
  };
124
126
 
125
- const current: Provider["complete"] = (request, options) => provider().then((p) => p.complete(request, options));
127
+ // models.json 里填的单价:jade/cost 每个回复都要查,是同步的,按文件的修改时间缓存(别的会话、手改文件也看得到)
128
+ let priced: { mtime: number; services: SavedService[] } | undefined;
129
+ const savedNow = (): SavedService[] => {
130
+ let mtime: number;
131
+ try {
132
+ mtime = statSync(modelsFile).mtimeMs;
133
+ } catch {
134
+ return [];
135
+ }
136
+ if (priced?.mtime !== mtime) priced = { mtime, services: parseSavedServices(readFileSync(modelsFile, "utf8")) };
137
+ return priced.services;
138
+ };
139
+ const price: NonNullable<Models["price"]> = (name, at) => {
140
+ const services = savedNow();
141
+ // 当前服务上的同名模型优先(不同服务上同一个模型可以不同价)
142
+ const here = hasProvider(env) ? services.find((s) => isBuiltinKind(providerKind(s.env)) && sameService(s.env, env)) : undefined;
143
+ const m = [...(here ? [here] : []), ...services].flatMap((s) => s.models).find((x) => x.name === name && x.price);
144
+ return m?.price ? priceAt(m.price, at) : undefined;
145
+ };
146
+
147
+ const current: RetryingProvider["complete"] = (request, options) => provider().then((p) => p.complete(request, options));
126
148
  const complete: Models["complete"] = (request, { model, ...options }) => (model ? saved(model).then((p) => p.complete(request, options)) : current(request, options));
127
149
 
128
150
  // 转发的 provider:会话创建时固定的是这个壳,/model 之后下一次请求就用新的配置
@@ -155,6 +177,7 @@ export default definePlugin({
155
177
  };
156
178
  },
157
179
  complete,
180
+ price,
158
181
  list: () => listModels(env),
159
182
  async saved() {
160
183
  const names = (await readSavedServices(modelsFile)).flatMap((s) => (isBuiltinKind(providerKind(s.env)) ? s.models.map((m) => m.name) : []));
@@ -332,6 +355,18 @@ export default definePlugin({
332
355
  },
333
356
  });
334
357
 
358
+ /** 两份配置是不是同一个服务:类型、地址、密钥都相同 */
359
+ function sameService(a: Env, b: Env): boolean {
360
+ try {
361
+ const x = providerInfo(a);
362
+ const y = providerInfo(b);
363
+ const kind = providerKind(a);
364
+ return isBuiltinKind(kind) && x.kind === y.kind && (x.baseURL ?? "") === (y.baseURL ?? "") && a[KEY_KEY[kind]] === b[KEY_KEY[kind]];
365
+ } catch {
366
+ return false;
367
+ }
368
+ }
369
+
335
370
  function via(kind: string, baseURL: string | undefined): string {
336
371
  const host = baseURL ? safeHost(baseURL) : undefined;
337
372
  if (kind === "anthropic") return host && host !== "api.anthropic.com" ? `the Anthropic API at ${host}` : "the Anthropic API";
@@ -0,0 +1,291 @@
1
+ // 模型的单价:/model 里填,存在 models.json 那个模型上(saved.ts),jade/cost 经 models@1.price 按请求的时间取。
2
+ //
3
+ // 基础价之外可以有按时间的规则(峰谷价、周末价、限时折扣):从上往下第一条符合的算数,都不符合时用基础价。
4
+ // 一条规则可以限定星期几、每天的时段(可以跨零点)、起止日期和时区,价格写成基础价的百分比,或者逐项写(没写的项用基础价)。
5
+
6
+ import type { Price } from "@uncarved/jade-api/services";
7
+
8
+ export type Currency = "USD" | "CNY";
9
+ export const CURRENCIES: Currency[] = ["USD", "CNY"];
10
+ const SYMBOL: Record<Currency, string> = { USD: "$", CNY: "¥" };
11
+
12
+ interface Rates {
13
+ input?: number;
14
+ output?: number;
15
+ cacheRead?: number;
16
+ cacheWrite?: number;
17
+ }
18
+
19
+ /** 一天里的一段 HH:MM:from 算在内、to 不算;from 比 to 晚时跨零点。只写一头时另一头是零点 */
20
+ export interface TimeRange {
21
+ from?: string;
22
+ to?: string;
23
+ }
24
+
25
+ export interface PriceRule extends Rates {
26
+ /** 星期几,0 是周日 */
27
+ days?: number[];
28
+ /** 每天的时段,在其中任一段里就算 */
29
+ times?: TimeRange[];
30
+ /** 起止日期 YYYY-MM-DD,两头都算在内 */
31
+ since?: string;
32
+ until?: string;
33
+ /** IANA 时区或 UTC+8 这种写法;没有时用本机时区 */
34
+ tz?: string;
35
+ /** 基础价的倍数(50% 是 0.5);有它时不看逐项的价格 */
36
+ scale?: number;
37
+ }
38
+
39
+ /** 每百万 token 的单价;cacheRead、cacheWrite 没有时按 input 算 */
40
+ export interface ModelPrice extends Required<Pick<Rates, "input" | "output">> {
41
+ currency: Currency;
42
+ cacheRead?: number;
43
+ cacheWrite?: number;
44
+ rules?: PriceRule[];
45
+ }
46
+
47
+ const DAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
48
+ const TIME = /^([01]?\d|2[0-3]):([0-5]\d)$/;
49
+ const DATE = /^\d{4}-\d{2}-\d{2}$/;
50
+ const OFFSET = /^(?:UTC|GMT)?([+-])(\d{1,2})(?::?(\d{2}))?$/i;
51
+ const RATE_KEYS = ["input", "output", "cacheRead", "cacheWrite"] as const;
52
+
53
+ const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : undefined);
54
+ const hhmm = (t: string) => {
55
+ const m = TIME.exec(t)!;
56
+ return `${m[1]!.padStart(2, "0")}:${m[2]}`;
57
+ };
58
+
59
+ function validTz(tz: string): boolean {
60
+ if (OFFSET.test(tz)) return true;
61
+ try {
62
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
63
+ return true;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /** models.json 里的单价;写错的整个不要,写错的规则跳过 */
70
+ export function readPrice(raw: unknown): ModelPrice | undefined {
71
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
72
+ const r = raw as Record<string, unknown>;
73
+ const input = num(r.input);
74
+ const output = num(r.output);
75
+ if (input === undefined || output === undefined) return undefined;
76
+ const currency: Currency = r.currency === "CNY" ? "CNY" : "USD";
77
+ const out: ModelPrice = { currency, input, output };
78
+ if (num(r.cacheRead) !== undefined) out.cacheRead = num(r.cacheRead);
79
+ if (num(r.cacheWrite) !== undefined) out.cacheWrite = num(r.cacheWrite);
80
+ const rules = Array.isArray(r.rules) ? r.rules.flatMap((x) => readRule(x) ?? []) : [];
81
+ if (rules.length) out.rules = rules;
82
+ return out;
83
+ }
84
+
85
+ function readRule(raw: unknown): PriceRule | undefined {
86
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
87
+ const r = raw as Record<string, unknown>;
88
+ const out: PriceRule = {};
89
+ if (Array.isArray(r.days)) {
90
+ const days = r.days.filter((d): d is number => Number.isInteger(d) && d >= 0 && d <= 6);
91
+ if (days.length) out.days = [...new Set(days)].sort();
92
+ }
93
+ // 早先的写法是规则上直接一个 from、to
94
+ const times = (Array.isArray(r.times) ? r.times : r.from !== undefined || r.to !== undefined ? [{ from: r.from, to: r.to }] : []).flatMap((x: unknown) => readRange(x) ?? []);
95
+ if (times.length) out.times = times;
96
+ for (const k of ["since", "until"] as const) if (typeof r[k] === "string" && DATE.test(r[k])) out[k] = r[k];
97
+ if (typeof r.tz === "string" && validTz(r.tz)) out.tz = r.tz;
98
+ if (num(r.scale) !== undefined) out.scale = num(r.scale);
99
+ else for (const k of RATE_KEYS) if (num(r[k]) !== undefined) out[k] = num(r[k]);
100
+ return out;
101
+ }
102
+
103
+ /** 一个时段;两头都没写或写错时 undefined */
104
+ function readRange(raw: unknown): TimeRange | undefined {
105
+ if (!raw || typeof raw !== "object") return undefined;
106
+ const r = raw as Record<string, unknown>;
107
+ const out: TimeRange = {};
108
+ for (const k of ["from", "to"] as const) {
109
+ if (r[k] === undefined) continue;
110
+ if (typeof r[k] !== "string" || !TIME.test(r[k])) return undefined;
111
+ out[k] = hhmm(r[k]);
112
+ }
113
+ return out.from !== undefined || out.to !== undefined ? out : undefined;
114
+ }
115
+
116
+ /** 在 tz 的当地时间:日期 YYYY-MM-DD、星期几、从零点起的分钟数 */
117
+ function localTime(at: Date, tz: string | undefined): { date: string; day: number; minutes: number } {
118
+ const offset = tz ? OFFSET.exec(tz) : null;
119
+ if (!tz || offset) {
120
+ // 本机时区,或者固定的偏移:挪到 UTC 上读
121
+ const shift = offset ? (offset[1] === "-" ? -1 : 1) * (Number(offset[2]) * 60 + Number(offset[3] ?? 0)) : -at.getTimezoneOffset();
122
+ const d = new Date(at.getTime() + shift * 60_000);
123
+ return { date: d.toISOString().slice(0, 10), day: d.getUTCDay(), minutes: d.getUTCHours() * 60 + d.getUTCMinutes() };
124
+ }
125
+ const parts = Object.fromEntries(
126
+ new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", weekday: "short" })
127
+ .formatToParts(at)
128
+ .map((p) => [p.type, p.value]),
129
+ );
130
+ return {
131
+ date: `${parts.year}-${parts.month}-${parts.day}`,
132
+ day: DAYS.indexOf(String(parts.weekday).toLowerCase().slice(0, 3)),
133
+ minutes: Number(parts.hour) * 60 + Number(parts.minute),
134
+ };
135
+ }
136
+
137
+ const minutesOf = (t: string) => Number(t.slice(0, 2)) * 60 + Number(t.slice(3));
138
+
139
+ const prevDate = (date: string) => new Date(Date.parse(`${date}T00:00:00Z`) - 86_400_000).toISOString().slice(0, 10);
140
+
141
+ /**
142
+ * 规则在 at 这一刻算不算数:在任一个时段里(没写时段时整天都算),并且星期、日期也符合。
143
+ * 跨零点的时段,零点之后那段的星期几和日期按开始的那天算
144
+ */
145
+ export function ruleMatches(rule: PriceRule, at: Date): boolean {
146
+ const t = localTime(at, rule.tz);
147
+ /** 现在落在时段里时,这一段从哪天开始 */
148
+ const startDays: { date: string; day: number }[] = [];
149
+ if (!rule.times?.length) startDays.push(t);
150
+ for (const r of rule.times ?? []) {
151
+ const from = r.from === undefined ? 0 : minutesOf(r.from);
152
+ const to = r.to === undefined ? 24 * 60 : minutesOf(r.to);
153
+ if (from < to) {
154
+ if (t.minutes >= from && t.minutes < to) startDays.push(t);
155
+ } else if (t.minutes >= from) startDays.push(t);
156
+ else if (t.minutes < to) startDays.push({ date: prevDate(t.date), day: (t.day + 6) % 7 });
157
+ }
158
+ return startDays.some(
159
+ ({ date, day }) => (!rule.days || rule.days.includes(day)) && (!rule.since || date >= rule.since) && (!rule.until || date <= rule.until),
160
+ );
161
+ }
162
+
163
+ /** at 这一刻的单价 */
164
+ export function priceAt(p: ModelPrice, at: Date): Price {
165
+ const base: Price = { input: p.input, output: p.output, currency: p.currency };
166
+ if (p.cacheRead !== undefined) base.cacheRead = p.cacheRead;
167
+ if (p.cacheWrite !== undefined) base.cacheWrite = p.cacheWrite;
168
+ const rule = p.rules?.find((r) => ruleMatches(r, at));
169
+ if (!rule) return base;
170
+ const out: Price = { ...base };
171
+ for (const k of RATE_KEYS) {
172
+ // 打折时缓存价没写的按输入价打;逐项写的规则没写的项留基础价(缓存价没写时 jade/cost 按这条规则的输入价算)
173
+ if (rule.scale !== undefined) out[k] = (base[k] ?? base.input) * rule.scale;
174
+ else if (rule[k] !== undefined) out[k] = rule[k];
175
+ }
176
+ return out;
177
+ }
178
+
179
+ // ---------- 在 /model 里输入和显示 ----------
180
+
181
+ const n = (v: number) => String(Number(v.toFixed(6)));
182
+
183
+ /** 一行价格:"3 15 0.3 3.75"(输入 输出 [缓存读 [缓存写]]);allowKeep 时 "-" 表示用基础价。写错时抛出 */
184
+ export function parseRates(text: string, allowKeep: boolean): Rates {
185
+ const parts = text.trim().split(/[\s,]+/).filter(Boolean);
186
+ if (parts.length < (allowKeep ? 1 : 2) || parts.length > 4) throw new Error(`Write ${allowKeep ? "1 to 4" : "2 to 4"} prices: input output [cache read] [cache write], got ${JSON.stringify(text)}`);
187
+ const out: Rates = {};
188
+ parts.forEach((p, i) => {
189
+ if (allowKeep && p === "-") return;
190
+ const v = Number(p.replace(/^[$¥]/, ""));
191
+ if (!Number.isFinite(v) || v < 0) throw new Error(`Prices must be numbers of at least 0, got ${JSON.stringify(p)}`);
192
+ out[RATE_KEYS[i]!] = v;
193
+ });
194
+ return out;
195
+ }
196
+
197
+ export function formatRates(r: Rates, keep = false): string {
198
+ const vals = RATE_KEYS.map((k) => (r[k] === undefined ? undefined : n(r[k]!)));
199
+ while (vals.length && vals.at(-1) === undefined) vals.pop();
200
+ return vals.map((v) => v ?? (keep ? "-" : "")).join(" ");
201
+ }
202
+
203
+ /** 规则的价格那一行:"50%",或者逐项的价格("-" 用基础价) */
204
+ export function parseRulePrices(text: string): Pick<PriceRule, "scale" | keyof Rates> {
205
+ const pct = /^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(text);
206
+ if (pct) return { scale: Number(pct[1]) / 100 };
207
+ const r = parseRates(text, true);
208
+ if (Object.keys(r).length === 0) throw new Error("Write a percentage such as 50%, or at least one price");
209
+ return r;
210
+ }
211
+
212
+ export function formatRulePrices(rule: PriceRule): string {
213
+ return rule.scale !== undefined ? `${n(rule.scale * 100)}%` : formatRates(rule, true);
214
+ }
215
+
216
+ /**
217
+ * 规则的时间那一行:空格分开的几项,顺序不限,都可以不写:
218
+ * 时段 "00:30-08:30"(可以有几段,"09:00-12:00,14:00-18:00" 或者分开写)、星期 "mon-fri" 或 "sat,sun"、日期 "2026-12-01..2026-12-31"(一头可以空着)、时区 "UTC+8" 或 "Asia/Shanghai"。
219
+ * 写错时抛出
220
+ */
221
+ export function parseWhen(text: string): Omit<PriceRule, "scale" | keyof Rates> {
222
+ const out: Omit<PriceRule, "scale" | keyof Rates> = {};
223
+ for (const part of text.trim().split(/\s+/).filter(Boolean)) {
224
+ const lower = part.toLowerCase();
225
+ const dates = /^(\d{4}-\d{2}-\d{2})?\.\.(\d{4}-\d{2}-\d{2})?$/.exec(part);
226
+ // 一项里可以用逗号写几个时段:09:00-12:00,14:00-18:00;也可以分开写成几项
227
+ const ranges = part.split(",").map((x) => /^(\d{1,2}:\d{2})?-(\d{1,2}:\d{2})?$/.exec(x));
228
+ if (ranges.every((m) => m && (m[1] || m[2]))) {
229
+ for (const m of ranges) {
230
+ for (const t of [m![1], m![2]]) if (t && !TIME.test(t)) throw new Error(`Not a time of day: ${t}`);
231
+ (out.times ??= []).push({ ...(m![1] ? { from: hhmm(m![1]) } : {}), ...(m![2] ? { to: hhmm(m![2]) } : {}) });
232
+ }
233
+ } else if (dates && (dates[1] || dates[2])) {
234
+ for (const d of [dates[1], dates[2]]) if (d && Number.isNaN(Date.parse(`${d}T00:00:00Z`))) throw new Error(`Not a date: ${d}`);
235
+ if (dates[1]) out.since = dates[1];
236
+ if (dates[2]) out.until = dates[2];
237
+ } else if (DATE.test(part)) {
238
+ out.since = out.until = part;
239
+ } else if (/^[a-z]{3}(?:[-,][a-z]{3})*$/.test(lower) && DAYS.includes(lower.slice(0, 3))) {
240
+ const days = new Set<number>(out.days);
241
+ for (const piece of lower.split(",")) {
242
+ const [a, b] = piece.split("-").map((d) => DAYS.indexOf(d));
243
+ if (a === undefined || a < 0 || (b !== undefined && b < 0)) throw new Error(`Days are written like mon-fri or sat,sun, got ${JSON.stringify(part)}`);
244
+ // mon-fri;fri-mon 跨过周末
245
+ for (let d = a; ; d = (d + 1) % 7) {
246
+ days.add(d);
247
+ if (b === undefined || d === b) break;
248
+ }
249
+ }
250
+ out.days = [...days].sort();
251
+ } else if (validTz(part)) {
252
+ out.tz = part;
253
+ } else {
254
+ throw new Error(`Not understood: ${JSON.stringify(part)}. Write times like 00:30-08:30, days like mon-fri, dates like 2026-12-01..2026-12-31, and a time zone like UTC+8 or Asia/Shanghai`);
255
+ }
256
+ }
257
+ return out;
258
+ }
259
+
260
+ /** parseWhen 的反过来:编辑时预填,菜单里显示 */
261
+ export function formatWhen(rule: PriceRule): string {
262
+ const parts: string[] = [];
263
+ if (rule.days) parts.push(formatDays(rule.days));
264
+ if (rule.times?.length) parts.push(rule.times.map((r) => `${r.from ?? ""}-${r.to ?? ""}`).join(","));
265
+ if (rule.since !== undefined && rule.since === rule.until) parts.push(rule.since);
266
+ else if (rule.since !== undefined || rule.until !== undefined) parts.push(`${rule.since ?? ""}..${rule.until ?? ""}`);
267
+ if (rule.tz) parts.push(rule.tz);
268
+ return parts.join(" ");
269
+ }
270
+
271
+ /** 连着的几天写成 mon-fri */
272
+ function formatDays(days: number[]): string {
273
+ const out: string[] = [];
274
+ for (let i = 0; i < days.length; ) {
275
+ let j = i;
276
+ while (j + 1 < days.length && days[j + 1] === days[j]! + 1) j++;
277
+ out.push(j - i >= 2 ? `${DAYS[days[i]!]}-${DAYS[days[j]!]}` : days.slice(i, j + 1).map((d) => DAYS[d]).join(","));
278
+ i = j + 1;
279
+ }
280
+ return out.join(",");
281
+ }
282
+
283
+ export const symbol = (c: string | undefined) => SYMBOL[c as Currency] ?? "$";
284
+
285
+ /** 菜单里的简要说明,例如 "$3 in · $15 out · 2 time rules" */
286
+ export function priceSummary(p: ModelPrice | undefined): string {
287
+ if (!p) return "not set";
288
+ const s = symbol(p.currency);
289
+ const rules = p.rules?.length ? ` · ${p.rules.length} time rule${p.rules.length > 1 ? "s" : ""}` : "";
290
+ return `${s}${n(p.input)} in · ${s}${n(p.output)} out${rules}`;
291
+ }
@@ -51,23 +51,38 @@ export interface RetryRecord {
51
51
  */
52
52
  export type RetriedResponse = ModelResponse & { retries?: RetryRecord[] };
53
53
 
54
- export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
54
+ /**
55
+ * withRetry 的 complete 比内核的 Provider 多收两个可选的回调,就是 models@1 的 complete 的 onWait、onSend
56
+ * (见 jade-api 的 Models.complete):请求开始等待(限速排队、重试前的等待)、真正发出时告诉调用方
57
+ */
58
+ export type RetryCallOptions = Parameters<Provider["complete"]>[1] & { onWait?: () => void; onSend?: () => void };
59
+
60
+ /** withRetry 包出来的 Provider:仍然是内核的 Provider(多出的参数都可选),models@1 经它把 onWait、onSend 传下来 */
61
+ export interface RetryingProvider extends Provider {
62
+ complete(request: ModelRequest, options: RetryCallOptions): Promise<RetriedResponse>;
63
+ }
64
+
65
+ export function withRetry(inner: Provider, opts: RetryOptions = {}): RetryingProvider {
55
66
  const delays = opts.delaysMs ?? RETRY_DELAYS_MS;
56
67
  const retries = opts.retries ?? delays.length;
57
68
  const max = opts.maxDelayMs ?? MAX_RETRY_DELAY_MS;
58
69
  const random = opts.random ?? Math.random;
59
70
  return {
60
71
  id: `retry(${inner.id})`,
61
- async complete(request, options): Promise<RetriedResponse> {
72
+ async complete(request: ModelRequest, options: RetryCallOptions): Promise<RetriedResponse> {
73
+ const { onWait, onSend, ...forwarded } = options;
62
74
  const failures: RetryRecord[] = [];
63
75
  for (let attempt = 1; ; attempt++) {
64
76
  let streamed = false;
77
+ // 排队的时间不算请求的耗时:调用方(例如审查的超时)据此暂停、重新计时
78
+ if (opts.gate) onWait?.();
65
79
  const done = await opts.gate?.acquire(options.signal, opts.onWait && ((delayMs) => opts.onWait!({ delayMs, request })));
80
+ onSend?.();
66
81
  opts.onRequest?.(attempt);
67
82
  try {
68
83
  const res = await inner
69
84
  .complete(request, {
70
- ...options,
85
+ ...forwarded,
71
86
  onDelta: (d) => {
72
87
  streamed = true;
73
88
  options.onDelta?.(d);
@@ -101,6 +116,7 @@ export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
101
116
  if (streamed) options.onDelta?.({ kind: "reset" });
102
117
  failures.push({ attempt, delayMs, error: err.message, ...(err.status !== undefined ? { status: err.status } : {}), ...(streamed ? { discarded: true as const } : {}) });
103
118
  opts.onRetry?.({ attempt, retries, delayMs, error: err, request });
119
+ onWait?.();
104
120
  await sleep(delayMs, options.signal);
105
121
  }
106
122
  }
@@ -109,7 +125,7 @@ export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
109
125
  }
110
126
 
111
127
  export interface RateGateOptions {
112
- /** 每分钟最多发几个请求(JADE_RPM);不设时不主动限速,被限流后按当时的请求数推一个 */
128
+ /** 每分钟最多发几个请求(JADE_RPM);被限流后会先降下来,回升时不超过它。不设时不主动限速,被限流后按当时的请求数推一个 */
113
129
  rpm?: number;
114
130
  now?: () => number;
115
131
  /** 要等一段时间才能发下一个请求时通知宿主(显示用) */
@@ -135,12 +151,17 @@ interface Sent {
135
151
  * 从请求结束算起:服务端常常在请求结束时才记一次,从发出时算、按 60s / 上限平均间隔的话,
136
152
  * 每隔上限个请求就正好卡在窗口边上被拒,每次再白等一个 Retry-After
137
153
  * - 收到 429 后,所有请求都等到重试时间之后再发
154
+ * - 被限流降下来的上限会回升,免得一次限流之后一直慢下去:把窗口发满的请求(发出时窗口里正好到上限)
155
+ * 每攒够上限那么多个都没被限流,上限加一,最高到 JADE_RPM。只数发满窗口的,上限就不会比实际用量高出去
138
156
  */
139
157
  export class RateGate {
140
158
  #rpm: number | undefined;
141
- readonly #explicit: boolean;
159
+ /** 回升的最高值(JADE_RPM);undefined 表示不封顶 */
160
+ readonly #ceiling: number | undefined;
142
161
  #sent: Sent[] = [];
143
162
  #until = 0;
163
+ /** 上次限流以后发满窗口的请求数,攒够上限那么多个就把上限加一 */
164
+ #full = 0;
144
165
  #queue: Promise<void> = Promise.resolve();
145
166
  readonly #now: () => number;
146
167
  readonly #opts: RateGateOptions;
@@ -148,7 +169,7 @@ export class RateGate {
148
169
  constructor(opts: RateGateOptions = {}) {
149
170
  this.#opts = opts;
150
171
  this.#rpm = opts.rpm;
151
- this.#explicit = opts.rpm !== undefined;
172
+ this.#ceiling = opts.rpm;
152
173
  this.#now = opts.now ?? Date.now;
153
174
  }
154
175
 
@@ -174,6 +195,7 @@ export class RateGate {
174
195
  onWait?.(wait);
175
196
  await sleep(wait, signal);
176
197
  }
198
+ this.#recover();
177
199
  let finish!: () => void;
178
200
  const sent: Sent = { at: this.#now(), inFlight: true, finished: new Promise((r) => (finish = r)) };
179
201
  this.#sent.push(sent);
@@ -203,13 +225,14 @@ export class RateGate {
203
225
  }
204
226
 
205
227
  /**
206
- * 被限流了:ms 内不再发请求。没设上限时,按最近一分钟发出的请求数推一个上限(比它少一个);
228
+ * 被限流了:ms 内不再发请求。按最近一分钟发出的请求数推一个上限(比它少一个),比当前上限低才换;
207
229
  * 一分钟里只发了一两个请求就被限流,多半是服务端繁忙,不是请求太多,不推;learn 为 false(并发数限流)时也不推
208
230
  */
209
231
  limited(ms: number, { learn = true }: { learn?: boolean } = {}) {
210
232
  const now = this.#now();
211
233
  this.#until = Math.max(this.#until, now + ms);
212
- if (this.#explicit || !learn) return;
234
+ this.#full = 0;
235
+ if (!learn) return;
213
236
  const recent = this.#recent(now);
214
237
  if (recent < 3) return;
215
238
  const next = recent - 1;
@@ -219,6 +242,15 @@ export class RateGate {
219
242
  }
220
243
  }
221
244
 
245
+ /** 要发一个请求了:它把窗口发满时记一个,攒够上限那么多个就把上限加一(不超过 JADE_RPM) */
246
+ #recover() {
247
+ if (this.#rpm === undefined || this.#rpm === this.#ceiling) return;
248
+ if (this.#recent(this.#now()) + 1 < this.#rpm) return;
249
+ if (++this.#full < this.#rpm) return;
250
+ this.#full = 0;
251
+ this.#rpm += 1;
252
+ }
253
+
222
254
  /** 还算在窗口里的请求数:没结束的,和最近一分钟里结束的 */
223
255
  #recent(now: number): number {
224
256
  this.#sent = this.#sent.filter((s) => s.inFlight || now - s.at < WINDOW_MS + WINDOW_MARGIN_MS);
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { mkdir, readFile, writeFile } from "node:fs/promises";
6
6
  import path from "node:path";
7
+ import { readPrice, type ModelPrice } from "./price.ts";
7
8
 
8
9
  export type Env = Record<string, string | undefined>;
9
10
 
@@ -14,9 +15,13 @@ export interface SavedModel {
14
15
  name: string;
15
16
  /** 这个模型自己的设置变量 */
16
17
  settings: Record<string, string>;
18
+ /** 用户填的单价(jade/cost 经 models@1.price 用) */
19
+ price?: ModelPrice;
17
20
  }
18
21
 
19
22
  export interface SavedService {
23
+ /** 用户给服务起的名字,/model 里按它分组;没有时显示地址的主机名 */
24
+ name?: string;
20
25
  /** 服务的变量:JADE_PROVIDER、地址、密钥等 */
21
26
  env: Record<string, string>;
22
27
  /** 最近用过的在前 */
@@ -29,10 +34,19 @@ const strings = (v: unknown): Record<string, string> =>
29
34
  /** 读不了或格式不对时返回空数组 */
30
35
  export async function readSavedServices(file: string): Promise<SavedService[]> {
31
36
  try {
32
- const data = JSON.parse(await readFile(file, "utf8")) as { services?: unknown };
37
+ return parseSavedServices(await readFile(file, "utf8"));
38
+ } catch {
39
+ return [];
40
+ }
41
+ }
42
+
43
+ /** models.json 的内容;格式不对时返回空数组 */
44
+ export function parseSavedServices(text: string): SavedService[] {
45
+ try {
46
+ const data = JSON.parse(text) as { services?: unknown };
33
47
  if (!Array.isArray(data.services)) return [];
34
48
  return data.services.flatMap((raw: unknown) => {
35
- const s = raw as { env?: unknown; models?: unknown } | null;
49
+ const s = raw as { name?: unknown; env?: unknown; models?: unknown } | null;
36
50
  if (!s || !Array.isArray(s.models)) return [];
37
51
  // 以前额外请求参数存在服务上:分给它下面没有自己那份的模型
38
52
  const { OPENAI_COMPAT_EXTRA_BODY: extraBody, ...env } = strings(s.env);
@@ -40,9 +54,11 @@ export async function readSavedServices(file: string): Promise<SavedService[]> {
40
54
  const name = (m as { name?: unknown } | null)?.name;
41
55
  const settings = strings((m as { settings?: unknown }).settings);
42
56
  if (extraBody && settings.OPENAI_COMPAT_EXTRA_BODY === undefined) settings.OPENAI_COMPAT_EXTRA_BODY = extraBody;
43
- return typeof name === "string" && name ? [{ name, settings }] : [];
57
+ const price = readPrice((m as { price?: unknown }).price);
58
+ return typeof name === "string" && name ? [{ name, settings, ...(price ? { price } : {}) }] : [];
44
59
  });
45
- return models.length ? [{ env, models }] : [];
60
+ const label = typeof s.name === "string" && s.name.trim() ? { name: s.name.trim() } : {};
61
+ return models.length ? [{ ...label, env, models }] : [];
46
62
  });
47
63
  } catch {
48
64
  return [];
@@ -15,9 +15,8 @@ import type { Approval, Commands, Keys, Modes, Prompts } from "@uncarved/jade-ap
15
15
 
16
16
  export const DESCRIPTIONS: Record<string, string> = {
17
17
  ask: "ask before edits and commands",
18
- auto: "edits in this directory and harmless commands run without asking; others still ask",
18
+ auto: "never asks: edits in this directory and harmless commands run; a model reviews the rest and blocks risky ones",
19
19
  plan: "change nothing: research read-only and propose a plan",
20
- readonly: "change nothing",
21
20
  yolo: "never ask",
22
21
  };
23
22
  const CYCLE = ["ask", "auto", "plan"];
@@ -81,9 +80,9 @@ const listeners = new Set<(mode: string) => void>();
81
80
 
82
81
  /**
83
82
  * 用户选的模式记在 $JADE_HOME/mode.json,下次启动接着用(比配置里的 mode 优先)。
84
- * plan 是一次任务里的,yolo 不该悄悄带到下一次启动:这两个不记
83
+ * plan 是一次任务里的,yolo 不该悄悄带到下一次启动:这两个不记。readonly 给子 Agent 用,/mode 里没有
85
84
  */
86
- const REMEMBERED = new Set(["ask", "auto", "readonly"]);
85
+ const REMEMBERED = new Set(["ask", "auto"]);
87
86
  let modeFile: string | undefined;
88
87
  /** 记下的模式只在第一个可交互的会话里恢复一次:jade -p 这类不能问用户的运行一直用配置的模式 */
89
88
  let restored = false;
@@ -36,7 +36,7 @@ const HOW: Line[] = [
36
36
  tools: ["ask_user"],
37
37
  },
38
38
  { text: "- Read before you change: use glob/grep/read_file to understand the code, then edit. Never guess file contents.", tools: ["read_file"] },
39
- { text: "- When you need several independent reads or searches, issue them in the same response: they run in parallel." },
39
+ { text: "- When you need several independent reads or searches, issue them in the same response: they run in parallel. Every response resends the whole conversation, so one call per response when you already know the next few is slow and costly." },
40
40
  {
41
41
  text: "- Change existing files with edit_file (multi_edit for several changes to one file); use write_file only for new files or when most of the file changes.",
42
42
  tools: ["edit_file"],
@@ -54,6 +54,10 @@ const HOW: Line[] = [
54
54
  },
55
55
  { text: "- If the user says not to test or check the result, do not: no tests, builds, screenshots or other checks of any kind. Finish the work and reply." },
56
56
  { text: "- Use the task tool for broad searches so that only conclusions come back into this conversation.", tools: ["task"] },
57
+ {
58
+ text: "- A task report is finished work with evidence: build on it, do not redo it. Check only the claims that are both uncertain and important to your answer, and issue those checks together in one response (or hand them to sub-agents in parallel) rather than one per response.",
59
+ tools: ["task"],
60
+ },
57
61
  {
58
62
  text: "- Do not guess about things outside the repository that may have changed (library APIs, versions, error messages): look them up with the web tools.",
59
63
  tools: ["web_fetch", "web_search"],