@oyasmi/pipiclaw 0.9.1 → 0.9.2-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 (149) hide show
  1. package/dist/agent/channel-runner.d.ts +2 -1
  2. package/dist/agent/channel-runner.js +9 -5
  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 +6 -4
  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 +5 -5
  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 +10 -10
  48. package/dist/runtime/task-driver.js +2 -2
  49. package/dist/security/block-message.d.ts +11 -0
  50. package/dist/security/block-message.js +12 -0
  51. package/dist/security/path-guard-check.d.ts +13 -0
  52. package/dist/security/path-guard-check.js +39 -0
  53. package/dist/security/path-guard.js +32 -14
  54. package/dist/settings.js +3 -2
  55. package/dist/shared/atomic-file.d.ts +17 -1
  56. package/dist/shared/atomic-file.js +50 -3
  57. package/dist/shared/duration.d.ts +2 -0
  58. package/dist/shared/duration.js +7 -0
  59. package/dist/shared/safe-id.d.ts +19 -0
  60. package/dist/shared/safe-id.js +24 -0
  61. package/dist/shared/text-utils.d.ts +1 -1
  62. package/dist/shared/text-utils.js +3 -8
  63. package/dist/shared/type-guards.d.ts +2 -0
  64. package/dist/shared/type-guards.js +4 -0
  65. package/dist/subagents/discovery.d.ts +44 -17
  66. package/dist/subagents/discovery.js +82 -111
  67. package/dist/subagents/external/claude-code.js +1 -3
  68. package/dist/subagents/external/harness.d.ts +1 -1
  69. package/dist/subagents/format.d.ts +3 -2
  70. package/dist/subagents/format.js +3 -7
  71. package/dist/subagents/runs.d.ts +1 -1
  72. package/dist/subagents/runs.js +4 -9
  73. package/dist/subagents/tool.d.ts +31 -19
  74. package/dist/subagents/tool.js +582 -561
  75. package/dist/subagents/workspace-lease.js +1 -1
  76. package/dist/tasks/control.js +7 -9
  77. package/dist/tasks/ledger.d.ts +2 -2
  78. package/dist/tasks/ledger.js +3 -7
  79. package/dist/tasks/transitions.d.ts +5 -1
  80. package/dist/tasks/transitions.js +2 -2
  81. package/dist/tools/bash.d.ts +0 -1
  82. package/dist/tools/bash.js +45 -40
  83. package/dist/tools/config.d.ts +6 -1
  84. package/dist/tools/config.js +9 -0
  85. package/dist/tools/edit.d.ts +2 -3
  86. package/dist/tools/edit.js +274 -86
  87. package/dist/tools/event-manage.d.ts +13 -7
  88. package/dist/tools/event-manage.js +52 -14
  89. package/dist/tools/glob-match.d.ts +11 -0
  90. package/dist/tools/glob-match.js +75 -0
  91. package/dist/tools/glob.d.ts +15 -0
  92. package/dist/tools/glob.js +113 -0
  93. package/dist/tools/grep.d.ts +0 -1
  94. package/dist/tools/grep.js +57 -42
  95. package/dist/tools/ignore-dirs.d.ts +6 -0
  96. package/dist/tools/ignore-dirs.js +15 -0
  97. package/dist/tools/index.d.ts +3 -0
  98. package/dist/tools/index.js +50 -40
  99. package/dist/tools/job.d.ts +0 -1
  100. package/dist/tools/job.js +1 -8
  101. package/dist/tools/line-index.d.ts +16 -0
  102. package/dist/tools/line-index.js +76 -0
  103. package/dist/tools/memory-manage.d.ts +20 -8
  104. package/dist/tools/memory-manage.js +65 -92
  105. package/dist/tools/presentation.d.ts +2 -0
  106. package/dist/tools/presentation.js +109 -0
  107. package/dist/tools/read.d.ts +2 -2
  108. package/dist/tools/read.js +97 -133
  109. package/dist/tools/registry.d.ts +4 -1
  110. package/dist/tools/registry.js +89 -22
  111. package/dist/tools/send-media.d.ts +6 -6
  112. package/dist/tools/send-media.js +16 -49
  113. package/dist/tools/session-search.d.ts +0 -1
  114. package/dist/tools/session-search.js +0 -1
  115. package/dist/tools/skill-security.d.ts +0 -2
  116. package/dist/tools/skill-security.js +0 -24
  117. package/dist/tools/skill.d.ts +31 -0
  118. package/dist/tools/skill.js +153 -0
  119. package/dist/tools/subagent-manage.d.ts +6 -5
  120. package/dist/tools/subagent-manage.js +47 -47
  121. package/dist/tools/task-manage/create.d.ts +2 -2
  122. package/dist/tools/task-manage/create.js +1 -3
  123. package/dist/tools/task-manage/lifecycle.d.ts +9 -6
  124. package/dist/tools/task-manage/lifecycle.js +49 -56
  125. package/dist/tools/task-manage/schema.d.ts +27 -15
  126. package/dist/tools/task-manage/schema.js +58 -74
  127. package/dist/tools/task-manage/shared.d.ts +11 -6
  128. package/dist/tools/task-manage/shared.js +30 -21
  129. package/dist/tools/task-manage/types.d.ts +14 -15
  130. package/dist/tools/task-manage/verification.d.ts +4 -4
  131. package/dist/tools/task-manage/verification.js +6 -8
  132. package/dist/tools/task-manage.d.ts +8 -11
  133. package/dist/tools/task-manage.js +63 -50
  134. package/dist/tools/tool-details.d.ts +17 -1
  135. package/dist/tools/tool-details.js +24 -0
  136. package/dist/tools/truncate.d.ts +5 -5
  137. package/dist/tools/truncate.js +5 -5
  138. package/dist/tools/web-fetch.d.ts +0 -1
  139. package/dist/tools/web-fetch.js +0 -1
  140. package/dist/tools/web-search.d.ts +0 -1
  141. package/dist/tools/web-search.js +0 -1
  142. package/dist/tools/write-content.d.ts +3 -3
  143. package/dist/tools/write-content.js +12 -51
  144. package/dist/tools/write.d.ts +2 -3
  145. package/dist/tools/write.js +3 -4
  146. package/dist/usage/ledger.js +7 -4
  147. package/package.json +1 -1
  148. package/dist/tools/skill-manage.d.ts +0 -41
  149. package/dist/tools/skill-manage.js +0 -232
