@oyasmi/pipiclaw 0.7.4 → 0.7.6
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 +5 -1
- package/dist/agent/channel-runner.js +14 -0
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +6 -0
- 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/memory/review-log.d.ts +1 -1
- package/dist/memory/task-digest.d.ts +21 -0
- package/dist/memory/task-digest.js +66 -0
- package/dist/runtime/bootstrap.js +13 -1
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +6 -2
- package/dist/runtime/event-commands.d.ts +5 -0
- package/dist/runtime/event-commands.js +2 -2
- package/dist/runtime/task-commands.d.ts +6 -0
- package/dist/runtime/task-commands.js +133 -0
- package/dist/settings.d.ts +7 -0
- package/dist/settings.js +13 -0
- package/dist/shared/task-ledger.d.ts +53 -0
- package/dist/shared/task-ledger.js +149 -0
- package/dist/tools/bash.d.ts +12 -0
- package/dist/tools/bash.js +67 -1
- package/dist/tools/config.d.ts +15 -0
- package/dist/tools/config.js +37 -0
- package/dist/tools/edit.js +0 -0
- package/dist/tools/event-manage.d.ts +35 -0
- package/dist/tools/event-manage.js +238 -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 +54 -17
- 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 +43 -0
- package/dist/tools/task-manage.js +226 -0
- 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 +70 -5
- package/dist/tui/app.js +2 -0
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +3 -0
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- 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,18 +1,25 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { readdir, readFile, stat } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { Type } from "typebox";
|
|
5
5
|
import { createAtomicTempPath, writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
|
-
import { resolveSkillPath, resolveSkillSupportingFile, scanSkillContent, validateSkillMarkdown, } from "./skill-security.js";
|
|
6
|
+
import { resolveSkillPath, resolveSkillSupportingFile, scanSkillContent, validateSkillFrontmatter, validateSkillMarkdown, validateSkillName, } from "./skill-security.js";
|
|
7
|
+
import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
|
|
7
8
|
const skillManageSchema = Type.Object({
|
|
8
|
-
label: Type.String({ description: "Brief description of the skill
|
|
9
|
-
action: Type.Union([
|
|
10
|
-
|
|
9
|
+
label: Type.String({ description: "Brief description of the skill action (shown to user)" }),
|
|
10
|
+
action: Type.Union([
|
|
11
|
+
Type.Literal("list"),
|
|
12
|
+
Type.Literal("view"),
|
|
13
|
+
Type.Literal("create"),
|
|
14
|
+
Type.Literal("patch"),
|
|
15
|
+
Type.Literal("write_file"),
|
|
16
|
+
], {
|
|
17
|
+
description: '"list" workspace skills, "view" one skill\'s contents, or "create"/"patch"/"write_file" to author them.',
|
|
11
18
|
}),
|
|
12
|
-
name: Type.String({ description: "Workspace skill name" }),
|
|
19
|
+
name: Type.Optional(Type.String({ description: "Workspace skill name (required for all actions except list)." })),
|
|
13
20
|
content: Type.Optional(Type.String({ description: "Full content for create/write_file." })),
|
|
14
21
|
filePath: Type.Optional(Type.String({
|
|
15
|
-
description: "
|
|
22
|
+
description: "Supporting file path inside the skill for view/patch/write_file. Defaults to SKILL.md. Supporting files must be under references/, templates/, scripts/, or assets/.",
|
|
16
23
|
})),
|
|
17
24
|
find: Type.Optional(Type.String({ description: "Exact text to replace when action is patch." })),
|
|
18
25
|
replace: Type.Optional(Type.String({ description: "Replacement text when action is patch." })),
|
|
@@ -23,11 +30,75 @@ function toWorkspacePath(options, hostPath) {
|
|
|
23
30
|
}
|
|
24
31
|
return hostPath;
|
|
25
32
|
}
|
|
26
|
-
function
|
|
33
|
+
function isNodeError(error) {
|
|
34
|
+
return error instanceof Error && "code" in error;
|
|
35
|
+
}
|
|
36
|
+
function extractDescription(content) {
|
|
37
|
+
const match = content.replace(/\r\n/g, "\n").match(/^---\n([\s\S]*?)\n---/);
|
|
38
|
+
if (!match) {
|
|
39
|
+
return "";
|
|
40
|
+
}
|
|
41
|
+
for (const line of (match[1] ?? "").split("\n")) {
|
|
42
|
+
const fieldMatch = line.match(/^description:\s*(.*)$/);
|
|
43
|
+
if (fieldMatch) {
|
|
44
|
+
return fieldMatch[1].replace(/^["']|["']$/g, "").trim();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return "";
|
|
48
|
+
}
|
|
49
|
+
export async function listWorkspaceSkills(options) {
|
|
50
|
+
const skillsDir = join(options.workspaceDir, "skills");
|
|
51
|
+
let names;
|
|
52
|
+
try {
|
|
53
|
+
names = await readdir(skillsDir);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
57
|
+
return [];
|
|
58
|
+
}
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
61
|
+
const summaries = [];
|
|
62
|
+
for (const name of names.sort()) {
|
|
63
|
+
const nameValidation = validateSkillName(name);
|
|
64
|
+
if (!nameValidation.ok) {
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
const skillDir = join(skillsDir, name);
|
|
68
|
+
const skillStats = await stat(skillDir).catch(() => null);
|
|
69
|
+
if (!skillStats?.isDirectory()) {
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const skillPath = join(skillDir, "SKILL.md");
|
|
73
|
+
let content;
|
|
74
|
+
try {
|
|
75
|
+
const skillFileStats = await stat(skillPath);
|
|
76
|
+
if (!skillFileStats.isFile()) {
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
content = await readFile(skillPath, "utf-8");
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
throw error;
|
|
86
|
+
}
|
|
87
|
+
const validation = validateSkillFrontmatter(content, name);
|
|
88
|
+
summaries.push({
|
|
89
|
+
name,
|
|
90
|
+
description: extractDescription(content),
|
|
91
|
+
path: `${options.workspacePath}/skills/${name}/SKILL.md`,
|
|
92
|
+
warning: validation.ok ? undefined : validation.error,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return summaries;
|
|
96
|
+
}
|
|
97
|
+
function parseWriteAction(action) {
|
|
27
98
|
if (action === "create" || action === "patch" || action === "write_file") {
|
|
28
99
|
return action;
|
|
29
100
|
}
|
|
30
|
-
throw new Error('Unsupported skill action. Use "create", "patch", or "write_file".');
|
|
101
|
+
throw new Error('Unsupported skill action. Use "list", "view", "create", "patch", or "write_file".');
|
|
31
102
|
}
|
|
32
103
|
function ensureSkillMarkdownSafe(content, name) {
|
|
33
104
|
const validation = validateSkillMarkdown(content, name);
|
|
@@ -113,15 +184,45 @@ export async function manageWorkspaceSkill(options, request) {
|
|
|
113
184
|
notice: `已沉淀:更新 workspace skill \`${request.name}\`。`,
|
|
114
185
|
};
|
|
115
186
|
}
|
|
187
|
+
async function viewWorkspaceSkill(options, name, filePath) {
|
|
188
|
+
const skillDir = resolveSkillPath(options.workspaceDir, name);
|
|
189
|
+
const targetPath = filePath ? resolveSkillSupportingFile(skillDir, filePath) : join(skillDir, "SKILL.md");
|
|
190
|
+
const workspacePath = toWorkspacePath(options, targetPath);
|
|
191
|
+
const content = await readFile(targetPath, "utf-8");
|
|
192
|
+
// Cap with the shared truncation limits so a large supporting file cannot flood context.
|
|
193
|
+
const truncation = truncateHead(content);
|
|
194
|
+
let body = truncation.content;
|
|
195
|
+
if (truncation.truncated) {
|
|
196
|
+
body += `\n\n[Truncated at ${formatSize(DEFAULT_MAX_BYTES)}. Use the read tool on ${workspacePath} to page through the rest.]`;
|
|
197
|
+
}
|
|
198
|
+
return {
|
|
199
|
+
content: [{ type: "text", text: `Skill: ${name}\nPath: ${workspacePath}\n\n${body}` }],
|
|
200
|
+
details: { kind: "skill_manage", action: "view", name, path: workspacePath, truncated: truncation.truncated },
|
|
201
|
+
};
|
|
202
|
+
}
|
|
116
203
|
export function createSkillManageTool(options) {
|
|
117
204
|
return {
|
|
118
205
|
name: "skill_manage",
|
|
119
206
|
label: "skill_manage",
|
|
120
|
-
description: "
|
|
207
|
+
description: "Manage workspace-level Pipiclaw skills (procedural memory): list them, view one's contents, or author them " +
|
|
208
|
+
"with create/patch/write_file. No channel-scoped skills.",
|
|
121
209
|
parameters: skillManageSchema,
|
|
122
210
|
execute: async (_toolCallId, args) => {
|
|
211
|
+
if (args.action === "list") {
|
|
212
|
+
const skills = await listWorkspaceSkills(options);
|
|
213
|
+
return {
|
|
214
|
+
content: [{ type: "text", text: JSON.stringify({ skills }) }],
|
|
215
|
+
details: { kind: "skill_manage", action: "list", count: skills.length },
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
if (!args.name) {
|
|
219
|
+
throw new Error(`Action "${args.action}" requires a skill name.`);
|
|
220
|
+
}
|
|
221
|
+
if (args.action === "view") {
|
|
222
|
+
return viewWorkspaceSkill(options, args.name, args.filePath);
|
|
223
|
+
}
|
|
123
224
|
const result = await manageWorkspaceSkill(options, {
|
|
124
|
-
action:
|
|
225
|
+
action: parseWriteAction(args.action),
|
|
125
226
|
name: args.name,
|
|
126
227
|
content: args.content,
|
|
127
228
|
filePath: args.filePath,
|
|
@@ -130,10 +231,7 @@ export function createSkillManageTool(options) {
|
|
|
130
231
|
});
|
|
131
232
|
return {
|
|
132
233
|
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
133
|
-
details: {
|
|
134
|
-
kind: "skill_manage",
|
|
135
|
-
...result,
|
|
136
|
-
},
|
|
234
|
+
details: { kind: "skill_manage", ...result },
|
|
137
235
|
};
|
|
138
236
|
},
|
|
139
237
|
};
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const WEB_CACHE_TTL_MS: number;
|
|
2
|
+
export interface WebCacheEntry {
|
|
3
|
+
body: string;
|
|
4
|
+
fetchedAt: number;
|
|
5
|
+
}
|
|
6
|
+
/** Cache key from the requested URL plus extract mode (markdown vs text render differently). */
|
|
7
|
+
export declare function webCacheKey(url: string, extractMode: string): string;
|
|
8
|
+
/** Return the cached body if present and within the TTL, else null. */
|
|
9
|
+
export declare function readWebCache(channelDir: string, key: string, ttlMs?: number): Promise<WebCacheEntry | null>;
|
|
10
|
+
/** Persist a body and evict the oldest entries beyond the cap. Best-effort; never throws. */
|
|
11
|
+
export declare function writeWebCache(channelDir: string, key: string, body: string): Promise<void>;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
6
|
+
/**
|
|
7
|
+
* Small per-channel cache of fetched web page bodies so a long page can be paged over with `offset`
|
|
8
|
+
* without re-issuing the (slow, non-deterministic) HTTP request. Bodies are the clean extracted text
|
|
9
|
+
* — the banner and windowing are re-applied by the tool on each read.
|
|
10
|
+
*/
|
|
11
|
+
const WEB_CACHE_DIR = "web-cache";
|
|
12
|
+
export const WEB_CACHE_TTL_MS = 15 * 60 * 1000;
|
|
13
|
+
const WEB_CACHE_MAX_FILES = 20;
|
|
14
|
+
function cacheDir(channelDir) {
|
|
15
|
+
return join(channelDir, WEB_CACHE_DIR);
|
|
16
|
+
}
|
|
17
|
+
/** Cache key from the requested URL plus extract mode (markdown vs text render differently). */
|
|
18
|
+
export function webCacheKey(url, extractMode) {
|
|
19
|
+
return createHash("sha256").update(`${extractMode}\n${url}`).digest("hex").slice(0, 24);
|
|
20
|
+
}
|
|
21
|
+
function bodyPath(channelDir, key) {
|
|
22
|
+
return join(cacheDir(channelDir), `${key}.txt`);
|
|
23
|
+
}
|
|
24
|
+
/** Return the cached body if present and within the TTL, else null. */
|
|
25
|
+
export async function readWebCache(channelDir, key, ttlMs = WEB_CACHE_TTL_MS) {
|
|
26
|
+
const path = bodyPath(channelDir, key);
|
|
27
|
+
try {
|
|
28
|
+
const stats = await stat(path);
|
|
29
|
+
// `>=` so a TTL of 0 means "always refetch" rather than depending on sub-ms timing.
|
|
30
|
+
if (Date.now() - stats.mtimeMs >= ttlMs) {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
return { body: await readFile(path, "utf-8"), fetchedAt: stats.mtimeMs };
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** Persist a body and evict the oldest entries beyond the cap. Best-effort; never throws. */
|
|
40
|
+
export async function writeWebCache(channelDir, key, body) {
|
|
41
|
+
try {
|
|
42
|
+
const dir = cacheDir(channelDir);
|
|
43
|
+
if (!existsSync(dir)) {
|
|
44
|
+
await mkdir(dir, { recursive: true });
|
|
45
|
+
}
|
|
46
|
+
await writeFileAtomically(bodyPath(channelDir, key), body);
|
|
47
|
+
await pruneWebCache(dir);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// Caching is an optimization; a failure just means the next read refetches.
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async function pruneWebCache(dir) {
|
|
54
|
+
const files = (await readdir(dir)).filter((name) => name.endsWith(".txt"));
|
|
55
|
+
if (files.length <= WEB_CACHE_MAX_FILES) {
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const withTimes = await Promise.all(files.map(async (name) => ({ name, mtimeMs: (await stat(join(dir, name)).catch(() => null))?.mtimeMs ?? 0 })));
|
|
59
|
+
withTimes.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
60
|
+
const excess = withTimes.slice(0, withTimes.length - WEB_CACHE_MAX_FILES);
|
|
61
|
+
await Promise.all(excess.map((entry) => rm(join(dir, entry.name), { force: true })));
|
|
62
|
+
}
|
|
@@ -7,12 +7,15 @@ declare const webFetchSchema: Type.TObject<{
|
|
|
7
7
|
url: Type.TString;
|
|
8
8
|
extractMode: Type.TOptional<Type.TUnion<[Type.TLiteral<"markdown">, Type.TLiteral<"text">]>>;
|
|
9
9
|
maxChars: Type.TOptional<Type.TNumber>;
|
|
10
|
+
offset: Type.TOptional<Type.TInteger>;
|
|
10
11
|
}>;
|
|
11
12
|
export interface WebFetchToolOptions {
|
|
12
13
|
webConfig: PipiclawWebToolsConfig;
|
|
13
14
|
securityConfig: SecurityConfig;
|
|
14
15
|
workspaceDir: string;
|
|
15
16
|
channelId?: string;
|
|
17
|
+
/** Present on the main path; enables per-channel body caching + offset pagination. */
|
|
18
|
+
channelDir?: string;
|
|
16
19
|
}
|
|
17
20
|
export declare function createWebFetchTool(options: WebFetchToolOptions): AgentTool<typeof webFetchSchema>;
|
|
18
21
|
export {};
|
package/dist/tools/web-fetch.js
CHANGED
|
@@ -1,29 +1,94 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import { resolveWebFetchRequest } from "../web/config.js";
|
|
3
3
|
import { runWebFetch } from "../web/fetch.js";
|
|
4
|
+
import { formatFetchedText, UNTRUSTED_WEB_CONTENT_BANNER } from "../web/format.js";
|
|
5
|
+
import { readWebCache, webCacheKey, writeWebCache } from "./web-cache.js";
|
|
6
|
+
// Large cap used to fetch the full readable body for caching; the displayed window is bounded by the
|
|
7
|
+
// configured/requested maxChars. Still smaller than maxResponseBytes so a hostile page can't OOM us.
|
|
8
|
+
const FULL_FETCH_MAX_CHARS = 2_000_000;
|
|
4
9
|
const webFetchSchema = Type.Object({
|
|
5
10
|
label: Type.String({ description: "Brief description of what you're fetching and why (shown to user)" }),
|
|
6
11
|
url: Type.String({ description: "HTTP or HTTPS URL to fetch" }),
|
|
7
12
|
extractMode: Type.Optional(Type.Union([Type.Literal("markdown"), Type.Literal("text")], {
|
|
8
13
|
description: "Preferred text extraction format for HTML pages",
|
|
9
14
|
})),
|
|
10
|
-
maxChars: Type.Optional(Type.Number({ description: "Maximum extracted text characters to return" })),
|
|
15
|
+
maxChars: Type.Optional(Type.Number({ description: "Maximum extracted text characters to return per call" })),
|
|
16
|
+
offset: Type.Optional(Type.Integer({
|
|
17
|
+
minimum: 0,
|
|
18
|
+
description: "Character offset into the page body to start from. Use the offset the previous call reported to page through a long page — it is served from cache with no refetch.",
|
|
19
|
+
})),
|
|
11
20
|
});
|
|
21
|
+
/** Strip the untrusted-content banner that runWebFetch prepends, so the cached body is clean. */
|
|
22
|
+
function stripBanner(text) {
|
|
23
|
+
if (text.startsWith(UNTRUSTED_WEB_CONTENT_BANNER)) {
|
|
24
|
+
return text.slice(UNTRUSTED_WEB_CONTENT_BANNER.length).replace(/^\n+/, "");
|
|
25
|
+
}
|
|
26
|
+
return text;
|
|
27
|
+
}
|
|
28
|
+
function windowResult(body, offset, maxChars, url, fromCache) {
|
|
29
|
+
const start = Math.min(offset, body.length);
|
|
30
|
+
const end = Math.min(start + maxChars, body.length);
|
|
31
|
+
const slice = body.slice(start, end);
|
|
32
|
+
let text = formatFetchedText(slice);
|
|
33
|
+
if (end < body.length) {
|
|
34
|
+
const cacheNote = fromCache ? " (served from cache, no refetch)" : "";
|
|
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
|
+
}
|
|
37
|
+
return {
|
|
38
|
+
content: [{ type: "text", text }],
|
|
39
|
+
details: {
|
|
40
|
+
kind: "web_fetch",
|
|
41
|
+
url,
|
|
42
|
+
offset: start,
|
|
43
|
+
shownChars: slice.length,
|
|
44
|
+
totalChars: body.length,
|
|
45
|
+
fromCache,
|
|
46
|
+
untrusted: true,
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
12
50
|
export function createWebFetchTool(options) {
|
|
13
51
|
return {
|
|
14
52
|
name: "web_fetch",
|
|
15
53
|
label: "web_fetch",
|
|
16
|
-
description: "Fetch a public URL and extract readable content. Returns text for HTML/JSON/text pages and image content
|
|
54
|
+
description: "Fetch a public URL and extract readable content. Returns text for HTML/JSON/text pages and image content " +
|
|
55
|
+
"blocks for images. Long pages are cached per channel; page through them with offset (no refetch).",
|
|
17
56
|
parameters: webFetchSchema,
|
|
18
|
-
execute: async (_toolCallId, { url, extractMode, maxChars, }, signal) => {
|
|
57
|
+
execute: async (_toolCallId, { url, extractMode, maxChars, offset, }, signal) => {
|
|
19
58
|
const request = resolveWebFetchRequest(options.webConfig.fetch, url, extractMode, maxChars);
|
|
59
|
+
const displayMaxChars = request.maxChars;
|
|
60
|
+
const startOffset = offset && offset > 0 ? offset : 0;
|
|
61
|
+
// Cache is per-channel; when no channelDir is available (e.g. sub-agent path) fall back to a
|
|
62
|
+
// plain single-shot fetch with the requested maxChars.
|
|
63
|
+
if (!options.channelDir) {
|
|
64
|
+
return runWebFetch({
|
|
65
|
+
webConfig: options.webConfig,
|
|
66
|
+
securityConfig: options.securityConfig,
|
|
67
|
+
workspaceDir: options.workspaceDir,
|
|
68
|
+
channelId: options.channelId,
|
|
69
|
+
}, request, signal);
|
|
70
|
+
}
|
|
71
|
+
const key = webCacheKey(url, request.extractMode);
|
|
72
|
+
const cached = await readWebCache(options.channelDir, key);
|
|
73
|
+
if (cached) {
|
|
74
|
+
return windowResult(cached.body, startOffset, displayMaxChars, url, true);
|
|
75
|
+
}
|
|
76
|
+
// Cache miss: fetch the full readable body once, cache it, then serve the window.
|
|
20
77
|
const result = await runWebFetch({
|
|
21
78
|
webConfig: options.webConfig,
|
|
22
79
|
securityConfig: options.securityConfig,
|
|
23
80
|
workspaceDir: options.workspaceDir,
|
|
24
81
|
channelId: options.channelId,
|
|
25
|
-
}, request, signal);
|
|
26
|
-
|
|
82
|
+
}, { ...request, maxChars: FULL_FETCH_MAX_CHARS }, signal);
|
|
83
|
+
// Images (and any non-text result) are passed through unchanged — nothing to page or cache.
|
|
84
|
+
const hasImage = result.content.some((part) => part.type === "image");
|
|
85
|
+
const textPart = result.content.find((part) => part.type === "text");
|
|
86
|
+
if (hasImage || !textPart || textPart.type !== "text") {
|
|
87
|
+
return result;
|
|
88
|
+
}
|
|
89
|
+
const body = stripBanner(textPart.text);
|
|
90
|
+
await writeWebCache(options.channelDir, key, body);
|
|
91
|
+
return windowResult(body, startOffset, displayMaxChars, url, false);
|
|
27
92
|
},
|
|
28
93
|
};
|
|
29
94
|
}
|
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 {
|
package/dist/tui/commands.d.ts
CHANGED
|
@@ -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. */
|