pi-web-ui 0.118.0 → 0.120.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 (195) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/bin/hub-upgrade.mjs +33 -15
  3. package/bin/lib/atomic-file.mjs +90 -0
  4. package/dist/server/agent-service-daemon.js +44 -10
  5. package/dist/server/agent-service.js +930 -166
  6. package/dist/server/approval-default-rules.js +4 -4
  7. package/dist/server/ask-user-question-tool.js +3 -40
  8. package/dist/server/atomic-file.js +130 -5
  9. package/dist/server/background-executors.js +235 -0
  10. package/dist/server/bash-timeout.js +47 -0
  11. package/dist/server/bash-tool.js +72 -5
  12. package/dist/server/bg-servers.js +19 -13
  13. package/dist/server/browser-page-tool.js +38 -29
  14. package/dist/server/browser-script-tool.js +119 -0
  15. package/dist/server/canvas/canvas-agent-tool.js +46 -35
  16. package/dist/server/canvas/canvas-dispatch.js +12 -1
  17. package/dist/server/claim-files-tool.js +6 -7
  18. package/dist/server/client-state.js +457 -41
  19. package/dist/server/communicate-tool.js +59 -77
  20. package/dist/server/compact-context-tool.js +4 -13
  21. package/dist/server/conversation-communication.js +23 -1
  22. package/dist/server/conversation-read-tool.js +14 -23
  23. package/dist/server/conversation-rows.js +17 -0
  24. package/dist/server/conversation-tool-names.js +2 -2
  25. package/dist/server/conversation-tool.js +23 -15
  26. package/dist/server/conversation-touches.js +1 -1
  27. package/dist/server/delegate-mode.js +0 -1
  28. package/dist/server/delegate-task.js +18 -39
  29. package/dist/server/device-center/approval-summary.js +0 -1
  30. package/dist/server/device-center/bot-execution.js +0 -1
  31. package/dist/server/device-center/group-router-runtime.js +2 -0
  32. package/dist/server/device-center/hub-upgrade.js +5 -10
  33. package/dist/server/device-center/task-progress.js +2 -2
  34. package/dist/server/dispatch-domain-handlers.js +97 -24
  35. package/dist/server/dispatch-plugin-handlers.js +10 -0
  36. package/dist/server/dsh/dsh-agent-service.js +21 -19
  37. package/dist/server/durable/durable-agent-service.js +1 -1
  38. package/dist/server/edit-tool.js +293 -0
  39. package/dist/server/engine-catalog.js +8 -2
  40. package/dist/server/engine-cli.js +29 -7
  41. package/dist/server/engine-probe.js +11 -6
  42. package/dist/server/eval-tool.js +5 -19
  43. package/dist/server/files-service.js +41 -19
  44. package/dist/server/fs-copy.js +93 -0
  45. package/dist/server/goal-review-gate.js +2 -3
  46. package/dist/server/index.js +92 -3
  47. package/dist/server/job-runner.js +345 -0
  48. package/dist/server/lsp-tool.js +10 -28
  49. package/dist/server/marker-service.js +42 -30
  50. package/dist/server/mcp-agent-tool.js +22 -47
  51. package/dist/server/model-session.js +16 -0
  52. package/dist/server/native-cli-session-hooks.js +3 -2
  53. package/dist/server/native-cli-session.js +27 -2
  54. package/dist/server/patch-tool.js +2 -8
  55. package/dist/server/phone-tool.js +167 -0
  56. package/dist/server/plan-mode.js +7 -4
  57. package/dist/server/plan-update-tool.js +5 -8
  58. package/dist/server/plugin-api-catalog.js +13 -1
  59. package/dist/server/plugin-bundled.js +35 -28
  60. package/dist/server/plugin-catalog.js +6 -0
  61. package/dist/server/plugin-delivery.js +358 -0
  62. package/dist/server/plugin-inbox.js +152 -0
  63. package/dist/server/plugin-installer.js +15 -0
  64. package/dist/server/plugin-ledger.js +183 -0
  65. package/dist/server/plugin-manifest-validate.js +19 -0
  66. package/dist/server/plugin-materialize.js +161 -0
  67. package/dist/server/plugin-paths.js +60 -0
  68. package/dist/server/plugin-removal.js +16 -3
  69. package/dist/server/plugin-schedule.js +8 -7
  70. package/dist/server/plugin-secrets.js +7 -3
  71. package/dist/server/plugin-updater.js +2 -4
  72. package/dist/server/plugins.js +205 -48
  73. package/dist/server/present-files-tool.js +7 -13
  74. package/dist/server/preset-fields.js +23 -12
  75. package/dist/server/preset-share.js +1 -1
  76. package/dist/server/process-utils.js +11 -0
  77. package/dist/server/project-scripts.js +38 -0
  78. package/dist/server/prompt-composer.js +40 -21
  79. package/dist/server/protocol-version.js +1 -1
  80. package/dist/server/question-params.js +98 -0
  81. package/dist/server/quick-ask-settings.js +0 -1
  82. package/dist/server/quick-ask.js +3 -0
  83. package/dist/server/read-tool.js +10 -17
  84. package/dist/server/remote-ssh-service.js +40 -1
  85. package/dist/server/sandbox-runtime-gate.js +1 -1
  86. package/dist/server/sandbox-service.js +0 -1
  87. package/dist/server/sandbox-tool.js +25 -34
  88. package/dist/server/schedule-agent-tool.js +9 -19
  89. package/dist/server/scm-commitmsg.js +2 -1
  90. package/dist/server/serialize.js +8 -0
  91. package/dist/server/session-list-index.js +246 -0
  92. package/dist/server/session-list-scan.js +5 -0
  93. package/dist/server/session-parser.js +16 -0
  94. package/dist/server/settings-service.js +49 -19
  95. package/dist/server/skill-tool.js +4 -6
  96. package/dist/server/subagent-budget.js +68 -0
  97. package/dist/server/subagent-evidence.js +297 -0
  98. package/dist/server/subagent-helpers.js +12 -0
  99. package/dist/server/subagent-ledger.js +401 -0
  100. package/dist/server/subagent-notify.js +6 -2
  101. package/dist/server/subagent-security-gate.js +2 -3
  102. package/dist/server/subagent-settle.js +71 -0
  103. package/dist/server/subagents.js +566 -211
  104. package/dist/server/tabs.js +8 -1
  105. package/dist/server/terminals.js +34 -28
  106. package/dist/server/tool-approval.js +15 -1
  107. package/dist/server/tool-guards.js +0 -91
  108. package/dist/server/tool-manager.js +127 -47
  109. package/dist/server/tool-overrides.js +8 -1
  110. package/dist/server/tool-prompt-overrides.js +3 -6
  111. package/dist/server/tool-prompts.js +60 -17
  112. package/dist/server/universal/driver-base.js +2 -0
  113. package/dist/server/universal/drivers/claude-code.js +210 -211
  114. package/dist/server/universal/drivers/codex.js +29 -24
  115. package/dist/server/universal/engine-mcp.js +107 -0
  116. package/dist/server/universal/universal-attachments.js +77 -1
  117. package/dist/server/universal/universal-service.js +1 -1
  118. package/dist/server/universal/universal-session.js +106 -69
  119. package/dist/server/vision-bridge.js +2 -0
  120. package/dist/server/workspace-handle.js +119 -17
  121. package/dist/server/workspace-queue.js +37 -0
  122. package/dist/server/worktree-tool.js +13 -20
  123. package/docs/README.md +40 -36
  124. package/docs/architecture-plugins.md +64 -35
  125. package/docs/device-center.md +1 -1
  126. package/package.json +16 -4
  127. package/plugin-sdk/index.d.ts +102 -0
  128. package/plugins/catalog.json +23 -51
  129. package/themes/bases/flow-base.css +8 -17
  130. package/themes/dark-teal.css +0 -3
  131. package/web/dist/.build-assets.json +1 -1
  132. package/web/dist/assets/BgTasksModal-BdOJ19Hj.js +1 -0
  133. package/web/dist/assets/BgTasksModal-SAH2XCkY.js +1 -0
  134. package/web/dist/assets/{CanvasStudio-CAWcs9tm.js → CanvasStudio-BB_Iq7pl.js} +3 -3
  135. package/web/dist/assets/CanvasStudio-DU6O3N4u.js +1579 -0
  136. package/web/dist/assets/DeviceCenter-By1zVTSY.js +3 -0
  137. package/web/dist/assets/DeviceCenter-Cnm0Tjrx.js +3 -0
  138. package/web/dist/assets/DeviceExecutionSettings-qJzbI0Cf.js +1 -0
  139. package/web/dist/assets/{DeviceGroups-C_fZMNeK.js → DeviceGroups-DPrQxW6B.js} +1 -1
  140. package/web/dist/assets/DeviceGroups-DoucyUjI.js +1 -0
  141. package/web/dist/assets/{Dropdown-CTgVLUbp.js → Dropdown-kj_NIj6e.js} +1 -1
  142. package/web/dist/assets/FilePreview-Bub8Y9uq.js +2 -0
  143. package/web/dist/assets/FilePreview-CC76Z6an.js +2 -0
  144. package/web/dist/assets/GlobalSearchModal-01nkgw4X.js +1 -0
  145. package/web/dist/assets/GlobalSearchModal-CiT6wBmR.js +1 -0
  146. package/web/dist/assets/GroupConversation-1-lsPO1f.js +61 -0
  147. package/web/dist/assets/GroupConversation-HeiyW_O_.js +61 -0
  148. package/web/dist/assets/{GroupWorkItems-BIvZtr10.js → GroupWorkItems-BYJv2XFj.js} +1 -1
  149. package/web/dist/assets/{HintTip-Da6qc566.js → HintTip-DFhoclDw.js} +1 -1
  150. package/web/dist/assets/ModelConfigModal-D2Ro-jUZ.js +2 -0
  151. package/web/dist/assets/ModelConfigModal-DPc9R1pq.js +2 -0
  152. package/web/dist/assets/{NativeCliPanel-CU1rZmyu.js → NativeCliPanel-B108d697.js} +3 -3
  153. package/web/dist/assets/NativeCliPanel-DupvGwQM.js +5 -0
  154. package/web/dist/assets/{PiSetupModal-DZKY5Wiw.js → PiSetupModal-D0HitBfd.js} +1 -1
  155. package/web/dist/assets/ProviderOAuthControls-BLKUEDde.js +1 -0
  156. package/web/dist/assets/SCMPanel-DDbWrUHR.js +2 -0
  157. package/web/dist/assets/SCMPanel-DluNcd2-.js +2 -0
  158. package/web/dist/assets/SettingsModal-Cy5lRC97.css +1 -0
  159. package/web/dist/assets/SettingsModal-DQu18366.js +33 -0
  160. package/web/dist/assets/SettingsModal-Dm_haPme.js +33 -0
  161. package/web/dist/assets/{TermXterm-Bt5WKAxP.js → TermXterm-SYc-MUk2.js} +2 -2
  162. package/web/dist/assets/TerminalPanel-CgA_lhVT.js +1 -0
  163. package/web/dist/assets/TerminalPanel-vdSIOPjD.js +1 -0
  164. package/web/dist/assets/TuiOverlayModal-Cy1jYYIw.js +1 -0
  165. package/web/dist/assets/TuiOverlayModal-kXY_4hV8.js +1 -0
  166. package/web/dist/assets/app-globals-CBEscsYP.js +129 -0
  167. package/web/dist/assets/{canvas-client-WkhM55mR.js → canvas-client-Clsypfs6.js} +1 -1
  168. package/web/dist/assets/{desktop-B8NZ3KW-.js → desktop-C6D9a8HZ.js} +1 -1
  169. package/web/dist/assets/index-BD29OL9L.js +404 -0
  170. package/web/dist/assets/index-BlCxbqqr.js +404 -0
  171. package/web/dist/assets/index-DB55rbKC.css +1 -0
  172. package/web/dist/assets/plugin-host-VWBcq-LQ.js +1 -0
  173. package/web/dist/assets/remote-ssh-client-C2eab5Kw.js +1 -0
  174. package/web/dist/assets/theme-CpQk_Agp.js +1 -0
  175. package/web/dist/index.html +10 -10
  176. package/web/dist/sw.js +1 -1
  177. package/dist/server/edit-soft-tool.js +0 -297
  178. package/web/dist/assets/BgTasksModal-D-x7kA63.js +0 -1
  179. package/web/dist/assets/DeviceCenter-Dc0whRcu.js +0 -3
  180. package/web/dist/assets/DeviceExecutionSettings-BoX7-0h7.js +0 -1
  181. package/web/dist/assets/FilePreview-C6W0PvaK.js +0 -2
  182. package/web/dist/assets/GlobalSearchModal-HR9LSspC.js +0 -1
  183. package/web/dist/assets/GroupConversation-C81YjF2C.js +0 -61
  184. package/web/dist/assets/ModelConfigModal-DhSyuIuV.js +0 -2
  185. package/web/dist/assets/ProviderOAuthControls-CIL85nA7.js +0 -1
  186. package/web/dist/assets/SCMPanel-CuEgzAlO.js +0 -2
  187. package/web/dist/assets/SettingsModal-Cdu5h29p.js +0 -33
  188. package/web/dist/assets/TerminalPanel-BCIBV8se.js +0 -1
  189. package/web/dist/assets/TuiOverlayModal-3NDd9T97.js +0 -1
  190. package/web/dist/assets/app-globals-CZjFtI4F.js +0 -129
  191. package/web/dist/assets/index-CQc3VrWa.css +0 -1
  192. package/web/dist/assets/index-D_AGu4Zv.js +0 -404
  193. package/web/dist/assets/plugin-host-uqZGpvCs.js +0 -1
  194. package/web/dist/assets/remote-ssh-client-Cdf-cTUe.js +0 -1
  195. package/web/dist/assets/theme-DGL7hLUs.js +0 -1
