@oyasmi/pipiclaw 0.9.3-beta.5 → 0.9.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 (144) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/dist/agent/channel-runner.d.ts +4 -8
  4. package/dist/agent/channel-runner.js +14 -34
  5. package/dist/agent/job-manager.d.ts +12 -0
  6. package/dist/agent/job-manager.js +42 -1
  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-index.d.ts +9 -2
  11. package/dist/channel/channel-index.js +25 -6
  12. package/dist/channel/project-scope-store.d.ts +20 -0
  13. package/dist/channel/project-scope-store.js +22 -7
  14. package/dist/commands/catalog.js +6 -12
  15. package/dist/events/event-commands.js +2 -2
  16. package/dist/events/events.d.ts +51 -30
  17. package/dist/events/events.js +70 -98
  18. package/dist/memory/journal.d.ts +2 -3
  19. package/dist/memory/journal.js +2 -3
  20. package/dist/memory/maintenance-tuning.d.ts +0 -1
  21. package/dist/memory/maintenance-tuning.js +0 -1
  22. package/dist/memory/scheduler.js +8 -16
  23. package/dist/memory/search.js +2 -3
  24. package/dist/memory/session-search.js +3 -9
  25. package/dist/memory/store.d.ts +1 -1
  26. package/dist/memory/store.js +9 -1
  27. package/dist/memory/task-digest.js +10 -11
  28. package/dist/memory/tombstones.js +2 -4
  29. package/dist/models/provider-login.d.ts +1 -1
  30. package/dist/models/provider-login.js +1 -1
  31. package/dist/playbooks/agent-delegation.md +6 -6
  32. package/dist/playbooks/background-jobs.md +1 -1
  33. package/dist/playbooks/event-scheduling.md +22 -13
  34. package/dist/playbooks/memory-and-learning.md +2 -2
  35. package/dist/playbooks/outbound-media.md +1 -1
  36. package/dist/playbooks/runtime-orientation.md +3 -3
  37. package/dist/playbooks/task-lead.md +82 -0
  38. package/dist/runtime/bootstrap.js +94 -187
  39. package/dist/runtime/durable-dispatch.js +30 -3
  40. package/dist/runtime/report-commands.d.ts +30 -0
  41. package/dist/runtime/report-commands.js +71 -0
  42. package/dist/runtime/subagent-commands.js +1 -1
  43. package/dist/runtime/task-commands.d.ts +0 -8
  44. package/dist/runtime/task-commands.js +48 -85
  45. package/dist/runtime/task-driver.d.ts +15 -10
  46. package/dist/runtime/task-driver.js +36 -41
  47. package/dist/runtime/task-migration.d.ts +23 -29
  48. package/dist/runtime/task-migration.js +364 -183
  49. package/dist/runtime/task-spawn.d.ts +24 -0
  50. package/dist/runtime/task-spawn.js +49 -0
  51. package/dist/runtime/task-wake.d.ts +33 -46
  52. package/dist/runtime/task-wake.js +15 -90
  53. package/dist/security/network.js +44 -9
  54. package/dist/settings.d.ts +1 -8
  55. package/dist/settings.js +1 -8
  56. package/dist/subagents/discovery.js +3 -15
  57. package/dist/subagents/external/run.d.ts +3 -1
  58. package/dist/subagents/external/run.js +2 -20
  59. package/dist/subagents/external/settlement.d.ts +4 -16
  60. package/dist/subagents/external/settlement.js +16 -67
  61. package/dist/subagents/runs.d.ts +15 -29
  62. package/dist/subagents/runs.js +70 -158
  63. package/dist/subagents/tool.d.ts +20 -4
  64. package/dist/subagents/tool.js +63 -87
  65. package/dist/subagents/verification-outcome.d.ts +13 -19
  66. package/dist/subagents/verification-outcome.js +8 -22
  67. package/dist/subagents/workspace-summary.d.ts +8 -0
  68. package/dist/subagents/workspace-summary.js +29 -0
  69. package/dist/tasks/board.d.ts +43 -0
  70. package/dist/tasks/board.js +134 -0
  71. package/dist/tasks/brief.d.ts +10 -5
  72. package/dist/tasks/brief.js +78 -26
  73. package/dist/tasks/budget.d.ts +13 -14
  74. package/dist/tasks/budget.js +21 -40
  75. package/dist/tasks/contract-input.d.ts +19 -0
  76. package/dist/tasks/contract-input.js +55 -0
  77. package/dist/tasks/create.d.ts +17 -0
  78. package/dist/tasks/create.js +36 -0
  79. package/dist/tasks/frontmatter.d.ts +20 -27
  80. package/dist/tasks/frontmatter.js +18 -31
  81. package/dist/tasks/ledger.d.ts +61 -117
  82. package/dist/tasks/ledger.js +78 -223
  83. package/dist/tasks/log.d.ts +62 -35
  84. package/dist/tasks/log.js +51 -29
  85. package/dist/tasks/session-path.d.ts +3 -3
  86. package/dist/tasks/session-path.js +4 -5
  87. package/dist/tasks/store.d.ts +27 -28
  88. package/dist/tasks/store.js +89 -83
  89. package/dist/tasks/ticket.d.ts +33 -66
  90. package/dist/tasks/ticket.js +31 -120
  91. package/dist/tasks/work-log.d.ts +20 -0
  92. package/dist/tasks/work-log.js +42 -0
  93. package/dist/tools/bash.d.ts +1 -1
  94. package/dist/tools/bash.js +1 -1
  95. package/dist/tools/event-manage.d.ts +16 -2
  96. package/dist/tools/event-manage.js +30 -12
  97. package/dist/tools/index.d.ts +5 -3
  98. package/dist/tools/index.js +5 -5
  99. package/dist/tools/registry.d.ts +6 -4
  100. package/dist/tools/registry.js +1 -4
  101. package/dist/tools/subagent-manage.js +4 -2
  102. package/dist/tools/task-manage/create.js +11 -27
  103. package/dist/tools/task-manage/lifecycle.d.ts +6 -7
  104. package/dist/tools/task-manage/lifecycle.js +23 -106
  105. package/dist/tools/task-manage/log-view.d.ts +3 -2
  106. package/dist/tools/task-manage/log-view.js +6 -6
  107. package/dist/tools/task-manage/schema.d.ts +10 -30
  108. package/dist/tools/task-manage/schema.js +33 -49
  109. package/dist/tools/task-manage/shared.d.ts +35 -42
  110. package/dist/tools/task-manage/shared.js +53 -192
  111. package/dist/tools/task-manage/step-end.d.ts +6 -6
  112. package/dist/tools/task-manage/step-end.js +61 -98
  113. package/dist/tools/task-manage/types.d.ts +8 -9
  114. package/dist/tools/task-manage.js +5 -5
  115. package/dist/tui/app.js +11 -38
  116. package/dist/tui/commands.d.ts +18 -8
  117. package/dist/tui/commands.js +2 -9
  118. package/dist/tui/turn-controller.d.ts +2 -14
  119. package/dist/tui/turn-controller.js +1 -17
  120. package/dist/web/client.js +9 -1
  121. package/examples/sub-agents/README.md +7 -4
  122. package/examples/sub-agents/agents/codex-flash.md +2 -2
  123. package/examples/sub-agents/agents/codex-high.md +1 -1
  124. package/examples/sub-agents/agents/codex-main.md +1 -1
  125. package/examples/sub-agents/agents/codex-review.md +23 -0
  126. package/examples/sub-agents/roles/verifier.md +1 -1
  127. package/package.json +1 -1
  128. package/dist/memory/maintenance-migration.d.ts +0 -5
  129. package/dist/memory/maintenance-migration.js +0 -91
  130. package/dist/memory/migrate.d.ts +0 -15
  131. package/dist/memory/migrate.js +0 -364
  132. package/dist/playbooks/task-loop.md +0 -90
  133. package/dist/tasks/artifact-subject.d.ts +0 -40
  134. package/dist/tasks/artifact-subject.js +0 -334
  135. package/dist/tasks/cycle.d.ts +0 -48
  136. package/dist/tasks/cycle.js +0 -94
  137. package/dist/tasks/rounds.d.ts +0 -41
  138. package/dist/tasks/rounds.js +0 -53
  139. package/dist/tasks/task-events.d.ts +0 -6
  140. package/dist/tasks/task-events.js +0 -14
  141. package/dist/tasks/task-schedule.d.ts +0 -18
  142. package/dist/tasks/task-schedule.js +0 -50
  143. package/dist/tasks/verification.d.ts +0 -114
  144. package/dist/tasks/verification.js +0 -226
