cortico-world-workbuddy 0.1.7 → 0.3.4

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.
@@ -0,0 +1,370 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 契约测试:不依赖 Coopanion 宿主,纯 Node 就能跑。
4
+ *
5
+ * 覆盖审查报告里「看起来对、其实悄悄失效」的那一类问题——静态清单与源码是否一致、
6
+ * 促销时间判定、安全清单分层、账本字段名,以及复检报告点名「没有回归断言」的那些行为:
7
+ * 哨兵语义、计费域选择、429 软硬区分、面板方法白名单、账本并发、SSE 尾行 flush、启动兜底。
8
+ *
9
+ * 用法:
10
+ * node scripts/contract.mjs # 全部断言
11
+ * node scripts/contract.mjs --verbose # 逐条打印
12
+ */
13
+
14
+ import { createServer } from 'node:http';
15
+ import { existsSync, mkdtempSync, readFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { tmpdir } from 'node:os';
18
+ import { fileURLToPath } from 'node:url';
19
+
20
+ import { buildDescribe, renderDescribe } from './gen-describe.mjs';
21
+ import { WB_DEFAULTS } from '../src/config.js';
22
+ import { attachPromos, parsePromos, priceViewOf } from '../src/promo.js';
23
+ import { classifyModel, CAUTION_MODEL_IDS, SAFE_MODEL_IDS } from '../src/safety.js';
24
+ import { UsageLedger, dayKey, summarize } from '../src/usage.js';
25
+ import { classifyHttpFailure, WbUpstream } from '../src/upstream.js';
26
+ import { PANEL_METHODS, TOKEN_AUTO, TOKEN_CLEARED, WorkBuddyWorld } from '../src/world.js';
27
+ import { runRegression } from './contract-regression.mjs';
28
+
29
+ const pkgDir = fileURLToPath(new URL('..', import.meta.url));
30
+ const verbose = process.argv.includes('--verbose');
31
+
32
+ let passed = 0;
33
+ const failures = [];
34
+
35
+ function ok(condition, label, detail) {
36
+ if (condition) {
37
+ passed += 1;
38
+ if (verbose) console.log(` ✓ ${label}`);
39
+ return;
40
+ }
41
+ const text = detail === undefined ? label : `${label}(实际:${JSON.stringify(detail)})`;
42
+ failures.push(text);
43
+ if (verbose || failures.length <= 5) console.error(` ✗ ${text}`);
44
+ }
45
+
46
+ function readJson(name) {
47
+ return JSON.parse(readFileSync(join(pkgDir, name), 'utf8'));
48
+ }
49
+
50
+ const pkg = readJson('package.json');
51
+ const describe = readJson('describe.json');
52
+
53
+ /* ---------------------------------------------------------------- 静态清单 */
54
+
55
+ console.log('· 清单与源码一致性');
56
+ ok(
57
+ renderDescribe(buildDescribe()) === readFileSync(join(pkgDir, 'describe.json'), 'utf8'),
58
+ 'describe.json 与 WB_TOOL_DECLS / ENV_PROMPT.md 一致(跑 node scripts/gen-describe.mjs 可修)',
59
+ );
60
+
61
+ const changelog = readFileSync(join(pkgDir, 'CHANGELOG.md'), 'utf8');
62
+ ok(
63
+ new RegExp(`^## ${pkg.version.replace(/\./g, '\\.')}$`, 'm').test(changelog),
64
+ `CHANGELOG.md 里有 ## ${pkg.version} 段落`,
65
+ );
66
+
67
+ ok(pkg.cortico?.kind === 'world', 'cortico.kind = world');
68
+ ok(typeof pkg.cortico?.api === 'number', 'cortico.api 是数字(宿主按它判断兼容)');
69
+ ok(Array.isArray(pkg.cortico?.tags), 'cortico.tags 是数组(市场会渲染标签)');
70
+ ok(Array.isArray(pkg.cortico?.os) && pkg.cortico.os.includes('win32'), 'cortico.os 明确声明 win32');
71
+
72
+ for (const rel of ['src/index.js', pkg.cortico.describe, pkg.cortico.icon, pkg.cortico.webUiClient, pkg.cortico.webUiStyle]) {
73
+ ok(existsSync(join(pkgDir, rel)), `文件存在:${rel}`);
74
+ }
75
+
76
+ ok(!existsSync(join(pkgDir, 'ENV_PROMPT.md')), '包里没有那份旧的根 ENV_PROMPT.md(真正模板在 src/)');
77
+ for (const need of ['src', 'dist', 'assets', 'scripts', 'describe.json', 'README.md', 'CHANGELOG.md']) {
78
+ ok((pkg.files ?? []).includes(need), `files 覆盖 ${need}`);
79
+ }
80
+
81
+ /* ------------------------------------------- 环境提示词占位符 ↔ envPromptVars */
82
+
83
+ console.log('· 环境提示词变量');
84
+ const worldSource = readFileSync(join(pkgDir, 'src/world.js'), 'utf8');
85
+ const declared = new Set([...worldSource.matchAll(/'(workbuddy\.[A-Za-z]+)':/g)].map((m) => m[1]));
86
+ const used = new Set([...describe.envPrompt.matchAll(/\{\{(workbuddy\.[A-Za-z]+)\}\}/g)].map((m) => m[1]));
87
+ const missing = [...used].filter((name) => !declared.has(name));
88
+ ok(missing.length === 0, 'envPrompt 里每个 {{workbuddy.x}} 都有对应变量', missing);
89
+ ok(used.size >= 8, `envPrompt 用到了 ${used.size} 个变量`);
90
+ ok(!used.has('workbuddy.priority'), '环境提示词不再引用已删除的「中转站优先」开关', [...used]);
91
+
92
+ const toolNames = describe.tools.map((t) => t.name).sort();
93
+ ok(
94
+ toolNames.join(',') === ['wb_chat', 'wb_credits', 'wb_list_models', 'wb_select_model'].join(','),
95
+ 'describe.tools 名字齐全',
96
+ );
97
+ ok(
98
+ describe.tools.every((t) => Array.isArray(t.tags) && t.parameters?.type === 'object'),
99
+ '每个工具都有 tags 与 object 参数',
100
+ );
101
+
102
+ /* ------------------------------------------------------------------- 促销 */
103
+
104
+ console.log('· 促销与倍率');
105
+ const NOW = Date.parse('2026-11-03T23:30:00+08:00');
106
+ const promotions = [
107
+ {
108
+ id: 'night',
109
+ kind: 'discount',
110
+ enabled: true,
111
+ priority: 100,
112
+ modelIds: ['glm-5.2'],
113
+ discount: { discountedCredits: '0.50x', factor: 0.5, displayMode: 'strikethrough' },
114
+ schedule: { timezone: 'Asia/Shanghai', daily: [{ start: '23:00', end: '7:50' }] },
115
+ },
116
+ {
117
+ id: 'badge-only',
118
+ kind: 'discount',
119
+ enabled: true,
120
+ priority: 500,
121
+ modelIds: ['glm-5.2'],
122
+ badge: { label: '白天徽标' },
123
+ schedule: { timezone: 'Asia/Shanghai', daily: [{ start: '00:00', end: '23:59' }] },
124
+ },
125
+ {
126
+ id: 'expired',
127
+ kind: 'discount',
128
+ enabled: true,
129
+ priority: 900,
130
+ modelIds: ['glm-5.2'],
131
+ discount: { discountedCredits: '0x', displayMode: 'replace' },
132
+ schedule: { timezone: 'Asia/Shanghai', validUntil: '2020-01-01T00:00:00Z' },
133
+ },
134
+ {
135
+ id: 'numeric',
136
+ kind: 'discount',
137
+ enabled: true,
138
+ priority: 60,
139
+ modelIds: ['hy3'],
140
+ discount: { discountedCredits: '0.25x', displayMode: 'replace' },
141
+ schedule: { timezone: 'Asia/Shanghai', validUntil: 1893456000 },
142
+ },
143
+ {
144
+ id: 'bad-zone',
145
+ kind: 'discount',
146
+ enabled: true,
147
+ priority: 40,
148
+ modelIds: ['hunyuan-chat'],
149
+ discount: { discountedCredits: '0.10x', displayMode: 'replace' },
150
+ schedule: { timezone: 'Not/AZone', daily: [{ start: '00:00', end: '23:59' }] },
151
+ },
152
+ ];
153
+ const promos = parsePromos(promotions, []);
154
+ const models = attachPromos(
155
+ [
156
+ { id: 'glm-5.2', credits: 'x0.79' },
157
+ { id: 'hy3', credits: 'x0' },
158
+ { id: 'hunyuan-chat', credits: 'x0.30' },
159
+ ],
160
+ promos,
161
+ );
162
+
163
+ const night = priceViewOf(models[0], NOW);
164
+ ok(night.promoId === 'night', '夜里挑的是真正改价的那条促销(不是优先级更高的徽标项)', night.promoId);
165
+ ok(night.effective === 0.5, '夜里生效倍率 = 0.5', night.effective);
166
+ ok(night.base === 0.79, '目录倍率 x0.79 解析正确', night.base);
167
+ ok(night.windowText === '23:00–07:50', '时段文案', night.windowText);
168
+ ok(night.discounted === true, 'discounted 标记为真');
169
+
170
+ const noon = priceViewOf(models[0], Date.parse('2026-11-03T12:00:00+08:00'));
171
+ ok(noon.effective === 0.79, '白天不打折', noon.effective);
172
+ ok(noon.promoId === undefined || noon.promoId === null, '白天不挂促销 id(过期那条与徽标条都不该改价)', noon.promoId);
173
+
174
+ const numeric = priceViewOf(models[1], NOW);
175
+ ok(numeric.promoId === 'numeric', '数字时间戳(Unix 秒)的有效期被识别', numeric.promoId);
176
+
177
+ const badZone = priceViewOf(models[2], NOW);
178
+ ok(badZone.promoId === 'bad-zone', '非法时区退回 UTC 后窗口仍生效', badZone.promoId);
179
+
180
+ const defaultZonePromo = parsePromos([{
181
+ id: 'default-zone', modelIds: ['glm-5.2'], discount: { discountedCredits: '0.50x', displayMode: 'replace' },
182
+ schedule: { daily: [{ start: '23:00', end: '7:50' }] },
183
+ }], []);
184
+ const defaultZoneModel = attachPromos([{ id: 'glm-5.2', credits: 'x0.79' }], defaultZonePromo)[0];
185
+ ok(priceViewOf(defaultZoneModel, NOW).effective === 0.5, 'daily 省略 timezone 时按 Asia/Shanghai 判定', priceViewOf(defaultZoneModel, NOW));
186
+
187
+ const dateOnlyPromo = parsePromos([{
188
+ id: 'date-only', modelIds: ['glm-5.2'], discount: { discountedCredits: '0.20x', displayMode: 'replace' },
189
+ schedule: { timezone: 'Asia/Shanghai', validFrom: '2026-11-03', validUntil: '2026-11-03' },
190
+ }], []);
191
+ const dateOnlyModel = attachPromos([{ id: 'glm-5.2', credits: 'x0.79' }], dateOnlyPromo)[0];
192
+ ok(priceViewOf(dateOnlyModel, Date.parse('2026-11-03T00:00:00+08:00')).effective === 0.2, '纯日期 validFrom 从当地 00:00 生效', dateOnlyPromo[0].schedule);
193
+ ok(priceViewOf(dateOnlyModel, Date.parse('2026-11-03T09:00:00+08:00')).effective === 0.2, '纯日期 validUntil 覆盖当天 08:00 之后', dateOnlyPromo[0].schedule);
194
+ ok(priceViewOf(dateOnlyModel, Date.parse('2026-11-04T00:00:00+08:00')).effective === 0.79, '纯日期 validUntil 到次日当地 00:00 才失效');
195
+ ok(priceViewOf(dateOnlyModel, Date.parse('2026-11-03T09:00:00+08:00')).absoluteText.endsWith('2026-11-03'), '纯日期有效期展示不写偏一天', priceViewOf(dateOnlyModel, NOW).absoluteText);
196
+
197
+ /* ------------------------------------------------------------------- 安全 */
198
+
199
+ console.log('· 安全清单');
200
+ ok(SAFE_MODEL_IDS.includes('hy4-preview'), 'hy4-preview 在安全清单里');
201
+ ok(CAUTION_MODEL_IDS.includes('hy4-preview'), 'hy4-preview 标为谨慎档');
202
+
203
+ const hy4 = classifyModel('hy4-preview', { id: 'hy4-preview' });
204
+ ok(hy4.allow === true && hy4.caution === true, 'hy4-preview 可调用但带谨慎提示', hy4);
205
+
206
+ const lite = classifyModel('wb-lite', { id: 'wb-lite', disabled: true });
207
+ ok(lite.tier === 'disabled' && lite.allow === false, '目录标 disabled 的模型被拒绝', lite.tier);
208
+
209
+ const alias = classifyModel('auto', { id: 'auto' });
210
+ ok(alias.tier === 'alias' && alias.allow === false, '内部别名被拒绝', alias.tier);
211
+
212
+ const media = classifyModel('hunyuan-image-alpha', { id: 'hunyuan-image-alpha' });
213
+ ok(media.tier === 'media' && media.allow === false, '媒体模型被拒绝', media.tier);
214
+
215
+ const retired = classifyModel('glm-4.6', { id: 'glm-4.6' });
216
+ ok(retired.tier === 'retired' && retired.allow === false, '已下架模型被拒绝', retired.tier);
217
+
218
+ const unknown = classifyModel('totally-new-model', { id: 'totally-new-model' });
219
+ ok(unknown.allow === false, '未知模型默认不放行', unknown.allow);
220
+
221
+ /* ------------------------------------------------------------------- 账本 */
222
+
223
+ console.log('· 用量账本');
224
+ const nowMs = Date.parse('2026-11-03T10:00:00+08:00');
225
+ const records = [
226
+ { ts: nowMs - 3600e3, model: 'deepseek-v4.1-flash', ok: true, promptTokens: 15, completionTokens: 4, totalTokens: 19, credit: 0, multiplier: 0.11 },
227
+ { ts: nowMs - 3 * 864e5, model: 'glm-5.2', ok: true, promptTokens: 100, completionTokens: 50, totalTokens: 150, credit: 1.25, multiplier: 0.5 },
228
+ { ts: nowMs - 40 * 864e5, model: 'hy3', ok: false, promptTokens: 0, completionTokens: 0, totalTokens: 0, credit: 0 },
229
+ ];
230
+ const summary = summarize(records, nowMs);
231
+ ok(summary.totals.today.calls === 1, '今天只统计今天那条', summary.totals.today.calls);
232
+ ok(summary.totals.week.calls === 2, '近 7 天含 3 天前那条', summary.totals.week.calls);
233
+ ok(summary.totals.month.calls === 2, '近 30 天不含 40 天前那条', summary.totals.month.calls);
234
+ ok(summary.totals.all.calls === 3, '全部含失败那条', summary.totals.all.calls);
235
+ ok(summary.totals.month.failed === 0, '近 30 天没有失败', summary.totals.month.failed);
236
+ ok(summary.recent[0].total === 19, '最近记录按时间倒序取到最新那条(total=19,不是最旧那条)', summary.recent[0].total);
237
+ ok(
238
+ summary.recent.every((r) => 'total' in r && 'prompt' in r && 'completion' in r),
239
+ '最近记录的字段名是 total/prompt/completion(面板按这三个名字读)',
240
+ );
241
+ ok(summary.byModel[0].model === 'glm-5.2', '按模型聚合按积分降序', summary.byModel.map((m) => m.model));
242
+ const creditGap = summarize([{ ts: nowMs, model: 'glm-5.2', ok: true, totalTokens: 3 }], nowMs);
243
+ ok(creditGap.totals.today.creditUnknown === 1, '上游未回传 credit 时计为未知,不静默算 0', creditGap.totals.today);
244
+ ok(creditGap.recent[0].credit === null, '最近调用的未知 credit 保持 null,与明确 0 区分', creditGap.recent[0]);
245
+ ok(!('windowDays' in summary) && !('spanDays' in summary), '未接线的 days/spanDays 参数与字段已删除');
246
+
247
+ /* --------------------------------------------------------------- 回归防线 */
248
+
249
+ console.log('· 回归防线(复检报告第 9 条点名缺断言的行为)');
250
+
251
+ // 哨兵:wb-cleared 表示用户登出,wb-auto 表示「允许自动发现」
252
+ ok(TOKEN_CLEARED === 'wb-cleared' && TOKEN_AUTO === 'wb-auto', '两个凭据哨兵的取值稳定', [TOKEN_CLEARED, TOKEN_AUTO]);
253
+
254
+ const emptyCredDir = mkdtempSync(join(tmpdir(), 'wb-cred-'));
255
+
256
+ /** 造一个最小 World:只喂 loadTokens 需要的东西,避免碰真机凭据。 */
257
+ function makeWorld(secretValue) {
258
+ const ctx = {
259
+ id: 'workbuddy',
260
+ cfg: { ...WB_DEFAULTS, credentialsDir: emptyCredDir, model: 'deepseek-v4.1-flash' },
261
+ timezone: 'Asia/Shanghai',
262
+ botName: 'Coo',
263
+ botDir: emptyCredDir,
264
+ packageDir: pkgDir,
265
+ dataDir: mkdtempSync(join(tmpdir(), 'wb-data-')),
266
+ repoRoot: pkgDir,
267
+ secret: () => secretValue,
268
+ storeSecret: () => {},
269
+ persist: () => {},
270
+ restart: async () => {},
271
+ };
272
+ return new WorkBuddyWorld({ ctx });
273
+ }
274
+
275
+ const signedOutWorld = makeWorld(TOKEN_CLEARED);
276
+ await signedOutWorld.loadTokens();
277
+ ok(signedOutWorld.tokens === null, 'wb-cleared:不读数据目录凭据', signedOutWorld.tokens);
278
+ ok(/已登出|重新探测/.test(String(signedOutWorld.lastError ?? '')), 'wb-cleared:提示用户已登出(可重新探测)', signedOutWorld.lastError);
279
+
280
+ const autoWorld = makeWorld(TOKEN_AUTO);
281
+ await autoWorld.loadTokens();
282
+ ok(autoWorld.tokens === null, 'wb-auto:空目录下没有可用凭据', autoWorld.tokens);
283
+ ok(
284
+ !/已登出/.test(String(autoWorld.lastError ?? '')),
285
+ 'wb-auto:不会把自己判成「已登出」(否则 rediscover 后重启又变未登录)',
286
+ autoWorld.lastError,
287
+ );
288
+
289
+ // 计费域:固定国内计费域,不按 baseUrl 猜;自定义 baseUrl 时跟着走同一出口
290
+ const cnUp = new WbUpstream({ baseUrl: 'https://copilot.tencent.com' });
291
+ ok(cnUp.billingUrl('/x').startsWith('https://www.codebuddy.cn'), '默认计费域是 www.codebuddy.cn', cnUp.billingUrl('/x'));
292
+ const proxyUp = new WbUpstream({ baseUrl: 'https://proxy.example.com' });
293
+ ok(proxyUp.billingUrl('/x') === 'https://proxy.example.com/x', '自定义 baseUrl 时计费走同一出口', proxyUp.billingUrl('/x'));
294
+
295
+ // 429 的软/硬区分
296
+ ok(classifyHttpFailure(429, '额度不足,请充值') === 'hard_credit', '429 + 额度文案 → hard_credit', classifyHttpFailure(429, '额度不足,请充值'));
297
+ ok(classifyHttpFailure(429, 'too many requests') === 'soft_rate', '429 普通限流 → soft_rate', classifyHttpFailure(429, 'too many requests'));
298
+
299
+ // 面板方法白名单
300
+ ok(
301
+ Array.isArray(PANEL_METHODS.account) && PANEL_METHODS.account.includes('setToken'),
302
+ '账号面板允许 setToken',
303
+ );
304
+ ok(!PANEL_METHODS.usage.includes('setToken'), '用量面板不能间接写密钥库(白名单生效)');
305
+ ok(!('priority' in PANEL_METHODS), '0.3.4 移除「中转站优先」面板后不再有 priority 方法表', Object.keys(PANEL_METHODS));
306
+
307
+ // 0.3.4:界面只剩 3 个面板,也不再声明 storage(宿主会据此生成空白「数据清理」页签)
308
+ const uiWorld = makeWorld(TOKEN_CLEARED);
309
+ const ui = uiWorld.webUi('zh');
310
+ ok(ui.panels.map((p) => p.id).join(',') === 'models,account,usage', '0.3.4 面板只剩 models/account/usage', ui.panels.map((p) => p.id));
311
+ ok(Array.isArray(ui.lamps) && ui.lamps.length === 2, '灯态只保留 WorkBuddy + 主进程两盏', ui.lamps?.length);
312
+ ok(!('storage' in ui), '不再声明 storage(否则宿主会生成空的「数据清理」页签)');
313
+ ok(!('prefer' in uiWorld.cfg), '配置里不再有 prefer 开关字段', Object.keys(uiWorld.cfg));
314
+
315
+ // 账本并发:append 与 prune 串行,不互相覆盖
316
+ const ledger = new UsageLedger({ dataDir: mkdtempSync(join(tmpdir(), 'wb-ledger-')), log: { warn: () => {} } });
317
+ await Promise.all(
318
+ Array.from({ length: 30 }, (_, i) =>
319
+ ledger.append({ ts: Date.now() - i * 1000, model: 'deepseek-v4.1-flash', ok: true, promptTokens: 1, completionTokens: 1, totalTokens: 2, credit: 0 }),
320
+ ),
321
+ );
322
+ await ledger.prune(Date.now());
323
+ const kept = await ledger.readAll();
324
+ ok(kept.length === 30, '并发 append + prune 后一条都没丢', kept.length);
325
+
326
+ // 「今天」按本地日期算,不是 UTC
327
+ ok(/getFullYear/.test(readFileSync(join(pkgDir, 'src', 'usage.js'), 'utf8')), 'dayKey 用本地日期字段(getFullYear),不用 toISOString');
328
+ const localDay = dayKey(Date.parse('2026-11-03T12:00:00+08:00'));
329
+ ok(/^\d{4}-\d{2}-\d{2}$/.test(localDay), 'dayKey 输出 YYYY-MM-DD', localDay);
330
+
331
+ // SSE:最后一段 data 没有换行时也要把 usage 处理掉(否则积分恒 0)
332
+ const sseServer = createServer((req, res) => {
333
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
334
+ res.write('data: {"code":0,"choices":[{"delta":{"content":"嗨"}}],"usage":{"prompt_tokens":7,"completion_tokens":3,"total_tokens":10}}\n\n');
335
+ // 末尾只带 credit 且故意不带换行:既不能丢尾帧,也不能覆盖前帧 token。
336
+ res.write('data: {"code":0,"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"credit":0.02}}');
337
+ res.end();
338
+ });
339
+ await new Promise((resolve) => sseServer.listen(0, '127.0.0.1', resolve));
340
+ const sseUrl = `http://127.0.0.1:${sseServer.address().port}`;
341
+ const sseUp = new WbUpstream({ baseUrl: sseUrl });
342
+ const chatOut = await sseUp.chat({ accessToken: 'test-token' }, { model: 'deepseek-v4.1-flash', messages: [{ role: 'user', content: 'hi' }], maxTokens: 64 }, () => {});
343
+ sseServer.close();
344
+ ok(chatOut.text === '嗨', 'SSE 正文拼接正确', chatOut.text);
345
+ ok(chatOut.usage?.totalTokens === 10, 'SSE 尾行(无换行)里的 usage 被解析', chatOut.usage);
346
+ ok(chatOut.credit === 0.02, 'SSE 尾行里的 credit 被解析', chatOut.credit);
347
+
348
+ // start() 兜底:pushEvent 失败也不能把 started 卡住(否则两盏灯永远「正在读取登录态…」)
349
+ const startWorld = makeWorld(TOKEN_CLEARED);
350
+ const failingHost = {
351
+ log: { info: () => {}, warn: () => {}, error: () => {} },
352
+ pushEvent: () => Promise.reject(new Error('boom')),
353
+ };
354
+ await startWorld.start(failingHost);
355
+ ok(startWorld.started === true, 'pushEvent 抛错时 start() 仍标记 started(灯态不卡住)');
356
+ await startWorld.stop();
357
+
358
+ // 0.3.1 审查报告新发现的回归防线(单独成文件,便于与上面 68 条基线区分)
359
+ await runRegression(ok, { pkgDir });
360
+
361
+ /* ------------------------------------------------------------------- 结果 */
362
+
363
+ console.log('');
364
+ if (failures.length === 0) {
365
+ console.log(`✓ contract 通过:${passed} 条断言`);
366
+ process.exit(0);
367
+ }
368
+ console.error(`✗ contract 失败:${failures.length} 条(通过 ${passed} 条)`);
369
+ for (const f of failures.slice(0, 20)) console.error(` - ${f}`);
370
+ process.exit(1);
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 生成 `describe.json`。
4
+ *
5
+ * 为什么需要它:`describe.json` 是给市场/宿主看的清单,`WB_TOOL_DECLS` 是运行时真正注册的
6
+ * 工具声明。两份各写各的,于是 0.1.7 里 `wb_chat` / `wb_credits` 的描述已经对不上了。
7
+ * 这里把 `describe.json` 变成生成物:
8
+ *
9
+ * - 工具名 / 描述 / 参数 / tags:来自 `src/world.js` 的 `WB_TOOL_DECLS`(唯一来源);
10
+ * - 中英摘要:本文件里的 `SUMMARIES`(市场展示用的短句,源码里没有这个概念);
11
+ * - 事件:本文件里的 `EVENTS`;
12
+ * - 环境提示词:`src/ENV_PROMPT.md` 全文。
13
+ *
14
+ * 用法:
15
+ * node scripts/gen-describe.mjs # 写回 describe.json
16
+ * node scripts/gen-describe.mjs --check # 只比对,不一致退出码 1
17
+ */
18
+
19
+ import { readFileSync, writeFileSync } from 'node:fs';
20
+ import { join, resolve } from 'node:path';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { WB_TOOL_DECLS } from '../src/world.js';
23
+
24
+ const pkgDir = fileURLToPath(new URL('..', import.meta.url));
25
+
26
+ /** 市场列表里显示的一两句摘要(describe.json 的 summary 字段)。 */
27
+ const SUMMARIES = {
28
+ wb_list_models: {
29
+ zh: '列出 WorkBuddy 公开对话模型(安全清单)及各自的积分倍率、上下文与推理档;all=true 时附上被排除的项与原因。',
30
+ en: 'Lists the safe WorkBuddy chat models with multiplier, context and reasoning efforts; all=true also lists excluded ones with reasons.',
31
+ },
32
+ wb_select_model: {
33
+ zh: '选择 wb_chat 默认使用的 WorkBuddy 模型,选择会持久保存。',
34
+ en: 'Selects the default WorkBuddy model for wb_chat; the choice persists across restarts.',
35
+ },
36
+ wb_chat: {
37
+ zh: '向当前选中的 WorkBuddy 模型发一句单轮提问并取回答,会消耗用户自己的 WorkBuddy 积分。',
38
+ en: "Asks the selected WorkBuddy model a single-turn question; spends the user's own WorkBuddy credits.",
39
+ },
40
+ wb_credits: {
41
+ zh: '读取当前 WorkBuddy 账号的剩余积分与各积分包的已用/剩余(只读)。',
42
+ en: 'Shows remaining WorkBuddy credits and per-package usage (read-only).',
43
+ },
44
+ };
45
+
46
+ const EVENTS = [
47
+ {
48
+ type: 'workbuddy.started',
49
+ description: {
50
+ zh: 'World 挂载完成,报告登录态与目录概况。',
51
+ en: 'The World was mounted; reports sign-in and catalog status.',
52
+ },
53
+ },
54
+ ];
55
+
56
+ /** 由源码生成 describe.json 的对象。 */
57
+ export function buildDescribe() {
58
+ const envPrompt = readFileSync(join(pkgDir, 'src', 'ENV_PROMPT.md'), 'utf8').replace(/\s+$/, '');
59
+ return {
60
+ tools: WB_TOOL_DECLS.map((decl) => ({
61
+ name: decl.name,
62
+ description: decl.description,
63
+ summary: SUMMARIES[decl.name] ?? { zh: decl.name, en: decl.name },
64
+ tags: [...(decl.tags ?? [])],
65
+ parameters: decl.parameters,
66
+ })),
67
+ events: EVENTS,
68
+ envPrompt,
69
+ };
70
+ }
71
+
72
+ /** 便于测试:把对象序列化成写入文件时的文本。 */
73
+ export function renderDescribe(obj = buildDescribe()) {
74
+ return `${JSON.stringify(obj, null, 2)}\n`;
75
+ }
76
+
77
+ const isMain = process.argv[1] !== undefined && resolve(process.argv[1]) === resolve(fileURLToPath(import.meta.url));
78
+ if (isMain) {
79
+ const target = join(pkgDir, 'describe.json');
80
+ const next = renderDescribe();
81
+ if (process.argv.includes('--check')) {
82
+ let current = '';
83
+ try {
84
+ current = readFileSync(target, 'utf8');
85
+ } catch {
86
+ current = '';
87
+ }
88
+ if (current !== next) {
89
+ console.error('✗ describe.json 与源码不一致;跑 `node scripts/gen-describe.mjs` 重新生成。');
90
+ process.exit(1);
91
+ }
92
+ console.log('✓ describe.json 与源码一致');
93
+ } else {
94
+ writeFileSync(target, next, 'utf8');
95
+ console.log(`✓ 已生成 describe.json(tools ${WB_TOOL_DECLS.length} 个)`);
96
+ }
97
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * 找 Coopanion 的 `resources/app` 目录(脚本共用)。
3
+ *
4
+ * 0.3.0 删掉了 `src/host.js`(不再注入宿主文件),但自检、UI 验证、构建脚本仍然需要
5
+ * 「宿主装在哪」这一个信息,所以把它单独抽成脚本侧的探测,扩展运行时不再依赖它。
6
+ */
7
+
8
+ import { existsSync, readFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+
11
+ /**
12
+ * @param {{ packageDir?: string }} [opts]
13
+ * @returns {string} app 目录绝对路径;找不到返回空串
14
+ */
15
+ export function findAppRoot(opts = {}) {
16
+ const candidates = [];
17
+
18
+ const fromEnv = process.env.COOPANION_APP_ROOT;
19
+ if (fromEnv) candidates.push(fromEnv);
20
+
21
+ // data-location.json 里记着 data 目录,app 在它旁边的 resources/app
22
+ const localApp = process.env.LOCALAPPDATA;
23
+ if (localApp) {
24
+ const dataLocation = join(localApp, 'Coopanion', 'data-location.json');
25
+ if (existsSync(dataLocation)) {
26
+ try {
27
+ const data = JSON.parse(readFileSync(dataLocation, 'utf8')).data;
28
+ if (typeof data === 'string' && data) candidates.push(join(dirname(data), 'resources', 'app'));
29
+ } catch {
30
+ /* 读不出来就走下面的默认位置 */
31
+ }
32
+ }
33
+ candidates.push(join(localApp, 'Programs', 'Coopanion', 'resources', 'app'));
34
+ }
35
+
36
+ for (const base of [process.env.ProgramFiles, process.env['ProgramFiles(x86)']]) {
37
+ if (base) candidates.push(join(base, 'Coopanion', 'resources', 'app'));
38
+ }
39
+
40
+ return candidates.find((dir) => existsSync(join(dir, 'build', 'console', 'index.html'))) ?? '';
41
+ }