typeclaw 0.45.1 → 0.46.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 (163) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +161 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +207 -0
  11. package/src/agent/plugin-tools.ts +377 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1310 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +163 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +30 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/README.md +23 -10
  32. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  33. package/src/bundled-plugins/backup/index.ts +85 -44
  34. package/src/bundled-plugins/backup/runner.ts +85 -1
  35. package/src/bundled-plugins/doc-render/render.ts +93 -12
  36. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  37. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  38. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  39. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  40. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  41. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  42. package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
  43. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  44. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  45. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  46. package/src/bundled-plugins/memory/README.md +32 -11
  47. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  48. package/src/bundled-plugins/memory/citations.ts +22 -9
  49. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  50. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  51. package/src/bundled-plugins/memory/index.ts +0 -4
  52. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  53. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  54. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  55. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  56. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  57. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  58. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  59. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  60. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  61. package/src/bundled-plugins/researcher/write-report.ts +8 -5
  62. package/src/bundled-plugins/reviewer/index.ts +2 -2
  63. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  64. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  65. package/src/bundled-plugins/scout/scout.ts +8 -0
  66. package/src/bundled-plugins/security/index.ts +4 -4
  67. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  68. package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
  69. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  70. package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
  71. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  72. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  73. package/src/channels/adapters/discord-bot.ts +66 -6
  74. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  75. package/src/channels/adapters/discord-id.ts +4 -0
  76. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  77. package/src/channels/adapters/discord.ts +57 -7
  78. package/src/channels/adapters/github/auth-app.ts +41 -12
  79. package/src/channels/adapters/github/inbound.ts +11 -0
  80. package/src/channels/adapters/github/index.ts +71 -65
  81. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  82. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  83. package/src/channels/adapters/github/review-submitter.ts +302 -0
  84. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  85. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  86. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  87. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  88. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  89. package/src/channels/adapters/slack-bot.ts +26 -10
  90. package/src/channels/adapters/slack-classify.ts +21 -2
  91. package/src/channels/adapters/slack-format.ts +245 -0
  92. package/src/channels/adapters/slack.ts +59 -7
  93. package/src/channels/adapters/telegram-bot.ts +18 -5
  94. package/src/channels/adapters/webex-bot.ts +8 -3
  95. package/src/channels/adapters/webex.ts +8 -3
  96. package/src/channels/fetch-attachment.ts +43 -0
  97. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  98. package/src/channels/github-token-bridge.ts +12 -6
  99. package/src/channels/manager.ts +9 -0
  100. package/src/channels/router.ts +248 -6
  101. package/src/channels/types.ts +28 -1
  102. package/src/cli/channel.ts +1 -1
  103. package/src/cli/init.ts +1 -1
  104. package/src/cli/model.ts +57 -7
  105. package/src/compose/stop.ts +17 -5
  106. package/src/config/config.ts +6 -6
  107. package/src/config/models-mutation.ts +13 -1
  108. package/src/config/providers.ts +176 -0
  109. package/src/container/docker-app.ts +42 -13
  110. package/src/container/start.ts +62 -10
  111. package/src/cron/bridge.ts +9 -2
  112. package/src/doctor/checks.ts +8 -3
  113. package/src/doctor/commit.ts +2 -1
  114. package/src/doctor/file-ownership.ts +52 -0
  115. package/src/dreams/git.ts +2 -1
  116. package/src/git/bound-gc-config.ts +82 -0
  117. package/src/git/hookless.ts +5 -0
  118. package/src/git/reconcile-ignored.ts +18 -5
  119. package/src/git/system-commit.ts +12 -6
  120. package/src/hostd/spawn.ts +133 -47
  121. package/src/init/dockerfile.ts +99 -5
  122. package/src/init/index.ts +17 -5
  123. package/src/init/models-dev.ts +4 -0
  124. package/src/init/validate-api-key.ts +2 -0
  125. package/src/inspect/replay.ts +21 -9
  126. package/src/inspect/session-list.ts +71 -33
  127. package/src/mcp/tools.ts +17 -3
  128. package/src/network/internal-destinations.ts +267 -0
  129. package/src/permissions/builtins.ts +3 -1
  130. package/src/plugin/context.ts +2 -0
  131. package/src/plugin/index.ts +1 -0
  132. package/src/plugin/manager.ts +4 -0
  133. package/src/plugin/types.ts +22 -0
  134. package/src/run/index.ts +40 -0
  135. package/src/run/llm-fetch-observer.ts +41 -4
  136. package/src/sandbox/build.ts +37 -15
  137. package/src/sandbox/canonical-secrets.ts +18 -0
  138. package/src/sandbox/env-exposure.ts +83 -0
  139. package/src/sandbox/errors.ts +13 -6
  140. package/src/sandbox/hidden-paths.ts +102 -44
  141. package/src/sandbox/index.ts +22 -4
  142. package/src/sandbox/package-install.ts +3 -27
  143. package/src/sandbox/policy.ts +16 -28
  144. package/src/sandbox/privileged-runtime.ts +256 -0
  145. package/src/sandbox/session-tmp.ts +8 -2
  146. package/src/sandbox/writable-zones.ts +204 -140
  147. package/src/secrets/index.ts +8 -0
  148. package/src/secrets/refresh-provider-oauth.ts +128 -0
  149. package/src/server/command-runner.ts +48 -4
  150. package/src/server/index.ts +4 -0
  151. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  152. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  153. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  154. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  155. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  156. package/src/skills/typeclaw-config/SKILL.md +27 -11
  157. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  158. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  159. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  160. package/src/skills/typeclaw-permissions/SKILL.md +36 -19
  161. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  162. package/src/usage/scan.ts +11 -2
  163. package/typeclaw.schema.json +25 -0
