@oyasmi/pipiclaw 0.9.5-beta.2 → 0.9.5-beta.3

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 (272) hide show
  1. package/README.en.md +9 -11
  2. package/README.md +9 -11
  3. package/dist/agent/channel-runner.d.ts +12 -24
  4. package/dist/agent/channel-runner.js +74 -30
  5. package/dist/agent/maintenance-context.d.ts +2 -0
  6. package/dist/agent/maintenance-context.js +15 -0
  7. package/dist/agent/prompt/sections.js +8 -6
  8. package/dist/agent/prompt/types.d.ts +1 -1
  9. package/dist/agent/runner-factory.js +1 -1
  10. package/dist/agent/session/command-extension.js +11 -0
  11. package/dist/agent/session/compaction-summary.js +6 -2
  12. package/dist/agent/session/execution-trace.d.ts +14 -0
  13. package/dist/agent/session/execution-trace.js +57 -0
  14. package/dist/agent/session/session-events.d.ts +2 -7
  15. package/dist/agent/session/session-events.js +35 -12
  16. package/dist/agent/session/session-host.d.ts +12 -22
  17. package/dist/agent/session/session-host.js +46 -65
  18. package/dist/agent/turn/task-digest.d.ts +1 -2
  19. package/dist/agent/turn/task-digest.js +33 -33
  20. package/dist/agent/turn/turn-context.d.ts +1 -1
  21. package/dist/agent/turn/turn-context.js +1 -1
  22. package/dist/agent/turn/turn-finish.d.ts +2 -2
  23. package/dist/agent/turn/turn-finish.js +3 -2
  24. package/dist/agent/turn/turn-pipeline.d.ts +4 -2
  25. package/dist/agent/turn/turn-pipeline.js +33 -5
  26. package/dist/agent/types.d.ts +64 -14
  27. package/dist/agent/types.js +3 -0
  28. package/dist/app/home.js +3 -4
  29. package/dist/channel/channel-event.d.ts +4 -12
  30. package/dist/channel/ingress.d.ts +1 -9
  31. package/dist/channel/store.d.ts +1 -1
  32. package/dist/commands/catalog.js +25 -19
  33. package/dist/commands/router.d.ts +5 -2
  34. package/dist/commands/router.js +9 -4
  35. package/dist/config/settings.d.ts +5 -12
  36. package/dist/config/settings.js +0 -7
  37. package/dist/config/tools.d.ts +2 -2
  38. package/dist/config/tools.js +2 -2
  39. package/dist/dingtalk/bot.d.ts +2 -0
  40. package/dist/dingtalk/bot.js +4 -0
  41. package/dist/dingtalk/cards.d.ts +7 -0
  42. package/dist/dingtalk/cards.js +32 -2
  43. package/dist/dingtalk/delivery.d.ts +5 -1
  44. package/dist/dingtalk/delivery.js +157 -142
  45. package/dist/dingtalk/progress.d.ts +55 -6
  46. package/dist/dingtalk/progress.js +195 -16
  47. package/dist/file-store.d.ts +4 -0
  48. package/dist/file-store.js +6 -1
  49. package/dist/jobs/completion-observer.d.ts +20 -0
  50. package/dist/jobs/completion-observer.js +107 -0
  51. package/dist/jobs/completion-signal.d.ts +9 -0
  52. package/dist/jobs/completion-signal.js +32 -0
  53. package/dist/jobs/completion-wake.d.ts +1 -1
  54. package/dist/jobs/completion-wake.js +2 -13
  55. package/dist/jobs/manager.d.ts +11 -29
  56. package/dist/jobs/manager.js +103 -176
  57. package/dist/jobs/probe.d.ts +3 -0
  58. package/dist/jobs/probe.js +42 -0
  59. package/dist/jobs/record.d.ts +3 -6
  60. package/dist/jobs/runtime.d.ts +28 -0
  61. package/dist/jobs/runtime.js +69 -0
  62. package/dist/memory/boundary-work.d.ts +2 -0
  63. package/dist/memory/boundary-work.js +79 -37
  64. package/dist/memory/commands.js +4 -1
  65. package/dist/memory/index-budget.js +18 -15
  66. package/dist/memory/journal.js +2 -1
  67. package/dist/memory/lifecycle.d.ts +4 -8
  68. package/dist/memory/lifecycle.js +21 -51
  69. package/dist/memory/reflect-job.d.ts +0 -6
  70. package/dist/memory/reflect-job.js +13 -34
  71. package/dist/memory/reflect.d.ts +4 -0
  72. package/dist/memory/reflect.js +32 -5
  73. package/dist/memory/review-log.d.ts +13 -0
  74. package/dist/memory/review-log.js +49 -0
  75. package/dist/memory/search.js +7 -4
  76. package/dist/memory/source-window.d.ts +18 -1
  77. package/dist/memory/source-window.js +59 -9
  78. package/dist/memory/store.d.ts +2 -0
  79. package/dist/memory/store.js +45 -13
  80. package/dist/playbooks/agent-delegation.md +10 -4
  81. package/dist/playbooks/background-jobs.md +4 -4
  82. package/dist/playbooks/event-scheduling.md +2 -2
  83. package/dist/playbooks/memory-and-learning.md +3 -3
  84. package/dist/playbooks/outbound-media.md +2 -2
  85. package/dist/playbooks/runtime-orientation.md +10 -6
  86. package/dist/playbooks/task-lead.md +54 -33
  87. package/dist/runtime/bootstrap.d.ts +11 -24
  88. package/dist/runtime/bootstrap.js +92 -59
  89. package/dist/runtime/channel-queue.d.ts +2 -0
  90. package/dist/runtime/channel-queue.js +5 -1
  91. package/dist/runtime/durable-dispatch.d.ts +7 -0
  92. package/dist/runtime/durable-dispatch.js +66 -7
  93. package/dist/runtime/ingress-busy.d.ts +1 -2
  94. package/dist/runtime/ingress-busy.js +2 -35
  95. package/dist/runtime/ingress-commands.d.ts +1 -1
  96. package/dist/runtime/ingress-commands.js +28 -20
  97. package/dist/runtime/ingress-deps.d.ts +4 -7
  98. package/dist/runtime/ingress.js +23 -13
  99. package/dist/runtime/shutdown.d.ts +1 -1
  100. package/dist/runtime/shutdown.js +2 -2
  101. package/dist/runtime/task-close.d.ts +4 -0
  102. package/dist/runtime/task-close.js +102 -0
  103. package/dist/runtime/task-control.d.ts +34 -0
  104. package/dist/runtime/task-control.js +225 -0
  105. package/dist/runtime/task-input.d.ts +13 -0
  106. package/dist/runtime/task-input.js +129 -0
  107. package/dist/runtime/task-lane-types.d.ts +123 -0
  108. package/dist/runtime/task-lane-types.js +14 -0
  109. package/dist/runtime/task-lane.d.ts +99 -0
  110. package/dist/runtime/task-lane.js +703 -0
  111. package/dist/runtime/task-pending.d.ts +8 -0
  112. package/dist/runtime/task-pending.js +40 -0
  113. package/dist/runtime/task-spawn.d.ts +4 -4
  114. package/dist/runtime/task-spawn.js +4 -4
  115. package/dist/runtime/task-step.d.ts +32 -0
  116. package/dist/runtime/task-step.js +276 -0
  117. package/dist/runtime/turn-run.d.ts +4 -16
  118. package/dist/runtime/turn-run.js +17 -155
  119. package/dist/runtime/wake-coalescing.d.ts +1 -3
  120. package/dist/runtime/wake-coalescing.js +2 -4
  121. package/dist/shared/format.d.ts +0 -6
  122. package/dist/shared/format.js +0 -17
  123. package/dist/shared/host-process.d.ts +2 -0
  124. package/dist/shared/host-process.js +16 -1
  125. package/dist/shared/jsonl-appender.d.ts +5 -0
  126. package/dist/shared/jsonl-appender.js +25 -2
  127. package/dist/skills/catalog.d.ts +9 -0
  128. package/dist/skills/catalog.js +34 -0
  129. package/dist/skills/commands.d.ts +3 -12
  130. package/dist/skills/commands.js +36 -22
  131. package/dist/skills/loader.d.ts +2 -31
  132. package/dist/skills/loader.js +101 -68
  133. package/dist/skills/roots.d.ts +12 -0
  134. package/dist/skills/roots.js +18 -0
  135. package/dist/skills/types.d.ts +24 -0
  136. package/dist/skills/types.js +1 -0
  137. package/dist/subagents/completion-wake.js +0 -10
  138. package/dist/subagents/discovery.d.ts +1 -1
  139. package/dist/subagents/discovery.js +10 -16
  140. package/dist/subagents/dispatch.js +8 -16
  141. package/dist/subagents/external/cursor-cli.d.ts +2 -0
  142. package/dist/subagents/external/cursor-cli.js +256 -0
  143. package/dist/subagents/external/harness.d.ts +5 -5
  144. package/dist/subagents/external/reconciliation.d.ts +7 -0
  145. package/dist/subagents/external/reconciliation.js +105 -0
  146. package/dist/subagents/external/recovery.d.ts +20 -0
  147. package/dist/subagents/external/recovery.js +71 -0
  148. package/dist/subagents/external/registry.js +2 -0
  149. package/dist/subagents/external/role-warnings.d.ts +17 -0
  150. package/dist/subagents/external/role-warnings.js +42 -0
  151. package/dist/subagents/external/run.js +18 -22
  152. package/dist/subagents/format.d.ts +1 -1
  153. package/dist/subagents/format.js +1 -1
  154. package/dist/subagents/grace.d.ts +2 -2
  155. package/dist/subagents/grace.js +3 -3
  156. package/dist/subagents/internal/run.js +7 -5
  157. package/dist/subagents/internal/worker.js +31 -2
  158. package/dist/subagents/result.js +2 -3
  159. package/dist/subagents/run-record.d.ts +4 -7
  160. package/dist/subagents/run-record.js +2 -2
  161. package/dist/subagents/runs.d.ts +33 -46
  162. package/dist/subagents/runs.js +126 -245
  163. package/dist/subagents/task-settlement.d.ts +3 -0
  164. package/dist/subagents/task-settlement.js +20 -0
  165. package/dist/subagents/types.d.ts +1 -2
  166. package/dist/subagents/workspace-summary.js +5 -1
  167. package/dist/tasks/archive.d.ts +11 -0
  168. package/dist/tasks/archive.js +141 -0
  169. package/dist/tasks/board.d.ts +5 -12
  170. package/dist/tasks/board.js +4 -30
  171. package/dist/tasks/bound-work.d.ts +12 -6
  172. package/dist/tasks/bound-work.js +37 -24
  173. package/dist/tasks/brief.d.ts +38 -14
  174. package/dist/tasks/brief.js +128 -70
  175. package/dist/tasks/budget.d.ts +3 -3
  176. package/dist/tasks/budget.js +9 -4
  177. package/dist/tasks/commands.d.ts +14 -9
  178. package/dist/tasks/commands.js +190 -121
  179. package/dist/tasks/completion.d.ts +12 -0
  180. package/dist/tasks/completion.js +35 -0
  181. package/dist/tasks/contract.d.ts +8 -17
  182. package/dist/tasks/contract.js +41 -43
  183. package/dist/tasks/control.d.ts +138 -0
  184. package/dist/tasks/control.js +1 -0
  185. package/dist/tasks/create.d.ts +1 -1
  186. package/dist/tasks/create.js +3 -3
  187. package/dist/tasks/delivery.d.ts +24 -0
  188. package/dist/tasks/delivery.js +221 -0
  189. package/dist/tasks/file-mutation.d.ts +5 -0
  190. package/dist/tasks/file-mutation.js +38 -0
  191. package/dist/tasks/frontmatter.d.ts +43 -28
  192. package/dist/tasks/frontmatter.js +83 -40
  193. package/dist/tasks/input-receipts.d.ts +7 -0
  194. package/dist/tasks/input-receipts.js +60 -0
  195. package/dist/tasks/loop-log.d.ts +147 -28
  196. package/dist/tasks/loop-log.js +239 -28
  197. package/dist/tasks/receipts.d.ts +19 -0
  198. package/dist/tasks/receipts.js +48 -0
  199. package/dist/tasks/state.d.ts +93 -0
  200. package/dist/tasks/state.js +156 -0
  201. package/dist/tasks/store.d.ts +81 -49
  202. package/dist/tasks/store.js +244 -147
  203. package/dist/tools/bash.d.ts +3 -5
  204. package/dist/tools/bash.js +8 -22
  205. package/dist/tools/contract/details.d.ts +6 -6
  206. package/dist/tools/contract/details.js +6 -6
  207. package/dist/tools/contract/execution-trace.d.ts +4 -0
  208. package/dist/tools/contract/execution-trace.js +23 -0
  209. package/dist/tools/contract/presentation.js +6 -2
  210. package/dist/tools/edit.d.ts +1 -0
  211. package/dist/tools/edit.js +45 -42
  212. package/dist/tools/index.d.ts +8 -12
  213. package/dist/tools/index.js +16 -6
  214. package/dist/tools/memory-manage.js +8 -1
  215. package/dist/tools/registry.d.ts +7 -11
  216. package/dist/tools/registry.js +52 -25
  217. package/dist/tools/skill.d.ts +2 -2
  218. package/dist/tools/skill.js +24 -10
  219. package/dist/tools/subagent-manage.js +7 -4
  220. package/dist/tools/subagent.d.ts +0 -2
  221. package/dist/tools/subagent.js +2 -7
  222. package/dist/tools/task-manage/control-tools.d.ts +4 -0
  223. package/dist/tools/task-manage/control-tools.js +65 -0
  224. package/dist/tools/task-manage/create.js +2 -1
  225. package/dist/tools/task-manage/factory.d.ts +12 -6
  226. package/dist/tools/task-manage/factory.js +72 -57
  227. package/dist/tools/task-manage/lifecycle.d.ts +7 -12
  228. package/dist/tools/task-manage/lifecycle.js +118 -66
  229. package/dist/tools/task-manage/log-view.js +8 -5
  230. package/dist/tools/task-manage/schema.d.ts +21 -26
  231. package/dist/tools/task-manage/schema.js +29 -35
  232. package/dist/tools/task-manage/shared.d.ts +8 -39
  233. package/dist/tools/task-manage/shared.js +19 -68
  234. package/dist/tools/task-manage/step-tools.d.ts +5 -0
  235. package/dist/tools/task-manage/step-tools.js +103 -0
  236. package/dist/tools/task-manage/types.d.ts +25 -18
  237. package/dist/tools/write-content.d.ts +1 -0
  238. package/dist/tools/write-content.js +6 -1
  239. package/dist/tools/write.d.ts +1 -0
  240. package/dist/tools/write.js +1 -0
  241. package/dist/usage/ledger.d.ts +4 -4
  242. package/dist/usage/render.js +2 -2
  243. package/dist/web/search-providers.js +0 -33
  244. package/dist/webapi/request-policy.js +1 -1
  245. package/examples/sub-agents/README.md +23 -16
  246. package/examples/sub-agents/agents/claude-high.md +1 -1
  247. package/examples/sub-agents/agents/claude-main.md +1 -1
  248. package/examples/sub-agents/agents/codex-flash.md +1 -1
  249. package/examples/sub-agents/agents/codex-high.md +1 -1
  250. package/examples/sub-agents/agents/codex-main.md +4 -4
  251. package/examples/sub-agents/agents/cursor-high.md +22 -0
  252. package/examples/sub-agents/agents/cursor-main.md +22 -0
  253. package/examples/sub-agents/agents/glm-flash.md +1 -1
  254. package/examples/sub-agents/agents/glm-high.md +2 -2
  255. package/examples/sub-agents/agents/scout.md +30 -0
  256. package/package.json +6 -6
  257. package/dist/runtime/task-driver.d.ts +0 -116
  258. package/dist/runtime/task-driver.js +0 -443
  259. package/dist/runtime/task-wake.d.ts +0 -48
  260. package/dist/runtime/task-wake.js +0 -32
  261. package/dist/shared/wake-claim.d.ts +0 -23
  262. package/dist/shared/wake-claim.js +0 -26
  263. package/dist/skills/validation.d.ts +0 -8
  264. package/dist/skills/validation.js +0 -91
  265. package/dist/skills/workspace.d.ts +0 -33
  266. package/dist/skills/workspace.js +0 -116
  267. package/dist/tasks/steer.d.ts +0 -8
  268. package/dist/tasks/steer.js +0 -81
  269. package/dist/tasks/ticket.d.ts +0 -71
  270. package/dist/tasks/ticket.js +0 -138
  271. package/dist/tools/task-manage/step-end.d.ts +0 -11
  272. package/dist/tools/task-manage/step-end.js +0 -117
