@namzu/sdk 74.0.0 → 75.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 (271) hide show
  1. package/CHANGELOG.md +65 -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 +9 -1
  5. package/dist/bridge/acp/server.js.map +1 -1
  6. package/dist/config/runtime.d.ts +3 -3
  7. package/dist/connector/mcp/adapter.d.ts +1 -1
  8. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  9. package/dist/connector/mcp/adapter.js +3 -2
  10. package/dist/connector/mcp/adapter.js.map +1 -1
  11. package/dist/connector/mcp/client.d.ts +4 -25
  12. package/dist/connector/mcp/client.d.ts.map +1 -1
  13. package/dist/connector/mcp/client.js +32 -32
  14. package/dist/connector/mcp/client.js.map +1 -1
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/manager/session/turn-recorder.d.ts +1 -0
  20. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  21. package/dist/manager/session/turn-recorder.js +31 -7
  22. package/dist/manager/session/turn-recorder.js.map +1 -1
  23. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  24. package/dist/pricing/catalogue.generated.js +176 -21
  25. package/dist/pricing/catalogue.generated.js.map +1 -1
  26. package/dist/provider/errors.d.ts.map +1 -1
  27. package/dist/provider/errors.js +13 -18
  28. package/dist/provider/errors.js.map +1 -1
  29. package/dist/provider/stream-request-timeout.d.ts +9 -0
  30. package/dist/provider/stream-request-timeout.d.ts.map +1 -0
  31. package/dist/provider/stream-request-timeout.js +34 -0
  32. package/dist/provider/stream-request-timeout.js.map +1 -0
  33. package/dist/public-runtime.d.ts +2 -0
  34. package/dist/public-runtime.d.ts.map +1 -1
  35. package/dist/public-runtime.js +2 -0
  36. package/dist/public-runtime.js.map +1 -1
  37. package/dist/public-tools.d.ts +1 -1
  38. package/dist/public-tools.d.ts.map +1 -1
  39. package/dist/public-tools.js +1 -1
  40. package/dist/public-tools.js.map +1 -1
  41. package/dist/runtime/query/executor.d.ts +3 -0
  42. package/dist/runtime/query/executor.d.ts.map +1 -1
  43. package/dist/runtime/query/executor.js +15 -3
  44. package/dist/runtime/query/executor.js.map +1 -1
  45. package/dist/runtime/query/file-evidence-replay.d.ts +1 -0
  46. package/dist/runtime/query/file-evidence-replay.d.ts.map +1 -1
  47. package/dist/runtime/query/file-evidence-replay.js +64 -21
  48. package/dist/runtime/query/file-evidence-replay.js.map +1 -1
  49. package/dist/runtime/query/file-evidence-seed.d.ts +7 -0
  50. package/dist/runtime/query/file-evidence-seed.d.ts.map +1 -1
  51. package/dist/runtime/query/file-evidence-seed.js +12 -1
  52. package/dist/runtime/query/file-evidence-seed.js.map +1 -1
  53. package/dist/runtime/query/guard.d.ts.map +1 -1
  54. package/dist/runtime/query/guard.js +12 -2
  55. package/dist/runtime/query/guard.js.map +1 -1
  56. package/dist/runtime/query/index.d.ts +2 -0
  57. package/dist/runtime/query/index.d.ts.map +1 -1
  58. package/dist/runtime/query/index.js +6 -2
  59. package/dist/runtime/query/index.js.map +1 -1
  60. package/dist/runtime/query/iteration/index.d.ts +3 -0
  61. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  62. package/dist/runtime/query/iteration/index.js +32 -11
  63. package/dist/runtime/query/iteration/index.js.map +1 -1
  64. package/dist/runtime/query/iteration/phases/advisory.js +2 -2
  65. package/dist/runtime/query/iteration/phases/advisory.js.map +1 -1
  66. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  67. package/dist/runtime/query/path-escalation.js +4 -3
  68. package/dist/runtime/query/path-escalation.js.map +1 -1
  69. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  70. package/dist/runtime/query/prepare-turn.js +1 -1
  71. package/dist/runtime/query/prepare-turn.js.map +1 -1
  72. package/dist/runtime/query/tooling.d.ts +2 -0
  73. package/dist/runtime/query/tooling.d.ts.map +1 -1
  74. package/dist/runtime/query/tooling.js +1 -0
  75. package/dist/runtime/query/tooling.js.map +1 -1
  76. package/dist/sandbox/file-walk-program.js +1 -1
  77. package/dist/sandbox/ignore-matcher.d.ts +2 -0
  78. package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
  79. package/dist/sandbox/ignore-matcher.js +8 -2
  80. package/dist/sandbox/ignore-matcher.js.map +1 -1
  81. package/dist/sandbox/ignore-source.d.ts.map +1 -1
  82. package/dist/sandbox/ignore-source.js +51 -7
  83. package/dist/sandbox/ignore-source.js.map +1 -1
  84. package/dist/sandbox/limit-error.d.ts +7 -0
  85. package/dist/sandbox/limit-error.d.ts.map +1 -0
  86. package/dist/sandbox/limit-error.js +13 -0
  87. package/dist/sandbox/limit-error.js.map +1 -0
  88. package/dist/sandbox/provider/local.d.ts +1 -0
  89. package/dist/sandbox/provider/local.d.ts.map +1 -1
  90. package/dist/sandbox/provider/local.js +95 -31
  91. package/dist/sandbox/provider/local.js.map +1 -1
  92. package/dist/schedules/cron.js +1 -1
  93. package/dist/schedules/cron.js.map +1 -1
  94. package/dist/schedules/describe.js +1 -1
  95. package/dist/schedules/describe.js.map +1 -1
  96. package/dist/schedules/next-fire.d.ts +2 -2
  97. package/dist/schedules/next-fire.d.ts.map +1 -1
  98. package/dist/schedules/next-fire.js +7 -4
  99. package/dist/schedules/next-fire.js.map +1 -1
  100. package/dist/schedules/spec.d.ts.map +1 -1
  101. package/dist/schedules/spec.js +23 -7
  102. package/dist/schedules/spec.js.map +1 -1
  103. package/dist/schedules/types.d.ts +2 -0
  104. package/dist/schedules/types.d.ts.map +1 -1
  105. package/dist/store/budget/ledger.d.ts +15 -1
  106. package/dist/store/budget/ledger.d.ts.map +1 -1
  107. package/dist/store/budget/ledger.js +80 -1
  108. package/dist/store/budget/ledger.js.map +1 -1
  109. package/dist/store/evidence/source-text.d.ts +1 -1
  110. package/dist/store/session-index/sqlite.d.ts.map +1 -1
  111. package/dist/store/session-index/sqlite.js +7 -3
  112. package/dist/store/session-index/sqlite.js.map +1 -1
  113. package/dist/store/session-log/core.d.ts.map +1 -1
  114. package/dist/store/session-log/core.js +88 -24
  115. package/dist/store/session-log/core.js.map +1 -1
  116. package/dist/store/session-log/disk.js +1 -1
  117. package/dist/store/session-log/disk.js.map +1 -1
  118. package/dist/tools/builtins/atomic-write-file.d.ts +2 -0
  119. package/dist/tools/builtins/atomic-write-file.d.ts.map +1 -1
  120. package/dist/tools/builtins/atomic-write-file.js +37 -8
  121. package/dist/tools/builtins/atomic-write-file.js.map +1 -1
  122. package/dist/tools/builtins/code-analysis.d.ts.map +1 -1
  123. package/dist/tools/builtins/code-analysis.js +4 -1
  124. package/dist/tools/builtins/code-analysis.js.map +1 -1
  125. package/dist/tools/builtins/edit-apply.d.ts.map +1 -1
  126. package/dist/tools/builtins/edit-apply.js +24 -10
  127. package/dist/tools/builtins/edit-apply.js.map +1 -1
  128. package/dist/tools/builtins/edit.d.ts.map +1 -1
  129. package/dist/tools/builtins/edit.js +31 -15
  130. package/dist/tools/builtins/edit.js.map +1 -1
  131. package/dist/tools/builtins/file-text.d.ts +3 -0
  132. package/dist/tools/builtins/file-text.d.ts.map +1 -0
  133. package/dist/tools/builtins/file-text.js +14 -0
  134. package/dist/tools/builtins/file-text.js.map +1 -0
  135. package/dist/tools/builtins/glob.d.ts.map +1 -1
  136. package/dist/tools/builtins/glob.js +7 -2
  137. package/dist/tools/builtins/glob.js.map +1 -1
  138. package/dist/tools/builtins/grep.d.ts.map +1 -1
  139. package/dist/tools/builtins/grep.js +8 -5
  140. package/dist/tools/builtins/grep.js.map +1 -1
  141. package/dist/tools/builtins/ls.d.ts.map +1 -1
  142. package/dist/tools/builtins/ls.js +2 -1
  143. package/dist/tools/builtins/ls.js.map +1 -1
  144. package/dist/tools/builtins/notebook-edit.d.ts.map +1 -1
  145. package/dist/tools/builtins/notebook-edit.js +19 -10
  146. package/dist/tools/builtins/notebook-edit.js.map +1 -1
  147. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  148. package/dist/tools/builtins/read-file.js +61 -29
  149. package/dist/tools/builtins/read-file.js.map +1 -1
  150. package/dist/tools/builtins/read-regular-file.d.ts +5 -0
  151. package/dist/tools/builtins/read-regular-file.d.ts.map +1 -0
  152. package/dist/tools/builtins/read-regular-file.js +23 -0
  153. package/dist/tools/builtins/read-regular-file.js.map +1 -0
  154. package/dist/tools/builtins/search-support.d.ts +2 -0
  155. package/dist/tools/builtins/search-support.d.ts.map +1 -1
  156. package/dist/tools/builtins/search-support.js +14 -0
  157. package/dist/tools/builtins/search-support.js.map +1 -1
  158. package/dist/tools/builtins/stale-before-review.d.ts.map +1 -1
  159. package/dist/tools/builtins/stale-before-review.js +8 -5
  160. package/dist/tools/builtins/stale-before-review.js.map +1 -1
  161. package/dist/tools/builtins/write-file.d.ts.map +1 -1
  162. package/dist/tools/builtins/write-file.js +17 -13
  163. package/dist/tools/builtins/write-file.js.map +1 -1
  164. package/dist/tools/defineTool.d.ts.map +1 -1
  165. package/dist/tools/defineTool.js +4 -3
  166. package/dist/tools/defineTool.js.map +1 -1
  167. package/dist/tools/paths.d.ts +9 -0
  168. package/dist/tools/paths.d.ts.map +1 -1
  169. package/dist/tools/paths.js +39 -9
  170. package/dist/tools/paths.js.map +1 -1
  171. package/dist/tools/posix-path.d.ts +2 -14
  172. package/dist/tools/posix-path.d.ts.map +1 -1
  173. package/dist/tools/posix-path.js +7 -0
  174. package/dist/tools/posix-path.js.map +1 -1
  175. package/dist/tools/tool-is-available.d.ts +4 -0
  176. package/dist/tools/tool-is-available.d.ts.map +1 -0
  177. package/dist/tools/tool-is-available.js +8 -0
  178. package/dist/tools/tool-is-available.js.map +1 -0
  179. package/dist/types/code-analysis/index.d.ts +1 -1
  180. package/dist/types/code-analysis/index.d.ts.map +1 -1
  181. package/dist/types/common/index.d.ts +6 -0
  182. package/dist/types/common/index.d.ts.map +1 -1
  183. package/dist/types/common/index.js +13 -0
  184. package/dist/types/common/index.js.map +1 -1
  185. package/dist/types/provider/errors.d.ts.map +1 -1
  186. package/dist/types/provider/errors.js +3 -5
  187. package/dist/types/provider/errors.js.map +1 -1
  188. package/dist/types/sandbox/index.d.ts +13 -2
  189. package/dist/types/sandbox/index.d.ts.map +1 -1
  190. package/dist/types/sandbox/index.js.map +1 -1
  191. package/dist/types/session/checkpoint.d.ts +4 -0
  192. package/dist/types/session/checkpoint.d.ts.map +1 -1
  193. package/dist/types/session/checkpoint.js +2 -0
  194. package/dist/types/session/checkpoint.js.map +1 -1
  195. package/dist/types/session/events.d.ts +1 -0
  196. package/dist/types/session/events.d.ts.map +1 -1
  197. package/dist/types/session/events.js.map +1 -1
  198. package/dist/types/session/records.d.ts +42 -6
  199. package/dist/types/session/records.d.ts.map +1 -1
  200. package/dist/types/session/records.js +1 -0
  201. package/dist/types/session/records.js.map +1 -1
  202. package/dist/types/tool/index.d.ts +2 -0
  203. package/dist/types/tool/index.d.ts.map +1 -1
  204. package/dist/types/tool/index.js.map +1 -1
  205. package/dist/utils/cost.d.ts +17 -0
  206. package/dist/utils/cost.d.ts.map +1 -1
  207. package/dist/utils/cost.js +78 -8
  208. package/dist/utils/cost.js.map +1 -1
  209. package/package.json +1 -1
  210. package/src/bridge/acp/server.ts +16 -7
  211. package/src/connector/mcp/adapter.ts +4 -3
  212. package/src/connector/mcp/client.ts +33 -32
  213. package/src/index.ts +2 -0
  214. package/src/manager/session/turn-recorder.ts +31 -7
  215. package/src/pricing/catalogue.generated.ts +176 -21
  216. package/src/pricing/rates.source.json +108 -33
  217. package/src/provider/errors.ts +12 -19
  218. package/src/provider/stream-request-timeout.ts +34 -0
  219. package/src/public-runtime.ts +2 -0
  220. package/src/public-tools.ts +1 -0
  221. package/src/runtime/query/executor.ts +29 -3
  222. package/src/runtime/query/file-evidence-replay.ts +73 -19
  223. package/src/runtime/query/file-evidence-seed.ts +16 -0
  224. package/src/runtime/query/guard.ts +13 -2
  225. package/src/runtime/query/index.ts +10 -1
  226. package/src/runtime/query/iteration/index.ts +32 -11
  227. package/src/runtime/query/iteration/phases/advisory.ts +2 -2
  228. package/src/runtime/query/path-escalation.ts +4 -3
  229. package/src/runtime/query/prepare-turn.ts +2 -1
  230. package/src/runtime/query/tooling.ts +3 -0
  231. package/src/sandbox/file-walk-program.ts +1 -1
  232. package/src/sandbox/ignore-matcher.ts +12 -3
  233. package/src/sandbox/ignore-source.ts +51 -7
  234. package/src/sandbox/limit-error.ts +10 -0
  235. package/src/sandbox/provider/local.ts +107 -48
  236. package/src/schedules/cron.ts +1 -1
  237. package/src/schedules/describe.ts +1 -1
  238. package/src/schedules/next-fire.ts +7 -4
  239. package/src/schedules/spec.ts +36 -7
  240. package/src/schedules/types.ts +2 -0
  241. package/src/store/budget/ledger.ts +93 -2
  242. package/src/store/session-index/sqlite.ts +8 -4
  243. package/src/store/session-log/core.ts +96 -25
  244. package/src/store/session-log/disk.ts +1 -1
  245. package/src/tools/builtins/atomic-write-file.ts +49 -7
  246. package/src/tools/builtins/code-analysis.ts +6 -1
  247. package/src/tools/builtins/edit-apply.ts +25 -10
  248. package/src/tools/builtins/edit.ts +31 -15
  249. package/src/tools/builtins/file-text.ts +14 -0
  250. package/src/tools/builtins/glob.ts +6 -1
  251. package/src/tools/builtins/grep.ts +7 -5
  252. package/src/tools/builtins/ls.ts +2 -1
  253. package/src/tools/builtins/notebook-edit.ts +18 -11
  254. package/src/tools/builtins/read-file.ts +71 -24
  255. package/src/tools/builtins/read-regular-file.ts +25 -0
  256. package/src/tools/builtins/search-support.ts +13 -0
  257. package/src/tools/builtins/stale-before-review.ts +8 -6
  258. package/src/tools/builtins/write-file.ts +18 -12
  259. package/src/tools/defineTool.ts +4 -3
  260. package/src/tools/paths.ts +49 -7
  261. package/src/tools/posix-path.ts +9 -0
  262. package/src/tools/tool-is-available.ts +11 -0
  263. package/src/types/code-analysis/index.ts +1 -1
  264. package/src/types/common/index.ts +24 -0
  265. package/src/types/provider/errors.ts +3 -5
  266. package/src/types/sandbox/index.ts +12 -1
  267. package/src/types/session/checkpoint.ts +2 -0
  268. package/src/types/session/events.ts +1 -0
  269. package/src/types/session/records.ts +1 -0
  270. package/src/types/tool/index.ts +2 -0
  271. package/src/utils/cost.ts +101 -8
