@oyasmi/pipiclaw 0.9.3-beta.4 → 0.9.3-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +15 -35
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +43 -3
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-context.d.ts +2 -2
  11. package/dist/channel/channel-context.js +2 -2
  12. package/dist/channel/channel-event.d.ts +3 -3
  13. package/dist/channel/project-scope-store.d.ts +20 -0
  14. package/dist/channel/project-scope-store.js +22 -7
  15. package/dist/commands/catalog.js +6 -12
  16. package/dist/events/event-commands.js +2 -2
  17. package/dist/events/events.d.ts +51 -30
  18. package/dist/events/events.js +70 -98
  19. package/dist/memory/journal.d.ts +2 -3
  20. package/dist/memory/journal.js +2 -3
  21. package/dist/memory/maintenance-tuning.d.ts +0 -1
  22. package/dist/memory/maintenance-tuning.js +0 -1
  23. package/dist/memory/scheduler.js +8 -16
  24. package/dist/memory/search.js +2 -3
  25. package/dist/memory/session-search.js +3 -9
  26. package/dist/memory/store.d.ts +1 -1
  27. package/dist/memory/store.js +9 -1
  28. package/dist/memory/task-digest.js +10 -11
  29. package/dist/memory/tombstones.js +2 -4
  30. package/dist/models/provider-login.d.ts +1 -1
  31. package/dist/models/provider-login.js +1 -1
  32. package/dist/playbooks/agent-delegation.md +18 -14
  33. package/dist/playbooks/background-jobs.md +2 -2
  34. package/dist/playbooks/event-scheduling.md +22 -13
  35. package/dist/playbooks/memory-and-learning.md +2 -2
  36. package/dist/playbooks/outbound-media.md +1 -1
  37. package/dist/playbooks/runtime-orientation.md +5 -3
  38. package/dist/playbooks/task-lead.md +82 -0
  39. package/dist/runtime/bootstrap.js +107 -196
  40. package/dist/runtime/delivery.d.ts +1 -2
  41. package/dist/runtime/delivery.js +57 -62
  42. package/dist/runtime/dingtalk.d.ts +15 -8
  43. package/dist/runtime/dingtalk.js +101 -35
  44. package/dist/runtime/durable-dispatch.js +30 -3
  45. package/dist/runtime/report-commands.d.ts +30 -0
  46. package/dist/runtime/report-commands.js +71 -0
  47. package/dist/runtime/subagent-commands.js +1 -1
  48. package/dist/runtime/task-commands.d.ts +0 -8
  49. package/dist/runtime/task-commands.js +48 -85
  50. package/dist/runtime/task-driver.d.ts +13 -9
  51. package/dist/runtime/task-driver.js +34 -39
  52. package/dist/runtime/task-migration.d.ts +18 -29
  53. package/dist/runtime/task-migration.js +195 -183
  54. package/dist/runtime/task-spawn.d.ts +24 -0
  55. package/dist/runtime/task-spawn.js +49 -0
  56. package/dist/runtime/task-wake.d.ts +33 -46
  57. package/dist/runtime/task-wake.js +15 -90
  58. package/dist/security/network.js +44 -9
  59. package/dist/settings.d.ts +1 -8
  60. package/dist/settings.js +1 -8
  61. package/dist/subagents/discovery.js +7 -17
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +3 -1
  65. package/dist/subagents/external/run.js +14 -23
  66. package/dist/subagents/external/settlement.d.ts +4 -16
  67. package/dist/subagents/external/settlement.js +16 -67
  68. package/dist/subagents/runs.d.ts +15 -29
  69. package/dist/subagents/runs.js +71 -160
  70. package/dist/subagents/tool.d.ts +20 -4
  71. package/dist/subagents/tool.js +63 -87
  72. package/dist/subagents/verification-outcome.d.ts +13 -19
  73. package/dist/subagents/verification-outcome.js +8 -22
  74. package/dist/subagents/workspace-summary.d.ts +8 -0
  75. package/dist/subagents/workspace-summary.js +29 -0
  76. package/dist/tasks/board.d.ts +43 -0
  77. package/dist/tasks/board.js +134 -0
  78. package/dist/tasks/brief.d.ts +10 -5
  79. package/dist/tasks/brief.js +78 -26
  80. package/dist/tasks/budget.d.ts +13 -14
  81. package/dist/tasks/budget.js +21 -40
  82. package/dist/tasks/contract-input.d.ts +19 -0
  83. package/dist/tasks/contract-input.js +55 -0
  84. package/dist/tasks/create.d.ts +17 -0
  85. package/dist/tasks/create.js +36 -0
  86. package/dist/tasks/frontmatter.d.ts +20 -27
  87. package/dist/tasks/frontmatter.js +18 -31
  88. package/dist/tasks/ledger.d.ts +61 -117
  89. package/dist/tasks/ledger.js +78 -223
  90. package/dist/tasks/log.d.ts +62 -35
  91. package/dist/tasks/log.js +51 -29
  92. package/dist/tasks/session-path.d.ts +3 -3
  93. package/dist/tasks/session-path.js +4 -5
  94. package/dist/tasks/store.d.ts +11 -29
  95. package/dist/tasks/store.js +39 -83
  96. package/dist/tasks/ticket.d.ts +33 -66
  97. package/dist/tasks/ticket.js +31 -120
  98. package/dist/tasks/work-log.d.ts +20 -0
  99. package/dist/tasks/work-log.js +42 -0
  100. package/dist/tools/bash.d.ts +1 -1
  101. package/dist/tools/bash.js +1 -1
  102. package/dist/tools/event-manage.d.ts +16 -2
  103. package/dist/tools/event-manage.js +30 -12
  104. package/dist/tools/index.d.ts +5 -3
  105. package/dist/tools/index.js +5 -5
  106. package/dist/tools/registry.d.ts +6 -4
  107. package/dist/tools/registry.js +1 -4
  108. package/dist/tools/subagent-manage.js +4 -2
  109. package/dist/tools/task-manage/create.js +11 -27
  110. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  111. package/dist/tools/task-manage/lifecycle.js +23 -106
  112. package/dist/tools/task-manage/log-view.d.ts +3 -2
  113. package/dist/tools/task-manage/log-view.js +6 -6
  114. package/dist/tools/task-manage/schema.d.ts +10 -30
  115. package/dist/tools/task-manage/schema.js +33 -49
  116. package/dist/tools/task-manage/shared.d.ts +35 -42
  117. package/dist/tools/task-manage/shared.js +53 -192
  118. package/dist/tools/task-manage/step-end.d.ts +6 -6
  119. package/dist/tools/task-manage/step-end.js +61 -98
  120. package/dist/tools/task-manage/types.d.ts +8 -9
  121. package/dist/tools/task-manage.js +5 -5
  122. package/dist/tui/app.js +11 -38
  123. package/dist/tui/commands.d.ts +18 -8
  124. package/dist/tui/commands.js +2 -9
  125. package/dist/tui/turn-controller.d.ts +2 -14
  126. package/dist/tui/turn-controller.js +1 -17
  127. package/dist/web/client.js +9 -1
  128. package/examples/sub-agents/README.md +67 -80
  129. package/examples/sub-agents/agents/claude-high.md +23 -0
  130. package/examples/sub-agents/agents/claude-main.md +23 -0
  131. package/examples/sub-agents/agents/codex-flash.md +23 -0
  132. package/examples/sub-agents/agents/codex-high.md +23 -0
  133. package/examples/sub-agents/agents/codex-main.md +23 -0
  134. package/examples/sub-agents/agents/codex-review.md +23 -0
  135. package/examples/sub-agents/agents/glm-flash.md +23 -0
  136. package/examples/sub-agents/agents/glm-high.md +23 -0
  137. package/examples/sub-agents/{verifier.md → roles/verifier.md} +1 -1
  138. package/package.json +1 -1
  139. package/dist/memory/maintenance-migration.d.ts +0 -5
  140. package/dist/memory/maintenance-migration.js +0 -91
  141. package/dist/memory/migrate.d.ts +0 -15
  142. package/dist/memory/migrate.js +0 -364
  143. package/dist/playbooks/task-loop.md +0 -90
  144. package/dist/tasks/artifact-subject.d.ts +0 -40
  145. package/dist/tasks/artifact-subject.js +0 -334
  146. package/dist/tasks/cycle.d.ts +0 -48
  147. package/dist/tasks/cycle.js +0 -94
  148. package/dist/tasks/rounds.d.ts +0 -41
  149. package/dist/tasks/rounds.js +0 -53
  150. package/dist/tasks/task-events.d.ts +0 -6
  151. package/dist/tasks/task-events.js +0 -14
  152. package/dist/tasks/task-schedule.d.ts +0 -18
  153. package/dist/tasks/task-schedule.js +0 -50
  154. package/dist/tasks/verification.d.ts +0 -114
  155. package/dist/tasks/verification.js +0 -226
  156. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  157. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  158. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  159. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  160. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  161. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  162. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -2,7 +2,8 @@ import * as log from "../log.js";
