weflow-cli 1.8.2 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/CHANGELOG.md +342 -0
  2. package/OPERATIONS.md +79 -0
  3. package/README.en.md +9 -2
  4. package/README.md +12 -2
  5. package/bin/weflow-cli-electron.cjs +2 -0
  6. package/bin/weflow-cli.ts +648 -79
  7. package/dist/bin/weflow-cli.js +675 -78
  8. package/dist/bin/weflow-cli.js.map +1 -1
  9. package/dist/mcp-server/http.d.ts +14 -0
  10. package/dist/mcp-server/http.d.ts.map +1 -0
  11. package/dist/mcp-server/http.js +84 -0
  12. package/dist/mcp-server/http.js.map +1 -0
  13. package/dist/mcp-server/httpConfig.d.ts +50 -0
  14. package/dist/mcp-server/httpConfig.d.ts.map +1 -0
  15. package/dist/mcp-server/httpConfig.js +104 -0
  16. package/dist/mcp-server/httpConfig.js.map +1 -0
  17. package/dist/mcp-server/index.d.ts +13 -1
  18. package/dist/mcp-server/index.d.ts.map +1 -1
  19. package/dist/mcp-server/index.js +39 -373
  20. package/dist/mcp-server/index.js.map +1 -1
  21. package/dist/src/panel/server.d.ts.map +1 -1
  22. package/dist/src/panel/server.js +26 -1
  23. package/dist/src/panel/server.js.map +1 -1
  24. package/dist/src/services/assistantEval.d.ts +69 -0
  25. package/dist/src/services/assistantEval.d.ts.map +1 -1
  26. package/dist/src/services/assistantEval.js +270 -8
  27. package/dist/src/services/assistantEval.js.map +1 -1
  28. package/dist/src/services/assistantScenes.d.ts +81 -0
  29. package/dist/src/services/assistantScenes.d.ts.map +1 -0
  30. package/dist/src/services/assistantScenes.js +322 -0
  31. package/dist/src/services/assistantScenes.js.map +1 -0
  32. package/dist/src/services/assistantService.d.ts +14 -4
  33. package/dist/src/services/assistantService.d.ts.map +1 -1
  34. package/dist/src/services/assistantService.js +82 -6
  35. package/dist/src/services/assistantService.js.map +1 -1
  36. package/dist/src/services/assistantSkills.d.ts +94 -0
  37. package/dist/src/services/assistantSkills.d.ts.map +1 -0
  38. package/dist/src/services/assistantSkills.js +330 -0
  39. package/dist/src/services/assistantSkills.js.map +1 -0
  40. package/dist/src/services/assistantTools.d.ts +7 -0
  41. package/dist/src/services/assistantTools.d.ts.map +1 -1
  42. package/dist/src/services/assistantTools.js +770 -61
  43. package/dist/src/services/assistantTools.js.map +1 -1
  44. package/dist/src/services/assistantTrace.d.ts +4 -0
  45. package/dist/src/services/assistantTrace.d.ts.map +1 -1
  46. package/dist/src/services/assistantTrace.js +9 -0
  47. package/dist/src/services/assistantTrace.js.map +1 -1
  48. package/dist/src/services/configService.d.ts +7 -0
  49. package/dist/src/services/configService.d.ts.map +1 -1
  50. package/dist/src/services/configService.js +4 -2
  51. package/dist/src/services/configService.js.map +1 -1
  52. package/dist/src/services/outboundSend.d.ts +53 -0
  53. package/dist/src/services/outboundSend.d.ts.map +1 -0
  54. package/dist/src/services/outboundSend.js +90 -0
  55. package/dist/src/services/outboundSend.js.map +1 -0
  56. package/dist/src/services/pythonBridge.d.ts.map +1 -1
  57. package/dist/src/services/pythonBridge.js +1 -0
  58. package/dist/src/services/pythonBridge.js.map +1 -1
  59. package/dist/src/utils/python.js +2 -2
  60. package/dist/src/utils/python.js.map +1 -1
  61. package/docs/BRANCHES.md +37 -0
  62. package/docs/DECISIONS.md +350 -0
  63. package/docs/EXTENDING.md +29 -3
  64. package/docs/MCP.md +56 -2
  65. package/docs/PROJECT_STATE.md +121 -9
  66. package/mcp-server/http.ts +108 -0
  67. package/mcp-server/httpConfig.ts +126 -0
  68. package/mcp-server/index.ts +344 -681
  69. package/package.json +1 -1
  70. package/resources/panel/ball-position.cjs +48 -2
  71. package/resources/panel/index.html +6 -4
  72. package/resources/panel/main.cjs +137 -5
  73. package/resources/panel/mascot-base.png +0 -0
  74. package/resources/panel/mascot-iris.png +0 -0
  75. package/resources/panel/mascot-peek.png +0 -0
  76. package/resources/panel/panel.css +95 -60
  77. package/resources/panel/preload.cjs +26 -0
  78. package/resources/panel/renderer.js +167 -10
  79. package/scripts/_utils.py +47 -1
  80. package/scripts/backfill_articles.py +202 -21
  81. package/scripts/biz_daily.py +8 -31
  82. package/scripts/bonds.py +331 -0
  83. package/scripts/chat_notes.py +551 -470
  84. package/scripts/chat_stats.py +8 -7
  85. package/scripts/compile_wiki.py +24 -2
  86. package/scripts/export_chat_html.py +3 -1
  87. package/scripts/mcp_bridge.py +6 -7
  88. package/scripts/wechat_voice.py +9 -0
  89. package/scripts/wiki_lint.py +30 -7
  90. package/src/panel/server.ts +25 -1
  91. package/src/services/assistantEval.ts +323 -12
  92. package/src/services/assistantScenes.ts +342 -0
  93. package/src/services/assistantService.ts +81 -6
  94. package/src/services/assistantSkills.ts +364 -0
  95. package/src/services/assistantTools.ts +738 -59
  96. package/src/services/assistantTrace.ts +9 -0
  97. package/src/services/configService.ts +412 -403
  98. package/src/services/outboundSend.ts +126 -0
  99. package/src/services/pythonBridge.ts +1 -0
  100. package/src/utils/python.ts +2 -2
package/bin/weflow-cli.ts CHANGED
@@ -21,8 +21,11 @@ import { DateRangeError, parseLocalDateOrIso, resolveExportDateRange } from '../
21
21
  import { resolvePackageRoot as resolvePackageRootFrom } from '../src/utils/packageRoot.js'
22
22
  import { WechatMessageService } from '../src/services/wechatMessageService.js'
23
23
  import { whitelistService, MAX_TEXT_LENGTH } from '../src/services/whitelistService.js'
24
+ import { authorizeOutbound, parseOutboundPolicy, performOutbound } from '../src/services/outboundSend.js'
24
25
  import { applyDerivedNtKeys, enableFavorites, detectFavDbPath } from '../src/services/initKeyService.js'
25
26
  import type { ChatSession } from '../src/types.js'
27
+ import { disabledIds, describeSkill, readSkillBody, scanSkills, skillRoots, skillState } from '../src/services/assistantSkills.js'
28
+ import { assistantScenes, validateSceneId, type Scene } from '../src/services/assistantScenes.js'
26
29
 
27
30
  const program = new Command()
28
31
 
