@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,33 +0,0 @@
1
- import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
2
- export interface WorkspaceSkillSummary {
3
- name: string;
4
- description: string;
5
- path: string;
6
- warning?: string;
7
- }
8
- export interface WorkspaceSkillOptions {
9
- workspaceDir: string;
10
- securityConfig?: SecurityConfig;
11
- securityContext?: SecurityRuntimeContext;
12
- channelId?: string;
13
- }
14
- export declare function listWorkspaceSkills(options: {
15
- workspaceDir: string;
16
- securityConfig?: SecurityConfig;
17
- securityContext?: SecurityRuntimeContext;
18
- }): Promise<WorkspaceSkillSummary[]>;
19
- export interface WorkspaceSkillFile {
20
- name: string;
21
- /** The guard-resolved path actually opened — never the raw pre-guard path. */
22
- path: string;
23
- /** The whole file; callers that need a size cap (the `skill` tool) apply it themselves. */
24
- content: string;
25
- }
26
- /**
27
- * Load one skill's `SKILL.md` bytes through the same path-guard every other file read goes
28
- * through. Shared by the `skill` tool's `read` action and the `/skills show` runtime command
29
- * (`skills/commands.ts`) — a `SKILL.md` that is itself a symlink pointing outside
30
- * `workspace/skills/` (planted via `bash ln -s`, not via `name` -- `resolveSkillPath` already
31
- * confines that) is caught here in both callers instead of being read verbatim.
32
- */
33
- export declare function loadWorkspaceSkillFile(options: WorkspaceSkillOptions, name: string): Promise<WorkspaceSkillFile>;
@@ -1,116 +0,0 @@
1
- /**
2
- * Workspace skill catalog access: list the skills under `workspace/skills/` and load one
3
- * `SKILL.md`, both through the path guard. The `skill` tool and `/skills` are thin adapters over
4
- * this file (spec 054 D8/D10).
5
- */
6
- import { existsSync } from "node:fs";
7
- import { readdir, readFile, stat } from "node:fs/promises";
8
- import { join } from "node:path";
9
- import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
10
- import { checkPathGuard } from "../security/path-guard-check.js";
11
- import { readGuardAllows } from "../security/path-guard-filter.js";
12
- import { isNodeError } from "../shared/os.js";
13
- import { RecoverableToolError } from "../shared/recoverable-error.js";
14
- import { resolveSkillPath, scanSkillContent, validateSkillFrontmatter, validateSkillName } from "./validation.js";
15
- function extractDescription(content) {
16
- const match = content.replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/);
17
- if (!match) {
18
- return "";
19
- }
20
- for (const line of (match[1] ?? "").split("\n")) {
21
- const fieldMatch = line.match(/^description:\s*(.*)$/);
22
- if (fieldMatch) {
23
- return fieldMatch[1].replace(/^["']|["']$/g, "").trim();
24
- }
25
- }
26
- return "";
27
- }
28
- export async function listWorkspaceSkills(options) {
29
- const skillsDir = join(options.workspaceDir, "skills");
30
- // `skill read` runs each SKILL.md through the path guard (`loadWorkspaceSkillFile`); `list`
31
- // must apply the same guard so a skill whose SKILL.md is a symlink out of `workspace/skills/`
32
- // is silently omitted here too, rather than being advertised and then refused on read.
33
- const guardConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
34
- const guardContext = options.securityContext ?? {
35
- agentWorkspaceDir: options.workspaceDir,
36
- cwd: options.workspaceDir,
37
- };
38
- let names;
39
- try {
40
- names = await readdir(skillsDir);
41
- }
42
- catch (error) {
43
- if (isNodeError(error) && error.code === "ENOENT") {
44
- return [];
45
- }
46
- throw error;
47
- }
48
- const summaries = [];
49
- for (const name of names.sort()) {
50
- const nameValidation = validateSkillName(name);
51
- if (!nameValidation.ok) {
52
- continue;
53
- }
54
- const skillDir = join(skillsDir, name);
55
- const skillStats = await stat(skillDir).catch(() => null);
56
- if (!skillStats?.isDirectory()) {
57
- continue;
58
- }
59
- const skillPath = join(skillDir, "SKILL.md");
60
- if (!readGuardAllows(skillPath, guardConfig, guardContext)) {
61
- continue;
62
- }
63
- let content;
64
- try {
65
- const skillFileStats = await stat(skillPath);
66
- if (!skillFileStats.isFile()) {
67
- continue;
68
- }
69
- content = await readFile(skillPath, "utf-8");
70
- }
71
- catch (error) {
72
- if (isNodeError(error) && error.code === "ENOENT") {
73
- continue;
74
- }
75
- throw error;
76
- }
77
- const validation = validateSkillFrontmatter(content, name);
78
- const scan = validation.ok ? scanSkillContent(content) : validation;
79
- summaries.push({
80
- name,
81
- description: extractDescription(content),
82
- path: `${options.workspaceDir}/skills/${name}/SKILL.md`,
83
- warning: scan.ok ? undefined : scan.error,
84
- });
85
- }
86
- return summaries;
87
- }
88
- /**
89
- * Load one skill's `SKILL.md` bytes through the same path-guard every other file read goes
90
- * through. Shared by the `skill` tool's `read` action and the `/skills show` runtime command
91
- * (`skills/commands.ts`) — a `SKILL.md` that is itself a symlink pointing outside
92
- * `workspace/skills/` (planted via `bash ln -s`, not via `name` -- `resolveSkillPath` already
93
- * confines that) is caught here in both callers instead of being read verbatim.
94
- */
95
- export async function loadWorkspaceSkillFile(options, name) {
96
- const nameValidation = validateSkillName(name);
97
- if (!nameValidation.ok) {
98
- throw new RecoverableToolError(nameValidation.error ?? `Invalid skill name "${name}".`);
99
- }
100
- const skillDir = resolveSkillPath(options.workspaceDir, name);
101
- const rawPath = join(skillDir, "SKILL.md");
102
- if (!existsSync(rawPath)) {
103
- throw new RecoverableToolError(`Workspace skill "${name}" does not exist. Use action "list" to see what's available.`);
104
- }
105
- const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
106
- const securityContext = options.securityContext ?? {
107
- agentWorkspaceDir: options.workspaceDir,
108
- cwd: options.workspaceDir,
109
- };
110
- const target = await checkPathGuard(rawPath, "read", securityConfig, securityContext, {
111
- tool: "skill",
112
- channelId: options.channelId,
113
- });
114
- const content = await readFile(target, "utf-8");
115
- return { name, path: target, content };
116
- }
@@ -1,8 +0,0 @@
1
- /** Queue guidance for the task's next step. Repeated calls append, so nothing is silently lost. */
2
- export declare function queueTaskSteer(deskDir: string, id: string, text: string, label?: string): Promise<void>;
3
- /** Read and clear the pending guidance. Returns `undefined` when there is none. */
4
- export declare function consumeTaskSteer(deskDir: string, id: string): Promise<string | undefined>;
5
- /** Whether guidance is waiting, without consuming it (for `/tasks show`). */
6
- export declare function hasTaskSteer(deskDir: string, id: string): boolean;
7
- export declare function queueTaskNotice(deskDir: string, id: string, text: string): Promise<void>;
8
- export declare function consumeTaskNotice(deskDir: string, id: string): Promise<string | undefined>;
@@ -1,81 +0,0 @@
1
- import { existsSync } from "node:fs";
2
- import { mkdir, readFile, rm } from "node:fs/promises";
3
- import { join } from "node:path";
4
- import { writeFileAtomically } from "../shared/atomic-file.js";
5
- import { formatLocalTime } from "../shared/local-time.js";
6
- import { normalizeTaskId } from "./contract.js";
7
- import { withTaskMutation } from "./mutation-lock.js";
8
- /**
9
- * Out-of-band guidance for a running task loop (spec 051, D11) — `/tasks steer` and `/tasks reply`.
10
- *
11
- * Kept as one small file per task rather than a frontmatter field or a log record: it is a
12
- * *pending instruction*, not durable task state, so it must not enter the contract (which the
13
- * loop injects whole and which has a hard size budget) and must be consumed exactly once. The
14
- * next step reads it, deletes it, and puts the text at the top of its own brief; nothing is left
15
- * behind for a later step to act on twice.
16
- *
17
- * Each read-modify-write runs under the task's mutation lock: a TUI's `/tasks steer` appending
18
- * while the daemon's step consumes would otherwise lose the appended line.
19
- */
20
- function steerDir(deskDir) {
21
- return join(deskDir, "tasks", ".steer");
22
- }
23
- function steerPath(deskDir, id) {
24
- return join(steerDir(deskDir), `${normalizeTaskId(id)}.md`);
25
- }
26
- /** Queue guidance for the task's next step. Repeated calls append, so nothing is silently lost. */
27
- export async function queueTaskSteer(deskDir, id, text, label = "用户指示") {
28
- const trimmed = text.trim();
29
- if (!trimmed)
30
- return;
31
- await withTaskMutation(deskDir, id, async () => {
32
- await mkdir(steerDir(deskDir), { recursive: true });
33
- const path = steerPath(deskDir, id);
34
- const existing = existsSync(path) ? `${await readFile(path, "utf-8")}\n` : "";
35
- await writeFileAtomically(path, `${existing}- [${formatLocalTime()}] ${label}:${trimmed}\n`);
36
- });
37
- }
38
- /** Read and clear the pending guidance. Returns `undefined` when there is none. */
39
- export async function consumeTaskSteer(deskDir, id) {
40
- return consumeOnce(deskDir, id, steerPath(deskDir, id));
41
- }
42
- async function consumeOnce(deskDir, id, path) {
43
- if (!existsSync(path))
44
- return undefined;
45
- return withTaskMutation(deskDir, id, async () => {
46
- try {
47
- const text = (await readFile(path, "utf-8")).trim();
48
- await rm(path, { force: true });
49
- return text || undefined;
50
- }
51
- catch {
52
- return undefined;
53
- }
54
- });
55
- }
56
- /** Whether guidance is waiting, without consuming it (for `/tasks show`). */
57
- export function hasTaskSteer(deskDir, id) {
58
- return existsSync(steerPath(deskDir, id));
59
- }
60
- /**
61
- * The other direction: what a step asked the runtime to tell the user (`task_step_end`'s
62
- * `notify`). Held in a file rather than returned inline because the tool result never reaches the
63
- * transport — the runtime reads and clears this after the step ends, and delivers it once.
64
- */
65
- function noticePath(deskDir, id) {
66
- return join(steerDir(deskDir), `${normalizeTaskId(id)}.out.md`);
67
- }
68
- export async function queueTaskNotice(deskDir, id, text) {
69
- const trimmed = text.trim();
70
- if (!trimmed)
71
- return;
72
- await withTaskMutation(deskDir, id, async () => {
73
- await mkdir(steerDir(deskDir), { recursive: true });
74
- const path = noticePath(deskDir, id);
75
- const existing = existsSync(path) ? `${await readFile(path, "utf-8")}\n\n` : "";
76
- await writeFileAtomically(path, `${existing}${trimmed}`);
77
- });
78
- }
79
- export async function consumeTaskNotice(deskDir, id) {
80
- return consumeOnce(deskDir, id, noticePath(deskDir, id));
81
- }
@@ -1,71 +0,0 @@
1
- /**
2
- * The waiting ticket — the only way a task may park (spec 051, D2; narrowed by spec 052, D3).
3
- *
4
- * A ticket is a claim the runtime can check at write time, and it always carries `by`, a backstop
5
- * instant after which the runtime reopens the task rather than leaving it parked forever: a
6
- * parked task either gets redeemed, or the user hears about it. Three kinds are enough:
7
- *
8
- * - `time` — wait for a moment; the driver redeems it.
9
- * - `work` — wait for the delegations and jobs this task has in flight; the first one to settle
10
- * redeems it. The leader never has to pick "which run is the real blocker".
11
- * - `ask` — wait for the user; `/tasks reply` redeems it.
12
- *
13
- * Waiting for an external condition is a background job (a sensor with a timeout) bound to the
14
- * task, i.e. a `work` ticket — not a separate kind.
15
- */
16
- export type TicketKind = "time" | "work" | "ask";
17
- export type Ticket = {
18
- kind: "time";
19
- at: string;
20
- by: string;
21
- }
22
- /** `refs` is display-only: redemption matches on `kind`, never on the ids. */
23
- | {
24
- kind: "work";
25
- refs: string[];
26
- by: string;
27
- } | {
28
- kind: "ask";
29
- asked: string;
30
- by: string;
31
- };
32
- /** A delegation or background job bound to this task that has not settled yet. */
33
- export interface PendingWorkRef {
34
- ref: string;
35
- /** Epoch ms after which the owner itself gives up on the work. */
36
- deadlineMs: number;
37
- }
38
- /**
39
- * Everything `resolveTicket` may consult, injected rather than imported: the run/job registries
40
- * are stateful singletons, and keeping them out of this module is what makes the whole
41
- * validation matrix unit-testable without a runtime.
42
- */
43
- export interface TicketContext {
44
- now: Date;
45
- /** Unsettled runs and still-running jobs whose `taskId` is this task. */
46
- pendingWork(): PendingWorkRef[];
47
- }
48
- /**
49
- * Validate one model-supplied ticket and stamp its backstop.
50
- *
51
- * This is the **only** way a `Ticket` value comes into existence — `task_step_end`, `/tasks
52
- * reply` and the converter all funnel through it. Anything that writes the `ticket` frontmatter
53
- * field directly is a defect: it would produce a park with no verified source or no `by`.
54
- */
55
- export declare function resolveTicket(input: unknown, ctx: TicketContext): Ticket;
56
- /** Read a persisted ticket back. Returns `undefined` for anything not shaped like a ticket. */
57
- export declare function parseTicket(raw: string): Ticket | undefined;
58
- /** Milliseconds of the ticket's backstop, or `undefined` when it is unparseable (never trusted). */
59
- export declare function ticketBackstopMs(ticket: Ticket): number | undefined;
60
- /**
61
- * Whether this ticket's backstop has passed. An unparseable `by` counts as expired: a park whose
62
- * deadline cannot be read is exactly the silent-forever state the backstop forbids, so it fails
63
- * toward waking the task rather than toward leaving it buried.
64
- */
65
- export declare function ticketExpired(ticket: Ticket, now?: Date): boolean;
66
- /** The moment a `time` ticket is *due*. Only `time` tickets are driver-polled; the rest are pushed by their owner. */
67
- export declare function ticketDueMs(ticket: Ticket): number | undefined;
68
- /** One-line summary for the step brief and the expiry record (model-facing). */
69
- export declare function describeTicket(ticket: Ticket): string;
70
- /** The same summary in the user's terms, for `/tasks` (spec 053, D4). */
71
- export declare function describeTicketForUser(ticket: Ticket): string;
@@ -1,138 +0,0 @@
1
- import { formatLocalTime, parseLocalTime, parseWakeInput } from "../shared/local-time.js";
2
- import { RecoverableToolError } from "../shared/recoverable-error.js";
3
- import { isPlainObject } from "../shared/type-guards.js";
4
- const TICKET_KINDS = ["time", "work", "ask"];
5
- /** `ask` has no source that could report back on its own, so it gets a generous fixed backstop. */
6
- const ASK_BACKSTOP_MS = 24 * 60 * 60 * 1000;
7
- /** Slack added to the latest pending deadline before the task gives up on the work. */
8
- const WORK_BACKSTOP_SLACK_MS = 10 * 60 * 1000;
9
- function requiredString(value, field) {
10
- if (typeof value !== "string" || !value.trim()) {
11
- throw new RecoverableToolError(`ticket.${field} is required and must be a non-empty string.`);
12
- }
13
- return value.trim();
14
- }
15
- /**
16
- * Validate one model-supplied ticket and stamp its backstop.
17
- *
18
- * This is the **only** way a `Ticket` value comes into existence — `task_step_end`, `/tasks
19
- * reply` and the converter all funnel through it. Anything that writes the `ticket` frontmatter
20
- * field directly is a defect: it would produce a park with no verified source or no `by`.
21
- */
22
- export function resolveTicket(input, ctx) {
23
- if (!isPlainObject(input)) {
24
- throw new RecoverableToolError(`ticket must be an object with a "kind" of: ${TICKET_KINDS.join(", ")}.`);
25
- }
26
- const kind = input.kind;
27
- if (typeof kind !== "string" || !TICKET_KINDS.includes(kind)) {
28
- throw new RecoverableToolError(`Unknown ticket kind "${String(kind)}". Use one of: ${TICKET_KINDS.join(", ")}.`);
29
- }
30
- const nowMs = ctx.now.getTime();
31
- switch (kind) {
32
- case "time": {
33
- const raw = requiredString(input.at, "at");
34
- const atMs = parseWakeInput(raw, ctx.now);
35
- if (atMs === undefined) {
36
- throw new RecoverableToolError(`ticket.at "${raw}" is not a valid local time or relative offset (e.g. 2026-09-06T09:00:00+08:00, +2h).`);
37
- }
38
- if (atMs <= nowMs) {
39
- throw new RecoverableToolError(`ticket.at "${raw}" is not in the future; a time ticket must wait for something.`);
40
- }
41
- const at = formatLocalTime(new Date(atMs));
42
- return { kind: "time", at, by: at };
43
- }
44
- case "work": {
45
- const pending = ctx.pendingWork();
46
- if (pending.length === 0) {
47
- throw new RecoverableToolError("This task has no delegation or background job in flight, so a work ticket has nothing to wait for. " +
48
- "Every result so far is already on the <task_board>: read it and continue, or dispatch more work first (with the task bound).");
49
- }
50
- const latest = Math.max(...pending.map((item) => item.deadlineMs));
51
- return {
52
- kind: "work",
53
- refs: pending.map((item) => item.ref),
54
- by: formatLocalTime(new Date(latest + WORK_BACKSTOP_SLACK_MS)),
55
- };
56
- }
57
- case "ask": {
58
- const asked = requiredString(input.asked, "asked");
59
- return { kind: "ask", asked, by: formatLocalTime(new Date(nowMs + ASK_BACKSTOP_MS)) };
60
- }
61
- }
62
- }
63
- /** Read a persisted ticket back. Returns `undefined` for anything not shaped like a ticket. */
64
- export function parseTicket(raw) {
65
- let value;
66
- try {
67
- value = JSON.parse(raw);
68
- }
69
- catch {
70
- return undefined;
71
- }
72
- if (!isPlainObject(value))
73
- return undefined;
74
- const kind = value.kind;
75
- const by = typeof value.by === "string" ? value.by.trim() : "";
76
- if (typeof kind !== "string" || !TICKET_KINDS.includes(kind) || !by)
77
- return undefined;
78
- if (parseLocalTime(by) === undefined)
79
- return undefined;
80
- switch (kind) {
81
- case "time":
82
- return typeof value.at === "string" && value.at ? { kind: "time", at: value.at, by } : undefined;
83
- case "work": {
84
- const refs = Array.isArray(value.refs)
85
- ? value.refs.filter((ref) => typeof ref === "string" && ref.length > 0)
86
- : [];
87
- return { kind: "work", refs, by };
88
- }
89
- case "ask":
90
- return typeof value.asked === "string" && value.asked ? { kind: "ask", asked: value.asked, by } : undefined;
91
- }
92
- }
93
- /** Milliseconds of the ticket's backstop, or `undefined` when it is unparseable (never trusted). */
94
- export function ticketBackstopMs(ticket) {
95
- return parseLocalTime(ticket.by);
96
- }
97
- /**
98
- * Whether this ticket's backstop has passed. An unparseable `by` counts as expired: a park whose
99
- * deadline cannot be read is exactly the silent-forever state the backstop forbids, so it fails
100
- * toward waking the task rather than toward leaving it buried.
101
- */
102
- export function ticketExpired(ticket, now = new Date()) {
103
- const by = ticketBackstopMs(ticket);
104
- return by === undefined || by <= now.getTime();
105
- }
106
- /** The moment a `time` ticket is *due*. Only `time` tickets are driver-polled; the rest are pushed by their owner. */
107
- export function ticketDueMs(ticket) {
108
- return ticket.kind === "time" ? parseLocalTime(ticket.at) : undefined;
109
- }
110
- /** One-line summary for the step brief and the expiry record (model-facing). */
111
- export function describeTicket(ticket) {
112
- switch (ticket.kind) {
113
- case "time":
114
- return `等待时间 ${ticket.at}`;
115
- case "work":
116
- return ticket.refs.length > 0 ? `等待委派/作业 ${ticket.refs.join(", ")}` : "等待委派/作业";
117
- case "ask":
118
- return `等待用户回答:${ticket.asked}`;
119
- }
120
- }
121
- /** `2026-10-12T09:00:00.000+08:00` → `10-12 09:00`, read off the stored wall-clock text. */
122
- function minuteOf(at) {
123
- const match = /^\d{4}-(\d{2}-\d{2})T(\d{2}:\d{2})/.exec(at);
124
- return match ? `${match[1]} ${match[2]}` : at;
125
- }
126
- /** The same summary in the user's terms, for `/tasks` (spec 053, D4). */
127
- export function describeTicketForUser(ticket) {
128
- switch (ticket.kind) {
129
- case "time":
130
- return `等到 ${minuteOf(ticket.at)}`;
131
- case "work":
132
- return ticket.refs.length > 0
133
- ? `等待 ${ticket.refs.map((ref) => `\`${ref}\``).join("、")} 完成`
134
- : "等待委派或后台作业完成";
135
- case "ask":
136
- return `等你回答:${ticket.asked}`;
137
- }
138
- }
@@ -1,11 +0,0 @@
1
- import type { TaskManageResult, TaskManageToolOptions, TaskStepEndRequest } from "./types.js";
2
- /**
3
- * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4; narrowed by spec 052, D7).
4
- *
5
- * One tool with three outcomes: the model states an *intent* ("keep going", "wait for this",
6
- * "we're done") and the runtime derives the state, so an illegal combination — parked with
7
- * nothing to wait for, active with a future wake — is not expressible rather than merely
8
- * diagnosed afterwards. Asking the user is not a fourth outcome but a park on an `ask` ticket,
9
- * which the runtime also announces.
10
- */
11
- export declare function endTaskStep(options: TaskManageToolOptions, request: TaskStepEndRequest): Promise<TaskManageResult>;
@@ -1,117 +0,0 @@
1
- import { applyTaskItemsPatch, normalizeTaskId } from "../../tasks/contract.js";
2
- import { appendTaskLog } from "../../tasks/loop-log.js";
3
- import { queueTaskNotice } from "../../tasks/steer.js";
4
- import { readStoredTask, writeStoredTask } from "../../tasks/store.js";
5
- import { describeTicket, resolveTicket } from "../../tasks/ticket.js";
6
- import { RecoverableToolError } from "../contract/details.js";
7
- import { buildTicketContext, closeTaskDocument, requiredField } from "./shared.js";
8
- /**
9
- * `task_step_end` — the loop's only closing move (spec 051, D4/§12.4; narrowed by spec 052, D7).
10
- *
11
- * One tool with three outcomes: the model states an *intent* ("keep going", "wait for this",
12
- * "we're done") and the runtime derives the state, so an illegal combination — parked with
13
- * nothing to wait for, active with a future wake — is not expressible rather than merely
14
- * diagnosed afterwards. Asking the user is not a fourth outcome but a park on an `ask` ticket,
15
- * which the runtime also announces.
16
- */
17
- export async function endTaskStep(options, request) {
18
- if (!options.taskId) {
19
- throw new RecoverableToolError("task_step_end is only available inside a task loop step.");
20
- }
21
- const id = normalizeTaskId(options.taskId);
22
- const document = await readStoredTask(options.deskDir, id);
23
- if (!document)
24
- throw new RecoverableToolError(`Task "${id}" no longer exists; nothing to end.`);
25
- const note = requiredField(request.note, "note", "task_step_end");
26
- if (request.items?.length) {
27
- document.body = applyTaskItemsPatch(document.body, request.items).body;
28
- }
29
- const seq = (document.fields.usage?.steps ?? 0) + 1;
30
- // The step's own model cost joins the task's usage here, before a `done` writes its close
31
- // record; bound delegations add theirs when they settle. A rough figure by design.
32
- const cost = options.getStepCost?.();
33
- const usd = cost && cost.usd > 0 ? cost.usd : 0;
34
- const usdEstimated = cost?.estimated === true;
35
- const usage = document.fields.usage;
36
- if (usage) {
37
- document.fields.usage = {
38
- ...usage,
39
- steps: seq,
40
- usd: usage.usd + usd,
41
- usdEstimated: usage.usdEstimated || usdEstimated,
42
- };
43
- }
44
- const tools = [...new Set(options.getToolsUsed?.() ?? [])];
45
- const report = request.report?.trim();
46
- const logStep = async (outcome) => {
47
- await appendTaskLog(options.deskDir, id, {
48
- kind: "step",
49
- seq,
50
- outcome,
51
- note,
52
- tools,
53
- ...(report ? { report } : {}),
54
- ...(usd > 0 ? { usd } : {}),
55
- ...(usdEstimated ? { usdEstimated: true } : {}),
56
- });
57
- };
58
- // Steps are silent by default (D9); `report` is the explicit opt-in the runtime delivers once
59
- // the step ends. The notice is an *outbound side effect*: it must not land before every
60
- // recoverable check (required fields, unmet acceptance items, work in flight, ticket
61
- // resolution) has passed, or a rejected `outcome=done` still tells the channel "task complete"
62
- // and a corrected retry queues a second notice. So it is computed here and only flushed past a
63
- // successful write, right before each return.
64
- let pendingNotice = report || undefined;
65
- const flushNotice = async () => {
66
- if (pendingNotice)
67
- await queueTaskNotice(options.deskDir, id, pendingNotice);
68
- };
69
- if (request.outcome === "done") {
70
- await closeTaskDocument({
71
- options,
72
- document,
73
- id,
74
- outcome: "complete",
75
- note,
76
- steps: seq,
77
- afterChecks: () => logStep("done"),
78
- });
79
- await flushNotice();
80
- return {
81
- action: "step_end",
82
- id,
83
- archived: true,
84
- notice: `任务 \`${id}\` 已完成并归档。`,
85
- };
86
- }
87
- let notice;
88
- if (request.outcome === "continue") {
89
- document.fields.state = "open";
90
- document.fields.ticket = undefined;
91
- notice = `步骤已记录,任务 \`${id}\` 继续。`;
92
- }
93
- else {
94
- if (!request.ticket) {
95
- throw new RecoverableToolError("task_step_end outcome=park requires a ticket describing what will wake this task.");
96
- }
97
- const context = await buildTicketContext(options, id);
98
- const ticket = resolveTicket(request.ticket, context);
99
- document.fields.state = "parked";
100
- document.fields.ticket = ticket;
101
- // A task waiting on the user that says nothing is the same silent dead end tickets exist to
102
- // prevent, so an `ask` park always speaks.
103
- if (ticket.kind === "ask") {
104
- pendingNotice = [
105
- report,
106
- `⚠️ 任务 \`${id}\` 需要你的决定:${ticket.asked}\n用 \`/tasks reply ${id} <内容>\` 回答。`,
107
- ]
108
- .filter(Boolean)
109
- .join("\n\n");
110
- }
111
- notice = `任务 \`${id}\` 已停泊:${describeTicket(ticket)}(兜底 ${ticket.by})。`;
112
- }
113
- await writeStoredTask(document);
114
- await logStep(request.outcome);
115
- await flushNotice();
116
- return { action: "step_end", id, state: document.fields.state, notice };
117
- }