@oyasmi/pipiclaw 0.7.6 → 0.7.7
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.
- package/README.md +6 -0
- package/dist/agent/channel-runner.js +7 -3
- package/dist/agent/commands.js +2 -1
- package/dist/agent/session-events.js +5 -0
- package/dist/memory/recall.js +6 -0
- package/dist/models/api-keys.d.ts +5 -1
- package/dist/models/api-keys.js +10 -4
- package/dist/runtime/bootstrap.js +2 -0
- package/dist/runtime/dingtalk.js +13 -1
- package/dist/runtime/task-commands.d.ts +3 -0
- package/dist/runtime/task-commands.js +148 -2
- package/dist/shared/atomic-file.js +23 -3
- package/dist/shared/task-events.d.ts +32 -0
- package/dist/shared/task-events.js +29 -0
- package/dist/shared/task-ledger.d.ts +26 -0
- package/dist/shared/task-ledger.js +38 -0
- package/dist/subagents/tool.js +26 -4
- package/dist/tools/registry.js +3 -2
- package/dist/tools/task-manage.d.ts +16 -2
- package/dist/tools/task-manage.js +119 -22
- package/dist/tools/web-fetch.js +3 -0
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -458,6 +458,9 @@ Pipiclaw 有两层命令。
|
|
|
458
458
|
| `/events show <name>` | 查看指定事件文件的完整 JSON |
|
|
459
459
|
| `/events delete <name>` | 删除指定事件文件 |
|
|
460
460
|
| `/events history [name]` | 查看事件调度历史,可按事件名过滤 |
|
|
461
|
+
| `/tasks [all\|archived]` | 查看当前通道的 active 或 archived 任务台账 |
|
|
462
|
+
| `/tasks show <id>` | 查看指定任务台账 |
|
|
463
|
+
| `/tasks doctor` | 诊断任务台账与 task event 的一致性问题 |
|
|
461
464
|
| `/status` | 查看运行时状态:执行状态、当前模型、上下文用量、运行时长、版本 |
|
|
462
465
|
| `/usage [7d\|month]` | 查看本通道与全局的 LLM 成本,按类型和 Top 模型拆分 |
|
|
463
466
|
|
|
@@ -513,6 +516,7 @@ Pipiclaw 的核心不是一个临时机器人实例,而是一组长期存在
|
|
|
513
516
|
│ ├── SESSION.md
|
|
514
517
|
│ ├── MEMORY.md
|
|
515
518
|
│ ├── HISTORY.md
|
|
519
|
+
│ ├── tasks/
|
|
516
520
|
│ ├── .channel-meta.json
|
|
517
521
|
│ ├── context.jsonl
|
|
518
522
|
│ ├── log.jsonl
|
|
@@ -533,6 +537,8 @@ Pipiclaw 的核心不是一个临时机器人实例,而是一组长期存在
|
|
|
533
537
|
稳定事实、决策和偏好
|
|
534
538
|
- `HISTORY.md`
|
|
535
539
|
更早上下文的摘要
|
|
540
|
+
- `<channel>/tasks/`
|
|
541
|
+
当前通道的长程任务台账;active 任务位于目录根部,完成后的任务归档到 `tasks/archive/`
|
|
536
542
|
|
|
537
543
|
## 记忆模型(Memory Model)
|
|
538
544
|
|
|
@@ -16,7 +16,6 @@ import { createExecutor } from "../sandbox.js";
|
|
|
16
16
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
17
17
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
18
18
|
import { formatConfigDiagnostic } from "../shared/config-diagnostics.js";
|
|
19
|
-
import { HAN_REGEX } from "../shared/text-utils.js";
|
|
20
19
|
import { isRecord } from "../shared/type-guards.js";
|
|
21
20
|
import { discoverSubAgents, formatSubAgentList } from "../subagents/discovery.js";
|
|
22
21
|
import { loadToolsConfigWithDiagnostics } from "../tools/config.js";
|
|
@@ -169,7 +168,6 @@ export class ChannelRunner {
|
|
|
169
168
|
const clippedInput = clipUserInput(ctx.message.text, MAX_USER_MESSAGE_CHARS);
|
|
170
169
|
const userMessage = this.formatUserMessage(clippedInput, ctx.message.userName);
|
|
171
170
|
const preserveRawInput = this.shouldPreserveRawInput(ctx.message.text);
|
|
172
|
-
await this.maybeRunPreventiveCompactionForIncomingText(preserveRawInput ? clippedInput : userMessage);
|
|
173
171
|
// Ensure channel directory exists
|
|
174
172
|
await mkdir(this.channelDir, { recursive: true });
|
|
175
173
|
let promptText = preserveRawInput ? clippedInput : userMessage;
|
|
@@ -188,7 +186,9 @@ export class ChannelRunner {
|
|
|
188
186
|
maxInjected: recallSettings.maxInjected,
|
|
189
187
|
maxChars: recallSettings.maxChars,
|
|
190
188
|
rerankWithModel: recallSettings.rerankWithModel,
|
|
191
|
-
|
|
189
|
+
// Let shouldUseModelRerank's own memory-intent gate decide (it already handles
|
|
190
|
+
// Chinese phrasing) — forcing autoRerank for every Han-script message triggered a
|
|
191
|
+
// model rerank (up to 8s) on nearly every Chinese turn once memory filled up.
|
|
192
192
|
model: this.session.model ?? this.activeModel,
|
|
193
193
|
resolveApiKey: async (model) => getApiKeyForModel(this.modelRegistry, model),
|
|
194
194
|
candidateStore: this.memoryCandidateStore,
|
|
@@ -217,6 +217,10 @@ export class ChannelRunner {
|
|
|
217
217
|
this.firstTurnMemoryBootstrapPending = false;
|
|
218
218
|
}
|
|
219
219
|
}
|
|
220
|
+
// Estimated against the fully assembled prompt (recall + task digest + bootstrap all
|
|
221
|
+
// prepended above), not just the bare user message — those pieces can add thousands of
|
|
222
|
+
// characters and must count against the projected context usage this guard is checking.
|
|
223
|
+
await this.maybeRunPreventiveCompactionForIncomingText(promptText);
|
|
220
224
|
// Debug: write context to last_prompt.json (only with PIPICLAW_DEBUG=1)
|
|
221
225
|
if (process.env.PIPICLAW_DEBUG) {
|
|
222
226
|
const debugContext = {
|
package/dist/agent/commands.js
CHANGED
|
@@ -24,11 +24,12 @@ These are handled directly by the DingTalk transport/runtime layer.
|
|
|
24
24
|
Example: \`/events show weekly-review\`
|
|
25
25
|
Example: \`/events delete weekly-review\`
|
|
26
26
|
Example: \`/events history weekly-review\`
|
|
27
|
-
- \`/tasks [show <id>|archive]\`
|
|
27
|
+
- \`/tasks [show <id>|archive|doctor]\`
|
|
28
28
|
View the channel's task ledger (read-only); to change a task, just tell me in plain language
|
|
29
29
|
Example: \`/tasks\`
|
|
30
30
|
Example: \`/tasks show weekly-report\`
|
|
31
31
|
Example: \`/tasks archive\`
|
|
32
|
+
Example: \`/tasks doctor\`
|
|
32
33
|
- \`/status\`
|
|
33
34
|
Show runtime status: run state, current model, context usage, uptime, version
|
|
34
35
|
Example: \`/status\`
|
|
@@ -216,6 +216,11 @@ export async function handleSessionEvent(event, context) {
|
|
|
216
216
|
.join("\n");
|
|
217
217
|
const trimmedFinalText = finalText.trim();
|
|
218
218
|
if (!trimmedFinalText) {
|
|
219
|
+
// No tool calls and no text: leaving finalOutcome at its "none" default means no
|
|
220
|
+
// delivery branch in channel-runner fires, so the progress card is stuck on
|
|
221
|
+
// "thinking…" forever. Treat it the same as an explicit [SILENT] turn.
|
|
222
|
+
runState.finalOutcome = { kind: "silent" };
|
|
223
|
+
memoryLifecycle.noteCompletedAssistantTurn();
|
|
219
224
|
return;
|
|
220
225
|
}
|
|
221
226
|
if (trimmedFinalText === "[SILENT]" || trimmedFinalText.startsWith("[SILENT]")) {
|
package/dist/memory/recall.js
CHANGED
|
@@ -488,6 +488,7 @@ function renderRecallResult(items, maxChars) {
|
|
|
488
488
|
"Relevant context for this turn:",
|
|
489
489
|
];
|
|
490
490
|
let usedChars = clippedLines.join("\n").length + "</runtime_context>".length + 2;
|
|
491
|
+
let includedCount = 0;
|
|
491
492
|
for (const item of items) {
|
|
492
493
|
const block = ["", `[${item.source}/${item.title}]`, `Path: ${item.path}`, item.content].join("\n");
|
|
493
494
|
if (usedChars + block.length > maxChars) {
|
|
@@ -495,6 +496,11 @@ function renderRecallResult(items, maxChars) {
|
|
|
495
496
|
}
|
|
496
497
|
clippedLines.push("", `[${item.source}/${item.title}]`, `Path: ${item.path}`, item.content);
|
|
497
498
|
usedChars += block.length;
|
|
499
|
+
includedCount++;
|
|
500
|
+
}
|
|
501
|
+
const omittedCount = items.length - includedCount;
|
|
502
|
+
if (omittedCount > 0) {
|
|
503
|
+
clippedLines.push("", `[- ${omittedCount} more item(s) omitted for length; use memory_manage search or session_search to look them up.]`);
|
|
498
504
|
}
|
|
499
505
|
clippedLines.push("</runtime_context>");
|
|
500
506
|
return clippedLines.join("\n");
|
|
@@ -2,6 +2,10 @@ import type { Api, Model } from "@earendil-works/pi-ai";
|
|
|
2
2
|
import type { ModelRegistry } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
/**
|
|
4
4
|
* Resolve an API key for the given model's provider.
|
|
5
|
-
*
|
|
5
|
+
* `ModelRegistry.getApiKeyForProvider` already checks that provider's own environment
|
|
6
|
+
* variable (e.g. OPENAI_API_KEY, GEMINI_API_KEY) internally, so a miss here means no
|
|
7
|
+
* credentials exist for this provider anywhere. Only fall back to ANTHROPIC_API_KEY when
|
|
8
|
+
* the model itself is Anthropic — falling back for other providers would silently send an
|
|
9
|
+
* Anthropic key to e.g. OpenAI and fail with a confusing 401.
|
|
6
10
|
*/
|
|
7
11
|
export declare function getApiKeyForModel(modelRegistry: ModelRegistry, model: Model<Api>): Promise<string>;
|
package/dist/models/api-keys.js
CHANGED
|
@@ -1,15 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Resolve an API key for the given model's provider.
|
|
3
|
-
*
|
|
3
|
+
* `ModelRegistry.getApiKeyForProvider` already checks that provider's own environment
|
|
4
|
+
* variable (e.g. OPENAI_API_KEY, GEMINI_API_KEY) internally, so a miss here means no
|
|
5
|
+
* credentials exist for this provider anywhere. Only fall back to ANTHROPIC_API_KEY when
|
|
6
|
+
* the model itself is Anthropic — falling back for other providers would silently send an
|
|
7
|
+
* Anthropic key to e.g. OpenAI and fail with a confusing 401.
|
|
4
8
|
*/
|
|
5
9
|
export async function getApiKeyForModel(modelRegistry, model) {
|
|
6
10
|
const key = await modelRegistry.getApiKeyForProvider(model.provider);
|
|
7
11
|
if (key) {
|
|
8
12
|
return key;
|
|
9
13
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
14
|
+
if (model.provider === "anthropic") {
|
|
15
|
+
const envKey = process.env.ANTHROPIC_API_KEY;
|
|
16
|
+
if (envKey) {
|
|
17
|
+
return envKey;
|
|
18
|
+
}
|
|
13
19
|
}
|
|
14
20
|
throw new Error(`No API key found for provider: ${model.provider}.\n\n` +
|
|
15
21
|
"Configure credentials in ~/.pi/pipiclaw/auth.json or ~/.pi/pipiclaw/models.json, or set the matching provider environment variable.");
|
|
@@ -471,6 +471,8 @@ export function createRuntimeContext(options) {
|
|
|
471
471
|
const response = await runTasksCommand({
|
|
472
472
|
args,
|
|
473
473
|
channelDir: getChannelDir(options.paths.workspaceDir, event.channelId),
|
|
474
|
+
workspaceDir: options.paths.workspaceDir,
|
|
475
|
+
channelId: event.channelId,
|
|
474
476
|
});
|
|
475
477
|
await bot.sendPlain(event.channelId, response);
|
|
476
478
|
},
|
package/dist/runtime/dingtalk.js
CHANGED
|
@@ -110,6 +110,12 @@ const DINGTALK_API = "https://api.dingtalk.com";
|
|
|
110
110
|
// (discardCard / replay / sendPlain) already handle.
|
|
111
111
|
const DINGTALK_HTTP_TIMEOUT_MS = 15_000;
|
|
112
112
|
const http = axios.create({ timeout: DINGTALK_HTTP_TIMEOUT_MS });
|
|
113
|
+
// Bounds enqueueStreamMessage (user messages + busy-message requeues), mirroring the
|
|
114
|
+
// existing cap on enqueueEvent. Without a limit, a busy channel getting flooded with
|
|
115
|
+
// messages (or repeated followUp requeues) grows this queue without bound — each item
|
|
116
|
+
// still runs a full serialized turn, so an unbounded queue means unbounded backlog time
|
|
117
|
+
// and unbounded memory, not just a slow channel.
|
|
118
|
+
const USER_MESSAGE_QUEUE_LIMIT = 20;
|
|
113
119
|
const TOKEN_REFRESH_SECS = 90 * 60; // 1.5 hours (tokens expire after 2 hours)
|
|
114
120
|
const CONNECT_ATTEMPT_TIMEOUT_MS = 10_000;
|
|
115
121
|
const SOCKET_CLOSE_GRACE_MS = 1_000;
|
|
@@ -560,7 +566,13 @@ export class DingTalkBot {
|
|
|
560
566
|
}
|
|
561
567
|
enqueueStreamMessage(event, textOverride) {
|
|
562
568
|
const queuedEvent = textOverride === undefined ? event : { ...event, text: textOverride };
|
|
563
|
-
this.getQueue(event.channelId)
|
|
569
|
+
const queue = this.getQueue(event.channelId);
|
|
570
|
+
if (queue.size() >= USER_MESSAGE_QUEUE_LIMIT) {
|
|
571
|
+
log.logWarning(`Message queue full for ${event.channelId} (limit ${USER_MESSAGE_QUEUE_LIMIT}), discarding: ${queuedEvent.text.substring(0, 50)}`);
|
|
572
|
+
this.sendPlain(event.channelId, `⚠️ 消息积压过多(超过 ${USER_MESSAGE_QUEUE_LIMIT} 条待处理),本条消息已丢弃,请稍后重试。`).catch(() => undefined);
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
queue.enqueue(async () => {
|
|
564
576
|
this.activeMessageProcessing = true;
|
|
565
577
|
try {
|
|
566
578
|
await this.handler.handleEvent(queuedEvent, this);
|
|
@@ -2,5 +2,8 @@ export interface HandleTasksCommandOptions {
|
|
|
2
2
|
args: string;
|
|
3
3
|
/** The channel directory; tasks live in `<channelDir>/tasks/`. */
|
|
4
4
|
channelDir: string;
|
|
5
|
+
/** Workspace directory; required for `/tasks doctor` because events are workspace-scoped. */
|
|
6
|
+
workspaceDir?: string;
|
|
7
|
+
channelId?: string;
|
|
5
8
|
}
|
|
6
9
|
export declare function handleTasksCommand(options: HandleTasksCommandOptions): Promise<string>;
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
2
|
import { readdir, readFile } from "node:fs/promises";
|
|
3
3
|
import { join, resolve, sep } from "node:path";
|
|
4
|
-
import {
|
|
4
|
+
import { isTaskCheckinEvent, isTaskScheduleEvent, parseTaskEventName, taskEventPrefix, taskScheduleEventName, } from "../shared/task-events.js";
|
|
5
|
+
import { extractTaskTitle, missingStandardTaskSections, normalizeTaskId, readActiveTasks, } from "../shared/task-ledger.js";
|
|
6
|
+
import { parseScheduledEventContent } from "./events.js";
|
|
5
7
|
function usage() {
|
|
6
8
|
return `# Tasks
|
|
7
9
|
|
|
@@ -9,7 +11,8 @@ Usage:
|
|
|
9
11
|
|
|
10
12
|
- \`/tasks\` — list active tasks in this channel
|
|
11
13
|
- \`/tasks show <id>\` — show a single task file (active or archived)
|
|
12
|
-
- \`/tasks archive\` — list archived (closed) tasks
|
|
14
|
+
- \`/tasks archive\` — list archived (closed) tasks
|
|
15
|
+
- \`/tasks doctor\` — check task/event consistency without changing files`;
|
|
13
16
|
}
|
|
14
17
|
function parseTasksCommand(args) {
|
|
15
18
|
const parts = args.trim().split(/\s+/).filter(Boolean);
|
|
@@ -30,6 +33,11 @@ function parseTasksCommand(args) {
|
|
|
30
33
|
throw new Error("Usage: /tasks archive");
|
|
31
34
|
return { action: "archive" };
|
|
32
35
|
}
|
|
36
|
+
if (action === "doctor") {
|
|
37
|
+
if (parts.length > 1)
|
|
38
|
+
throw new Error("Usage: /tasks doctor");
|
|
39
|
+
return { action: "doctor" };
|
|
40
|
+
}
|
|
33
41
|
throw new Error(`Unknown /tasks action: ${action}`);
|
|
34
42
|
}
|
|
35
43
|
function tasksDir(channelDir) {
|
|
@@ -56,6 +64,67 @@ function relativeWake(wakeMs, now) {
|
|
|
56
64
|
const rel = minutes < 60 ? `${minutes}m` : minutes < 1440 ? `${Math.round(minutes / 60)}h` : `${Math.round(minutes / 1440)}d`;
|
|
57
65
|
return `${iso} (${rel})`;
|
|
58
66
|
}
|
|
67
|
+
function eventDir(workspaceDir) {
|
|
68
|
+
return join(workspaceDir, "events");
|
|
69
|
+
}
|
|
70
|
+
async function readArchivedTaskIds(channelDir) {
|
|
71
|
+
const archiveDir = join(tasksDir(channelDir), "archive");
|
|
72
|
+
const ids = new Set();
|
|
73
|
+
if (!existsSync(archiveDir))
|
|
74
|
+
return ids;
|
|
75
|
+
for (const filename of await readdir(archiveDir)) {
|
|
76
|
+
if (filename.endsWith(".md"))
|
|
77
|
+
ids.add(filename.slice(0, -".md".length));
|
|
78
|
+
}
|
|
79
|
+
return ids;
|
|
80
|
+
}
|
|
81
|
+
async function readTaskEvents(workspaceDir, channelId) {
|
|
82
|
+
const dir = eventDir(workspaceDir);
|
|
83
|
+
if (!existsSync(dir))
|
|
84
|
+
return [];
|
|
85
|
+
const prefix = taskEventPrefix(channelId);
|
|
86
|
+
const events = [];
|
|
87
|
+
for (const filename of (await readdir(dir)).filter((name) => name.endsWith(".json")).sort()) {
|
|
88
|
+
const name = filename.slice(0, -".json".length);
|
|
89
|
+
if (!name.startsWith(prefix))
|
|
90
|
+
continue;
|
|
91
|
+
const split = parseTaskEventName(name, channelId);
|
|
92
|
+
const info = { filename, name, ...(split ?? {}) };
|
|
93
|
+
try {
|
|
94
|
+
info.event = parseScheduledEventContent(await readFile(join(dir, filename), "utf-8"), filename);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
info.error = error instanceof Error ? error.message : String(error);
|
|
98
|
+
}
|
|
99
|
+
events.push(info);
|
|
100
|
+
}
|
|
101
|
+
return events;
|
|
102
|
+
}
|
|
103
|
+
function eventKey(events, id, use) {
|
|
104
|
+
return events.find((event) => event.id === id && event.use === use);
|
|
105
|
+
}
|
|
106
|
+
function isParseableSchedule(events, id) {
|
|
107
|
+
const schedule = eventKey(events, id, "schedule");
|
|
108
|
+
return schedule ? isTaskScheduleEvent(schedule) : false;
|
|
109
|
+
}
|
|
110
|
+
function validWakeMs(entry) {
|
|
111
|
+
const wake = entry.frontmatter.wake;
|
|
112
|
+
if (!wake)
|
|
113
|
+
return undefined;
|
|
114
|
+
const ms = new Date(wake).getTime();
|
|
115
|
+
return Number.isFinite(ms) ? ms : undefined;
|
|
116
|
+
}
|
|
117
|
+
function issue(problem, nextStep) {
|
|
118
|
+
return `- ${problem}\n Next step: ${nextStep}`;
|
|
119
|
+
}
|
|
120
|
+
async function readActiveTaskContent(channelDir, id) {
|
|
121
|
+
try {
|
|
122
|
+
return await readFile(join(tasksDir(channelDir), `${id}.md`), "utf-8");
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
59
128
|
async function listTasks(channelDir) {
|
|
60
129
|
const dir = tasksDir(channelDir);
|
|
61
130
|
const now = Date.now();
|
|
@@ -107,6 +176,81 @@ async function listArchive(channelDir) {
|
|
|
107
176
|
}
|
|
108
177
|
return `# Archived Tasks: ${blocks.length}\n\n${blocks.join("\n")}`;
|
|
109
178
|
}
|
|
179
|
+
async function doctor(options) {
|
|
180
|
+
if (!options.workspaceDir || !options.channelId) {
|
|
181
|
+
return "# Task Doctor\n\nNot available: workspaceDir and channelId are required.";
|
|
182
|
+
}
|
|
183
|
+
const now = Date.now();
|
|
184
|
+
const entries = await readActiveTasks(tasksDir(options.channelDir), now);
|
|
185
|
+
const activeIds = new Set(entries.map((entry) => entry.id));
|
|
186
|
+
const archivedIds = await readArchivedTaskIds(options.channelDir);
|
|
187
|
+
const events = await readTaskEvents(options.workspaceDir, options.channelId);
|
|
188
|
+
const issues = [];
|
|
189
|
+
for (const entry of entries) {
|
|
190
|
+
const status = entry.frontmatter.status ?? "open";
|
|
191
|
+
if (!entry.frontmatter.readable) {
|
|
192
|
+
issues.push(issue(`tasks/${entry.id}.md has unreadable frontmatter; wake/status cannot be trusted.`, `Fix tasks/${entry.id}.md so it starts with readable status/wake/recurrence frontmatter.`));
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (status === "done" && !isParseableSchedule(events, entry.id)) {
|
|
196
|
+
issues.push(issue(`tasks/${entry.id}.md is done but still in the active directory.`, `Ask the agent to archive one-shot task ${entry.id}, or add a parseable .schedule event if it is recurring.`));
|
|
197
|
+
}
|
|
198
|
+
const content = await readActiveTaskContent(options.channelDir, entry.id);
|
|
199
|
+
if (content === undefined) {
|
|
200
|
+
issues.push(issue(`tasks/${entry.id}.md could not be read during doctor checks.`, `Open tasks/${entry.id}.md manually and repair permissions or file contents.`));
|
|
201
|
+
}
|
|
202
|
+
else {
|
|
203
|
+
const missing = missingStandardTaskSections(content);
|
|
204
|
+
if (missing.length > 0) {
|
|
205
|
+
issues.push(issue(`tasks/${entry.id}.md is missing standard section(s): ${missing.join(", ")}.`, `Ask the agent to normalize tasks/${entry.id}.md to the standard task skeleton.`));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (entry.frontmatter.recurrence && !isParseableSchedule(events, entry.id)) {
|
|
209
|
+
issues.push(issue(`tasks/${entry.id}.md has recurrence but no parseable ${taskScheduleEventName(options.channelId, entry.id)} event.`, `Create or repair events/${taskScheduleEventName(options.channelId, entry.id)}.json as a periodic event.`));
|
|
210
|
+
}
|
|
211
|
+
const checkin = eventKey(events, entry.id, "checkin");
|
|
212
|
+
if (checkin && isTaskCheckinEvent(checkin)) {
|
|
213
|
+
const wakeMs = validWakeMs(entry);
|
|
214
|
+
const atMs = new Date(checkin.event.at).getTime();
|
|
215
|
+
if (wakeMs === undefined) {
|
|
216
|
+
issues.push(issue(`tasks/${entry.id}.md has a .checkin event but no valid wake value.`, `Set tasks/${entry.id}.md wake to ${checkin.event.at}, or delete the stale .checkin event.`));
|
|
217
|
+
}
|
|
218
|
+
else if (Number.isFinite(atMs) && Math.abs(atMs - wakeMs) > 60_000) {
|
|
219
|
+
issues.push(issue(`tasks/${entry.id}.md wake does not match its .checkin event time.`, `Sync tasks/${entry.id}.md wake with events/${checkin.filename} at ${checkin.event.at}.`));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
else if (status === "awaiting-user" && validWakeMs(entry) !== undefined) {
|
|
223
|
+
issues.push(issue(`tasks/${entry.id}.md is awaiting-user with wake set but has no parseable .checkin event.`, `Create task.${options.channelId}.${entry.id}.checkin as a one-shot event for the wake time, or clear wake.`));
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
for (const event of events) {
|
|
227
|
+
if (!event.id || !event.use) {
|
|
228
|
+
issues.push(issue(`events/${event.filename} does not follow task.<channelId>.<taskId>.<use>.json.`, "Rename the event to the task-owned naming convention or manage it as a normal event."));
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
if (event.error) {
|
|
232
|
+
issues.push(issue(`events/${event.filename} is not parseable: ${event.error}`, `Fix or delete events/${event.filename}; invalid task-owned events cannot be trusted.`));
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (!activeIds.has(event.id) && !archivedIds.has(event.id)) {
|
|
236
|
+
issues.push(issue(`events/${event.filename} points to missing task ${event.id}.`, `Delete events/${event.filename}, or recreate tasks/${event.id}.md if that task still exists conceptually.`));
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
if (archivedIds.has(event.id)) {
|
|
240
|
+
issues.push(issue(`events/${event.filename} points to archived task ${event.id}; closed tasks should have no live events.`, `Delete events/${event.filename}; archived tasks should not wake the agent.`));
|
|
241
|
+
}
|
|
242
|
+
if (event.use === "schedule" && !isTaskScheduleEvent(event)) {
|
|
243
|
+
issues.push(issue(`events/${event.filename} is a schedule event but is not periodic.`, `Change events/${event.filename} to type periodic, or rename it away from .schedule.`));
|
|
244
|
+
}
|
|
245
|
+
if (event.use === "checkin" && !isTaskCheckinEvent(event)) {
|
|
246
|
+
issues.push(issue(`events/${event.filename} is a checkin event but is not one-shot.`, `Change events/${event.filename} to type one-shot, or rename it away from .checkin.`));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
if (issues.length === 0) {
|
|
250
|
+
return "# Task Doctor\n\nNo task ledger issues found.";
|
|
251
|
+
}
|
|
252
|
+
return `# Task Doctor\n\nFound ${issues.length} issue${issues.length === 1 ? "" : "s"}:\n\n${issues.join("\n")}`;
|
|
253
|
+
}
|
|
110
254
|
export async function handleTasksCommand(options) {
|
|
111
255
|
let command;
|
|
112
256
|
try {
|
|
@@ -124,6 +268,8 @@ export async function handleTasksCommand(options) {
|
|
|
124
268
|
return await showTask(options.channelDir, command.id);
|
|
125
269
|
case "archive":
|
|
126
270
|
return await listArchive(options.channelDir);
|
|
271
|
+
case "doctor":
|
|
272
|
+
return await doctor(options);
|
|
127
273
|
}
|
|
128
274
|
}
|
|
129
275
|
catch (error) {
|
|
@@ -1,14 +1,34 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { mkdir, rename, unlink
|
|
2
|
+
import { mkdir, open, rename, unlink } from "node:fs/promises";
|
|
3
3
|
import { dirname } from "node:path";
|
|
4
4
|
export function createAtomicTempPath(path) {
|
|
5
5
|
return `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
6
6
|
}
|
|
7
7
|
export async function writeFileAtomically(path, content, tempPath = createAtomicTempPath(path)) {
|
|
8
|
-
|
|
8
|
+
const dir = dirname(path);
|
|
9
|
+
await mkdir(dir, { recursive: true });
|
|
9
10
|
try {
|
|
10
|
-
await
|
|
11
|
+
const handle = await open(tempPath, "w");
|
|
12
|
+
try {
|
|
13
|
+
await handle.writeFile(content, "utf-8");
|
|
14
|
+
await handle.sync();
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
await handle.close();
|
|
18
|
+
}
|
|
11
19
|
await rename(tempPath, path);
|
|
20
|
+
// Best-effort: the rename already succeeded, so a directory-fsync failure
|
|
21
|
+
// (e.g. unsupported on this platform/filesystem) should not surface as a write failure.
|
|
22
|
+
await open(dir, "r")
|
|
23
|
+
.then(async (dirHandle) => {
|
|
24
|
+
try {
|
|
25
|
+
await dirHandle.sync();
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await dirHandle.close();
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
.catch(() => undefined);
|
|
12
32
|
}
|
|
13
33
|
catch (error) {
|
|
14
34
|
await unlink(tempPath).catch(() => undefined);
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface ParsedTaskEventName {
|
|
2
|
+
id: string;
|
|
3
|
+
use: string;
|
|
4
|
+
}
|
|
5
|
+
export interface TaskEventLike {
|
|
6
|
+
id?: string;
|
|
7
|
+
use?: string;
|
|
8
|
+
event?: {
|
|
9
|
+
type: string;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
type EventOf<T> = T extends {
|
|
13
|
+
event?: infer E;
|
|
14
|
+
} ? E : never;
|
|
15
|
+
export declare function taskEventPrefix(channelId: string, id?: string): string;
|
|
16
|
+
export declare function taskEventName(channelId: string, id: string, use: string): string;
|
|
17
|
+
export declare function taskScheduleEventName(channelId: string, id: string): string;
|
|
18
|
+
export declare function taskScheduleEventFilename(channelId: string, id: string): string;
|
|
19
|
+
export declare function parseTaskEventName(name: string, channelId: string): ParsedTaskEventName | undefined;
|
|
20
|
+
export declare function isTaskScheduleEvent<T extends TaskEventLike>(info: T): info is T & {
|
|
21
|
+
use: "schedule";
|
|
22
|
+
event: Extract<EventOf<T>, {
|
|
23
|
+
type: "periodic";
|
|
24
|
+
}>;
|
|
25
|
+
};
|
|
26
|
+
export declare function isTaskCheckinEvent<T extends TaskEventLike>(info: T): info is T & {
|
|
27
|
+
use: "checkin";
|
|
28
|
+
event: Extract<EventOf<T>, {
|
|
29
|
+
type: "one-shot";
|
|
30
|
+
}>;
|
|
31
|
+
};
|
|
32
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export function taskEventPrefix(channelId, id) {
|
|
2
|
+
return id ? `task.${channelId}.${id}.` : `task.${channelId}.`;
|
|
3
|
+
}
|
|
4
|
+
export function taskEventName(channelId, id, use) {
|
|
5
|
+
return `${taskEventPrefix(channelId, id)}${use}`;
|
|
6
|
+
}
|
|
7
|
+
export function taskScheduleEventName(channelId, id) {
|
|
8
|
+
return taskEventName(channelId, id, "schedule");
|
|
9
|
+
}
|
|
10
|
+
export function taskScheduleEventFilename(channelId, id) {
|
|
11
|
+
return `${taskScheduleEventName(channelId, id)}.json`;
|
|
12
|
+
}
|
|
13
|
+
export function parseTaskEventName(name, channelId) {
|
|
14
|
+
const normalized = name.endsWith(".json") ? name.slice(0, -".json".length) : name;
|
|
15
|
+
const prefix = taskEventPrefix(channelId);
|
|
16
|
+
if (!normalized.startsWith(prefix))
|
|
17
|
+
return undefined;
|
|
18
|
+
const rest = normalized.slice(prefix.length);
|
|
19
|
+
const lastDot = rest.lastIndexOf(".");
|
|
20
|
+
if (lastDot <= 0 || lastDot === rest.length - 1)
|
|
21
|
+
return undefined;
|
|
22
|
+
return { id: rest.slice(0, lastDot), use: rest.slice(lastDot + 1) };
|
|
23
|
+
}
|
|
24
|
+
export function isTaskScheduleEvent(info) {
|
|
25
|
+
return info.use === "schedule" && info.event?.type === "periodic";
|
|
26
|
+
}
|
|
27
|
+
export function isTaskCheckinEvent(info) {
|
|
28
|
+
return info.use === "checkin" && info.event?.type === "one-shot";
|
|
29
|
+
}
|
|
@@ -28,6 +28,29 @@ export interface TaskLedgerEntry {
|
|
|
28
28
|
/** First bullet/line under a "当前周期"/"current cycle" heading, if any (digest only). */
|
|
29
29
|
latestNote?: string;
|
|
30
30
|
}
|
|
31
|
+
export interface TaskSkeletonInput {
|
|
32
|
+
title: string;
|
|
33
|
+
goal: string;
|
|
34
|
+
dod: string;
|
|
35
|
+
manual?: string;
|
|
36
|
+
}
|
|
37
|
+
export declare const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
|
|
38
|
+
export declare const STANDARD_TASK_SECTIONS: readonly [{
|
|
39
|
+
readonly label: "Goal";
|
|
40
|
+
readonly names: readonly ["Goal", "目标"];
|
|
41
|
+
}, {
|
|
42
|
+
readonly label: "DoD";
|
|
43
|
+
readonly names: readonly ["DoD"];
|
|
44
|
+
}, {
|
|
45
|
+
readonly label: "Manual";
|
|
46
|
+
readonly names: readonly ["Manual", "手册"];
|
|
47
|
+
}, {
|
|
48
|
+
readonly label: "Current Cycle";
|
|
49
|
+
readonly names: readonly ["Current Cycle", "当前周期"];
|
|
50
|
+
}, {
|
|
51
|
+
readonly label: "History";
|
|
52
|
+
readonly names: readonly ["History", "历史"];
|
|
53
|
+
}];
|
|
31
54
|
/** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
|
|
32
55
|
export declare function normalizeTaskId(id: string): string;
|
|
33
56
|
/** The document body after the leading frontmatter block, or the whole content when there is none. */
|
|
@@ -42,6 +65,9 @@ export declare function parseTaskFrontmatter(content: string): TaskFrontmatter;
|
|
|
42
65
|
export declare function isTaskActionable(frontmatter: TaskFrontmatter, now: number): boolean;
|
|
43
66
|
/** First `# ` heading after the frontmatter block, or the id when there is none. */
|
|
44
67
|
export declare function extractTaskTitle(content: string, fallbackId: string): string;
|
|
68
|
+
export declare function hasTaskHeading(content: string, names: readonly string[]): boolean;
|
|
69
|
+
export declare function missingStandardTaskSections(content: string): string[];
|
|
70
|
+
export declare function renderStandardTaskBody(input: TaskSkeletonInput): string;
|
|
45
71
|
/** Actionable first; then earliest wake first (unset wake sorts as "ready now"); then id. */
|
|
46
72
|
export declare function compareTaskEntries(a: TaskLedgerEntry, b: TaskLedgerEntry): number;
|
|
47
73
|
/**
|
|
@@ -2,6 +2,14 @@ import { readdir, readFile } from "node:fs/promises";
|
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
const FRONTMATTER_FIELDS = ["status", "wake", "recurrence"];
|
|
4
4
|
const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
5
|
+
export const DEFAULT_TASK_MANUAL = "- Follow the DoD, keep the current cycle log updated, and schedule check-ins when waiting.";
|
|
6
|
+
export const STANDARD_TASK_SECTIONS = [
|
|
7
|
+
{ label: "Goal", names: ["Goal", "目标"] },
|
|
8
|
+
{ label: "DoD", names: ["DoD"] },
|
|
9
|
+
{ label: "Manual", names: ["Manual", "手册"] },
|
|
10
|
+
{ label: "Current Cycle", names: ["Current Cycle", "当前周期"] },
|
|
11
|
+
{ label: "History", names: ["History", "历史"] },
|
|
12
|
+
];
|
|
5
13
|
/** Validate/normalize a task id (filename without `.md`), rejecting path traversal. */
|
|
6
14
|
export function normalizeTaskId(id) {
|
|
7
15
|
const trimmed = id.trim();
|
|
@@ -68,6 +76,36 @@ export function extractTaskTitle(content, fallbackId) {
|
|
|
68
76
|
}
|
|
69
77
|
return fallbackId;
|
|
70
78
|
}
|
|
79
|
+
export function hasTaskHeading(content, names) {
|
|
80
|
+
return content.split("\n").some((line) => {
|
|
81
|
+
const match = /^#{1,6}\s+(.+?)\s*$/.exec(line);
|
|
82
|
+
return match ? names.some((name) => match[1].trim().toLowerCase() === name.toLowerCase()) : false;
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
export function missingStandardTaskSections(content) {
|
|
86
|
+
return STANDARD_TASK_SECTIONS.filter((section) => !hasTaskHeading(content, section.names)).map((section) => section.label);
|
|
87
|
+
}
|
|
88
|
+
export function renderStandardTaskBody(input) {
|
|
89
|
+
const manual = input.manual?.trim() || DEFAULT_TASK_MANUAL;
|
|
90
|
+
return [
|
|
91
|
+
`# ${input.title}`,
|
|
92
|
+
"",
|
|
93
|
+
"## Goal",
|
|
94
|
+
input.goal,
|
|
95
|
+
"",
|
|
96
|
+
"## DoD",
|
|
97
|
+
input.dod,
|
|
98
|
+
"",
|
|
99
|
+
"## Manual",
|
|
100
|
+
manual,
|
|
101
|
+
"",
|
|
102
|
+
"## Current Cycle",
|
|
103
|
+
"- Created; next step: start work and append progress here before ending each turn.",
|
|
104
|
+
"",
|
|
105
|
+
"## History",
|
|
106
|
+
"",
|
|
107
|
+
].join("\n");
|
|
108
|
+
}
|
|
71
109
|
/** First non-empty bullet/line under a "当前周期"/"current cycle" heading. */
|
|
72
110
|
function extractLatestNote(content) {
|
|
73
111
|
const lines = content.split("\n");
|
package/dist/subagents/tool.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { convertToLlm } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
|
-
import { readChannelSession } from "../memory/files.js";
|
|
4
|
+
import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
|
|
5
5
|
import { recallRelevantMemory } from "../memory/recall.js";
|
|
6
6
|
import { formatModelReference } from "../models/utils.js";
|
|
7
7
|
import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
8
8
|
import { splitH1Sections } from "../shared/markdown-sections.js";
|
|
9
|
-
import { clipText, extractAssistantText, extractLabelFromArgs
|
|
9
|
+
import { clipText, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
|
|
10
10
|
import { buildToolSet } from "../tools/registry.js";
|
|
11
11
|
import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, } from "./discovery.js";
|
|
12
12
|
const subagentSchema = Type.Object({
|
|
@@ -83,13 +83,36 @@ function buildStoppedText(config, reason, finalText) {
|
|
|
83
83
|
}
|
|
84
84
|
return `[Sub-agent ${config.name} stopped: ${reason}]\n\n${trimmedFinalText}`;
|
|
85
85
|
}
|
|
86
|
+
/**
|
|
87
|
+
* Sub-agents share the main agent's `write`/`edit` tools but only receive the runtime
|
|
88
|
+
* context (task text), never the "don't touch MEMORY.md/HISTORY.md/SESSION.md, use
|
|
89
|
+
* memory_manage instead" rule the main agent gets in its system prompt (memory_manage
|
|
90
|
+
* itself is withheld from sub-agents). Denying these paths at the path-guard level closes
|
|
91
|
+
* that gap structurally instead of relying on a sub-agent to infer an instruction it never
|
|
92
|
+
* received — a stray write/edit here would race the shared memory serial queue
|
|
93
|
+
* (channel-maintenance-queue) and silently corrupt durable memory.
|
|
94
|
+
*/
|
|
95
|
+
function withSubagentMemoryWriteDeny(securityConfig, channelDir) {
|
|
96
|
+
const protectedPaths = [
|
|
97
|
+
getChannelMemoryPath(channelDir),
|
|
98
|
+
getChannelHistoryPath(channelDir),
|
|
99
|
+
getChannelSessionPath(channelDir),
|
|
100
|
+
];
|
|
101
|
+
return {
|
|
102
|
+
...securityConfig,
|
|
103
|
+
pathGuard: {
|
|
104
|
+
...securityConfig.pathGuard,
|
|
105
|
+
writeDeny: [...securityConfig.pathGuard.writeDeny, ...protectedPaths],
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
86
109
|
/**
|
|
87
110
|
* Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
|
|
88
111
|
* available to sub-agents (files + web). Sub-agents run with their own security context
|
|
89
112
|
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
90
113
|
*/
|
|
91
114
|
function buildSubagentTools(executor, bashTimeoutSec, options) {
|
|
92
|
-
const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
|
|
115
|
+
const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir);
|
|
93
116
|
return buildToolSet({
|
|
94
117
|
executor,
|
|
95
118
|
securityConfig,
|
|
@@ -191,7 +214,6 @@ async function buildContextualBlocks(task, config, options, currentModel) {
|
|
|
191
214
|
maxInjected: recallSettings.maxInjected,
|
|
192
215
|
maxChars: Math.min(recallSettings.maxChars, MAX_RECALL_CONTEXT_CHARS),
|
|
193
216
|
rerankWithModel: recallSettings.rerankWithModel,
|
|
194
|
-
autoRerank: HAN_REGEX.test(recallQuery),
|
|
195
217
|
model: currentModel,
|
|
196
218
|
resolveApiKey: options.resolveApiKey,
|
|
197
219
|
allowedSources: ["workspace-memory", "channel-memory", "channel-history"],
|
package/dist/tools/registry.js
CHANGED
|
@@ -149,8 +149,9 @@ export const TOOL_REGISTRY = [
|
|
|
149
149
|
},
|
|
150
150
|
{
|
|
151
151
|
name: "task_manage",
|
|
152
|
-
promptHint: "
|
|
153
|
-
"cleans up
|
|
152
|
+
promptHint: "Manage the task ledger: create standard task skeletons, set status/wake/recurrence, close tasks out " +
|
|
153
|
+
"(archives one-shot tasks and cleans up residual events; done requires summary and evidence), or list active " +
|
|
154
|
+
"tasks. Use write/edit for substantial body changes.",
|
|
154
155
|
availableToSubagents: false,
|
|
155
156
|
enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
|
|
156
157
|
create: (ctx) => createTaskManageTool({
|
|
@@ -2,13 +2,20 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
declare const taskManageSchema: Type.TObject<{
|
|
4
4
|
label: Type.TString;
|
|
5
|
-
action: Type.TUnion<[Type.TLiteral<"set">, Type.TLiteral<"done">, Type.TLiteral<"list">]>;
|
|
5
|
+
action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"set">, Type.TLiteral<"done">, Type.TLiteral<"list">]>;
|
|
6
6
|
id: Type.TOptional<Type.TString>;
|
|
7
|
+
title: Type.TOptional<Type.TString>;
|
|
8
|
+
goal: Type.TOptional<Type.TString>;
|
|
9
|
+
dod: Type.TOptional<Type.TString>;
|
|
10
|
+
manual: Type.TOptional<Type.TString>;
|
|
7
11
|
status: Type.TOptional<Type.TUnion<Type.TLiteral<"open" | "blocked" | "in-progress" | "awaiting-user">[]>>;
|
|
8
12
|
wake: Type.TOptional<Type.TString>;
|
|
9
13
|
recurrence: Type.TOptional<Type.TString>;
|
|
14
|
+
summary: Type.TOptional<Type.TString>;
|
|
15
|
+
evidence: Type.TOptional<Type.TString>;
|
|
16
|
+
residualRisk: Type.TOptional<Type.TString>;
|
|
10
17
|
}>;
|
|
11
|
-
export type TaskManageAction = "set" | "done" | "list";
|
|
18
|
+
export type TaskManageAction = "create" | "set" | "done" | "list";
|
|
12
19
|
export interface TaskManageResult {
|
|
13
20
|
action: TaskManageAction;
|
|
14
21
|
id?: string;
|
|
@@ -28,9 +35,16 @@ export interface TaskManageResult {
|
|
|
28
35
|
export interface TaskManageRequest {
|
|
29
36
|
action: TaskManageAction;
|
|
30
37
|
id?: string;
|
|
38
|
+
title?: string;
|
|
39
|
+
goal?: string;
|
|
40
|
+
dod?: string;
|
|
41
|
+
manual?: string;
|
|
31
42
|
status?: string;
|
|
32
43
|
wake?: string;
|
|
33
44
|
recurrence?: string;
|
|
45
|
+
summary?: string;
|
|
46
|
+
evidence?: string;
|
|
47
|
+
residualRisk?: string;
|
|
34
48
|
}
|
|
35
49
|
export interface TaskManageToolOptions {
|
|
36
50
|
workspaceDir: string;
|
|
@@ -4,25 +4,35 @@ import { join } from "node:path";
|
|
|
4
4
|
import { Type } from "typebox";
|
|
5
5
|
import { parseScheduledEventContent } from "../runtime/events.js";
|
|
6
6
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
7
|
-
import {
|
|
7
|
+
import { isTaskScheduleEvent, taskEventPrefix, taskScheduleEventFilename } from "../shared/task-events.js";
|
|
8
|
+
import { normalizeTaskId, parseTaskFrontmatter, readActiveTasks, renderStandardTaskBody, taskBody, } from "../shared/task-ledger.js";
|
|
8
9
|
const SETTABLE_STATUSES = ["open", "in-progress", "awaiting-user", "blocked"];
|
|
9
10
|
const taskManageSchema = Type.Object({
|
|
10
11
|
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: '"
|
|
12
|
+
action: Type.Union([Type.Literal("create"), Type.Literal("set"), Type.Literal("done"), Type.Literal("list")], {
|
|
13
|
+
description: '"create" writes a standard task skeleton; "set" updates status/wake/recurrence; "done" closes it out and requires summary/evidence; "list" returns active tasks.',
|
|
13
14
|
}),
|
|
14
|
-
id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for set/done." })),
|
|
15
|
-
|
|
15
|
+
id: Type.Optional(Type.String({ description: "Task id (filename without .md). Required for create/set/done." })),
|
|
16
|
+
title: Type.Optional(Type.String({ description: "Required for create: task title used as the H1 heading." })),
|
|
17
|
+
goal: Type.Optional(Type.String({ description: "Required for create: concise task goal." })),
|
|
18
|
+
dod: Type.Optional(Type.String({ description: "Required for create: acceptance criteria / definition of done." })),
|
|
19
|
+
manual: Type.Optional(Type.String({ description: "Optional for create: initial operating steps or checklist." })),
|
|
20
|
+
status: Type.Optional(Type.Union(SETTABLE_STATUSES.map((status) => Type.Literal(status)), { description: "New status for create/set. To close a task use action done, not status." })),
|
|
16
21
|
wake: Type.Optional(Type.String({
|
|
17
22
|
description: "ISO8601 earliest-recheck time for set; empty string clears it. Keep in sync with any .checkin event.",
|
|
18
23
|
})),
|
|
19
24
|
recurrence: Type.Optional(Type.String({ description: "Annotation only (e.g. 每周一); empty string clears it." })),
|
|
25
|
+
summary: Type.Optional(Type.String({ description: "Required for done: concise completion summary." })),
|
|
26
|
+
evidence: Type.Optional(Type.String({
|
|
27
|
+
description: "Required for done: verification evidence (tests, commands, review result, external confirmation, or a clear not-run reason).",
|
|
28
|
+
})),
|
|
29
|
+
residualRisk: Type.Optional(Type.String({ description: "Optional for done: remaining risk or follow-up note." })),
|
|
20
30
|
});
|
|
21
31
|
function parseAction(action) {
|
|
22
|
-
if (action === "set" || action === "done" || action === "list") {
|
|
32
|
+
if (action === "create" || action === "set" || action === "done" || action === "list") {
|
|
23
33
|
return action;
|
|
24
34
|
}
|
|
25
|
-
throw new Error('Unsupported task action. Use "set", "done", or "list".');
|
|
35
|
+
throw new Error('Unsupported task action. Use "create", "set", "done", or "list".');
|
|
26
36
|
}
|
|
27
37
|
function toWorkspacePath(options, hostPath) {
|
|
28
38
|
if (hostPath.startsWith(options.workspaceDir)) {
|
|
@@ -45,6 +55,54 @@ function renderTaskFile(fields, body) {
|
|
|
45
55
|
lines.push("---");
|
|
46
56
|
return `${lines.join("\n")}\n${body}`;
|
|
47
57
|
}
|
|
58
|
+
function requiredField(value, field, action) {
|
|
59
|
+
const trimmed = value?.trim();
|
|
60
|
+
if (!trimmed) {
|
|
61
|
+
throw new Error(`action "${action}" requires ${field}.`);
|
|
62
|
+
}
|
|
63
|
+
return trimmed;
|
|
64
|
+
}
|
|
65
|
+
function requireNonEmpty(value, field) {
|
|
66
|
+
return requiredField(value, field, "done");
|
|
67
|
+
}
|
|
68
|
+
function markdownValue(value) {
|
|
69
|
+
const lines = value.trim().split(/\r?\n/);
|
|
70
|
+
if (lines.length === 1)
|
|
71
|
+
return lines[0];
|
|
72
|
+
return lines.map((line, index) => (index === 0 ? line : ` ${line}`)).join("\n");
|
|
73
|
+
}
|
|
74
|
+
function appendCompletionEvidence(body, request) {
|
|
75
|
+
const summary = requireNonEmpty(request.summary, "summary");
|
|
76
|
+
const evidence = requireNonEmpty(request.evidence, "evidence");
|
|
77
|
+
const lines = [
|
|
78
|
+
"## Completion Evidence",
|
|
79
|
+
"",
|
|
80
|
+
`- Summary: ${markdownValue(summary)}`,
|
|
81
|
+
`- Evidence: ${markdownValue(evidence)}`,
|
|
82
|
+
];
|
|
83
|
+
const residualRisk = request.residualRisk?.trim();
|
|
84
|
+
if (residualRisk) {
|
|
85
|
+
lines.push(`- Residual risk: ${markdownValue(residualRisk)}`);
|
|
86
|
+
}
|
|
87
|
+
const normalizedBody = body.endsWith("\n") ? body.replace(/\n+$/, "\n") : `${body}\n`;
|
|
88
|
+
return `${normalizedBody}\n${lines.join("\n")}\n`;
|
|
89
|
+
}
|
|
90
|
+
function normalizeCreateStatus(status) {
|
|
91
|
+
if (status === undefined)
|
|
92
|
+
return "open";
|
|
93
|
+
if (SETTABLE_STATUSES.includes(status)) {
|
|
94
|
+
return status;
|
|
95
|
+
}
|
|
96
|
+
throw new Error(`Invalid status "${status}". Use one of ${SETTABLE_STATUSES.join(", ")}.`);
|
|
97
|
+
}
|
|
98
|
+
function renderTaskSkeleton(request) {
|
|
99
|
+
const title = requiredField(request.title, "title", "create");
|
|
100
|
+
const goal = requiredField(request.goal, "goal", "create");
|
|
101
|
+
const dod = requiredField(request.dod, "dod", "create");
|
|
102
|
+
const fields = applySet({ status: normalizeCreateStatus(request.status) }, request);
|
|
103
|
+
const body = renderStandardTaskBody({ title, goal, dod, manual: request.manual });
|
|
104
|
+
return { fields, body };
|
|
105
|
+
}
|
|
48
106
|
/**
|
|
49
107
|
* Read a task file and split it into its three-field frontmatter and verbatim body.
|
|
50
108
|
* Fail-closed: an unreadable frontmatter block is rejected (fix it with edit first)
|
|
@@ -95,19 +153,47 @@ function applySet(fields, request) {
|
|
|
95
153
|
}
|
|
96
154
|
return next;
|
|
97
155
|
}
|
|
156
|
+
async function createTask(options, request) {
|
|
157
|
+
if (!request.id)
|
|
158
|
+
throw new Error('action "create" requires an id.');
|
|
159
|
+
const id = normalizeTaskId(request.id);
|
|
160
|
+
const dir = tasksDir(options);
|
|
161
|
+
const taskPath = join(dir, `${id}.md`);
|
|
162
|
+
const archivePath = join(dir, "archive", `${id}.md`);
|
|
163
|
+
if (existsSync(taskPath)) {
|
|
164
|
+
throw new Error(`Task "${id}" already exists; use action "set" or edit the body instead.`);
|
|
165
|
+
}
|
|
166
|
+
if (existsSync(archivePath)) {
|
|
167
|
+
throw new Error(`Archived task "${id}" already exists; choose a new id or restore it manually first.`);
|
|
168
|
+
}
|
|
169
|
+
const { fields, body } = renderTaskSkeleton(request);
|
|
170
|
+
await mkdir(dir, { recursive: true });
|
|
171
|
+
await writeFileAtomically(taskPath, renderTaskFile(fields, body));
|
|
172
|
+
return {
|
|
173
|
+
action: "create",
|
|
174
|
+
id,
|
|
175
|
+
path: toWorkspacePath(options, taskPath),
|
|
176
|
+
status: fields.status,
|
|
177
|
+
notice: `已创建任务 \`${id}\`(status: ${fields.status})。`,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
98
180
|
/**
|
|
99
|
-
* On close-out,
|
|
100
|
-
*
|
|
101
|
-
*
|
|
181
|
+
* On close-out, keep only the task's recurring cadence event
|
|
182
|
+
* (`task.<channelId>.<id>.schedule`) and delete every other task-owned event.
|
|
183
|
+
*
|
|
184
|
+
* A task may also own temporary periodic events (for example an agentmux idle sensor).
|
|
185
|
+
* Those are lifecycle check-ins, not proof that the task itself is recurring, so they
|
|
186
|
+
* must not prevent a one-shot task from being archived.
|
|
102
187
|
*/
|
|
103
188
|
async function cleanupTaskEvents(options, id) {
|
|
104
189
|
const dir = eventsDir(options);
|
|
105
190
|
if (!existsSync(dir))
|
|
106
|
-
return { deleted: [],
|
|
107
|
-
const prefix =
|
|
191
|
+
return { deleted: [], hasSchedule: false };
|
|
192
|
+
const prefix = taskEventPrefix(options.channelId, id);
|
|
193
|
+
const scheduleFilename = taskScheduleEventFilename(options.channelId, id);
|
|
108
194
|
const deleted = [];
|
|
109
|
-
let
|
|
110
|
-
for (const filename of await readdir(dir)) {
|
|
195
|
+
let hasSchedule = false;
|
|
196
|
+
for (const filename of (await readdir(dir)).sort()) {
|
|
111
197
|
if (!filename.endsWith(".json") || !filename.startsWith(prefix))
|
|
112
198
|
continue;
|
|
113
199
|
const eventPath = join(dir, filename);
|
|
@@ -118,14 +204,14 @@ async function cleanupTaskEvents(options, id) {
|
|
|
118
204
|
catch {
|
|
119
205
|
continue; // can't classify → leave it for /events to handle
|
|
120
206
|
}
|
|
121
|
-
if (
|
|
122
|
-
|
|
207
|
+
if (filename === scheduleFilename && isTaskScheduleEvent({ use: "schedule", event: { type } })) {
|
|
208
|
+
hasSchedule = true; // the cadence lives on for the next cycle
|
|
123
209
|
continue;
|
|
124
210
|
}
|
|
125
211
|
await unlink(eventPath);
|
|
126
212
|
deleted.push(filename.slice(0, -".json".length));
|
|
127
213
|
}
|
|
128
|
-
return { deleted,
|
|
214
|
+
return { deleted, hasSchedule };
|
|
129
215
|
}
|
|
130
216
|
async function setTask(options, request) {
|
|
131
217
|
if (!request.id)
|
|
@@ -150,12 +236,13 @@ async function doneTask(options, request) {
|
|
|
150
236
|
const dir = tasksDir(options);
|
|
151
237
|
const taskPath = join(dir, `${id}.md`);
|
|
152
238
|
const { fields, body } = await readTaskDocument(taskPath, id);
|
|
153
|
-
|
|
154
|
-
|
|
239
|
+
const bodyWithEvidence = appendCompletionEvidence(body, request);
|
|
240
|
+
await writeFileAtomically(taskPath, renderTaskFile({ ...fields, status: "done" }, bodyWithEvidence));
|
|
241
|
+
const { deleted, hasSchedule } = await cleanupTaskEvents(options, id);
|
|
155
242
|
// Periodic task → sleeps in place until its schedule fires next; one-shot → archive.
|
|
156
243
|
let archived = false;
|
|
157
244
|
let finalPath = taskPath;
|
|
158
|
-
if (!
|
|
245
|
+
if (!hasSchedule) {
|
|
159
246
|
const archiveDir = join(dir, "archive");
|
|
160
247
|
await mkdir(archiveDir, { recursive: true });
|
|
161
248
|
finalPath = join(archiveDir, `${id}.md`);
|
|
@@ -190,6 +277,8 @@ async function listTasks(options) {
|
|
|
190
277
|
}
|
|
191
278
|
export async function manageTask(options, request) {
|
|
192
279
|
switch (request.action) {
|
|
280
|
+
case "create":
|
|
281
|
+
return createTask(options, request);
|
|
193
282
|
case "set":
|
|
194
283
|
return setTask(options, request);
|
|
195
284
|
case "done":
|
|
@@ -203,16 +292,24 @@ export function createTaskManageTool(options) {
|
|
|
203
292
|
name: "task_manage",
|
|
204
293
|
label: "task_manage",
|
|
205
294
|
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
|
|
207
|
-
"(goal, DoD, manual, cycle log) with write/edit; this tool owns only the
|
|
295
|
+
"(requiring summary/evidence, archiving one-shot tasks, and cleaning up residual events), or list active " +
|
|
296
|
+
"tasks. Write the task body (goal, DoD, manual, cycle log) with write/edit; this tool owns only the " +
|
|
297
|
+
"frontmatter and close-out evidence.",
|
|
208
298
|
parameters: taskManageSchema,
|
|
209
299
|
execute: async (_toolCallId, args) => {
|
|
210
300
|
const result = await manageTask(options, {
|
|
211
301
|
action: parseAction(args.action),
|
|
212
302
|
id: args.id,
|
|
303
|
+
title: args.title,
|
|
304
|
+
goal: args.goal,
|
|
305
|
+
dod: args.dod,
|
|
306
|
+
manual: args.manual,
|
|
213
307
|
status: args.status,
|
|
214
308
|
wake: args.wake,
|
|
215
309
|
recurrence: args.recurrence,
|
|
310
|
+
summary: args.summary,
|
|
311
|
+
evidence: args.evidence,
|
|
312
|
+
residualRisk: args.residualRisk,
|
|
216
313
|
});
|
|
217
314
|
return {
|
|
218
315
|
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
package/dist/tools/web-fetch.js
CHANGED
|
@@ -34,6 +34,9 @@ function windowResult(body, offset, maxChars, url, fromCache) {
|
|
|
34
34
|
const cacheNote = fromCache ? " (served from cache, no refetch)" : "";
|
|
35
35
|
text += `\n\n[Showing chars ${start}-${end} of ${body.length}. Re-call web_fetch with the same url and offset=${end} to continue${cacheNote}.]`;
|
|
36
36
|
}
|
|
37
|
+
else if (offset >= body.length && body.length > 0) {
|
|
38
|
+
text += `\n\n[Reached end of page (${body.length} chars). No more content.]`;
|
|
39
|
+
}
|
|
37
40
|
return {
|
|
38
41
|
content: [{ type: "text", text }],
|
|
39
42
|
details: {
|
package/dist/tui/app.js
CHANGED
|
@@ -89,7 +89,7 @@ export async function runTuiApp(options) {
|
|
|
89
89
|
renderHelp: () => renderBuiltInHelp(),
|
|
90
90
|
renderUsage: (args) => renderUsageReport(getUsageLedger(), channelId, parseUsageMode(args), new Date()),
|
|
91
91
|
runEvents: (args) => handleEventsCommand({ args, workspaceDir: paths.workspaceDir, historyPath: paths.eventHistoryPath }),
|
|
92
|
-
runTasks: (args) => handleTasksCommand({ args, channelDir }),
|
|
92
|
+
runTasks: (args) => handleTasksCommand({ args, channelDir, workspaceDir: paths.workspaceDir, channelId }),
|
|
93
93
|
statusInfo: { version: readCliVersion(), sandbox, startedAt: Date.now() },
|
|
94
94
|
});
|
|
95
95
|
try {
|
package/dist/tui/commands.js
CHANGED
|
@@ -58,7 +58,7 @@ export const TUI_SLASH_COMMANDS = [
|
|
|
58
58
|
{ name: "status", description: "Show model, context and run state" },
|
|
59
59
|
{ name: "usage", description: "Show LLM cost for this channel", argumentHint: "[7d|month]" },
|
|
60
60
|
{ name: "events", description: "Manage scheduled events", argumentHint: "<list|show|delete|history>" },
|
|
61
|
-
{ name: "tasks", description: "View the task ledger (read-only)", argumentHint: "[show <id>|archive]" },
|
|
61
|
+
{ name: "tasks", description: "View the task ledger (read-only)", argumentHint: "[show <id>|archive|doctor]" },
|
|
62
62
|
{ name: "model", description: "Show or switch the model", argumentHint: "[provider/model]" },
|
|
63
63
|
{ name: "new", description: "Start a new session" },
|
|
64
64
|
{ name: "compact", description: "Compact the session context", argumentHint: "[instructions]" },
|
package/package.json
CHANGED