@uncarved/jade 0.3.1 → 0.4.1

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