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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (272) hide show
  1. package/README.en.md +9 -11
  2. package/README.md +9 -11
  3. package/dist/agent/channel-runner.d.ts +12 -24
  4. package/dist/agent/channel-runner.js +74 -30
  5. package/dist/agent/maintenance-context.d.ts +2 -0
  6. package/dist/agent/maintenance-context.js +15 -0
  7. package/dist/agent/prompt/sections.js +8 -6
  8. package/dist/agent/prompt/types.d.ts +1 -1
  9. package/dist/agent/runner-factory.js +1 -1
  10. package/dist/agent/session/command-extension.js +11 -0
  11. package/dist/agent/session/compaction-summary.js +6 -2
  12. package/dist/agent/session/execution-trace.d.ts +14 -0
  13. package/dist/agent/session/execution-trace.js +57 -0
  14. package/dist/agent/session/session-events.d.ts +2 -7
  15. package/dist/agent/session/session-events.js +35 -12
  16. package/dist/agent/session/session-host.d.ts +12 -22
  17. package/dist/agent/session/session-host.js +46 -65
  18. package/dist/agent/turn/task-digest.d.ts +1 -2
  19. package/dist/agent/turn/task-digest.js +33 -33
  20. package/dist/agent/turn/turn-context.d.ts +1 -1
  21. package/dist/agent/turn/turn-context.js +1 -1
  22. package/dist/agent/turn/turn-finish.d.ts +2 -2
  23. package/dist/agent/turn/turn-finish.js +3 -2
  24. package/dist/agent/turn/turn-pipeline.d.ts +4 -2
  25. package/dist/agent/turn/turn-pipeline.js +33 -5
  26. package/dist/agent/types.d.ts +64 -14
  27. package/dist/agent/types.js +3 -0
  28. package/dist/app/home.js +3 -4
  29. package/dist/channel/channel-event.d.ts +4 -12
  30. package/dist/channel/ingress.d.ts +1 -9
  31. package/dist/channel/store.d.ts +1 -1
  32. package/dist/commands/catalog.js +25 -19
  33. package/dist/commands/router.d.ts +5 -2
  34. package/dist/commands/router.js +9 -4
  35. package/dist/config/settings.d.ts +5 -12
  36. package/dist/config/settings.js +0 -7
  37. package/dist/config/tools.d.ts +2 -2
  38. package/dist/config/tools.js +2 -2
  39. package/dist/dingtalk/bot.d.ts +2 -0
  40. package/dist/dingtalk/bot.js +4 -0
  41. package/dist/dingtalk/cards.d.ts +7 -0
  42. package/dist/dingtalk/cards.js +32 -2
  43. package/dist/dingtalk/delivery.d.ts +5 -1
  44. package/dist/dingtalk/delivery.js +157 -142
  45. package/dist/dingtalk/progress.d.ts +55 -6
  46. package/dist/dingtalk/progress.js +195 -16
  47. package/dist/file-store.d.ts +4 -0
  48. package/dist/file-store.js +6 -1
  49. package/dist/jobs/completion-observer.d.ts +20 -0
  50. package/dist/jobs/completion-observer.js +107 -0
  51. package/dist/jobs/completion-signal.d.ts +9 -0
  52. package/dist/jobs/completion-signal.js +32 -0
  53. package/dist/jobs/completion-wake.d.ts +1 -1
  54. package/dist/jobs/completion-wake.js +2 -13
  55. package/dist/jobs/manager.d.ts +11 -29
  56. package/dist/jobs/manager.js +103 -176
  57. package/dist/jobs/probe.d.ts +3 -0
  58. package/dist/jobs/probe.js +42 -0
  59. package/dist/jobs/record.d.ts +3 -6
  60. package/dist/jobs/runtime.d.ts +28 -0
  61. package/dist/jobs/runtime.js +69 -0
  62. package/dist/memory/boundary-work.d.ts +2 -0
  63. package/dist/memory/boundary-work.js +79 -37
  64. package/dist/memory/commands.js +4 -1
  65. package/dist/memory/index-budget.js +18 -15
  66. package/dist/memory/journal.js +2 -1
  67. package/dist/memory/lifecycle.d.ts +4 -8
  68. package/dist/memory/lifecycle.js +21 -51
  69. package/dist/memory/reflect-job.d.ts +0 -6
  70. package/dist/memory/reflect-job.js +13 -34
  71. package/dist/memory/reflect.d.ts +4 -0
  72. package/dist/memory/reflect.js +32 -5
  73. package/dist/memory/review-log.d.ts +13 -0
  74. package/dist/memory/review-log.js +49 -0
  75. package/dist/memory/search.js +7 -4
  76. package/dist/memory/source-window.d.ts +18 -1
  77. package/dist/memory/source-window.js +59 -9
  78. package/dist/memory/store.d.ts +2 -0
  79. package/dist/memory/store.js +45 -13
  80. package/dist/playbooks/agent-delegation.md +10 -4
  81. package/dist/playbooks/background-jobs.md +4 -4
  82. package/dist/playbooks/event-scheduling.md +2 -2
  83. package/dist/playbooks/memory-and-learning.md +3 -3
  84. package/dist/playbooks/outbound-media.md +2 -2
  85. package/dist/playbooks/runtime-orientation.md +10 -6
  86. package/dist/playbooks/task-lead.md +54 -33
  87. package/dist/runtime/bootstrap.d.ts +11 -24
  88. package/dist/runtime/bootstrap.js +92 -59
  89. package/dist/runtime/channel-queue.d.ts +2 -0
  90. package/dist/runtime/channel-queue.js +5 -1
  91. package/dist/runtime/durable-dispatch.d.ts +7 -0
  92. package/dist/runtime/durable-dispatch.js +66 -7
  93. package/dist/runtime/ingress-busy.d.ts +1 -2
  94. package/dist/runtime/ingress-busy.js +2 -35
  95. package/dist/runtime/ingress-commands.d.ts +1 -1
  96. package/dist/runtime/ingress-commands.js +28 -20
  97. package/dist/runtime/ingress-deps.d.ts +4 -7
  98. package/dist/runtime/ingress.js +23 -13
  99. package/dist/runtime/shutdown.d.ts +1 -1
  100. package/dist/runtime/shutdown.js +2 -2
  101. package/dist/runtime/task-close.d.ts +4 -0
  102. package/dist/runtime/task-close.js +102 -0
  103. package/dist/runtime/task-control.d.ts +34 -0
  104. package/dist/runtime/task-control.js +225 -0
  105. package/dist/runtime/task-input.d.ts +13 -0
  106. package/dist/runtime/task-input.js +129 -0
  107. package/dist/runtime/task-lane-types.d.ts +123 -0
  108. package/dist/runtime/task-lane-types.js +14 -0
  109. package/dist/runtime/task-lane.d.ts +99 -0
  110. package/dist/runtime/task-lane.js +703 -0
  111. package/dist/runtime/task-pending.d.ts +8 -0
  112. package/dist/runtime/task-pending.js +40 -0
  113. package/dist/runtime/task-spawn.d.ts +4 -4
  114. package/dist/runtime/task-spawn.js +4 -4
  115. package/dist/runtime/task-step.d.ts +32 -0
  116. package/dist/runtime/task-step.js +276 -0
  117. package/dist/runtime/turn-run.d.ts +4 -16
  118. package/dist/runtime/turn-run.js +17 -155
  119. package/dist/runtime/wake-coalescing.d.ts +1 -3
  120. package/dist/runtime/wake-coalescing.js +2 -4
  121. package/dist/shared/format.d.ts +0 -6
  122. package/dist/shared/format.js +0 -17
  123. package/dist/shared/host-process.d.ts +2 -0
  124. package/dist/shared/host-process.js +16 -1
  125. package/dist/shared/jsonl-appender.d.ts +5 -0
  126. package/dist/shared/jsonl-appender.js +25 -2
  127. package/dist/skills/catalog.d.ts +9 -0
  128. package/dist/skills/catalog.js +34 -0
  129. package/dist/skills/commands.d.ts +3 -12
  130. package/dist/skills/commands.js +36 -22
  131. package/dist/skills/loader.d.ts +2 -31
  132. package/dist/skills/loader.js +101 -68
  133. package/dist/skills/roots.d.ts +12 -0
  134. package/dist/skills/roots.js +18 -0
  135. package/dist/skills/types.d.ts +24 -0
  136. package/dist/skills/types.js +1 -0
  137. package/dist/subagents/completion-wake.js +0 -10
  138. package/dist/subagents/discovery.d.ts +1 -1
  139. package/dist/subagents/discovery.js +10 -16
  140. package/dist/subagents/dispatch.js +8 -16
  141. package/dist/subagents/external/cursor-cli.d.ts +2 -0
  142. package/dist/subagents/external/cursor-cli.js +256 -0
  143. package/dist/subagents/external/harness.d.ts +5 -5
  144. package/dist/subagents/external/reconciliation.d.ts +7 -0
  145. package/dist/subagents/external/reconciliation.js +105 -0
  146. package/dist/subagents/external/recovery.d.ts +20 -0
  147. package/dist/subagents/external/recovery.js +71 -0
  148. package/dist/subagents/external/registry.js +2 -0
  149. package/dist/subagents/external/role-warnings.d.ts +17 -0
  150. package/dist/subagents/external/role-warnings.js +42 -0
  151. package/dist/subagents/external/run.js +18 -22
  152. package/dist/subagents/format.d.ts +1 -1
  153. package/dist/subagents/format.js +1 -1
  154. package/dist/subagents/grace.d.ts +2 -2
  155. package/dist/subagents/grace.js +3 -3
  156. package/dist/subagents/internal/run.js +7 -5
  157. package/dist/subagents/internal/worker.js +31 -2
  158. package/dist/subagents/result.js +2 -3
  159. package/dist/subagents/run-record.d.ts +4 -7
  160. package/dist/subagents/run-record.js +2 -2
  161. package/dist/subagents/runs.d.ts +33 -46
  162. package/dist/subagents/runs.js +126 -245
  163. package/dist/subagents/task-settlement.d.ts +3 -0
  164. package/dist/subagents/task-settlement.js +20 -0
  165. package/dist/subagents/types.d.ts +1 -2
  166. package/dist/subagents/workspace-summary.js +5 -1
  167. package/dist/tasks/archive.d.ts +11 -0
  168. package/dist/tasks/archive.js +141 -0
  169. package/dist/tasks/board.d.ts +5 -12
  170. package/dist/tasks/board.js +4 -30
  171. package/dist/tasks/bound-work.d.ts +12 -6
  172. package/dist/tasks/bound-work.js +37 -24
  173. package/dist/tasks/brief.d.ts +38 -14
  174. package/dist/tasks/brief.js +128 -70
  175. package/dist/tasks/budget.d.ts +3 -3
  176. package/dist/tasks/budget.js +9 -4
  177. package/dist/tasks/commands.d.ts +14 -9
  178. package/dist/tasks/commands.js +190 -121
  179. package/dist/tasks/completion.d.ts +12 -0
  180. package/dist/tasks/completion.js +35 -0
  181. package/dist/tasks/contract.d.ts +8 -17
  182. package/dist/tasks/contract.js +41 -43
  183. package/dist/tasks/control.d.ts +138 -0
  184. package/dist/tasks/control.js +1 -0
  185. package/dist/tasks/create.d.ts +1 -1
  186. package/dist/tasks/create.js +3 -3
  187. package/dist/tasks/delivery.d.ts +24 -0
  188. package/dist/tasks/delivery.js +221 -0
  189. package/dist/tasks/file-mutation.d.ts +5 -0
  190. package/dist/tasks/file-mutation.js +38 -0
  191. package/dist/tasks/frontmatter.d.ts +43 -28
  192. package/dist/tasks/frontmatter.js +83 -40
  193. package/dist/tasks/input-receipts.d.ts +7 -0
  194. package/dist/tasks/input-receipts.js +60 -0
  195. package/dist/tasks/loop-log.d.ts +147 -28
  196. package/dist/tasks/loop-log.js +239 -28
  197. package/dist/tasks/receipts.d.ts +19 -0
  198. package/dist/tasks/receipts.js +48 -0
  199. package/dist/tasks/state.d.ts +93 -0
  200. package/dist/tasks/state.js +156 -0
  201. package/dist/tasks/store.d.ts +81 -49
  202. package/dist/tasks/store.js +244 -147
  203. package/dist/tools/bash.d.ts +3 -5
  204. package/dist/tools/bash.js +8 -22
  205. package/dist/tools/contract/details.d.ts +6 -6
  206. package/dist/tools/contract/details.js +6 -6
  207. package/dist/tools/contract/execution-trace.d.ts +4 -0
  208. package/dist/tools/contract/execution-trace.js +23 -0
  209. package/dist/tools/contract/presentation.js +6 -2
  210. package/dist/tools/edit.d.ts +1 -0
  211. package/dist/tools/edit.js +45 -42
  212. package/dist/tools/index.d.ts +8 -12
  213. package/dist/tools/index.js +16 -6
  214. package/dist/tools/memory-manage.js +8 -1
  215. package/dist/tools/registry.d.ts +7 -11
  216. package/dist/tools/registry.js +52 -25
  217. package/dist/tools/skill.d.ts +2 -2
  218. package/dist/tools/skill.js +24 -10
  219. package/dist/tools/subagent-manage.js +7 -4
  220. package/dist/tools/subagent.d.ts +0 -2
  221. package/dist/tools/subagent.js +2 -7
  222. package/dist/tools/task-manage/control-tools.d.ts +4 -0
  223. package/dist/tools/task-manage/control-tools.js +65 -0
  224. package/dist/tools/task-manage/create.js +2 -1
  225. package/dist/tools/task-manage/factory.d.ts +12 -6
  226. package/dist/tools/task-manage/factory.js +72 -57
  227. package/dist/tools/task-manage/lifecycle.d.ts +7 -12
  228. package/dist/tools/task-manage/lifecycle.js +118 -66
  229. package/dist/tools/task-manage/log-view.js +8 -5
  230. package/dist/tools/task-manage/schema.d.ts +21 -26
  231. package/dist/tools/task-manage/schema.js +29 -35
  232. package/dist/tools/task-manage/shared.d.ts +8 -39
  233. package/dist/tools/task-manage/shared.js +19 -68
  234. package/dist/tools/task-manage/step-tools.d.ts +5 -0
  235. package/dist/tools/task-manage/step-tools.js +103 -0
  236. package/dist/tools/task-manage/types.d.ts +25 -18
  237. package/dist/tools/write-content.d.ts +1 -0
  238. package/dist/tools/write-content.js +6 -1
  239. package/dist/tools/write.d.ts +1 -0
  240. package/dist/tools/write.js +1 -0
  241. package/dist/usage/ledger.d.ts +4 -4
  242. package/dist/usage/render.js +2 -2
  243. package/dist/web/search-providers.js +0 -33
  244. package/dist/webapi/request-policy.js +1 -1
  245. package/examples/sub-agents/README.md +23 -16
  246. package/examples/sub-agents/agents/claude-high.md +1 -1
  247. package/examples/sub-agents/agents/claude-main.md +1 -1
  248. package/examples/sub-agents/agents/codex-flash.md +1 -1
  249. package/examples/sub-agents/agents/codex-high.md +1 -1
  250. package/examples/sub-agents/agents/codex-main.md +4 -4
  251. package/examples/sub-agents/agents/cursor-high.md +22 -0
  252. package/examples/sub-agents/agents/cursor-main.md +22 -0
  253. package/examples/sub-agents/agents/glm-flash.md +1 -1
  254. package/examples/sub-agents/agents/glm-high.md +2 -2
  255. package/examples/sub-agents/agents/scout.md +30 -0
  256. package/package.json +6 -6
  257. package/dist/runtime/task-driver.d.ts +0 -116
  258. package/dist/runtime/task-driver.js +0 -443
  259. package/dist/runtime/task-wake.d.ts +0 -48
  260. package/dist/runtime/task-wake.js +0 -32
  261. package/dist/shared/wake-claim.d.ts +0 -23
  262. package/dist/shared/wake-claim.js +0 -26
  263. package/dist/skills/validation.d.ts +0 -8
  264. package/dist/skills/validation.js +0 -91
  265. package/dist/skills/workspace.d.ts +0 -33
  266. package/dist/skills/workspace.js +0 -116
  267. package/dist/tasks/steer.d.ts +0 -8
  268. package/dist/tasks/steer.js +0 -81
  269. package/dist/tasks/ticket.d.ts +0 -71
  270. package/dist/tasks/ticket.js +0 -138
  271. package/dist/tools/task-manage/step-end.d.ts +0 -11
  272. package/dist/tools/task-manage/step-end.js +0 -117