@@ -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,11 +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'
11
+ import { toolIsAvailable } from '../tool-is-available.js'
10
12
  import { TEXT_MAX_INPUT_BYTES, readBoundedChunks, readBoundedFile } from './bounded-file-read.js'
11
13
  import { fingerprintContent } from './content-fingerprint.js'
14
+ import { decodeFileText } from './file-text.js'
12
15
  import {
13
16
  type MediaRead,
14
17
  NOTEBOOK_MAX_BYTES,
@@ -89,12 +92,15 @@ export const ReadFileTool = defineTool({
89
92
  },
90
93
 
91
94
  async execute(input, context) {
95
+ const shellAvailable = toolIsAvailable(context, 'bash')
92
96
  // This session's own retained tool output lives on the host, outside the
93
97
  // roots and outside any sandbox. It is read here, as a plain window of text,
94
98
  // because the result that named it told the model to.
95
99
  const retained = await resolveRetainedOutput(context.retainedOutputDirectory, input.path)
96
- // Sandbox-aware: route through sandbox.readFile() when available
97
- 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)
98
104
  const sandbox = context.sandbox
99
105
  const buffer = await readBoundedChunks(
100
106
  (offset, length) =>
@@ -105,7 +111,7 @@ export const ReadFileTool = defineTool({
105
111
  )
106
112
  const media = await readMediaFile(buffer, input.path, input, context, true)
107
113
  if (media) return media
108
- const binaryGuidance = describeStructuredBinaryRead(input.path)
114
+ const binaryGuidance = describeStructuredBinaryRead(input.path, true, shellAvailable)
109
115
  if (binaryGuidance) {
110
116
  return {
111
117
  success: false,
@@ -123,8 +129,9 @@ export const ReadFileTool = defineTool({
123
129
  },
124
130
  }
125
131
  }
126
- const content = buffer.toString('utf-8')
127
- if (looksBinary(content)) return unreadableAsText(input.path, buffer.length, true)
132
+ const content = decodeFileText(buffer)
133
+ if (content === undefined || looksBinary(content))
134
+ return unreadableAsText(input.path, buffer.length, true, shellAvailable)
128
135
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
129
136
  if (!capped.ok) return refusedRead(input.path, buffer.length, capped.message, true)
130
137
  const rendered = capped.rendered
@@ -146,7 +153,8 @@ export const ReadFileTool = defineTool({
146
153
  }
147
154
  }
148
155
 
149
- const filePath = retained ?? (await resolveWithinAnyReal(toolRoots(context), input.path))
156
+ const filePath =
157
+ retained ?? allowed ?? (await resolveWithinAnyReal(toolRoots(context), input.path))
150
158
  // Pictures, PDFs and notebooks are not text: they have their own size
151
159
  // limits and are never numbered, so the text cap below does not apply.
152
160
  const namesMediaFile = namesMedia(filePath)
@@ -162,7 +170,7 @@ export const ReadFileTool = defineTool({
162
170
  )
163
171
  const media = await readMediaFile(buffer, filePath, input, context, false)
164
172
  if (media) return media
165
- const binaryGuidance = describeStructuredBinaryRead(filePath)
173
+ const binaryGuidance = describeStructuredBinaryRead(filePath, false, shellAvailable)
166
174
  if (binaryGuidance) {
167
175
  return {
168
176
  success: false,
@@ -179,8 +187,9 @@ export const ReadFileTool = defineTool({
179
187
  },
180
188
  }
181
189
  }
182
- const content = buffer.toString('utf-8')
183
- if (looksBinary(content)) return unreadableAsText(filePath, buffer.length, false)
190
+ const content = decodeFileText(buffer)
191
+ if (content === undefined || looksBinary(content))
192
+ return unreadableAsText(filePath, buffer.length, false, shellAvailable)
184
193
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
185
194
  if (!capped.ok) return refusedRead(filePath, buffer.length, capped.message, false)
186
195
  const rendered = capped.rendered
@@ -289,6 +298,10 @@ async function readMediaFile(
289
298
  )
290
299
  }
291
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
+ }
292
305
  const media: MediaRead =
293
306
  kind === 'pdf'
294
307
  ? await readPdfPages(buffer, input.pages, path, context.abortSignal)
@@ -297,7 +310,7 @@ async function readMediaFile(
297
310
  // A notebook shown whole is a read like any other: the body is what a later
298
311
  // edit of it is checked against, and `notebook_edit` refuses a notebook the
299
312
  // session has not read.
300
- if (kind === 'notebook') context.fileReadTracker?.recordRead(path, buffer.toString('utf-8'))
313
+ if (notebookText !== undefined) context.fileReadTracker?.recordRead(path, notebookText)
301
314
  const text = media.parts
302
315
  .filter((part) => part.type === 'text')
303
316
  .map((part) => part.text)
@@ -337,10 +350,18 @@ function capOptions(
337
350
  * A file whose bytes are not text. The model gets a short note with the size
338
351
  * and the next step, never the numbered garbage a decode would produce.
339
352
  */
340
- function unreadableAsText(path: string, bytes: number, sandboxed: boolean) {
353
+ function unreadableAsText(
354
+ path: string,
355
+ bytes: number,
356
+ sandboxed: boolean,
357
+ shellAvailable: boolean,
358
+ ) {
359
+ const hint = shellAvailable
360
+ ? ' Inspect it with a shell command such as file or xxd, or use a tool made for its format.'
361
+ : ''
341
362
  return {
342
363
  success: false as const,
343
- output: `This file is not readable as text (${humanBytes(bytes)} of binary or non-UTF-8 data). Inspect it with a shell command such as file or xxd, or use a tool made for its format.`,
364
+ output: `This file is not readable as text (${humanBytes(bytes)} of binary or non-UTF-8 data).${hint}`,
344
365
  data: { path, binary: true, ...(sandboxed ? { sandboxed: true } : {}) },
345
366
  facts: { kind: 'read' as const, path, binary: true, bytes },
346
367
  }
@@ -463,19 +484,45 @@ function unchangedRead(
463
484
  }
464
485
  }
465
486
 
466
- function describeStructuredBinaryRead(path: string): string | null {
467
- const ext = extname(path).toLowerCase()
468
- if (ext === '.docx') return buildStructuredBinaryGuidance(path, 'DOCX', 'python-docx')
469
- if (ext === '.pptx') return buildStructuredBinaryGuidance(path, 'PPTX', 'python-pptx')
470
- if (ext === '.xlsx') return buildStructuredBinaryGuidance(path, 'XLSX', 'openpyxl')
471
- return null
472
- }
473
-
474
- function buildStructuredBinaryGuidance(path: string, format: string, extractor: string): string {
487
+ function describeStructuredBinaryRead(
488
+ path: string,
489
+ sandboxed: boolean,
490
+ shellAvailable: boolean,
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
+ }
515
+ const description = `The file "${path}" is a ${format} document package, not UTF-8 text.`
516
+ if (!shellAvailable) return description
475
517
  return [
476
- `The file "${path}" is a ${format} document package, not UTF-8 text.`,
518
+ description,
477
519
  'Do not use the read/cat tools as evidence for this raw file.',
478
- `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.',
479
522
  'If extraction fails, report the exact filename and extraction error instead of claiming the attachment is unavailable.',
480
523
  ].join('\n')
481
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 type {
8
8
  import type { ToolPresentation } from '../types/tool/presentation.js'
9
9
  import { toErrorMessage } from '../utils/error.js'
10
10
  import { failureFactsFromError } from './failure-facts.js'
11
+ import { toolIsAvailable } from './tool-is-available.js'
11
12
 
12
13
  export interface DefineToolOptions<S extends z.ZodType> {
13
14
  name: string
@@ -211,7 +212,7 @@ export function defineTool<S extends z.ZodType>(
211
212
  try {
212
213
  return await options.execute(input, context)
213
214
  } catch (err) {
214
- const message = `${toErrorMessage(err)}${missingPathNote(options.name, err)}`
215
+ const message = `${toErrorMessage(err)}${missingPathNote(options.name, err, context)}`
215
216
  const facts = failureFactsFromError(err)
216
217
  return {
217
218
  success: false,
@@ -232,8 +233,8 @@ const PATH_GUESSING_TOOLS: ReadonlySet<string> = new Set(['read', 'edit'])
232
233
  * What to do when a path does not exist. A model that is told only "no such
233
234
  * file" tries another guess; listing the folder finds the real name in one call.
234
235
  */
235
- function missingPathNote(toolName: string, err: unknown): string {
236
- if (!PATH_GUESSING_TOOLS.has(toolName)) return ''
236
+ function missingPathNote(toolName: string, err: unknown, context: ToolContext): string {
237
+ if (!PATH_GUESSING_TOOLS.has(toolName) || !toolIsAvailable(context, 'glob')) return ''
237
238
  return (err as { code?: unknown } | null)?.code === 'ENOENT'
238
239
  ? ' Nothing exists at that path. Find the file with `glob` instead of trying another guess.'
239
240
  : ''
@@ -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.
@@ -0,0 +1,11 @@
1
+ import type { ToolContext } from '../types/tool/index.js'
2
+
3
+ /** Whether the model can call a follow-up tool in the current step. */
4
+ export function toolIsAvailable(context: ToolContext, name: string): boolean {
5
+ const registry = context.toolRegistry
6
+ return (
7
+ registry?.has(name) === true &&
8
+ registry.availability(name) === 'active' &&
9
+ (context.allowedTools === undefined || context.allowedTools.includes(name))
10
+ )
11
+ }
@@ -206,7 +206,7 @@ export interface FindLiteralRequest extends AnalysisPaging {
206
206
  readonly text: string
207
207
  /** Absolute file or directory to restrict the search to. */
208
208
  readonly path?: string
209
- /** Default `true`. */
209
+ /** Default `true`. Set to `false` for Unicode simple case folding without locale tailoring. */
210
210
  readonly caseSensitive?: boolean
211
211
  }
212
212
 
@@ -12,6 +12,11 @@ export interface TokenUsage {
12
12
  cachedTokens: number
13
13
  cacheWriteTokens: number
14
14
 
15
+ /** Cache reads and writes already included in the prompt count, when explicitly measured. */
16
+ cacheTokensInPrompt?: number
17
+ /** Billing route selected for this model request. */
18
+ billingRoute?: 'subscription' | 'api'
19
+
15
20
  /**
16
21
  * The whole prompt this call processed, cache reads and cache writes
17
22
  * included: the size of the context the model was given.
@@ -155,6 +160,12 @@ export function accumulateTokenUsage(current: TokenUsage, addition: TokenUsage):
155
160
  totalTokens: current.totalTokens + addition.totalTokens,
156
161
  cachedTokens: current.cachedTokens + addition.cachedTokens,
157
162
  cacheWriteTokens: current.cacheWriteTokens + addition.cacheWriteTokens,
163
+ ...(current.cacheTokensInPrompt !== undefined || addition.cacheTokensInPrompt !== undefined
164
+ ? {
165
+ cacheTokensInPrompt:
166
+ (current.cacheTokensInPrompt ?? 0) + (addition.cacheTokensInPrompt ?? 0),
167
+ }
168
+ : {}),
158
169
  // Summed only when at least one side reported it. Coercing absent to
159
170
  // zero would turn 'this driver does not tell us' into 'it spent none',
160
171
  // and a turn mixing a reporting driver with a silent one would read as
@@ -202,6 +213,17 @@ export function mergeTokenUsage(current: TokenUsage, next: TokenUsage): TokenUsa
202
213
  totalTokens: Math.max(current.totalTokens, next.totalTokens, promptTokens + completionTokens),
203
214
  cachedTokens: Math.max(current.cachedTokens, next.cachedTokens),
204
215
  cacheWriteTokens: Math.max(current.cacheWriteTokens, next.cacheWriteTokens),
216
+ ...((next.billingRoute ?? current.billingRoute)
217
+ ? { billingRoute: next.billingRoute ?? current.billingRoute }
218
+ : {}),
219
+ ...(current.cacheTokensInPrompt !== undefined || next.cacheTokensInPrompt !== undefined
220
+ ? {
221
+ cacheTokensInPrompt: Math.max(
222
+ current.cacheTokensInPrompt ?? 0,
223
+ next.cacheTokensInPrompt ?? 0,
224
+ ),
225
+ }
226
+ : {}),
205
227
  ...(current.fullPromptTokens !== undefined || next.fullPromptTokens !== undefined
206
228
  ? { fullPromptTokens: Math.max(current.fullPromptTokens ?? 0, next.fullPromptTokens ?? 0) }
207
229
  : {}),
@@ -241,6 +263,8 @@ export function mergeTokenUsage(current: TokenUsage, next: TokenUsage): TokenUsa
241
263
  }
242
264
 
243
265
  export interface CostInfo {
266
+ /** Tokens covered by a subscription plan. */
267
+ includedTokens?: number
244
268
  /**
245
269
  * The input rate this total was accumulated at — present only when ONE rate
246
270
  * card describes the whole total.