@oyasmi/pipiclaw 0.9.3 → 0.9.4-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 (113) hide show
  1. package/dist/agent/channel-runner.js +137 -61
  2. package/dist/agent/command-extension.js +47 -34
  3. package/dist/agent/job-manager.js +31 -11
  4. package/dist/agent/model-fallback.js +1 -1
  5. package/dist/agent/prompt/manifest.d.ts +6 -1
  6. package/dist/agent/prompt/manifest.js +45 -64
  7. package/dist/agent/prompt/resources.js +4 -1
  8. package/dist/agent/run-queue.js +7 -2
  9. package/dist/agent/session-adapter.js +1 -1
  10. package/dist/agent/session-events.js +17 -6
  11. package/dist/agent/session-resource-gate.js +3 -1
  12. package/dist/agent/status-render.d.ts +0 -1
  13. package/dist/agent/status-render.js +4 -16
  14. package/dist/agent/turn-error.d.ts +31 -0
  15. package/dist/agent/turn-error.js +68 -0
  16. package/dist/app-services.js +7 -4
  17. package/dist/channel/channel-index.js +4 -1
  18. package/dist/channel/project-scope-store.js +1 -1
  19. package/dist/commands/catalog.d.ts +21 -4
  20. package/dist/commands/catalog.js +88 -41
  21. package/dist/commands/reply-limits.d.ts +6 -0
  22. package/dist/commands/reply-limits.js +24 -0
  23. package/dist/events/event-commands.js +94 -44
  24. package/dist/events/event-validation.d.ts +13 -2
  25. package/dist/events/event-validation.js +17 -9
  26. package/dist/events/events.js +77 -32
  27. package/dist/executor.js +2 -2
  28. package/dist/log.d.ts +12 -2
  29. package/dist/log.js +26 -34
  30. package/dist/main.js +1 -1
  31. package/dist/memory/commands.js +29 -23
  32. package/dist/memory/lifecycle.js +26 -5
  33. package/dist/memory/maintenance-state.js +4 -1
  34. package/dist/memory/scheduler.js +3 -1
  35. package/dist/models/auth-cli.js +3 -2
  36. package/dist/paths.d.ts +2 -0
  37. package/dist/paths.js +9 -0
  38. package/dist/playbooks/agent-delegation.md +2 -2
  39. package/dist/runtime/app-home.d.ts +6 -0
  40. package/dist/runtime/app-home.js +21 -3
  41. package/dist/runtime/bootstrap.js +189 -60
  42. package/dist/runtime/channel-queue.js +1 -1
  43. package/dist/runtime/delivery.js +29 -15
  44. package/dist/runtime/dingtalk.js +96 -42
  45. package/dist/runtime/durable-dispatch.d.ts +27 -1
  46. package/dist/runtime/durable-dispatch.js +111 -3
  47. package/dist/runtime/project-commands.js +16 -15
  48. package/dist/runtime/proxy.js +4 -2
  49. package/dist/runtime/report-commands.js +1 -1
  50. package/dist/runtime/skill-commands.d.ts +1 -1
  51. package/dist/runtime/skill-commands.js +17 -10
  52. package/dist/runtime/subagent-commands.d.ts +5 -4
  53. package/dist/runtime/subagent-commands.js +116 -77
  54. package/dist/runtime/task-commands.d.ts +1 -1
  55. package/dist/runtime/task-commands.js +110 -64
  56. package/dist/runtime/task-driver.d.ts +4 -2
  57. package/dist/runtime/task-driver.js +55 -20
  58. package/dist/runtime/task-migration.js +23 -6
  59. package/dist/runtime/task-spawn.js +12 -5
  60. package/dist/runtime/wake-coalescing.d.ts +18 -0
  61. package/dist/runtime/wake-coalescing.js +29 -0
  62. package/dist/security/block-message.d.ts +22 -1
  63. package/dist/security/block-message.js +66 -1
  64. package/dist/security/network.d.ts +2 -1
  65. package/dist/security/network.js +3 -2
  66. package/dist/security/path-guard-check.js +2 -2
  67. package/dist/settings.d.ts +3 -2
  68. package/dist/settings.js +4 -1
  69. package/dist/shared/format.d.ts +12 -0
  70. package/dist/shared/format.js +37 -0
  71. package/dist/shared/host-process.js +15 -3
  72. package/dist/shared/with-timeout.d.ts +3 -2
  73. package/dist/shared/with-timeout.js +14 -3
  74. package/dist/subagents/external/claude-code.js +23 -1
  75. package/dist/subagents/external/progress-tail.d.ts +17 -0
  76. package/dist/subagents/external/progress-tail.js +64 -17
  77. package/dist/subagents/external/run.d.ts +3 -0
  78. package/dist/subagents/external/run.js +21 -7
  79. package/dist/subagents/external/settlement.d.ts +3 -0
  80. package/dist/subagents/external/settlement.js +1 -1
  81. package/dist/subagents/runs.d.ts +21 -1
  82. package/dist/subagents/runs.js +137 -32
  83. package/dist/subagents/tool.d.ts +22 -15
  84. package/dist/subagents/tool.js +226 -32
  85. package/dist/subagents/workspace-summary.d.ts +16 -4
  86. package/dist/subagents/workspace-summary.js +74 -18
  87. package/dist/tasks/board.d.ts +8 -1
  88. package/dist/tasks/board.js +37 -2
  89. package/dist/tasks/frontmatter.d.ts +5 -0
  90. package/dist/tasks/frontmatter.js +8 -0
  91. package/dist/tasks/log.d.ts +11 -1
  92. package/dist/tasks/log.js +58 -2
  93. package/dist/tasks/store.js +4 -2
  94. package/dist/tasks/ticket.d.ts +3 -1
  95. package/dist/tasks/ticket.js +19 -1
  96. package/dist/tools/bash.js +2 -2
  97. package/dist/tools/index.d.ts +2 -0
  98. package/dist/tools/index.js +1 -0
  99. package/dist/tools/memory-manage.js +4 -1
  100. package/dist/tools/subagent-manage.d.ts +1 -1
  101. package/dist/tools/subagent-manage.js +16 -11
  102. package/dist/tools/task-manage/step-end.js +4 -1
  103. package/dist/tools/tool-details.d.ts +10 -2
  104. package/dist/tools/tool-details.js +39 -2
  105. package/dist/tui/cli.js +2 -2
  106. package/dist/tui/commands.js +4 -4
  107. package/dist/tui/pitui-frontend.js +1 -1
  108. package/dist/tui/renderer.js +3 -2
  109. package/dist/tui/turn-controller.d.ts +2 -0
  110. package/dist/tui/turn-controller.js +36 -21
  111. package/dist/usage/ledger.js +3 -1
  112. package/dist/usage/render.js +3 -1
  113. package/package.json +1 -1
