@oyasmi/pipiclaw 0.9.1 → 0.9.2-beta.2

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 (167) hide show
  1. package/dist/agent/channel-runner.d.ts +15 -1
  2. package/dist/agent/channel-runner.js +76 -24
  3. package/dist/agent/effect-ledger.js +9 -2
  4. package/dist/agent/job-manager.d.ts +4 -0
  5. package/dist/agent/job-manager.js +17 -2
  6. package/dist/agent/prompt/manifest.d.ts +1 -1
  7. package/dist/agent/prompt/manifest.js +1 -1
  8. package/dist/agent/prompt/sections.js +8 -5
  9. package/dist/agent/session-events.d.ts +2 -0
  10. package/dist/agent/session-events.js +29 -14
  11. package/dist/agent/turn-recovery.js +2 -2
  12. package/dist/agent/type-guards.js +5 -1
  13. package/dist/agent/workspace-resources.d.ts +2 -2
  14. package/dist/agent/workspace-resources.js +41 -3
  15. package/dist/executor.d.ts +14 -0
  16. package/dist/executor.js +96 -24
  17. package/dist/file-store.d.ts +96 -0
  18. package/dist/file-store.js +189 -0
  19. package/dist/memory/consolidation.js +2 -26
  20. package/dist/memory/files.js +7 -7
  21. package/dist/memory/maintenance-jobs.js +2 -34
  22. package/dist/memory/maintenance-state.js +2 -1
  23. package/dist/memory/recall.d.ts +10 -0
  24. package/dist/memory/recall.js +15 -7
  25. package/dist/memory/session-search.js +6 -22
  26. package/dist/memory/transcript.d.ts +10 -0
  27. package/dist/memory/transcript.js +39 -0
  28. package/dist/playbooks/agent-delegation.md +7 -5
  29. package/dist/playbooks/background-jobs.md +1 -1
  30. package/dist/playbooks/catalog.d.ts +1 -1
  31. package/dist/playbooks/catalog.js +1 -1
  32. package/dist/playbooks/event-scheduling.md +2 -0
  33. package/dist/playbooks/memory-and-learning.md +11 -11
  34. package/dist/playbooks/runtime-orientation.md +3 -3
  35. package/dist/playbooks/task-driving.md +7 -7
  36. package/dist/playbooks/task-planning.md +5 -5
  37. package/dist/runtime/app-home.js +1 -1
  38. package/dist/runtime/bootstrap.js +10 -0
  39. package/dist/runtime/dingtalk.js +3 -2
  40. package/dist/runtime/durable-dispatch.d.ts +26 -1
  41. package/dist/runtime/durable-dispatch.js +51 -5
  42. package/dist/runtime/event-commands.js +7 -16
  43. package/dist/runtime/events.d.ts +4 -2
  44. package/dist/runtime/events.js +15 -20
  45. package/dist/runtime/subagent-commands.js +1 -1
  46. package/dist/runtime/task-commands.d.ts +1 -1
  47. package/dist/runtime/task-commands.js +17 -12
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/runtime/task-wake.d.ts +2 -2
  50. package/dist/runtime/task-wake.js +2 -2
  51. package/dist/security/block-message.d.ts +11 -0
  52. package/dist/security/block-message.js +12 -0
  53. package/dist/security/path-guard-check.d.ts +13 -0
  54. package/dist/security/path-guard-check.js +39 -0
  55. package/dist/security/path-guard.js +32 -14
  56. package/dist/settings.js +3 -2
  57. package/dist/shared/atomic-file.d.ts +17 -1
  58. package/dist/shared/atomic-file.js +50 -3
  59. package/dist/shared/duration.d.ts +2 -0
  60. package/dist/shared/duration.js +7 -0
  61. package/dist/shared/safe-id.d.ts +19 -0
  62. package/dist/shared/safe-id.js +24 -0
  63. package/dist/shared/text-utils.d.ts +1 -1
  64. package/dist/shared/text-utils.js +3 -8
  65. package/dist/shared/type-guards.d.ts +2 -0
  66. package/dist/shared/type-guards.js +4 -0
  67. package/dist/subagents/discovery.d.ts +44 -17
  68. package/dist/subagents/discovery.js +82 -111
  69. package/dist/subagents/external/claude-code.js +1 -3
  70. package/dist/subagents/external/harness.d.ts +1 -1
  71. package/dist/subagents/external/run.d.ts +6 -0
  72. package/dist/subagents/external/run.js +122 -58
  73. package/dist/subagents/external/settlement.d.ts +3 -0
  74. package/dist/subagents/external/settlement.js +19 -5
  75. package/dist/subagents/format.d.ts +3 -2
  76. package/dist/subagents/format.js +3 -7
  77. package/dist/subagents/runs.d.ts +45 -9
  78. package/dist/subagents/runs.js +184 -64
  79. package/dist/subagents/tool.d.ts +35 -24
  80. package/dist/subagents/tool.js +631 -577
  81. package/dist/subagents/verification-outcome.js +1 -1
  82. package/dist/subagents/workspace-lease.js +1 -1
  83. package/dist/tasks/artifact-subject.d.ts +30 -4
  84. package/dist/tasks/artifact-subject.js +257 -25
  85. package/dist/tasks/control.js +7 -9
  86. package/dist/tasks/ledger.d.ts +2 -2
  87. package/dist/tasks/ledger.js +3 -7
  88. package/dist/tasks/transitions.d.ts +5 -1
  89. package/dist/tasks/transitions.js +2 -2
  90. package/dist/tasks/verification.d.ts +24 -2
  91. package/dist/tasks/verification.js +113 -21
  92. package/dist/tools/bash.d.ts +0 -1
  93. package/dist/tools/bash.js +45 -40
  94. package/dist/tools/config.d.ts +6 -1
  95. package/dist/tools/config.js +9 -0
  96. package/dist/tools/edit.d.ts +2 -3
  97. package/dist/tools/edit.js +274 -86
  98. package/dist/tools/event-manage.d.ts +13 -7
  99. package/dist/tools/event-manage.js +52 -14
  100. package/dist/tools/glob-match.d.ts +11 -0
  101. package/dist/tools/glob-match.js +75 -0
  102. package/dist/tools/glob.d.ts +15 -0
  103. package/dist/tools/glob.js +113 -0
  104. package/dist/tools/grep.d.ts +0 -1
  105. package/dist/tools/grep.js +57 -42
  106. package/dist/tools/ignore-dirs.d.ts +6 -0
  107. package/dist/tools/ignore-dirs.js +15 -0
  108. package/dist/tools/index.d.ts +3 -0
  109. package/dist/tools/index.js +50 -40
  110. package/dist/tools/job.d.ts +0 -1
  111. package/dist/tools/job.js +1 -8
  112. package/dist/tools/line-index.d.ts +16 -0
  113. package/dist/tools/line-index.js +76 -0
  114. package/dist/tools/memory-manage.d.ts +20 -8
  115. package/dist/tools/memory-manage.js +65 -92
  116. package/dist/tools/presentation.d.ts +2 -0
  117. package/dist/tools/presentation.js +109 -0
  118. package/dist/tools/read.d.ts +2 -2
  119. package/dist/tools/read.js +97 -133
  120. package/dist/tools/registry.d.ts +4 -1
  121. package/dist/tools/registry.js +89 -22
  122. package/dist/tools/send-media.d.ts +6 -6
  123. package/dist/tools/send-media.js +16 -49
  124. package/dist/tools/session-search.d.ts +0 -1
  125. package/dist/tools/session-search.js +0 -1
  126. package/dist/tools/skill-security.d.ts +0 -2
  127. package/dist/tools/skill-security.js +0 -24
  128. package/dist/tools/skill.d.ts +31 -0
  129. package/dist/tools/skill.js +153 -0
  130. package/dist/tools/subagent-manage.d.ts +6 -5
  131. package/dist/tools/subagent-manage.js +60 -60
  132. package/dist/tools/task-manage/create.d.ts +2 -2
  133. package/dist/tools/task-manage/create.js +1 -3
  134. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  135. package/dist/tools/task-manage/lifecycle.js +56 -60
  136. package/dist/tools/task-manage/schema.d.ts +27 -15
  137. package/dist/tools/task-manage/schema.js +58 -74
  138. package/dist/tools/task-manage/shared.d.ts +11 -6
  139. package/dist/tools/task-manage/shared.js +30 -21
  140. package/dist/tools/task-manage/types.d.ts +14 -15
  141. package/dist/tools/task-manage/verification.d.ts +5 -5
  142. package/dist/tools/task-manage/verification.js +18 -15
  143. package/dist/tools/task-manage.d.ts +8 -11
  144. package/dist/tools/task-manage.js +63 -50
  145. package/dist/tools/tool-details.d.ts +17 -1
  146. package/dist/tools/tool-details.js +24 -0
  147. package/dist/tools/truncate.d.ts +5 -5
  148. package/dist/tools/truncate.js +5 -5
  149. package/dist/tools/web-fetch.d.ts +0 -1
  150. package/dist/tools/web-fetch.js +0 -1
  151. package/dist/tools/web-search.d.ts +0 -1
  152. package/dist/tools/web-search.js +0 -1
  153. package/dist/tools/write-content.d.ts +3 -3
  154. package/dist/tools/write-content.js +12 -51
  155. package/dist/tools/write.d.ts +2 -3
  156. package/dist/tools/write.js +3 -4
  157. package/dist/tui/pitui-frontend.js +3 -3
  158. package/dist/usage/ledger.js +7 -4
  159. package/examples/sub-agents/README.md +13 -13
  160. package/examples/sub-agents/documenter.md +2 -1
  161. package/examples/sub-agents/reviewer.md +2 -0
  162. package/examples/sub-agents/scout.md +2 -1
  163. package/examples/sub-agents/verifier.md +6 -4
  164. package/examples/sub-agents/worker.md +2 -1
  165. package/package.json +5 -5
  166. package/dist/tools/skill-manage.d.ts +0 -41
  167. package/dist/tools/skill-manage.js +0 -232
