@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.
Files changed (54) hide show
  1. package/README.md +11 -1
  2. package/dist/agent/channel-runner.js +7 -3
  3. package/dist/agent/commands.js +2 -1
  4. package/dist/agent/job-manager.d.ts +79 -0
  5. package/dist/agent/job-manager.js +241 -0
  6. package/dist/agent/prompt-builder.js +13 -4
  7. package/dist/agent/session-events.js +5 -0
  8. package/dist/memory/recall.js +6 -0
  9. package/dist/memory/review-log.d.ts +1 -1
  10. package/dist/models/api-keys.d.ts +5 -1
  11. package/dist/models/api-keys.js +10 -4
  12. package/dist/runtime/bootstrap.js +2 -0
  13. package/dist/runtime/dingtalk.js +13 -1
  14. package/dist/runtime/task-commands.d.ts +3 -0
  15. package/dist/runtime/task-commands.js +148 -2
  16. package/dist/shared/atomic-file.js +23 -3
  17. package/dist/shared/task-events.d.ts +32 -0
  18. package/dist/shared/task-events.js +29 -0
  19. package/dist/shared/task-ledger.d.ts +26 -0
  20. package/dist/shared/task-ledger.js +38 -0
  21. package/dist/subagents/tool.js +26 -4
  22. package/dist/tools/bash.d.ts +12 -0
  23. package/dist/tools/bash.js +67 -1
  24. package/dist/tools/config.d.ts +9 -0
  25. package/dist/tools/config.js +23 -0
  26. package/dist/tools/edit.js +0 -0
  27. package/dist/tools/grep.d.ts +19 -0
  28. package/dist/tools/grep.js +262 -0
  29. package/dist/tools/index.js +5 -0
  30. package/dist/tools/job.d.ts +13 -0
  31. package/dist/tools/job.js +92 -0
  32. package/dist/tools/memory-manage.d.ts +24 -0
  33. package/dist/tools/memory-manage.js +150 -0
  34. package/dist/tools/read.js +103 -16
  35. package/dist/tools/registry.d.ts +7 -1
  36. package/dist/tools/registry.js +31 -23
  37. package/dist/tools/session-search.js +4 -1
  38. package/dist/tools/skill-manage.d.ts +12 -5
  39. package/dist/tools/skill-manage.js +113 -15
  40. package/dist/tools/task-manage.d.ts +16 -2
  41. package/dist/tools/task-manage.js +119 -22
  42. package/dist/tools/web-cache.d.ts +11 -0
  43. package/dist/tools/web-cache.js +62 -0
  44. package/dist/tools/web-fetch.d.ts +3 -0
  45. package/dist/tools/web-fetch.js +73 -5
  46. package/dist/tui/app.js +1 -1
  47. package/dist/tui/commands.js +1 -1
  48. package/package.json +1 -1
  49. package/dist/tools/memory-save.d.ts +0 -16
  50. package/dist/tools/memory-save.js +0 -42
  51. package/dist/tools/skill-list.d.ts +0 -18
  52. package/dist/tools/skill-list.js +0 -86
  53. package/dist/tools/skill-view.d.ts +0 -13
  54. package/dist/tools/skill-view.js +0 -44