@@ -12,7 +12,7 @@ import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
12
12
  import { existsSync, mkdirSync, readFileSync } from "fs";
13
13
  import { dirname, join } from "path";
14
14
  import { getChannelDir } from "../channel/channel-paths.js";
15
- import { formatBusyCommandList, parseBuiltInCommand, renderBuiltInHelp, slashCommandName, } from "../commands/catalog.js";
15
+ import { formatBusyHint, 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
18
  import { createSerialQueue } from "../shared/serial-queue.js";
@@ -304,16 +304,22 @@ export class DingTalkBot {
304
304
  socket.close?.();
305
305
  }
306
306
  catch (err) {
307
- log.logWarning(`DingTalk: socket close failed during ${reason}`, errorMessage(err));
307
+ log.logWarn("dingtalk.socket.close_failed", "Socket close failed", {
308
+ reason: errorMessage(err),
309
+ fields: { during: reason },
310
+ });
308
311
  }
309
312
  const closed = await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_CLOSE_GRACE_MS);
310
313
  if (!closed) {
311
- log.logWarning(`DingTalk: forcing socket termination during ${reason}`);
314
+ log.logWarn("dingtalk.socket.terminating", "Forcing socket termination", { fields: { during: reason } });
312
315
  try {
313
316
  socket.terminate?.();
314
317
  }
315
318
  catch (err) {
316
- log.logWarning(`DingTalk: socket terminate failed during ${reason}`, errorMessage(err));
319
+ log.logWarn("dingtalk.socket.terminate_failed", "Socket terminate failed", {
320
+ reason: errorMessage(err),
321
+ fields: { during: reason },
322
+ });
317
323
  }
318
324
  await this.waitForSocketState(socket, SOCKET_STATE_CLOSED, SOCKET_TERMINATE_GRACE_MS);
319
325
  }
@@ -363,7 +369,7 @@ export class DingTalkBot {
363
369
  this.reconnectTimer = this.setTrackedTimeout(() => {
364
370
  this.reconnectTimer = null;
365
371
  this.doReconnect(immediate).catch((err) => {
366
- log.logWarning("DingTalk: reconnect failed", errorMessage(err));
372
+ log.logWarn("dingtalk.reconnect.failed", "Reconnect failed", { reason: errorMessage(err) });
367
373
  });
368
374
  }, delayMs);
369
375
  }
