@oyasmi/pipiclaw 0.9.3-beta.6 → 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 (118) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.js +137 -61
  4. package/dist/agent/command-extension.js +47 -34
  5. package/dist/agent/job-manager.js +31 -11
  6. package/dist/agent/model-fallback.js +1 -1
  7. package/dist/agent/prompt/manifest.d.ts +6 -1
  8. package/dist/agent/prompt/manifest.js +45 -64
  9. package/dist/agent/prompt/resources.js +4 -1
  10. package/dist/agent/run-queue.js +7 -2
  11. package/dist/agent/session-adapter.js +1 -1
  12. package/dist/agent/session-events.js +17 -6
  13. package/dist/agent/session-resource-gate.js +3 -1
  14. package/dist/agent/status-render.d.ts +0 -1
  15. package/dist/agent/status-render.js +4 -16
  16. package/dist/agent/turn-error.d.ts +31 -0
  17. package/dist/agent/turn-error.js +68 -0
  18. package/dist/app-services.js +7 -4
  19. package/dist/channel/channel-index.d.ts +9 -2
  20. package/dist/channel/channel-index.js +29 -7
  21. package/dist/channel/project-scope-store.js +1 -1
  22. package/dist/commands/catalog.d.ts +21 -4
  23. package/dist/commands/catalog.js +88 -41
  24. package/dist/commands/reply-limits.d.ts +6 -0
  25. package/dist/commands/reply-limits.js +24 -0
  26. package/dist/events/event-commands.js +94 -44
  27. package/dist/events/event-validation.d.ts +13 -2
  28. package/dist/events/event-validation.js +17 -9
  29. package/dist/events/events.js +77 -32
  30. package/dist/executor.js +2 -2
  31. package/dist/log.d.ts +12 -2
  32. package/dist/log.js +26 -34
  33. package/dist/main.js +1 -1
  34. package/dist/memory/commands.js +29 -23
  35. package/dist/memory/lifecycle.js +26 -5
  36. package/dist/memory/maintenance-state.js +4 -1
  37. package/dist/memory/scheduler.js +3 -1
  38. package/dist/models/auth-cli.js +3 -2
  39. package/dist/paths.d.ts +2 -0
  40. package/dist/paths.js +9 -0
  41. package/dist/playbooks/agent-delegation.md +2 -2
  42. package/dist/runtime/app-home.d.ts +6 -0
  43. package/dist/runtime/app-home.js +21 -3
  44. package/dist/runtime/bootstrap.js +192 -64
  45. package/dist/runtime/channel-queue.js +1 -1
  46. package/dist/runtime/delivery.js +29 -15
  47. package/dist/runtime/dingtalk.js +96 -42
  48. package/dist/runtime/durable-dispatch.d.ts +27 -1
  49. package/dist/runtime/durable-dispatch.js +111 -3
  50. package/dist/runtime/project-commands.js +16 -15
  51. package/dist/runtime/proxy.js +4 -2
  52. package/dist/runtime/report-commands.js +1 -1
  53. package/dist/runtime/skill-commands.d.ts +1 -1
  54. package/dist/runtime/skill-commands.js +17 -10
  55. package/dist/runtime/subagent-commands.d.ts +5 -4
  56. package/dist/runtime/subagent-commands.js +116 -77
  57. package/dist/runtime/task-commands.d.ts +1 -1
  58. package/dist/runtime/task-commands.js +110 -64
  59. package/dist/runtime/task-driver.d.ts +6 -3
  60. package/dist/runtime/task-driver.js +57 -22
  61. package/dist/runtime/task-migration.d.ts +7 -2
  62. package/dist/runtime/task-migration.js +247 -61
  63. package/dist/runtime/task-spawn.js +12 -5
  64. package/dist/runtime/wake-coalescing.d.ts +18 -0
  65. package/dist/runtime/wake-coalescing.js +29 -0
  66. package/dist/security/block-message.d.ts +22 -1
  67. package/dist/security/block-message.js +66 -1
  68. package/dist/security/network.d.ts +2 -1
  69. package/dist/security/network.js +3 -2
  70. package/dist/security/path-guard-check.js +2 -2
  71. package/dist/settings.d.ts +3 -2
  72. package/dist/settings.js +4 -1
  73. package/dist/shared/format.d.ts +12 -0
  74. package/dist/shared/format.js +37 -0
  75. package/dist/shared/host-process.js +15 -3
  76. package/dist/shared/with-timeout.d.ts +3 -2
  77. package/dist/shared/with-timeout.js +14 -3
  78. package/dist/subagents/external/claude-code.js +23 -1
  79. package/dist/subagents/external/progress-tail.d.ts +17 -0
  80. package/dist/subagents/external/progress-tail.js +64 -17
  81. package/dist/subagents/external/run.d.ts +3 -0
  82. package/dist/subagents/external/run.js +21 -7
  83. package/dist/subagents/external/settlement.d.ts +3 -0
  84. package/dist/subagents/external/settlement.js +1 -1
  85. package/dist/subagents/runs.d.ts +21 -1
  86. package/dist/subagents/runs.js +137 -32
  87. package/dist/subagents/tool.d.ts +22 -15
  88. package/dist/subagents/tool.js +226 -32
  89. package/dist/subagents/workspace-summary.d.ts +16 -4
  90. package/dist/subagents/workspace-summary.js +74 -18
  91. package/dist/tasks/board.d.ts +8 -1
  92. package/dist/tasks/board.js +37 -2
  93. package/dist/tasks/frontmatter.d.ts +5 -0
  94. package/dist/tasks/frontmatter.js +8 -0
  95. package/dist/tasks/log.d.ts +11 -1
  96. package/dist/tasks/log.js +58 -2
  97. package/dist/tasks/store.d.ts +18 -1
  98. package/dist/tasks/store.js +61 -9
  99. package/dist/tasks/ticket.d.ts +3 -1
  100. package/dist/tasks/ticket.js +19 -1
  101. package/dist/tools/bash.js +2 -2
  102. package/dist/tools/index.d.ts +2 -0
  103. package/dist/tools/index.js +1 -0
  104. package/dist/tools/memory-manage.js +4 -1
  105. package/dist/tools/subagent-manage.d.ts +1 -1
  106. package/dist/tools/subagent-manage.js +16 -11
  107. package/dist/tools/task-manage/step-end.js +4 -1
  108. package/dist/tools/tool-details.d.ts +10 -2
  109. package/dist/tools/tool-details.js +39 -2
  110. package/dist/tui/cli.js +2 -2
  111. package/dist/tui/commands.js +4 -4
  112. package/dist/tui/pitui-frontend.js +1 -1
  113. package/dist/tui/renderer.js +3 -2
  114. package/dist/tui/turn-controller.d.ts +2 -0
  115. package/dist/tui/turn-controller.js +36 -21
  116. package/dist/usage/ledger.js +3 -1
  117. package/dist/usage/render.js +3 -1
  118. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import * as log from "../log.js";