@@ -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
- // Get total line count first
93
- const countResult = await executor.exec(`awk 'END { print NR }' ${shellEscape(path)}`, { signal });
94
- if (countResult.code !== 0) {
95
- throw new Error(countResult.stderr || `Failed to read file: ${path}`);
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
- throw new Error(`Offset ${offset} is beyond end of file (${totalFileLines} lines total)`);
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 with offset
107
- let cmd;
108
- if (startLine === 1) {
109
- cmd = `cat ${shellEscape(path)}`;
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
- const result = await executor.exec(cmd, { signal });
115
- if (result.code !== 0) {
116
- throw new Error(result.stderr || `Failed to read file: ${path}`);
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) {
@@ -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 / memory_save / skills. */
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>;
@@ -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 { createMemorySaveTool } from "./memory-save.js";
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: "memory_save",
106
- promptHint: "Save a durable fact to this channel's long-term memory immediately when the user asks",
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) => createMemorySaveTool({
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: "Create or maintain workspace-level procedural memory in skills/",
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 }),
@@ -150,8 +149,9 @@ export const TOOL_REGISTRY = [
150
149
  },
151
150
  {
152
151
  name: "task_manage",
153
- promptHint: "Update the task ledger: set a task's status/wake/recurrence, close a task out (archives one-shot tasks and " +
154
- "cleans up its residual events), or list active tasks. Write the task body with write/edit; this owns the frontmatter.",
152
+ promptHint: "Manage the task ledger: create standard task skeletons, set status/wake/recurrence, close tasks out " +
153
+ "(archives one-shot tasks and cleans up residual events; done requires summary and evidence), or list active " +
154
+ "tasks. Use write/edit for substantial body changes.",
155
155
  availableToSubagents: false,
156
156
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
157
157
  create: (ctx) => createTaskManageTool({
@@ -161,6 +161,14 @@ export const TOOL_REGISTRY = [
161
161
  channelId: ctx.channelId,
162
162
  }),
163
163
  },
164
+ {
165
+ name: "job",
166
+ promptHint: "Inspect/poll/cancel background bash jobs started with bash async:true",
167
+ availableToSubagents: false,
168
+ // Present only when a job manager was supplied (tools.jobs.enabled on the main path).
169
+ enabledBy: (ctx) => ctx.jobManager !== undefined,
170
+ create: (ctx) => createJobTool({ jobManager: req(ctx.jobManager, "jobManager") }),
171
+ },
164
172
  ];
165
173
  /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
166
174
  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: JSON.stringify(response),
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
- export type SkillManageAction = "create" | "patch" | "write_file";
12
+ type SkillWriteAction = "create" | "patch" | "write_file";
13
13
  export interface SkillManageResult {
14
- action: SkillManageAction;
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: SkillManageAction;
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 management change (shown to user)" }),
9
- action: Type.Union([Type.Literal("create"), Type.Literal("patch"), Type.Literal("write_file")], {
10
- description: 'The skill management action to perform: "create", "patch", or "write_file".',
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: "Optional supporting file path for patch/write_file. Defaults to SKILL.md for patch. Supporting files must be under references/, templates/, scripts/, or assets/.",
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 parseAction(action) {
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: "Create or update workspace-level Pipiclaw skills as procedural memory. Supports create, patch, and write_file only; no channel-scoped skills.",
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: parseAction(args.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
  };
@@ -2,13 +2,20 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  declare const taskManageSchema: Type.TObject<{
4
4
  label: Type.TString;
5
- action: Type.TUnion<[Type.TLiteral<"set">, Type.TLiteral<"done">, Type.TLiteral<"list">]>;
5
+ action: Type.TUnion<[Type.TLiteral<"create">, Type.TLiteral<"set">, Type.TLiteral<"done">, Type.TLiteral<"list">]>;
6
6
  id: Type.TOptional<Type.TString>;
7
+ title: Type.TOptional<Type.TString>;
8
+ goal: Type.TOptional<Type.TString>;
9
+ dod: Type.TOptional<Type.TString>;
10
+ manual: Type.TOptional<Type.TString>;
7
11
  status: Type.TOptional<Type.TUnion<Type.TLiteral<"open" | "blocked" | "in-progress" | "awaiting-user">[]>>;
8
12
  wake: Type.TOptional<Type.TString>;
9
13
  recurrence: Type.TOptional<Type.TString>;
14
+ summary: Type.TOptional<Type.TString>;
15
+ evidence: Type.TOptional<Type.TString>;
16
+ residualRisk: Type.TOptional<Type.TString>;
10
17
  }>;
11
- export type TaskManageAction = "set" | "done" | "list";
18
+ export type TaskManageAction = "create" | "set" | "done" | "list";
12
19
  export interface TaskManageResult {
13
20
  action: TaskManageAction;
14
21
  id?: string;
@@ -28,9 +35,16 @@ export interface TaskManageResult {
28
35
  export interface TaskManageRequest {
29
36
  action: TaskManageAction;
30
37
  id?: string;
38
+ title?: string;
39
+ goal?: string;
40
+ dod?: string;
41
+ manual?: string;
31
42
  status?: string;
32
43
  wake?: string;
33
44
  recurrence?: string;
45
+ summary?: string;
46
+ evidence?: string;
47
+ residualRisk?: string;
34
48
  }
35
49
  export interface TaskManageToolOptions {
36
50
  workspaceDir: string;