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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (162) hide show
  1. package/README.en.md +12 -12
  2. package/README.md +12 -12
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +15 -35
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +43 -3
  7. package/dist/agent/prompt/sections.js +2 -2
  8. package/dist/agent/runner-factory.d.ts +2 -2
  9. package/dist/agent/types.d.ts +11 -7
  10. package/dist/channel/channel-context.d.ts +2 -2
  11. package/dist/channel/channel-context.js +2 -2
  12. package/dist/channel/channel-event.d.ts +3 -3
  13. package/dist/channel/project-scope-store.d.ts +20 -0
  14. package/dist/channel/project-scope-store.js +22 -7
  15. package/dist/commands/catalog.js +6 -12
  16. package/dist/events/event-commands.js +2 -2
  17. package/dist/events/events.d.ts +51 -30
  18. package/dist/events/events.js +70 -98
  19. package/dist/memory/journal.d.ts +2 -3
  20. package/dist/memory/journal.js +2 -3
  21. package/dist/memory/maintenance-tuning.d.ts +0 -1
  22. package/dist/memory/maintenance-tuning.js +0 -1
  23. package/dist/memory/scheduler.js +8 -16
  24. package/dist/memory/search.js +2 -3
  25. package/dist/memory/session-search.js +3 -9
  26. package/dist/memory/store.d.ts +1 -1
  27. package/dist/memory/store.js +9 -1
  28. package/dist/memory/task-digest.js +10 -11
  29. package/dist/memory/tombstones.js +2 -4
  30. package/dist/models/provider-login.d.ts +1 -1
  31. package/dist/models/provider-login.js +1 -1
  32. package/dist/playbooks/agent-delegation.md +18 -14
  33. package/dist/playbooks/background-jobs.md +2 -2
  34. package/dist/playbooks/event-scheduling.md +22 -13
  35. package/dist/playbooks/memory-and-learning.md +2 -2
  36. package/dist/playbooks/outbound-media.md +1 -1
  37. package/dist/playbooks/runtime-orientation.md +5 -3
  38. package/dist/playbooks/task-lead.md +82 -0
  39. package/dist/runtime/bootstrap.js +107 -196
  40. package/dist/runtime/delivery.d.ts +1 -2
  41. package/dist/runtime/delivery.js +57 -62
  42. package/dist/runtime/dingtalk.d.ts +15 -8
  43. package/dist/runtime/dingtalk.js +101 -35
  44. package/dist/runtime/durable-dispatch.js +30 -3
  45. package/dist/runtime/report-commands.d.ts +30 -0
  46. package/dist/runtime/report-commands.js +71 -0
  47. package/dist/runtime/subagent-commands.js +1 -1
  48. package/dist/runtime/task-commands.d.ts +0 -8
  49. package/dist/runtime/task-commands.js +48 -85
  50. package/dist/runtime/task-driver.d.ts +13 -9
  51. package/dist/runtime/task-driver.js +34 -39
  52. package/dist/runtime/task-migration.d.ts +18 -29
  53. package/dist/runtime/task-migration.js +195 -183
  54. package/dist/runtime/task-spawn.d.ts +24 -0
  55. package/dist/runtime/task-spawn.js +49 -0
  56. package/dist/runtime/task-wake.d.ts +33 -46
  57. package/dist/runtime/task-wake.js +15 -90
  58. package/dist/security/network.js +44 -9
  59. package/dist/settings.d.ts +1 -8
  60. package/dist/settings.js +1 -8
  61. package/dist/subagents/discovery.js +7 -17
  62. package/dist/subagents/external/claude-code.js +3 -1
  63. package/dist/subagents/external/harness.d.ts +4 -2
  64. package/dist/subagents/external/run.d.ts +3 -1
  65. package/dist/subagents/external/run.js +14 -23
  66. package/dist/subagents/external/settlement.d.ts +4 -16
  67. package/dist/subagents/external/settlement.js +16 -67
  68. package/dist/subagents/runs.d.ts +15 -29
  69. package/dist/subagents/runs.js +71 -160
  70. package/dist/subagents/tool.d.ts +20 -4
  71. package/dist/subagents/tool.js +63 -87
  72. package/dist/subagents/verification-outcome.d.ts +13 -19
  73. package/dist/subagents/verification-outcome.js +8 -22
  74. package/dist/subagents/workspace-summary.d.ts +8 -0
  75. package/dist/subagents/workspace-summary.js +29 -0
  76. package/dist/tasks/board.d.ts +43 -0
  77. package/dist/tasks/board.js +134 -0
  78. package/dist/tasks/brief.d.ts +10 -5
  79. package/dist/tasks/brief.js +78 -26
  80. package/dist/tasks/budget.d.ts +13 -14
  81. package/dist/tasks/budget.js +21 -40
  82. package/dist/tasks/contract-input.d.ts +19 -0
  83. package/dist/tasks/contract-input.js +55 -0
  84. package/dist/tasks/create.d.ts +17 -0
  85. package/dist/tasks/create.js +36 -0
  86. package/dist/tasks/frontmatter.d.ts +20 -27
  87. package/dist/tasks/frontmatter.js +18 -31
  88. package/dist/tasks/ledger.d.ts +61 -117
  89. package/dist/tasks/ledger.js +78 -223
  90. package/dist/tasks/log.d.ts +62 -35
  91. package/dist/tasks/log.js +51 -29
  92. package/dist/tasks/session-path.d.ts +3 -3
  93. package/dist/tasks/session-path.js +4 -5
  94. package/dist/tasks/store.d.ts +11 -29
  95. package/dist/tasks/store.js +39 -83
  96. package/dist/tasks/ticket.d.ts +33 -66
  97. package/dist/tasks/ticket.js +31 -120
  98. package/dist/tasks/work-log.d.ts +20 -0
  99. package/dist/tasks/work-log.js +42 -0
  100. package/dist/tools/bash.d.ts +1 -1
  101. package/dist/tools/bash.js +1 -1
  102. package/dist/tools/event-manage.d.ts +16 -2
  103. package/dist/tools/event-manage.js +30 -12
  104. package/dist/tools/index.d.ts +5 -3
  105. package/dist/tools/index.js +5 -5
  106. package/dist/tools/registry.d.ts +6 -4
  107. package/dist/tools/registry.js +1 -4
  108. package/dist/tools/subagent-manage.js +4 -2
  109. package/dist/tools/task-manage/create.js +11 -27
  110. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  111. package/dist/tools/task-manage/lifecycle.js +23 -106
  112. package/dist/tools/task-manage/log-view.d.ts +3 -2
  113. package/dist/tools/task-manage/log-view.js +6 -6
  114. package/dist/tools/task-manage/schema.d.ts +10 -30
  115. package/dist/tools/task-manage/schema.js +33 -49
  116. package/dist/tools/task-manage/shared.d.ts +35 -42
  117. package/dist/tools/task-manage/shared.js +53 -192
  118. package/dist/tools/task-manage/step-end.d.ts +6 -6
  119. package/dist/tools/task-manage/step-end.js +61 -98
  120. package/dist/tools/task-manage/types.d.ts +8 -9
  121. package/dist/tools/task-manage.js +5 -5
  122. package/dist/tui/app.js +11 -38
  123. package/dist/tui/commands.d.ts +18 -8
  124. package/dist/tui/commands.js +2 -9
  125. package/dist/tui/turn-controller.d.ts +2 -14
  126. package/dist/tui/turn-controller.js +1 -17
  127. package/dist/web/client.js +9 -1
  128. package/examples/sub-agents/README.md +67 -80
  129. package/examples/sub-agents/agents/claude-high.md +23 -0
  130. package/examples/sub-agents/agents/claude-main.md +23 -0
  131. package/examples/sub-agents/agents/codex-flash.md +23 -0
  132. package/examples/sub-agents/agents/codex-high.md +23 -0
  133. package/examples/sub-agents/agents/codex-main.md +23 -0
  134. package/examples/sub-agents/agents/codex-review.md +23 -0
  135. package/examples/sub-agents/agents/glm-flash.md +23 -0
  136. package/examples/sub-agents/agents/glm-high.md +23 -0
  137. package/examples/sub-agents/{verifier.md → roles/verifier.md} +1 -1
  138. package/package.json +1 -1
  139. package/dist/memory/maintenance-migration.d.ts +0 -5
  140. package/dist/memory/maintenance-migration.js +0 -91
  141. package/dist/memory/migrate.d.ts +0 -15
  142. package/dist/memory/migrate.js +0 -364
  143. package/dist/playbooks/task-loop.md +0 -90
  144. package/dist/tasks/artifact-subject.d.ts +0 -40
  145. package/dist/tasks/artifact-subject.js +0 -334
  146. package/dist/tasks/cycle.d.ts +0 -48
  147. package/dist/tasks/cycle.js +0 -94
  148. package/dist/tasks/rounds.d.ts +0 -41
  149. package/dist/tasks/rounds.js +0 -53
  150. package/dist/tasks/task-events.d.ts +0 -6
  151. package/dist/tasks/task-events.js +0 -14
  152. package/dist/tasks/task-schedule.d.ts +0 -18
  153. package/dist/tasks/task-schedule.js +0 -50
  154. package/dist/tasks/verification.d.ts +0 -114
  155. package/dist/tasks/verification.js +0 -226
  156. /package/examples/sub-agents/{builder-hard.md → roles/builder-hard.md} +0 -0
  157. /package/examples/sub-agents/{builder.md → roles/builder.md} +0 -0
  158. /package/examples/sub-agents/{explorer.md → roles/explorer.md} +0 -0
  159. /package/examples/sub-agents/{git-committer.md → roles/git-committer.md} +0 -0
  160. /package/examples/sub-agents/{planner.md → roles/planner.md} +0 -0
  161. /package/examples/sub-agents/{reviewer.md → roles/reviewer.md} +0 -0
  162. /package/examples/sub-agents/{worker.md → roles/worker.md} +0 -0