@@ -1,48 +1,40 @@
1
- import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { writeJsonAtomicSync } from "./atomic-file.js";
4
4
  import { BUILTIN_MODULE_IDS, isBuiltinModule } from "./builtin-modules.js";
5
+ import { isMaterialized, materializePlugin } from "./plugin-materialize.js";
5
6
  const ID_RE = /^[A-Za-z0-9_-]+$/;
6
7
  function preparePayload(dataDir, catalogPath, id) {
7
- const source = join(dirname(catalogPath), id);
8
- const target = join(dataDir, "plugins", id);
9
- if (existsSync(target))
10
- return true;
11
- if (!existsSync(join(source, "manifest.json")))
12
- return false;
13
- const manifest = JSON.parse(readFileSync(join(source, "manifest.json"), "utf8"));
14
- if (manifest.id !== id)
15
- return false;
16
- mkdirSync(dirname(target), { recursive: true });
17
- const staging = mkdtempSync(join(dirname(target), ".bundled-"));
18
- try {
19
- cpSync(source, staging, {
20
- recursive: true,
21
- filter: (path) => !/(^|[\\/])(\.git|node_modules)([\\/]|$)/.test(path),
22
- });
23
- renameSync(staging, target);
24
- }
25
- finally {
26
- rmSync(staging, { recursive: true, force: true });
27
- }
28
- return true;
8
+ return materializePlugin({
9
+ id,
10
+ sourceDir: join(dirname(catalogPath), id),
11
+ targetDir: join(dataDir, "plugins", id),
12
+ });
29
13
  }
