@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
@@ -11,7 +11,7 @@ import { createChannelIndex } from "../channel/channel-index.js";
11
11
  import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
12
12
  import { resolveProjectScope } from "../channel/project-scope-store.js";
13
13
  import { ChannelStore } from "../channel/store.js";
14
- import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
14
+ import { BUILT_IN_COMMANDS, formatMissingQueueMessage, formatNewSessionReply, formatSteerQueued, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
15
15
  import { createEventsWatcher } from "../events/events.js";
16
16
  import { createExecutor } from "../executor.js";
17
17
  import * as log from "../log.js";
@@ -32,10 +32,10 @@ import { consumeTaskNotice } from "../tasks/steer.js";
32
32
  import { pauseTask as pauseStoredTask } from "../tasks/store.js";
33
33
  import { getToolsConfigPath, loadToolsConfig } from "../tools/config.js";
34
34
  import { getUsageLedger } from "../usage/ledger.js";
35
- import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
35
+ import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, printFirstRunGuide, readCliVersion, } from "./app-home.js";
36
36
  import { createDingTalkContext } from "./delivery.js";
37
37
  import { DingTalkBot, } from "./dingtalk.js";
38
- import { DurableDispatchService } from "./durable-dispatch.js";
38
+ import { DurableDispatchService, renderDispatchExhaustedNotice } from "./durable-dispatch.js";
39
39
  import { extensionForMimeType } from "./inbound-media.js";
40
40
  import { runReportCommand } from "./report-commands.js";
41
41
  import { renderRunNotice } from "./subagent-commands.js";
@@ -43,6 +43,7 @@ import { createTaskDriverEvent, parseDriverTaskId, TaskDriver } from "./task-dri
43
43
  import { migrateTasksToV5 } from "./task-migration.js";
44
44
  import { createTaskSpawner } from "./task-spawn.js";
45
45
  import { claimVerifiedWake } from "./task-wake.js";
46
+ import { isCoalescableWake, MAX_COALESCED_WAKES, mergeCompletionWakes } from "./wake-coalescing.js";
46
47
  const SHUTDOWN_WAIT_MS = 15000;
47
48
  const SHUTDOWN_FLUSH_WAIT_MS = 45000;
48
49
  const SHUTDOWN_ABORT_WAIT_MS = 5000;
@@ -83,7 +84,10 @@ async function evictIdleRunnersOverCap(channelRunners) {
83
84
  continue;
84
85
  channelRunners.delete(channelId);
85
86
  await runner.dispose().catch((err) => {
86
- log.logWarning(`[${channelId}] Failed to dispose evicted runner`, errorMessage(err));
87
+ log.logWarn("runtime.runner.evict_dispose_failed", "Evicted runner dispose failed", {
88
+ channelId: channelId,
89
+ reason: errorMessage(err),
90
+ });
87
91
  });
88
92
  }
89
93
  }
@@ -165,7 +169,11 @@ function createDingTalkHandler(deps) {
165
169
  return { taskId, brief };
166
170
  }
167
171
  catch (error) {
168
- log.logWarning(`[${event.channelId}] Could not start task step for ${taskId}`, errorMessage(error));
172
+ log.logWarn("taskdriver.step.start_failed", "Task step start failed", {
173
+ channelId: event.channelId,
174
+ reason: errorMessage(error),
175
+ fields: { taskId },
176
+ });
169
177
  return undefined;
170
178
  }
171
179
  };
@@ -181,11 +189,18 @@ function createDingTalkHandler(deps) {
181
189
  if (delivered)
182
190
  await store.logBotResponse(channelId, notice, Date.now().toString());
183
191
  else
184
- log.logWarning(`[${channelId}] Failed to deliver task notice for ${taskId}`);
192
+ log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
193
+ channelId: channelId,
194
+ fields: { taskId },
195
+ });
185
196
  }
186
197
  }
187
198
  catch (error) {
188
- log.logWarning(`[${channelId}] Could not deliver task notice for ${taskId}`, errorMessage(error));
199
+ log.logWarn("taskdriver.notice.delivery_failed", "Task notice delivery failed", {
200
+ channelId: channelId,
201
+ reason: errorMessage(error),
202
+ fields: { taskId },
203
+ });
189
204
  }
190
205
  await getRunner(channelId).bindChatSession();
191
206
  };