@@ -282,7 +285,7 @@ program
282
285
  read: {
283
286
  sessions: { cli: 'sessions --json', mcp: 'wechat.list_sessions' },
284
287
  messages: { cli: 'messages <talker> --json', mcp: 'wechat.export_messages' },
285
- contacts: { cli: 'contacts --json' },
288
+ contacts: { cli: 'contacts --json', mcp: 'wechat.list_contacts', localIdentifiersInModelContext: false },
286
289
  exports: {
287
290
  cli: 'export <talker> <json|txt|html|excel>',
288
291
  mcp: 'wechat.export_messages',
@@ -316,8 +319,36 @@ program
316
319
  },
317
320
  dailyReader: { cli: 'daily-server --status --json' },
318
321
  dailyStats: { cli: 'daily-stats --json' },
322
+ // 只读、纯本地、不调模型。**故意没有 mcp 那一栏**(D-062):它给的是关于第三方的推断
323
+ // ——谁在被冷落、你会失去谁 —— 所以不进助手、不进 MCP、不喂模型。
324
+ bonds: { cli: 'bonds --json', mcp: null, leavesTheMachine: false },
319
325
  diagnostics: { cli: 'check --json' },
320
326
  todos: { cli: 'todos list --json' },
327
+ // 2026-09-29 三个界面对齐时新开的读取能力(D-058)。逐个写清它会不会出境,
328
+ // 因为其中两个会——`fetch_article` 白名单 + 逐跳复检,`search_public` 没有任何守卫。
329
+ review: { cli: 'review ...', mcp: 'wechat.get_review', writesReport: true },
330
+ concepts: { cli: 'wiki ...', mcp: 'wechat.get_concepts' },
331
+ articleFetch: {
332
+ cli: null, // 没有对应的 CLI 命令:它本来就是为模型准备的读取能力
333
+ mcp: 'wechat.fetch_article',
334
+ network: true,
335
+ allowlist: 'https only, host must be exactly mp.weixin.qq.com',
336
+ redirectsReValidatedPerHop: true,
337
+ confirmationRequired: false,
338
+ },
339
+ publicArticleSearch: {
340
+ mcp: 'wechat.search_public',
341
+ network: true,
342
+ // **这条是如实的**:搜索词由模型决定、发到第三方搜索页,没有白名单也没有预览。
343
+ // 它在该项目的边界内是被明确接受的残余风险(D-058),这里不能写成"无出境"。
344
+ allowlist: null,
345
+ modelAuthoredQueryLeavesTheMachine: true,
346
+ confirmationRequired: false,
347
+ },
348
+ articleFormatting: { mcp: 'wechat.format_article', cli: null, writesNothing: true, network: false },
349
+ themes: { mcp: 'wechat.list_themes', writesNothing: true },
350
+ wikiLint: { cli: 'wiki lint --json', mcp: 'wechat.lint_wiki', readsLocalChat: false, writesNothing: true },
351
+ skillCheck: { cli: 'skill check --json', mcp: 'wechat.check_skills', writesNothing: true },
321
352
  awaiting: {
322
353
  cli: 'awaiting --yes',
323
354
  preview: 'awaiting --dry-run --json',
@@ -400,6 +431,33 @@ program
400
431
  execute: 'todos <done|undone|rm> <id> --yes --json',
401
432
  confirmationRequired: true,
402
433
  },
434
+ skills: {
435
+ list: 'skill list [--query <q>] --json',
436
+ show: 'skill show <id> --json',
437
+ check: 'skill check --json',
438
+ readOnly: true,
439
+ // 技能是**资料**,不是插件:助手只把它当提示词/正文读,不执行里面的脚本,
440
+ // 也不因为装了技能就多出任何工具(P4 验收标准:扩展读不到配置与数据库)。
441
+ installsAnything: false,
442
+ executesSkillCode: false,
443
+ grantsTools: false,
444
+ directories: 'skillDirs config (default: ~/.claude/skills, ~/.weflow-cli/skills)',
445
+ disable: 'config set skillDisabled <id,...>(技能自己也能写 enabled: false)',
446
+ },
447
+ scenes: {
448
+ list: 'scene list --json',
449
+ show: 'scene show <id> --json',
450
+ preview: 'scene <add|remove|enable|disable|bind|unbind> … --dry-run --json',
451
+ execute: 'scene <add|remove|enable|disable|bind|unbind> … --yes --json',
452
+ confirmationRequired: true,
453
+ // 场景只改**本机提示词预设**,不发消息、不读聊天、不调模型
454
+ readsLocalChat: false,
455
+ invokesAI: false,
456
+ sendsNothing: true,
457
+ stateLocation: 'local-user-config-dir',
458
+ stateSchema: 'weflow-scenes/v1',
459
+ modelWritable: false,
460
+ },
403
461
  accessControlMutations: {
404
462
  preview: '<whitelist|blacklist> <add|rm> <target> --dry-run --json',
405
463
  execute: '<whitelist|blacklist> <add|rm> <target> --yes --json',
@@ -1011,6 +1069,7 @@ const configurableKeys = [
1011
1069
  'wereadApiKey',
1012
1070
  'assistantPrivacy', 'assistantWhitelist', 'assistantGroupWhitelist',
1013
1071
  'assistantGroupRequireMention', 'assistantFastRoute', 'assistantPanelUser', 'quickReplyContacts',
1072
+ 'skillDirs', 'skillDisabled',
1014
1073
  'dailySources', 'dailySourceCategories',
1015
1074
  'dailyExcludeTopics', 'dailyAiEnabled',
1016
1075
  'emoticonSeed',
@@ -3237,54 +3296,45 @@ program
3237
3296
  process.exit(1)
3238
3297
  }
3239
3298
 
3240
- // 黑名单优先拦截
3241
- if (whitelistService.isBlocked(wxid)) {
3242
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'TARGET_BLOCKED', error: '目标在黑名单中', target: { wxid, displayName } }))
3243
- else {
3299
+ // 三道闸(黑名单 → 白名单 → 限速)与"每次尝试都写审计"在 `src/services/outboundSend.ts`
3300
+ // 里**只有一份**,因为 2026-10-01 起有了第二条发送路(`draft --pick N --send`,见 D-063)。
3301
+ // 两份写同一件事,分叉的后果具体是"某一条路绕过了白名单"。
3302
+ const policy = parseOutboundPolicy(Number(opts.rateWindow), Number(opts.rateMax))
3303
+ if ('code' in policy) {
3304
+ if (opts.json) console.log(JSON.stringify({ success: false, code: policy.code, error: policy.error }))
3305
+ else console.log(chalk.red('速率参数无效:rate-window 必须为 1000-3600000,rate-max 必须为 1-100'))
3306
+ process.exit(1)
3307
+ }
3308
+ const attempt = {
3309
+ wxid, displayName, kind, preview, text: message,
3310
+ mediaPath: kind === 'text' ? undefined : String(opts.image || opts.file),
3311
+ }
3312
+ const decision = authorizeOutbound(attempt, policy)
3313
+ if (!decision.ok) {
3314
+ const { refusal } = decision
3315
+ if (opts.json) {
3316
+ console.log(JSON.stringify({
3317
+ success: false, code: refusal.code, error: refusal.error,
3318
+ ...(refusal.code === 'TARGET_BLOCKED' || refusal.code === 'TARGET_NOT_ALLOWED'
3319
+ ? { target: { wxid, displayName } } : {}),
3320
+ ...(refusal.rateLimit ? { rateLimit: refusal.rateLimit } : {}),
3321
+ }))
3322
+ } else if (refusal.code === 'TARGET_BLOCKED') {
3244
3323
  console.log(chalk.red('\n❌ 目标在黑名单中,绝对禁止发送'))
3245
3324
  console.log(chalk.gray(` wxid: ${wxid}`))
3246
3325
  console.log(chalk.gray(` 解除: weflow-cli blacklist rm ${wxid}\n`))
3247
- }
3248
- whitelistService.auditSend({
3249
- timestamp: Date.now(), action: 'send', targetWxid: wxid, targetName: displayName,
3250
- kind, success: false, preview, error: 'blocked by blacklist',
3251
- })
3252
- process.exit(1)
3253
- }
3254
-
3255
- // Whitelist check
3256
- if (!whitelistService.isAllowed(wxid)) {
3257
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'TARGET_NOT_ALLOWED', error: '目标不在白名单中', target: { wxid, displayName } }))
3258
- else {
3326
+ } else if (refusal.code === 'TARGET_NOT_ALLOWED') {
3259
3327
  console.log(chalk.red('\n❌ 目标不在白名单中,拒绝发送'))
3260
3328
  console.log(chalk.gray(` 先运行: weflow-cli whitelist add ${target}`))
3261
3329
  console.log(chalk.gray(` 查看名单: weflow-cli whitelist\n`))
3262
- }
3263
- process.exit(1)
3264
- }
3265
-
3266
- // 速率限制 (dry-run 不计入, 不检查也行, 但保持一致检查)
3267
- const windowMs = Number(opts.rateWindow)
3268
- const max = Number(opts.rateMax)
3269
- if (!Number.isInteger(windowMs) || windowMs < 1000 || windowMs > 3_600_000 ||
3270
- !Number.isInteger(max) || max < 1 || max > 100) {
3271
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_RATE_LIMIT', error: 'rate-window 必须为 1000-3600000,rate-max 必须为 1-100' }))
3272
- else console.log(chalk.red('速率参数无效:rate-window 必须为 1000-3600000,rate-max 必须为 1-100'))
3273
- process.exit(1)
3274
- }
3275
- const rate = whitelistService.checkRateLimit(windowMs, max)
3276
- if (!rate.allowed) {
3277
- if (opts.json) console.log(JSON.stringify({ success: false, code: 'RATE_LIMITED', error: '触发发送速率限制', rateLimit: rate }))
3278
- else {
3330
+ } else {
3331
+ const rate = refusal.rateLimit!
3279
3332
  console.log(chalk.red(`\n❌ 触发速率限制: 最近 ${rate.windowMs / 1000}s 内已发送 ${rate.count} 条 (上限 ${rate.max})`))
3280
3333
  console.log(chalk.gray(' 请稍后再试, 或调整 --rate-window / --rate-max\n'))
3281
3334
  }
3282
- whitelistService.auditSend({
3283
- timestamp: Date.now(), action: 'send', targetWxid: wxid, targetName: displayName,
3284
- kind, success: false, preview, error: `rate limited (${rate.count}/${rate.max})`,
3285
- })
3286
3335
  process.exit(1)
3287
3336
  }
