@oyasmi/pipiclaw 0.9.2-beta.3 → 0.9.2-beta.6

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 (142) hide show
  1. package/README.md +3 -0
  2. package/dist/agent/channel-runner.d.ts +45 -19
  3. package/dist/agent/channel-runner.js +156 -102
  4. package/dist/agent/command-extension.js +1 -1
  5. package/dist/agent/context-budget.d.ts +17 -1
  6. package/dist/agent/context-budget.js +20 -6
  7. package/dist/agent/job-manager.d.ts +3 -1
  8. package/dist/agent/job-manager.js +7 -1
  9. package/dist/agent/prompt/builder.d.ts +0 -1
  10. package/dist/agent/prompt/builder.js +1 -14
  11. package/dist/agent/prompt/manifest.js +2 -1
  12. package/dist/agent/prompt/sections.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +19 -1
  14. package/dist/agent/runner-factory.js +8 -1
  15. package/dist/agent/session-events.d.ts +2 -2
  16. package/dist/agent/session-events.js +2 -22
  17. package/dist/agent/turn-prompt.d.ts +35 -0
  18. package/dist/agent/turn-prompt.js +37 -0
  19. package/dist/agent/turn-recovery.js +1 -1
  20. package/dist/agent/turn-state.d.ts +60 -0
  21. package/dist/agent/turn-state.js +95 -0
  22. package/dist/agent/types.d.ts +5 -4
  23. package/dist/{runtime → channel}/channel-context.d.ts +10 -2
  24. package/dist/{runtime → channel}/channel-context.js +6 -2
  25. package/dist/{runtime → channel}/channel-event.d.ts +39 -0
  26. package/dist/channel/channel-event.js +11 -0
  27. package/dist/channel/channel-paths.d.ts +16 -0
  28. package/dist/{runtime → channel}/channel-paths.js +20 -0
  29. package/dist/{runtime → channel}/project-scope-store.js +6 -11
  30. package/dist/{runtime → channel}/store.d.ts +7 -0
  31. package/dist/{agent/commands.d.ts → commands/catalog.d.ts} +17 -2
  32. package/dist/{agent/commands.js → commands/catalog.js} +30 -0
  33. package/dist/index.d.ts +1 -1
  34. package/dist/log.js +14 -5
  35. package/dist/main.js +29 -0
  36. package/dist/memory/bootstrap.js +3 -5
  37. package/dist/memory/candidates.js +2 -4
  38. package/dist/memory/commands.js +2 -2
  39. package/dist/memory/files.d.ts +0 -1
  40. package/dist/memory/files.js +6 -9
  41. package/dist/memory/maintenance-state.d.ts +8 -0
  42. package/dist/memory/maintenance-state.js +51 -4
  43. package/dist/memory/scheduler.d.ts +6 -0
  44. package/dist/memory/scheduler.js +19 -16
  45. package/dist/playbooks/agent-delegation.md +2 -2
  46. package/dist/runtime/bootstrap.d.ts +14 -8
  47. package/dist/runtime/bootstrap.js +158 -81
  48. package/dist/runtime/delivery.d.ts +3 -3
  49. package/dist/runtime/delivery.js +1 -0
  50. package/dist/runtime/dingtalk.d.ts +62 -6
  51. package/dist/runtime/dingtalk.js +194 -85
  52. package/dist/runtime/durable-dispatch.d.ts +7 -1
  53. package/dist/runtime/durable-dispatch.js +12 -2
  54. package/dist/runtime/event-commands.js +2 -2
  55. package/dist/runtime/events.d.ts +8 -1
  56. package/dist/runtime/events.js +15 -3
  57. package/dist/runtime/inbound-media.d.ts +60 -0
  58. package/dist/runtime/inbound-media.js +95 -0
  59. package/dist/runtime/project-commands.js +2 -2
  60. package/dist/runtime/skill-commands.d.ts +27 -0
  61. package/dist/runtime/skill-commands.js +72 -0
  62. package/dist/runtime/subagent-commands.js +1 -1
  63. package/dist/runtime/task-commands.js +2 -2
  64. package/dist/runtime/task-driver.d.ts +12 -1
  65. package/dist/runtime/task-driver.js +36 -56
  66. package/dist/runtime/task-migration.d.ts +11 -0
  67. package/dist/runtime/task-migration.js +14 -2
  68. package/dist/runtime/task-wake.d.ts +1 -1
  69. package/dist/runtime/task-wake.js +1 -1
  70. package/dist/security/command-guard.js +1 -3
  71. package/dist/security/config.d.ts +1 -1
  72. package/dist/security/config.js +8 -32
  73. package/dist/security/path-guard.js +1 -6
  74. package/dist/security/project-scope.js +1 -3
  75. package/dist/settings.d.ts +3 -2
  76. package/dist/settings.js +82 -20
  77. package/dist/shared/atomic-file.d.ts +2 -3
  78. package/dist/shared/atomic-file.js +8 -9
  79. package/dist/shared/config-diagnostic.d.ts +21 -0
  80. package/dist/shared/config-diagnostic.js +32 -0
  81. package/dist/shared/numeric.d.ts +7 -0
  82. package/dist/shared/numeric.js +19 -0
  83. package/dist/shared/text-utils.d.ts +10 -0
  84. package/dist/shared/text-utils.js +16 -0
  85. package/dist/shared/token-estimate.d.ts +1 -0
  86. package/dist/shared/token-estimate.js +19 -0
  87. package/dist/shared/types.d.ts +23 -0
  88. package/dist/shared/types.js +12 -0
  89. package/dist/shared/with-timeout.d.ts +3 -0
  90. package/dist/shared/with-timeout.js +8 -0
  91. package/dist/subagents/discovery.d.ts +7 -7
  92. package/dist/subagents/discovery.js +27 -59
  93. package/dist/subagents/runs.d.ts +15 -4
  94. package/dist/subagents/runs.js +118 -11
  95. package/dist/subagents/tool.js +199 -131
  96. package/dist/subagents/workspace-lease.js +1 -3
  97. package/dist/tasks/control.d.ts +2 -0
  98. package/dist/tasks/control.js +2 -0
  99. package/dist/tasks/ledger.d.ts +0 -9
  100. package/dist/tasks/ledger.js +92 -158
  101. package/dist/tools/config.d.ts +1 -1
  102. package/dist/tools/config.js +9 -46
  103. package/dist/tools/glob-match.d.ts +25 -4
  104. package/dist/tools/glob-match.js +175 -53
  105. package/dist/tools/glob.js +5 -2
  106. package/dist/tools/index.d.ts +1 -1
  107. package/dist/tools/registry.d.ts +1 -1
  108. package/dist/tools/send-media.d.ts +1 -1
  109. package/dist/tools/skill.d.ts +15 -0
  110. package/dist/tools/skill.js +17 -11
  111. package/dist/tools/truncate.js +24 -28
  112. package/dist/tui/app.js +6 -4
  113. package/dist/tui/commands.d.ts +1 -0
  114. package/dist/tui/commands.js +3 -1
  115. package/dist/tui/terminal-context.d.ts +2 -2
  116. package/dist/tui/terminal-media-sender.d.ts +1 -1
  117. package/dist/tui/turn-controller.d.ts +2 -1
  118. package/dist/tui/turn-controller.js +2 -1
  119. package/dist/web/config.js +3 -15
  120. package/examples/sub-agents/README.md +2 -2
  121. package/examples/sub-agents/builder.md +1 -1
  122. package/examples/sub-agents/documenter.md +1 -1
  123. package/examples/sub-agents/explorer.md +4 -4
  124. package/examples/sub-agents/git-committer.md +5 -4
  125. package/examples/sub-agents/log-sifter.md +4 -4
  126. package/examples/sub-agents/planner.md +1 -1
  127. package/examples/sub-agents/reviewer.md +1 -1
  128. package/examples/sub-agents/verifier.md +1 -1
  129. package/examples/sub-agents/worker.md +3 -3
  130. package/package.json +3 -2
  131. package/dist/agent/index.d.ts +0 -2
  132. package/dist/agent/index.js +0 -1
  133. package/dist/runtime/channel-event.js +0 -1
  134. package/dist/runtime/channel-paths.d.ts +0 -4
  135. /package/dist/{runtime → channel}/active-session-store.d.ts +0 -0
  136. /package/dist/{runtime → channel}/active-session-store.js +0 -0
  137. /package/dist/{runtime → channel}/channel-index.d.ts +0 -0
  138. /package/dist/{runtime → channel}/channel-index.js +0 -0
  139. /package/dist/{runtime → channel}/project-scope-store.d.ts +0 -0
  140. /package/dist/{runtime → channel}/store.js +0 -0
  141. /package/dist/{agent → commands}/reply-limits.d.ts +0 -0
  142. /package/dist/{agent → commands}/reply-limits.js +0 -0