@@ -0,0 +1,15 @@
1
+ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
+ import { Type } from "typebox";
3
+ import type { FileStore } from "../file-store.js";
4
+ import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
+ declare const globSchema: Type.TObject<{
6
+ pattern: Type.TString;
7
+ path: Type.TOptional<Type.TString>;
8
+ }>;
9
+ export interface GlobToolOptions {
10
+ securityConfig?: SecurityConfig;
11
+ securityContext?: SecurityRuntimeContext;
12
+ channelId?: string;
13
+ }
14
+ export declare function createGlobTool(fileStore: FileStore, options?: GlobToolOptions): AgentTool<typeof globSchema>;
15
+ export {};
@@ -0,0 +1,113 @@
1
+ import { join } from "node:path";
2
+ import { Type } from "typebox";
3
+ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
+ import { checkPathGuard } from "../security/path-guard-check.js";
5
+ import { RecoverableToolError } from "../shared/recoverable-error.js";
6
+ import { compileGlobPattern } from "./glob-match.js";
7
+ import { IGNORED_DIR_SEGMENTS } from "./ignore-dirs.js";
8
+ import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
9
+ /**
10
+ * Path discovery by glob pattern, over `FileStore.walkFiles` rather than a `find` shell-out: no
11
+ * GNU/BSD flag drift to worry about, and the walk (prune, entry cap) and the match/sort/format
12
+ * pipeline are both ours to bound. Complements `grep` (content search) — this tool never reads
13
+ * file bytes.
14
+ */
15
+ /** Hard bound on directory entries the walk itself will traverse, regardless of match count. */
16
+ const MAX_SCAN_ENTRIES = 50_000;
17
+ /** Matched files are only `stat`-ed (for mtime ordering) up to this many; beyond it, scan order stands. */
18
+ const MAX_STAT_FOR_SORT = 2_000;
19
+ /** Paths shown inline; matching `grep`'s FILE_PAGE_LIMIT order of magnitude for a discovery tool. */
20
+ const GLOB_MAX_RESULTS = 100;
21
+ const globSchema = Type.Object({
22
+ pattern: Type.String({
23
+ description: 'Glob pattern to match file paths against (e.g. "**/*.ts", "src/**/*.test.js"). A pattern with no "/" ' +
24
+ 'matches the basename at any depth, so "*" and "*.ts" both search the whole tree; include a "/" to anchor the depth.',
25
+ }),
26
+ path: Type.Optional(Type.String({ description: "Directory to search in. Defaults to the workspace/project root." })),
27
+ });
28
+ export function createGlobTool(fileStore, options = {}) {
29
+ const securityConfig = options.securityConfig ?? DEFAULT_SECURITY_CONFIG;
30
+ const securityContext = options.securityContext ?? {
31
+ agentWorkspaceDir: process.cwd(),
32
+ projectRoot: process.cwd(),
33
+ };
34
+ return {
35
+ name: "glob",
36
+ label: "glob",
37
+ description: "Find files whose paths match a glob pattern. Returns matching file paths only (never directories), " +
38
+ "including hidden files; VCS/build directories (node_modules, .git, dist, ...) are excluded. Prefer this " +
39
+ "over `bash find`/`ls -R` for path discovery — it is bounded and sorted by modification time (newest first) " +
40
+ `when few enough files match; up to ${GLOB_MAX_RESULTS} paths come back inline.`,
41
+ parameters: globSchema,
42
+ execute: async (_toolCallId, { pattern, path }, signal) => {
43
+ if (!pattern.trim()) {
44
+ throw new RecoverableToolError("Pattern must not be empty.");
45
+ }
46
+ const searchPath = path?.trim() || ".";
47
+ const target = await checkPathGuard(searchPath, "read", securityConfig, securityContext, {
48
+ tool: "glob",
49
+ channelId: options.channelId,
50
+ });
51
+ let matcher;
52
+ try {
53
+ matcher = compileGlobPattern(pattern);
54
+ }
55
+ catch {
56
+ throw new RecoverableToolError(`Invalid glob pattern: ${pattern}`);
57
+ }
58
+ const walk = await fileStore.walkFiles(target, {
59
+ maxEntries: MAX_SCAN_ENTRIES,
60
+ prune: (name) => IGNORED_DIR_SEGMENTS.has(name),
61
+ signal,
62
+ });
63
+ const matched = walk.files.filter((relativePath) => matcher.test(relativePath));
64
+ if (matched.length === 0) {
65
+ const scope = path ? `${searchPath}` : "the workspace";
66
+ const text = walk.truncated
67
+ ? `Scan of ${scope} hit the ${MAX_SCAN_ENTRIES.toLocaleString()}-file limit before any path matched "${pattern}". ` +
68
+ "Narrow path to a smaller subtree so the scan can complete."
69
+ : `No files matching "${pattern}" in ${scope}.`;
70
+ return { content: [{ type: "text", text }], details: { matchCount: 0 } };
71
+ }
72
+ const sortableByMtime = matched.length <= MAX_STAT_FOR_SORT;
73
+ let ordered;
74
+ if (sortableByMtime) {
75
+ const withMtime = [];
76
+ for (const relativePath of matched) {
77
+ const stat = await fileStore.stat(join(target, ...relativePath.split("/")));
78
+ withMtime.push({ relativePath, mtimeMs: stat?.mtimeMs ?? 0 });
79
+ }
80
+ withMtime.sort((a, b) => b.mtimeMs - a.mtimeMs);
81
+ ordered = withMtime.map((entry) => entry.relativePath);
82
+ }
83
+ else {
84
+ ordered = matched;
85
+ }
86
+ const page = ordered.slice(0, GLOB_MAX_RESULTS);
87
+ const footerParts = [];
88
+ if (ordered.length > page.length) {
89
+ footerParts.push(`Showing ${page.length} of ${ordered.length} matches${sortableByMtime ? ", newest first" : ""}. ` +
90
+ "Narrow the pattern, or pass path=<subdir>, to see the rest.");
91
+ }
92
+ else if (!sortableByMtime) {
93
+ footerParts.push(`${ordered.length} matches, in scan order (too many to sort by modification time).`);
94
+ }
95
+ if (walk.truncated) {
96
+ footerParts.push(`Scan stopped after ${MAX_SCAN_ENTRIES.toLocaleString()} files; results may be incomplete. Narrow path to search a smaller subtree.`);
97
+ }
98
+ const body = page.join("\n");
99
+ const truncation = truncateHead(body);
100
+ let outputText = truncation.content;
101
+ if (footerParts.length > 0) {
102
+ outputText += `\n\n[${footerParts.join(" ")}]`;
103
+ }
104
+ if (truncation.truncated) {
105
+ outputText += `\n\n[Output truncated at ${formatSize(DEFAULT_MAX_BYTES)}; narrow the pattern or path to see the rest.]`;
106
+ }
107
+ return {
108
+ content: [{ type: "text", text: outputText }],
109
+ details: { matchCount: ordered.length, shownCount: page.length, scanTruncated: walk.truncated },
110
+ };
111
+ },
112
+ };
113
+ }
@@ -3,7 +3,6 @@ import { Type } from "typebox";
3
3
  import type { Executor } from "../executor.js";
