@zifeng1023/dsh-bot 0.3.0 → 0.3.2

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/README.md CHANGED
@@ -75,6 +75,17 @@ node dev/gen-tools-doc.mjs # 重新生成工具清单文档
75
75
 
76
76
  改动必须过 `verify:all`;工具数量与 HTTP 路由数量有注册断言(删了/漏了会红)。
77
77
 
78
+ ## 模型渠道建议
79
+
80
+ | 渠道 | 适配状态 | 说明 |
81
+ |---|---|---|
82
+ | **deepseek-official / deepseek-account** | ✅ 推荐 | 验证最充分:文本协议 + 双轮回喂 + 流稳定性都打磨过 |
83
+ | deepseek-web | ✅ 可用 | 免费网页渠道 |
84
+ | 其他渠道(our-free-model / zcode / qoder / trae…) | ⚠️ 逐步优化 | 可能出现空回复或流中断;每个版本公告会注明本版优化了哪个渠道 |
85
+
86
+ > **遇到「模型返回了空内容」?** 九成是渠道兼容性问题——先换 DeepSeek 系渠道试试。
87
+ > 渠道兼容性矩阵(含逐渠道验证结果)见 [docs/ROADMAP-v0.3.md](./docs/ROADMAP-v0.3.md) v0.5.0 节。
88
+
78
89
  ## 诚实限制清单
79
90
 
80
91
  - **演习本身计费**:dry-run 拦截的是工具执行,模型调用是真实的
@@ -95,3 +106,4 @@ node dev/gen-tools-doc.mjs # 重新生成工具清单文档
95
106
  ## License
96
107
 
97
108
  MIT
109
+
Binary file
Binary file
Binary file
package/dsh-plugin.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "manifestVersion": "0.15",
4
4
  "id": "dsh-bot.core",
5
5
  "name": "dsh-bot",
6
- "version": "0.2.0",
6
+ "version": "0.3.2",
7
7
  "license": "MIT",
8
8
  "facets": {
9
9
  "host": {
@@ -122,3 +122,6 @@
122
122
  },
123
123
  "subscriptions": []
124
124
  }
125
+
126
+
127
+
package/lib/client.js CHANGED
@@ -485,6 +485,17 @@ report('bundle-executing', 'v2 design-system');
485
485
  // 插件
486
486
  // ============================================================
487
487
 
488
+ // ============================================================
489
+ // 加载哨兵:文件一旦被宿主执行就立即上报(factory 之前)。
490
+ // 用于区分「文件没被加载」vs「加载后抛错」两种故障。
491
+ // ============================================================
492
+ try {
493
+ fetch('/_dsh-bot/client-status', {
494
+ method: 'POST',
495
+ headers: { 'content-type': 'application/json' },
496
+ body: JSON.stringify({ status: 'sentinel', detail: 'bundle file evaluated', at: new Date().toISOString() }),
497
+ }).catch(function () {});
498
+ } catch (e) {}
488
499
  window.__ModuleLoader__.load({
489
500
  id: 'dsh-bot',
490
501
  factory: (require) => {
@@ -891,6 +902,21 @@ window.__ModuleLoader__.load({
891
902
  ? `provider「${provider || '未选'}」没有报告可用模型,请手填 model。`
892
903
  : '下拉里是这个环境真实可用的选项。',
893
904
  ),
905
+ // ⭐ 渠道适配提示(v0.3.1):本插件的工具循环协议对 DeepSeek
906
+ // 系适配器打磨最充分;其他渠道可能存在空内容/流中断等
907
+ // 兼容性问题(详见 docs 渠道能力表,v0.5.0 起系统性支持)。
908
+ h(
909
+ 'div',
910
+ {
911
+ style: {
912
+ fontSize: 10, color: WARN, marginTop: 5, lineHeight: 1.7,
913
+ padding: '5px 8px', borderRadius: R_SM, background: BG_L3,
914
+ },
915
+ },
916
+ '💡 建议:优先选 deepseek-official / deepseek-account 渠道——',
917
+ h('br'),
918
+ '本插件对 DeepSeek 系模型适配与验证最充分,其他渠道(如 our-free-model / zcode 等)可能出现空回复或流中断,正在逐步优化中(每版公告会注明)。',
919
+ ),
894
920
  )
895
921
  : null,
896
922
 
@@ -1289,14 +1315,29 @@ window.__ModuleLoader__.load({
1289
1315
  );
1290
1316
  const rj = await r.json();
1291
1317
  if (!rj?.ok) return [];
1292
- return (rj.value?.runs ?? []).map((run) => ({ ...run, botName: b.name, botId: b.id }));
1318
+ return {
1319
+ runs: (rj.value?.runs ?? []).map((run) => ({ ...run, botName: b.name, botId: b.id })),
1320
+ health: rj.value?.health ?? null,
1321
+ botName: b.name,
1322
+ };
1293
1323
  } catch {
1294
1324
  return [];
1295
1325
  }
1296
1326
  }),
1297
1327
  );
1298
- const all = results.flat().sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));
1299
- setData({ bots, runs: all.slice(0, 30) });
1328
+ const all = results
1329
+ .flatMap((r) => r.runs)
1330
+ .sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));
1331
+ const healths = results.filter((r) => r.health);
1332
+ setData({
1333
+ bots,
1334
+ runs: all.slice(0, 30),
1335
+ healths,
1336
+ avgSuccessRate:
1337
+ healths.length > 0
1338
+ ? healths.reduce((s, r) => s + (r.health.successRate ?? 0), 0) / healths.length
1339
+ : null,
1340
+ });
1300
1341
  setErr('');