14
+ /**
15
+ * 把随包分发的插件(内置模块 + `preinstall` 候选)物化到数据目录。
16
+ *
17
+ * 「目录存在」不再等于「已准备」:完整性由物化回执裁定,半残目录会被就地修复,
18
+ * 而不是留下一个永远报 `manifest.json 缺失或解析失败` 的空壳(issue #856)。
19
+ */
30
20
  export function prepareBundledPlugins(dataDir, catalogPath, overriddenIds = new Set()) {
21
+ const outcomes = [];
31
22
  for (const id of BUILTIN_MODULE_IDS)
32
- preparePayload(dataDir, catalogPath, id);
23
+ outcomes.push(preparePayload(dataDir, catalogPath, id));
33
24
  const catalog = JSON.parse(readFileSync(catalogPath, "utf8"));
34
25
  if (!Array.isArray(catalog))
35
- return;
26
+ return outcomes;
36
27
  const optional = catalog.filter((entry) => entry &&
37
28
  entry.preinstall === true &&
38
29
  typeof entry.id === "string" &&
39
30
  ID_RE.test(entry.id) &&
40
31
  !isBuiltinModule(entry.id));
41
32
  if (!optional.length)
42
- return;
33
+ return outcomes;
43
34
  const receiptPath = join(dataDir, "bundled-plugin-installs.json");
44
35
  let initialized = new Set();
45
36
  if (existsSync(receiptPath)) {
37
+ // 回执损坏时不猜:直接报错,绝不能当成「没装过」把用户卸掉的预装插件重新装回来
46
38
  const receipt = JSON.parse(readFileSync(receiptPath, "utf8"));
47
39
  if (!receipt ||
48
40
  typeof receipt !== "object" ||
@@ -56,13 +48,28 @@ export function prepareBundledPlugins(dataDir, catalogPath, overriddenIds = new
56
48
  let changed = false;
57
49
  for (const entry of optional) {
58
50
  const id = entry.id;
59
- if (initialized.has(id))
51
+ if (overriddenIds.has(id))
60
52
  continue;
61
- if (!overriddenIds.has(id) && !preparePayload(dataDir, catalogPath, id))
53
+ const targetDir = join(dataDir, "plugins", id);
54
+ if (initialized.has(id)) {
55
+ // 预装过一次就不再复活:用户主动删掉目录就当卸载,但半残目录必须修
56
+ if (!existsSync(targetDir) || isMaterialized(targetDir, id))
57
+ continue;
58
+ const outcome = preparePayload(dataDir, catalogPath, id);
59
+ outcomes.push(outcome);
60
+ if (outcome.status === "failed" || outcome.status === "source-invalid") {
61
+ console.warn(`[plugins] 修复预装插件 ${id} 失败:${outcome.error ?? outcome.status}`);
62
+ }
63
+ continue;
64
+ }
65
+ const outcome = preparePayload(dataDir, catalogPath, id);
66
+ outcomes.push(outcome);
67
+ if (outcome.status === "source-invalid" || outcome.status === "failed")
62
68
  continue;
63
69
  initialized.add(id);
64
70
  changed = true;
65
71
  }
66
72
  if (changed)
67
73
  writeJsonAtomicSync(receiptPath, { version: 1, ids: [...initialized].sort() });
74
+ return outcomes;
68
75
  }
@@ -123,6 +123,12 @@ export function readCatalog(builtinPath, customPath, communityPath) {
123
123
  continue;
124
124
  const idx = out.findIndex((x) => x.id === e.id);
125
125
  if (idx >= 0) {
126
+ // 同 id 同 source = 同一条目被重复登记(典型:同步整份官方目录写进了自定义文件)。
127
+ // 这种情况不是「用户用 fork 覆盖内置」,保留原有条目与 origin,否则标签会在宿主自带/手动添加之间乱跳。
128
+ if (out[idx].source === e.source) {
129
+ seen.add(e.id);
130
+ continue;
131
+ }
126
132
  out[idx] = { ...e, builtin: false, origin: "custom", overridesBuiltin: seenBuiltin.has(e.id) };
127
133
  }
128
134
  else {
@@ -0,0 +1,358 @@
1
+ /**
2
+ * 插件出站投递队列(DeliveryQueue)
3
+ *
4
+ * 与入站(`PluginInbox`)共用同一个账本(`PluginLedgerStore`,`direction: "out"`)。
5
+ * 解决的问题:以前渠道插件发送失败直接 `throw`,大多数调用点 `.catch(() => {})` 吞掉 ——
6
+ * 回复静默消失,只剩一行 log,也没人知道「这条彻底没发出去」。
7
+ *
8
+ * 设计取舍(对 IM 场景很重要):
9
+ * - **不是无条件重试**:`classify()` 由插件给(它懂平台错误码)。`rejected`(内容/权限被拒)、
10
+ * `auth` 之类不该重试 —— 重试 100 次也不会成功,只会更快撞限流。只有 `network` / `rate_limited`
11
+ * 这类瞬时错误才进队列退避。
12
+ * - **快路径不变**:`sendNow()` 仍然立刻尝试一次并 `await`(成功路径与改造前完全一致);
13
+ * 只有「可重试失败」才转成后台队列。这样不会把一条同步链路改成异步链路。
14
+ * - **TTL 兜底**:平台有被动回复窗口,超窗的消息重发也没意义,`ttlMs` 到期直接死信。
15
+ * - **串行**:pump 逐条 `await`(并发 1)。同渠道消息顺序比吞吐重要,渠道量也远没到瓶颈。
16
+ */
17
+ import { randomUUID } from "node:crypto";
18
+ import { normalizeLedgerKey, PluginLedgerStore } from "./plugin-ledger.js";
19
+ /** 可重试的错误类别:瞬时故障才值得排队。 */
20
+ const RETRYABLE = new Set([
21
+ "network",
22
+ "rate_limited",
23
+ "expired",
24
+ "unknown",
25
+ ]);
26
+ const DEFAULT_BACKOFF_MS = [5_000, 30_000, 120_000, 600_000];
27
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
28
+ const DEFAULT_SEND_TIMEOUT_MS = 30_000;
29
+ const DEFAULT_PUMP_MS = 5_000;
30
+ export class DeliveryQueue {
31
+ ledger;
32
+ ownsLedger;
33
+ senders = new Map();
34
+ inflight = new Set();
35
+ backoffMs;
36
+ ttlMs;
37
+ sendTimeoutMs;
38
+ now;
39
+ timer = null;
40
+ constructor(opts) {
41
+ if (opts.ledger) {
42
+ this.ledger = opts.ledger;
43
+ this.ownsLedger = false;
44
+ }
45
+ else {
46
+ if (!opts.dataDir || !opts.pluginId)
47
+ throw new Error("DeliveryQueue requires ledger or dataDir+pluginId");
48
+ this.ledger = new PluginLedgerStore({
49
+ dataDir: opts.dataDir,
50
+ pluginId: opts.pluginId,
51
+ ...(opts.now ? { now: opts.now } : {}),
52
+ });
53
+ this.ownsLedger = true;
54
+ }
55
+ this.backoffMs = opts.backoffMs ?? DEFAULT_BACKOFF_MS;
56
+ this.ttlMs = Math.max(0, opts.ttlMs ?? DEFAULT_TTL_MS);
57
+ this.sendTimeoutMs = Math.max(1_000, opts.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS);
58
+ this.now = opts.now ?? this.ledger.now;
59
+ }
60
+ registerSender(channel, send) {
61
+ const key = String(channel ?? "").trim();
62
+ if (!key)
63
+ throw new Error("delivery.registerSender: channel 不能为空");
64
+ this.senders.set(key, send);
65
+ }
66
+ hasSender(channel) {
67
+ return this.senders.has(String(channel ?? "").trim());
68
+ }
69
+ /** 插件反激活时注销发送器(队列里残留的项会因 str 缺 sender 而停下)。 */
70
+ unregisterSender(channel) {
71
+ this.senders.delete(String(channel ?? "").trim());
72
+ }
73
+ /**
74
+ * 立刻尝试发送一次。
75
+ * - 成功 → `sent`(账本记 done,供统计与幂等)
76
+ * - 可重试失败 → `queued`(不抛,后台 pump 继续重试)
77
+ * - 不可重试 / 超 TTL / 无 sender → **抛错**(调用方决定怎么告知用户)
78
+ */
79
+ async sendNow(req) {
80
+ const channel = String(req.channel ?? "").trim();
81
+ const sender = this.senders.get(channel);
82
+ if (!sender)
83
+ throw new Error(`delivery: 未注册渠道「${channel}」的发送器`);
84
+ const key = normalizeLedgerKey(req.key ?? `out:${randomUUID()}`);
85
+ if (!key)
86
+ throw new Error("delivery: 幂等键非法");
87
+ const now = this.now();
88
+ const existing = this.ledger.get(key);
89
+ // 幂等:已经发成功 / 正在发 / 排着队,都不重复发。
90
+ if (existing && existing.direction === "out") {
91
+ if (existing.state === "done" || this.inflight.has(key))
92
+ return { status: "duplicate" };
93
+ if (existing.state === "claimed" && !this.ledger.isTerminal(existing))
94
+ return { status: "duplicate" };
95
+ }
96
+ const attempts = (existing && existing.direction === "out" ? existing.attempts : 0) + 1;
97
+ const item = toItem(channel, key, req, existing, attempts, now);
98
+ this.inflight.add(key);
99
+ try {
100
+ await withTimeout(sender(item), this.sendTimeoutMs);
101
+ this.ledger.put(doneRecord(this.ledger, item, now));
102
+ return { status: "sent" };
103
+ }
104
+ catch (err) {
105
+ const errorClass = classifyError(req, err);
106
+ const retryable = errorClass !== null && RETRYABLE.has(errorClass);
107
+ const expired = this.ttlMs > 0 && now - item.createdAt >= this.ttlMs;
108
+ if (!retryable || expired) {
109
+ this.ledger.put(failedRecord(this.ledger, item, attempts, errorClass, err, now));
110
+ throw deliveryError(err, errorClass, expired);
111
+ }
112
+ const nextAttemptAt = now + this.backoffFor(attempts);
113
+ this.ledger.put(queuedRecord(this.ledger, item, attempts, errorClass, err, now, nextAttemptAt));
114
+ return { status: "queued", attempts, nextAttemptAt };
115
+ }
116
+ finally {
117
+ this.inflight.delete(key);
118
+ }
119
+ }
120
+ /** 后台重试:把到期项逐条发出去(并发 1,保证同渠道顺序)。 */
121
+ async pump(now = this.now()) {
122
+ let sent = 0;
123
+ let retried = 0;
124
+ let dead = 0;
125
+ const due = this.ledger
126
+ .byDirection("out")
127
+ .filter((r) => r.state === "claimed" &&
128
+ !this.inflight.has(r.key) &&
129
+ (r.nextAttemptAt === undefined || r.nextAttemptAt <= now))
130
+ .sort((a, b) => a.updatedAt - b.updatedAt);
131
+ for (const record of due) {
132
+ const channel = String(record.channel ?? "");
133
+ const sender = this.senders.get(channel);
134
+ if (!sender)
135
+ continue;
136
+ const item = recordToItem(record);
137
+ const attempts = record.attempts + 1;
138
+ if (this.ttlMs > 0 && now - record.createdAt >= this.ttlMs) {
139
+ this.ledger.put(failedRecord(this.ledger, item, attempts, "expired", new Error("delivery TTL exceeded"), now));
140
+ dead += 1;
141
+ continue;
142
+ }
143
+ this.inflight.add(record.key);
144
+ try {
145
+ await withTimeout(sender(item), this.sendTimeoutMs);
146
+ this.ledger.put(doneRecord(this.ledger, item, now));
147
+ sent += 1;
148
+ }
149
+ catch (err) {
150
+ const errorClass = classifyError(undefined, err);
151
+ const retryable = errorClass !== null && RETRYABLE.has(errorClass) && attempts < this.ledger.maxAttempts;
152
+ if (!retryable) {
153
+ this.ledger.put(failedRecord(this.ledger, item, attempts, errorClass, err, now));
154
+ dead += 1;
155
+ }
156
+ else {
157
+ this.ledger.put(queuedRecord(this.ledger, item, attempts, errorClass, err, now, now + this.backoffFor(attempts)));
158
+ retried += 1;
159
+ }
160
+ }
161
+ finally {
162
+ this.inflight.delete(record.key);
163
+ }
164
+ }
165
+ if (sent + retried + dead > 0)
166
+ this.ledger.flush();
167
+ return { sent, retried, dead };
168
+ }
169
+ /** 启动后台 pump(默认 5s,`unref` 不阻止进程退出)。重复调用无副作用。 */
170
+ start(intervalMs = DEFAULT_PUMP_MS) {
171
+ if (this.timer)
172
+ return;
173
+ const ms = Math.max(500, Math.min(intervalMs, 10 * 60_000));
174
+ this.timer = setInterval(() => void this.pump().catch(() => { }), ms);
175
+ this.timer.unref?.();
176
+ }
177
+ stop() {
178
+ if (!this.timer)
179
+ return;
180
+ clearInterval(this.timer);
181
+ this.timer = null;
182
+ }
183
+ stats(now = this.now()) {
184
+ let queued = 0;
185
+ let due = 0;
186
+ let dead = 0;
187
+ let done = 0;
188
+ for (const r of this.ledger.byDirection("out")) {
189
+ if (r.state === "done") {
190
+ done += 1;
191
+ continue;
192
+ }
193
+ if (this.ledger.isTerminal(r)) {
194
+ dead += 1;
195
+ continue;
196
+ }
197
+ queued += 1;
198
+ if (r.nextAttemptAt === undefined || r.nextAttemptAt <= now)
199
+ due += 1;
200
+ }
201
+ return { queued, due, dead, done };
202
+ }
203
+ /** 排队中的出站消息(排障:为什么用户没收到)。 */
204
+ pending() {
205
+ return this.ledger
206
+ .byDirection("out")
207
+ .filter((r) => r.state === "claimed" && !this.ledger.isTerminal(r))
208
+ .map(recordToItem);
209
+ }
210
+ /** 彻底放弃的出站消息(需要人或上层告知用户)。 */
211
+ dead() {
212
+ return this.ledger
213
+ .byDirection("out")
214
+ .filter((r) => this.ledger.isTerminal(r))
215
+ .map(recordToItem);
216
+ }
217
+ flush() {
218
+ this.ledger.flush();
219
+ }
220
+ dispose() {
221
+ this.stop();
222
+ if (this.ownsLedger)
223
+ this.ledger.dispose();
224
+ else
225
+ this.ledger.flush();
226
+ }
227
+ backoffFor(attempts) {
228
+ if (this.backoffMs.length === 0)
229
+ return 30_000;
230
+ const idx = Math.min(Math.max(0, attempts - 1), this.backoffMs.length - 1);
231
+ return this.backoffMs[idx] ?? 30_000;
232
+ }
233
+ }
234
+ function toItem(channel, key, req, existing, attempts, now) {
235
+ return {
236
+ id: existing?.id ?? key,
237
+ key,
238
+ channel,
239
+ target: req.target,
240
+ payload: req.payload,
241
+ attempts,
242
+ createdAt: existing?.createdAt ?? now,
243
+ };
244
+ }
245
+ function recordToItem(record) {
246
+ return {
247
+ id: record.id,
248
+ key: record.key,
249
+ channel: String(record.channel ?? ""),
250
+ target: record.target,
251
+ payload: record.payload,
252
+ attempts: record.attempts,
253
+ createdAt: record.createdAt,
254
+ ...(record.errorClass ? { errorClass: record.errorClass } : {}),
255
+ ...(record.error ? { error: record.error } : {}),
256
+ };
257
+ }
258
+ function doneRecord(ledger, item, now) {
259
+ const existing = ledger.get(item.key);
260
+ return {
261
+ id: existing?.id ?? item.id,
262
+ key: item.key,
263
+ direction: "out",
264
+ state: "done",
265
+ attempts: item.attempts,
266
+ createdAt: existing?.createdAt ?? item.createdAt,
267
+ updatedAt: now,
268
+ channel: item.channel,
269
+ target: item.target,
270
+ payload: item.payload,
271
+ };
272
+ }
273
+ function queuedRecord(ledger, item, attempts, errorClass, err, now, nextAttemptAt) {
274
+ const existing = ledger.get(item.key);
275
+ return {
276
+ id: existing?.id ?? item.id,
277
+ key: item.key,
278
+ direction: "out",
279
+ state: "claimed",
280
+ attempts,
281
+ createdAt: existing?.createdAt ?? item.createdAt,
282
+ updatedAt: now,
283
+ channel: item.channel,
284
+ target: item.target,
285
+ payload: item.payload,
286
+ nextAttemptAt,
287
+ ...(errorClass ? { errorClass } : {}),
288
+ error: errorText(err),
289
+ };
290
+ }
291
+ function failedRecord(ledger, item, attempts, errorClass, err, now) {
292
+ const existing = ledger.get(item.key);
293
+ return {
294
+ id: existing?.id ?? item.id,
295
+ key: item.key,
296
+ direction: "out",
297
+ state: "failed",
298
+ // 死信需要 attempts >= maxAttempts 才会被 isTerminal 认,这里直接顶到上限。
299
+ attempts: Math.max(attempts, ledger.maxAttempts),
300
+ createdAt: existing?.createdAt ?? item.createdAt,
301
+ updatedAt: now,
302
+ channel: item.channel,
303
+ target: item.target,
304
+ payload: item.payload,
305
+ ...(errorClass ? { errorClass } : {}),
306
+ error: errorText(err),
307
+ };
308
+ }
309
+ function classifyError(req, err) {
310
+ if (req?.classify) {
311
+ try {
312
+ return req.classify(err);
313
+ }
314
+ catch {
315
+ return "unknown";
316
+ }
317
+ }
318
+ const tagged = err;
319
+ const tag = tagged && typeof tagged === "object" ? tagged.deliveryClass : undefined;
320
+ if (tag === "network" || tag === "rate_limited" || tag === "expired" || tag === "auth" || tag === "rejected")
321
+ return tag;
322
+ if (tag === null)
323
+ return null;
324
+ return "unknown";
325
+ }
326
+ function errorText(error) {
327
+ const text = error instanceof Error ? error.message : String(error ?? "");
328
+ return text.slice(0, 500);
329
+ }
330
+ function deliveryError(err, errorClass, expired) {
331
+ const message = expired ? `delivery TTL exceeded: ${errorText(err)}` : errorText(err);
332
+ const out = new Error(message);
333
+ out.deliveryClass = expired
334
+ ? "expired"
335
+ : errorClass;
336
+ out.cause = err;
337
+ return out;
338
+ }
339
+ async function withTimeout(promise, ms) {
340
+ let timer = null;
341
+ try {
342
+ await Promise.race([
343
+ promise,
344
+ new Promise((_, reject) => {
345
+ timer = setTimeout(() => {
346
+ const err = new Error(`delivery send timed out after ${ms}ms`);
347
+ err.deliveryClass = "network";
348
+ reject(err);
349
+ }, ms);
350
+ timer.unref?.();
351
+ }),
352
+ ]);
353
+ }
354
+ finally {
355
+ if (timer)
356
+ clearTimeout(timer);
357
+ }
358
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * 插件入站账本视图(至少一次投递 + 幂等键)
3
+ *
4
+ * 渠道插件(QQ / 微信 / Telegram …)收消息的第一件事是「这条我处理过没有」。以前那是各插件
5
+ * 自己攒的内存 Set(QQ 是 500 条上限,进程重启即失),于是崩溃/重启会重复投递,出问题也查不到
6
+ * 哪条消息卡在哪一步。
7
+ *
8
+ * 语义:
9
+ * - `claim(key)`:首次 → `new`;已 `done` → `duplicate`;仍在处理且未超时 → `duplicate`(防并发双投);
10
+ * 处理中卡死超过 `stallMs`、或失败未到上限 → **允许重投**(`new`,`attempts+1`)。
11
+ * - `complete(key)` / `fail(key)`:把这条交付的状态与 conversationId/runId 记下来,供排障。
12
+ * - `pending()` / `dead()`:卡住的与超过重试上限的死信,运维可读。
13
+ *
14
+ * 存储与出站方向共用 `PluginLedgerStore`(`server/plugin-ledger.ts`)—— 一个账本,两个方向。
15
+ * 边界:`<dataDir>/plugin-inbox/<pluginId>.json`,写入是 debounce 的原子写。
16
+ */
17
+ import { normalizeLedgerKey, PluginLedgerStore } from "./plugin-ledger.js";
18
+ const DEFAULT_STALL_MS = 10 * 60 * 1000;
19
+ export class PluginInbox {
20
+ ledger;
21
+ ownsLedger;
22
+ stallMs;
23
+ constructor(opts) {
24
+ this.ledger = opts.ledger ?? new PluginLedgerStore(opts);
25
+ this.ownsLedger = !opts.ledger;
26
+ this.stallMs = Math.max(1_000, opts.stallMs ?? DEFAULT_STALL_MS);
27
+ }
28
+ get now() {
29
+ return this.ledger.now();
30
+ }
31
+ /**
32
+ * 幂等占位。返回 `new` 表示「这条该你处理」,`duplicate` 表示「别重复处理」。
33
+ * 不会抛错:非法 key、写盘失败都退化成可用结果(宁可重复处理也不要丢消息)。
34
+ */
35
+ claim(key, meta) {
36
+ const now = this.now;
37
+ const k = normalizeLedgerKey(key);
38
+ if (!k) {
39
+ // 没有消息 id 的入站事件无法去重,只能放行。
40
+ return { id: `${this.ledger.pluginId}:`, status: "new", attempts: 1 };
41
+ }
42
+ const existing = this.ledger.get(k);
43
+ if (existing && existing.direction === "in") {
44
+ if (existing.state === "done") {
45
+ return { id: existing.id, status: "duplicate", attempts: existing.attempts, reason: "done" };
46
+ }
47
+ if (existing.state === "failed" && existing.attempts >= this.ledger.maxAttempts) {
48
+ return { id: existing.id, status: "duplicate", attempts: existing.attempts, reason: "dead" };
49
+ }
50
+ const stalled = now - existing.updatedAt >= this.stallMs;
51
+ if (existing.state === "claimed" && !stalled) {
52
+ return { id: existing.id, status: "duplicate", attempts: existing.attempts, reason: "in-flight" };
53
+ }
54
+ existing.state = "claimed";
55
+ existing.attempts += 1;
56
+ existing.updatedAt = now;
57
+ if (meta)
58
+ existing.meta = { ...existing.meta, ...meta };
59
+ delete existing.error;
60
+ this.ledger.put(existing);
61
+ return { id: existing.id, status: "new", attempts: existing.attempts };
62
+ }
63
+ const record = this.ledger.newRecord({
64
+ key: k,
65
+ direction: "in",
66
+ state: "claimed",
67
+ attempts: 1,
68
+ ...(meta ? { record: { meta } } : {}),
69
+ });
70
+ this.ledger.put(record);
71
+ return { id: record.id, status: "new", attempts: 1 };
72
+ }
73
+ complete(key, opts = {}) {
74
+ const k = normalizeLedgerKey(key);
75
+ if (!k)
76
+ return;
77
+ const record = this.ledger.get(k);
78
+ if (!record || record.direction !== "in")
79
+ return;
80
+ record.state = "done";
81
+ record.updatedAt = this.now;
82
+ delete record.error;
83
+ if (opts.conversationId)
84
+ record.conversationId = opts.conversationId;
85
+ if (opts.runId)
86
+ record.runId = opts.runId;
87
+ if (opts.meta)
88
+ record.meta = { ...record.meta, ...opts.meta };
89
+ this.ledger.put(record);
90
+ }
91
+ fail(key, error) {
92
+ const k = normalizeLedgerKey(key);
93
+ if (!k)
94
+ return;
95
+ const record = this.ledger.get(k);
96
+ if (!record || record.direction !== "in")
97
+ return;
98
+ record.state = "failed";
99
+ record.updatedAt = this.now;
100
+ record.error = errorText(error);
101
+ this.ledger.put(record);
102
+ }
103
+ /** 卡在处理中、已经可以重投的记录(重启后第一次 claim 会命中它们)。 */
104
+ pending() {
105
+ return this.ledger
106
+ .byDirection("in")
107
+ .filter((r) => !this.ledger.isTerminal(r) && this.now - r.updatedAt >= this.stallMs)
108
+ .map(snapshotOf);
109
+ }
110
+ /** 超过重试上限的死信:需要人看。 */
111
+ dead() {
112
+ return this.ledger
113
+ .byDirection("in")
114
+ .filter((r) => this.ledger.isTerminal(r) && r.state === "failed")
115
+ .map(snapshotOf);
116
+ }
117
+ snapshot() {
118
+ return this.ledger.byDirection("in").map(snapshotOf);
119
+ }
120
+ flush() {
121
+ this.ledger.flush();
122
+ }
123
+ dispose() {
124
+ if (this.ownsLedger)
125
+ this.ledger.dispose();
126
+ else
127
+ this.ledger.flush();
128
+ }
129
+ }
130
+ function snapshotOf(record) {
131
+ const out = {
132
+ id: record.id,
133
+ key: record.key,
134
+ state: record.state,
135
+ attempts: record.attempts,
136
+ createdAt: record.createdAt,
137
+ updatedAt: record.updatedAt,
138
+ };
139
+ if (record.conversationId)
140
+ out.conversationId = record.conversationId;
141
+ if (record.runId)
142
+ out.runId = record.runId;
143
+ if (record.error)
144
+ out.error = record.error;
145
+ if (record.meta)
146
+ out.meta = record.meta;
147
+ return out;
148
+ }
149
+ function errorText(error) {
150
+ const text = error instanceof Error ? error.message : String(error ?? "");
151
+ return text.slice(0, 500);
152
+ }
@@ -52,6 +52,21 @@ export function buildPluginJobArgs(spec, dataDir, lang) {
52
52
  args.push("--no-build");
53
53
  return { args };
54
54
  }
55
+ /**
56
+ * 安装成功后的启用运算:把插件 id 从 `disabledPlugins` 里摘掉,返回新的禁用列表。
57
+ * 出厂默认设置把一批可选插件写进了禁用清单(`DEFAULT_CLIENT_SETTINGS.disabledPlugins`),
58
+ * 安装若不同步启用,用户拿到的是「装好了但界面上完全找不到」——「安装即启用」由这里兜住。
59
+ * 无需改动(未禁用 / 空 id)时返回 null,调用方据此跳过写盘。
60
+ */
61
+ export function enablePluginAfterInstall(disabledPlugins, pluginId) {
62
+ const id = String(pluginId ?? "").trim();
63
+ if (!id)
64
+ return null;
65
+ const list = disabledPlugins ?? [];
66
+ if (!list.includes(id))
67
+ return null;
68
+ return list.filter((x) => x !== id);
69
+ }
55
70
  export async function inspectInstallSpec(rawSpec, deps) {
56
71
  const local = inspectLocalInstallSpec(rawSpec, deps);
57
72
  const rejectBuiltin = () => ({ ...local, problem: "invalid-spec", detail: builtinModuleError("en") });