@uncarved/jade 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/README.md +1 -0
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/host.d.ts +2 -0
  5. package/dist/host.js +39 -5
  6. package/dist/host.js.map +1 -1
  7. package/dist/remote.js +5 -0
  8. package/dist/remote.js.map +1 -1
  9. package/dist/session.d.ts +7 -0
  10. package/dist/session.js +482 -27
  11. package/dist/session.js.map +1 -1
  12. package/package.json +4 -4
  13. package/plugins/approval/index.ts +49 -24
  14. package/plugins/approval/policy.ts +48 -25
  15. package/plugins/approval/review.ts +9 -5
  16. package/plugins/checks/checks.ts +10 -7
  17. package/plugins/checks/index.ts +13 -13
  18. package/plugins/checks/plugin.json +1 -1
  19. package/plugins/checks/project.ts +37 -38
  20. package/plugins/commands/index.ts +27 -3
  21. package/plugins/compact/compact.ts +13 -5
  22. package/plugins/compact/index.ts +20 -3
  23. package/plugins/compact/style.ts +13 -14
  24. package/plugins/completions/index.ts +35 -0
  25. package/plugins/completions/plugin.json +7 -0
  26. package/plugins/copy/index.ts +46 -0
  27. package/plugins/copy/plugin.json +7 -0
  28. package/plugins/editor/index.ts +10 -4
  29. package/plugins/fs/diff.ts +7 -6
  30. package/plugins/fs/fs.ts +8 -4
  31. package/plugins/fs/grep.ts +55 -12
  32. package/plugins/fs/index.ts +2 -7
  33. package/plugins/fs/plugin.json +1 -1
  34. package/plugins/fs/renderers.ts +16 -15
  35. package/plugins/fs/style.ts +16 -15
  36. package/plugins/hooks/index.ts +3 -2
  37. package/plugins/keys/index.ts +5 -1
  38. package/plugins/mcp/index.ts +197 -78
  39. package/plugins/mcp/install.ts +5 -3
  40. package/plugins/mcp/mcp.ts +163 -11
  41. package/plugins/mcp/plugin.json +2 -1
  42. package/plugins/mcp/project.ts +47 -50
  43. package/plugins/memory/index.ts +4 -4
  44. package/plugins/memory/style.ts +13 -14
  45. package/plugins/mentions/candidates.ts +67 -0
  46. package/plugins/mentions/index.ts +12 -5
  47. package/plugins/mentions/plugin.json +1 -1
  48. package/plugins/mentions/style.ts +13 -14
  49. package/plugins/models/configure.ts +10 -9
  50. package/plugins/models/index.ts +31 -4
  51. package/plugins/models/provider.ts +12 -1
  52. package/plugins/modes/index.ts +13 -2
  53. package/plugins/print/index.ts +7 -4
  54. package/plugins/prompts/index.ts +0 -0
  55. package/plugins/renderers/index.ts +10 -5
  56. package/plugins/repeats/index.ts +39 -9
  57. package/plugins/schedule/index.ts +2 -0
  58. package/plugins/screenshot/browser.ts +231 -0
  59. package/plugins/screenshot/index.ts +3 -2
  60. package/plugins/screenshot/tool.ts +27 -51
  61. package/plugins/sessions/index.ts +48 -2
  62. package/plugins/shell/index.ts +75 -22
  63. package/plugins/shell/plugin.json +1 -2
  64. package/plugins/shell/renderers.ts +9 -7
  65. package/plugins/shell/shell.ts +93 -34
  66. package/plugins/skills/index.ts +28 -19
  67. package/plugins/skills/project.ts +12 -7
  68. package/plugins/steer/index.ts +5 -4
  69. package/plugins/task/index.ts +81 -81
  70. package/plugins/task/plugin.json +5 -2
  71. package/plugins/task/style.ts +13 -14
  72. package/plugins/task/subagent.ts +67 -184
  73. package/plugins/todo/index.ts +39 -9
  74. package/plugins/tools/index.ts +57 -0
  75. package/plugins/tools/plugin.json +7 -0
  76. package/plugins/tui/frontend.ts +161 -87
  77. package/plugins/tui/index.ts +2 -3
  78. package/plugins/tui/mascot.ts +8 -7
  79. package/plugins/tui/mentions.ts +11 -80
  80. package/plugins/tui/plugin.json +1 -1
  81. package/plugins/tui/screen.ts +55 -5
  82. package/plugins/tui/transcript.ts +17 -7
  83. package/plugins/tui/tui.ts +356 -104
  84. package/plugins/tui/vendor.ts +1 -1
  85. package/plugins/undo/checkpoint.ts +5 -3
  86. package/plugins/undo/index.ts +43 -14
  87. package/plugins/undo/style.ts +13 -14
  88. package/plugins/web/index.ts +7 -18
  89. package/plugins/web/plugin.json +1 -1
  90. package/plugins-dist/approval/index.js +363 -414
  91. package/plugins-dist/approval/policy.js +395 -497
  92. package/plugins-dist/approval/review.js +132 -158
  93. package/plugins-dist/approval/schema.js +50 -55
  94. package/plugins-dist/ask/index.js +115 -129
  95. package/plugins-dist/budget/index.js +27 -31
  96. package/plugins-dist/checks/checks.js +293 -329
  97. package/plugins-dist/checks/index.js +119 -139
  98. package/plugins-dist/checks/plugin.json +2 -1
  99. package/plugins-dist/checks/project.js +57 -65
  100. package/plugins-dist/commands/index.js +47 -29
  101. package/plugins-dist/compact/compact.js +233 -249
  102. package/plugins-dist/compact/index.js +98 -95
  103. package/plugins-dist/compact/style.js +9 -14
  104. package/plugins-dist/completions/index.js +30 -0
  105. package/plugins-dist/completions/plugin.json +9 -0
  106. package/plugins-dist/continue/index.js +40 -52
  107. package/plugins-dist/copy/index.js +40 -0
  108. package/plugins-dist/copy/plugin.json +9 -0
  109. package/plugins-dist/cost/index.js +98 -115
  110. package/plugins-dist/custom-commands/index.js +55 -72
  111. package/plugins-dist/editor/index.js +64 -72
  112. package/plugins-dist/fs/diff.js +111 -124
  113. package/plugins-dist/fs/fs.js +426 -469
  114. package/plugins-dist/fs/grep.js +262 -244
  115. package/plugins-dist/fs/index.js +20 -34
  116. package/plugins-dist/fs/plugin.json +1 -2
  117. package/plugins-dist/fs/renderers.js +100 -112
  118. package/plugins-dist/fs/style.js +11 -15
  119. package/plugins-dist/fs/sys.js +31 -43
  120. package/plugins-dist/hooks/index.js +107 -127
  121. package/plugins-dist/keys/index.js +27 -31
  122. package/plugins-dist/mcp/index.js +271 -199
  123. package/plugins-dist/mcp/install.js +123 -137
  124. package/plugins-dist/mcp/mcp.js +638 -577
  125. package/plugins-dist/mcp/plugin.json +3 -1
  126. package/plugins-dist/mcp/project.js +98 -115
  127. package/plugins-dist/memory/index.js +83 -88
  128. package/plugins-dist/memory/memory.js +111 -128
  129. package/plugins-dist/memory/style.js +9 -14
  130. package/plugins-dist/mentions/attach.js +91 -99
  131. package/plugins-dist/mentions/candidates.js +49 -0
  132. package/plugins-dist/mentions/index.js +71 -81
  133. package/plugins-dist/mentions/plugin.json +2 -1
  134. package/plugins-dist/mentions/style.js +9 -14
  135. package/plugins-dist/models/config.js +29 -43
  136. package/plugins-dist/models/configure.js +392 -473
  137. package/plugins-dist/models/context.js +14 -22
  138. package/plugins-dist/models/index.js +182 -188
  139. package/plugins-dist/models/provider.js +243 -295
  140. package/plugins-dist/models/saved.js +59 -71
  141. package/plugins-dist/modes/index.js +138 -165
  142. package/plugins-dist/plugins/index.js +34 -34
  143. package/plugins-dist/print/index.js +192 -175
  144. package/plugins-dist/prompts/index.js +81 -89
  145. package/plugins-dist/prompts/notes.js +31 -37
  146. package/plugins-dist/prompts/prompts.js +155 -193
  147. package/plugins-dist/prompts/results.js +40 -53
  148. package/plugins-dist/prompts/sys.js +39 -50
  149. package/plugins-dist/renderers/index.js +32 -32
  150. package/plugins-dist/repeats/index.js +134 -151
  151. package/plugins-dist/schedule/cron.js +49 -56
  152. package/plugins-dist/schedule/index.js +229 -247
  153. package/plugins-dist/schedule/store.js +93 -109
  154. package/plugins-dist/scratch/index.js +12 -18
  155. package/plugins-dist/screenshot/browser.js +169 -0
  156. package/plugins-dist/screenshot/index.js +37 -45
  157. package/plugins-dist/screenshot/sys.js +53 -65
  158. package/plugins-dist/screenshot/tool.js +101 -151
  159. package/plugins-dist/sessions/index.js +149 -117
  160. package/plugins-dist/shell/index.js +117 -74
  161. package/plugins-dist/shell/plugin.json +1 -2
  162. package/plugins-dist/shell/renderers.js +28 -33
  163. package/plugins-dist/shell/service.js +17 -23
  164. package/plugins-dist/shell/shell.js +317 -320
  165. package/plugins-dist/shell/sys.js +64 -79
  166. package/plugins-dist/skills/index.js +193 -211
  167. package/plugins-dist/skills/install.js +122 -149
  168. package/plugins-dist/skills/project.js +65 -73
  169. package/plugins-dist/skills/skills.js +135 -171
  170. package/plugins-dist/steer/index.js +108 -125
  171. package/plugins-dist/suggest/index.js +235 -259
  172. package/plugins-dist/task/index.js +130 -148
  173. package/plugins-dist/task/plugin.json +5 -4
  174. package/plugins-dist/task/style.js +9 -14
  175. package/plugins-dist/task/subagent.js +156 -279
  176. package/plugins-dist/todo/index.js +79 -63
  177. package/plugins-dist/tools/index.js +43 -0
  178. package/plugins-dist/tools/plugin.json +9 -0
  179. package/plugins-dist/tui/editor.js +145 -160
  180. package/plugins-dist/tui/frontend.js +641 -655
  181. package/plugins-dist/tui/history.js +34 -37
  182. package/plugins-dist/tui/index.js +16 -18
  183. package/plugins-dist/tui/markdown.js +203 -247
  184. package/plugins-dist/tui/mascot.js +266 -353
  185. package/plugins-dist/tui/mentions.js +67 -144
  186. package/plugins-dist/tui/plugin.json +1 -2
  187. package/plugins-dist/tui/render.js +35 -45
  188. package/plugins-dist/tui/screen.js +197 -180
  189. package/plugins-dist/tui/transcript.js +436 -468
  190. package/plugins-dist/tui/tui.js +1554 -1645
  191. package/plugins-dist/tui/vendor.js +1388 -1088
  192. package/plugins-dist/undo/checkpoint.js +95 -118
  193. package/plugins-dist/undo/index.js +185 -192
  194. package/plugins-dist/undo/snapshot.js +83 -99
  195. package/plugins-dist/undo/style.js +9 -14
  196. package/plugins-dist/update/index.js +26 -28
  197. package/plugins-dist/web/env.js +55 -68
  198. package/plugins-dist/web/index.js +80 -110
  199. package/plugins-dist/web/plugin.json +1 -2
  200. package/plugins-dist/web/renderers.js +4 -5
  201. package/plugins-dist/web/web.js +514 -593
  202. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  203. package/sdk/python/jade_plugin.py +9 -2
  204. package/src/api.ts +1 -1
  205. package/src/host.ts +39 -4
  206. package/src/remote.ts +6 -1
  207. package/src/session.ts +489 -34