@@ -0,0 +1,8 @@
1
+ import type { TaskPendingWork } from "../tasks/control.js";
2
+ import type { TaskLaneOptions } from "./task-lane-types.js";
3
+ /**
4
+ * Delegations and background jobs bound to a task and not yet settled — the facts a task's wait
5
+ * is derived from (spec 064, D8/INV-4). Read from the run and job managers, which also own each
6
+ * one's hard deadline.
7
+ */
8
+ export declare function listPendingWork(options: Pick<TaskLaneOptions, "getRuns" | "getJobs">, desk: string, now: number, withActivity?: boolean): Promise<Map<string, TaskPendingWork[]>>;
@@ -0,0 +1,40 @@
1
+ import { readLastOutputAt, STALL_THRESHOLD_MS } from "../subagents/external/progress-tail.js";
2
+ /**
3
+ * Delegations and background jobs bound to a task and not yet settled — the facts a task's wait
4
+ * is derived from (spec 064, D8/INV-4). Read from the run and job managers, which also own each
5
+ * one's hard deadline.
6
+ */
7
+ export async function listPendingWork(options, desk, now, withActivity = false) {
8
+ const byTask = new Map();
9
+ await options.getRuns(desk).retryTaskSettlements?.();
10
+ const add = (taskId, work) => {
11
+ const list = byTask.get(taskId);
12
+ if (list)
13
+ list.push(work);
14
+ else
15
+ byTask.set(taskId, [work]);
16
+ };
17
+ for (const run of options.getRuns(desk).list()) {
18
+ if (!run.taskId || run.settledAt !== undefined)
19
+ continue;
20
+ let lastOutputAt;
21
+ if (withActivity && run.runtime === "external")
22
+ lastOutputAt = await readLastOutputAt(run.artifactDir);
23
+ const quietSince = lastOutputAt ?? run.processStartedAt ?? run.startedAt;
24
+ add(run.taskId, {
25
+ ref: run.runId,
26
+ kind: "delegation",
27
+ label: run.agent,
28
+ startedAt: run.startedAt,
29
+ ...(lastOutputAt !== undefined ? { lastOutputAt } : {}),
30
+ stalled: run.runtime === "external" && withActivity && now - quietSince >= STALL_THRESHOLD_MS,
31
+ });
32
+ }
33
+ const jobs = await options.getJobs(desk).list();
34
+ for (const job of jobs) {
35
+ if (!job.taskId || job.status !== "running")
36
+ continue;
37
+ add(job.taskId, { ref: job.id, kind: "job", label: job.label, startedAt: job.startedAt, stalled: false });
38
+ }
39
+ return byTask;
40
+ }
@@ -2,8 +2,8 @@ import type { SpawnTaskRequest, SpawnTaskResult } from "../events/types.js";
2
2
  export interface TaskSpawnerOptions {
3
3
  /** The event's desk directory: the instance is created in its `tasks/`. */
4
4
  getDeskDir: (desk: string) => string;
5
- /** Wake the driver so the new instance's first step is queued promptly. */
6
- nudge: () => void;
5
+ /** Tell the task lane so the new instance is admitted promptly. */
6
+ wake: () => void;
7
7
  /** Direct, non-LLM receipt to the event's channel, through the desk's binding guard (D7). */
8
8
  notify: (desk: string, channelId: string, text: string) => Promise<unknown>;
9
9
  }
