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

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 +4 -1
  44. package/dist/dingtalk/delivery.js +104 -191
  45. package/dist/dingtalk/progress.d.ts +41 -6
  46. package/dist/dingtalk/progress.js +173 -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 grows in a local window,
5
+ * folds at its byte ceiling, and publishes paced deltas between replacement snapshots. 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,7 @@ 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
+ supportsStreamingAppend(): boolean;
24
27
  finalizeCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
25
28
  finalizeExistingCard(channelId: string, content: string, generation?: symbol): Promise<boolean>;
26
29
  discardCard(channelId: string, generation?: symbol): void;
@@ -2,22 +2,17 @@ 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 { ProgressWindow, renderCardStatus } from "./progress.js";
6
+ // A minimum gap after each completed write gives the client time to display a fold. This is
7
+ // a throttle, not a debounce: continuous events cannot postpone the next frame indefinitely.
8
+ const PROGRESS_INTERVAL_MS = 800;
8
9
  const WAITING_TEXT = "正在处理…";
9
10
  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 = "- ";
11
+ const SILENT_STATUS = "已处理,无需答复。";
15
12
  // Last-resort ceiling on how long flush() will block a caller. Outbound HTTP now
16
13
  // has its own timeout, so the sync loop is already bounded; this only guards against
17
14
  // an unforeseen stall so run()'s finally can never hang the channel forever.
18
15
  const FLUSH_DEADLINE_MS = 60_000;
