@namzu/sdk 74.1.0 → 76.0.0

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 (251) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/dist/bridge/acp/server.d.ts +2 -0
  3. package/dist/bridge/acp/server.d.ts.map +1 -1
  4. package/dist/bridge/acp/server.js +13 -2
  5. package/dist/bridge/acp/server.js.map +1 -1
  6. package/dist/bridge/acp/update.d.ts.map +1 -1
  7. package/dist/bridge/acp/update.js +22 -2
  8. package/dist/bridge/acp/update.js.map +1 -1
  9. package/dist/connector/mcp/adapter.d.ts +1 -1
  10. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  11. package/dist/connector/mcp/adapter.js +3 -2
  12. package/dist/connector/mcp/adapter.js.map +1 -1
  13. package/dist/connector/mcp/client.d.ts +4 -25
  14. package/dist/connector/mcp/client.d.ts.map +1 -1
  15. package/dist/connector/mcp/client.js +32 -32
  16. package/dist/connector/mcp/client.js.map +1 -1
  17. package/dist/peers/record.d.ts +3 -3
  18. package/dist/provider/errors.d.ts.map +1 -1
  19. package/dist/provider/errors.js +13 -18
  20. package/dist/provider/errors.js.map +1 -1
  21. package/dist/provider/stream-request-timeout.d.ts +9 -0
  22. package/dist/provider/stream-request-timeout.d.ts.map +1 -0
  23. package/dist/provider/stream-request-timeout.js +34 -0
  24. package/dist/provider/stream-request-timeout.js.map +1 -0
  25. package/dist/public-runtime.d.ts +3 -2
  26. package/dist/public-runtime.d.ts.map +1 -1
  27. package/dist/public-runtime.js +2 -1
  28. package/dist/public-runtime.js.map +1 -1
  29. package/dist/public-tools.d.ts +1 -1
  30. package/dist/public-tools.d.ts.map +1 -1
  31. package/dist/public-tools.js +1 -1
  32. package/dist/public-tools.js.map +1 -1
  33. package/dist/runtime/query/executor.d.ts +3 -0
  34. package/dist/runtime/query/executor.d.ts.map +1 -1
  35. package/dist/runtime/query/executor.js +25 -4
  36. package/dist/runtime/query/executor.js.map +1 -1
  37. package/dist/runtime/query/file-evidence-replay.d.ts +1 -0
  38. package/dist/runtime/query/file-evidence-replay.d.ts.map +1 -1
  39. package/dist/runtime/query/file-evidence-replay.js +64 -21
  40. package/dist/runtime/query/file-evidence-replay.js.map +1 -1
  41. package/dist/runtime/query/file-evidence-seed.d.ts +7 -0
  42. package/dist/runtime/query/file-evidence-seed.d.ts.map +1 -1
  43. package/dist/runtime/query/file-evidence-seed.js +12 -1
  44. package/dist/runtime/query/file-evidence-seed.js.map +1 -1
  45. package/dist/runtime/query/index.d.ts +2 -0
  46. package/dist/runtime/query/index.d.ts.map +1 -1
  47. package/dist/runtime/query/index.js +5 -2
  48. package/dist/runtime/query/index.js.map +1 -1
  49. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  50. package/dist/runtime/query/path-escalation.js +4 -3
  51. package/dist/runtime/query/path-escalation.js.map +1 -1
  52. package/dist/runtime/query/tooling.d.ts +2 -0
  53. package/dist/runtime/query/tooling.d.ts.map +1 -1
  54. package/dist/runtime/query/tooling.js +1 -0
  55. package/dist/runtime/query/tooling.js.map +1 -1
  56. package/dist/sandbox/provider/local.d.ts.map +1 -1
  57. package/dist/sandbox/provider/local.js +45 -18
  58. package/dist/sandbox/provider/local.js.map +1 -1
  59. package/dist/schedules/cron.js +1 -1
  60. package/dist/schedules/cron.js.map +1 -1
  61. package/dist/schedules/describe.js +1 -1
  62. package/dist/schedules/describe.js.map +1 -1
  63. package/dist/schedules/next-fire.d.ts +2 -2
  64. package/dist/schedules/next-fire.d.ts.map +1 -1
  65. package/dist/schedules/next-fire.js +7 -4
  66. package/dist/schedules/next-fire.js.map +1 -1
  67. package/dist/schedules/spec.d.ts.map +1 -1
  68. package/dist/schedules/spec.js +23 -7
  69. package/dist/schedules/spec.js.map +1 -1
  70. package/dist/schedules/types.d.ts +2 -0
  71. package/dist/schedules/types.d.ts.map +1 -1
  72. package/dist/session/workspace/git-worktree.d.ts +18 -0
  73. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  74. package/dist/session/workspace/git-worktree.js +100 -1
  75. package/dist/session/workspace/git-worktree.js.map +1 -1
  76. package/dist/session/workspace/index.d.ts +1 -1
  77. package/dist/session/workspace/index.d.ts.map +1 -1
  78. package/dist/session/workspace/index.js +1 -1
  79. package/dist/session/workspace/index.js.map +1 -1
  80. package/dist/store/checkpoint/contract.d.ts.map +1 -1
  81. package/dist/store/checkpoint/contract.js +5 -2
  82. package/dist/store/checkpoint/contract.js.map +1 -1
  83. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  84. package/dist/store/session-index/sqlite.js +7 -3
  85. package/dist/store/session-index/sqlite.js.map +1 -1
  86. package/dist/store/session-log/core.d.ts.map +1 -1
  87. package/dist/store/session-log/core.js +118 -25
  88. package/dist/store/session-log/core.js.map +1 -1
  89. package/dist/store/session-log/disk.js +1 -1
  90. package/dist/store/session-log/disk.js.map +1 -1
  91. package/dist/tools/admit-facts.d.ts.map +1 -1
  92. package/dist/tools/admit-facts.js +19 -0
  93. package/dist/tools/admit-facts.js.map +1 -1
  94. package/dist/tools/builtins/bash.d.ts +1 -1
  95. package/dist/tools/builtins/bash.d.ts.map +1 -1
  96. package/dist/tools/builtins/bash.js +9 -7
  97. package/dist/tools/builtins/bash.js.map +1 -1
  98. package/dist/tools/builtins/browser.d.ts +2 -2
  99. package/dist/tools/builtins/browser.d.ts.map +1 -1
  100. package/dist/tools/builtins/browser.js +15 -3
  101. package/dist/tools/builtins/browser.js.map +1 -1
  102. package/dist/tools/builtins/code-analysis.d.ts.map +1 -1
  103. package/dist/tools/builtins/code-analysis.js +4 -1
  104. package/dist/tools/builtins/code-analysis.js.map +1 -1
  105. package/dist/tools/builtins/computer-use.d.ts +19 -3
  106. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  107. package/dist/tools/builtins/computer-use.js +150 -50
  108. package/dist/tools/builtins/computer-use.js.map +1 -1
  109. package/dist/tools/builtins/edit-apply.d.ts.map +1 -1
  110. package/dist/tools/builtins/edit-apply.js +24 -10
  111. package/dist/tools/builtins/edit-apply.js.map +1 -1
  112. package/dist/tools/builtins/edit.d.ts.map +1 -1
  113. package/dist/tools/builtins/edit.js +31 -15
  114. package/dist/tools/builtins/edit.js.map +1 -1
  115. package/dist/tools/builtins/file-text.d.ts +3 -0
  116. package/dist/tools/builtins/file-text.d.ts.map +1 -0
  117. package/dist/tools/builtins/file-text.js +14 -0
  118. package/dist/tools/builtins/file-text.js.map +1 -0
  119. package/dist/tools/builtins/glob.d.ts.map +1 -1
  120. package/dist/tools/builtins/glob.js +7 -2
  121. package/dist/tools/builtins/glob.js.map +1 -1
  122. package/dist/tools/builtins/grep.d.ts.map +1 -1
  123. package/dist/tools/builtins/grep.js +8 -5
  124. package/dist/tools/builtins/grep.js.map +1 -1
  125. package/dist/tools/builtins/ls.d.ts.map +1 -1
  126. package/dist/tools/builtins/ls.js +2 -1
  127. package/dist/tools/builtins/ls.js.map +1 -1
  128. package/dist/tools/builtins/notebook-edit.d.ts.map +1 -1
  129. package/dist/tools/builtins/notebook-edit.js +19 -10
  130. package/dist/tools/builtins/notebook-edit.js.map +1 -1
  131. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  132. package/dist/tools/builtins/read-file.js +48 -24
  133. package/dist/tools/builtins/read-file.js.map +1 -1
  134. package/dist/tools/builtins/read-regular-file.d.ts +5 -0
  135. package/dist/tools/builtins/read-regular-file.d.ts.map +1 -0
  136. package/dist/tools/builtins/read-regular-file.js +23 -0
  137. package/dist/tools/builtins/read-regular-file.js.map +1 -0
  138. package/dist/tools/builtins/search-support.d.ts +2 -0
  139. package/dist/tools/builtins/search-support.d.ts.map +1 -1
  140. package/dist/tools/builtins/search-support.js +14 -0
  141. package/dist/tools/builtins/search-support.js.map +1 -1
  142. package/dist/tools/builtins/stale-before-review.d.ts.map +1 -1
  143. package/dist/tools/builtins/stale-before-review.js +8 -5
  144. package/dist/tools/builtins/stale-before-review.js.map +1 -1
  145. package/dist/tools/builtins/write-file.d.ts.map +1 -1
  146. package/dist/tools/builtins/write-file.js +17 -13
  147. package/dist/tools/builtins/write-file.js.map +1 -1
  148. package/dist/tools/coordinator/agent.d.ts.map +1 -1
  149. package/dist/tools/coordinator/agent.js +6 -0
  150. package/dist/tools/coordinator/agent.js.map +1 -1
  151. package/dist/tools/coordinator/index.d.ts.map +1 -1
  152. package/dist/tools/coordinator/index.js +6 -0
  153. package/dist/tools/coordinator/index.js.map +1 -1
  154. package/dist/tools/coordinator/progress.d.ts +9 -0
  155. package/dist/tools/coordinator/progress.d.ts.map +1 -0
  156. package/dist/tools/coordinator/progress.js +30 -0
  157. package/dist/tools/coordinator/progress.js.map +1 -0
  158. package/dist/tools/paths.d.ts +9 -0
  159. package/dist/tools/paths.d.ts.map +1 -1
  160. package/dist/tools/paths.js +39 -9
  161. package/dist/tools/paths.js.map +1 -1
  162. package/dist/tools/posix-path.d.ts +2 -14
  163. package/dist/tools/posix-path.d.ts.map +1 -1
  164. package/dist/tools/posix-path.js +7 -0
  165. package/dist/tools/posix-path.js.map +1 -1
  166. package/dist/tools/shell-output-window.d.ts +12 -0
  167. package/dist/tools/shell-output-window.d.ts.map +1 -0
  168. package/dist/tools/shell-output-window.js +92 -0
  169. package/dist/tools/shell-output-window.js.map +1 -0
  170. package/dist/types/acp/index.d.ts +3 -0
  171. package/dist/types/acp/index.d.ts.map +1 -1
  172. package/dist/types/browser/index.d.ts +4 -0
  173. package/dist/types/browser/index.d.ts.map +1 -1
  174. package/dist/types/code-analysis/index.d.ts +1 -1
  175. package/dist/types/code-analysis/index.d.ts.map +1 -1
  176. package/dist/types/computer-use/index.d.ts +4 -0
  177. package/dist/types/computer-use/index.d.ts.map +1 -1
  178. package/dist/types/provider/errors.d.ts.map +1 -1
  179. package/dist/types/provider/errors.js +3 -5
  180. package/dist/types/provider/errors.js.map +1 -1
  181. package/dist/types/session/checkpoint.d.ts +13 -0
  182. package/dist/types/session/checkpoint.d.ts.map +1 -1
  183. package/dist/types/session/checkpoint.js +33 -0
  184. package/dist/types/session/checkpoint.js.map +1 -1
  185. package/dist/types/session/events.d.ts +3 -0
  186. package/dist/types/session/events.d.ts.map +1 -1
  187. package/dist/types/session/events.js.map +1 -1
  188. package/dist/types/tool/index.d.ts +17 -0
  189. package/dist/types/tool/index.d.ts.map +1 -1
  190. package/dist/types/tool/index.js.map +1 -1
  191. package/dist/types/tool/presentation.d.ts +8 -0
  192. package/dist/types/tool/presentation.d.ts.map +1 -1
  193. package/package.json +1 -1
  194. package/src/bridge/acp/server.ts +22 -8
  195. package/src/bridge/acp/update.ts +23 -2
  196. package/src/connector/mcp/adapter.ts +4 -3
  197. package/src/connector/mcp/client.ts +33 -32
  198. package/src/provider/errors.ts +12 -19
  199. package/src/provider/stream-request-timeout.ts +34 -0
  200. package/src/public-runtime.ts +3 -0
  201. package/src/public-tools.ts +1 -0
  202. package/src/runtime/query/executor.ts +41 -6
  203. package/src/runtime/query/file-evidence-replay.ts +73 -19
  204. package/src/runtime/query/file-evidence-seed.ts +16 -0
  205. package/src/runtime/query/index.ts +9 -1
  206. package/src/runtime/query/path-escalation.ts +4 -3
  207. package/src/runtime/query/tooling.ts +3 -0
  208. package/src/sandbox/provider/local.ts +53 -25
  209. package/src/schedules/cron.ts +1 -1
  210. package/src/schedules/describe.ts +1 -1
  211. package/src/schedules/next-fire.ts +7 -4
  212. package/src/schedules/spec.ts +36 -7
  213. package/src/schedules/types.ts +2 -0
  214. package/src/session/workspace/git-worktree.ts +115 -1
  215. package/src/session/workspace/index.ts +6 -1
  216. package/src/store/checkpoint/contract.ts +9 -2
  217. package/src/store/session-index/sqlite.ts +8 -4
  218. package/src/store/session-log/core.ts +130 -26
  219. package/src/store/session-log/disk.ts +1 -1
  220. package/src/tools/admit-facts.ts +20 -0
  221. package/src/tools/builtins/bash.ts +11 -12
  222. package/src/tools/builtins/browser.ts +16 -3
  223. package/src/tools/builtins/code-analysis.ts +6 -1
  224. package/src/tools/builtins/computer-use.ts +188 -44
  225. package/src/tools/builtins/edit-apply.ts +25 -10
  226. package/src/tools/builtins/edit.ts +31 -15
  227. package/src/tools/builtins/file-text.ts +14 -0
  228. package/src/tools/builtins/glob.ts +6 -1
  229. package/src/tools/builtins/grep.ts +7 -5
  230. package/src/tools/builtins/ls.ts +2 -1
  231. package/src/tools/builtins/notebook-edit.ts +18 -11
  232. package/src/tools/builtins/read-file.ts +52 -27
  233. package/src/tools/builtins/read-regular-file.ts +25 -0
  234. package/src/tools/builtins/search-support.ts +13 -0
  235. package/src/tools/builtins/stale-before-review.ts +8 -6
  236. package/src/tools/builtins/write-file.ts +18 -12
  237. package/src/tools/coordinator/agent.ts +6 -0
  238. package/src/tools/coordinator/index.ts +6 -0
  239. package/src/tools/coordinator/progress.ts +40 -0
  240. package/src/tools/paths.ts +49 -7
  241. package/src/tools/posix-path.ts +9 -0
  242. package/src/tools/shell-output-window.ts +97 -0
  243. package/src/types/acp/index.ts +3 -0
  244. package/src/types/browser/index.ts +2 -0
  245. package/src/types/code-analysis/index.ts +1 -1
  246. package/src/types/computer-use/index.ts +17 -0
  247. package/src/types/provider/errors.ts +3 -5
  248. package/src/types/session/checkpoint.ts +37 -0
  249. package/src/types/session/events.ts +3 -0
  250. package/src/types/tool/index.ts +12 -0
  251. package/src/types/tool/presentation.ts +12 -1
