@oyasmi/pipiclaw 0.6.10 → 0.7.0-beta.1

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 (55) hide show
  1. package/README.md +1 -1
  2. package/dist/agent/channel-runner.d.ts +11 -1
  3. package/dist/agent/channel-runner.js +39 -3
  4. package/dist/agent/commands.d.ts +1 -1
  5. package/dist/agent/commands.js +4 -0
  6. package/dist/agent/prompt-builder.d.ts +17 -0
  7. package/dist/agent/prompt-builder.js +42 -23
  8. package/dist/agent/types.d.ts +7 -0
  9. package/dist/memory/bootstrap.js +35 -1
  10. package/dist/memory/candidates.js +21 -3
  11. package/dist/memory/consolidation.d.ts +6 -1
  12. package/dist/memory/consolidation.js +99 -33
  13. package/dist/memory/files.d.ts +40 -0
  14. package/dist/memory/files.js +0 -0
  15. package/dist/memory/maintenance-jobs.js +9 -4
  16. package/dist/memory/post-turn-review.js +3 -2
  17. package/dist/memory/promotion-signals.js +0 -1
  18. package/dist/memory/recall.js +10 -2
  19. package/dist/memory/session.js +43 -13
  20. package/dist/memory/transcript.d.ts +9 -0
  21. package/dist/memory/transcript.js +30 -0
  22. package/dist/runtime/bootstrap.js +140 -15
  23. package/dist/runtime/delivery.js +17 -0
  24. package/dist/runtime/dingtalk.d.ts +1 -0
  25. package/dist/runtime/dingtalk.js +15 -4
  26. package/dist/sandbox.d.ts +8 -0
  27. package/dist/sandbox.js +21 -17
  28. package/dist/settings.d.ts +4 -0
  29. package/dist/settings.js +2 -0
  30. package/dist/subagents/tool.d.ts +2 -2
  31. package/dist/subagents/tool.js +24 -56
  32. package/dist/tools/bash.d.ts +8 -1
  33. package/dist/tools/bash.js +46 -21
  34. package/dist/tools/config.d.ts +3 -0
  35. package/dist/tools/config.js +9 -0
  36. package/dist/tools/edit.d.ts +1 -0
  37. package/dist/tools/edit.js +18 -11
  38. package/dist/tools/index.js +18 -53
  39. package/dist/tools/memory-save.d.ts +17 -0
  40. package/dist/tools/memory-save.js +43 -0
  41. package/dist/tools/read.d.ts +2 -2
  42. package/dist/tools/read.js +2 -2
  43. package/dist/tools/registry.d.ts +63 -0
  44. package/dist/tools/registry.js +153 -0
  45. package/dist/tools/session-search.d.ts +2 -2
  46. package/dist/tools/session-search.js +9 -5
  47. package/dist/tools/skill-list.js +1 -1
  48. package/dist/tools/skill-manage.d.ts +1 -1
  49. package/dist/tools/skill-manage.js +3 -1
  50. package/dist/tools/skill-view.js +12 -11
  51. package/dist/tools/web-search.d.ts +1 -1
  52. package/dist/tools/web-search.js +1 -1
  53. package/package.json +5 -5
  54. package/dist/tools/attach.d.ts +0 -20
  55. package/dist/tools/attach.js +0 -69
@@ -1,23 +1,34 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { createWriteStream } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join } from "node:path";
5
2
  import { Type } from "typebox";
6
3
  import { guardCommand } from "../security/command-guard.js";
7
4
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
8
5
  import { logSecurityEvent } from "../security/logger.js";
6
+ import { shellEscapePath } from "../shared/shell-escape.js";
9
7
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateTail } from "./truncate.js";
10
8
  /**
11
- * Generate a unique temp file path for bash output
9
+ * Default wall-clock timeout for bash commands when the caller supplies neither a
10
+ * per-call `timeout` nor a tool-level default. Without this, a hung command (a stray
11
+ * dev server, an interactive prompt) would block the channel's run queue until `/stop`.
12
+ * Callers that legitimately need longer must pass an explicit `timeout`.
12
13
  */