4
4
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
5
5
  declare const grepSchema: Type.TObject<{
6
- label: Type.TString;
7
6
  pattern: Type.TString;
8
7
  path: Type.TOptional<Type.TString>;
9
8
  glob: Type.TOptional<Type.TString>;
@@ -1,10 +1,10 @@
1
1
  import { Type } from "typebox";
2
2
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
3
- import { logSecurityEvent } from "../security/logger.js";
4
- import { guardPath } from "../security/path-guard.js";
3
+ import { checkPathGuard } from "../security/path-guard-check.js";
5
4
  import { RecoverableToolError } from "../shared/recoverable-error.js";
6
5
  import { shellEscape } from "../shared/shell-escape.js";
7
- import { DEFAULT_MAX_BYTES, truncateHead } from "./truncate.js";
6
+ import { IGNORED_DIR_SEGMENTS } from "./ignore-dirs.js";
7
+ import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
8
8
  /**
9
9
  * Structured content search over the filesystem. The execution layer is deliberately thin — one
10
10
  * `grep -rnH -B1 -A3` invocation through the shared Executor, with no native dependency. The value
@@ -20,10 +20,15 @@ const SINGLE_FILE_MATCHES = 200;
20
20
  /** Files shown per page; `skip` pages through the rest. */
21
21
  const FILE_PAGE_LIMIT = 20;
22
22
  const SEARCH_TIMEOUT_SECONDS = 30;
23
- /** Directories never worth scanning; filtered in JS since busybox grep lacks --exclude-dir. */
24
- const IGNORED_DIR_SEGMENTS = new Set(["node_modules", ".git", ".hg", ".svn", "dist", "build", ".next", ".cache"]);
23
+ /**
24
+ * Raw `grep` stdout capture cap (spec 044, D5.2). Bounded well under the executor's 10MB default so
25
+ * a broad search can never flood memory, and `ExecResult.stdoutTruncated` (D6.2) says honestly
26
+ * whether the cap was hit -- unlike piping through `head -n`, this leaves `result.code` as grep's
27
+ * own exit status, so a real `grep` error (bad regex, missing path) still surfaces as one instead
28
+ * of being masked by `head` exiting 0 regardless of what fed it.
29
+ */
30
+ const MAX_RAW_RESULT_BYTES = 768 * 1024;
25
31
  const grepSchema = Type.Object({
26
- label: Type.String({ description: "Brief description of what you're searching for and why (shown to user)" }),
27
32
  pattern: Type.String({ description: "Extended regular expression (ERE) to search for in file contents." }),
28
33
  path: Type.Optional(Type.String({ description: "File or directory to search. Defaults to the workspace root." })),
29
34
  glob: Type.Optional(Type.String({
@@ -32,16 +37,6 @@ const grepSchema = Type.Object({
32
37
  caseSensitive: Type.Optional(Type.Boolean({ description: "Case-sensitive match. Defaults to true." })),
33
38
  skip: Type.Optional(Type.Integer({ minimum: 0, description: "File-page offset for paging through many matching files." })),
34
39
  });
35
- function formatPathBlockMessage(resolvedPath, category, reason) {
36
- const lines = [`Path blocked${category ? ` [${category}]` : ""}`];
37
- if (reason) {
38
- lines.push(`Reason: ${reason}`);
39
- }
40
- if (resolvedPath) {
41
- lines.push(`Resolved path: ${resolvedPath}`);
42
- }
43
- return lines.join("\n");
44
- }
45
40
  /** Convert a simple `*`/`?` glob into an anchored regex matched against a basename. */
46
41
  function globToRegExp(glob) {
47
42
  const escaped = glob
@@ -150,36 +145,50 @@ export function createGrepTool(executor, options = {}) {
150
145
  throw new RecoverableToolError("Pattern must not be empty.");
151
146
  }
152
147
  const searchPath = path?.trim() || ".";
153
- if (securityConfig.enabled && securityConfig.pathGuard.enabled) {
154
- const guardResult = guardPath(searchPath, "read", { ...securityContext, config: securityConfig.pathGuard });
155
- if (!guardResult.allowed) {
156
- await logSecurityEvent(securityContext.agentWorkspaceDir, securityConfig, {
157
- type: "path",
158
- tool: "grep",
159
- channelId: options.channelId,
160
- rawPath: searchPath,
161
- operation: "read",
162
- resolvedPath: guardResult.resolvedPath,
163
- category: guardResult.category,
164
- reason: guardResult.reason,
165
- });
166
- throw new Error(formatPathBlockMessage(guardResult.resolvedPath, guardResult.category, guardResult.reason));
167
- }
168
- }
148
+ // Resolved once, then used for both the guard's judgment and the actual `grep` target
149
+ // (spec 044, D1.1): no separate `cwd` needed on the executor call, so there is no chance of
150
+ // the guard resolving against `projectRoot` while the shell actually runs against the
151
+ // daemon's own cwd (F6).
152
+ const target = await checkPathGuard(searchPath, "read", securityConfig, securityContext, {
153
+ tool: "grep",
154
+ channelId: options.channelId,
155
+ });
169
156
  const flags = ["-rnH", "-E", `-B${CONTEXT_BEFORE}`, `-A${CONTEXT_AFTER}`];
170
157
  if (caseSensitive === false) {
171
158
  flags.push("-i");
172
159
  }
173
- // `--` terminates flags so a pattern beginning with `-` is not read as one.
174
- const command = `grep ${flags.join(" ")} -- ${shellEscape(pattern)} ${shellEscape(searchPath)}`;
175
- const result = await executor.exec(command, { timeout: SEARCH_TIMEOUT_SECONDS, signal });
160
+ // Push directory and glob filters down into `grep` itself (D5.1) so a huge `node_modules`
161
+ // is never scanned in the first place, rather than being scanned, capped, and then
162
+ // filtered away in JS after it already ate the whole result budget (F7). The JS-side
163
+ // `isIgnoredPath`/`globRegExp` filtering below stays as a backstop for a `grep` whose
164
+ // `--exclude-dir` semantics differ.
165
+ for (const segment of IGNORED_DIR_SEGMENTS) {
166
+ flags.push(`--exclude-dir=${segment}`);
167
+ }
168
+ if (glob) {
169
+ flags.push(`--include=${glob}`);
170
+ }
171
+ // `--` terminates flags so a pattern beginning with `-` is not read as one. Bounded via
172
+ // `maxCaptureBytes` (D5.2) rather than a `| head -n` pipe: piping through `head` would
173
+ // have `sh -c` (no pipefail) report `head`'s exit status instead of grep's, silently
174
+ // masking a real grep error (bad regex, missing path) behind `head`'s always-0 exit.
175
+ const command = `grep ${flags.join(" ")} -- ${shellEscape(pattern)} ${shellEscape(target)}`;
176
+ const result = await executor.exec(command, {
177
+ timeout: SEARCH_TIMEOUT_SECONDS,
178
+ signal,
179
+ maxCaptureBytes: MAX_RAW_RESULT_BYTES,
180
+ });
176
181
  // grep exit code 1 = no matches (normal), 0 = matches, >=2 = error.
177
182
  if (result.code >= 2) {
178
183
  const stderr = result.stderr.trim();
179
184
  throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}. Check the regex (ERE syntax) and that the path exists.`);
180
185
  }
186
+ const rawTruncated = result.stdoutTruncated === true;
187
+ // A truncated capture may end mid-line; drop that dangling partial line rather than feed
188
+ // it to the parser, which expects each line to be a complete match or context line.
189
+ const boundedStdout = rawTruncated ? result.stdout.slice(0, result.stdout.lastIndexOf("\n")) : result.stdout;
181
190
  const globRegExp = glob ? globToRegExp(glob) : undefined;
182
- const parsed = parseGrepOutput(result.stdout);
191
+ const parsed = parseGrepOutput(boundedStdout);
183
192
  // Filter ignored dirs and (for directory scopes) the optional glob, on the basename.
184
193
  const files = [];
185
194
  for (const [file, entries] of parsed) {
@@ -197,13 +206,16 @@ export function createGrepTool(executor, options = {}) {
197
206
  }
198
207
  if (files.length === 0) {
199
208
  const scope = glob ? `${searchPath} (glob ${glob})` : searchPath;
209
+ // D5.3: a result set that hit the raw-line cap but still filtered down to nothing must
210
+ // not be reported as "no matches" -- that tells the model to try a *broader* search,
211
+ // which is exactly backwards when the real problem is that the cap was hit before
212
+ // filtering ever got a chance to keep anything.
213
+ const text = rawTruncated
214
+ ? `Search hit the ${formatSize(MAX_RAW_RESULT_BYTES)} raw result cap before any match survived filtering in ${scope}. ` +
215
+ "Narrow the path or pattern so fewer raw hits are needed."
216
+ : `No matches found in ${scope}. Try a broader pattern, drop the glob, or widen the path.`;
200
217
  return {
201
- content: [
202
- {
203
- type: "text",
204
- text: `No matches found in ${scope}. Try a broader pattern, drop the glob, or widen the path.`,
205
- },
206
- ],
218
+ content: [{ type: "text", text }],
207
219
  details: { matchCount: 0, fileCount: 0 },
208
220
  };
209
221
  }
@@ -240,6 +252,9 @@ export function createGrepTool(executor, options = {}) {
240
252
  if (moreFiles > 0) {
241
253
  footerLines.push(`[${moreFiles} more matching file(s). Use skip=${startOffset + page.length} for the next page.]`);
242
254
  }
255
+ if (rawTruncated) {
256
+ footerLines.push(`[Search hit the ${formatSize(MAX_RAW_RESULT_BYTES)} raw result cap; there may be matches beyond what's shown above. Narrow the path or pattern to see them.]`);
257
+ }
243
258
  const body = blocks.join("\n\n");
244
259
  const footer = footerLines.length > 0 ? `\n\n${footerLines.join("\n")}` : "";
245
260
  const truncation = truncateHead(body);
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Directory names that discovery/search tools should never descend into. Shared by `grep` (pushed
3
+ * down as `grep --exclude-dir=`) and `glob` (pushed down as a walk-time prune), so the two tools
4
+ * agree on what "noise" means instead of drifting independently.
5
+ */
6
+ export declare const IGNORED_DIR_SEGMENTS: Set<string>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Directory names that discovery/search tools should never descend into. Shared by `grep` (pushed
3
+ * down as `grep --exclude-dir=`) and `glob` (pushed down as a walk-time prune), so the two tools
4
+ * agree on what "noise" means instead of drifting independently.
5
+ */
6
+ export const IGNORED_DIR_SEGMENTS = new Set([
7
+ "node_modules",
8
+ ".git",
9
+ ".hg",
10
+ ".svn",
11
+ "dist",
12
+ "build",
13
+ ".next",
14
+ ".cache",
15
+ ]);
@@ -1,6 +1,7 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import type { Executor } from "../executor.js";
4
+ import type { FileStore } from "../file-store.js";
4
5
  import type { MemoryCandidateStore } from "../memory/candidates.js";
5
6
  import type { MediaSender } from "../runtime/channel-context.js";
6
7
  import type { ProjectScope } from "../security/project-scope.js";
@@ -10,6 +11,8 @@ import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
10
11
  import type { PipiclawToolsConfig } from "./config.js";
11
12
  export interface CreatePipiclawToolsOptions {
12
13
  executor: Executor;
14
+ /** File-content port for the generic file tools (spec 044, D1); `Executor` stays command-only. */
15
+ fileStore: FileStore;
13
16
  getCurrentModel: () => Model<Api>;
14
17
  getAvailableModels: () => Model<Api>[];
15
18
  resolveApiKey: (model: Model<Api>) => Promise<string>;
@@ -2,10 +2,10 @@ import { getChannelJobManager } from "../agent/job-manager.js";
2
2
  import { APP_HOME_DIR } from "../paths.js";
3
3
  import { loadSecurityConfig } from "../security/config.js";
4
4
  import { withSubAgentsDirWriteDeny } from "../subagents/discovery.js";
5
- import { createSubAgentTool } from "../subagents/tool.js";
5
+ import { createSubAgentInlineTool, createSubAgentTool } from "../subagents/tool.js";
6
6
  import { loadToolsConfig } from "./config.js";
7
7
  import { buildToolSet } from "./registry.js";
8
- import { createSubAgentManageTool } from "./subagent-manage.js";
8
+ import { createSubAgentListTool, createSubAgentRunTool } from "./subagent-manage.js";
9
9
  import { withToolDetails } from "./tool-details.js";
10
10
  export function createPipiclawTools(options) {
11
11
  // Spec 040, D8.1: the main agent's own write/edit tools can write a self-authorizing
@@ -27,6 +27,7 @@ export function createPipiclawTools(options) {
27
27
  // and keeping it out of the registry avoids a registry ↔ subagents/tool import cycle.
28
28
  const leafTools = buildToolSet({
29
29
  executor: options.executor,
30
+ fileStore: options.fileStore,
30
31
  securityConfig,
31
32
  securityContext,
32
33
  channelId: options.channelId,
@@ -43,47 +44,56 @@ export function createPipiclawTools(options) {
43
44
  memoryCandidateStore: options.memoryCandidateStore,
44
45
  mediaSender: options.mediaSender,
45
46
  });
47
+ const subAgentToolOptions = {
48
+ executor: options.executor,
49
+ fileStore: options.fileStore,
50
+ getCurrentModel: options.getCurrentModel,
51
+ getAvailableModels: options.getAvailableModels,
52
+ resolveApiKey: options.resolveApiKey,
53
+ workspaceDir: options.workspaceDir,
54
+ // D6.2: an internal sub-agent defaults to the parent's ProjectRoot; a model-requested
55
+ // explicit workingDirectory is validated (in subagents/tool.ts) to stay within it.
56
+ workingDirectory: options.projectScope.projectRoot,
57
+ projectBoundary: options.projectScope.boundary,
58
+ channelDir: options.channelDir,
59
+ getSubAgentDiscovery: options.getSubAgentDiscovery,
60
+ getMemoryRecallSettings: options.getMemoryRecallSettings,
61
+ getSubAgentModelReference: options.getSubAgentModelReference,
62
+ memoryCandidateStore: options.memoryCandidateStore,
63
+ securityConfig,
64
+ webConfig: toolsConfig.tools.web,
65
+ rtkEnabled: toolsConfig.tools.rtk.enabled,
66
+ runtimeContext: {
67
+ workspaceDir: options.workspaceDir,
68
+ channelId: options.channelId,
69
+ },
70
+ };
71
+ const subAgentManageOptions = {
72
+ channelId: options.channelId,
73
+ channelDir: options.channelDir,
74
+ getSubAgentDiscovery: options.getSubAgentDiscovery,
75
+ workspaceDir: options.workspaceDir,
76
+ workingDirectory: options.projectScope.projectRoot,
77
+ projectBoundary: options.projectScope.boundary,
78
+ securityConfig,
79
+ // Spec 042 D7: follow_up builds its envelope through the same buildContextualBlocks
80
+ // the initial dispatch uses, which needs these to resolve a memory: relevant recall.
81
+ getCurrentModel: options.getCurrentModel,
82
+ resolveApiKey: options.resolveApiKey,
83
+ getMemoryRecallSettings: options.getMemoryRecallSettings,
84
+ memoryCandidateStore: options.memoryCandidateStore,
85
+ };
46
86
  return [
47
87
  ...leafTools,
48
88
  // Bound to the same `details` contract as the registry's tools; it is registered here
49
89
  // rather than in TOOL_REGISTRY only to avoid a registry ↔ subagents/tool import cycle.
50
- withToolDetails(createSubAgentTool({
51
- executor: options.executor,
52
- getCurrentModel: options.getCurrentModel,
53
- getAvailableModels: options.getAvailableModels,
54
- resolveApiKey: options.resolveApiKey,
55
- workspaceDir: options.workspaceDir,
56
- // D6.2: an internal sub-agent defaults to the parent's ProjectRoot; a model-requested
57
- // explicit workingDirectory is validated (in subagents/tool.ts) to stay within it.
58
- workingDirectory: options.projectScope.projectRoot,
59
- projectBoundary: options.projectScope.boundary,
60
- channelDir: options.channelDir,
61
- getSubAgentDiscovery: options.getSubAgentDiscovery,
62
- getMemoryRecallSettings: options.getMemoryRecallSettings,
63
- getSubAgentModelReference: options.getSubAgentModelReference,
64
- memoryCandidateStore: options.memoryCandidateStore,
65
- securityConfig,
66
- webConfig: toolsConfig.tools.web,
67
- rtkEnabled: toolsConfig.tools.rtk.enabled,
68
- runtimeContext: {
69
- workspaceDir: options.workspaceDir,
70
- channelId: options.channelId,
71
- },
72
- }), "subagent"),
73
- withToolDetails(createSubAgentManageTool({
74
- channelId: options.channelId,
75
- channelDir: options.channelDir,
76
- getSubAgentDiscovery: options.getSubAgentDiscovery,
77
- workspaceDir: options.workspaceDir,
78
- workingDirectory: options.projectScope.projectRoot,
79
- projectBoundary: options.projectScope.boundary,
80
- securityConfig,
81
- // Spec 042 D7: follow_up builds its envelope through the same buildContextualBlocks
82
- // the initial dispatch uses, which needs these to resolve a memory: relevant recall.
83
- getCurrentModel: options.getCurrentModel,
84
- resolveApiKey: options.resolveApiKey,
85
- getMemoryRecallSettings: options.getMemoryRecallSettings,
86
- memoryCandidateStore: options.memoryCandidateStore,
87
- }), "subagent_manage"),
90
+ withToolDetails(createSubAgentTool(subAgentToolOptions), "subagent"),
91
+ // Spec 046, D2.3: gated by `tools.json` (deployer decision, not a model-visible field) —
92
+ // omitted from the tool set entirely when off, not merely rejected at call time.
93
+ ...(toolsConfig.tools.subagentInline.enabled
94
+ ? [withToolDetails(createSubAgentInlineTool(subAgentToolOptions), "subagent_inline")]
95
+ : []),
96
+ withToolDetails(createSubAgentListTool(subAgentManageOptions), "subagent_list"),
97
+ withToolDetails(createSubAgentRunTool(subAgentManageOptions), "subagent_run"),
88
98
  ];
89
99
  }
@@ -2,7 +2,6 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
3
  import type { ChannelJobManager } from "../agent/job-manager.js";
4
4
  declare const jobSchema: Type.TObject<{
5
- label: Type.TString;
6
5
  op: Type.TUnion<[Type.TLiteral<"list">, Type.TLiteral<"poll">, Type.TLiteral<"cancel">]>;
7
6
  ids: Type.TOptional<Type.TArray<Type.TString>>;
8
7
  }>;
package/dist/tools/job.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Type } from "typebox";
2
+ import { formatDuration } from "../shared/duration.js";
2
3
  import { RecoverableToolError } from "../shared/recoverable-error.js";
3
4
  import { truncateTail } from "./truncate.js";
4
5
  const jobSchema = Type.Object({
5
- label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
6
6
  op: Type.Union([Type.Literal("list"), Type.Literal("poll"), Type.Literal("cancel")], {
7
7
  description: '"list" a snapshot of background jobs, "poll" to wait (briefly) for one to finish, or "cancel" jobs by id.',
8
8
  }),
@@ -10,13 +10,6 @@ const jobSchema = Type.Object({
10
10
  description: "Job ids for poll/cancel. For poll, omit to watch all running jobs.",
11
11
  })),
12
12
  });
13
- function formatDuration(ms) {
14
- const seconds = Math.round(ms / 1000);
15
- if (seconds < 60) {
16
- return `${seconds}s`;
17
- }
18
- return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
19
- }
20
13
  function formatJobLine(job) {
21
14
  const exit = job.exitCode !== undefined ? `, exit ${job.exitCode}` : "";
22
15
  return `- [${job.id}] ${job.label} — ${job.status} (${formatDuration(job.durationMs)}${exit})`;
@@ -0,0 +1,16 @@
1
+ import type { FileStat, FileStore } from "../file-store.js";
2
+ /** Only for tests: line-index state must not leak between unrelated test files sharing a path. */
3
+ export declare function clearLineIndexCacheForTests(): void;
4
+ export interface LineOffsetResult {
5
+ /** Byte offset where `line` starts, or `undefined` if the index has not reached that line (yet, or ever). */
6
+ offset: number | undefined;
7
+ /** Whether the index has scanned to EOF -- `knownLines` is exact only when this is true. */
8
+ eof: boolean;
9
+ /** Lines discovered so far. Exact total when `eof`; otherwise a lower bound (D4.3: "of >= N"). */
10
+ knownLines: number;
11
+ }
12
+ /**
13
+ * Resolve the byte offset of `line` (1-indexed), scanning forward from wherever this file's index
14
+ * last left off. Never re-scans bytes already indexed.
15
+ */
16
+ export declare function resolveLineOffset(fileStore: FileStore, path: string, stat: FileStat, line: number, signal?: AbortSignal): Promise<LineOffsetResult>;
@@ -0,0 +1,76 @@
1
+ const CACHE_CAPACITY = 32;
2
+ const SCAN_CHUNK_BYTES = 256 * 1024;
3
+ class LineIndexLru {
4
+ constructor() {
5
+ this.map = new Map();
6
+ }
7
+ get(key) {
8
+ const value = this.map.get(key);
9
+ if (value) {
10
+ this.map.delete(key);
11
+ this.map.set(key, value);
12
+ }
13
+ return value;
14
+ }
15
+ set(key, value) {
16
+ this.map.delete(key);
17
+ this.map.set(key, value);
18
+ if (this.map.size > CACHE_CAPACITY) {
19
+ const oldest = this.map.keys().next().value;
20
+ if (oldest !== undefined) {
21
+ this.map.delete(oldest);
22
+ }
23
+ }
24
+ }
25
+ clear() {
26
+ this.map.clear();
27
+ }
28
+ }
29
+ const cache = new LineIndexLru();
30
+ function cacheKey(path, stat) {
31
+ return `${path}\0${stat.size}\0${stat.mtimeMs}`;
32
+ }
33
+ /** Only for tests: line-index state must not leak between unrelated test files sharing a path. */
34
+ export function clearLineIndexCacheForTests() {
35
+ cache.clear();
36
+ }
37
+ /**
38
+ * Resolve the byte offset of `line` (1-indexed), scanning forward from wherever this file's index
39
+ * last left off. Never re-scans bytes already indexed.
40
+ */
41
+ export async function resolveLineOffset(fileStore, path, stat, line, signal) {
42
+ const key = cacheKey(path, stat);
43
+ let entry = cache.get(key);
44
+ if (!entry) {
45
+ entry = { lineOffsets: [0], scannedBytes: 0, eof: stat.size === 0 };
46
+ cache.set(key, entry);
47
+ }
48
+ while (entry.lineOffsets.length < line && !entry.eof) {
49
+ const { data, eof } = await fileStore.readBytes(path, {
50
+ start: entry.scannedBytes,
51
+ maxBytes: SCAN_CHUNK_BYTES,
52
+ signal,
53
+ });
54
+ for (let i = 0; i < data.length; i++) {
55
+ if (data[i] === 0x0a) {
56
+ entry.lineOffsets.push(entry.scannedBytes + i + 1);
57
+ }
58
+ }
59
+ entry.scannedBytes += data.length;
60
+ if (eof) {
61
+ entry.eof = true;
62
+ }
63
+ if (data.length === 0) {
64
+ break; // Defensive: readBytes returned nothing without reporting eof.
65
+ }
66
+ }
67
+ const lastOffset = entry.lineOffsets[entry.lineOffsets.length - 1];
68
+ // A file ending exactly on a newline should not count a phantom empty final line -- mirrors
69
+ // the old `content.endsWith("\n") ? lines.length - 1 : lines.length` in truncate.ts's caller.
70
+ // Once `eof` is reached, that phantom entry (if any) is also not a valid *offset* to resolve --
71
+ // asking for line N+1 of an N-line file must report out of bounds, not silently hand back EOF.
72
+ const knownLines = entry.eof && lastOffset === stat.size ? entry.lineOffsets.length - 1 : entry.lineOffsets.length;
73
+ const resolvableLines = entry.eof ? knownLines : entry.lineOffsets.length;
74
+ const offset = line <= resolvableLines ? entry.lineOffsets[line - 1] : undefined;
75
+ return { offset, eof: entry.eof, knownLines };
76
+ }
@@ -3,15 +3,25 @@ import type { Api, Model } from "@earendil-works/pi-ai";
3
3
  import { Type } from "typebox";
4
4
  import type { MemoryCandidateStore } from "../memory/candidates.js";
5
5
  import { type ChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
6
- declare const memoryManageSchema: Type.TObject<{
7
- label: Type.TString;
8
- op: Type.TUnion<[Type.TLiteral<"save">, Type.TLiteral<"search">, Type.TLiteral<"forget">]>;
9
- content: Type.TOptional<Type.TString>;
10
- query: Type.TOptional<Type.TString>;
11
- target: Type.TOptional<Type.TString>;
12
- kind: Type.TOptional<Type.TUnion<[Type.TLiteral<"preference">, Type.TLiteral<"fact">, Type.TLiteral<"decision">, Type.TLiteral<"constraint">, Type.TLiteral<"open-loop">, Type.TLiteral<"lesson">]>>;
6
+ /**
7
+ * Spec 047, P4: the old single `memory_manage` routed three fully disjoint payloads through an
8
+ * `op` enum. Splitting into one tool per payload shape drops the `op` routing prose and the
9
+ * "Required for save:" prefixes, and lets each op's one required field be schema-required
10
+ * instead of `Type.Optional` + a hand-rolled `rejectMissingArgument`. The streamed-argument
11
+ * truncation that `rejectMissingArgument` guarded against (M-write-03) is now caught by the SDK
12
+ * validator before `execute`; spec 047 D4.2 makes that rejection surface as a recoverable
13
+ * rejection rather than a user-visible error.
14
+ */
15
+ declare const memorySaveSchema: Type.TObject<{
16
+ content: Type.TString;
13
17
  supersedes: Type.TOptional<Type.TString>;
14
18
  }>;
19
+ declare const memorySearchSchema: Type.TObject<{
20
+ query: Type.TString;
21
+ }>;
22
+ declare const memoryForgetSchema: Type.TObject<{
23
+ target: Type.TString;
24
+ }>;
15
25
  export interface MemoryManageToolOptions {
16
26
  channelId: string;
17
27
  channelDir: string;
@@ -21,5 +31,7 @@ export interface MemoryManageToolOptions {
21
31
  resolveApiKey: (model: Model<Api>) => Promise<string>;
22
32
  channelMemoryQueue?: ChannelMemoryQueue;
23
33
  }
24
- export declare function createMemoryManageTool(options: MemoryManageToolOptions): AgentTool<typeof memoryManageSchema>;
34
+ export declare function createMemorySaveTool(options: MemoryManageToolOptions): AgentTool<typeof memorySaveSchema>;
35
+ export declare function createMemorySearchTool(options: MemoryManageToolOptions): AgentTool<typeof memorySearchSchema>;
36
+ export declare function createMemoryForgetTool(options: MemoryManageToolOptions): AgentTool<typeof memoryForgetSchema>;
25
37
  export {};