@oyasmi/pipiclaw 0.8.10-beta.2 → 0.8.10-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 (43) hide show
  1. package/dist/agent/channel-runner.d.ts +12 -0
  2. package/dist/agent/channel-runner.js +46 -13
  3. package/dist/agent/commands.js +30 -28
  4. package/dist/agent/effect-ledger.d.ts +13 -4
  5. package/dist/agent/effect-ledger.js +18 -5
  6. package/dist/agent/job-manager.d.ts +9 -0
  7. package/dist/agent/job-manager.js +45 -10
  8. package/dist/agent/maintenance-context.js +3 -2
  9. package/dist/agent/progress-formatter.d.ts +10 -1
  10. package/dist/agent/progress-formatter.js +14 -2
  11. package/dist/executor.d.ts +2 -0
  12. package/dist/executor.js +1 -0
  13. package/dist/memory/maintenance-gates.d.ts +24 -10
  14. package/dist/memory/maintenance-gates.js +11 -9
  15. package/dist/memory/maintenance-jobs.d.ts +3 -2
  16. package/dist/memory/maintenance-jobs.js +33 -21
  17. package/dist/memory/scheduler.d.ts +7 -2
  18. package/dist/playbooks/task-closeout.md +2 -0
  19. package/dist/playbooks/task-delegation.md +12 -8
  20. package/dist/playbooks/task-driving.md +2 -2
  21. package/dist/playbooks/task-planning.md +1 -1
  22. package/dist/runtime/bootstrap.js +7 -4
  23. package/dist/runtime/delivery.js +31 -6
  24. package/dist/runtime/dingtalk.d.ts +9 -1
  25. package/dist/runtime/dingtalk.js +7 -4
  26. package/dist/runtime/task-commands.js +130 -53
  27. package/dist/runtime/task-driver.js +38 -9
  28. package/dist/shared/task-ledger.js +19 -3
  29. package/dist/subagents/tool.d.ts +1 -0
  30. package/dist/subagents/tool.js +33 -3
  31. package/dist/tasks/control.d.ts +1 -0
  32. package/dist/tasks/control.js +2 -2
  33. package/dist/tasks/verification.d.ts +8 -0
  34. package/dist/tasks/verification.js +4 -1
  35. package/dist/tools/bash.js +12 -12
  36. package/dist/tools/task-manage/lifecycle.js +6 -3
  37. package/dist/tools/task-manage/verification.d.ts +2 -1
  38. package/dist/tools/task-manage/verification.js +2 -1
  39. package/dist/tui/turn-controller.js +3 -3
  40. package/dist/usage/ledger.d.ts +2 -0
  41. package/dist/usage/ledger.js +7 -2
  42. package/dist/usage/render.js +17 -8
  43. package/package.json +1 -1
