@oyasmi/pipiclaw 0.7.5 → 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/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/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 +28 -21
- 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/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/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
package/dist/tools/read.js
CHANGED
|
@@ -22,6 +22,48 @@ function isImageFile(filePath) {
|
|
|
22
22
|
const ext = extname(filePath).toLowerCase();
|
|
23
23
|
return IMAGE_MIME_TYPES[ext] || null;
|
|
24
24
|
}
|
|
25
|
+
/** Directory tree caps, mirroring oh-my-pi's read: shallow and per-directory bounded. */
|
|
26
|
+
const DIR_MAX_DEPTH = 2;
|
|
27
|
+
const DIR_PER_DIR_LIMIT = 12;
|
|
28
|
+
/**
|
|
29
|
+
* Render a depth-2 directory tree from a newline-separated list of paths (directories carry a
|
|
30
|
+
* trailing `/`, produced by the shell). Kept deliberately portable — no sizes or mtimes, since
|
|
31
|
+
* `find -printf` / `stat` formats differ across BSD, GNU, and busybox; the structure is the value.
|
|
32
|
+
*/
|
|
33
|
+
function renderDirectoryTree(rootPath, rawPaths) {
|
|
34
|
+
const rootPrefix = rootPath.endsWith("/") ? rootPath : `${rootPath}/`;
|
|
35
|
+
const entries = rawPaths
|
|
36
|
+
.split("\n")
|
|
37
|
+
.map((line) => line.trim())
|
|
38
|
+
.filter((line) => line.length > 0 && line !== rootPath && line !== rootPrefix)
|
|
39
|
+
.map((line) => (line.startsWith(rootPrefix) ? line.slice(rootPrefix.length) : line))
|
|
40
|
+
.sort((a, b) => a.replace(/\/$/, "").localeCompare(b.replace(/\/$/, "")));
|
|
41
|
+
if (entries.length === 0) {
|
|
42
|
+
return "(empty directory)";
|
|
43
|
+
}
|
|
44
|
+
// Group by immediate parent so we can cap children per directory.
|
|
45
|
+
const perParentCount = new Map();
|
|
46
|
+
const lines = [];
|
|
47
|
+
const elided = new Map();
|
|
48
|
+
for (const entry of entries) {
|
|
49
|
+
const isDir = entry.endsWith("/");
|
|
50
|
+
const rel = isDir ? entry.slice(0, -1) : entry;
|
|
51
|
+
const segments = rel.split("/");
|
|
52
|
+
const depth = segments.length - 1;
|
|
53
|
+
const parent = depth === 0 ? "" : segments.slice(0, -1).join("/");
|
|
54
|
+
const count = (perParentCount.get(parent) ?? 0) + 1;
|
|
55
|
+
perParentCount.set(parent, count);
|
|
56
|
+
if (count > DIR_PER_DIR_LIMIT) {
|
|
57
|
+
elided.set(parent, (elided.get(parent) ?? 0) + 1);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
lines.push(`${" ".repeat(depth)}${segments[segments.length - 1]}${isDir ? "/" : ""}`);
|
|
61
|
+
}
|
|
62
|
+
for (const [, count] of elided) {
|
|
63
|
+
lines.push(` [+${count} more]`);
|
|
64
|
+
}
|
|
65
|
+
return lines.join("\n");
|
|
66
|
+
}
|
|
25
67
|
const readSchema = Type.Object({
|
|
26
68
|
label: Type.String({ description: "Brief description of what you're reading and why (shown to user)" }),
|
|
27
69
|
path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
|
|
@@ -89,33 +131,78 @@ export function createReadTool(executor, options = {}) {
|
|
|
89
131
|
details: undefined,
|
|
90
132
|
};
|
|
91
133
|
}
|
|
92
|
-
//
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
134
|
+
// PDF documents are converted to text with pdftotext, then run through the same
|
|
135
|
+
// offset/limit/truncation pipeline as any text file.
|
|
136
|
+
const isPdf = extname(path).toLowerCase() === ".pdf";
|
|
137
|
+
let pdfText = "";
|
|
138
|
+
if (isPdf) {
|
|
139
|
+
const converted = await executor.exec(`pdftotext -layout ${shellEscape(path)} - 2>&1`, { signal });
|
|
140
|
+
if (converted.code === 127) {
|
|
141
|
+
throw new Error(`Cannot read ${path}: pdftotext is not installed. Install poppler-utils (host) or rebuild the Docker sandbox image, or ask the user to send a text version.`);
|
|
142
|
+
}
|
|
143
|
+
if (converted.code !== 0 || !converted.stdout.trim()) {
|
|
144
|
+
throw new Error(`Cannot read .pdf file ${path}: ${converted.stdout.trim() || "conversion produced no text"}. ` +
|
|
145
|
+
`The file may be scanned/image-based — ask the user for a text version or a screenshot.`);
|
|
146
|
+
}
|
|
147
|
+
pdfText = converted.stdout;
|
|
148
|
+
}
|
|
149
|
+
// Get total line count. For non-PDF paths this same command also detects a directory
|
|
150
|
+
// (`cat`/`awk` on a directory would fail), so a directory read is a shallow tree rather
|
|
151
|
+
// than a confusing error — all in one exec to keep the call sequence unchanged.
|
|
152
|
+
let totalFileLines;
|
|
153
|
+
if (isPdf) {
|
|
154
|
+
totalFileLines = countTextLines(pdfText);
|
|
155
|
+
}
|
|
156
|
+
else {
|
|
157
|
+
const countResult = await executor.exec(`if [ -d ${shellEscape(path)} ]; then echo __DIR__; else awk 'END { print NR }' ${shellEscape(path)}; fi`, { signal });
|
|
158
|
+
if (countResult.code !== 0) {
|
|
159
|
+
throw new Error(countResult.stderr || `Failed to read file: ${path}`);
|
|
160
|
+
}
|
|
161
|
+
if (countResult.stdout.trim() === "__DIR__") {
|
|
162
|
+
const listing = await executor.exec(`{ find ${shellEscape(path)} -maxdepth ${DIR_MAX_DEPTH} -type d | sed 's,$,/,'; ` +
|
|
163
|
+
`find ${shellEscape(path)} -maxdepth ${DIR_MAX_DEPTH} ! -type d; }`, { signal });
|
|
164
|
+
if (listing.code !== 0) {
|
|
165
|
+
throw new Error(listing.stderr || `Failed to list directory: ${path}`);
|
|
166
|
+
}
|
|
167
|
+
return {
|
|
168
|
+
content: [
|
|
169
|
+
{ type: "text", text: `Directory: ${path}\n\n${renderDirectoryTree(path, listing.stdout)}` },
|
|
170
|
+
],
|
|
171
|
+
details: undefined,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
totalFileLines = Number.parseInt(countResult.stdout.trim(), 10);
|
|
96
175
|
}
|
|
97
|
-
const totalFileLines = Number.parseInt(countResult.stdout.trim(), 10);
|
|
98
176
|
// Apply offset if specified (1-indexed)
|
|
99
177
|
const startLine = offset ? Math.max(1, offset) : 1;
|
|
100
178
|
const startLineDisplay = startLine;
|
|
101
179
|
// Check if offset is out of bounds
|
|
102
180
|
if ((totalFileLines === 0 && offset !== undefined && startLine > 1) ||
|
|
103
181
|
(totalFileLines > 0 && startLine > totalFileLines)) {
|
|
104
|
-
|
|
182
|
+
const guidance = totalFileLines > 0
|
|
183
|
+
? `Use offset=${totalFileLines} to read the last line, or omit offset to read from the start.`
|
|
184
|
+
: "The file is empty; omit offset.";
|
|
185
|
+
throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total). ${guidance}`);
|
|
105
186
|
}
|
|
106
|
-
// Read content
|
|
107
|
-
let
|
|
108
|
-
if (
|
|
109
|
-
|
|
187
|
+
// Read content from the offset. PDF text is already in memory; files stream from disk.
|
|
188
|
+
let selectedContent;
|
|
189
|
+
if (isPdf) {
|
|
190
|
+
selectedContent =
|
|
191
|
+
startLine === 1
|
|
192
|
+
? pdfText
|
|
193
|
+
: pdfText
|
|
194
|
+
.split("\n")
|
|
195
|
+
.slice(startLine - 1)
|
|
196
|
+
.join("\n");
|
|
110
197
|
}
|
|
111
198
|
else {
|
|
112
|
-
cmd = `tail -n +${startLine} ${shellEscape(path)}`;
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
199
|
+
const cmd = startLine === 1 ? `cat ${shellEscape(path)}` : `tail -n +${startLine} ${shellEscape(path)}`;
|
|
200
|
+
const result = await executor.exec(cmd, { signal });
|
|
201
|
+
if (result.code !== 0) {
|
|
202
|
+
throw new Error(result.stderr || `Failed to read file: ${path}`);
|
|
203
|
+
}
|
|
204
|
+
selectedContent = result.stdout;
|
|
117
205
|
}
|
|
118
|
-
let selectedContent = result.stdout;
|
|
119
206
|
let userLimitedLines;
|
|
120
207
|
// Apply user limit if specified
|
|
121
208
|
if (limit !== undefined) {
|
package/dist/tools/registry.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
2
2
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
3
|
+
import type { ChannelJobManager } from "../agent/job-manager.js";
|
|
3
4
|
import type { MemoryCandidateStore } from "../memory/candidates.js";
|
|
4
5
|
import type { Executor } from "../sandbox.js";
|
|
5
6
|
import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
|
|
@@ -24,12 +25,17 @@ export interface ToolBuildContext {
|
|
|
24
25
|
workspacePath: string;
|
|
25
26
|
/** Main set: `toolsConfig.tools.web`; sub-agent set: the sub-agent's own webConfig. */
|
|
26
27
|
webConfig?: PipiclawWebToolsConfig;
|
|
27
|
-
/** Present only on the main path; gates session_search /
|
|
28
|
+
/** Present only on the main path; gates session_search / memory_manage / skills. */
|
|
28
29
|
toolsConfig?: PipiclawToolsConfig;
|
|
29
30
|
/** Sub-agent set passes its per-invocation bash timeout; the main set relies on the built-in default. */
|
|
30
31
|
bashDefaultTimeoutSeconds?: number;
|
|
31
32
|
/** Gates the bash tool's rtk command optimizer (`tools.rtk.enabled`). Threaded to both sets. */
|
|
32
33
|
rtkEnabled?: boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Present only on the main path when `tools.jobs.enabled` is on. Enables bash `async` and the
|
|
36
|
+
* `job` tool. The sub-agent set never supplies it, so sub-agents get neither.
|
|
37
|
+
*/
|
|
38
|
+
jobManager?: ChannelJobManager;
|
|
33
39
|
getCurrentModel?: () => Model<Api>;
|
|
34
40
|
getAvailableModels?: () => Model<Api>[];
|
|
35
41
|
resolveApiKey?: (model: Model<Api>) => Promise<string>;
|
package/dist/tools/registry.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { createBashTool } from "./bash.js";
|
|
2
2
|
import { createEditTool } from "./edit.js";
|
|
3
3
|
import { createEventManageTool } from "./event-manage.js";
|
|
4
|
-
import {
|
|
4
|
+
import { createGrepTool } from "./grep.js";
|
|
5
|
+
import { createJobTool } from "./job.js";
|
|
6
|
+
import { createMemoryManageTool } from "./memory-manage.js";
|
|
5
7
|
import { createReadTool } from "./read.js";
|
|
6
8
|
import { createSessionSearchTool } from "./session-search.js";
|
|
7
|
-
import { createSkillListTool } from "./skill-list.js";
|
|
8
9
|
import { createSkillManageTool } from "./skill-manage.js";
|
|
9
|
-
import { createSkillViewTool } from "./skill-view.js";
|
|
10
10
|
import { createTaskManageTool } from "./task-manage.js";
|
|
11
11
|
import { createWebFetchTool } from "./web-fetch.js";
|
|
12
12
|
import { createWebSearchTool } from "./web-search.js";
|
|
@@ -47,6 +47,8 @@ export const TOOL_REGISTRY = [
|
|
|
47
47
|
create: (ctx) => createBashTool(ctx.executor, {
|
|
48
48
|
...fileToolOptions(ctx),
|
|
49
49
|
rtkEnabled: ctx.rtkEnabled === true,
|
|
50
|
+
interceptorEnabled: ctx.toolsConfig?.tools.bashInterceptor.enabled === true,
|
|
51
|
+
...(ctx.jobManager ? { jobManager: ctx.jobManager } : {}),
|
|
50
52
|
...(ctx.bashDefaultTimeoutSeconds !== undefined
|
|
51
53
|
? { defaultTimeoutSeconds: ctx.bashDefaultTimeoutSeconds }
|
|
52
54
|
: {}),
|
|
@@ -58,6 +60,13 @@ export const TOOL_REGISTRY = [
|
|
|
58
60
|
availableToSubagents: true,
|
|
59
61
|
create: (ctx) => createEditTool(ctx.executor, fileToolOptions(ctx)),
|
|
60
62
|
},
|
|
63
|
+
{
|
|
64
|
+
name: "grep",
|
|
65
|
+
promptHint: "Search file contents with a regex; grouped, paginated, token-bounded — prefer over bash grep",
|
|
66
|
+
availableToSubagents: true,
|
|
67
|
+
enabledBy: (ctx) => ctx.toolsConfig?.tools.grep.enabled !== false,
|
|
68
|
+
create: (ctx) => createGrepTool(ctx.executor, fileToolOptions(ctx)),
|
|
69
|
+
},
|
|
61
70
|
{
|
|
62
71
|
name: "write",
|
|
63
72
|
promptHint: "Create or overwrite files when needed",
|
|
@@ -86,6 +95,7 @@ export const TOOL_REGISTRY = [
|
|
|
86
95
|
securityConfig: ctx.securityConfig,
|
|
87
96
|
workspaceDir: ctx.workspaceDir,
|
|
88
97
|
channelId: ctx.channelId,
|
|
98
|
+
channelDir: ctx.channelDir,
|
|
89
99
|
}),
|
|
90
100
|
},
|
|
91
101
|
{
|
|
@@ -102,33 +112,22 @@ export const TOOL_REGISTRY = [
|
|
|
102
112
|
}),
|
|
103
113
|
},
|
|
104
114
|
{
|
|
105
|
-
name: "
|
|
106
|
-
promptHint: "Save a durable fact
|
|
115
|
+
name: "memory_manage",
|
|
116
|
+
promptHint: "Save a durable fact, search stored memory on demand, or forget an entry — when the user asks",
|
|
107
117
|
availableToSubagents: false,
|
|
108
118
|
enabledBy: (ctx) => ctx.toolsConfig?.tools.memory.save.enabled !== false,
|
|
109
|
-
create: (ctx) =>
|
|
119
|
+
create: (ctx) => createMemoryManageTool({
|
|
110
120
|
channelId: ctx.channelId,
|
|
111
121
|
channelDir: ctx.channelDir,
|
|
122
|
+
workspaceDir: ctx.workspaceDir,
|
|
112
123
|
memoryCandidateStore: req(ctx.memoryCandidateStore, "memoryCandidateStore"),
|
|
124
|
+
getCurrentModel: req(ctx.getCurrentModel, "getCurrentModel"),
|
|
125
|
+
resolveApiKey: req(ctx.resolveApiKey, "resolveApiKey"),
|
|
113
126
|
}),
|
|
114
127
|
},
|
|
115
|
-
{
|
|
116
|
-
name: "skill_list",
|
|
117
|
-
promptHint: "List workspace-level procedural memory in skills/",
|
|
118
|
-
availableToSubagents: false,
|
|
119
|
-
enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
|
|
120
|
-
create: (ctx) => createSkillListTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
|
|
121
|
-
},
|
|
122
|
-
{
|
|
123
|
-
name: "skill_view",
|
|
124
|
-
promptHint: "Inspect a workspace-level skill's contents",
|
|
125
|
-
availableToSubagents: false,
|
|
126
|
-
enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
|
|
127
|
-
create: (ctx) => createSkillViewTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
|
|
128
|
-
},
|
|
129
128
|
{
|
|
130
129
|
name: "skill_manage",
|
|
131
|
-
promptHint: "
|
|
130
|
+
promptHint: "List, view, create, or maintain workspace-level procedural memory in skills/",
|
|
132
131
|
availableToSubagents: false,
|
|
133
132
|
enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
|
|
134
133
|
create: (ctx) => createSkillManageTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
|
|
@@ -161,6 +160,14 @@ export const TOOL_REGISTRY = [
|
|
|
161
160
|
channelId: ctx.channelId,
|
|
162
161
|
}),
|
|
163
162
|
},
|
|
163
|
+
{
|
|
164
|
+
name: "job",
|
|
165
|
+
promptHint: "Inspect/poll/cancel background bash jobs started with bash async:true",
|
|
166
|
+
availableToSubagents: false,
|
|
167
|
+
// Present only when a job manager was supplied (tools.jobs.enabled on the main path).
|
|
168
|
+
enabledBy: (ctx) => ctx.jobManager !== undefined,
|
|
169
|
+
create: (ctx) => createJobTool({ jobManager: req(ctx.jobManager, "jobManager") }),
|
|
170
|
+
},
|
|
164
171
|
];
|
|
165
172
|
/** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
|
|
166
173
|
export const SUBAGENT_TOOL_HINT = "Delegate a focused task to a sub-agent with its own isolated context";
|
|
@@ -43,11 +43,14 @@ export function createSessionSearchTool(options) {
|
|
|
43
43
|
model,
|
|
44
44
|
resolveApiKey: options.resolveApiKey,
|
|
45
45
|
});
|
|
46
|
+
const text = response.results.length === 0
|
|
47
|
+
? `${JSON.stringify(response)}\n\nNo matches in cold transcript storage. Try a broader query, drop roleFilter, or read the distilled memory directly (MEMORY.md / HISTORY.md in this channel).`
|
|
48
|
+
: JSON.stringify(response);
|
|
46
49
|
return {
|
|
47
50
|
content: [
|
|
48
51
|
{
|
|
49
52
|
type: "text",
|
|
50
|
-
text
|
|
53
|
+
text,
|
|
51
54
|
},
|
|
52
55
|
],
|
|
53
56
|
details: {
|
|
@@ -2,16 +2,16 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
|
|
|
2
2
|
import { Type } from "typebox";
|
|
3
3
|
declare const skillManageSchema: Type.TObject<{
|
|
4
4
|
label: Type.TString;
|
|
5
|
-
action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"patch">, Type.TLiteral<"write_file">]>;
|
|
6
|
-
name: Type.TString
|
|
5
|
+
action: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"view">, Type.TLiteral<"create">, Type.TLiteral<"patch">, Type.TLiteral<"write_file">]>;
|
|
6
|
+
name: Type.TOptional<Type.TString>;
|
|
7
7
|
content: Type.TOptional<Type.TString>;
|
|
8
8
|
filePath: Type.TOptional<Type.TString>;
|
|
9
9
|
find: Type.TOptional<Type.TString>;
|
|
10
10
|
replace: Type.TOptional<Type.TString>;
|
|
11
11
|
}>;
|
|
12
|
-
|
|
12
|
+
type SkillWriteAction = "create" | "patch" | "write_file";
|
|
13
13
|
export interface SkillManageResult {
|
|
14
|
-
action:
|
|
14
|
+
action: SkillWriteAction;
|
|
15
15
|
name: string;
|
|
16
16
|
path: string;
|
|
17
17
|
bytesWritten: number;
|
|
@@ -19,17 +19,24 @@ export interface SkillManageResult {
|
|
|
19
19
|
notice: string;
|
|
20
20
|
}
|
|
21
21
|
export interface SkillManageRequest {
|
|
22
|
-
action:
|
|
22
|
+
action: SkillWriteAction;
|
|
23
23
|
name: string;
|
|
24
24
|
content?: string;
|
|
25
25
|
filePath?: string;
|
|
26
26
|
find?: string;
|
|
27
27
|
replace?: string;
|
|
28
28
|
}
|
|
29
|
+
export interface WorkspaceSkillSummary {
|
|
30
|
+
name: string;
|
|
31
|
+
description: string;
|
|
32
|
+
path: string;
|
|
33
|
+
warning?: string;
|
|
34
|
+
}
|
|
29
35
|
export interface SkillManageToolOptions {
|
|
30
36
|
workspaceDir: string;
|
|
31
37
|
workspacePath: string;
|
|
32
38
|
}
|
|
39
|
+
export declare function listWorkspaceSkills(options: SkillManageToolOptions): Promise<WorkspaceSkillSummary[]>;
|
|
33
40
|
export declare function manageWorkspaceSkill(options: SkillManageToolOptions, request: SkillManageRequest): Promise<SkillManageResult>;
|
|
34
41
|
export declare function createSkillManageTool(options: SkillManageToolOptions): AgentTool<typeof skillManageSchema>;
|
|
35
42
|
export {};
|
|
@@ -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,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 {};
|