@oyasmi/pipiclaw 0.9.5 → 0.9.6-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 (345) hide show
  1. package/README.en.md +300 -142
  2. package/README.md +295 -140
  3. package/dist/agent/builtin-commands.d.ts +1 -1
  4. package/dist/agent/builtin-commands.js +1 -1
  5. package/dist/agent/channel-runner.d.ts +4 -3
  6. package/dist/agent/channel-runner.js +17 -28
  7. package/dist/agent/maintenance-context.js +2 -2
  8. package/dist/agent/prompt/builder.d.ts +1 -1
  9. package/dist/agent/prompt/builder.js +1 -1
  10. package/dist/agent/prompt/extension.d.ts +1 -1
  11. package/dist/agent/prompt/extension.js +1 -1
  12. package/dist/agent/prompt/manifest.d.ts +6 -1
  13. package/dist/agent/prompt/manifest.js +12 -5
  14. package/dist/agent/prompt/resources.d.ts +0 -3
  15. package/dist/agent/prompt/resources.js +0 -6
  16. package/dist/agent/prompt/sections.d.ts +2 -2
  17. package/dist/agent/prompt/sections.js +36 -26
  18. package/dist/agent/prompt/types.d.ts +3 -2
  19. package/dist/agent/runner-factory.js +1 -1
  20. package/dist/agent/session/command-extension.js +3 -1
  21. package/dist/agent/session/compaction-summary.js +3 -6
  22. package/dist/agent/session/compaction.d.ts +2 -0
  23. package/dist/agent/session/compaction.js +22 -14
  24. package/dist/agent/session/event-guards.d.ts +2 -1
  25. package/dist/agent/session/event-guards.js +6 -0
  26. package/dist/agent/session/model-selection.d.ts +2 -1
  27. package/dist/agent/session/model-selection.js +5 -5
  28. package/dist/agent/session/session-events.js +31 -4
  29. package/dist/agent/session/session-host.d.ts +5 -3
  30. package/dist/agent/session/session-host.js +20 -16
  31. package/dist/agent/status-render.js +3 -0
  32. package/dist/agent/stop-watchdog.js +5 -1
  33. package/dist/agent/turn/task-digest.d.ts +2 -5
  34. package/dist/agent/turn/task-digest.js +25 -45
  35. package/dist/agent/turn/turn-context.js +4 -6
  36. package/dist/agent/turn/turn-error.d.ts +1 -1
  37. package/dist/agent/turn/turn-error.js +9 -0
  38. package/dist/agent/turn/turn-pipeline.d.ts +10 -5
  39. package/dist/agent/turn/turn-pipeline.js +36 -7
  40. package/dist/agent/turn/turn-prompt.d.ts +2 -0
  41. package/dist/agent/turn/turn-prompt.js +2 -1
  42. package/dist/agent/turn/turn-recovery.js +4 -1
  43. package/dist/agent/turn/turn-state.d.ts +2 -0
  44. package/dist/agent/turn/turn-state.js +2 -1
  45. package/dist/agent/types.d.ts +23 -3
  46. package/dist/agent/types.js +2 -0
  47. package/dist/app/auth-command.d.ts +25 -0
  48. package/dist/app/auth-command.js +200 -67
  49. package/dist/app/home.d.ts +7 -8
  50. package/dist/app/home.js +143 -56
  51. package/dist/channel/attachments.d.ts +4 -0
  52. package/dist/channel/attachments.js +4 -0
  53. package/dist/channel/channel-context.d.ts +6 -0
  54. package/dist/channel/config.d.ts +3 -0
  55. package/dist/channel/config.js +11 -5
  56. package/dist/channel/store.d.ts +1 -1
  57. package/dist/commands/catalog.js +42 -10
  58. package/dist/commands/router.js +5 -1
  59. package/dist/desk/commands.d.ts +44 -5
  60. package/dist/desk/commands.js +162 -28
  61. package/dist/desk/paths.d.ts +6 -0
  62. package/dist/desk/paths.js +21 -1
  63. package/dist/desk/registry.d.ts +17 -2
  64. package/dist/desk/registry.js +122 -12
  65. package/dist/desk/types.d.ts +83 -1
  66. package/dist/dingtalk/bot.d.ts +1 -1
  67. package/dist/dingtalk/bot.js +4 -3
  68. package/dist/dingtalk/config.js +10 -10
  69. package/dist/dingtalk/delivery.js +15 -8
  70. package/dist/dingtalk/inbound-media.d.ts +36 -14
  71. package/dist/dingtalk/inbound-media.js +71 -12
  72. package/dist/dingtalk/inbound.d.ts +9 -2
  73. package/dist/dingtalk/inbound.js +17 -2
  74. package/dist/dingtalk/media.d.ts +4 -10
  75. package/dist/dingtalk/media.js +58 -32
  76. package/dist/events/commands.d.ts +2 -0
  77. package/dist/events/commands.js +13 -8
  78. package/dist/events/history.d.ts +9 -0
  79. package/dist/events/history.js +66 -0
  80. package/dist/events/parse.js +7 -3
  81. package/dist/events/types.d.ts +3 -0
  82. package/dist/events/watcher.d.ts +4 -8
  83. package/dist/events/watcher.js +53 -58
  84. package/dist/jobs/kill.d.ts +23 -0
  85. package/dist/jobs/kill.js +65 -0
  86. package/dist/jobs/manager.d.ts +19 -18
  87. package/dist/jobs/manager.js +36 -103
  88. package/dist/main.js +15 -3
  89. package/dist/memory/boundary-work.d.ts +2 -1
  90. package/dist/memory/boundary-work.js +1 -1
  91. package/dist/memory/lifecycle.d.ts +2 -1
  92. package/dist/memory/lifecycle.js +2 -2
  93. package/dist/memory/reflect-job.d.ts +2 -1
  94. package/dist/memory/reflect-job.js +1 -1
  95. package/dist/memory/reflect.d.ts +2 -1
  96. package/dist/memory/reflect.js +25 -4
  97. package/dist/memory/scheduler.d.ts +2 -1
  98. package/dist/memory/scheduler.js +1 -1
  99. package/dist/memory/session-corpus.d.ts +1 -1
  100. package/dist/memory/session-corpus.js +76 -1
  101. package/dist/memory/session-search.d.ts +2 -1
  102. package/dist/memory/session-search.js +14 -12
  103. package/dist/memory/sidecar-worker.d.ts +2 -1
  104. package/dist/memory/sidecar-worker.js +2 -4
  105. package/dist/memory/store.d.ts +2 -0
  106. package/dist/memory/store.js +19 -9
  107. package/dist/models/credential-work.d.ts +7 -0
  108. package/dist/models/credential-work.js +36 -0
  109. package/dist/models/login-ui.js +4 -4
  110. package/dist/models/provider-login.js +7 -6
  111. package/dist/models/requests.d.ts +8 -0
  112. package/dist/models/requests.js +69 -0
  113. package/dist/models/runtime.d.ts +3 -1
  114. package/dist/models/runtime.js +9 -2
  115. package/dist/playbooks/agent-delegation.md +20 -45
  116. package/dist/playbooks/background-jobs.md +1 -1
  117. package/dist/playbooks/catalog.js +1 -1
  118. package/dist/playbooks/delegation-inline.md +25 -0
  119. package/dist/playbooks/delegation-recovery.md +28 -0
  120. package/dist/playbooks/event-scheduling.md +18 -37
  121. package/dist/playbooks/event-sensors.md +26 -0
  122. package/dist/playbooks/event-task-template.md +22 -0
  123. package/dist/playbooks/learning-and-skills.md +26 -0
  124. package/dist/playbooks/memory-operations.md +36 -0
  125. package/dist/playbooks/outbound-media.md +2 -2
  126. package/dist/playbooks/runtime-files.md +29 -0
  127. package/dist/playbooks/runtime-operations.md +25 -0
  128. package/dist/playbooks/runtime-orientation.md +18 -53
  129. package/dist/playbooks/task-lead.md +22 -68
  130. package/dist/playbooks/task-manage.md +38 -0
  131. package/dist/playbooks/task-recovery.md +24 -0
  132. package/dist/playbooks/task-verify.md +22 -0
  133. package/dist/runtime/bootstrap.d.ts +10 -0
  134. package/dist/runtime/bootstrap.js +93 -29
  135. package/dist/runtime/daemon-lock.js +3 -3
  136. package/dist/runtime/desk-runtime.d.ts +40 -7
  137. package/dist/runtime/desk-runtime.js +330 -44
  138. package/dist/runtime/durable-dispatch.d.ts +14 -2
  139. package/dist/runtime/durable-dispatch.js +207 -65
  140. package/dist/runtime/ingress-busy.js +17 -8
  141. package/dist/runtime/ingress-commands.js +24 -4
  142. package/dist/runtime/ingress-deps.d.ts +4 -1
  143. package/dist/runtime/ingress.js +6 -1
  144. package/dist/runtime/request-execution.js +7 -6
  145. package/dist/runtime/shutdown.d.ts +4 -1
  146. package/dist/runtime/shutdown.js +88 -35
  147. package/dist/runtime/task-close.d.ts +1 -1
  148. package/dist/runtime/task-close.js +6 -3
  149. package/dist/runtime/task-control.d.ts +2 -3
  150. package/dist/runtime/task-control.js +38 -11
  151. package/dist/runtime/task-input.js +1 -1
  152. package/dist/runtime/task-lane-types.d.ts +12 -2
  153. package/dist/runtime/task-lane-types.js +9 -0
  154. package/dist/runtime/task-lane.d.ts +2 -0
  155. package/dist/runtime/task-lane.js +38 -20
  156. package/dist/runtime/task-step.d.ts +3 -3
  157. package/dist/runtime/task-step.js +34 -16
  158. package/dist/runtime/transports.js +6 -5
  159. package/dist/runtime/turn-run.js +103 -66
  160. package/dist/security/command-guard.d.ts +1 -1
  161. package/dist/security/command-guard.js +259 -314
  162. package/dist/security/path-guard.js +48 -7
  163. package/dist/security/shell-parse.d.ts +10 -0
  164. package/dist/security/shell-parse.js +224 -0
  165. package/dist/security/types.d.ts +2 -0
  166. package/dist/subagents/commands.d.ts +1 -1
  167. package/dist/subagents/commands.js +14 -5
  168. package/dist/subagents/completion-wake.js +6 -0
  169. package/dist/subagents/detached-discovery.d.ts +1 -1
  170. package/dist/subagents/discovery.d.ts +18 -199
  171. package/dist/subagents/discovery.js +35 -289
  172. package/dist/subagents/dispatch.d.ts +1 -2
  173. package/dist/subagents/dispatch.js +50 -29
  174. package/dist/subagents/external/antigravity-cli.d.ts +2 -0
  175. package/dist/subagents/external/antigravity-cli.js +517 -0
  176. package/dist/subagents/external/claude-code.js +8 -17
  177. package/dist/subagents/external/codex-cli.js +8 -18
  178. package/dist/subagents/external/cursor-cli.js +34 -31
  179. package/dist/subagents/external/dispatch.d.ts +21 -7
  180. package/dist/subagents/external/dispatch.js +146 -12
  181. package/dist/subagents/external/exec.js +3 -0
  182. package/dist/subagents/external/harness.d.ts +57 -33
  183. package/dist/subagents/external/harness.js +69 -40
  184. package/dist/subagents/external/reconciliation.js +1 -0
  185. package/dist/subagents/external/registry.js +4 -1
  186. package/dist/subagents/external/role-warnings.d.ts +4 -13
  187. package/dist/subagents/external/role-warnings.js +4 -28
  188. package/dist/subagents/external/run.d.ts +1 -2
  189. package/dist/subagents/external/run.js +16 -26
  190. package/dist/subagents/external/settlement.d.ts +2 -0
  191. package/dist/subagents/external/settlement.js +13 -3
  192. package/dist/subagents/format.d.ts +1 -1
  193. package/dist/subagents/format.js +1 -1
  194. package/dist/subagents/internal/outcome.d.ts +1 -2
  195. package/dist/subagents/internal/outcome.js +19 -12
  196. package/dist/subagents/internal/provider-retry.d.ts +1 -2
  197. package/dist/subagents/internal/provider-retry.js +2 -4
  198. package/dist/subagents/internal/run.d.ts +2 -3
  199. package/dist/subagents/internal/run.js +27 -4
  200. package/dist/subagents/internal/state.d.ts +2 -5
  201. package/dist/subagents/internal/state.js +1 -2
  202. package/dist/subagents/internal/worker.d.ts +1 -2
  203. package/dist/subagents/internal/worker.js +20 -10
  204. package/dist/subagents/resolve.d.ts +56 -0
  205. package/dist/subagents/resolve.js +202 -0
  206. package/dist/subagents/result.d.ts +6 -4
  207. package/dist/subagents/result.js +39 -6
  208. package/dist/subagents/run-record.d.ts +54 -2
  209. package/dist/subagents/run-record.js +7 -0
  210. package/dist/subagents/runs.d.ts +6 -31
  211. package/dist/subagents/runs.js +26 -31
  212. package/dist/subagents/task-envelope.d.ts +1 -2
  213. package/dist/subagents/task-envelope.js +13 -4
  214. package/dist/subagents/task-settlement.js +1 -0
  215. package/dist/subagents/types.d.ts +105 -6
  216. package/dist/subagents/types.js +16 -1
  217. package/dist/subagents/workspace-lease.d.ts +41 -24
  218. package/dist/subagents/workspace-lease.js +159 -24
  219. package/dist/subagents/worktree.d.ts +52 -0
  220. package/dist/subagents/worktree.js +363 -0
  221. package/dist/tasks/archive.js +4 -0
  222. package/dist/tasks/brief.d.ts +5 -1
  223. package/dist/tasks/brief.js +19 -5
  224. package/dist/tasks/commands.d.ts +6 -1
  225. package/dist/tasks/commands.js +32 -7
  226. package/dist/tasks/control.d.ts +11 -0
  227. package/dist/tasks/delivery.d.ts +2 -0
  228. package/dist/tasks/delivery.js +141 -21
  229. package/dist/tasks/loop-log.d.ts +12 -0
  230. package/dist/tasks/loop-log.js +10 -1
  231. package/dist/tasks/receipts.d.ts +7 -3
  232. package/dist/tasks/receipts.js +34 -5
  233. package/dist/tools/bash.d.ts +3 -0
  234. package/dist/tools/bash.js +29 -15
  235. package/dist/tools/contract/presentation.js +7 -5
  236. package/dist/tools/edit-diff.d.ts +11 -0
  237. package/dist/tools/edit-diff.js +148 -0
  238. package/dist/tools/edit-match.d.ts +18 -0
  239. package/dist/tools/edit-match.js +242 -0
  240. package/dist/tools/edit.d.ts +10 -2
  241. package/dist/tools/edit.js +91 -361
  242. package/dist/tools/event-manage.d.ts +2 -1
  243. package/dist/tools/event-manage.js +46 -39
  244. package/dist/tools/file-observations.d.ts +9 -0
  245. package/dist/tools/file-observations.js +50 -0
  246. package/dist/tools/glob-match.d.ts +3 -1
  247. package/dist/tools/glob-match.js +40 -17
  248. package/dist/tools/glob.d.ts +1 -0
  249. package/dist/tools/glob.js +39 -19
  250. package/dist/tools/grep-command.d.ts +13 -0
  251. package/dist/tools/grep-command.js +77 -0
  252. package/dist/tools/grep.js +96 -201
  253. package/dist/tools/index.d.ts +6 -2
  254. package/dist/tools/index.js +9 -4
  255. package/dist/tools/job.js +12 -11
  256. package/dist/tools/read.d.ts +2 -0
  257. package/dist/tools/read.js +10 -2
  258. package/dist/tools/registry.d.ts +16 -11
  259. package/dist/tools/registry.js +32 -12
  260. package/dist/tools/send-media.js +9 -5
  261. package/dist/tools/session-search.d.ts +2 -1
  262. package/dist/tools/session-search.js +15 -5
  263. package/dist/tools/skill.js +13 -12
  264. package/dist/tools/subagent-manage.d.ts +1 -1
  265. package/dist/tools/subagent-manage.js +25 -152
  266. package/dist/tools/subagent.d.ts +24 -2
  267. package/dist/tools/subagent.js +24 -18
  268. package/dist/tools/task-manage/control-tools.js +1 -1
  269. package/dist/tools/task-manage/factory.d.ts +2 -2
  270. package/dist/tools/task-manage/factory.js +40 -4
  271. package/dist/tools/task-manage/lifecycle.d.ts +3 -3
  272. package/dist/tools/task-manage/lifecycle.js +56 -13
  273. package/dist/tools/task-manage/schema.d.ts +4 -1
  274. package/dist/tools/task-manage/schema.js +4 -1
  275. package/dist/tools/task-manage/shared.d.ts +1 -1
  276. package/dist/tools/task-manage/types.d.ts +5 -1
  277. package/dist/tools/write-content.d.ts +7 -1
  278. package/dist/tools/write-content.js +18 -6
  279. package/dist/tools/write.d.ts +3 -0
  280. package/dist/tools/write.js +6 -2
  281. package/dist/tui/cli.d.ts +6 -6
  282. package/dist/tui/cli.js +120 -28
  283. package/dist/tui/client.d.ts +7 -0
  284. package/dist/tui/client.js +67 -16
  285. package/dist/tui/frontend.d.ts +2 -0
  286. package/dist/tui/pitui-frontend.d.ts +4 -0
  287. package/dist/tui/pitui-frontend.js +27 -0
  288. package/dist/tui/render.d.ts +1 -0
  289. package/dist/tui/render.js +5 -0
  290. package/dist/tui/session.js +6 -0
  291. package/dist/usage/ledger.d.ts +1 -1
  292. package/dist/usage/render.js +1 -1
  293. package/dist/web/client.d.ts +1 -0
  294. package/dist/web/client.js +11 -0
  295. package/dist/web/fetch.js +6 -3
  296. package/dist/webapi/auth.d.ts +0 -3
  297. package/dist/webapi/auth.js +3 -7
  298. package/dist/webapi/config.js +17 -14
  299. package/dist/webapi/key-command.js +41 -41
  300. package/dist/webapi/response-state.d.ts +7 -1
  301. package/dist/webapi/response-state.js +166 -3
  302. package/dist/webapi/routes/websocket.js +24 -1
  303. package/dist/webapi/server.d.ts +3 -1
  304. package/dist/webapi/server.js +32 -1
  305. package/dist/webapi/service.js +8 -0
  306. package/dist/webapi/transport.d.ts +2 -0
  307. package/dist/webapi/transport.js +11 -1
  308. package/examples/sub-agents/README.md +43 -75
  309. package/examples/sub-agents/agy-main.md +21 -0
  310. package/examples/sub-agents/claude-high.md +21 -0
  311. package/examples/sub-agents/claude-main.md +21 -0
  312. package/examples/sub-agents/codex-flash.md +21 -0
  313. package/examples/sub-agents/codex-high.md +21 -0
  314. package/examples/sub-agents/codex-main.md +21 -0
  315. package/examples/sub-agents/codex-review.md +20 -0
  316. package/examples/sub-agents/cursor-high.md +20 -0
  317. package/examples/sub-agents/cursor-main.md +20 -0
  318. package/examples/sub-agents/glm-flash.md +21 -0
  319. package/examples/sub-agents/glm-high.md +21 -0
  320. package/examples/sub-agents/pi-scout.md +20 -0
  321. package/package.json +11 -12
  322. package/dist/agent/session/request-tools.d.ts +0 -3
  323. package/dist/agent/session/request-tools.js +0 -20
  324. package/dist/models/api-keys.d.ts +0 -11
  325. package/dist/models/api-keys.js +0 -22
  326. package/dist/playbooks/memory-and-learning.md +0 -55
  327. package/examples/sub-agents/agents/claude-high.md +0 -23
  328. package/examples/sub-agents/agents/claude-main.md +0 -23
  329. package/examples/sub-agents/agents/codex-flash.md +0 -23
  330. package/examples/sub-agents/agents/codex-high.md +0 -23
  331. package/examples/sub-agents/agents/codex-main.md +0 -23
  332. package/examples/sub-agents/agents/codex-review.md +0 -23
  333. package/examples/sub-agents/agents/cursor-high.md +0 -22
  334. package/examples/sub-agents/agents/cursor-main.md +0 -22
  335. package/examples/sub-agents/agents/glm-flash.md +0 -23
  336. package/examples/sub-agents/agents/glm-high.md +0 -23
  337. package/examples/sub-agents/agents/scout.md +0 -30
  338. package/examples/sub-agents/roles/builder-hard.md +0 -34
  339. package/examples/sub-agents/roles/builder.md +0 -34
  340. package/examples/sub-agents/roles/explorer.md +0 -39
  341. package/examples/sub-agents/roles/git-committer.md +0 -43
  342. package/examples/sub-agents/roles/planner.md +0 -33
  343. package/examples/sub-agents/roles/reviewer.md +0 -33
  344. package/examples/sub-agents/roles/verifier.md +0 -35
  345. package/examples/sub-agents/roles/worker.md +0 -34