3337
+ const rate = decision.rate
3288
3338
 
3289
3339
  // 二次确认 — 同时显示 wxid + displayName + 消息预览
3290
3340
  const actionPreview = {
@@ -3338,41 +3388,8 @@ program
3338
3388
  process.exit(1)
3339
3389
  }
3340
3390
 
3341
- const service = new WechatMessageService({ token })
3342
-
3343
- let success = false
3344
- let errorMsg: string | undefined
3345
- try {
3346
- if (opts.image) {
3347
- success = await service.sendImage(wxid, opts.image)
3348
- } else if (opts.file) {
3349
- success = await service.sendFile(wxid, opts.file)
3350
- } else {
3351
- success = await service.sendText(wxid, message)
3352
- }
3353
- } catch {
3354
- errorMsg = '消息通道调用失败'
3355
- }
3356
-
3357
- if (!success && !errorMsg) {
3358
- // 检查是否因缺少 context_token
3359
- const hasToken = !!(configService.getContextTokens()[wxid])
3360
- errorMsg = hasToken
3361
- ? '发送失败 (接口返回错误, 可能 token 过期)'
3362
- : '缺少 context_token — 需先收到对方一条消息 (或运行 weflow-cli listen 等待对方消息)'
3363
- }
3364
-
3365
- // 审计日志
3366
- whitelistService.auditSend({
3367
- timestamp: Date.now(),
3368
- action: 'send',
3369
- targetWxid: wxid,
3370
- targetName: displayName,
3371
- kind,
3372
- success,
3373
- preview,
3374
- error: success ? undefined : errorMsg,
3375
- })
3391
+ // 真的发 + 按结果写审计,都在共享模块里(与 `draft --send` 同一份)
3392
+ const { success, error: errorMsg } = await performOutbound(attempt)
3376
3393
 
3377
3394
  if (success) {
3378
3395
  if (opts.json) console.log(JSON.stringify({ success: true, ...actionPreview }))
@@ -4520,6 +4537,7 @@ program
4520
4537
  }
4521
4538
 
4522
4539
  const child = spawn(getPythonCommand(), args, {
4540
+ windowsHide: true,
4523
4541
  stdio: 'inherit',
4524
4542
  env: pythonProcessEnv(),
4525
4543
  })
@@ -5003,6 +5021,7 @@ program
5003
5021
  // 交互模式:使用 spawn 保持终端交互
5004
5022
  args.push('--interactive', '--top-k', String(topK))
5005
5023
  const child = spawn(getPythonCommand(), args, {
5024
+ windowsHide: true,
5006
5025
  stdio: 'inherit',
5007
5026
  env: {
5008
5027
  ...pythonProcessEnv(opts.apiKey),
@@ -5271,6 +5290,10 @@ program
5271
5290
  .command('draft <talker>')
5272
5291
  .description('帮我起草回复:先判断(意图/风险/该不该给实质),再起草候选 —— **只产出文本,不发送**')
5273
5292
  .option('--count <n>', '要几条候选', '3')
5293
+ .option('--pick <n>', '选第几条(从 1 数);不带 --send 时只把那条的完整原文打出来')
5294
+ .option('--send', '把选中的那条发出去 —— **必须同时给 --pick**(不允许"自己挑一条发"),仍需 --yes/--dry-run')
5295
+ .option('--rate-window <ms>', '发送速率窗口毫秒(与 send 同一份策略)', '60000')
5296
+ .option('--rate-max <n>', '窗口内最大发送条数', '10')
5274
5297
  .option('--gate-commitment', '承诺未兑现时也拒绝起草(默认只在提示词里约束)')
5275
5298
  .option('--dry-run', '仅预览会发多少字符给哪两个模型,不调用')
5276
5299
  .option('--yes', '确认把这段对话发送到判断模型与生成模型')
@@ -5279,9 +5302,20 @@ program
5279
5302
  const { execFile } = await import('child_process')
5280
5303
  const { promisify } = await import('util')
5281
5304
  const execFileAsync = promisify(execFile)
5305
+ // **用法错误先报**,而且都在调模型之前报:`--send` 少了 `--pick` 是"你没说发哪条",
5306
+ // `--pick 9` 而只有 3 条是"那条根本不存在" —— 两者都不该先问一遍"要不要把对话发给云端模型"、
5307
+ // 更不该先花掉模型调用再拒绝。
5308
+ const count = parseCliInteger(opts.count, 'count', 1, 5, opts.json)
5309
+ if (opts.send && opts.pick === undefined) {
5310
+ const message = '--send 必须同时给 --pick <序号>:先看候选,再点名要发哪一条'
5311
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'PICK_REQUIRED', error: message }))
5312
+ else console.log(chalk.red(`
5313
+ ❌ ${message}`))
5314
+ process.exit(1)
5315
+ }
5316
+ const pick = opts.pick === undefined ? 0 : parseCliInteger(opts.pick, 'pick', 1, count, opts.json)
5282
5317
  const pkgRoot = resolvePackageRoot()