@@ -1,10 +1,10 @@
1
1
  import { extname } from "path";
2
2
  import { Type } from "typebox";
3
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
- import { logSecurityEvent } from "../security/logger.js";
5
- import { guardPath } from "../security/path-guard.js";
4
+ import { checkPathGuard } from "../security/path-guard-check.js";
6
5
  import { RecoverableToolError } from "../shared/recoverable-error.js";
7
6
  import { shellEscape } from "../shared/shell-escape.js";
7
+ import { resolveLineOffset } from "./line-index.js";
8
8
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, MAX_INLINE_BINARY_BYTES, truncateHead, } from "./truncate.js";
9
9
  /**
10
10
  * Map of file extensions to MIME types for common image formats
@@ -27,29 +27,20 @@ function isImageFile(filePath) {
27
27
  const DIR_MAX_DEPTH = 2;
28
28
  const DIR_PER_DIR_LIMIT = 12;
29
29
  /**
30
- * Render a depth-2 directory tree from a newline-separated list of paths (directories carry a
31
- * trailing `/`, produced by the shell). Kept deliberately portable — no sizes or mtimes, since
32
- * `find -printf` / `stat` formats differ across BSD, GNU, and busybox; the structure is the value.
30
+ * Render a depth-2 directory tree from `FileStore.listDirectory` entries. Kept deliberately
31
+ * portable — no sizes or mtimes, since formats differ across platforms; the structure is the value.
33
32
  */