@@ -1,20 +1,17 @@
1
- import { basename } from "node:path";
1
+ import { isAbsolute, relative } from "node: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
5
  import { partitionByReadGuard, readGuardAllows } from "../security/path-guard-filter.js";
6
- import { shellEscape } from "../shared/os.js";
7
6
  import { RecoverableToolError } from "../shared/recoverable-error.js";
7
+ import { errorMessage } from "../shared/text-utils.js";
8
+ import { compileGlobPattern } from "./glob-match.js";
9
+ import { buildSearchCommand, isRgAvailable } from "./grep-command.js";
8
10
  import { IGNORED_DIR_SEGMENTS } from "./ignore-dirs.js";
9
11
  import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
10
12
  /**
11
- * Structured content search over the filesystem. The execution layer is deliberately thin — one
12
- * `grep -rnH -B1 -A3` invocation through the shared Executor, with no native dependency. The value
13
- * lives in the JS-side output shaping: per-file grouping, per-file and per-page caps, and a final
14
- * byte bound, so a broad search can never flood the model's context the way raw `bash grep -rn` would.
13
+ * Structured filesystem search via ripgrep or grep, with per-file grouping, pagination and output limits.
15
14
  */
16
- const CONTEXT_BEFORE = 1;
17
- const CONTEXT_AFTER = 3;
18
15
  const LINE_MAX_CHARS = 512;