1301
1342
  } catch (e) {
1302
1343
  setErr(String(e?.message ?? e));
@@ -1427,6 +1468,20 @@ window.__ModuleLoader__.load({
1427
1468
  modeBtn('compact', '滚动'),
1428
1469
  ),
1429
1470
  h('div', { style: { flex: 1 } }),
1471
+ (() => {
1472
+ const rate = data.avgSuccessRate;
1473
+ if (rate === null || rate === undefined) return null;
1474
+ const pct = Math.round(rate * 100);
1475
+ const tone = pct >= 90 ? OK : pct >= 70 ? WARN : ERR;
1476
+ return h(
1477
+ 'span',
1478
+ {
1479
+ title: '近 10 轮成功率(各 Bot 平均)——低于 70% 建议换模型或检查数据源',
1480
+ style: { fontSize: 10, color: tone, fontWeight: 600, marginRight: 6 },
1481
+ },
1482
+ `健康 ${pct}%`,
1483
+ );
1484
+ })(),
1430
1485
  h('div', { style: { fontSize: 10, color: LABEL_3 } }, `共 ${data.runs.length} 条`),
1431
1486
  ),
1432
1487
  // ---- 列表主体 ----
@@ -1627,23 +1682,81 @@ window.__ModuleLoader__.load({
1627
1682
  ),
1628
1683
  )
1629
1684
  : null,
1630
- // ---- 输出预览 ----
1631
- h(
1632
- 'div',
1633
- null,
1634
- h('div', { style: { fontSize: 11, fontWeight: 600, color: LABEL_2, marginBottom: 4 } }, '输出预览(前 200 字)'),
1635
- h(
1685
+ // ---- 运行输出(全文可滚动;markdown 以等宽渲染;文件产物给路径提示) ----
1686
+ (() => {
1687
+ const out = run.outputPreview || '';
1688
+ const chars = out.length;
1689
+ // 文件产物识别:输出中引用的本地文件路径(Windows 盘符 / ~/.dsh 常见落点)
1690
+ const FILE_EXT_RE = new RegExp("\\.(md|txt|json|ya?ml|log|csv|html?|tgz|zip|png|jpe?g)$", "i");
1691
+ const FILE_PATH_RE = new RegExp("([A-Za-z]:\\\\[^\\s\"]+\\.[a-z0-9]{2,4})|(~\\/\\.dsh\\/[^\\s\"]+\\.[a-z0-9]{2,4})", "gi");
1692
+ const pathMatches = [];
1693
+ for (const p of out.match(FILE_PATH_RE) || []) {
1694
+ if (FILE_EXT_RE.test(p) && !pathMatches.includes(p)) pathMatches.push(p);
1695
+ }
1696
+ const truncated = out.includes('[已截断') || chars >= 50_000;
1697
+ return h(
1636
1698
  'div',
1637
- {
1638
- style: {
1639
- fontSize: 11, color: LABEL_1, padding: 8, borderRadius: R_SM,
1640
- background: BG_L3, whiteSpace: 'pre-wrap', wordBreak: 'break-word',
1641
- maxHeight: 160, overflow: 'auto',
1699
+ null,
1700
+ h(
1701
+ 'div',
1702
+ { style: { display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 4 } },
1703
+ h('div', { style: { fontSize: 11, fontWeight: 600, color: LABEL_2 } }, '运行输出'),
1704
+ h(
1705
+ 'div',
1706
+ { style: { fontSize: 10, color: LABEL_3, flex: 1 } },
1707
+ chars ? `${chars.toLocaleString()} 字${truncated ? '(超长已截断,完整全文见 runs 归档 JSON)' : ''}` : '',
1708
+ ),
1709
+ chars
1710
+ ? h(
1711
+ 'button',
1712
+ {
1713
+ type: 'button',
1714
+ onClick: () => {
1715
+ try { navigator.clipboard.writeText(out); } catch {}
1716
+ },
1717
+ style: {
1718
+ border: 'none', background: 'transparent', cursor: 'pointer',
1719
+ fontSize: 10, color: BRAND, textDecoration: 'underline',
1720
+ },
1721
+ },
1722
+ '复制全文',
1723
+ )
1724
+ : null,
1725
+ ),
1726
+ // 文件产物提示:报告落盘/导出的路径让用户找得到
1727
+ pathMatches.length
1728
+ ? h(
1729
+ 'div',
1730
+ {
1731
+ style: {
1732
+ fontSize: 10, color: BRAND, padding: '5px 8px', marginBottom: 4,
1733
+ borderRadius: R_SM, background: BG_L3, lineHeight: 1.7,
1734
+ },
1735
+ },
1736
+ '📎 本轮提到的文件产物:',
1737
+ ...pathMatches.slice(0, 5).map((p, i) =>
1738
+ h(
1739
+ 'div',
1740
+ { key: i, style: { fontFamily: 'ui-monospace, monospace', wordBreak: 'break-all' } },
1741
+ p,
1742
+ ),
1743
+ ),
1744
+ )
1745
+ : null,
1746
+ h(
1747
+ 'div',
1748
+ {
1749
+ style: {
1750
+ fontSize: 11, color: LABEL_1, padding: 8, borderRadius: R_SM,
1751
+ background: BG_L3, whiteSpace: 'pre-wrap', wordBreak: 'break-word',
1752
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
1753
+ maxHeight: 260, overflow: 'auto', lineHeight: 1.6,
1754
+ },
1642
1755
  },
1643
- },
1644
- run.outputPreview || '(无)',
1645
- ),
1646
- ),
1756
+ out || '(无文本输出——若本轮产出为文件,见上方路径提示或运行归档)',
1757
+ ),
1758
+ );
1759
+ })(),
1647
1760
  ),
1648
1761
  );