2
+ import { formatElapsedZh } from "../shared/format.js";
2
3
  import { errorMessage } from "../shared/text-utils.js";
3
4
  const MIN_UPDATE_INTERVAL_MS = 800;
4
5
  const ROLLING_WINDOW_SIZE = 3;
@@ -76,7 +77,10 @@ class ChannelDeliveryController {
76
77
  }
77
78
  const delivered = await this.bot.sendPlain(this.event.channelId, text);
78
79
  if (!delivered) {
79
- log.logWarning(`[${this.event.channelId}] Failed to send light notice`, text.substring(0, 200));
80
+ log.logWarn("delivery.notice.failed", "Light notice delivery failed", {
81
+ channelId: this.event.channelId,
82
+ fields: { text: text.substring(0, 200) },
83
+ });
80
84
  }
81
85
  },
82
86
  setTyping: async (_isTyping) => { },
@@ -117,7 +121,10 @@ class ChannelDeliveryController {
117
121
  }
118
122
  archiveBotResponse(text) {
119
123
  void this.store.logBotResponse(this.event.channelId, text, Date.now().toString()).catch((err) => {
120
- log.logWarning(`[${this.event.channelId}] Failed to archive bot response`, errorMessage(err));
124
+ log.logWarn("channel.archive.write_failed", "Bot response archive failed", {
125
+ channelId: this.event.channelId,
126
+ reason: errorMessage(err),
127
+ });
121
128
  });
122
129
  }
123
130
  async appendProgress(text, shouldLog) {
@@ -275,7 +282,7 @@ class ChannelDeliveryController {
275
282
  if (content || this.cardWarmupTriggered) {
276
283
  const finalProgressText = this.progressStyle === "rolling"
277
284
  ? this.buildSummaryText()
278
- : [body, "答复已发送。"].filter(Boolean).join("\n\n");
285
+ : [body, "已答复。"].filter(Boolean).join("\n\n");
279
286
  touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, finalProgressText, this.cardGeneration);
280
287
  }
281
288
  }