19
16
  /** Match cap per file: tight for multi-file scopes (anti-monopoly), generous for a single file. */
20
17
  const MULTI_FILE_PER_FILE_MATCHES = 20;
@@ -32,142 +29,73 @@ const SEARCH_TIMEOUT_SECONDS = 30;
32
29
  const MAX_RAW_RESULT_BYTES = 768 * 1024;
33
30
  const grepSchema = Type.Object({
34
31
  pattern: Type.String({
35
- description: "Text to search for. An extended regular expression (ERE) unless `literal` is set.",
32
+ description: "Regex or literal search pattern.",
36
33
  }),
37
- path: Type.Optional(Type.String({ description: "File or directory to search. Defaults to the workspace root." })),
34
+ path: Type.Optional(Type.String({ description: "File or directory; defaults to cwd." })),
38
35
  glob: Type.Optional(Type.String({
39
36
  description: 'Filename filter for directory searches, matched against the basename. Supports `*`, `?`, `[abc]`, and `{a,b}` — e.g. "*.{ts,tsx}".',
40
37
  })),
41
38
  literal: Type.Optional(Type.Boolean({ description: "Treat `pattern` as a literal string, not a regex (like `grep -F`)." })),
42
39
  mode: Type.Optional(Type.Union([Type.Literal("content"), Type.Literal("files"), Type.Literal("count")], {
43
- description: '"content" (default) = matching lines; "files" = matching paths only; "count" = per-file counts. files/count cost far fewer tokens when you only need to locate.',
40
+ description: '"content" (default) includes context. "files" lists paths; "count" counts matching lines per file.',
44
41
  })),
45
42
  caseSensitive: Type.Optional(Type.Boolean({ description: "Case-sensitive match. Defaults to true." })),
46
43
  skip: Type.Optional(Type.Integer({ minimum: 0, description: "File-page offset for paging through many matching files." })),
47
44
  });
