@oyasmi/pipiclaw 0.7.4 → 0.7.5

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.
@@ -38,6 +38,12 @@ export interface PipiclawToolsConfig {
38
38
  enabled: boolean;
39
39
  };
40
40
  };
41
+ events: {
42
+ enabled: boolean;
43
+ };
44
+ tasks: {
45
+ enabled: boolean;
46
+ };
41
47
  rtk: {
42
48
  enabled: boolean;
43
49
  };
@@ -38,6 +38,12 @@ export const DEFAULT_TOOLS_CONFIG = {
38
38
  enabled: true,
39
39
  },
40
40
  },
41
+ events: {
42
+ enabled: true,
43
+ },
44
+ tasks: {
45
+ enabled: true,
46
+ },
41
47
  rtk: {
42
48
  enabled: false,
43
49
  },
@@ -89,6 +95,8 @@ function mergeToolsConfig(source, configPath, diagnostics) {
89
95
  const memorySave = isRecord(memory.save) ? memory.save : {};
90
96
  const skills = isRecord(tools.skills) ? tools.skills : {};
91
97
  const manage = isRecord(skills.manage) ? skills.manage : {};
98
+ const events = isRecord(tools.events) ? tools.events : {};
99
+ const tasks = isRecord(tools.tasks) ? tools.tasks : {};
92
100
  const rtk = isRecord(tools.rtk) ? tools.rtk : {};
93
101
  const search = isRecord(web.search) ? web.search : {};
94
102
  const fetch = isRecord(web.fetch) ? web.fetch : {};
@@ -173,6 +181,12 @@ function mergeToolsConfig(source, configPath, diagnostics) {
173
181
  : DEFAULT_TOOLS_CONFIG.tools.skills.manage.enabled,
174
182
  },
175
183
  },
184
+ events: {
185
+ enabled: typeof events.enabled === "boolean" ? events.enabled : DEFAULT_TOOLS_CONFIG.tools.events.enabled,
186
+ },
187
+ tasks: {
188
+ enabled: typeof tasks.enabled === "boolean" ? tasks.enabled : DEFAULT_TOOLS_CONFIG.tools.tasks.enabled,
189
+ },
176
190
  rtk: {
177
191
  enabled: typeof rtk.enabled === "boolean" ? rtk.enabled : DEFAULT_TOOLS_CONFIG.tools.rtk.enabled,
178
192
  },