1649
1762
  }
@@ -1745,7 +1858,7 @@ window.__ModuleLoader__.load({
1745
1858
  }),
1746
1859
  h(ToggleRow, {
1747
1860
  label: '仅异常时打扰',
1748
- hint: '开启后只有失败/部分成功/需要拍板才响;关闭则每次运行都通知',
1861
+ hint: '开启后自动轮次只有失败/部分成功才响;手动点「执行」的成功结果始终会通知',
1749
1862
  value: s.notifyOnlyOnDecision !== false,
1750
1863
  onChange: (v) => patch('notifyOnlyOnDecision', v),
1751
1864
  }),
@@ -3567,6 +3680,19 @@ window.__ModuleLoader__.load({
3567
3680
  detail.routines?.length
3568
3681
  ? renderRoutines(detail.routines)
3569
3682
  : null,
3683
+ !(detail.semantic?.facts?.length) && !(detail.routines?.length)
3684
+ ? h(
3685
+ 'div',
3686
+ {
3687
+ style: {
3688
+ fontSize: 10, color: LABEL_3, lineHeight: 1.8,
3689
+ padding: '6px 8px', borderRadius: R_SM, background: BG_L3,
3690
+ marginBottom: 6,
3691
+ },
3692
+ },
3693
+ '还没有长期记忆。从下一次定时运行起,每轮报告的首行结论会自动蒸馏到这里(上限 50 条,去重)。',
3694
+ )
3695
+ : null,
3570
3696
  )
3571
3697
  : null,
3572
3698
 
@@ -3896,14 +4022,17 @@ window.__ModuleLoader__.load({
3896
4022
  };
3897
4023
 
3898
4024
  const fireNotification = (botName, run) => {
4025
+ const retried = Array.isArray(run.steps)
4026
+ ? run.steps.some((s) => s.name === 'retry')
4027
+ : false;
3899
4028
  const title =
3900
4029
  run.status === 'success'
3901
- ? `✅ ${botName}:运行完成`
4030
+ ? `✅ ${botName}:运行完成${retried ? '(已自动重试)' : ''}`
3902
4031
  : run.status === 'partial'
3903
4032
  ? `🟡 ${botName}:部分成功`
3904
4033
  : run.status === 'budget_exceeded'
3905
4034
  ? `🛑 ${botName}:预算熔断`
3906
- : `❌ ${botName}:运行失败`;
4035
+ : `❌ ${botName}:运行失败${retried ? '(重试后仍失败)' : '(下轮定时将自动重试)'}`;
3907
4036
  const cost = run.usage
3908
4037
  ? run.usage.costKind === 'free'
3909
4038
  ? '免费'
@@ -3911,7 +4040,8 @@ window.__ModuleLoader__.load({
3911
4040
  ? `¥${run.usage.costCny.toFixed(4)}`
3912
4041
  : '费用未知'
3913
4042
  : '—';
3914
- const body = `${new Date(run.startedAt).toLocaleTimeString('zh-CN')} · ${cost}` +
4043
+ // runId 前 8 位:用户报问题时可对齐具体轮次(v0.3.1 R2)
4044
+ const body = `${new Date(run.startedAt).toLocaleTimeString('zh-CN')} · ${cost} · #${String(run.id).slice(0, 8)}` +
3915
4045
  (run.error?.message ? ` · ${String(run.error.message).slice(0, 80)}` : '') +
3916
4046
  (run.outputPreview ? `\n${run.outputPreview.slice(0, 100)}` : '');
3917
4047
  try {
@@ -3960,10 +4090,10 @@ window.__ModuleLoader__.load({
3960
4090
  const attention =
3961
4091
  run.status !== 'success' ||
3962
4092
  (run.goalAssessment?.needsHuman === true);
3963
- if (settings.notifyOnlyOnDecision !== true && !attention) {
3964
- // 全部提醒模式:成功也响
3965
- fireNotification(b.name, run);
3966
- } else if (attention) {
4093
+ // v0.3.1 体验修正:手动触发(用户点了「执行」在等结果)→ 成功也响;
4094
+ // 只有自动轮(goal/schedule)才按「仅异常时打扰」静默成功。
4095
+ const manualRun = run.trigger === 'manual';
4096
+ if (settings.notifyOnlyOnDecision !== true || attention || manualRun) {
3967
4097
  fireNotification(b.name, run);
3968
4098
  }
3969
4099
  }
@@ -4008,10 +4138,15 @@ window.__ModuleLoader__.load({
4008
4138
 
4009
4139
  report('ok', 'v2 activated, slot=conversation.input.dock');
4010
4140
  } catch (e) {
4011
- report('error', String(e?.message ?? e));
4141
+ report('error', (e?.stack ?? String(e)).slice(0, 900));
4012
4142
  }
4013
4143
  }
4014
4144
 
4015
4145
  return { name: 'dsh-bot-client', inject, apply };
4016
4146
  },
4017
4147
  });
4148
+
4149
+
4150
+
4151
+
4152
+
package/lib/index.js CHANGED
@@ -918,6 +918,10 @@ function createLlmInvoker(ctx) {
918
918
  }]
919
919
  });
920
920
  let text = "";
921
+ /** R3b 流空闲计时器(try 外声明,catch 也要清) */
922
+ let idleTimer;
923
+ /** 流式工具调用累积器:key=chunk.index */
924
+ const streamingToolCalls = /* @__PURE__ */ new Map();
921
925
  let reasoning = "";
922
926
  let usage = void 0;
923
927
  const toolUses = [];
@@ -932,45 +936,116 @@ function createLlmInvoker(ctx) {
932
936
  reasoningEffort: input.reasoningEffort
933
937
  };
934
938
  if (input.maxTokens !== void 0) options.maxTokens = input.maxTokens;
939
+ else {
940
+ const hit = [
941
+ {
942
+ re: /deepseek-(?:v4|reasoner)|deepseek-flash/i,
943
+ max: 16384
944
+ },
945
+ {
946
+ re: /glm|zcode/i,
947
+ max: 16384
948
+ },
949
+ {
950
+ re: /kimi|moonshot/i,
951
+ max: 16384
952
+ },
953
+ {
954
+ re: /qwen|qwen3/i,
955
+ max: 16384
956
+ },
957
+ {
958
+ re: /o[1-9]|gpt-5|gpt-4\.|openai\//i,
959
+ max: 16384
960
+ },
961
+ {
962
+ re: /claude|opus|sonnet|haiku/i,
963
+ max: 16384
964
+ },
965
+ {
966
+ re: /free|openrouter/i,
967
+ max: 8192
968
+ }
969
+ ].find((t) => t.re.test(`${input.provider}/${input.model}`));
970
+ if (hit) options.maxTokens = hit.max;
971
+ }
935
972
  if (input.signal) options.signal = input.signal;
936
973
  if (input.tools?.length) options.tools = input.tools;
937
974
  try {
938
- for await (const chunk of llm.stream(options)) switch (chunk?.type) {
939
- case "text-delta":
940
- text += chunk.text ?? "";
941
- break;
942
- case "reasoning-delta":
943
- reasoning += chunk.text ?? "";
944
- break;
945
- case "usage":
946
- usage = chunk.usage;
947
- break;
948
- case "finish":
949
- stopReason = chunk.stopReason ?? chunk.finishReason ?? chunk.reason;
950
- break;
951
- case "block-end": {
952
- const block = chunk.block;
953
- if (block?.type === "text" && !text) text = block.text ?? "";
954
- if (block?.type === "reasoning" && !reasoning) reasoning = block.text ?? "";
955
- const tu = asToolUse(block);
956
- if (tu) toolUses.push(tu);
957
- break;
975
+ const IDLE_MS = 9e4;
976
+ const idleController = new AbortController();
977
+ const resetIdle = () => {
978
+ if (idleTimer) clearTimeout(idleTimer);
979
+ idleTimer = setTimeout(() => idleController.abort(/* @__PURE__ */ new Error("stream idle > 90s")), IDLE_MS);
980
+ };
981
+ resetIdle();
982
+ options.signal = options.signal ? AbortSignal.any([options.signal, idleController.signal]) : idleController.signal;
983
+ for await (const chunk of llm.stream(options)) {
984
+ resetIdle();
985
+ switch (chunk?.type) {
986
+ case "text-delta":
987
+ text += chunk.text ?? "";
988
+ break;
989
+ case "reasoning-delta":
990
+ reasoning += chunk.text ?? "";
991
+ break;
992
+ case "usage":
993
+ usage = chunk.usage;
994
+ break;
995
+ case "finish":
996
+ stopReason = chunk.stopReason ?? chunk.finishReason ?? chunk.reason;
997
+ break;
998
+ case "tool-call-delta": {
999
+ const idx = Number(chunk.index ?? 0);
1000
+ let partial = streamingToolCalls.get(idx);
1001
+ if (!partial) {
1002
+ partial = {
1003
+ id: void 0,
1004
+ name: void 0,
1005
+ args: ""
1006
+ };
1007
+ streamingToolCalls.set(idx, partial);
1008
+ }
1009
+ if (typeof chunk.id === "string") partial.id = chunk.id;
1010
+ if (typeof chunk.name === "string") partial.name = chunk.name;
1011
+ if (typeof chunk.argumentsDelta === "string") partial.args += chunk.argumentsDelta;
1012
+ break;
1013
+ }
1014
+ case "block-end": {
1015
+ const block = chunk.block;
1016
+ if (block?.type === "text" && !text) text = block.text ?? "";
1017
+ if (block?.type === "reasoning" && !reasoning) reasoning = block.text ?? "";
1018
+ const tu = asToolUse(block);
1019
+ if (tu) toolUses.push(tu);
1020
+ break;
1021
+ }
1022
+ case "error":
1023
+ case "adapter-failure":
1024
+ case "aborted":
1025
+ streamError = chunk;
1026
+ break;
1027
+ case "block-start":
1028
+ case "block-delta": break;
1029
+ default:
1030
+ if (chunk?.type) oddChunks.push(String(chunk.type));
1031
+ break;
958
1032
  }
959
- case "error":
960
- case "adapter-failure":
961
- case "aborted":
962
- streamError = chunk;
963
- break;
964
- case "block-start":
965
- case "block-delta": break;
966
- default:
967
- if (chunk?.type) oddChunks.push(String(chunk.type));
968
- break;
969
1033
  }
1034
+ if (idleTimer) clearTimeout(idleTimer);
970
1035
  } catch (e) {
1036
+ if (idleTimer) clearTimeout(idleTimer);
971
1037
  const detail = describeLlmError(e);
972
1038
  throw new Error(`模型调用失败(${input.provider}/${input.model}):${detail}`);
973
1039
  }
1040
+ if (streamingToolCalls.size > 0) for (const [, partial] of [...streamingToolCalls.entries()].sort((a, b) => a[0] - b[0])) {
1041
+ if (!partial.name) continue;
1042
+ const args = sanitizeToolArgs(partial.args ? safeJsonParse(partial.args) : {});
1043
+ if (!toolUses.some((t) => t.name === partial.name && JSON.stringify(t.input) === JSON.stringify(args))) toolUses.push({
1044
+ id: partial.id,
1045
+ name: partial.name,
1046
+ input: args
1047
+ });
1048
+ }
974
1049
  if (streamError && !text && toolUses.length === 0) {
975
1050
  const detail = describeLlmError(streamError.error ?? streamError);
976
1051
  throw new Error(`模型返回错误(${input.provider}/${input.model}):${detail}`);
@@ -1046,6 +1121,13 @@ function asToolUse(block) {
1046
1121
  * JSON round-trip 一次即可重建为宿主接受的普通对象;
1047
1122
  * 参数本来就是模型产出的 JSON,round-trip 无损。
1048
1123
  */
1124
+ function safeJsonParse(s) {
1125
+ try {
1126
+ return JSON.parse(s);
1127
+ } catch {
1128
+ return s;
1129
+ }
1130
+ }
1049
1131
  function sanitizeToolArgs(input) {
1050
1132
  try {
1051
1133
  return JSON.parse(JSON.stringify(input ?? {}));
@@ -4938,10 +5020,16 @@ var RoutineRunner = class {
4938
5020
  break;
4939
5021
  } catch (e) {
4940
5022
  lastError = e;
4941
- if (attempt < maxAttempts) {
4942
- if (backoffMs > 0) await sleep(backoffMs);
4943
- continue;
4944
- }
5023
+ if (new Set([
5024
+ "UNKNOWN_TOOL",
5025
+ "INVALID_ARGS",
5026
+ "UNSUPPORTED_STEP",
5027
+ "BOT_NOT_FOUND",
5028
+ "INVALID_ROUTINE",
5029
+ "ASSERT_FAILED"
5030
+ ]).has(e?.code) || attempt >= maxAttempts) break;
5031
+ if (backoffMs > 0) await sleep(backoffMs);
5032
+ continue;
4945
5033
  }
4946
5034
  }
4947
5035
  stepRecord.durationMs = Date.now() - t0;
@@ -5095,156 +5183,186 @@ var RoutineRunner = class {
5095
5183
  let finalText = "";
5096
5184
  let rounds = 0;
5097
5185
  let endedByLimit = false;
5186
+ let retried = false;
5187
+ let retrySignal = false;
5098
5188
  try {
5099
- let effectiveModel = {
5100
- provider: bot.model.provider,
5101
- model: bot.model.model,
5102
- reasoningEffort: bot.model.reasoningEffort
5103
- };
5104
- if (this.deps.resolveRunnableModel) try {
5105
- const resolved = await this.deps.resolveRunnableModel(bot);
5106
- effectiveModel = {
5107
- provider: resolved.provider,
5108
- model: resolved.model,
5109
- reasoningEffort: resolved.reasoningEffort
5189
+ for (let attempt = 0;; attempt++) {
5190
+ let effectiveModel = {
5191
+ provider: bot.model.provider,
5192
+ model: bot.model.model,
5193
+ reasoningEffort: bot.model.reasoningEffort
5110
5194
  };
5111
- if (resolved.fallbackUsed) stepRecord.args = { modelFallback: `Bot 绑定的 ${bot.model.provider}/${bot.model.model} 当前不可运行,已兜底为 ${resolved.provider}/${resolved.model}。${resolved.note ?? ""}` };
5112
- } catch {}
5113
- for (rounds = 0; rounds <= MAX_TOOL_ROUNDS; rounds++) {
5114
- const out = await this.deps.llm({
5115
- provider: effectiveModel.provider,
5116
- model: effectiveModel.model,
5117
- reasoningEffort: effectiveModel.reasoningEffort,
5118
- system,
5119
- prompt: task,
5120
- messages: convo,
5121
- signal
5122
- });
5123
- record.usage = addUsage(record.usage, out.usage);
5124
- const over = this.overBudget(bot, baseline, record.usage.costCny);
5125
- if (over) {
5126
- record.status = "budget_exceeded";
5127
- record.error = over;
5128
- break;
5129
- }
5130
- const rawText = out.text ?? "";
5131
- const native = out.toolUses ?? [];
5132
- let uses;
5133
- let cleanedText;
5134
- if (native.length > 0) {
5135
- uses = native.map((u) => ({
5136
- id: u.id,
5137
- name: u.name,
5138
- input: u.input
5139
- }));
5140
- cleanedText = rawText;
5141
- } else {
5142
- const parsed = parseToolCallMarkers(rawText);
5143
- uses = parsed.calls.map((c) => ({
5144
- name: c.name,
5145
- input: c.args
5146
- }));
5147
- cleanedText = parsed.cleaned;
5148
- }
5149
- if (uses.length === 0) {
5150
- finalText = cleanedText;
5151
- break;
5195
+ if (this.deps.resolveRunnableModel) try {
5196
+ const resolved = await this.deps.resolveRunnableModel(bot);
5197
+ effectiveModel = {
5198
+ provider: resolved.provider,
5199
+ model: resolved.model,
5200
+ reasoningEffort: resolved.reasoningEffort
5201
+ };
5202
+ if (resolved.fallbackUsed) stepRecord.args = { modelFallback: `Bot 绑定的 ${bot.model.provider}/${bot.model.model} 当前不可运行,已兜底为 ${resolved.provider}/${resolved.model}。${resolved.note ?? ""}` };
5203
+ } catch {}
5204
+ for (rounds = 0; rounds <= MAX_TOOL_ROUNDS; rounds++) {
5205
+ const out = await this.deps.llm({
5206
+ provider: effectiveModel.provider,
5207
+ model: effectiveModel.model,
5208
+ reasoningEffort: effectiveModel.reasoningEffort,
5209
+ system,
5210
+ prompt: task,
5211
+ messages: convo,
5212
+ signal
5213
+ });
5214
+ record.usage = addUsage(record.usage, out.usage);
5215
+ const over = this.overBudget(bot, baseline, record.usage.costCny);
5216
+ if (over) {
5217
+ record.status = "budget_exceeded";
5218
+ record.error = over;
5219
+ break;
5220
+ }
5221
+ const rawText = out.text ?? "";
5222
+ const native = out.toolUses ?? [];
5223
+ let uses;
5224
+ let cleanedText;
5225
+ if (native.length > 0) {
5226
+ uses = native.map((u) => ({
5227
+ id: u.id,
5228
+ name: u.name,
5229
+ input: u.input
5230
+ }));
5231
+ cleanedText = rawText;
5232
+ } else {
5233
+ const parsed = parseToolCallMarkers(rawText);
5234
+ uses = parsed.calls.map((c) => ({
5235
+ name: c.name,
5236
+ input: c.args
5237
+ }));
5238
+ cleanedText = parsed.cleaned;
5239
+ }
5240
+ if (uses.length === 0) {
5241
+ finalText = cleanedText;
5242
+ break;
5243
+ }
5244
+ if (rounds === MAX_TOOL_ROUNDS) {
5245
+ endedByLimit = true;
5246
+ break;
5247
+ }
5248
+ const assistantBlocks = [];
5249
+ const resultBlocks = [];
5250
+ for (const u of uses) {
5251
+ const id = u.id ?? this.deps.newId("tu");
5252
+ if (native.length > 0) assistantBlocks.push({
5253
+ type: "tool_use",
5254
+ id,
5255
+ name: u.name,
5256
+ input: u.input ?? {}
5257
+ });
5258
+ const sr = {
5259
+ index: record.steps.length,
5260
+ kind: "tool",
5261
+ name: u.name,
5262
+ args: u.input,
5263
+ durationMs: 0
5264
+ };
5265
+ const tTool = Date.now();
5266
+ const verdict = await this.dispatchToolUse(bot, u.name, u.input, flags, signal);
5267
+ sr.durationMs = Date.now() - tTool;
5268
+ if (verdict.blocked) sr.blocked = { reason: verdict.blocked };
5269
+ else if (verdict.error) sr.error = verdict.error;
5270
+ else sr.result = verdict.result;
5271
+ record.steps.push(sr);
5272
+ if (native.length > 0) resultBlocks.push({
5273
+ type: "tool_result",
5274
+ tool_use_id: id,
5275
+ content: verdict.contentForModel
5276
+ });
5277
+ else resultBlocks.push({
5278
+ type: "text",
5279
+ text: `[${u.name}] ${verdict.contentForModel}`
5280
+ });
5281
+ }
5282
+ if (native.length > 0) {
5283
+ if (rawText.trim()) assistantBlocks.unshift({
5284
+ type: "text",
5285
+ text: rawText
5286
+ });
5287
+ convo = [
5288
+ ...convo ?? [{
5289
+ role: "user",
5290
+ content: [{
5291
+ type: "text",
5292
+ text: task
5293
+ }]
5294
+ }],
5295
+ {
5296
+ role: "assistant",
5297
+ content: assistantBlocks
5298
+ },
5299
+ {
5300
+ role: "user",
5301
+ content: resultBlocks
5302
+ }
5303
+ ];
5304
+ } else convo = [{
5305
+ role: "user",
5306
+ content: [{
5307
+ type: "text",
5308
+ text: `${convo === void 0 ? task : (() => {
5309
+ const parts = [];
5310
+ for (const m of convo ?? []) {
5311
+ const blocks = Array.isArray(m.content) ? m.content : [];
5312
+ for (const b of blocks) if (b?.type === "text" && typeof b.text === "string") parts.push(b.text);
5313
+ }
5314
+ return parts.join("\n\n");
5315
+ })()}\n\n(系统)以下是上一轮你发起的工具调用的执行结果,请据此继续;如已拿到足够信息,直接输出面向用户的总结:\n\n` + resultBlocks.map((b) => b.text).join("\n\n")
5316
+ }]
5317
+ }];
5152
5318
  }
5153
- if (rounds === MAX_TOOL_ROUNDS) {
5154
- endedByLimit = true;
5155
- break;
5319
+ if (endedByLimit) {
5320
+ record.status = "failed";
5321
+ record.error = {
5322
+ code: "TOOL_LOOP_LIMIT",
5323
+ message: `连续 ${MAX_TOOL_ROUNDS} 轮工具调用仍未给出总结,已中止。可能是工具结果无法满足目标,或模型陷入循环调用。`
5324
+ };
5325
+ } else if (record.status === "success" && !finalText.trim()) {
5326
+ record.status = "failed";
5327
+ record.error = {
5328
+ code: "EMPTY_OUTPUT",
5329
+ message: "模型返回了空内容。常见原因:模型服务未就绪(看 ~/.dsh/bot/.plugin-loaded.json 的 llmReady 字段)、provider/model 配置不匹配,或本次调用被静默中断。"
5330
+ };
5156
5331
  }
5157
- const assistantBlocks = [];
5158
- const resultBlocks = [];
5159
- for (const u of uses) {
5160
- const id = u.id ?? this.deps.newId("tu");
5161
- if (native.length > 0) assistantBlocks.push({
5162
- type: "tool_use",
5163
- id,
5164
- name: u.name,
5165
- input: u.input ?? {}
5166
- });
5167
- const sr = {
5332
+ if (record.status === "failed" && record.error?.code === "EMPTY_OUTPUT" && !retried && !flags.dryRun) {
5333
+ retried = true;
5334
+ record.steps.push({
5168
5335
  index: record.steps.length,
5169
- kind: "tool",
5170
- name: u.name,
5171
- args: u.input,
5172
- durationMs: 0
5173
- };
5174
- const tTool = Date.now();
5175
- const verdict = await this.dispatchToolUse(bot, u.name, u.input, flags, signal);
5176
- sr.durationMs = Date.now() - tTool;
5177
- if (verdict.blocked) sr.blocked = { reason: verdict.blocked };
5178
- else if (verdict.error) sr.error = verdict.error;
5179
- else sr.result = verdict.result;
5180
- record.steps.push(sr);
5181
- if (native.length > 0) resultBlocks.push({
5182
- type: "tool_result",
5183
- tool_use_id: id,
5184
- content: verdict.contentForModel
5185
- });
5186
- else resultBlocks.push({
5187
- type: "text",
5188
- text: `[${u.name}] ${verdict.contentForModel}`
5336
+ kind: "llm",
5337
+ name: "retry",
5338
+ durationMs: 0,
5339
+ result: { output: "" },
5340
+ args: { note: "检测到空输出,自动重试一次(v0.3.1 R1)" }
5189
5341
  });
5342
+ record.error = void 0;
5343
+ record.status = "success";
5344
+ retrySignal = true;
5190
5345
  }
5191
- if (native.length > 0) {
5192
- if (rawText.trim()) assistantBlocks.unshift({
5193
- type: "text",
5194
- text: rawText
5195
- });
5196
- convo = [
5197
- ...convo ?? [{
5198
- role: "user",
5199
- content: [{
5200
- type: "text",
5201
- text: task
5202
- }]
5203
- }],
5204
- {
5205
- role: "assistant",
5206
- content: assistantBlocks
5207
- },
5208
- {
5209
- role: "user",
5210
- content: resultBlocks
5211
- }
5212
- ];
5213
- } else convo = [{
5214
- role: "user",
5215
- content: [{
5216
- type: "text",
5217
- text: `${convo === void 0 ? task : (() => {
5218
- const parts = [];
5219
- for (const m of convo ?? []) {
5220
- const blocks = Array.isArray(m.content) ? m.content : [];
5221
- for (const b of blocks) if (b?.type === "text" && typeof b.text === "string") parts.push(b.text);
5222
- }
5223
- return parts.join("\n\n");
5224
- })()}\n\n(系统)以下是上一轮你发起的工具调用的执行结果,请据此继续;如已拿到足够信息,直接输出面向用户的总结:\n\n` + resultBlocks.map((b) => b.text).join("\n\n")
5225
- }]
5226
- }];
5227
- }
5228
- if (endedByLimit) {
5229
- record.status = "failed";
5230
- record.error = {
5231
- code: "TOOL_LOOP_LIMIT",
5232
- message: `连续 ${MAX_TOOL_ROUNDS} 轮工具调用仍未给出总结,已中止。可能是工具结果无法满足目标,或模型陷入循环调用。`
5233
- };
5234
- } else if (record.status === "success" && !finalText.trim()) {
5235
- record.status = "failed";
5236
- record.error = {
5237
- code: "EMPTY_OUTPUT",
5238
- message: "模型返回了空内容。常见原因:模型服务未就绪(看 ~/.dsh/bot/.plugin-loaded.json 的 llmReady 字段)、provider/model 配置不匹配,或本次调用被静默中断。"
5346
+ stepRecord.result = { output: finalText };
5347
+ stepRecord.args = {
5348
+ prompt: task,
5349
+ toolRounds: rounds,
5350
+ toolSchemas: toolSchemas.length
5239
5351
  };
5352
+ if (record.error) stepRecord.error = record.error;
5353
+ if (retrySignal) {
5354
+ retrySignal = false;
5355
+ record.status = "success";
5356
+ record.error = void 0;
5357
+ finalText = "";
5358
+ rounds = 0;
5359
+ endedByLimit = false;
5360
+ convo = void 0;
5361
+ stepRecord.result = { output: "" };
5362
+ continue;
5363
+ }
5364
+ break;
5240
5365
  }
5241
- stepRecord.result = { output: finalText };
5242
- stepRecord.args = {
5243
- prompt: task,
5244
- toolRounds: rounds,
5245
- toolSchemas: toolSchemas.length
5246
- };
5247
- if (record.error) stepRecord.error = record.error;
5248
5366
  } catch (e) {
5249
5367
  record.status = e?.code === "BUDGET_EXCEEDED" ? "budget_exceeded" : "failed";
5250
5368
  record.error = {
@@ -5270,6 +5388,13 @@ var RoutineRunner = class {
5270
5388
  record.endedAt = this.deps.nowIso();
5271
5389
  await this.deps.service.saveRun(record);
5272
5390
  await this.recordMemory(botId, record, `执行任务「${task.slice(0, 60)}」`, "task");
5391
+ if (record.status === "success" && !record.dryRun && (record.trigger === "goal" || record.trigger === "schedule")) try {
5392
+ const out = record.steps.find((s) => s.kind === "llm")?.result?.output;
5393
+ if (typeof out === "string" && out.trim()) {
5394
+ const fact = (out.split("\n").map((l) => l.trim()).find((l) => l && !l.startsWith("#") && !l.startsWith("|") && !l.startsWith("```")) ?? "").slice(0, 120);
5395
+ if (fact) await this.deps.service.addFact(botId, `[${record.startedAt.slice(5, 16).replace("T", " ")}] ${fact}`);
5396
+ }
5397
+ } catch {}
5273
5398
  return record;
5274
5399
  }
5275
5400
  /**
@@ -6243,6 +6368,22 @@ function makeBotApiRoutes(service, runAction) {
6243
6368
  }
6244
6369
  const bot = await service.get(botId);
6245
6370
  const runs = await service.listRuns(botId, limit);
6371
+ const recent = runs.slice(0, 10);
6372
+ const ok = recent.filter((r) => r.status === "success").length;
6373
+ const failedRuns = recent.filter((r) => r.status === "failed");
6374
+ const costSum = recent.reduce((s, r) => s + (Number(r.usage?.costCny) || 0), 0);
6375
+ const retryCount = recent.filter((r) => (r.steps ?? []).some((s) => s.name === "retry")).length;
6376
+ const health = {
6377
+ sample: recent.length,
6378
+ successRate: recent.length ? ok / recent.length : null,
6379
+ failuresByCode: failedRuns.reduce((m, r) => {
6380
+ const code = r.error?.code ?? "UNKNOWN";
6381
+ m[code] = (m[code] ?? 0) + 1;
6382
+ return m;
6383
+ }, {}),
6384
+ avgCostCny: recent.length ? costSum / recent.length : null,
6385
+ retryUsed: retryCount
6386
+ };
6246
6387
  writeJson(res, 200, {
6247
6388
  ok: true,
6248
6389
  value: {
@@ -6251,6 +6392,7 @@ function makeBotApiRoutes(service, runAction) {
6251
6392
  name: bot.name,
6252
6393
  model: bot.model
6253
6394
  },
6395
+ health,
6254
6396
  runs: runs.map((r) => ({
6255
6397
  id: r.id,
6256
6398
  trigger: r.trigger,
@@ -6261,8 +6403,12 @@ function makeBotApiRoutes(service, runAction) {
6261
6403
  error: r.error,
6262
6404
  usage: r.usage,
6263
6405
  modelFallback: r.steps?.[0]?.args?.modelFallback,
6264
- outputPreview: typeof r.steps?.[0]?.result?.output === "string" ? r.steps[0].result.output.slice(0, 200) : void 0,
6406
+ outputPreview: typeof r.steps?.[0]?.result?.output === "string" ? r.steps[0].result.output.slice(0, 5e4) : void 0,
6265
6407
  stepCount: r.steps?.length ?? 0,
6408
+ steps: (r.steps ?? []).map((s) => ({
6409
+ kind: s.kind,
6410
+ name: s.name
6411
+ })),
6266
6412
  toolSteps: (r.steps ?? []).filter((s) => s.kind === "tool").map((s) => ({
6267
6413
  name: s.name,
6268
6414
  durationMs: s.durationMs,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zifeng1023/dsh-bot",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "常驻 AI 队友:记得住、守得住、收得回。默认 dry-run 演习、执行前自动快照、可一键回滚,并支持错峰调度省钱。",
5
5
  "repository": {
6
6
  "type": "git",
@@ -86,8 +86,5 @@
86
86
  },
87
87
  "license": "MIT"
88
88
  }
89
-
90
-
91
-
92
89
 
93
90
 
package/screenshots.json CHANGED
@@ -1,3 +1,5 @@
1
1
  [
2
- "assets/icon-180.png"
2
+ "assets/screenshot-1.png",
3
+ "assets/screenshot-2.png",
4
+ "assets/screenshot-3.png"
3
5
  ]