19
- /** How long a turn may stay silent before a "正在处理…" card appears. */
20
- const CARD_WARMUP_MS = 3500;
21
16
  class ChannelDeliveryController {
22
17
  constructor(turn, bot, archive,
23
18
  /** A quiet turn (a background wake) shows no progress, whatever the channel is configured for. */
@@ -25,9 +20,10 @@ 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.nextProgressAt = 0;
24
+ /** What the card shows after the waiting line has been replaced. Empty until the first real frame. */
25
+ this.document = "";
26
+ this.documentEpoch = -1;
31
27
  this.mode = "progress";
32
28
  this.desiredRevision = 0;
33
29
  this.appliedRevision = 0;
@@ -36,23 +32,21 @@ class ChannelDeliveryController {
36
32
  this.finalResponseDelivered = false;
37
33
  this.ending = false;
38
34
  this.progressFailures = 0;
39
- this.cardWarmupScheduled = false;
40
- this.cardWarmupTriggered = false;
41
- this.progressStartedAt = 0;
42
- this.progressWindowStartedAt = 0;
35
+ this.progressStartedAt = Date.now();
43
36
  this.toolCallCount = 0;
44
- this.lastDeliveredAt = 0;
45
37
  this.timer = null;
46
- this.cardWarmupTimer = null;
47
38
  this.flushWaiters = [];
48
- this.sentProgressChars = 0;
49
- this.replayRequired = false;
50
39
  this.finalReplacementText = "";
51
40
  /** Deliveries run one after another in the order the events arrived. */
52
41
  this.chain = Promise.resolve();
53
42
  this.lastAnswer = "";
54
43
  this.event = { channelId: turn.channelId };
44
+ this.progress = new ProgressWindow(this.progressStyle === "rolling" ? "rolling" : "full");
55
45
  this.cardGeneration = bot.getCardGeneration(turn.channelId);
46
+ // Start the waiting card in the same sync loop as progress and completion. Do not await
47
+ // its HTTP request: the caller can start the model while card creation is in flight.
48
+ if (this.progressStyle !== "none")
49
+ this.bumpRevision(true);
56
50
  }
57
51
  get isCurrent() {
58
52
  return this.bot.isCardGenerationCurrent(this.event.channelId, this.cardGeneration);
@@ -96,17 +90,18 @@ class ChannelDeliveryController {
96
90
  async deliver(event) {
97
91
  switch (event.type) {
98
92
  case "tool.start":
99
- await this.appendProgress(formatProgressEntry("tool", describeToolCall(event.tool, event.args)), false, true);
93
+ await this.remember(describeToolCall(event.tool, event.args), "➜", { countTool: true });
100
94
  return;
101
95
  case "tool.update":
102
- await this.appendProgress(formatProgressEntry("tool", event.text), false);
96
+ await this.remember(event.text, "➜");
103
97
  return;
104
98
  case "tool.end":
105
99
  if (event.failure)
106
- await this.appendProgress(formatProgressEntry("error", event.failure), false);
100
+ await this.remember(event.failure, "✕");
107
101
  return;
108
102
  case "reasoning":
109
- await this.appendProgress(formatProgressEntry("thinking", event.text), false);
103
+ // Both modes record thinking chronologically; full retains the latest thought on a fold.
104
+ await this.remember(event.text, "✦", { tail: true });
110
105
  return;
111
106
  case "commentary":
112
107
  await this.deliverCommentary(event.text, event.level);
@@ -115,9 +110,8 @@ class ChannelDeliveryController {
115
110
  await this.deliverAnswer(event.text);
116
111
  return;
117
112
  case "compaction":
118
- if (event.phase === "start") {
119
- await this.appendProgress(formatProgressEntry("assistant", "正在压缩上下文…"), false);
120
- }
113
+ if (event.phase === "start")
114
+ await this.remember("正在压缩上下文…", "");
121
115
  return;
122
116
  case "steer.applied":
123
117
  return;
@@ -126,14 +120,14 @@ class ChannelDeliveryController {
126
120
  async deliverCommentary(text, level) {
127
121
  switch (level) {
128
122
  case undefined:
129
- await this.appendProgress(formatProgressEntry("assistant", text), false);
123
+ await this.remember(text, "");
130
124
  return;
131
125
  case "error":
132
- await this.appendProgress(formatProgressEntry("error", text), false);
126
+ await this.remember(text, "✕");
133
127
  return;
134
128
  case "warning":
135
129
  if (this.progressStyle !== "none") {
136
- await this.appendProgress(formatProgressEntry("error", text), false);
130
+ await this.remember(text, "✕");
137
131
  }
138
132
  else {
139
133
  await this.notice(`⚠️ ${text}`);
@@ -188,6 +182,7 @@ class ChannelDeliveryController {
188
182
  await this.silence();
189
183
  break;
190
184
  case "cancelled":
185
+ await this.silence();
191
186
  break;
192
187
  case "completed":
193
188
  if (this.lastAnswer && !this.finalResponseDelivered) {
@@ -209,32 +204,6 @@ class ChannelDeliveryController {
209
204
  await this.close();
210
205
  }
211
206
  }
212
- primeCard(delayMs) {
213
- if (this.closed ||
214
- this.ending ||
215
- this.progressStyle === "none" ||
216
- this.cardWarmupScheduled ||
217
- this.cardWarmupTriggered) {
218
- return;
219
- }
220
- this.cardWarmupScheduled = true;
221
- this.cardWarmupTimer = setTimeout(() => {
222
- this.cardWarmupScheduled = false;
223
- this.cardWarmupTimer = null;
224
- if (this.closed || this.ending || !this.isCurrent || this.desiredRevision > 0)
225
- return;
226
- this.cardWarmupTriggered = true;
227
- // Use the same serialized loop as progress and completion; no detached create request.
228
- this.bumpRevision(true);
229
- }, Math.max(0, delayMs));
230
- }
231
- clearCardWarmup() {
232
- this.cardWarmupScheduled = false;
233
- if (this.cardWarmupTimer) {
234
- clearTimeout(this.cardWarmupTimer);
235
- this.cardWarmupTimer = null;
236
- }
237
- }
238
207
  archiveBotResponse(text) {
239
208
  void this.archive(this.event.channelId, text).catch((err) => {
240
209
  log.logWarn("channel.archive.write_failed", "Bot response archive failed", {
@@ -243,38 +212,21 @@ class ChannelDeliveryController {
243
212
  });
244
213
  });
245
214
  }
246
- async appendProgress(text, shouldLog, isToolCall = false) {
215
+ /**
216
+ * Record the latest desired view; bursts update it while one paced request publishes it.
217
+ */
218
+ async remember(text, marker, options) {
247
219
  if (this.closed || this.ending || !this.isCurrent || !text.trim())
248
220
  return;
249
221
  // Final-card-only mode shows no progress; ignore any stray progress writes
250
222
  // so we never create or flicker a card before the final replacement.
251
223
  if (this.progressStyle === "none")
252
224
  return;
253
- this.clearCardWarmup();
254
- if (this.progressStartedAt === 0) {
255
- this.progressStartedAt = Date.now();
256
- }
257
- if (isToolCall) {
225
+ if (options?.countTool)
258
226
  this.toolCallCount++;
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);
277
- }
227
+ const changed = this.progress.record({ marker, text, tail: options?.tail === true });
228
+ if (!changed && !options?.countTool)
229
+ return;
278
230
  this.mode = "progress";
279
231
  this.bumpRevision(false);
280
232
  }
@@ -282,11 +234,10 @@ class ChannelDeliveryController {
282
234
  if (this.closed || this.ending || !this.isCurrent || !text.trim())
283
235
  return this.finalResponseDelivered;
284
236
  this.ending = true;
285
- this.clearCardWarmup();
286
237
  if (this.timer)
287
238
  clearTimeout(this.timer);
288
239
  this.timer = null;
289
- if (this.cardWarmupTriggered && !this.getProgressText().trim()) {
240
+ if (this.progressStyle !== "none" && !this.hasRecordedProgress()) {
290
241
  // The card only ever said "正在处理…": the answer goes into it rather than into a second
291
242
  // message under a card that would just read "已答复。".
292
243
  this.finalReplacementText = text;
@@ -315,7 +266,6 @@ class ChannelDeliveryController {
315
266
  if (this.closed || this.finalResponseDelivered || !this.isCurrent || !text.trim())
316
267
  return;
317
268
  this.ending = true;
318
- this.clearCardWarmup();
319
269
  this.finalReplacementText = text;
320
270
  this.mode = "finalize-with-fallback";
321
271
  this.bumpRevision(true);
@@ -328,7 +278,6 @@ class ChannelDeliveryController {
328
278
  if (this.closed || this.finalResponseDelivered)
329
279
  return;
330
280
  this.ending = true;
331
- this.clearCardWarmup();
332
281
  this.mode = "silent";
333
282
  this.bumpRevision(true);
334
283
  }
@@ -339,22 +288,20 @@ class ChannelDeliveryController {
339
288
  schedule(forceImmediate) {
340
289
  if (this.running)
341
290
  return;
342
- if (this.timer) {
343
- clearTimeout(this.timer);
291
+ if (forceImmediate || this.mode !== "progress") {
292
+ if (this.timer)
293
+ clearTimeout(this.timer);
344
294
  this.timer = null;
345
- }
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) {
351
295
  void this.runSyncLoop();
352
296
  return;
353
297
  }
298
+ if (this.timer)
299
+ return;
300
+ // One macrotask coalesces the first burst; subsequent frames respect the minimum gap.
354
301
  this.timer = setTimeout(() => {
355
302
  this.timer = null;
356
303
  void this.runSyncLoop();
357
- }, delay);
304
+ }, Math.max(0, this.nextProgressAt - Date.now()));
358
305
  }
359
306
  async runSyncLoop() {
360
307
  if (this.running)
@@ -363,54 +310,18 @@ class ChannelDeliveryController {
363
310
  try {
364
311
  while (this.appliedRevision < this.desiredRevision) {
365
312
  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
313
  const revision = this.desiredRevision;
382
- const content = progressText.trim();
383
314
  const replacementText = this.finalReplacementText;
384
315
  let touchedRemote = false;
385
316
  try {
386
317
  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
- }
318
+ if (this.isCurrent && this.progressFailures < MAX_PROGRESS_FAILURES) {
319
+ touchedRemote = await this.publishProgress();
406
320
  }
407
321
  }
408
322
  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);
323
+ if (this.progressStyle !== "none") {
324
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, this.buildSummaryText(), this.cardGeneration);
414
325
  }
415
326
  }
416
327
  else if (mode === "finalize-with-fallback") {
@@ -420,8 +331,8 @@ class ChannelDeliveryController {
420
331
  }
421
332
  }
422
333
  else if (mode === "silent") {
423
- if (content) {
424
- touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, [body, "已处理,无需答复。"].filter(Boolean).join("\n\n"), this.cardGeneration);
334
+ if (this.progressStyle !== "none") {
335
+ touchedRemote = await this.bot.finalizeExistingCard(this.event.channelId, renderCardStatus(SILENT_STATUS), this.cardGeneration);
425
336
  }
426
337
  }
427
338
  }
@@ -430,18 +341,14 @@ class ChannelDeliveryController {
430
341
  channelId: this.event.channelId,
431
342
  reason: errorMessage(err),
432
343
  });
433
- if (mode === "progress") {
344
+ if (mode === "progress")
434
345
  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
346
  }
444
347
  this.appliedRevision = revision;
348
+ // Events received during HTTP must wait for the next display interval. An ending
349
+ // still runs immediately after the in-flight write, without draining old progress.
350
+ if (mode === "progress" && this.mode === "progress")
351
+ break;
445
352
  }
446
353
  }
447
354
  finally {
@@ -493,7 +400,6 @@ class ChannelDeliveryController {
493
400
  return;
494
401
  }
495
402
  this.closed = true;
496
- this.clearCardWarmup();
497
403
  if (this.mode === "progress") {
498
404
  this.mode = "silent";
499
405
  this.bumpRevision(true);
@@ -501,15 +407,51 @@ class ChannelDeliveryController {
501
407
  await this.flush();
502
408
  this.bot.discardCard(this.event.channelId, this.cardGeneration);
503
409
  }
504
- getProgressText() {
505
- if (!this.progressTextDirty) {
506
- return this.cachedProgressText;
410
+ /** True once this turn has something to show besides the waiting line. */
411
+ hasRecordedProgress() {
412
+ return this.progress.hasContent || this.document !== "";
413
+ }
414
+ /** Publish one bounded write per display interval, anchored to the last successful write. */
415
+ async publishProgress() {
416
+ if (this.ending || !this.isCurrent)
417
+ return false;
418
+ const hasProgress = this.progress.hasContent;
419
+ const planned = hasProgress
420
+ ? this.progress.plan(this.buildLiveHeader(), { epoch: this.documentEpoch, content: this.document }, this.bot.supportsStreamingAppend())
421
+ : { epoch: -1, content: WAITING_TEXT, append: false, document: "", complete: true };
422
+ if (!planned)
423
+ return false;
424
+ try {
425
+ const write = planned.append ? this.bot.appendToCard.bind(this.bot) : this.bot.replaceCard.bind(this.bot);
426
+ const ok = await write(this.event.channelId, planned.content, false, false, this.cardGeneration);
427
+ if (ok) {
428
+ if (hasProgress) {
429
+ // Apply this immutable request's baseline, even if newer events folded the desired
430
+ // view during HTTP. Its epoch forces the next write to replace that old cycle.
431
+ this.document = planned.document;
432
+ this.documentEpoch = planned.epoch;
433
+ }
434
+ this.progressFailures = 0;
435
+ if (!planned.complete && !this.ending)
436
+ this.bumpRevision(false);
437
+ }
438
+ else {
439
+ this.progressFailures++;
440
+ if (planned.append) {
441
+ // The server may have applied an append whose response was lost. Replacing a short
442
+ // new cycle restores certainty without duplicating that delta or replaying history.
443
+ this.progress.rebase();
444
+ if (this.progressFailures < MAX_PROGRESS_FAILURES && !this.ending)
445
+ this.bumpRevision(false);
446
+ }
447
+ }
448
+ return ok;
449
+ }
450
+ finally {
451
+ this.nextProgressAt = Date.now() + PROGRESS_INTERVAL_MS;
507
452
  }
508
- this.cachedProgressText = this.progressSegments.join("");
509
- this.progressTextDirty = false;
510
- return this.cachedProgressText;
511
453
  }
512
- /** Clock-style elapsed time (`0:42`, `1:02`, `1:05:09`) for the narrow rolling header. */
454
+ /** Clock-style elapsed time (`0:42`, `1:02`, `1:05:09`) for the card's first line. */
513
455
  formatClock(ms) {
514
456
  const seconds = Math.max(0, Math.round(ms / 1000));
515
457
  const minutes = Math.floor(seconds / 60);
@@ -519,44 +461,19 @@ class ChannelDeliveryController {
519
461
  return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${ss}`;
520
462
  }
521
463
  elapsedMs() {
522
- return this.progressStartedAt > 0 ? Date.now() - this.progressStartedAt : 0;
464
+ return Date.now() - this.progressStartedAt;
523
465
  }
524
466
  /**
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).
467
+ * Cycle header, refreshed on replacement so it remains a stable prefix for appended progress.
468
+ * A long turn can retain only the latest thought and a few activity lines after a fold, so
469
+ * without this a long turn looks identical to one that just started. Counted as tool calls,
470
+ * never "steps" — a step is a task's unit (spec 053, D4).
529
471
  */
530
- buildRollingHeader() {
472
+ buildLiveHeader() {
531
473
  return `⏱ ${this.formatClock(this.elapsedMs())} · 工具 ${this.toolCallCount}`;
532
474
  }
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
475
  buildSummaryText() {
559
- return `完成 · 工具调用 ${this.toolCallCount} 次 · ${formatElapsedZh(this.elapsedMs())}`;
476
+ return renderCardStatus(`完成 · 工具调用 ${this.toolCallCount} 次 · ${formatElapsedZh(this.elapsedMs())}`);
560
477
  }
561
478
  }
562
479
  /**
@@ -565,9 +482,5 @@ class ChannelDeliveryController {
565
482
  */
566
483
  export function createDingTalkContext(turn, port, archive, quiet) {
567
484
  const controller = new ChannelDeliveryController(turn, port, archive, quiet);
568
- const context = controller.buildContext();
569
- // Same warm-up as before: a card that says "正在处理…" appears if the first output is slow.
570
- if (!quiet)
571
- controller.primeCard(CARD_WARMUP_MS);
572
- return context;
485
+ return controller.buildContext();
573
486
  }
@@ -1,8 +1,43 @@
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
+ * Locally owned progress cycles. Full mode grows to the document budget; rolling keeps recent
3
+ * activities. Epochs distinguish a replacement from growth, even when retained text is identical.
4
+ * Writes contain only acknowledged-prefix deltas, bounded to complete markdown list items.
5
5
  */
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;
6
+ export declare const CARD_REQUEST_MAX_BYTES = 1000;
7
+ export declare const CARD_DOCUMENT_MAX_BYTES = 2900;
8
+ /** A line already classified by the delivery controller. `tail` keeps the end of the text. */
9
+ export interface ProgressActivity {
10
+ marker: "" | "➜" | "✕" | "✦";
11
+ text: string;
12
+ tail?: boolean;
13
+ }
14
+ /** One bounded, complete list item; long model text cannot cause a sudden height jump. */
15
+ export declare function renderProgressLine(activity: ProgressActivity, maxBytes?: number): string;
16
+ export interface ProgressFrame {
17
+ epoch: number;
18
+ content: string;
19
+ }
20
+ export interface ProgressWrite extends ProgressFrame {
21
+ append: boolean;
22
+ /** The document acknowledged if this write succeeds, including any prior prefix. */
23
+ document: string;
24
+ complete: boolean;
25
+ }
26
+ /** Desired view independent of an in-flight write; old cycles never remain in a replay queue. */
27
+ export declare class ProgressWindow {
28
+ private readonly style;
29
+ private thinking;
30
+ private activities;
31
+ private epoch;
32
+ private header;
33
+ constructor(style: "full" | "rolling");
34
+ get hasContent(): boolean;
35
+ record(activity: ProgressActivity): boolean;
36
+ plan(header: string, acknowledged: ProgressFrame, append: boolean): ProgressWrite | undefined;
37
+ /** An ambiguous append is recovered with a short replacement, never by replaying its delta. */
38
+ rebase(): void;
39
+ private restart;
40
+ private body;
41
+ }
42
+ /** A one-line card ending. Falls back to a fixed line if the text could not stay plain markdown. */
43
+ export declare function renderCardStatus(text: string): string;