@@ -0,0 +1,35 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ import { type ScheduledEvent } from "../runtime/events.js";
4
+ import type { SecurityConfig } from "../security/types.js";
5
+ declare const eventManageSchema: Type.TObject<{
6
+ label: Type.TString;
7
+ action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"update">, Type.TLiteral<"delete">]>;
8
+ name: Type.TString;
9
+ definition: Type.TOptional<Type.TString>;
10
+ }>;
11
+ export type EventManageAction = "create" | "update" | "delete";
12
+ export interface EventManageResult {
13
+ action: EventManageAction;
14
+ name: string;
15
+ path: string;
16
+ eventType?: ScheduledEvent["type"];
17
+ channelId?: string;
18
+ bytesWritten?: number;
19
+ deleted?: boolean;
20
+ notice: string;
21
+ }
22
+ export interface EventManageRequest {
23
+ action: EventManageAction;
24
+ name: string;
25
+ definition?: string;
26
+ }
27
+ export interface EventManageToolOptions {
28
+ workspaceDir: string;
29
+ workspacePath: string;
30
+ channelId: string;
31
+ commandGuardConfig: SecurityConfig["commandGuard"];
32
+ }
33
+ export declare function manageEvent(options: EventManageToolOptions, request: EventManageRequest): Promise<EventManageResult>;
34
+ export declare function createEventManageTool(options: EventManageToolOptions): AgentTool<typeof eventManageSchema>;
35
+ export {};
@@ -0,0 +1,238 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readdir, readFile, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { Cron } from "croner";
5
+ import { Type } from "typebox";
6
+ import { resolveEventPath } from "../runtime/event-commands.js";
7
+ import { parseScheduledEventContent } from "../runtime/events.js";
8
+ import { guardCommand } from "../security/command-guard.js";
9
+ import { writeFileAtomically } from "../shared/atomic-file.js";
10
+ import { isRecord } from "../shared/type-guards.js";
11
+ /** one-shot events must be scheduled at least this far out; anything sooner is effectively self-triggering. */
12
+ const MIN_ONE_SHOT_LEAD_MS = 2 * 60 * 1000;
13
+ /** periodic events without a preAction gate may fire no more often than this. */
14
+ const MIN_PERIODIC_INTERVAL_MS = 30 * 60 * 1000;
15
+ /**
16
+ * periodic events WITH a preAction gate may fire this often: the sensor is the token guard
17
+ * (it exits non-zero and stays silent when there is nothing to do), so a tighter cadence is
18
+ * safe and is exactly the design-endorsed posture for completion-driven checks (e.g. polling
19
+ * an agentmux instance until it goes idle). A hard sub-floor still applies so a bogus
20
+ * always-pass preAction cannot drive an arbitrarily hot loop.
21
+ */
22
+ const MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS = 5 * 60 * 1000;
23
+ /** sanity cap on total event files to keep the directory (and the scheduler) from being flooded. */
24
+ const MAX_EVENT_FILES = 50;
25
+ const eventManageSchema = Type.Object({
26
+ label: Type.String({ description: "Brief description of the scheduling change (shown to the user)" }),
27
+ action: Type.Union([Type.Literal("create"), Type.Literal("update"), Type.Literal("delete")], {
28
+ description: 'The event management action to perform: "create", "update", or "delete".',
29
+ }),
30
+ name: Type.String({
31
+ description: "Event name (filename without .json). For task-owned events use `task.<channelId>.<taskId>.<use>`, e.g. `task.dm_123.weekly-report.checkin`.",
32
+ }),
33
+ definition: Type.Optional(Type.String({
34
+ description: "Full event JSON (required for create/update). one-shot / periodic only; immediate is rejected. channelId defaults to the current channel.",
35
+ })),
36
+ });
37
+ function parseAction(action) {
38
+ if (action === "create" || action === "update" || action === "delete") {
39
+ return action;
40
+ }
41
+ throw new Error('Unsupported event action. Use "create", "update", or "delete".');
42
+ }
43
+ function toWorkspacePath(options, hostPath) {
44
+ if (hostPath.startsWith(options.workspaceDir)) {
45
+ return `${options.workspacePath}${hostPath.slice(options.workspaceDir.length)}`;
46
+ }
47
+ return hostPath;
48
+ }
49
+ function validateTimezone(timezone) {
50
+ try {
51
+ new Intl.DateTimeFormat(undefined, { timeZone: timezone });
52
+ }
53
+ catch {
54
+ throw new Error(`Invalid timezone: ${timezone}`);
55
+ }
56
+ }
57
+ function validateOneShot(event) {
58
+ const atTime = new Date(event.at).getTime();
59
+ if (!Number.isFinite(atTime)) {
60
+ throw new Error(`one-shot 'at' is not a valid date: ${event.at}`);
61
+ }
62
+ if (atTime < Date.now() + MIN_ONE_SHOT_LEAD_MS) {
63
+ throw new Error("one-shot 'at' must be at least 2 minutes in the future (self-triggering guard).");
64
+ }
65
+ }
66
+ function validatePeriodic(event) {
67
+ validateTimezone(event.timezone);
68
+ let runs;
69
+ try {
70
+ const cron = new Cron(event.schedule, { timezone: event.timezone });
71
+ runs = cron.nextRuns(3);
72
+ cron.stop();
73
+ }
74
+ catch (error) {
75
+ const message = error instanceof Error ? error.message : String(error);
76
+ throw new Error(`Invalid cron schedule "${event.schedule}": ${message}`);
77
+ }
78
+ // A preAction gate makes a tighter cadence safe (the sensor keeps most fires silent);
79
+ // without one, hold the 30-minute floor so a bare high-frequency cron can't burn tokens.
80
+ const floorMs = event.preAction ? MIN_PERIODIC_INTERVAL_WITH_PREACTION_MS : MIN_PERIODIC_INTERVAL_MS;
81
+ const floorMinutes = Math.round(floorMs / 60000);
82
+ // Fewer than two upcoming runs means no meaningful cadence to rate-limit (e.g. a one-off cron); allow it.
83
+ for (let i = 1; i < runs.length; i++) {
84
+ if (runs[i].getTime() - runs[i - 1].getTime() < floorMs) {
85
+ throw new Error(`periodic events must fire no more often than every ${floorMinutes} minutes` +
86
+ `${event.preAction ? " (even with a preAction gate)" : "; for tighter checks add a preAction gate (min 5 minutes) instead of a high-frequency cron"}.`);
87
+ }
88
+ }
89
+ }
90
+ function validatePreAction(event, commandGuardConfig) {
91
+ if (!event.preAction)
92
+ return;
93
+ const result = guardCommand(event.preAction.command, commandGuardConfig);
94
+ if (!result.allowed) {
95
+ throw new Error(`preAction command blocked by guard: ${result.reason ?? "not allowed"}`);
96
+ }
97
+ }
98
+ /**
99
+ * Validate an agent-supplied event definition and return the normalized, typed event.
100
+ * Rejects immediate events, near-term one-shots, high-frequency periodics, guard-blocked
101
+ * preActions, and cross-channel channelIds. The returned event is what gets persisted, so
102
+ * the file on disk is exactly what was validated.
103
+ */
104
+ function validateDefinition(rawDefinition, name, options) {
105
+ let data;
106
+ try {
107
+ data = JSON.parse(rawDefinition);
108
+ }
109
+ catch (error) {
110
+ const message = error instanceof Error ? error.message : String(error);
111
+ throw new Error(`definition is not valid JSON: ${message}`);
112
+ }
113
+ if (!isRecord(data)) {
114
+ throw new Error("definition must be a JSON object.");
115
+ }
116
+ const providedChannelId = data.channelId;
117
+ if (providedChannelId === undefined || providedChannelId === null || providedChannelId === "") {
118
+ data.channelId = options.channelId;
119
+ }
120
+ else if (providedChannelId !== options.channelId) {
121
+ throw new Error(`definition channelId "${String(providedChannelId)}" does not match the current channel "${options.channelId}".`);
122
+ }
123
+ const event = parseScheduledEventContent(JSON.stringify(data), `${name}.json`);
124
+ if (event.type === "immediate") {
125
+ throw new Error("event_manage cannot create or update immediate events (self-triggering loop guard); " +
126
+ "do the work in the current turn instead.");
127
+ }
128
+ if (event.type === "one-shot") {
129
+ validateOneShot(event);
130
+ }
131
+ if (event.type === "periodic") {
132
+ validatePeriodic(event);
133
+ }
134
+ validatePreAction(event, options.commandGuardConfig);
135
+ return event;
136
+ }
137
+ async function readOwnedEvent(eventPath, name, options) {
138
+ let existing;
139
+ try {
140
+ existing = parseScheduledEventContent(await readFile(eventPath, "utf-8"), `${name}.json`);
141
+ }
142
+ catch (error) {
143
+ const message = error instanceof Error ? error.message : String(error);
144
+ throw new Error(`Existing event "${name}" could not be parsed (${message}); use /events to manage it directly.`);
145
+ }
146
+ if (existing.channelId !== options.channelId) {
147
+ throw new Error(`Event "${name}" belongs to another channel and cannot be modified from here.`);
148
+ }
149
+ return existing;
150
+ }
151
+ async function countEventFiles(dir) {
152
+ if (!existsSync(dir))
153
+ return 0;
154
+ const filenames = await readdir(dir);
155
+ return filenames.filter((filename) => filename.endsWith(".json")).length;
156
+ }
157
+ export async function manageEvent(options, request) {
158
+ const { eventName, eventPath } = resolveEventPath(options.workspaceDir, request.name);
159
+ const eventsDir = join(options.workspaceDir, "events");
160
+ if (request.action === "delete") {
161
+ if (!existsSync(eventPath)) {
162
+ return {
163
+ action: "delete",
164
+ name: eventName,
165
+ path: toWorkspacePath(options, eventPath),
166
+ deleted: false,
167
+ notice: `事件 \`${eventName}\` 不存在,无需删除。`,
168
+ };
169
+ }
170
+ await readOwnedEvent(eventPath, eventName, options);
171
+ await unlink(eventPath);
172
+ return {
173
+ action: "delete",
174
+ name: eventName,
175
+ path: toWorkspacePath(options, eventPath),
176
+ deleted: true,
177
+ notice: `已删除事件 \`${eventName}\`。`,
178
+ };
179
+ }
180
+ if (!request.definition || request.definition.trim().length === 0) {
181
+ throw new Error(`${request.action} requires a non-empty definition.`);
182
+ }
183
+ if (request.action === "create") {
184
+ if (existsSync(eventPath)) {
185
+ throw new Error(`Event "${eventName}" already exists; use action "update" to replace it.`);
186
+ }
187
+ if ((await countEventFiles(eventsDir)) >= MAX_EVENT_FILES) {
188
+ throw new Error(`Too many event files (>= ${MAX_EVENT_FILES}) in workspace/events; clean up stale events before creating more.`);
189
+ }
190
+ }
191
+ else {
192
+ if (!existsSync(eventPath)) {
193
+ throw new Error(`Event "${eventName}" does not exist; use action "create" to add it.`);
194
+ }
195
+ const existing = await readOwnedEvent(eventPath, eventName, options);
196
+ if (existing.type === "immediate") {
197
+ throw new Error(`Event "${eventName}" is an immediate event and cannot be updated via event_manage.`);
198
+ }
199
+ }
200
+ const event = validateDefinition(request.definition, eventName, options);
201
+ const content = `${JSON.stringify(event, null, 2)}\n`;
202
+ await writeFileAtomically(eventPath, content);
203
+ return {
204
+ action: request.action,
205
+ name: eventName,
206
+ path: toWorkspacePath(options, eventPath),
207
+ eventType: event.type,
208
+ channelId: event.channelId,
209
+ bytesWritten: Buffer.byteLength(content, "utf-8"),
210
+ notice: request.action === "create"
211
+ ? `已创建 ${event.type} 事件 \`${eventName}\`。`
212
+ : `已更新 ${event.type} 事件 \`${eventName}\`。`,
213
+ };
214
+ }
215
+ export function createEventManageTool(options) {
216
+ return {
217
+ name: "event_manage",
218
+ label: "event_manage",
219
+ description: "Create, update, or delete scheduled events (one-shot check-ins and periodic cadences) that wake this " +
220
+ "channel later. Use for task self-scheduling: arrange a follow-up after delegating, reschedule while " +
221
+ "blocked, clean up on close. immediate events are rejected; do that work in the current turn.",
222
+ parameters: eventManageSchema,
223
+ execute: async (_toolCallId, args) => {
224
+ const result = await manageEvent(options, {
225
+ action: parseAction(args.action),
226
+ name: args.name,
227
+ definition: args.definition,
228
+ });
229
+ return {
230
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
231
+ details: {
232
+ kind: "event_manage",
233
+ ...result,
234
+ },
235
+ };
236
+ },
237
+ };
238
+ }
@@ -1,11 +1,13 @@
1
1
  import { createBashTool } from "./bash.js";