@@ -51,10 +51,10 @@ export function shouldRunSessionRefresh(input) {
51
51
  if (!sessionRefreshThresholdMet(input.state, input.sessionMemory)) {
52
52
  return deny("session-refresh", "threshold-not-met");
53
53
  }
54
- if (!input.hasNewSessionEntry) {
54
+ if (!input.hasNewSessionEntry()) {
55
55
  return deny("session-refresh", "no-new-session-entry");
56
56
  }
57
- if (!input.hasMeaningfulMaterial) {
57
+ if (!input.hasMeaningfulMaterial()) {
58
58
  return deny("session-refresh", "no-meaningful-material");
59
59
  }
60
60
  return allow("session-refresh");
@@ -75,18 +75,19 @@ export function shouldRunMemoryCheckpoint(input) {
75
75
  if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
76
76
  return deny("memory-checkpoint", "backoff-active");
77
77
  }
78
- if (!input.hasNewEntry) {
78
+ const material = input.material();
79
+ if (!material.hasNewEntry) {
79
80
  return deny("memory-checkpoint", "no-new-entry");
80
81
  }
81
- if (!input.hasMeaningfulExchange) {
82
+ if (!material.hasMeaningfulExchange) {
82
83
  return deny("memory-checkpoint", "no-meaningful-exchange");
83
84
  }
84
- if (input.batchSize < (input.minBatchSize ?? 2)) {
85
+ if (material.batchSize < (input.minBatchSize ?? 2)) {
85
86
  return deny("memory-checkpoint", "batch-threshold-not-met");
86
87
  }
87
88
  return allow("memory-checkpoint");
88
89
  }
89
- export function shouldRunStructuralMaintenance(input) {
90
+ export async function shouldRunStructuralMaintenance(input) {
90
91
  const jobKind = "structural-maintenance";
91
92
  const denyStructural = (skipReason) => ({
92
93
  allowed: false,
@@ -104,11 +105,12 @@ export function shouldRunStructuralMaintenance(input) {
104
105
  if (isBeforeOptional(input.now, input.state.failureBackoffUntil)) {
105
106
  return denyStructural("backoff-active");
106
107
  }
107
- if (!input.hasMemoryContent && !input.hasHistoryContent) {
108
+ const material = await input.material();
109
+ if (!material.hasMemoryContent && !material.hasHistoryContent) {
108
110
  return denyStructural("empty-template-files");
109
111
  }
110
- const runMemoryCleanup = input.memoryCleanupNeeded;
111
- const runHistoryFolding = input.historyFoldingNeeded;
112
+ const runMemoryCleanup = material.memoryCleanupNeeded;
113
+ const runHistoryFolding = material.historyFoldingNeeded;
112
114
  if (!runMemoryCleanup && !runHistoryFolding) {
113
115
  return denyStructural("nothing-to-maintain");
114
116
  }
@@ -17,8 +17,9 @@ interface BaseMaintenanceJobInput {
17
17
  settings: MaintenanceJobSettings;
18
18
  model: Model<Api>;
19
19
  resolveApiKey: (model: Model<Api>) => Promise<string>;
20
- messages: AgentMessage[];
21
- sessionEntries: SessionEntry[];
20
+ /** Transcript accessors: only called once a gate has decided the job may actually run. */
21
+ messages: () => AgentMessage[];
22
+ sessionEntries: () => SessionEntry[];
22
23
  queue?: ChannelMemoryQueue;
23
24
  }
24
25
  export interface SessionRefreshJobInput extends BaseMaintenanceJobInput {
@@ -8,6 +8,14 @@ import { appendMemoryReviewLog } from "./review-log.js";
8
8
  import { updateChannelSessionMemory } from "./session.js";
9
9
  import { buildIncrementalMemorySourceWindow } from "./source-window.js";
10
10
  import { sanitizeMessagesForMemory } from "./transcript.js";
11
+ /** Evaluate `load` at most once, so a gate and the job body can share one expensive read. */
12
+ function once(load) {
13
+ let cached;
14
+ return () => {
15
+ cached ??= { value: load() };
16
+ return cached.value;
17
+ };
18
+ }
11
19
  function latestEntryId(entries) {
12
20
  return entries.at(-1)?.id;
13
21
  }
@@ -52,8 +60,8 @@ function makeRunOptions(input, usageCorrelationId) {
52
60
  channelDir: input.channelDir,
53
61
  model: input.model,
54
62
  resolveApiKey: input.resolveApiKey,
55
- messages: input.messages,
56
- sessionEntries: input.sessionEntries,
63
+ messages: input.messages(),
64
+ sessionEntries: input.sessionEntries(),
57
65
  usageCorrelationId,
58
66
  minAutoWriteConfidence: input.settings.memoryMaintenance.minMemoryAutoWriteConfidence,
59
67
  };
@@ -90,26 +98,28 @@ export async function runSessionRefreshJob(input) {
90
98
  return runQueued(input, async () => {
91
99
  const now = input.now ?? new Date();
92
100
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
93
- const latestId = latestEntryId(input.sessionEntries);
101
+ const messages = once(input.messages);
102
+ const latestEntry = once(() => latestEntryId(input.sessionEntries()));
94
103
  const decision = shouldRunSessionRefresh({
95
104
  now,
96
105
  state,
97
106
  sessionMemory: input.settings.sessionMemory,
98
107
  maintenance: input.settings.memoryMaintenance,
99
108
  channelActive: input.channelActive,
100
- hasNewSessionEntry: latestId !== undefined && latestId !== state.lastSessionRefreshedEntryId,
101
- hasMeaningfulMaterial: hasMeaningfulMessages(input.messages),
109
+ hasNewSessionEntry: () => latestEntry() !== undefined && latestEntry() !== state.lastSessionRefreshedEntryId,
110
+ hasMeaningfulMaterial: () => hasMeaningfulMessages(messages()),
102
111
  });
103
112
  if (!decision.allowed) {
104
113
  await appendJobReviewLog(input.channelDir, input.channelId, "session-refresh-job", { skipped: [{ target: "SESSION.md", reason: decision.skipReason }] }, now);
105
114
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
106
115
  }
116
+ const latestId = latestEntry();
107
117
  try {
108
118
  const correlationId = `session-refresh:${latestId ?? now.toISOString()}`;
109
119
  await updateChannelSessionMemory({
110
120
  channelId: input.channelId,
111
121
  channelDir: input.channelDir,
112
- messages: input.messages,
122
+ messages: messages(),
113
123
  model: input.model,
114
124
  resolveApiKey: input.resolveApiKey,
115
125
  timeoutMs: input.settings.sessionMemory.timeoutMs,
@@ -142,26 +152,31 @@ export async function runMemoryCheckpointJob(input) {
142
152
  return runQueued(input, async () => {
143
153
  const now = input.now ?? new Date();
144
154
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
145
- const sourceWindow = buildIncrementalMemorySourceWindow({
146
- entries: input.sessionEntries,
155
+ const loadSourceWindow = once(() => buildIncrementalMemorySourceWindow({
156
+ entries: input.sessionEntries(),
147
157
  lastEntryId: state.lastCheckpointEntryId,
148
158
  sourceKind: "idle",
149
- fallbackMessages: input.messages,
150
- });
151
- const newEntries = sourceWindow.entries;
159
+ fallbackMessages: input.messages(),
160
+ }));
152
161
  const decision = shouldRunMemoryCheckpoint({
153
162
  now,
154
163
  state,
155
164
  maintenance: input.settings.memoryMaintenance,
156
165
  channelActive: input.channelActive,
157
- hasNewEntry: newEntries.length > 0,
158
- hasMeaningfulExchange: hasMeaningfulMessages(sourceWindow.messages),
159
- batchSize: newEntries.length,
166
+ material: () => {
167
+ const window = loadSourceWindow();
168
+ return {
169
+ hasNewEntry: window.entries.length > 0,
170
+ hasMeaningfulExchange: hasMeaningfulMessages(window.messages),
171
+ batchSize: window.entries.length,
172
+ };
173
+ },
160
174
  });
161
175
  if (!decision.allowed) {
162
176
  await appendJobReviewLog(input.channelDir, input.channelId, "memory-checkpoint-job", { skipped: [{ target: "consolidation", reason: decision.skipReason }] }, now);
163
177
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
164
178
  }
179
+ const sourceWindow = loadSourceWindow();
165
180
  try {
166
181
  const result = await runInlineConsolidation({
167
182
  ...makeRunOptions(input),
@@ -205,22 +220,19 @@ export async function runStructuralMaintenanceJob(input) {
205
220
  return runQueued(input, async () => {
206
221
  const now = input.now ?? new Date();
207
222
  const state = await readMemoryMaintenanceState(input.appHomeDir, input.channelId);
208
- const [currentMemory, currentHistory] = await Promise.all([
209
- readChannelMemory(input.channelDir),
210
- readChannelHistory(input.channelDir),
211
- ]);
212
- const stats = getStructuralMaintenanceStats(currentMemory, currentHistory);
213
- const decision = shouldRunStructuralMaintenance({
223
+ const loadFiles = once(() => Promise.all([readChannelMemory(input.channelDir), readChannelHistory(input.channelDir)]));
224
+ const decision = await shouldRunStructuralMaintenance({
214
225
  now,
215
226
  state,
216
227
  maintenance: input.settings.memoryMaintenance,
217
228
  channelActive: input.channelActive,
218
- ...stats,
229
+ material: async () => getStructuralMaintenanceStats(...(await loadFiles())),
219
230
  });
220
231
  if (!decision.allowed) {
221
232
  await appendJobReviewLog(input.channelDir, input.channelId, "structural-maintenance-job", { skipped: [{ target: "structural-maintenance", reason: decision.skipReason }] }, now);
222
233
  return skipped(decision.jobKind, decision.skipReason ?? "skipped");
223
234
  }
235
+ const [currentMemory, currentHistory] = await loadFiles();
224
236
  try {
225
237
  const correlationId = `structural-maintenance:${now.toISOString()}`;
226
238
  const options = makeRunOptions(input, correlationId);
@@ -5,8 +5,13 @@ import type { PipiclawMemoryMaintenanceSettings, PipiclawSessionMemorySettings }
5
5
  export interface MemoryMaintenanceRuntimeContext {
6
6
  channelId: string;
7
7
  channelDir: string;
8
- messages: AgentMessage[];
9
- sessionEntries: SessionEntry[];
8
+ /**
9
+ * Transcript accessors, not arrays: the scheduler visits a channel every tick but almost
10
+ * every tick is denied by a cheap schedule gate. Copying (and then scanning) the whole
11
+ * transcript before that verdict was the entire steady-state cost of an idle daemon.
12
+ */
13
+ messages: () => AgentMessage[];
14
+ sessionEntries: () => SessionEntry[];
10
15
  model: Model<Api>;
11
16
  resolveApiKey: (model: Model<Api>) => Promise<string>;
12
17
  settings: {
@@ -7,6 +7,8 @@ priority: 42
7
7
 
8
8
  # 验收、外部审批与闭环
9
9
 
10
+ 本文件是验收(verify)与外部审批(approval)门禁规则的唯一真相源,`task-driving.md` 与 `task-planning.md` 只保留指针。
11
+
10
12
  ## 独立验收
11
13
 
12
14
  1. 只在证据成立后勾选 DoD / Verification checkbox。
@@ -29,18 +29,22 @@ priority: 45
29
29
 
30
30
  ## 文件系统隔离
31
31
 
32
- 没有。子代理与主代理共享同一个 checkout,只隔离对话上下文。需要在独立检出上作业时,在宿主侧自行 `git worktree add`,把它当作普通工作目录传给子代理,并自己负责 review、merge 与清理。
32
+ 没有。子代理默认与主代理共享同一个 checkout,只隔离对话上下文。需要在独立检出上作业时,在宿主侧自行 `git worktree add`,把该路径作为 `workingDirectory` 传给子代理(它是子代理的 shell cwd 与相对路径根,必须已存在),并自己负责 review、merge 与清理。`purpose: verify` 的 attestation 会绑定该目录的 git 产物状态,后续 `task_manage verify` / `done` 也在同一目录复算。
33
33
 
34
34
  ## 外部 agent 工具
35
35
 
36
- Pipiclaw 不内置或假设第三方 agent 工具的命令、状态 JSON、检测脚本。如何启动、inspect、capture、steer 由用户安装的可执行文件和 workspace skill 决定。
36
+ Pipiclaw 不内置或假设第三方 agent 工具的命令、状态 JSON、检测脚本。如何启动、探活、取回、steer 由用户安装的可执行文件和 workspace skill 决定——先读那份 skill,再决定用哪条命令,不要临时复制来源不明的脚本。
37
37
 
38
- runtime 只规定长程委派的恢复纪律:
38
+ 启动、纠偏、取回、停止都是秒级的同步命令,直接 `bash` 调用即可。runtime 只补它们补不了的那一块:**你不在场的那段等待**。按用户工具的能力从优到劣选一条:
39
39
 
40
- 1. 在 task 正文记录工具、实例标识、工作目录/分支、预期产物和验收方法。
41
- 2. `progress` 置 blocked,并设置合理 wake。
42
- 3. wake 后按用户 skill 检查状态;未完成则更新证据和 wake,完成则取回、review、验证并推进。
43
- 4. 如确需条件触发,按 `event-scheduling.md` 使用用户提供的稳定检测命令;不要临时复制未知脚本,也不要把第三方协议写进 runtime playbook。
44
- 5. task 闭环前清理临时事件和外部实例。
40
+ 1. **阻塞等待包成后台作业(首选)**:工具若提供"等到外部实例结束/空闲才返回"的命令,用 `bash async` + `taskId` 跑它,`progress` 置 `waiting` 且**不设 wake**,然后结束回合——作业结束时 runtime 自动叫醒你并带上输出尾部,见 `background-jobs.md`。作业超时只终止等待本身,不会杀掉外部实例:醒来确认对方还在跑,再起一个等待作业即可。给等待作业一个明显长于预计耗时的 `timeout`,别让它每五分钟叫你一次。
41
+ 2. **稳定的完成态检测命令**:只有状态查询、没有阻塞等待时,按 `event-scheduling.md` 用 periodic + preAction 门控——对方忙就静默跳过,零 token。
42
+ 3. **wake 轮询(兜底)**:两者都没有时才用,`progress` 置 `waiting` + 合理 `wake`,醒来查状态、更新证据、必要时把 wake 推后。
43
+
44
+ 无论走哪条,三条纪律不变:
45
+
46
+ 1. 委派时把工具、实例标识、工作目录/分支、预期产物和验收方法写进 task 正文,等谁、等什么写进 `blockedReason`。重启后这些是唯一能恢复现场的东西。
47
+ 2. 取回后自己 review 和验证。对方报告完成、进程退出码为 0、实例回到空闲,都不是验收证据。
48
+ 3. task 闭环前清理临时事件和外部实例。
45
49
 
46
50
  任何委派都不能转移最终交付责任。父代理必须确认成果已进入目标 checkout,而不是只停留在外部实例或口头报告中。
@@ -22,7 +22,7 @@ priority: 41
22
22
 
23
23
  以下生命周期动作本身就是原子 checkpoint,不要再追加 progress:`candidate`、`done`、`skip`、`cancel`。
24
24
 
25
- `verify` 只更新 control、不改正文。PASS 后若还要等外部审批(approval),用 `task_manage set wake=<合理时间>` 停留在 `verifying` 车道——**只改 wake、不换状态**,离开 verifying 会作废 PASS——并请用户 `/tasks approve <id>`。门禁的绑定规则见 `task-closeout.md`。除此之外不要用 `set` 代替正常进度日志。
25
+ `verify` 只更新 control、不改正文。验收与外部审批的全部门禁规则(PASS/approval 的绑定与失效、两个门并存时的顺序)以 `task-closeout.md` 为准,需要时读它,不要凭记忆推断。除此之外不要用 `set` 代替正常进度日志。
26
26
 
27
27
  ## 等待与继续
28
28
 
@@ -32,7 +32,7 @@ priority: 41
32
32
 
33
33
  内建 driver 分钟级扫描 DingTalk `dm_*/group_*` channel,`wake` 到期后接续;无需 heartbeat、`.checkin` 或额外传感器。TUI 关闭后没有 daemon,不能自动唤醒。
34
34
 
35
- 有语义 checkpoint 时按较短 continuation delay 接续;只有用量变化、没有任务变化时按 stalled retry 退避。**不要为了拿到短退避而伪造 progress。**
35
+ 接续节奏由这一轮**实际做了什么**决定,不需要你去操纵:产生了可见 effect(write/edit/subagent/后台 job/给用户的回复,或一条跑通并有输出的同步 bash)就立即接续;只改了台账按 continuation delay;什么都没变按 stalled retry 退避。**不要为了拿到短退避而伪造 progress 或跑无意义命令**——真做事自然就快。
36
36
 
37
37
  ## 汇报与静默
38
38
 
@@ -32,7 +32,7 @@ priority: 40
32
32
  - `sideEffects`:`workspace` 或 `external`。发送、发布、部署、修改外部系统必须选 `external`,它会要求用户 `/tasks approve` 后才能 done。
33
33
  - 任务之间没有父子或依赖字段。需要表达先后次序时写进 `goal`/`manual`,或用 `wake` 把后续任务排到合适的时间;每个任务只按自己的 DoD 收尾。
34
34
 
35
- 外部副作用与独立验收并存时,DoD/Verification 要验收"**待执行动作及其输入已准备正确**"(内容、目标、参数、预演、回滚方案),不要把尚未获批的外部动作本身写成 candidate 前必须勾选的项——否则会形成"先执行才能勾选"与"先验收批准才能执行"的死循环。实际执行结果由审批记录和 done evidence 收口。
35
+ 外部副作用与独立验收并存时,DoD/Verification 只验收"**待执行动作及其输入已准备正确**",不要把尚未获批的外部动作本身写成必须勾选的项;理由与完整门禁顺序见 `task-closeout.md`。
36
36
 
37
37
  DoD 描述最终可验收结果,不把未执行动作写成 `[x] skipped`。存在条件分支时,用一个结果项表达“完成 A,或在条件不成立时交付 B 并附理由”;执行哪条路径由 evidence 证明。
38
38
 
@@ -442,6 +442,7 @@ export function createRuntimeContext(options) {
442
442
  },
443
443
  async handleStop(channelId, _bot) {
444
444
  const runner = channelRunners.get(channelId);
445
+ let pausedTaskId;
445
446
  if (runner?.isBusy()) {
446
447
  runner.requestStop();
447
448
  const taskId = /^\[TASK_(?:DRIVER|CYCLE):([A-Za-z0-9._-]+)\]/.exec(runner.getTurnStatus().taskText ?? "")?.[1];
@@ -451,6 +452,7 @@ export function createRuntimeContext(options) {
451
452
  channelDir: getChannelDir(options.paths.workspaceDir, channelId),
452
453
  approver: "user via /stop",
453
454
  }, taskId);
455
+ pausedTaskId = taskId;
454
456
  log.logInfo(`[${channelId}] ${pauseResult}`);
455
457
  }
456
458
  _bot.discardCard(channelId);
@@ -469,6 +471,7 @@ export function createRuntimeContext(options) {
469
471
  });
470
472
  log.logInfo(`[${channelId}] Stop requested`);
471
473
  }
474
+ return { pausedTaskId };
472
475
  },
473
476
  async handleEventsCommand(event, bot, args) {
474
477
  const response = await runEventsCommand({
@@ -527,7 +530,7 @@ export function createRuntimeContext(options) {
527
530
  const trimmedQueueText = queueText.trim();
528
531
  if (!trimmedQueueText) {
529
532
  const commandName = mode === "followUp" ? "followup" : "steer";
530
- await bot.sendPlain(event.channelId, `Could not queue this message: /${commandName} requires a message.`);
533
+ await bot.sendPlain(event.channelId, `无法排队:/${commandName} 需要带上消息内容。`);
531
534
  return { kind: "handled" };
532
535
  }
533
536
  if (mode === "followUp") {
@@ -550,8 +553,8 @@ export function createRuntimeContext(options) {
550
553
  skipContextSync: true,
551
554
  }, `${mode} message`);
552
555
  const confirmation = event.text.trim().startsWith("/")
553
- ? "Queued as steer. I’ll apply it after the current tool step finishes."
554
- : "Queued as steer. I’ll apply this after the current tool step finishes. Use `/followup <message>` to queue it after completion.";
556
+ ? "已作为 steer 排队,当前工具步骤结束后生效。"
557
+ : "已作为 steer 排队,当前工具步骤结束后生效。想等整个回合结束再执行,用 `/followup <消息>`。";
555
558
  await bot.sendPlain(event.channelId, confirmation);
556
559
  log.logEvent("info", "agent.turn.steer_queued", "Steer queued", {
557
560
  ctx: { channelId: event.channelId, userName: event.userName },
@@ -566,7 +569,7 @@ export function createRuntimeContext(options) {
566
569
  return { kind: "requeue", text: trimmedQueueText };
567
570
  }
568
571
  log.logWarning(`[${event.channelId}] Failed to queue ${mode}`, errMsg);
569
- await bot.sendPlain(event.channelId, `Could not queue this message: ${errMsg}`);
572
+ await bot.sendPlain(event.channelId, `无法排队这条消息:${errMsg}`);
570
573
  return { kind: "handled" };
571
574
  }
572
575
  },
@@ -124,6 +124,10 @@ class ChannelDeliveryController {
124
124
  this.progressTextDirty = true;
125
125
  if (this.bot.progressStyle === "rolling") {
126
126
  this.trimToRecentEntries(ROLLING_WINDOW_SIZE);
127
+ // The header carries elapsed time and a step count, so it changes on every update:
128
+ // an append-only delta would leave a stale header on the card.
129
+ this.replayRequired = true;
130
+ this.sentProgressChars = 0;
127
131
  }
128
132
  if (this.progressWindowStartedAt === 0) {
129
133
  this.progressWindowStartedAt = Date.now();
@@ -199,7 +203,10 @@ class ChannelDeliveryController {
199
203
  try {
200
204
  while (this.appliedRevision < this.desiredRevision) {
201
205
  const mode = this.mode;
202
- const progressText = this.getProgressText();
206
+ const body = this.getProgressText();
207
+ const progressText = mode === "progress" && this.bot.progressStyle === "rolling" && body
208
+ ? `${this.buildRollingHeader()}\n\n${body}`
209
+ : body;
203
210
  const throttleBaseAt = this.lastDeliveredAt > 0 ? this.lastDeliveredAt : this.progressWindowStartedAt;
204
211
  if (mode === "progress" && throttleBaseAt > 0) {
205
212
  const remaining = MIN_UPDATE_INTERVAL_MS - (Date.now() - throttleBaseAt);
@@ -238,7 +245,7 @@ class ChannelDeliveryController {
238
245
  }
239
246
  else if (mode === "finalize-existing") {
240
247
  if (content || this.cardWarmupTriggered) {
241
- const finalProgressText = this.bot.progressStyle === "rolling" ? this.buildSummaryText("Done") : progressText;
248
+ const finalProgressText = this.bot.progressStyle === "rolling" ? this.buildSummaryText() : progressText;
242
249
  touchedRemote = await this.bot.replaceCard(this.event.channelId, content || this.bot.progressStyle === "rolling" ? finalProgressText : NO_CONTENT, true);
243
250
  if (!touchedRemote) {
244
251
  this.bot.discardCard(this.event.channelId);
@@ -345,6 +352,26 @@ class ChannelDeliveryController {
345
352
  this.progressTextDirty = false;
346
353
  return this.cachedProgressText;
347
354
  }
355
+ formatElapsed(ms) {
356
+ const seconds = Math.max(0, Math.round(ms / 1000));
357
+ if (seconds < 60)
358
+ return `${seconds}s`;
359
+ const minutes = Math.floor(seconds / 60);
360
+ if (minutes < 60)
361
+ return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
362
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
363
+ }
364
+ elapsedMs() {
365
+ return this.progressStartedAt > 0 ? Date.now() - this.progressStartedAt : 0;
366
+ }
367
+ /**
368
+ * Standing first line for rolling mode. The window only keeps the last few entries, so a long
369
+ * turn otherwise gave no way to tell "still working, 14 steps in" from "stuck": every visible
370
+ * line looked the same as a minute ago. The numbers are already tracked for the closing summary.
371
+ */
372
+ buildRollingHeader() {
373
+ return `⏱ ${this.formatElapsed(this.elapsedMs())} · ${this.toolCallCount} 步`;
374
+ }
348
375
  trimToRecentEntries(maxEntries) {
349
376
  let entryCount = 0;
350
377
  for (const segment of this.progressSegments) {
@@ -370,10 +397,8 @@ class ChannelDeliveryController {
370
397
  this.replayRequired = true;
371
398
  this.sentProgressChars = 0;
372
399
  }
373
- buildSummaryText(status) {
374
- const elapsedSeconds = this.progressStartedAt > 0 ? Math.round((Date.now() - this.progressStartedAt) / 1000) : 0;
375
- const toolLabel = this.toolCallCount === 1 ? "1 tool call" : `${this.toolCallCount} tool calls`;
376
- return `${status} · ${toolLabel} · ${elapsedSeconds}s`;
400
+ buildSummaryText() {
401
+ return `完成 · ${this.toolCallCount} 步 · ${this.formatElapsed(this.elapsedMs())}`;
377
402
  }
378
403
  }
379
404
  export function createDingTalkContext(event, bot, store) {
@@ -38,10 +38,18 @@ export type BusyMessageResult = {
38
38
  kind: "requeue";
39
39
  text: string;
40
40
  };
41
+ /**
42
+ * What `/stop` actually did. Stopping a task-driven turn also pauses that task, which the user
43
+ * has to be told: a paused task is never picked up again until `/tasks resume <id>`, so silence
44
+ * here reads as "the turn was interrupted" while the whole task has in fact gone quiet.
45
+ */
46
+ export interface StopOutcome {
47
+ pausedTaskId?: string;
48
+ }
41
49
  export interface DingTalkHandler {
42
50
  isRunning(channelId: string): boolean;
43
51
  handleEvent(event: DingTalkEvent, bot: DingTalkBot, isEvent?: boolean): Promise<void>;
44
- handleStop(channelId: string, bot: DingTalkBot): Promise<void>;
52
+ handleStop(channelId: string, bot: DingTalkBot): Promise<StopOutcome>;
45
53
  handleEventsCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
46
54
  handleTasksCommand(event: DingTalkEvent, bot: DingTalkBot, args: string): Promise<void>;
47
55
  handleStatusCommand(event: DingTalkEvent, bot: DingTalkBot): Promise<void>;
@@ -1080,10 +1080,13 @@ export class DingTalkBot {
1080
1080
  case "help":
1081
1081
  await this.sendPlain(channelId, renderBuiltInHelp());
1082
1082
  return;
1083
- case "stop":
1084
- await this.handler.handleStop(channelId, this);
1085
- await this.sendPlain(channelId, "Stopping the current task.");
1083
+ case "stop": {
1084
+ const outcome = await this.handler.handleStop(channelId, this);
1085
+ await this.sendPlain(channelId, outcome.pausedTaskId
1086
+ ? `已停止当前回合。任务 \`${outcome.pausedTaskId}\` 已暂停,用 \`/tasks resume ${outcome.pausedTaskId}\` 继续。`
1087
+ : "已停止当前回合。");
1086
1088
  return;
1089
+ }
1087
1090
  case "steer":
1088
1091
  case "followup": {
1089
1092
  const mode = builtInCommand.name === "steer" ? "steer" : "followUp";
@@ -1113,7 +1116,7 @@ export class DingTalkBot {
1113
1116
  // Session commands (/model, /new, …) and unknown slash commands cannot
1114
1117
  // run mid-turn: they would need the idle session layer.
1115
1118
  if (isSlashCommand) {
1116
- await this.sendPlain(channelId, `A task is already running. While streaming you can use: ${formatBusyCommandList()}. Session commands (\`/model\`, \`/new\`, \`/compact\`, \`/session\`) are available when idle.`);
1119
+ await this.sendPlain(channelId, `当前已有回合在运行。运行中可用:${formatBusyCommandList()}。会话命令(\`/model\`、\`/new\`、\`/compact\`、\`/session\`)需要等空闲后再用。`);
1117
1120
  return;
1118
1121
  }
1119
1122
  const result = await this.handler.handleBusyMessage(event, this, this.busyMessageDefault, content);