@@ -3,7 +3,6 @@ import { join, relative } from "path";
3
3
  import { createJobRuntime } from "../agent/job-manager.js";
4
4
  import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
5
5
  import { createRunner } from "../agent/runner-factory.js";
6
- import { renderStatus } from "../agent/status-render.js";
7
6
  import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
8
7
  import { prepareAppServices } from "../app-services.js";
9
8
  import { createFreshActiveSession } from "../channel/active-session-store.js";
@@ -13,42 +12,37 @@ import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
13
12
  import { resolveProjectScope } from "../channel/project-scope-store.js";
14
13
  import { ChannelStore } from "../channel/store.js";
15
14
  import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
16
- import { handleEventsCommand as runEventsCommand } from "../events/event-commands.js";
17
15
  import { createEventsWatcher } from "../events/events.js";
18
16
  import { createExecutor } from "../executor.js";
19
17
  import * as log from "../log.js";
20
- import { migrateMemoryMaintenanceStates } from "../memory/maintenance-migration.js";
21
18
  import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
22
19
  import { defaultModel } from "../models/utils.js";
23
20
  import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
24
21
  import { flushSecurityLogs } from "../security/logger.js";
25
22
  import { resolveProjectAccessPolicy } from "../security/project-scope.js";
26
- import { PipiclawSettingsManager, TASK_DRIVER_SETTINGS } from "../settings.js";
23
+ import { PipiclawSettingsManager } from "../settings.js";
27
24
  import { fileStamp } from "../shared/format.js";