@@ -4,10 +4,12 @@ import type { ToolContext, ToolResult } from '../../types/tool/index.js'
4
4
  import type { ToolFacts } from '../../types/tool/presentation.js'
5
5
  import { defineTool } from '../defineTool.js'
6
6
  import { resolveWithinAnyReal, toolRoots } from '../paths.js'
7
+ import { refuseSandboxHomePath } from '../posix-path.js'
7
8
  import { atomicWriteFile } from './atomic-write-file.js'
8
9
  import { clip } from './classifier-input.js'
9
10
  import { CURRENT_ON_DISK, movedSinceRead, staleFileError } from './content-fingerprint.js'
10
11
  import { withFileMutationLock } from './file-mutation-lock.js'
12
+ import { decodeFileText, unreadableFileText } from './file-text.js'
11
13
  import { lineDiff } from './line-diff.js'
12
14
  import { applyNotebookEdit } from './notebook-cells.js'
13
15
  import { isNotebookPath, notebookRefusal } from './notebook-guard.js'
@@ -117,9 +119,9 @@ function record(context: ToolContext, key: string, content: string): void {
117
119
  tracker.recordRead(key, content)
118
120
  }
119
121
 
120
- async function readHost(path: string): Promise<string | undefined> {
122
+ async function readHost(path: string): Promise<Buffer | undefined> {
121
123
  try {
122
- return await readFile(path, 'utf-8')
124
+ return await readFile(path)
123
125
  } catch (error) {
124
126
  if ((error as { code?: unknown } | null)?.code === 'ENOENT') return undefined
125
127
  throw error
@@ -141,14 +143,16 @@ async function refuseBeforeReview(
141
143
  if (!isNotebookPath(path)) return { error: NOT_A_NOTEBOOK }
142
144
  if (context.sandbox) return undefined
143
145
  let key: string
144
- let current: string | undefined
146
+ let bytes: Buffer | undefined
145
147
  try {
146
148
  key = await resolveWithinAnyReal(toolRoots(context), path)
147
- current = await readHost(key)
149
+ bytes = await readHost(key)
148
150
  } catch {
149
151
  return undefined
150
152
  }
151
- if (current === undefined) return undefined
153
+ if (bytes === undefined) return undefined
154
+ const current = decodeFileText(bytes)
155
+ if (current === undefined) return { error: unreadableFileText(bytes.length) }
152
156
  const problem = freshnessProblem(context, key, current)
153
157
  return problem
154
158
  ? { error: problem.error, ...(problem.facts ? { facts: problem.facts } : {}) }
@@ -213,22 +217,25 @@ export const NotebookEditTool = defineTool({
213
217
  const lockKey = context.sandbox ? `sandbox:${key}` : `local:${key}`
214
218
 
215
219
  return withFileMutationLock(lockKey, async () => {
216
- let before: string | undefined
220
+ let bytes: Buffer | undefined
217
221
  if (context.sandbox) {
222
+ refuseSandboxHomePath(key)
218
223
  try {
219
- before = (await context.sandbox.readFile(key)).toString('utf-8')
224
+ bytes = await context.sandbox.readFile(key)
220
225
  } catch {
221
- before = undefined
226
+ bytes = undefined
222
227
  }
223
228
  } else {
224
- before = await readHost(key)
229
+ bytes = await readHost(key)
225
230
  }
226
- if (before === undefined) return failure(`Notebook file does not exist: ${key}.`)
227
- if (Buffer.byteLength(before) > NOTEBOOK_MAX_BYTES) {
231
+ if (bytes === undefined) return failure(`Notebook file does not exist: ${key}.`)
232
+ if (bytes.length > NOTEBOOK_MAX_BYTES) {
228
233
  return failure(
229
234
  `${key} is larger than this tool reads. Change it with \`edit\` or a shell command. The file was not changed.`,
230
235
  )
231
236
  }
237
+ const before = decodeFileText(bytes)
238
+ if (before === undefined) return failure(unreadableFileText(bytes.length))
232
239
  const stale = freshnessProblem(context, key, before)
233
240
  if (stale) return stale
234
241
 
@@ -4,12 +4,14 @@ import { z } from 'zod'
4
4
  import type { ToolContext, ToolResult } from '../../types/tool/index.js'
5
5
  import type { ToolFacts } from '../../types/tool/presentation.js'
6
6
  import { defineTool } from '../defineTool.js'
7
- import { resolveWithinAnyReal, toolRoots } from '../paths.js'
7
+ import { resolveAllowedFile, resolveWithinAnyReal, toolRoots } from '../paths.js'
8
+ import { refuseSandboxHomePath } from '../posix-path.js'
8
9
  import { resolveRetainedOutput } from '../retained-output.js'
9
10
  import { looksBinary } from '../text-window.js'
10
11
  import { toolIsAvailable } from '../tool-is-available.js'
11
12
  import { TEXT_MAX_INPUT_BYTES, readBoundedChunks, readBoundedFile } from './bounded-file-read.js'
12
13
  import { fingerprintContent } from './content-fingerprint.js'
14
+ import { decodeFileText } from './file-text.js'
13
15
  import {
14
16
  type MediaRead,
15
17
  NOTEBOOK_MAX_BYTES,
@@ -95,8 +97,10 @@ export const ReadFileTool = defineTool({
95
97
  // roots and outside any sandbox. It is read here, as a plain window of text,
96
98
  // because the result that named it told the model to.
97
99
  const retained = await resolveRetainedOutput(context.retainedOutputDirectory, input.path)
98
- // Sandbox-aware: route through sandbox.readFile() when available
99
- if (context.sandbox && retained === undefined) {
100
+ const allowed =
101
+ retained === undefined ? await resolveAllowedFile(context, input.path) : undefined
102
+ if (context.sandbox && retained === undefined && allowed === undefined) {
103
+ refuseSandboxHomePath(input.path)
100
104
  const sandbox = context.sandbox
101
105
  const buffer = await readBoundedChunks(
102
106
  (offset, length) =>
@@ -107,7 +111,7 @@ export const ReadFileTool = defineTool({
107
111
  )
108
112
  const media = await readMediaFile(buffer, input.path, input, context, true)
109
113
  if (media) return media
110
- const binaryGuidance = describeStructuredBinaryRead(input.path, shellAvailable)
114
+ const binaryGuidance = describeStructuredBinaryRead(input.path, true, shellAvailable)
111
115
  if (binaryGuidance) {
112
116
  return {
113
117
  success: false,
@@ -125,8 +129,8 @@ export const ReadFileTool = defineTool({
125
129
  },
126
130
  }
127
131
  }
128
- const content = buffer.toString('utf-8')
129
- if (looksBinary(content))
132
+ const content = decodeFileText(buffer)
133
+ if (content === undefined || looksBinary(content))
130
134
  return unreadableAsText(input.path, buffer.length, true, shellAvailable)
131
135
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
132
136
  if (!capped.ok) return refusedRead(input.path, buffer.length, capped.message, true)
@@ -149,7 +153,8 @@ export const ReadFileTool = defineTool({
149
153
  }
150
154
  }
151
155
 
152
- const filePath = retained ?? (await resolveWithinAnyReal(toolRoots(context), input.path))
156
+ const filePath =
157
+ retained ?? allowed ?? (await resolveWithinAnyReal(toolRoots(context), input.path))
153
158
  // Pictures, PDFs and notebooks are not text: they have their own size
154
159
  // limits and are never numbered, so the text cap below does not apply.
155
160
  const namesMediaFile = namesMedia(filePath)
@@ -165,7 +170,7 @@ export const ReadFileTool = defineTool({
165
170
  )
166
171
  const media = await readMediaFile(buffer, filePath, input, context, false)
167
172
  if (media) return media
168
- const binaryGuidance = describeStructuredBinaryRead(filePath, shellAvailable)
173
+ const binaryGuidance = describeStructuredBinaryRead(filePath, false, shellAvailable)
169
174
  if (binaryGuidance) {
170
175
  return {
171
176
  success: false,
@@ -182,8 +187,8 @@ export const ReadFileTool = defineTool({
182
187
  },
183
188
  }
184
189
  }
185
- const content = buffer.toString('utf-8')
186
- if (looksBinary(content))
190
+ const content = decodeFileText(buffer)
191
+ if (content === undefined || looksBinary(content))
187
192
  return unreadableAsText(filePath, buffer.length, false, shellAvailable)
188
193
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
189
194
  if (!capped.ok) return refusedRead(filePath, buffer.length, capped.message, false)
@@ -293,6 +298,10 @@ async function readMediaFile(
293
298
  )
294
299
  }
295
300
  }
301
+ const notebookText = kind === 'notebook' ? decodeFileText(buffer) : undefined
302
+ if (kind === 'notebook' && notebookText === undefined) {
303
+ return unreadableAsText(path, buffer.length, sandboxed, toolIsAvailable(context, 'bash'))
304
+ }
296
305
  const media: MediaRead =
297
306
  kind === 'pdf'
298
307
  ? await readPdfPages(buffer, input.pages, path, context.abortSignal)
@@ -301,7 +310,7 @@ async function readMediaFile(
301
310
  // A notebook shown whole is a read like any other: the body is what a later
302
311
  // edit of it is checked against, and `notebook_edit` refuses a notebook the
303
312
  // session has not read.
304
- if (kind === 'notebook') context.fileReadTracker?.recordRead(path, buffer.toString('utf-8'))
313
+ if (notebookText !== undefined) context.fileReadTracker?.recordRead(path, notebookText)
305
314
  const text = media.parts
306
315
  .filter((part) => part.type === 'text')
307
316
  .map((part) => part.text)
@@ -475,29 +484,45 @@ function unchangedRead(
475
484
  }
476
485
  }
477
486
 
478
- function describeStructuredBinaryRead(path: string, shellAvailable: boolean): string | null {
479
- const ext = extname(path).toLowerCase()
480
- if (ext === '.docx')
481
- return buildStructuredBinaryGuidance(path, 'DOCX', 'python-docx', shellAvailable)
482
- if (ext === '.pptx')
483
- return buildStructuredBinaryGuidance(path, 'PPTX', 'python-pptx', shellAvailable)
484
- if (ext === '.xlsx')
485
- return buildStructuredBinaryGuidance(path, 'XLSX', 'openpyxl', shellAvailable)
486
- return null
487
- }
488
-
489
- function buildStructuredBinaryGuidance(
487
+ function describeStructuredBinaryRead(
490
488
  path: string,
491
- format: string,
492
- extractor: string,
489
+ sandboxed: boolean,
493
490
  shellAvailable: boolean,
494
- ): string {
491
+ ): string | null {
492
+ const format = extname(path).slice(1).toUpperCase()
493
+ const environment = sandboxed ? 'in the sandbox' : 'on the host'
494
+ let extraction: string
495
+ switch (format) {
496
+ case 'DOCX':
497
+ extraction = pythonExtractorGuidance('python-docx', 'docx', environment)
498
+ break
499
+ case 'DOCM':
500
+ extraction = `Use Python's zipfile and XML tools ${environment} to extract text from word/document.xml without running macros.`
501
+ break
502
+ case 'PPTX':
503
+ extraction = pythonExtractorGuidance('python-pptx', 'pptx', environment)
504
+ break
505
+ case 'XLSX':
506
+ case 'XLSM':
507
+ extraction = pythonExtractorGuidance('openpyxl', 'openpyxl', environment)
508
+ break
509
+ case 'ODT':
510
+ extraction = pythonExtractorGuidance('odfpy', 'odf', environment)
511
+ break
512
+ default:
513
+ return null
514
+ }
495
515
  const description = `The file "${path}" is a ${format} document package, not UTF-8 text.`
496
516
  if (!shellAvailable) return description
497
517
  return [
498
518
  description,
499
519
  'Do not use the read/cat tools as evidence for this raw file.',
500
- `Extract its text with shell/Python tooling already available in the sandbox (${extractor}), write the extracted text or summary under scratch, then read that text file.`,
520
+ extraction,
521
+ 'Write the extracted text or summary under scratch, then read that text file.',
501
522
  'If extraction fails, report the exact filename and extraction error instead of claiming the attachment is unavailable.',
502
523
  ].join('\n')
503
524
  }
525
+
526
+ function pythonExtractorGuidance(pkg: string, module: string, environment: string): string {
527
+ return `Check for the ${pkg} extractor ${environment} with python3 -c "import ${module}". If the module is missing, you may need python3 -m pip install ${pkg} in that Python environment before extracting text.`
528
+ }
@@ -0,0 +1,25 @@
1
+ import { constants } from 'node:fs'
2
+ import { lstat, open } from 'node:fs/promises'
3
+
4
+ /** Read a canonical mutation target's bytes without blocking on special files. */
5
+ export async function readRegularFileBytes(
6
+ path: string,
7
+ operation: 'Edit' | 'Write',
8
+ ): Promise<Buffer> {
9
+ const regularFileError = () => new Error(`${operation} requires a regular file.`)
10
+ if (!(await lstat(path)).isFile()) throw regularFileError()
11
+
12
+ // If the target changes after lstat, a FIFO still cannot block the open.
13
+ const file = await open(path, constants.O_RDONLY | constants.O_NONBLOCK)
14
+ try {
15
+ if (!(await file.stat()).isFile()) throw regularFileError()
16
+ return await file.readFile()
17
+ } finally {
18
+ await file.close()
19
+ }
20
+ }
21
+
22
+ /** The same read as lenient text, for the checks that only compare content (a write's staleness). */
23
+ export async function readRegularFile(path: string, operation: 'Edit' | 'Write'): Promise<string> {
24
+ return (await readRegularFileBytes(path, operation)).toString('utf-8')
25
+ }
@@ -1,8 +1,21 @@
1
+ import { stat } from 'node:fs/promises'
1
2
  import { isAbsolute, join as joinPath, posix, relative, sep } from 'node:path'
2
3
 
3
4
  import { subscribeToAbort } from '../../utils/abort.js'
4
5
  import { readPositiveIntEnv } from '../../utils/env.js'
5
6
 
7
+ /** Report a missing host search root separately from an empty search. */
8
+ export async function missingSearchRoot(path: string): Promise<boolean> {
9
+ try {
10
+ await stat(path)
11
+ return false
12
+ } catch (error) {
13
+ const code = (error as NodeJS.ErrnoException).code
14
+ if (code === 'ENOENT' || code === 'ENOTDIR') return true
15
+ throw error
16
+ }
17
+ }
18
+
6
19
  /**
7
20
  * How long grep and glob search before they return what they have. The tool
8
21
  * deadline (budget + 3 s) cancels a call outright and discards its output; a
@@ -1,9 +1,9 @@
1
- import { readFile } from 'node:fs/promises'
2
-
3
1
  import type { ToolContext } from '../../types/tool/index.js'
4
2
  import type { ToolFacts } from '../../types/tool/presentation.js'
5
- import { resolveWithinAnyReal, toolRoots } from '../paths.js'
3
+ import { resolveAllowedFile, resolveWithinAnyReal, toolRoots } from '../paths.js'
4
+ import { refuseSandboxHomePath } from '../posix-path.js'
6
5
  import { movedSinceRead, staleFileError } from './content-fingerprint.js'
6
+ import { readRegularFile } from './read-regular-file.js'
7
7
 
8
8
  /**
9
9
  * The refusal a file mutation would give for a file that moved on disk since
@@ -26,12 +26,14 @@ export async function staleBeforeReview(
26
26
  let key: string
27
27
  let current: string
28
28
  try {
29
- if (context.sandbox) {
29
+ const allowed = await resolveAllowedFile(context, path)
30
+ if (context.sandbox && allowed === undefined) {
31
+ refuseSandboxHomePath(path)
30
32
  key = path
31
33
  current = (await context.sandbox.readFile(path)).toString('utf-8')
32
34
  } else {
33
- key = await resolveWithinAnyReal(toolRoots(context), path)
34
- current = await readFile(key, 'utf-8')
35
+ key = allowed ?? (await resolveWithinAnyReal(toolRoots(context), path))
36
+ current = await readRegularFile(key, operation === 'write' ? 'Write' : 'Edit')
35
37
  }
36
38
  } catch {
37
39
  return undefined
@@ -1,10 +1,11 @@
1
- import { mkdir, readFile } from 'node:fs/promises'
1
+ import { mkdir } from 'node:fs/promises'
2
2
  import { dirname } from 'node:path'
3
3
  import { z } from 'zod'
4
4
  import type { ToolContext, ToolResult } from '../../types/tool/index.js'
5
5
  import type { ToolFacts } from '../../types/tool/presentation.js'
6
6
  import { defineTool } from '../defineTool.js'
7
- import { resolveWithinAnyReal, toolRoots } from '../paths.js'
7
+ import { resolveAllowedFile, resolveWithinAnyReal, toolRoots } from '../paths.js'
8
+ import { refuseSandboxHomePath } from '../posix-path.js'
8
9
  import { atomicWriteFile } from './atomic-write-file.js'
9
10
  import { clip } from './classifier-input.js'
10
11
  import { fingerprintContent, staleFileError } from './content-fingerprint.js'
@@ -12,6 +13,7 @@ import { withFileMutationLock } from './file-mutation-lock.js'
12
13
  import { fileWriteResult } from './file-write-result.js'
13
14
  import { jsonStringEscapes } from './json-string-hint.js'
14
15
  import { notebookRefusal } from './notebook-guard.js'
16
+ import { readRegularFile } from './read-regular-file.js'
15
17
  import { staleBeforeReview } from './stale-before-review.js'
16
18
 
17
19
  const inputSchema = z
@@ -154,9 +156,12 @@ export const WriteFileTool = defineTool({
154
156
  }
155
157
  const valid = parsed.data
156
158
  const content = valid.content ?? valid.newStr ?? ''
159
+ const allowed = await resolveAllowedFile(context, valid.path)
160
+ const sandbox = allowed === undefined ? context.sandbox : undefined
157
161
  // The sandbox has its own root, so its path is checked as typed. The
158
162
  // host path is checked below, once containment has resolved symlinks.
159
- if (context.sandbox) {
163
+ if (sandbox) {
164
+ refuseSandboxHomePath(valid.path)
160
165
  const notebook = notebookRefusal(valid.path, content)
161
166
  if (notebook) return { success: false as const, output: '', error: notebook }
162
167
  }
@@ -164,9 +169,8 @@ export const WriteFileTool = defineTool({
164
169
  // own root and its own resolver; canonicalizing a sandbox-relative
165
170
  // path against the HOST filesystem asks a question about the wrong
166
171
  // machine and answers it with whatever happens to exist there.
167
- const filePath = context.sandbox
168
- ? undefined
169
- : await resolveWithinAnyReal(toolRoots(context), valid.path)
172
+ const filePath =
173
+ allowed ?? (sandbox ? undefined : await resolveWithinAnyReal(toolRoots(context), valid.path))
170
174
  if (filePath !== undefined) {
171
175
  const notebook = notebookRefusal(filePath, content)
172
176
  if (notebook) return { success: false as const, output: '', error: notebook }
@@ -174,16 +178,16 @@ export const WriteFileTool = defineTool({
174
178
  // The exists-check and the write are a check-then-act pair. Unlocked,
175
179
  // two writers both see "absent", both skip the read-before-overwrite
176
180
  // guard, and the second silently discards the first.
177
- const lockKey = context.sandbox ? `sandbox:${valid.path}` : `local:${filePath as string}`
181
+ const lockKey = sandbox ? `sandbox:${valid.path}` : `local:${filePath as string}`
178
182
 
179
183
  return withFileMutationLock(lockKey, async () => {
180
- if (context.sandbox) {
184
+ if (sandbox) {
181
185
  const current = await readSandboxFileIfPresent(context, valid.path)
182
186
  if (current !== undefined && current !== null) {
183
187
  const guard = enforceFreshOverwrite(context, valid.path, current.toString('utf-8'))
184
188
  if (guard) return guard
185
189
  }
186
- await context.sandbox.writeFile(valid.path, content)
190
+ await sandbox.writeFile(valid.path, content)
187
191
  // This write is now the runtime's newest observation. Recording only
188
192
  // the boolean would leave an older content fingerprint in place and
189
193
  // make the next same-run write refuse its own predecessor as drift.
@@ -229,12 +233,14 @@ async function refuseWriteBeforeReview(
229
233
  // unread-file refusals are given when the call runs there, so a guest that is
230
234
  // not admitted yet, or that holds a file the host has never seen, is not
231
235
  // judged from a read made before anyone approved the call.
232
- if (context.sandbox) return staleBeforeReview(context, input.path, 'write')
233
236
  const tracker = context.fileReadTracker
234
237
  if (!tracker) return undefined
235
238
  let key: string
236
239
  try {
237
- key = await resolveWithinAnyReal(toolRoots(context), input.path)
240
+ const allowed = await resolveAllowedFile(context, input.path)
241
+ if (context.sandbox && allowed === undefined)
242
+ return staleBeforeReview(context, input.path, 'write')
243
+ key = allowed ?? (await resolveWithinAnyReal(toolRoots(context), input.path))
238
244
  if ((await readHostFileIfPresent(key)) === undefined) return undefined
239
245
  } catch {
240
246
  return undefined
@@ -288,7 +294,7 @@ function enforceFreshOverwrite(
288
294
 
289
295
  async function readHostFileIfPresent(hostPath: string): Promise<string | undefined> {
290
296
  try {
291
- return await readFile(hostPath, 'utf-8')
297
+ return await readRegularFile(hostPath, 'Write')
292
298
  } catch (error) {
293
299
  if (isMissingFileError(error)) return undefined
294
300
  throw error
@@ -8,6 +8,7 @@ import { defineTool } from '../defineTool.js'
8
8
  import { KERNEL_RECORD_PREFIX, wrapUntrusted } from '../untrusted-envelope.js'
9
9
  import { describeOutcomeRecord } from './outcome-record.js'
10
10
  import { failureLabel, taskSucceeded } from './outcome.js'
11
+ import { delegationFacts, delegationProgress } from './progress.js'
11
12
 
12
13
  import { DELEGATION_TIMEOUT_MS } from './index.js'
13
14
  import type { TaskLaunchedCallback } from './index.js'
@@ -82,6 +83,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
82
83
 
83
84
  return defineTool({
84
85
  name: 'Agent',
86
+ presentCall: ({ description }) => ({ kind: 'generic', label: description.slice(0, 240) }),
85
87
  description: `Delegate a task to a specialized subagent. BLOCKING: returns when the subagent has finished, with the subagent's final text as the tool result. The subagent runs in its own context window and cannot see your conversation — include all necessary context in the prompt. Available subagents: ${agentIds.join(', ')}. To run multiple subagents in parallel, call this tool multiple times in a single response.`,
86
88
  inputSchema: z.object({
87
89
  description: z.string().describe('Short label for tracking (shown to the user)'),
@@ -150,6 +152,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
150
152
  agentId,
151
153
  prompt,
152
154
  workingDirectory: cwd,
155
+ onEvent: delegationProgress(context),
153
156
  runtimeContext: opts.runtimeContext,
154
157
  // Hang the child off the executing tool's span, so the
155
158
  // delegation appears inside the turn that asked for it rather
@@ -203,6 +206,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
203
206
  // it: a review caught this site, and nothing carried the answer to
204
207
  // the other one.
205
208
  const succeeded = taskSucceeded(completed)
209
+ const facts = delegationFacts(completed, description)
206
210
 
207
211
  // A schema-configured child answers with an OBJECT, and this used to
208
212
  // hand the parent model the child's prose instead — so a supervisor
@@ -240,6 +244,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
240
244
  return {
241
245
  success: false,
242
246
  output: '',
247
+ facts,
243
248
  error: `Subagent ${agentId} ${failureLabel(completed)}: ${detail}${recordLine ? `\n${recordLine}` : ''}`,
244
249
  data: {
245
250
  task_id: handle.taskId,
@@ -260,6 +265,7 @@ export function buildAgentTool(opts: AgentToolOptions): ToolDefinition {
260
265
  // the result programmatically.
261
266
  return {
262
267
  success: true,
268
+ facts,
263
269
  output: `${wrapUntrusted(
264
270
  {
265
271
  kind: 'agent-result',
@@ -17,6 +17,7 @@ import { defineTool } from '../defineTool.js'
17
17
  import { wrapUntrusted } from '../untrusted-envelope.js'
18
18
  import { buildAskUserQuestionTool } from './ask-user-question.js'
19
19
  import { failureLabel, taskSucceeded } from './outcome.js'
20
+ import { delegationFacts, delegationProgress } from './progress.js'
20
21
  export { ASK_USER_QUESTION_TOOL_NAME } from './ask-user-question.js'
21
22
  import { resolvePlanDependencies } from './plan-dependencies.js'
22
23
  import { describeWaitTimeout, waitForTaskWithBounds } from './wait-with-idle-bound.js'
@@ -537,6 +538,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
537
538
 
538
539
  const createTask = defineTool({
539
540
  name: 'create_task',
541
+ presentCall: ({ description }) => ({ kind: 'generic', label: description.slice(0, 240) }),
540
542
  description: `Launch a task on a specialized agent.${backgroundClause} Available agents: ${agentIds.join(', ')}. Prefer compact assignments; for large context, write/read shared workspace files and pass filenames or references. To launch multiple tasks in parallel, call this tool multiple times in a single assistant turn — the runtime executes every tool_use block from one response concurrently and delivers all tool_results together, so 'fan out 8 specialists' is one assistant message with 8 create_task blocks. Do not race: until a worker's result reaches you, you know nothing about it — never fabricate, summarise or predict what it will say, in any form.`,
541
543
  inputSchema: z.object({
542
544
  agent_id: agentIdEnum.describe('Which agent to run'),
@@ -665,6 +667,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
665
667
  agentId: agent_id,
666
668
  prompt,
667
669
  workingDirectory: cwd,
670
+ onEvent: delegationProgress(_context),
668
671
  runtimeContext: opts.runtimeContext,
669
672
  ...(planStepId ? { planStepId } : {}),
670
673
  ...(planId ? { planId } : {}),
@@ -782,6 +785,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
782
785
  // lets `wait_for_task` and `agent_task_list` reach the output.
783
786
  return {
784
787
  success: true,
788
+ facts: delegationFacts(handle, description),
785
789
  output: `Launched ${agent_id} in the background as task ${handle.taskId}. You are not waiting on it: keep working, and its result will arrive as a task notification. To fetch it yourself, call wait_for_task with this task_id.`,
786
790
  data: {
787
791
  task_id: handle.taskId,
@@ -814,6 +818,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
814
818
  if (outcome.kind === 'timeout') {
815
819
  return {
816
820
  success: false,
821
+ facts: delegationFacts(gateway.getTask(handle.taskId) ?? handle, description),
817
822
  output: describeWaitTimeout(outcome),
818
823
  data: { task_id: handle.taskId, agent_id, timed_out: outcome.cause },
819
824
  }
@@ -850,6 +855,7 @@ export function buildCoordinatorTools(opts: CoordinatorToolsOptions): ToolDefini
850
855
 
851
856
  return {
852
857
  success,
858
+ facts: delegationFacts(completed, description),
853
859
  // Framed, because a delegated worker is the component MOST
854
860
  // likely to have consumed something nobody here wrote. It was
855
861
  // handed a task like "read these files and report", it ran
@@ -0,0 +1,40 @@
1
+ import type { TaskHandle } from '../../types/agent/scheduler.js'
2
+ import type { SessionEventListener } from '../../types/session/events.js'
3
+ import type { ToolContext } from '../../types/tool/index.js'
4
+ import type { ToolFacts } from '../../types/tool/presentation.js'
5
+
6
+ export function delegationFacts(
7
+ handle: TaskHandle,
8
+ description: string,
9
+ ): Extract<ToolFacts, { kind: 'delegate' }> {
10
+ return {
11
+ kind: 'delegate',
12
+ description: description.slice(0, 240),
13
+ childSessionId: handle.childSessionId,
14
+ childStatus:
15
+ handle.result?.status === 'cancelled'
16
+ ? 'canceled'
17
+ : handle.result?.status === 'failed'
18
+ ? 'failed'
19
+ : handle.state,
20
+ }
21
+ }
22
+
23
+ export function delegationProgress(context: ToolContext): SessionEventListener {
24
+ return (event) => {
25
+ const message =
26
+ event.type === 'tool_executing'
27
+ ? `Running ${event.toolName}`
28
+ : event.type === 'agent_pending' || event.type === 'turn_started'
29
+ ? 'Starting delegated work'
30
+ : event.type === 'message_started'
31
+ ? 'Writing a reply'
32
+ : undefined
33
+ if (message) {
34
+ context.report?.(message, undefined, {
35
+ childSessionId: event.sessionId,
36
+ childStatus: 'running',
37
+ })
38
+ }
39
+ }
40
+ }
@@ -1,7 +1,15 @@
1
- import { realpath } from 'node:fs/promises'
2
- import { tmpdir } from 'node:os'
1
+ import { lstat, realpath } from 'node:fs/promises'
2
+ import { homedir, tmpdir } from 'node:os'
3
3
  import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
4
4
 
5
+ export function isHomeRelativePath(path: string | undefined): boolean {
6
+ return path === '~' || path?.startsWith('~/') === true
7
+ }
8
+
9
+ export function expandHomePath(path: string): string {
10
+ return isHomeRelativePath(path) ? join(homedir(), path.slice(1)) : path
11
+ }
12
+
5
13
  /**
6
14
  * Resolve a caller-supplied path against a root, refusing anything that
7
15
  * lands outside it.
@@ -83,6 +91,36 @@ export function toolRoots(context: {
83
91
  ]
84
92
  }
85
93
 
94
+ /** Match the resolved spelling of one host-supplied absolute filename. */
95
+ export function isAllowedFile(
96
+ context: {
97
+ readonly workingDirectory: string
98
+ readonly allowedFiles?: readonly string[] | undefined
99
+ },
100
+ path: string,
101
+ ): boolean {
102
+ if (path === '' || path.includes('\0') || !context.allowedFiles?.length) return false
103
+ const target = resolve(context.workingDirectory, path)
104
+ return context.allowedFiles.some((file) => isAbsolute(file) && resolve(file) === target)
105
+ }
106
+
107
+ /** A listed file may be created, but an existing entry must be a regular file. */
108
+ export async function resolveAllowedFile(
109
+ context: Parameters<typeof isAllowedFile>[0],
110
+ path: string,
111
+ ): Promise<string | undefined> {
112
+ if (!isAllowedFile(context, path)) return undefined
113
+ const target = resolve(context.workingDirectory, path)
114
+ const entry = await lstat(target).catch((error: NodeJS.ErrnoException) => {
115
+ if (error.code !== 'ENOENT') throw error
116
+ return undefined
117
+ })
118
+ if (entry && !entry.isFile()) {
119
+ throw new Error(`The session file must be a regular file: ${target}.`)
120
+ }
121
+ return canonicalize(target)
122
+ }
123
+
86
124
  /**
87
125
  * The absolute path `candidate` names when it lies outside every root, or
88
126
  * `undefined` when a tool would accept it as it stands.
@@ -105,7 +143,7 @@ export async function pathOutsideRoots(
105
143
  await resolveWithinAnyReal(roots, candidate)
106
144
  return undefined
107
145
  } catch {
108
- return resolve(resolve(first), candidate)
146
+ return resolve(first, expandHomePath(candidate))
109
147
  }
110
148
  }
111
149
 
@@ -122,11 +160,13 @@ function describeRoots(roots: readonly string[]): string {
122
160
  export function resolveWithinAny(roots: readonly string[], candidate: string | undefined): string {
123
161
  const [first, ...rest] = roots
124
162
  if (first === undefined) throw new Error('No root to resolve within.')
125
- if (rest.length === 0) return resolveWithin(first, candidate)
163
+ if (rest.length === 0) {
164
+ return resolveWithin(first, candidate === undefined ? undefined : expandHomePath(candidate))
165
+ }
126
166
  const resolved =
127
167
  candidate === undefined || candidate === ''
128
168
  ? resolve(first)
129
- : resolve(resolve(first), candidate)
169
+ : resolve(first, expandHomePath(candidate))
130
170
  for (const root of roots) {
131
171
  if (isWithin(root, resolved)) return resolveWithin(root, resolved)
132
172
  }
@@ -142,11 +182,13 @@ export async function resolveWithinAnyReal(
142
182
  ): Promise<string> {
143
183
  const [first, ...rest] = roots
144
184
  if (first === undefined) throw new Error('No root to resolve within.')
145
- if (rest.length === 0) return resolveWithinReal(first, candidate)
185
+ if (rest.length === 0) {
186
+ return resolveWithinReal(first, candidate === undefined ? undefined : expandHomePath(candidate))
187
+ }
146
188
  const resolved =
147
189
  candidate === undefined || candidate === ''
148
190
  ? resolve(first)
149
- : resolve(resolve(first), candidate)
191
+ : resolve(first, expandHomePath(candidate))
150
192
  let firstError: unknown
151
193
  for (const root of roots) {
152
194
  try {
@@ -1,3 +1,5 @@
1
+ import { isHomeRelativePath } from './paths.js'
2
+
1
3
  /**
2
4
  * Path arithmetic in the SANDBOX's coordinate system.
3
5
  *
@@ -54,6 +56,13 @@ export function relativePosix(from: string, to: string): string {
54
56
  return [...up, ...toSegments.slice(shared)].join('/')
55
57
  }
56
58
 
59
+ /** The sandbox adapter does not expose the guest's home directory. */
60
+ export function refuseSandboxHomePath(candidate: string | undefined): void {
61
+ if (isHomeRelativePath(candidate)) {
62
+ throw new Error('Use an explicit sandbox path instead of ~ or ~/.')
63
+ }
64
+ }
65
+
57
66
  /**
58
67
  * Resolve `candidate` against `root`, refusing anything that lands
59
68
  * outside. The sandbox-side twin of the host containment check.