@@ -372,11 +378,11 @@ export class DingTalkBot {
372
378
  // ==========================================================================
373
379
  async start() {
374
380
  if (!this.config.clientId || !this.config.clientSecret) {
375
- log.logWarning("DingTalk: clientId / clientSecret not configured");
381
+ log.logWarn("dingtalk.config.missing_credentials", "clientId / clientSecret not configured");
376
382
  return;
377
383
  }
378
384
  if (!this.config.cardTemplateId) {
379
- log.logWarning("DingTalk: cardTemplateId not configured — AI Card streaming will not work");
385
+ log.logWarn("dingtalk.config.missing_card_template", "cardTemplateId not configured; AI Card streaming is off");
380
386
  }
381
387
  log.logEvent("info", "runtime.dingtalk.connecting", "Initializing stream client", {
382
388
  fields: { clientIdPrefix: this.config.clientId.substring(0, 8) },
@@ -394,7 +400,7 @@ export class DingTalkBot {
394
400
  });
395
401
  const connected = await this.doReconnect(true); // Initial connection
396
402
  if (!connected) {
397
- log.logWarning("DingTalk: initial stream connection not ready yet; retrying in background");
403
+ log.logWarn("dingtalk.connect.pending", "Initial stream connection not ready; retrying in background");
398
404
  }
399
405
  }
400
406
  handleRawMessage(msg) {
@@ -417,11 +423,11 @@ export class DingTalkBot {
417
423
  }
418
424
  // Fire-and-forget processing
419
425
  this.onStreamMessage(data).catch((err) => {
420
- log.logWarning("DingTalk handler error", errorMessage(err));
426
+ log.logWarn("dingtalk.handler.failed", "Message handler failed", { reason: errorMessage(err) });
421
427
  });
422
428
  }
423
429
  catch (err) {
424
- log.logWarning("DingTalk: failed to parse message", errorMessage(err));
430
+ log.logWarn("dingtalk.message.parse_failed", "Message parse failed", { reason: errorMessage(err) });
425
431
  }
426
432
  return { status: "SUCCESS", message: "OK" };
427
433
  }
@@ -473,7 +479,7 @@ export class DingTalkBot {
473
479
  // never emit a close event. Proactively force a reconnect instead
474
480
  // of waiting indefinitely. scheduleReconnect no-ops if an attempt
475
481
  // is already in flight or the bot has stopped.
476
- log.logWarning("DingTalk: connection timeout detected (>90s); forcing reconnect.");
482
+ log.logWarn("dingtalk.connection.timeout", "Connection timeout (>90s); forcing reconnect");
477
483
  this.scheduleReconnect(1000, true);
478
484
  return;
479
485
  }
@@ -493,7 +499,7 @@ export class DingTalkBot {
493
499
  this.lastSocketAvailableTime = Date.now();
494
500
  });