@@ -212,28 +227,43 @@ function createDingTalkHandler(deps) {
212
227
  reason: "用户 /stop 中止了该任务的当前步骤。",
213
228
  });
214
229
  pausedTaskId = taskId;
215
- log.logInfo(`[${channelId}] Paused task ${taskId} on /stop`);
230
+ log.logInfoEvent("tasks.task.paused_on_stop", "Task paused on /stop", {
231
+ channelId: channelId,
232
+ fields: { taskId },
233
+ });
216
234
  }
217
235
  _bot.discardCard(channelId);
218
236
  // Drop queued-but-not-started messages so a burst does not keep
219
237
  // running after the user asked to halt; abort the in-flight one.
220
238
  const dropped = _bot.clearPendingMessages(channelId);
221
239
  if (dropped > 0) {
222
- log.logInfo(`[${channelId}] Dropped ${dropped} queued message(s) on stop`);
240
+ log.logInfoEvent("agent.turn.queue_dropped", "Queued messages dropped on /stop", {
241
+ channelId: channelId,
242
+ fields: { count: dropped },
243
+ });
223
244
  }
224
245
  void runner.abort().catch((err) => {
225
- log.logWarning(`[${channelId}] Failed to abort run`, errorMessage(err));
246
+ log.logWarn("agent.turn.abort_failed", "Turn abort failed", {
247
+ channelId: channelId,
248
+ reason: errorMessage(err),
249
+ });
226
250
  });
227
251
  void getDurableDispatch()
228
252
  ?.cancelChannel(channelId)
229
253
  .then((canceled) => {
230
254
  if (canceled)
231
- log.logInfo(`[${channelId}] Reset ${canceled} durable-dispatch lease(s) on stop`);
255
+ log.logInfoEvent("dispatch.cancel.reset", "Durable dispatch leases reset on /stop", {
256
+ channelId: channelId,
257
+ fields: { count: canceled },
258
+ });
232
259
  })
233
260
  .catch((err) => {
234
- log.logWarning(`[${channelId}] Failed to reset durable-dispatch leases on stop`, errorMessage(err));
261
+ log.logWarn("dispatch.cancel.failed", "Durable dispatch lease reset on stop failed", {
262
+ channelId: channelId,
263
+ reason: errorMessage(err),
264
+ });
235
265
  });