13
- function getTempFilePath() {
14
+ export const DEFAULT_BASH_TIMEOUT_SECONDS = 300;
15
+ /**
16
+ * Generate a unique spill file path for full bash output. This lives inside the
17
+ * executor's filesystem (the sandbox), not the host, so the path we report back is
18
+ * reachable by the same `read`/`bash` tools the model uses to open it. `/tmp` exists
19
+ * and is writable in both the host and Docker (Alpine) sandboxes.
20
+ */
21
+ function getSpillFilePath() {
14
22
  const id = randomBytes(8).toString("hex");
15
- return join(tmpdir(), `pipiclaw-bash-${id}.log`);
23
+ return `/tmp/pipiclaw-bash-${id}.log`;
16
24
  }
17
25
  const bashSchema = Type.Object({
18
26
  label: Type.String({ description: "Brief description of what this command does (shown to user)" }),
19
27
  command: Type.String({ description: "Bash command to execute" }),
20
- timeout: Type.Optional(Type.Number({ description: "Timeout in seconds (optional, no default timeout)" })),
28
+ timeout: Type.Optional(Type.Integer({
29
+ minimum: 1,
30
+ description: `Timeout in seconds. Defaults to ${DEFAULT_BASH_TIMEOUT_SECONDS}s; pass a larger value for long-running commands.`,
31
+ })),
21
32
  });
22
33
  function formatCommandBlockMessage(command, category, reason, matchedText) {
23
34
  const lines = [`Command blocked${category ? ` [${category}]` : ""}`];
@@ -42,7 +53,7 @@ export function createBashTool(executor, options = {}) {
42
53
  return {
43
54
  name: "bash",
44
55
  label: "bash",
45
- description: `Execute a bash command in the current working directory. Returns stdout and stderr. Output is truncated to last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, full output is saved to a temp file. Optionally provide a timeout in seconds.`,
56
+ description: `Execute a bash command in the current working directory. Returns stdout, stderr, and the exit code (a non-zero exit code is reported in the output, not raised as an error). Output is truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). If truncated, the full output is saved to a temp file whose path is included. Commands time out after ${DEFAULT_BASH_TIMEOUT_SECONDS}s unless you pass a larger \`timeout\`.`,
46
57
  parameters: bashSchema,
47
58
  execute: async (_toolCallId, { command, timeout }, signal) => {
48
59
  if (securityConfig.enabled && securityConfig.commandGuard.enabled) {
@@ -61,10 +72,7 @@ export function createBashTool(executor, options = {}) {
61
72
  throw new Error(formatCommandBlockMessage(command, guardResult.category, guardResult.reason, guardResult.matchedText));
62
73
  }
63
74
  }
64
- // Track output for potential temp file writing
65
- let tempFilePath;
66
- let tempFileStream;
67
- const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds;
75
+ const effectiveTimeout = timeout ?? options.defaultTimeoutSeconds ?? DEFAULT_BASH_TIMEOUT_SECONDS;
68
76
  const result = await executor.exec(command, { timeout: effectiveTimeout, signal });
69
77
  let output = "";
70
78
  if (result.stdout)
@@ -75,12 +83,24 @@ export function createBashTool(executor, options = {}) {
75
83
  output += result.stderr;
76
84
  }
77
85
  const totalBytes = Buffer.byteLength(output, "utf-8");
78
- // Write to temp file if output exceeds limit
86
+ // Spill the full output to a temp file (inside the executor's filesystem, so the
87
+ // reported path is reachable by the model) when it exceeds the inline limit.
88
+ // Best-effort: if the write fails, we simply omit the path hint from the notice.
89
+ let tempFilePath;
79
90
  if (totalBytes > DEFAULT_MAX_BYTES) {
80
- tempFilePath = getTempFilePath();
81
- tempFileStream = createWriteStream(tempFilePath);
82
- tempFileStream.write(output);
83
- tempFileStream.end();
91
+ const candidatePath = getSpillFilePath();
92
+ try {
93
+ const spillResult = await executor.exec(`cat > ${shellEscapePath(candidatePath)}`, {
94
+ signal,
95
+ stdin: output,
96
+ });
97
+ if (spillResult.code === 0) {
98
+ tempFilePath = candidatePath;
99
+ }
100
+ }
101
+ catch {
102
+ // Ignore spill failures; the truncated output is still returned.
103
+ }
84
104
  }
85
105
  // Apply tail truncation
86
106
  const truncation = truncateTail(output);
@@ -95,20 +115,25 @@ export function createBashTool(executor, options = {}) {
95
115
  // Build actionable notice
96
116
  const startLine = truncation.totalLines - truncation.outputLines + 1;
97
117
  const endLine = truncation.totalLines;
118
+ const fullOutputHint = tempFilePath ? ` Full output: ${tempFilePath}` : "";
98
119
  if (truncation.lastLinePartial) {
99
120
  // Edge case: last line alone > 50KB
100
121
  const lastLineSize = formatSize(Buffer.byteLength(output.split("\n").pop() || "", "utf-8"));
101
- outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${tempFilePath}]`;
122
+ outputText += `\n\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}).${fullOutputHint}]`;
102
123
  }
103
124
  else if (truncation.truncatedBy === "lines") {
104
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${tempFilePath}]`;
125
+ outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}.${fullOutputHint}]`;
105
126
  }
106
127
  else {
107
- outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Full output: ${tempFilePath}]`;
128
+ outputText += `\n\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(DEFAULT_MAX_BYTES)} limit).${fullOutputHint}]`;
108
129
  }