5283
5318
  const script = join(pkgRoot, 'scripts', 'draft_reply.py')
5284
- const count = parseCliInteger(opts.count, 'count', 1, 5, opts.json)
5285
5319
  // **"确认过了"只用一个变量表示**(`--yes` 或交互回答"是"),参数在确认之后才拼。
5286
5320
  // 原来的写法是先拼参数、再问,于是**交互确认那条路是坏的**:答了"是",`args` 里
5287
5321
  // 却从没补上 `--yes`,脚本照样拒绝(用户看到的是"我确认了它却说没确认")。
@@ -5309,6 +5343,149 @@ program
5309
5343
  return
5310
5344
  }
5311
5345
  }
5346
+ // ---------------- 选中并(可选)发送 ----------------
5347
+ //
5348
+ // **只有给了 `--pick` 或 `--send` 才走这条分支**;不带它们的调用与以前逐字相同(原样透传脚本输出)。
5349
+ //
5350
+ // 这条分支存在的理由:起草那一半早就有了(判断 → 候选 → 排序),缺的是"人选定之后能真的发出去"。
5351
+ // 而它的**要点是这个 `--pick`**:发送必须由人点名"第几条"。少了它,就成了"模型起草三条、
5352
+ // 模型挑一条、模型发出去" —— 那正是本仓库划掉的那件事
5353
+ // (docs/EXTENDING.md:sending is structurally unreachable from a model-driven path)。
5354
+ if (opts.pick !== undefined || opts.send) {
5355
+ // **`--dry-run` 的语义是"零出境"**,而候选必须由模型产出来 —— 两者不可兼得:不起草就没有
5356
+ // 候选,"预览某一条会发什么"这件事本身不成立。所以这里只报"会发多少字符给哪两个模型"
5357
+ // (脚本的 dry-run 本来就报这个),并把话说清楚,而不是假装预览了一条。
5358
+ if (opts.dryRun) {
5359
+ try {
5360
+ const { stdout } = await execFileAsync(getPythonCommand(),
5361
+ [script, '--talker', String(talker), '--count', String(count), '--dry-run',
5362
+ ...(opts.json ? ['--json'] : [])],
5363
+ { timeout: 120_000, maxBuffer: 20 * 1024 * 1024, env: pythonProcessEnv() })
5364
+ process.stdout.write(stdout)
5365
+ } catch (error) {
5366
+ console.error(chalk.red(`\n✗ ${safeSubprocessError(error, '预览失败')}`))
5367
+ process.exit(1)
5368
+ }
5369
+ if (!opts.json) {
5370
+ console.log(chalk.gray('\n候选要由模型产出来,所以 --dry-run 下没有候选可挑。'
5371
+ + '要预览"发第几条":先起草一次(会调用模型),再用 --pick N --send。\n'))
5372
+ }
5373
+ return
5374
+ }
5375
+ // `--pick`/`--send` 的用法错误在 action 开头就报过了(那一段全在调模型之前)
5376
+ // 内部一律用 `--json` 拿结构化结果(用户那侧的 `--json` 管的是最终输出,两回事)
5377
+ const pickArgs = [script, '--talker', String(talker), '--count', String(count), '--json',
5378
+ ...(confirmed ? ['--yes'] : []),
5379
+ ...(opts.gateCommitment ? ['--gate-commitment'] : [])]
5380
+ let drafts: Array<{ text: string }> = []
5381
+ try {
5382
+ const { stdout } = await execFileAsync(getPythonCommand(), pickArgs, {
5383
+ timeout: 300_000, maxBuffer: 50 * 1024 * 1024, env: pythonProcessEnv(),
5384
+ })
5385
+ const parsed = JSON.parse(stdout)
5386
+ if (parsed.gate === 'refused') {
5387
+ // **不起草就不发**:那道闸(涉钱/风险高)拒绝时压根没有候选,这里也不能凭空发点什么
5388
+ const message = `这次不起草:${parsed.reason || '判断层拒绝了'}`
5389
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'DRAFT_REFUSED', error: message, advice: parsed.advice || [] }))
5390
+ else {
5391
+ console.log(chalk.yellow(`\n${message}`))
5392
+ for (const item of parsed.advice || []) console.log(chalk.gray(` · ${item}`))
5393
+ }
5394
+ process.exit(1)
5395
+ }
5396
+ drafts = parsed.drafts || []
5397
+ } catch (error) {
5398
+ const message = safeSubprocessError(error, '起草失败')
5399
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'DRAFT_FAILED', error: message }))
5400
+ else console.error(chalk.red(`\n✗ ${message}`))
5401
+ process.exit(1)
5402
+ }
5403
+ const chosen = drafts[pick - 1]
5404
+ if (!chosen) {
5405
+ const message = `没有第 ${pick} 条候选(这次只有 ${drafts.length} 条)`
5406
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'PICK_OUT_OF_RANGE', error: message }))
5407
+ else console.log(chalk.red(`\n❌ ${message}`))
5408
+ process.exit(1)
5409
+ }
5410
+ if (!opts.send) {
5411
+ if (opts.json) console.log(JSON.stringify({ success: true, action: 'draft', sent: false, pick, text: chosen.text }))
5412
+ else console.log(`第 ${pick} 条:\n${chosen.text}\n\n${chalk.gray('(没有发送任何东西;要发加 --send)')}`)
5413
+ return
5414
+ }
5415
+
5416
+ // 发送这一半走**与 `send` 命令完全相同的那份策略**(黑名单 → 白名单 → 限速 → 审计)
5417
+ let wxid: string
5418
+ try {
5419
+ wxid = await resolveTalker(String(talker), !!opts.json, !!opts.json)
5420
+ } catch (error: any) {
5421
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'TALKER_RESOLUTION_FAILED', error: error.message }))
5422
+ else console.log(chalk.red(`\n❌ ${error.message}`))
5423
+ process.exit(1)
5424
+ }
5425
+ let displayName = whitelistService.lookupName(wxid)
5426
+ if (displayName === wxid) {
5427
+ try {
5428
+ const sessions = await chatService.listSessions(undefined, 200)
5429
+ const match = sessions.find(s => s.username === wxid)
5430
+ if (match?.displayName) displayName = match.displayName
5431
+ } catch { /* 拿不到名字就退回 wxid */ }
5432
+ }
5433
+ const policy = parseOutboundPolicy(Number(opts.rateWindow), Number(opts.rateMax))
5434
+ if ('code' in policy) {
5435
+ if (opts.json) console.log(JSON.stringify({ success: false, code: policy.code, error: policy.error }))
5436
+ else console.log(chalk.red(`\n❌ ${policy.error}`))
5437
+ process.exit(1)
5438
+ }
5439
+ const attempt = {
5440
+ wxid, displayName, kind: 'text' as const,
5441
+ preview: chosen.text.slice(0, 80) + (chosen.text.length > 80 ? '...' : ''),
5442
+ text: chosen.text,
5443
+ }
5444
+ const decision = authorizeOutbound(attempt, policy)
5445
+ if (!decision.ok) {
5446
+ const { refusal } = decision
5447
+ if (opts.json) {
5448
+ // 这里**还没有** sendPreview(它在闸门通过之后才建),所以逐字段写
5449
+ console.log(JSON.stringify({ success: false, code: refusal.code, error: refusal.error,
5450
+ ...(refusal.rateLimit ? { rateLimit: refusal.rateLimit } : {}) }))
5451
+ } else {
5452
+ console.log(chalk.red(`\n❌ ${refusal.error}`))
5453
+ if (refusal.code === 'TARGET_NOT_ALLOWED') console.log(chalk.gray(` 先运行: weflow-cli whitelist add ${talker}\n`))
5454
+ if (refusal.code === 'TARGET_BLOCKED') console.log(chalk.gray(' 这个人在黑名单里,任何一条命令行都不会发给他\n'))
5455
+ if (refusal.rateLimit) console.log(chalk.gray(` 最近 ${refusal.rateLimit.windowMs / 1000}s 内已发 ${refusal.rateLimit.count} 条\n`))
5456
+ }
5457
+ process.exit(1)
5458
+ }
5459
+ const sendPreview = { success: true, action: 'draft-send', target: { wxid, displayName },
5460
+ pick, text: chosen.text, rateLimit: decision.rate }
5461
+ // 两段式在这里:不给 `--yes` 时,JSON 模式回 `CONFIRMATION_REQUIRED`(**带着要发的原文**),
5462
+ // 交互模式则问一句"确定把第 N 条发给 X?"。`--dry-run` 那条路在上面的分支入口就返回了
5463
+ // (它意味着零出境,与"必须由模型产出候选"不可兼得),所以这里没有第三个预览分支。
5464
+ if (opts.json && !opts.yes) {
5465
+ console.log(JSON.stringify({ ...sendPreview, success: false, code: 'CONFIRMATION_REQUIRED', error: '使用 --yes 确认发送' }))
5466
+ process.exit(1)
5467
+ }
5468
+ if (!opts.yes) {
5469
+ const answer = await inquirer.prompt([{
5470
+ type: 'confirm', name: 'send', default: false,
5471
+ message: `确定把第 ${pick} 条发给 ${displayName}?`,
5472
+ }])
5473
+ if (!answer.send) {
5474
+ console.log(chalk.gray('已取消,没有发送'))
5475
+ return
5476
+ }
5477
+ }
5478
+ const sent = await performOutbound(attempt)
5479
+ if (sent.success) {
5480
+ if (opts.json) console.log(JSON.stringify(sendPreview))
5481
+ else console.log(chalk.green('✓ 发送成功'))
5482
+ return
5483
+ }
5484
+ if (opts.json) console.log(JSON.stringify({ ...sendPreview, success: false, code: 'SEND_FAILED', error: sent.error }))
5485
+ else console.log(chalk.red(`✗ 发送失败 — ${sent.error}`))
5486
+ process.exit(1)
5487
+ }
5488
+
5312
5489
  const args = [script, '--talker', String(talker), '--count', String(count),
5313
5490
  // 脚本自己有第二道闸门(`--yes` 才真的把对话发出去),所以要透传
5314
5491
  ...(confirmed ? ['--yes'] : []),
@@ -5783,6 +5960,7 @@ program
5783
5960
 
5784
5961
  dailyLog(chalk.cyan(`\n📰 正在生成 ${targetDate} 公众号日报${noAi ? '(AI 已关闭)' : ''}...\n`))
5785
5962
  const child = spawn(getPythonCommand(), args, {
5963
+ windowsHide: true,
5786
5964
  stdio: opts.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
5787
5965
  env: pythonProcessEnv(apiKey),
5788
5966
  })
@@ -5798,6 +5976,7 @@ program
5798
5976
  const dryRunArgs = [bizDaily, '--date', date, '--engine', 'local', '--dry-run']
5799
5977
  for (const source of opts.source || []) dryRunArgs.push('--source', source)
5800
5978
  const child = spawn(getPythonCommand(), dryRunArgs, {
5979
+ windowsHide: true,
5801
5980
  stdio: opts.json ? ['ignore', 'pipe', 'pipe'] : 'inherit',
5802
5981
  env: pythonProcessEnv(),
5803
5982
  })
@@ -5959,6 +6138,349 @@ dailyFavoritesCmd
5959
6138
 
5960
6139
  program.commands.find(c => c.name() === 'daily')?.addCommand(dailyFavoritesCmd)
5961
6140
 
6141
+ // ==================== skill (本机技能包) ====================
6142
+ // 技能就是磁盘上的 `SKILL.md`,所以这里**没有安装/卸载**:读、看、体检三件事。
6143
+ // 体检(`check`)是最有用的一个 —— 它把"读不出来""不合规范""跨目录撞名"这些
6144
+ // 平时完全静默的问题一次报出来(少一个技能不会报错,只会少一个技能)。
6145
+ const skillCmd = program
6146
+ .command('skill')
6147
+ .description('本机技能包(SKILL.md):列出、查看、体检')
6148
+
6149
+ skillCmd
6150
+ .command('list')
6151
+ .description('列出扫描到的技能')
6152
+ .option('--query <q>', '按关键词过滤(匹配 id、名称、说明、触发词)')
6153
+ .option('--json', 'JSON 输出')
6154
+ .action((opts) => {
6155
+ const scan = scanSkills()
6156
+ const disabled = disabledIds()
6157
+ const q = String(opts.query || '').trim().toLowerCase()
6158
+ const rows = scan.skills.filter(s => !q
6159
+ || [s.id, s.name, s.description, ...s.triggers].some(x => String(x).toLowerCase().includes(q)))
6160
+ .map(s => ({
6161
+ id: s.id,
6162
+ name: s.name,
6163
+ description: s.description,
6164
+ version: s.version,
6165
+ state: skillState(s, disabled),
6166
+ notes: s.notes,
6167
+ // **不给路径**:这是机器输出,路径只有在用户明确要 `show` 时才出现
6168
+ }))
6169
+ if (opts.json) {
6170
+ console.log(JSON.stringify({
6171
+ success: true,
6172
+ roots: skillRoots(),
6173
+ missingRoots: scan.missingRoots,
6174
+ total: rows.length,
6175
+ skills: rows,
6176
+ }))
6177
+ return
6178
+ }
6179
+ if (!rows.length) {
6180
+ console.log(chalk.gray(scan.skills.length ? `没有匹配「${opts.query}」的技能` : '没有扫描到技能'))
6181
+ console.log(chalk.gray(`技能目录:${skillRoots().join('、')}`))
6182
+ for (const dir of scan.missingRoots) console.log(chalk.gray(` (不存在:${dir})`))
6183
+ return
6184
+ }
6185
+ for (const r of rows) {
6186
+ const tag = r.state === 'disabled' ? chalk.gray('[已禁用] ') : ''
6187
+ console.log(`${tag}${chalk.cyan(r.id)}${r.version ? chalk.gray(' v' + r.version) : ''} ${r.name}`)
6188
+ if (r.description) console.log(chalk.gray(` ${r.description.slice(0, 100)}`))
6189
+ for (const n of r.notes) console.log(chalk.yellow(` ⚠ ${n}`))
6190
+ }
6191
+ console.log(chalk.gray(`\n共 ${rows.length} 个。正文:weflow-cli skill show <id>`))
6192
+ })
6193
+
6194
+ skillCmd
6195
+ .command('show')
6196
+ .argument('<id>', '技能 id')
6197
+ .description('打印一个技能的 SKILL.md 正文')
6198
+ .option('--json', 'JSON 输出')
6199
+ .action((id, opts) => {
6200
+ const body = readSkillBody(id)
6201
+ if (!body.ok) {
6202
+ if (opts.json) {
6203
+ console.log(JSON.stringify({ success: false, code: 'SKILL_NOT_READABLE', error: body.text }))
6204
+ process.exit(1)
6205
+ }
6206
+ console.log(chalk.red(body.text))
6207
+ return
6208
+ }
6209
+ if (opts.json) {
6210
+ const scan = scanSkills()
6211
+ const info = scan.skills.find(s => s.id === id)
6212
+ console.log(JSON.stringify({
6213
+ success: true,
6214
+ id,
6215
+ name: info?.name ?? id,
6216
+ version: info?.version ?? '',
6217
+ truncated: !!body.truncated,
6218
+ body: body.text,
6219
+ }))
6220
+ return
6221
+ }
6222
+ console.log(body.text)
6223
+ })
6224
+
6225
+ skillCmd
6226
+ .command('check')
6227
+ .description('体检:不可读的 SKILL.md、跨目录同名、非规范 id、被禁用的技能')
6228
+ .option('--json', 'JSON 输出')
6229
+ .action((opts) => {
6230
+ const scan = scanSkills()
6231
+ const disabled = disabledIds()
6232
+ const disabledRows = scan.skills.filter(s => skillState(s, disabled) === 'disabled').map(s => s.id)
6233
+ const warned = scan.skills.filter(s => s.notes.length).map(s => ({ id: s.id, notes: s.notes }))
6234
+ const payload = {
6235
+ success: true,
6236
+ roots: skillRoots(),
6237
+ missingRoots: scan.missingRoots,
6238
+ total: scan.skills.length,
6239
+ unreadable: scan.unreadable,
6240
+ conflicts: scan.conflicts,
6241
+ warned,
6242
+ disabled: disabledRows,
6243
+ }
6244
+ if (opts.json) {
6245
+ console.log(JSON.stringify(payload))
6246
+ // 不可读 = 真出事了(有文件却读不出来),体检失败;警告与冲突只提示,不算失败
6247
+ if (scan.unreadable.length) process.exit(1)
6248
+ return
6249
+ }
6250
+ console.log(`技能目录:${skillRoots().join('、')}`)
6251
+ for (const dir of scan.missingRoots) console.log(chalk.gray(` 不存在:${dir}`))
6252
+ console.log(`扫描到 ${scan.skills.length} 个技能`)
6253
+ if (scan.unreadable.length) {
6254
+ console.log(chalk.red(`\n不可读 ${scan.unreadable.length} 个:`))
6255
+ for (const u of scan.unreadable) console.log(chalk.red(` ✗ ${u.file}\n ${u.reason}`))
6256
+ }
6257
+ if (scan.conflicts.length) {
6258
+ console.log(chalk.yellow(`\n跨目录同名 ${scan.conflicts.length} 个(靠前的目录胜出,不会覆盖):`))
6259
+ for (const c of scan.conflicts) console.log(chalk.yellow(` ! ${c.id}\n 用:${c.winner}\n 忽略:${c.loser}`))
6260
+ }
6261
+ if (warned.length) {
6262
+ console.log(chalk.yellow(`\n有提醒的 ${warned.length} 个:`))
6263
+ for (const w of warned) for (const n of w.notes) console.log(chalk.yellow(` · ${w.id}:${n}`))
6264
+ }
6265
+ if (disabledRows.length) console.log(chalk.gray(`\n已禁用:${disabledRows.join('、')}`))
6266
+ if (!scan.unreadable.length && !scan.conflicts.length) console.log(chalk.green('\n没有不可读或撞名的技能'))
6267
+ })
6268
+
6269
+ // ==================== scene (会话场景) ====================
6270
+ const sceneCmd = program
6271
+ .command('scene')
6272
+ .description('会话场景:按会话生效的提示词预设(绑定 → 关键词 → 上次用过的)')
6273
+
6274
+ /** 写场景是**本机文件写**,不是 python mutation:同样两段式,措辞照 todos 那条 */
6275
+ async function confirmSceneWrite(
6276
+ opts: { dryRun?: boolean; yes?: boolean; json?: boolean },
6277
+ preview: Record<string, unknown>,
6278
+ message: string,
6279
+ apply: () => { ok: boolean; reason?: string },
6280
+ ): Promise<void> {
6281
+ if (opts.dryRun) {
6282
+ if (opts.json) console.log(JSON.stringify({ success: true, dryRun: true, ...preview }))
6283
+ else console.log(chalk.cyan('预览:') + message)
6284
+ return
6285
+ }
6286
+ if (!opts.yes) {
6287
+ if (opts.json) {
6288
+ console.log(JSON.stringify({
6289
+ success: false,
6290
+ code: 'CONFIRMATION_REQUIRED',
6291
+ error: '先使用 --dry-run --json 预览,再由用户确认后使用 --yes --json 执行',
6292
+ }))
6293
+ process.exit(1)
6294
+ }
6295
+ const { confirmed } = await inquirer.prompt([{ type: 'confirm', name: 'confirmed', message, default: false }])
6296
+ if (!confirmed) {
6297
+ console.log(chalk.gray('已取消'))
6298
+ return
6299
+ }
6300
+ }
6301
+ const result = apply()
6302
+ if (result.ok) assistantScenes.save()
6303
+ const saved = result.ok && !assistantScenes.lastSaveError
6304
+ if (opts.json) {
6305
+ if (!result.ok) {
6306
+ console.log(JSON.stringify({ success: false, code: 'SCENE_OPERATION_FAILED', error: result.reason }))
6307
+ process.exit(1)
6308
+ }
6309
+ // 写失败要说出来:`save()` 不抛异常,代价是必须有地方把它讲出来
6310
+ console.log(JSON.stringify({
6311
+ success: saved,
6312
+ ...(saved ? {} : { code: 'SCENE_SAVE_FAILED', error: assistantScenes.lastSaveError }),
6313
+ ...preview,
6314
+ }))
6315
+ if (!saved) process.exit(1)
6316
+ return
6317
+ }
6318
+ if (!result.ok) {
6319
+ console.log(chalk.red(`✗ ${result.reason}`))
6320
+ process.exit(1)
6321
+ }
6322
+ if (!saved) console.log(chalk.red(`⚠ 已改动内存,但落盘失败:${assistantScenes.lastSaveError}`))
6323
+ else console.log(chalk.green('✓ 完成'))
6324
+ }
6325
+
6326
+ sceneCmd
6327
+ .command('list')
6328
+ .description('列出所有场景')
6329
+ .option('--json', 'JSON 输出')
6330
+ .action((opts) => {
6331
+ const scenes = assistantScenes.list()
6332
+ if (opts.json) {
6333
+ console.log(JSON.stringify({ success: true, total: scenes.length, scenes }))
6334
+ return
6335
+ }
6336
+ if (!scenes.length) {
6337
+ console.log(chalk.gray('还没有场景。加一个:'))
6338
+ console.log(chalk.gray(' weflow-cli scene add --id 日报 --keywords 日报,推文 --instruction "按主题分组" --dry-run'))
6339
+ return
6340
+ }
6341
+ for (const s of scenes) {
6342
+ console.log(`${s.enabled ? chalk.cyan(s.id) : chalk.gray(s.id + ' [已停用]')} ${s.name}`)
6343
+ if (s.keywords.length) console.log(chalk.gray(` 关键词:${s.keywords.join('、')}`))
6344
+ if (s.instruction) console.log(chalk.gray(` ${s.instruction.split('\n')[0].slice(0, 80)}`))
6345
+ }
6346
+ })
6347
+
6348
+ sceneCmd
6349
+ .command('show')
6350
+ .argument('<id>', '场景 id')
6351
+ .description('打印一个场景的全部字段')
6352
+ .option('--json', 'JSON 输出')
6353
+ .action((id, opts) => {
6354
+ const scene = assistantScenes.get(id)
6355
+ if (!scene) {
6356
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
6357
+ else console.log(chalk.red(`没有场景「${id}」`))
6358
+ process.exit(1)
6359
+ }
6360
+ if (opts.json) {
6361
+ console.log(JSON.stringify({ success: true, scene }))
6362
+ return
6363
+ }
6364
+ console.log(`id ${scene.id}`)
6365
+ console.log(`名称 ${scene.name}`)
6366
+ console.log(`状态 ${scene.enabled ? '启用' : '已停用'}`)
6367
+ console.log(`关键词 ${scene.keywords.join('、') || '(无)'}`)
6368
+ console.log(`所需技能 ${scene.skills.join('、') || '(无)'}`)
6369
+ console.log(`附加指令 ${scene.instruction || '(无)'}`)
6370
+ if (scene.outputSpec) console.log(`输出规范 ${scene.outputSpec}`)
6371
+ })
6372
+
6373
+ sceneCmd
6374
+ .command('add')
6375
+ .description('新增一个场景')
6376
+ .requiredOption('--id <id>', '场景 id(字母数字开头,可用 . _ -)')
6377
+ .option('--name <name>', '显示名(默认用 id)')
6378
+ .option('--keywords <list>', '关键词,逗号分隔')
6379
+ .option('--instruction <text>', '附加指令(长文本用 --from-file)')
6380
+ .option('--from-file <path>', '从文件读附加指令(多行中文走这条)')
6381
+ .option('--output-spec <text>', '输出规范')
6382
+ .option('--skills <list>', '所需技能 id,逗号分隔')
6383
+ .option('--dry-run', '仅预览,不写入')
6384
+ .option('--yes', '确认写入')
6385
+ .option('--json', 'JSON 输出')
6386
+ .action(async (opts) => {
6387
+ const id = String(opts.id || '').trim()
6388
+ const idError = validateSceneId(id)
6389
+ if (idError) {
6390
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'INVALID_SCENE_ID', error: idError }))
6391
+ else console.log(chalk.red(idError))
6392
+ process.exit(1)
6393
+ }
6394
+ let instruction = String(opts.instruction || '')
6395
+ if (opts.fromFile) {
6396
+ const path = String(opts.fromFile)
6397
+ if (!existsSync(path)) {
6398
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'FILE_NOT_FOUND', error: `读不到 ${path}` }))
6399
+ else console.log(chalk.red(`读不到 ${path}`))
6400
+ process.exit(1)
6401
+ }
6402
+ instruction = readFileSync(path, 'utf8')
6403
+ }
6404
+ const splitList = (v: unknown): string[] => String(v || '').split(/[,;]/).map(s => s.trim()).filter(Boolean)
6405
+ const scene: Scene = {
6406
+ id,
6407
+ name: String(opts.name || '').trim() || id,
6408
+ keywords: splitList(opts.keywords),
6409
+ instruction,
6410
+ outputSpec: String(opts.outputSpec || ''),
6411
+ skills: splitList(opts.skills),
6412
+ enabled: true,
6413
+ }
6414
+ await confirmSceneWrite(opts, { action: 'scene.add', scene: { ...scene, instruction: `(${instruction.length} 字)` } },
6415
+ `确认新增场景「${scene.name}」?`, () => assistantScenes.add(scene))
6416
+ })
6417
+
6418
+ sceneCmd
6419
+ .command('remove')
6420
+ .argument('<id>', '场景 id')
6421
+ .description('删除一个场景(连同指向它的绑定)')
6422
+ .option('--dry-run', '仅预览,不删除')
6423
+ .option('--yes', '确认删除')
6424
+ .option('--json', 'JSON 输出')
6425
+ .action(async (id, opts) => {
6426
+ const scene = assistantScenes.get(id)
6427
+ if (!scene) {
6428
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
6429
+ else console.log(chalk.red(`没有场景「${id}」`))
6430
+ process.exit(1)
6431
+ }
6432
+ await confirmSceneWrite(opts, { action: 'scene.remove', id }, `确认删除场景「${scene.name}」?`,
6433
+ () => { assistantScenes.remove(id); return { ok: true } })
6434
+ })
6435
+
6436
+ const toggleScene = (on: boolean) => async (id: string, opts: { dryRun?: boolean; yes?: boolean; json?: boolean }) => {
6437
+ const scene = assistantScenes.get(id)
6438
+ if (!scene) {
6439
+ if (opts.json) console.log(JSON.stringify({ success: false, code: 'SCENE_NOT_FOUND', error: `没有场景「${id}」` }))
6440
+ else console.log(chalk.red(`没有场景「${id}」`))
6441
+ process.exit(1)
6442
+ }
6443
+ await confirmSceneWrite(opts, { action: on ? 'scene.enable' : 'scene.disable', id },
6444
+ `确认${on ? '启用' : '停用'}场景「${scene.name}」?`,
6445
+ () => ({ ok: assistantScenes.setEnabled(id, on) }))
6446
+ }
6447
+
6448
+ sceneCmd.command('enable')
6449
+ .argument('<id>', '场景 id')
6450
+ .description('启用一个场景')
6451
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6452
+ .action(toggleScene(true))
6453
+
6454
+ sceneCmd.command('disable')
6455
+ .argument('<id>', '场景 id')
6456
+ .description('停用一个场景(它不再参与匹配)')
6457
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6458
+ .action(toggleScene(false))
6459
+
6460
+ sceneCmd
6461
+ .command('bind')
6462
+ .argument('<conversation>', '会话 id(微信里就是 conversationId;本机面板用它的记忆桶)')
6463
+ .requiredOption('--scene <id>', '要绑定的场景 id')
6464
+ .description('把某个场景固定绑到一个会话')
6465
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6466
+ .action(async (conversation, opts) => {
6467
+ const id = String(opts.scene || '').trim()
6468
+ await confirmSceneWrite(opts, { action: 'scene.bind', conversation, scene: id },
6469
+ `确认把场景「${id}」绑到会话 ${conversation}?`,
6470
+ () => assistantScenes.bind(conversation, id))
6471
+ })
6472
+
6473
+ sceneCmd
6474
+ .command('unbind')
6475
+ .argument('<conversation>', '会话 id')
6476
+ .description('解绑:这个会话回到按关键词自动挑')
6477
+ .option('--dry-run', '仅预览').option('--yes', '确认').option('--json', 'JSON 输出')
6478
+ .action(async (conversation, opts) => {
6479
+ await confirmSceneWrite(opts, { action: 'scene.unbind', conversation },
6480
+ `确认解绑会话 ${conversation}?`,
6481
+ () => assistantScenes.bind(conversation, null))
6482
+ })
6483
+
5962
6484
  // ==================== assistant (第二大脑持久化 Agent) ====================
