@oyasmi/pipiclaw 0.9.3-beta.2 → 0.9.3-beta.4

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 (148) hide show
  1. package/dist/agent/channel-runner.d.ts +4 -18
  2. package/dist/agent/channel-runner.js +25 -120
  3. package/dist/agent/context-budget.js +1 -1
  4. package/dist/agent/job-manager.d.ts +20 -17
  5. package/dist/agent/job-manager.js +95 -70
  6. package/dist/agent/prompt/builder.d.ts +1 -1
  7. package/dist/agent/prompt/builder.js +2 -18
  8. package/dist/agent/prompt/manifest.d.ts +0 -1
  9. package/dist/agent/prompt/manifest.js +2 -2
  10. package/dist/agent/prompt/sections.js +3 -12
  11. package/dist/agent/prompt/types.d.ts +2 -18
  12. package/dist/agent/prompt/types.js +1 -1
  13. package/dist/agent/runner-factory.d.ts +4 -0
  14. package/dist/agent/session-adapter.d.ts +19 -0
  15. package/dist/agent/session-adapter.js +77 -0
  16. package/dist/app-services.d.ts +18 -0
  17. package/dist/app-services.js +43 -0
  18. package/dist/{runtime → events}/events.d.ts +1 -1
  19. package/dist/executor.d.ts +5 -1
  20. package/dist/executor.js +35 -5
  21. package/dist/file-store.d.ts +4 -1
  22. package/dist/file-store.js +5 -0
  23. package/dist/memory/journal.d.ts +13 -0
  24. package/dist/memory/journal.js +47 -4
  25. package/dist/memory/maintenance-gates.d.ts +0 -3
  26. package/dist/memory/maintenance-gates.js +2 -2
  27. package/dist/memory/maintenance-migration.d.ts +5 -0
  28. package/dist/memory/maintenance-migration.js +91 -0
  29. package/dist/memory/maintenance-state.js +5 -44
  30. package/dist/memory/migrate.js +1 -1
  31. package/dist/memory/reflect-job.d.ts +1 -9
  32. package/dist/memory/reflect-job.js +1 -3
  33. package/dist/memory/reflect.js +1 -1
  34. package/dist/memory/search.js +13 -6
  35. package/dist/memory/session-corpus.d.ts +11 -0
  36. package/dist/memory/session-corpus.js +16 -5
  37. package/dist/memory/session-search.d.ts +3 -0
  38. package/dist/memory/session-search.js +45 -8
  39. package/dist/memory/store.d.ts +9 -0
  40. package/dist/memory/store.js +26 -3
  41. package/dist/models/auth-cli.js +1 -1
  42. package/dist/playbooks/agent-delegation.md +35 -76
  43. package/dist/playbooks/background-jobs.md +14 -16
  44. package/dist/playbooks/event-scheduling.md +20 -25
  45. package/dist/playbooks/memory-and-learning.md +28 -61
  46. package/dist/playbooks/outbound-media.md +10 -12
  47. package/dist/playbooks/runtime-orientation.md +34 -53
  48. package/dist/playbooks/task-loop.md +49 -69
  49. package/dist/runtime/bootstrap.d.ts +5 -15
  50. package/dist/runtime/bootstrap.js +57 -67
  51. package/dist/runtime/subagent-commands.d.ts +2 -1
  52. package/dist/runtime/subagent-commands.js +10 -12
  53. package/dist/runtime/task-wake.d.ts +4 -5
  54. package/dist/runtime/task-wake.js +2 -12
  55. package/dist/security/path-guard-filter.d.ts +22 -0
  56. package/dist/security/path-guard-filter.js +35 -0
  57. package/dist/security/types.d.ts +7 -0
  58. package/dist/security/types.js +16 -1
  59. package/dist/settings.d.ts +8 -0
  60. package/dist/settings.js +24 -1
  61. package/dist/shared/exact-keys.d.ts +13 -0
  62. package/dist/shared/exact-keys.js +1 -0
  63. package/dist/shared/format.d.ts +20 -0
  64. package/dist/shared/format.js +64 -0
  65. package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
  66. package/dist/shared/{fs-utils.js → os.js} +8 -0
  67. package/dist/subagents/discovery.d.ts +18 -6
  68. package/dist/subagents/discovery.js +12 -8
  69. package/dist/subagents/external/run.d.ts +2 -1
  70. package/dist/subagents/external/run.js +1 -2
  71. package/dist/subagents/external/settlement.js +10 -5
  72. package/dist/subagents/format.d.ts +1 -1
  73. package/dist/subagents/format.js +1 -1
  74. package/dist/subagents/runs.d.ts +13 -12
  75. package/dist/subagents/runs.js +108 -89
  76. package/dist/subagents/tool.d.ts +13 -7
  77. package/dist/subagents/tool.js +21 -13
  78. package/dist/tasks/brief.d.ts +1 -1
  79. package/dist/tasks/brief.js +12 -2
  80. package/dist/tasks/log.d.ts +4 -0
  81. package/dist/tasks/log.js +13 -1
  82. package/dist/tools/bash.d.ts +13 -0
  83. package/dist/tools/bash.js +123 -20
  84. package/dist/tools/command-optimizer.js +1 -1
  85. package/dist/tools/config.d.ts +7 -0
  86. package/dist/tools/config.js +16 -1
  87. package/dist/tools/edit.js +36 -5
  88. package/dist/tools/event-manage.d.ts +26 -5
  89. package/dist/tools/event-manage.js +84 -36
  90. package/dist/tools/glob.js +57 -4
  91. package/dist/tools/grep.d.ts +2 -0
  92. package/dist/tools/grep.js +188 -15
  93. package/dist/tools/index.d.ts +4 -0
  94. package/dist/tools/index.js +4 -2
  95. package/dist/tools/job.js +17 -5
  96. package/dist/tools/memory-manage.js +80 -41
  97. package/dist/tools/read.js +43 -6
  98. package/dist/tools/registry.d.ts +9 -3
  99. package/dist/tools/registry.js +22 -57
  100. package/dist/tools/send-media.js +6 -4
  101. package/dist/tools/session-search.js +4 -1
  102. package/dist/tools/skill.d.ts +2 -0
  103. package/dist/tools/skill.js +13 -1
  104. package/dist/tools/subagent-manage.d.ts +2 -0
  105. package/dist/tools/subagent-manage.js +8 -8
  106. package/dist/tools/subagent-tool-names.d.ts +11 -0
  107. package/dist/tools/subagent-tool-names.js +19 -0
  108. package/dist/tools/task-manage/log-view.js +6 -3
  109. package/dist/tools/task-manage/schema.d.ts +6 -6
  110. package/dist/tools/task-manage/schema.js +5 -12
  111. package/dist/tools/task-manage/shared.js +20 -11
  112. package/dist/tools/task-manage/step-end.js +22 -5
  113. package/dist/tools/task-manage/types.d.ts +4 -0
  114. package/dist/tools/task-manage.js +9 -1
  115. package/dist/tools/web-cache.d.ts +11 -3
  116. package/dist/tools/web-cache.js +26 -8
  117. package/dist/tools/web-fetch.d.ts +1 -0
  118. package/dist/tools/web-fetch.js +68 -15
  119. package/dist/tools/write.js +3 -0
  120. package/dist/tui/app.js +22 -7
  121. package/dist/web/config.js +1 -1
  122. package/dist/web/fetch.d.ts +5 -0
  123. package/dist/web/fetch.js +36 -1
  124. package/examples/sub-agents/README.md +14 -4
  125. package/examples/sub-agents/builder-hard.md +12 -34
  126. package/examples/sub-agents/builder.md +11 -31
  127. package/examples/sub-agents/explorer.md +10 -16
  128. package/examples/sub-agents/git-committer.md +15 -20
  129. package/examples/sub-agents/planner.md +11 -21
  130. package/examples/sub-agents/reviewer.md +10 -31
  131. package/examples/sub-agents/verifier.md +12 -27
  132. package/examples/sub-agents/worker.md +11 -35
  133. package/package.json +8 -3
  134. package/dist/shared/duration.d.ts +0 -2
  135. package/dist/shared/duration.js +0 -7
  136. package/dist/shared/file-stamp.d.ts +0 -10
  137. package/dist/shared/file-stamp.js +0 -19
  138. package/dist/shared/numeric.d.ts +0 -7
  139. package/dist/shared/numeric.js +0 -19
  140. package/dist/shared/shell-escape.d.ts +0 -5
  141. package/dist/shared/shell-escape.js +0 -7
  142. package/dist/shared/token-estimate.d.ts +0 -1
  143. package/dist/shared/token-estimate.js +0 -19
  144. /package/dist/{runtime → events}/event-commands.d.ts +0 -0
  145. /package/dist/{runtime → events}/event-commands.js +0 -0
  146. /package/dist/{runtime → events}/event-validation.d.ts +0 -0
  147. /package/dist/{runtime → events}/event-validation.js +0 -0
  148. /package/dist/{runtime → events}/events.js +0 -0