34
- function renderDirectoryTree(rootPath, rawPaths) {
35
- const rootPrefix = rootPath.endsWith("/") ? rootPath : `${rootPath}/`;
36
- const entries = rawPaths
37
- .split("\n")
38
- .map((line) => line.trim())
39
- .filter((line) => line.length > 0 && line !== rootPath && line !== rootPrefix)
40
- .map((line) => (line.startsWith(rootPrefix) ? line.slice(rootPrefix.length) : line))
41
- .sort((a, b) => a.replace(/\/$/, "").localeCompare(b.replace(/\/$/, "")));
33
+ function renderDirectoryTree(entries) {
42
34
  if (entries.length === 0) {
43
35
  return "(empty directory)";
44
36
  }
37
+ const sorted = [...entries].sort((a, b) => a.relativePath.localeCompare(b.relativePath));
45
38
  // Group by immediate parent so we can cap children per directory.
46
39
  const perParentCount = new Map();
47
40
  const lines = [];
48
41
  const elided = new Map();
49
- for (const entry of entries) {
50
- const isDir = entry.endsWith("/");
51
- const rel = isDir ? entry.slice(0, -1) : entry;
52
- const segments = rel.split("/");
42
+ for (const entry of sorted) {
43
+ const segments = entry.relativePath.split("/");
53
44
  const depth = segments.length - 1;
54
45
  const parent = depth === 0 ? "" : segments.slice(0, -1).join("/");
55
46
  const count = (perParentCount.get(parent) ?? 0) + 1;
@@ -58,7 +49,7 @@ function renderDirectoryTree(rootPath, rawPaths) {
58
49
  elided.set(parent, (elided.get(parent) ?? 0) + 1);
59
50
  continue;
60
51
  }
61
- lines.push(`${" ".repeat(depth)}${segments[segments.length - 1]}${isDir ? "/" : ""}`);
52
+ lines.push(`${" ".repeat(depth)}${entry.name}${entry.isDirectory ? "/" : ""}`);
62
53
  }
63
54
  for (const [, count] of elided) {
64
55
  lines.push(` [+${count} more]`);
@@ -66,7 +57,6 @@ function renderDirectoryTree(rootPath, rawPaths) {
66
57
  return lines.join("\n");
67
58
  }
68
59
  const readSchema = Type.Object({
69
- label: Type.String({ description: "Brief description of what you're reading and why (shown to user)" }),
70
60
  path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
71
61
  offset: Type.Optional(Type.Integer({ minimum: 1, description: "Line number to start reading from (1-indexed)" })),
72
62
  limit: Type.Optional(Type.Integer({ minimum: 1, description: "Maximum number of lines to read" })),
@@ -78,20 +68,7 @@ function countSplitLines(content, lines) {
78
68
  }
79
69
  return content.endsWith("\n") ? lines.length - 1 : lines.length;
80
70
  }
81
- function countTextLines(content) {
82
- return countSplitLines(content, content.split("\n"));
83
- }
84
- function formatPathBlockMessage(resolvedPath, category, reason) {
85
- const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
86
- if (reason) {
87
- lines.push(`Reason: ${reason}`);
88
- }
89
- if (resolvedPath) {
90
- lines.push(`Resolved path: ${resolvedPath}`);
91
- }
92
- return lines.join("\n");
93
- }
94
- export function createReadTool(executor, options = {}) {
71
+ export function createReadTool(executor, fileStore, options = {}) {
95
72
  const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
96
73
  const securityContext = options.securityContext ?? {
97
74
  agentWorkspaceDir: process.cwd(),
@@ -103,57 +80,39 @@ export function createReadTool(executor, options = {}) {
103
80
  description: `Read the contents of a file. Supports text files and images (jpg, png, gif, webp). Images are sent as attachments. For text files, output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first). Use offset/limit for large files.`,
104
81
  parameters: readSchema,
105
82
  execute: async (_toolCallId, { path, offset, limit }, signal) => {
106
- if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
107
- const guardResult = guardPath(path, "read", { ...securityContext, config: securityConfig.pathGuard });
108
- if (!guardResult.allowed) {
109
- await logSecurityEvent(securityContext.agentWorkspaceDir, securityConfig, {
110
- type: "path",
111
- tool: "read",
112
- channelId: options.channelId,
113
- rawPath: path,
114
- operation: "read",
115
- resolvedPath: guardResult.resolvedPath,
116
- category: guardResult.category,
117
- reason: guardResult.reason,
118
- });
119
- throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
120
- }
121
- }
83
+ const target = await checkPathGuard(path, "read", securityConfig, securityContext, {
84
+ tool: "read",
85
+ channelId: options.channelId,
86
+ });
122
87
  const mimeType = isImageFile(path);
123
88
  if (mimeType) {
124
- // Guard the file size before `base64`: base64 inflates to 4/3, and the executor caps
125
- // captured stdout at 10MB, so a file above MAX_INLINE_BINARY_BYTES would be silently
126
- // truncated mid-encoding into a buffer that still decodes -- a corrupt image handed to
127
- // the model with no error (fix plan §2.3).
128
- const sizeCheck = await executor.exec(`wc -c < ${shellEscape(path)} 2>&1 || echo __SIZE_FAILED__`, {
129
- signal,
130
- });
131
- const sizeBytes = Number.parseInt(sizeCheck.stdout.trim(), 10);
132
- if (Number.isFinite(sizeBytes) && sizeBytes > MAX_INLINE_BINARY_BYTES) {
133
- throw new RecoverableToolError(`Image ${path} is ${formatSize(sizeBytes)}, over the ${formatSize(MAX_INLINE_BINARY_BYTES)} inline limit. ` +
134
- "Compress or resize it first with bash (e.g. sips/convert/ffmpeg), or read it as text to inspect metadata only.");
89
+ // Stat before reading: base64-encoding a file over the inline limit is pointless work,
90
+ // and doing it via `FileStore.readBytes` rather than shelling out to `base64` (spec 044,
91
+ // D7) means there is no 4/3 blow-up through a captured stdout string to worry about.
92
+ const stat = await fileStore.stat(target);
93
+ if (!stat || !stat.isFile) {
94
+ throw new RecoverableToolError(`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
135
95
  }
136
- // Read as image (binary) - use base64
137
- const result = await executor.exec(`base64 < ${shellEscape(path)}`, { signal });
138
- if (result.code !== 0) {
139
- throw new RecoverableToolError(result.stderr ||
140
- `Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
96
+ if (stat.size > MAX_INLINE_BINARY_BYTES) {
97
+ throw new RecoverableToolError(`Image ${path} is ${formatSize(stat.size)}, over the ${formatSize(MAX_INLINE_BINARY_BYTES)} inline limit. ` +
98
+ "Compress or resize it first with bash (e.g. sips/convert/ffmpeg), or read it as text to inspect metadata only.");
141
99
  }
142
- const base64 = result.stdout.replace(/\s/g, ""); // Remove whitespace from base64
100
+ const { data } = await fileStore.readBytes(target, { signal });
143
101
  return {
144
102
  content: [
145
103
  { type: "text", text: `Read image file [${mimeType}]` },
146
- { type: "image", data: base64, mimeType },
104
+ { type: "image", data: data.toString("base64"), mimeType },
147
105
  ],
148
106
  details: undefined,
149
107
  };
150
108
  }
151
109
  // PDF documents are converted to text with pdftotext, then run through the same
152
- // offset/limit/truncation pipeline as any text file.
110
+ // offset/limit/truncation pipeline as any text file. That's a command, not a file read, so
111
+ // it still goes through `Executor`.
153
112
  const isPdf = extname(path).toLowerCase() === ".pdf";
154
113
  let pdfText = "";
155
114
  if (isPdf) {
156
- const converted = await executor.exec(`pdftotext -layout ${shellEscape(path)} - 2>&1`, { signal });
115
+ const converted = await executor.exec(`pdftotext -layout ${shellEscape(target)} - 2>&1`, { signal });
157
116
  if (converted.code === 127) {
158
117
  throw new Error(`Cannot read ${path}: pdftotext is not installed. Install poppler-utils, or ask the user to send a text version.`);
159
118
  }
@@ -163,75 +122,78 @@ export function createReadTool(executor, options = {}) {
163
122
  }
164
123
  pdfText = converted.stdout;
165
124
  }
166
- // Get total line count. For non-PDF paths this same command also detects a directory
167
- // (`cat`/`awk` on a directory would fail), so a directory read is a shallow tree rather
168
- // than a confusing error — all in one exec to keep the call sequence unchanged.
169
- let totalFileLines;
170
- if (isPdf) {
171
- totalFileLines = countTextLines(pdfText);
125
+ const stat = isPdf ? undefined : await fileStore.stat(target);
126
+ if (!isPdf && !stat) {
127
+ throw new RecoverableToolError(`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
172
128
  }
173
- else {
174
- const countResult = await executor.exec(`if [ -d ${shellEscape(path)} ]; then echo __DIR__; else awk 'END { print NR }' ${shellEscape(path)}; fi`, { signal });
175
- if (countResult.code !== 0) {
176
- throw new RecoverableToolError(countResult.stderr ||
177
- `Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
178
- }
179
- if (countResult.stdout.trim() === "__DIR__") {
180
- const listing = await executor.exec(`{ find ${shellEscape(path)} -maxdepth ${DIR_MAX_DEPTH} -type d | sed 's,$,/,'; ` +
181
- `find ${shellEscape(path)} -maxdepth ${DIR_MAX_DEPTH} ! -type d; }`, { signal });
182
- if (listing.code !== 0) {
183
- throw new Error(listing.stderr || `Failed to list directory: ${path}`);
184
- }
185
- return {
186
- content: [
187
- { type: "text", text: `Directory: ${path}\n\n${renderDirectoryTree(path, listing.stdout)}` },
188
- ],
189
- details: undefined,
190
- };
191
- }
192
- totalFileLines = Number.parseInt(countResult.stdout.trim(), 10);
129
+ if (stat?.isDirectory) {
130
+ const entries = await fileStore.listDirectory(target, { maxDepth: DIR_MAX_DEPTH });
131
+ return {
132
+ content: [{ type: "text", text: `Directory: ${path}\n\n${renderDirectoryTree(entries)}` }],
133
+ details: undefined,
134
+ };
193
135
  }
194
- // Apply offset if specified (1-indexed)
195
136
  const startLine = offset ? Math.max(1, offset) : 1;
196
137
  const startLineDisplay = startLine;
197
- // Check if offset is out of bounds
198
- if ((totalFileLines === 0 && offset !== undefined && startLine > 1) ||
199
- (totalFileLines > 0 && startLine > totalFileLines)) {
200
- const guidance = totalFileLines > 0
201
- ? `Use offset=${totalFileLines} to read the last line, or omit offset to read from the start.`
202
- : "The file is empty; omit offset.";
203
- throw new RecoverableToolError(`Offset ${offset} is beyond end of file (${totalFileLines} lines total). ${guidance}`);
204
- }
205
- // Read content from the offset. PDF text is already in memory; files stream from disk.
138
+ // Resolve the byte offset of `startLine` via the incremental line index (D4.2). PDF text is
139
+ // small and already fully in memory, so it just splits directly. For a real file, the index
140
+ // scans forward from wherever it last left off; reaching EOF without finding `startLine`
141
+ // means the offset is out of bounds -- decided from what the scan actually observed (D4.3),
142
+ // never from a separate precomputed total.
206
143
  let selectedContent;
144
+ let windowEof;
145
+ let linesBeforeWindow;
207
146
  if (isPdf) {
208
- selectedContent =
209
- startLine === 1
210
- ? pdfText
211
- : pdfText
212
- .split("\n")
213
- .slice(startLine - 1)
214
- .join("\n");
147
+ const pdfLines = pdfText.split("\n");
148
+ const totalPdfLines = countSplitLines(pdfText, pdfLines);
149
+ if (startLine > Math.max(totalPdfLines, 1)) {
150
+ throw new RecoverableToolError(`Offset ${offset} is beyond end of file (${totalPdfLines} lines total). ` +
151
+ (totalPdfLines > 0
152
+ ? `Use offset=${totalPdfLines} to read the last line, or omit offset to read from the start.`
153
+ : "The file is empty; omit offset."));
154
+ }
155
+ selectedContent = startLine === 1 ? pdfText : pdfLines.slice(startLine - 1).join("\n");
156
+ windowEof = true;
157
+ linesBeforeWindow = startLine - 1;
215
158
  }
216
159
  else {
217
- // Bounded at the source. The output is capped below at min(DEFAULT_MAX_LINES,
218
- // DEFAULT_MAX_BYTES) anyway, so piping a multi-hundred-megabyte log through the
219
- // executor and materializing it as a JS string first only bought a second full read
220
- // of the file and the peak memory to hold it. Reading twice the byte cap always
221
- // leaves `truncateHead` enough to apply whichever limit binds first — the byte cap
222
- // is half the window, and however short the lines are, DEFAULT_MAX_LINES of them
223
- // are either within the window or already past the byte cap.
224
- const readWindowBytes = DEFAULT_MAX_BYTES * 2;
225
- const source = startLine === 1 ? `cat ${shellEscape(path)}` : `tail -n +${startLine} ${shellEscape(path)}`;
226
- // `sh -c` runs without pipefail, so the pipeline reports head's status; head closing
227
- // the pipe early is the point, not a failure.
228
- const result = await executor.exec(`${source} | head -c ${readWindowBytes}`, { signal });
229
- if (result.code !== 0) {
230
- throw new RecoverableToolError(result.stderr ||
231
- `Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
160
+ const fileStat = stat;
161
+ if (fileStat.size === 0) {
162
+ if (offset !== undefined && startLine > 1) {
163
+ throw new RecoverableToolError(`Offset ${offset} is beyond end of file (0 lines total). The file is empty; omit offset.`);
164
+ }
165
+ selectedContent = "";
166
+ windowEof = true;
167
+ linesBeforeWindow = 0;
168
+ }
169
+ else {
170
+ const located = await resolveLineOffset(fileStore, target, fileStat, startLine, signal);
171
+ if (located.offset === undefined) {
172
+ const guidance = located.knownLines > 0
173
+ ? `Use offset=${located.knownLines} to read the last line, or omit offset to read from the start.`
174
+ : "The file is empty; omit offset.";
175
+ throw new RecoverableToolError(`Offset ${offset} is beyond end of file (${located.knownLines} lines total). ${guidance}`);
176
+ }
177
+ // Bounded at the source: read at most twice the byte cap, which always leaves
178
+ // `truncateHead` enough to apply whichever limit binds first (line or byte), however
179
+ // short the lines are.
180
+ const readWindowBytes = DEFAULT_MAX_BYTES * 2;
181
+ const { data, eof } = await fileStore.readBytes(target, {
182
+ start: located.offset,
183
+ maxBytes: readWindowBytes,
184
+ signal,
185
+ });
186
+ selectedContent = data.toString("utf-8");
187
+ windowEof = eof;
188
+ linesBeforeWindow = startLine - 1;
232
189
  }
233
- selectedContent = result.stdout;
234
190
  }
191
+ // Total lines known so far, from the *whole* read window before any user `limit` slices
192
+ // it down: exact when the window reached the real EOF, a lower bound otherwise (D4.3) --
193
+ // never a number nobody actually counted.
194
+ const linesInWindow = countSplitLines(selectedContent, selectedContent.split("\n"));
195
+ const knownTotalLines = linesBeforeWindow + linesInWindow;
196
+ const totalIsExact = windowEof;
235
197
  let userLimitedLines;
236
198
  // Apply user limit if specified
237
199
  if (limit !== undefined) {
@@ -254,23 +216,25 @@ export function createReadTool(executor, options = {}) {
254
216
  // Truncation occurred - build actionable notice
255
217
  const endLineDisplay = startLineDisplay + truncation.outputLines - 1;
256
218
  const nextOffset = endLineDisplay + 1;
219
+ const totalLabel = totalIsExact ? `${knownTotalLines}` : `>=${knownTotalLines}`;
257
220
  outputText = truncation.content;
258
221
  if (truncation.truncatedBy === "lines") {
259
- outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines}. Use offset=${nextOffset} to continue]`;
222
+ outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalLabel}. Use offset=${nextOffset} to continue]`;
260
223
  }
261
224
  else {
262
- outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalFileLines} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue]`;
225
+ outputText += `\n\n[Showing lines ${startLineDisplay}-${endLineDisplay} of ${totalLabel} (${formatSize(DEFAULT_MAX_BYTES)} limit). Use offset=${nextOffset} to continue]`;
263
226
  }
264
227
  details = { truncation };
265
228
  }
266
229
  else if (userLimitedLines !== undefined) {
267
230
  // User specified limit, check if there's more content
268
231
  const linesFromStart = startLine - 1 + userLimitedLines;
269
- if (linesFromStart < totalFileLines) {
270
- const remaining = totalFileLines - linesFromStart;
232
+ const moreAvailable = !windowEof || linesFromStart < knownTotalLines;
233
+ if (moreAvailable) {
271
234
  const nextOffset = startLine + userLimitedLines;
272
235
  outputText = truncation.content;
273
- outputText += `\n\n[${remaining} more lines in file. Use offset=${nextOffset} to continue]`;
236
+ const remainingLabel = windowEof ? `${knownTotalLines - linesFromStart}` : "more";
237
+ outputText += `\n\n[${remainingLabel} more lines in file. Use offset=${nextOffset} to continue]`;
274
238
  }
275
239
  else {
276
240
  outputText = truncation.content;
@@ -2,6 +2,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
4
  import type { Executor } from "../executor.js";
5
+ import type { FileStore } from "../file-store.js";
5
6
  import type { MemoryCandidateStore } from "../memory/candidates.js";
6
7
  import type { MediaSender } from "../runtime/channel-context.js";
7
8
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
@@ -19,6 +20,8 @@ import { type ToolDetailsKind } from "./tool-details.js";
19
20
  */
20
21
  export interface ToolBuildContext {
21
22
  executor: Executor;
23
+ /** File-content port for the generic file tools (spec 044, D1); `Executor` stays command-only. */
24
+ fileStore: FileStore;
22
25
  securityConfig: SecurityConfig;
23
26
  securityContext: SecurityRuntimeContext;
24
27
  channelId: string;
@@ -26,7 +29,7 @@ export interface ToolBuildContext {
26
29
  workspaceDir: string;
27
30
  /** Main set: `toolsConfig.tools.web`; sub-agent set: the sub-agent's own webConfig. */
28
31
  webConfig?: PipiclawWebToolsConfig;
29
- /** Present only on the main path; gates task_manage and the bash interceptor. */
32
+ /** Present only on the main path; gates the task_* tools and the bash interceptor. */
30
33
  toolsConfig?: PipiclawToolsConfig;
31
34
  /** Sub-agent set passes its per-invocation bash timeout; the main set relies on the built-in default. */
32
35
  bashDefaultTimeoutSeconds?: number;
@@ -1,14 +1,15 @@
1
1
  import { createBashTool } from "./bash.js";
2
2
  import { createEditTool } from "./edit.js";
3
3
  import { createEventManageTool } from "./event-manage.js";
4
+ import { createGlobTool } from "./glob.js";
4
5
  import { createGrepTool } from "./grep.js";
5
6
  import { createJobTool } from "./job.js";
6
- import { createMemoryManageTool } from "./memory-manage.js";
7
+ import { createMemoryForgetTool, createMemorySaveTool, createMemorySearchTool } from "./memory-manage.js";
7
8
  import { createReadTool } from "./read.js";
8
9
  import { createSendMediaTool } from "./send-media.js";
9
10
  import { createSessionSearchTool } from "./session-search.js";
10
- import { createSkillManageTool } from "./skill-manage.js";
11
- import { createTaskManageTool } from "./task-manage.js";
11
+ import { createSkillTool } from "./skill.js";
12
+ import { createTaskCloseTool, createTaskCreateTool, createTaskListTool, createTaskUpdateTool, createTaskVerifyTool, } from "./task-manage.js";
12
13
  import { withToolDetails } from "./tool-details.js";
13
14
  import { createWebFetchTool } from "./web-fetch.js";
14
15
  import { createWebSearchTool } from "./web-search.js";
@@ -26,6 +27,16 @@ function fileToolOptions(ctx) {
26
27
  channelId: ctx.channelId,
27
28
  };
28
29
  }
30
+ function memoryToolOptions(ctx) {
31
+ return {
32
+ channelId: ctx.channelId,
33
+ channelDir: ctx.channelDir,
34
+ workspaceDir: ctx.workspaceDir,
35
+ memoryCandidateStore: req(ctx.memoryCandidateStore, "memoryCandidateStore"),
36
+ getCurrentModel: req(ctx.getCurrentModel, "getCurrentModel"),
37
+ resolveApiKey: req(ctx.resolveApiKey, "resolveApiKey"),
38
+ };
39
+ }
29
40
  function webEnabled(ctx) {
30
41
  return ctx.webConfig != null && ctx.webConfig.enable !== false;
31
42
  }
@@ -39,7 +50,7 @@ export const TOOL_REGISTRY = [
39
50
  {
40
51
  name: "read",
41
52
  availableToSubagents: true,
42
- create: (ctx) => createReadTool(ctx.executor, fileToolOptions(ctx)),
53
+ create: (ctx) => createReadTool(ctx.executor, ctx.fileStore, fileToolOptions(ctx)),
43
54
  },
44
55
  {
45
56
  name: "bash",
@@ -57,17 +68,22 @@ export const TOOL_REGISTRY = [
57
68
  {
58
69
  name: "edit",
59
70
  availableToSubagents: true,
60
- create: (ctx) => createEditTool(ctx.executor, fileToolOptions(ctx)),
71
+ create: (ctx) => createEditTool(ctx.fileStore, fileToolOptions(ctx)),
61
72
  },
62
73
  {
63
74
  name: "grep",
64
75
  availableToSubagents: true,
65
76
  create: (ctx) => createGrepTool(ctx.executor, fileToolOptions(ctx)),
66
77
  },
78
+ {
79
+ name: "glob",
80
+ availableToSubagents: true,
81
+ create: (ctx) => createGlobTool(ctx.fileStore, fileToolOptions(ctx)),
82
+ },
67
83
  {
68
84
  name: "write",
69
85
  availableToSubagents: true,
70
- create: (ctx) => createWriteTool(ctx.executor, fileToolOptions(ctx)),
86
+ create: (ctx) => createWriteTool(ctx.fileStore, fileToolOptions(ctx)),
71
87
  },
72
88
  {
73
89
  name: "web_search",
@@ -98,7 +114,7 @@ export const TOOL_REGISTRY = [
98
114
  // Enabled only when the driving transport supplied a media sender (the DingTalk
99
115
  // bot, or the terminal). Absent it, the tool is not built or advertised.
100
116
  enabledBy: (ctx) => ctx.mediaSender != null,
101
- create: (ctx) => createSendMediaTool(ctx.executor, {
117
+ create: (ctx) => createSendMediaTool(ctx.fileStore, {
102
118
  mediaSender: req(ctx.mediaSender, "mediaSender"),
103
119
  channelId: ctx.channelId,
104
120
  securityConfig: ctx.securityConfig,
@@ -116,39 +132,88 @@ export const TOOL_REGISTRY = [
116
132
  getSessionSearchSettings: req(ctx.getSessionSearchSettings, "getSessionSearchSettings"),
117
133
  }),
118
134
  },
135
+ // Spec 047, P4: one tool per payload shape. All three share the same build options.
119
136
  {
120
- name: "memory_manage",
137
+ name: "memory_save",
121
138
  availableToSubagents: false,
122
- create: (ctx) => createMemoryManageTool({
139
+ create: (ctx) => createMemorySaveTool(memoryToolOptions(ctx)),
140
+ },
141
+ {
142
+ name: "memory_search",
143
+ availableToSubagents: false,
144
+ create: (ctx) => createMemorySearchTool(memoryToolOptions(ctx)),
145
+ },
146
+ {
147
+ name: "memory_forget",
148
+ availableToSubagents: false,
149
+ create: (ctx) => createMemoryForgetTool(memoryToolOptions(ctx)),
150
+ },
151
+ {
152
+ name: "skill",
153
+ availableToSubagents: false,
154
+ create: (ctx) => createSkillTool({ workspaceDir: ctx.workspaceDir, ...fileToolOptions(ctx) }),
155
+ },
156
+ {
157
+ name: "event_manage",
158
+ availableToSubagents: false,
159
+ create: (ctx) => createEventManageTool({
160
+ workspaceDir: ctx.workspaceDir,
123
161
  channelId: ctx.channelId,
162
+ commandGuardConfig: ctx.securityConfig.commandGuard,
163
+ }),
164
+ },
165
+ // tools.tasks is the master switch for the whole autonomous long-running task mechanism;
166
+ // the TaskDriver and per-turn task digest honor the same flag. Five tools, one per payload
167
+ // shape (spec 046, D3.1) — all share it, since none is meaningful without the others.
168
+ {
169
+ name: "task_list",
170
+ availableToSubagents: false,
171
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
172
+ create: (ctx) => createTaskListTool({
173
+ workspaceDir: ctx.workspaceDir,
124
174
  channelDir: ctx.channelDir,
175
+ channelId: ctx.channelId,
176
+ workingDirectory: ctx.securityContext.projectRoot,
177
+ }),
178
+ },
179
+ {
180
+ name: "task_create",
181
+ availableToSubagents: false,
182
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
183
+ create: (ctx) => createTaskCreateTool({
125
184
  workspaceDir: ctx.workspaceDir,
126
- memoryCandidateStore: req(ctx.memoryCandidateStore, "memoryCandidateStore"),
127
- getCurrentModel: req(ctx.getCurrentModel, "getCurrentModel"),
128
- resolveApiKey: req(ctx.resolveApiKey, "resolveApiKey"),
185
+ channelDir: ctx.channelDir,
186
+ channelId: ctx.channelId,
187
+ workingDirectory: ctx.securityContext.projectRoot,
129
188
  }),
130
189
  },
131
190
  {
132
- name: "skill_manage",
191
+ name: "task_update",
133
192
  availableToSubagents: false,
134
- create: (ctx) => createSkillManageTool({ workspaceDir: ctx.workspaceDir }),
193
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
194
+ create: (ctx) => createTaskUpdateTool({
195
+ workspaceDir: ctx.workspaceDir,
196
+ channelDir: ctx.channelDir,
197
+ channelId: ctx.channelId,
198
+ workingDirectory: ctx.securityContext.projectRoot,
199
+ }),
135
200
  },
136
201
  {
137
- name: "event_manage",
202
+ name: "task_close",
138
203
  availableToSubagents: false,
139
- create: (ctx) => createEventManageTool({
204
+ enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
205
+ create: (ctx) => createTaskCloseTool({
140
206
  workspaceDir: ctx.workspaceDir,
207
+ channelDir: ctx.channelDir,
141
208
  channelId: ctx.channelId,
142
- commandGuardConfig: ctx.securityConfig.commandGuard,
209
+ workingDirectory: ctx.securityContext.projectRoot,
143
210
  }),
144
211
  },
145
212
  {
146
- name: "task_manage",
213
+ name: "task_verify",
147
214
  availableToSubagents: false,
148
- // tools.tasks is the master switch for the whole autonomous long-running task
149
- // mechanism; the TaskDriver and per-turn task digest honor the same flag.
150
215
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
151
- create: (ctx) => createTaskManageTool({
216
+ create: (ctx) => createTaskVerifyTool({
152
217
  workspaceDir: ctx.workspaceDir,
153
218
  channelDir: ctx.channelDir,
154
219
  channelId: ctx.channelId,
@@ -178,7 +243,9 @@ export const TOOL_REGISTRY = [
178
243
  export const TOOL_NAMES = new Set([
179
244
  ...TOOL_REGISTRY.map((registration) => registration.name),
180
245
  "subagent",
181
- "subagent_manage",
246
+ "subagent_inline",
247
+ "subagent_list",
248
+ "subagent_run",
182
249
  ]);
183
250
  /**
184
251
  * Build a tool set from the registry, honoring sub-agent availability and config gates.
@@ -1,10 +1,9 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
- import type { Executor } from "../executor.js";
3
+ import type { FileStore } from "../file-store.js";
4
4
  import type { MediaSender } from "../runtime/channel-context.js";
5
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
6
  declare const sendMediaSchema: Type.TObject<{
7
- label: Type.TString;
8
7
  path: Type.TString;
9
8
  fileName: Type.TOptional<Type.TString>;
10
9
  }>;
@@ -20,9 +19,10 @@ export interface SendMediaToolOptions {
20
19
  * Send a workspace file to the current channel as a native attachment (inline
21
20
  * image or downloadable file). Bound to its channel at build time — like `read`
22
21
  * and `bash` — so the model never chooses the destination. The file is read
23
- * through the `Executor` (base64, exactly as `read` does for images) so the tool
24
- * works regardless of where the executor runs, and every path passes the same
25
- * path-guard as the file tools before any bytes leave the box.
22
+ * through `FileStore` (spec 044, D7) rather than shelling out to `base64`, so
23
+ * there is no 4/3 blow-up through a captured stdout string to size against, and
24
+ * every path passes the same path-guard as the file tools before any bytes leave
25
+ * the box.
26
26
  */
27
- export declare function createSendMediaTool(executor: Executor, options: SendMediaToolOptions): AgentTool<typeof sendMediaSchema>;
27
+ export declare function createSendMediaTool(fileStore: FileStore, options: SendMediaToolOptions): AgentTool<typeof sendMediaSchema>;
28
28
  export {};