@oyasmi/pipiclaw 0.9.5-beta.4 → 0.9.6-beta.1

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 (185) hide show
  1. package/README.en.md +220 -126
  2. package/README.md +217 -123
  3. package/dist/agent/channel-runner.d.ts +1 -1
  4. package/dist/agent/channel-runner.js +1 -1
  5. package/dist/agent/prompt/sections.js +1 -1
  6. package/dist/agent/prompt/types.d.ts +2 -1
  7. package/dist/agent/session/compaction.d.ts +2 -0
  8. package/dist/agent/session/compaction.js +22 -14
  9. package/dist/agent/session/session-host.d.ts +1 -1
  10. package/dist/agent/session/session-host.js +3 -1
  11. package/dist/agent/stop-watchdog.js +5 -1
  12. package/dist/agent/turn/turn-state.d.ts +2 -0
  13. package/dist/agent/turn/turn-state.js +2 -1
  14. package/dist/agent/types.d.ts +3 -1
  15. package/dist/channel/attachments.d.ts +4 -0
  16. package/dist/channel/attachments.js +4 -0
  17. package/dist/channel/store.d.ts +1 -1
  18. package/dist/commands/catalog.js +25 -9
  19. package/dist/commands/router.js +5 -1
  20. package/dist/desk/commands.d.ts +14 -2
  21. package/dist/desk/commands.js +68 -20
  22. package/dist/desk/registry.d.ts +6 -2
  23. package/dist/desk/registry.js +70 -4
  24. package/dist/desk/types.d.ts +17 -0
  25. package/dist/dingtalk/bot.d.ts +1 -1
  26. package/dist/dingtalk/bot.js +4 -3
  27. package/dist/dingtalk/delivery.js +13 -8
  28. package/dist/dingtalk/inbound-media.d.ts +36 -14
  29. package/dist/dingtalk/inbound-media.js +71 -12
  30. package/dist/dingtalk/inbound.d.ts +9 -2
  31. package/dist/dingtalk/inbound.js +18 -2
  32. package/dist/dingtalk/media.d.ts +4 -10
  33. package/dist/dingtalk/media.js +58 -32
  34. package/dist/events/commands.d.ts +2 -0
  35. package/dist/events/commands.js +13 -8
  36. package/dist/events/history.d.ts +9 -0
  37. package/dist/events/history.js +66 -0
  38. package/dist/events/parse.js +7 -3
  39. package/dist/events/types.d.ts +3 -0
  40. package/dist/events/watcher.d.ts +3 -7
  41. package/dist/events/watcher.js +51 -56
  42. package/dist/jobs/kill.d.ts +23 -0
  43. package/dist/jobs/kill.js +65 -0
  44. package/dist/jobs/manager.d.ts +19 -18
  45. package/dist/jobs/manager.js +36 -103
  46. package/dist/memory/reflect.js +23 -3
  47. package/dist/memory/session-corpus.d.ts +1 -1
  48. package/dist/memory/session-corpus.js +70 -1
  49. package/dist/memory/session-search.js +13 -11
  50. package/dist/memory/store.d.ts +2 -0
  51. package/dist/memory/store.js +19 -9
  52. package/dist/playbooks/agent-delegation.md +34 -44
  53. package/dist/playbooks/memory-and-learning.md +4 -4
  54. package/dist/playbooks/runtime-orientation.md +1 -1
  55. package/dist/playbooks/task-lead.md +48 -64
  56. package/dist/runtime/bootstrap.d.ts +6 -0
  57. package/dist/runtime/bootstrap.js +11 -7
  58. package/dist/runtime/desk-runtime.d.ts +8 -2
  59. package/dist/runtime/desk-runtime.js +35 -4
  60. package/dist/runtime/durable-dispatch.d.ts +14 -2
  61. package/dist/runtime/durable-dispatch.js +207 -65
  62. package/dist/runtime/ingress-busy.js +17 -8
  63. package/dist/runtime/ingress-deps.d.ts +4 -1
  64. package/dist/runtime/ingress.js +6 -1
  65. package/dist/runtime/request-execution.js +7 -6
  66. package/dist/runtime/shutdown.d.ts +1 -0
  67. package/dist/runtime/shutdown.js +87 -35
  68. package/dist/runtime/task-control.d.ts +1 -0
  69. package/dist/runtime/task-control.js +25 -2
  70. package/dist/runtime/task-lane.d.ts +1 -0
  71. package/dist/runtime/task-lane.js +21 -6
  72. package/dist/runtime/task-spawn.d.ts +3 -2
  73. package/dist/runtime/task-spawn.js +3 -2
  74. package/dist/runtime/task-step.js +11 -2
  75. package/dist/runtime/turn-run.js +103 -66
  76. package/dist/security/command-guard.d.ts +1 -1
  77. package/dist/security/command-guard.js +237 -314
  78. package/dist/security/path-guard.js +48 -7
  79. package/dist/security/shell-parse.d.ts +10 -0
  80. package/dist/security/shell-parse.js +224 -0
  81. package/dist/security/types.d.ts +2 -0
  82. package/dist/subagents/commands.d.ts +1 -1
  83. package/dist/subagents/detached-discovery.d.ts +1 -1
  84. package/dist/subagents/discovery.d.ts +18 -199
  85. package/dist/subagents/discovery.js +35 -289
  86. package/dist/subagents/dispatch.d.ts +1 -2
  87. package/dist/subagents/dispatch.js +39 -20
  88. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  89. package/dist/subagents/external/antigravity-cli.js +517 -0
  90. package/dist/subagents/external/claude-code.js +8 -17
  91. package/dist/subagents/external/codex-cli.js +8 -18
  92. package/dist/subagents/external/cursor-cli.js +34 -31
  93. package/dist/subagents/external/dispatch.d.ts +21 -7
  94. package/dist/subagents/external/dispatch.js +139 -11
  95. package/dist/subagents/external/exec.js +3 -0
  96. package/dist/subagents/external/harness.d.ts +57 -33
  97. package/dist/subagents/external/harness.js +69 -40
  98. package/dist/subagents/external/reconciliation.js +1 -0
  99. package/dist/subagents/external/registry.js +4 -1
  100. package/dist/subagents/external/role-warnings.d.ts +4 -13
  101. package/dist/subagents/external/role-warnings.js +4 -28
  102. package/dist/subagents/external/run.d.ts +1 -2
  103. package/dist/subagents/external/run.js +11 -11
  104. package/dist/subagents/external/settlement.d.ts +2 -0
  105. package/dist/subagents/external/settlement.js +8 -2
  106. package/dist/subagents/format.d.ts +1 -1
  107. package/dist/subagents/format.js +1 -1
  108. package/dist/subagents/internal/outcome.d.ts +1 -2
  109. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  110. package/dist/subagents/internal/provider-retry.js +1 -1
  111. package/dist/subagents/internal/run.d.ts +1 -2
  112. package/dist/subagents/internal/state.d.ts +1 -2
  113. package/dist/subagents/internal/worker.d.ts +1 -2
  114. package/dist/subagents/internal/worker.js +3 -1
  115. package/dist/subagents/resolve.d.ts +56 -0
  116. package/dist/subagents/resolve.js +202 -0
  117. package/dist/subagents/result.d.ts +1 -2
  118. package/dist/subagents/result.js +7 -3
  119. package/dist/subagents/run-record.d.ts +33 -2
  120. package/dist/subagents/run-record.js +2 -0
  121. package/dist/subagents/runs.d.ts +2 -24
  122. package/dist/subagents/runs.js +6 -0
  123. package/dist/subagents/task-envelope.d.ts +1 -2
  124. package/dist/subagents/task-envelope.js +8 -4
  125. package/dist/subagents/types.d.ts +93 -4
  126. package/dist/subagents/types.js +16 -1
  127. package/dist/subagents/workspace-lease.d.ts +11 -21
  128. package/dist/subagents/workspace-lease.js +48 -21
  129. package/dist/subagents/worktree.d.ts +10 -0
  130. package/dist/subagents/worktree.js +77 -0
  131. package/dist/tasks/archive.js +4 -0
  132. package/dist/tasks/commands.d.ts +3 -0
  133. package/dist/tasks/commands.js +16 -2
  134. package/dist/tasks/control.d.ts +2 -0
  135. package/dist/tasks/delivery.d.ts +2 -0
  136. package/dist/tasks/delivery.js +141 -21
  137. package/dist/tasks/loop-log.d.ts +2 -0
  138. package/dist/tasks/loop-log.js +9 -0
  139. package/dist/tools/bash.js +2 -0
  140. package/dist/tools/contract/presentation.js +3 -4
  141. package/dist/tools/event-manage.d.ts +2 -0
  142. package/dist/tools/event-manage.js +20 -2
  143. package/dist/tools/index.d.ts +2 -1
  144. package/dist/tools/index.js +2 -0
  145. package/dist/tools/registry.js +3 -1
  146. package/dist/tools/send-media.js +9 -5
  147. package/dist/tools/session-search.js +1 -1
  148. package/dist/tools/subagent-manage.d.ts +1 -1
  149. package/dist/tools/subagent-manage.js +15 -149
  150. package/dist/tools/subagent.d.ts +2 -0
  151. package/dist/tools/subagent.js +6 -1
  152. package/dist/tools/task-manage/factory.js +2 -2
  153. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  154. package/dist/tools/task-manage/lifecycle.js +49 -9
  155. package/dist/tools/task-manage/schema.d.ts +4 -1
  156. package/dist/tools/task-manage/schema.js +4 -1
  157. package/dist/tools/task-manage/types.d.ts +4 -1
  158. package/dist/tui/cli.d.ts +1 -6
  159. package/dist/tui/cli.js +29 -3
  160. package/dist/tui/client.d.ts +2 -0
  161. package/dist/tui/client.js +13 -4
  162. package/dist/usage/ledger.d.ts +1 -1
  163. package/dist/usage/render.js +1 -1
  164. package/examples/sub-agents/README.md +39 -73
  165. package/examples/sub-agents/agents/agy-main.md +23 -0
  166. package/examples/sub-agents/agents/claude-high.md +9 -9
  167. package/examples/sub-agents/agents/claude-main.md +9 -9
  168. package/examples/sub-agents/agents/codex-flash.md +9 -9
  169. package/examples/sub-agents/agents/codex-high.md +9 -9
  170. package/examples/sub-agents/agents/codex-main.md +9 -9
  171. package/examples/sub-agents/agents/codex-review.md +9 -9
  172. package/examples/sub-agents/agents/cursor-high.md +9 -9
  173. package/examples/sub-agents/agents/cursor-main.md +9 -9
  174. package/examples/sub-agents/agents/glm-flash.md +9 -9
  175. package/examples/sub-agents/agents/glm-high.md +9 -9
  176. package/package.json +8 -8
  177. package/examples/sub-agents/agents/scout.md +0 -30
  178. package/examples/sub-agents/roles/builder-hard.md +0 -34
  179. package/examples/sub-agents/roles/builder.md +0 -34
  180. package/examples/sub-agents/roles/explorer.md +0 -39
  181. package/examples/sub-agents/roles/git-committer.md +0 -43
  182. package/examples/sub-agents/roles/planner.md +0 -33
  183. package/examples/sub-agents/roles/reviewer.md +0 -33
  184. package/examples/sub-agents/roles/verifier.md +0 -35
  185. package/examples/sub-agents/roles/worker.md +0 -34