@@ -0,0 +1,1310 @@
1
+ import { constants, createWriteStream, lstatSync, type Stats } from 'node:fs'
2
+ import { chmod, mkdir, mkdtemp, open, readdir, realpath, rm, stat, unlink, type FileHandle } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import path from 'node:path'
5
+ import { Transform } from 'node:stream'
6
+ import { pipeline } from 'node:stream/promises'
7
+ import { fileURLToPath, pathToFileURL } from 'node:url'
8
+
9
+ import {
10
+ checkPrivateSurfaceReadGuard,
11
+ createPrivateSurfaceReadIdentityVerifier,
12
+ type PrivateSurfaceIdentityVerifier,
13
+ } from '@/bundled-plugins/security/policies/private-surface-read'
14
+ import type { ToolFileOperands, ToolLogger, ToolResult } from '@/plugin'
15
+ import { CANONICAL_AGENT_SECRET_FILES } from '@/sandbox/canonical-secrets'
16
+ import type { HiddenPaths } from '@/sandbox/hidden-paths'
17
+
18
+ import { TOOLS_WITHOUT_LOCAL_FILE_OPERANDS } from './tools-without-local-file-operands'
19
+
20
+ export { TOOLS_WITHOUT_LOCAL_FILE_OPERANDS }
21
+
22
+ type Rewrite = { original: string; pinned: string }
23
+ type FileTarget = { get(): string; original: string; set(value: string): void; uri: boolean }
24
+ type OutputTarget = { target: FileTarget; mode: 'reserved' | 'exclusive-create' }
25
+ type VerifiedInput = {
26
+ target: FileTarget
27
+ original: string
28
+ resolved: string
29
+ dev: number
30
+ ino: number
31
+ size: number
32
+ kind: 'file' | 'directory'
33
+ }
34
+
35
+ export const TOOL_INPUT_MAX_BYTES = {
36
+ // read supports offset/limit browsing, so permit large source files while
37
+ // bounding the immutable whole-object snapshot.
38
+ read: 64 * 1024 * 1024,
39
+ // Keep local images on the same budget as look_at's bounded URL fetch.
40
+ look_at: 20 * 1024 * 1024,
41
+ // Preserve common channel upload sizes without allowing unbounded copies.
42
+ channel_upload: 100 * 1024 * 1024,
43
+ } as const
44
+
45
+ export const TOOL_INPUT_MAX_COUNT = {
46
+ read: 1,
47
+ look_at: 16,
48
+ channel_upload: 32,
49
+ } as const
50
+
51
+ export const PINNED_SNAPSHOT_GLOBAL_MAX_BYTES = TOOL_INPUT_MAX_BYTES.channel_upload
52
+ export const PINNED_SNAPSHOT_GLOBAL_MAX_COUNT = TOOL_INPUT_MAX_COUNT.channel_upload
53
+ export const PINNED_SNAPSHOT_MAX_WAITERS = 32
54
+ const TOOL_OUTPUT_MAX_COUNT = 32
55
+ const TREE_SNAPSHOT_MAX_ENTRIES = 4096
56
+ const AGENT_ROOT_SNAPSHOT_EXCLUDED_DIRS = new Set(['.git', '.gitstore', 'node_modules'])
57
+
58
+ export const TOOL_INPUT_TEMP_PREFIX = 'typeclaw-tool-input-'
59
+
60
+ export type PinnedToolFiles = {
61
+ restoreResult(result: ToolResult): ToolResult
62
+ cleanup(): Promise<void>
63
+ }
64
+
65
+ type PinnedOutputTarget = PinnedToolFiles & {
66
+ rollback(): Promise<void>
67
+ }
68
+
69
+ // Test-only seam: pauses between budget acquisition and source open/stream so a
70
+ // test can grow a file post-authorization deterministically, without racing the
71
+ // scheduler. Production never passes hooks.
72
+ export type EnforceAndPinToolFilesHooks = {
73
+ afterBudgetAcquire?(): void | Promise<void>
74
+ }
75
+
76
+ export async function enforceAndPinToolFiles(
77
+ options: {
78
+ tool: string
79
+ args: Record<string, unknown>
80
+ agentDir: string
81
+ tempRoot?: string
82
+ genericInputs?: boolean
83
+ fileOperands?: ToolFileOperands
84
+ hidden?: HiddenPaths
85
+ logger?: Pick<ToolLogger, 'warn'>
86
+ signal?: AbortSignal
87
+ },
88
+ hooks: EnforceAndPinToolFilesHooks = {},
89
+ ): Promise<PinnedToolFiles> {
90
+ if (options.signal?.aborted === true) throw abortError(options.signal)
91
+ const maxCount = maxInputCount(options.tool)
92
+ const targets = fileTargets(
93
+ options.tool,
94
+ options.args,
95
+ maxCount,
96
+ options.genericInputs === true,
97
+ options.fileOperands,
98
+ options.agentDir,
99
+ options.logger,
100
+ )
101
+ enforceCanonicalSecretDenial(options)
102
+ const outputs = outputTargets(options.tool, options.args, TOOL_OUTPUT_MAX_COUNT, options.fileOperands)
103
+ if (targets.length === 0) return outputs.length === 0 ? noPinnedFiles() : await pinOutputTargets(options, outputs)
104
+
105
+ let dir: string | undefined
106
+ const rewrites: Rewrite[] = []
107
+ const verified: VerifiedInput[] = []
108
+ const maxBytes = maxInputBytes(options.tool)
109
+ const identityOptions = {
110
+ tool: options.tool,
111
+ agentDir: options.agentDir,
112
+ hidden: options.hidden ?? { dirs: [], files: [] },
113
+ }
114
+ const initialIdentityVerifier = createPrivateSurfaceReadIdentityVerifier(identityOptions)
115
+ let lease: BudgetLease | undefined
116
+ try {
117
+ let declaredBytes = 0
118
+ for (const target of targets) {
119
+ const original = target.get()
120
+ const absolute = path.resolve(options.agentDir, original)
121
+ const resolved = await realpath(absolute).catch((error) => {
122
+ if (isNotFoundError(error)) throw new Error(`tool input did not exist while being authorized: ${original}`)
123
+ throw error
124
+ })
125
+ enforceCanonicalSecretDenial({ tool: options.tool, args: { path: resolved }, agentDir: options.agentDir })
126
+ const inspected = await stat(resolved)
127
+ const kind = inspected.isFile()
128
+ ? 'file'
129
+ : inspected.isDirectory() && isTreeInputTool(options.tool)
130
+ ? 'directory'
131
+ : undefined
132
+ if (kind === undefined) throw new Error(`tool input is not a supported regular file or directory: ${original}`)
133
+ if (kind === 'file') {
134
+ assertRegularInputFile(inspected, original)
135
+ enforceInputIdentityDenial(initialIdentityVerifier, inspected)
136
+ }
137
+ if (kind === 'file' && inspected.size > maxBytes) throw inputTooLarge(original, inspected.size, maxBytes)
138
+ declaredBytes += kind === 'file' ? inspected.size : 0
139
+ if (declaredBytes > maxBytes) throw aggregateInputTooLarge(declaredBytes, maxBytes)
140
+ verified.push({ target, original, resolved, dev: inspected.dev, ino: inspected.ino, size: inspected.size, kind })
141
+ }
142
+
143
+ lease = await pinnedSnapshotBudget.acquire(declaredBytes, verified.length, options.signal)
144
+ await hooks.afterBudgetAcquire?.()
145
+ const openedIdentityVerifier = createPrivateSurfaceReadIdentityVerifier(identityOptions)
146
+
147
+ dir = await mkdtemp(path.join(options.tempRoot ?? tmpdir(), TOOL_INPUT_TEMP_PREFIX))
148
+ let copiedBytes = 0
149
+ for (let i = 0; i < verified.length; i++) {
150
+ const input = verified[i] as VerifiedInput
151
+ const pinned = path.join(dir, String(i))
152
+ if (input.kind === 'file') {
153
+ const source = await openInput(input.resolved, input.original)
154
+ try {
155
+ const opened = await source.stat()
156
+ assertRegularInputFile(opened, input.original)
157
+ if (opened.dev !== input.dev || opened.ino !== input.ino) {
158
+ throw new Error(`tool input changed while waiting for snapshot capacity: ${input.original}`)
159
+ }
160
+ enforceInputIdentityDenial(openedIdentityVerifier, opened)
161
+ copiedBytes += await streamSnapshot(
162
+ source,
163
+ pinned,
164
+ input.original,
165
+ maxBytes,
166
+ copiedBytes,
167
+ lease,
168
+ verified.length,
169
+ options.signal,
170
+ )
171
+ await chmod(pinned, 0o400)
172
+ } finally {
173
+ await source.close()
174
+ }
175
+ } else {
176
+ copiedBytes += await snapshotDirectoryTree({
177
+ source: input,
178
+ destination: pinned,
179
+ agentDir: options.agentDir,
180
+ tool: options.tool,
181
+ maxBytes,
182
+ previouslyCopied: copiedBytes,
183
+ lease,
184
+ operandCount: verified.length,
185
+ hidden: options.hidden,
186
+ signal: options.signal,
187
+ })
188
+ }
189
+ const executionValue = input.target.uri ? pathToFileURL(pinned).href : pinned
190
+ input.target.set(executionValue)
191
+ rewrites.push({ original: input.target.original, pinned: executionValue })
192
+ }
193
+ if (!lease.resize(copiedBytes, verified.length)) throw processBudgetGrowthExceeded(copiedBytes)
194
+ } catch (error) {
195
+ try {
196
+ if (dir !== undefined) await removePinnedSnapshot(dir)
197
+ } finally {
198
+ lease?.release()
199
+ }
200
+ throw error
201
+ }
202
+
203
+ if (dir === undefined) return noPinnedFiles()
204
+
205
+ let cleaned = false
206
+
207
+ const inputPinned: PinnedToolFiles = {
208
+ restoreResult(result) {
209
+ let restored = result
210
+ for (const rewrite of rewrites) restored = replaceResultPath(restored, rewrite)
211
+ return restored
212
+ },
213
+ async cleanup() {
214
+ if (cleaned) return
215
+ cleaned = true
216
+ try {
217
+ await removePinnedSnapshot(dir)
218
+ } finally {
219
+ lease?.release()
220
+ }
221
+ },
222
+ }
223
+ if (outputs.length === 0) return inputPinned
224
+
225
+ try {
226
+ const outputPinned = await pinOutputTargets(options, outputs)
227
+ return composePinnedFiles([inputPinned, outputPinned])
228
+ } catch (error) {
229
+ await cleanupPinnedFilesReverse([inputPinned], true)
230
+ throw error
231
+ }
232
+ }
233
+
234
+ async function removePinnedSnapshot(root: string): Promise<void> {
235
+ const pending = [root]
236
+ while (pending.length > 0) {
237
+ const directory = pending.pop()
238
+ if (directory === undefined) break
239
+ await chmod(directory, 0o700)
240
+ const entries = await readdir(directory, { withFileTypes: true })
241
+ for (const entry of entries) {
242
+ if (entry.isDirectory()) pending.push(path.join(directory, entry.name))
243
+ }
244
+ }
245
+ await rm(root, { recursive: true, force: true })
246
+ }
247
+
248
+ export function enforceCanonicalSecretDenial(options: {
249
+ tool: string
250
+ args: Record<string, unknown>
251
+ agentDir: string
252
+ }): void {
253
+ const blocked = checkPrivateSurfaceReadGuard({ ...options, hidden: { dirs: [], files: [] } })
254
+ if (blocked !== undefined) throw new Error(`blocked: ${blocked.reason}`)
255
+ }
256
+
257
+ function fileTargets(
258
+ tool: string,
259
+ args: Record<string, unknown>,
260
+ maxCount: number,
261
+ genericInputs: boolean,
262
+ fileOperands: ToolFileOperands | undefined,
263
+ agentDir: string,
264
+ logger: Pick<ToolLogger, 'warn'> | undefined,
265
+ ): FileTarget[] {
266
+ if (isOutputTool(tool)) return []
267
+ if (TOOLS_WITHOUT_LOCAL_FILE_OPERANDS.has(tool)) return []
268
+ if (tool === 'read' && typeof args.path === 'string') return [propertyTarget(args, 'path')]
269
+ if (isTreeInputTool(tool)) {
270
+ if (typeof args.path !== 'string') args.path = '.'
271
+ return [propertyTarget(args, 'path')]
272
+ }
273
+ const targets: FileTarget[] = []
274
+ const addPath = (value: unknown): void => {
275
+ if (!isRecord(value) || typeof value.path !== 'string') return
276
+ targets.push(propertyTarget(value, 'path'))
277
+ if (targets.length > maxCount) throw inputCountTooLarge(targets.length, maxCount)
278
+ }
279
+ if (tool === 'look_at') {
280
+ if (Array.isArray(args.images)) for (const image of args.images) addPath(image)
281
+ return targets
282
+ }
283
+ // The only file operand for these tools is `attachments[].path`; `text` is free-form
284
+ // prose (dates like "7/16", URLs, fractions) that must never reach the generic scan,
285
+ // which rejects any value carrying a `/` or `\`. Return early even without attachments
286
+ // so a text-only message is never misread as a path. Attachment pinning is unchanged.
287
+ if (tool === 'channel_send' || tool === 'channel_reply') {
288
+ if (Array.isArray(args.attachments)) for (const attachment of args.attachments) addPath(attachment)
289
+ return targets
290
+ }
291
+ if (tool === 'channel_fetch_attachment') return targets
292
+ // post_github_review has no local file operands: `comments[].path` are remote
293
+ // GitHub diff anchors and the `body` fields are markdown. Scanning them as
294
+ // generic operands either pins a real-repo anchor into a /tmp file:// path that
295
+ // leaks into the posted review, or throws "ambiguous local file operand".
296
+ if (tool === 'post_github_review') return targets
297
+ if (genericInputs) collectGenericFileTargets(tool, args, targets, maxCount, fileOperands, agentDir, logger)
298
+ return targets
299
+ }
300
+
301
+ // Exact tool + operand-path pairs for first-party PROSE operands (message
302
+ // bodies, prompts, queries, regex/CSS/jq strings) that are never a local file.
303
+ // This table is for tools that ALSO have a real file operand and so cannot be
304
+ // whole-tool exempt via TOOLS_WITHOUT_LOCAL_FILE_OPERANDS: web_fetch pins its
305
+ // `url` (non-file URLs are exempt while file: URIs still snapshot) and treats
306
+ // `query`/`selector`/`pattern` as prose. Pure control-token tools (reload, grant_role, stream_snapshot,
307
+ // channel_edit, …) live in that set instead, so they are absent here.
308
+ //
309
+ // Scoped by full operand path, NOT key name — this is the fail-closed invariant:
310
+ // an undeclared plugin/MCP reader that reuses `content`/`prompt`/`query` must
311
+ // still hit the scan and cannot inherit an exemption from a common key name.
312
+ // Plugin/MCP tools declare their own via `fileOperands.nonFile` (survives the
313
+ // runtime `__plugin_*` name prefix, which a static table here would not).
314
+ const NON_FILE_OPERANDS: Readonly<Record<string, ReadonlySet<string>>> = {
315
+ skip_response: new Set(['reason']),
316
+ web_search: new Set(['query']),
317
+ web_fetch: new Set(['url', 'query', 'selector', 'pattern']),
318
+ todo_write: new Set(['todos.content']),
319
+ }
320
+
321
+ function isKnownNonFileOperand(tool: string, operandPath: string): boolean {
322
+ return NON_FILE_OPERANDS[tool]?.has(operandPath) === true
323
+ }
324
+
325
+ // Detection trims first: a leading-whitespace ` file://…` is still a file
326
+ // reference to any consumer that trims before parsing, so it must be pinned or
327
+ // denied, never passed through untouched. The original untrimmed string is
328
+ // preserved on the target for result restoration; the trimmed URI is what gets
329
+ // normalized and snapshotted.
330
+ function isFileUri(value: string): boolean {
331
+ return value.trim().toLocaleLowerCase().startsWith('file:')
332
+ }
333
+
334
+ function propertyTarget(object: Record<string, unknown>, key: string): FileTarget {
335
+ const raw = object[key] as string
336
+ return {
337
+ get: () => normalizeFileReference(object[key] as string),
338
+ original: raw,
339
+ set: (value) => {
340
+ object[key] = value
341
+ },
342
+ uri: isFileUri(raw),
343
+ }
344
+ }
345
+
346
+ function arrayTarget(array: unknown[], index: number): FileTarget {
347
+ const raw = array[index] as string
348
+ return {
349
+ get: () => normalizeFileReference(array[index] as string),
350
+ original: raw,
351
+ set: (value) => {
352
+ array[index] = value
353
+ },
354
+ uri: isFileUri(raw),
355
+ }
356
+ }
357
+
358
+ function outputTargets(
359
+ tool: string,
360
+ args: Record<string, unknown>,
361
+ maxCount: number,
362
+ operands: ToolFileOperands | undefined,
363
+ ): OutputTarget[] {
364
+ if (isOutputTool(tool)) {
365
+ return typeof args.path === 'string' ? [{ target: propertyTarget(args, 'path'), mode: 'reserved' }] : []
366
+ }
367
+ const outputPaths = new Set(operands?.output ?? [])
368
+ const createPaths = new Set(operands?.create ?? [])
369
+ for (const operandPath of outputPaths) {
370
+ if (createPaths.has(operandPath)) {
371
+ throw new Error(`file operand ${JSON.stringify(operandPath)} cannot be both output and create`)
372
+ }
373
+ }
374
+ const targets: OutputTarget[] = []
375
+ collectDeclaredOutputTargets(args, targets, maxCount, outputPaths, 'reserved')
376
+ collectDeclaredOutputTargets(args, targets, maxCount, createPaths, 'exclusive-create')
377
+ return targets
378
+ }
379
+
380
+ function collectDeclaredOutputTargets(
381
+ value: unknown,
382
+ out: OutputTarget[],
383
+ maxCount: number,
384
+ declared: ReadonlySet<string>,
385
+ mode: OutputTarget['mode'],
386
+ parentPath = '',
387
+ ): void {
388
+ if (Array.isArray(value)) {
389
+ const declaredOutput = declared.has(parentPath)
390
+ for (const [index, item] of value.entries()) {
391
+ if (typeof item === 'string') {
392
+ if (declaredOutput) {
393
+ out.push({ target: arrayTarget(value, index), mode })
394
+ if (out.length > maxCount) throw outputCountTooLarge(out.length, maxCount)
395
+ }
396
+ continue
397
+ }
398
+ collectDeclaredOutputTargets(item, out, maxCount, declared, mode, parentPath)
399
+ }
400
+ return
401
+ }
402
+ if (!isRecord(value)) return
403
+ for (const [childKey, item] of Object.entries(value)) {
404
+ const operandPath = parentPath === '' ? childKey : `${parentPath}.${childKey}`
405
+ if (typeof item === 'string' && declared.has(operandPath)) {
406
+ out.push({ target: propertyTarget(value, childKey), mode })
407
+ if (out.length > maxCount) throw outputCountTooLarge(out.length, maxCount)
408
+ continue
409
+ }
410
+ collectDeclaredOutputTargets(item, out, maxCount, declared, mode, operandPath)
411
+ }
412
+ }
413
+
414
+ function collectGenericFileTargets(
415
+ tool: string,
416
+ value: unknown,
417
+ out: FileTarget[],
418
+ maxCount: number,
419
+ operands: ToolFileOperands | undefined,
420
+ agentDir: string,
421
+ logger: Pick<ToolLogger, 'warn'> | undefined,
422
+ parentPath = '',
423
+ ): void {
424
+ if (Array.isArray(value)) {
425
+ const declaredInput = operands?.input?.includes(parentPath) === true
426
+ const nonInput =
427
+ operands?.output?.includes(parentPath) === true ||
428
+ operands?.create?.includes(parentPath) === true ||
429
+ operands?.destructive?.includes(parentPath) === true
430
+ const key = parentPath.split('.').at(-1) ?? parentPath
431
+ // Precedence: declared input pins; declared output/destructive is not an
432
+ // input; a known non-file operand is opaque (skipped, even a file: URI);
433
+ // otherwise an explicit file: URI pins and an undeclared path-shaped value
434
+ // fails closed. Both the static first-party table and a plugin's declared
435
+ // `fileOperands.nonFile` are tool+operand-path scoped, so an unknown tool
436
+ // never inherits an exemption from a common key name.
437
+ const declaredNonFile = !declaredInput && operands?.nonFile?.includes(parentPath) === true
438
+ const knownNonFile = !declaredInput && isKnownNonFileOperand(tool, parentPath)
439
+ for (const [index, item] of value.entries()) {
440
+ if (typeof item === 'string') {
441
+ if (declaredNonFile || (knownNonFile && !isFileUri(item))) continue
442
+ if (!nonInput && (isFileUri(item) || declaredInput)) {
443
+ out.push(arrayTarget(value, index))
444
+ if (out.length > maxCount) throw inputCountTooLarge(out.length, maxCount)
445
+ } else if (!nonInput && isAmbiguousUndeclaredLocalOperand(item, agentDir, key)) {
446
+ warnForUndeclaredExistingLocalOperand(logger, tool, parentPath, item, agentDir)
447
+ throw new Error(
448
+ `ambiguous local file operand at key ${JSON.stringify(parentPath)}; the tool author must declare fileOperands.input or the caller must use a file: URI`,
449
+ )
450
+ }
451
+ continue
452
+ }
453
+ collectGenericFileTargets(tool, item, out, maxCount, operands, agentDir, logger, parentPath)
454
+ }
455
+ return
456
+ }
457
+ if (!isRecord(value)) return
458
+ for (const [childKey, item] of Object.entries(value)) {
459
+ const operandPath = parentPath === '' ? childKey : `${parentPath}.${childKey}`
460
+ if (typeof item === 'string') {
461
+ const declaredInput = operands?.input?.includes(operandPath) === true
462
+ const nonInput =
463
+ operands?.output?.includes(operandPath) === true ||
464
+ operands?.create?.includes(operandPath) === true ||
465
+ operands?.destructive?.includes(operandPath) === true
466
+ // Declared input wins; a known non-file operand (web_search.query,
467
+ // web_fetch.selector, a plugin's declared `fileOperands.nonFile`, …) is
468
+ // opaque and skipped even when its value is a file: URI; everything else
469
+ // falls to the file:/heuristic scan below. Scoped by exact tool+operand-
470
+ // path so an undeclared plugin reader using `content`/`prompt` still
471
+ // fails closed.
472
+ const declaredNonFile = !declaredInput && operands?.nonFile?.includes(operandPath) === true
473
+ const knownNonFile = !declaredInput && isKnownNonFileOperand(tool, operandPath)
474
+ if (declaredNonFile || (knownNonFile && !isFileUri(item))) continue
475
+ if (!nonInput && (isFileUri(item) || declaredInput)) {
476
+ out.push(propertyTarget(value, childKey))
477
+ if (out.length > maxCount) throw inputCountTooLarge(out.length, maxCount)
478
+ continue
479
+ }
480
+ if (!nonInput && isAmbiguousUndeclaredLocalOperand(item, agentDir, childKey)) {
481
+ warnForUndeclaredExistingLocalOperand(logger, tool, operandPath, item, agentDir)
482
+ throw new Error(
483
+ `ambiguous local file operand at key ${JSON.stringify(operandPath)}; the tool author must declare fileOperands.input or the caller must use a file: URI`,
484
+ )
485
+ }
486
+ }
487
+ collectGenericFileTargets(tool, item, out, maxCount, operands, agentDir, logger, operandPath)
488
+ }
489
+ }
490
+
491
+ function noPinnedFiles(): PinnedToolFiles {
492
+ return { restoreResult: (result) => result, cleanup: async () => {} }
493
+ }
494
+
495
+ function composePinnedFiles(pinned: readonly PinnedToolFiles[]): PinnedToolFiles {
496
+ return {
497
+ restoreResult(result) {
498
+ return pinned.reduceRight((restored, entry) => entry.restoreResult(restored), result)
499
+ },
500
+ async cleanup() {
501
+ await cleanupPinnedFilesReverse(pinned)
502
+ },
503
+ }
504
+ }
505
+
506
+ async function cleanupPinnedFilesReverse(pinned: readonly PinnedToolFiles[], suppressErrors = false): Promise<void> {
507
+ let firstError: unknown
508
+ for (let index = pinned.length - 1; index >= 0; index -= 1) {
509
+ try {
510
+ await pinned[index]?.cleanup()
511
+ } catch (error) {
512
+ firstError ??= error
513
+ }
514
+ }
515
+ if (!suppressErrors && firstError !== undefined) throw firstError
516
+ }
517
+
518
+ async function openInput(absolute: string, original: string): Promise<FileHandle> {
519
+ try {
520
+ return await open(absolute, constants.O_RDONLY)
521
+ } catch (error) {
522
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
523
+ throw new Error(`tool input did not exist while being authorized: ${original}`)
524
+ }
525
+ throw error
526
+ }
527
+ }
528
+
529
+ async function pinOutputTargets(
530
+ options: {
531
+ tool: string
532
+ args: Record<string, unknown>
533
+ agentDir: string
534
+ signal?: AbortSignal
535
+ },
536
+ targets: OutputTarget[],
537
+ ): Promise<PinnedToolFiles> {
538
+ const pinned: PinnedOutputTarget[] = []
539
+ try {
540
+ for (const target of targets) pinned.push(await pinOutputTarget(options, target))
541
+ } catch (error) {
542
+ for (let index = pinned.length - 1; index >= 0; index -= 1) {
543
+ await pinned[index]?.rollback().catch(() => {})
544
+ }
545
+ throw error
546
+ }
547
+ return composePinnedFiles(pinned)
548
+ }
549
+
550
+ async function pinOutputTarget(
551
+ options: {
552
+ tool: string
553
+ args: Record<string, unknown>
554
+ agentDir: string
555
+ signal?: AbortSignal
556
+ },
557
+ output: OutputTarget,
558
+ ): Promise<PinnedOutputTarget> {
559
+ const { target } = output
560
+ if (options.signal?.aborted === true) throw abortError(options.signal)
561
+ const original = target.get()
562
+ const absolute = path.resolve(options.agentDir, original)
563
+ enforceCanonicalSecretDenial({ tool: options.tool, args: { path: absolute }, agentDir: options.agentDir })
564
+ if (process.platform !== 'linux') {
565
+ throw new Error('write/edit output authorization requires Linux inode anchoring; refusing an unanchored path')
566
+ }
567
+ const parent = path.dirname(absolute)
568
+ const basename = path.basename(absolute)
569
+ const noFollow = constants.O_NOFOLLOW ?? 0
570
+ const directory = await open(parent, constants.O_RDONLY | constants.O_DIRECTORY | noFollow).catch((error) => {
571
+ if (isNotFoundError(error))
572
+ throw new Error(`write/edit parent directory does not exist for anchored output: ${parent}`)
573
+ throw error
574
+ })
575
+ let targetHandle: FileHandle | undefined
576
+ let targetIdentity: { dev: number; ino: number } | undefined
577
+ let created = false
578
+ let anchored: string | undefined
579
+ try {
580
+ const fdRoot = '/proc/self/fd'
581
+ const resolvedParent = await realpath(`${fdRoot}/${directory.fd}`)
582
+ enforceCanonicalSecretDenial({
583
+ tool: options.tool,
584
+ args: { path: path.join(resolvedParent, basename) },
585
+ agentDir: options.agentDir,
586
+ })
587
+ const anchoredOutput = `${fdRoot}/${directory.fd}/${basename}`
588
+ anchored = anchoredOutput
589
+ if (output.mode === 'exclusive-create') {
590
+ const existing = await open(anchoredOutput, constants.O_RDONLY | noFollow).catch((error) => {
591
+ if (isNotFoundError(error)) return undefined
592
+ throw error
593
+ })
594
+ if (existing !== undefined) {
595
+ await existing.close()
596
+ throw new Error(`write/edit output must not already exist: ${original}`)
597
+ }
598
+ target.set(anchoredOutput)
599
+ let cleaned = false
600
+ const finalize = async (verifyCreated: boolean): Promise<void> => {
601
+ if (cleaned) return
602
+ cleaned = true
603
+ let verifyError: unknown
604
+ if (verifyCreated) {
605
+ try {
606
+ await verifyExclusiveCreatedOutput({
607
+ anchored: anchoredOutput,
608
+ original,
609
+ noFollow,
610
+ tool: options.tool,
611
+ agentDir: options.agentDir,
612
+ })
613
+ } catch (error) {
614
+ verifyError = error
615
+ }
616
+ }
617
+ const closeError = await directory.close().catch((error) => error)
618
+ if (verifyError !== undefined) throw verifyError
619
+ if (closeError !== undefined) throw closeError
620
+ }
621
+ return {
622
+ restoreResult(result) {
623
+ return replaceResultPath(result, { original, pinned: anchoredOutput })
624
+ },
625
+ async cleanup() {
626
+ await finalize(true)
627
+ },
628
+ async rollback() {
629
+ await finalize(false)
630
+ },
631
+ }
632
+ }
633
+ targetHandle = await open(anchoredOutput, constants.O_RDWR | noFollow).catch((error) => {
634
+ if (isNotFoundError(error)) return undefined
635
+ throw error
636
+ })
637
+ if (targetHandle === undefined) {
638
+ targetHandle = await open(
639
+ anchoredOutput,
640
+ constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | noFollow,
641
+ 0o666,
642
+ ).catch((error) => {
643
+ if (error instanceof Error && 'code' in error && (error.code === 'EEXIST' || error.code === 'ELOOP')) {
644
+ throw new Error(`write/edit output destination changed while being authorized: ${original}`)
645
+ }
646
+ throw error
647
+ })
648
+ created = true
649
+ }
650
+ const inspected = await targetHandle.stat()
651
+ if (!inspected.isFile() || inspected.nlink !== 1) {
652
+ throw new Error(`write/edit output is not a single-link regular file: ${original}`)
653
+ }
654
+ const authorizedIdentity = { dev: inspected.dev, ino: inspected.ino }
655
+ targetIdentity = authorizedIdentity
656
+ const resolved = await realpath(`${fdRoot}/${targetHandle.fd}`)
657
+ enforceCanonicalSecretDenial({ tool: options.tool, args: { path: resolved }, agentDir: options.agentDir })
658
+ const executionPath = `${fdRoot}/${targetHandle.fd}`
659
+ target.set(executionPath)
660
+ let cleaned = false
661
+ const finalize = async (removeCreated: boolean): Promise<void> => {
662
+ if (cleaned) return
663
+ cleaned = true
664
+ let verifyError: unknown
665
+ try {
666
+ await verifyOutputEntry({
667
+ anchored: anchoredOutput,
668
+ original,
669
+ identity: authorizedIdentity,
670
+ noFollow,
671
+ remove: removeCreated && created,
672
+ tool: options.tool,
673
+ agentDir: options.agentDir,
674
+ })
675
+ } catch (error) {
676
+ verifyError = error
677
+ }
678
+ const outcomes = await Promise.allSettled([targetHandle?.close(), directory.close()])
679
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected')
680
+ if (verifyError !== undefined) throw verifyError
681
+ if (failed?.status === 'rejected') throw failed.reason
682
+ }
683
+ return {
684
+ restoreResult(result) {
685
+ return replaceResultPath(result, { original, pinned: executionPath })
686
+ },
687
+ async cleanup() {
688
+ await finalize(false)
689
+ },
690
+ async rollback() {
691
+ await finalize(true)
692
+ },
693
+ }
694
+ } catch (error) {
695
+ if (created && anchored !== undefined && targetIdentity !== undefined) {
696
+ await verifyOutputEntry({
697
+ anchored,
698
+ original,
699
+ identity: targetIdentity,
700
+ noFollow,
701
+ remove: true,
702
+ tool: options.tool,
703
+ agentDir: options.agentDir,
704
+ }).catch(() => {})
705
+ }
706
+ await Promise.allSettled([targetHandle?.close(), directory.close()])
707
+ throw error
708
+ }
709
+ }
710
+
711
+ async function verifyExclusiveCreatedOutput(options: {
712
+ anchored: string
713
+ original: string
714
+ noFollow: number
715
+ tool: string
716
+ agentDir: string
717
+ }): Promise<void> {
718
+ const verified = await open(options.anchored, constants.O_RDONLY | options.noFollow)
719
+ try {
720
+ const inspected = await verified.stat()
721
+ if (!inspected.isFile() || inspected.nlink !== 1) {
722
+ throw new Error(`write/edit output is not a single-link regular file: ${options.original}`)
723
+ }
724
+ const resolved = await realpath(`/proc/self/fd/${verified.fd}`)
725
+ enforceCanonicalSecretDenial({ tool: options.tool, args: { path: resolved }, agentDir: options.agentDir })
726
+ } finally {
727
+ await verified.close()
728
+ }
729
+ }
730
+
731
+ async function verifyOutputEntry(options: {
732
+ anchored: string
733
+ original: string
734
+ identity: { dev: number; ino: number }
735
+ noFollow: number
736
+ remove: boolean
737
+ tool: string
738
+ agentDir: string
739
+ }): Promise<void> {
740
+ const verified = await open(options.anchored, constants.O_RDONLY | options.noFollow)
741
+ try {
742
+ const inspected = await verified.stat()
743
+ if (!inspected.isFile() || inspected.nlink !== 1) {
744
+ throw new Error(`write/edit output is not a single-link regular file: ${options.original}`)
745
+ }
746
+ if (inspected.dev !== options.identity.dev || inspected.ino !== options.identity.ino) {
747
+ throw new Error(`write/edit output destination changed during execution: ${options.original}`)
748
+ }
749
+ const resolved = await realpath(`/proc/self/fd/${verified.fd}`)
750
+ enforceCanonicalSecretDenial({ tool: options.tool, args: { path: resolved }, agentDir: options.agentDir })
751
+ if (options.remove) await unlink(options.anchored)
752
+ } finally {
753
+ await verified.close()
754
+ }
755
+ }
756
+
757
+ export async function writeFileAnchored(options: {
758
+ targetPath: string
759
+ data: Uint8Array
760
+ agentDir: string
761
+ tool: string
762
+ }): Promise<void> {
763
+ const absolute = path.resolve(options.targetPath)
764
+ enforceCanonicalSecretDenial({ tool: options.tool, args: { path: absolute }, agentDir: options.agentDir })
765
+ if (process.platform !== 'linux') {
766
+ throw new Error('safe attachment writes require Linux inode anchoring; refusing an unanchored destination')
767
+ }
768
+ const parent = await createAndOpenAnchoredDirectory(path.dirname(absolute))
769
+ let output: FileHandle | undefined
770
+ let operationError: unknown
771
+ let cleanupError: unknown
772
+ try {
773
+ const anchored = `/proc/self/fd/${parent.fd}/${path.basename(absolute)}`
774
+ output = await open(anchored, constants.O_WRONLY | constants.O_CREAT | constants.O_NOFOLLOW, 0o600)
775
+ const opened = await output.stat()
776
+ if (!opened.isFile() || opened.nlink !== 1)
777
+ throw new Error('attachment destination is not a single-link regular file')
778
+ const resolved = await realpath(`/proc/self/fd/${output.fd}`)
779
+ enforceCanonicalSecretDenial({ tool: options.tool, args: { path: resolved }, agentDir: options.agentDir })
780
+ await output.truncate(0)
781
+ await output.writeFile(options.data)
782
+ } catch (error) {
783
+ operationError = error
784
+ } finally {
785
+ const outcomes = await Promise.allSettled([output?.close(), parent.close()])
786
+ const failed = outcomes.find((outcome) => outcome.status === 'rejected')
787
+ if (failed?.status === 'rejected') cleanupError = failed.reason
788
+ }
789
+ if (operationError !== undefined) throw operationError
790
+ if (cleanupError !== undefined) throw cleanupError
791
+ }
792
+
793
+ export async function writeToolOutputNoFollow(targetPath: string, content: string): Promise<void> {
794
+ const trustedDescriptorPath = /^\/proc\/self\/fd\/\d+$/.test(targetPath)
795
+ const flags = trustedDescriptorPath
796
+ ? constants.O_WRONLY | constants.O_TRUNC
797
+ : constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW
798
+ const output = await open(targetPath, flags, 0o666)
799
+ try {
800
+ await output.writeFile(content, 'utf8')
801
+ } finally {
802
+ await output.close()
803
+ }
804
+ }
805
+
806
+ async function createAndOpenAnchoredDirectory(absolute: string): Promise<FileHandle> {
807
+ if (!path.isAbsolute(absolute)) throw new Error(`anchored directory must be absolute: ${absolute}`)
808
+ const components = absolute.split(path.sep).filter(Boolean)
809
+ let current = await open(path.parse(absolute).root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
810
+ try {
811
+ for (const component of components) {
812
+ const anchored = `/proc/self/fd/${current.fd}/${component}`
813
+ let next: FileHandle
814
+ try {
815
+ next = await open(anchored, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
816
+ } catch (error) {
817
+ if (!isNotFoundError(error)) throw error
818
+ await mkdir(anchored, { mode: 0o700 })
819
+ next = await open(anchored, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
820
+ }
821
+ await current.close()
822
+ current = next
823
+ }
824
+ return current
825
+ } catch (error) {
826
+ await current.close()
827
+ throw error
828
+ }
829
+ }
830
+
831
+ function isNotFoundError(error: unknown): boolean {
832
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT'
833
+ }
834
+
835
+ async function streamSnapshot(
836
+ source: FileHandle,
837
+ destination: string,
838
+ original: string,
839
+ maxBytes: number,
840
+ previouslyCopied: number,
841
+ lease: BudgetLease,
842
+ operandCount: number,
843
+ signal?: AbortSignal,
844
+ ): Promise<number> {
845
+ let copied = 0
846
+ const limiter = new Transform({
847
+ transform(chunk: Buffer, _encoding, callback) {
848
+ copied += chunk.byteLength
849
+ if (copied > maxBytes) {
850
+ callback(inputTooLarge(original, copied, maxBytes))
851
+ return
852
+ }
853
+ if (previouslyCopied + copied > maxBytes) {
854
+ callback(aggregateInputTooLarge(previouslyCopied + copied, maxBytes))
855
+ return
856
+ }
857
+ if (!lease.resize(previouslyCopied + copied, operandCount)) {
858
+ callback(processBudgetGrowthExceeded(previouslyCopied + copied))
859
+ return
860
+ }
861
+ callback(null, chunk)
862
+ },
863
+ })
864
+ await pipeline(
865
+ source.createReadStream({ autoClose: false, start: 0 }),
866
+ limiter,
867
+ createWriteStream(destination, {
868
+ flags: 'wx',
869
+ mode: 0o400,
870
+ }),
871
+ { signal },
872
+ )
873
+ return copied
874
+ }
875
+
876
+ async function snapshotDirectoryTree(options: {
877
+ source: VerifiedInput
878
+ destination: string
879
+ agentDir: string
880
+ tool: string
881
+ maxBytes: number
882
+ previouslyCopied: number
883
+ lease: BudgetLease
884
+ operandCount: number
885
+ hidden?: HiddenPaths
886
+ signal?: AbortSignal
887
+ }): Promise<number> {
888
+ if (process.platform !== 'linux') {
889
+ throw new Error('directory tool inputs require Linux inode anchoring; refusing an unanchored traversal')
890
+ }
891
+ const root = await open(options.source.resolved, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
892
+ try {
893
+ const opened = await root.stat()
894
+ if (opened.dev !== options.source.dev || opened.ino !== options.source.ino) {
895
+ throw new Error(`tool input changed while waiting for snapshot capacity: ${options.source.original}`)
896
+ }
897
+ await mkdir(options.destination, { mode: 0o700 })
898
+ const state = { copied: 0, entries: 0 }
899
+ const identityVerifier = createPrivateSurfaceReadIdentityVerifier({
900
+ tool: options.tool,
901
+ agentDir: options.agentDir,
902
+ hidden: options.hidden ?? { dirs: [], files: [] },
903
+ })
904
+ const openedRoot = await realpath(`/proc/self/fd/${root.fd}`)
905
+ const realAgentDir = await realpath(options.agentDir)
906
+ await snapshotOpenedDirectory(
907
+ root,
908
+ options.destination,
909
+ options,
910
+ state,
911
+ identityVerifier,
912
+ openedRoot === realAgentDir,
913
+ )
914
+ await chmod(options.destination, 0o500)
915
+ return state.copied
916
+ } finally {
917
+ await root.close()
918
+ }
919
+ }
920
+
921
+ async function snapshotOpenedDirectory(
922
+ directory: FileHandle,
923
+ destination: string,
924
+ options: Parameters<typeof snapshotDirectoryTree>[0],
925
+ state: { copied: number; entries: number },
926
+ identityVerifier: PrivateSurfaceIdentityVerifier,
927
+ isAgentRoot: boolean,
928
+ ): Promise<void> {
929
+ const sourceRoot = `/proc/self/fd/${directory.fd}`
930
+ const sourcePath = await realpath(sourceRoot)
931
+ const entries = await readdir(sourceRoot, { withFileTypes: true })
932
+ for (const entry of entries) {
933
+ if (options.signal?.aborted === true) throw abortError(options.signal)
934
+ if (isAgentRoot && AGENT_ROOT_SNAPSHOT_EXCLUDED_DIRS.has(entry.name)) continue
935
+ state.entries += 1
936
+ if (state.entries > TREE_SNAPSHOT_MAX_ENTRIES) {
937
+ throw new Error(`directory snapshot exceeds entry limit (${state.entries} > ${TREE_SNAPSHOT_MAX_ENTRIES})`)
938
+ }
939
+ const anchored = `${sourceRoot}/${entry.name}`
940
+ const target = path.join(destination, entry.name)
941
+ const candidate = path.join(sourcePath, entry.name)
942
+ if (entry.isSymbolicLink()) {
943
+ if (isDeniedSnapshotPath(candidate, options)) continue
944
+ throw new Error(`directory snapshot refuses symbolic link: ${entry.name}`)
945
+ }
946
+ if (entry.isDirectory()) {
947
+ if (isDeniedSnapshotPath(candidate, options)) continue
948
+ const child = await open(anchored, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW)
949
+ try {
950
+ const resolved = await realpath(`/proc/self/fd/${child.fd}`)
951
+ if (isDeniedSnapshotPath(resolved, options)) continue
952
+ await mkdir(target, { mode: 0o700 })
953
+ await snapshotOpenedDirectory(child, target, options, state, identityVerifier, false)
954
+ await chmod(target, 0o500)
955
+ } finally {
956
+ await child.close()
957
+ }
958
+ continue
959
+ }
960
+ if (!entry.isFile()) {
961
+ if (isDeniedSnapshotPath(candidate, options)) continue
962
+ throw new Error(`directory snapshot refuses non-regular entry: ${entry.name}`)
963
+ }
964
+ const source = await open(anchored, constants.O_RDONLY | constants.O_NOFOLLOW)
965
+ try {
966
+ const opened = await source.stat()
967
+ assertRegularInputFile(opened, candidate)
968
+ enforceInputIdentityDenial(identityVerifier, opened)
969
+ const resolved = await realpath(`/proc/self/fd/${source.fd}`)
970
+ if (isDeniedSnapshotPath(resolved, options)) continue
971
+ state.copied += await streamSnapshot(
972
+ source,
973
+ target,
974
+ resolved,
975
+ options.maxBytes,
976
+ options.previouslyCopied + state.copied,
977
+ options.lease,
978
+ options.operandCount,
979
+ options.signal,
980
+ )
981
+ await chmod(target, 0o400)
982
+ } finally {
983
+ await source.close()
984
+ }
985
+ }
986
+ }
987
+
988
+ function assertRegularInputFile(stats: Stats, original: string): void {
989
+ if (!stats.isFile()) throw new Error(`tool input changed to a non-regular file before snapshot: ${original}`)
990
+ }
991
+
992
+ function maxInputBytes(tool: string): number {
993
+ if (tool === 'look_at') return TOOL_INPUT_MAX_BYTES.look_at
994
+ if (tool === 'channel_send' || tool === 'channel_reply') return TOOL_INPUT_MAX_BYTES.channel_upload
995
+ return TOOL_INPUT_MAX_BYTES.read
996
+ }
997
+
998
+ function maxInputCount(tool: string): number {
999
+ if (tool === 'look_at') return TOOL_INPUT_MAX_COUNT.look_at
1000
+ if (tool === 'channel_send' || tool === 'channel_reply') return TOOL_INPUT_MAX_COUNT.channel_upload
1001
+ return TOOL_INPUT_MAX_COUNT.read
1002
+ }
1003
+
1004
+ function isOutputTool(tool: string): boolean {
1005
+ return tool === 'write' || tool === 'edit'
1006
+ }
1007
+
1008
+ function isTreeInputTool(tool: string): boolean {
1009
+ return tool === 'grep' || tool === 'find' || tool === 'ls'
1010
+ }
1011
+
1012
+ function isAmbiguousUndeclaredLocalOperand(value: string, agentDir: string, key: string): boolean {
1013
+ // Filesystem reality wins over semantic spelling: an existing entry named
1014
+ // like a repository slug, date, URL, or package coordinate is still a local
1015
+ // operand and must be declared so it is authorized and pinned.
1016
+ const resolved = path.resolve(agentDir, value)
1017
+ try {
1018
+ lstatSync(resolved)
1019
+ return true
1020
+ } catch (error) {
1021
+ if (!isNotFoundError(error)) return true
1022
+ }
1023
+
1024
+ const basename = path.posix.basename(value.replaceAll('\\', '/'))
1025
+ if (CANONICAL_AGENT_SECRET_FILES.includes(basename as (typeof CANONICAL_AGENT_SECRET_FILES)[number])) return true
1026
+
1027
+ if (isFileShapedKey(key)) return !(normalizedKey(key) === 'path' && isSafeApiRoute(value))
1028
+ if (value.startsWith('/') || /^[A-Za-z]:[\\/]/.test(value) || /^(?:\\\\|\/\/)[^\\/]/.test(value)) return true
1029
+ if (value.startsWith('./') || value.startsWith('../')) return true
1030
+ if (isSemanticGenericString(key, value)) return false
1031
+ if (/[\\/]/.test(value)) return true
1032
+ if (/^[^./\\\s][^/\\\s]*\.[A-Za-z0-9][A-Za-z0-9._-]*$/.test(value)) return true
1033
+ return false
1034
+ }
1035
+
1036
+ function isFileShapedKey(key: string): boolean {
1037
+ const normalized = normalizedKey(key)
1038
+ return (
1039
+ normalized === 'path' ||
1040
+ normalized === 'file' ||
1041
+ normalized === 'filepath' ||
1042
+ normalized === 'filename' ||
1043
+ normalized.endsWith('path') ||
1044
+ normalized.endsWith('filepath') ||
1045
+ normalized.endsWith('filename')
1046
+ )
1047
+ }
1048
+
1049
+ function normalizedKey(key: string): string {
1050
+ return key.replaceAll(/[-_]/g, '').toLocaleLowerCase()
1051
+ }
1052
+
1053
+ function isSemanticGenericString(key: string, value: string): boolean {
1054
+ if (isExplicitNonFileUrl(value)) return true
1055
+ const normalized = normalizedKey(key)
1056
+ if (
1057
+ (normalized === 'repository' || normalized === 'repositoryslug' || normalized === 'reposlug') &&
1058
+ isSafeRepositorySlug(value)
1059
+ ) {
1060
+ return true
1061
+ }
1062
+ if ((normalized === 'date' || normalized === 'fraction') && isSafeNumericDateOrFraction(value)) return true
1063
+ return isPackageCoordinateKey(normalized) && isSafePackageCoordinate(value)
1064
+ }
1065
+
1066
+ function isExplicitNonFileUrl(value: string): boolean {
1067
+ const trimmed = value.trim()
1068
+ if (/^[A-Za-z]:[\\/]/.test(trimmed)) return false
1069
+ if (!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(trimmed) || trimmed.toLocaleLowerCase().startsWith('file:')) return false
1070
+ try {
1071
+ return new URL(trimmed).protocol !== 'file:'
1072
+ } catch {
1073
+ return false
1074
+ }
1075
+ }
1076
+
1077
+ function isSafeApiRoute(value: string): boolean {
1078
+ if (!/^\/v\d+\//.test(value) || value.includes('\\') || value.includes('//')) return false
1079
+ for (const segment of value.split('/').slice(1)) {
1080
+ if (segment.length === 0) return false
1081
+ let decoded: string
1082
+ try {
1083
+ decoded = decodeURIComponent(segment)
1084
+ } catch {
1085
+ return false
1086
+ }
1087
+ if (decoded === '.' || decoded === '..' || decoded.includes('/') || decoded.includes('\\')) return false
1088
+ }
1089
+ return true
1090
+ }
1091
+
1092
+ function isSafeRepositorySlug(value: string): boolean {
1093
+ const match = /^([A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?)\/([A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?)$/.exec(
1094
+ value,
1095
+ )
1096
+ return match !== null && match[1] !== '.' && match[1] !== '..' && match[2] !== '.' && match[2] !== '..'
1097
+ }
1098
+
1099
+ function isSafeNumericDateOrFraction(value: string): boolean {
1100
+ return /^\d{1,4}([/-])\d{1,2}(?:\1\d{1,4})?$/.test(value)
1101
+ }
1102
+
1103
+ function isPackageCoordinateKey(normalized: string): boolean {
1104
+ return (
1105
+ normalized === 'package' ||
1106
+ normalized === 'packagename' ||
1107
+ normalized === 'packagespec' ||
1108
+ normalized === 'packagecoordinate'
1109
+ )
1110
+ }
1111
+
1112
+ function isSafePackageCoordinate(value: string): boolean {
1113
+ if (/^@[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*(?:@[^\s/]+)?$/.test(value)) return true
1114
+ if (/^[A-Za-z0-9][A-Za-z0-9._-]*@[^\s/@]+$/.test(value)) return true
1115
+ if (/^[A-Za-z0-9_.-]+:[A-Za-z0-9_.-]+(?::[A-Za-z0-9_.+-]+){0,3}$/.test(value)) return true
1116
+ if (/^(?:[A-Za-z_][A-Za-z0-9_-]*\.)+[A-Za-z_][A-Za-z0-9_-]*$/.test(value)) return true
1117
+ const segments = value.split('/')
1118
+ return segments.length > 1 && segments.every((segment) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(segment))
1119
+ }
1120
+
1121
+ function warnForUndeclaredExistingLocalOperand(
1122
+ logger: Pick<ToolLogger, 'warn'> | undefined,
1123
+ tool: string,
1124
+ operandPath: string,
1125
+ value: string,
1126
+ agentDir: string,
1127
+ ): void {
1128
+ if (logger === undefined) return
1129
+ try {
1130
+ lstatSync(path.resolve(agentDir, value))
1131
+ } catch {
1132
+ return
1133
+ }
1134
+ try {
1135
+ logger.warn(
1136
+ `[tool-file-safety] ${tool} received an undeclared existing local operand at ${JSON.stringify(operandPath)}; declare fileOperands.input to authorize immutable snapshotting`,
1137
+ )
1138
+ } catch {
1139
+ // Diagnostics must never change authorization behavior.
1140
+ }
1141
+ }
1142
+
1143
+ function enforceInputIdentityDenial(
1144
+ verifier: PrivateSurfaceIdentityVerifier,
1145
+ identity: Pick<Stats, 'dev' | 'ino' | 'nlink'>,
1146
+ ): void {
1147
+ const blocked = verifier.check(identity)
1148
+ if (blocked !== undefined) throw new Error(`blocked: ${blocked.reason}`)
1149
+ }
1150
+
1151
+ function isDeniedSnapshotPath(
1152
+ candidate: string,
1153
+ options: { agentDir: string; tool: string; hidden?: HiddenPaths },
1154
+ ): boolean {
1155
+ return (
1156
+ checkPrivateSurfaceReadGuard({
1157
+ tool: options.tool,
1158
+ args: { path: candidate },
1159
+ agentDir: options.agentDir,
1160
+ hidden: options.hidden ?? { dirs: [], files: [] },
1161
+ }) !== undefined
1162
+ )
1163
+ }
1164
+
1165
+ function normalizeFileReference(value: string): string {
1166
+ const trimmed = value.trim()
1167
+ if (!trimmed.toLocaleLowerCase().startsWith('file:')) return value
1168
+ try {
1169
+ return fileURLToPath(trimmed)
1170
+ } catch {
1171
+ throw new Error(`invalid file URI: ${value}`)
1172
+ }
1173
+ }
1174
+
1175
+ function inputTooLarge(original: string, size: number, maxBytes: number): Error {
1176
+ return new Error(`tool input is too large: ${original} (${size} bytes > ${maxBytes} byte limit)`)
1177
+ }
1178
+
1179
+ function aggregateInputTooLarge(size: number, maxBytes: number): Error {
1180
+ return new Error(`tool inputs exceed the aggregate byte limit (${size} bytes > ${maxBytes} byte limit)`)
1181
+ }
1182
+
1183
+ function processBudgetGrowthExceeded(size: number): Error {
1184
+ return new Error(`tool snapshot growth exceeds the process-wide pinned byte budget (${size} bytes requested)`)
1185
+ }
1186
+
1187
+ function inputCountTooLarge(count: number, maxCount: number): Error {
1188
+ return new Error(`tool input count exceeds the per-invocation limit (${count} > ${maxCount})`)
1189
+ }
1190
+
1191
+ function outputCountTooLarge(count: number, maxCount: number): Error {
1192
+ return new Error(`tool output count exceeds the per-invocation limit (${count} > ${maxCount})`)
1193
+ }
1194
+
1195
+ function replaceResultPath(result: ToolResult, rewrite: Rewrite): ToolResult {
1196
+ const content = result.content.map((part) =>
1197
+ part.type === 'text' ? { ...part, text: part.text.split(rewrite.pinned).join(rewrite.original) } : part,
1198
+ )
1199
+ const details = replaceDeep(result.details, rewrite)
1200
+ return { content, details }
1201
+ }
1202
+
1203
+ function replaceDeep(value: unknown, rewrite: Rewrite): unknown {
1204
+ if (typeof value === 'string') return value.split(rewrite.pinned).join(rewrite.original)
1205
+ if (Array.isArray(value)) return value.map((item) => replaceDeep(item, rewrite))
1206
+ if (isRecord(value))
1207
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, replaceDeep(item, rewrite)]))
1208
+ return value
1209
+ }
1210
+
1211
+ function isRecord(value: unknown): value is Record<string, unknown> {
1212
+ return value !== null && typeof value === 'object'
1213
+ }
1214
+
1215
+ type BudgetRequest = {
1216
+ bytes: number
1217
+ count: number
1218
+ signal?: AbortSignal
1219
+ resolve(lease: BudgetLease): void
1220
+ reject(error: Error): void
1221
+ onAbort?: () => void
1222
+ }
1223
+
1224
+ type BudgetLease = {
1225
+ resize(bytes: number, count: number): boolean
1226
+ release(): void
1227
+ }
1228
+
1229
+ class PinnedSnapshotBudget {
1230
+ private bytes = 0
1231
+ private count = 0
1232
+ private readonly queue: BudgetRequest[] = []
1233
+
1234
+ async acquire(bytes: number, count: number, signal?: AbortSignal): Promise<BudgetLease> {
1235
+ if (bytes > PINNED_SNAPSHOT_GLOBAL_MAX_BYTES || count > PINNED_SNAPSHOT_GLOBAL_MAX_COUNT) {
1236
+ throw new Error('tool inputs exceed the process-wide pinned snapshot budget')
1237
+ }
1238
+ if (signal?.aborted === true) throw abortError(signal)
1239
+ if (this.queue.length >= PINNED_SNAPSHOT_MAX_WAITERS) {
1240
+ throw new Error(`pinned snapshot waiter queue is full (${PINNED_SNAPSHOT_MAX_WAITERS} waiters)`)
1241
+ }
1242
+ return await new Promise<BudgetLease>((resolve, reject) => {
1243
+ const request: BudgetRequest = { bytes, count, signal, resolve, reject }
1244
+ if (signal !== undefined) {
1245
+ request.onAbort = () => {
1246
+ const index = this.queue.indexOf(request)
1247
+ if (index === -1) return
1248
+ this.queue.splice(index, 1)
1249
+ reject(abortError(signal))
1250
+ this.drain()
1251
+ }
1252
+ signal.addEventListener('abort', request.onAbort, { once: true })
1253
+ }
1254
+ this.queue.push(request)
1255
+ this.drain()
1256
+ })
1257
+ }
1258
+
1259
+ private drain(): void {
1260
+ while (this.queue.length > 0) {
1261
+ const next = this.queue[0] as BudgetRequest
1262
+ if (
1263
+ this.bytes + next.bytes > PINNED_SNAPSHOT_GLOBAL_MAX_BYTES ||
1264
+ this.count + next.count > PINNED_SNAPSHOT_GLOBAL_MAX_COUNT
1265
+ ) {
1266
+ return
1267
+ }
1268
+ this.queue.shift()
1269
+ if (next.onAbort !== undefined) next.signal?.removeEventListener('abort', next.onAbort)
1270
+ this.bytes += next.bytes
1271
+ this.count += next.count
1272
+ let released = false
1273
+ let leasedBytes = next.bytes
1274
+ let leasedCount = next.count
1275
+ next.resolve({
1276
+ resize: (bytes, count) => {
1277
+ if (released) return false
1278
+ const byteDelta = bytes - leasedBytes
1279
+ const countDelta = count - leasedCount
1280
+ if (
1281
+ this.bytes + byteDelta > PINNED_SNAPSHOT_GLOBAL_MAX_BYTES ||
1282
+ this.count + countDelta > PINNED_SNAPSHOT_GLOBAL_MAX_COUNT
1283
+ ) {
1284
+ return false
1285
+ }
1286
+ this.bytes += byteDelta
1287
+ this.count += countDelta
1288
+ leasedBytes = bytes
1289
+ leasedCount = count
1290
+ this.drain()
1291
+ return true
1292
+ },
1293
+ release: () => {
1294
+ if (released) return
1295
+ released = true
1296
+ this.bytes -= leasedBytes
1297
+ this.count -= leasedCount
1298
+ this.drain()
1299
+ },
1300
+ })
1301
+ }
1302
+ }
1303
+ }
1304
+
1305
+ const pinnedSnapshotBudget = new PinnedSnapshotBudget()
1306
+
1307
+ function abortError(signal: AbortSignal): Error {
1308
+ const reason = signal.reason
1309
+ return new Error(`pinned snapshot wait aborted${reason === undefined ? '' : `: ${String(reason)}`}`)
1310
+ }