@@ -1,335 +1,283 @@
1
- // Provider:按环境变量选择,外面包一层重试(4.7:重试是包装 Provider 的事)。
2
1
  import { ProviderError } from "uncarved";
3
2
  import { parseTokens } from "./config.js";
4
- /** 默认的重试等待:一次比一次久,最长 3 分钟 */
5
3
  export const RETRY_DELAYS_MS = [2, 5, 10, 20, 30, 45, 60, 120, 180].map((s) => s * 1000);
6
- const MAX_RETRY_DELAY_MS = 180_000;
7
- /** 是不是被限流了(429,或者错误信息里这么说) */
4
+ const MAX_RETRY_DELAY_MS = 180000;
8
5
  export const isRateLimit = (err) => err.status === 429 || /\b429\b|rate.?limit|too many requests/i.test(err.message);
9
- /**
10
- * 是不是同时进行的请求太多("concurrency limit"),而不是每分钟的请求太多。
11
- * 这种限流也要一起等,但不能拿来推每分钟的上限:等前面的请求结束就好了,推出来的上限只会让之后一直变慢
12
- */
13
6
  export const isConcurrencyLimit = (err) => /concurren/i.test(err.message);
14
7
  export function withRetry(inner, opts = {}) {
15
- const delays = opts.delaysMs ?? RETRY_DELAYS_MS;
16
- const retries = opts.retries ?? delays.length;
17
- const max = opts.maxDelayMs ?? MAX_RETRY_DELAY_MS;
18
- const random = opts.random ?? Math.random;
19
- return {
20
- id: `retry(${inner.id})`,
21
- async complete(request, options) {
22
- const failures = [];
23
- for (let attempt = 1;; attempt++) {
24
- let streamed = false;
25
- await opts.gate?.acquire(options.signal);
26
- opts.onRequest?.(attempt);
27
- try {
28
- const res = await inner.complete(request, {
29
- ...options,
30
- onDelta: (d) => {
31
- streamed = true;
32
- options.onDelta?.(d);
33
- },
34
- });
35
- // 实际回复的是被包装者(4.7 第 3 款)
36
- return { ...res, provider: res.provider ?? inner.id, ...(failures.length > 0 ? { retries: failures } : {}) };
37
- }
38
- catch (err) {
39
- if (!(err instanceof ProviderError) || !err.retryable || attempt > retries || options.signal.aborted)
40
- throw err;
41
- // 在计划的时间上随机缩短最多 20%,并行的子 Agent 同时遇到 429 时不会同时重试。
42
- // 上游给的 retryAfterMs 只当下限:有的服务(尤其是并发数限流)每次都回 Retry-After: 1,
43
- // 拿它代替退避计划会每秒撞一次,十几秒就把重试次数用完
44
- const planned = delays[Math.min(attempt, delays.length) - 1] ?? 1000;
45
- const delayMs = Math.round(Math.min(Math.max(err.retryAfterMs ?? 0, planned * (0.8 + 0.2 * random())), max));
46
- // 限流时所有共用这个 gate 的请求(子 Agent、压缩)一起等,不再各自去撞
47
- if (isRateLimit(err))
48
- opts.gate?.limited(delayMs, { learn: !isConcurrencyLimit(err) });
49
- // 失败的这次已经推送过增量的,先让订阅者作废它们(4.7)
50
- if (streamed)
51
- options.onDelta?.({ kind: "reset" });
52
- failures.push({ attempt, delayMs, error: err.message, ...(err.status !== undefined ? { status: err.status } : {}), ...(streamed ? { discarded: true } : {}) });
53
- opts.onRetry?.({ attempt, retries, delayMs, error: err });
54
- await sleep(delayMs, options.signal);
55
- }
8
+ const delays = opts.delaysMs ?? RETRY_DELAYS_MS;
9
+ const retries = opts.retries ?? delays.length;
10
+ const max = opts.maxDelayMs ?? MAX_RETRY_DELAY_MS;
11
+ const random = opts.random ?? Math.random;
12
+ return {
13
+ id: `retry(${inner.id})`,
14
+ async complete(request, options) {
15
+ const failures = [];
16
+ for (let attempt = 1;; attempt++) {
17
+ let streamed = false;
18
+ await opts.gate?.acquire(options.signal);
19
+ opts.onRequest?.(attempt);
20
+ try {
21
+ const res = await inner.complete(request, {
22
+ ...options,
23
+ onDelta: (d) => {
24
+ streamed = true;
25
+ options.onDelta?.(d);
56
26
  }
57
- },
58
- };
59
- }
60
- /**
61
- * 同一个服务的所有请求共用的限速。免费模型常常按每分钟请求数限流,主 Agent、并行的子 Agent、压缩各自重试会一起撞上去。
62
- * - 有上限(JADE_RPM,或者被限流后推出来的)时,相邻两个请求至少间隔 60s / 上限,平均分布在一分钟里
63
- * - 收到 429 后,所有请求都等到重试时间之后再发
64
- */
65
- export class RateGate {
66
- #rpm;
67
- #explicit;
68
- #sent = [];
69
- #until = 0;
70
- #queue = Promise.resolve();
71
- #now;
72
- #opts;
73
- constructor(opts = {}) {
74
- this.#opts = opts;
75
- this.#rpm = opts.rpm;
76
- this.#explicit = opts.rpm !== undefined;
77
- this.#now = opts.now ?? Date.now;
78
- }
79
- /** 当前的每分钟请求数上限;undefined 表示不限 */
80
- get rpm() {
81
- return this.#rpm;
82
- }
83
- /** 等到可以发下一个请求,并记下这个请求。排队的请求按先来后到 */
84
- acquire(signal) {
85
- const turn = this.#queue.then(async () => {
86
- signal.throwIfAborted();
87
- for (let wait = this.#delay(); wait > 0; wait = this.#delay()) {
88
- this.#opts.onWait?.(wait);
89
- await sleep(wait, signal);
90
- }
91
- this.#sent.push(this.#now());
92
- });
93
- this.#queue = turn.catch(() => { });
94
- // 排队时被取消的也要立即返回(I-9);轮到它时看到已取消,不会记成发出了请求
95
- return new Promise((resolve, reject) => {
96
- const stop = () => reject(signal.reason);
97
- if (signal.aborted)
98
- return stop();
99
- signal.addEventListener("abort", stop, { once: true });
100
- turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
101
- });
102
- }
103
- /**
104
- * 被限流了:ms 内不再发请求。没设上限时,按最近一分钟发出的请求数推一个上限(比它少一个);
105
- * 一分钟里只发了一两个请求就被限流,多半是服务端繁忙,不是请求太多,不推;learn 为 false(并发数限流)时也不推
106
- */
107
- limited(ms, { learn = true } = {}) {
108
- const now = this.#now();
109
- this.#until = Math.max(this.#until, now + ms);
110
- if (this.#explicit || !learn)
111
- return;
112
- const recent = this.#recent(now);
113
- if (recent < 3)
114
- return;
115
- const next = recent - 1;
116
- if (this.#rpm === undefined || next < this.#rpm) {
117
- this.#rpm = next;
118
- this.#opts.onLearn?.(next);
27
+ });
28
+ return { ...res, provider: res.provider ?? inner.id, ...failures.length > 0 ? { retries: failures } : {} };
29
+ } catch (err) {
30
+ if (!(err instanceof ProviderError) || options.signal.aborted)
31
+ throw err;
32
+ if (!err.retryable || attempt > retries) {
33
+ if (failures.length === 0)
34
+ throw err;
35
+ const waited = Math.round(failures.reduce((ms, f) => ms + f.delayMs, 0) / 1000);
36
+ throw new ProviderError(`${err.message} (after ${failures.length} ${failures.length === 1 ? "retry" : "retries"}, ${waited}s of waiting)`, {
37
+ retryable: err.retryable,
38
+ status: err.status,
39
+ retryAfterMs: err.retryAfterMs,
40
+ cause: err
41
+ });
42
+ }
43
+ const planned = delays[Math.min(attempt, delays.length) - 1] ?? 1000;
44
+ const delayMs = Math.round(Math.min(Math.max(err.retryAfterMs ?? 0, planned * (0.8 + 0.2 * random())), max));
45
+ if (isRateLimit(err))
46
+ opts.gate?.limited(delayMs, { learn: !isConcurrencyLimit(err) });
47
+ if (streamed)
48
+ options.onDelta?.({ kind: "reset" });
49
+ failures.push({ attempt, delayMs, error: err.message, ...err.status !== undefined ? { status: err.status } : {}, ...streamed ? { discarded: true } : {} });
50
+ opts.onRetry?.({ attempt, retries, delayMs, error: err });
51
+ await sleep(delayMs, options.signal);
119
52
  }
53
+ }
120
54
  }
121
- #recent(now) {
122
- this.#sent = this.#sent.filter((t) => now - t < 60_000);
123
- return this.#sent.length;
124
- }
125
- #delay() {
126
- const now = this.#now();
127
- this.#recent(now);
128
- let wait = this.#until - now;
129
- const last = this.#sent.at(-1);
130
- if (this.#rpm !== undefined && last !== undefined)
131
- wait = Math.max(wait, last + 60_000 / this.#rpm - now);
132
- return Math.ceil(wait);
133
- }
55
+ };
134
56
  }
135
- function sleep(ms, signal) {
57
+
58
+ export class RateGate {
59
+ #rpm;
60
+ #explicit;
61
+ #sent = [];
62
+ #until = 0;
63
+ #queue = Promise.resolve();
64
+ #now;
65
+ #opts;
66
+ constructor(opts = {}) {
67
+ this.#opts = opts;
68
+ this.#rpm = opts.rpm;
69
+ this.#explicit = opts.rpm !== undefined;
70
+ this.#now = opts.now ?? Date.now;
71
+ }
72
+ get rpm() {
73
+ return this.#rpm;
74
+ }
75
+ acquire(signal) {
76
+ const turn = this.#queue.then(async () => {
77
+ signal.throwIfAborted();
78
+ for (let wait = this.#delay();wait > 0; wait = this.#delay()) {
79
+ this.#opts.onWait?.(wait);
80
+ await sleep(wait, signal);
81
+ }
82
+ this.#sent.push(this.#now());
83
+ });
84
+ this.#queue = turn.catch(() => {});
136
85
  return new Promise((resolve, reject) => {
137
- const done = () => {
138
- signal.removeEventListener("abort", stop);
139
- resolve();
140
- };
141
- const timer = setTimeout(done, ms);
142
- const stop = () => {
143
- clearTimeout(timer);
144
- reject(signal.reason);
145
- };
146
- signal.addEventListener("abort", stop, { once: true });
86
+ const stop = () => reject(signal.reason);
87
+ if (signal.aborted)
88
+ return stop();
89
+ signal.addEventListener("abort", stop, { once: true });
90
+ turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
147
91
  });
92
+ }
93
+ limited(ms, { learn = true } = {}) {
94
+ const now = this.#now();
95
+ this.#until = Math.max(this.#until, now + ms);
96
+ if (this.#explicit || !learn)
97
+ return;
98
+ const recent = this.#recent(now);
99
+ if (recent < 3)
100
+ return;
101
+ const next = recent - 1;
102
+ if (this.#rpm === undefined || next < this.#rpm) {
103
+ this.#rpm = next;
104
+ this.#opts.onLearn?.(next);
105
+ }
106
+ }
107
+ #recent(now) {
108
+ this.#sent = this.#sent.filter((t) => now - t < 60000);
109
+ return this.#sent.length;
110
+ }
111
+ #delay() {
112
+ const now = this.#now();
113
+ this.#recent(now);
114
+ let wait = this.#until - now;
115
+ const last = this.#sent.at(-1);
116
+ if (this.#rpm !== undefined && last !== undefined)
117
+ wait = Math.max(wait, last + 60000 / this.#rpm - now);
118
+ return Math.ceil(wait);
119
+ }
120
+ }
121
+ function sleep(ms, signal) {
122
+ return new Promise((resolve, reject) => {
123
+ const done = () => {
124
+ signal.removeEventListener("abort", stop);
125
+ resolve();
126
+ };
127
+ const timer = setTimeout(done, ms);
128
+ const stop = () => {
129
+ clearTimeout(timer);
130
+ reject(signal.reason);
131
+ };
132
+ signal.addEventListener("abort", stop, { once: true });
133
+ });
148
134
  }
149
135
  export const PROVIDER_KINDS = ["openai-compat", "openai", "anthropic"];
150
136
  export const isBuiltinKind = (kind) => PROVIDER_KINDS.includes(kind);
151
- /** 每种内置服务的模型名、密钥、地址各放在哪个环境变量里 */
152
137
  export const MODEL_KEY = { "openai-compat": "OPENAI_COMPAT_MODEL", openai: "OPENAI_MODEL", anthropic: "ANTHROPIC_MODEL" };
153
138
  export const KEY_KEY = { "openai-compat": "OPENAI_COMPAT_API_KEY", openai: "OPENAI_API_KEY", anthropic: "ANTHROPIC_API_KEY" };
154
139
  export const URL_KEY = { "openai-compat": "OPENAI_COMPAT_BASE_URL", openai: "OPENAI_BASE_URL", anthropic: "ANTHROPIC_BASE_URL" };
155
- /** JADE_EFFORT 可取的值;openai-compat 没有统一的字段,用 OPENAI_COMPAT_EXTRA_BODY 自己设 */
156
140
  export const EFFORTS = {
157
- anthropic: ["low", "medium", "high", "xhigh", "max"],
158
- openai: ["minimal", "low", "medium", "high"],
159
- "openai-compat": undefined,
141
+ anthropic: ["low", "medium", "high", "xhigh", "max"],
142
+ openai: ["minimal", "low", "medium", "high"],
143
+ "openai-compat": undefined
160
144
  };
161
- /** JADE_RPM:每分钟最多发几个模型请求(免费模型常按这个限流);不设时不主动限速 */
162
145
  export function rpmFromEnv(env = process.env) {
163
- const text = env.JADE_RPM?.trim();
164
- if (!text)
165
- return undefined;
166
- const n = Number(text);
167
- if (!Number.isFinite(n) || n <= 0)
168
- throw new Error(`JADE_RPM must be a positive number of requests per minute, got ${JSON.stringify(text)}`);
169
- return n;
146
+ const text = env.JADE_RPM?.trim();
147
+ if (!text)
148
+ return;
149
+ const n = Number(text);
150
+ if (!Number.isFinite(n) || n <= 0)
151
+ throw new Error(`JADE_RPM must be a positive number of requests per minute, got ${JSON.stringify(text)}`);
152
+ return n;
170
153
  }
171
- /**
172
- * JADE_IDLE_TIMEOUT:多少秒没收到模型服务的任何数据(等响应头、流中两段数据之间)就中断并重试;0 表示不限。
173
- * 不设时用 provider 的默认值(90 秒)。只对 OpenAI 和 OpenAI 兼容服务生效,Claude 由 SDK 自己处理超时
174
- */
175
154
  export function idleTimeoutFromEnv(env = process.env) {
176
- const text = env.JADE_IDLE_TIMEOUT?.trim();
177
- if (!text)
178
- return undefined;
179
- const n = Number(text);
180
- if (!Number.isFinite(n) || n < 0)
181
- throw new Error(`JADE_IDLE_TIMEOUT must be a number of seconds (0 for no limit), got ${JSON.stringify(text)}`);
182
- return Math.round(n * 1000);
155
+ const text = env.JADE_IDLE_TIMEOUT?.trim();
156
+ if (!text)
157
+ return;
158
+ const n = Number(text);
159
+ if (!Number.isFinite(n) || n < 0)
160
+ throw new Error(`JADE_IDLE_TIMEOUT must be a number of seconds (0 for no limit), got ${JSON.stringify(text)}`);
161
+ return Math.round(n * 1000);
183
162
  }
184
- /**
185
- * JADE_VISION:模型能不能看图片(工具读到的图片、截图)。不设时 Claude 和 OpenAI 算能看;
186
- * OpenAI 兼容服务的模型五花八门,算不能看:不支持图片的模型收到图片会拒绝整个请求,而图片会一直留在历史里
187
- */
188
163
  export function visionFromEnv(env = process.env) {
189
- const text = env.JADE_VISION?.trim().toLowerCase();
190
- if (!text)
191
- return providerKind(env) === "openai" || providerKind(env) === "anthropic";
192
- if (["1", "true", "on", "yes"].includes(text))
193
- return true;
194
- if (["0", "false", "off", "no"].includes(text))
195
- return false;
196
- throw new Error(`JADE_VISION must be on or off, got ${JSON.stringify(env.JADE_VISION)}`);
164
+ const text = env.JADE_VISION?.trim().toLowerCase();
165
+ if (!text)
166
+ return providerKind(env) === "openai" || providerKind(env) === "anthropic";
167
+ if (["1", "true", "on", "yes"].includes(text))
168
+ return true;
169
+ if (["0", "false", "off", "no"].includes(text))
170
+ return false;
171
+ throw new Error(`JADE_VISION must be on or off, got ${JSON.stringify(env.JADE_VISION)}`);
197
172
  }
198
- /** JADE_EFFORT;不设时 Claude 用 high,OpenAI 用服务端默认值 */
199
173
  export function effortFromEnv(env = process.env) {
200
- const effort = env.JADE_EFFORT;
201
- if (!effort)
202
- return undefined;
203
- const kind = providerKind(env);
204
- if (!isBuiltinKind(kind))
205
- return effort;
206
- const allowed = EFFORTS[kind];
207
- if (!allowed)
208
- throw new Error(`JADE_EFFORT is not supported for the ${kind} provider; set it in OPENAI_COMPAT_EXTRA_BODY instead`);
209
- if (!allowed.includes(effort))
210
- throw new Error(`JADE_EFFORT must be one of ${allowed.join(", ")} for the ${kind} provider, got ${JSON.stringify(effort)}`);
174
+ const effort = env.JADE_EFFORT;
175
+ if (!effort)
176
+ return;
177
+ const kind = providerKind(env);
178
+ if (!isBuiltinKind(kind))
211
179
  return effort;
180
+ const allowed = EFFORTS[kind];
181
+ if (!allowed)
182
+ throw new Error(`JADE_EFFORT is not supported for the ${kind} provider; set it in OPENAI_COMPAT_EXTRA_BODY instead`);
183
+ if (!allowed.includes(effort))
184
+ throw new Error(`JADE_EFFORT must be one of ${allowed.join(", ")} for the ${kind} provider, got ${JSON.stringify(effort)}`);
185
+ return effort;
212
186
  }
213
- /** JADE_PROVIDER 指定时用它;否则按 OPENAI_API_KEY、OPENAI_COMPAT_BASE_URL、ANTHROPIC_API_KEY 的顺序。不认识的名字原样返回,创建时报错 */
214
187
  export function providerKind(env = process.env) {
215
- const named = env.JADE_PROVIDER;
216
- if (named)
217
- return named;
218
- if (env.OPENAI_API_KEY)
219
- return "openai";
220
- if (env.OPENAI_COMPAT_BASE_URL)
221
- return "openai-compat";
222
- return "anthropic";
188
+ const named = env.JADE_PROVIDER;
189
+ if (named)
190
+ return named;
191
+ if (env.OPENAI_API_KEY)
192
+ return "openai";
193
+ if (env.OPENAI_COMPAT_BASE_URL)
194
+ return "openai-compat";
195
+ return "anthropic";
223
196
  }
224
- /** 当前配置会用哪个服务、哪个模型(状态栏和 /model 显示用) */
225
197
  export function providerInfo(env = process.env) {
226
- const kind = providerKind(env);
227
- if (kind === "openai")
228
- return { kind, model: env.OPENAI_MODEL ?? "gpt-5", baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1" };
229
- if (kind === "openai-compat")
230
- return { kind, model: env.OPENAI_COMPAT_MODEL ?? "", baseURL: env.OPENAI_COMPAT_BASE_URL };
231
- return { kind, model: env.ANTHROPIC_MODEL ?? "claude-opus-5-5", baseURL: env.ANTHROPIC_BASE_URL };
198
+ const kind = providerKind(env);
199
+ if (kind === "openai")
200
+ return { kind, model: env.OPENAI_MODEL ?? "gpt-5", baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1" };
201
+ if (kind === "openai-compat")
202
+ return { kind, model: env.OPENAI_COMPAT_MODEL ?? "", baseURL: env.OPENAI_COMPAT_BASE_URL };
203
+ return { kind, model: env.ANTHROPIC_MODEL ?? "claude-opus-5-5", baseURL: env.ANTHROPIC_BASE_URL };
232
204
  }
233
- /**
234
- * 按环境变量创建,服务由 providerKind 决定:
235
- * - openai:OpenAI Responses API,OPENAI_API_KEY,可选 OPENAI_BASE_URL、OPENAI_MODEL
236
- * - openai-compat:兼容 /chat/completions 的服务,OPENAI_COMPAT_BASE_URL + OPENAI_COMPAT_MODEL(+ OPENAI_COMPAT_API_KEY),
237
- * 可选 OPENAI_COMPAT_EXTRA_BODY(JSON 对象,合并进每次请求体,例如开启思考的 {"enable_thinking":true})
238
- * - anthropic:Claude,ANTHROPIC_API_KEY,可选 ANTHROPIC_MODEL
239
- * JADE_MAX_TOKENS 是每次回复的输出上限。不设时 Claude 用 64000,其他服务用服务端默认值(有的只有 4096,思考很容易用完)
240
- * JADE_EFFORT 是思考的力度,见 effortFromEnv
241
- * JADE_RPM 是每分钟最多发几个请求,见 rpmFromEnv(限速在 withRetry 的 gate 里做)
242
- * JADE_IDLE_TIMEOUT 是等模型服务回数据的时限,见 idleTimeoutFromEnv
243
- * JADE_VISION 是模型能不能看图片,见 visionFromEnv
244
- * 只导入用到的那个服务的包:Anthropic 的 SDK 加载要一百多毫秒,拖慢启动
245
- */
246
205
  export async function providerFromEnv(env = process.env) {
247
- const kind = providerKind(env);
248
- if (!isBuiltinKind(kind))
249
- throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(kind)}`);
250
- const maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
251
- const effort = effortFromEnv(env);
252
- // 写错时在这里就报错,不等到第一次请求
253
- rpmFromEnv(env);
254
- const idleTimeoutMs = idleTimeoutFromEnv(env);
255
- const toolResultImages = visionFromEnv(env);
256
- if (kind === "openai") {
257
- if (!env.OPENAI_API_KEY)
258
- throw new Error("OPENAI_API_KEY is required for the openai provider");
259
- const { openaiResponsesProvider } = await import("@uncarved/provider-openai-responses");
260
- return openaiResponsesProvider({
261
- baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1",
262
- apiKey: env.OPENAI_API_KEY,
263
- model: env.OPENAI_MODEL ?? "gpt-5",
264
- maxTokens,
265
- // 设了思考力度说明是会思考的模型,顺带要思考摘要,否则服务端只思考不返回内容。
266
- // 没设时不发 reasoning:不知道模型会不会思考,发给不支持的模型会被拒绝
267
- reasoning: effort ? { effort: effort, summary: "auto" } : undefined,
268
- idleTimeoutMs,
269
- toolResultImages,
270
- });
271
- }
272
- if (kind === "openai-compat") {
273
- if (!env.OPENAI_COMPAT_BASE_URL)
274
- throw new Error("OPENAI_COMPAT_BASE_URL is required for the openai-compat provider");
275
- if (!env.OPENAI_COMPAT_MODEL)
276
- throw new Error("OPENAI_COMPAT_MODEL is required when OPENAI_COMPAT_BASE_URL is set");
277
- const { openaiCompatProvider } = await import("@uncarved/provider-openai-compat");
278
- return openaiCompatProvider({
279
- baseURL: env.OPENAI_COMPAT_BASE_URL,
280
- apiKey: env.OPENAI_COMPAT_API_KEY,
281
- model: env.OPENAI_COMPAT_MODEL,
282
- maxTokens,
283
- extraBody: env.OPENAI_COMPAT_EXTRA_BODY ? jsonObject("OPENAI_COMPAT_EXTRA_BODY", env.OPENAI_COMPAT_EXTRA_BODY) : undefined,
284
- idleTimeoutMs,
285
- toolResultImages,
286
- });
287
- }
288
- const { anthropicProvider } = await import("@uncarved/provider-anthropic");
289
- // 地址和密钥从 env 取,不让 SDK 自己读 process.env:ctx.complete 指定的保存过的模型,env 不是 process.env
290
- return anthropicProvider({
291
- apiKey: env.ANTHROPIC_API_KEY,
292
- baseURL: env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com",
293
- model: env.ANTHROPIC_MODEL,
294
- effort: (effort ?? "high"),
295
- maxTokens,
206
+ const kind = providerKind(env);
207
+ if (!isBuiltinKind(kind))
208
+ throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(kind)}`);
209
+ const maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
210
+ const effort = effortFromEnv(env);
211
+ rpmFromEnv(env);
212
+ const idleTimeoutMs = idleTimeoutFromEnv(env);
213
+ const toolResultImages = visionFromEnv(env);
214
+ if (kind === "openai") {
215
+ if (!env.OPENAI_API_KEY)
216
+ throw new Error("OPENAI_API_KEY is required for the openai provider");
217
+ const { openaiResponsesProvider } = await import("@uncarved/provider-openai-responses");
218
+ return openaiResponsesProvider({
219
+ baseURL: env.OPENAI_BASE_URL ?? "https://api.openai.com/v1",
220
+ apiKey: env.OPENAI_API_KEY,
221
+ model: env.OPENAI_MODEL ?? "gpt-5",
222
+ maxTokens,
223
+ reasoning: effort ? { effort, summary: "auto" } : undefined,
224
+ idleTimeoutMs,
225
+ toolResultImages
296
226
  });
227
+ }
228
+ if (kind === "openai-compat") {
229
+ if (!env.OPENAI_COMPAT_BASE_URL)
230
+ throw new Error("OPENAI_COMPAT_BASE_URL is required for the openai-compat provider");
231
+ if (!env.OPENAI_COMPAT_MODEL)
232
+ throw new Error("OPENAI_COMPAT_MODEL is required when OPENAI_COMPAT_BASE_URL is set");
233
+ const { openaiCompatProvider } = await import("@uncarved/provider-openai-compat");
234
+ return openaiCompatProvider({
235
+ baseURL: env.OPENAI_COMPAT_BASE_URL,
236
+ apiKey: env.OPENAI_COMPAT_API_KEY,
237
+ model: env.OPENAI_COMPAT_MODEL,
238
+ maxTokens,
239
+ extraBody: env.OPENAI_COMPAT_EXTRA_BODY ? jsonObject("OPENAI_COMPAT_EXTRA_BODY", env.OPENAI_COMPAT_EXTRA_BODY) : undefined,
240
+ idleTimeoutMs,
241
+ toolResultImages
242
+ });
243
+ }
244
+ const { anthropicProvider } = await import("@uncarved/provider-anthropic");
245
+ return anthropicProvider({
246
+ apiKey: env.ANTHROPIC_API_KEY,
247
+ baseURL: env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com",
248
+ model: env.ANTHROPIC_MODEL,
249
+ effort: effort ?? "high",
250
+ maxTokens
251
+ });
297
252
  }
298
- /** 服务提供的模型列表;不支持或出错时返回空数组 */
299
253
  export async function listModels(env = process.env, fetchImpl = fetch) {
300
- const kind = providerKind(env);
301
- if (!isBuiltinKind(kind))
302
- return [];
303
- const info = providerInfo(env);
304
- const base = (info.baseURL ?? "https://api.anthropic.com").replace(/\/$/, "");
305
- const headers = kind === "anthropic"
306
- ? { "x-api-key": env.ANTHROPIC_API_KEY ?? "", "anthropic-version": "2023-06-01" }
307
- : (kind === "openai" ? env.OPENAI_API_KEY : env.OPENAI_COMPAT_API_KEY)
308
- ? { authorization: `Bearer ${kind === "openai" ? env.OPENAI_API_KEY : env.OPENAI_COMPAT_API_KEY}` }
309
- : {};
310
- try {
311
- const res = await fetchImpl(kind === "anthropic" ? `${base}/v1/models?limit=100` : `${base}/models`, {
312
- headers,
313
- signal: AbortSignal.timeout(10_000),
314
- });
315
- if (!res.ok)
316
- return [];
317
- const body = (await res.json());
318
- return (body.data ?? []).flatMap((m) => (typeof m.id === "string" ? [m.id] : []));
319
- }
320
- catch {
321
- return [];
322
- }
254
+ const kind = providerKind(env);
255
+ if (!isBuiltinKind(kind))
256
+ return [];
257
+ const info = providerInfo(env);
258
+ const base = (info.baseURL ?? "https://api.anthropic.com").replace(/\/$/, "");
259
+ const headers = kind === "anthropic" ? { "x-api-key": env.ANTHROPIC_API_KEY ?? "", "anthropic-version": "2023-06-01" } : (kind === "openai" ? env.OPENAI_API_KEY : env.OPENAI_COMPAT_API_KEY) ? { authorization: `Bearer ${kind === "openai" ? env.OPENAI_API_KEY : env.OPENAI_COMPAT_API_KEY}` } : {};
260
+ try {
261
+ const res = await fetchImpl(kind === "anthropic" ? `${base}/v1/models?limit=100` : `${base}/models`, {
262
+ headers,
263
+ signal: AbortSignal.timeout(1e4)
264
+ });
265
+ if (!res.ok)
266
+ return [];
267
+ const body = await res.json();
268
+ return (body.data ?? []).flatMap((m) => typeof m.id === "string" ? [m.id] : []);
269
+ } catch {
270
+ return [];
271
+ }
323
272
  }
324
273
  export function jsonObject(name, text) {
325
- let value;
326
- try {
327
- value = JSON.parse(text);
328
- }
329
- catch {
330
- throw new Error(`${name} must be a JSON object, got ${JSON.stringify(text)}`);
331
- }
332
- if (typeof value !== "object" || value === null || Array.isArray(value))
333
- throw new Error(`${name} must be a JSON object, got ${text}`);
334
- return value;
274
+ let value;
275
+ try {
276
+ value = JSON.parse(text);
277
+ } catch {
278
+ throw new Error(`${name} must be a JSON object, got ${JSON.stringify(text)}`);
279
+ }
280
+ if (typeof value !== "object" || value === null || Array.isArray(value))
281
+ throw new Error(`${name} must be a JSON object, got ${text}`);
282
+ return value;
335
283
  }