2
2
  import { createEditTool } from "./edit.js";
3
+ import { createEventManageTool } from "./event-manage.js";
3
4
  import { createMemorySaveTool } from "./memory-save.js";
4
5
  import { createReadTool } from "./read.js";
5
6
  import { createSessionSearchTool } from "./session-search.js";
6
7
  import { createSkillListTool } from "./skill-list.js";
7
8
  import { createSkillManageTool } from "./skill-manage.js";
8
9
  import { createSkillViewTool } from "./skill-view.js";
10
+ import { createTaskManageTool } from "./task-manage.js";
9
11
  import { createWebFetchTool } from "./web-fetch.js";
10
12
  import { createWebSearchTool } from "./web-search.js";
11
13
  import { createWriteTool } from "./write.js";
@@ -131,6 +133,34 @@ export const TOOL_REGISTRY = [
131
133
  enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
132
134
  create: (ctx) => createSkillManageTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
133
135
  },
136
+ {
137
+ name: "event_manage",
138
+ promptHint: "Schedule your own follow-ups: create/update/delete one-shot check-ins and periodic cadences for this channel. " +
139
+ "Name task-owned events `task.<channelId>.<taskId>.<use>` (e.g. .checkin, .schedule) so they clean up together. " +
140
+ "Keep a task's `wake` and its .checkin one-shot in sync — move both, clear both. " +
141
+ "No immediate events; periodic no more often than every 30 min (or 5 min when it carries a preAction gate).",
142
+ availableToSubagents: false,
143
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.events.enabled !== false,
144
+ create: (ctx) => createEventManageTool({
145
+ workspaceDir: ctx.workspaceDir,
146
+ workspacePath: ctx.workspacePath,
147
+ channelId: ctx.channelId,
148
+ commandGuardConfig: ctx.securityConfig.commandGuard,
149
+ }),
150
+ },
151
+ {
152
+ name: "task_manage",
153
+ promptHint: "Update the task ledger: set a task's status/wake/recurrence, close a task out (archives one-shot tasks and " +
154
+ "cleans up its residual events), or list active tasks. Write the task body with write/edit; this owns the frontmatter.",
155
+ availableToSubagents: false,
156
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
157
+ create: (ctx) => createTaskManageTool({
158
+ workspaceDir: ctx.workspaceDir,
159
+ workspacePath: ctx.workspacePath,
160
+ channelDir: ctx.channelDir,
161
+ channelId: ctx.channelId,
162
+ }),
163
+ },
134
164
  ];