2
2
  import { errorMessage } from "../shared/text-utils.js";
3
3
  const MIN_UPDATE_INTERVAL_MS = 800;
4
4
  const ROLLING_WINDOW_SIZE = 3;
5
- const NO_CONTENT = "";
5
+ const WAITING_TEXT = "正在处理…";
6
+ const MAX_PROGRESS_FAILURES = 2;
6
7
  // DingTalk's card renderer swallows a bare "\n" between plain lines (and a blank-line
7
8
  // paragraph break leaves too much vertical gap), but it does reliably break a markdown
8
9
  // list onto separate lines. Render each progress entry as a list item instead.
@@ -29,6 +30,8 @@ class ChannelDeliveryController {
29
30
  this.running = false;
30
31
  this.closed = false;
31
32
  this.finalResponseDelivered = false;
33
+ this.ending = false;
34
+ this.progressFailures = 0;
32
35
  this.cardWarmupScheduled = false;
33
36
  this.cardWarmupTriggered = false;
34
37
  this.progressStartedAt = 0;
@@ -41,6 +44,10 @@ class ChannelDeliveryController {
41
44
  this.sentProgressChars = 0;
42
45
  this.replayRequired = false;
43
46
  this.finalReplacementText = "";
47
+ this.cardGeneration = bot.getCardGeneration(event.channelId);
48
+ }
49
+ get isCurrent() {
50
+ return this.bot.isCardGenerationCurrent(this.event.channelId, this.cardGeneration);
44
51
  }
45
52
  /** The style this turn actually delivers with: the override when present, else the channel's. */
46
53
  get progressStyle() {
@@ -64,7 +71,7 @@ class ChannelDeliveryController {
64
71
  respondPlain: async (text, shouldLog = true, title) => this.sendFinal(text, shouldLog, title),
65
72
  replaceMessage: async (text) => this.replaceWithFinal(text),
66
73
  respondInThread: async (text) => {
67
- if (this.closed || !text.trim()) {
74
+ if (this.closed || !this.isCurrent || !text.trim()) {
68
75
  return;
69
76
  }
70
77
  const delivered = await this.bot.sendPlain(this.event.channelId, text);
@@ -83,29 +90,24 @@ class ChannelDeliveryController {
83
90
  };
84
91
  }
85
92
  primeCard(delayMs) {
86
- if (this.closed || this.finalResponseDelivered || this.cardWarmupScheduled || this.cardWarmupTriggered) {
93
+ if (this.closed ||
94
+ this.ending ||
95
+ this.progressStyle === "none" ||
96
+ this.cardWarmupScheduled ||
97
+ this.cardWarmupTriggered) {
87
98
  return;
88
99
  }
89
100
  this.cardWarmupScheduled = true;
90
101
  this.cardWarmupTimer = setTimeout(() => {
91
102
  this.cardWarmupScheduled = false;
92
103
  this.cardWarmupTimer = null;
93
- void this.triggerCardWarmup();
104
+ if (this.closed || this.ending || !this.isCurrent || this.desiredRevision > 0)
105
+ return;
106
+ this.cardWarmupTriggered = true;
107
+ // Use the same serialized loop as progress and completion; no detached create request.
108
+ this.bumpRevision(true);
94
109
  }, Math.max(0, delayMs));
95
110
  }
96
- async triggerCardWarmup() {
97
- if (this.closed || this.finalResponseDelivered || this.desiredRevision > 0) {
98
- return;
99
- }
100
- this.cardWarmupTriggered = true;
101
- try {
102
- await this.bot.ensureCard(this.event.channelId);
103
- }
104
- catch (err) {
105
- log.logWarning(`[${this.event.channelId}] Failed to warm AI card`, errorMessage(err));
106
- this.bot.discardCard(this.event.channelId);
107
- }
108
- }
109
111
  clearCardWarmup() {
110
112
  this.cardWarmupScheduled = false;
111
113
  if (this.cardWarmupTimer) {
@@ -119,7 +121,7 @@ class ChannelDeliveryController {
119
121
  });
120
122
  }
121
123
  async appendProgress(text, shouldLog) {
122
- if (this.closed || this.finalResponseDelivered || !text.trim())
124
+ if (this.closed || this.ending || !this.isCurrent || !text.trim())
123
125
  return;
124
126
  // Final-card-only mode shows no progress; ignore any stray progress writes
125
127
  // so we never create or flicker a card before the final replacement.
@@ -154,9 +156,13 @@ class ChannelDeliveryController {
154
156
  this.bumpRevision(false);
155
157
  }
156
158
  async sendFinal(text, shouldLog, title) {
157
- if (this.closed || this.finalResponseDelivered)
159
+ if (this.closed || this.ending || !this.isCurrent || !text.trim())
158
160
  return this.finalResponseDelivered;
161
+ this.ending = true;
159
162
  this.clearCardWarmup();
163
+ if (this.timer)
164
+ clearTimeout(this.timer);
165
+ this.timer = null;
160
166
  const delivered = await this.bot.sendPlain(this.event.channelId, text, title ? { title, markdown: true } : undefined);
161
167
  if (!delivered) {
162
168
  // Do not archive a response we failed to deliver: the conversation log
@@ -172,18 +178,23 @@ class ChannelDeliveryController {
172
178
  return true;
173
179
  }
174
180
  async replaceWithFinal(text) {
175
- if (this.closed || this.finalResponseDelivered)
181
+ if (this.closed || this.finalResponseDelivered || !this.isCurrent || !text.trim())
176
182
  return;
183
+ this.ending = true;
177
184
  this.clearCardWarmup();
178
185
  this.finalReplacementText = text;
179
186
  this.mode = "finalize-with-fallback";
180
187
  this.bumpRevision(true);
188
+ await this.flush();
189
+ if (!this.finalResponseDelivered && this.isCurrent) {
190
+ throw new Error("最终答复发送失败,请稍后重试。");
191
+ }
181
192
  }
182
193
  async silence() {
183
- if (this.closed)
194
+ if (this.closed || this.finalResponseDelivered)
184
195
  return;
196
+ this.ending = true;
185
197
  this.clearCardWarmup();
186
- this.finalResponseDelivered = true;
187
198
  this.mode = "silent";
188
199
  this.bumpRevision(true);
189
200
  }
@@ -221,7 +232,7 @@ class ChannelDeliveryController {
221
232
  const body = this.getProgressText();
222
233
  const progressText = mode === "progress" && this.progressStyle === "rolling" && body
223
234
  ? `${this.buildRollingHeader()}\n\n${body}`
224
- : body;
235
+ : body || (this.cardWarmupTriggered ? WAITING_TEXT : "");
225
236
  const throttleBaseAt = this.lastDeliveredAt > 0 ? this.lastDeliveredAt : this.progressWindowStartedAt;
226
237
  if (mode === "progress" && throttleBaseAt > 0) {
227
238
  const remaining = MIN_UPDATE_INTERVAL_MS - (Date.now() - throttleBaseAt);
@@ -239,71 +250,51 @@ class ChannelDeliveryController {
239
250
  let touchedRemote = false;
240
251
  try {
241
252
  if (mode === "progress") {
242
- if (content) {
253
+ if (content && this.isCurrent && this.progressFailures < MAX_PROGRESS_FAILURES) {
243
254
  const nextSentChars = progressText.length;
244
- if (this.replayRequired) {
245
- touchedRemote = await this.bot.replaceCard(this.event.channelId, progressText);
255
+ if (this.replayRequired || this.sentProgressChars === 0) {
256
+ touchedRemote = await this.bot.replaceCard(this.event.channelId, progressText, false, false, this.cardGeneration);
246
257
  }
247
258
  else {
248
259
  const delta = progressText.slice(this.sentProgressChars);
249
- touchedRemote = delta ? await this.bot.appendToCard(this.event.channelId, delta) : true;
260
+ touchedRemote = delta
261
+ ? await this.bot.appendToCard(this.event.channelId, delta, false, false, this.cardGeneration)
262
+ : true;
250
263
  }
251
264
  if (!touchedRemote) {
252
- this.bot.discardCard(this.event.channelId);
265
+ this.progressFailures++;
253
266
  this.replayRequired = true;
254
267
  }
255
268
  else {
256
- this.sentProgressChars = nextSentChars;
269
+ this.sentProgressChars = body ? nextSentChars : 0;
257
270
  this.replayRequired = false;
258
271
  }
259
272
  }
260
273
  }
261
274
  else if (mode === "finalize-existing") {
262
275
  if (content || this.cardWarmupTriggered) {
263
- const isRolling = this.progressStyle === "rolling";
264
- const finalProgressText = isRolling ? this.buildSummaryText() : progressText;
265
- // A warmed-but-empty card in full mode has nothing to show, so it finalizes
266
- // blank; rolling mode always has its closing summary to put there.
267
- // (`||` binds tighter than `?:` — this used to read as one condition and
268
- // was a standing invitation to misparse it.)
269
- const finalCardText = content || isRolling ? finalProgressText : NO_CONTENT;
270
- touchedRemote = await this.bot.replaceCard(this.event.channelId, finalCardText, true);
271
- if (!touchedRemote) {
272
- this.bot.discardCard(this.event.channelId);
273
- }
274
- else {
275
- this.sentProgressChars = finalProgressText.length;
276
- this.replayRequired = false;
277
- }
278
- }
279
- else {
280
- this.bot.discardCard(this.event.channelId);
276
+ const finalProgressText = this.progressStyle === "rolling"
277
+ ? this.buildSummaryText()
278
+ : [body, "答复已发送。"].filter(Boolean).join("\n\n");
279
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, finalProgressText, this.cardGeneration);
281
280
  }
282
281
  }
283
282
  else if (mode === "finalize-with-fallback") {
284
283
  if (replacementText.trim()) {
285
- touchedRemote = await this.bot.finalizeCard(this.event.channelId, replacementText);
286
- if (!touchedRemote) {
287
- this.bot.discardCard(this.event.channelId);
288
- }
289
- }
290
- else {
291
- this.bot.discardCard(this.event.channelId);
284
+ touchedRemote = await this.bot.finalizeCard(this.event.channelId, replacementText, this.cardGeneration);
285
+ this.finalResponseDelivered = touchedRemote;
292
286
  }
293
287
  }
294
288
  else if (mode === "silent") {
295
- if (this.cardWarmupTriggered) {
296
- touchedRemote = await this.bot.replaceCard(this.event.channelId, NO_CONTENT, true);
297
- }
298
- if (!touchedRemote) {
299
- this.bot.discardCard(this.event.channelId);
289
+ if (content) {
290
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "处理已结束。"].filter(Boolean).join("\n\n"), this.cardGeneration);
300
291
  }
301
292
  }
302
293
  }
303
294
  catch (err) {
304
295
  log.logWarning(`[${this.event.channelId}] Delivery sync failed`, errorMessage(err));
305
- this.bot.discardCard(this.event.channelId);
306
296
  if (mode === "progress") {
297
+ this.progressFailures++;
307
298
  this.replayRequired = true;
308
299
  }
309
300
  }
@@ -363,7 +354,12 @@ class ChannelDeliveryController {
363
354
  }
364
355
  this.closed = true;
365
356
  this.clearCardWarmup();
357
+ if (this.mode === "progress") {
358
+ this.mode = "silent";
359
+ this.bumpRevision(true);
360
+ }
366
361
  await this.flush();
362
+ this.bot.discardCard(this.event.channelId, this.cardGeneration);
367
363
  }
368
364
  getProgressText() {
369
365
  if (!this.progressTextDirty) {
@@ -427,8 +423,7 @@ class ChannelDeliveryController {
427
423
  *
428
424
  * `progressStyleOverride` lets the caller quiet a turn the user did not ask for. Background wakes
429
425
  * (task driver, finished jobs, scheduled events) pass `"none"`: without it every autonomous step
430
- * created an AI card in the human's conversation, streamed the model's thinking into it, and — for
431
- * the `[SILENT]` turns that are the *normal* outcome of a check-in — deleted the card again. The
426
+ * created an AI card in the human's conversation even when the check-in ended `[SILENT]`. The
432
427
  * final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
433
428
  * background turn that has something to say still says it.
434
429
  */
@@ -89,6 +89,8 @@ export declare class DingTalkBot implements MediaSender {
89
89
  private tokenExpiry;
90
90
  private tokenRefreshPromise;
91
91
  private activeCards;
92
+ private cardGenerations;
93
+ private cardCreationAttempted;
92
94
  private cardCreationInFlight;
93
95
  private convMeta;
94
96
  private channelLastActiveAt;
@@ -144,18 +146,19 @@ export declare class DingTalkBot implements MediaSender {
144
146
  */
145
147
  enqueueEvent(event: DingTalkEvent): boolean;
146
148
  private enqueueStreamMessage;
147
- /**
148
- * Get or create an AI Card for a channel.
149
- */
150
- ensureCard(channelId: string): Promise<void>;
149
+ /** Capture the current turn's identity; close, /stop and /new invalidate it. */
150
+ getCardGeneration(channelId: string): symbol;
151
+ isCardGenerationCurrent(channelId: string, generation: symbol): boolean;
152
+ /** Get or create an AI card without joining an earlier turn's in-flight creation. */
153
+ ensureCard(channelId: string, generation?: symbol): Promise<void>;
151
154
  /**
152
155
  * Replace the active card content with a full snapshot.
153
156
  */
154
- replaceCard(channelId: string, content: string, finalize?: boolean, failed?: boolean): Promise<boolean>;
157
+ replaceCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
155
158
  /**
156
159
  * Append a delta to the active card transcript.
157
160
  */
158
- appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean): Promise<boolean>;
161
+ appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
159
162
  /**
160
163
  * Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
161
164
  * two (a full-snapshot replace opens one for a finalize/failed close too; a delta append only
@@ -167,8 +170,11 @@ export declare class DingTalkBot implements MediaSender {
167
170
  /**
168
171
  * Finalize and remove the active card for a channel.
169
172
  */
170
- finalizeCard(channelId: string, content: string): Promise<boolean>;
171
- discardCard(channelId: string): void;
173
+ finalizeCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
174
+ /** Finish progress only: never create a card or send a fallback chat message. */
175
+ finalizeExistingCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
176
+ /** Invalidate this turn's local state. This is not a remote message deletion. */
177
+ discardCard(channelId: string, generation?: symbol | undefined): void;
172
178
  /**
173
179
  * Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
174
180
  *
@@ -235,6 +241,7 @@ export declare class DingTalkBot implements MediaSender {
235
241
  private createCard;
236
242
  private createCardUncached;
237
243
  private streamCard;
244
+ private streamCardRequest;
238
245
  private getAccessToken;
239
246
  private refreshAccessToken;
240
247
  private onStreamMessage;
@@ -95,7 +95,7 @@ const SUPPORTED_FILE_TYPES = new Set(["xlsx", "pdf", "zip", "rar", "doc", "docx"
95
95
  // hung connection, and a stalled card-streaming request would wedge the delivery
96
96
  // sync loop (never resolving flush()), leaving the whole channel permanently busy.
97
97
  // A timeout turns "hang" into a normal failure that the existing fallback paths
98
- // (discardCard / replay / sendPlain) already handle.
98
+ // (bounded snapshot replay / sendPlain) already handle.
99
99
  const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
100
100
  const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
101
101
  // Bounds enqueueStreamMessage (user messages + busy-message requeues), mirroring the
@@ -129,9 +129,9 @@ export class DingTalkBot {
129
129
  this.tokenRefreshPromise = null;
130
130
  // Active AI cards: channelId → AICard
131
131
  this.activeCards = new Map();
132
- // Singleflight for card creation: warmup and the first progress update can
133
- // race before activeCards is populated, which would create two cards. Sharing
134
- // the in-flight promise per channel guarantees at most one create call.
132
+ this.cardGenerations = new Map();
133
+ this.cardCreationAttempted = new Set();
134
+ // Share creation within a turn, but never let a late old turn own a new turn's card.
135
135
  this.cardCreationInFlight = new Map();
136
136
  // Conversation metadata cache: channelId → metadata
137
137
  this.convMeta = new Map();
@@ -607,28 +607,38 @@ export class DingTalkBot {
607
607
  // ==========================================================================
608
608
  // AI Card operations
609
609
  // ==========================================================================
610
- /**
611
- * Get or create an AI Card for a channel.
612
- */
613
- async ensureCard(channelId) {
614
- if (!this.config.cardTemplateId)
610
+ /** Capture the current turn's identity; close, /stop and /new invalidate it. */
611
+ getCardGeneration(channelId) {
612
+ let generation = this.cardGenerations.get(channelId);
613
+ if (!generation) {
614
+ generation = Symbol(channelId);
615
+ this.cardGenerations.set(channelId, generation);
616
+ }
617
+ return generation;
618
+ }
619
+ isCardGenerationCurrent(channelId, generation) {
620
+ return this.cardGenerations.get(channelId) === generation;
621
+ }
622
+ /** Get or create an AI card without joining an earlier turn's in-flight creation. */
623
+ async ensureCard(channelId, generation = this.getCardGeneration(channelId)) {
624
+ if (!this.config.cardTemplateId || !this.isCardGenerationCurrent(channelId, generation))
615
625
  return;
616
626
  const existing = this.activeCards.get(channelId);
617
627
  if (existing && !existing.finished)
618
628
  return;
619
- await this.createCard(channelId);
629
+ await this.createCard(channelId, generation);
620
630
  }
621
631
  /**
622
632
  * Replace the active card content with a full snapshot.
623
633
  */
624
- async replaceCard(channelId, content, finalize = false, failed = false) {
625
- return this.writeCard(channelId, content, { append: false, finalize, failed });
634
+ async replaceCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
635
+ return this.writeCard(channelId, content, { append: false, finalize, failed }, generation);
626
636
  }
627
637
  /**
628
638
  * Append a delta to the active card transcript.
629
639
  */
630
- async appendToCard(channelId, content, finalize = false, failed = false) {
631
- return this.writeCard(channelId, content, { append: true, finalize, failed });
640
+ async appendToCard(channelId, content, finalize = false, failed = false, generation = this.getCardGeneration(channelId)) {
641
+ return this.writeCard(channelId, content, { append: true, finalize, failed }, generation);
632
642
  }
633
643
  /**
634
644
  * Shared body of `replaceCard`/`appendToCard`: whether to open a fresh card differs between the
@@ -637,7 +647,9 @@ export class DingTalkBot {
637
647
  * being collapsed away — everything after it (stream, then drop the card on finalize/failed/a
638
648
  * failed stream) is identical either way.
639
649
  */
640
- async writeCard(channelId, content, options) {
650
+ async writeCard(channelId, content, options, generation) {
651
+ if (!this.isCardGenerationCurrent(channelId, generation))
652
+ return false;
641
653
  const { append, finalize, failed } = options;
642
654
  if (append && !content && !finalize && !failed) {
643
655
  return true;
@@ -647,17 +659,18 @@ export class DingTalkBot {
647
659
  ? !finalize && !failed && content.trim().length > 0
648
660
  : content.trim().length > 0 || !finalize || failed;
649
661
  if ((!card || card.finished) && this.config.cardTemplateId && shouldEnsure) {
650
- await this.ensureCard(channelId);
662
+ await this.ensureCard(channelId, generation);
663
+ if (!this.isCardGenerationCurrent(channelId, generation))
664
+ return false;
651
665
  card = this.activeCards.get(channelId);
652
666
  }
653
667
  if (!card || card.finished) {
654
- if (finalize && content.trim()) {
655
- return this.sendPlain(channelId, content);
656
- }
657
668
  return false;
658
669
  }
659
- const streamed = await this.streamCard(card, content, { append, finalize, failed });
660
- if (!streamed || finalize || failed) {
670
+ // Never erase a visible card, including callers finishing with no new text.
671
+ const snapshot = !append && !content.trim() ? card.content || "处理已结束。" : content;
672
+ const streamed = await this.streamCard(card, snapshot, { append, finalize, failed });
673
+ if (streamed && (finalize || failed) && this.activeCards.get(channelId) === card) {
661
674
  this.activeCards.delete(channelId);
662
675
  }
663
676
  return streamed;
@@ -665,15 +678,37 @@ export class DingTalkBot {
665
678
  /**
666
679
  * Finalize and remove the active card for a channel.
667
680
  */
668
- async finalizeCard(channelId, content) {
669
- const finalized = await this.replaceCard(channelId, content, true, false);
670
- if (!finalized) {
681
+ async finalizeCard(channelId, content, generation = this.getCardGeneration(channelId)) {
682
+ if (!content.trim() || !this.isCardGenerationCurrent(channelId, generation))
683
+ return false;
684
+ const finalized = await this.replaceCard(channelId, content, true, false, generation);
685
+ if (!finalized && this.isCardGenerationCurrent(channelId, generation)) {
671
686
  return this.sendPlain(channelId, content);
672
687
  }
673
- return true;
688
+ return finalized;
674
689
  }
675
- discardCard(channelId) {
690
+ /** Finish progress only: never create a card or send a fallback chat message. */
691
+ async finalizeExistingCard(channelId, content, generation = this.getCardGeneration(channelId)) {
692
+ if (!this.isCardGenerationCurrent(channelId, generation) || !this.activeCards.has(channelId))
693
+ return false;
694
+ return this.replaceCard(channelId, content, true, false, generation);
695
+ }
696
+ /** Invalidate this turn's local state. This is not a remote message deletion. */
697
+ discardCard(channelId, generation = this.cardGenerations.get(channelId)) {
698
+ if (!generation || !this.isCardGenerationCurrent(channelId, generation))
699
+ return;
700
+ this.cardGenerations.delete(channelId);
701
+ this.cardCreationAttempted.delete(generation);
702
+ const card = this.activeCards.get(channelId);
676
703
  this.activeCards.delete(channelId);
704
+ // /stop and /new may invalidate a turn before its controller gets to finish.
705
+ if (card && !card.finished) {
706
+ void this.streamCard(card, `${card.content || "正在处理…"}\n\n处理已结束。`, {
707
+ append: false,
708
+ finalize: true,
709
+ failed: false,
710
+ });
711
+ }
677
712
  }
678
713
  /**
679
714
  * Send a normal message natively mapping DM and Group to correct endpoints (fallback when no card).
@@ -917,7 +952,7 @@ export class DingTalkBot {
917
952
  // ==========================================================================
918
953
  // Private - AI Card implementation
919
954
  // ==========================================================================
920
- async createCard(channelId) {
955
+ async createCard(channelId, generation) {
921
956
  // Re-check under the singleflight: a concurrent caller may have already
922
957
  // created the card while we awaited, so avoid a duplicate create.
923
958
  const existing = this.activeCards.get(channelId);
@@ -925,18 +960,24 @@ export class DingTalkBot {
925
960
  return existing;
926
961
  }
927
962
  const inFlight = this.cardCreationInFlight.get(channelId);
928
- if (inFlight) {
929
- return inFlight;
963
+ if (inFlight?.generation === generation) {
964
+ return inFlight.promise;
930
965
  }
931
- const creation = this.createCardUncached(channelId).finally(() => {
932
- this.cardCreationInFlight.delete(channelId);
966
+ // A failed create may already have reached DingTalk. Never mint another ID in this turn.
967
+ if (this.cardCreationAttempted.has(generation))
968
+ return null;
969
+ this.cardCreationAttempted.add(generation);
970
+ const creation = this.createCardUncached(channelId, generation).finally(() => {
971
+ if (this.cardCreationInFlight.get(channelId)?.generation === generation) {
972
+ this.cardCreationInFlight.delete(channelId);
973
+ }
933
974
  });
934
- this.cardCreationInFlight.set(channelId, creation);
975
+ this.cardCreationInFlight.set(channelId, { generation, promise: creation });
935
976
  return creation;
936
977
  }
937
- async createCardUncached(channelId) {
978
+ async createCardUncached(channelId, generation) {
938
979
  const token = await this.getAccessToken();
939
- if (!token)
980
+ if (!token || !this.isCardGenerationCurrent(channelId, generation))
940
981
  return null;
941
982
  const meta = this.getConversationMeta(channelId);
942
983
  if (!meta) {
@@ -957,6 +998,7 @@ export class DingTalkBot {
957
998
  outTrackId: instanceId,
958
999
  cardData: {
959
1000
  cardParamMap: {
1001
+ [this.config.cardTemplateKey || "content"]: "正在处理…",
960
1002
  sys_full_json_obj: JSON.stringify({
961
1003
  config: {
962
1004
  autoLayout: this.config.cardAutoLayout ?? true,
@@ -1000,13 +1042,33 @@ export class DingTalkBot {
1000
1042
  templateKey: this.config.cardTemplateKey || "content",
1001
1043
  createdAt: Date.now() / 1000,
1002
1044
  lastUpdated: Date.now() / 1000,
1003
- content: "",
1045
+ content: "正在处理…",
1004
1046
  finished: false,
1005
1047
  };
1048
+ if (!this.isCardGenerationCurrent(channelId, generation)) {
1049
+ await this.streamCard(card, "处理已结束。", { append: false, finalize: true, failed: false });
1050
+ return null;
1051
+ }
1006
1052
  this.activeCards.set(channelId, card);
1007
1053
  return card;
1008
1054
  }
1009
1055
  async streamCard(card, content, options) {
1056
+ // A stop/new-session close can arrive while the prior HTTP write is in flight.
1057
+ // Order writes by instance so that close remains the last update to the old card.
1058
+ const pending = (card.pendingWrite ?? Promise.resolve(true))
1059
+ .then(async () => {
1060
+ if (card.finished)
1061
+ return false;
1062
+ return this.streamCardRequest(card, content, options);
1063
+ })
1064
+ .catch((error) => {
1065
+ log.logWarning("DingTalk Card: streaming failed", errorMessage(error));
1066
+ return false;
1067
+ });
1068
+ card.pendingWrite = pending;
1069
+ return pending;
1070
+ }
1071
+ async streamCardRequest(card, content, options) {
1010
1072
  // Refresh token if needed
1011
1073
  const ageSecs = Date.now() / 1000 - card.createdAt;
1012
1074
  if (ageSecs > TOKEN_REFRESH_SECS) {
@@ -1342,6 +1404,10 @@ export class DingTalkBot {
1342
1404
  if (card && card.lastUpdated * 1000 > cutoff)
1343
1405
  continue;
1344
1406
  this.activeCards.delete(channelId);
1407
+ const generation = this.cardGenerations.get(channelId);
1408
+ if (generation)
1409
+ this.cardCreationAttempted.delete(generation);
1410
+ this.cardGenerations.delete(channelId);
1345
1411
  this.convMeta.delete(channelId);
1346
1412
  this.queues.delete(channelId);
1347
1413
  this.channelLastActiveAt.delete(channelId);
@@ -13,8 +13,28 @@ const DEFAULT_INTERVAL_MS = 30_000;
13
13
  const MAX_DELIVERIES = 8;
14
14
  const MIN_RETRY_BACKOFF_MS = 30_000;
15
15
  const MAX_RETRY_BACKOFF_MS = 10 * 60_000;
16
+ /**
17
+ * Business-id dispatch ids can contain `/` (a DingTalk group id is base64 and routinely does —
18
+ * see `channel/channel-paths.ts`). Used verbatim as a filename that turns into a nested path a
19
+ * flat `readdir(stateDir)` scan can never find again (R1): a queue rejection or a restart then
20
+ * makes that record un-drainable and un-cancellable forever, even once capacity returns. Percent-
21
+ * encoding keeps the mapping reversible and collision-free without touching the id itself — only
22
+ * the on-disk filename changes.
23
+ */
24
+ function encodeDispatchId(id) {
25
+ return encodeURIComponent(id);
26
+ }
27
+ /** Inverse of {@link encodeDispatchId}. */
28
+ function decodeDispatchId(encoded) {
29
+ try {
30
+ return decodeURIComponent(encoded);
31
+ }
32
+ catch {
33
+ return encoded;
34
+ }
35
+ }
16
36
  function recordPath(stateDir, id) {
17
- return join(stateDir, `${id}.json`);
37
+ return join(stateDir, `${encodeDispatchId(id)}.json`);
18
38
  }
19
39
  /**
20
40
  * Prefix a redelivered wake with what the runtime already knows (spec 031, D3).
@@ -149,7 +169,7 @@ export class DurableDispatchService {
149
169
  }
150
170
  let canceled = 0;
151
171
  for (const filename of filenames) {
152
- const id = filename.slice(0, -".json".length);
172
+ const id = decodeDispatchId(filename.slice(0, -".json".length));
153
173
  await this.queue.run(id, async () => {
154
174
  const record = await this.read(id);
155
175
  if (!record || record.event.channelId !== channelId)
@@ -220,7 +240,7 @@ export class DurableDispatchService {
220
240
  return;
221
241
  }
222
242
  for (const filename of filenames) {
223
- const id = filename.slice(0, -".json".length);
243
+ const id = decodeDispatchId(filename.slice(0, -".json".length));
224
244
  await this.drainRecord(id, now);
225
245
  }
226
246
  }
@@ -275,7 +295,14 @@ export class DurableDispatchService {
275
295
  const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
276
296
  if (accepted)
277
297
  return;
298
+ // Admission rejection (queue full, bot stopped) is backpressure, not a delivery attempt —
299
+ // the handler never ran and never got a chance to fail (R2). Counting it against
300
+ // MAX_DELIVERIES meant a few minutes of congestion permanently exhausted a record that
301
+ // was never actually tried; undo the increment above so only real handler outcomes
302
+ // (markCompleted/markRetryable, or a crash-lease redelivery) count toward the poison-pill
303
+ // limit.
278
304
  record.status = "pending";
305
+ record.deliveries--;
279
306
  record.leaseExpiresAt = undefined;
280
307
  await this.write(record);
281
308
  });
@@ -0,0 +1,30 @@
1
+ import type { AgentRunner } from "../agent/types.js";
2
+ import type { RuntimeCommandName } from "../commands/catalog.js";
3
+ import type { SubAgentRunManager } from "../subagents/runs.js";
4
+ import type { BootstrapPaths } from "./app-home.js";
5
+ /**
6
+ * The stateless report commands (`/events /tasks /status /usage /context /subagents /project
7
+ * /skills`) as one transport-neutral handler. The DingTalk runtime and the terminal TUI both route
8
+ * through it, so a report cannot behave differently depending on where it was typed; each
9
+ * transport supplies only what is genuinely its own (how to find its runner, how to rebuild one
10
+ * after `/project`, whether a task can be woken immediately).
11
+ */
12
+ export interface ReportCommandContext {
13
+ channelId: string;
14
+ paths: Pick<BootstrapPaths, "workspaceDir" | "appHomeDir" | "eventHistoryPath" | "authConfigPath" | "modelsConfigPath">;
15
+ actor: "dingtalk-command" | "tui-command";
16
+ version: string;
17
+ startedAt: number;
18
+ /** The channel's live runner, if one exists; never builds one. */
19
+ peekRunner: () => AgentRunner | undefined;
20
+ /** The channel's runner, built on demand (`/context` needs a session to report on). */
21
+ getRunner: () => AgentRunner;
22
+ runManager: SubAgentRunManager;
23
+ /** One line per running background job, for `/project`'s "busy" check. */
24
+ runningJobLines: () => string[];
25
+ /** Drop the runner built under the old project scope so the next access rebuilds it. */
26
+ onScopeChanged: () => Promise<void>;
27
+ /** Immediate task wake for `/tasks run|reply`; absent where there is no durable dispatch (the TUI). */
28
+ dispatchTask?: (taskId: string) => Promise<boolean>;
29
+ }
30
+ export declare function runReportCommand(context: ReportCommandContext, name: RuntimeCommandName, args: string): Promise<string>;