@@ -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
- },
408
- });
409
- case "skills":
410
- return runSkillsCommand({
411
- args,
412
- workspaceDir: options.paths.workspaceDir,
413
- appHomeDir: options.paths.appHomeDir,
414
- channelId: event.channelId,
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));
415
337
  });
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 },
@@ -592,65 +540,24 @@ 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
- // Both wake formats below carry an unauthenticated claim in plain text: anything
596
- // that can put a message on this channel can *write* "[JOB:x] ... belongs to task
597
- // y." or "[SUBAGENT:x] ... belongs to task y." — including another user, or an
598
- // external agent's own untrusted stdout (spec 040, D8's threat model explicitly
599
- // treats external output as untrusted). Activating a waiting task on text pattern
600
- // alone lets that forged claim wake an unrelated task early. The
601
- // pattern match only extracts a *candidate* id pair now; both paths verify the
602
- // named run/job actually exists, is done, and really is the one that names this
603
- // taskId before ever calling `activateWaitingTask` (T9).
604
- const jobTextMatch = /^\[JOB:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
605
- const jobMatch = event.internalWake?.kind === "job"
606
- ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
607
- : jobTextMatch;
608
- if (jobMatch) {
609
- const [, jobId, jobTaskId] = jobMatch;
610
- const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getJobs().get(event.channelId), options.wakeTransitionHooks?.job);
611
- if (claimed) {
612
- 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}`);
613
551
  structuredWakeFinalized = true;
614
- // Drop without a turn only when something else is still driving this task (a
615
- // sibling wake in the same fan-out already activated it); every other case —
616
- // the task is done, archived, disabled, or gone — has nobody left to see this
617
- // result if it is dropped here, so it must still reach a normal turn (P3-1).
618
- if (event.internalWake?.kind === "job" && !claimed.activated && claimed.taskStillDriven)
619
- return;
620
- }
621
- else {
622
- log.logWarning(`[${event.channelId}] Ignored an unverifiable [JOB:${jobId}] wake claiming task ${jobTaskId}`);
623
- if (event.internalWake?.kind === "job") {
624
- structuredWakeFinalized = true;
625
- return;
626
- }
627
- }
628
- }
629
- // Spec 040, D7: a delegation run's completion wake carries the same "belongs to
630
- // task" contract as a background job's, and reactivates a task parked with
631
- // waitingFor="external-signal" the same way — verified the same way (T9).
632
- const delegationTextMatch = /^\[SUBAGENT:([^\]]+)\][\s\S]*?belongs to task ([A-Za-z0-9._-]+)\./.exec(event.text);
633
- const delegationMatch = event.internalWake?.kind === "subagent"
634
- ? [event.text, event.internalWake.resourceId, event.internalWake.taskId]
635
- : delegationTextMatch;
636
- if (delegationMatch) {
637
- const [, runId, delegationTaskId] = delegationMatch;
638
- const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, getRuns().get(event.channelId), options.wakeTransitionHooks?.subagent);
639
- if (claimed) {
640
- await claimed.finish();
641
- structuredWakeFinalized = true;
642
- // See the JOB branch above (P3-1): only skip the turn when the task is still
643
- // driven by something else.
644
- if (event.internalWake?.kind === "subagent" && !claimed.activated && claimed.taskStillDriven)
645
- return;
646
- }
647
- else {
648
- log.logWarning(`[${event.channelId}] Ignored an unverifiable [SUBAGENT:${runId}] wake claiming task ${delegationTaskId}`);
649
- if (event.internalWake?.kind === "subagent") {
650
- structuredWakeFinalized = true;
651
- return;
652
- }
552
+ return;
653
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;
654
561
  }
655
562
  // Verified job/run wakes that activate a task are task steps too. Verification must happen
656
563
  // first: routing directly from user-controlled wake text would grant task-only tools.
@@ -702,7 +609,6 @@ function createDingTalkHandler(deps) {
702
609
  return handler;
703
610
  }
704
611
  export async function createRuntimeContext(options) {
705
- await migrateMemoryMaintenanceStates(options.paths.appHomeDir);
706
612
  const startServices = options.startServices ?? true;
707
613
  const registerSignalHandlers = options.registerSignalHandlers ?? true;
708
614
  const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
@@ -858,7 +764,11 @@ export async function createRuntimeContext(options) {
858
764
  }
859
765
  const eventsWatcher = options.createEventsWatcher
860
766
  ? options.createEventsWatcher(options.paths.workspaceDir, bot, executor, options.paths.eventHistoryPath)
861
- : 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
+ }));
862
772
  const memoryMaintenanceScheduler = options.createMemoryMaintenanceScheduler
863
773
  ? options.createMemoryMaintenanceScheduler()
864
774
  : new MemoryMaintenanceScheduler({
@@ -890,8 +800,7 @@ export async function createRuntimeContext(options) {
890
800
  intervalMs: options.memoryMaintenanceSchedulerIntervalMs,
891
801
  });
892
802
  // `tools.json` is re-read on every driver tick — and a tick follows every turn — so cache the
893
- // parse behind the file's change token. `settings.json` gets the same treatment inside
894
- // `PipiclawSettingsManager.reload()`, which is why the getSettings closure below stays as-is.
803
+ // parse behind the file's change token.
895
804
  let cachedToolsStamp;
896
805
  let cachedTasksEnabled = true;
897
806
  const tasksToolEnabled = () => {
@@ -911,10 +820,6 @@ export async function createRuntimeContext(options) {
911
820
  dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
912
821
  onDispatch: options.onTaskDriverDispatch,
913
822
  notify: (receipt) => bot.sendPlain(receipt.channelId, receipt.text),
914
- getSettings: () => {
915
- runtimeSettingsManager.reload();
916
- return TASK_DRIVER_SETTINGS;
917
- },
918
823
  isEnabled: tasksToolEnabled,
919
824
  });
920
825
  const shutdownWithReason = async (reason = "manual") => {
@@ -1005,9 +910,11 @@ export async function createRuntimeContext(options) {
1005
910
  });
1006
911
  }
1007
912
  if (startServices) {
1008
- // Upgrade every v3 task file to the v4 contract before the driver relies on it (spec 051, D14). Marker-gated: the pass rewrites
1009
- // bodies and imports history into the loop log, so it must run exactly once per install.
1010
- void migrateTasksToV4(options.paths.workspaceDir, join(options.paths.appHomeDir, "state"));
913
+ // Convert supported v3 task files and their schedules (v4 beta files are skipped) before services 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
+ // A failed or partial conversion throws and aborts startup: nothing may run on half-migrated state.
917
+ await migrateTasksToV5(options.paths.workspaceDir, join(options.paths.appHomeDir, "state"));
1011
918
  eventsWatcher.start();
1012
919
  memoryMaintenanceScheduler.start();
1013
920
  taskDriver.start();
@@ -13,8 +13,28 @@ const DEFAULT_INTERVAL_MS = 30_000;
13
13
  const MAX_DELIVERIES = 8;
14
14
  const MIN_RETRY_BACKOFF_MS = 30_000;
15
15
  const MAX_RETRY_BACKOFF_MS = 10 * 60_000;
16
+ /**
17
+ * Business-id dispatch ids can contain `/` (a DingTalk group id is base64 and routinely does —
18
+ * see `channel/channel-paths.ts`). Used verbatim as a filename that turns into a nested path a
19
+ * flat `readdir(stateDir)` scan can never find again (R1): a queue rejection or a restart then
20
+ * makes that record un-drainable and un-cancellable forever, even once capacity returns. Percent-
21
+ * encoding keeps the mapping reversible and collision-free without touching the id itself — only
22
+ * the on-disk filename changes.
23
+ */
24
+ function encodeDispatchId(id) {
25
+ return encodeURIComponent(id);
26
+ }
27
+ /** Inverse of {@link encodeDispatchId}. */
28
+ function decodeDispatchId(encoded) {
29
+ try {
30
+ return decodeURIComponent(encoded);
31
+ }
32
+ catch {
33
+ return encoded;
34
+ }
35
+ }
16
36
  function recordPath(stateDir, id) {
17
- return join(stateDir, `${id}.json`);
37
+ return join(stateDir, `${encodeDispatchId(id)}.json`);
18
38
  }
19
39
  /**
20
40
  * Prefix a redelivered wake with what the runtime already knows (spec 031, D3).
@@ -149,7 +169,7 @@ export class DurableDispatchService {
149
169
  }
150
170
  let canceled = 0;
151
171
  for (const filename of filenames) {
152
- const id = filename.slice(0, -".json".length);
172
+ const id = decodeDispatchId(filename.slice(0, -".json".length));
153
173
  await this.queue.run(id, async () => {
154
174
  const record = await this.read(id);
155
175
  if (!record || record.event.channelId !== channelId)
@@ -220,7 +240,7 @@ export class DurableDispatchService {
220
240
  return;
221
241
  }
222
242
  for (const filename of filenames) {
223
- const id = filename.slice(0, -".json".length);
243
+ const id = decodeDispatchId(filename.slice(0, -".json".length));
224
244
  await this.drainRecord(id, now);
225
245
  }
226
246
  }
@@ -275,7 +295,14 @@ export class DurableDispatchService {
275
295
  const accepted = this.options.bot.enqueueEvent(withRedeliveryNotice({ ...record.event, dispatchId: record.id }, record.deliveries));
276
296
  if (accepted)
277
297
  return;
298
+ // Admission rejection (queue full, bot stopped) is backpressure, not a delivery attempt —
299
+ // the handler never ran and never got a chance to fail (R2). Counting it against
300
+ // MAX_DELIVERIES meant a few minutes of congestion permanently exhausted a record that
301
+ // was never actually tried; undo the increment above so only real handler outcomes
302
+ // (markCompleted/markRetryable, or a crash-lease redelivery) count toward the poison-pill
303
+ // limit.
278
304
  record.status = "pending";
305
+ record.deliveries--;
279
306
  record.leaseExpiresAt = undefined;
280
307
  await this.write(record);
281
308
  });
@@ -0,0 +1,30 @@
1
+ import type { AgentRunner } from "../agent/types.js";
2
+ import type { RuntimeCommandName } from "../commands/catalog.js";
3
+ import type { SubAgentRunManager } from "../subagents/runs.js";
4
+ import type { BootstrapPaths } from "./app-home.js";
5
+ /**
6
+ * The stateless report commands (`/events /tasks /status /usage /context /subagents /project
7
+ * /skills`) as one transport-neutral handler. The DingTalk runtime and the terminal TUI both route
8
+ * through it, so a report cannot behave differently depending on where it was typed; each
9
+ * transport supplies only what is genuinely its own (how to find its runner, how to rebuild one
10
+ * after `/project`, whether a task can be woken immediately).
11
+ */
12
+ export interface ReportCommandContext {
13
+ channelId: string;
14
+ paths: Pick<BootstrapPaths, "workspaceDir" | "appHomeDir" | "eventHistoryPath" | "authConfigPath" | "modelsConfigPath">;
15
+ actor: "dingtalk-command" | "tui-command";
16
+ version: string;
17
+ startedAt: number;
18
+ /** The channel's live runner, if one exists; never builds one. */
19
+ peekRunner: () => AgentRunner | undefined;
20
+ /** The channel's runner, built on demand (`/context` needs a session to report on). */
21
+ getRunner: () => AgentRunner;
22
+ runManager: SubAgentRunManager;
23
+ /** One line per running background job, for `/project`'s "busy" check. */
24
+ runningJobLines: () => string[];
25
+ /** Drop the runner built under the old project scope so the next access rebuilds it. */
26
+ onScopeChanged: () => Promise<void>;
27
+ /** Immediate task wake for `/tasks run|reply`; absent where there is no durable dispatch (the TUI). */
28
+ dispatchTask?: (taskId: string) => Promise<boolean>;
29
+ }
30
+ export declare function runReportCommand(context: ReportCommandContext, name: RuntimeCommandName, args: string): Promise<string>;
@@ -0,0 +1,71 @@
1
+ import { renderStatus } from "../agent/status-render.js";
2
+ import { getChannelDir } from "../channel/channel-paths.js";
3
+ import { handleEventsCommand } from "../events/event-commands.js";
4
+ import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
5
+ import { getUsageLedger } from "../usage/ledger.js";
6
+ import { parseUsageMode, renderUsageReport } from "../usage/render.js";
7
+ import { handleProjectCommand } from "./project-commands.js";
8
+ import { handleSkillsCommand } from "./skill-commands.js";
9
+ import { handleSubagentsCommand } from "./subagent-commands.js";
10
+ import { handleTasksCommand } from "./task-commands.js";
11
+ export async function runReportCommand(context, name, args) {
12
+ const { channelId, paths } = context;
13
+ const channelDir = getChannelDir(paths.workspaceDir, channelId);
14
+ switch (name) {
15
+ case "events":
16
+ return handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath });
17
+ case "tasks":
18
+ return handleTasksCommand({ args, channelDir, dispatchTask: context.dispatchTask });
19
+ case "status":
20
+ return renderStatus({
21
+ runner: context.peekRunner(),
22
+ version: context.version,
23
+ uptimeMs: Date.now() - context.startedAt,
24
+ });
25
+ case "usage":
26
+ return renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date());
27
+ // Read-only prompt accounting; safe mid-turn.
28
+ case "context":
29
+ return context.getRunner().renderContextReport(args);
30
+ // A human control path independent of the model (spec 040, D6): `/stop` does not kill a
31
+ // dispatched delegation, so cancel must work whether or not a runner is currently active.
32
+ case "subagents":
33
+ return handleSubagentsCommand({
34
+ args,
35
+ runManager: context.runManager,
36
+ channelId,
37
+ discovery: context.peekRunner()?.getSubAgentDiscoverySnapshot(),
38
+ // `roles` needs a role directory even for a channel that has never spoken this boot —
39
+ // resolved from disk, without spinning up a full runner (spec 041).
40
+ getDetachedDiscovery: () => loadDetachedSubAgentDiscovery({
41
+ workspaceDir: paths.workspaceDir,
42
+ authConfigPath: paths.authConfigPath,
43
+ modelsConfigPath: paths.modelsConfigPath,
44
+ }),
45
+ });
46
+ case "project":
47
+ return handleProjectCommand({
48
+ args,
49
+ channelId,
50
+ channelDir,
51
+ appHomeDir: paths.appHomeDir,
52
+ actor: context.actor,
53
+ isBusy: () => context.peekRunner()?.isBusy() ?? false,
54
+ listActiveBlockers: () => [
55
+ ...context.runManager
56
+ .list()
57
+ .filter((record) => record.status === "running")
58
+ .map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
59
+ ...context.runningJobLines(),
60
+ ],
61
+ onScopeChanged: context.onScopeChanged,
62
+ });
63
+ case "skills":
64
+ return handleSkillsCommand({
65
+ args,
66
+ workspaceDir: paths.workspaceDir,
67
+ appHomeDir: paths.appHomeDir,
68
+ channelId,
69
+ });
70
+ }
71
+ }
@@ -184,7 +184,7 @@ async function showRun(manager, ref) {
184
184
  if (record.failureReason)
185
185
  lines.push(`- 失败原因:${record.failureReason}`);
186
186
  if (record.verificationVerdict) {
187
- lines.push(`- 验收结论:${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}${record.verificationStrength === "advisory" ? "(advisory)" : ""}`);
187
+ lines.push(`- 检查结论:${record.verificationVerdict === "pass" ? "PASS" : "FAIL"}`);
188
188
  }
189
189
  lines.push(`- 开始:${new Date(record.startedAt).toLocaleString()}`);
190
190
  if (record.finishedAt)
@@ -3,9 +3,6 @@ export interface HandleTasksCommandOptions {
3
3
  args: string;
4
4
  /** The channel directory; tasks live in `<channelDir>/tasks/`. */
5
5
  channelDir: string;
6
- /** Workspace directory; kept for callers that still pass it (doctor reads task-owned events). */
7
- workspaceDir?: string;
8
- channelId?: string;
9
6
  /** Optional immediate task wake, available in the long-lived DingTalk runtime. */
10
7
  dispatchTask?: (id: string) => Promise<boolean>;
11
8
  }
@@ -17,7 +14,6 @@ type TasksCommand = {
17
14
  } | {
18
15
  action: "log";
19
16
  id: string;
20
- cycle?: string;
21
17
  } | {
22
18
  action: "archive";
23
19
  } | {
@@ -29,9 +25,6 @@ type TasksCommand = {
29
25
  action: "resume";
30
26
  id: string;
31
27
  grants: Partial<TaskBudget>;
32
- } | {
33
- action: "run";
34
- id: string;
35
28
  } | {
36
29
  action: "steer";
37
30
  id: string;
@@ -43,7 +36,6 @@ type TasksCommand = {
43
36
  };
44
37
  /** Exported so `test/commands-subcommands.test.ts` can feed every broadcast example back through it. */
45
38
  export declare function parseTasksCommand(args: string): TasksCommand;
46
- export declare function pauseTask(options: HandleTasksCommandOptions, idInput: string): Promise<string>;
47
39
  export declare function resumeTask(options: HandleTasksCommandOptions, idInput: string, grants?: Partial<TaskBudget>): Promise<string>;
48
40
  export declare function handleTasksCommand(options: HandleTasksCommandOptions): Promise<string>;
49
41
  export {};