5963
6485
  const assistantCmd = program
5964
6486
  .command('assistant')
@@ -6394,6 +6916,51 @@ program
6394
6916
  }
6395
6917
  })
6396
6918
 
6919
+ // ==================== bonds ====================
6920
+ program
6921
+ .command('bonds')
6922
+ .description('关系温度:谁在冷却、谁在变热、谁只有微信这一条线(只读本地库,不联网、不调模型)')
6923
+ .option('--days <number>', '看最近多少天', '365')
6924
+ .option('--limit <number>', '最多扫几个会话', '400')
6925
+ .option('--top <number>', '每组列几条', '12')
6926
+ .option('--skip <name>', '排除某个名字或 id(可重复)', (value: string, acc: string[]) => {
6927
+ acc.push(value)
6928
+ return acc
6929
+ }, [] as string[])
6930
+ .option('--json', '输出 JSON 格式')
6931
+ .action(async (opts) => {
6932
+ const { execFile } = await import('child_process')
6933
+ const { promisify } = await import('util')
6934
+ const execFileAsync = promisify(execFile)
6935
+ const script = join(resolvePackageRoot(), 'scripts', 'bonds.py')
6936
+ const days = parseCliInteger(opts.days, 'days', 1, 3650, opts.json)
6937
+ const limit = parseCliInteger(opts.limit, 'limit', 1, 5000, opts.json)
6938
+ const top = parseCliInteger(opts.top, 'top', 1, 200, opts.json)
6939
+
6940
+ try {
6941
+ const args = [script, '--days', String(days), '--limit', String(limit), '--top', String(top)]
6942
+ for (const name of (opts.skip as string[]) || []) args.push('--skip', name)
6943
+ if (opts.json) args.push('--json')
6944
+ const { stdout } = await execFileAsync(getPythonCommand(), args, {
6945
+ timeout: 300_000,
6946
+ maxBuffer: 10 * 1024 * 1024,
6947
+ env: pythonProcessEnv(),
6948
+ })
6949
+ console.log(stdout)
6950
+ } catch (e: any) {
6951
+ if (opts.json) {
6952
+ console.log(JSON.stringify({
6953
+ success: false,
6954
+ code: 'BONDS_FAILED',
6955
+ error: '关系温度不可用,请运行 check --json 检查配置和依赖',
6956
+ }))
6957
+ process.exit(1)
6958
+ }
6959
+ console.error(chalk.red(`\n${safeSubprocessError(e, '统计失败')}`))
6960
+ process.exit(1)
6961
+ }
6962
+ })
6963
+
6397
6964
  // ==================== daily-server ====================