236
- log.logInfo(`[${channelId}] Stop requested`);
266
+ log.logInfoEvent("agent.turn.stop_requested", "Stop requested", { channelId: channelId });
237
267
  if (!stopWatchdogs.has(channelId)) {
238
268
  stopWatchdogs.add(channelId);
239
269
  void forceEndStuckTurnAfterStop({
@@ -243,7 +273,10 @@ function createDingTalkHandler(deps) {
243
273
  notify: (text) => _bot.sendPlain(channelId, text),
244
274
  })
245
275
  .catch((err) => {
246
- log.logWarning(`[${channelId}] Stop watchdog failed`, errorMessage(err));
276
+ log.logWarn("agent.turn.stop_watchdog_failed", "Stop watchdog failed", {
277
+ channelId: channelId,
278
+ reason: errorMessage(err),
279
+ });
247
280
  })
248
281
  .finally(() => {
249
282
  stopWatchdogs.delete(channelId);
@@ -279,14 +312,20 @@ function createDingTalkHandler(deps) {
279
312
  catch (error) {
280
313
  // The active pointer already names the new session. Retirement is
281
314
  // best-effort cleanup and must not misreport the committed reset as failed.
282
- log.logWarning(`[${event.channelId}] Old runner retirement failed after /new`, errorMessage(error));
315
+ log.logWarn("agent.session.retire_failed", "Old runner retirement after /new failed", {
316
+ channelId: event.channelId,
317
+ reason: errorMessage(error),
318
+ });
283
319
  }
284
320
  }
285
321
  const dropped = _bot.resetChannelQueue(event.channelId);
286
322
  if (dropped > 0) {
287
- log.logInfo(`[${event.channelId}] /new discarded ${dropped} queued old-session message(s)`);
323
+ log.logInfoEvent("agent.session.queue_dropped", "Old-session queued messages discarded by /new", {
324
+ channelId: event.channelId,
325
+ fields: { count: dropped },
326
+ });
288
327
  }
289
- await _bot.sendPlain(event.channelId, `已开启新会话。\n\nSession ID: \`${result.sessionId}\``);
328
+ await _bot.sendPlain(event.channelId, formatNewSessionReply(result.sessionId));
290
329
  void archiveIncomingMessage(event.channelId, {
291
330
  date: new Date().toISOString(),
292
331
  ts: event.ts,
@@ -299,8 +338,11 @@ function createDingTalkHandler(deps) {
299
338
  }
300
339
  catch (error) {
301
340
  const message = errorMessage(error);
302
- log.logWarning(`[${event.channelId}] Failed to create a fresh session`, message);
303
- await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n\n旧会话仍保持不变;请重试 \`/new\`。`);
341
+ log.logWarn("agent.session.create_failed", "Fresh session creation failed", {
342
+ channelId: event.channelId,
343
+ reason: message,
344
+ });
345
+ await _bot.sendPlain(event.channelId, `新会话创建失败:${message}\n旧会话保持不变,可以重试 \`/new\`。`);
304
346
  }
305
347
  });
306
348
  sessionResetChains.set(event.channelId, reset);
@@ -333,7 +375,10 @@ function createDingTalkHandler(deps) {
333
375
  const runner = channelRunners.get(channelId);
334
376
  channelRunners.delete(channelId);
335
377
  await runner?.dispose().catch((err) => {
336
- log.logWarning(`[${channelId}] Failed to dispose runner after /project`, errorMessage(err));
378
+ log.logWarn("runtime.runner.dispose_failed", "Runner dispose after /project failed", {
379
+ channelId: channelId,
380
+ reason: errorMessage(err),
381
+ });
337
382
  });
338
383
  },
339
384
  dispatchTask: async (id) => {
@@ -358,15 +403,16 @@ function createDingTalkHandler(deps) {
358
403
  const runner = getRunner(event.channelId);
359
404
  const trimmedQueueText = queueText.trim();
360
405
  if (!trimmedQueueText) {
361
- const commandName = mode === "followUp" ? "followup" : "steer";
362
- await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
406
+ await bot.sendPlain(event.channelId, formatMissingQueueMessage(mode === "followUp" ? "followup" : "steer"));
363
407
  return { kind: "handled" };
364
408
  }
365
409
  // Compaction is maintenance, not user work. A new message cancels it and is
366
410
  // kept as a normal queued turn instead of trying to steer an agent loop that
367
411
  // is currently disconnected for summarization.
368
412
  if (runner.interruptCompaction()) {
369
- log.logInfo(`[${event.channelId}] Interrupted compaction for a new user message`);
413
+ log.logInfoEvent("agent.compaction.interrupted", "Compaction interrupted for a new user message", {
414
+ channelId: event.channelId,
415
+ });
370
416
  return { kind: "requeue", text: trimmedQueueText };
371
417
  }
372
418
  // A task step runs in the task's own session and is muted: a steer here would land in
@@ -401,10 +447,7 @@ function createDingTalkHandler(deps) {
401
447
  skipContextSync: true,
402
448
  images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
403
449
  }, `${mode} message`);
404
- const confirmation = event.text.trim().startsWith("/")
405
- ? "已作为 steer 排队,当前工具步骤结束后生效。"
406
- : "已作为 steer 排队,当前工具步骤结束后生效。想等整个回合结束再执行,用 `/followup <消息>`。";
407
- await bot.sendPlain(event.channelId, confirmation);
450
+ await bot.sendPlain(event.channelId, formatSteerQueued(!event.text.trim().startsWith("/")));
408
451
  log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
409
452
  ctx: { channelId: event.channelId, userName: event.userName },
410
453
  fields: { messageLength: trimmedQueueText.length },
@@ -414,11 +457,18 @@ function createDingTalkHandler(deps) {
414
457
  catch (err) {
415
458
  const errMsg = errorMessage(err);
416
459
  if (isNoRunningTaskQueueError(err)) {
417
- log.logInfo(`[${event.channelId}] Busy ${mode} window closed; requeueing as a normal message`);
460
+ log.logInfoEvent("agent.turn.requeued", "Busy window closed; message requeued as a normal turn", {
461
+ channelId: event.channelId,
462
+ fields: { mode },
463
+ });
418
464
  return { kind: "requeue", text: trimmedQueueText };
419
465
  }
420
- log.logWarning(`[${event.channelId}] Failed to queue ${mode}`, errMsg);
421
- await bot.sendPlain(event.channelId, `无法排队这条消息:${errMsg}`);
466
+ log.logWarn("agent.turn.queue_failed", "Busy message queueing failed", {
467
+ channelId: event.channelId,
468
+ reason: errMsg,
469
+ fields: { mode },
470
+ });
471
+ await bot.sendPlain(event.channelId, `这条消息没能排进当前回合:${errMsg}\n等当前回合结束后重发,或用 \`/followup <消息>\` 排到它之后。`);
422
472
  return { kind: "handled" };
423
473
  }
424
474
  },
@@ -443,7 +493,10 @@ function createDingTalkHandler(deps) {
443
493
  };
444
494
  }
445
495
  catch (err) {
446
- log.logWarning(`[${channelId}] Failed to persist inbound image`, errorMessage(err));
496
+ log.logWarn("dingtalk.media.persist_failed", "Inbound image persist failed", {
497
+ channelId: channelId,
498
+ reason: errorMessage(err),
499
+ });
447
500
  return null;
448
501
  }
449
502
  },
@@ -455,12 +508,40 @@ function createDingTalkHandler(deps) {
455
508
  async handleEvent(inboundEvent, bot, _isEvent) {
456
509
  let event = inboundEvent;
457
510
  if (isShuttingDown()) {
458
- log.logInfo(`[${event.channelId}] Ignoring event during shutdown`);
511
+ log.logInfoEvent("runtime.shutdown.event_ignored", "Event ignored during shutdown", {
512
+ channelId: event.channelId,
513
+ });
459
514
  return;
460
515
  }
461
516
  const runner = getRunner(event.channelId);
462
- await getDurableDispatch()?.markStarted(event.dispatchId);
517
+ const durable = getDurableDispatch();
518
+ if (durable && !(await durable.markStarted(event.dispatchId))) {
519
+ // A stale delivery of a wake an earlier turn already absorbed and handled.
520
+ runner.endTurn();
521
+ return;
522
+ }
463
523
  let structuredWakeFinalized = event.internalWake === undefined;
524
+ /** Other completion wakes folded into this turn; finished together with this one. */
525
+ let absorbedDispatchIds = [];
526
+ if (durable && event.dispatchId && isCoalescableWake(event)) {
527
+ const absorbed = await durable
528
+ .absorbPending(event.channelId, event.dispatchId, isCoalescableWake, MAX_COALESCED_WAKES - 1)
529
+ .catch((error) => {
530
+ log.logWarn("dispatch.wake.absorb_failed", "Wake coalescing failed", {
531
+ channelId: event.channelId,
532
+ reason: errorMessage(error),
533
+ });
534
+ return [];
535
+ });
536
+ if (absorbed.length > 0) {
537
+ event = mergeCompletionWakes(event, absorbed);
538
+ absorbedDispatchIds = absorbed.flatMap((absorbedEvent) => absorbedEvent.dispatchId ? [absorbedEvent.dispatchId] : []);
539
+ log.logInfoEvent("dispatch.wake.coalesced", "Completion wakes coalesced", {
540
+ channelId: event.channelId,
541
+ fields: { primary: event.dispatchId, absorbed: absorbedDispatchIds.length },
542
+ });
543
+ }
544
+ }
464
545
  const task = (async () => {
465
546
  let baseCtx;
466
547
  try {
@@ -504,7 +585,10 @@ function createDingTalkHandler(deps) {
504
585
  markdown: true,
505
586
  });
506
587
  if (!delivered) {
507
- log.logWarning(`[${event.channelId}] Failed to deliver /${builtInCommand.name} reply`, `${response.length} chars`);
588
+ log.logWarn("delivery.command_reply.failed", "Command reply delivery failed", {
589
+ channelId: event.channelId,
590
+ fields: { command: builtInCommand.name, chars: response.length },
591
+ });
508
592
  }
509
593
  }
510
594
  else if (isRunnerBuiltInCommand(builtInCommand)) {
@@ -547,7 +631,10 @@ function createDingTalkHandler(deps) {
547
631
  const { kind, resourceId, taskId: wakeTaskId } = event.internalWake;
548
632
  const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
549
633
  if (!claimed) {
550
- log.logWarning(`[${event.channelId}] Ignored an unverifiable ${kind} wake for ${resourceId} claiming task ${wakeTaskId}`);
634
+ log.logWarn("dispatch.wake.unverified", "Unverifiable wake ignored", {
635
+ channelId: event.channelId,
636
+ fields: { kind, resourceId, taskId: wakeTaskId },
637
+ });
551
638
  structuredWakeFinalized = true;
552
639
  return;
553
640
  }
@@ -574,7 +661,7 @@ function createDingTalkHandler(deps) {
574
661
  if (taskStep)
575
662
  await finishTaskStep(event.channelId, taskStep.taskId, bot);
576
663
  if (result.stopReason === "aborted" && runner.getTurnStatus().stopRequested) {
577
- log.logInfo(`[${event.channelId}] Stopped`);
664
+ log.logInfoEvent("agent.turn.stopped", "Turn stopped", { channelId: event.channelId });
578
665
  }
579
666
  }
580
667
  catch (err) {
@@ -585,12 +672,19 @@ function createDingTalkHandler(deps) {
585
672
  }
586
673
  finally {
587
674
  await baseCtx?.close().catch((error) => {
588
- log.logWarning(`[${event.channelId}] Failed to close delivery`, errorMessage(error));
675
+ log.logWarn("delivery.close.failed", "Delivery close failed", {
676
+ channelId: event.channelId,
677
+ reason: errorMessage(error),
678
+ });
589
679
  });
590
680
  if (structuredWakeFinalized)
591
681
  await getDurableDispatch()?.markCompleted(event.dispatchId);
592
682
  else
593
683
  await getDurableDispatch()?.markRetryable(event.dispatchId);
684
+ // Absorbed wakes are chat-level only (no structured claim), so the turn finishing is
685
+ // what finalizes them — exactly as it would have for each on its own.
686
+ for (const absorbedId of absorbedDispatchIds)
687
+ await getDurableDispatch()?.markCompleted(absorbedId);
594
688
  runner.endTurn();
595
689
  // A finished turn may have written task files; rescan now so `outcome: continue`
596
690
  // queues the next step immediately instead of waiting out the current sleep.
@@ -632,7 +726,11 @@ export async function createRuntimeContext(options) {
632
726
  await store.logMessage(channelId, message);
633
727
  }
634
728
  catch (err) {
635
- log.logWarning(`[${channelId}] Failed to archive ${contextLabel}`, errorMessage(err));
729
+ log.logWarn("channel.archive.write_failed", "Message archive failed", {
730
+ channelId: channelId,
731
+ reason: errorMessage(err),
732
+ fields: { label: contextLabel },
733
+ });
636
734
  }
637
735
  };
638
736
  const getRunner = (channelId) => {
@@ -692,18 +790,21 @@ export async function createRuntimeContext(options) {
692
790
  const bot = options.createBot
693
791
  ? options.createBot(handler, options.dingtalkConfig)
694
792
  : new DingTalkBot(handler, options.dingtalkConfig);
793
+ const dispatchStateDir = join(options.paths.appHomeDir, "state", "dispatch");
695
794
  durableDispatch = new DurableDispatchService({
696
- stateDir: join(options.paths.appHomeDir, "state", "dispatch"),
795
+ stateDir: dispatchStateDir,
697
796
  bot,
698
797
  // A structured wake (job/subagent completion, task-driver) that keeps failing before it can
699
798
  // ever mark itself complete would otherwise redeliver forever (30s tick, no backoff prior to
700
799
  // this notice). Surface it once instead of looping silently; the record stays on disk for
701
800
  // inspection until a human clears it.
702
801
  onExhausted: async (record) => {
703
- log.logWarning(`[${record.event.channelId}] Dispatch ${record.id} exhausted after ${record.deliveries} deliveries`, record.event.text.slice(0, 500));
704
- await bot.sendPlain(record.event.channelId, `一个后台唤醒(${record.event.user})连续 ${record.deliveries} 次投递均未能完成,已停止自动重试:\n` +
705
- `${record.event.text.slice(0, 300)}\n` +
706
- `记录文件:state/dispatch/${record.id}.json(已保留,供排查)。`);
802
+ log.logEvent("warn", "dispatch.exhausted", "Dispatch exhausted", {
803
+ ctx: { channelId: record.event.channelId },
804
+ details: record.event.text.slice(0, 500),
805
+ fields: { dispatchId: record.id, deliveries: record.deliveries, producer: record.event.user },
806
+ });
807
+ await bot.sendPlain(record.event.channelId, renderDispatchExhaustedNotice(record, dispatchStateDir));
707
808
  },
708
809
  });
709
810
  const executor = options.executor ?? createExecutor();
@@ -727,7 +828,7 @@ export async function createRuntimeContext(options) {
727
828
  const level = runtimeSettingsManager.getDelegationSettings().notices;
728
829
  if (level === "off")
729
830
  return;
730
- if (level === "settled" && notice.kind !== "settled")
831
+ if (level === "settled" && notice.kind === "progress")
731
832
  return;
732
833
  const text = renderRunNotice(notice);
733
834
  if (text)
@@ -755,12 +856,18 @@ export async function createRuntimeContext(options) {
755
856
  model: defaultModel.id,
756
857
  });
757
858
  if (recoveryReport.repaired.length > 0) {
758
- log.logWarning("Repaired interrupted turns on restart", `${recoveryReport.repaired.length}/${recoveryReport.scanned} channel(s): ${recoveryReport.repaired
759
- .map((r) => r.channelDir)
760
- .join(", ")}`);
859
+ log.logWarn("runtime.recovery.repaired", "Interrupted turns repaired on restart", {
860
+ fields: {
861
+ repaired: recoveryReport.repaired.length,
862
+ scanned: recoveryReport.scanned,
863
+ channels: recoveryReport.repaired.map((r) => r.channelDir),
864
+ },
865
+ });
761
866
  }
762
867
  if (recoveryReport.blocked.length > 0) {
763
- log.logWarning("Some channels have an unrecoverable session and will refuse new turns", recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "));
868
+ log.logWarn("runtime.recovery.blocked", "Channels with an unrecoverable session will refuse new turns", {
869
+ reason: recoveryReport.blocked.map((b) => `${b.channelDir}: ${b.reason}`).join("; "),
870
+ });
764
871
  }
765
872
  const eventsWatcher = options.createEventsWatcher
766
873
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
@@ -828,7 +935,7 @@ export async function createRuntimeContext(options) {
828
935
  }
829
936
  shutdownPromise = (async () => {
830
937
  shuttingDown = true;
831
- log.logInfo(`Shutting down (${reason})...`);
938
+ log.logInfoEvent("runtime.shutdown.started", "Shutting down", { fields: { reason } });
832
939
  taskDriver.stop();
833
940
  durableDispatch?.stop();
834
941
  memoryMaintenanceScheduler.stop();
@@ -838,18 +945,27 @@ export async function createRuntimeContext(options) {
838
945
  await bot.stop();
839
946
  const runningTasks = Array.from(activeTasks);
840
947
  if (runningTasks.length > 0) {
841
- log.logInfo(`Waiting for ${runningTasks.length} active task(s) to finish`);
948
+ log.logInfoEvent("runtime.shutdown.waiting", "Waiting for active turns to finish", {
949
+ fields: { activeTurns: runningTasks.length },
950
+ });
842
951
  const completed = await waitForTasks(runningTasks, SHUTDOWN_WAIT_MS);
843
952
  if (!completed) {
844
- log.logWarning(`Shutdown grace period exceeded ${SHUTDOWN_WAIT_MS}ms, aborting active runs`);
953
+ log.logWarn("runtime.shutdown.grace_exceeded", "Shutdown grace period exceeded; aborting active turns", {
954
+ fields: { waitMs: SHUTDOWN_WAIT_MS },
955
+ });
845
956
  const aborts = [];
846
957
  for (const [channelId, runner] of channelRunners) {
847
958
  if (!runner.isBusy())
848
959
  continue;
849
960
  runner.requestStop();
850
- log.logInfo(`[${channelId}] Aborting active run for shutdown`);
961
+ log.logInfoEvent("runtime.shutdown.aborting", "Aborting active turn for shutdown", {
962
+ channelId: channelId,
963
+ });
851
964
  aborts.push(runner.abort().catch((err) => {
852
- log.logWarning(`[${channelId}] Failed to abort run during shutdown`, errorMessage(err));
965
+ log.logWarn("runtime.shutdown.abort_failed", "Turn abort during shutdown failed", {
966
+ channelId: channelId,
967
+ reason: errorMessage(err),
968
+ });
853
969
  }));
854
970
  }
855
971
  await Promise.allSettled(aborts);
@@ -857,7 +973,9 @@ export async function createRuntimeContext(options) {
857
973
  if (remainingTasks.length > 0) {
858
974
  const abortedCompleted = await waitForTasks(remainingTasks, SHUTDOWN_ABORT_WAIT_MS);
859
975
  if (!abortedCompleted) {
860
- log.logWarning(`Shutdown forced exit with ${remainingTasks.length} task(s) still active`);
976
+ log.logWarn("runtime.shutdown.forced", "Shutdown forced with turns still active", {
977
+ fields: { activeTurns: remainingTasks.length },
978
+ });
861
979
  }
862
980
  }
863
981
  }
@@ -870,14 +988,21 @@ export async function createRuntimeContext(options) {
870
988
  if (runner.isBusy())
871
989
  continue;
872
990
  disposals.push(runner.dispose().catch((err) => {
873
- log.logWarning(`[${channelId}] Failed to dispose runner during shutdown`, errorMessage(err));
991
+ log.logWarn("runtime.shutdown.dispose_failed", "Runner dispose during shutdown failed", {
992
+ channelId: channelId,
993
+ reason: errorMessage(err),
994
+ });
874
995
  }));
875
996
  }
876
997
  if (disposals.length > 0) {
877
- log.logInfo(`Disposing ${disposals.length} idle channel runner(s) before shutdown`);
998
+ log.logInfoEvent("runtime.shutdown.disposing", "Disposing idle channel runners", {
999
+ fields: { count: disposals.length },
1000
+ });
878
1001
  const disposed = await waitForTasks(disposals, SHUTDOWN_FLUSH_WAIT_MS);
879
1002
  if (!disposed) {
880
- log.logWarning(`Shutdown runner disposal exceeded ${SHUTDOWN_FLUSH_WAIT_MS}ms`);
1003
+ log.logWarn("runtime.shutdown.dispose_timeout", "Runner disposal during shutdown timed out", {
1004
+ fields: { waitMs: SHUTDOWN_FLUSH_WAIT_MS },
1005
+ });
881
1006
  }
882
1007
  }
883
1008
  channelRunners.clear();
@@ -891,7 +1016,9 @@ export async function createRuntimeContext(options) {
891
1016
  ];
892
1017
  const storageFlushed = await waitForTasks(storageFlushes, SHUTDOWN_LOG_FLUSH_WAIT_MS);
893
1018
  if (!storageFlushed) {
894
- log.logWarning(`Shutdown log flush exceeded ${SHUTDOWN_LOG_FLUSH_WAIT_MS}ms`);
1019
+ log.logWarn("runtime.shutdown.flush_timeout", "Log flush during shutdown timed out", {
1020
+ fields: { waitMs: SHUTDOWN_LOG_FLUSH_WAIT_MS },
1021
+ });
895
1022
  }
896
1023
  await waitForTasks([log.flushLogging()], SHUTDOWN_LOG_FLUSH_WAIT_MS);
897
1024
  })();
@@ -940,9 +1067,11 @@ export async function bootstrap(argv, options = {}) {
940
1067
  parseArgs(argv, paths, io);
941
1068
  const bootstrapResult = bootstrapAppHome(paths);
942
1069
  printBootstrapSummary(bootstrapResult, io, paths);
1070
+ // A freshly written template is the expected first-run outcome, not a failure: guide and exit 0.
1071
+ // A template that exists but is still unfilled is caught by `loadConfig` below and exits 1.
943
1072
  if (bootstrapResult.channelTemplateCreated) {
944
- io.error(`Fill in ${paths.channelConfigPath} and run \`${paths.appName}\` again.`);
945
- throw new BootstrapExitError(1);
1073
+ printFirstRunGuide(io, paths);
1074
+ throw new BootstrapExitError(0);
946
1075
  }
947
1076
  const dingtalkConfig = loadConfig(paths, io);
948
1077
  dingtalkConfig.stateDir = paths.workspaceDir;
@@ -34,7 +34,7 @@ export class ChannelQueue {
34
34
  await work();
35
35
  }
36
36
  catch (err) {
37
- log.logWarning("Queue error", errorMessage(err));
37
+ log.logWarn("runtime.queue.item_failed", "Channel queue item failed", { reason: errorMessage(err) });
38
38
  }
39
39
  this.processing = false;
40
40
  this.processNext();
@@ -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
  /**