109
130
  }
131
+ // A non-zero exit code is a normal result, not a tool failure: commands like
132
+ // `grep` (no match), `diff` (differences), and `test` use exit codes as data.
133
+ // Report the code inline so the model can react without treating it as an error.
110
134
  if (result.code !== 0) {
111
- throw new Error(`${outputText}\n\nCommand exited with code ${result.code}`.trim());
135
+ outputText += `\n\nExit code: ${result.code}`;
136
+ details = { ...details, exitCode: result.code };
112
137
  }
113
138
  return { content: [{ type: "text", text: outputText }], details };
114
139
  },
@@ -29,6 +29,9 @@ export interface PipiclawToolsConfig {
29
29
  sessionSearch: {
30
30
  enabled: boolean;
31
31
  };
32
+ save: {
33
+ enabled: boolean;
34
+ };
32
35
  };
33
36
  skills: {
34
37
  manage: {
@@ -29,6 +29,9 @@ export const DEFAULT_TOOLS_CONFIG = {
29
29
  sessionSearch: {
30
30
  enabled: true,
31
31
  },
32
+ save: {
33
+ enabled: true,
34
+ },
32
35
  },
33
36
  skills: {
34
37
  manage: {
@@ -80,6 +83,7 @@ function mergeToolsConfig(source, configPath, diagnostics) {
80
83
  const web = isRecord(tools.web) ? tools.web : {};
81
84
  const memory = isRecord(tools.memory) ? tools.memory : {};
82
85
  const sessionSearch = isRecord(memory.sessionSearch) ? memory.sessionSearch : {};
86
+ const memorySave = isRecord(memory.save) ? memory.save : {};
83
87
  const skills = isRecord(tools.skills) ? tools.skills : {};
84
88
  const manage = isRecord(skills.manage) ? skills.manage : {};
85
89
  const search = isRecord(web.search) ? web.search : {};
@@ -152,6 +156,11 @@ function mergeToolsConfig(source, configPath, diagnostics) {
152
156
  ? sessionSearch.enabled
153
157
  : DEFAULT_TOOLS_CONFIG.tools.memory.sessionSearch.enabled,
154
158
  },
159
+ save: {
160
+ enabled: typeof memorySave.enabled === "boolean"
161
+ ? memorySave.enabled
162
+ : DEFAULT_TOOLS_CONFIG.tools.memory.save.enabled,
163
+ },
155
164
  },
156
165
  skills: {
157
166
  manage: {
@@ -7,6 +7,7 @@ declare const editSchema: Type.TObject<{
7
7
  path: Type.TString;
8
8
  oldText: Type.TString;
9
9
  newText: Type.TString;
10
+ replaceAll: Type.TOptional<Type.TBoolean>;
10
11
  }>;
11
12
  export interface EditToolOptions {
12
13
  securityConfig?: SecurityConfig;
@@ -82,6 +82,9 @@ const editSchema = Type.Object({
82
82
  path: Type.String({ description: "Path to the file to edit (relative or absolute)" }),
83
83
  oldText: Type.String({ description: "Exact text to find and replace (must match exactly)" }),
84
84
  newText: Type.String({ description: "New text to replace the old text with" }),
85
+ replaceAll: Type.Optional(Type.Boolean({
86
+ description: "Replace every occurrence instead of requiring a unique match. Defaults to false (the match must be unique).",
87
+ })),
85
88
  });
86
89
  function formatPathBlockMessage(resolvedPath, category, reason) {
87
90
  const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
@@ -105,7 +108,7 @@ export function createEditTool(executor, options = {}) {
105
108
  label: "edit",
106
109
  description: "Edit a file by replacing exact text. The oldText must match exactly (including whitespace). Use this for precise, surgical edits.",
107
110
  parameters: editSchema,
108
- execute: async (_toolCallId, { path, oldText, newText }, signal) => {
111
+ execute: async (_toolCallId, { path, oldText, newText, replaceAll, }, signal) => {
109
112
  if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
110
113
  const readGuard = guardPath(path, "read", { ...securityContext, config: securityConfig.pathGuard });
111
114
  if (!readGuard.allowed) {
@@ -134,12 +137,18 @@ export function createEditTool(executor, options = {}) {
134
137
  }
135
138
  // Count occurrences
136
139
  const occurrences = content.split(oldText).length - 1;
137
- if (occurrences > 1) {
138
- throw new Error(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique. Please provide more context to make it unique.`);
140
+ if (occurrences > 1 && !replaceAll) {
141
+ throw new Error(`Found ${occurrences} occurrences of the text in ${path}. The text must be unique, or pass replaceAll: true to replace all of them. Please provide more context to make it unique.`);
139
142
  }
140
143
  // Perform replacement
141
- const index = content.indexOf(oldText);
142
- const newContent = content.substring(0, index) + newText + content.substring(index + oldText.length);
144
+ let newContent;
145
+ if (replaceAll) {
146
+ newContent = content.split(oldText).join(newText);
147
+ }
148
+ else {
149
+ const index = content.indexOf(oldText);
150
+ newContent = content.substring(0, index) + newText + content.substring(index + oldText.length);
151
+ }
143
152
  if (content === newContent) {
144
153
  throw new Error(`No changes made to ${path}. The replacement produced identical content. This might indicate an issue with special characters or the text not existing as expected.`);
145
154
  }
@@ -150,13 +159,11 @@ export function createEditTool(executor, options = {}) {
150
159
  channelId: options.channelId,
151
160
  toolName: "edit",
152
161
  });
162
+ const replacementSummary = replaceAll
163
+ ? `Replaced ${occurrences} occurrence${occurrences === 1 ? "" : "s"} in ${path}.`
164
+ : `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`;
153
165
  return {
154
- content: [
155
- {
156
- type: "text",
157
- text: `Successfully replaced text in ${path}. Changed ${oldText.length} characters to ${newText.length} characters.`,
158
- },
159
- ],
166
+ content: [{ type: "text", text: replacementSummary }],
160
167
  details: {
161
168
  diff: generateDiffString(content, newContent),
162
169
  patch: Diff.createPatch(path, content, newContent),
@@ -5,12 +5,7 @@ import { createBashTool } from "./bash.js";
5
5
  import { loadToolsConfig } from "./config.js";
6
6
  import { createEditTool } from "./edit.js";
7
7
  import { createReadTool } from "./read.js";
8
- import { createSessionSearchTool } from "./session-search.js";
9
- import { createSkillListTool } from "./skill-list.js";
10
- import { createSkillManageTool } from "./skill-manage.js";
11
- import { createSkillViewTool } from "./skill-view.js";
12
- import { createWebFetchTool } from "./web-fetch.js";
13
- import { createWebSearchTool } from "./web-search.js";
8
+ import { buildToolSet } from "./registry.js";
14
9
  import { createWriteTool } from "./write.js";
15
10
  export function createPipiclawBaseTools(executor, options = {}) {
16
11
  const hasSecurityOptions = options.securityConfig || options.securityContext || options.channelId;
@@ -36,58 +31,28 @@ export function createPipiclawTools(options) {
36
31
  workspacePath: options.workspacePath,
37
32
  cwd: process.cwd(),
38
33
  };
39
- const baseTools = createPipiclawBaseTools(options.executor, {
34
+ // The leaf tools (files, web, memory, skills) come from the single declarative
35
+ // registry so this set, the sub-agent set, and the prompt hints share one source.
36
+ // The `subagent` tool is appended separately: it is never available to sub-agents
37
+ // and keeping it out of the registry avoids a registry ↔ subagents/tool import cycle.
38
+ const leafTools = buildToolSet({
39
+ executor: options.executor,
40
40
  securityConfig,
41
41
  securityContext,
42
42
  channelId: options.channelId,
43
+ channelDir: options.channelDir,
44
+ workspaceDir: options.workspaceDir,
45
+ workspacePath: options.workspacePath,
46
+ webConfig: toolsConfig.tools.web,
47
+ toolsConfig,
48
+ getCurrentModel: options.getCurrentModel,
49
+ getAvailableModels: options.getAvailableModels,
50
+ resolveApiKey: options.resolveApiKey,
51
+ getSessionSearchSettings: options.getSessionSearchSettings,
52
+ memoryCandidateStore: options.memoryCandidateStore,
43
53
  });
44
- const webTools = toolsConfig.tools.web.enable === false
45
- ? []
46
- : [
47
- createWebSearchTool({
48
- webConfig: toolsConfig.tools.web,
49
- securityConfig,
50
- workspaceDir: options.workspaceDir,
51
- channelId: options.channelId,
52
- }),
53
- createWebFetchTool({
54
- webConfig: toolsConfig.tools.web,
55
- securityConfig,
56
- workspaceDir: options.workspaceDir,
57
- channelId: options.channelId,
58
- }),
59
- ];
60
- const memoryTools = toolsConfig.tools.memory.sessionSearch.enabled === false
61
- ? []
62
- : [
63
- createSessionSearchTool({
64
- channelDir: options.channelDir,
65
- getCurrentModel: options.getCurrentModel,
66
- resolveApiKey: options.resolveApiKey,
67
- getSessionSearchSettings: options.getSessionSearchSettings,
68
- }),
69
- ];
70
- const skillTools = toolsConfig.tools.skills.manage.enabled === false
71
- ? []
72
- : [
73
- createSkillListTool({
74
- workspaceDir: options.workspaceDir,
75
- workspacePath: options.workspacePath,
76
- }),
77
- createSkillViewTool({
78
- workspaceDir: options.workspaceDir,
79
- workspacePath: options.workspacePath,
80
- }),
81
- createSkillManageTool({
82
- workspaceDir: options.workspaceDir,
83
- workspacePath: options.workspacePath,
84
- }),
85
- ];
86
54
  return [
87
- ...baseTools,
88
- ...webTools,
89
- ...memoryTools,
90
- ...skillTools,
55
+ ...leafTools,
91
56
  createSubAgentTool({
92
57
  executor: options.executor,
93
58
  getCurrentModel: options.getCurrentModel,
@@ -0,0 +1,17 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ import type { MemoryCandidateStore } from "../memory/candidates.js";
4
+ import { type ChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
5
+ declare const memorySaveSchema: Type.TObject<{
6
+ label: Type.TString;
7
+ content: Type.TString;
8
+ kind: Type.TOptional<Type.TUnion<[Type.TLiteral<"preference">, Type.TLiteral<"fact">, Type.TLiteral<"decision">, Type.TLiteral<"constraint">, Type.TLiteral<"open-loop">]>>;
9
+ }>;
10
+ export interface MemorySaveToolOptions {
11
+ channelId: string;
12
+ channelDir: string;
13
+ memoryCandidateStore: MemoryCandidateStore;
14
+ channelMemoryQueue?: ChannelMemoryQueue;
15
+ }
16
+ export declare function createMemorySaveTool(options: MemorySaveToolOptions): AgentTool<typeof memorySaveSchema>;
17
+ export {};
@@ -0,0 +1,43 @@
1
+ import { Type } from "typebox";
2
+ import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
3
+ import { applyChannelMemoryOps, getChannelMemoryPath } from "../memory/files.js";
4
+ const memorySaveSchema = Type.Object({
5
+ label: Type.String({ description: "Brief description of what you're saving and why (shown to user)" }),
6
+ content: Type.String({
7
+ description: "The durable fact to remember, as a single self-contained, keyword-rich sentence. Write it so future keyword search can find it.",
8
+ }),
9
+ kind: Type.Optional(Type.Union([
10
+ Type.Literal("preference"),
11
+ Type.Literal("fact"),
12
+ Type.Literal("decision"),
13
+ Type.Literal("constraint"),
14
+ Type.Literal("open-loop"),
15
+ ], { description: "What kind of durable memory this is." })),
16
+ });
17
+ export function createMemorySaveTool(options) {
18
+ const queue = options.channelMemoryQueue ?? getDefaultChannelMemoryQueue();
19
+ return {
20
+ name: "memory_save",
21
+ label: "memory_save",
22
+ description: "Save a durable fact to this channel's long-term MEMORY.md immediately. Use when the user explicitly asks you to remember something (a preference, decision, constraint, or long-running commitment), so it survives restarts and future sessions. Do not use for transient task state — that is captured automatically.",
23
+ parameters: memorySaveSchema,
24
+ execute: async (_toolCallId, { content, kind }) => {
25
+ const trimmed = content.trim();
26
+ if (!trimmed) {
27
+ return {
28
+ content: [{ type: "text", text: "No content provided; nothing was saved." }],
29
+ details: { kind: "memory_save", saved: false },
30
+ };
31
+ }
32
+ // Serialize through the shared channel memory queue so this never races with
33
+ // background consolidation/maintenance on the same channel's files.
34
+ const result = await queue.run(options.channelId, () => applyChannelMemoryOps(options.channelDir, [{ op: "add", content: trimmed }]));
35
+ // Make the new memory recallable within this same turn.
36
+ options.memoryCandidateStore.invalidate(getChannelMemoryPath(options.channelDir));
37
+ return {
38
+ content: [{ type: "text", text: `Saved to channel memory${kind ? ` (${kind})` : ""}.` }],
39
+ details: { kind: "memory_save", saved: result.added > 0 },
40
+ };
41
+ },
42
+ };
43
+ }
@@ -5,8 +5,8 @@ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.j
5
5
  declare const readSchema: Type.TObject<{
6
6
  label: Type.TString;
7
7
  path: Type.TString;
8
- offset: Type.TOptional<Type.TNumber>;
9
- limit: Type.TOptional<Type.TNumber>;
8
+ offset: Type.TOptional<Type.TInteger>;
9
+ limit: Type.TOptional<Type.TInteger>;
10
10
  }>;
11
11
  export interface ReadToolOptions {
12
12
  securityConfig?: SecurityConfig;
@@ -25,8 +25,8 @@ function isImageFile(filePath) {
25
25
  const readSchema = Type.Object({
26
26
  label: Type.String({ description: "Brief description of what you're reading and why (shown to user)" }),
27
27
  path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
28
- offset: Type.Optional(Type.Number({ description: "Line number to start reading from (1-indexed)" })),
29
- limit: Type.Optional(Type.Number({ description: "Maximum number of lines to read" })),
28
+ offset: Type.Optional(Type.Integer({ minimum: 1, description: "Line number to start reading from (1-indexed)" })),
29
+ limit: Type.Optional(Type.Integer({ minimum: 1, description: "Maximum number of lines to read" })),
30
30
  });
31
31
  function countTextLines(content) {
32
32
  if (content.length === 0) {
@@ -0,0 +1,63 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import type { Api, Model } from "@earendil-works/pi-ai";
3
+ import type { MemoryCandidateStore } from "../memory/candidates.js";
4
+ import type { Executor } from "../sandbox.js";
5
+ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
+ import type { PipiclawSessionSearchSettings } from "../settings.js";
7
+ import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
8
+ /**
9
+ * Unified build context passed to every tool's `create` closure. It carries the union
10
+ * of everything any registered tool might need; each closure reads only its own fields.
11
+ *
12
+ * Fields used exclusively by main-agent-only tools (models, session-search settings,
13
+ * memory store) are optional: the sub-agent tool set never builds those tools, so it
14
+ * does not supply them. Closures assert presence via `req()` to turn a missing
15
+ * dependency into a loud error instead of a silent undefined.
16
+ */
17
+ export interface ToolBuildContext {
18
+ executor: Executor;
19
+ securityConfig: SecurityConfig;
20
+ securityContext: SecurityRuntimeContext;
21
+ channelId: string;
22
+ channelDir: string;
23
+ workspaceDir: string;
24
+ workspacePath: string;
25
+ /** Main set: `toolsConfig.tools.web`; sub-agent set: the sub-agent's own webConfig. */
26
+ webConfig?: PipiclawWebToolsConfig;
27
+ /** Present only on the main path; gates session_search / memory_save / skills. */
28
+ toolsConfig?: PipiclawToolsConfig;
29
+ /** Sub-agent set passes its per-invocation bash timeout; the main set relies on the built-in default. */
30
+ bashDefaultTimeoutSeconds?: number;
31
+ getCurrentModel?: () => Model<Api>;
32
+ getAvailableModels?: () => Model<Api>[];
33
+ resolveApiKey?: (model: Model<Api>) => Promise<string>;
34
+ getSessionSearchSettings?: () => PipiclawSessionSearchSettings;
35
+ memoryCandidateStore?: MemoryCandidateStore;
36
+ }
37
+ export interface ToolRegistration {
38
+ name: string;
39
+ /** One-line hint rendered in the system prompt's `## Tools` section. */
40
+ promptHint: string;
41
+ /** Whether this tool is included in a sub-agent's tool set. */
42
+ availableToSubagents: boolean;
43
+ /** Config gate; when omitted the tool is always enabled. */
44
+ enabledBy?: (ctx: ToolBuildContext) => boolean;
45
+ create: (ctx: ToolBuildContext) => AgentTool<any>;
46
+ }
47
+ /**
48
+ * Single source of truth for the agent's leaf tools. The `subagent` tool is intentionally
49
+ * NOT here: it is never available to sub-agents, needs runtime context the registry does
50
+ * not model, and keeping it out avoids a `registry` ↔ `subagents/tool` import cycle (the
51
+ * sub-agent tool set is built by importing `buildToolSet` from this module).
52
+ */
53
+ export declare const TOOL_REGISTRY: ToolRegistration[];
54
+ /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
55
+ export declare const SUBAGENT_TOOL_HINT = "Delegate a focused task to a sub-agent with its own isolated context";
56
+ /** Single source of truth for prompt hints, keyed by tool name (leaf tools + subagent). */
57
+ export declare const TOOL_PROMPT_HINTS: Record<string, string>;
58
+ export interface BuildToolSetOptions {
59
+ /** When true, include only tools flagged `availableToSubagents`. */
60
+ forSubagent?: boolean;
61
+ }
62
+ /** Build a tool set from the registry, honoring sub-agent availability and config gates. */
63
+ export declare function buildToolSet(ctx: ToolBuildContext, options?: BuildToolSetOptions): AgentTool<any>[];
@@ -0,0 +1,153 @@
1
+ import { createBashTool } from "./bash.js";
2
+ import { createEditTool } from "./edit.js";
3
+ import { createMemorySaveTool } from "./memory-save.js";
4
+ import { createReadTool } from "./read.js";
5
+ import { createSessionSearchTool } from "./session-search.js";
6
+ import { createSkillListTool } from "./skill-list.js";
7
+ import { createSkillManageTool } from "./skill-manage.js";
8
+ import { createSkillViewTool } from "./skill-view.js";
9
+ import { createWebFetchTool } from "./web-fetch.js";
10
+ import { createWebSearchTool } from "./web-search.js";
11
+ import { createWriteTool } from "./write.js";
12
+ function req(value, name) {
13
+ if (value === undefined) {
14
+ throw new Error(`Tool build context is missing required dependency "${name}"`);
15
+ }
16
+ return value;
17
+ }
18
+ function fileToolOptions(ctx) {
19
+ return {
20
+ securityConfig: ctx.securityConfig,
21
+ securityContext: ctx.securityContext,
22
+ channelId: ctx.channelId,
23
+ };
24
+ }
25
+ function webEnabled(ctx) {
26
+ return ctx.webConfig != null && ctx.webConfig.enable !== false;
27
+ }
28
+ /**
29
+ * Single source of truth for the agent's leaf tools. The `subagent` tool is intentionally
30
+ * NOT here: it is never available to sub-agents, needs runtime context the registry does
31
+ * not model, and keeping it out avoids a `registry` ↔ `subagents/tool` import cycle (the
32
+ * sub-agent tool set is built by importing `buildToolSet` from this module).
33
+ */
34
+ export const TOOL_REGISTRY = [
35
+ {
36
+ name: "read",
37
+ promptHint: "Read files",
38
+ availableToSubagents: true,
39
+ create: (ctx) => createReadTool(ctx.executor, fileToolOptions(ctx)),
40
+ },
41
+ {
42
+ name: "bash",
43
+ promptHint: "Run shell commands and external programs",
44
+ availableToSubagents: true,
45
+ create: (ctx) => createBashTool(ctx.executor, {
46
+ ...fileToolOptions(ctx),
47
+ ...(ctx.bashDefaultTimeoutSeconds !== undefined
48
+ ? { defaultTimeoutSeconds: ctx.bashDefaultTimeoutSeconds }
49
+ : {}),
50
+ }),
51
+ },
52
+ {
53
+ name: "edit",
54
+ promptHint: "Surgical file edits",
55
+ availableToSubagents: true,
56
+ create: (ctx) => createEditTool(ctx.executor, fileToolOptions(ctx)),
57
+ },
58
+ {
59
+ name: "write",
60
+ promptHint: "Create or overwrite files when needed",
61
+ availableToSubagents: true,
62
+ create: (ctx) => createWriteTool(ctx.executor, fileToolOptions(ctx)),
63
+ },
64
+ {
65
+ name: "web_search",
66
+ promptHint: "Search the public web and return titles, URLs, and snippets",
67
+ availableToSubagents: true,
68
+ enabledBy: webEnabled,
69
+ create: (ctx) => createWebSearchTool({
70
+ webConfig: req(ctx.webConfig, "webConfig"),
71
+ securityConfig: ctx.securityConfig,
72
+ workspaceDir: ctx.workspaceDir,
73
+ channelId: ctx.channelId,
74
+ }),
75
+ },
76
+ {
77
+ name: "web_fetch",
78
+ promptHint: "Fetch a public URL and extract readable content",
79
+ availableToSubagents: true,
80
+ enabledBy: webEnabled,
81
+ create: (ctx) => createWebFetchTool({
82
+ webConfig: req(ctx.webConfig, "webConfig"),
83
+ securityConfig: ctx.securityConfig,
84
+ workspaceDir: ctx.workspaceDir,
85
+ channelId: ctx.channelId,
86
+ }),
87
+ },
88
+ {
89
+ name: "session_search",
90
+ promptHint: "Search current-channel cold transcript storage for older conversation details",
91
+ availableToSubagents: false,
92
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.memory.sessionSearch.enabled !== false,
93
+ create: (ctx) => createSessionSearchTool({
94
+ channelDir: ctx.channelDir,
95
+ getCurrentModel: req(ctx.getCurrentModel, "getCurrentModel"),
96
+ resolveApiKey: req(ctx.resolveApiKey, "resolveApiKey"),
97
+ getSessionSearchSettings: req(ctx.getSessionSearchSettings, "getSessionSearchSettings"),
98
+ }),
99
+ },
100
+ {
101
+ name: "memory_save",
102
+ promptHint: "Save a durable fact to this channel's long-term memory immediately when the user asks",
103
+ availableToSubagents: false,
104
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.memory.save.enabled !== false,
105
+ create: (ctx) => createMemorySaveTool({
106
+ channelId: ctx.channelId,
107
+ channelDir: ctx.channelDir,
108
+ memoryCandidateStore: req(ctx.memoryCandidateStore, "memoryCandidateStore"),
109
+ }),
110
+ },
111
+ {
112
+ name: "skill_list",
113
+ promptHint: "List workspace-level procedural memory in skills/",
114
+ availableToSubagents: false,
115
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
116
+ create: (ctx) => createSkillListTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
117
+ },
118
+ {
119
+ name: "skill_view",
120
+ promptHint: "Inspect a workspace-level skill's contents",
121
+ availableToSubagents: false,
122
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
123
+ create: (ctx) => createSkillViewTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
124
+ },
125
+ {
126
+ name: "skill_manage",
127
+ promptHint: "Create or maintain workspace-level procedural memory in skills/",
128
+ availableToSubagents: false,
129
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.skills.manage.enabled !== false,
130
+ create: (ctx) => createSkillManageTool({ workspaceDir: ctx.workspaceDir, workspacePath: ctx.workspacePath }),
131
+ },
132
+ ];
133
+ /** Prompt hint for the `subagent` tool, which is registered outside TOOL_REGISTRY. */
134
+ export const SUBAGENT_TOOL_HINT = "Delegate a focused task to a sub-agent with its own isolated context";
135
+ /** Single source of truth for prompt hints, keyed by tool name (leaf tools + subagent). */
136
+ export const TOOL_PROMPT_HINTS = {
137
+ ...Object.fromEntries(TOOL_REGISTRY.map((registration) => [registration.name, registration.promptHint])),
138
+ subagent: SUBAGENT_TOOL_HINT,
139
+ };
140
+ /** Build a tool set from the registry, honoring sub-agent availability and config gates. */
141
+ export function buildToolSet(ctx, options = {}) {
142
+ const result = [];
143
+ for (const registration of TOOL_REGISTRY) {
144
+ if (options.forSubagent && !registration.availableToSubagents) {
145
+ continue;
146
+ }
147
+ if (registration.enabledBy && !registration.enabledBy(ctx)) {
148
+ continue;
149
+ }
150
+ result.push(registration.create(ctx));
151
+ }
152
+ return result;
153
+ }
@@ -5,8 +5,8 @@ import type { PipiclawSessionSearchSettings } from "../settings.js";
5
5
  declare const sessionSearchSchema: Type.TObject<{
6
6
  label: Type.TString;
7
7
  query: Type.TOptional<Type.TString>;
8
- limit: Type.TOptional<Type.TNumber>;
9
- roleFilter: Type.TOptional<Type.TArray<Type.TString>>;
8
+ limit: Type.TOptional<Type.TInteger>;
9
+ roleFilter: Type.TOptional<Type.TArray<Type.TUnion<[Type.TLiteral<"user">, Type.TLiteral<"assistant">, Type.TLiteral<"tool">, Type.TLiteral<"system">, Type.TLiteral<"unknown">]>>>;
10
10
  }>;
11
11
  export interface SessionSearchToolOptions {
12
12
  channelDir: string;