@@ -107,7 +107,7 @@ class ChannelDeliveryController {
107
107
  await this.deliverCommentary(event.text, event.level);
108
108
  return;
109
109
  case "answer":
110
- await this.deliverAnswer(event.text);
110
+ await this.deliverAnswer(event.text, event.title);
111
111
  return;
112
112
  case "compaction":
113
113
  if (event.phase === "start")
@@ -138,13 +138,13 @@ class ChannelDeliveryController {
138
138
  return;
139
139
  }
140
140
  }
141
- async deliverAnswer(text) {
141
+ async deliverAnswer(text, title) {
142
142
  this.lastAnswer = text;
143
143
  if (this.bot.finalDelivery === "card") {
144
- await this.replaceWithFinal(text);
144
+ await this.replaceWithFinal(text, true);
145
145
  }
146
146
  else {
147
- await this.sendFinal(text, true);
147
+ await this.sendFinal(text, true, title);
148
148
  }
149
149
  }
150
150
  /** A standalone side message: not part of the progress, sent even when progress is off. */
@@ -187,7 +187,7 @@ class ChannelDeliveryController {
187
187
  case "completed":
188
188
  if (this.lastAnswer && !this.finalResponseDelivered) {
189
189
  try {
190
- await this.replaceWithFinal(this.lastAnswer);
190
+ await this.replaceWithFinal(this.lastAnswer, true);
191
191
  }
192
192
  catch (err) {
193
193
  log.logWarn("delivery.final_reply.failed", "Final reply replacement failed", {
@@ -262,7 +262,7 @@ class ChannelDeliveryController {
262
262
  }
263
263
  return true;
264
264
  }
265
- async replaceWithFinal(text) {
265
+ async replaceWithFinal(text, shouldLog = false) {
266
266
  if (this.closed || this.finalResponseDelivered || !this.isCurrent || !text.trim())
267
267
  return;
268
268
  this.ending = true;
@@ -270,8 +270,13 @@ class ChannelDeliveryController {
270
270
  this.mode = "finalize-with-fallback";
271
271
  this.bumpRevision(true);
272
272
  await this.flush();
273
- if (!this.finalResponseDelivered && this.isCurrent) {
274
- throw new Error("最终答复发送失败,请稍后重试。");
273
+ if (!this.finalResponseDelivered) {
274
+ if (this.isCurrent)
275
+ throw new Error("最终答复发送失败,请稍后重试。");
276
+ return;
277
+ }
278
+ if (shouldLog) {
279
+ this.archiveBotResponse(text);
275
280
  }
276
281
  }
277
282
  async silence() {
@@ -1,44 +1,66 @@
1
1
  /**
2
- * Pure parsing of DingTalk inbound image attachments (spec 049).
2
+ * Pure parsing of DingTalk inbound messages and attachments (spec 049 + audio/file/reply).
3
3
  *
4
4
  * Kept separate from `dingtalk.ts` — which owns the network calls (`downloadMessageFile`) and
5
5
  * the per-channel serialization of the download — so the message-shape parsing rules can be unit tested without a `DingTalkBot` instance or any I/O.
6
6
  */
7
+ export interface InboundQuotedMessage {
8
+ msgType?: string;
9
+ content?: {
10
+ text?: string;
11
+ title?: string;
12
+ recognition?: string;
13
+ fileName?: string;
14
+ richText?: Array<Record<string, string>>;
15
+ };
16
+ }
7
17
  /** Structural subset of the raw DingTalk callback payload this module reads. */
8
18
  export interface InboundMessagePayload {
9
19
  msgtype?: string;
10
20
  text?: {
11
21
  content?: string;
22
+ isReplyMsg?: boolean;
23
+ repliedMsg?: InboundQuotedMessage;
12
24
  };
25
+ repliedMsg?: InboundQuotedMessage;
13
26
  content?: {
14
27
  richText?: Array<Record<string, string>>;
15
- /** Present on a `picture` message; the credential `robot/messageFiles/download` needs. */
28
+ /** Present on `picture`, `file` and `audio` messages; the credential `robot/messageFiles/download` needs. */
16
29
  downloadCode?: string;
30
+ /** Present on `audio` messages when DingTalk Stream ASR transcribed the voice clip. */
31
+ recognition?: string;
32
+ audioType?: string;
33
+ /** Present on `file` messages. */
34
+ fileName?: string;
17
35
  };
18
36
  }
37
+ export interface InboundFileDescriptor {
38
+ downloadCode: string;
39
+ fileName: string;
40
+ }
19
41
  export interface ParsedInboundMessage {
20
42
  /**
21
- * User text with `[图片N]` markers inserted at each image's position in a richText mix, or a
22
- * synthetic `[图片1]` marker for a text-less `picture` message. Empty when the message carries
23
- * neither text nor an image — the caller still drops that case.
43
+ * User text with `[图片N]` / `[文件N]` markers inserted, `[语音转写]` for ASR audio, and optional
44
+ * `[引用消息:...]` prefix when replying to an earlier message. Empty when the message carries
45
+ * neither text nor an attachment — the caller drops or hints on that case.
24
46
  */
25
47
  text: string;
26
48
  /** In the same order as the `[图片N]` markers in `text`, one entry per image. */
27
49
  downloadCodes: string[];
50
+ /** In the same order as the `[文件N]` markers in `text`; omitted when empty. */
51
+ files?: InboundFileDescriptor[];
28
52
  }
29
53
  /** Mirrors `MEDIA_UPLOAD_TIMEOUT_MS`: a multi-MB download over a slow link needs more than the
30
54
  * 15s default HTTP timeout. */
31
55
  export declare const MEDIA_DOWNLOAD_TIMEOUT_MS = 60000;
32
56
  /**
33
- * Parse one raw DingTalk callback payload into text + ordered image credentials.
57
+ * Parse one raw DingTalk callback payload into text + ordered attachment credentials.
34
58
  *
35
- * - `text` messages: unchanged, no images.
36
- * - `picture` messages: carry no text of their own; a synthetic `[图片1]` marker stands in so
37
- * the turn never becomes a genuinely empty message (spec 049 D4 — `handleBusyMessage` rejects
38
- * those, and the runtime warns and drops a truly empty message outright).
39
- * - `richText` messages: text and image credentials interleave in payload order; each image's
40
- * marker is inserted at its position in the text stream so "this picture" / "the one above" in
41
- * a follow-up still resolves to the right attachment (D5), even though the SDK's `prompt()`
42
- * itself appends every image after all text once the turn is actually sent.
59
+ * - `text` messages: text content (with `[引用消息:...]` when replying to a prior message).
60
+ * - `audio` messages: uses DingTalk's built-in `content.recognition` ASR transcript when present;
61
+ * falls back to downloading the voice file via `downloadCode` when ASR is empty.
62
+ * - `file` messages: synthetic `[文件1]` marker + `{ downloadCode, fileName }` descriptor.
63
+ * - `picture` messages: synthetic `[图片1]` marker + `downloadCode`.
64
+ * - `richText` messages: text and image credentials interleave in payload order.
43
65
  */
44
66
  export declare function parseInboundMessage(data: InboundMessagePayload): ParsedInboundMessage;
@@ -1,25 +1,84 @@
1
1
  /** Mirrors `MEDIA_UPLOAD_TIMEOUT_MS`: a multi-MB download over a slow link needs more than the
2
2
  * 15s default HTTP timeout. */
3
3
  export const MEDIA_DOWNLOAD_TIMEOUT_MS = 60_000;
4
+ const MAX_QUOTED_CHARS = 300;
5
+ function extractQuotedSummary(replied) {
6
+ if (!replied?.content)
7
+ return "";
8
+ const { content, msgType } = replied;
9
+ if (typeof content.text === "string" && content.text.trim()) {
10
+ return content.text.trim();
11
+ }
12
+ if (Array.isArray(content.richText)) {
13
+ const rich = content.richText
14
+ .map((item) => item.text || (item.downloadCode ? "[图片]" : ""))
15
+ .join("")
16
+ .trim();
17
+ if (rich)
18
+ return rich;
19
+ }
20
+ if (typeof content.recognition === "string" && content.recognition.trim()) {
21
+ return `[语音转写] ${content.recognition.trim()}`;
22
+ }
23
+ if (typeof content.title === "string" && content.title.trim()) {
24
+ return content.title.trim();
25
+ }
26
+ if (typeof content.fileName === "string" && content.fileName.trim()) {
27
+ return `[文件: ${content.fileName.trim()}]`;
28
+ }
29
+ if (msgType === "picture")
30
+ return "[图片]";
31
+ return "";
32
+ }
33
+ function withReplyContext(body, data) {
34
+ if (!body)
35
+ return "";
36
+ const rawQuote = extractQuotedSummary(data.text?.repliedMsg ?? data.repliedMsg);
37
+ if (!rawQuote)
38
+ return body;
39
+ const normalized = rawQuote.replace(/\s+/g, " ").trim();
40
+ const clipped = normalized.length > MAX_QUOTED_CHARS ? `${normalized.slice(0, MAX_QUOTED_CHARS)}…` : normalized;
41
+ return `[引用消息:${clipped}]\n${body}`;
42
+ }
4
43
  /**
5
- * Parse one raw DingTalk callback payload into text + ordered image credentials.
44
+ * Parse one raw DingTalk callback payload into text + ordered attachment credentials.
6
45
  *
7
- * - `text` messages: unchanged, no images.
8
- * - `picture` messages: carry no text of their own; a synthetic `[图片1]` marker stands in so
9
- * the turn never becomes a genuinely empty message (spec 049 D4 — `handleBusyMessage` rejects
10
- * those, and the runtime warns and drops a truly empty message outright).
11
- * - `richText` messages: text and image credentials interleave in payload order; each image's
12
- * marker is inserted at its position in the text stream so "this picture" / "the one above" in
13
- * a follow-up still resolves to the right attachment (D5), even though the SDK's `prompt()`
14
- * itself appends every image after all text once the turn is actually sent.
46
+ * - `text` messages: text content (with `[引用消息:...]` when replying to a prior message).
47
+ * - `audio` messages: uses DingTalk's built-in `content.recognition` ASR transcript when present;
48
+ * falls back to downloading the voice file via `downloadCode` when ASR is empty.
49
+ * - `file` messages: synthetic `[文件1]` marker + `{ downloadCode, fileName }` descriptor.
50
+ * - `picture` messages: synthetic `[图片1]` marker + `downloadCode`.
51
+ * - `richText` messages: text and image credentials interleave in payload order.
15
52
  */
16
53
  export function parseInboundMessage(data) {
17
54
  const textContent = (data.text?.content || "").trim();
18
55
  if (textContent) {
19
- return { text: textContent, downloadCodes: [] };
56
+ return { text: withReplyContext(textContent, data), downloadCodes: [] };
57
+ }
58
+ if (data.msgtype === "audio") {
59
+ const recognition = data.content?.recognition?.trim();
60
+ if (recognition) {
61
+ return { text: withReplyContext(`[语音转写] ${recognition}`, data), downloadCodes: [] };
62
+ }
63
+ if (data.content?.downloadCode) {
64
+ const ext = (data.content.audioType || "amr").replace(/[^a-z0-9]/gi, "").toLowerCase() || "amr";
65
+ return {
66
+ text: withReplyContext("[文件1]", data),
67
+ downloadCodes: [],
68
+ files: [{ downloadCode: data.content.downloadCode, fileName: `voice.${ext}` }],
69
+ };
70
+ }
71
+ }
72
+ if (data.msgtype === "file" && data.content?.downloadCode) {
73
+ const fileName = data.content.fileName?.trim() || "attachment.bin";
74
+ return {
75
+ text: withReplyContext("[文件1]", data),
76
+ downloadCodes: [],
77
+ files: [{ downloadCode: data.content.downloadCode, fileName }],
78
+ };
20
79
  }
21
80
  if (data.msgtype === "picture" && data.content?.downloadCode) {
22
- return { text: "[图片1]", downloadCodes: [data.content.downloadCode] };
81
+ return { text: withReplyContext("[图片1]", data), downloadCodes: [data.content.downloadCode] };
23
82
  }
24
83
  if (data.content?.richText) {
25
84
  const parts = [];
@@ -35,7 +94,7 @@ export function parseInboundMessage(data) {
35
94
  }
36
95
  const joined = parts.join("").trim();
37
96
  if (joined) {
38
- return { text: joined, downloadCodes };
97
+ return { text: withReplyContext(joined, data), downloadCodes };
39
98
  }
40
99
  }
41
100
  return { text: "", downloadCodes: [] };
@@ -8,7 +8,7 @@ import type { DWClientDownStream } from "dingtalk-stream";
8
8
  import type { InboundAttachment, Ingress } from "../channel/ingress.js";
9
9
  import type { DingTalkConfig } from "./config.js";
10
10
  import type { ConversationMetaStore } from "./conversation-meta.js";
11
- import { type ParsedInboundMessage } from "./inbound-media.js";
11
+ import { type InboundQuotedMessage, type ParsedInboundMessage } from "./inbound-media.js";
12
12
  interface DingTalkIncomingMessage {
13
13
  msgId?: string;
14
14
  senderStaffId?: string;
@@ -21,11 +21,17 @@ interface DingTalkIncomingMessage {
21
21
  msgtype?: string;
22
22
  text?: {
23
23
  content?: string;
24
+ isReplyMsg?: boolean;
25
+ repliedMsg?: InboundQuotedMessage;
24
26
  };
27
+ repliedMsg?: InboundQuotedMessage;
25
28
  content?: {
26
29
  richText?: Array<Record<string, string>>;
27
- /** Present on a `picture` message; see `inbound-media.ts`'s `parseInboundMessage`. */
30
+ /** Present on `picture` / `file` / `audio` messages; see `inbound-media.ts`'s `parseInboundMessage`. */
28
31
  downloadCode?: string;
32
+ recognition?: string;
33
+ audioType?: string;
34
+ fileName?: string;
29
35
  };
30
36
  }
31
37
  /** What the DingTalk side needs from the runtime: the one door inbound messages go through. */
@@ -41,6 +47,7 @@ export interface InboundMessagesDeps {
41
47
  text: string;
42
48
  attachments: InboundAttachment[];
43
49
  }>;
50
+ sendPlain?: (channelId: string, text: string) => Promise<boolean>;
44
51
  }
45
52
  export declare class InboundMessages {
46
53
  private deps;
@@ -4,6 +4,7 @@ import { errorMessage } from "../shared/text-utils.js";
4
4
  import { isRecord } from "../shared/type-guards.js";
5
5
  import { dingtalkDmChannelId, dingtalkGroupChannelId } from "./channel-ids.js";
6
6
  import { parseInboundMessage } from "./inbound-media.js";
7
+ const UNSUPPORTED_HINT_MSGTYPES = new Set(["video", "chatRecord", "interactiveCard"]);
7
8
  export class InboundMessages {
8
9
  constructor(deps) {
9
10
  this.deps = deps;
@@ -74,8 +75,10 @@ export class InboundMessages {
74
75
  const senderName = data.senderNick || "Unknown";
75
76
  const conversationId = data.conversationId || "";
76
77
  const conversationType = data.conversationType || "1";
77
- if (!parsed.text && parsed.downloadCodes.length === 0) {
78
- const msgtype = typeof data.msgtype === "string" ? data.msgtype : "unknown";
78
+ const hasMedia = parsed.downloadCodes.length > 0 || (parsed.files?.length ?? 0) > 0;
79
+ const msgtype = typeof data.msgtype === "string" ? data.msgtype : "unknown";
80
+ const isUnsupportedMedia = !parsed.text && !hasMedia && UNSUPPORTED_HINT_MSGTYPES.has(msgtype);
81
+ if (!parsed.text && !hasMedia && !isUnsupportedMedia) {
79
82
  log.logWarn("dingtalk.message.empty", "Empty message ignored", { fields: { msgtype } });
80
83
  return;
81
84
  }
@@ -89,6 +92,19 @@ export class InboundMessages {
89
92
  }
90
93
  // Determine channel ID
91
94
  const channelId = conversationType === "2" ? dingtalkGroupChannelId(conversationId) : dingtalkDmChannelId(senderId);
95
+ if (isUnsupportedMedia) {
96
+ log.logWarn("dingtalk.message.unsupported", "Unsupported message type rejected", {
97
+ channelId,
98
+ fields: { msgtype },
99
+ });
100
+ this.deps.conversations.set(channelId, {
101
+ conversationId,
102
+ conversationType,
103
+ senderId,
104
+ });
105
+ await this.deps.sendPlain?.(channelId, `⚠️ 暂不支持直接解析 \`${msgtype}\` 类型消息,请改发文字、语音、图片或文件附件。`);
106
+ return;
107
+ }
92
108
  // Parsing above is free; downloading image attachments below is a real network round-trip.
93
109
  // Serialize the whole "download attachments → hand over" unit per channel (spec 049 D3):
94
110
  // without this, a message needing a download can be overtaken, in delivery order, by a later
@@ -12,7 +12,7 @@ export interface DingTalkMediaDeps {
12
12
  * The inbound file fetch used while resolving attachments. The bot supplies its own overridable
13
13
  * `downloadMessageFile`, so the deterministic e2e harness can stub the network out.
14
14
  */
15
- downloadMessageFile: (downloadCode: string) => Promise<{
15
+ downloadMessageFile: (downloadCode: string, maxBytes?: number) => Promise<{
16
16
  data: Buffer;
17
17
  } | null>;
18
18
  }
@@ -44,18 +44,12 @@ export declare class DingTalkMedia {
44
44
  * queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
45
45
  * already expired.
46
46
  */
47
- downloadMessageFile(downloadCode: string): Promise<{
47
+ downloadMessageFile(downloadCode: string, maxBytes?: number): Promise<{
48
48
  data: Buffer;
49
49
  } | null>;
50
50
  /**
51
- * Download one parsed message's images and say, in the text, what became of the ones that did
52
- * not make it (spec 049 D8): a failed download, an oversized file, or more images than
53
- * `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one image never drops the rest of the
54
- * message — only that one `[图片N]` marker changes. The bytes of the others go to the runtime as
55
- * attachments (it persists them under the bound desk and settles the remaining markers).
56
- *
57
- * No-op (no network call at all) when the message carries no image credentials, so a plain
58
- * text message never pays for this method's existence.
51
+ * Download one parsed message's images/files and say, in the text, what became of any that did
52
+ * not make it (spec 049 D8). No-op when the message carries no attachment credentials.
59
53
  */
60
54
  collectInboundAttachments(parsed: ParsedInboundMessage): Promise<{
61
55
  text: string;
@@ -3,7 +3,7 @@
3
3
  * per-message attachment collection built on it (spec 049).
4
4
  */
5
5
  import axios from "axios";
6
- import { MAX_INBOUND_IMAGE_BYTES, MAX_INBOUND_IMAGES_PER_MESSAGE } from "../channel/attachments.js";
6
+ import { MAX_INBOUND_FILE_BYTES, MAX_INBOUND_FILES_PER_MESSAGE, MAX_INBOUND_IMAGE_BYTES, MAX_INBOUND_IMAGES_PER_MESSAGE, } from "../channel/attachments.js";
7
7
  import * as log from "../log.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { isRecord } from "../shared/type-guards.js";
@@ -125,7 +125,7 @@ export class DingTalkMedia {
125
125
  * queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
126
126
  * already expired.
127
127
  */
128
- async downloadMessageFile(downloadCode) {
128
+ async downloadMessageFile(downloadCode, maxBytes = MAX_INBOUND_IMAGE_BYTES) {
129
129
  const token = await this.deps.getAccessToken();
130
130
  if (!token)
131
131
  return null;
@@ -142,7 +142,7 @@ export class DingTalkMedia {
142
142
  const fileResp = await http.get(downloadUrl, {
143
143
  responseType: "arraybuffer",
144
144
  // Reject an oversized body before it fully lands in memory rather than after.
145
- maxContentLength: MAX_INBOUND_IMAGE_BYTES,
145
+ maxContentLength: maxBytes,
146
146
  timeout: MEDIA_DOWNLOAD_TIMEOUT_MS,
147
147
  });
148
148
  return { data: Buffer.from(fileResp.data) };
@@ -161,41 +161,67 @@ export class DingTalkMedia {
161
161
  }
162
162
  }
163
163
  /**
164
- * Download one parsed message's images and say, in the text, what became of the ones that did
165
- * not make it (spec 049 D8): a failed download, an oversized file, or more images than
166
- * `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one image never drops the rest of the
167
- * message — only that one `[图片N]` marker changes. The bytes of the others go to the runtime as
168
- * attachments (it persists them under the bound desk and settles the remaining markers).
169
- *
170
- * No-op (no network call at all) when the message carries no image credentials, so a plain
171
- * text message never pays for this method's existence.
164
+ * Download one parsed message's images/files and say, in the text, what became of any that did
165
+ * not make it (spec 049 D8). No-op when the message carries no attachment credentials.
172
166
  */
173
167
  async collectInboundAttachments(parsed) {
174
- if (parsed.downloadCodes.length === 0) {
168
+ const files = parsed.files ?? [];
169
+ if (parsed.downloadCodes.length === 0 && files.length === 0) {
175
170
  return { text: parsed.text, attachments: [] };
176
171
  }
177
172
  let text = parsed.text;
178
- const attachments = [];
179
- const replaceMarker = (index, replacement) => {
173
+ const imageAttachments = [];
174
+ const fileAttachments = [];
175
+ const replaceImageMarker = (index, replacement) => {
180
176
  text = text.replace(`[图片${index + 1}]`, replacement);
181
177
  };
182
- await Promise.all(parsed.downloadCodes.map(async (downloadCode, index) => {
183
- const marker = index + 1;
184
- if (index >= MAX_INBOUND_IMAGES_PER_MESSAGE) {
185
- replaceMarker(index, `[图片${marker}:超出单条消息图片数量上限,已丢弃]`);
186
- return;
187
- }
188
- const downloaded = await this.deps.downloadMessageFile(downloadCode);
189
- if (!downloaded) {
190
- replaceMarker(index, `[图片${marker}:接收失败]`);
191
- return;
192
- }
193
- if (downloaded.data.byteLength > MAX_INBOUND_IMAGE_BYTES) {
194
- replaceMarker(index, `[图片${marker}:文件过大(${formatSize(downloaded.data.byteLength)}),已丢弃]`);
195
- return;
196
- }
197
- attachments[index] = { kind: "image", index: marker, data: downloaded.data };
198
- }));
199
- return { text, attachments: attachments.filter((attachment) => !!attachment) };
178
+ const replaceFileMarker = (index, replacement) => {
179
+ text = text.replace(`[文件${index + 1}]`, replacement);
180
+ };
181
+ await Promise.all([
182
+ ...parsed.downloadCodes.map(async (downloadCode, index) => {
183
+ const marker = index + 1;
184
+ if (index >= MAX_INBOUND_IMAGES_PER_MESSAGE) {
185
+ replaceImageMarker(index, `[图片${marker}:超出单条消息图片数量上限,已丢弃]`);
186
+ return;
187
+ }
188
+ const downloaded = await this.deps.downloadMessageFile(downloadCode, MAX_INBOUND_IMAGE_BYTES);
189
+ if (!downloaded) {
190
+ replaceImageMarker(index, `[图片${marker}:接收失败]`);
191
+ return;
192
+ }
193
+ if (downloaded.data.byteLength > MAX_INBOUND_IMAGE_BYTES) {
194
+ replaceImageMarker(index, `[图片${marker}:文件过大(${formatSize(downloaded.data.byteLength)}),已丢弃]`);
195
+ return;
196
+ }
197
+ imageAttachments[index] = { kind: "image", index: marker, data: downloaded.data };
198
+ }),
199
+ ...files.map(async (file, index) => {
200
+ const marker = index + 1;
201
+ if (index >= MAX_INBOUND_FILES_PER_MESSAGE) {
202
+ replaceFileMarker(index, `[文件${marker}:超出单条消息附件数量上限,已丢弃]`);
203
+ return;
204
+ }
205
+ const downloaded = await this.deps.downloadMessageFile(file.downloadCode, MAX_INBOUND_FILE_BYTES);
206
+ if (!downloaded) {
207
+ replaceFileMarker(index, `[文件${marker}(${file.fileName}):接收失败]`);
208
+ return;
209
+ }
210
+ if (downloaded.data.byteLength > MAX_INBOUND_FILE_BYTES) {
211
+ replaceFileMarker(index, `[文件${marker}(${file.fileName}):文件过大(${formatSize(downloaded.data.byteLength)}),已丢弃]`);
212
+ return;
213
+ }
214
+ fileAttachments[index] = {
215
+ kind: "file",
216
+ index: marker,
217
+ data: downloaded.data,
218
+ fileName: file.fileName,
219
+ };
220
+ }),
221
+ ]);
222
+ return {
223
+ text,
224
+ attachments: [...imageAttachments, ...fileAttachments].filter((attachment) => !!attachment),
225
+ };
200
226
  }
201
227
  }
@@ -1,10 +1,12 @@
1
1
  import type { ChannelDescription } from "../channel/channel-id.js";
2
+ import type { SecurityConfig } from "../security/types.js";
2
3
  export interface HandleEventsCommandOptions {
3
4
  args: string;
4
5
  /** The asking channel's desk: its `events/` and its history records are the whole scope. */
5
6
  desk: string;
6
7
  deskDir: string;
7
8
  historyPath: string;
9
+ commandGuardConfig?: SecurityConfig["commandGuard"];
8
10
  /** Names a delivery channel and says whether it is still bound to this desk. */
9
11
  describeChannel: (channelId: string) => ChannelDescription;
10
12
  }
@@ -9,6 +9,7 @@ import { renderSubcommandUsage } from "../commands/catalog.js";
9
9
  import { capReply } from "../commands/reply-limits.js";
10
10
  import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
11
11
  import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
12
+ import { readEventHistoryLines } from "./history.js";
12
13
  import { describeEventPayload, parseScheduledEventContent } from "./parse.js";
13
14
  import { EventDefinitionError, validateScheduledEvent } from "./validation.js";
14
15
  const EVENT_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
@@ -116,8 +117,14 @@ async function listEvents(options) {
116
117
  const event = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename);
117
118
  // The same definition rules the watcher applies, so "listed as fine" means "will run".
118
119
  // The lead-time rule is creation-only (an overdue one-shot is a legitimate recovery).
119
- validateScheduledEvent(event, { enforceOneShotLead: false });
120
- blocks.push(formatEventSummary(name, event, options.describeChannel));
120
+ validateScheduledEvent(event, {
121
+ enforceOneShotLead: false,
122
+ commandGuardConfig: options.commandGuardConfig,
123
+ });
124
+ const summary = formatEventSummary(name, event, options.describeChannel);
125
+ blocks.push(existsSync(`${eventPath}.error.txt`)
126
+ ? `${summary}\n- ⚠️ 最近加载或触发失败,用 \`/events history ${name}\` 查看`
127
+ : summary);
121
128
  }
122
129
  catch (error) {
123
130
  blocks.push(`**${name}**\n- ⚠️ 无效:${describeEventProblem(error, name)}`);
@@ -170,6 +177,7 @@ async function deleteEvent(options, name) {
170
177
  // Unparseable content is still safe to delete; just skip the summary.
171
178
  }
172
179
  await unlink(eventPath);
180
+ await unlink(`${eventPath}.error.txt`).catch(() => undefined);
173
181
  return summary ? `已删除事件:\n\n${summary}` : `已删除事件 \`${eventName}\`。`;
174
182
  }
175
183
  function parseHistoryLine(line) {
@@ -225,13 +233,10 @@ async function showHistory(options, name) {
225
233
  const empty = eventName
226
234
  ? `暂无事件 \`${eventName}\` 的触发记录。\n事件触发后会记录在这里。`
227
235
  : "暂无事件触发记录。\n事件触发后会记录在这里。";
228
- if (!existsSync(historyPath))
236
+ const lines = await readEventHistoryLines(historyPath);
237
+ if (lines.length === 0)
229
238
  return empty;
230
- const raw = await readFile(historyPath, "utf-8");
231
- const records = raw
232
- .split("\n")
233
- .map((line) => line.trim())
234
- .filter(Boolean)
239
+ const records = lines
235
240
  .map(parseHistoryLine)
236
241
  .filter((record) => !!record)
237
242
  .filter((record) => belongsToDesk(record, options))
@@ -0,0 +1,9 @@
1
+ import { type JsonlAppender } from "../shared/jsonl-appender.js";
2
+ export declare const EVENT_HISTORY_MAX_BYTES: number;
3
+ export declare function getEventHistoryAppender(path: string, maxSizeBytes?: number): JsonlAppender;
4
+ export declare function ensureEventHistoryFile(historyPath: string): void;
5
+ /**
6
+ * Read retained history shards from oldest to newest (`.2` → `.1` → active file) so `/events history`
7
+ * remains continuous right across a rotation boundary.
8
+ */
9
+ export declare function readEventHistoryLines(historyPath: string): Promise<string[]>;
@@ -0,0 +1,66 @@
1
+ import { chmodSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import * as log from "../log.js";
5
+ import { createJsonlAppender } from "../shared/jsonl-appender.js";
6
+ export const EVENT_HISTORY_MAX_BYTES = 2 * 1024 * 1024;
7
+ const EVENT_HISTORY_ROTATIONS = 2;
8
+ /**
9
+ * Shared per-path appenders: every desk's `EventsWatcher` writes into the same app-level
10
+ * `events-history.jsonl`, so they must share one serialized queue and file-size cache for
11
+ * size-based rotation to stay race-free across desks.
12
+ */
13
+ const appenders = new Map();
14
+ export function getEventHistoryAppender(path, maxSizeBytes = EVENT_HISTORY_MAX_BYTES) {
15
+ const key = `${path}:${maxSizeBytes}`;
16
+ let appender = appenders.get(key);
17
+ if (!appender) {
18
+ appender = createJsonlAppender({
19
+ path,
20
+ maxSizeBytes,
21
+ maxRotations: EVENT_HISTORY_ROTATIONS,
22
+ maxPendingRecords: 4_000,
23
+ maxPendingBytes: 8 * 1024 * 1024,
24
+ });
25
+ appenders.set(key, appender);
26
+ }
27
+ return appender;
28
+ }
29
+ export function ensureEventHistoryFile(historyPath) {
30
+ try {
31
+ mkdirSync(dirname(historyPath), { recursive: true, mode: 0o700 });
32
+ writeFileSync(historyPath, "", { flag: "a", mode: 0o600 });
33
+ chmodSync(historyPath, 0o600);
34
+ }
35
+ catch (err) {
36
+ log.logWarn("events.history.init_failed", "Event history file init failed", { reason: String(err) });
37
+ }
38
+ }
39
+ /**
40
+ * Read retained history shards from oldest to newest (`.2` → `.1` → active file) so `/events history`
41
+ * remains continuous right across a rotation boundary.
42
+ */
43
+ export async function readEventHistoryLines(historyPath) {
44
+ const shards = [
45
+ ...Array.from({ length: EVENT_HISTORY_ROTATIONS }, (_, index) => `${historyPath}.${EVENT_HISTORY_ROTATIONS - index}`),
46
+ historyPath,
47
+ ];
48
+ const lines = [];
49
+ for (const shard of shards) {
50
+ if (!existsSync(shard))
51
+ continue;
52
+ try {
53
+ const raw = await readFile(shard, "utf-8");
54
+ for (const line of raw.split("\n")) {
55
+ const trimmed = line.trim();
56
+ if (trimmed)
57
+ lines.push(trimmed);
58
+ }
59
+ }
60
+ catch (error) {
61
+ if (error.code !== "ENOENT")
62
+ throw error;
63
+ }
64
+ }
65
+ return lines;
66
+ }
@@ -46,15 +46,19 @@ function parsePreAction(data, filename) {
46
46
  if (typeof action.command !== "string" || action.command.trim().length === 0) {
47
47
  throw new EventDefinitionError("pre-action", `Missing or empty 'preAction.command' in ${filename}`);
48
48
  }
49
- if (action.timeout !== undefined) {
50
- if (typeof action.timeout !== "number" || !Number.isFinite(action.timeout) || action.timeout <= 0) {
49
+ if (action.timeout !== undefined && action.timeoutMs !== undefined && action.timeout !== action.timeoutMs) {
50
+ throw new EventDefinitionError("pre-action", `Conflicting 'preAction.timeout' and 'preAction.timeoutMs' in ${filename}; specify timeoutMs only`);
51
+ }
52
+ const rawTimeout = action.timeout ?? action.timeoutMs;
53
+ if (rawTimeout !== undefined) {
54
+ if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
51
55
  throw new EventDefinitionError("pre-action", `Invalid 'preAction.timeout' in ${filename}, expected a positive millisecond value`);
52
56
  }
53
57
  }
54
58
  return {
55
59
  type: "bash",
56
60
  command: action.command,
57
- ...(typeof action.timeout === "number" ? { timeout: action.timeout } : {}),
61
+ ...(typeof rawTimeout === "number" ? { timeout: rawTimeout } : {}),
58
62
  };
59
63
  }
60
64
  export function parseScheduledEventContent(content, filename) {