@@ -13,6 +13,13 @@ export declare class CardController {
13
13
  private cardGenerations;
14
14
  private cardCreationAttempted;
15
15
  private cardCreationInFlight;
16
+ /**
17
+ * The live template accepts appended list items. A markdown variable that does not is remembered
18
+ * for the process: later progress updates send a full snapshot instead of trying append again.
19
+ */
20
+ private appendSupported;
21
+ /** False after this process has seen the template reject an appended fragment. */
22
+ supportsStreamingAppend(): boolean;
16
23
  constructor(deps: CardControllerDeps);
17
24
  /** Capture the current turn's identity; close, /stop and /new invalidate it. */
18
25
  getCardGeneration(channelId: string): symbol;
@@ -7,8 +7,19 @@ import axios from "axios";
7
7
  import * as log from "../log.js";
8
8
  import { errorMessage } from "../shared/text-utils.js";
9
9
  import { DINGTALK_API, http } from "./api.js";
10
+ import { CARD_REQUEST_MAX_BYTES } from "./progress.js";
10
11
  const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
12
+ /** A streaming variable that is markdown rejects `isFull: false`. The message names one of these. */
13
+ function rejectsMarkdownAppend(data) {
14
+ const text = typeof data === "string" ? data : JSON.stringify(data ?? "");
15
+ const normalized = text.toLowerCase();
16
+ return normalized.includes("isfull") || normalized.includes("markdown");
17
+ }
11
18
  export class CardController {
19
+ /** False after this process has seen the template reject an appended fragment. */
20
+ supportsStreamingAppend() {
21
+ return this.appendSupported;
22
+ }
12
23
  constructor(deps) {
13
24
  this.deps = deps;
14
25
  // Active AI cards: channelId → AICard
@@ -17,6 +28,11 @@ export class CardController {
17
28
  this.cardCreationAttempted = new Set();
18
29
  // Share creation within a turn, but never let a late old turn own a new turn's card.
19
30
  this.cardCreationInFlight = new Map();
31
+ /**
32
+ * The live template accepts appended list items. A markdown variable that does not is remembered
33
+ * for the process: later progress updates send a full snapshot instead of trying append again.
34
+ */
35
+ this.appendSupported = true;
20
36
  }
21
37
  /** Capture the current turn's identity; close, /stop and /new invalidate it. */
22
38
  getCardGeneration(channelId) {
@@ -62,6 +78,8 @@ export class CardController {
62
78
  if (!this.isCardGenerationCurrent(channelId, generation))
63
79
  return false;
64
80
  const { append, finalize, failed } = options;
81
+ if (append && !this.appendSupported)
82
+ return false;
65
83
  if (append && !content && !finalize && !failed) {
66
84
  return true;
67
85
  }
@@ -114,7 +132,9 @@ export class CardController {
114
132
  this.activeCards.delete(channelId);
115
133
  // /stop and /new may invalidate a turn before its controller gets to finish.
116
134
  if (card && !card.finished) {
117
- void this.streamCard(card, `${card.content || "正在处理…"}\n\n处理已结束。`, {
135
+ // One plain line. Keeping the transcript would leave an unfinished markdown document
136
+ // in the chat, and a card cannot be deleted.
137
+ void this.streamCard(card, "处理已结束。", {
118
138
  append: false,
119
139
  finalize: true,
120
140
  failed: false,
@@ -269,6 +289,14 @@ export class CardController {
269
289
  card.accessToken = token;
270
290
  }
271
291
  }
292
+ // Progress updates stay within one request. A finalized answer is the model's own markdown
293
+ // and may be longer; a failed finalize falls back to a normal message.
294
+ if (!options.finalize && !options.failed && Buffer.byteLength(content) > CARD_REQUEST_MAX_BYTES) {
295
+ log.logWarn("dingtalk.card.frame_too_large", "Card streaming skipped an oversized frame", {
296
+ fields: { bytes: Buffer.byteLength(content) },
297
+ });
298
+ return false;
299
+ }
272
300
  const body = {
273
301
  outTrackId: card.instanceId,
274
302
  guid: `${Date.now()}_${Math.random().toString(36).substring(2, 8)}`,
@@ -296,7 +324,7 @@ export class CardController {
296
324
  });
297
325
  }
298
326
  card.lastUpdated = Date.now() / 1000;
299
- card.content = options.append ? `${card.content}${content}` : content;
327
+ card.content = options.append ? card.content + content : content;
300
328
  if (options.finalize || options.failed) {
301
329
  card.finished = true;
302
330
  }
@@ -304,6 +332,8 @@ export class CardController {
304
332
  }
305
333
  catch (err) {
306
334
  if (axios.isAxiosError(err) && err.response) {
335
+ if (options.append && rejectsMarkdownAppend(err.response.data))
336
+ this.appendSupported = false;
307
337
  log.logWarn("dingtalk.card.stream_failed", "Card streaming failed", {
308
338
  reason: JSON.stringify(err.response.data),
309
339
  fields: { status: err.response.status },
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * The DingTalk implementation of the turn output port (`ChannelContext`): it reads a turn's
3
3
  * structured events and renders them as AI-Card progress, plain messages and a final answer,
4
- * including the "card failed, send it plainly" fallbacks.
4
+ * including the "card failed, send it plainly" fallbacks. Progress appends whole list items
5
+ * until the card nears the document ceiling, then one short snapshot replaces it. The answer
6
+ * is a normal message and the card then folds to one line.
5
7
  */
6
8
  import type { ChannelContext } from "../channel/channel-context.js";
7
9
  import type { TurnInfo } from "../channel/transport.js";
@@ -21,6 +23,8 @@ export interface DeliveryPort {
21
23
  isCardGenerationCurrent(channelId: string, generation: symbol): boolean;
22
24
  replaceCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
23
25
  appendToCard(channelId: string, content: string, finalize?: boolean, failed?: boolean, generation?: symbol): Promise<boolean>;
26
+ /** False once this process has learned that the template rejects an appended fragment. */
27
+ supportsStreamingAppend(): boolean;
24
28
  finalizeCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
25
29
  finalizeExistingCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
26
30
  discardCard(channelId: string, generation?: symbol): void;
@@ -2,16 +2,11 @@ import * as log from "../log.js";
2
2
  import { formatElapsedZh } from "../shared/format.js";
3
3
  import { errorMessage } from "../shared/text-utils.js";
4
4
  import { describeToolCall } from "../tools/contract/presentation.js";
5
- import { formatProgressEntry } from "./progress.js";
6
- const MIN_UPDATE_INTERVAL_MS = 800;
7
- const ROLLING_WINDOW_SIZE = 3;
5
+ import { CARD_COMPACT_MAX_BYTES, CARD_REQUEST_MAX_BYTES, planProgressWrite, renderCardStatus, renderProgressFrame, renderProgressLine, } from "./progress.js";
6
+ const PROGRESS_WINDOW = 3;
8
7
  const WAITING_TEXT = "正在处理…";
9
8
  const MAX_PROGRESS_FAILURES = 2;
10
- // DingTalk's card renderer swallows a bare "\n" between plain lines (and a blank-line
11
- // paragraph break leaves too much vertical gap), but it does reliably break a markdown
12
- // list onto separate lines. Render each progress entry as a list item instead.
13
- const PROGRESS_LINE_BREAK = "\n";
14
- const PROGRESS_ENTRY_PREFIX = "- ";
9
+ const SILENT_STATUS = "已处理,无需答复。";
15
10
  // Last-resort ceiling on how long flush() will block a caller. Outbound HTTP now
16
11
  // has its own timeout, so the sync loop is already bounded; this only guards against
17
12
  // an unforeseen stall so run()'s finally can never hang the channel forever.
@@ -25,9 +20,13 @@ class ChannelDeliveryController {
25
20
  this.bot = bot;
26
21
  this.archive = archive;
27
22
  this.quiet = quiet;
28
- this.progressSegments = [];
29
- this.cachedProgressText = "";
30
- this.progressTextDirty = false;
23
+ this.thinking = "";
24
+ this.activities = [];
25
+ /** What the card shows after the warmup line has been replaced. Empty until the first real frame. */
26
+ this.document = "";
27
+ /** Whole list items not yet on the card. */
28
+ this.pendingLines = [];
29
+ this.warmupDelivered = false;
31
30
  this.mode = "progress";
32
31
  this.desiredRevision = 0;
33
32
  this.appliedRevision = 0;
@@ -39,14 +38,10 @@ class ChannelDeliveryController {
39
38
  this.cardWarmupScheduled = false;
40
39
  this.cardWarmupTriggered = false;
41
40
  this.progressStartedAt = 0;
42
- this.progressWindowStartedAt = 0;
43
41
  this.toolCallCount = 0;
44
- this.lastDeliveredAt = 0;
45
42
  this.timer = null;
46
43
  this.cardWarmupTimer = null;
47
44
  this.flushWaiters = [];
48
- this.sentProgressChars = 0;
49
- this.replayRequired = false;
50
45
  this.finalReplacementText = "";
51
46
  /** Deliveries run one after another in the order the events arrived. */
52
47
  this.chain = Promise.resolve();
@@ -96,17 +91,18 @@ class ChannelDeliveryController {
96
91
  async deliver(event) {
97
92
  switch (event.type) {
98
93
  case "tool.start":
99
- await this.appendProgress(formatProgressEntry("tool", describeToolCall(event.tool, event.args)), false, true);
94
+ await this.remember(describeToolCall(event.tool, event.args), "➜", { countTool: true });
100
95
  return;
101
96
  case "tool.update":
102
- await this.appendProgress(formatProgressEntry("tool", event.text), false);
97
+ await this.remember(event.text, "➜");
103
98
  return;
104
99
  case "tool.end":
105
100
  if (event.failure)
106
- await this.appendProgress(formatProgressEntry("error", event.failure), false);
101
+ await this.remember(event.failure, "✕");
107
102
  return;
108
103
  case "reasoning":
109
- await this.appendProgress(formatProgressEntry("thinking", event.text), false);
104
+ // Full mode keeps the latest thought pinned. Rolling lets it scroll with everything else.
105
+ await this.remember(event.text, "✦", { pin: this.progressStyle === "full", tail: true });
110
106
  return;
111
107
  case "commentary":
112
108
  await this.deliverCommentary(event.text, event.level);
@@ -115,9 +111,8 @@ class ChannelDeliveryController {
115
111
  await this.deliverAnswer(event.text);
116
112
  return;
117
113
  case "compaction":
118
- if (event.phase === "start") {
119
- await this.appendProgress(formatProgressEntry("assistant", "正在压缩上下文…"), false);
120
- }
114
+ if (event.phase === "start")
115
+ await this.remember("正在压缩上下文…", "");
121
116
  return;
122
117
  case "steer.applied":
123
118
  return;
@@ -126,14 +121,14 @@ class ChannelDeliveryController {
126
121
  async deliverCommentary(text, level) {
127
122
  switch (level) {
128
123
  case undefined:
129
- await this.appendProgress(formatProgressEntry("assistant", text), false);
124
+ await this.remember(text, "");
130
125
  return;
131
126
  case "error":
132
- await this.appendProgress(formatProgressEntry("error", text), false);
127
+ await this.remember(text, "✕");
133
128
  return;
134
129
  case "warning":
135
130
  if (this.progressStyle !== "none") {
136
- await this.appendProgress(formatProgressEntry("error", text), false);
131
+ await this.remember(text, "✕");
137
132
  }
138
133
  else {
139
134
  await this.notice(`⚠️ ${text}`);
@@ -243,7 +238,11 @@ class ChannelDeliveryController {
243
238
  });
244
239
  });
245
240
  }
246
- async appendProgress(text, shouldLog, isToolCall = false) {
241
+ /**
242
+ * Record one progress line. `pin` holds the latest thinking for the next snapshot. The line
243
+ * itself is queued and appended; the header is rewritten only when the card is compressed.
244
+ */
245
+ async remember(text, marker, options) {
247
246
  if (this.closed || this.ending || !this.isCurrent || !text.trim())
248
247
  return;
249
248
  // Final-card-only mode shows no progress; ignore any stray progress writes
@@ -251,33 +250,32 @@ class ChannelDeliveryController {
251
250
  if (this.progressStyle === "none")
252
251
  return;
253
252
  this.clearCardWarmup();
254
- if (this.progressStartedAt === 0) {
253
+ if (this.progressStartedAt === 0)
255
254
  this.progressStartedAt = Date.now();
256
- }
257
- if (isToolCall) {
255
+ if (options?.countTool)
258
256
  this.toolCallCount++;
257
+ if (options?.pin) {
258
+ this.thinking = text;
259
259
  }
260
- if (this.progressSegments.length > 0) {
261
- this.progressSegments.push(PROGRESS_LINE_BREAK);
262
- }
263
- this.progressSegments.push(`${PROGRESS_ENTRY_PREFIX}${text}`);
264
- this.progressTextDirty = true;
265
- if (this.progressStyle === "rolling") {
266
- this.trimToRecentEntries(ROLLING_WINDOW_SIZE);
267
- // The header carries elapsed time and a step count, so it changes on every update:
268
- // an append-only delta would leave a stale header on the card.
269
- this.replayRequired = true;
270
- this.sentProgressChars = 0;
271
- }
272
- if (this.progressWindowStartedAt === 0) {
273
- this.progressWindowStartedAt = Date.now();
274
- }
275
- if (shouldLog) {
276
- this.archiveBotResponse(text);
260
+ else {
261
+ this.activities.push({ marker, text, tail: options?.tail === true });
262
+ while (this.activities.length > PROGRESS_WINDOW)
263
+ this.activities.shift();
277
264
  }
265
+ this.queueLine(marker, text, options?.tail === true);
278
266
  this.mode = "progress";
279
267
  this.bumpRevision(false);
280
268
  }
269
+ /** Queue one finished list item. An unchanged tail is not sent again. */
270
+ queueLine(marker, text, tail) {
271
+ const line = renderProgressLine({ marker, text, tail });
272
+ if (!line)
273
+ return;
274
+ const last = this.pendingLines.at(-1) ?? (this.document ? this.document.split("\n").at(-1) : undefined);
275
+ if (line === last)
276
+ return;
277
+ this.pendingLines.push(line);
278
+ }
281
279
  async sendFinal(text, shouldLog, title) {
282
280
  if (this.closed || this.ending || !this.isCurrent || !text.trim())
283
281
  return this.finalResponseDelivered;
@@ -286,7 +284,7 @@ class ChannelDeliveryController {
286
284
  if (this.timer)
287
285
  clearTimeout(this.timer);
288
286
  this.timer = null;
289
- if (this.cardWarmupTriggered && !this.getProgressText().trim()) {
287
+ if (this.cardWarmupTriggered && !this.hasRecordedProgress()) {
290
288
  // The card only ever said "正在处理…": the answer goes into it rather than into a second
291
289
  // message under a card that would just read "已答复。".
292
290
  this.finalReplacementText = text;
@@ -343,18 +341,16 @@ class ChannelDeliveryController {
343
341
  clearTimeout(this.timer);
344
342
  this.timer = null;
345
343
  }
346
- const delay = forceImmediate || this.mode !== "progress"
347
- ? 0
348
- : Math.max(0, MIN_UPDATE_INTERVAL_MS -
349
- (Date.now() - (this.lastDeliveredAt > 0 ? this.lastDeliveredAt : this.progressWindowStartedAt)));
350
- if (delay === 0) {
344
+ // Endings go out immediately. Progress waits one macrotask so events already queued on the
345
+ // delivery chain collapse into one write. Nothing polls on a clock.
346
+ if (forceImmediate || this.mode !== "progress") {
351
347
  void this.runSyncLoop();
352
348
  return;
353
349
  }
354
350
  this.timer = setTimeout(() => {
355
351
  this.timer = null;
356
352
  void this.runSyncLoop();
357
- }, delay);
353
+ }, 0);
358
354
  }
359
355
  async runSyncLoop() {
360
356
  if (this.running)
@@ -363,54 +359,18 @@ class ChannelDeliveryController {
363
359
  try {
364
360
  while (this.appliedRevision < this.desiredRevision) {
365
361
  const mode = this.mode;
366
- const body = this.getProgressText();
367
- const progressText = mode === "progress" && this.progressStyle === "rolling" && body
368
- ? `${this.buildRollingHeader()}\n\n${body}`
369
- : body || (this.cardWarmupTriggered ? WAITING_TEXT : "");
370
- const throttleBaseAt = this.lastDeliveredAt > 0 ? this.lastDeliveredAt : this.progressWindowStartedAt;
371
- if (mode === "progress" && throttleBaseAt > 0) {
372
- const remaining = MIN_UPDATE_INTERVAL_MS - (Date.now() - throttleBaseAt);
373
- if (remaining > 0) {
374
- this.timer = setTimeout(() => {
375
- this.timer = null;
376
- void this.runSyncLoop();
377
- }, remaining);
378
- return;
379
- }
380
- }
381
362
  const revision = this.desiredRevision;
382
- const content = progressText.trim();
383
363
  const replacementText = this.finalReplacementText;
384
364
  let touchedRemote = false;
385
365
  try {
386
366
  if (mode === "progress") {
387
- if (content && this.isCurrent && this.progressFailures < MAX_PROGRESS_FAILURES) {
388
- const nextSentChars = progressText.length;
389
- if (this.replayRequired || this.sentProgressChars === 0) {
390
- touchedRemote = await this.bot.replaceCard(this.event.channelId, progressText, false, false, this.cardGeneration);
391
- }
392
- else {
393
- const delta = progressText.slice(this.sentProgressChars);
394
- touchedRemote = delta
395
- ? await this.bot.appendToCard(this.event.channelId, delta, false, false, this.cardGeneration)
396
- : true;
397
- }
398
- if (!touchedRemote) {
399
- this.progressFailures++;
400
- this.replayRequired = true;
401
- }
402
- else {
403
- this.sentProgressChars = body ? nextSentChars : 0;
404
- this.replayRequired = false;
405
- }
367
+ if (this.isCurrent && this.progressFailures < MAX_PROGRESS_FAILURES) {
368
+ touchedRemote = await this.publishProgress();
406
369
  }
407
370
  }
408
371
  else if (mode === "finalize-existing") {
409
- if (content || this.cardWarmupTriggered) {
410
- const finalProgressText = this.progressStyle === "rolling"
411
- ? this.buildSummaryText()
412
- : [body, "已答复。"].filter(Boolean).join("\n\n");
413
- touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, finalProgressText, this.cardGeneration);
372
+ if (this.document || this.cardWarmupTriggered || this.hasRecordedProgress()) {
373
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, this.buildSummaryText(), this.cardGeneration);
414
374
  }
415
375
  }
416
376
  else if (mode === "finalize-with-fallback") {
@@ -420,8 +380,8 @@ class ChannelDeliveryController {
420
380
  }
421
381
  }
422
382
  else if (mode === "silent") {
423
- if (content) {
424
- touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "已处理,无需答复。"].filter(Boolean).join("\n\n"), this.cardGeneration);
383
+ if (this.document || this.cardWarmupTriggered || this.hasRecordedProgress()) {
384
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, renderCardStatus(SILENT_STATUS), this.cardGeneration);
425
385
  }
426
386
  }
427
387
  }
@@ -430,16 +390,8 @@ class ChannelDeliveryController {
430
390
  channelId: this.event.channelId,
431
391
  reason: errorMessage(err),
432
392
  });
433
- if (mode === "progress") {
393
+ if (mode === "progress")
434
394
  this.progressFailures++;
435
- this.replayRequired = true;
436
- }
437
- }
438
- if (touchedRemote) {
439
- this.lastDeliveredAt = Date.now();
440
- }
441
- if (mode !== "progress" || touchedRemote) {
442
- this.progressWindowStartedAt = 0;
443
395
  }
444
396
  this.appliedRevision = revision;
445
397
  }
@@ -501,15 +453,104 @@ class ChannelDeliveryController {
501
453
  await this.flush();
502
454
  this.bot.discardCard(this.event.channelId, this.cardGeneration);
503
455
  }
504
- getProgressText() {
505
- if (!this.progressTextDirty) {
506
- return this.cachedProgressText;
456
+ /** True once this turn has something to show besides the warmup line. */
457
+ hasRecordedProgress() {
458
+ return this.thinking !== "" || this.activities.length > 0 || this.document !== "";
459
+ }
460
+ /** Send queued progress, or the one-shot warmup line when nothing has been recorded yet. */
461
+ async publishProgress() {
462
+ if (this.pendingLines.length === 0)
463
+ return this.publishWarmup();
464
+ let touched = false;
465
+ while (this.pendingLines.length > 0 && this.progressFailures < MAX_PROGRESS_FAILURES) {
466
+ const step = await this.sendPending();
467
+ if (step.touched)
468
+ touched = true;
469
+ if (!step.cont)
470
+ break;
471
+ }
472
+ return touched;
473
+ }
474
+ async publishWarmup() {
475
+ if (this.document || !this.cardWarmupTriggered || this.warmupDelivered)
476
+ return false;
477
+ const ok = await this.bot.replaceCard(this.event.channelId, WAITING_TEXT, false, false, this.cardGeneration);
478
+ if (!ok) {
479
+ this.progressFailures++;
480
+ return false;
507
481
  }
508
- this.cachedProgressText = this.progressSegments.join("");
509
- this.progressTextDirty = false;
510
- return this.cachedProgressText;
482
+ this.warmupDelivered = true;
483
+ return true;
484
+ }
485
+ async sendPending() {
486
+ const planned = planProgressWrite({
487
+ document: this.document,
488
+ pending: this.pendingLines,
489
+ append: this.bot.supportsStreamingAppend(),
490
+ header: this.buildLiveHeader(),
491
+ fallback: this.snapshot(CARD_REQUEST_MAX_BYTES, this.activities),
492
+ compact: this.snapshot(CARD_COMPACT_MAX_BYTES, this.activities.slice(-1)),
493
+ });
494
+ if (!planned || planned.method === "drop") {
495
+ if (planned?.method === "drop")
496
+ this.pendingLines.shift();
497
+ else
498
+ this.pendingLines = [];
499
+ return { touched: false, cont: planned?.method === "drop" };
500
+ }
501
+ const ok = await this.writeProgress(planned);
502
+ if (ok) {
503
+ this.applySent(planned);
504
+ this.progressFailures = 0;
505
+ return { touched: true, cont: true };
506
+ }
507
+ if (planned.method === "append") {
508
+ const frame = this.bot.supportsStreamingAppend()
509
+ ? this.snapshot(CARD_COMPACT_MAX_BYTES, this.activities.slice(-1))
510
+ : this.snapshot(CARD_REQUEST_MAX_BYTES, this.activities);
511
+ const replaced = await this.bot.replaceCard(this.event.channelId, frame, false, false, this.cardGeneration);
512
+ if (replaced) {
513
+ this.document = frame;
514
+ this.pendingLines = this.bot.supportsStreamingAppend()
515
+ ? this.pendingLines.filter((line) => !frame.split("\n").includes(line))
516
+ : [];
517
+ this.progressFailures = 0;
518
+ return { touched: true, cont: false };
519
+ }
520
+ }
521
+ this.progressFailures++;
522
+ return { touched: false, cont: false };
523
+ }
524
+ async writeProgress(planned) {
525
+ if (planned.method === "append") {
526
+ return this.bot.appendToCard(this.event.channelId, planned.content, false, false, this.cardGeneration);
527
+ }
528
+ return this.bot.replaceCard(this.event.channelId, planned.content, false, false, this.cardGeneration);
529
+ }
530
+ applySent(planned) {
531
+ if (planned.method === "append") {
532
+ this.document += planned.content;
533
+ this.pendingLines.shift();
534
+ return;
535
+ }
536
+ this.document = planned.content;
537
+ if (planned.clearPending) {
538
+ this.pendingLines = [];
539
+ return;
540
+ }
541
+ const lines = new Set(planned.content.split("\n"));
542
+ this.pendingLines = this.pendingLines.filter((line) => !lines.has(line));
543
+ }
544
+ /** A full snapshot: the live header, pinned thinking in full mode, and the given activities. */
545
+ snapshot(maxBytes, activities) {
546
+ return renderProgressFrame({
547
+ header: this.buildLiveHeader(),
548
+ thinking: this.progressStyle === "full" ? this.thinking : undefined,
549
+ activities,
550
+ maxBytes,
551
+ });
511
552
  }
512
- /** Clock-style elapsed time (`0:42`, `1:02`, `1:05:09`) for the narrow rolling header. */
553
+ /** Clock-style elapsed time (`0:42`, `1:02`, `1:05:09`) for the card's first line. */
513
554
  formatClock(ms) {
514
555
  const seconds = Math.max(0, Math.round(ms / 1000));
515
556
  const minutes = Math.floor(seconds / 60);
@@ -522,41 +563,15 @@ class ChannelDeliveryController {
522
563
  return this.progressStartedAt > 0 ? Date.now() - this.progressStartedAt : 0;
523
564
  }
524
565
  /**
525
- * Standing first line for rolling mode. The window only keeps the last few entries, so a long
526
- * turn otherwise gave no way to tell "still working, 14 tool calls in" from "stuck": every
527
- * visible line looked the same as a minute ago. The numbers are already tracked for the closing
528
- * summary. Counted as tool calls, never "steps" — a step is a task's unit (spec 053, D4).
566
+ * Standing first line. The card only keeps the latest thought and a few activity lines, so
567
+ * without this a long turn looks identical to one that just started. Counted as tool calls,
568
+ * never "steps" — a step is a task's unit (spec 053, D4).
529
569
  */
530
- buildRollingHeader() {
570
+ buildLiveHeader() {
531
571
  return `⏱ ${this.formatClock(this.elapsedMs())} · 工具 ${this.toolCallCount}`;
532
572
  }
533
- trimToRecentEntries(maxEntries) {
534
- let entryCount = 0;
535
- for (const segment of this.progressSegments) {
536
- if (segment !== PROGRESS_LINE_BREAK) {
537
- entryCount++;
538
- }
539
- }
540
- if (entryCount <= maxEntries) {
541
- return;
542
- }
543
- const entriesToRemove = entryCount - maxEntries;
544
- let removedEntries = 0;
545
- while (removedEntries < entriesToRemove && this.progressSegments.length > 0) {
546
- const segment = this.progressSegments.shift();
547
- if (segment !== PROGRESS_LINE_BREAK) {
548
- removedEntries++;
549
- }
550
- }
551
- while (this.progressSegments[0] === PROGRESS_LINE_BREAK) {
552
- this.progressSegments.shift();
553
- }
554
- this.progressTextDirty = true;
555
- this.replayRequired = true;
556
- this.sentProgressChars = 0;
557
- }
558
573
  buildSummaryText() {
559
- return `完成 · 工具调用 ${this.toolCallCount} 次 · ${formatElapsedZh(this.elapsedMs())}`;
574
+ return renderCardStatus(`完成 · 工具调用 ${this.toolCallCount} 次 · ${formatElapsedZh(this.elapsedMs())}`);
560
575
  }
561
576
  }
562
577
  /**
@@ -1,8 +1,57 @@
1
1
  /**
2
- * How a turn's events read as a DingTalk progress card: one line per entry, prefixed by what kind
3
- * of entry it is (`➜` a tool call, `✦` thinking, `✕` an error, plain text for the model's own
4
- * words).
2
+ * Text for the live DingTalk progress card.
3
+ *
4
+ * A live update is one complete markdown list (`isFull: true`) or one extra list item
5
+ * (`isFull: false`). The configured template accepts both. Each request stays within
6
+ * {@link CARD_REQUEST_MAX_BYTES}. Once the next item would carry the card past
7
+ * {@link CARD_DOCUMENT_MAX_BYTES}, the card is replaced by a short snapshot and appending resumes.
8
+ * Dynamic text is made markdown-inert first, and every line is finished before it is cut.
5
9
  */
6
- export type ProgressEntryKind = "tool" | "thinking" | "error" | "assistant";
7
- /** `""` when there is nothing to show. */
8
- export declare function formatProgressEntry(kind: ProgressEntryKind, text: string): string;
10
+ export declare const CARD_REQUEST_MAX_BYTES = 1000;
11
+ export declare const CARD_DOCUMENT_MAX_BYTES = 2900;
12
+ export declare const CARD_COMPACT_MAX_BYTES = 200;
13
+ /** A line already classified by the delivery controller. `tail` keeps the end of the text. */
14
+ export interface ProgressActivity {
15
+ marker: "" | "➜" | "✕" | "✦";
16
+ text: string;
17
+ tail?: boolean;
18
+ }
19
+ /** The next card write. `drop` discards one queued line that cannot be sent on its own. */
20
+ export interface ProgressWrite {
21
+ method: "replace" | "append" | "drop";
22
+ content: string;
23
+ /** The snapshot already stands for every queued line. */
24
+ clearPending: boolean;
25
+ }
26
+ /** One list item, sized so a request that prefixes a newline still fits in one update. */
27
+ export declare function renderProgressLine(activity: ProgressActivity, maxBytes?: number): string;
28
+ /**
29
+ * One complete markdown list: a header, the latest thinking excerpt, then the activity window.
30
+ * Lines are dropped whole, then shortened, until the frame fits `maxBytes`.
31
+ */
32
+ export declare function renderProgressFrame(input: {
33
+ header: string;
34
+ thinking?: string;
35
+ activities: ProgressActivity[];
36
+ maxBytes?: number;
37
+ }): string;
38
+ /**
39
+ * The first real progress frame. It replaces the warmup line instead of appending onto it, and
40
+ * it keeps only the queued items that fit in one request. The rest stay queued for append.
41
+ */
42
+ export declare function renderOpeningFrame(header: string, pending: readonly string[]): string;
43
+ /**
44
+ * Choose the next progress write. Appending continues while the card stays under the document
45
+ * ceiling; crossing it sends the short snapshot first. With append unavailable, every update is
46
+ * one snapshot that already fits in a single request.
47
+ */
48
+ export declare function planProgressWrite(input: {
49
+ document: string;
50
+ pending: readonly string[];
51
+ append: boolean;
52
+ header: string;
53
+ fallback: string;
54
+ compact: string;
55
+ }): ProgressWrite | undefined;
56
+ /** A one-line card ending. Falls back to a fixed line if the text could not stay plain markdown. */
57
+ export declare function renderCardStatus(text: string): string;