@oyasmi/pipiclaw 0.9.2-beta.4 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/dist/agent/channel-runner.d.ts +32 -1
  2. package/dist/agent/channel-runner.js +112 -12
  3. package/dist/agent/context-budget.d.ts +9 -1
  4. package/dist/agent/context-budget.js +11 -5
  5. package/dist/agent/job-manager.d.ts +2 -0
  6. package/dist/agent/job-manager.js +1 -0
  7. package/dist/agent/session-events.js +2 -22
  8. package/dist/agent/types.d.ts +2 -1
  9. package/dist/channel/channel-context.d.ts +4 -0
  10. package/dist/channel/channel-event.d.ts +39 -0
  11. package/dist/channel/channel-event.js +11 -1
  12. package/dist/channel/project-scope-store.js +6 -11
  13. package/dist/channel/store.d.ts +7 -0
  14. package/dist/commands/catalog.d.ts +1 -1
  15. package/dist/memory/bootstrap.js +3 -5
  16. package/dist/memory/candidates.js +2 -4
  17. package/dist/memory/files.d.ts +0 -1
  18. package/dist/memory/files.js +6 -9
  19. package/dist/memory/maintenance-state.js +4 -0
  20. package/dist/runtime/bootstrap.d.ts +12 -6
  21. package/dist/runtime/bootstrap.js +144 -75
  22. package/dist/runtime/delivery.js +1 -0
  23. package/dist/runtime/dingtalk.d.ts +59 -3
  24. package/dist/runtime/dingtalk.js +192 -83
  25. package/dist/runtime/inbound-media.d.ts +60 -0
  26. package/dist/runtime/inbound-media.js +95 -0
  27. package/dist/runtime/task-driver.d.ts +7 -0
  28. package/dist/runtime/task-driver.js +23 -44
  29. package/dist/runtime/task-migration.d.ts +11 -0
  30. package/dist/runtime/task-migration.js +11 -0
  31. package/dist/security/command-guard.js +1 -3
  32. package/dist/security/config.d.ts +1 -1
  33. package/dist/security/config.js +8 -32
  34. package/dist/security/path-guard.js +1 -6
  35. package/dist/security/project-scope.js +1 -3
  36. package/dist/settings.d.ts +2 -2
  37. package/dist/settings.js +13 -20
  38. package/dist/shared/atomic-file.d.ts +2 -3
  39. package/dist/shared/atomic-file.js +8 -9
  40. package/dist/shared/config-diagnostic.d.ts +21 -0
  41. package/dist/shared/config-diagnostic.js +32 -0
  42. package/dist/shared/numeric.d.ts +7 -0
  43. package/dist/shared/numeric.js +19 -0
  44. package/dist/shared/text-utils.d.ts +10 -0
  45. package/dist/shared/text-utils.js +16 -0
  46. package/dist/shared/types.d.ts +23 -0
  47. package/dist/shared/types.js +12 -0
  48. package/dist/shared/with-timeout.d.ts +3 -0
  49. package/dist/shared/with-timeout.js +8 -0
  50. package/dist/subagents/discovery.d.ts +7 -7
  51. package/dist/subagents/discovery.js +27 -59
  52. package/dist/subagents/runs.d.ts +6 -0
  53. package/dist/subagents/runs.js +11 -0
  54. package/dist/subagents/tool.js +195 -128
  55. package/dist/subagents/workspace-lease.js +1 -3
  56. package/dist/tasks/control.d.ts +2 -0
  57. package/dist/tasks/control.js +2 -0
  58. package/dist/tasks/ledger.d.ts +0 -9
  59. package/dist/tasks/ledger.js +92 -158
  60. package/dist/tools/config.d.ts +1 -1
  61. package/dist/tools/config.js +9 -46
  62. package/dist/tools/skill.js +1 -3
  63. package/dist/tools/truncate.js +24 -28
  64. package/dist/tui/app.js +1 -1
  65. package/dist/web/config.js +3 -15
  66. package/examples/sub-agents/builder.md +1 -1
  67. package/examples/sub-agents/documenter.md +1 -1
  68. package/examples/sub-agents/explorer.md +4 -4
  69. package/examples/sub-agents/git-committer.md +4 -4
  70. package/examples/sub-agents/log-sifter.md +3 -3
  71. package/examples/sub-agents/planner.md +1 -1
  72. package/examples/sub-agents/reviewer.md +1 -1
  73. package/examples/sub-agents/worker.md +1 -1
  74. package/package.json +3 -2
  75. package/dist/agent/index.d.ts +0 -2
  76. package/dist/agent/index.js +0 -1