495
501
  s?.on("close", (code, reason) => {
496
- log.logWarning(`DingTalk: WebSocket closed: code=${code}, reason=${reason}`);
502
+ log.logWarn("dingtalk.socket.closed", "WebSocket closed", { fields: { code, reason } });
497
503
  if (this.isStopped)
498
504
  return;
499
505
  this.scheduleReconnect(1000, true);
@@ -502,7 +508,7 @@ export class DingTalkBot {
502
508
  try {
503
509
  const msg = JSON.parse(raw);
504
510
  if (msg.type === "SYSTEM" && msg.headers?.topic === "disconnect") {
505
- log.logWarning("DingTalk: disconnect event received from server.");
511
+ log.logWarn("dingtalk.connection.disconnected", "Server sent a disconnect event");
506
512
  if (!this.isStopped) {
507
513
  this.doReconnect(true).catch(() => { });
508
514
  }
@@ -517,7 +523,7 @@ export class DingTalkBot {
517
523
  await this.cleanupSocket("reconnect failure");
518
524
  this.reconnectAttempts++;
519
525
  connectionFailed = true;
520
- log.logWarning("DingTalk: connection failed", errorMessage(err));
526
+ log.logWarn("dingtalk.connect.failed", "Connection failed", { reason: errorMessage(err) });
521
527
  }
522
528
  finally {
523
529
  this.isReconnecting = false;
@@ -529,7 +535,7 @@ export class DingTalkBot {
529
535
  return connected;
530
536
  }
531
537
  async stop() {
532
- log.logInfo("DingTalk: stopping bot");
538
+ log.logInfoEvent("dingtalk.bot.stopping", "Stopping bot");
533
539
  this.isStopped = true;
534
540
  this.clearAllTimers();
535
541
  if (this.channelCacheSweepTimer) {
@@ -544,7 +550,7 @@ export class DingTalkBot {
544
550
  await this.cleanupSocket("stop");
545
551
  }
546
552
  catch (err) {
547
- log.logWarning("DingTalk: failed to disconnect cleanly", errorMessage(err));
553
+ log.logWarn("dingtalk.disconnect.failed", "Clean disconnect failed", { reason: errorMessage(err) });
548
554
  }
549
555
  finally {
550
556
  this.client = null;
@@ -588,7 +594,10 @@ export class DingTalkBot {
588
594
  const queuedEvent = textOverride === undefined ? event : { ...event, text: textOverride };
589
595
  const queue = this.getQueue(event.channelId);
590
596
  if (queue.size() >= USER_MESSAGE_QUEUE_LIMIT) {
591
- log.logWarning(`Message queue full for ${event.channelId} (limit ${USER_MESSAGE_QUEUE_LIMIT}), discarding: ${queuedEvent.text.substring(0, 50)}`);
597
+ log.logWarn("dingtalk.queue.full", "Message discarded: channel queue full", {
598
+ channelId: event.channelId,
599
+ fields: { limit: USER_MESSAGE_QUEUE_LIMIT, preview: queuedEvent.text.substring(0, 50) },
600
+ });
592
601
  this.sendPlain(event.channelId, `⚠️ 消息积压过多(超过 ${USER_MESSAGE_QUEUE_LIMIT} 条待处理),本条消息已丢弃,请稍后重试。`).catch(() => undefined);
593
602
  return;
594
603
  }
@@ -724,7 +733,9 @@ export class DingTalkBot {
724
733
  async sendPlain(channelId, text, opts) {
725
734
  const meta = this.getConversationMeta(channelId);
726
735
  if (!meta) {
727
- log.logWarning(`No conversation metadata for ${channelId}, cannot send plain message`);
736
+ log.logWarn("dingtalk.send.no_metadata", "Plain message not sent: no conversation metadata", {
737
+ channelId: channelId,
738
+ });
728
739
  return false;
729
740
  }
730
741
  const hasMarkdown = opts?.markdown ?? /^#{1,6}\s|^\s*[-*]\s|\*\*.*\*\*|```|`[^`]+`|\[.*?\]\(.*?\)/m.test(text);
@@ -794,21 +805,29 @@ export class DingTalkBot {
794
805
  { timeout: MEDIA_UPLOAD_TIMEOUT_MS });
795
806
  const body = isRecord(resp.data) ? resp.data : {};
796
807
  if (body.errcode && body.errcode !== 0) {
797
- log.logWarning(`DingTalk media upload failed (errcode=${body.errcode})`, String(body.errmsg ?? ""));
808
+ log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
809
+ reason: String(body.errmsg ?? ""),
810
+ fields: { errcode: body.errcode },
811
+ });
798
812
  return null;
799
813
  }
800
814
  const mediaId = typeof body.media_id === "string" ? body.media_id : null;
801
815
  if (!mediaId) {
802
- log.logWarning("DingTalk media upload returned no media_id", JSON.stringify(body));
816
+ log.logWarn("dingtalk.media.upload_failed", "Media upload returned no media_id", {
817
+ reason: JSON.stringify(body),
818
+ });
803
819
  }
804
820
  return mediaId;
805
821
  }
806
822
  catch (err) {
807
823
  if (axios.isAxiosError(err) && err.response) {
808
- log.logWarning(`DingTalk media upload error (${err.response.status})`, JSON.stringify(err.response.data));
824
+ log.logWarn("dingtalk.media.upload_failed", "Media upload failed", {
825
+ reason: JSON.stringify(err.response.data),
826
+ fields: { status: err.response.status },
827
+ });
809
828
  }
810
829
  else {
811
- log.logWarning("DingTalk media upload error", errorMessage(err));
830
+ log.logWarn("dingtalk.media.upload_failed", "Media upload failed", { reason: errorMessage(err) });
812
831
  }
813
832
  return null;
814
833
  }
@@ -836,7 +855,9 @@ export class DingTalkBot {
836
855
  const downloadUrlResp = await http.post(`${DINGTALK_API}/v1.0/robot/messageFiles/download`, { robotCode, downloadCode }, { headers: { "x-acs-dingtalk-access-token": token } });
837
856
  const downloadUrl = isRecord(downloadUrlResp.data) ? downloadUrlResp.data.downloadUrl : undefined;
838
857
  if (typeof downloadUrl !== "string" || !downloadUrl) {
839
- log.logWarning("DingTalk: messageFiles/download returned no downloadUrl", JSON.stringify(downloadUrlResp.data));
858
+ log.logWarn("dingtalk.file.download_failed", "Inbound file download returned no downloadUrl", {
859
+ reason: JSON.stringify(downloadUrlResp.data),
860
+ });
840
861
  return null;
841
862
  }
842
863
  const fileResp = await http.get(downloadUrl, {
@@ -849,10 +870,13 @@ export class DingTalkBot {
849
870
  }
850
871
  catch (err) {
851
872
  if (axios.isAxiosError(err) && err.response) {
852
- log.logWarning(`DingTalk: inbound file download failed (${err.response.status})`, JSON.stringify(err.response.data));
873
+ log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", {
874
+ reason: JSON.stringify(err.response.data),
875
+ fields: { status: err.response.status },
876
+ });
853
877
  }
854
878
  else {
855
- log.logWarning("DingTalk: inbound file download failed", errorMessage(err));
879
+ log.logWarn("dingtalk.file.download_failed", "Inbound file download failed", { reason: errorMessage(err) });
856
880
  }
857
881
  return null;
858
882
  }
@@ -941,10 +965,16 @@ export class DingTalkBot {
941
965
  }
942
966
  catch (err) {
943
967
  if (axios.isAxiosError(err) && err.response) {
944
- log.logWarning(`DingTalk ${msgKey} send failed (${err.response.status})`, JSON.stringify(err.response.data));
968
+ log.logWarn("dingtalk.send.failed", "Message send failed", {
969
+ reason: JSON.stringify(err.response.data),
970
+ fields: { msgKey, status: err.response.status },
971
+ });
945
972
  }
946
973
  else {
947
- log.logWarning(`DingTalk ${msgKey} send error`, errorMessage(err));
974
+ log.logWarn("dingtalk.send.failed", "Message send failed", {
975
+ reason: errorMessage(err),
976
+ fields: { msgKey },
977
+ });
948
978
  }
949
979
  return false;
950
980
  }
@@ -981,7 +1011,9 @@ export class DingTalkBot {
981
1011
  return null;
982
1012
  const meta = this.getConversationMeta(channelId);
983
1013
  if (!meta) {
984
- log.logWarning(`No conversation metadata for ${channelId}, cannot create card`);
1014
+ log.logWarn("dingtalk.card.no_metadata", "Card not created: no conversation metadata", {
1015
+ channelId: channelId,
1016
+ });
985
1017
  return null;
986
1018
  }
987
1019
  const isGroup = meta.conversationType === "2";
@@ -1028,10 +1060,13 @@ export class DingTalkBot {
1028
1060
  }
1029
1061
  catch (err) {
1030
1062
  if (axios.isAxiosError(err) && err.response) {
1031
- log.logWarning(`DingTalk Card: create failed (${err.response.status})`, JSON.stringify(err.response.data));
1063
+ log.logWarn("dingtalk.card.create_failed", "Card create failed", {
1064
+ reason: JSON.stringify(err.response.data),
1065
+ fields: { status: err.response.status },
1066
+ });
1032
1067
  }
1033
1068
  else {
1034
- log.logWarning("DingTalk Card: create failed", errorMessage(err));
1069
+ log.logWarn("dingtalk.card.create_failed", "Card create failed", { reason: errorMessage(err) });
1035
1070
  }
1036
1071
  return null;
1037
1072
  }
@@ -1062,7 +1097,7 @@ export class DingTalkBot {
1062
1097
  return this.streamCardRequest(card, content, options);
1063
1098
  })
1064
1099
  .catch((error) => {
1065
- log.logWarning("DingTalk Card: streaming failed", errorMessage(error));
1100
+ log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", { reason: errorMessage(error) });
1066
1101
  return false;
1067
1102
  });
1068
1103
  card.pendingWrite = pending;
@@ -1099,7 +1134,9 @@ export class DingTalkBot {
1099
1134
  });
1100
1135
  const duration = Date.now() - start;
1101
1136
  if (duration > 1000) {
1102
- log.logWarning(`DingTalk Card: streaming request took ${duration}ms (slow)`);
1137
+ log.logWarn("dingtalk.card.stream_slow", "Card streaming request slow", {
1138
+ fields: { durationMs: duration },
1139
+ });
1103
1140
  }
1104
1141
  card.lastUpdated = Date.now() / 1000;
1105
1142
  card.content = options.append ? `${card.content}${content}` : content;
@@ -1110,10 +1147,13 @@ export class DingTalkBot {
1110
1147
  }
1111
1148
  catch (err) {
1112
1149
  if (axios.isAxiosError(err) && err.response) {
1113
- log.logWarning(`DingTalk Card: streaming failed (${err.response.status})`, JSON.stringify(err.response.data));
1150
+ log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", {
1151
+ reason: JSON.stringify(err.response.data),
1152
+ fields: { status: err.response.status },
1153
+ });
1114
1154
  }
1115
1155
  else {
1116
- log.logWarning("DingTalk Card: streaming failed", errorMessage(err));
1156
+ log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", { reason: errorMessage(err) });
1117
1157
  }
1118
1158
  return false;
1119
1159
  }
@@ -1148,10 +1188,13 @@ export class DingTalkBot {
1148
1188
  }
1149
1189
  catch (err) {
1150
1190
  if (axios.isAxiosError(err) && err.response) {
1151
- log.logWarning(`DingTalk: failed to get access token (${err.response.status})`, JSON.stringify(err.response.data));
1191
+ log.logWarn("dingtalk.token.failed", "Access token request failed", {
1192
+ reason: JSON.stringify(err.response.data),
1193
+ fields: { status: err.response.status },
1194
+ });
1152
1195
  }
1153
1196
  else {
1154
- log.logWarning("DingTalk: failed to get access token", errorMessage(err));
1197
+ log.logWarn("dingtalk.token.failed", "Access token request failed", { reason: errorMessage(err) });
1155
1198
  }
1156
1199
  return null;
1157
1200
  }
@@ -1170,12 +1213,14 @@ export class DingTalkBot {
1170
1213
  const conversationType = data.conversationType || "1";
1171
1214
  if (!parsed.text && parsed.downloadCodes.length === 0) {
1172
1215
  const msgtype = typeof data.msgtype === "string" ? data.msgtype : "unknown";
1173
- log.logWarning(`DingTalk: empty message (type=${msgtype})`);
1216
+ log.logWarn("dingtalk.message.empty", "Empty message ignored", { fields: { msgtype } });
1174
1217
  return;
1175
1218
  }
1176
1219
  if (this.config.allowFrom && this.config.allowFrom.length > 0) {
1177
1220
  if (!this.config.allowFrom.includes(senderId)) {
1178
- log.logWarning(`DingTalk: ignoring message from unauthorized user ${senderName} (${senderId})`);
1221
+ log.logWarn("dingtalk.message.unauthorized", "Message from unauthorized user ignored", {
1222
+ fields: { senderName, senderId },
1223
+ });
1179
1224
  return;
1180
1225
  }
1181
1226
  }
@@ -1283,7 +1328,10 @@ export class DingTalkBot {
1283
1328
  markdown: true,
1284
1329
  });
1285
1330
  if (!delivered) {
1286
- log.logWarning(`[${channelId}] Failed to deliver /${builtInCommand.name} reply`, `${response.length} chars`);
1331
+ log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
1332
+ channelId: channelId,
1333
+ fields: { command: builtInCommand.name, chars: response.length },
1334
+ });
1287
1335
  }
1288
1336
  return;
1289
1337
  }
@@ -1292,7 +1340,7 @@ export class DingTalkBot {
1292
1340
  // Other session commands (/model, /compact, …) and unknown slash commands cannot
1293
1341
  // run mid-turn: they would need the idle session layer.
1294
1342
  if (isSlashCommand) {
1295
- await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
1343
+ await this.sendPlain(channelId, formatBusyHint());
1296
1344
  return;
1297
1345
  }
1298
1346
  const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);
@@ -1366,7 +1414,10 @@ export class DingTalkBot {
1366
1414
  return meta;
1367
1415
  }
1368
1416
  catch (err) {
1369
- log.logWarning(`Failed to load conversation metadata for ${channelId}`, errorMessage(err));
1417
+ log.logWarn("dingtalk.metadata.load_failed", "Conversation metadata load failed", {
1418
+ channelId: channelId,
1419
+ reason: errorMessage(err),
1420
+ });
1370
1421
  return null;
1371
1422
  }
1372
1423
  }
@@ -1381,7 +1432,10 @@ export class DingTalkBot {
1381
1432
  writeFileAtomicallySync(metaPath, JSON.stringify(meta, null, 2));
1382
1433
  }
1383
1434
  catch (err) {
1384
- log.logWarning(`Failed to persist conversation metadata for ${channelId}`, errorMessage(err));
1435
+ log.logWarn("dingtalk.metadata.persist_failed", "Conversation metadata persist failed", {
1436
+ channelId: channelId,
1437
+ reason: errorMessage(err),
1438
+ });
1385
1439
  }
1386
1440
  }
1387
1441
  getConversationMetaPath(channelId) {
@@ -24,6 +24,11 @@ export interface DurableDispatchOptions {
24
24
  * caller is expected to notify the channel. */
25
25
  onExhausted?: (record: DurableDispatchRecord) => void | Promise<void>;
26
26
  }
27
+ /**
28
+ * The notice a channel gets when a wake is given up on (`onExhausted`). It names the source and
29
+ * the record's absolute path — never the wake text, which is a model prompt (spec 053, D2/D6).
30
+ */
31
+ export declare function renderDispatchExhaustedNotice(record: DurableDispatchRecord, stateDir: string): string;
27
32
  /**
28
33
  * Tiny file-backed outbox for synthetic work. It intentionally provides
29
34
  * at-least-once delivery: a crash after enqueue may replay a task/event, while
@@ -45,6 +50,12 @@ export declare class DurableDispatchService {
45
50
  * lease lapses.
46
51
  */
47
52
  private readonly running;
53
+ /**
54
+ * Queued dispatch ids folded into another record's turn by `absorbPending`. Each still has its
55
+ * own closure waiting in the channel queue; `markStarted` turns that stale delivery away instead
56
+ * of running the same wake a second time.
57
+ */
58
+ private readonly absorbed;
48
59
  constructor(options: DurableDispatchOptions);
49
60
  start(): void;
50
61
  /**
@@ -57,7 +68,22 @@ export declare class DurableDispatchService {
57
68
  dispatch(event: ChannelEvent): Promise<boolean>;
58
69
  /** Reset any in-flight records for a channel so a stop/abort can redeliver on the next tick, not after the lease expires. */
59
70
  cancelChannel(channelId: string): Promise<number>;
60
- markStarted(id: string | undefined): Promise<void>;
71
+ /**
72
+ * Claim a dispatch for the turn about to run it. Returns false — run nothing — for a stale
73
+ * delivery of a record another turn already absorbed (see `absorbPending`).
74
+ */
75
+ markStarted(id: string | undefined): Promise<boolean>;
76
+ /**
77
+ * Fold other not-yet-started dispatches of `channelId` that `accept` into the turn that is
78
+ * starting `primaryId`, oldest first, at most `limit` of them. Each one is claimed exactly as
79
+ * `markStarted` would claim it (running, leased, counted as a delivery), so the caller must
80
+ * finish every returned id with `markCompleted` / `markRetryable` alongside the primary — and a
81
+ * crash mid-turn redelivers each of them on its own, unchanged. Returned events carry their
82
+ * own redelivery notice, like a normal delivery would.
83
+ */
84
+ absorbPending(channelId: string, primaryId: string, accept: (event: ChannelEvent) => boolean, limit: number): Promise<ChannelEvent[]>;
85
+ /** Not started anywhere: still waiting for delivery (`pending`) or queued behind the current turn. */
86
+ private isAbsorbable;
61
87
  markCompleted(id: string | undefined): Promise<void>;
62
88
  /** Release a failed handler's in-process claim without deleting its durable record. Structured
63
89
  * wake activation uses this for transient task/job/run persistence failures so the next drain
@@ -55,6 +55,40 @@ function withRedeliveryNotice(event, deliveries) {
55
55
  event.text,
56
56
  };
57
57
  }
58
+ /**
59
+ * What a wake was for, in the user's terms (spec 053, D2). The wake's own `text` is a prompt for
60
+ * the model and its `user` an internal producer tag (`TASK_DRIVER`, `SUBAGENT`, …), so neither
61
+ * may reach the chat; every in-process producer prefixes its text with a `[KIND:id…]` tag, which
62
+ * is what this reads instead.
63
+ */
64
+ function describeWakeSource(event) {
65
+ const tag = /^\[(TASK_DRIVER|SUBAGENT|JOB|EVENT):([^:\]\s]+)/.exec(event.text);
66
+ const id = tag?.[2];
67
+ switch (tag?.[1]) {
68
+ case "TASK_DRIVER":
69
+ return { label: `任务 \`${id}\` 的一次后台唤醒`, nextStep: `用 \`/tasks show ${id}\` 确认任务状态` };
70
+ case "SUBAGENT":
71
+ return { label: `委派 \`${id}\` 的完成通知`, nextStep: `用 \`/subagents show ${id}\` 查看结果` };
72
+ case "JOB":
73
+ return { label: `后台作业 \`${id}\` 的完成通知`, nextStep: "需要时让我查看这个作业的结果" };
74
+ case "EVENT": {
75
+ const name = id?.replace(/\.json$/, "");
76
+ return { label: `定时事件 \`${name}\` 的一次触发`, nextStep: `用 \`/events history ${name}\` 查看触发记录` };
77
+ }
78
+ default:
79
+ return { label: "一次后台唤醒" };
80
+ }
81
+ }
82
+ /**
83
+ * The notice a channel gets when a wake is given up on (`onExhausted`). It names the source and
84
+ * the record's absolute path — never the wake text, which is a model prompt (spec 053, D2/D6).
85
+ */
86
+ export function renderDispatchExhaustedNotice(record, stateDir) {
87
+ const source = describeWakeSource(record.event);
88
+ const where = `排查记录在 \`${recordPath(stateDir, record.id)}\``;
89
+ return (`⚠️ ${source.label}连续 ${record.deliveries} 次未能完成,已停止重试。\n` +
90
+ (source.nextStep ? `${source.nextStep};${where}。` : `${where}。`));
91
+ }
58
92
  function dispatchId(event) {
59
93
  return createHash("sha256")
60
94
  .update(JSON.stringify([event.channelId, event.user, event.ts, event.text, event.conversationId]))
@@ -105,6 +139,12 @@ export class DurableDispatchService {
105
139
  * lease lapses.
106
140
  */
107
141
  this.running = new Set();
142
+ /**
143
+ * Queued dispatch ids folded into another record's turn by `absorbPending`. Each still has its
144
+ * own closure waiting in the channel queue; `markStarted` turns that stale delivery away instead
145
+ * of running the same wake a second time.
146
+ */
147
+ this.absorbed = new Set();
108
148
  this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;
109
149
  }
110
150
  start() {
@@ -121,7 +161,7 @@ export class DurableDispatchService {
121
161
  */
122
162
  drainSafely() {
123
163
  this.drainOnce().catch((error) => {
124
- log.logWarning("Durable dispatch drain failed", errorMessage(error));
164
+ log.logWarn("dispatch.drain.failed", "Durable dispatch drain failed", { reason: errorMessage(error) });
125
165
  });
126
166
  }
127
167
  stop() {
@@ -179,6 +219,8 @@ export class DurableDispatchService {
179
219
  // Drop the liveness claim too, or the renew branch above would keep this record
180
220
  // alive forever and the cancelled turn would never be redelivered.
181
221
  this.running.delete(id);
222
+ // `/stop` already dropped the queued closures; the redelivery must not be turned away.
223
+ this.absorbed.delete(id);
182
224
  record.leaseExpiresAt = undefined;
183
225
  await this.write(record);
184
226
  canceled++;
@@ -186,9 +228,15 @@ export class DurableDispatchService {
186
228
  }
187
229
  return canceled;
188
230
  }
231
+ /**
232
+ * Claim a dispatch for the turn about to run it. Returns false — run nothing — for a stale
233
+ * delivery of a record another turn already absorbed (see `absorbPending`).
234
+ */
189
235
  async markStarted(id) {
190
236
  if (!id)
191
- return;
237
+ return true;
238
+ if (this.absorbed.delete(id))
239
+ return false;
192
240
  this.running.add(id);
193
241
  await this.queue.run(id, async () => {
194
242
  const record = await this.read(id);
@@ -198,6 +246,63 @@ export class DurableDispatchService {
198
246
  record.leaseExpiresAt = new Date(Date.now() + this.leaseMs).toISOString();
199
247
  await this.write(record);
200
248
  });
249
+ return true;
250
+ }
251
+ /**
252
+ * Fold other not-yet-started dispatches of `channelId` that `accept` into the turn that is
253
+ * starting `primaryId`, oldest first, at most `limit` of them. Each one is claimed exactly as
254
+ * `markStarted` would claim it (running, leased, counted as a delivery), so the caller must
255
+ * finish every returned id with `markCompleted` / `markRetryable` alongside the primary — and a
256
+ * crash mid-turn redelivers each of them on its own, unchanged. Returned events carry their
257
+ * own redelivery notice, like a normal delivery would.
258
+ */
259
+ async absorbPending(channelId, primaryId, accept, limit) {
260
+ if (limit <= 0)
261
+ return [];
262
+ let filenames;
263
+ try {
264
+ filenames = (await readdir(this.options.stateDir)).filter((name) => name.endsWith(".json"));
265
+ }
266
+ catch {
267
+ return [];
268
+ }
269
+ const candidates = [];
270
+ for (const filename of filenames) {
271
+ const id = decodeDispatchId(filename.slice(0, -".json".length));
272
+ if (id === primaryId || this.running.has(id))
273
+ continue;
274
+ const record = await this.read(id);
275
+ if (record && this.isAbsorbable(record, channelId, accept))
276
+ candidates.push({ id, createdAt: record.createdAt });
277
+ }
278
+ candidates.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
279
+ const events = [];
280
+ for (const { id } of candidates.slice(0, limit)) {
281
+ await this.queue.run(id, async () => {
282
+ // Re-checked under the record's own lock: a drain or its own delivery may have moved it.
283
+ const record = await this.read(id);
284
+ if (!record || this.running.has(id) || !this.isAbsorbable(record, channelId, accept))
285
+ return;
286
+ if (record.status === "queued")
287
+ this.absorbed.add(id);
288
+ else
289
+ record.deliveries++;
290
+ record.status = "running";
291
+ record.leaseExpiresAt = new Date(Date.now() + this.leaseMs).toISOString();
292
+ record.nextAttemptAt = undefined;
293
+ this.running.add(id);
294
+ await this.write(record);
295
+ events.push(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
296
+ });
297
+ }
298
+ return events;
299
+ }
300
+ /** Not started anywhere: still waiting for delivery (`pending`) or queued behind the current turn. */
301
+ isAbsorbable(record, channelId, accept) {
302
+ return (record.event.channelId === channelId &&
303
+ (record.status === "pending" || record.status === "queued") &&
304
+ record.deliveries < MAX_DELIVERIES &&
305
+ accept(record.event));
201
306
  }
202
307
  async markCompleted(id) {
203
308
  if (!id)
@@ -283,7 +388,10 @@ export class DurableDispatchService {
283
388
  await this.options.onExhausted?.(record);
284
389
  }
285
390
  catch (err) {
286
- log.logWarning(`Dispatch onExhausted handler failed for ${id}`, errorMessage(err));
391
+ log.logWarn("dispatch.exhausted_handler.failed", "Exhausted-dispatch handler failed", {
392
+ reason: errorMessage(err),
393
+ fields: { dispatchId: id },
394
+ });
287
395
  }
288
396
  return;
289
397
  }