6398
6965
  program
6399
6966
  .command('daily-server')
@@ -6469,6 +7036,7 @@ program
6469
7036
  }
6470
7037
 
6471
7038
  const child = spawn(getPythonCommand(), [favServer, '--date', date, '--port', String(port)], {
7039
+ windowsHide: true,
6472
7040
  stdio: 'inherit',
6473
7041
  env: pythonProcessEnv(),
6474
7042
  })
@@ -6571,12 +7139,12 @@ program
6571
7139
  const optionalDependencies = ['scrapling']
6572
7140
  let pythonVersion = ''
6573
7141
  try {
6574
- pythonVersion = execFileSync(getPythonCommand(), ['--version'], { encoding: 'utf8', timeout: 5000 }).trim()
7142
+ pythonVersion = execFileSync(getPythonCommand(), ['--version'], { windowsHide: true, encoding: 'utf8', timeout: 5000 }).trim()
6575
7143
  } catch {}
6576
7144
  const dependencyStatus = (name: string): boolean => {
6577
7145
  if (!pythonVersion) return false
6578
7146
  try {
6579
- execFileSync(getPythonCommand(), ['-c', `import ${name}`], { stdio: 'ignore', timeout: 5000 })
7147
+ execFileSync(getPythonCommand(), ['-c', `import ${name}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
6580
7148
  return true
6581
7149
  } catch {
6582
7150
  return false
@@ -6632,7 +7200,7 @@ program
6632
7200
  const pythonCommand = getPythonCommand()
6633
7201
  let pythonOk = false
6634
7202
  try {
6635
- const pyVer = execFileSync(pythonCommand, ['--version'], { encoding: 'utf-8', timeout: 5000 }).trim()
7203
+ const pyVer = execFileSync(pythonCommand, ['--version'], { windowsHide: true, encoding: 'utf-8', timeout: 5000 }).trim()
6636
7204
  console.log(chalk.white('Python: '), chalk.green(pyVer))
6637
7205
  pythonOk = true
6638
7206
  } catch {
@@ -6646,7 +7214,7 @@ program
6646
7214
  let allOk = true
6647
7215
  for (const dep of deps) {
6648
7216
  try {
6649
- execFileSync(pythonCommand, ['-c', `import ${dep}`], { stdio: 'ignore', timeout: 5000 })
7217
+ execFileSync(pythonCommand, ['-c', `import ${dep}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
6650
7218
  console.log(` ${dep.padEnd(20)} ${chalk.green('✓')}`)
6651
7219
  } catch {
6652
7220
  console.log(` ${dep.padEnd(20)} ${chalk.red('✗ 缺失')}`)
@@ -6667,7 +7235,7 @@ program
6667
7235
  console.log(chalk.white('\n可选依赖(提升抓取成功率):'))
6668
7236
  for (const dep of optDeps) {
6669
7237
  try {
6670
- execFileSync(pythonCommand, ['-c', `import ${dep}`], { stdio: 'ignore', timeout: 5000 })
7238
+ execFileSync(pythonCommand, ['-c', `import ${dep}`], { windowsHide: true, stdio: 'ignore', timeout: 5000 })
6671
7239
  console.log(` ${dep.padEnd(20)} ${chalk.green('✓')}`)
6672
7240
  } catch {
6673
7241
  console.log(` ${dep.padEnd(20)} ${chalk.gray('○ (pip install scrapling)')}`)
@@ -6924,6 +7492,7 @@ async function showInteractiveMenu() {
6924
7492
  const pipeline = join(resolvePackageRoot(), 'scripts', 'pipeline.py')
6925
7493
  console.log(chalk.cyan(`\n📰 正在生成 ${dateStr} 公众号日报...\n`))
6926
7494
  const child = spawn(getPythonCommand(), [pipeline, '--date', dateStr, '--interest', 'AI', '--skip-wiki'], {
7495
+ windowsHide: true,
6927
7496
  stdio: 'inherit',
6928
7497
  env: pythonProcessEnv(apiKey),
6929
7498
  })