@zifeng1023/dsh-bot 0.3.8 → 0.3.10

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/lib/index.js CHANGED
@@ -933,9 +933,10 @@ function createLlmInvoker(ctx) {
933
933
  const options = {
934
934
  provider: input.provider,
935
935
  model: input.model,
936
- messages,
937
- reasoningEffort: input.reasoningEffort
936
+ messages
938
937
  };
938
+ const sentEffort = input.reasoningEffort;
939
+ if (sentEffort !== void 0) options.reasoningEffort = sentEffort;
939
940
  if (input.maxTokens !== void 0) options.maxTokens = input.maxTokens;
940
941
  else {
941
942
  const hit = [
@@ -972,7 +973,8 @@ function createLlmInvoker(ctx) {
972
973
  }
973
974
  if (input.signal) options.signal = input.signal;
974
975
  if (input.tools?.length) options.tools = input.tools;
975
- try {
976
+ /** 把「一次流式尝试」跑完,结果写回上面的状态变量(供失败重试用) */
977
+ const consumeStream = async (opts) => {
976
978
  const IDLE_MS = 9e4;
977
979
  const idleController = new AbortController();
978
980
  const resetIdle = () => {
@@ -980,63 +982,99 @@ function createLlmInvoker(ctx) {
980
982
  idleTimer = setTimeout(() => idleController.abort(/* @__PURE__ */ new Error("stream idle > 90s")), IDLE_MS);
981
983
  };
982
984
  resetIdle();
983
- options.signal = options.signal ? AbortSignal.any([options.signal, idleController.signal]) : idleController.signal;
984
- for await (const chunk of llm.stream(options)) {
985
- resetIdle();
986
- switch (chunk?.type) {
987
- case "text-delta":
988
- text += chunk.text ?? "";
989
- break;
990
- case "reasoning-delta":
991
- reasoning += chunk.text ?? "";
992
- break;
993
- case "usage":
994
- usage = chunk.usage;
995
- break;
996
- case "finish":
997
- stopReason = chunk.stopReason ?? chunk.finishReason ?? chunk.reason;
998
- break;
999
- case "tool-call-delta": {
1000
- const idx = Number(chunk.index ?? 0);
1001
- let partial = streamingToolCalls.get(idx);
1002
- if (!partial) {
1003
- partial = {
1004
- id: void 0,
1005
- name: void 0,
1006
- args: ""
985
+ opts.signal = opts.signal ? AbortSignal.any([opts.signal, idleController.signal]) : idleController.signal;
986
+ try {
987
+ for await (const chunk of llm.stream(opts)) {
988
+ resetIdle();
989
+ switch (chunk?.type) {
990
+ case "text-delta":
991
+ text += chunk.text ?? "";
992
+ break;
993
+ case "reasoning-delta":
994
+ reasoning += chunk.text ?? "";
995
+ break;
996
+ case "usage":
997
+ usage = chunk.usage;
998
+ break;
999
+ case "finish": {
1000
+ const reason = chunk.reason;
1001
+ if (reason && typeof reason === "object" && reason.kind !== void 0 && reason.kind !== "stop" && reason.kind !== "length") streamError = {
1002
+ type: "finish",
1003
+ reason
1007
1004
  };
1008
- streamingToolCalls.set(idx, partial);
1005
+ else stopReason = chunk.stopReason ?? chunk.finishReason ?? reason;
1006
+ break;
1009
1007
  }
1010
- if (typeof chunk.id === "string") partial.id = chunk.id;
1011
- if (typeof chunk.name === "string") partial.name = chunk.name;
1012
- if (typeof chunk.argumentsDelta === "string") partial.args += chunk.argumentsDelta;
1013
- break;
1014
- }
1015
- case "block-end": {
1016
- const block = chunk.block;
1017
- if (block?.type === "text" && !text) text = block.text ?? "";
1018
- if (block?.type === "reasoning" && !reasoning) reasoning = block.text ?? "";
1019
- const tu = asToolUse(block);
1020
- if (tu) toolUses.push(tu);
1021
- break;
1008
+ case "tool-call-delta": {
1009
+ const idx = Number(chunk.index ?? 0);
1010
+ let partial = streamingToolCalls.get(idx);
1011
+ if (!partial) {
1012
+ partial = {
1013
+ id: void 0,
1014
+ name: void 0,
1015
+ args: ""
1016
+ };
1017
+ streamingToolCalls.set(idx, partial);
1018
+ }
1019
+ if (typeof chunk.id === "string") partial.id = chunk.id;
1020
+ if (typeof chunk.name === "string") partial.name = chunk.name;
1021
+ if (typeof chunk.argumentsDelta === "string") partial.args += chunk.argumentsDelta;
1022
+ break;
1023
+ }
1024
+ case "block-end": {
1025
+ const block2 = chunk.block;
1026
+ if (block2?.type === "text" && !text) text = block2.text ?? "";
1027
+ if (block2?.type === "reasoning" && !reasoning) reasoning = block2.text ?? "";
1028
+ const tu = asToolUse(block2);
1029
+ if (tu) toolUses.push(tu);
1030
+ break;
1031
+ }
1032
+ case "error":
1033
+ case "adapter-failure":
1034
+ case "aborted":
1035
+ streamError = chunk;
1036
+ break;
1037
+ case "block-start":
1038
+ case "block-delta": break;
1039
+ default:
1040
+ if (chunk?.type) oddChunks.push(String(chunk.type));
1041
+ break;
1022
1042
  }
1023
- case "error":
1024
- case "adapter-failure":
1025
- case "aborted":
1026
- streamError = chunk;
1027
- break;
1028
- case "block-start":
1029
- case "block-delta": break;
1030
- default:
1031
- if (chunk?.type) oddChunks.push(String(chunk.type));
1032
- break;
1033
1043
  }
1044
+ } catch (e) {
1045
+ streamError = {
1046
+ type: "thrown",
1047
+ error: e
1048
+ };
1049
+ } finally {
1050
+ if (idleTimer) clearTimeout(idleTimer);
1034
1051
  }
1035
- if (idleTimer) clearTimeout(idleTimer);
1036
- } catch (e) {
1037
- if (idleTimer) clearTimeout(idleTimer);
1038
- const detail = describeLlmError(e);
1039
- throw new Error(`模型调用失败(${input.provider}/${input.model}):${detail}`);
1052
+ };
1053
+ /** 从任意失败形状里取出 { code, message }(宿主用 reason.failure,我们归一后用 error) */
1054
+ const failureOf = (err) => {
1055
+ if (!err) return {};
1056
+ const f = err.reason?.failure ?? err.failure ?? err.error ?? err;
1057
+ if (!f) return {};
1058
+ return {
1059
+ code: typeof f.code === "string" ? f.code : void 0,
1060
+ message: typeof f.message === "string" ? f.message : void 0
1061
+ };
1062
+ };
1063
+ await consumeStream(options);
1064
+ const notes = [];
1065
+ if (streamError && sentEffort !== void 0 && failureOf(streamError).code === "UNSUPPORTED_REASONING_EFFORT") {
1066
+ text = "";
1067
+ reasoning = "";
1068
+ usage = void 0;
1069
+ stopReason = void 0;
1070
+ streamError = void 0;
1071
+ oddChunks.length = 0;
1072
+ toolUses.length = 0;
1073
+ streamingToolCalls.clear();
1074
+ const retryOptions = { ...options };
1075
+ delete retryOptions.reasoningEffort;
1076
+ await consumeStream(retryOptions);
1077
+ if (!streamError) notes.push(`模型 ${input.provider}/${input.model} 未声明推理级别,已自动关闭 reasoningEffort=${sentEffort} 重试。要保留该设置,请在模型条目里声明 reasoningEfforts。`);
1040
1078
  }
1041
1079
  if (streamingToolCalls.size > 0) for (const [, partial] of [...streamingToolCalls.entries()].sort((a, b) => a[0] - b[0])) {
1042
1080
  if (!partial.name) continue;
@@ -1048,7 +1086,11 @@ function createLlmInvoker(ctx) {
1048
1086
  });
1049
1087
  }
1050
1088
  if (streamError && !text && toolUses.length === 0) {
1051
- const detail = describeLlmError(streamError.error ?? streamError);
1089
+ const f = failureOf(streamError);
1090
+ const detail = describeLlmError({
1091
+ code: f.code,
1092
+ message: f.message
1093
+ });
1052
1094
  throw new Error(`模型返回错误(${input.provider}/${input.model}):${detail}`);
1053
1095
  }
1054
1096
  if (!text.trim() && toolUses.length === 0) {
@@ -1071,6 +1113,7 @@ function createLlmInvoker(ctx) {
1071
1113
  outputTokens
1072
1114
  });
1073
1115
  return {
1116
+ notes: notes.length ? notes : void 0,
1074
1117
  text,
1075
1118
  reasoning: reasoning || void 0,
1076
1119
  usage: {
@@ -2106,6 +2149,8 @@ var BotService = class {
2106
2149
  todayCostCny: todayCost,
2107
2150
  lastRunAt: runs[0]?.startedAt,
2108
2151
  lastRunStatus: runs[0]?.status,
2152
+ model: identity.model,
2153
+ budget: identity.budget,
2109
2154
  goalDescription: goal?.description,
2110
2155
  goalStatus: goal?.status,
2111
2156
  goalType: goal?.type,
@@ -2577,13 +2622,10 @@ const DEFAULT_SETTINGS = {
2577
2622
  notifySystem: true,
2578
2623
  notifyOnlyOnDecision: true,
2579
2624
  quietHours: null,
2580
- followSessionModel: true,
2581
2625
  reasoningEffort: "high",
2582
2626
  dailyCny: 5,
2583
2627
  monthlyCny: 100,
2584
2628
  onExceed: "stop",
2585
- autoPropose: true,
2586
- defaultCadence: "",
2587
2629
  costSensitiveScheduling: true,
2588
2630
  snapshotKeepRecent: 10,
2589
2631
  snapshotEnabled: true,
@@ -2625,8 +2667,6 @@ function sanitizeSettings(raw) {
2625
2667
  };
2626
2668
  bool("notifySystem", raw.notifySystem);
2627
2669
  bool("notifyOnlyOnDecision", raw.notifyOnlyOnDecision);
2628
- bool("followSessionModel", raw.followSessionModel);
2629
- bool("autoPropose", raw.autoPropose);
2630
2670
  bool("costSensitiveScheduling", raw.costSensitiveScheduling);
2631
2671
  bool("snapshotEnabled", raw.snapshotEnabled);
2632
2672
  bool("sidebarEntry", raw.sidebarEntry);
@@ -2639,7 +2679,6 @@ function sanitizeSettings(raw) {
2639
2679
  if (Number.isFinite(raw.monthlyCny) && raw.monthlyCny >= 0) out.monthlyCny = Number(raw.monthlyCny);
2640
2680
  if (["stop", "downgrade"].includes(raw.onExceed)) out.onExceed = raw.onExceed;
2641
2681
  if (Number.isFinite(raw.snapshotKeepRecent) && raw.snapshotKeepRecent >= 0) out.snapshotKeepRecent = Math.floor(Number(raw.snapshotKeepRecent));
2642
- if (typeof raw.defaultCadence === "string") out.defaultCadence = raw.defaultCadence.trim();
2643
2682
  if (raw.quietHours === null) out.quietHours = null;
2644
2683
  else if (raw.quietHours && typeof raw.quietHours.start === "string" && typeof raw.quietHours.end === "string" && isValidClock(raw.quietHours.start) && isValidClock(raw.quietHours.end)) out.quietHours = {
2645
2684
  start: raw.quietHours.start,
@@ -2647,6 +2686,12 @@ function sanitizeSettings(raw) {
2647
2686
  };
2648
2687
  return out;
2649
2688
  }
2689
+ /** 可在单 Bot 层覆盖的通知项(其余项始终跟随全局) */
2690
+ const NOTIFY_OVERRIDE_KEYS = [
2691
+ "notifySystem",
2692
+ "notifyOnlyOnDecision",
2693
+ "quietHours"
2694
+ ];
2650
2695
  /** 设置存储 */
2651
2696
  var SettingsStore = class {
2652
2697
  constructor(homeDir) {
@@ -2672,14 +2717,29 @@ var SettingsStore = class {
2672
2717
  async getForBot(botId) {
2673
2718
  return readJsonSync(this.botPath(botId)) ?? {};
2674
2719
  }
2675
- async setForBot(botId, patch) {
2720
+ /**
2721
+ * 单 Bot 设置写入。
2722
+ *
2723
+ * ⭐ v0.3.9 刀 2:`clear` 让「恢复跟随全局」有确定语义——
2724
+ * 直接把该键从单 Bot 文件里删掉,而不是写一个假值。
2725
+ * quietHours 的 null 仍表示「这个 Bot 明确不免打扰」,与「跟随全局」不同。
2726
+ */
2727
+ async setForBot(botId, patch, clear = []) {
2728
+ const stored = { ...await this.getForBot(botId) };
2729
+ for (const key of clear) if (NOTIFY_OVERRIDE_KEYS.includes(key)) delete stored[key];
2676
2730
  const merged = {
2677
- ...await this.getForBot(botId),
2731
+ ...stored,
2678
2732
  ...sanitizeSettings(patch)
2679
2733
  };
2680
- await writeJsonAtomic$1(this.botPath(botId), merged);
2734
+ if (Object.keys(merged).length === 0) await fsp.rm(this.botPath(botId), { force: true });
2735
+ else await writeJsonAtomic$1(this.botPath(botId), merged);
2681
2736
  return this.resolve(botId);
2682
2737
  }
2738
+ /** 该 Bot 覆盖了哪些键(UI 用来显示「跟随全局 / 已覆盖」) */
2739
+ async overridesFor(botId) {
2740
+ const raw = await this.getForBot(botId);
2741
+ return NOTIFY_OVERRIDE_KEYS.filter((k) => raw[k] !== void 0);
2742
+ }
2683
2743
  /** 全局 + 单 Bot 合并后的有效设置 */
2684
2744
  async resolve(botId) {
2685
2745
  return mergeSettings(await this.getGlobal(), botId ? await this.getForBot(botId) : void 0);
@@ -5266,6 +5326,10 @@ var RoutineRunner = class {
5266
5326
  signal
5267
5327
  });
5268
5328
  record.usage = addUsage(record.usage, out.usage);
5329
+ if (out.notes?.length) stepRecord.args = {
5330
+ ...stepRecord.args ?? {},
5331
+ notes: out.notes
5332
+ };
5269
5333
  const over = this.overBudget(bot, baseline, record.usage.costCny);
5270
5334
  if (over) {
5271
5335
  record.status = "budget_exceeded";
@@ -5904,7 +5968,26 @@ function makeBotApiRoutes(service, runAction) {
5904
5968
  onExceed: body.budget.onExceed === "downgrade" ? "downgrade" : "stop"
5905
5969
  };
5906
5970
  }
5907
- if (Object.keys(patch).length === 0 && cadencePatch === void 0) throw new BotError("INVALID_ARGS", "没有可更新的字段");
5971
+ if (Object.keys(patch).length === 0 && cadencePatch === void 0) {
5972
+ if (body?.model && typeof body.model === "object") {
5973
+ const provider = String(body.model.provider ?? "").trim();
5974
+ const model = String(body.model.model ?? "").trim();
5975
+ if (!provider || !model) throw new BotError("INVALID_ARGS", "需要 model.provider 与 model.model");
5976
+ const known = await runAction.getAvailableModels?.() ?? [];
5977
+ if (known.length > 0) {
5978
+ const hit = known.find((x) => x.provider === provider);
5979
+ if (!hit) throw new BotError("INVALID_ARGS", `当前环境没有 provider「${provider}」。可用:` + known.map((x) => x.provider).join(", "));
5980
+ if (hit.models && hit.models.length > 0 && !hit.models.includes(model)) throw new BotError("INVALID_ARGS", `provider「${provider}」下没有模型「${model}」。可用:` + hit.models.join(", "));
5981
+ }
5982
+ const cur = await service.get(botId);
5983
+ patch.model = {
5984
+ provider,
5985
+ model,
5986
+ reasoningEffort: body.model.reasoningEffort ?? cur.model?.reasoningEffort ?? "high"
5987
+ };
5988
+ }
5989
+ throw new BotError("INVALID_ARGS", "没有可更新的字段");
5990
+ }
5908
5991
  const next = await service.update(botId, patch);
5909
5992
  if (cadencePatch !== void 0) {
5910
5993
  const goal = await service.getGoal(botId);
@@ -6620,12 +6703,17 @@ function makeBotApiRoutes(service, runAction) {
6620
6703
  try {
6621
6704
  if (req.method === "GET") {
6622
6705
  const botId = new URL(req.url ?? "/", "http://x").searchParams.get("botId") ?? void 0;
6623
- const [effective, global] = await Promise.all([runAction.getSettings?.(botId), runAction.getGlobalSettings?.()]);
6706
+ const [effective, global, overrides] = await Promise.all([
6707
+ runAction.getSettings?.(botId),
6708
+ runAction.getGlobalSettings?.(),
6709
+ runAction.getSettingsOverrides?.(botId)
6710
+ ]);
6624
6711
  writeJson(res, 200, {
6625
6712
  ok: true,
6626
6713
  value: {
6627
6714
  effective: effective ?? null,
6628
- global: global ?? null
6715
+ global: global ?? null,
6716
+ overrides: overrides ?? []
6629
6717
  }
6630
6718
  });
6631
6719
  return;
@@ -6639,9 +6727,10 @@ function makeBotApiRoutes(service, runAction) {
6639
6727
  }
6640
6728
  const body = await readJsonBody(req);
6641
6729
  const target = body?.botId ? String(body.botId) : void 0;
6730
+ const clear = Array.isArray(body?.clear) ? body.clear.map((k) => String(k)) : [];
6642
6731
  writeJson(res, 200, {
6643
6732
  ok: true,
6644
- value: await runAction.saveSettings?.(target, body?.settings ?? {}) ?? null
6733
+ value: await runAction.saveSettings?.(target, body?.settings ?? {}, clear) ?? null
6645
6734
  });
6646
6735
  } catch (e) {
6647
6736
  writeError(res, e);
@@ -6728,6 +6817,67 @@ function makeBotApiRoutes(service, runAction) {
6728
6817
  }
6729
6818
  }
6730
6819
  },
6820
+ {
6821
+ kind: "exact",
6822
+ path: `${API_PREFIX}/runs/aggregate`,
6823
+ handler: async (req, res) => {
6824
+ if (req.method !== "GET") {
6825
+ writeJson(res, 405, {
6826
+ ok: false,
6827
+ code: "METHOD_NOT_ALLOWED"
6828
+ });
6829
+ return;
6830
+ }
6831
+ try {
6832
+ const url = new URL(req.url ?? "/", "http://x");
6833
+ const limit = Math.min(Math.max(Number(url.searchParams.get("limit")) || 20, 1), 100);
6834
+ const bots = await service.list();
6835
+ const runs = [];
6836
+ const byBot = {};
6837
+ for (const b of bots) {
6838
+ const list = await service.listRuns(b.id, limit);
6839
+ const sample = list.length;
6840
+ const ok = list.filter((r) => r.status === "success").length;
6841
+ byBot[b.id] = {
6842
+ botName: b.name,
6843
+ sample,
6844
+ successRate: sample ? ok / sample : 0
6845
+ };
6846
+ for (const r of list) runs.push({
6847
+ id: r.id,
6848
+ botId: b.id,
6849
+ botName: b.name,
6850
+ status: r.status,
6851
+ trigger: r.trigger,
6852
+ startedAt: r.startedAt,
6853
+ endedAt: r.endedAt,
6854
+ usage: r.usage,
6855
+ steps: (r.steps ?? []).map((s) => ({
6856
+ kind: s.kind,
6857
+ name: s.name
6858
+ }))
6859
+ });
6860
+ }
6861
+ runs.sort((a, b) => String(b.startedAt ?? "").localeCompare(String(a.startedAt ?? "")));
6862
+ const total = runs.length;
6863
+ const success = runs.filter((r) => r.status === "success").length;
6864
+ writeJson(res, 200, {
6865
+ ok: true,
6866
+ value: {
6867
+ runs,
6868
+ byBot,
6869
+ health: {
6870
+ sample: total,
6871
+ successRate: total ? success / total : 0
6872
+ },
6873
+ botCount: bots.length
6874
+ }
6875
+ });
6876
+ } catch (e) {
6877
+ writeError(res, e);
6878
+ }
6879
+ }
6880
+ },
6731
6881
  {
6732
6882
  kind: "exact",
6733
6883
  path: `${API_PREFIX}/runs/clear`,
@@ -7862,8 +8012,9 @@ function applyInner(ctx, rawConfig) {
7862
8012
  getAvailableModels: () => listAvailableModels(ctx),
7863
8013
  getSettings: (botId) => settingsStore.resolve(botId),
7864
8014
  getGlobalSettings: () => settingsStore.getGlobal(),
7865
- saveSettings: async (botId, patch) => {
7866
- if (botId) return settingsStore.setForBot(botId, patch);
8015
+ getSettingsOverrides: (botId) => botId ? settingsStore.overridesFor(botId) : Promise.resolve([]),
8016
+ saveSettings: async (botId, patch, clear) => {
8017
+ if (botId) return settingsStore.setForBot(botId, patch, clear ?? []);
7867
8018
  return settingsStore.setGlobal(patch);
7868
8019
  },
7869
8020
  doctor: doctorReport
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zifeng1023/dsh-bot",
3
- "version": "0.3.8",
3
+ "version": "0.3.10",
4
4
  "description": "常驻 AI 队友:记得住、守得住、收得回。默认 dry-run 演习、执行前自动快照、可一键回滚,并支持错峰调度省钱。",
5
5
  "repository": {
6
6
  "type": "git",
@@ -72,8 +72,8 @@
72
72
  "vitest": "^3.0.0"
73
73
  },
74
74
  "scripts": {
75
- "build": "tsdown",
76
- "prepare": "tsdown",
75
+ "build": "node dev/concat-parts.mjs && tsdown",
76
+ "prepare": "node dev/concat-parts.mjs && tsdown",
77
77
  "dev": "tsdown --watch",
78
78
  "test": "vitest run",
79
79
  "test:watch": "vitest",
@@ -82,7 +82,8 @@
82
82
  "verify:static": "node dev/check-undefined.mjs",
83
83
  "verify:e2e": "node dev/demo-goal-cycle.mjs && node dev/demo-goal-cadence.mjs && node dev/demo-model-binding.mjs",
84
84
  "verify:all": "npm run verify:static && npm run typecheck && npm run test && npm run build && npm run verify:client && npm run verify:e2e",
85
- "gen:tools": "node dev/gen-tools-doc.mjs"
85
+ "gen:tools": "node dev/gen-tools-doc.mjs",
86
+ "concat": "node dev/concat-parts.mjs"
86
87
  },
87
88
  "license": "MIT"
88
89
  }
package/screenshots.json CHANGED
@@ -1,5 +1,5 @@
1
1
  [
2
- "assets/screenshot-1.png",
3
- "assets/screenshot-2.png",
4
- "assets/screenshot-3.png"
2
+ "assets/screenshot-v039-1.jpg",
3
+ "assets/screenshot-v039-2.jpg",
4
+ "assets/screenshot-v039-3.jpg"
5
5
  ]