28
25
  import { localStampForFilename } from "../shared/local-time.js";
29
26
  import { errorMessage } from "../shared/text-utils.js";
30
27
  import { sleepUnref } from "../shared/with-timeout.js";
31
- import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
32
28
  import { createSubAgentRuntime } from "../subagents/runs.js";
33
29
  import { buildTaskStepBrief } from "../tasks/brief.js";
34
30
  import { readActiveTasks } from "../tasks/ledger.js";
35
31
  import { consumeTaskNotice } from "../tasks/steer.js";
36
- import { readStoredTask } from "../tasks/store.js";
32
+ import { pauseTask as pauseStoredTask } from "../tasks/store.js";
37
33
  import { getToolsConfigPath, loadToolsConfig } from "../tools/config.js";
38
34
  import { getUsageLedger } from "../usage/ledger.js";
39
- import { parseUsageMode, renderUsageReport } from "../usage/render.js";
40
35
  import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
41
36
  import { createDingTalkContext } from "./delivery.js";
42
37
  import { DingTalkBot, } from "./dingtalk.js";
43
38
  import { DurableDispatchService } from "./durable-dispatch.js";
44
39
  import { extensionForMimeType } from "./inbound-media.js";
45
- import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
46
- import { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
47
- import { renderRunNotice, handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
48
- import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
49
- import { createTaskDriverEvent, TaskDriver } from "./task-driver.js";
50
- import { migrateTasksToV4 } from "./task-migration.js";
51
- import { claimVerifiedDelegationWake, claimVerifiedJobWake } from "./task-wake.js";
40
+ import { runReportCommand } from "./report-commands.js";
41
+ import { renderRunNotice } from "./subagent-commands.js";
42
+ import { createTaskDriverEvent, parseDriverTaskId, TaskDriver } from "./task-driver.js";
43
+ import { migrateTasksToV5 } from "./task-migration.js";
44
+ import { createTaskSpawner } from "./task-spawn.js";
45
+ import { claimVerifiedWake } from "./task-wake.js";
52
46
  const SHUTDOWN_WAIT_MS = 15000;
53
47
  const SHUTDOWN_FLUSH_WAIT_MS = 45000;
54
48
  const SHUTDOWN_ABORT_WAIT_MS = 5000;
@@ -159,19 +153,15 @@ function createDingTalkHandler(deps) {
159
153
  * cannot open its session should still be visible, not silently skipped.
160
154
  */
161
155
  const prepareTaskStep = async (event, runner) => {
162
- const match = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(event.text);
163
- const taskId = match?.[1] ?? event.internalWake?.taskId;
164
- if (!taskId || !runner.bindTaskSession)
156
+ const taskId = parseDriverTaskId(event.text) ?? event.internalWake?.taskId;
157
+ if (!taskId)
165
158
  return undefined;
166
159
  const channelDir = ensureChannelDir(options.paths.workspaceDir, event.channelId);
167
160
  try {
168
- const document = await readStoredTask(channelDir, taskId);
169
- if (!document)
170
- return undefined;
171
161
  const brief = await buildTaskStepBrief({ channelDir, taskId });
172
162
  if (!brief)
173
163
  return undefined;
174
- await runner.bindTaskSession(taskId, document.fields.cycle?.id ?? "c-adhoc");
164
+ await runner.bindTaskSession(taskId);
175
165
  return { taskId, brief };
176
166
  }
177
167
  catch (error) {
@@ -197,7 +187,7 @@ function createDingTalkHandler(deps) {
197
187
  catch (error) {
198
188
  log.logWarning(`[${channelId}] Could not deliver task notice for ${taskId}`, errorMessage(error));
199
189
  }
200
- await getRunner(channelId).bindChatSession?.();
190
+ await getRunner(channelId).bindChatSession();
201
191
  };
202
192
  const handler = {
203
193
  isRunning(channelId) {
@@ -213,14 +203,16 @@ function createDingTalkHandler(deps) {
213
203
  let pausedTaskId;
214
204
  if (runner?.isBusy()) {
215
205
  runner.requestStop();
216
- const taskId = /^\[TASK_DRIVER:([A-Za-z0-9._-]+)\]/.exec(runner.getTurnStatus().taskText ?? "")?.[1];
206
+ // Stopping a task step stops the task: otherwise the driver would queue the next step
207
+ // straight away. The step may not be bound to its session yet, so fall back to the text.
208
+ const taskId = runner.getTaskLoop()?.taskId ?? parseDriverTaskId(runner.getTurnStatus().taskText);
217
209
  if (taskId) {
218
- const pauseResult = await pauseTask({
219
- args: "",
220
- channelDir: getChannelDir(options.paths.workspaceDir, channelId),
221
- }, taskId);
210
+ await pauseStoredTask(getChannelDir(options.paths.workspaceDir, channelId), taskId, {
211
+ by: "user",
212
+ reason: "用户 /stop 中止了该任务的当前步骤。",
213
+ });
222
214
  pausedTaskId = taskId;
223
- log.logInfo(`[${channelId}] ${pauseResult}`);
215
+ log.logInfo(`[${channelId}] Paused task ${taskId} on /stop`);
224
216
  }
225
217
  _bot.discardCard(channelId);
226
218
  // Drop queued-but-not-started messages so a burst does not keep
@@ -282,7 +274,7 @@ function createDingTalkHandler(deps) {
282
274
  if (oldRunner) {
283
275
  channelRunners.delete(event.channelId);
284
276
  try {
285
- oldRunner.retireForNewSession?.();
277
+ oldRunner.retireForNewSession();
286
278
  }
287
279
  catch (error) {
288
280
  // The active pointer already names the new session. Retirement is
@@ -324,96 +316,40 @@ function createDingTalkHandler(deps) {
324
316
  }
325
317
  },
326
318
  async runRuntimeCommand(event, name, args) {
327
- switch (name) {
328
- case "events":
329
- return runEventsCommand({
330
- args,
331
- workspaceDir: options.paths.workspaceDir,
332
- historyPath: options.paths.eventHistoryPath,
333
- });
334
- case "tasks":
335
- return runTasksCommand({
336
- args,
337
- channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
338
- workspaceDir: options.paths.workspaceDir,
339
- channelId: event.channelId,
340
- dispatchTask: async (id) => {
341
- const channelDir = getChannelDir(options.paths.workspaceDir, event.channelId);
342
- const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
343
- if (!entry)
344
- return false;
345
- // A human asking to run a task twice means twice, so this key is deliberately
346
- // unique per invocation rather than sharing the driver's occurrence key (D1).
347
- const now = Date.now();
348
- const driverEvent = createTaskDriverEvent(event.channelId, entry, now);
349
- return ((await getDurableDispatch()?.dispatch({
350
- ...driverEvent,
351
- dispatchId: `task:${event.channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
352
- })) ?? false);
353
- },
354
- });
355
- case "status":
356
- return renderStatus({
357
- runner: channelRunners.get(event.channelId),
358
- version: cliVersion,
359
- uptimeMs: Date.now() - startedAt,
360
- });
361
- case "usage":
362
- return renderUsageReport(getUsageLedger(), event.channelId, parseUsageMode(args), new Date());
363
- // Read-only prompt accounting; safe mid-turn, so the busy path answers it through
364
- // this stateless report rather than the runner's ChannelContext-aware idle path.
365
- case "context":
366
- return getRunner(event.channelId).renderContextReport(args);
367
- // A human control path independent of the model (spec 040, D6): `/stop` no longer kills a
368
- // dispatched delegation, so cancel must work whether or not a runner is currently active.
369
- case "subagents":
370
- return runSubagentsCommand({
371
- args,
372
- runManager: getRuns().get(event.channelId),
373
- channelId: event.channelId,
374
- discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
375
- // `roles` needs a role directory even for a channel that has never spoken this boot —
376
- // resolved from disk, without spinning up a full ChannelRunner (spec 041).
377
- getDetachedDiscovery: () => loadDetachedSubAgentDiscovery({
378
- workspaceDir: options.paths.workspaceDir,
379
- authConfigPath: options.paths.authConfigPath,
380
- modelsConfigPath: options.paths.modelsConfigPath,
381
- }),
382
- });
383
- case "project":
384
- return runProjectCommand({
385
- args,
386
- channelId: event.channelId,
387
- channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
388
- appHomeDir: options.paths.appHomeDir,
389
- actor: "dingtalk-command",
390
- isBusy: () => channelRunners.get(event.channelId)?.isBusy() ?? false,
391
- listActiveBlockers: () => [
392
- ...getRuns()
393
- .get(event.channelId)
394
- .list()
395
- .filter((record) => record.status === "running")
396
- .map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
397
- ...getJobs().runningLines(event.channelId),
398
- ],
399
- // D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
400
- // The active-session ref is untouched — same session, new project root.
401
- onScopeChanged: async () => {
402
- const runner = channelRunners.get(event.channelId);
403
- channelRunners.delete(event.channelId);
404
- await runner?.dispose().catch((err) => {
405
- log.logWarning(`[${event.channelId}] Failed to dispose runner after /project`, errorMessage(err));
406
- });
407
- },
319
+ const { channelId } = event;
320
+ return runReportCommand({
321
+ channelId,
322
+ paths: options.paths,
323
+ actor: "dingtalk-command",
324
+ version: cliVersion,
325
+ startedAt,
326
+ peekRunner: () => channelRunners.get(channelId),
327
+ getRunner: () => getRunner(channelId),
328
+ runManager: getRuns().get(channelId),
329
+ runningJobLines: () => getJobs().runningLines(channelId),
330
+ // D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
331
+ // The active-session ref is untouched — same session, new project root.
332
+ onScopeChanged: async () => {
333
+ const runner = channelRunners.get(channelId);
334
+ channelRunners.delete(channelId);
335
+ await runner?.dispose().catch((err) => {
336
+ log.logWarning(`[${channelId}] Failed to dispose runner after /project`, errorMessage(err));
408
337
  });
409
- case "skills":
410
- return runSkillsCommand({
411
- args,
412
- workspaceDir: options.paths.workspaceDir,
413
- appHomeDir: options.paths.appHomeDir,
414
- channelId: event.channelId,
415
- });
416
- }
338
+ },
339
+ dispatchTask: async (id) => {
340
+ const channelDir = getChannelDir(options.paths.workspaceDir, channelId);
341
+ const entry = (await readActiveTasks(join(channelDir, "tasks"))).find((candidate) => candidate.id === id);
342
+ if (!entry)
343
+ return false;
344
+ // A human asking to run a task twice means twice, so this key is deliberately
345
+ // unique per invocation rather than sharing the driver's occurrence key (D1).
346
+ const now = Date.now();
347
+ return ((await getDurableDispatch()?.dispatch({
348
+ ...createTaskDriverEvent(channelId, entry, now),
349
+ dispatchId: `task:${channelId}:${entry.id}:manual:${new Date(now).toISOString()}`,
350
+ })) ?? false);
351
+ },
352
+ }, name, args);
417
353
  },
418
354
  async handleBusyMessage(event, bot, mode, queueText) {
419
355
  if (isShuttingDown()) {
@@ -429,10 +365,22 @@ function createDingTalkHandler(deps) {
429
365
  // Compaction is maintenance, not user work. A new message cancels it and is
430
366
  // kept as a normal queued turn instead of trying to steer an agent loop that
431
367
  // is currently disconnected for summarization.
432
- if (runner.interruptCompaction?.()) {
368
+ if (runner.interruptCompaction()) {
433
369
  log.logInfo(`[${event.channelId}] Interrupted compaction for a new user message`);
434
370
  return { kind: "requeue", text: trimmedQueueText };
435
371
  }
372
+ // A task step runs in the task's own session and is muted: a steer here would land in
373
+ // the background task's context and its answer would never reach the user, while the
374
+ // message itself is kept out of the chat session. Run it as the next chat turn instead.
375
+ const taskLoop = runner.getTaskLoop();
376
+ if (taskLoop) {
377
+ await bot.sendPlain(event.channelId, `后台任务 \`${taskLoop.taskId}\` 正在执行一步,你的消息会在这一步结束后处理;要给该任务补充指示,用 \`/tasks steer ${taskLoop.taskId} <内容>\`。`);
378
+ log.logEvent("info", "agent.turn.followup_queued", "Message deferred past a task step", {
379
+ ctx: { channelId: event.channelId, userName: event.userName },
380
+ fields: { messageLength: trimmedQueueText.length, taskId: taskLoop.taskId },
381
+ });
382
+ return { kind: "requeue", text: trimmedQueueText };
383
+ }
436
384
  if (mode === "followUp") {
437
385
  log.logEvent("info", "agent.turn.followup_queued", "Follow-up queued", {
438
386
  ctx: { channelId: event.channelId, userName: event.userName },
@@ -514,6 +462,7 @@ function createDingTalkHandler(deps) {
514
462
  await getDurableDispatch()?.markStarted(event.dispatchId);
515
463
  let structuredWakeFinalized = event.internalWake === undefined;
516
464
  const task = (async () => {
465
+ let baseCtx;
517
466
  try {
518
467
  // Computed before archiving so a command's own text can be excluded from
519
468
  // memory-extraction input (review 2026-08-24 §1.2): it is control-plane
@@ -530,16 +479,15 @@ function createDingTalkHandler(deps) {
530
479
  images: relativeImagePaths(options.paths.workspaceDir, event.channelId, event.images),
531
480
  }, "user message");
532
481
  // Background wakes deliver their result, not their process: no progress card, no
533
- // thinking stream, nothing to delete when the check-in ends `[SILENT]`. An "awaited"
534
- // wake (a delegation or job finishing) is the opposite — a human is actually waiting
535
- // on it — so it renders progress the same way a normal message does (P0-2).
536
- const backgroundOnly = Boolean(_isEvent) && event.presentation !== "awaited";
482
+ // thinking stream, nothing to clean up when a check-in ends `[SILENT]`.
483
+ // Awaited completions deliver their result too, without opening another progress card.
484
+ const backgroundOnly = Boolean(_isEvent);
537
485
  // Spec 051, D3: a task-driver dispatch runs as a *task step* — in the task cycle's
538
486
  // own session, with a brief instead of the wake text, and silent unless the step
539
487
  // asked for a notify. Everything below (busy state, /stop, delivery) is unchanged;
540
488
  // only which session the turn is bound to, and what reaches the channel, differ.
541
489
  let taskStep;
542
- let baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
490
+ baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
543
491
  let ctx = baseCtx;
544
492
  if (builtInCommand) {
545
493
  const commandStartedAt = Date.now();
@@ -592,77 +540,36 @@ function createDingTalkHandler(deps) {
592
540
  ctx: { channelId: event.channelId, userName: event.userName },
593
541
  fields: { messageLength: event.text.length, source: _isEvent ? "event" : "message" },
594
542
  });
595
- if (!backgroundOnly) {
596
- ctx.primeCard(350);
597
- }
598
- // Both wake formats below carry an unauthenticated claim in plain text: anything
599
- // that can put a message on this channel can *write* "[JOB:x] ... belongs to task
600
- // y." or "[SUBAGENT:x] ... belongs to task y." — including another user, or an
601
- // external agent's own untrusted stdout (spec 040, D8's threat model explicitly
602
- // treats external output as untrusted). Activating a waiting task on text pattern
603
- // alone lets that forged claim wake an unrelated task early. The
604
- // pattern match only extracts a *candidate* id pair now; both paths verify the
605
- // named run/job actually exists, is done, and really is the one that names this
606
- // taskId before ever calling `activateWaitingTask` (T9).
607
- const jobTextMatch = /^\[JOB:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
608
- const jobMatch = event.internalWake?.kind === "job"
609
- ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
610
- : jobTextMatch;
611
- if (jobMatch) {
612
- const [, jobId, jobTaskId] = jobMatch;
613
- const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getJobs().get(event.channelId), options.wakeTransitionHooks?.job);
614
- if (claimed) {
615
- await claimed.finish();
543
+ // A completion wake for a task's job or delegation: verified against the resource's own
544
+ // record before it may reopen the task (see `claimVerifiedWake`). Plain "belongs to task"
545
+ // text in a message never counts — only the producer-created `internalWake` envelope.
546
+ if (event.internalWake) {
547
+ const { kind, resourceId, taskId: wakeTaskId } = event.internalWake;
548
+ const claimed = await claimVerifiedWake(event, options.paths.workspaceDir, kind === "job" ? getJobs().get(event.channelId) : getRuns().get(event.channelId), options.wakeTransitionHooks?.[kind]);
549
+ if (!claimed) {
550
+ log.logWarning(`[${event.channelId}] Ignored an unverifiable ${kind} wake for ${resourceId} claiming task ${wakeTaskId}`);
616
551
  structuredWakeFinalized = true;
617
- // Drop without a turn only when something else is still driving this task (a
618
- // sibling wake in the same fan-out already activated it); every other case —
619
- // the task is done, archived, disabled, or gone — has nobody left to see this
620
- // result if it is dropped here, so it must still reach a normal turn (P3-1).
621
- if (event.internalWake?.kind === "job" && !claimed.activated && claimed.taskStillDriven)
622
- return;
623
- }
624
- else {
625
- log.logWarning(`[${event.channelId}] Ignored an unverifiable [JOB:${jobId}] wake claiming task ${jobTaskId}`);
626
- if (event.internalWake?.kind === "job") {
627
- structuredWakeFinalized = true;
628
- return;
629
- }
630
- }
631
- }
632
- // Spec 040, D7: a delegation run's completion wake carries the same "belongs to
633
- // task" contract as a background job's, and reactivates a task parked with
634
- // waitingFor="external-signal" the same way — verified the same way (T9).
635
- const delegationTextMatch = /^\[SUBAGENT:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
636
- const delegationMatch = event.internalWake?.kind === "subagent"
637
- ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
638
- : delegationTextMatch;
639
- if (delegationMatch) {
640
- const [, runId, delegationTaskId] = delegationMatch;
641
- const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, getRuns().get(event.channelId), options.wakeTransitionHooks?.subagent);
642
- if (claimed) {
643
- await claimed.finish();
644
- structuredWakeFinalized = true;
645
- // See the JOB branch above (P3-1): only skip the turn when the task is still
646
- // driven by something else.
647
- if (event.internalWake?.kind === "subagent" && !claimed.activated && claimed.taskStillDriven)
648
- return;
649
- }
650
- else {
651
- log.logWarning(`[${event.channelId}] Ignored an unverifiable [SUBAGENT:${runId}] wake claiming task ${delegationTaskId}`);
652
- if (event.internalWake?.kind === "subagent") {
653
- structuredWakeFinalized = true;
654
- return;
655
- }
552
+ return;
656
553
  }
554
+ await claimed.finish();
555
+ structuredWakeFinalized = true;
556
+ // Drop without a turn only when something else is still driving this task (a sibling
557
+ // wake in the same fan-out already reopened it); in every other case nobody else will
558
+ // look at this result, so it still reaches a normal turn.
559
+ if (!claimed.activated && claimed.taskStillDriven)
560
+ return;
657
561
  }
658
562
  // Verified job/run wakes that activate a task are task steps too. Verification must happen
659
563
  // first: routing directly from user-controlled wake text would grant task-only tools.
660
564
  taskStep = await prepareTaskStep(event, runner);
661
565
  if (taskStep) {
566
+ await baseCtx.close();
662
567
  event = { ...event, text: taskStep.brief };
663
- baseCtx = createDingTalkContext(event, bot, store, backgroundOnly ? "none" : undefined);
568
+ baseCtx = createDingTalkContext(event, bot, store, "none");
664
569
  ctx = muteChannelContext(baseCtx);
665
570
  }
571
+ if (!backgroundOnly && !taskStep)
572
+ ctx.primeCard(1500);
666
573
  const result = await runner.run(ctx, store);
667
574
  if (taskStep)
668
575
  await finishTaskStep(event.channelId, taskStep.taskId, bot);
@@ -677,6 +584,9 @@ function createDingTalkHandler(deps) {
677
584
  });
678
585
  }
679
586
  finally {
587
+ await baseCtx?.close().catch((error) => {
588
+ log.logWarning(`[${event.channelId}] Failed to close delivery`, errorMessage(error));
589
+ });
680
590
  if (structuredWakeFinalized)
681
591
  await getDurableDispatch()?.markCompleted(event.dispatchId);
682
592
  else
@@ -699,7 +609,6 @@ function createDingTalkHandler(deps) {
699
609
  return handler;
700
610
  }
701
611
  export async function createRuntimeContext(options) {
702
- await migrateMemoryMaintenanceStates(options.paths.appHomeDir);
703
612
  const startServices = options.startServices ?? true;
704
613
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
705
614
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
@@ -855,7 +764,11 @@ export async function createRuntimeContext(options) {
855
764
  }
856
765
  const eventsWatcher = options.createEventsWatcher
857
766
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
858
- : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false);
767
+ : createEventsWatcher(options.paths.workspaceDir, bot, executor, loadSecurityConfigWithDiagnostics(options.paths.appHomeDir).config.commandGuard, options.paths.eventHistoryPath, (event) => durableDispatch?.dispatch(event) ?? false, createTaskSpawner({
768
+ getChannelDir: (channelId) => getChannelDir(options.paths.workspaceDir, channelId),
769
+ nudge: () => getTaskDriver().nudge?.(),
770
+ notify: (channelId, text) => bot.sendPlain(channelId, text),
771
+ }));
859
772
  const memoryMaintenanceScheduler = options.createMemoryMaintenanceScheduler
860
773
  ? options.createMemoryMaintenanceScheduler()
861
774
  : new MemoryMaintenanceScheduler({
@@ -887,8 +800,7 @@ export async function createRuntimeContext(options) {
887
800
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
888
801
  });
889
802
  // `tools.json` is re-read on every driver tick — and a tick follows every turn — so cache the
890
- // parse behind the file's change token. `settings.json` gets the same treatment inside
891
- // `PipiclawSettingsManager.reload()`, which is why the getSettings closure below stays as-is.
803
+ // parse behind the file's change token.
892
804
  let cachedToolsStamp;
893
805
  let cachedTasksEnabled = true;
894
806
  const tasksToolEnabled = () => {
@@ -908,10 +820,6 @@ export async function createRuntimeContext(options) {
908
820
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
909
821
  onDispatch: options.onTaskDriverDispatch,
910
822
  notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
911
- getSettings: () => {
912
- runtimeSettingsManager.reload();
913
- return TASK_DRIVER_SETTINGS;
914
- },
915
823
  isEnabled: tasksToolEnabled,
916
824
  });
917
825
  const shutdownWithReason = async (reason = "manual") => {
@@ -1002,9 +910,12 @@ export async function createRuntimeContext(options) {
1002
910
  });
1003
911
  }
1004
912
  if (startServices) {
1005
- // Upgrade every v3 task file to the v4 contract before the driver relies on it (spec 051, D14). Marker-gated: the pass rewrites
1006
- // bodies and imports history into the loop log, so it must run exactly once per install.
1007
- void migrateTasksToV4(options.paths.workspaceDir, join(options.paths.appHomeDir, "state"));
913
+ // Convert v4 task files and their recurring schedules before the watcher or the driver rely
914
+ // on the v5 layout (spec 052, D12). Marker-gated and awaited: the pass writes event
915
+ // templates the watcher is about to load, so the services must not start underneath it.
916
+ await migrateTasksToV5(options.paths.workspaceDir, join(options.paths.appHomeDir, "state")).catch((error) => {
917
+ log.logWarning("Task conversion to v5 failed; tasks may need /tasks doctor", errorMessage(error));
918
+ });
1008
919
  eventsWatcher.start();
1009
920
  memoryMaintenanceScheduler.start();
1010
921
  taskDriver.start();
@@ -7,8 +7,7 @@ import type { DingTalkBot } from "./dingtalk.js";
7
7
  *
8
8
  * `progressStyleOverride` lets the caller quiet a turn the user did not ask for. Background wakes
9
9
  * (task driver, finished jobs, scheduled events) pass `"none"`: without it every autonomous step
10
- * created an AI card in the human's conversation, streamed the model's thinking into it, and — for
11
- * the `[SILENT]` turns that are the *normal* outcome of a check-in — deleted the card again. The
10
+ * created an AI card in the human's conversation even when the check-in ended `[SILENT]`. The
12
11
  * final answer is unaffected; it is delivered by `respondPlain`/`replaceMessage` either way, so a
13
12
  * background turn that has something to say still says it.
14
13
  */