135
165
  /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
136
166
  export const SUBAGENT_TOOL_HINT = "Delegate a focused task to a sub-agent with its own isolated context";
@@ -0,0 +1,43 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ declare const taskManageSchema: Type.TObject<{
4
+ label: Type.TString;
5
+ action: Type.TUnion<[Type.TLiteral<"set">, Type.TLiteral<"done">, Type.TLiteral<"list">]>;
6
+ id: Type.TOptional<Type.TString>;
7
+ status: Type.TOptional<Type.TUnion<Type.TLiteral<"open" | "blocked" | "in-progress" | "awaiting-user">[]>>;
8
+ wake: Type.TOptional<Type.TString>;
9
+ recurrence: Type.TOptional<Type.TString>;
10
+ }>;
11
+ export type TaskManageAction = "set" | "done" | "list";
12
+ export interface TaskManageResult {
13
+ action: TaskManageAction;
14
+ id?: string;
15
+ path?: string;
16
+ status?: string;
17
+ archived?: boolean;
18
+ deletedEvents?: string[];
19
+ tasks?: Array<{
20
+ id: string;
21
+ title: string;
22
+ status: string;
23
+ wake?: string;
24
+ actionable: boolean;
25
+ }>;
26
+ notice: string;
27
+ }
28
+ export interface TaskManageRequest {
29
+ action: TaskManageAction;
30
+ id?: string;
31
+ status?: string;
32
+ wake?: string;
33
+ recurrence?: string;
34
+ }
35
+ export interface TaskManageToolOptions {
36
+ workspaceDir: string;
37
+ workspacePath: string;
38
+ channelDir: string;
39
+ channelId: string;
40
+ }
41
+ export declare function manageTask(options: TaskManageToolOptions, request: TaskManageRequest): Promise<TaskManageResult>;
42
+ export declare function createTaskManageTool(options: TaskManageToolOptions): AgentTool<typeof taskManageSchema>;
43
+ export {};
@@ -0,0 +1,226 @@
1
+ import { existsSync } from "node:fs";
2
+ import { mkdir, readdir, readFile, rename, unlink } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { Type } from "typebox";
5
+ import { parseScheduledEventContent } from "../runtime/events.js";
6
+ import { writeFileAtomically } from "../shared/atomic-file.js";
7
+ import { normalizeTaskId, parseTaskFrontmatter, readActiveTasks, taskBody } from "../shared/task-ledger.js";
8
+ const SETTABLE_STATUSES = ["open", "in-progress", "awaiting-user", "blocked"];
9
+ const taskManageSchema = Type.Object({
10
+ label: Type.String({ description: "Brief description of the ledger change (shown to the user)" }),
11
+ action: Type.Union([Type.Literal("set"), Type.Literal("done"), Type.Literal("list")], {
12
+ description: '"set" updates a task\'s status/wake/recurrence; "done" closes it out (archive one-shot tasks, clean up residual events); "list" returns active tasks.',
13
+ }),
14
+ id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for set/done." })),
15
+ status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for set. To close a task use action done, not status." })),
16
+ wake: Type.Optional(Type.String({
17
+ description: "ISO8601 earliest-recheck time for set; empty string clears it. Keep in sync with any .checkin event.",
18
+ })),
19
+ recurrence: Type.Optional(Type.String({ description: "Annotation only (e.g. 每周一); empty string clears it." })),
20
+ });
21
+ function parseAction(action) {
22
+ if (action === "set" || action === "done" || action === "list") {
23
+ return action;
24
+ }
25
+ throw new Error('Unsupported task action. Use "set", "done", or "list".');
26
+ }
27
+ function toWorkspacePath(options, hostPath) {
28
+ if (hostPath.startsWith(options.workspaceDir)) {
29
+ return `${options.workspacePath}${hostPath.slice(options.workspaceDir.length)}`;
30
+ }
31
+ return hostPath;
32
+ }
33
+ function tasksDir(options) {
34
+ return join(options.channelDir, "tasks");
35
+ }
36
+ function eventsDir(options) {
37
+ return join(options.workspaceDir, "events");
38
+ }
39
+ function renderTaskFile(fields, body) {
40
+ const lines = ["---", `status: ${fields.status}`];
41
+ if (fields.wake)
42
+ lines.push(`wake: ${fields.wake}`);
43
+ if (fields.recurrence)
44
+ lines.push(`recurrence: ${fields.recurrence}`);
45
+ lines.push("---");
46
+ return `${lines.join("\n")}\n${body}`;
47
+ }
48
+ /**
49
+ * Read a task file and split it into its three-field frontmatter and verbatim body.
50
+ * Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
51
+ * rather than guessed at, so task_manage never silently mangles a body.
52
+ */
53
+ async function readTaskDocument(taskPath, id) {
54
+ if (!existsSync(taskPath)) {
55
+ throw new Error(`Task "${id}" does not exist; create it with write first.`);
56
+ }
57
+ const content = await readFile(taskPath, "utf-8");
58
+ const frontmatter = parseTaskFrontmatter(content);
59
+ if (!frontmatter.readable) {
60
+ throw new Error(`Task "${id}" has no readable frontmatter; fix it with edit before using task_manage.`);
61
+ }
62
+ return {
63
+ fields: {
64
+ status: frontmatter.status ?? "open",
65
+ wake: frontmatter.wake,
66
+ recurrence: frontmatter.recurrence,
67
+ },
68
+ body: taskBody(content),
69
+ };
70
+ }
71
+ /** Apply a `set` request's optional fields onto the existing frontmatter. */
72
+ function applySet(fields, request) {
73
+ const next = { ...fields };
74
+ if (request.status !== undefined) {
75
+ if (!SETTABLE_STATUSES.includes(request.status)) {
76
+ throw new Error(`Invalid status "${request.status}". Use one of ${SETTABLE_STATUSES.join(", ")}, or action "done".`);
77
+ }
78
+ next.status = request.status;
79
+ }
80
+ if (request.wake !== undefined) {
81
+ const trimmed = request.wake.trim();
82
+ if (trimmed === "") {
83
+ next.wake = undefined;
84
+ }
85
+ else if (!Number.isFinite(new Date(trimmed).getTime())) {
86
+ throw new Error(`wake "${request.wake}" is not a valid ISO8601 date.`);
87
+ }
88
+ else {
89
+ next.wake = trimmed;
90
+ }
91
+ }
92
+ if (request.recurrence !== undefined) {
93
+ const trimmed = request.recurrence.trim();
94
+ next.recurrence = trimmed === "" ? undefined : trimmed;
95
+ }
96
+ return next;
97
+ }
98
+ /**
99
+ * On close-out, delete residual one-shot/immediate events named `task.<channelId>.<id>.*`
100
+ * and report whether a periodic (schedule) event survives. Unparseable events with the
101
+ * prefix are left untouched (fail-safe: don't blind-delete something we can't classify).
102
+ */
103
+ async function cleanupTaskEvents(options, id) {
104
+ const dir = eventsDir(options);
105
+ if (!existsSync(dir))
106
+ return { deleted: [], hasPeriodic: false };
107
+ const prefix = `task.${options.channelId}.${id}.`;
108
+ const deleted = [];
109
+ let hasPeriodic = false;
110
+ for (const filename of await readdir(dir)) {
111
+ if (!filename.endsWith(".json") || !filename.startsWith(prefix))
112
+ continue;
113
+ const eventPath = join(dir, filename);
114
+ let type;
115
+ try {
116
+ type = parseScheduledEventContent(await readFile(eventPath, "utf-8"), filename).type;
117
+ }
118
+ catch {
119
+ continue; // can't classify → leave it for /events to handle
120
+ }
121
+ if (type === "periodic") {
122
+ hasPeriodic = true; // the cadence lives on for the next cycle
123
+ continue;
124
+ }
125
+ await unlink(eventPath);
126
+ deleted.push(filename.slice(0, -".json".length));
127
+ }
128
+ return { deleted, hasPeriodic };
129
+ }
130
+ async function setTask(options, request) {
131
+ if (!request.id)
132
+ throw new Error('action "set" requires an id.');
133
+ const id = normalizeTaskId(request.id);
134
+ const taskPath = join(tasksDir(options), `${id}.md`);
135
+ const { fields, body } = await readTaskDocument(taskPath, id);
136
+ const nextFields = applySet(fields, request);
137
+ await writeFileAtomically(taskPath, renderTaskFile(nextFields, body));
138
+ return {
139
+ action: "set",
140
+ id,
141
+ path: toWorkspacePath(options, taskPath),
142
+ status: nextFields.status,
143
+ notice: `已更新任务 \`${id}\`(status: ${nextFields.status}${nextFields.wake ? `, wake: ${nextFields.wake}` : ""})。`,
144
+ };
145
+ }
146
+ async function doneTask(options, request) {
147
+ if (!request.id)
148
+ throw new Error('action "done" requires an id.');
149
+ const id = normalizeTaskId(request.id);
150
+ const dir = tasksDir(options);
151
+ const taskPath = join(dir, `${id}.md`);
152
+ const { fields, body } = await readTaskDocument(taskPath, id);
153
+ await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "done" }, body));
154
+ const { deleted, hasPeriodic } = await cleanupTaskEvents(options, id);
155
+ // Periodic task → sleeps in place until its schedule fires next; one-shot → archive.
156
+ let archived = false;
157
+ let finalPath = taskPath;
158
+ if (!hasPeriodic) {
159
+ const archiveDir = join(dir, "archive");
160
+ await mkdir(archiveDir, { recursive: true });
161
+ finalPath = join(archiveDir, `${id}.md`);
162
+ await rename(taskPath, finalPath);
163
+ archived = true;
164
+ }
165
+ const cleanup = deleted.length > 0 ? `,清理事件 ${deleted.join(", ")}` : "";
166
+ const disposition = archived ? "已归档" : "周期任务留原地待下次唤醒";
167
+ return {
168
+ action: "done",
169
+ id,
170
+ path: toWorkspacePath(options, finalPath),
171
+ status: "done",
172
+ archived,
173
+ deletedEvents: deleted,
174
+ notice: `任务 \`${id}\` 已完成(${disposition}${cleanup})。`,
175
+ };
176
+ }
177
+ async function listTasks(options) {
178
+ const entries = await readActiveTasks(tasksDir(options));
179
+ return {
180
+ action: "list",
181
+ tasks: entries.map((entry) => ({
182
+ id: entry.id,
183
+ title: entry.title,
184
+ status: entry.frontmatter.readable ? (entry.frontmatter.status ?? "open") : "unreadable",
185
+ wake: entry.frontmatter.wake,
186
+ actionable: entry.actionable,
187
+ })),
188
+ notice: `台账共有 ${entries.length} 个 active 任务。`,
189
+ };
190
+ }
191
+ export async function manageTask(options, request) {
192
+ switch (request.action) {
193
+ case "set":
194
+ return setTask(options, request);
195
+ case "done":
196
+ return doneTask(options, request);
197
+ case "list":
198
+ return listTasks(options);
199
+ }
200
+ }
201
+ export function createTaskManageTool(options) {
202
+ return {
203
+ name: "task_manage",
204
+ label: "task_manage",
205
+ description: "Manage this channel's task ledger frontmatter and lifecycle: set status/wake/recurrence, close a task out " +
206
+ "(archiving one-shot tasks and cleaning up its residual events), or list active tasks. Write the task body " +
207
+ "(goal, DoD, manual, cycle log) with write/edit; this tool owns only the frontmatter and close-out.",
208
+ parameters: taskManageSchema,
209
+ execute: async (_toolCallId, args) => {
210
+ const result = await manageTask(options, {
211
+ action: parseAction(args.action),
212
+ id: args.id,
213
+ status: args.status,
214
+ wake: args.wake,
215
+ recurrence: args.recurrence,
216
+ });
217
+ return {
218
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
219
+ details: {
220
+ kind: "task_manage",
221
+ ...result,
222
+ },
223
+ };
224
+ },
225
+ };
226
+ }
package/dist/tui/app.js CHANGED
@@ -17,6 +17,7 @@ import { ensureChannelDir } from "../runtime/channel-paths.js";
17
17
  import { finalDeliveryOf, progressStyleOf } from "../runtime/dingtalk.js";