@@ -11,15 +11,19 @@ import axios from "axios";
11
11
  import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
12
  import { existsSync, mkdirSync, readFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
- import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../agent/commands.js";
14
+ import { getChannelDir } from "../channel/channel-paths.js";
15
+ import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
15
16
  import * as log from "../log.js";
16
17
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
18
+ import { createSerialQueue } from "../shared/serial-queue.js";
17
19
  import { errorMessage } from "../shared/text-utils.js";
18
20
  import { isRecord } from "../shared/type-guards.js";
19
- import { getChannelDir } from "./channel-paths.js";
21
+ import { sleepUnref } from "../shared/with-timeout.js";
22
+ import { formatSize } from "../tools/truncate.js";
20
23
  // Turn serialization is runtime policy; the queue lives in its own module and
21
24
  // this transport only consumes it.
22
25
  import { ChannelQueue } from "./channel-queue.js";
26
+ import { MAX_INBOUND_IMAGE_BYTES, MAX_INBOUND_IMAGES_PER_MESSAGE, MEDIA_DOWNLOAD_TIMEOUT_MS, parseInboundMessage, sniffImageMimeType, } from "./inbound-media.js";
23
27
  const RESPONSE_MODE_VALUES = [
24
28
  "full_progress_then_plain_final",
25
29
  "rolling_progress_then_plain_final",
@@ -134,6 +138,13 @@ export class DingTalkBot {
134
138
  this.channelLastActiveAt = new Map();
135
139
  // Per-channel queues
136
140
  this.queues = new Map();
141
+ // Serializes "resolve inbound image attachments → build event → route" per channel (spec 049
142
+ // D3): a message needing a download must not be overtaken, in delivery order, by a later
143
+ // download-free message on the same channel. `pendingInboundIngestCount` lets
144
+ // `allChannelQueuesIdle()` see this in-flight network work, which `ChannelQueue.isIdle()`
145
+ // alone cannot — the event has not been built yet, let alone enqueued.
146
+ this.inboundIngestQueue = createSerialQueue();
147
+ this.pendingInboundIngestCount = 0;
137
148
  // Connection stability
138
149
  this.client = null;
139
150
  this.lastSocketAvailableTime = Date.now();
@@ -246,12 +257,6 @@ export class DingTalkBot {
246
257
  this.clearReconnectTimer();
247
258
  this.clearReconnectDelay();
248
259
  }
249
- async sleep(delayMs) {
250
- await new Promise((resolve) => {
251
- const timer = setTimeout(resolve, delayMs);
252
- timer.unref?.();
253
- });
254
- }
255
260
  async waitForDelay(delayMs) {
256
261
  await new Promise((resolve) => {
257
262
  this.reconnectDelayResolve = resolve;
@@ -265,7 +270,7 @@ export class DingTalkBot {
265
270
  async waitForSocketState(socket, expectedState, timeoutMs) {
266
271
  const deadline = Date.now() + timeoutMs;
267
272
  while ((socket.readyState ?? SOCKET_STATE_CLOSED) !== expectedState && Date.now() < deadline) {
268
- await this.sleep(25);
273
+ await sleepUnref(25);
269
274
  }
270
275
  return (socket.readyState ?? SOCKET_STATE_CLOSED) === expectedState;
271
276
  }
@@ -617,36 +622,31 @@ export class DingTalkBot {
617
622
  * Replace the active card content with a full snapshot.
618
623
  */
619
624
  async replaceCard(channelId, content, finalize = false, failed = false) {
620
- let card = this.activeCards.get(channelId);
621
- if ((!card || card.finished) && this.config.cardTemplateId && (content.trim() || !finalize || failed)) {
622
- await this.ensureCard(channelId);
623
- card = this.activeCards.get(channelId);
624
- }
625
- if (!card || card.finished) {
626
- if (finalize && content.trim()) {
627
- return this.sendPlain(channelId, content);
628
- }
629
- return false;
630
- }
631
- const streamed = await this.streamCard(card, content, {
632
- append: false,
633
- finalize,
634
- failed,
635
- });
636
- if (!streamed || finalize || failed) {
637
- this.activeCards.delete(channelId);
638
- }
639
- return streamed;
625
+ return this.writeCard(channelId, content, { append: false, finalize, failed });
640
626
  }
641
627
  /**
642
628
  * Append a delta to the active card transcript.
643
629
  */
644
630
  async appendToCard(channelId, content, finalize = false, failed = false) {
645
- if (!content && !finalize && !failed) {
631
+ return this.writeCard(channelId, content, { append: true, finalize, failed });
632
+ }
633
+ /**
634
+ * Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
635
+ * two (a full-snapshot replace opens one for a finalize/failed close too; a delta append only
636
+ * opens one for genuinely new content), so that predicate stays keyed on `append` rather than
637
+ * being collapsed away — everything after it (stream, then drop the card on finalize/failed/a
638
+ * failed stream) is identical either way.
639
+ */
640
+ async writeCard(channelId, content, options) {
641
+ const { append, finalize, failed } = options;
642
+ if (append && !content && !finalize && !failed) {
646
643
  return true;
647
644
  }
648
645
  let card = this.activeCards.get(channelId);
649
- if ((!card || card.finished) && !finalize && !failed && this.config.cardTemplateId && content.trim()) {
646
+ const shouldEnsure = append
647
+ ? !finalize && !failed && content.trim().length > 0
648
+ : content.trim().length > 0 || !finalize || failed;
649
+ if ((!card || card.finished) && this.config.cardTemplateId && shouldEnsure) {
650
650
  await this.ensureCard(channelId);
651
651
  card = this.activeCards.get(channelId);
652
652
  }
@@ -656,11 +656,7 @@ export class DingTalkBot {
656
656
  }
657
657
  return false;
658
658
  }
659
- const streamed = await this.streamCard(card, content, {
660
- append: true,
661
- finalize,
662
- failed,
663
- });
659
+ const streamed = await this.streamCard(card, content, { append, finalize, failed });
664
660
  if (!streamed || finalize || failed) {
665
661
  this.activeCards.delete(channelId);
666
662
  }
@@ -782,6 +778,102 @@ export class DingTalkBot {
782
778
  return null;
783
779
  }
784
780
  }
781
+ /**
782
+ * Two-step DingTalk inbound file download (spec 049): `messageFiles/download` exchanges the
783
+ * message's `downloadCode` for a short-lived `downloadUrl`, then that URL is fetched for the
784
+ * actual bytes. Both hops reuse `getAccessToken()` — the same app access token works across
785
+ * DingTalk's hosts, as the comment on `DINGTALK_OAPI` above explains for the outbound side.
786
+ *
787
+ * This runs from `onStreamMessage`'s per-channel ingestion queue, never from inside a turn: a
788
+ * busy channel can queue a message for minutes (`USER_MESSAGE_QUEUE_LIMIT`), and by the time a
789
+ * queued turn actually ran, a `downloadCode`/`downloadUrl` fetched only then could easily have
790
+ * already expired.
791
+ *
792
+ * `protected` so the deterministic e2e harness can override it and run this path with zero
793
+ * network, the same pattern `HarnessDingTalkBot` already uses for outbound calls.
794
+ */
795
+ async downloadMessageFile(downloadCode) {
796
+ const token = await this.getAccessToken();
797
+ if (!token)
798
+ return null;
799
+ const robotCode = this.config.robotCode || this.config.clientId;
800
+ try {
801
+ const downloadUrlResp = await http.post(`${DINGTALK_API}/v1.0/robot/messageFiles/download`, { robotCode, downloadCode }, { headers: { "x-acs-dingtalk-access-token": token } });
802
+ const downloadUrl = isRecord(downloadUrlResp.data) ? downloadUrlResp.data.downloadUrl : undefined;
803
+ if (typeof downloadUrl !== "string" || !downloadUrl) {
804
+ log.logWarning("DingTalk: messageFiles/download returned no downloadUrl", JSON.stringify(downloadUrlResp.data));
805
+ return null;
806
+ }
807
+ const fileResp = await http.get(downloadUrl, {
808
+ responseType: "arraybuffer",
809
+ // Reject an oversized body before it fully lands in memory rather than after.
810
+ maxContentLength: MAX_INBOUND_IMAGE_BYTES,
811
+ timeout: MEDIA_DOWNLOAD_TIMEOUT_MS,
812
+ });
813
+ return { data: Buffer.from(fileResp.data) };
814
+ }
815
+ catch (err) {
816
+ if (axios.isAxiosError(err) && err.response) {
817
+ log.logWarning(`DingTalk: inbound file download failed (${err.response.status})`, JSON.stringify(err.response.data));
818
+ }
819
+ else {
820
+ log.logWarning("DingTalk: inbound file download failed", errorMessage(err));
821
+ }
822
+ return null;
823
+ }
824
+ }
825
+ /**
826
+ * Resolve one parsed message's image credentials into persisted `InboundImage`s and a text
827
+ * with every `[图片N]` marker either left as-is (success) or replaced with a reason (spec 049
828
+ * D8): a download failure, an unrecognized format, an oversized file, or a message that
829
+ * simply carried more images than `MAX_INBOUND_IMAGES_PER_MESSAGE` allows. A failure on one
830
+ * image never drops the rest of the message — only that one marker changes.
831
+ *
832
+ * No-op (no network call at all) when the message carries no image credentials, so a plain
833
+ * text message never pays for this method's existence.
834
+ */
835
+ async resolveInboundAttachments(channelId, parsed) {
836
+ if (parsed.downloadCodes.length === 0) {
837
+ return { text: parsed.text, images: [] };
838
+ }
839
+ let text = parsed.text;
840
+ const images = [];
841
+ const replaceMarker = (index, replacement) => {
842
+ text = text.replace(`[图片${index + 1}]`, replacement);
843
+ };
844
+ await Promise.all(parsed.downloadCodes.map(async (downloadCode, index) => {
845
+ const marker = index + 1;
846
+ if (index >= MAX_INBOUND_IMAGES_PER_MESSAGE) {
847
+ replaceMarker(index, `[图片${marker}:超出单条消息图片数量上限,已丢弃]`);
848
+ return;
849
+ }
850
+ const downloaded = await this.downloadMessageFile(downloadCode);
851
+ if (!downloaded) {
852
+ replaceMarker(index, `[图片${marker}:接收失败]`);
853
+ return;
854
+ }
855
+ if (downloaded.data.byteLength > MAX_INBOUND_IMAGE_BYTES) {
856
+ replaceMarker(index, `[图片${marker}:文件过大(${formatSize(downloaded.data.byteLength)}),已丢弃]`);
857
+ return;
858
+ }
859
+ const mimeType = sniffImageMimeType(downloaded.data);
860
+ const persisted = await this.handler.persistInboundImage?.(channelId, {
861
+ data: downloaded.data,
862
+ mimeType,
863
+ });
864
+ if (!persisted) {
865
+ replaceMarker(index, `[图片${marker}:保存失败]`);
866
+ return;
867
+ }
868
+ if (!mimeType) {
869
+ // Persisted for the record, but never handed to a model — see the handler
870
+ // contract's doc comment on `persistInboundImage`.
871
+ replaceMarker(index, `[图片${marker}:格式不支持,已保存]`);
872
+ }
873
+ images[index] = persisted;
874
+ }));
875
+ return { text, images: images.filter((image) => image !== undefined) };
876
+ }
785
877
  /**
786
878
  * POST a robot message with an arbitrary msgKey/msgParam, routing DM vs group
787
879
  * to the correct endpoint. The single outbound path for every non-card message:
@@ -1005,34 +1097,16 @@ export class DingTalkBot {
1005
1097
  // ==========================================================================
1006
1098
  // Private - Message handling
1007
1099
  // ==========================================================================
1008
- extractContent(data) {
1009
- // 1. text 类型消息:从 text.content 提取
1010
- const textContent = (data.text?.content || "").trim();
1011
- if (textContent)
1012
- return textContent;
1013
- // 2. richText 类型消息:从 content.richText 列表提取文本片段
1014
- if (data.content?.richText) {
1015
- const parts = [];
1016
- for (const item of data.content.richText) {
1017
- if (item.text)
1018
- parts.push(item.text);
1019
- }
1020
- const joined = parts.join("").trim();
1021
- if (joined)
1022
- return joined;
1023
- }
1024
- return "";
1025
- }
1026
1100
  async onStreamMessage(data) {
1027
1101
  if (this.isStopped) {
1028
1102
  return;
1029
1103
  }
1030
- const content = this.extractContent(data);
1104
+ const parsed = parseInboundMessage(data);
1031
1105
  const senderId = data.senderStaffId || data.senderId || "";
1032
1106
  const senderName = data.senderNick || "Unknown";
1033
1107
  const conversationId = data.conversationId || "";
1034
1108
  const conversationType = data.conversationType || "1";
1035
- if (!content) {
1109
+ if (!parsed.text && parsed.downloadCodes.length === 0) {
1036
1110
  const msgtype = typeof data.msgtype === "string" ? data.msgtype : "unknown";
1037
1111
  log.logWarning(`DingTalk: empty message (type=${msgtype})`);
1038
1112
  return;
@@ -1045,35 +1119,60 @@ export class DingTalkBot {
1045
1119
  }
1046
1120
  // Determine channel ID
1047
1121
  const channelId = conversationType === "2" ? `group_${conversationId}` : `dm_${senderId}`;
1048
- log.logEvent("info", "runtime.dingtalk.message_received", "Accepted incoming message", {
1049
- ctx: { channelId, userName: senderName },
1050
- fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
1051
- });
1052
- // A group carries its title on every message; a DM has none, so the peer's nickname is
1053
- // the only human-readable handle that channel will ever have.
1054
- const conversationTitle = typeof data.conversationTitle === "string" ? data.conversationTitle.trim() : "";
1055
- const channelName = (conversationType === "2" ? conversationTitle : senderName) || undefined;
1056
- // Cache conversation metadata for card creation
1057
- this.setConversationMeta(channelId, {
1058
- conversationId,
1059
- conversationType,
1060
- senderId,
1061
- });
1062
- // The one place a real person's message is seen before command/busy routing splits the
1063
- // path, so the channel index counts every human message and no synthetic wake.
1064
- this.handler.noteChannelActivity?.({ channelId, name: channelName, at: Date.now() });
1065
- // Build event
1066
- const event = {
1067
- type: conversationType === "2" ? "group" : "dm",
1068
- channelId,
1069
- ts: Date.now().toString(),
1070
- user: senderId,
1071
- userName: senderName,
1072
- text: content,
1073
- conversationId,
1074
- conversationType,
1075
- ...(channelName ? { channelName } : {}),
1076
- };
1122
+ // Parsing above is free; resolving image attachments below is a real network round-trip.
1123
+ // Serialize the whole "resolve attachments → build event → route" unit per channel (spec
1124
+ // 049 D3): without this, a message needing a download can be overtaken, in delivery order,
1125
+ // by a later download-free message on the same channel — nothing upstream of
1126
+ // `enqueueStreamMessage` otherwise waits on anything asynchronous.
1127
+ this.pendingInboundIngestCount++;
1128
+ try {
1129
+ await this.inboundIngestQueue.run(channelId, async () => {
1130
+ const { text: content, images } = await this.resolveInboundAttachments(channelId, parsed);
1131
+ log.logEvent("info", "runtime.dingtalk.message_received", "Accepted incoming message", {
1132
+ ctx: { channelId, userName: senderName },
1133
+ fields: { messageType: conversationType === "2" ? "group" : "dm", messageLength: content.length },
1134
+ });
1135
+ // A group carries its title on every message; a DM has none, so the peer's nickname
1136
+ // is the only human-readable handle that channel will ever have.
1137
+ const conversationTitle = typeof data.conversationTitle === "string" ? data.conversationTitle.trim() : "";
1138
+ const channelName = (conversationType === "2" ? conversationTitle : senderName) || undefined;
1139
+ // Cache conversation metadata for card creation
1140
+ this.setConversationMeta(channelId, {
1141
+ conversationId,
1142
+ conversationType,
1143
+ senderId,
1144
+ });
1145
+ // The one place a real person's message is seen before command/busy routing splits
1146
+ // the path, so the channel index counts every human message and no synthetic wake.
1147
+ this.handler.noteChannelActivity?.({ channelId, name: channelName, at: Date.now() });
1148
+ // Build event
1149
+ const event = {
1150
+ type: conversationType === "2" ? "group" : "dm",
1151
+ channelId,
1152
+ ts: Date.now().toString(),
1153
+ user: senderId,
1154
+ userName: senderName,
1155
+ text: content,
1156
+ conversationId,
1157
+ conversationType,
1158
+ ...(channelName ? { channelName } : {}),
1159
+ ...(images.length > 0 ? { images } : {}),
1160
+ };
1161
+ await this.routeInboundEvent(event);
1162
+ });
1163
+ }
1164
+ finally {
1165
+ this.pendingInboundIngestCount--;
1166
+ }
1167
+ }
1168
+ /**
1169
+ * Command / busy / `/new` routing for one inbound event, ending in `enqueueStreamMessage`
1170
+ * for a normal message. Split out of `onStreamMessage` so the deterministic e2e harness
1171
+ * (spec 048) can exercise the real transport queue and busy semantics without a socket.
1172
+ */
1173
+ async routeInboundEvent(event) {
1174
+ const { channelId } = event;
1175
+ const content = event.text;
1077
1176
  const builtInCommand = parseBuiltInCommand(content);
1078
1177
  const isSlashCommand = content.trim().startsWith("/");
1079
1178
  // `/new` is an emergency boundary as well as a session command. Route it before
@@ -1163,6 +1262,16 @@ export class DingTalkBot {
1163
1262
  this.discardCard(channelId);
1164
1263
  return dropped;
1165
1264
  }
1265
+ /** Test seam (spec 048): true when no channel queue has pending or in-flight work. */
1266
+ allChannelQueuesIdle() {
1267
+ if (this.pendingInboundIngestCount > 0)
1268
+ return false;
1269
+ for (const queue of this.queues.values()) {
1270
+ if (!queue.isIdle())
1271
+ return false;
1272
+ }
1273
+ return true;
1274
+ }
1166
1275
  getQueue(channelId) {
1167
1276
  this.touchChannel(channelId);
1168
1277
  let queue = this.queues.get(channelId);
@@ -1,4 +1,4 @@
1
- import type { ChannelEvent } from "./channel-event.js";
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
2
2
  import type { DingTalkBot } from "./dingtalk.js";
3
3
  type DispatchStatus = "pending" | "queued" | "running" | "exhausted";
4
4
  export interface DurableDispatchRecord {
@@ -47,6 +47,12 @@ export declare class DurableDispatchService {
47
47
  private readonly running;
48
48
  constructor(options: DurableDispatchOptions);
49
49
  start(): void;
50
+ /**
51
+ * The drain is timer-driven, so nothing above it can catch a rejection: a record write that
52
+ * fails (ENOSPC, EACCES) would take the process down rather than skip one tick. The next
53
+ * tick retries from the same persisted state, which is the whole point of the store.
54
+ */
55
+ private drainSafely;
50
56
  stop(): void;
51
57
  dispatch(event: ChannelEvent): Promise<boolean>;
52
58
  /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
@@ -90,10 +90,20 @@ export class DurableDispatchService {
90
90
  start() {
91
91
  if (this.timer)
92
92
  return;
93
- void this.drainOnce();
94
- this.timer = setInterval(() => void this.drainOnce(), this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
93
+ this.drainSafely();
94
+ this.timer = setInterval(() => this.drainSafely(), this.options.intervalMs ?? DEFAULT_INTERVAL_MS);
95
95
  this.timer.unref?.();
96
96
  }
97
+ /**
98
+ * The drain is timer-driven, so nothing above it can catch a rejection: a record write that
99
+ * fails (ENOSPC, EACCES) would take the process down rather than skip one tick. The next
100
+ * tick retries from the same persisted state, which is the whole point of the store.
101
+ */
102
+ drainSafely() {
103
+ this.drainOnce().catch((error) => {
104
+ log.logWarning("Durable dispatch drain failed", errorMessage(error));
105
+ });
106
+ }
97
107
  stop() {
98
108
  if (!this.timer)
99
109
  return;
@@ -1,8 +1,8 @@
1
1
  import { existsSync } from "fs";
2
2
  import { readdir, readFile, unlink } from "fs/promises";
3
3
  import { join } from "path";
4
- import { renderSubcommandUsage } from "../agent/commands.js";
5
- import { capReply } from "../agent/reply-limits.js";
4
+ import { renderSubcommandUsage } from "../commands/catalog.js";
5
+ import { capReply } from "../commands/reply-limits.js";
6
6
  import { normalizeSafeId, resolveSafeIdPath } from "../shared/safe-id.js";
7
7
  import { errorMessage, eventNameFromFilename, clipText as sharedClipText } from "../shared/text-utils.js";
8
8
  import { parseScheduledEventContent } from "./events.js";
@@ -1,6 +1,6 @@
1
+ import type { ChannelEvent } from "../channel/channel-event.js";
1
2
  import type { Executor } from "../executor.js";
2
3
  import type { SecurityConfig } from "../security/types.js";
3
- import type { ChannelEvent } from "./channel-event.js";
4
4
  import type { DingTalkBot } from "./dingtalk.js";
5
5
  export interface EventAction {
6
6
  type: "bash";
@@ -84,6 +84,13 @@ export declare class EventsWatcher {
84
84
  private debounce;
85
85
  private scanExisting;
86
86
  private handleFileChange;
87
+ /**
88
+ * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
89
+ * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
90
+ * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
91
+ * the live path. One bad file must not take the watcher, or the process, down with it.
92
+ */
93
+ private handleFileSafely;
87
94
  private handleDelete;
88
95
  private cancelScheduled;
89
96
  private handleFile;
@@ -2,6 +2,7 @@ import { Cron } from "croner";
2
2
  import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync, watch, writeFileSync, } from "fs";
3
3
  import { readFile } from "fs/promises";
4
4
  import { dirname, join, resolve } from "path";
5
+ import { getChannelDir } from "../channel/channel-paths.js";
5
6
  import * as log from "../log.js";
6
7
  import { guardCommand } from "../security/command-guard.js";
7
8
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
@@ -261,12 +262,23 @@ export class EventsWatcher {
261
262
  }
262
263
  else if (this.knownFiles.has(filename)) {
263
264
  this.cancelScheduled(filename);
264
- this.handleFile(filename);
265
+ this.handleFileSafely(filename);
265
266
  }
266
267
  else {
267
- this.handleFile(filename);
268
+ this.handleFileSafely(filename);
268
269
  }
269
270
  }
271
+ /**
272
+ * Watch callbacks are the top of their own stack, so a rejection here reaches nobody — and
273
+ * `handleFile` can reject: reloading a due one-shot dispatches it inline, and dispatch
274
+ * writes to disk. `scanExisting` already wraps its own calls; this is the same guard for
275
+ * the live path. One bad file must not take the watcher, or the process, down with it.
276
+ */
277
+ handleFileSafely(filename) {
278
+ void this.handleFile(filename).catch((err) => {
279
+ log.logWarning(`Failed to load event file: ${filename}`, errorMessage(err));
280
+ });
281
+ }
270
282
  handleDelete(filename) {
271
283
  if (!this.knownFiles.has(filename))
272
284
  return;
@@ -485,7 +497,7 @@ export class EventsWatcher {
485
497
  if (!parsed)
486
498
  return undefined;
487
499
  const taskId = parsed.id;
488
- const taskPath = join(dirname(this.eventsDir), event.channelId, "tasks", `${taskId}.md`);
500
+ const taskPath = join(getChannelDir(dirname(this.eventsDir), event.channelId), "tasks", `${taskId}.md`);
489
501
  let content;
490
502
  try {
491
503
  content = await readFile(taskPath, "utf-8");
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Pure parsing + magic-byte sniffing for DingTalk inbound image attachments (spec 049).
3
+ *
4
+ * Kept separate from `dingtalk.ts` — which owns the network calls (`downloadMessageFile`) and
5
+ * the per-channel serialization of the download — so the message-shape parsing and the sniffing
6
+ * rules can be unit tested without a `DingTalkBot` instance or any I/O.
7
+ */
8
+ import { MAX_INBOUND_IMAGE_BYTES } from "../channel/channel-event.js";
9
+ /** Re-exported for `dingtalk.ts`'s convenience — see `channel-event.ts` for why the constant
10
+ * itself lives there rather than here. */
11
+ export { MAX_INBOUND_IMAGE_BYTES };
12
+ /** Structural subset of the raw DingTalk callback payload this module reads. */
13
+ export interface InboundMessagePayload {
14
+ msgtype?: string;
15
+ text?: {
16
+ content?: string;
17
+ };
18
+ content?: {
19
+ richText?: Array<Record<string, string>>;
20
+ /** Present on a `picture` message; the credential `robot/messageFiles/download` needs. */
21
+ downloadCode?: string;
22
+ };
23
+ }
24
+ export interface ParsedInboundMessage {
25
+ /**
26
+ * User text with `[图片N]` markers inserted at each image's position in a richText mix, or a
27
+ * synthetic `[图片1]` marker for a text-less `picture` message. Empty when the message carries
28
+ * neither text nor an image — the caller still drops that case.
29
+ */
30
+ text: string;
31
+ /** In the same order as the `[图片N]` markers in `text`, one entry per image. */
32
+ downloadCodes: string[];
33
+ }
34
+ /** Defensive hard cap on how many images one inbound message can carry. */
35
+ export declare const MAX_INBOUND_IMAGES_PER_MESSAGE = 9;
36
+ /** Mirrors `MEDIA_UPLOAD_TIMEOUT_MS`: a multi-MB download over a slow link needs more than the
37
+ * 15s default HTTP timeout. */
38
+ export declare const MEDIA_DOWNLOAD_TIMEOUT_MS = 60000;
39
+ /**
40
+ * Parse one raw DingTalk callback payload into text + ordered image credentials.
41
+ *
42
+ * - `text` messages: unchanged, no images.
43
+ * - `picture` messages: carry no text of their own; a synthetic `[图片1]` marker stands in so
44
+ * the turn never becomes a genuinely empty message (spec 049 D4 — `handleBusyMessage` rejects
45
+ * those, and the runtime warns and drops a truly empty message outright).
46
+ * - `richText` messages: text and image credentials interleave in payload order; each image's
47
+ * marker is inserted at its position in the text stream so "this picture" / "the one above" in
48
+ * a follow-up still resolves to the right attachment (D5), even though the SDK's `prompt()`
49
+ * itself appends every image after all text once the turn is actually sent.
50
+ */
51
+ export declare function parseInboundMessage(data: InboundMessagePayload): ParsedInboundMessage;
52
+ /**
53
+ * Identify a downloaded file's real format from its magic bytes rather than trusting the
54
+ * `Content-Type` DingTalk's CDN happens to answer with (spec 049 D8) — the four formats `read`
55
+ * and outbound `send_media` already treat as images. `null` means "downloaded fine, but not a
56
+ * recognized image format"; the caller still persists the bytes but never hands them to a model.
57
+ */
58
+ export declare function sniffImageMimeType(data: Buffer): string | null;
59
+ /** File extension to persist a downloaded attachment under, from its sniffed MIME type. */
60
+ export declare function extensionForMimeType(mimeType: string | null): string;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Pure parsing + magic-byte sniffing for DingTalk inbound image attachments (spec 049).
3
+ *
4
+ * Kept separate from `dingtalk.ts` — which owns the network calls (`downloadMessageFile`) and
5
+ * the per-channel serialization of the download — so the message-shape parsing and the sniffing
6
+ * rules can be unit tested without a `DingTalkBot` instance or any I/O.
7
+ */
8
+ import { MAX_INBOUND_IMAGE_BYTES } from "../channel/channel-event.js";
9
+ /** Re-exported for `dingtalk.ts`'s convenience — see `channel-event.ts` for why the constant
10
+ * itself lives there rather than here. */
11
+ export { MAX_INBOUND_IMAGE_BYTES };
12
+ /** Defensive hard cap on how many images one inbound message can carry. */
13
+ export const MAX_INBOUND_IMAGES_PER_MESSAGE = 9;
14
+ /** Mirrors `MEDIA_UPLOAD_TIMEOUT_MS`: a multi-MB download over a slow link needs more than the
15
+ * 15s default HTTP timeout. */
16
+ export const MEDIA_DOWNLOAD_TIMEOUT_MS = 60_000;
17
+ /**
18
+ * Parse one raw DingTalk callback payload into text + ordered image credentials.
19
+ *
20
+ * - `text` messages: unchanged, no images.
21
+ * - `picture` messages: carry no text of their own; a synthetic `[图片1]` marker stands in so
22
+ * the turn never becomes a genuinely empty message (spec 049 D4 — `handleBusyMessage` rejects
23
+ * those, and the runtime warns and drops a truly empty message outright).
24
+ * - `richText` messages: text and image credentials interleave in payload order; each image's
25
+ * marker is inserted at its position in the text stream so "this picture" / "the one above" in
26
+ * a follow-up still resolves to the right attachment (D5), even though the SDK's `prompt()`
27
+ * itself appends every image after all text once the turn is actually sent.
28
+ */
29
+ export function parseInboundMessage(data) {
30
+ const textContent = (data.text?.content || "").trim();
31
+ if (textContent) {
32
+ return { text: textContent, downloadCodes: [] };
33
+ }
34
+ if (data.msgtype === "picture" && data.content?.downloadCode) {
35
+ return { text: "[图片1]", downloadCodes: [data.content.downloadCode] };
36
+ }
37
+ if (data.content?.richText) {
38
+ const parts = [];
39
+ const downloadCodes = [];
40
+ for (const item of data.content.richText) {
41
+ if (item.text) {
42
+ parts.push(item.text);
43
+ }
44
+ else if (item.downloadCode) {
45
+ downloadCodes.push(item.downloadCode);
46
+ parts.push(`[图片${downloadCodes.length}]`);
47
+ }
48
+ }
49
+ const joined = parts.join("").trim();
50
+ if (joined) {
51
+ return { text: joined, downloadCodes };
52
+ }
53
+ }
54
+ return { text: "", downloadCodes: [] };
55
+ }
56
+ /**
57
+ * Identify a downloaded file's real format from its magic bytes rather than trusting the
58
+ * `Content-Type` DingTalk's CDN happens to answer with (spec 049 D8) — the four formats `read`
59
+ * and outbound `send_media` already treat as images. `null` means "downloaded fine, but not a
60
+ * recognized image format"; the caller still persists the bytes but never hands them to a model.
61
+ */
62
+ export function sniffImageMimeType(data) {
63
+ if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
64
+ return "image/jpeg";
65
+ }
66
+ if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
67
+ return "image/png";
68
+ }
69
+ if (data.length >= 6) {
70
+ const header = data.subarray(0, 6).toString("latin1");
71
+ if (header === "GIF87a" || header === "GIF89a")
72
+ return "image/gif";
73
+ }
74
+ if (data.length >= 12 &&
75
+ data.subarray(0, 4).toString("latin1") === "RIFF" &&
76
+ data.subarray(8, 12).toString("latin1") === "WEBP") {
77
+ return "image/webp";
78
+ }
79
+ return null;
80
+ }
81
+ /** File extension to persist a downloaded attachment under, from its sniffed MIME type. */
82
+ export function extensionForMimeType(mimeType) {
83
+ switch (mimeType) {
84
+ case "image/jpeg":
85
+ return "jpg";
86
+ case "image/png":
87
+ return "png";
88
+ case "image/gif":
89
+ return "gif";
90
+ case "image/webp":
91
+ return "webp";
92
+ default:
93
+ return "bin";
94
+ }
95
+ }
@@ -1,8 +1,8 @@
1
- import { renderSubcommandUsage } from "../agent/commands.js";
1
+ import { commitProjectSelection, readProjectSelection } from "../channel/project-scope-store.js";
2
+ import { renderSubcommandUsage } from "../commands/catalog.js";
2
3
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
3
4
  import { currentProjectSandboxStatus, isWithinAllowedRoots, resolveExistingDirectory, resolveProjectAccessPolicy, } from "../security/project-scope.js";
4
5
  import { errorMessage } from "../shared/text-utils.js";
5
- import { commitProjectSelection, readProjectSelection } from "./project-scope-store.js";
6
6
  function usage() {
7
7
  return renderSubcommandUsage("project");
8
8
  }