@aiyiran/myclaw 1.1.208 → 1.1.210

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.
package/index.js CHANGED
@@ -1843,7 +1843,6 @@ function runInteractiveMenu() {
1843
1843
 
1844
1844
  const INJECT_MENU = [
1845
1845
  { key: '1', cmd: 'inject-minimax', desc: '注入 MiniMax 模型配置' },
1846
- { key: '2', cmd: 'inject-zai', desc: '注入智谱 GLM 模型配置' },
1847
1846
  { key: '3', cmd: 'inject-claude', desc: '注入 B.AI 多模型配置 (Claude/GPT/Gemini)' },
1848
1847
  { key: '4', cmd: 'inject-image', desc: '注入图像生成模型配置 (vveai)' },
1849
1848
  { key: '4', cmd: 'inject-search', desc: '注入 Tavily 搜索插件配置' },
@@ -2631,7 +2630,6 @@ function showHelp() {
2631
2630
  console.log(' unpatch 回滚 UI 注入(恢复原版)');
2632
2631
  console.log(' inject 交互选择要执行的注入脚本');
2633
2632
  console.log(' inject-minimax 注入 MiniMax 模型配置 (可选: --key sk-xxx, -f 强制清理其他模型)');
2634
- console.log(' inject-zai 注入智谱 GLM 模型配置 (可选: --key xxx, -f 强制清理其他模型)');
2635
2633
  console.log(' inject-claude 注入 B.AI 多模型配置 (Claude/GPT/Gemini,仅追加)');
2636
2634
  console.log(' inject-image 注入图像生成模型配置 (基于 vveai)');
2637
2635
  console.log(' inject-token 设置 Gateway Token 为 aiyiran');
@@ -9,14 +9,13 @@
9
9
  * myclaw inject-minimax # 仅追加 minimax provider,不改默认,副作用最小
10
10
  * myclaw inject-minimax --default # 追加 + 设为默认 + 全部对话迁移到 MiniMax-M3
11
11
  * myclaw inject-minimax --only # 追加 + 设为默认 + 全部对话迁移 + 清掉所有其他 provider
12
- * myclaw inject-minimax --beta # 6.X 模式: minimax + zai 共存,写 SQLite 鉴权,默认 minimax
12
+ * myclaw inject-minimax --beta # 6.X 模式: 仅 minimax,写 SQLite 鉴权,默认 minimax
13
13
  * myclaw inject-minimax --key sk-xxx # 使用指定 API Key (仅 minimax)
14
14
  *
15
15
  * --beta 说明:
16
16
  * - 适配 openclaw 6.X: 直接写 openclaw-agent.sqlite (6.X 运行时唯一鉴权源)
17
17
  * - 去掉 minimax 的 authHeader
18
- * - 附带配置 zai: glm-5.2 / glm-5-turbo,同样写 SQLite 让其在 6.X 可用
19
- * - 独占清理时保留 minimax + zai 两个 provider,默认模型仍为 minimax
18
+ * * - 独占清理时保留 minimax provider,默认模型仍为 minimax
20
19
  */
21
20
 
22
21
  const fs = require('fs');
@@ -29,29 +28,6 @@ const DEFAULT_MINIMAX_KEY = "sk-cp-dZnzWB-ScLfjo8bO7DKTqSutkBXQsLWUmjhNDBRkgJd5e
29
28
  const PROVIDER_ID = "minimax";
30
29
  const DEFAULT_MODEL = "minimax/MiniMax-M2.7-highspeed";
31
30
 
32
- // ── zai (智谱 GLM) 配置:仅 --beta 模式下附带注入 ──
33
- const DEFAULT_ZAI_KEY = "a7ae7806dea8406bb85eea5d859c00ad.pVnBuagTz6942JHp";
34
- const ZAI_BETA_MODELS = [
35
- {
36
- id: "glm-5.2",
37
- name: "GLM-5.2",
38
- reasoning: true,
39
- input: ["text"],
40
- cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
41
- contextWindow: 202800,
42
- maxTokens: 131100
43
- },
44
- {
45
- id: "glm-5-turbo",
46
- name: "GLM-5 Turbo",
47
- reasoning: true,
48
- input: ["text"],
49
- cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
50
- contextWindow: 202800,
51
- maxTokens: 131100
52
- }
53
- ];
54
-
55
31
  function run(cliArgs) {
56
32
  // ── 解析参数 ──
57
33
  let apiKey = null;
@@ -92,8 +68,8 @@ function run(cliArgs) {
92
68
  console.log('📍 找到配置: ' + configPath);
93
69
  console.log('📌 模式: ' + (betaMode ? '--beta (独占+6.X兼容)' : onlyMode ? '--only (独占)' : setDefault ? '--default (设默认)' : '追加'));
94
70
 
95
- // ── 保留集合:--beta 同时保留 minimax + zai,普通 --only 仅保留 minimax ──
96
- const keepProviders = betaMode ? [PROVIDER_ID, 'zai'] : [PROVIDER_ID];
71
+ // ── 保留集合:所有独占模式仅保留 minimax ──
72
+ const keepProviders = [PROVIDER_ID];
97
73
  const keepProfile = (key) => keepProviders.some((p) => key.startsWith(p + ':'));
98
74
  const keepModel = (key) => keepProviders.some((p) => key.startsWith(p + '/'));
99
75
 
@@ -177,29 +153,6 @@ function run(cliArgs) {
177
153
  config.agents.defaults.models["minimax/MiniMax-M3"] = {};
178
154
  config.agents.defaults.models["minimax/MiniMax-M2.7-highspeed"] = {};
179
155
 
180
- // ── --beta 附带注入 zai (glm-5.2 / glm-5-turbo) ──
181
- if (betaMode) {
182
- console.log('🔗 [--beta] 附带注入 zai: glm-5.2 / glm-5-turbo');
183
- config.auth.profiles["zai:default"] = { provider: "zai", mode: "api_key" };
184
- config.models.providers.zai = {
185
- baseUrl: "https://open.bigmodel.cn/api/coding/paas/v4",
186
- api: "openai-completions",
187
- models: ZAI_BETA_MODELS
188
- };
189
-
190
- // 清理白名单里遗留的其他 zai 模型(比如之前版本注入过的 glm-5 / glm-4.7 / glm-5.1)
191
- const allowedZaiKeys = new Set(ZAI_BETA_MODELS.map((m) => 'zai/' + m.id));
192
- for (const key of Object.keys(config.agents.defaults.models)) {
193
- if (key.startsWith('zai/') && !allowedZaiKeys.has(key)) {
194
- delete config.agents.defaults.models[key];
195
- console.log(' ✓ 清除多余 zai 模型: ' + key);
196
- }
197
- }
198
- for (const key of allowedZaiKeys) {
199
- config.agents.defaults.models[key] = {};
200
- }
201
- }
202
-
203
156
  // ── Step 3:--default 设默认模型 ──
204
157
  if (setDefault) {
205
158
  config.agents.defaults.model = { primary: DEFAULT_MODEL };
@@ -257,13 +210,8 @@ CREATE TABLE IF NOT EXISTS auth_profile_state (
257
210
  state_key TEXT NOT NULL PRIMARY KEY, state_json TEXT NOT NULL, updated_at INTEGER NOT NULL
258
211
  );`;
259
212
 
260
- const zaiKey = DEFAULT_ZAI_KEY;
261
213
  const sqliteStorePayload = { version: 1, profiles: { "minimax:cn": { type: "api_key", provider: "minimax", key: apiKey } } };
262
214
  const sqliteStatePayload = { lastGood: { "minimax": "minimax:cn" } };
263
- if (betaMode) {
264
- sqliteStorePayload.profiles["zai:default"] = { type: "api_key", provider: "zai", key: zaiKey };
265
- sqliteStatePayload.lastGood["zai"] = "zai:default";
266
- }
267
215
 
268
216
  let okCount = 0, skipCount = 0;
269
217
 
@@ -284,10 +232,11 @@ CREATE TABLE IF NOT EXISTS auth_profile_state (
284
232
  }
285
233
  profiles.profiles["minimax:cn"] = { type: "api_key", provider: "minimax", key: apiKey };
286
234
  profiles.lastGood["minimax"] = "minimax:cn";
287
- if (betaMode) {
288
- profiles.profiles["zai:default"] = { type: "api_key", provider: "zai", key: zaiKey };
289
- profiles.lastGood["zai"] = "zai:default";
235
+ // 智谱已停用,移除旧版写入的鉴权。
236
+ for (const id of Object.keys(profiles.profiles)) {
237
+ if (profiles.profiles[id]?.provider === 'zai' || id.startsWith('zai:')) delete profiles.profiles[id];
290
238
  }
239
+ delete profiles.lastGood.zai;
291
240
  try { fs.writeFileSync(profilesPath, JSON.stringify(profiles, null, 2) + '\n', 'utf8'); } catch { /* ignore */ }
292
241
 
293
242
  // ── 6.X (--beta):写入 openclaw-agent.sqlite(运行时唯一鉴权源)──
@@ -336,7 +285,6 @@ CREATE TABLE IF NOT EXISTS auth_profile_state (
336
285
  if (!m) continue;
337
286
  // 修复无前缀的旧格式残留
338
287
  if (m === 'MiniMax-M2.7-highspeed') { sessions[key].model = 'minimax/MiniMax-M3'; changed++; continue; }
339
- if (m === 'glm-5.1') { sessions[key].model = 'zai/glm-5.1'; changed++; continue; }
340
288
  // 统一迁移到新默认
341
289
  if (m !== DEFAULT_MODEL) { sessions[key].model = DEFAULT_MODEL; changed++; }
342
290
  }
@@ -356,9 +304,9 @@ CREATE TABLE IF NOT EXISTS auth_profile_state (
356
304
  console.log('');
357
305
  console.log('✅ MiniMax 注入完成');
358
306
  console.log(' 默认模型: ' + (setDefault ? DEFAULT_MODEL : '(未修改)'));
359
- console.log(' 备选模型: minimax/MiniMax-M2.7-highspeed' + (betaMode ? ' + zai/glm-5.2 + zai/glm-5-turbo' : ''));
307
+ console.log(' 备选模型: minimax/MiniMax-M2.7-highspeed');
360
308
  console.log(' Agent: ' + okCount + ' 个写入,' + skipCount + ' 个跳过');
361
- if (betaMode) console.log(' 其他 provider 已清除 (保留 minimax + zai)');
309
+ if (betaMode) console.log(' 其他 provider 已清除 (保留 minimax)');
362
310
  else if (onlyMode) console.log(' 其他 provider 已清除');
363
311
  console.log('');
364
312
  }
@@ -1,353 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- /**
4
- * inject-zai.js
5
- *
6
- * 注入智谱 GLM 模型配置到 openclaw.json,并为所有 agent 写入 API Key。
7
- *
8
- * 用法:
9
- * myclaw inject-zai # 仅追加 zai provider,不改默认,副作用最小
10
- * myclaw inject-zai --default # 追加 + 设为默认 + 全部对话迁移到 glm-5.2
11
- * myclaw inject-zai --only # 追加 + 设为默认 + 全部对话迁移 + 清掉所有其他 provider
12
- * myclaw inject-zai --key xxx # 使用指定 API Key
13
- */
14
-
15
- const { readConfig, writeConfig } = require('../find-config');
16
- const fs = require('fs');
17
- const path = require('path');
18
- const os = require('os');
19
-
20
- const DEFAULT_ZAI_KEY = "a7ae7806dea8406bb85eea5d859c00ad.pVnBuagTz6942JHp";
21
-
22
- const PROVIDER_ID = "zai";
23
- const DEFAULT_MODEL = "zai/glm-5.2";
24
-
25
- const ZAI_MODELS = [
26
- {
27
- id: "glm-5.2",
28
- name: "GLM-5.2",
29
- reasoning: true,
30
- input: ["text"],
31
- cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
32
- contextWindow: 202800,
33
- maxTokens: 131100
34
- },
35
- {
36
- id: "glm-5.1",
37
- name: "GLM-5.1",
38
- reasoning: true,
39
- input: ["text"],
40
- cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
41
- contextWindow: 202800,
42
- maxTokens: 131100
43
- },
44
- {
45
- id: "glm-5",
46
- name: "GLM-5",
47
- reasoning: true,
48
- input: ["text"],
49
- cost: { input: 1, output: 3.2, cacheRead: 0.2, cacheWrite: 0 },
50
- contextWindow: 202800,
51
- maxTokens: 131100
52
- },
53
- {
54
- id: "glm-5-turbo",
55
- name: "GLM-5 Turbo",
56
- reasoning: true,
57
- input: ["text"],
58
- cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
59
- contextWindow: 202800,
60
- maxTokens: 131100
61
- },
62
- {
63
- id: "glm-5v-turbo",
64
- name: "GLM-5V Turbo",
65
- reasoning: true,
66
- input: ["text", "image"],
67
- cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
68
- contextWindow: 202800,
69
- maxTokens: 131100
70
- },
71
- {
72
- id: "glm-4.7",
73
- name: "GLM-4.7",
74
- reasoning: true,
75
- input: ["text"],
76
- cost: { input: 0.6, output: 2.2, cacheRead: 0.11, cacheWrite: 0 },
77
- contextWindow: 204800,
78
- maxTokens: 131072
79
- },
80
- {
81
- id: "glm-4.7-flash",
82
- name: "GLM-4.7 Flash",
83
- reasoning: true,
84
- input: ["text"],
85
- cost: { input: 0.07, output: 0.4, cacheRead: 0, cacheWrite: 0 },
86
- contextWindow: 200000,
87
- maxTokens: 131072
88
- },
89
- {
90
- id: "glm-4.7-flashx",
91
- name: "GLM-4.7 FlashX",
92
- reasoning: true,
93
- input: ["text"],
94
- cost: { input: 0.06, output: 0.4, cacheRead: 0.01, cacheWrite: 0 },
95
- contextWindow: 200000,
96
- maxTokens: 128000
97
- },
98
- {
99
- id: "glm-4.6",
100
- name: "GLM-4.6",
101
- reasoning: true,
102
- input: ["text"],
103
- cost: { input: 0.6, output: 2.2, cacheRead: 0.11, cacheWrite: 0 },
104
- contextWindow: 204800,
105
- maxTokens: 131072
106
- },
107
- {
108
- id: "glm-4.6v",
109
- name: "GLM-4.6V",
110
- reasoning: true,
111
- input: ["text", "image"],
112
- cost: { input: 0.3, output: 0.9, cacheRead: 0, cacheWrite: 0 },
113
- contextWindow: 128000,
114
- maxTokens: 32768
115
- },
116
- {
117
- id: "glm-4.5",
118
- name: "GLM-4.5",
119
- reasoning: true,
120
- input: ["text"],
121
- cost: { input: 0.6, output: 2.2, cacheRead: 0.11, cacheWrite: 0 },
122
- contextWindow: 131072,
123
- maxTokens: 98304
124
- },
125
- {
126
- id: "glm-4.5-air",
127
- name: "GLM-4.5 Air",
128
- reasoning: true,
129
- input: ["text"],
130
- cost: { input: 0.2, output: 1.1, cacheRead: 0.03, cacheWrite: 0 },
131
- contextWindow: 131072,
132
- maxTokens: 98304
133
- },
134
- {
135
- id: "glm-4.5-flash",
136
- name: "GLM-4.5 Flash",
137
- reasoning: true,
138
- input: ["text"],
139
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
140
- contextWindow: 131072,
141
- maxTokens: 98304
142
- },
143
- {
144
- id: "glm-4.5v",
145
- name: "GLM-4.5V",
146
- reasoning: true,
147
- input: ["text", "image"],
148
- cost: { input: 0.6, output: 1.8, cacheRead: 0, cacheWrite: 0 },
149
- contextWindow: 64000,
150
- maxTokens: 16384
151
- }
152
- ];
153
-
154
- function run(cliArgs) {
155
- // ── 解析参数 ──
156
- let apiKey = null;
157
- let setDefault = false;
158
- let onlyMode = false;
159
-
160
- for (let i = 0; i < cliArgs.length; i++) {
161
- if (cliArgs[i] === '--key' && cliArgs[i + 1]) {
162
- apiKey = cliArgs[i + 1];
163
- i++;
164
- } else if (cliArgs[i] === '--default') {
165
- setDefault = true;
166
- } else if (cliArgs[i] === '--only') {
167
- onlyMode = true;
168
- setDefault = true; // --only 隐含 --default
169
- }
170
- }
171
-
172
- if (!apiKey) {
173
- apiKey = DEFAULT_ZAI_KEY;
174
- console.log('💡 未传入 --key,使用默认 API Key');
175
- }
176
-
177
- // ── 读取配置 ──
178
- let config, configPath;
179
- try {
180
- ({ config, configPath } = readConfig());
181
- } catch (err) {
182
- console.error('❌ ' + err.message);
183
- process.exit(1);
184
- }
185
-
186
- console.log('📍 找到配置: ' + configPath);
187
- console.log('📌 模式: ' + (onlyMode ? '--only (独占)' : setDefault ? '--default (设默认)' : '追加'));
188
-
189
- // ── Step 1:--only 清掉所有其他 provider ──
190
- if (onlyMode) {
191
- console.log('');
192
- console.log('🧹 [--only] 清理其他所有 provider...');
193
-
194
- if (config.models?.providers) {
195
- for (const key of Object.keys(config.models.providers)) {
196
- if (key !== PROVIDER_ID) {
197
- delete config.models.providers[key];
198
- console.log(' ✓ 删除 provider: ' + key);
199
- }
200
- }
201
- }
202
- if (config.auth?.profiles) {
203
- for (const key of Object.keys(config.auth.profiles)) {
204
- if (!key.startsWith(PROVIDER_ID + ':')) {
205
- delete config.auth.profiles[key];
206
- console.log(' ✓ 删除 auth profile: ' + key);
207
- }
208
- }
209
- }
210
- if (config.agents?.defaults?.models) {
211
- for (const key of Object.keys(config.agents.defaults.models)) {
212
- if (!key.startsWith(PROVIDER_ID + '/')) {
213
- delete config.agents.defaults.models[key];
214
- console.log(' ✓ 删除白名单: ' + key);
215
- }
216
- }
217
- }
218
- }
219
-
220
- // ── Step 2:注入 zai provider 配置 ──
221
- console.log('');
222
- console.log('📝 [Step 2] 注入智谱 GLM 配置...');
223
-
224
- if (!config.auth) config.auth = {};
225
- if (!config.auth.profiles) config.auth.profiles = {};
226
- config.auth.profiles["zai:default"] = { provider: "zai", mode: "api_key" };
227
-
228
- if (!config.models) config.models = {};
229
- if (!config.models.mode) config.models.mode = "merge";
230
- if (!config.models.providers) config.models.providers = {};
231
-
232
- config.models.providers.zai = {
233
- baseUrl: "https://open.bigmodel.cn/api/coding/paas/v4",
234
- api: "openai-completions",
235
- models: ZAI_MODELS
236
- };
237
-
238
- if (!config.agents) config.agents = {};
239
- if (!config.agents.defaults) config.agents.defaults = {};
240
- if (!config.agents.defaults.models) config.agents.defaults.models = {};
241
-
242
- // 白名单:glm-5.2 + glm-5-turbo
243
- config.agents.defaults.models["zai/glm-5.2"] = {};
244
- config.agents.defaults.models["zai/glm-5-turbo"] = {};
245
-
246
- // ── Step 3:--default 设默认模型 ──
247
- if (setDefault) {
248
- config.agents.defaults.model = { primary: DEFAULT_MODEL };
249
- console.log('⚡ 默认模型 → ' + DEFAULT_MODEL);
250
- } else {
251
- console.log('⊘ 未传 --default,保留现有默认模型');
252
- }
253
-
254
- // ── --only 额外清除 per-agent 覆盖 ──
255
- if (onlyMode) {
256
- let overrideCount = 0;
257
- for (const agent of (config.agents.list || [])) {
258
- if (agent.model && agent.model !== DEFAULT_MODEL) {
259
- delete agent.model;
260
- overrideCount++;
261
- }
262
- }
263
- if (overrideCount > 0) console.log('🧹 --only: 已清除 ' + overrideCount + ' 个 agent 的独立 model 覆盖');
264
- }
265
-
266
- writeConfig(config, configPath);
267
- console.log('✅ openclaw.json 已更新');
268
-
269
- // ── Step 4:为所有 agent 写入 API Key ──
270
- console.log('');
271
- console.log('🔑 [Step 4] 写入 API Key 到所有 agent...');
272
-
273
- const DEFAULT_MAIN_DIR = path.join(os.homedir(), '.openclaw', 'agents', 'main', 'agent');
274
- const agentList = (config.agents && config.agents.list) || [];
275
-
276
- const agentDirs = new Map();
277
- agentDirs.set(DEFAULT_MAIN_DIR, 'main');
278
- for (const agent of agentList) {
279
- if (agent.agentDir) agentDirs.set(agent.agentDir, agent.id);
280
- }
281
-
282
- let okCount = 0, skipCount = 0;
283
-
284
- for (const [agentDir, agentId] of agentDirs) {
285
- const profilesPath = path.join(agentDir, 'auth-profiles.json');
286
- let profiles = { version: 1, profiles: {}, lastGood: {} };
287
- if (fs.existsSync(profilesPath)) {
288
- try {
289
- const parsed = JSON.parse(fs.readFileSync(profilesPath, 'utf8'));
290
- if (parsed.profiles) profiles = parsed;
291
- if (!profiles.lastGood) profiles.lastGood = {};
292
- } catch { /* 解析失败用空骨架 */ }
293
- }
294
-
295
- profiles.profiles["zai:default"] = { type: "api_key", provider: "zai", key: apiKey };
296
- profiles.lastGood["zai"] = "zai:default";
297
-
298
- try {
299
- if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true });
300
- fs.writeFileSync(profilesPath, JSON.stringify(profiles, null, 2) + '\n', 'utf8');
301
- console.log(' ✅ ' + agentId);
302
- okCount++;
303
- } catch (err) {
304
- console.log(' ⚠ ' + agentId + ': ' + err.message);
305
- skipCount++;
306
- }
307
- }
308
-
309
- // ── Step 5:--default / --only 迁移全部对话 ──
310
- if (setDefault) {
311
- console.log('');
312
- console.log('🔄 [Step 5] 迁移全部对话 → ' + DEFAULT_MODEL + ' ...');
313
- let sessionOk = 0, sessionSkip = 0, sessionChanged = 0;
314
-
315
- for (const [agentDir] of agentDirs) {
316
- const sessionsPath = path.join(agentDir, '..', 'sessions', 'sessions.json');
317
- if (!fs.existsSync(sessionsPath)) continue;
318
- try {
319
- const sessions = JSON.parse(fs.readFileSync(sessionsPath, 'utf8'));
320
- let changed = 0;
321
- for (const key of Object.keys(sessions)) {
322
- const m = sessions[key]?.model;
323
- if (!m) continue;
324
- // 修复无前缀的旧格式残留
325
- if (m === 'glm-5.1') { sessions[key].model = 'zai/glm-5.2'; changed++; continue; }
326
- if (m === 'zai/glm-5.1') { sessions[key].model = 'zai/glm-5.2'; changed++; continue; }
327
- if (m === 'MiniMax-M2.7-highspeed') { sessions[key].model = 'minimax/MiniMax-M3'; changed++; continue; }
328
- // 统一迁移到新默认
329
- if (m !== DEFAULT_MODEL) { sessions[key].model = DEFAULT_MODEL; changed++; }
330
- }
331
- if (changed > 0) {
332
- fs.writeFileSync(sessionsPath, JSON.stringify(sessions, null, 2) + '\n', 'utf8');
333
- sessionChanged += changed;
334
- }
335
- sessionOk++;
336
- } catch {
337
- sessionSkip++;
338
- }
339
- }
340
- console.log(' 对话迁移: ' + sessionChanged + ' 条,文件: ' + sessionOk + ' 个,跳过: ' + sessionSkip + ' 个');
341
- }
342
-
343
- // ── 汇总 ──
344
- console.log('');
345
- console.log('✅ GLM 注入完成');
346
- console.log(' 默认模型: ' + (setDefault ? DEFAULT_MODEL : '(未修改)'));
347
- console.log(' 模型数量: ' + ZAI_MODELS.length + ' 个可选');
348
- console.log(' Agent: ' + okCount + ' 个写入,' + skipCount + ' 个跳过');
349
- if (onlyMode) console.log(' 其他 provider 已清除');
350
- console.log('');
3
+ // 保留旧命令兼容入口;智谱已全面停用,不再写入配置或凭据。
4
+ function run() {
5
+ console.log('智谱 GLM 已停用,不再支持注入。');
351
6
  }
352
-
353
7
  module.exports = { run };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiyiran/myclaw",
3
- "version": "1.1.208",
3
+ "version": "1.1.210",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * VoiceInput - 独立语音转文字 SDK
3
- * 基于讯飞语音听写 WebAPI(流式版)
3
+ * 已升级对接火山引擎(豆包语音)大模型实时语音识别
4
4
  *
5
- * 零依赖,纯原生 JS,任何静态 HTML 页面都能用
5
+ * 零依赖,纯原生 JS,任何静态 HTML 页面或扩展脚本都能用
6
6
  *
7
7
  * 用法:
8
8
  * const voice = new VoiceInput({
@@ -14,18 +14,20 @@
14
14
  (function (global) {
15
15
  'use strict';
16
16
 
17
- // ============ 默认配置 ============
17
+ // ============ 默认配置(火山引擎豆包语音) ============
18
18
  var DEFAULT_CONFIG = {
19
- APPID: '029f22a0',
20
- APISecret: 'Njk1Y2VlYjhhODhkNTYxM2Y3YTE4YzRl',
21
- APIKey: '60f2b651b26629030c861e5b2c96102d',
22
- url: 'wss://iat.xf-yun.com/v1',
23
- host: 'iat.xf-yun.com',
24
- language: 'zh_cn',
25
- accent: 'mandarin'
19
+ APPID: '3086995618',
20
+ AccessToken: 'R8Ydr2JYkZSDiP3luU63eWTmjZQ6CQmf',
21
+ SecretKey: 'XgANQB0u3RNdEqENjGX76clLxPQH2dpb',
22
+ resourceId: 'volc.seedasr.sauc.duration',
23
+ proxyUrl: (typeof window !== 'undefined' && window.location && window.location.hostname)
24
+ ? ('ws://' + window.location.hostname + ':9998/ws/asr')
25
+ : 'ws://localhost:9998/ws/asr',
26
+ url: 'wss://openspeech.bytedance.com/api/v3/sauc/bigmodel_async',
27
+ language: 'zh_cn'
26
28
  };
27
29
 
28
- // ============ 主线程音频处理(避免 CSP 限制 blob Worker)============
30
+ // ============ 主线程音频处理(44.1kHz -> 16kHz PCM) ============
29
31
  var _processorSampleRate = 44100;
30
32
 
31
33
  function to16kHz(data) {
@@ -64,29 +66,6 @@
64
66
  return arr;
65
67
  }
66
68
 
67
- // ============ 工具函数 ============
68
-
69
- // 使用浏览器原生 SubtleCrypto 做 HMAC-SHA256(无需 CryptoJS)
70
- function hmacSHA256(key, message) {
71
- var enc = new TextEncoder();
72
- return crypto.subtle.importKey(
73
- 'raw', enc.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
74
- ).then(function (cryptoKey) {
75
- return crypto.subtle.sign('HMAC', cryptoKey, enc.encode(message));
76
- }).then(function (sig) {
77
- return arrayBufferToBase64(sig);
78
- });
79
- }
80
-
81
- function arrayBufferToBase64(buffer) {
82
- var binary = '';
83
- var bytes = new Uint8Array(buffer);
84
- for (var i = 0; i < bytes.length; i++) {
85
- binary += String.fromCharCode(bytes[i]);
86
- }
87
- return btoa(binary);
88
- }
89
-
90
69
  function toBase64(buffer) {
91
70
  var binary = '';
92
71
  var bytes = new Uint8Array(buffer);
@@ -116,12 +95,12 @@
116
95
 
117
96
  // 配置
118
97
  this.APPID = opts.APPID || DEFAULT_CONFIG.APPID;
119
- this.APISecret = opts.APISecret || DEFAULT_CONFIG.APISecret;
120
- this.APIKey = opts.APIKey || DEFAULT_CONFIG.APIKey;
98
+ this.AccessToken = opts.AccessToken || DEFAULT_CONFIG.AccessToken;
99
+ this.SecretKey = opts.SecretKey || DEFAULT_CONFIG.SecretKey;
100
+ this.resourceId = opts.resourceId || DEFAULT_CONFIG.resourceId;
101
+ this.proxyUrl = opts.proxyUrl || DEFAULT_CONFIG.proxyUrl;
121
102
  this.url = opts.url || DEFAULT_CONFIG.url;
122
- this.host = opts.host || DEFAULT_CONFIG.host;
123
103
  this.language = opts.language || DEFAULT_CONFIG.language;
124
- this.accent = opts.accent || DEFAULT_CONFIG.accent;
125
104
 
126
105
  // 回调
127
106
  this.onResult = opts.onResult || function () {};
@@ -139,11 +118,10 @@
139
118
  this.streamRef = null;
140
119
  this.sendInterval = null;
141
120
  this.resultTimeout = null;
142
- this.worker = null;
121
+ this.stopSignalSent = false;
143
122
  }
144
123
 
145
124
  VoiceInput.prototype._initProcessor = function () {
146
- // 主线程处理,无需 Worker
147
125
  this._processorReady = true;
148
126
  };
149
127
 
@@ -164,14 +142,7 @@
164
142
 
165
143
  VoiceInput.prototype._getWebSocketUrl = function () {
166
144
  var self = this;
167
- var date = new Date().toUTCString();
168
- var signatureOrigin = 'host: ' + self.host + '\ndate: ' + date + '\nGET /v1 HTTP/1.1';
169
-
170
- return hmacSHA256(self.APISecret, signatureOrigin).then(function (signature) {
171
- var authOrigin = 'api_key="' + self.APIKey + '", algorithm="hmac-sha256", headers="host date request-line", signature="' + signature + '"';
172
- var authorization = btoa(authOrigin);
173
- return self.url + '?authorization=' + authorization + '&date=' + encodeURIComponent(date) + '&host=' + self.host;
174
- });
145
+ return Promise.resolve(self.proxyUrl || 'ws://localhost:9998/ws/asr');
175
146
  };
176
147
 
177
148
  VoiceInput.prototype.start = function () {
@@ -180,6 +151,7 @@
180
151
  var self = this;
181
152
  this.audioData = [];
182
153
  this.textSegments = [];
154
+ this.stopSignalSent = false;
183
155
  this._setStatus('connecting');
184
156
 
185
157
  // 获取麦克风
@@ -229,13 +201,14 @@
229
201
  var timeout = setTimeout(function () {
230
202
  if (ws.readyState === WebSocket.CONNECTING) {
231
203
  ws.close();
232
- self.onError('WebSocket 连接超时');
204
+ self.onError('无法连接语音代理服务(' + url + '),请确保服务已启动(npm run voice-proxy)');
233
205
  self._cleanup();
234
206
  }
235
207
  }, 5000);
236
208
 
237
209
  ws.onopen = function () {
238
210
  clearTimeout(timeout);
211
+ console.log('[VoiceInput] 火山语音代理连接成功');
239
212
  self._setStatus('recording');
240
213
  setTimeout(function () { self._startSending(); }, 300);
241
214
  };
@@ -246,7 +219,7 @@
246
219
 
247
220
  ws.onerror = function () {
248
221
  clearTimeout(timeout);
249
- self.onError('WebSocket 连接错误');
222
+ self.onError('无法连接语音服务(' + url + '),请确保语音代理服务已运行(npm run voice-proxy)');
250
223
  self._cleanup();
251
224
  };
252
225
 
@@ -257,7 +230,7 @@
257
230
  }
258
231
  };
259
232
  }).catch(function (err) {
260
- self.onError('签名失败: ' + err);
233
+ self.onError('获取连接地址失败: ' + err);
261
234
  self._cleanup();
262
235
  });
263
236
  };
@@ -266,32 +239,13 @@
266
239
  var self = this;
267
240
  if (!this.webSocket || this.webSocket.readyState !== 1) return;
268
241
 
269
- // 发送首帧(带参数)
242
+ // 发送首帧音频
270
243
  var firstAudio = this.audioData.splice(0, 1280);
271
- if (firstAudio.length === 0) firstAudio = [0]; // 保底
272
-
273
- this.webSocket.send(JSON.stringify({
274
- header: { app_id: this.APPID, status: 0 },
275
- parameter: {
276
- iat: {
277
- domain: 'slm',
278
- language: this.language,
279
- accent: this.accent,
280
- eos: 6000,
281
- vinfo: 1,
282
- dwa: 'wpgs',
283
- result: { encoding: 'utf8', compress: 'raw', format: 'json' }
284
- }
285
- },
286
- payload: {
287
- audio: {
288
- encoding: 'raw', sample_rate: 16000, channels: 1, bit_depth: 16,
289
- seq: 1, status: 0, audio: toBase64(firstAudio)
290
- }
291
- }
292
- }));
244
+ if (firstAudio.length > 0) {
245
+ self.webSocket.send(new Uint8Array(firstAudio).buffer);
246
+ }
293
247
 
294
- // 每 40ms 发送后续帧
248
+ // 每 40ms 发送后续帧音频
295
249
  this.sendInterval = setInterval(function () {
296
250
  if (!self.webSocket || self.webSocket.readyState !== 1 || self.status === 'idle') {
297
251
  clearInterval(self.sendInterval);
@@ -305,18 +259,30 @@
305
259
  var chunk = self.audioData.splice(0, 1280);
306
260
  if (chunk.length === 0) return;
307
261
 
308
- self.webSocket.send(JSON.stringify({
309
- header: { app_id: self.APPID, status: 1 },
310
- payload: {
311
- audio: { status: 1, audio: toBase64(chunk) }
312
- }
313
- }));
262
+ self.webSocket.send(new Uint8Array(chunk).buffer);
314
263
  }, 40);
315
264
  };
316
265
 
317
266
  VoiceInput.prototype._handleResult = function (data) {
318
267
  try {
319
268
  var json = JSON.parse(data);
269
+ // 1. 火山引擎代理格式
270
+ if (json.type === 'result') {
271
+ if (json.text !== undefined) {
272
+ this.onResult(json.text);
273
+ }
274
+ if (json.is_final) {
275
+ this._cleanupWebSocket();
276
+ }
277
+ return;
278
+ }
279
+ if (json.type === 'error') {
280
+ console.error('[VoiceInput] 火山语音错误:', json.message);
281
+ this.onError(json.message || '语音识别服务异常');
282
+ return;
283
+ }
284
+
285
+ // 2. 兼容旧讯飞数据格式
320
286
  if (json.payload && json.payload.result) {
321
287
  var text = base64ToUtf8(json.payload.result.text);
322
288
  var result = JSON.parse(text);
@@ -329,12 +295,11 @@
329
295
  this.onResult(finalText);
330
296
  }
331
297
  }
332
- // status=2 表示服务端已返回全部结果
333
298
  if (json.header && json.header.status === 2) {
334
299
  this._cleanupWebSocket();
335
300
  }
336
301
  } catch (e) {
337
- // 解析失败忽略
302
+ // 忽略解析错误
338
303
  }
339
304
  };
340
305
 
@@ -368,17 +333,10 @@
368
333
  this.audioContext.suspend();
369
334
  }
370
335
 
371
- // 发送尾帧
372
- if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN) {
373
- this.webSocket.send(JSON.stringify({
374
- header: { app_id: this.APPID, status: 2 },
375
- payload: {
376
- audio: {
377
- encoding: 'raw', sample_rate: 16000, channels: 1, bit_depth: 16,
378
- seq: 999, status: 2, audio: ''
379
- }
380
- }
381
- }));
336
+ // 发送停止信号
337
+ if (this.webSocket && this.webSocket.readyState === WebSocket.OPEN && !this.stopSignalSent) {
338
+ this.stopSignalSent = true;
339
+ this.webSocket.send(JSON.stringify({ type: 'stop' }));
382
340
 
383
341
  // 3秒超时强制关闭
384
342
  var self = this;
@@ -399,39 +357,32 @@
399
357
  this.webSocket.close();
400
358
  this.webSocket = null;
401
359
  }
402
- this._stopAudioStream();
403
- this._setStatus('idle');
360
+ this._cleanup();
404
361
  };
405
362
 
406
- VoiceInput.prototype._stopAudioStream = function () {
363
+ VoiceInput.prototype._cleanup = function () {
364
+ if (this.sendInterval) {
365
+ clearInterval(this.sendInterval);
366
+ this.sendInterval = null;
367
+ }
407
368
  if (this.streamRef) {
408
- this.streamRef.getTracks().forEach(function (t) { t.stop(); });
369
+ try {
370
+ this.streamRef.getTracks().forEach(function (t) { t.stop(); });
371
+ } catch (e) {}
409
372
  this.streamRef = null;
410
373
  }
411
- if (this.scriptProcessor) {
412
- this.scriptProcessor.disconnect();
413
- this.scriptProcessor = null;
414
- }
415
- if (this.mediaSource) {
416
- this.mediaSource.disconnect();
417
- this.mediaSource = null;
418
- }
419
374
  if (this.audioContext) {
420
- this.audioContext.close();
375
+ try { this.audioContext.close(); } catch (e) {}
421
376
  this.audioContext = null;
422
377
  }
423
- };
424
-
425
- VoiceInput.prototype._cleanup = function () {
426
- if (this.sendInterval) {
427
- clearInterval(this.sendInterval);
428
- this.sendInterval = null;
429
- }
430
- this._cleanupWebSocket();
378
+ this.scriptProcessor = null;
379
+ this.mediaSource = null;
380
+ this._setStatus('idle');
431
381
  };
432
382
 
433
383
  VoiceInput.prototype.destroy = function () {
434
- this._cleanup();
384
+ this.stop();
385
+ this._cleanupWebSocket();
435
386
  };
436
387
 
437
388
  // 暴露到全局