18
18
  import { handleEventsCommand } from "../runtime/event-commands.js";
19
19
  import { ChannelStore } from "../runtime/store.js";
20
+ import { handleTasksCommand } from "../runtime/task-commands.js";
20
21
  import { getUsageLedger } from "../usage/ledger.js";
21
22
  import { parseUsageMode, renderUsageReport } from "../usage/render.js";
22
23
  import { TUI_SLASH_COMMANDS } from "./commands.js";
@@ -88,6 +89,7 @@ export async function runTuiApp(options) {
88
89
  renderHelp: () => renderBuiltInHelp(),
89
90
  renderUsage: (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
90
91
  runEvents: (args) => handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath }),
92
+ runTasks: (args) => handleTasksCommand({ args, channelDir }),
91
93
  statusInfo: { version: readCliVersion(), sandbox, startedAt: Date.now() },
92
94
  });
93
95
  try {
@@ -37,6 +37,7 @@ export interface DispatchDeps {
37
37
  renderStatus(): string;
38
38
  renderUsage(args: string): string;
39
39
  runEvents(args: string): Promise<string>;
40
+ runTasks(args: string): Promise<string>;
40
41
  }
41
42
  export declare function dispatch(input: string, deps: DispatchDeps): Promise<DispatchOutcome>;
42
43
  /** Slash commands offered in editor autocomplete: transport + session + TUI-only. */