48
- /**
49
- * Convert a basename glob into an anchored regex. Supports `*`, `?`, character classes `[...]`, and
50
- * brace alternation `{a,b}` so the JS-side backstop filter is never *stricter* than the `--include`
51
- * glob pushed to `grep` — a mismatch there produced silent "no results" (fix plan §3.5).
52
- */
53
- function globToRegExp(glob) {
54
- let out = "";
55
- for (let i = 0; i < glob.length; i++) {
56
- const ch = glob[i];
57
- if (ch === "*") {
58
- out += ".*";
59
- }
60
- else if (ch === "?") {
61
- out += ".";
62
- }
63
- else if (ch === "[") {
64
- // Copy the class verbatim to the closing `]` (leading `!` -> `^` for negation).
65
- let j = i + 1;
66
- let cls = "";
67
- if (glob[j] === "!" || glob[j] === "^") {
68
- cls += "^";
69
- j++;
70
- }
71
- while (j < glob.length && glob[j] !== "]") {
72
- cls += glob[j];
73
- j++;
74
- }
75
- if (j < glob.length) {
76
- out += `[${cls}]`;
77
- i = j;
78
- }
79
- else {
80
- out += "\\[";
81
- }
82
- }
83
- else if (ch === "{") {
84
- const end = glob.indexOf("}", i);
85
- if (end > i) {
86
- const alts = glob
87
- .slice(i + 1, end)
88
- .split(",")
89
- .map((alt) => alt.replace(/[.+^${}()|[\]\\]/g, "\\$&"));
90
- out += `(?:${alts.join("|")})`;
91
- i = end;
92
- }
93
- else {
94
- out += "\\{";
95
- }
96
- }
97
- else if (/[.+^$()|\\]/.test(ch)) {
98
- out += `\\${ch}`;
99
- }
100
- else {
101
- out += ch;
102
- }
103
- }
104
- return new RegExp(`^${out}$`);
105
- }
106
45
  function truncateLine(text) {
107
46
  return text.length > LINE_MAX_CHARS ? `${text.slice(0, LINE_MAX_CHARS)}…` : text;
108
47
  }