@@ -1,4 +1,3 @@
1
- import { getChannelJobManager } from "../agent/job-manager.js";
2
1
  import { APP_HOME_DIR } from "../paths.js";
3
2
  import { loadSecurityConfig } from "../security/config.js";
4
3
  import { withSubAgentsDirWriteDeny } from "../subagents/discovery.js";
@@ -37,7 +36,8 @@ export function createPipiclawTools(options) {
37
36
  webConfig: toolsConfig.tools.web,
38
37
  toolsConfig,
39
38
  rtkEnabled: toolsConfig.tools.rtk.enabled,
40
- jobManager: getChannelJobManager(options.channelId, options.executor),
39
+ jobManager: options.jobManager,
40
+ runManager: options.runManager,
41
41
  getCurrentModel: options.getCurrentModel,
42
42
  getAvailableModels: options.getAvailableModels,
43
43
  resolveApiKey: options.resolveApiKey,
@@ -47,6 +47,7 @@ export function createPipiclawTools(options) {
47
47
  getToolsUsed: options.getToolsUsed,
48
48
  });
49
49
  const subAgentToolOptions = {
50
+ getRunManager: () => options.runManager,
50
51
  executor: options.executor,
51
52
  fileStore: options.fileStore,
52
53
  getCurrentModel: options.getCurrentModel,
@@ -69,6 +70,7 @@ export function createPipiclawTools(options) {
69
70
  },
70
71
  };
71
72
  const subAgentManageOptions = {
73
+ runManager: options.runManager,
72
74
  channelId: options.channelId,
73
75
  channelDir: options.channelDir,
74
76
  getSubAgentDiscovery: options.getSubAgentDiscovery,
package/dist/tools/job.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Type } from "typebox";
2
- import { formatDuration } from "../shared/duration.js";
2
+ import { formatDuration } from "../shared/format.js";
3
3
  import { RecoverableToolError } from "../shared/recoverable-error.js";
4
4
  import { truncateTail } from "./truncate.js";
