@oyasmi/pipiclaw 0.8.8 → 0.8.9-beta.2

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 (110) hide show
  1. package/README.md +8 -3
  2. package/dist/agent/channel-runner.d.ts +1 -0
  3. package/dist/agent/channel-runner.js +3 -2
  4. package/dist/agent/effect-ledger.d.ts +11 -0
  5. package/dist/agent/effect-ledger.js +42 -0
  6. package/dist/agent/job-manager.d.ts +90 -13
  7. package/dist/agent/job-manager.js +235 -20
  8. package/dist/agent/prompt/sections.js +11 -2
  9. package/dist/agent/prompt/types.d.ts +7 -1
  10. package/dist/agent/runner-factory.d.ts +7 -0
  11. package/dist/agent/session-events.js +20 -1
  12. package/dist/index.d.ts +1 -1
  13. package/dist/log.d.ts +6 -0
  14. package/dist/log.js +12 -0
  15. package/dist/memory/consolidation.d.ts +5 -0
  16. package/dist/memory/consolidation.js +35 -147
  17. package/dist/memory/extraction.d.ts +45 -0
  18. package/dist/memory/extraction.js +227 -0
  19. package/dist/memory/lifecycle.js +5 -0
  20. package/dist/memory/maintenance-jobs.js +7 -0
  21. package/dist/memory/post-turn-review.d.ts +3 -1
  22. package/dist/memory/post-turn-review.js +20 -189
  23. package/dist/memory/recall.d.ts +0 -1
  24. package/dist/memory/recall.js +135 -77
  25. package/dist/memory/sidecar-worker.d.ts +7 -0
  26. package/dist/memory/sidecar-worker.js +23 -5
  27. package/dist/memory/task-digest.js +1 -1
  28. package/dist/paths.d.ts +1 -0
  29. package/dist/paths.js +11 -0
  30. package/dist/playbooks/background-jobs.md +40 -0
  31. package/dist/playbooks/catalog.d.ts +1 -7
  32. package/dist/playbooks/catalog.js +4 -14
  33. package/dist/playbooks/event-scheduling.md +8 -4
  34. package/dist/playbooks/memory-and-learning.md +1 -1
  35. package/dist/playbooks/outbound-media.md +45 -0
  36. package/dist/playbooks/runtime-orientation.md +1 -1
  37. package/dist/playbooks/task-closeout.md +12 -11
  38. package/dist/playbooks/task-delegation.md +11 -5
  39. package/dist/playbooks/task-driving.md +54 -21
  40. package/dist/playbooks/task-planning.md +46 -19
  41. package/dist/runtime/bootstrap.js +29 -4
  42. package/dist/runtime/channel-context.d.ts +33 -0
  43. package/dist/runtime/dingtalk.d.ts +22 -2
  44. package/dist/runtime/dingtalk.js +141 -0
  45. package/dist/runtime/durable-dispatch.d.ts +10 -0
  46. package/dist/runtime/durable-dispatch.js +42 -1
  47. package/dist/runtime/event-validation.d.ts +48 -0
  48. package/dist/runtime/event-validation.js +81 -0
  49. package/dist/runtime/events.d.ts +17 -8
  50. package/dist/runtime/events.js +96 -22
  51. package/dist/runtime/store.d.ts +1 -1
  52. package/dist/runtime/task-commands.js +29 -51
  53. package/dist/runtime/task-driver.d.ts +5 -8
  54. package/dist/runtime/task-driver.js +120 -93
  55. package/dist/runtime/task-migration.d.ts +11 -0
  56. package/dist/runtime/task-migration.js +70 -0
  57. package/dist/settings.d.ts +11 -0
  58. package/dist/settings.js +12 -0
  59. package/dist/shared/recoverable-error.d.ts +26 -0
  60. package/dist/shared/recoverable-error.js +29 -0
  61. package/dist/shared/task-events.d.ts +0 -26
  62. package/dist/shared/task-events.js +0 -15
  63. package/dist/shared/task-ledger.d.ts +32 -8
  64. package/dist/shared/task-ledger.js +66 -17
  65. package/dist/subagents/builtin/explorer.md +16 -0
  66. package/dist/subagents/builtin/researcher.md +17 -0
  67. package/dist/subagents/builtin/verifier.md +17 -0
  68. package/dist/subagents/discovery.d.ts +17 -3
  69. package/dist/subagents/discovery.js +88 -15
  70. package/dist/subagents/tool.d.ts +21 -1
  71. package/dist/subagents/tool.js +140 -12
  72. package/dist/tasks/control.d.ts +4 -0
  73. package/dist/tasks/control.js +3 -0
  74. package/dist/tasks/store.d.ts +28 -1
  75. package/dist/tasks/store.js +63 -6
  76. package/dist/tasks/transitions.d.ts +40 -0
  77. package/dist/tasks/transitions.js +82 -0
  78. package/dist/tools/bash.d.ts +2 -0
  79. package/dist/tools/bash.js +18 -5
  80. package/dist/tools/event-manage.js +28 -77
  81. package/dist/tools/index.d.ts +4 -0
  82. package/dist/tools/index.js +7 -2
  83. package/dist/tools/job.js +2 -2
  84. package/dist/tools/memory-manage.js +0 -1
  85. package/dist/tools/registry.d.ts +29 -8
  86. package/dist/tools/registry.js +39 -22
  87. package/dist/tools/send-media.d.ts +28 -0
  88. package/dist/tools/send-media.js +88 -0
  89. package/dist/tools/task-manage/create.d.ts +2 -0
  90. package/dist/tools/task-manage/create.js +35 -0
  91. package/dist/tools/task-manage/lifecycle.d.ts +6 -0
  92. package/dist/tools/task-manage/lifecycle.js +197 -0
  93. package/dist/tools/task-manage/schema.d.ts +43 -0
  94. package/dist/tools/task-manage/schema.js +90 -0
  95. package/dist/tools/task-manage/shared.d.ts +36 -0
  96. package/dist/tools/task-manage/shared.js +247 -0
  97. package/dist/tools/task-manage/types.d.ts +53 -0
  98. package/dist/tools/task-manage/types.js +1 -0
  99. package/dist/tools/task-manage/verification.d.ts +16 -0
  100. package/dist/tools/task-manage/verification.js +112 -0
  101. package/dist/tools/task-manage.d.ts +9 -89
  102. package/dist/tools/task-manage.js +8 -696
  103. package/dist/tools/tool-details.d.ts +44 -0
  104. package/dist/tools/tool-details.js +62 -0
  105. package/dist/tui/app.js +2 -0
  106. package/dist/tui/terminal-media-sender.d.ts +9 -0
  107. package/dist/tui/terminal-media-sender.js +15 -0
  108. package/package.json +2 -2
  109. package/dist/playbooks/task-recurring.md +0 -41
  110. package/dist/playbooks/task-repair.md +0 -45
