@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
@@ -1,20 +1,199 @@
1
- function sanitizeProgressText(text) {
2
- return text.replace(//g, "").replace(/\r/g, "").trim();
1
+ /**
2
+ * Text for the live DingTalk progress card.
3
+ *
4
+ * A live update is one complete markdown list (`isFull: true`) or one extra list item
5
+ * (`isFull: false`). The configured template accepts both. Each request stays within
6
+ * {@link CARD_REQUEST_MAX_BYTES}. Once the next item would carry the card past
7
+ * {@link CARD_DOCUMENT_MAX_BYTES}, the card is replaced by a short snapshot and appending resumes.
8
+ * Dynamic text is made markdown-inert first, and every line is finished before it is cut.
9
+ */
10
+ export const CARD_REQUEST_MAX_BYTES = 1000;
11
+ export const CARD_DOCUMENT_MAX_BYTES = 2900;
12
+ export const CARD_COMPACT_MAX_BYTES = 200;
13
+ const LINE_BYTES = 180;
14
+ const ELLIPSIS = "…";
15
+ /**
16
+ * Make one line of model or tool text safe to drop into a markdown list.
17
+ *
18
+ * Fences, backticks, links and angle brackets are rewritten because cutting one in half leaves
19
+ * the document unfinished. A run of emphasis markers (`**`, `__`) is split with a zero-width
20
+ * space so it cannot open a span; a single `*` or `_` stays, which keeps globs and file names.
21
+ */
22
+ function inert(text) {
23
+ return text
24
+ .replace(//g, "")
25
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, "")
26
+ .replace(/\r/g, "")
27
+ .replace(/\s+/g, " ")
28
+ .replace(/```/g, "")
29
+ .replace(/`/g, "'")
30
+ .replace(/\[/g, "[")
31
+ .replace(/\]/g, "]")
32
+ .replace(/\\/g, "\")
33
+ .replace(/</g, "<")
34
+ .replace(/>/g, ">")
35
+ .replace(/([*_~])\1+/g, (run) => [...run].join("\u200b"))
36
+ .trim();
3
37
  }
4
- /** `""` when there is nothing to show. */
5
- export function formatProgressEntry(kind, text) {
6
- const cleaned = sanitizeProgressText(text);
7
- if (!cleaned)
38
+ function byteLength(text) {
39
+ return Buffer.byteLength(text);
40
+ }
41
+ function clip(text, maxBytes, tail) {
42
+ if (byteLength(text) <= maxBytes)
43
+ return text;
44
+ const budget = maxBytes - byteLength(ELLIPSIS);
45
+ if (budget <= 0)
46
+ return "";
47
+ let kept = "";
48
+ const chars = [...text];
49
+ if (tail) {
50
+ for (let index = chars.length - 1; index >= 0; index--) {
51
+ const next = `${chars[index] ?? ""}${kept}`;
52
+ if (byteLength(next) > budget)
53
+ break;
54
+ kept = next;
55
+ }
56
+ return kept ? `${ELLIPSIS}${kept}` : "";
57
+ }
58
+ for (const char of chars) {
59
+ const next = `${kept}${char}`;
60
+ if (byteLength(next) > budget)
61
+ break;
62
+ kept = next;
63
+ }
64
+ return kept ? `${kept}${ELLIPSIS}` : "";
65
+ }
66
+ function markedLine(marker, text, maxBytes, tail) {
67
+ const body = inert(text);
68
+ if (!body)
69
+ return "";
70
+ const prefix = marker ? `${marker} ` : "";
71
+ const clipped = clip(body, Math.max(0, maxBytes - byteLength(prefix)), tail);
72
+ if (!clipped)
73
+ return "";
74
+ return `${prefix}${clipped}`;
75
+ }
76
+ function listItem(text) {
77
+ return `- ${text}`;
78
+ }
79
+ /** A tight list whose lines cannot leave a fence, link, or emphasis span open. */
80
+ function isCompleteMarkdownList(frame) {
81
+ if (/```|`|\[|\]|\\|[<>]|[*_~]{2}/.test(frame))
82
+ return false;
83
+ const lines = frame.split("\n");
84
+ return lines.length > 0 && lines.every((line) => line.startsWith("- ") && line === line.trim() && line.length > 2);
85
+ }
86
+ /** One list item, sized so a request that prefixes a newline still fits in one update. */
87
+ export function renderProgressLine(activity, maxBytes = CARD_REQUEST_MAX_BYTES - 1) {
88
+ const text = markedLine(activity.marker, activity.text, Math.max(0, maxBytes - 2), activity.tail === true);
89
+ if (!text)
90
+ return "";
91
+ const line = listItem(text);
92
+ if (byteLength(line) > maxBytes || !isCompleteMarkdownList(line))
8
93
  return "";
9
- const normalized = cleaned.replace(/\n+/g, " ").trim();
10
- switch (kind) {
11
- case "tool":
12
- return `➜ ${normalized}`;
13
- case "thinking":
14
- return `✦ ${normalized}`;
15
- case "error":
16
- return `✕ ${normalized}`;
17
- case "assistant":
18
- return normalized;
94
+ return line;
95
+ }
96
+ /**
97
+ * One complete markdown list: a header, the latest thinking excerpt, then the activity window.
98
+ * Lines are dropped whole, then shortened, until the frame fits `maxBytes`.
99
+ */
100
+ export function renderProgressFrame(input) {
101
+ const maxBytes = input.maxBytes ?? CARD_REQUEST_MAX_BYTES;
102
+ const headerLine = listItem(inert(input.header) || "正在处理…");
103
+ let thinkingBudget = Math.min(LINE_BYTES, maxBytes);
104
+ let lineBudget = Math.min(LINE_BYTES, maxBytes);
105
+ let activities = input.activities.filter((activity) => inert(activity.text));
106
+ const build = () => {
107
+ const lines = [headerLine];
108
+ if (input.thinking) {
109
+ const thinking = markedLine("✦", input.thinking, thinkingBudget, true);
110
+ if (thinking)
111
+ lines.push(listItem(thinking));
112
+ }
113
+ for (const activity of activities) {
114
+ const line = markedLine(activity.marker, activity.text, lineBudget, activity.tail === true);
115
+ if (line)
116
+ lines.push(listItem(line));
117
+ }
118
+ return lines.join("\n");
119
+ };
120
+ let frame = build();
121
+ while (byteLength(frame) > maxBytes && activities.length > 1) {
122
+ activities = activities.slice(1);
123
+ frame = build();
124
+ }
125
+ while (byteLength(frame) > maxBytes && thinkingBudget > 24) {
126
+ thinkingBudget = Math.floor(thinkingBudget * 0.6);
127
+ frame = build();
128
+ }
129
+ while (byteLength(frame) > maxBytes && lineBudget > 24) {
130
+ lineBudget = Math.floor(lineBudget * 0.6);
131
+ frame = build();
132
+ }
133
+ while (byteLength(frame) > maxBytes && activities.length > 0) {
134
+ activities = activities.slice(1);
135
+ frame = build();
136
+ }
137
+ if (byteLength(frame) <= maxBytes && isCompleteMarkdownList(frame))
138
+ return frame;
139
+ if (byteLength(headerLine) <= maxBytes && isCompleteMarkdownList(headerLine))
140
+ return headerLine;
141
+ return "- 正在处理…";
142
+ }
143
+ /**
144
+ * The first real progress frame. It replaces the warmup line instead of appending onto it, and
145
+ * it keeps only the queued items that fit in one request. The rest stay queued for append.
146
+ */
147
+ export function renderOpeningFrame(header, pending) {
148
+ const head = renderProgressLine({ marker: "", text: header });
149
+ const lines = [];
150
+ if (head)
151
+ lines.push(head);
152
+ for (const line of pending) {
153
+ const candidate = [...lines, line].join("\n");
154
+ if (byteLength(candidate) > CARD_REQUEST_MAX_BYTES)
155
+ break;
156
+ lines.push(line);
19
157
  }
158
+ const frame = lines.join("\n");
159
+ if (frame && byteLength(frame) <= CARD_REQUEST_MAX_BYTES && isCompleteMarkdownList(frame))
160
+ return frame;
161
+ return head && byteLength(head) <= CARD_REQUEST_MAX_BYTES ? head : "- 正在处理…";
162
+ }
163
+ /**
164
+ * Choose the next progress write. Appending continues while the card stays under the document
165
+ * ceiling; crossing it sends the short snapshot first. With append unavailable, every update is
166
+ * one snapshot that already fits in a single request.
167
+ */
168
+ export function planProgressWrite(input) {
169
+ const pending = input.pending.filter((line) => line.trim());
170
+ if (pending.length === 0)
171
+ return undefined;
172
+ if (!input.append) {
173
+ if (!input.fallback || input.fallback === input.document)
174
+ return undefined;
175
+ return { method: "replace", content: input.fallback, clearPending: true };
176
+ }
177
+ if (!input.document) {
178
+ const opening = renderOpeningFrame(input.header, pending);
179
+ if (!opening)
180
+ return undefined;
181
+ return { method: "replace", content: opening, clearPending: false };
182
+ }
183
+ const delta = `\n${pending[0]}`;
184
+ if (byteLength(delta) > CARD_REQUEST_MAX_BYTES)
185
+ return { method: "drop", content: "", clearPending: false };
186
+ if (byteLength(input.document) + byteLength(delta) > CARD_DOCUMENT_MAX_BYTES) {
187
+ if (!input.compact || input.compact === input.document)
188
+ return { method: "drop", content: "", clearPending: false };
189
+ return { method: "replace", content: input.compact, clearPending: false };
190
+ }
191
+ return { method: "append", content: delta, clearPending: false };
192
+ }
193
+ /** A one-line card ending. Falls back to a fixed line if the text could not stay plain markdown. */
194
+ export function renderCardStatus(text) {
195
+ const line = inert(text);
196
+ if (line && byteLength(line) <= CARD_REQUEST_MAX_BYTES && !/```|`|\[|\]|\\|[<>]|[*_~]{2}/.test(line))
197
+ return line;
198
+ return "处理已结束。";
20
199
  }
@@ -68,6 +68,10 @@ export interface WalkFilesResult {
68
68
  truncated: boolean;
69
69
  }
70
70
  export interface FileStore {
71
+ /** Optional host directory events; a basename or an unspecified directory change is only a hint. */
72
+ watchDirectory?(path: string, onChange: (name?: string) => void, onError: (error: Error) => void): {
73
+ close(): void;
74
+ };
71
75
  /** ENOENT resolves to `undefined` rather than throwing. */
72
76
  stat(path: string): Promise<FileStat | undefined>;
73
77
  /** Single bounded read. `eof` tells the caller whether there is more file left to fetch. */
@@ -1,4 +1,4 @@
1
- import { createReadStream } from "node:fs";
1
+ import { createReadStream, watch } from "node:fs";
2
2
  import { stat as fsStat, mkdir, open, readdir, rename, unlink } from "node:fs/promises";
3
3
  import { dirname, join } from "node:path";
4
4
  import { Writable } from "node:stream";
@@ -41,6 +41,11 @@ async function fsyncDir(dir) {
41
41
  .catch(() => undefined);
42
42
  }
43
43
  class HostFileStore {
44
+ watchDirectory(path, onChange, onError) {
45
+ const watcher = watch(path, { persistent: false }, (_event, filename) => onChange(filename ?? undefined));
46
+ watcher.on("error", onError);
47
+ return watcher;
48
+ }
44
49
  async stat(path) {
45
50
  try {
46
51
  return toFileStat(await fsStat(path));
@@ -0,0 +1,20 @@
1
+ import type { FileStore } from "../file-store.js";
2
+ /** File events are hints; only the manager may interpret completion artifacts. */
3
+ export declare class JobCompletionObserver {
4
+ private readonly store;
5
+ private readonly check;
6
+ private readonly entries;
7
+ private readonly directories;
8
+ private readonly dirty;
9
+ private scheduled?;
10
+ private processing;
11
+ private stopped;
12
+ constructor(store: FileStore, check: (ids: string[]) => Promise<void>);
13
+ add(id: string, exitFile: string, ready?: boolean): void;
14
+ ready(id: string): void;
15
+ retry(): void;
16
+ remove(id: string): void;
17
+ stop(): void;
18
+ private watch;
19
+ private mark;
20
+ }
@@ -0,0 +1,107 @@
1
+ import { basename, dirname } from "node:path";
2
+ import * as log from "../log.js";
3
+ import { errorMessage } from "../shared/text-utils.js";
4
+ /** File events are hints; only the manager may interpret completion artifacts. */
5
+ export class JobCompletionObserver {
6
+ constructor(store, check) {
7
+ this.store = store;
8
+ this.check = check;
9
+ this.entries = new Map();
10
+ this.directories = new Map();
11
+ this.dirty = new Set();
12
+ this.processing = false;
13
+ this.stopped = false;
14
+ }
15
+ add(id, exitFile, ready = false) {
16
+ if (this.stopped)
17
+ return;
18
+ this.entries.set(id, { directory: dirname(exitFile), name: basename(exitFile), ready });
19
+ this.watch(dirname(exitFile));
20
+ if (ready)
21
+ this.mark(id);
22
+ }
23
+ ready(id) {
24
+ const entry = this.entries.get(id);
25
+ if (entry) {
26
+ entry.ready = true;
27
+ this.mark(id);
28
+ }
29
+ }
30
+ retry() {
31
+ for (const directory of this.directories.keys())
32
+ this.watch(directory);
33
+ }
34
+ remove(id) {
35
+ const entry = this.entries.get(id);
36
+ this.entries.delete(id);
37
+ this.dirty.delete(id);
38
+ if (entry && ![...this.entries.values()].some((other) => other.directory === entry.directory)) {
39
+ this.directories.get(entry.directory)?.handle?.close();
40
+ this.directories.delete(entry.directory);
41
+ }
42
+ }
43
+ stop() {
44
+ this.stopped = true;
45
+ if (this.scheduled)
46
+ clearImmediate(this.scheduled);
47
+ for (const directory of this.directories.values())
48
+ directory.handle?.close();
49
+ this.directories.clear();
50
+ this.entries.clear();
51
+ this.dirty.clear();
52
+ }
53
+ watch(path) {
54
+ if (this.stopped || !this.store.watchDirectory)
55
+ return;
56
+ let directory = this.directories.get(path);
57
+ if (!directory) {
58
+ directory = { retryAt: 0 };
59
+ this.directories.set(path, directory);
60
+ }
61
+ if (directory.handle || Date.now() < directory.retryAt)
62
+ return;
63
+ const failed = (error) => {
64
+ directory.handle?.close();
65
+ directory.handle = undefined;
66
+ directory.retryAt = Date.now() + 10_000;
67
+ log.logWarn("job.observer.failed", "Background job observation failed", { reason: errorMessage(error) });
68
+ };
69
+ try {
70
+ directory.handle = this.store.watchDirectory(path, (name) => {
71
+ for (const [id, entry] of this.entries) {
72
+ if (entry.directory === path && (name === undefined || name === entry.name))
73
+ this.mark(id);
74
+ }
75
+ }, failed);
76
+ }
77
+ catch (error) {
78
+ failed(error);
79
+ }
80
+ }
81
+ mark(id) {
82
+ this.dirty.add(id);
83
+ if (this.stopped || this.scheduled || this.processing)
84
+ return;
85
+ this.scheduled = setImmediate(() => {
86
+ this.scheduled = undefined;
87
+ const ids = [...this.dirty].filter((id) => this.entries.get(id)?.ready);
88
+ for (const id of ids)
89
+ this.dirty.delete(id);
90
+ if (!ids.length || this.stopped)
91
+ return;
92
+ this.processing = true;
93
+ void this.check(ids)
94
+ .catch((error) => log.logWarn("job.observer.reconcile_failed", "Background job reconcile failed", {
95
+ reason: errorMessage(error),
96
+ }))
97
+ .finally(() => {
98
+ this.processing = false;
99
+ for (const id of this.dirty)
100
+ if (this.entries.get(id)?.ready) {
101
+ this.mark(id);
102
+ break;
103
+ }
104
+ });
105
+ });
106
+ }
107
+ }
@@ -0,0 +1,9 @@
1
+ /** Revision check and registration are synchronous, so a completion cannot fall between them. */
2
+ export declare class CompletionSignal {
3
+ revision: number;
4
+ private readonly waiters;
5
+ private stopped;
6
+ publish(): void;
7
+ stop(): void;
8
+ wait(revision: number, ms: number, signal?: AbortSignal): Promise<void>;
9
+ }
@@ -0,0 +1,32 @@
1
+ /** Revision check and registration are synchronous, so a completion cannot fall between them. */
2
+ export class CompletionSignal {
3
+ constructor() {
4
+ this.revision = 0;
5
+ this.waiters = new Set();
6
+ this.stopped = false;
7
+ }
8
+ publish() {
9
+ this.revision++;
10
+ for (const wake of [...this.waiters])
11
+ wake();
12
+ }
13
+ stop() {
14
+ this.stopped = true;
15
+ this.publish();
16
+ }
17
+ wait(revision, ms, signal) {
18
+ if (this.stopped || this.revision !== revision || signal?.aborted)
19
+ return Promise.resolve();
20
+ return new Promise((resolve) => {
21
+ const wake = () => {
22
+ clearTimeout(timer);
23
+ this.waiters.delete(wake);
24
+ signal?.removeEventListener("abort", wake);
25
+ resolve();
26
+ };
27
+ const timer = setTimeout(wake, ms);
28
+ this.waiters.add(wake);
29
+ signal?.addEventListener("abort", wake, { once: true });
30
+ });
31
+ }
32
+ }
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import type { WakeEvent } from "../channel/channel-event.js";
6
6
  import type { JobRecord } from "./record.js";
7
- /** The wake's dispatch id — the only id `beginWakeConsumption` accepts for it. */
7
+ /** The wake's dispatch id. */
8
8
  export declare function jobWakeDispatchId(desk: string, jobId: string): string;
9
9
  export declare function buildJobCompletionWake(input: {
10
10
  desk: string;
@@ -1,4 +1,4 @@
1
- /** The wake's dispatch id — the only id `beginWakeConsumption` accepts for it. */
1
+ /** The wake's dispatch id. */
2
2
  export function jobWakeDispatchId(desk, jobId) {
3
3
  return `job:${desk}:${jobId}:done`;
4
4
  }
@@ -6,13 +6,12 @@ export function buildJobCompletionWake(input) {
6
6
  const { desk, channelId, record, tail } = input;
7
7
  const exit = record.exitCode !== undefined ? `exit ${record.exitCode}` : record.status;
8
8
  const seconds = Math.round(record.durationMs / 1000);
9
- const belongsTo = record.contract.taskId ? ` It belongs to task ${record.contract.taskId}.` : "";
10
9
  const dispatchId = jobWakeDispatchId(desk, record.id);
11
10
  return {
12
11
  source: "wake",
13
12
  channelId,
14
13
  producer: "JOB",
15
- text: `[JOB:${record.id}] Background job "${record.label}" finished: ${record.status} (${exit}, ${seconds}s).${belongsTo} ` +
14
+ text: `[JOB:${record.id}] Background job "${record.label}" finished: ${record.status} (${exit}, ${seconds}s). ` +
16
15
  `Command: ${record.command}\n` +
17
16
  `Output tail:\n${tail || "(no output)"}\n` +
18
17
  `Full output: ${record.spillFile}\n` +
@@ -22,15 +21,5 @@ export function buildJobCompletionWake(input) {
22
21
  desk,
23
22
  // The result is awaited; the wake itself still runs without a progress card.
24
23
  presentation: "awaited",
25
- ...(record.contract.taskId
26
- ? {
27
- internalWake: {
28
- kind: "job",
29
- resourceId: record.id,
30
- taskId: record.contract.taskId,
31
- dispatchId,
32
- },
33
- }
34
- : {}),
35
24
  };
36
25
  }
@@ -7,6 +7,7 @@ export interface JobStartOptions {
7
7
  channelId: string;
8
8
  signal?: AbortSignal;
9
9
  notify?: boolean;
10
+ /** The task whose step starts the job (spec 064, INV-8): its completion is recorded there instead of waking `channelId`. */
10
11
  taskId?: string;
11
12
  }
12
13
  export interface JobManagerOptions {
@@ -16,6 +17,8 @@ export interface JobManagerOptions {
16
17
  isBoundTo?: (channelId: string, desk: string) => boolean;
17
18
  /** Delivers the completion wake. Omit to disable waking (sub-agent and test paths). */
18
19
  dispatch?: (event: WakeEvent) => boolean | Promise<boolean>;
20
+ /** A task-bound job settled and its record is in the task's log; the lane recomputes from it (spec 064, D19). */
21
+ onTaskInput?: (desk: string, taskId: string) => void;
19
22
  sweepIntervalMs?: number;
20
23
  /** File-content port for reading a job's spill file (spec 044, D8). Defaults to `createFileStore()`. */
21
24
  fileStore?: FileStore;
@@ -44,8 +47,10 @@ export declare const FINISHED_JOB_RETENTION_MS: number;
44
47
  export declare class DeskJobManager {
45
48
  private readonly target;
46
49
  private readonly executor;
50
+ private readonly pendingCompletion;
51
+ private readonly completion;
52
+ private readonly observer;
47
53
  private readonly jobs;
48
- private readonly wakeQueue;
49
54
  /**
50
55
  * Serializes every probe → decide → terminal-transition sequence for a single job. The sweeper,
51
56
  * `list`/`poll`/`restore` (via `refresh`), `cancel`, and the persist-failure rollback all pass
@@ -141,10 +146,11 @@ export declare class DeskJobManager {
141
146
  private applyProbe;
142
147
  /** Move a job to a terminal status: record it, persist it, and wake the channel once. */
143
148
  private finish;
149
+ private commitCompletion;
144
150
  /**
145
- * Tell the owning task this job settled (spec 052, D4). Runs before the completion wake is
146
- * dispatched, so the step the wake starts already finds the result on its board. Best-effort and
147
- * once-only: a task that no longer exists, or a replayed finish, writes nothing.
151
+ * Tell the owning task this job settled (spec 052, D4). Runs before the lane is told, so the step
152
+ * it starts already finds the result in its inputs. Best-effort and once-only: a task that no
153
+ * longer exists, or a replayed finish, writes nothing.
148
154
  */
149
155
  private logSettlementToTask;
150
156
  /**
@@ -155,7 +161,7 @@ export declare class DeskJobManager {
155
161
  * version that persisted `notified` first, which could crash-lose the wake entirely).
156
162
  */
157
163
  private announce;
158
- /** Same contract as `SubAgentRunManager.suppressWake`: drop the wake, still redeem the `work` ticket. */
164
+ /** Same contract as `SubAgentRunManager.suppressWake`: drop the chat wake of a job whose channel left the desk. */
159
165
  private suppressWake;
160
166
  /**
161
167
  * The shell command that terminates `record`'s process and prints one token describing what
@@ -176,8 +182,6 @@ export declare class DeskJobManager {
176
182
  */
177
183
  private runKill;
178
184
  list(signal?: AbortSignal): Promise<JobSnapshot[]>;
179
- beginWakeConsumption(id: string, taskId: string, dispatchId: string): Promise<boolean>;
180
- finishWakeConsumption(id: string, dispatchId: string): Promise<void>;
181
185
  cancel(ids: string[], signal?: AbortSignal): Promise<Array<{
182
186
  id: string;
183
187
  status: JobStatus | "not_found";
@@ -202,25 +206,3 @@ export declare class DeskJobManager {
202
206
  text: string;
203
207
  } | undefined>;
204
208
  }
205
- interface JobRuntimeConfig {
206
- /** Root of the per-desk record directories (`<jobsStateDir>/<desk>/`). */
207
- jobsStateDir?: string;
208
- /**
209
- * The agent workspace root. A job's full-output spill goes to `<desk>/logs/` so the
210
- * "Full output: …" pointer is a file the model can read (fix plan §2.2). The path is stable
211
- * across restarts, so a re-adopted job's spill is still found.
212
- */
213
- workspaceDir?: string;
214
- dispatch?: (event: WakeEvent) => boolean | Promise<boolean>;
215
- isBoundTo?: JobManagerOptions["isBoundTo"];
216
- /** Sweep cadence override for the lazily-built desk managers (tests). */
217
- sweepIntervalMs?: number;
218
- }
219
- /** One application's jobs; the executor and configuration cannot change after construction. */
220
- export declare function createJobRuntime(executor: Executor, options?: JobRuntimeConfig): {
221
- get: (desk: string) => DeskJobManager;
222
- restore: () => Promise<number>;
223
- stop: () => void;
224
- };
225
- export type JobRuntime = ReturnType<typeof createJobRuntime>;
226
- export {};