@oyasmi/pipiclaw 0.7.5 → 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 +11 -1
- package/dist/agent/channel-runner.js +7 -3
- package/dist/agent/commands.js +2 -1
- package/dist/agent/job-manager.d.ts +79 -0
- package/dist/agent/job-manager.js +241 -0
- package/dist/agent/prompt-builder.js +13 -4
- package/dist/agent/session-events.js +5 -0
- package/dist/memory/recall.js +6 -0
- package/dist/memory/review-log.d.ts +1 -1
- 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/bash.d.ts +12 -0
- package/dist/tools/bash.js +67 -1
- package/dist/tools/config.d.ts +9 -0
- package/dist/tools/config.js +23 -0
- package/dist/tools/edit.js +0 -0
- package/dist/tools/grep.d.ts +19 -0
- package/dist/tools/grep.js +262 -0
- package/dist/tools/index.js +5 -0
- package/dist/tools/job.d.ts +13 -0
- package/dist/tools/job.js +92 -0
- package/dist/tools/memory-manage.d.ts +24 -0
- package/dist/tools/memory-manage.js +150 -0
- package/dist/tools/read.js +103 -16
- package/dist/tools/registry.d.ts +7 -1
- package/dist/tools/registry.js +31 -23
- package/dist/tools/session-search.js +4 -1
- package/dist/tools/skill-manage.d.ts +12 -5
- package/dist/tools/skill-manage.js +113 -15
- package/dist/tools/task-manage.d.ts +16 -2
- package/dist/tools/task-manage.js +119 -22
- package/dist/tools/web-cache.d.ts +11 -0
- package/dist/tools/web-cache.js +62 -0
- package/dist/tools/web-fetch.d.ts +3 -0
- package/dist/tools/web-fetch.js +73 -5
- package/dist/tui/app.js +1 -1
- package/dist/tui/commands.js +1 -1
- package/package.json +1 -1
- package/dist/tools/memory-save.d.ts +0 -16
- package/dist/tools/memory-save.js +0 -42
- package/dist/tools/skill-list.d.ts +0 -18
- package/dist/tools/skill-list.js +0 -86
- package/dist/tools/skill-view.d.ts +0 -13
- package/dist/tools/skill-view.js +0 -44
|
@@ -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/bash.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import { Type } from "typebox";
|
|
3
|
+
import type { ChannelJobManager } from "../agent/job-manager.js";
|
|
3
4
|
import type { Executor } from "../sandbox.js";
|
|
4
5
|
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
5
6
|
/**
|
|
@@ -13,6 +14,7 @@ declare const bashSchema: Type.TObject<{
|
|
|
13
14
|
label: Type.TString;
|
|
14
15
|
command: Type.TString;
|
|
15
16
|
timeout: Type.TOptional<Type.TInteger>;
|
|
17
|
+
async: Type.TOptional<Type.TBoolean>;
|
|
16
18
|
}>;
|
|
17
19
|
export interface BashToolOptions {
|
|
18
20
|
defaultTimeoutSeconds?: number;
|
|
@@ -25,6 +27,16 @@ export interface BashToolOptions {
|
|
|
25
27
|
* Gated by `tools.rtk.enabled` in tools.json.
|
|
26
28
|
*/
|
|
27
29
|
rtkEnabled?: boolean;
|
|
30
|
+
/**
|
|
31
|
+
* Present only on the main path when `tools.jobs.enabled` is on. Enables `async: true`
|
|
32
|
+
* background execution. Absent on the sub-agent path, so sub-agents cannot background jobs.
|
|
33
|
+
*/
|
|
34
|
+
jobManager?: ChannelJobManager;
|
|
35
|
+
/**
|
|
36
|
+
* When true (`tools.bashInterceptor.enabled`), block a few bare shell patterns that have a
|
|
37
|
+
* better dedicated tool and steer the model to it. Off by default; main path only.
|
|
38
|
+
*/
|
|
39
|
+
interceptorEnabled?: boolean;
|
|
28
40
|
}
|
|
29
41
|
export declare function createBashTool(executor: Executor, options?: BashToolOptions): AgentTool<typeof bashSchema>;
|
|
30
42
|
export {};
|
package/dist/tools/bash.js
CHANGED
|
@@ -30,7 +30,44 @@ const bashSchema = Type.Object({
|
|
|
30
30
|
minimum: 1,
|
|
31
31
|
description: `Timeout in seconds. Defaults to ${DEFAULT_BASH_TIMEOUT_SECONDS}s; pass a larger value for long-running commands.`,
|
|
32
32
|
})),
|
|
33
|
+
async: Type.Optional(Type.Boolean({
|
|
34
|
+
description: "Run in the background and return immediately with a job id instead of blocking. Use for long commands so the channel stays responsive; check it later with the job tool or a scheduled event_manage check-in.",
|
|
35
|
+
})),
|
|
33
36
|
});
|
|
37
|
+
/**
|
|
38
|
+
* Bare shell patterns that a dedicated tool handles better (with truncation, grouping, or a diff).
|
|
39
|
+
* Deliberately narrow — only unambiguous bare forms, never piped/compound commands — so a legitimate
|
|
40
|
+
* `cat x | jq` is untouched. Runs after the security guard (which must see the real command) and
|
|
41
|
+
* before rtk. Complements rtk: rtk makes output cheaper, this steers to the right tool.
|
|
42
|
+
*/
|
|
43
|
+
const BASH_INTERCEPTOR_RULES = [
|
|
44
|
+
{
|
|
45
|
+
test: /^\s*cat\s+[^|&;<>`$()]+$/,
|
|
46
|
+
tool: "read",
|
|
47
|
+
why: "it truncates safely and tells you how to page through the rest",
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
// Anchored to end and free of pipe/redirect chars so only a *bare* recursive grep is caught;
|
|
51
|
+
// a piped/compound form like `grep -rn foo . | wc -l` is a legitimate use and must pass through.
|
|
52
|
+
test: /^\s*grep\b[^|&;<>]*\s-[A-Za-z]*r[A-Za-z]*\b[^|&;<>]*$/,
|
|
53
|
+
tool: "grep",
|
|
54
|
+
why: "it groups, paginates, and bounds output instead of flooding the context",
|
|
55
|
+
},
|
|
56
|
+
{ test: /^\s*rg\b[^|&;]*$/, tool: "grep", why: "it groups, paginates, and bounds output" },
|
|
57
|
+
{
|
|
58
|
+
test: /\b(?:sed|perl)\b[^|&;]*\s-i\b/,
|
|
59
|
+
tool: "edit",
|
|
60
|
+
why: "it verifies a unique match and echoes a diff of the change",
|
|
61
|
+
},
|
|
62
|
+
];
|
|
63
|
+
function checkBashInterception(command) {
|
|
64
|
+
for (const rule of BASH_INTERCEPTOR_RULES) {
|
|
65
|
+
if (rule.test.test(command)) {
|
|
66
|
+
return `Blocked: use the ${rule.tool} tool instead — ${rule.why}. Command: ${command}`;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
34
71
|
function formatCommandBlockMessage(command, category, reason, matchedText) {
|
|
35
72
|
const lines = [`Command blocked${category ? ` [${category}]` : ""}`];
|
|
36
73
|
if (reason) {
|
|
@@ -42,6 +79,7 @@ function formatCommandBlockMessage(command, category, reason, matchedText) {
|
|
|
42
79
|
else {
|
|
43
80
|
lines.push(`Command: ${command}`);
|
|
44
81
|
}
|
|
82
|
+
lines.push("If this operation is genuinely needed, explain the intent to the user so they can adjust security.json.");
|
|
45
83
|
return lines.join("\n");
|
|
46
84
|
}
|
|
47
85
|
export function createBashTool(executor, options = {}) {
|
|
@@ -56,7 +94,7 @@ export function createBashTool(executor, options = {}) {
|
|
|
56
94
|
label: "bash",
|
|
57
95
|
description: `Execute a bash command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a temp file whose path is included. Commands time out after ${DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
|
|
58
96
|
parameters: bashSchema,
|
|
59
|
-
execute: async (_toolCallId, { command, timeout }, signal) => {
|
|
97
|
+
execute: async (_toolCallId, { label, command, timeout, async: runAsync, }, signal) => {
|
|
60
98
|
if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
|
|
61
99
|
const guardResult = guardCommand(command, securityConfig.commandGuard);
|
|
62
100
|
if (!guardResult.allowed) {
|
|
@@ -73,11 +111,39 @@ export function createBashTool(executor, options = {}) {
|
|
|
73
111
|
throw new Error(formatCommandBlockMessage(command, guardResult.category, guardResult.reason, guardResult.matchedText));
|
|
74
112
|
}
|
|
75
113
|
}
|
|
114
|
+
// Steer a few bare shell patterns to their dedicated tool. After the guard (which must see
|
|
115
|
+
// the real command), before rtk (which would reshape it). Off by default.
|
|
116
|
+
if (options.interceptorEnabled) {
|
|
117
|
+
const intercepted = checkBashInterception(command);
|
|
118
|
+
if (intercepted) {
|
|
119
|
+
throw new Error(intercepted);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
76
122
|
// Optimize *after* the security guard: the guard must inspect the operator's real
|
|
77
123
|
// intent (`command`), while rtk only reshapes a semantically-equivalent command for
|
|
78
124
|
// compact output. Optimizing first would hide the true command from the guard.
|
|
79
125
|
const effectiveCommand = options.rtkEnabled ? await maybeOptimizeCommand(command, executor, signal) : command;
|
|
80
126
|
const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS;
|
|
127
|
+
// Background execution: hand off to the channel's job manager and return immediately so
|
|
128
|
+
// the run queue is not held for the command's duration. Gated by `tools.jobs.enabled`
|
|
129
|
+
// (the main path supplies a jobManager; the sub-agent path never does).
|
|
130
|
+
if (runAsync) {
|
|
131
|
+
if (!options.jobManager) {
|
|
132
|
+
throw new Error("Background execution is not available here (enable tools.jobs.enabled, and note it is off for sub-agents). Run the command without async, or shorten it.");
|
|
133
|
+
}
|
|
134
|
+
const job = await options.jobManager.start(effectiveCommand, label, effectiveTimeout, signal);
|
|
135
|
+
return {
|
|
136
|
+
content: [
|
|
137
|
+
{
|
|
138
|
+
type: "text",
|
|
139
|
+
text: `Background job ${job.id} started: ${label}\n` +
|
|
140
|
+
"It runs off-turn; you can end your turn now. Check it with the job tool (op:poll/list), " +
|
|
141
|
+
"or schedule an event_manage check-in to be woken when it is likely done.",
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
details: { kind: "bash", async: { state: "running", jobId: job.id } },
|
|
145
|
+
};
|
|
146
|
+
}
|
|
81
147
|
const result = await executor.exec(effectiveCommand, { timeout: effectiveTimeout, signal });
|
|
82
148
|
let output = "";
|
|
83
149
|
if (result.stdout)
|
package/dist/tools/config.d.ts
CHANGED
package/dist/tools/config.js
CHANGED
|
@@ -44,6 +44,15 @@ export const DEFAULT_TOOLS_CONFIG = {
|
|
|
44
44
|
tasks: {
|
|
45
45
|
enabled: true,
|
|
46
46
|
},
|
|
47
|
+
grep: {
|
|
48
|
+
enabled: true,
|
|
49
|
+
},
|
|
50
|
+
jobs: {
|
|
51
|
+
enabled: true,
|
|
52
|
+
},
|
|
53
|
+
bashInterceptor: {
|
|
54
|
+
enabled: true,
|
|
55
|
+
},
|
|
47
56
|
rtk: {
|
|
48
57
|
enabled: false,
|
|
49
58
|
},
|
|
@@ -97,6 +106,9 @@ function mergeToolsConfig(source, configPath, diagnostics) {
|
|
|
97
106
|
const manage = isRecord(skills.manage) ? skills.manage : {};
|
|
98
107
|
const events = isRecord(tools.events) ? tools.events : {};
|
|
99
108
|
const tasks = isRecord(tools.tasks) ? tools.tasks : {};
|
|
109
|
+
const grep = isRecord(tools.grep) ? tools.grep : {};
|
|
110
|
+
const jobs = isRecord(tools.jobs) ? tools.jobs : {};
|
|
111
|
+
const bashInterceptor = isRecord(tools.bashInterceptor) ? tools.bashInterceptor : {};
|
|
100
112
|
const rtk = isRecord(tools.rtk) ? tools.rtk : {};
|
|
101
113
|
const search = isRecord(web.search) ? web.search : {};
|
|
102
114
|
const fetch = isRecord(web.fetch) ? web.fetch : {};
|
|
@@ -187,6 +199,17 @@ function mergeToolsConfig(source, configPath, diagnostics) {
|
|
|
187
199
|
tasks: {
|
|
188
200
|
enabled: typeof tasks.enabled === "boolean" ? tasks.enabled : DEFAULT_TOOLS_CONFIG.tools.tasks.enabled,
|
|
189
201
|
},
|
|
202
|
+
grep: {
|
|
203
|
+
enabled: typeof grep.enabled === "boolean" ? grep.enabled : DEFAULT_TOOLS_CONFIG.tools.grep.enabled,
|
|
204
|
+
},
|
|
205
|
+
jobs: {
|
|
206
|
+
enabled: typeof jobs.enabled === "boolean" ? jobs.enabled : DEFAULT_TOOLS_CONFIG.tools.jobs.enabled,
|
|
207
|
+
},
|
|
208
|
+
bashInterceptor: {
|
|
209
|
+
enabled: typeof bashInterceptor.enabled === "boolean"
|
|
210
|
+
? bashInterceptor.enabled
|
|
211
|
+
: DEFAULT_TOOLS_CONFIG.tools.bashInterceptor.enabled,
|
|
212
|
+
},
|
|
190
213
|
rtk: {
|
|
191
214
|
enabled: typeof rtk.enabled === "boolean" ? rtk.enabled : DEFAULT_TOOLS_CONFIG.tools.rtk.enabled,
|
|
192
215
|
},
|
package/dist/tools/edit.js
CHANGED
|
Binary file
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
|
+
import { Type } from "typebox";
|
|
3
|
+
import type { Executor } from "../sandbox.js";
|
|
4
|
+
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
5
|
+
declare const grepSchema: Type.TObject<{
|
|
6
|
+
label: Type.TString;
|
|
7
|
+
pattern: Type.TString;
|
|
8
|
+
path: Type.TOptional<Type.TString>;
|
|
9
|
+
glob: Type.TOptional<Type.TString>;
|
|
10
|
+
caseSensitive: Type.TOptional<Type.TBoolean>;
|
|
11
|
+
skip: Type.TOptional<Type.TInteger>;
|
|
12
|
+
}>;
|
|
13
|
+
export interface GrepToolOptions {
|
|
14
|
+
securityConfig?: SecurityConfig;
|
|
15
|
+
securityContext?: SecurityRuntimeContext;
|
|
16
|
+
channelId?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare function createGrepTool(executor: Executor, options?: GrepToolOptions): AgentTool<typeof grepSchema>;
|
|
19
|
+
export {};
|