@@ -15,11 +15,15 @@ import { getChannelDir } from "../channel/channel-paths.js";
15
15
  import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
16
16
  import * as log from "../log.js";
17
17
  import { writeFileAtomicallySync } from "../shared/atomic-file.js";
18
+ import { createSerialQueue } from "../shared/serial-queue.js";
18
19
  import { errorMessage } from "../shared/text-utils.js";
19
20
  import { isRecord } from "../shared/type-guards.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);
@@ -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
+ }
@@ -70,5 +70,12 @@ export declare class TaskDriver {
70
70
  /** Fold `candidate` into the earliest interesting wake moment. */
71
71
  private noteHorizon;
72
72
  private collectHorizons;
73
+ /**
74
+ * Escalate one task to the governor and best-effort notify, returning whether it actually
75
+ * escalated (a caller only needs to react — reset attempt state, log — when it did). The
76
+ * notify failure itself is never fatal to the escalation: `escalateTask` already made the
77
+ * durable disable; a delivery hiccup is logged and swallowed, not retried here.
78
+ */
79
+ private escalateAndNotify;
73
80
  runOnce(now?: Date): Promise<void>;
74
81
  }
@@ -291,6 +291,24 @@ export class TaskDriver {
291
291
  }
292
292
  }
293
293
  }