109
- function isIgnoredPath(relPath) {
110
- return relPath.split("/").some((segment) => IGNORED_DIR_SEGMENTS.has(segment));
48
+ function isIgnoredPath(filePath, searchTarget) {
49
+ const checkPath = isAbsolute(filePath) && isAbsolute(searchTarget) ? relative(searchTarget, filePath) : filePath;
50
+ if (!checkPath || checkPath.startsWith(".."))
51
+ return false;
52
+ return checkPath
53
+ .split("/")
54
+ .slice(0, -1)
55
+ .some((segment) => IGNORED_DIR_SEGMENTS.has(segment));
111
56
  }
112
57
  /**
113
- * Parse `grep -rnH -B -A` output into ordered per-file entries. Match lines are `path:N:text`;
114
- * context lines are `path-N-text`. Context is attributed by anchoring on the current match file's
115
- * exact path string, so a hyphen or colon inside a filename can never misattribute a line. Before
116
- * context (which precedes a file's first match) is buffered until that match names the file.
58
+ * Both engines emit NUL-terminated filenames. Only the payload after NUL contains line syntax;
59
+ * guessing the boundary from ':' or '-' can attribute a denied file's content to another path.
60
+ * Complete records survive a capture cut; a partial filename or payload is discarded.
117
61
  */
118
- function parseGrepOutput(stdout) {
62
+ function* searchRecords(stdout, truncated) {
63
+ let cursor = 0;
64
+ while (cursor < stdout.length) {
65
+ if (stdout.startsWith("--\n", cursor))
66
+ cursor += 3;
67
+ const delimiter = stdout.indexOf("\0", cursor);
68
+ if (delimiter < 0)
69
+ break;
70
+ const newline = stdout.indexOf("\n", delimiter + 1);
71
+ if (newline < 0 && truncated)
72
+ break;
73
+ const end = newline < 0 ? stdout.length : newline;
74
+ yield [stdout.slice(cursor, delimiter), stdout.slice(delimiter + 1, end)];
75
+ cursor = end + 1;
76
+ }
77
+ }
78
+ function parseGrepOutput(stdout, truncated) {
119
79
  const files = new Map();
120
- let currentFile;
121
- const pendingContext = [];
122
- const ensure = (file) => {
123
- let entries = files.get(file);
124
- if (!entries) {
125
- entries = [];
126
- files.set(file, entries);
127
- }
128
- return entries;
129
- };
130
- const attributeContext = (raw, file) => {
131
- const prefix = `${file}-`;
132
- if (!raw.startsWith(prefix)) {
133
- return false;
134
- }
135
- const rest = raw.slice(prefix.length);
136
- const sep = rest.indexOf("-");
137
- if (sep < 0) {
138
- return false;
139
- }
140
- const lineNum = Number.parseInt(rest.slice(0, sep), 10);
141
- if (!Number.isFinite(lineNum)) {
142
- return false;
143
- }
144
- ensure(file).push({ line: lineNum, text: rest.slice(sep + 1), isMatch: false });
145
- return true;
146
- };
147
- for (const raw of stdout.split("\n")) {
148
- if (raw === "" || raw === "--") {
80
+ for (const [file, payload] of searchRecords(stdout, truncated)) {
81
+ const prefix = /^(\d+)([:-])/.exec(payload);
82
+ if (!prefix)
149
83
  continue;
150
- }
151
- const matchDelim = raw.match(/^(.+?):(\d+):/);
152
- if (matchDelim) {
153
- const file = matchDelim[1];
154
- const line = Number.parseInt(matchDelim[2], 10);
155
- const text = raw.slice(matchDelim[0].length);
156
- currentFile = file;
157
- // Retro-attribute any before-context buffered ahead of this file's first match.
158
- for (const buffered of pendingContext.splice(0)) {
159
- attributeContext(buffered, file);
160
- }
161
- ensure(file).push({ line, text, isMatch: true });
162
- continue;
163
- }
164
- // Context line: attribute to the current file, else buffer for the next match.
165
- if (!currentFile || !attributeContext(raw, currentFile)) {
166
- pendingContext.push(raw);
167
- }
84
+ const entry = { line: Number(prefix[1]), text: payload.slice(prefix[0].length), isMatch: prefix[2] === ":" };
85
+ const entries = files.get(file);
86
+ if (entries)
87
+ entries.push(entry);
88
+ else
89
+ files.set(file, [entry]);
168
90
  }
169
91
  return files;
170
92
  }
93
+ function boundedList(body) {
94
+ const result = truncateHead(body);
95
+ return result.truncated
96
+ ? `${result.content}\n\n[Output truncated; narrow the pattern or path to see the rest.]`
97
+ : result.content;
98
+ }
171
99
  function renderFileGroup(file, entries, perFileMatchCap) {
172
100
  const lines = [`== ${file} ==`];
173
101
  let matchesShown = 0;
@@ -194,10 +122,7 @@ export function createGrepTool(executor, options = {}) {
194
122
  return {
195
123
  name: "grep",
196
124
  label: "grep",
197
- description: "Search file contents across a file or directory tree — an ERE regex, or a literal string with `literal:true`. " +
198
- "Output is grouped by file, capped per file, paginated, and token-bounded — prefer this over `bash grep -rn`, " +
199
- 'which floods context. `mode:"files"` returns just matching paths and `mode:"count"` per-file counts (both ' +
200
- "much cheaper when you only need to locate). Match lines are marked with `*`, context lines with a space.",
125
+ description: "Search file contents with a regex or literal pattern. Content mode marks matches with * and shows nearby context. Use files/count to locate matches cheaply.",
201
126
  parameters: grepSchema,
202
127
  execute: async (_toolCallId, { pattern, path, glob, literal, mode, caseSensitive, skip, }, signal) => {
203
128
  if (!pattern.trim()) {
@@ -213,51 +138,26 @@ export function createGrepTool(executor, options = {}) {
213
138
  tool: "grep",
214
139
  channelId: options.channelId,
215
140
  });
216
- // `-rnH` for content; `-rlH` (paths only) for `files`; `-rcH` (per-file counts) for `count`.
217
- const flags = effectiveMode === "files"
218
- ? ["-rlH"]
219
- : effectiveMode === "count"
220
- ? ["-rcH"]
221
- : ["-rnH", `-B${CONTEXT_BEFORE}`, `-A${CONTEXT_AFTER}`];
222
- flags.push(literal ? "-F" : "-E");
223
- if (caseSensitive === false) {
224
- flags.push("-i");
225
- }
226
- // Push directory and glob filters down into `grep` itself (D5.1) so a huge `node_modules`
227
- // is never scanned in the first place, rather than being scanned, capped, and then
228
- // filtered away in JS after it already ate the whole result budget (F7). The JS-side
229
- // `isIgnoredPath`/`globRegExp` filtering below stays as a backstop for a `grep` whose
230
- // `--exclude-dir` semantics differ.
231
- for (const segment of IGNORED_DIR_SEGMENTS) {
232
- flags.push(`--exclude-dir=${segment}`);
233
- }
234
- // Push `readDeny` down into `grep` so a denied subtree is never opened (D5.1). `grep`'s
235
- // `--exclude`/`--exclude-dir` match a *basename* glob, so a plain (non-glob) deny entry
236
- // becomes a basename exclude — coarser than the path guard (it also skips a same-named
237
- // dir elsewhere), but only ever *more* restrictive, and the post-parse read-guard filter
238
- // below is the actual guarantee that no denied content is returned.
239
- const denyBasenames = new Set();
240
- for (const entry of securityConfig.pathGuard.readDeny) {
241
- if (!/[*?[\]{}]/.test(entry)) {
242
- const base = basename(entry.replace(/\/+$/, ""));
243
- if (base && base !== "." && base !== "..")
244
- denyBasenames.add(base);
245
- }
246
- }
247
- for (const base of denyBasenames) {
248
- flags.push(`--exclude-dir=${shellEscape(base)}`, `--exclude=${shellEscape(base)}`);
249
- }
141
+ let basenameFilter;
250
142
  if (glob) {
251
- // Model-controlled, so it must be shell-escaped like the pattern and path below -- the
252
- // executor runs the command via `sh -c`, and an unescaped glob such as `*.ts; rm -rf x`
253
- // would otherwise run as an extra command instead of matching nothing.
254
- flags.push(`--include=${shellEscape(glob)}`);
143
+ try {
144
+ basenameFilter = compileGlobPattern(glob, { characterClasses: true });
145
+ }
146
+ catch (error) {
147
+ throw new RecoverableToolError(`Invalid filename glob (${errorMessage(error)}). Simplify the glob or omit it.`);
148
+ }
255
149
  }
256
- // `--` terminates flags so a pattern beginning with `-` is not read as one. Bounded via
257
- // `maxCaptureBytes` (D5.2) rather than a `| head -n` pipe: piping through `head` would
258
- // have `sh -c` (no pipefail) report `head`'s exit status instead of grep's, silently
259
- // masking a real grep error (bad regex, missing path) behind `head`'s always-0 exit.
260
- const command = `grep ${flags.join(" ")} -- ${shellEscape(pattern)} ${shellEscape(target)}`;
150
+ const useRg = await isRgAvailable(executor);
151
+ signal?.throwIfAborted();
152
+ const command = buildSearchCommand(useRg, {
153
+ mode: effectiveMode,
154
+ pattern,
155
+ target,
156
+ glob,
157
+ literal,
158
+ caseSensitive,
159
+ readDeny: securityConfig.pathGuard.readDeny,
160
+ });
261
161
  const result = await executor.exec(command, {
262
162
  timeout: SEARCH_TIMEOUT_SECONDS,
263
163
  signal,
@@ -266,22 +166,16 @@ export function createGrepTool(executor, options = {}) {
266
166
  // grep exit code 1 = no matches (normal), 0 = matches, >=2 = error.
267
167
  if (result.code >= 2) {
268
168
  const stderr = result.stderr.trim();
269
- throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}. ${literal
270
- ? "Check that the path exists."
271
- : "Check the regex (ERE syntax) and that the path exists, or pass literal:true."}`);
169
+ throw new RecoverableToolError(`grep failed: ${stderr || `exit code ${result.code}`}. ${literal ? "Check that the path exists." : "Check the regex syntax and path, or pass literal:true."}`);
272
170
  }
273
171
  const rawTruncated = result.stdoutTruncated === true;
274
- // A truncated capture may end mid-line; drop that dangling partial line rather than feed
275
- // it to the parser, which expects each line to be a complete match or context line.
276
- const boundedStdout = rawTruncated ? result.stdout.slice(0, result.stdout.lastIndexOf("\n")) : result.stdout;
277
- const globRegExp = glob ? globToRegExp(glob) : undefined;
278
172
  const keepFile = (file) => {
279
173
  const normalized = file.replace(/^\.\//, "");
280
- if (isIgnoredPath(normalized))
174
+ if (isIgnoredPath(normalized, target))
281
175
  return false;
282
- if (globRegExp) {
176
+ if (basenameFilter) {
283
177
  const base = normalized.split("/").pop() ?? normalized;
284
- if (!globRegExp.test(base))
178
+ if (!basenameFilter.test(base))
285
179
  return false;
286
180
  }
287
181
  return readGuardAllows(normalized, securityConfig, securityContext);
@@ -291,12 +185,7 @@ export function createGrepTool(executor, options = {}) {
291
185
  : "";
292
186
  // `mode: "files"` — just the paths that matched, one per line.
293
187
  if (effectiveMode === "files") {
294
- const paths = [
295
- ...new Set(boundedStdout
296
- .split("\n")
297
- .map((l) => l.trim())
298
- .filter(Boolean)),
299
- ]
188
+ const paths = [...new Set(result.stdout.split("\0").slice(0, -1).filter(Boolean))]
300
189
  .filter(keepFile)
301
190
  .sort((a, b) => a.localeCompare(b));
302
191
  if (paths.length === 0) {
@@ -306,21 +195,25 @@ export function createGrepTool(executor, options = {}) {
306
195
  };
307
196
  }
308
197
  return {
309
- content: [{ type: "text", text: truncateHead(paths.join("\n")).content + truncationFooter }],
198
+ content: [{ type: "text", text: boundedList(paths.join("\n")) + truncationFooter }],
310
199
  details: { fileCount: paths.length, mode: "files" },
311
200
  };
312
201
  }
313
- // `mode: "count"` — `path:N` per file that matched.
202
+ // Both engines count matching lines. The fallback derives counts from numbered records.
314
203
  if (effectiveMode === "count") {
315
- const rows = [];
316
- for (const line of boundedStdout.split("\n")) {
317
- const m = line.match(/^(.*):(\d+)$/);
318
- if (!m)
319
- continue;
320
- const count = Number.parseInt(m[2], 10);
321
- if (count > 0 && keepFile(m[1]))
322
- rows.push([m[1].replace(/^\.\//, ""), count]);
204
+ const counts = new Map();
205
+ for (const [file, payload] of searchRecords(result.stdout, rawTruncated)) {
206
+ if (useRg) {
207
+ if (/^\d+$/.test(payload))
208
+ counts.set(file, Number(payload));
209
+ }
210
+ else if (/^\d+:/.test(payload)) {
211
+ counts.set(file, (counts.get(file) ?? 0) + 1);
212
+ }
323
213
  }
214
+ const rows = [...counts]
215
+ .filter(([file, count]) => count > 0 && keepFile(file))
216
+ .map(([file, count]) => [file.replace(/^\.\//, ""), count]);
324
217
  rows.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
325
218
  if (rows.length === 0) {
326
219
  return {
@@ -331,21 +224,23 @@ export function createGrepTool(executor, options = {}) {
331
224
  const total = rows.reduce((sum, [, n]) => sum + n, 0);
332
225
  const body = rows.map(([f, n]) => `${n}\t${f}`).join("\n");
333
226
  return {
334
- content: [{ type: "text", text: truncateHead(body).content + truncationFooter }],
227
+ content: [{ type: "text", text: boundedList(body) + truncationFooter }],
335
228
  details: { matchCount: total, fileCount: rows.length, mode: "count" },
336
229
  };
337
230
  }
338
- const parsed = parseGrepOutput(boundedStdout);
231
+ const parsed = parseGrepOutput(result.stdout, rawTruncated);
339
232
  // Filter ignored dirs and (for directory scopes) the optional glob, on the basename.
340
233
  const files = [];
341
234
  for (const [file, entries] of parsed) {
235
+ if (!entries.some((entry) => entry.isMatch))
236
+ continue;
342
237
  const normalized = file.replace(/^\.\//, "");
343
- if (isIgnoredPath(normalized)) {
238
+ if (isIgnoredPath(normalized, target)) {
344
239
  continue;
345
240
  }
346
- if (globRegExp) {
241
+ if (basenameFilter) {
347
242
  const base = normalized.split("/").pop() ?? normalized;
348
- if (!globRegExp.test(base)) {
243
+ if (!basenameFilter.test(base)) {
349
244
  continue;
350
245
  }
351
246
  }
@@ -6,20 +6,24 @@ import type { PipiclawToolsConfig } from "../config/tools.js";
6
6
  import type { Executor } from "../executor.js";
7
7
  import type { FileStore } from "../file-store.js";
8
8
  import type { DeskJobManager } from "../jobs/manager.js";
9
+ import type { ModelRequests } from "../models/requests.js";
9
10
  import type { SecurityConfig } from "../security/types.js";
10
- import { type SubAgentDiscoveryResult } from "../subagents/discovery.js";
11
11
  import type { SubAgentRunManager } from "../subagents/runs.js";
12
+ import type { SubAgentDiscoveryResult } from "../subagents/types.js";
12
13
  import type { TaskControl, TaskSessionContext } from "../tasks/control.js";
13
14
  export interface CreatePipiclawToolsOptions {
14
15
  jobManager: DeskJobManager;
16
+ /** A standalone Web API request has no persistent delivery address. */
17
+ requestScoped?: boolean;
15
18
  runManager: SubAgentRunManager;
16
19
  executor: Executor;
17
20
  /** File-content port for the generic file tools (spec 044, D1); `Executor` stays command-only. */
18
21
  fileStore: FileStore;
19
22
  getCurrentModel: () => Model<Api>;
20
23
  getAvailableModels: () => Model<Api>[];
21
- resolveApiKey: (model: Model<Api>) => Promise<string>;
24
+ modelRequests: ModelRequests;
22
25
  workspaceDir: string;
26
+ appHomeDir?: string;
23
27
  /** Base for relative paths in the generic file tools, the shell's cwd and the default delegation `workingDirectory`. */
24
28
  cwd: string;
25
29
  desk: string;
@@ -11,6 +11,7 @@ export function createPipiclawTools(options) {
11
11
  const securityContext = {
12
12
  agentWorkspaceDir: options.workspaceDir,
13
13
  cwd: options.cwd,
14
+ ...(options.appHomeDir ? { appHomeDir: options.appHomeDir } : {}),
14
15
  };
15
16
  // The leaf tools (files, web, memory, skills) come from the single declarative
16
17
  // registry so this set, the sub-agent set, and the prompt hints share one source.
@@ -30,16 +31,18 @@ export function createPipiclawTools(options) {
30
31
  webConfig: toolsConfig.tools.web,
31
32
  toolsConfig,
32
33
  rtkEnabled: toolsConfig.tools.rtk.enabled,
33
- jobManager: options.jobManager,
34
+ jobManager: options.requestScoped ? undefined : options.jobManager,
34
35
  runManager: options.runManager,
35
36
  getCurrentModel: options.getCurrentModel,
36
37
  getAvailableModels: options.getAvailableModels,
37
- resolveApiKey: options.resolveApiKey,
38
+ modelRequests: options.modelRequests,
38
39
  getSessionSearchSettings: options.getSessionSearchSettings,
39
40
  sendMedia: options.sendMedia,
40
41
  taskSession: options.taskSession,
41
42
  taskControl: options.taskControl,
42
- });
43
+ }, { requestScoped: options.requestScoped });
44
+ if (options.requestScoped)
45
+ return leafTools;
43
46
  const subAgentToolOptions = {
44
47
  buildWorkerTools: (request) => buildToolSet(request, { forSubagent: true }),
45
48
  getRunManager: () => options.runManager,
@@ -47,8 +50,9 @@ export function createPipiclawTools(options) {
47
50
  fileStore: options.fileStore,
48
51
  getCurrentModel: options.getCurrentModel,
49
52
  getAvailableModels: options.getAvailableModels,
50
- resolveApiKey: options.resolveApiKey,
53
+ modelRequests: options.modelRequests,
51
54
  workspaceDir: options.workspaceDir,
55
+ appHomeDir: options.appHomeDir,
52
56
  // A delegation runs in the parent's cwd unless the model passes an explicit workingDirectory.
53
57
  workingDirectory: options.cwd,
54
58
  deskDir: options.deskDir,
@@ -58,6 +62,7 @@ export function createPipiclawTools(options) {
58
62
  securityConfig,
59
63
  webConfig: toolsConfig.tools.web,
60
64
  rtkEnabled: toolsConfig.tools.rtk.enabled,
65
+ bashInterceptorEnabled: toolsConfig.tools.bashInterceptor.enabled,
61
66
  runtimeContext: {
62
67
  workspaceDir: options.workspaceDir,
63
68
  desk: options.desk,
package/dist/tools/job.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Type } from "typebox";
2
2
  import { formatDuration } from "../shared/format.js";
3
3
  import { RecoverableToolError } from "../shared/recoverable-error.js";
4
+ import { BASH_MAX_OUTPUT_BYTES, BASH_MAX_OUTPUT_LINES, formatFullOutputHint } from "./bash.js";
4
5
  import { truncateTail } from "./truncate.js";
5
6
  const jobSchema = Type.Object({
6
7
  op: Type.Union([Type.Literal("list"), Type.Literal("poll"), Type.Literal("cancel")], {
@@ -26,15 +27,19 @@ export function createJobTool(options) {
26
27
  for (const job of jobs) {
27
28
  const header = `### [${job.id}] ${job.label} — ${job.status}${job.exitCode !== undefined ? `, exit ${job.exitCode}` : ""}`;
28
29
  const output = await jobManager.readOutput(job.id);
29
- // Total budget across all finished jobs in one poll: 5 jobs × the 50KB per-job tail would
30
- // otherwise be 250KB of context. Once spent, later jobs get a header + a pointer only.
31
- if (spent >= COMPLETED_DETAIL_TOTAL_BUDGET) {
32
- sections.push(`${header}\n(output omitted to stay within budget — run \`job op=poll ids=["${job.id}"]\` for it)${output ? `\nFull output: ${output.spillFile}` : ""}`);
30
+ const remaining = COMPLETED_DETAIL_TOTAL_BUDGET - spent;
31
+ const path = output ? `\n${formatFullOutputHint(output.spillFile)}` : "";
32
+ if (remaining <= 0) {
33
+ sections.push(`${header}\n(output omitted to stay within budget — run \`job op=poll ids=["${job.id}"]\` for it)${path}`);
33
34
  continue;
34
35
  }
35
- const tail = output ? truncateTail(output.text).content : "";
36
+ const tail = output
37
+ ? truncateTail(output.text, {
38
+ maxBytes: Math.min(remaining, BASH_MAX_OUTPUT_BYTES),
39
+ maxLines: BASH_MAX_OUTPUT_LINES,
40
+ }).content
41
+ : "";
36
42
  const body = tail.trim() ? tail : "(no output)";
37
- const path = output ? `\nFull output: ${output.spillFile}` : "";
38
43
  spent += Buffer.byteLength(body, "utf-8");
39
44
  sections.push(`${header}\n${body}${path}`);
40
45
  }
@@ -43,11 +48,7 @@ export function createJobTool(options) {
43
48
  return {
44
49
  name: "job",
45
50
  label: "job",
46
- description: "Inspect and control this desk's background bash jobs (started with bash async:true), shared by every " +
47
- "channel bound to it. op=list shows a snapshot; op=poll waits briefly for a running job to finish and " +
48
- "returns its output; op=cancel stops jobs by id. A job's completion wakes the channel that started it " +
49
- '(a job from another channel is marked "started in <channel>"); for your own jobs, finish independent ' +
50
- "work, then end the turn when only waiting remains.",
51
+ description: "Inspect/control this desk's background bash jobs. Completion wakes the starter; other channels' jobs are marked with their origin. Finish independent work, then end the turn rather than repeatedly polling. Read background-jobs.md for job workflows.",
51
52
  parameters: jobSchema,
52
53
  execute: async (_toolCallId, { op, ids }, signal) => {
53
54
  if (op === "cancel") {
@@ -3,12 +3,14 @@ import { Type } from "typebox";
3
3
  import type { Executor } from "../executor.js";
4
4
  import type { FileStore } from "../file-store.js";
5
5
  import type { SecurityConfig, SecurityRuntimeContext } from "../security/types.js";
6
+ import type { FileObservations } from "./file-observations.js";
6
7
  declare const readSchema: Type.TObject<{
7
8
  path: Type.TString;
8
9
  offset: Type.TOptional<Type.TInteger>;
9
10
  limit: Type.TOptional<Type.TInteger>;
10
11
  }>;
11
12
  export interface ReadToolOptions {
13
+ observations?: FileObservations;
12
14
  securityConfig?: SecurityConfig;
13
15
  securityContext?: SecurityRuntimeContext;
14
16
  channelId?: string;
@@ -117,7 +117,8 @@ export function createReadTool(executor, fileStore, options = {}) {
117
117
  throw new RecoverableToolError(`Image ${path} is ${formatSize(stat.size)}, over the ${formatSize(MAX_INLINE_BINARY_BYTES)} inline limit. ` +
118
118
  "Compress or resize it first with bash (e.g. sips/convert/ffmpeg), or read it as text to inspect metadata only.");
119
119
  }
120
- const { data } = await fileStore.readBytes(target, { signal });
120
+ const { data, stat: readStat } = await fileStore.readBytes(target, { signal });
121
+ options.observations?.record(target, readStat);
121
122
  return {
122
123
  content: [
123
124
  { type: "text", text: `Read image file [${mimeType}]` },
@@ -131,7 +132,9 @@ export function createReadTool(executor, fileStore, options = {}) {
131
132
  // it still goes through `Executor`.
132
133
  const isPdf = extname(path).toLowerCase() === ".pdf";
133
134
  let pdfText = "";
135
+ let observedStat;
134
136
  if (isPdf) {
137
+ const pdfStat = options.observations ? await fileStore.stat(target).catch(() => undefined) : undefined;
135
138
  const converted = await executor.exec(`pdftotext -layout ${shellEscape(target)} - 2>&1`, { signal });
136
139
  if (converted.code === 127) {
137
140
  throw new Error(`Cannot read ${path}: pdftotext is not installed. Install poppler-utils, or ask the user to send a text version.`);
@@ -140,6 +143,7 @@ export function createReadTool(executor, fileStore, options = {}) {
140
143
  throw new Error(`Cannot read .pdf file ${path}: ${converted.stdout.trim() || "conversion produced no text"}. ` +
141
144
  `The file may be scanned/image-based — ask the user for a text version or a screenshot.`);
142
145
  }
146
+ observedStat = pdfStat;
143
147
  pdfText = converted.stdout;
144
148
  if (converted.stdoutTruncated) {
145
149
  // The 10MB capture cap hit mid-conversion — the rest of the PDF's text is gone.
@@ -199,6 +203,7 @@ export function createReadTool(executor, fileStore, options = {}) {
199
203
  if (offset !== undefined && startLine > 1) {
200
204
  throw new RecoverableToolError(`Offset ${offset} is beyond end of file (0 lines total). The file is empty; omit offset.`);
201
205
  }
206
+ observedStat = fileStat;
202
207
  selectedContent = "";
203
208
  windowEof = true;
204
209
  linesBeforeWindow = 0;
@@ -215,11 +220,12 @@ export function createReadTool(executor, fileStore, options = {}) {
215
220
  // `truncateHead` enough to apply whichever limit binds first (line or byte), however
216
221
  // short the lines are.
217
222
  const readWindowBytes = DEFAULT_MAX_BYTES * 2;
218
- const { data, eof } = await fileStore.readBytes(target, {
223
+ const { data, eof, stat: readStat, } = await fileStore.readBytes(target, {
219
224
  start: located.offset,
220
225
  maxBytes: readWindowBytes,
221
226
  signal,
222
227
  });
228
+ observedStat = readStat;
223
229
  selectedContent = data.toString("utf-8");
224
230
  windowEof = eof;
225
231
  linesBeforeWindow = startLine - 1;
@@ -281,6 +287,8 @@ export function createReadTool(executor, fileStore, options = {}) {
281
287
  // No truncation, no user limit exceeded
282
288
  outputText = truncation.content;
283
289
  }
290
+ if (observedStat)
291
+ options.observations?.record(target, observedStat);
284
292
  return {
285
293
  content: [{ type: "text", text: outputText }],
286
294
  details,