@@ -0,0 +1,88 @@
1
+ import { basename, extname } from "path";
2
+ import { Type } from "typebox";
3
+ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
+ import { logSecurityEvent } from "../security/logger.js";
5
+ import { guardPath } from "../security/path-guard.js";
6
+ import { shellEscape } from "../shared/shell-escape.js";
7
+ /** Extensions delivered as inline images; everything else goes as a file attachment. */
8
+ const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"]);
9
+ const sendMediaSchema = Type.Object({
10
+ label: Type.String({ description: "Brief description of what you're sending and why (shown to the user)" }),
11
+ path: Type.String({ description: "Path to the local file to send (relative to the workspace, or absolute)" }),
12
+ fileName: Type.Optional(Type.String({ description: "Display name for the recipient; defaults to the file's own name" })),
13
+ });
14
+ function formatPathBlockMessage(resolvedPath, category, reason) {
15
+ const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
16
+ if (reason)
17
+ lines.push(`Reason: ${reason}`);
18
+ if (resolvedPath)
19
+ lines.push(`Resolved path: ${resolvedPath}`);
20
+ return lines.join("\n");
21
+ }
22
+ /**
23
+ * Send a workspace file to the current channel as a native attachment (inline
24
+ * image or downloadable file). Bound to its channel at build time — like `read`
25
+ * and `bash` — so the model never chooses the destination. The file is read
26
+ * through the `Executor` (base64, exactly as `read` does for images) so the tool
27
+ * works regardless of where the executor runs, and every path passes the same
28
+ * path-guard as the file tools before any bytes leave the box.
29
+ */
30
+ export function createSendMediaTool(executor, options) {
31
+ const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
32
+ const securityContext = options.securityContext ?? { workspaceDir: process.cwd(), cwd: process.cwd() };
33
+ return {
34
+ name: "send_media",
35
+ label: "send_media",
36
+ description: "Send a local file to the user in the current channel as a native attachment. " +
37
+ "Image files (jpg, png, gif, webp, bmp) are delivered inline; everything else is sent as a downloadable file. " +
38
+ "Use this to hand the user a generated report, screenshot, chart, or export — not for showing file contents to yourself (use `read` for that).",
39
+ parameters: sendMediaSchema,
40
+ execute: async (_toolCallId, { path, fileName }, signal) => {
41
+ if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
42
+ const guardResult = guardPath(path, "read", { ...securityContext, config: securityConfig.pathGuard });
43
+ if (!guardResult.allowed) {
44
+ await logSecurityEvent(securityContext.workspaceDir, securityConfig, {
45
+ type: "path",
46
+ tool: "send_media",
47
+ channelId: options.channelId,
48
+ rawPath: path,
49
+ operation: "read",
50
+ resolvedPath: guardResult.resolvedPath,
51
+ category: guardResult.category,
52
+ reason: guardResult.reason,
53
+ });
54
+ throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
55
+ }
56
+ }
57
+ // Confirm the target is a readable regular file before reading it, so the
58
+ // agent gets "not a file" rather than a confusing base64 error.
59
+ const stat = await executor.exec(`test -f ${shellEscape(path)} && echo OK || echo NO`, { signal });
60
+ if (stat.stdout.trim() !== "OK") {
61
+ throw new Error(`Cannot send ${path}: not a regular file (does it exist?).`);
62
+ }
63
+ const encoded = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
64
+ if (encoded.code !== 0) {
65
+ throw new Error(encoded.stderr || `Failed to read file: ${path}`);
66
+ }
67
+ const data = Buffer.from(encoded.stdout.replace(/\s/g, ""), "base64");
68
+ if (data.length === 0) {
69
+ throw new Error(`Cannot send ${path}: the file is empty.`);
70
+ }
71
+ const name = fileName?.trim() || basename(path);
72
+ const kind = IMAGE_EXTENSIONS.has(extname(name).toLowerCase()) ? "image" : "file";
73
+ const result = await options.mediaSender.sendMedia(options.channelId, { data, fileName: name, kind });
74
+ if (!result.ok) {
75
+ throw new Error(result.error ?? "Failed to send the file to the channel.");
76
+ }
77
+ return {
78
+ content: [
79
+ {
80
+ type: "text",
81
+ text: `Sent ${kind === "image" ? "image" : "file"} "${name}" (${(data.length / 1024).toFixed(1)}KB) to the channel.`,
82
+ },
83
+ ],
84
+ details: undefined,
85
+ };
86
+ },
87
+ };
88
+ }
@@ -0,0 +1,2 @@
1
+ import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./types.js";
2
+ export declare function createTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
@@ -0,0 +1,35 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { writeFileAtomically } from "../../shared/atomic-file.js";
5
+ import { normalizeTaskId, uncheckedTaskAcceptanceItems } from "../../shared/task-ledger.js";
6
+ import { RecoverableToolError } from "../tool-details.js";
7
+ import { renderTaskFile, renderTaskSkeleton, tasksDir, validateTaskRelations } from "./shared.js";
8
+ export async function createTask(options, request) {
9
+ if (!request.id)
10
+ throw new RecoverableToolError('action "create" requires an id.');
11
+ const id = normalizeTaskId(request.id);
12
+ const dir = tasksDir(options);
13
+ const taskPath = join(dir, `${id}.md`);
14
+ const archivePath = join(dir, "archive", `${id}.md`);
15
+ if (existsSync(taskPath)) {
16
+ throw new RecoverableToolError(`Task "${id}" already exists; use action "set" or edit the body instead.`);
17
+ }
18
+ if (existsSync(archivePath)) {
19
+ throw new RecoverableToolError(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
20
+ }
21
+ const { fields, body } = renderTaskSkeleton(request);
22
+ const badDod = uncheckedTaskAcceptanceItems(body).find((item) => item.startsWith("DoD has no checklist items"));
23
+ if (badDod)
24
+ throw new RecoverableToolError(badDod);
25
+ await validateTaskRelations(options, id, fields);
26
+ await mkdir(dir, { recursive: true });
27
+ await writeFileAtomically(taskPath, renderTaskFile(fields, body));
28
+ return {
29
+ action: "create",
30
+ id,
31
+ path: taskPath,
32
+ status: fields.status,
33
+ notice: `已创建任务 \`${id}\`(status: ${fields.status}${fields.wake ? `, 首次唤醒: ${fields.wake}` : ""})。`,
34
+ };
35
+ }
@@ -0,0 +1,6 @@
1
+ import type { TaskManageRequest, TaskManageResult, TaskManageToolOptions } from "./types.js";
2
+ export declare function setTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
3
+ export declare function progressTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
4
+ export declare function doneTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
5
+ export declare function cancelTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
6
+ export declare function listTasks(options: TaskManageToolOptions): Promise<TaskManageResult>;
@@ -0,0 +1,197 @@
1
+ import { mkdir, rename } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { writeFileAtomically } from "../../shared/atomic-file.js";
4
+ import { appendCurrentCycleNote, normalizeTaskId, readActiveTasks, uncheckedTaskAcceptanceItems, } from "../../shared/task-ledger.js";
5
+ import { workspaceSubjectHash } from "../../tasks/artifact-subject.js";
6
+ import { invalidateTaskVerification } from "../../tasks/control.js";
7
+ import { dependencyState, taskBodyHash } from "../../tasks/store.js";
8
+ import { normalizeStoredStatus, resolveTaskTransition } from "../../tasks/transitions.js";
9
+ import { RecoverableToolError } from "../tool-details.js";
10
+ import { appendCompletionEvidence, applySet, cleanupTaskEvents, markdownValue, readTaskDocument, renderTaskFile, requiredField, tasksDir, unfinishedChildren, validateTaskRelations, } from "./shared.js";
11
+ import { assertVerificationAttestationMatches } from "./verification.js";
12
+ export async function setTask(options, request) {
13
+ if (!request.id)
14
+ throw new RecoverableToolError('action "set" requires an id.');
15
+ const id = normalizeTaskId(request.id);
16
+ const taskPath = join(tasksDir(options), `${id}.md`);
17
+ const { fields, body } = await readTaskDocument(taskPath, id, request.control !== undefined);
18
+ const fromStatus = normalizeStoredStatus(fields.status);
19
+ resolveTaskTransition("set", id, fromStatus, request.status);
20
+ const nextFields = applySet(fields, request);
21
+ // Leaving the verification lane by hand invalidates any recorded verdict — a passed/failed
22
+ // attestation only describes the task while it stayed in `verifying` (D3).
23
+ if (fromStatus === "verifying" && nextFields.status !== "verifying" && nextFields.control) {
24
+ nextFields.control = invalidateTaskVerification(nextFields.control);
25
+ }
26
+ await validateTaskRelations(options, id, nextFields);
27
+ await writeFileAtomically(taskPath, renderTaskFile(nextFields, body));
28
+ return {
29
+ action: "set",
30
+ id,
31
+ path: taskPath,
32
+ status: nextFields.status,
33
+ notice: `已更新任务 \`${id}\`(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
34
+ };
35
+ }
36
+ export async function progressTask(options, request) {
37
+ if (!request.id)
38
+ throw new RecoverableToolError('action "progress" requires an id.');
39
+ const id = normalizeTaskId(request.id);
40
+ const note = requiredField(request.note, "note", "progress");
41
+ const taskPath = join(tasksDir(options), `${id}.md`);
42
+ const { fields, body } = await readTaskDocument(taskPath, id);
43
+ resolveTaskTransition("progress", id, normalizeStoredStatus(fields.status), request.status);
44
+ const nextFields = applySet(fields, request);
45
+ await validateTaskRelations(options, id, nextFields);
46
+ // D4: a progress note only appends to Current Cycle — it never touches the contract segment
47
+ // that PASS/approval bind to, so it no longer invalidates verification or approval. A real
48
+ // contract change (Goal/DoD/Manual/Verification) goes through write/edit and is caught by the
49
+ // contract-hash checks in verify/done/approve.
50
+ if (nextFields.control) {
51
+ if (request.status === "waiting") {
52
+ nextFields.control.lastOutcome = "blocked";
53
+ }
54
+ else if (request.control?.lastOutcome === undefined) {
55
+ nextFields.control.lastOutcome = "progress";
56
+ if (request.control?.blockedReason === undefined)
57
+ nextFields.control.blockedReason = undefined;
58
+ }
59
+ }
60
+ const nextBody = appendCurrentCycleNote(body, note);
61
+ await writeFileAtomically(taskPath, renderTaskFile(nextFields, nextBody));
62
+ return {
63
+ action: "progress",
64
+ id,
65
+ path: taskPath,
66
+ status: nextFields.status,
67
+ notice: `已记录任务 \`${id}\` 的进展(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
68
+ };
69
+ }
70
+ export async function doneTask(options, request) {
71
+ if (!request.id)
72
+ throw new RecoverableToolError('action "done" requires an id.');
73
+ const id = normalizeTaskId(request.id);
74
+ const dir = tasksDir(options);
75
+ const taskPath = join(dir, `${id}.md`);
76
+ const { fields, body } = await readTaskDocument(taskPath, id);
77
+ resolveTaskTransition("done", id, normalizeStoredStatus(fields.status));
78
+ const uncheckedAcceptance = uncheckedTaskAcceptanceItems(body);
79
+ if (uncheckedAcceptance.length > 0) {
80
+ throw new RecoverableToolError(`Task "${id}" still has unchecked acceptance items: ${uncheckedAcceptance.join("; ")}. Check them with evidence before done.`);
81
+ }
82
+ const dependencies = await dependencyState(options.channelDir, fields.control?.dependsOn ?? [], id);
83
+ if (!dependencies.ready) {
84
+ throw new RecoverableToolError(`Task "${id}" cannot be completed: ${dependencies.reason}. Complete its dependencies first.`);
85
+ }
86
+ const children = await unfinishedChildren(options, id);
87
+ if (children.length > 0) {
88
+ throw new RecoverableToolError(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Finish or cancel them first.`);
89
+ }
90
+ if (fields.control?.sideEffects === "external") {
91
+ if (fields.control.externalApproval === "required") {
92
+ throw new Error(`Task "${id}" requires explicit external-action approval before it can be completed.`);
93
+ }
94
+ if (fields.control.externalApproval === "granted" && fields.control.approvalBodyHash !== taskBodyHash(body)) {
95
+ throw new Error(`Task "${id}" changed after external-action approval; ask the user to run /tasks approve ${id} again.`);
96
+ }
97
+ }
98
+ if (fields.control?.verification.mode === "independent") {
99
+ const verification = fields.control.verification;
100
+ if (verification.status !== "passed" || !verification.bodyHash || !verification.runId) {
101
+ throw new RecoverableToolError(`Task "${id}" requires an independent PASS. Run a purpose=verify sub-agent, then task_manage verify with its run id.`);
102
+ }
103
+ if (verification.bodyHash !== taskBodyHash(body)) {
104
+ throw new RecoverableToolError(`Task "${id}" changed after its independent PASS; rerun verification before done.`);
105
+ }
106
+ if (verification.subjectHash) {
107
+ const currentSubject = await workspaceSubjectHash(options.workingDirectory ?? process.cwd());
108
+ if (currentSubject !== verification.subjectHash) {
109
+ throw new RecoverableToolError(`Task "${id}" artifacts changed after its independent PASS; rerun verification before done.`);
110
+ }
111
+ }
112
+ await assertVerificationAttestationMatches(options.channelDir, id, verification);
113
+ }
114
+ const bodyWithEvidence = appendCompletionEvidence(body, request);
115
+ if (fields.control) {
116
+ fields.control.lastOutcome = "verified";
117
+ fields.control.blockedReason = undefined;
118
+ }
119
+ // A recurring task (schedule frontmatter) sleeps in place until its next occurrence. The
120
+ // wake is cleared here and refilled to the next cron occurrence by the single time rule
121
+ // (`normalizeTaskFields`) on the write path, so "done + wake" always describes "asleep
122
+ // until next cycle" without a per-action recompute (D1).
123
+ const doneFields = { ...fields, status: "done", wake: undefined };
124
+ await writeFileAtomically(taskPath, renderTaskFile(doneFields, bodyWithEvidence));
125
+ const { deleted } = await cleanupTaskEvents(options, id);
126
+ // Recurring (schedule frontmatter) sleeps in place; one-shot → archive.
127
+ const recurring = Boolean(fields.schedule);
128
+ let archived = false;
129
+ let finalPath = taskPath;
130
+ if (!recurring) {
131
+ const archiveDir = join(dir, "archive");
132
+ await mkdir(archiveDir, { recursive: true });
133
+ finalPath = join(archiveDir, `${id}.md`);
134
+ await rename(taskPath, finalPath);
135
+ archived = true;
136
+ }
137
+ const cleanup = deleted.length > 0 ? `,清理事件 ${deleted.join(", ")}` : "";
138
+ const disposition = archived ? "已归档" : "周期任务留原地待下次唤醒";
139
+ return {
140
+ action: "done",
141
+ id,
142
+ path: finalPath,
143
+ status: "done",
144
+ archived,
145
+ deletedEvents: deleted,
146
+ notice: `任务 \`${id}\` 已完成(${disposition}${cleanup})。`,
147
+ };
148
+ }
149
+ export async function cancelTask(options, request) {
150
+ if (!request.id)
151
+ throw new RecoverableToolError('action "cancel" requires an id.');
152
+ const id = normalizeTaskId(request.id);
153
+ const reason = requiredField(request.reason, "reason", "cancel");
154
+ const dir = tasksDir(options);
155
+ const taskPath = join(dir, `${id}.md`);
156
+ const { fields, body } = await readTaskDocument(taskPath, id);
157
+ resolveTaskTransition("cancel", id, normalizeStoredStatus(fields.status));
158
+ const children = await unfinishedChildren(options, id);
159
+ if (children.length > 0) {
160
+ throw new RecoverableToolError(`Task "${id}" still has unfinished child tasks: ${children.join(", ")}. Cancel or re-parent them first.`);
161
+ }
162
+ if (fields.control) {
163
+ fields.control.lastOutcome = "blocked";
164
+ fields.control.blockedReason = `Cancelled: ${reason}`;
165
+ }
166
+ const cancelledBody = `${body.replace(/\n+$/, "\n")}\n## Cancellation\n\n- Reason: ${markdownValue(reason)}\n`;
167
+ await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "cancelled", wake: undefined }, cancelledBody));
168
+ const { deleted } = await cleanupTaskEvents(options, id);
169
+ const archiveDir = join(dir, "archive");
170
+ await mkdir(archiveDir, { recursive: true });
171
+ const finalPath = join(archiveDir, `${id}.md`);
172
+ await rename(taskPath, finalPath);
173
+ return {
174
+ action: "cancel",
175
+ id,
176
+ path: finalPath,
177
+ status: "cancelled",
178
+ archived: true,
179
+ deletedEvents: deleted,
180
+ notice: `任务 \`${id}\` 已取消并归档${deleted.length ? `,清理事件 ${deleted.join(", ")}` : ""}。`,
181
+ };
182
+ }
183
+ export async function listTasks(options) {
184
+ const entries = await readActiveTasks(tasksDir(options));
185
+ return {
186
+ action: "list",
187
+ tasks: entries.map((entry) => ({
188
+ id: entry.id,
189
+ title: entry.title,
190
+ status: entry.frontmatter.readable ? (entry.frontmatter.status ?? "active") : "unreadable",
191
+ wake: entry.frontmatter.wake,
192
+ actionable: entry.actionable,
193
+ control: entry.frontmatter.control,
194
+ })),
195
+ notice: `台账共有 ${entries.length} 个 active 任务。`,
196
+ };
197
+ }
@@ -0,0 +1,43 @@
1
+ import { Type } from "typebox";
2
+ import type { TaskManageAction } from "./types.js";
3
+ export declare const SETTABLE_STATUSES: readonly ["active", "waiting", "paused"];
4
+ export declare const taskManageSchema: Type.TObject<{
5
+ label: Type.TString;
6
+ action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"progress">, Type.TLiteral<"set">, Type.TLiteral<"verify">, Type.TLiteral<"done">, Type.TLiteral<"cancel">, Type.TLiteral<"candidate">, Type.TLiteral<"list">]>;
7
+ id: Type.TOptional<Type.TString>;
8
+ title: Type.TOptional<Type.TString>;
9
+ goal: Type.TOptional<Type.TString>;
10
+ dod: Type.TOptional<Type.TString>;
11
+ manual: Type.TOptional<Type.TString>;
12
+ verificationPlan: Type.TOptional<Type.TString>;
13
+ control: Type.TOptional<Type.TObject<{
14
+ priority: Type.TOptional<Type.TUnion<[Type.TLiteral<"low">, Type.TLiteral<"normal">, Type.TLiteral<"high">, Type.TLiteral<"critical">]>>;
15
+ deadline: Type.TOptional<Type.TString>;
16
+ nextAction: Type.TOptional<Type.TString>;
17
+ lastOutcome: Type.TOptional<Type.TUnion<[Type.TLiteral<"pending">, Type.TLiteral<"running">, Type.TLiteral<"progress">, Type.TLiteral<"blocked">, Type.TLiteral<"failed">, Type.TLiteral<"verified">]>>;
18
+ blockedReason: Type.TOptional<Type.TString>;
19
+ parent: Type.TOptional<Type.TString>;
20
+ dependsOn: Type.TOptional<Type.TArray<Type.TString>>;
21
+ isolation: Type.TOptional<Type.TUnion<[Type.TLiteral<"shared">, Type.TLiteral<"worktree">]>>;
22
+ sideEffects: Type.TOptional<Type.TUnion<[Type.TLiteral<"read-only">, Type.TLiteral<"workspace">, Type.TLiteral<"external">]>>;
23
+ externalApproval: Type.TOptional<Type.TUnion<[Type.TLiteral<"not-required">, Type.TLiteral<"required">]>>;
24
+ maxAttempts: Type.TOptional<Type.TInteger>;
25
+ maxTokens: Type.TOptional<Type.TNumber>;
26
+ maxCostUsd: Type.TOptional<Type.TNumber>;
27
+ maxWallTimeMinutes: Type.TOptional<Type.TNumber>;
28
+ verificationMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"evidence">, Type.TLiteral<"independent">]>>;
29
+ worktreePath: Type.TOptional<Type.TString>;
30
+ worktreeBranch: Type.TOptional<Type.TString>;
31
+ }>>;
32
+ status: Type.TOptional<Type.TUnion<Type.TLiteral<"active" | "waiting" | "paused">[]>>;
33
+ wake: Type.TOptional<Type.TString>;
34
+ schedule: Type.TOptional<Type.TString>;
35
+ recurrence: Type.TOptional<Type.TString>;
36
+ note: Type.TOptional<Type.TString>;
37
+ verifierRunId: Type.TOptional<Type.TString>;
38
+ summary: Type.TOptional<Type.TString>;
39
+ evidence: Type.TOptional<Type.TString>;
40
+ residualRisk: Type.TOptional<Type.TString>;
41
+ reason: Type.TOptional<Type.TString>;
42
+ }>;
43
+ export declare function parseAction(action: string): TaskManageAction;
@@ -0,0 +1,90 @@
1
+ import { Type } from "typebox";
2
+ import { SETTABLE_TASK_STATUSES } from "../../tasks/transitions.js";
3
+ import { RecoverableToolError } from "../tool-details.js";
4
+ export const SETTABLE_STATUSES = SETTABLE_TASK_STATUSES;
5
+ const taskControlSchema = Type.Object({
6
+ priority: Type.Optional(Type.Union([Type.Literal("low"), Type.Literal("normal"), Type.Literal("high"), Type.Literal("critical")])),
7
+ deadline: Type.Optional(Type.String({ description: "ISO8601 deadline; empty string clears it." })),
8
+ nextAction: Type.Optional(Type.String({ description: "Concrete next executable step; empty string clears it." })),
9
+ lastOutcome: Type.Optional(Type.Union([
10
+ Type.Literal("pending"),
11
+ Type.Literal("running"),
12
+ Type.Literal("progress"),
13
+ Type.Literal("blocked"),
14
+ Type.Literal("failed"),
15
+ Type.Literal("verified"),
16
+ ])),
17
+ blockedReason: Type.Optional(Type.String({ description: "Why work cannot currently proceed; empty clears it." })),
18
+ parent: Type.Optional(Type.String({ description: "Parent task id; empty clears it." })),
19
+ dependsOn: Type.Optional(Type.Array(Type.String(), { description: "Task ids that must be done first." })),
20
+ isolation: Type.Optional(Type.Union([Type.Literal("shared"), Type.Literal("worktree")])),
21
+ sideEffects: Type.Optional(Type.Union([Type.Literal("read-only"), Type.Literal("workspace"), Type.Literal("external")])),
22
+ externalApproval: Type.Optional(Type.Union([Type.Literal("not-required"), Type.Literal("required")], {
23
+ description: 'External approval can only be granted by a user with "/tasks approve <id>".',
24
+ })),
25
+ maxAttempts: Type.Optional(Type.Integer({ minimum: 1 })),
26
+ maxTokens: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
27
+ maxCostUsd: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
28
+ maxWallTimeMinutes: Type.Optional(Type.Number({ minimum: 0, description: "0 clears this budget." })),
29
+ verificationMode: Type.Optional(Type.Union([Type.Literal("evidence"), Type.Literal("independent")], {
30
+ description: 'On create, defaults to "evidence" (maker self-checks the DoD against concrete evidence). Set "independent" only when the task produces a checkable artifact (code, config, a runnable command) that a separate read-only verifier sub-agent can inspect — for research/writing/reminder-style tasks, "evidence" is cheaper and just as trustworthy.',
31
+ })),
32
+ worktreePath: Type.Optional(Type.String({ description: "Owned worktree path; empty clears it." })),
33
+ worktreeBranch: Type.Optional(Type.String()),
34
+ });
35
+ export const taskManageSchema = Type.Object({
36
+ label: Type.String({ description: "Brief description of the ledger change (shown to the user)" }),
37
+ action: Type.Union([
38
+ Type.Literal("create"),
39
+ Type.Literal("progress"),
40
+ Type.Literal("set"),
41
+ Type.Literal("verify"),
42
+ Type.Literal("done"),
43
+ Type.Literal("cancel"),
44
+ Type.Literal("candidate"),
45
+ Type.Literal("list"),
46
+ ], {
47
+ description: '"create" writes a governed task; "progress" atomically checkpoints work; "candidate" requests independent verification; "set" repairs metadata; "verify" imports an independent verifier attestation; "done" closes verified work; "cancel" closes abandoned work; "list" returns tasks. Recurring cycles are reopened automatically by the runtime.',
48
+ }),
49
+ id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/progress/set/done." })),
50
+ title: Type.Optional(Type.String({ description: "Required for create: task title used as the H1 heading." })),
51
+ goal: Type.Optional(Type.String({ description: "Required for create: concise task goal." })),
52
+ dod: Type.Optional(Type.String({
53
+ description: 'Required for create: acceptance criteria as Markdown checklist items, one per line, e.g. "- [ ] <criterion>". Plain prose or a numbered list without checkboxes is rejected — candidate/done can only verify items that are checkable.',
54
+ })),
55
+ manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
56
+ verificationPlan: Type.Optional(Type.String({ description: "Optional for create: deterministic checks the verifier must perform." })),
57
+ control: Type.Optional(taskControlSchema),
58
+ status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/progress/set. To close a task use action done, not status." })),
59
+ wake: Type.Optional(Type.String({
60
+ description: "ISO8601 earliest-recheck time for create/progress/set; empty string clears it. The native task driver resumes it; no .checkin event is needed.",
61
+ })),
62
+ schedule: Type.Optional(Type.String({
63
+ description: "Five-field cron cadence (host timezone) that makes this a recurring task; empty string clears it. " +
64
+ "On done, the driver sleeps the task until the next occurrence and reopens the next cycle automatically. Min every 30 minutes.",
65
+ })),
66
+ recurrence: Type.Optional(Type.String({ description: "Human annotation only (e.g. 每周一); empty string clears it." })),
67
+ note: Type.Optional(Type.String({
68
+ description: "Required for progress: concise Current Cycle entry covering what changed, evidence observed, and the next step.",
69
+ })),
70
+ verifierRunId: Type.Optional(Type.String({ description: "Required for verify: run id returned by a purpose=verify sub-agent." })),
71
+ summary: Type.Optional(Type.String({ description: "Required for done: concise completion summary." })),
72
+ evidence: Type.Optional(Type.String({
73
+ description: "Required for done: verification evidence (tests, commands, review result, external confirmation, or a clear not-run reason).",
74
+ })),
75
+ residualRisk: Type.Optional(Type.String({ description: "Optional for done: remaining risk or follow-up note." })),
76
+ reason: Type.Optional(Type.String({ description: "Required for cancel: why the task was abandoned." })),
77
+ });
78
+ export function parseAction(action) {
79
+ if (action === "create" ||
80
+ action === "progress" ||
81
+ action === "candidate" ||
82
+ action === "set" ||
83
+ action === "verify" ||
84
+ action === "done" ||
85
+ action === "cancel" ||
86
+ action === "list") {
87
+ return action;
88
+ }
89
+ throw new RecoverableToolError("Unsupported task action. Use create, progress, candidate, set, verify, done, cancel, or list.");
90
+ }
@@ -0,0 +1,36 @@
1
+ import type { TaskFields, TaskManageRequest, TaskManageToolOptions } from "./types.js";
2
+ export declare function tasksDir(options: TaskManageToolOptions): string;
3
+ export declare function eventsDir(options: TaskManageToolOptions): string;
4
+ export declare function renderTaskFile(fields: TaskFields, body: string): string;
5
+ export declare function requiredField(value: string | undefined, field: string, action: string): string;
6
+ export declare function requireNonEmpty(value: string | undefined, field: string): string;
7
+ export declare function markdownValue(value: string): string;
8
+ export declare function appendCompletionEvidence(body: string, request: TaskManageRequest): string;
9
+ export declare function renderTaskSkeleton(request: TaskManageRequest): {
10
+ fields: TaskFields;
11
+ body: string;
12
+ };
13
+ /**
14
+ * Read a task file and split it into validated frontmatter and a verbatim body.
15
+ * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
16
+ * rather than guessed at, so task_manage never silently mangles a body.
17
+ */
18
+ export declare function readTaskDocument(taskPath: string, id: string, allowControlRepair?: boolean): Promise<{
19
+ fields: TaskFields;
20
+ body: string;
21
+ }>;
22
+ /** Apply a `set` request's optional fields onto the existing frontmatter. */
23
+ export declare function applySet(fields: TaskFields, request: TaskManageRequest): TaskFields;
24
+ export declare function validateTaskRelations(options: TaskManageToolOptions, id: string, fields: TaskFields): Promise<void>;
25
+ /**
26
+ * On close-out (done or cancel), delete every task-owned event.
27
+ *
28
+ * Recurrence cadence now lives solely in the task's `schedule` frontmatter (027/029), so a
29
+ * recurring task needs no surviving `.schedule` event — the driver reopens each cycle from
30
+ * frontmatter. Any remaining task-owned events are temporary sensors/check-ins that a closed
31
+ * task should not keep alive. A file that cannot be parsed is left for `/events` to handle.
32
+ */
33
+ export declare function cleanupTaskEvents(options: TaskManageToolOptions, id: string): Promise<{
34
+ deleted: string[];
35
+ }>;
36
+ export declare function unfinishedChildren(options: TaskManageToolOptions, parentId: string): Promise<string[]>;