@@ -18,7 +18,7 @@ export interface TaskSpawnerOptions {
18
18
  * A second instance of the same event never runs alongside the first: two copies of the same
19
19
  * recurring job mostly duplicate work or collide. The occurrence is skipped and the user is told
20
20
  * every time (INV-7) — a stuck instance is something they need to know about, not something to
21
- * hide behind a quiet skip. The stuck instance itself is bounded by its budget, idle detection and
22
- * ticket backstops, so the skipping cannot go on forever.
21
+ * hide behind a quiet skip. The stuck instance itself is bounded by its budget and the lane's
22
+ * guards, so the skipping cannot go on forever.
23
23
  */
24
24
  export declare function createTaskSpawner(options: TaskSpawnerOptions): (request: SpawnTaskRequest) => Promise<SpawnTaskResult>;
@@ -15,8 +15,8 @@ import { archivedTaskPath, taskPath, tasksDir } from "../tasks/store.js";
15
15
  * A second instance of the same event never runs alongside the first: two copies of the same
16
16
  * recurring job mostly duplicate work or collide. The occurrence is skipped and the user is told
17
17
  * every time (INV-7) — a stuck instance is something they need to know about, not something to
18
- * hide behind a quiet skip. The stuck instance itself is bounded by its budget, idle detection and
19
- * ticket backstops, so the skipping cannot go on forever.
18
+ * hide behind a quiet skip. The stuck instance itself is bounded by its budget and the lane's
19
+ * guards, so the skipping cannot go on forever.
20
20
  */
21
21
  export function createTaskSpawner(options) {
22
22
  return async (request) => {
@@ -27,7 +27,7 @@ export function createTaskSpawner(options) {
27
27
  }
28
28
  const active = (await readActiveTasks(tasksDir(deskDir))).find((entry) => entry.fields.origin === request.eventName && !entry.fields.outcome);
29
29
  if (active) {
30
- const state = `${taskStateLabel(active.fields.state)}${active.fields.paused ? ",已暂停" : ""}`;
30
+ const state = taskStateLabel(active.fields);
31
31
  await options
32
32
  .notify(request.desk, request.channelId, `⚠️ 周期任务 \`${request.eventName}\` 本次(${instanceStamp(request.occurrence)})未启动:上一个实例 \`${active.id}\` 仍未结束(${state})。\n查看:\`/tasks show ${active.id}\``)
33
33
  .catch((error) => {
@@ -51,7 +51,7 @@ export function createTaskSpawner(options) {
51
51
  channelId: request.channelId,
52
52
  fields: { event: request.eventName, taskId: id },
53
53
  });
54
- options.nudge();
54
+ options.wake();
55
55
  return { outcome: "spawned", id };
56
56
  };
57
57
  }
@@ -0,0 +1,32 @@
1
+ import { type AgentRunner } from "../agent/types.js";
2
+ import type { TaskStepIntent } from "../tasks/control.js";
3
+ import { type TaskStepResult } from "../tasks/loop-log.js";
4
+ import type { StepDerivation } from "../tasks/state.js";
5
+ import { type EndedStep } from "../tasks/store.js";
6
+ import type { LaneContext, LiveTask, StepAbort } from "./task-lane-types.js";
7
+ /** The task's runner, built on first use and kept until the task leaves execution (D13). */
8
+ export declare function ensureRunner(ctx: LaneContext, live: LiveTask): AgentRunner;
9
+ /** Stop the running step: the turn is asked to end, and the abort cuts a tool that would not. */
10
+ export declare function abortStep(ctx: LaneContext, live: LiveTask, reason: StepAbort): void;
11
+ /** What a finished step tells the drive loop. */
12
+ export type StepReport =
13
+ /** The task is gone, or was paused or moved to a wait since the lane decided to run it: nothing ran. */
14
+ {
15
+ kind: "skipped";
16
+ }
17
+ /** The process is stopping: the step's `step_end` is written by the next start's reconciliation (D10). */
18
+ | {
19
+ kind: "interrupted";
20
+ } | {
21
+ kind: "ended";
22
+ result: TaskStepResult;
23
+ ended: EndedStep | undefined;
24
+ derivation: StepDerivation;
25
+ intent: TaskStepIntent;
26
+ };
27
+ /**
28
+ * One step (spec 064, D14): write the `step` record, build the brief, run the turn in the task's
29
+ * own session with a time limit, and write what happened. The state that follows is derived from the
30
+ * step's facts inside `endStep`, not declared by the model (INV-2).
31
+ */
32
+ export declare function executeStep(ctx: LaneContext, live: LiveTask): Promise<StepReport>;
@@ -0,0 +1,276 @@
1
+ import { clipUserInput } from "../agent/turn/progress-formatter.js";
2
+ import { MAX_USER_MESSAGE_CHARS } from "../agent/types.js";
3
+ import * as log from "../log.js";
4
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
5
+ import { errorMessage } from "../shared/text-utils.js";
6
+ import { BRIEF_INPUT_LIMIT, buildTaskStepBrief, contractOpenTag, contractSha, } from "../tasks/brief.js";
7
+ import { taskReportDelivered } from "../tasks/completion.js";
8
+ import { drainTaskDeliveries, queueTaskReport } from "../tasks/delivery.js";
9
+ import { acknowledgeTaskInputs, taskInputTag } from "../tasks/input-receipts.js";
10
+ import { readTaskLog } from "../tasks/loop-log.js";
11
+ import { beginStep, endStep, pauseTask, readStoredTask } from "../tasks/store.js";
12
+ import { listPendingWork } from "./task-pending.js";
13
+ /** A task step speaks to nobody: only `task_report`, `task_ask` and the lane's receipts reach a channel (INV-1). */
14
+ const SILENT_CONTEXT = { emit: () => undefined, finish: async () => undefined };
15
+ /** The task session's view of its lane: which step is running and where it reports. */
16
+ function sessionContextOf(ctx, live) {
17
+ const assertActive = () => {
18
+ if (!live.step || live.step.abort || live.quarantined || ctx.isStopped())
19
+ throw new RecoverableToolError("This task step has stopped. End the turn; the runtime will preserve its pending inputs.");
20
+ };
21
+ return {
22
+ assertActive,
23
+ taskId: live.taskId,
24
+ seq: () => {
25
+ assertActive();
26
+ return live.seq;
27
+ },
28
+ intent: () => {
29
+ assertActive();
30
+ return live.intent;
31
+ },
32
+ report: async (text) => {
33
+ assertActive();
34
+ const message = await queueTaskReport(live.deskDir, live.taskId, live.seq, live.channelId, text);
35
+ await drainTaskDeliveries(live.deskDir, (channel, text) => ctx.options.deliver(live.desk, channel, text), (channel) => ctx.options.isBoundTo(channel, live.desk) && ctx.options.isReachable(channel), ctx.now());
36
+ ctx.notify();
37
+ return {
38
+ id: message.id,
39
+ delivered: taskReportDelivered(await readTaskLog(live.deskDir, live.taskId), message.id),
40
+ };
41
+ },
42
+ };
43
+ }
44
+ /** The task's runner, built on first use and kept until the task leaves execution (D13). */
45
+ export function ensureRunner(ctx, live) {
46
+ if (live.runner)
47
+ return live.runner;
48
+ live.runner = ctx.options.createTaskRunner({
49
+ desk: live.desk,
50
+ deskDir: live.deskDir,
51
+ taskId: live.taskId,
52
+ channelId: live.channelId,
53
+ session: sessionContextOf(ctx, live),
54
+ });
55
+ return live.runner;
56
+ }
57
+ /** Stop the running step: the turn is asked to end, and the abort cuts a tool that would not. */
58
+ export function abortStep(ctx, live, reason) {
59
+ const step = live.step;
60
+ if (!step || step.abort)
61
+ return;
62
+ step.abort = reason;
63
+ const runner = live.runner;
64
+ if (!runner)
65
+ return;
66
+ runner.requestStop();
67
+ if (reason !== "shutdown") {
68
+ step.stopTimer = setTimeout(() => {
69
+ if (live.step !== step)
70
+ return;
71
+ live.quarantined = true;
72
+ runner.retireForRecovery();
73
+ void pauseTask(live.deskDir, live.taskId, {
74
+ by: "runtime",
75
+ reason: "当前步骤未能停止,请联系部署者重启服务后再恢复任务",
76
+ })
77
+ .then(async () => {
78
+ await ctx.options.deliver(live.desk, live.channelId, `⚠️ 任务 \`${live.taskId}\` 的当前步骤未能停止,已暂停后续执行。请联系部署者重启服务,再用 \`/tasks resume ${live.taskId}\` 恢复。`);
79
+ })
80
+ .catch((error) => log.logWarn("tasks.step.quarantine_failed", "Task step quarantine failed", {
81
+ reason: errorMessage(error),
82
+ fields: { taskId: live.taskId, desk: live.desk },
83
+ }));
84
+ }, ctx.timing.stopGraceMs);
85
+ step.stopTimer.unref?.();
86
+ }
87
+ void runner.abort().catch((error) => {
88
+ log.logWarn("tasks.step.abort_failed", "Task step abort failed", {
89
+ channelId: live.channelId,
90
+ reason: errorMessage(error),
91
+ fields: { taskId: live.taskId, desk: live.desk },
92
+ });
93
+ });
94
+ }
95
+ function notifyStep(ctx, event) {
96
+ try {
97
+ ctx.options.onStep?.(event);
98
+ }
99
+ catch (error) {
100
+ log.logWarn("tasks.step.observer_failed", "Task step observer failed", { reason: errorMessage(error) });
101
+ }
102
+ }
103
+ /**
104
+ * One step (spec 064, D14): write the `step` record, build the brief, run the turn in the task's
105
+ * own session with a time limit, and write what happened. The state that follows is derived from the
106
+ * step's facts inside `endStep`, not declared by the model (INV-2).
107
+ */
108
+ export async function executeStep(ctx, live) {
109
+ const { options } = ctx;
110
+ const document = await readStoredTask(live.deskDir, live.taskId);
111
+ if (!document || document.fields.outcome)
112
+ return { kind: "skipped" };
113
+ await acknowledgeTaskInputs(live.deskDir, live.taskId);
114
+ const runner = ensureRunner(ctx, live);
115
+ // Whether the session still holds the current contract is read from the session itself, so a
116
+ // compaction that dropped it, or an edit that changed it, brings the full brief back (D15).
117
+ const full = !(await runner.contextIncludes(contractOpenTag(live.taskId, contractSha(document.body))));
118
+ const begun = await beginStep(live.deskDir, live.taskId, {
119
+ brief: full ? "full" : "delta",
120
+ allowed: (fields) => !ctx.isStopped() &&
121
+ options.isEnabled?.() !== false &&
122
+ !!fields.channel &&
123
+ options.isBoundTo(fields.channel, live.desk) &&
124
+ options.isReachable(fields.channel),
125
+ });
126
+ if (!begun)
127
+ return { kind: "skipped" };
128
+ live.seq = begun.seq;
129
+ live.intent = { reports: 0 };
130
+ const now = ctx.now();
131
+ const pendingMap = await listPendingWork(options, live.desk, now);
132
+ const pending = (pendingMap.get(live.taskId) ?? []).map((work) => ({
133
+ ref: work.ref,
134
+ label: work.label,
135
+ runningMs: now - work.startedAt,
136
+ }));
137
+ const brief = await buildTaskStepBrief({
138
+ deskDir: live.deskDir,
139
+ document: begun.document,
140
+ seq: begun.seq,
141
+ records: begun.records,
142
+ inputs: begun.inputs,
143
+ full,
144
+ pending,
145
+ now,
146
+ });
147
+ const visibleBrief = clipUserInput(brief.text, MAX_USER_MESSAGE_CHARS);
148
+ const step = {
149
+ seq: begun.seq,
150
+ startedAt: now,
151
+ submittedInputIds: new Set(begun.inputs
152
+ .slice(-BRIEF_INPUT_LIMIT)
153
+ .flatMap((input) => (input.id && visibleBrief.includes(taskInputTag(input.id)) ? [input.id] : []))),
154
+ };
155
+ live.step = step;
156
+ step.timer = setTimeout(() => abortStep(ctx, live, "timeout"), ctx.timing.stepTimeLimitMs);
157
+ step.timer.unref?.();
158
+ const info = {
159
+ channelId: live.channelId,
160
+ user: "TASK",
161
+ userName: "TASK",
162
+ text: brief.text,
163
+ ts: String(now),
164
+ };
165
+ notifyStep(ctx, { phase: "started", desk: live.desk, taskId: live.taskId, seq: begun.seq });
166
+ log.logInfoEvent("tasks.step.started", "Task step started", {
167
+ channelId: live.channelId,
168
+ fields: {
169
+ taskId: live.taskId,
170
+ desk: live.desk,
171
+ seq: begun.seq,
172
+ reason: begun.reason,
173
+ brief: full ? "full" : "delta",
174
+ },
175
+ });
176
+ let result = "ok";
177
+ let error;
178
+ let finalText = "";
179
+ let toolsUsed = [];
180
+ let usd = 0;
181
+ let usdEstimated = false;
182
+ let usdKnown = false;
183
+ try {
184
+ const running = runner.run(info, SILENT_CONTEXT, options.store);
185
+ ctx.inputAvailable(live.desk, live.taskId);
186
+ const run = await running;
187
+ finalText = run.finalText ?? "";
188
+ toolsUsed = run.toolsUsed ?? [];
189
+ usd = run.assistantCost?.usd ?? 0;
190
+ usdEstimated = run.assistantCost?.estimated === true;
191
+ usdKnown = run.assistantCost?.known ?? run.costKnown ?? run.assistantCost !== undefined;
192
+ if (run.stopReason === "error") {
193
+ result = "error";
194
+ error = run.errorMessage;
195
+ }
196
+ else if (run.stopReason === "aborted") {
197
+ result = "aborted";
198
+ }
199
+ }
200
+ catch (cause) {
201
+ result = "error";
202
+ error = errorMessage(cause);
203
+ }
204
+ finally {
205
+ if (step.timer)
206
+ clearTimeout(step.timer);
207
+ if (step.stopTimer)
208
+ clearTimeout(step.stopTimer);
209
+ }
210
+ step.ending = true;
211
+ await step.submitting;
212
+ // Only this task step can own the SDK queue here; the next step has not started.
213
+ runner.clearTaskStepQueue?.(step.seq);
214
+ await acknowledgeTaskInputs(live.deskDir, live.taskId, {
215
+ desk: live.desk,
216
+ seq: step.seq,
217
+ generation: runner.generation,
218
+ });
219
+ live.step = undefined;
220
+ // A stop from the lane decides the result whatever the turn reported on its way out.
221
+ switch (step.abort) {
222
+ case "shutdown":
223
+ return { kind: "interrupted" };
224
+ case "timeout":
225
+ result = "timeout";
226
+ break;
227
+ case "pause":
228
+ case "cancel":
229
+ result = "aborted";
230
+ break;
231
+ case undefined:
232
+ break;
233
+ }
234
+ // The leader's intent counts only if the step went well: a step that failed or was cut off
235
+ // did not finish what it started, so it is re-run rather than half-believed.
236
+ const intent = live.intent;
237
+ const honoured = result === "ok";
238
+ const ended = await endStep(live.deskDir, live.taskId, {
239
+ seq: begun.seq,
240
+ result,
241
+ note: finalText.trim() || "(无)",
242
+ tools: toolsUsed,
243
+ usd,
244
+ usdEstimated,
245
+ usdKnown,
246
+ ...(error ? { error } : {}),
247
+ ...(honoured && intent.close ? { close: intent.close } : {}),
248
+ facts: {
249
+ result,
250
+ closed: honoured && intent.close !== undefined,
251
+ pausedByUser: step.abort === "pause" || step.abort === "cancel" || live.quarantined === true,
252
+ ...(honoured && intent.ask ? { asked: intent.ask } : {}),
253
+ ...(honoured && intent.waitUntil ? { waitUntil: intent.waitUntil } : {}),
254
+ pendingWork: (await listPendingWork(options, live.desk, ctx.now())).get(live.taskId)?.length ?? 0,
255
+ },
256
+ });
257
+ notifyStep(ctx, {
258
+ phase: "ended",
259
+ desk: live.desk,
260
+ taskId: live.taskId,
261
+ seq: begun.seq,
262
+ result,
263
+ ...(ended ? { next: ended.derivation.next } : {}),
264
+ });
265
+ log.logInfoEvent("tasks.step.ended", "Task step ended", {
266
+ channelId: live.channelId,
267
+ fields: { taskId: live.taskId, desk: live.desk, seq: begun.seq, result, next: ended?.derivation.next },
268
+ });
269
+ return {
270
+ kind: "ended",
271
+ result,
272
+ ended,
273
+ derivation: ended?.derivation ?? { next: "continue", state: "queued", keepSlot: false },
274
+ intent,
275
+ };
276
+ }
@@ -1,18 +1,15 @@
1
1
  /**
2
2
  * One turn of the daemon's per-channel pipeline (what a channel queue runs for each item): dispatch
3
- * admission, built-in commands, wake verification, the agent run — as a task step when the wake is
4
- * one — and the settle-and-release epilogue that runs whatever happens.
3
+ * admission, built-in commands, the agent run, and the settle-and-release epilogue that runs
4
+ * whatever happens. Task steps never come through here — they run in the task lane (spec 064).
5
5
  */
6
6
  import type { AgentRunner } from "../agent/types.js";
7
- import type { BootstrapPaths } from "../app/home.js";
8
7
  import { type ChannelEvent, type WakeEvent } from "../channel/channel-event.js";
9
8
  import type { ChannelStore } from "../channel/store.js";
10
9
  import { type RuntimeCommandName } from "../commands/catalog.js";
11
- import type { JobRuntime } from "../jobs/manager.js";
12
- import type { SubAgentRuntime } from "../subagents/run-registry.js";
10
+ import type { TaskControl } from "../tasks/control.js";
13
11
  import { type ChannelResolution } from "./desk-runtime.js";
14
12
  import type { DurableDispatchService } from "./durable-dispatch.js";
15
- import type { WakeTaskTransitionHooks } from "./task-wake.js";
16
13
  import type { TransportRegistry } from "./transports.js";
17
14
  /** A wake from an in-process producer rather than a person (spec 061, D8: the event's `source`). */
18
15
  export declare function isSyntheticEvent(event: ChannelEvent): event is WakeEvent;
@@ -29,11 +26,6 @@ export interface ArchivedMessage {
29
26
  images?: string[];
30
27
  }
31
28
  export interface EventTurnDeps {
32
- options: {
33
- paths: BootstrapPaths;
34
- /** Test-only fault seams for the atomic structured-wake task transition. */
35
- wakeTransitionHooks?: Partial<Record<"job" | "subagent", WakeTaskTransitionHooks>>;
36
- };
37
29
  transports: TransportRegistry;
38
30
  store: ChannelStore;
39
31
  activeTasks: Set<Promise<void>>;
@@ -46,11 +38,7 @@ export interface EventTurnDeps {
46
38
  reservedTurns: WeakSet<ChannelEvent>;
47
39
  isShuttingDown: () => boolean;
48
40
  getDurableDispatch: () => DurableDispatchService | undefined;
49
- getJobs: () => JobRuntime;
50
- getRuns: () => SubAgentRuntime;
51
- getTaskDriver: () => {
52
- nudge?(): void;
53
- };
41
+ getTaskControl: () => TaskControl | undefined;
54
42
  /** The handler's `runRuntimeCommand`, for stateless reports typed on an idle channel. */
55
43
  runRuntimeCommand: (event: ChannelEvent, name: RuntimeCommandName, args: string) => Promise<string>;
56
44
  }