5
5
  const jobSchema = Type.Object({
@@ -7,9 +7,12 @@ const jobSchema = Type.Object({
7
7
  description: '"list" a snapshot of background jobs, "poll" to wait (briefly) for one to finish, or "cancel" jobs by id.',
8
8
  }),
9
9
  ids: Type.Optional(Type.Array(Type.String(), {
10
- description: "Job ids for poll/cancel. For poll, omit to watch all running jobs.",
10
+ description: "Job ids for poll/cancel. For poll, omit to watch every job running when the call starts " +
11
+ "(a job started later is not folded into that same poll).",
11
12
  })),
12
13
  });
14
+ /** Total bytes of job output `op=poll` inlines across all finished jobs in one call. */
15
+ const COMPLETED_DETAIL_TOTAL_BUDGET = 96 * 1024;
13
16
  function formatJobLine(job) {
14
17
  const exit = job.exitCode !== undefined ? `, exit ${job.exitCode}` : "";
15
18
  return `- [${job.id}] ${job.label} — ${job.status} (${formatDuration(job.durationMs)}${exit})`;
@@ -18,12 +21,21 @@ export function createJobTool(options) {
18
21
  const { jobManager } = options;
19
22
  async function completedDetail(jobs) {
20
23
  const sections = [];
24
+ let spent = 0;
21
25
  for (const job of jobs) {
26
+ const header = `### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}`;
22
27
  const output = await jobManager.readOutput(job.id);
28
+ // Total budget across all finished jobs in one poll: 5 jobs × the 50KB per-job tail would
29
+ // otherwise be 250KB of context. Once spent, later jobs get a header + a pointer only.
30
+ if (spent >= COMPLETED_DETAIL_TOTAL_BUDGET) {
31
+ sections.push(`${header}\n(output omitted to stay within budget — run \`job op=poll ids=["${job.id}"]\` for it)${output ? `\nFull output: ${output.spillFile}` : ""}`);
32
+ continue;
33
+ }
23
34
  const tail = output ? truncateTail(output.text).content : "";
24
35
  const body = tail.trim() ? tail : "(no output)";
25
36
  const path = output ? `\nFull output: ${output.spillFile}` : "";
26
- sections.push(`### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}\n${body}${path}`);
37
+ spent += Buffer.byteLength(body, "utf-8");
38
+ sections.push(`${header}\n${body}${path}`);
27
39
  }
28
40
  return sections;
29
41
  }
@@ -32,7 +44,7 @@ export function createJobTool(options) {
32
44
  label: "job",
33
45
  description: "Inspect and control background bash jobs (started with bash async:true). op=list shows a snapshot; " +
34
46
  "op=poll waits briefly for a running job to finish and returns its output; op=cancel stops jobs by id. " +
35
- "A finished job wakes this channel by itself, so never schedule a check-in for one — end the turn instead.",
47
+ "Completion wakes this channel; finish independent work, then end the turn when only waiting remains.",
36
48
  parameters: jobSchema,
37
49
  execute: async (_toolCallId, { op, ids }, signal) => {
38
50
  if (op === "cancel") {
@@ -75,7 +87,7 @@ export function createJobTool(options) {
75
87
  }
76
88
  if (running.length > 0) {
77
89
  parts.push(`## Still running (${running.length})`, ...running.map(formatJobLine));
78
- parts.push("Poll again to keep waiting, or just end your turn — you are woken when the job finishes.");
90
+ parts.push("Finish independent work, then end the turn; completion wakes this channel. Do not loop on poll.");
79
91
  }
80
92
  return {
81
93
  content: [{ type: "text", text: parts.join("\n\n") }],
@@ -3,6 +3,7 @@ import { join } from "node:path";
3
3
  import { Type } from "typebox";
4
4
  import * as log from "../log.js";
5
5
  import { getDefaultChannelMemoryQueue } from "../memory/channel-maintenance-queue.js";
6
+ import { readJournalForSearch } from "../memory/journal.js";
6
7
  import { appendMemoryReviewLog } from "../memory/review-log.js";
7
8
  import { findNearDuplicateEntries, searchMemory } from "../memory/search.js";
8
9
  import { containsSecret } from "../memory/secret-redaction.js";
@@ -32,7 +33,7 @@ const memorySaveSchema = Type.Object({
32
33
  });
33
34
  const memorySearchSchema = Type.Object({
34
35
  query: Type.String({
35
- description: "What to look for across this channel's memory, journal, and workspace MEMORY.md.",
36
+ description: "What to look for across this channel's memory, recent journal files, and workspace MEMORY.md.",
36
37
  }),
37
38
  });
38
39
  const memoryForgetSchema = Type.Object({
@@ -64,73 +65,111 @@ function buildMemoryClosures(options) {
64
65
  if (args.name && !isValidMemoryName(args.name)) {
65
66
  throw new RecoverableToolError(`"${args.name}" is not a valid memory name. Use lowercase letters, digits, and hyphens only (e.g. deploy-window-thursday).`);
66
67
  }
67
- const entries = await listMemoryEntries(options.channelDir);
68
- if (!args.replaces) {
69
- const similar = findNearDuplicateEntries(content, entries);
70
- if (similar.length > 0) {
71
- throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
72
- similar.map((entry) => `- ${entry.name}: ${entry.description}`).join("\n") +
73
- '\nRe-issue the save with "replaces" set to the name this replaces, or to "none" if both facts are true at once.');
74
- }
75
- }
76
68
  const replaces = args.replaces && args.replaces !== "none" ? args.replaces : undefined;
77
- const result = await queue.run(options.channelId, () => applyMemoryOps(options.channelDir, [
78
- replaces
79
- ? {
80
- op: "update",
81
- name: replaces,
82
- description: content,
83
- type: args.type,
84
- details: args.details,
85
- expires: null,
69
+ // The near-duplicate judgment ("read existing facts → decide → write") has to run inside the
70
+ // same per-channel critical section as the write, or two concurrent saves of the same fact
71
+ // each see "no duplicate" and both add it. A `null` return means "blocked by near-duplicates,
72
+ // nothing written".
73
+ let similar = [];
74
+ const result = await queue.run(options.channelId, async () => {
75
+ // `replaces: "none"` is an explicit "both facts are true, keep both" waiver, so it skips
76
+ // the near-duplicate gate just like naming a real target does.
77
+ if (!args.replaces) {
78
+ const existing = await listMemoryEntries(options.channelDir);
79
+ const near = findNearDuplicateEntries(content, existing);
80
+ if (near.length > 0) {
81
+ similar = near;
82
+ return null;
86
83
  }
87
- : {
88
- op: "add",
89
- description: content,
90
- source: "user",
91
- name: args.name,
92
- type: args.type ?? "project",
93
- details: args.details,
94
- },
95
- ]));
84
+ }
85
+ return applyMemoryOps(options.channelDir, [
86
+ replaces
87
+ ? {
88
+ op: "update",
89
+ name: replaces,
90
+ description: content,
91
+ type: args.type,
92
+ details: args.details,
93
+ expires: null,
94
+ }
95
+ : {
96
+ op: "add",
97
+ description: content,
98
+ source: "user",
99
+ name: args.name,
100
+ type: args.type ?? "project",
101
+ details: args.details,
102
+ },
103
+ ]);
104
+ });
105
+ if (result === null) {
106
+ throw new RecoverableToolError(`Nothing was saved yet. This channel already stores ${similar.length} similar entr${similar.length === 1 ? "y" : "ies"}:\n` +
107
+ similar.map((entry) => `- ${entry.name}: ${entry.description}`).join("\n") +
108
+ '\nRe-issue the save with "replaces" set to the name this replaces, or to "none" if both facts are true at once.');
109
+ }
96
110
  if (replaces && result.updated.length === 0 && result.missingTarget > 0) {
97
111
  throw new RecoverableToolError(`No memory named "${replaces}" exists in this channel. Check the name, or omit "replaces" to save a new entry.`);
98
112
  }
99
- await appendMemoryReviewLog(options.channelDir, {
113
+ // Report what actually landed on disk — never a name for an entry that was not written.
114
+ // The old code read `replaces ?? result.added[0]` unconditionally, so a skipped add
115
+ // rendered "Saved ... as `undefined`." and told the user a lie the model could not see.
116
+ if (replaces) {
117
+ await logMemorySave(options, replaces, "update");
118
+ return textResult(`Replaced channel memory \`${replaces}\`.`, { saved: true, name: replaces });
119
+ }
120
+ const addedName = result.added[0];
121
+ if (addedName) {
122
+ await logMemorySave(options, addedName, "add");
123
+ return textResult(`Saved to channel memory as \`${addedName}\`.`, { saved: true, name: addedName });
124
+ }
125
+ if (result.skippedSecret > 0) {
126
+ return textResult("Not saved: the content still reads as a credential or secret after the first check. Store the secret itself in an approved secret manager and save only a pointer to it here.", { saved: false, blockedReason: "secret" });
127
+ }
128
+ if (result.skippedTombstone > 0) {
129
+ return textResult(`Not saved: "${content}" was explicitly forgotten in this channel and is still tombstoned. ` +
130
+ "Confirm with the user that they want it back, then re-save (an explicit user save is allowed through), or reword it so it is not byte-for-byte the forgotten fact.", { saved: false, blockedReason: "tombstone" });
131
+ }
132
+ return textResult("Not saved, and the store reported no specific reason (it may already be stored under another entry). " +
133
+ "Run memory_search for this fact before trying again.", { saved: false, blockedReason: "unknown" });
134
+ }
135
+ async function logMemorySave(opts, name, op) {
136
+ await appendMemoryReviewLog(opts.channelDir, {
100
137
  timestamp: new Date().toISOString(),
101
- channelId: options.channelId,
138
+ channelId: opts.channelId,
102
139
  reason: "memory-save",
103
- actions: [{ op: replaces ? "update" : "add", name: replaces ?? result.added[0] }],
140
+ actions: [{ op, name }],
104
141
  }).catch(() => { });
105
- const savedName = replaces ?? result.added[0];
106
- return textResult(replaces ? `Replaced channel memory \`${savedName}\`.` : `Saved to channel memory as \`${savedName}\`.`, { saved: result.added.length > 0 || result.updated.length > 0, name: savedName });
107
142
  }
108
143
  async function search({ query }) {
109
144
  const trimmed = query.trim();
110
145
  if (!trimmed) {
111
146
  throw new RecoverableToolError("memory_search requires a non-empty query.");
112
147
  }
113
- const [entries, workspaceMemory] = await Promise.all([
148
+ const [entries, workspaceMemory, journal] = await Promise.all([
114
149
  listMemoryEntries(options.channelDir),
115
150
  readWorkspaceMemory(options.workspaceDir),
151
+ readJournalForSearch(options.channelDir),
116
152
  ]);
117
- const hits = searchMemory({ query: trimmed, entries, workspaceMemory });
153
+ const hits = searchMemory({ query: trimmed, entries, workspaceMemory, journal: journal.days });
154
+ const scopeHint = journal.omittedDays > 0 || journal.truncatedDates.length > 0
155
+ ? `\nJournal search omitted ${journal.omittedDays} older day files and older text in ${journal.truncatedDates.length} large files. Use grep in ${join(options.channelDir, "journal")} or read a dated file to search the omitted history.`
156
+ : "";
118
157
  if (hits.length === 0) {
119
- return textResult(`No stored memory matched "${trimmed}". Try a broader query, or the fact may not be saved yet.`, {
158
+ return textResult(`No stored memory matched "${trimmed}". Try a broader query; no match does not prove the fact was never recorded.${scopeHint}`, {
120
159
  resultCount: 0,
121
160
  });
122
161
  }
123
162
  const rendered = hits
124
163
  .map((hit) => {
125
164
  const where = hit.kind === "memory"
126
- ? `memory/${hit.label}`
165
+ ? `memory/${hit.label}.md`
127
166
  : hit.kind === "journal"
128
- ? `journal ${hit.date}`
167
+ ? `journal/${hit.date}.md`
129
168
  : `workspace MEMORY.md › ${hit.label}`;
130
169
  return `- [${where}] ${hit.line}`;
131
170
  })
132
171
  .join("\n");
133
- return textResult(`Found ${hits.length} match${hits.length === 1 ? "" : "es"}:\n\n${rendered}`, {
172
+ return textResult(`Found ${hits.length} match${hits.length === 1 ? "" : "es"}:\n\n${rendered}${scopeHint}\nResults are excerpts. Read a cited file for full context; narrow the query for more specific matches.`, {
134
173
  resultCount: hits.length,
135
174
  });
136
175
  }
@@ -164,7 +203,7 @@ export function createMemorySaveTool(options) {
164
203
  name: "memory_save",
165
204
  label: "memory_save",
166
205
  description: "Save a durable fact into this channel's memory when the user asks you to remember it. Not for transient task state — " +
167
- "put in-progress work in the journal or a task instead.",
206
+ "keep in-progress work in a task (task_log) instead; the journal is written only by the background reflect pass.",
168
207
  parameters: memorySaveSchema,
169
208
  execute: async (_toolCallId, args) => save(args),
170
209
  };
@@ -174,7 +213,7 @@ export function createMemorySearchTool(options) {
174
213
  return {
175
214
  name: "memory_search",
176
215
  label: "memory_search",
177
- description: "Search this channel's stored memory, journal, and the workspace MEMORY.md on demand. The memory index is only " +
216
+ description: "Search this channel's stored memory, recent journal, and the workspace MEMORY.md on demand. The memory index is only " +
178
217
  "injected at the start of a session, so use this when you suspect something was recorded since.",
179
218
  parameters: memorySearchSchema,
180
219
  execute: async (_toolCallId, args) => search(args),
@@ -2,8 +2,8 @@ import { extname } from "path";
2
2
  import { Type } from "typebox";
3
3
  import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
4
4
  import { checkPathGuard } from "../security/path-guard-check.js";
5
+ import { shellEscape } from "../shared/os.js";
5
6
  import { RecoverableToolError } from "../shared/recoverable-error.js";
6
- import { shellEscape } from "../shared/shell-escape.js";
7
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
  /**
@@ -26,6 +26,8 @@ function isImageFile(filePath) {
26
26
  /** Directory tree caps, mirroring oh-my-pi's read: shallow and per-directory bounded. */
27
27
  const DIR_MAX_DEPTH = 2;
28
28
  const DIR_PER_DIR_LIMIT = 12;
29
+ /** Source cap on entries `listDirectory` collects before we ever start rendering (fix plan §2.4). */
30
+ const DIR_MAX_ENTRIES = 4_000;
29
31
  /**
30
32
  * Render a depth-2 directory tree from `FileStore.listDirectory` entries. Kept deliberately
31
33
  * portable — no sizes or mtimes, since formats differ across platforms; the structure is the value.
@@ -39,23 +41,41 @@ function renderDirectoryTree(entries) {
39
41
  const perParentCount = new Map();
40
42
  const lines = [];
41
43
  const elided = new Map();
44
+ // Parents whose own line was omitted (over the per-dir cap). Their descendants must be skipped
45
+ // too — otherwise the tree shows children of a directory it never listed.
46
+ const elidedParents = new Set();
42
47
  for (const entry of sorted) {
43
48
  const segments = entry.relativePath.split("/");
44
49
  const depth = segments.length - 1;
45
50
  const parent = depth === 0 ? "" : segments.slice(0, -1).join("/");
51
+ if (isUnderElidedParent(parent, elidedParents)) {
52
+ continue;
53
+ }
46
54
  const count = (perParentCount.get(parent) ?? 0) + 1;
47
55
  perParentCount.set(parent, count);
48
56
  if (count > DIR_PER_DIR_LIMIT) {
49
57
  elided.set(parent, (elided.get(parent) ?? 0) + 1);
58
+ if (entry.isDirectory) {
59
+ elidedParents.add(entry.relativePath);
60
+ }
50
61
  continue;
51
62
  }
52
63
  lines.push(`${" ".repeat(depth)}${entry.name}${entry.isDirectory ? "/" : ""}`);
53
64
  }
54
- for (const [, count] of elided) {
55
- lines.push(` [+${count} more]`);
65
+ for (const [parent, count] of elided) {
66
+ const indent = parent === "" ? "" : " ".repeat(parent.split("/").length);
67
+ lines.push(`${indent} [+${count} more]`);
56
68
  }
57
69
  return lines.join("\n");
58
70
  }
71
+ function isUnderElidedParent(parent, elidedParents) {
72
+ for (const elided of elidedParents) {
73
+ if (parent === elided || parent.startsWith(`${elided}/`)) {
74
+ return true;
75
+ }
76
+ }
77
+ return false;
78
+ }
59
79
  const readSchema = Type.Object({
60
80
  path: Type.String({ description: "Path to the file to read (relative or absolute)" }),
61
81
  offset: Type.Optional(Type.Integer({ minimum: 1, description: "Line number to start reading from (1-indexed)" })),
@@ -77,7 +97,7 @@ export function createReadTool(executor, fileStore, options = {}) {
77
97
  return {
78
98
  name: "read",
79
99
  label: "read",
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.`,
100
+ description: `Read a file, a PDF (converted to text), or a directory (rendered as a shallow tree). Also reads images (jpg, png, gif, webp), returned as attachments. Text/PDF output is truncated to ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); use offset/limit to page a large file. A directory tree is depth-2, capped per directory, and points you to subdirectories for the rest.`,
81
101
  parameters: readSchema,
82
102
  execute: async (_toolCallId, { path, offset, limit }, signal) => {
83
103
  const target = await checkPathGuard(path, "read", securityConfig, securityContext, {
@@ -121,15 +141,32 @@ export function createReadTool(executor, fileStore, options = {}) {
121
141
  `The file may be scanned/image-based — ask the user for a text version or a screenshot.`);
122
142
  }
123
143
  pdfText = converted.stdout;
144
+ if (converted.stdoutTruncated) {
145
+ // The 10MB capture cap hit mid-conversion — the rest of the PDF's text is gone.
146
+ // Say so rather than presenting a partial extraction as the whole document.
147
+ pdfText += `\n\n[pdftotext output exceeded the command capture limit and was cut off here; this is not the complete document. Ask the user for a text version to read the rest.]`;
148
+ }
124
149
  }
125
150
  const stat = isPdf ? undefined : await fileStore.stat(target);
126
151
  if (!isPdf && !stat) {
127
152
  throw new RecoverableToolError(`Failed to read file: ${path}. Check the path — try \`read\` on its parent directory to confirm it exists.`);
128
153
  }
129
154
  if (stat?.isDirectory) {
130
- const entries = await fileStore.listDirectory(target, { maxDepth: DIR_MAX_DEPTH });
155
+ const entries = await fileStore.listDirectory(target, {
156
+ maxDepth: DIR_MAX_DEPTH,
157
+ maxEntries: DIR_MAX_ENTRIES,
158
+ });
159
+ const tree = renderDirectoryTree(entries);
160
+ const clamped = truncateHead(tree);
161
+ let text = `Directory: ${path}\n\n${clamped.content}`;
162
+ if (entries.length >= DIR_MAX_ENTRIES) {
163
+ text += `\n\n[Listing stopped at ${DIR_MAX_ENTRIES} entries; this directory is large. read a specific subdirectory to see the rest.]`;
164
+ }
165
+ else if (clamped.truncated) {
166
+ text += `\n\n[Tree truncated at ${DEFAULT_MAX_BYTES / 1024}KB; read a specific subdirectory to see the rest.]`;
167
+ }
131
168
  return {
132
- content: [{ type: "text", text: `Directory: ${path}\n\n${renderDirectoryTree(entries)}` }],
169
+ content: [{ type: "text", text }],
133
170
  details: undefined,
134
171
  };
135
172
  }
@@ -6,6 +6,7 @@ import type { Executor } from "../executor.js";
6
6
  import type { FileStore } from "../file-store.js";
7
7
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
8
8
  import type { PipiclawSessionSearchSettings } from "../settings.js";
9
+ import type { SubAgentRunManager } from "../subagents/runs.js";
9
10
  import type { PipiclawToolsConfig, PipiclawWebToolsConfig } from "./config.js";
10
11
  import { type ToolDetailsKind } from "./tool-details.js";
11
12
  /**
@@ -34,11 +35,18 @@ export interface ToolBuildContext {
34
35
  bashDefaultTimeoutSeconds?: number;
35
36
  /** Gates the bash tool's rtk command optimizer (`tools.rtk.enabled`). Threaded to both sets. */
36
37
  rtkEnabled?: boolean;
38
+ /**
39
+ * Set by `buildToolSet` from `BuildToolSetOptions.forSubagent`. A sub-agent's `securityContext`
40
+ * has no `channelDir` and may be project-bounded, so tools that would otherwise write into the
41
+ * channel directory (bash/job output spill) must fall back to a neutral location for it.
42
+ */
43
+ forSubagent?: boolean;
37
44
  /**
38
45
  * Present only on the main path. Enables bash `async` and the `job` tool.
39
46
  * The sub-agent set never supplies it, so sub-agents get neither.
40
47
  */
41
48
  jobManager?: ChannelJobManager;
49
+ runManager?: SubAgentRunManager;
42
50
  getCurrentModel?: () => Model<Api>;
43
51
  getAvailableModels?: () => Model<Api>[];
44
52
  resolveApiKey?: (model: Model<Api>) => Promise<string>;
@@ -63,8 +71,6 @@ export interface ToolBuildContext {
63
71
  export interface ToolRegistration {
64
72
  /** Also the tool's `details.kind`: the name is the authoritative discriminator. */
65
73
  name: ToolDetailsKind;
66
- /** Whether this tool is included in a sub-agent's tool set. */
67
- availableToSubagents: boolean;
68
74
  /** Config gate; when omitted the tool is always enabled. */
69
75
  enabledBy?: (ctx: ToolBuildContext) => boolean;
70
76
  create: (ctx: ToolBuildContext) => AgentTool<any>;
@@ -89,7 +95,7 @@ export declare const TOOL_REGISTRY: ToolRegistration[];
89
95
  */
90
96
  export declare const TOOL_NAMES: ReadonlySet<string>;
91
97
  export interface BuildToolSetOptions {
92
- /** When true, include only tools flagged `availableToSubagents`. */
98
+ /** When true, include only tools in the sub-agent whitelist. */
93
99
  forSubagent?: boolean;
94
100
  }
95
101
  /**
@@ -9,6 +9,7 @@ import { createReadTool } from "./read.js";
9
9
  import { createSendMediaTool } from "./send-media.js";
10
10
  import { createSessionSearchTool } from "./session-search.js";
11
11
  import { createSkillTool } from "./skill.js";
12
+ import { SUBAGENT_TOOL_NAMES } from "./subagent-tool-names.js";
12
13
  import { createTaskCloseTool, createTaskCreateTool, createTaskListTool, createTaskLogTool, createTaskStepEndTool, createTaskUpdateTool, } from "./task-manage.js";
13
14
  import { withToolDetails } from "./tool-details.js";
14
15
  import { createWebFetchTool } from "./web-fetch.js";
@@ -34,6 +35,16 @@ function memoryToolOptions(ctx) {
34
35
  workspaceDir: ctx.workspaceDir,
35
36
  };
36
37
  }
38
+ function taskToolOptions(ctx) {
39
+ return {
40
+ jobManager: req(ctx.jobManager, "jobManager"),
41
+ runManager: req(ctx.runManager, "runManager"),
42
+ workspaceDir: ctx.workspaceDir,
43
+ channelDir: ctx.channelDir,
44
+ channelId: ctx.channelId,
45
+ workingDirectory: ctx.securityContext.projectRoot,
46
+ };
47
+ }
37
48
  function webEnabled(ctx) {
38
49
  return ctx.webConfig != null && ctx.webConfig.enable !== false;
39
50
  }
@@ -46,16 +57,17 @@ function webEnabled(ctx) {
46
57
  export const TOOL_REGISTRY = [
47
58
  {
48
59
  name: "read",
49
- availableToSubagents: true,
50
60
  create: (ctx) => createReadTool(ctx.executor, ctx.fileStore, fileToolOptions(ctx)),
51
61
  },
52
62
  {
53
63
  name: "bash",
54
- availableToSubagents: true,
55
64
  create: (ctx) => createBashTool(ctx.executor, {
56
65
  ...fileToolOptions(ctx),
57
66
  rtkEnabled: ctx.rtkEnabled === true,
58
67
  interceptorEnabled: ctx.toolsConfig?.tools.bashInterceptor.enabled === true,
68
+ // Sub-agents get no channel dir (their guard context has none); their spill stays in tmpdir.
69
+ ...(ctx.forSubagent ? {} : { channelDir: ctx.channelDir }),
70
+ ...(ctx.taskLoop ? { boundTaskId: ctx.taskLoop.taskId } : {}),
59
71
  ...(ctx.jobManager ? { jobManager: ctx.jobManager } : {}),
60
72
  ...(ctx.bashDefaultTimeoutSeconds !== undefined
61
73
  ? { defaultTimeoutSeconds: ctx.bashDefaultTimeoutSeconds }
@@ -64,27 +76,22 @@ export const TOOL_REGISTRY = [
64
76
  },
65
77
  {
66
78
  name: "edit",
67
- availableToSubagents: true,
68
79
  create: (ctx) => createEditTool(ctx.fileStore, fileToolOptions(ctx)),
69
80
  },
70
81
  {
71
82
  name: "grep",
72
- availableToSubagents: true,
73
83
  create: (ctx) => createGrepTool(ctx.executor, fileToolOptions(ctx)),
74
84
  },
75
85
  {
76
86
  name: "glob",
77
- availableToSubagents: true,
78
87
  create: (ctx) => createGlobTool(ctx.fileStore, fileToolOptions(ctx)),
79
88
  },
80
89
  {
81
90
  name: "write",
82
- availableToSubagents: true,
83
91
  create: (ctx) => createWriteTool(ctx.fileStore, fileToolOptions(ctx)),
84
92
  },
85
93
  {
86
94
  name: "web_search",
87
- availableToSubagents: true,
88
95
  enabledBy: webEnabled,
89
96
  create: (ctx) => createWebSearchTool({
90
97
  webConfig: req(ctx.webConfig, "webConfig"),
@@ -95,7 +102,6 @@ export const TOOL_REGISTRY = [
95
102
  },
96
103
  {
97
104
  name: "web_fetch",
98
- availableToSubagents: true,
99
105
  enabledBy: webEnabled,
100
106
  create: (ctx) => createWebFetchTool({
101
107
  webConfig: req(ctx.webConfig, "webConfig"),
@@ -107,7 +113,6 @@ export const TOOL_REGISTRY = [
107
113
  },
108
114
  {
109
115
  name: "send_media",
110
- availableToSubagents: false,
111
116
  // Enabled only when the driving transport supplied a media sender (the DingTalk
112
117
  // bot, or the terminal). Absent it, the tool is not built or advertised.
113
118
  enabledBy: (ctx) => ctx.mediaSender != null,
@@ -120,7 +125,6 @@ export const TOOL_REGISTRY = [
120
125
  },
121
126
  {
122
127
  name: "session_search",
123
- availableToSubagents: false,
124
128
  create: (ctx) => createSessionSearchTool({
125
129
  channelId: ctx.channelId,
126
130
  channelDir: ctx.channelDir,
@@ -132,27 +136,22 @@ export const TOOL_REGISTRY = [
132
136
  // Spec 047, P4: one tool per payload shape. All three share the same build options.
133
137
  {
134
138
  name: "memory_save",
135
- availableToSubagents: false,
136
139
  create: (ctx) => createMemorySaveTool(memoryToolOptions(ctx)),
137
140
  },
138
141
  {
139
142
  name: "memory_search",
140
- availableToSubagents: false,
141
143
  create: (ctx) => createMemorySearchTool(memoryToolOptions(ctx)),
142
144
  },
143
145
  {
144
146
  name: "memory_forget",
145
- availableToSubagents: false,
146
147
  create: (ctx) => createMemoryForgetTool(memoryToolOptions(ctx)),
147
148
  },
148
149
  {
149
150
  name: "skill",
150
- availableToSubagents: false,
151
151
  create: (ctx) => createSkillTool({ workspaceDir: ctx.workspaceDir, ...fileToolOptions(ctx) }),
152
152
  },
153
153
  {
154
154
  name: "event_manage",
155
- availableToSubagents: false,
156
155
  create: (ctx) => createEventManageTool({
157
156
  workspaceDir: ctx.workspaceDir,
158
157
  channelId: ctx.channelId,
@@ -164,68 +163,35 @@ export const TOOL_REGISTRY = [
164
163
  // shape (spec 046, D3.1) — all share it, since none is meaningful without the others.
165
164
  {
166
165
  name: "task_list",
167
- availableToSubagents: false,
168
166
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
169
- create: (ctx) => createTaskListTool({
170
- workspaceDir: ctx.workspaceDir,
171
- channelDir: ctx.channelDir,
172
- channelId: ctx.channelId,
173
- workingDirectory: ctx.securityContext.projectRoot,
174
- }),
167
+ create: (ctx) => createTaskListTool(taskToolOptions(ctx)),
175
168
  },
176
169
  {
177
170
  name: "task_create",
178
- availableToSubagents: false,
179
171
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
180
- create: (ctx) => createTaskCreateTool({
181
- workspaceDir: ctx.workspaceDir,
182
- channelDir: ctx.channelDir,
183
- channelId: ctx.channelId,
184
- workingDirectory: ctx.securityContext.projectRoot,
185
- }),
172
+ create: (ctx) => createTaskCreateTool(taskToolOptions(ctx)),
186
173
  },
187
174
  {
188
175
  name: "task_update",
189
- availableToSubagents: false,
190
176
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
191
- create: (ctx) => createTaskUpdateTool({
192
- workspaceDir: ctx.workspaceDir,
193
- channelDir: ctx.channelDir,
194
- channelId: ctx.channelId,
195
- workingDirectory: ctx.securityContext.projectRoot,
196
- }),
177
+ create: (ctx) => createTaskUpdateTool(taskToolOptions(ctx)),
197
178
  },
198
179
  {
199
180
  name: "task_close",
200
- availableToSubagents: false,
201
181
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
202
- create: (ctx) => createTaskCloseTool({
203
- workspaceDir: ctx.workspaceDir,
204
- channelDir: ctx.channelDir,
205
- channelId: ctx.channelId,
206
- workingDirectory: ctx.securityContext.projectRoot,
207
- }),
182
+ create: (ctx) => createTaskCloseTool(taskToolOptions(ctx)),
208
183
  },
209
184
  {
210
185
  name: "task_log",
211
- availableToSubagents: false,
212
186
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false,
213
- create: (ctx) => createTaskLogTool({
214
- workspaceDir: ctx.workspaceDir,
215
- channelDir: ctx.channelDir,
216
- channelId: ctx.channelId,
217
- }),
187
+ create: (ctx) => createTaskLogTool(taskToolOptions(ctx)),
218
188
  },
219
189
  {
220
190
  name: "task_step_end",
221
- availableToSubagents: false,
222
191
  // Only inside a task session: it is the loop's closing move, not a chat action.
223
192
  enabledBy: (ctx) => ctx.toolsConfig?.tools.tasks.enabled !== false && ctx.taskLoop !== undefined,
224
193
  create: (ctx) => createTaskStepEndTool({
225
- workspaceDir: ctx.workspaceDir,
226
- channelDir: ctx.channelDir,
227
- channelId: ctx.channelId,
228
- workingDirectory: ctx.securityContext.projectRoot,
194
+ ...taskToolOptions(ctx),
229
195
  taskId: ctx.taskLoop?.taskId,
230
196
  cycleId: ctx.taskLoop?.cycleId,
231
197
  getToolsUsed: ctx.getToolsUsed,
@@ -233,7 +199,6 @@ export const TOOL_REGISTRY = [
233
199
  },
234
200
  {
235
201
  name: "job",
236
- availableToSubagents: false,
237
202
  // Present only when a job manager was supplied (always on the main path,
238
203
  // never for sub-agents).
239
204
  enabledBy: (ctx) => ctx.jobManager !== undefined,
@@ -269,13 +234,13 @@ export const TOOL_NAMES = new Set([
269
234
  export function buildToolSet(ctx, options = {}) {
270
235
  const result = [];
271
236
  for (const registration of TOOL_REGISTRY) {
272
- if (options.forSubagent && !registration.availableToSubagents) {
237
+ if (options.forSubagent && !SUBAGENT_TOOL_NAMES.some((name) => name === registration.name)) {
273
238
  continue;
274
239
  }
275
240
  if (registration.enabledBy && !registration.enabledBy(ctx)) {
276
241
  continue;
277
242
  }
278
- result.push(withToolDetails(registration.create(ctx), registration.name));
243
+ result.push(withToolDetails(registration.create({ ...ctx, forSubagent: options.forSubagent }), registration.name));
279
244
  }
280
245
  return result;
281
246
  }