@@ -287,12 +294,15 @@ class ChannelDeliveryController {
287
294
  }
288
295
  else if (mode === "silent") {
289
296
  if (content) {
290
- touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "处理已结束。"].filter(Boolean).join("\n\n"), this.cardGeneration);
297
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "已处理,无需答复。"].filter(Boolean).join("\n\n"), this.cardGeneration);
291
298
  }
292
299
  }
293
300
  }
294
301
  catch (err) {
295
- log.logWarning(`[${this.event.channelId}] Delivery sync failed`, errorMessage(err));
302
+ log.logWarn("delivery.sync.failed", "Delivery sync failed", {
303
+ channelId: this.event.channelId,
304
+ reason: errorMessage(err),
305
+ });
296
306
  if (mode === "progress") {
297
307
  this.progressFailures++;
298
308
  this.replayRequired = true;
@@ -335,7 +345,10 @@ class ChannelDeliveryController {
335
345
  this.flushWaiters.push(resolve);
336
346
  deadlineTimer = setTimeout(() => {
337
347
  if (this.flushWaiters.includes(resolve)) {
338
- log.logWarning(`[${this.event.channelId}] Delivery flush deadline exceeded (${FLUSH_DEADLINE_MS}ms); releasing caller`);
348
+ log.logWarn("delivery.flush.timeout", "Delivery flush deadline exceeded; releasing caller", {
349
+ channelId: this.event.channelId,
350
+ fields: { deadlineMs: FLUSH_DEADLINE_MS },
351
+ });
339
352
  this.flushWaiters = this.flushWaiters.filter((waiter) => waiter !== resolve);
340
353
  resolve();
341
354
  }
@@ -369,25 +382,26 @@ class ChannelDeliveryController {
369
382
  this.progressTextDirty = false;
370
383
  return this.cachedProgressText;
371
384
  }
372
- formatElapsed(ms) {
385
+ /** Clock-style elapsed time (`0:42`, `1:02`, `1:05:09`) for the narrow rolling header. */
386
+ formatClock(ms) {
373
387
  const seconds = Math.max(0, Math.round(ms / 1000));
374
- if (seconds < 60)
375
- return `${seconds}s`;
376
388
  const minutes = Math.floor(seconds / 60);
389
+ const ss = String(seconds % 60).padStart(2, "0");
377
390
  if (minutes < 60)
378
- return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
379
- return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
391
+ return `${minutes}:${ss}`;
392
+ return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${ss}`;
380
393
  }
381
394
  elapsedMs() {
382
395
  return this.progressStartedAt > 0 ? Date.now() - this.progressStartedAt : 0;
383
396
  }
384
397
  /**
385
398
  * Standing first line for rolling mode. The window only keeps the last few entries, so a long
386
- * turn otherwise gave no way to tell "still working, 14 steps in" from "stuck": every visible
387
- * line looked the same as a minute ago. The numbers are already tracked for the closing summary.
399
+ * turn otherwise gave no way to tell "still working, 14 tool calls in" from "stuck": every
400
+ * visible line looked the same as a minute ago. The numbers are already tracked for the closing
401
+ * summary. Counted as tool calls, never "steps" — a step is a task's unit (spec 053, D4).
388
402
  */
389
403
  buildRollingHeader() {
390
- return `⏱ ${this.formatElapsed(this.elapsedMs())} · ${this.toolCallCount} 步`;
404
+ return `⏱ ${this.formatClock(this.elapsedMs())} · 工具 ${this.toolCallCount}`;
391
405
  }
392
406
  trimToRecentEntries(maxEntries) {
393
407
  let entryCount = 0;
@@ -415,7 +429,7 @@ class ChannelDeliveryController {
415
429
  this.sentProgressChars = 0;
416
430
  }
417
431
  buildSummaryText() {
418
- return `完成 · ${this.toolCallCount} 步 · ${this.formatElapsed(this.elapsedMs())}`;
432
+ return `完成 · 工具调用 ${this.toolCallCount} 次 · ${formatElapsedZh(this.elapsedMs())}`;
419
433
  }
420
434
  }
421
435
  /**
@@ -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