@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,516 +1,463 @@
1
- // /model:选服务、填地址和密钥、选模型、改输出上限、思考力度、上下文窗口、限速和能不能看图。
2
- // 配置写进 $JADE_HOME/.env;用过的服务和模型记在 $JADE_HOME/models.json 里(saved.ts),可以直接切回去。
3
- //
4
- // 从旧 jade 的 ui/configure.ts 移植。省掉了旧 jade 的"插件提供的模型服务"(新的 jade 还没有这种服务),
5
- // 其余流程一样。
6
1
  import { readFile, rm, writeFile } from "node:fs/promises";
7
2
  import { hasProvider, parseTokens } from "./config.js";
8
3
  import { contextWindow } from "./context.js";
9
- import { EFFORTS, isBuiltinKind, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
4
+ import { EFFORTS, fallbacksFromEnv, isBuiltinKind, isOfficialAnthropic, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
10
5
  import { MODEL_SETTINGS, readSavedServices, updateEnvFile, writeSavedServices } from "./saved.js";
11
6
  const PROVIDERS = [
12
- { kind: "openai-compat", label: "OpenAI-compatible service", hint: "any /chat/completions endpoint" },
13
- { kind: "openai", label: "OpenAI", hint: "Responses API" },
14
- { kind: "anthropic", label: "Anthropic", hint: "Claude" },
7
+ { kind: "openai-compat", label: "OpenAI-compatible service", hint: "any /chat/completions endpoint" },
8
+ { kind: "openai", label: "OpenAI", hint: "Responses API" },
9
+ { kind: "anthropic", label: "Anthropic", hint: "Claude" }
15
10
  ];
16
- /** JADE_VISION 设成了什么;没设或写错时 undefined */
17
11
  function visionSetting(env) {
18
- if (!env.JADE_VISION?.trim())
19
- return undefined;
20
- try {
21
- return visionFromEnv({ JADE_VISION: env.JADE_VISION });
22
- }
23
- catch {
24
- return undefined;
25
- }
12
+ if (!env.JADE_VISION?.trim())
13
+ return;
14
+ try {
15
+ return visionFromEnv({ JADE_VISION: env.JADE_VISION });
16
+ } catch {
17
+ return;
18
+ }
26
19
  }
27
20
  function visionHint(env, kind) {
28
- const v = visionSetting(env);
29
- return v === undefined ? `${isBuiltinKind(kind) && kind !== "openai-compat" ? "yes" : "no"} (default)` : v ? "yes" : "no";
21
+ const v = visionSetting(env);
22
+ return v === undefined ? `${isBuiltinKind(kind) && kind !== "openai-compat" ? "yes" : "no"} (default)` : v ? "yes" : "no";
23
+ }
24
+ function fallbacksSetting(env) {
25
+ if (!env.JADE_FALLBACKS?.trim())
26
+ return;
27
+ try {
28
+ return fallbacksFromEnv({ JADE_FALLBACKS: env.JADE_FALLBACKS });
29
+ } catch {
30
+ return;
31
+ }
32
+ }
33
+ function fallbacksHint(env, baseURL) {
34
+ const v = fallbacksSetting(env);
35
+ return v === undefined ? `${isOfficialAnthropic(baseURL) ? "on" : "off"} (default)` : v ? "on" : "off";
30
36
  }
31
- /** 一个服务包含的变量(不含模型名) */
32
37
  const serviceKeys = (kind) => ["JADE_PROVIDER", URL_KEY[kind], KEY_KEY[kind]];
33
38
  const pick = (env, keys) => {
34
- const out = {};
35
- for (const k of keys)
36
- if (env[k] !== undefined)
37
- out[k] = env[k];
38
- return out;
39
+ const out = {};
40
+ for (const k of keys)
41
+ if (env[k] !== undefined)
42
+ out[k] = env[k];
43
+ return out;
39
44
  };
40
- /** keys 里明确清掉(设成默认)的那些:空字符串表示"不设",写进 models.json 时删掉;env 里没提到的不算 */
41
45
  const blank = (env, keys) => {
42
- const out = {};
43
- for (const k of keys)
44
- if (k in env && env[k] === undefined)
45
- out[k] = "";
46
- return out;
46
+ const out = {};
47
+ for (const k of keys)
48
+ if (k in env && env[k] === undefined)
49
+ out[k] = "";
50
+ return out;
47
51
  };
48
- /** 服务的类型、地址和密钥都相同的算同一个;配置无效时返回 undefined */
49
52
  function serviceId(env) {
50
- try {
51
- const i = providerInfo(env);
52
- if (!isBuiltinKind(i.kind))
53
- return undefined;
54
- return `${i.kind}|${i.baseURL ?? ""}|${env[KEY_KEY[i.kind]] ?? ""}`;
55
- }
56
- catch {
57
- return undefined;
58
- }
53
+ try {
54
+ const i = providerInfo(env);
55
+ if (!isBuiltinKind(i.kind))
56
+ return;
57
+ return `${i.kind}|${i.baseURL ?? ""}|${env[KEY_KEY[i.kind]] ?? ""}`;
58
+ } catch {
59
+ return;
60
+ }
59
61
  }
60
- /** 选择列表里服务的说明:类型和地址的主机名 */
61
62
  function describeService(service) {
62
- const i = providerInfo(service.env);
63
- let host = i.baseURL ?? "";
64
- try {
65
- host = new URL(host).host;
66
- }
67
- catch { }
68
- return [i.kind, host].filter(Boolean).join(" · ");
63
+ const i = providerInfo(service.env);
64
+ let host = i.baseURL ?? "";
65
+ try {
66
+ host = new URL(host).host;
67
+ } catch {}
68
+ return [i.kind, host].filter(Boolean).join(" · ");
69
69
  }
70
- /** 保存过的、不是当前的模型,按服务分组:当前服务的在前 */
71
70
  function otherModels(services, currentId, currentModel) {
72
- return [...services.filter((s) => serviceId(s.env) === currentId), ...services.filter((s) => serviceId(s.env) !== currentId)].flatMap((s) => s.models.filter((m) => !(serviceId(s.env) === currentId && m.name === currentModel)).map((m) => ({ service: s, model: m })));
71
+ return [...services.filter((s) => serviceId(s.env) === currentId), ...services.filter((s) => serviceId(s.env) !== currentId)].flatMap((s) => s.models.filter((m) => !(serviceId(s.env) === currentId && m.name === currentModel)).map((m) => ({ service: s, model: m })));
73
72
  }
74
- /** Claude 不设输出上限时用的值:和 @uncarved/provider-anthropic 里的默认值一致(不从那里导入:加载它的 SDK 要一百多毫秒) */
75
73
  const ANTHROPIC_DEFAULT_MAX_TOKENS = 64000;
76
- /** 选项说明里放不下的长文本截短 */
77
- const shorten = (text, max = 40) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
78
- const errorText = (err) => (err instanceof Error ? err.message : String(err));
79
- /** 模型设置那一项的简要说明,例如 "64K out · 1M ctx · images";settings 是这个模型自己的设置变量 */
74
+ const shorten = (text, max = 40) => text.length > max ? `${text.slice(0, max - 1)}…` : text;
75
+ const errorText = (err) => err instanceof Error ? err.message : String(err);
80
76
  function settingsSummary(settings, kind, window) {
81
- const images = visionSetting({ JADE_VISION: settings.JADE_VISION }) ?? (isBuiltinKind(kind) && kind !== "openai-compat");
82
- return [
83
- settings.JADE_MAX_TOKENS && `${settings.JADE_MAX_TOKENS} out`,
84
- settings.JADE_EFFORT && `${settings.JADE_EFFORT} effort`,
85
- `${settings.JADE_CONTEXT_WINDOW ?? window} ctx`,
86
- settings.JADE_RPM && `${settings.JADE_RPM}/min`,
87
- images ? "images" : "no images",
88
- ]
89
- .filter(Boolean)
90
- .join(" · ");
77
+ const images = visionSetting({ JADE_VISION: settings.JADE_VISION }) ?? (isBuiltinKind(kind) && kind !== "openai-compat");
78
+ return [
79
+ settings.JADE_MAX_TOKENS && `${settings.JADE_MAX_TOKENS} out`,
80
+ settings.JADE_EFFORT && `${settings.JADE_EFFORT} effort`,
81
+ `${settings.JADE_CONTEXT_WINDOW ?? window} ctx`,
82
+ settings.JADE_RPM && `${settings.JADE_RPM}/min`,
83
+ images ? "images" : "no images"
84
+ ].filter(Boolean).join(" · ");
91
85
  }
92
86
  export function configurator(opts) {
93
- const { ui, envFile, modelsFile } = opts;
94
- const report = (text) => opts.report(text);
95
- /** 保存过的、有效的服务,最近用过的在前 */
96
- const savedServices = async () => (await readSavedServices(modelsFile)).filter((s) => serviceId(s.env) !== undefined);
97
- /** 输入的 token 数:空表示不设;写错时报告并返回 false */
98
- const tokensInput = (name, text) => {
99
- if (!text)
100
- return true;
101
- try {
102
- parseTokens(name, text);
103
- return true;
104
- }
105
- catch (err) {
106
- report(errorText(err));
107
- return false;
108
- }
87
+ const { ui, envFile, modelsFile } = opts;
88
+ const report = (text) => opts.report(text);
89
+ const savedServices = async () => (await readSavedServices(modelsFile)).filter((s) => serviceId(s.env) !== undefined);
90
+ const tokensInput = (name, text) => {
91
+ if (!text)
92
+ return true;
93
+ try {
94
+ parseTokens(name, text);
95
+ return true;
96
+ } catch (err) {
97
+ report(errorText(err));
98
+ return false;
99
+ }
100
+ };
101
+ async function remember(replacing) {
102
+ const env = opts.env();
103
+ if (!hasProvider(env))
104
+ return;
105
+ const id = serviceId(env);
106
+ const model = providerInfo(env).model;
107
+ const kind = providerKind(env);
108
+ if (!id || !model || !isBuiltinKind(kind))
109
+ return;
110
+ const all = await readSavedServices(modelsFile);
111
+ const old = all.filter((s) => {
112
+ const sid = serviceId(s.env);
113
+ return sid !== undefined && (sid === id || replacing !== undefined && sid === replacing);
114
+ });
115
+ const models = old.flatMap((s) => s.models).filter((m, i, list) => m.name !== model && list.findIndex((x) => x.name === m.name) === i);
116
+ const service = {
117
+ env: { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind },
118
+ models: [{ name: model, settings: pick(env, MODEL_SETTINGS) }, ...models]
109
119
  };
110
- /**
111
- * 把当前的服务和模型记下来,都放到最前面。
112
- * replacing:换了密钥的那个服务原来的 id,它下面的模型归到新的密钥下
113
- */
114
- async function remember(replacing) {
115
- const env = opts.env();
116
- if (!hasProvider(env))
117
- return;
118
- const id = serviceId(env);
119
- const model = providerInfo(env).model;
120
- const kind = providerKind(env);
121
- if (!id || !model || !isBuiltinKind(kind))
122
- return;
123
- // 写回时保留现在认不出的服务,不然它和它的密钥就丢了
124
- const all = await readSavedServices(modelsFile);
125
- const old = all.filter((s) => {
126
- const sid = serviceId(s.env);
127
- return sid !== undefined && (sid === id || (replacing !== undefined && sid === replacing));
128
- });
129
- const models = old.flatMap((s) => s.models).filter((m, i, list) => m.name !== model && list.findIndex((x) => x.name === m.name) === i);
130
- const service = {
131
- env: { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind },
132
- models: [{ name: model, settings: pick(env, MODEL_SETTINGS) }, ...models],
133
- };
134
- await writeSavedServices(modelsFile, [service, ...all.filter((s) => !old.includes(s))]);
120
+ await writeSavedServices(modelsFile, [service, ...all.filter((s) => !old.includes(s))]);
121
+ }
122
+ async function applyConfig(updates, replacing) {
123
+ const before = await readFile(envFile, "utf8").catch(() => {
124
+ return;
125
+ });
126
+ await updateEnvFile(envFile, updates, { ...opts.env() });
127
+ try {
128
+ await opts.apply();
129
+ } catch (err) {
130
+ await (before === undefined ? rm(envFile, { force: true }) : writeFile(envFile, before)).catch(() => {});
131
+ report(`Not saved: the configuration is incomplete: ${errorText(err)}`);
132
+ return false;
135
133
  }
136
- /** 保存配置并换上新的 provider;失败时报告原因,旧的配置和 provider 继续用 */
137
- async function applyConfig(updates, replacing) {
138
- const before = await readFile(envFile, "utf8").catch(() => undefined);
139
- // 传一份拷贝:apply 成功之前插件用的还是旧的那份(失败时状态栏显示的就是实际在用的)
140
- await updateEnvFile(envFile, updates, { ...opts.env() });
141
- try {
142
- await opts.apply();
143
- }
144
- catch (err) {
145
- // 放回原来的 .env:不然这次会话还用旧的,下次启动却读到这份用不了的配置
146
- await (before === undefined ? rm(envFile, { force: true }) : writeFile(envFile, before)).catch(() => { });
147
- report(`Not saved: the configuration is incomplete: ${errorText(err)}`);
148
- return false;
149
- }
150
- const info = providerInfo(opts.env());
151
- await remember(replacing).catch((err) => report(`Could not save the model list to ${modelsFile}: ${errorText(err)}`));
152
- report(`Model: ${info.model} (${info.kind}${info.baseURL ? `, ${info.baseURL}` : ""}). Saved to ${envFile}.`);
153
- return true;
134
+ const info = providerInfo(opts.env());
135
+ await remember(replacing).catch((err) => report(`Could not save the model list to ${modelsFile}: ${errorText(err)}`));
136
+ report(`Model: ${info.model} (${info.kind}${info.baseURL ? `, ${info.baseURL}` : ""}). Saved to ${envFile}.`);
137
+ return true;
138
+ }
139
+ function useSaved(s, m) {
140
+ const kind = providerKind(s.env);
141
+ if (!isBuiltinKind(kind)) {
142
+ report(`The saved service ${describeService(s)} is not one of the built-in providers.`);
143
+ return Promise.resolve(false);
154
144
  }
155
- /** 换成保存过的服务 s 上的模型 m:服务的变量和模型的设置写进 .env,模型没设的设置删掉 */
156
- function useSaved(s, m) {
157
- const kind = providerKind(s.env);
158
- if (!isBuiltinKind(kind)) {
159
- report(`The saved service ${describeService(s)} is not one of the built-in providers.`);
160
- return Promise.resolve(false);
161
- }
162
- const updates = {};
163
- for (const k of serviceKeys(kind))
164
- updates[k] = s.env[k];
165
- for (const k of MODEL_SETTINGS)
166
- updates[k] = m.settings[k];
167
- updates.JADE_PROVIDER = kind;
168
- updates[MODEL_KEY[kind]] = m.name;
169
- return applyConfig(updates);
145
+ const updates = {};
146
+ for (const k of serviceKeys(kind))
147
+ updates[k] = s.env[k];
148
+ for (const k of MODEL_SETTINGS)
149
+ updates[k] = m.settings[k];
150
+ updates.JADE_PROVIDER = kind;
151
+ updates[MODEL_KEY[kind]] = m.name;
152
+ return applyConfig(updates);
153
+ }
154
+ async function switchModel(model) {
155
+ const env = opts.env();
156
+ const id = serviceId(env);
157
+ const service = (await savedServices()).find((s) => serviceId(s.env) === id);
158
+ const saved = service?.models.find((m) => m.name === model);
159
+ if (service && saved)
160
+ return useSaved(service, saved);
161
+ const kind = providerKind(env);
162
+ if (!isBuiltinKind(kind)) {
163
+ report(`JADE_PROVIDER must be one of ${PROVIDERS.map((p) => p.kind).join(", ")}; set the model in ${envFile}.`);
164
+ return false;
170
165
  }
171
- /**
172
- * 在当前的服务上换成 model:用过的带上它自己的设置;新的模型沿用输出上限、思考力度和额外请求参数,
173
- * 上下文窗口不沿用(不同模型差别很大),按模型名推断
174
- */
175
- async function switchModel(model) {
176
- const env = opts.env();
177
- const id = serviceId(env);
178
- const service = (await savedServices()).find((s) => serviceId(s.env) === id);
179
- const saved = service?.models.find((m) => m.name === model);
180
- if (service && saved)
181
- return useSaved(service, saved);
182
- const kind = providerKind(env);
183
- if (!isBuiltinKind(kind)) {
184
- report(`JADE_PROVIDER must be one of ${PROVIDERS.map((p) => p.kind).join(", ")}; set the model in ${envFile}.`);
185
- return false;
186
- }
187
- return applyConfig({ [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined });
166
+ return applyConfig({ [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined });
167
+ }
168
+ async function chooseModel(env, current, saved = []) {
169
+ const models = await listModels(env, opts.fetch);
170
+ const BACK = "\x00back";
171
+ if (models.length > 0) {
172
+ const OTHER = "\x00other";
173
+ const picked = await ui.select({
174
+ title: "Choose a model",
175
+ options: [...models.map((m) => ({ label: m, value: m, ...m === current ? { hint: "current" } : saved.includes(m) ? { hint: "saved" } : {} })), { label: "Enter a name…", value: OTHER }, { label: "Back", value: BACK }]
176
+ }, opts.signal);
177
+ if (picked === BACK)
178
+ return;
179
+ if (picked !== OTHER)
180
+ return picked;
188
181
  }
189
- /** 选模型:服务能列出模型时从列表里选,否则手动输入。选 Back 和取消一样返回 undefined */
190
- async function chooseModel(env, current, saved = []) {
191
- const models = await listModels(env, opts.fetch);
192
- const BACK = "\0back";
193
- if (models.length > 0) {
194
- const OTHER = "\0other";
195
- const picked = await ui.select({
196
- title: "Choose a model",
197
- options: [...models.map((m) => ({ label: m, value: m, ...(m === current ? { hint: "current" } : saved.includes(m) ? { hint: "saved" } : {}) })), { label: "Enter a name…", value: OTHER }, { label: "Back", value: BACK }],
198
- }, opts.signal);
199
- if (picked === BACK)
200
- return undefined;
201
- if (picked !== OTHER)
202
- return picked;
203
- }
204
- return (await ui.input({ title: "Model name", ...(current ? { initial: current } : {}) }, opts.signal)) || undefined;
182
+ return await ui.input({ title: "Model name", ...current ? { initial: current } : {} }, opts.signal) || undefined;
183
+ }
184
+ async function configureProvider() {
185
+ const env = opts.env();
186
+ const current = hasProvider(env) ? providerInfo(env) : undefined;
187
+ const currentId = hasProvider(env) ? serviceId(env) : undefined;
188
+ const kindName = await ui.select({
189
+ title: "Which service should jade use?",
190
+ options: PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.kind === current?.kind ? `${p.hint} · current` : p.hint }))
191
+ }, opts.signal);
192
+ if (!kindName || !isBuiltinKind(kindName))
193
+ return false;
194
+ const kind = kindName;
195
+ const same = kind === current?.kind;
196
+ let baseURL = env[URL_KEY[kind]];
197
+ const fallback = kind === "openai" ? "https://api.openai.com/v1" : "";
198
+ const placeholder = kind === "anthropic" ? "empty for https://api.anthropic.com (SDK adds /v1)" : "https://example.com/v1";
199
+ const url = await ui.input({ title: "Base URL", initial: baseURL ?? fallback, placeholder }, opts.signal);
200
+ if (url === undefined)
201
+ return false;
202
+ if (kind === "openai-compat" && !url) {
203
+ report("A base URL is required.");
204
+ return false;
205
205
  }
206
- async function configureProvider() {
207
- const env = opts.env();
208
- const current = hasProvider(env) ? providerInfo(env) : undefined;
209
- const currentId = hasProvider(env) ? serviceId(env) : undefined;
210
- const kindName = await ui.select({
211
- title: "Which service should jade use?",
212
- options: PROVIDERS.map((p) => ({ label: p.label, value: p.kind, hint: p.kind === current?.kind ? `${p.hint} · current` : p.hint })),
206
+ baseURL = url || undefined;
207
+ const sameAddress = (e) => {
208
+ const i = providerInfo(e);
209
+ return i.kind === kind && (i.baseURL ?? "") === (providerInfo({ JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL }).baseURL ?? "");
210
+ };
211
+ const services = await savedServices();
212
+ const known = current && sameAddress(env) ? env[KEY_KEY[kind]] : services.find((s) => sameAddress(s.env))?.env[KEY_KEY[kind]];
213
+ const answer = await ui.input({
214
+ title: "API key",
215
+ mask: true,
216
+ placeholder: known ? "leave empty to keep the saved key" : kind === "openai-compat" ? "leave empty if the service needs none" : ""
217
+ }, opts.signal);
218
+ if (answer === undefined)
219
+ return false;
220
+ const key = answer || known;
221
+ const serviceEnv = { JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL, [KEY_KEY[kind]]: key };
222
+ const target = services.find((s) => serviceId(s.env) === serviceId(serviceEnv));
223
+ const model = await chooseModel({ ...env, ...serviceEnv }, same ? current?.model : undefined, target?.models.map((m) => m.name));
224
+ if (!model)
225
+ return false;
226
+ const saved = target?.models.find((m) => m.name === model);
227
+ if (target && saved)
228
+ return useSaved({ ...target, env: { ...target.env, ...pick(serviceEnv, serviceKeys(kind)) } }, saved);
229
+ const updates = { ...serviceEnv, [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined };
230
+ const sameService = same && sameAddress(env);
231
+ if (!sameService)
232
+ for (const k of MODEL_SETTINGS)
233
+ updates[k] = undefined;
234
+ if (kind !== "anthropic" && !(sameService && env.JADE_MAX_TOKENS)) {
235
+ const max = await ui.input({ title: "Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", initial: "32K" }, opts.signal);
236
+ if (max === undefined || !tokensInput("Output limit", max))
237
+ return false;
238
+ if (max)
239
+ updates.JADE_MAX_TOKENS = max;
240
+ }
241
+ const rekeyed = sameService && currentId !== undefined && key !== env[KEY_KEY[kind]];
242
+ return applyConfig(updates, rekeyed ? currentId : undefined);
243
+ }
244
+ async function configureSettings(target) {
245
+ const { title, kind, model, baseURL } = target;
246
+ const efforts = isBuiltinKind(kind) ? EFFORTS[kind] : undefined;
247
+ while (true) {
248
+ const env = await target.read();
249
+ const action = await ui.select({
250
+ title: `Settings for ${title}`,
251
+ options: [
252
+ { label: "Output limit per reply", value: "max", hint: env.JADE_MAX_TOKENS ? `${env.JADE_MAX_TOKENS} tokens` : kind === "anthropic" ? `${ANTHROPIC_DEFAULT_MAX_TOKENS} tokens (default)` : "service default" },
253
+ ...efforts ? [{ label: "Reasoning effort", value: "effort", hint: env.JADE_EFFORT ?? (kind === "anthropic" ? "high (default)" : "service default") }] : [],
254
+ { label: "Context window", value: "window", hint: `${contextWindow(model, env)} tokens${env.JADE_CONTEXT_WINDOW ? "" : " (default)"}` },
255
+ { label: "Requests per minute", value: "rpm", hint: env.JADE_RPM ? `${env.JADE_RPM}/min` : "no limit (slows down after being rate limited)" },
256
+ { label: "Can see images", value: "vision", hint: visionHint(env, kind) },
257
+ ...kind === "anthropic" ? [{ label: "Server-side fallback", value: "fallbacks", hint: fallbacksHint(env, baseURL) }] : [],
258
+ ...kind === "openai-compat" ? [{ label: "Extra request body", value: "extra", hint: env.OPENAI_COMPAT_EXTRA_BODY ? shorten(env.OPENAI_COMPAT_EXTRA_BODY) : "none" }] : [],
259
+ { label: "Back", value: "back" }
260
+ ]
261
+ }, opts.signal);
262
+ if (action === undefined || action === "back")
263
+ return;
264
+ if (action === "max") {
265
+ const max = await ui.input({ title: "Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", initial: env.JADE_MAX_TOKENS ?? "32K" }, opts.signal);
266
+ if (max !== undefined && tokensInput("Output limit", max))
267
+ await target.update({ JADE_MAX_TOKENS: max || undefined });
268
+ } else if (action === "effort" && efforts) {
269
+ const DEFAULT = "\x00default";
270
+ const effort = await ui.select({
271
+ title: "Reasoning effort",
272
+ options: [...efforts.map((e) => ({ label: e, value: e, ...e === env.JADE_EFFORT ? { hint: "current" } : {} })), { label: "Default", value: DEFAULT, hint: kind === "anthropic" ? "high" : "service default" }]
213
273
  }, opts.signal);
214
- if (!kindName || !isBuiltinKind(kindName))
215
- return false;
216
- const kind = kindName;
217
- const same = kind === current?.kind;
218
- let baseURL = env[URL_KEY[kind]];
219
- if (kind !== "anthropic") {
220
- const fallback = kind === "openai" ? "https://api.openai.com/v1" : "";
221
- const answer = await ui.input({ title: "Base URL", initial: baseURL ?? fallback, placeholder: "https://example.com/v1" }, opts.signal);
222
- if (answer === undefined)
223
- return false;
224
- if (kind === "openai-compat" && !answer) {
225
- report("A base URL is required.");
226
- return false;
227
- }
228
- baseURL = answer || undefined;
274
+ if (effort !== undefined)
275
+ await target.update({ JADE_EFFORT: effort === DEFAULT ? undefined : effort });
276
+ } else if (action === "rpm") {
277
+ const n = await ui.input({ title: "Requests per minute, e.g. 20 for most free models (empty for no limit)", initial: env.JADE_RPM ?? "" }, opts.signal);
278
+ if (n === undefined)
279
+ continue;
280
+ try {
281
+ rpmFromEnv({ JADE_RPM: n });
282
+ } catch (err) {
283
+ report(errorText(err));
284
+ continue;
229
285
  }
230
- // 已知的密钥:当前服务的,或者保存过的同一个地址的服务的(最近用过的那个)
231
- const sameAddress = (e) => {
232
- const i = providerInfo(e);
233
- return i.kind === kind && (i.baseURL ?? "") === (providerInfo({ JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL }).baseURL ?? "");
234
- };
235
- const services = await savedServices();
236
- const known = current && sameAddress(env) ? env[KEY_KEY[kind]] : services.find((s) => sameAddress(s.env))?.env[KEY_KEY[kind]];
237
- const answer = await ui.input({
238
- title: "API key",
239
- mask: true,
240
- placeholder: known ? "leave empty to keep the saved key" : kind === "openai-compat" ? "leave empty if the service needs none" : "",
286
+ await target.update({ JADE_RPM: n.trim() || undefined });
287
+ } else if (action === "vision") {
288
+ const DEFAULT = "\x00default";
289
+ const current = visionSetting(env);
290
+ const choice = await ui.select({
291
+ title: "Can this model see images (screenshots, image files)?",
292
+ options: [
293
+ { label: "Yes", value: "on", hint: current === true ? "current" : "images are sent to the model" },
294
+ { label: "No", value: "off", hint: current === false ? "current" : "images are replaced with a note" },
295
+ { label: "Default", value: DEFAULT, hint: isBuiltinKind(kind) && kind !== "openai-compat" ? "yes" : "no" }
296
+ ]
241
297
  }, opts.signal);
242
- if (answer === undefined)
243
- return false;
244
- const key = answer || known;
245
- const serviceEnv = { JADE_PROVIDER: kind, [URL_KEY[kind]]: baseURL, [KEY_KEY[kind]]: key };
246
- const target = services.find((s) => serviceId(s.env) === serviceId(serviceEnv));
247
- const model = await chooseModel({ ...env, ...serviceEnv }, same ? current?.model : undefined, target?.models.map((m) => m.name));
248
- if (!model)
249
- return false;
250
- // 用过的模型带上它自己的设置
251
- const saved = target?.models.find((m) => m.name === model);
252
- if (target && saved)
253
- return useSaved({ ...target, env: { ...target.env, ...pick(serviceEnv, serviceKeys(kind)) } }, saved);
254
- const updates = { ...serviceEnv, [MODEL_KEY[kind]]: model, JADE_CONTEXT_WINDOW: undefined };
255
- // 换了服务的新模型从新服务的默认值开始:思考力度、额外请求参数各服务写法不同,限速、输出上限、
256
- // 能不能看图也是跟着服务和模型走的,沿用当前的容易错(例如免费服务的限速带到付费服务上)。
257
- // 同一个服务(只换了密钥)照旧沿用
258
- const sameService = same && sameAddress(env);
259
- if (!sameService)
260
- for (const k of MODEL_SETTINGS)
261
- updates[k] = undefined;
262
- // 其他服务常常默认只给 4096 个输出 token,带思考的模型很容易用完
263
- if (kind !== "anthropic" && !(sameService && env.JADE_MAX_TOKENS)) {
264
- const max = await ui.input({ title: "Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", initial: "32K" }, opts.signal);
265
- if (max === undefined || !tokensInput("Output limit", max))
266
- return false;
267
- if (max)
268
- updates.JADE_MAX_TOKENS = max;
269
- }
270
- // 同一个地址只换了密钥:原来的服务下的模型归到新的密钥下
271
- const rekeyed = sameService && currentId !== undefined && key !== env[KEY_KEY[kind]];
272
- return applyConfig(updates, rekeyed ? currentId : undefined);
273
- }
274
- /**
275
- * 某个模型的设置(输出上限、思考力度、上下文窗口、限速、能不能看图,openai-compat 还有额外请求参数)。
276
- * 改完一项回到这个菜单接着改(重新读一遍,显示的是改过的值);Back 或 Esc 才离开
277
- */
278
- async function configureSettings(target) {
279
- const { title, kind, model } = target;
280
- const efforts = isBuiltinKind(kind) ? EFFORTS[kind] : undefined;
281
- while (true) {
282
- const env = await target.read();
283
- const action = await ui.select({
284
- title: `Settings for ${title}`,
285
- options: [
286
- { label: "Output limit per reply", value: "max", hint: env.JADE_MAX_TOKENS ? `${env.JADE_MAX_TOKENS} tokens` : kind === "anthropic" ? `${ANTHROPIC_DEFAULT_MAX_TOKENS} tokens (default)` : "service default" },
287
- ...(efforts ? [{ label: "Reasoning effort", value: "effort", hint: env.JADE_EFFORT ?? (kind === "anthropic" ? "high (default)" : "service default") }] : []),
288
- { label: "Context window", value: "window", hint: `${contextWindow(model, env)} tokens${env.JADE_CONTEXT_WINDOW ? "" : " (default)"}` },
289
- { label: "Requests per minute", value: "rpm", hint: env.JADE_RPM ? `${env.JADE_RPM}/min` : "no limit (slows down after being rate limited)" },
290
- { label: "Can see images", value: "vision", hint: visionHint(env, kind) },
291
- ...(kind === "openai-compat" ? [{ label: "Extra request body", value: "extra", hint: env.OPENAI_COMPAT_EXTRA_BODY ? shorten(env.OPENAI_COMPAT_EXTRA_BODY) : "none" }] : []),
292
- { label: "Back", value: "back" },
293
- ],
294
- }, opts.signal);
295
- if (action === undefined || action === "back")
296
- return;
297
- // 每一项里按 Esc 或者输入有误:什么都不改,回到这个菜单
298
- if (action === "max") {
299
- const max = await ui.input({ title: "Output limit per reply in tokens, e.g. 32000, 64K (empty for the service default)", initial: env.JADE_MAX_TOKENS ?? "32K" }, opts.signal);
300
- if (max !== undefined && tokensInput("Output limit", max))
301
- await target.update({ JADE_MAX_TOKENS: max || undefined });
302
- }
303
- else if (action === "effort" && efforts) {
304
- const DEFAULT = "\0default";
305
- const effort = await ui.select({
306
- title: "Reasoning effort",
307
- options: [...efforts.map((e) => ({ label: e, value: e, ...(e === env.JADE_EFFORT ? { hint: "current" } : {}) })), { label: "Default", value: DEFAULT, hint: kind === "anthropic" ? "high" : "service default" }],
308
- }, opts.signal);
309
- if (effort !== undefined)
310
- await target.update({ JADE_EFFORT: effort === DEFAULT ? undefined : effort });
311
- }
312
- else if (action === "rpm") {
313
- const n = await ui.input({ title: "Requests per minute, e.g. 20 for most free models (empty for no limit)", initial: env.JADE_RPM ?? "" }, opts.signal);
314
- if (n === undefined)
315
- continue;
316
- try {
317
- rpmFromEnv({ JADE_RPM: n });
318
- }
319
- catch (err) {
320
- report(errorText(err));
321
- continue;
322
- }
323
- await target.update({ JADE_RPM: n.trim() || undefined });
324
- }
325
- else if (action === "vision") {
326
- const DEFAULT = "\0default";
327
- const current = visionSetting(env);
328
- const choice = await ui.select({
329
- title: "Can this model see images (screenshots, image files)?",
330
- options: [
331
- { label: "Yes", value: "on", hint: current === true ? "current" : "images are sent to the model" },
332
- { label: "No", value: "off", hint: current === false ? "current" : "images are replaced with a note" },
333
- { label: "Default", value: DEFAULT, hint: isBuiltinKind(kind) && kind !== "openai-compat" ? "yes" : "no" },
334
- ],
335
- }, opts.signal);
336
- if (choice === undefined)
337
- continue;
338
- if (await target.update({ JADE_VISION: choice === DEFAULT ? undefined : choice })) {
339
- const on = choice === DEFAULT ? isBuiltinKind(kind) && kind !== "openai-compat" : choice === "on";
340
- report(on ? "Images will be sent to the model." : "Images will be replaced with a note.");
341
- }
342
- }
343
- else if (action === "window") {
344
- const n = await ui.input({ title: "Context window in tokens, e.g. 128000, 512K, 1M (empty to infer it from the model name, or 256K if unknown)", initial: env.JADE_CONTEXT_WINDOW ?? "" }, opts.signal);
345
- if (n !== undefined && tokensInput("Context window", n))
346
- await target.update({ JADE_CONTEXT_WINDOW: n || undefined });
347
- }
348
- else if (action === "extra" && kind === "openai-compat") {
349
- const text = await ui.input({ title: 'JSON merged into every request for this model, e.g. {"enable_thinking":true} (empty for none)', initial: env.OPENAI_COMPAT_EXTRA_BODY ?? "" }, opts.signal);
350
- if (text === undefined)
351
- continue;
352
- if (text.trim()) {
353
- try {
354
- jsonObject("Extra request body", text);
355
- }
356
- catch (err) {
357
- report(errorText(err));
358
- continue;
359
- }
360
- }
361
- await target.update({ OPENAI_COMPAT_EXTRA_BODY: text.trim() || undefined });
362
- }
298
+ if (choice === undefined)
299
+ continue;
300
+ if (await target.update({ JADE_VISION: choice === DEFAULT ? undefined : choice })) {
301
+ const on = choice === DEFAULT ? isBuiltinKind(kind) && kind !== "openai-compat" : choice === "on";
302
+ report(on ? "Images will be sent to the model." : "Images will be replaced with a note.");
363
303
  }
364
- }
365
- /** 把模型的设置写进 models.json 里那一个模型;.env 不变(当前用的还是原来的模型)。改回默认值的设置从 settings 里删掉 */
366
- async function writeSavedModel(service, model, settings) {
367
- const id = serviceId(service.env);
368
- const all = await readSavedServices(modelsFile);
369
- const mine = id === undefined ? undefined : all.find((s) => serviceId(s.env) === id);
370
- if (!mine) {
371
- report(`Not saved: ${describeService(service)} is no longer in ${modelsFile}.`);
372
- return false;
304
+ } else if (action === "fallbacks" && kind === "anthropic") {
305
+ const DEFAULT = "\x00default";
306
+ const current = fallbacksSetting(env);
307
+ const choice = await ui.select({
308
+ title: "Retry with another model on the service side when Claude refuses for safety reasons?",
309
+ options: [
310
+ { label: "On", value: "on", hint: current === true ? "current" : "official API only; most relays reject it" },
311
+ { label: "Off", value: "off", hint: current === false ? "current" : "the field is not sent" },
312
+ { label: "Default", value: DEFAULT, hint: isOfficialAnthropic(baseURL) ? "on (official API)" : "off (not the official API)" }
313
+ ]
314
+ }, opts.signal);
315
+ if (choice !== undefined)
316
+ await target.update({ JADE_FALLBACKS: choice === DEFAULT ? undefined : choice });
317
+ } else if (action === "window") {
318
+ const n = await ui.input({ title: "Context window in tokens, e.g. 128000, 512K, 1M (empty to infer it from the model name, or 256K if unknown)", initial: env.JADE_CONTEXT_WINDOW ?? "" }, opts.signal);
319
+ if (n !== undefined && tokensInput("Context window", n))
320
+ await target.update({ JADE_CONTEXT_WINDOW: n || undefined });
321
+ } else if (action === "extra" && kind === "openai-compat") {
322
+ const text = await ui.input({ title: 'JSON merged into every request for this model, e.g. {"enable_thinking":true} (empty for none)', initial: env.OPENAI_COMPAT_EXTRA_BODY ?? "" }, opts.signal);
323
+ if (text === undefined)
324
+ continue;
325
+ if (text.trim()) {
326
+ try {
327
+ jsonObject("Extra request body", text);
328
+ } catch (err) {
329
+ report(errorText(err));
330
+ continue;
331
+ }
373
332
  }
374
- const mineIndex = all.indexOf(mine);
375
- const modelIndex = mine.models.findIndex((m) => m.name === model.name);
376
- // 在文件里现在的设置上改:菜单打开之后 models.json 可能被别的会话改过
377
- const merged = { ...(mine.models[modelIndex]?.settings ?? model.settings), ...pick(settings, MODEL_SETTINGS), ...blank(settings, MODEL_SETTINGS) };
378
- const next = { name: model.name, settings: Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined && v !== "")) };
379
- const models = modelIndex === -1 ? [next, ...mine.models] : [...mine.models.slice(0, modelIndex), next, ...mine.models.slice(modelIndex + 1)];
380
- await writeSavedServices(modelsFile, [...all.slice(0, mineIndex), { ...mine, models }, ...all.slice(mineIndex + 1)]);
381
- report(`Settings for ${model.name} (${describeService(mine)}) saved to ${modelsFile}.`);
382
- return true;
333
+ await target.update({ OPENAI_COMPAT_EXTRA_BODY: text.trim() || undefined });
334
+ }
383
335
  }
384
- /** 把保存过的模型从 models.json 里删掉;服务下没有模型了就连服务(和它的密钥)一起删掉 */
385
- async function forgetModel(service, model) {
386
- const id = serviceId(service.env);
387
- if (!id)
388
- return;
389
- const rest = (await readSavedServices(modelsFile))
390
- .map((s) => (serviceId(s.env) === id ? { ...s, models: s.models.filter((m) => m.name !== model.name) } : s))
391
- .filter((s) => s.models.length > 0);
392
- await writeSavedServices(modelsFile, rest);
393
- report(`Removed ${model.name} (${describeService(service)}).`);
336
+ }
337
+ async function writeSavedModel(service, model, settings) {
338
+ const id = serviceId(service.env);
339
+ const all = await readSavedServices(modelsFile);
340
+ const mine = id === undefined ? undefined : all.find((s) => serviceId(s.env) === id);
341
+ if (!mine) {
342
+ report(`Not saved: ${describeService(service)} is no longer in ${modelsFile}.`);
343
+ return false;
394
344
  }
395
- /**
396
- * 选中主菜单里一个模型后:切换、配置它(不用先切到它)、把它删掉或返回主菜单。
397
- * 当前的模型只能配置(切换没意义;删掉了下次进 /model 又会被记回来)。从设置里出来回到这个菜单;
398
- * 切换、删除、Back 或 Esc 回到主菜单
399
- */
400
- async function pickModelAction(o, isCurrent) {
401
- const kind = providerKind(o.service.env);
402
- // 当前的模型改 .env 就好——applyConfig 里的 remember 会把改完的 .env 写回 models.json;
403
- // 其他保存过的模型只改 models.json 里的那一个
404
- const read = isCurrent ? async () => pick(opts.env(), MODEL_SETTINGS) : () => savedSettings(o.service, o.model);
405
- while (true) {
406
- const settings = await read();
407
- const action = await ui.select({
408
- title: o.model.name,
409
- options: [
410
- ...(isCurrent
411
- ? []
412
- : [{ label: "Switch to it", value: "switch", hint: serviceId(o.service.env) === serviceId(opts.env()) ? "this service" : describeService(o.service) }]),
413
- { label: "Settings…", value: "settings", hint: settingsSummary(settings, kind, contextWindow(o.model.name, settings)) },
414
- ...(isCurrent ? [] : [{ label: "Remove", value: "forget" }]),
415
- { label: "Back", value: "back" },
416
- ],
417
- }, opts.signal);
418
- if (action === "settings") {
419
- await configureSettings({
420
- title: o.model.name,
421
- kind,
422
- model: o.model.name,
423
- read,
424
- update: (updates) => (isCurrent ? applyConfig(updates) : writeSavedModel(o.service, o.model, updates)),
425
- });
426
- continue;
427
- }
428
- // 用刚读到的设置切换:在这个菜单里改过的也带上
429
- if (action === "switch")
430
- await useSaved(o.service, { ...o.model, settings });
431
- else if (action === "forget")
432
- await forgetModel(o.service, o.model);
433
- return;
434
- }
345
+ const mineIndex = all.indexOf(mine);
346
+ const modelIndex = mine.models.findIndex((m) => m.name === model.name);
347
+ const merged = { ...mine.models[modelIndex]?.settings ?? model.settings, ...pick(settings, MODEL_SETTINGS), ...blank(settings, MODEL_SETTINGS) };
348
+ const next = { name: model.name, settings: Object.fromEntries(Object.entries(merged).filter(([, v]) => v !== undefined && v !== "")) };
349
+ const models = modelIndex === -1 ? [next, ...mine.models] : [...mine.models.slice(0, modelIndex), next, ...mine.models.slice(modelIndex + 1)];
350
+ await writeSavedServices(modelsFile, [...all.slice(0, mineIndex), { ...mine, models }, ...all.slice(mineIndex + 1)]);
351
+ report(`Settings for ${model.name} (${describeService(mine)}) saved to ${modelsFile}.`);
352
+ return true;
353
+ }
354
+ async function forgetModel(service, model) {
355
+ const id = serviceId(service.env);
356
+ if (!id)
357
+ return;
358
+ const rest = (await readSavedServices(modelsFile)).map((s) => serviceId(s.env) === id ? { ...s, models: s.models.filter((m) => m.name !== model.name) } : s).filter((s) => s.models.length > 0);
359
+ await writeSavedServices(modelsFile, rest);
360
+ report(`Removed ${model.name} (${describeService(service)}).`);
361
+ }
362
+ async function pickModelAction(o, isCurrent) {
363
+ const kind = providerKind(o.service.env);
364
+ const read = isCurrent ? async () => pick(opts.env(), MODEL_SETTINGS) : () => savedSettings(o.service, o.model);
365
+ while (true) {
366
+ const settings = await read();
367
+ const action = await ui.select({
368
+ title: o.model.name,
369
+ options: [
370
+ ...isCurrent ? [] : [{ label: "Switch to it", value: "switch", hint: serviceId(o.service.env) === serviceId(opts.env()) ? "this service" : describeService(o.service) }],
371
+ { label: "Settings…", value: "settings", hint: settingsSummary(settings, kind, contextWindow(o.model.name, settings)) },
372
+ ...isCurrent ? [] : [{ label: "Remove", value: "forget" }],
373
+ { label: "Back", value: "back" }
374
+ ]
375
+ }, opts.signal);
376
+ if (action === "settings") {
377
+ await configureSettings({
378
+ title: o.model.name,
379
+ kind,
380
+ model: o.model.name,
381
+ baseURL: providerInfo(o.service.env).baseURL,
382
+ read,
383
+ update: (updates) => isCurrent ? applyConfig(updates) : writeSavedModel(o.service, o.model, updates)
384
+ });
385
+ continue;
386
+ }
387
+ if (action === "switch")
388
+ await useSaved(o.service, { ...o.model, settings });
389
+ else if (action === "forget")
390
+ await forgetModel(o.service, o.model);
391
+ return;
435
392
  }
436
- /** 保存过的模型在 models.json 里现在的设置;找不到时用 fallback 那份 */
437
- async function savedSettings(service, fallback) {
438
- const id = serviceId(service.env);
439
- const mine = id === undefined ? undefined : (await readSavedServices(modelsFile)).find((s) => serviceId(s.env) === id);
440
- return mine?.models.find((m) => m.name === fallback.name)?.settings ?? fallback.settings;
393
+ }
394
+ async function savedSettings(service, fallback) {
395
+ const id = serviceId(service.env);
396
+ const mine = id === undefined ? undefined : (await readSavedServices(modelsFile)).find((s) => serviceId(s.env) === id);
397
+ return mine?.models.find((m) => m.name === fallback.name)?.settings ?? fallback.settings;
398
+ }
399
+ async function configureModel(arg) {
400
+ const env = opts.env();
401
+ if (!hasProvider(env))
402
+ return void await configureProvider();
403
+ await remember().catch(() => {});
404
+ if (arg) {
405
+ const saved = otherModels(await savedServices(), serviceId(env), providerInfo(env).model).find((o) => o.model.name === arg);
406
+ return void await (saved ? useSaved(saved.service, saved.model) : switchModel(arg));
441
407
  }
442
- async function configureModel(arg) {
443
- const env = opts.env();
444
- // 还没有配置模型:没有"当前的服务"可以换模型,先选服务
445
- if (!hasProvider(env))
446
- return void (await configureProvider());
447
- // 之前只有 .env 时配置的模型也记下来,之后换了不会丢
448
- await remember().catch(() => { });
449
- if (arg) {
450
- // 保存过的模型按名字切换(当前服务的优先),否则换当前服务的模型
451
- const saved = otherModels(await savedServices(), serviceId(env), providerInfo(env).model).find((o) => o.model.name === arg);
452
- return void (await (saved ? useSaved(saved.service, saved.model) : switchModel(arg)));
453
- }
454
- // 主菜单循环:保存过的模型全部直接列出(当前的在最前,然后是同一服务的),选中出一个子菜单
455
- // (切换 / 设置 / 删除 / 返回);配置某个模型、把它删掉都不用先切到它,做完回到主菜单再选。
456
- // 每一轮都重读当前配置:切换、配置之后模型和它的设置可能都变了
457
- while (true) {
458
- const env = opts.env();
459
- const id = serviceId(env);
460
- const kind = providerKind(env);
461
- const kindKnown = isBuiltinKind(kind);
462
- const info = providerInfo(env);
463
- const here = describeService({ env: kindKnown ? pick(env, serviceKeys(kind)) : {}, models: [] });
464
- const services = await savedServices();
465
- const multi = services.length > 1;
466
- const others = otherModels(services, id, info.model);
467
- const action = await ui.select({
468
- title: "Switch model",
469
- options: [
470
- {
471
- label: info.model,
472
- value: "current",
473
- hint: `${multi ? `${here} · ` : ""}current · ${settingsSummary(env, info.kind, contextWindow(info.model, env))}`,
474
- },
475
- ...others.map((o, i) => ({
476
- label: o.model.name,
477
- value: `saved:${i}`,
478
- hint: `${multi ? `${describeService(o.service)} · ` : ""}${settingsSummary(o.model.settings, providerKind(o.service.env), contextWindow(o.model.name, o.model.settings))}`,
479
- })),
480
- { label: "Add a model…", value: "add", hint: "from this service or another one" },
481
- ],
482
- }, opts.signal);
483
- if (action === undefined)
484
- return; // Esc:整个 /model 结束
485
- if (action === "current") {
486
- const service = { env: kindKnown ? { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind } : { JADE_PROVIDER: kind }, models: [] };
487
- await pickModelAction({ service, model: { name: info.model, settings: pick(env, MODEL_SETTINGS) } }, true);
488
- }
489
- else if (action.startsWith("saved:")) {
490
- const o = others[Number(action.slice(6))];
491
- if (o)
492
- await pickModelAction(o, false);
493
- }
494
- else if (action === "add") {
495
- const where = await ui.select({
496
- title: "Add a model from",
497
- options: [
498
- { label: "This service", value: "model", hint: here },
499
- { label: "Another service…", value: "provider", hint: "or change this one's base URL / API key" },
500
- { label: "Back", value: "back" },
501
- ],
502
- }, opts.signal);
503
- // 做完、Back、Esc 或没填完,都回到主菜单
504
- if (where === "model") {
505
- const saved = services.find((s) => serviceId(s.env) === id)?.models.map((m) => m.name);
506
- const model = await chooseModel(env, info.model, saved);
507
- if (model && model !== info.model)
508
- await switchModel(model);
509
- }
510
- else if (where === "provider")
511
- await configureProvider();
512
- }
513
- }
408
+ while (true) {
409
+ const env = opts.env();
410
+ const id = serviceId(env);
411
+ const kind = providerKind(env);
412
+ const kindKnown = isBuiltinKind(kind);
413
+ const info = providerInfo(env);
414
+ const here = describeService({ env: kindKnown ? pick(env, serviceKeys(kind)) : {}, models: [] });
415
+ const services = await savedServices();
416
+ const multi = services.length > 1;
417
+ const others = otherModels(services, id, info.model);
418
+ const action = await ui.select({
419
+ title: "Switch model",
420
+ options: [
421
+ {
422
+ label: info.model,
423
+ value: "current",
424
+ hint: `${multi ? `${here} · ` : ""}current · ${settingsSummary(env, info.kind, contextWindow(info.model, env))}`
425
+ },
426
+ ...others.map((o, i) => ({
427
+ label: o.model.name,
428
+ value: `saved:${i}`,
429
+ hint: `${multi ? `${describeService(o.service)} · ` : ""}${settingsSummary(o.model.settings, providerKind(o.service.env), contextWindow(o.model.name, o.model.settings))}`
430
+ })),
431
+ { label: "Add a model…", value: "add", hint: "from this service or another one" }
432
+ ]
433
+ }, opts.signal);
434
+ if (action === undefined)
435
+ return;
436
+ if (action === "current") {
437
+ const service = { env: kindKnown ? { ...pick(env, serviceKeys(kind)), JADE_PROVIDER: kind } : { JADE_PROVIDER: kind }, models: [] };
438
+ await pickModelAction({ service, model: { name: info.model, settings: pick(env, MODEL_SETTINGS) } }, true);
439
+ } else if (action.startsWith("saved:")) {
440
+ const o = others[Number(action.slice(6))];
441
+ if (o)
442
+ await pickModelAction(o, false);
443
+ } else if (action === "add") {
444
+ const where = await ui.select({
445
+ title: "Add a model from",
446
+ options: [
447
+ { label: "This service", value: "model", hint: here },
448
+ { label: "Another service…", value: "provider", hint: "or change this one's base URL / API key" },
449
+ { label: "Back", value: "back" }
450
+ ]
451
+ }, opts.signal);
452
+ if (where === "model") {
453
+ const saved = services.find((s) => serviceId(s.env) === id)?.models.map((m) => m.name);
454
+ const model = await chooseModel(env, info.model, saved);
455
+ if (model && model !== info.model)
456
+ await switchModel(model);
457
+ } else if (where === "provider")
458
+ await configureProvider();
459
+ }
514
460
  }
515
- return { provider: configureProvider, model: configureModel };
461
+ }
462
+ return { provider: configureProvider, model: configureModel };
516
463
  }