294
+ /**
295
+ * Escalate one task to the governor and best-effort notify, returning whether it actually
296
+ * escalated (a caller only needs to react — reset attempt state, log — when it did). The
297
+ * notify failure itself is never fatal to the escalation: `escalateTask` already made the
298
+ * durable disable; a delivery hiccup is logged and swallowed, not retried here.
299
+ */
300
+ async escalateAndNotify(channelDir, channelId, entry, reason, nowMs) {
301
+ if (!(await escalateTask(channelDir, entry.id, reason)))
302
+ return false;
303
+ const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
304
+ try {
305
+ await this.options.notify?.(receipt);
306
+ }
307
+ catch (error) {
308
+ log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
309
+ }
310
+ return true;
311
+ }
294
312
  async runOnce(now = new Date()) {
295
313
  if (this.options.isEnabled?.() === false || this.running)
296
314
  return;
@@ -336,30 +354,12 @@ export class TaskDriver {
336
354
  if (entry.frontmatter.status !== "sleeping" || entry.frontmatter.enabled === false)
337
355
  continue;
338
356
  if (!entry.frontmatter.schedule) {
339
- const reason = "sleeping recurring task has no schedule";
340
- if (await escalateTask(channelDir, entry.id, reason)) {
341
- const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
342
- try {
343
- await this.options.notify?.(receipt);
344
- }
345
- catch (error) {
346
- log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
347
- }
348
- }
357
+ await this.escalateAndNotify(channelDir, channelId, entry, "sleeping recurring task has no schedule", nowMs);
349
358
  continue;
350
359
  }
351
360
  const scheduleWake = nextTaskWake(entry.frontmatter.schedule, now);
352
361
  if (!scheduleWake) {
353
- const reason = `sleeping task has invalid schedule: ${entry.frontmatter.schedule}`;
354
- if (await escalateTask(channelDir, entry.id, reason)) {
355
- const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
356
- try {
357
- await this.options.notify?.(receipt);
358
- }
359
- catch (error) {
360
- log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
361
- }
362
- }
362
+ await this.escalateAndNotify(channelDir, channelId, entry, `sleeping task has invalid schedule: ${entry.frontmatter.schedule}`, nowMs);
363
363
  continue;
364
364
  }
365
365
  if (!needsWakeHeal(entry))
@@ -386,14 +386,7 @@ export class TaskDriver {
386
386
  if (!escalationReason)
387
387
  continue;
388
388
  governanceHandled = true;
389
- if (await escalateTask(channelDir, candidate.id, escalationReason)) {
390
- const receipt = taskGovernorReceipt(channelId, candidate, escalationReason, nowMs);
391
- try {
392
- await this.options.notify?.(receipt);
393
- }
394
- catch (error) {
395
- log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
396
- }
389
+ if (await this.escalateAndNotify(channelDir, channelId, candidate, escalationReason, nowMs)) {
397
390
  log.logWarning(`[${channelId}] Task driver disabled ${candidate.id} (governor)`, escalationReason);
398
391
  }
399
392
  break;
@@ -481,14 +474,7 @@ export class TaskDriver {
481
474
  const futileCount = !repairOnly && previous?.accepted && previous.fingerprint === fingerprint ? previous.futileCount + 1 : 0;
482
475
  if (futileCount >= FUTILE_WAKE_LIMIT) {
483
476
  const reason = `task made no visible progress in ${FUTILE_WAKE_LIMIT} consecutive wakes`;
484
- if (await escalateTask(channelDir, entry.id, reason)) {
485
- const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
486
- try {
487
- await this.options.notify?.(receipt);
488
- }
489
- catch (error) {
490
- log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
491
- }
477
+ if (await this.escalateAndNotify(channelDir, channelId, entry, reason, nowMs)) {
492
478
  this.attempts.delete(key);
493
479
  this.lastDispatchedTaskId.set(channelId, entry.id);
494
480
  log.logWarning(`[${channelId}] Task driver disabled ${entry.id} (governor)`, reason);
@@ -499,14 +485,7 @@ export class TaskDriver {
499
485
  const wakeCount = !repairOnly && previous && previous.cycleId === cycleId ? previous.wakeCount + 1 : 1;
500
486
  if (wakeCount > MAX_WAKES_PER_CYCLE) {
501
487
  const reason = `task exceeded ${MAX_WAKES_PER_CYCLE} wakes in this cycle (runaway failsafe)`;
502
- if (await escalateTask(channelDir, entry.id, reason)) {
503
- const receipt = taskGovernorReceipt(channelId, entry, reason, nowMs);
504
- try {
505
- await this.options.notify?.(receipt);
506
- }
507
- catch (error) {
508
- log.logWarning(`[${channelId}] Task governor receipt failed`, errorMessage(error));
509
- }
488
+ if (await this.escalateAndNotify(channelDir, channelId, entry, reason, nowMs)) {
510
489
  this.attempts.delete(key);
511
490
  this.lastDispatchedTaskId.set(channelId, entry.id);
512
491
  log.logWarning(`[${channelId}] Task driver disabled ${entry.id} (governor)`, reason);
@@ -1,3 +1,14 @@
1
+ /**
2
+ * RETIRE AT v0.9.3 (code review 2026-08-30): both migrations in this file are startup self-heal
3
+ * passes for on-disk state written by pre-0.9 betas (the pre-spec-029 `.schedule` event format,
4
+ * and pre-spec-043 v1/v2 task control blocks and status vocabulary). Every 0.9.2-beta install is
5
+ * a small, actively-developed fleet; by the 0.9.3 stable cut every install will have booted at
6
+ * least once on a version that already runs these passes, so there is no longer any on-disk
7
+ * state left for them to find. At 0.9.3: delete both exported functions here, their call sites
8
+ * in `bootstrap.ts`, `parseLegacyTaskControl` in `../tasks/control.js` (this file's only caller),
9
+ * and the paired legacy-state fold in `../memory/maintenance-state.js` (same rationale, unrelated
10
+ * subsystem). Confirm first that no currently-supported version predates the pass being removed.
11
+ */
1
12
  /**
2
13
  * One-time migration closing the 027 window (spec 029, D6).
3
14
  *