@namzu/sdk 73.0.0 → 74.1.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 +56 -0
  2. package/README.md +34 -34
  3. package/dist/authorization/protected-paths.d.ts +7 -0
  4. package/dist/authorization/protected-paths.d.ts.map +1 -1
  5. package/dist/authorization/protected-paths.js +7 -0
  6. package/dist/authorization/protected-paths.js.map +1 -1
  7. package/dist/authorization/readonly-commands.d.ts +23 -0
  8. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  9. package/dist/authorization/readonly-commands.js +89 -3
  10. package/dist/authorization/readonly-commands.js.map +1 -1
  11. package/dist/authorization/shell-paths.d.ts +8 -0
  12. package/dist/authorization/shell-paths.d.ts.map +1 -1
  13. package/dist/authorization/shell-paths.js +125 -2
  14. package/dist/authorization/shell-paths.js.map +1 -1
  15. package/dist/bridge/acp/permission.d.ts +6 -0
  16. package/dist/bridge/acp/permission.d.ts.map +1 -1
  17. package/dist/bridge/acp/permission.js.map +1 -1
  18. package/dist/bridge/acp/server.d.ts.map +1 -1
  19. package/dist/bridge/acp/server.js +21 -3
  20. package/dist/bridge/acp/server.js.map +1 -1
  21. package/dist/compaction/context-window.d.ts.map +1 -1
  22. package/dist/compaction/context-window.js +11 -0
  23. package/dist/compaction/context-window.js.map +1 -1
  24. package/dist/compaction/manual.d.ts.map +1 -1
  25. package/dist/compaction/manual.js +15 -8
  26. package/dist/compaction/manual.js.map +1 -1
  27. package/dist/compaction/plan.d.ts +2 -1
  28. package/dist/compaction/plan.d.ts.map +1 -1
  29. package/dist/compaction/plan.js +6 -5
  30. package/dist/compaction/plan.js.map +1 -1
  31. package/dist/compaction/retained-images.d.ts +16 -0
  32. package/dist/compaction/retained-images.d.ts.map +1 -0
  33. package/dist/compaction/retained-images.js +113 -0
  34. package/dist/compaction/retained-images.js.map +1 -0
  35. package/dist/compaction/token-estimate.d.ts +8 -3
  36. package/dist/compaction/token-estimate.d.ts.map +1 -1
  37. package/dist/compaction/token-estimate.js +76 -8
  38. package/dist/compaction/token-estimate.js.map +1 -1
  39. package/dist/compaction/tool-result-editing.d.ts.map +1 -1
  40. package/dist/compaction/tool-result-editing.js +15 -8
  41. package/dist/compaction/tool-result-editing.js.map +1 -1
  42. package/dist/config/runtime.d.ts +3 -3
  43. package/dist/constants/acp/index.d.ts +2 -0
  44. package/dist/constants/acp/index.d.ts.map +1 -1
  45. package/dist/constants/acp/index.js +2 -0
  46. package/dist/constants/acp/index.js.map +1 -1
  47. package/dist/index.d.ts +1 -0
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +1 -0
  50. package/dist/index.js.map +1 -1
  51. package/dist/manager/session/turn-recorder.d.ts +1 -0
  52. package/dist/manager/session/turn-recorder.d.ts.map +1 -1
  53. package/dist/manager/session/turn-recorder.js +31 -7
  54. package/dist/manager/session/turn-recorder.js.map +1 -1
  55. package/dist/pricing/catalogue.generated.d.ts.map +1 -1
  56. package/dist/pricing/catalogue.generated.js +353 -21
  57. package/dist/pricing/catalogue.generated.js.map +1 -1
  58. package/dist/provider/attribution.js +1 -1
  59. package/dist/provider/attribution.js.map +1 -1
  60. package/dist/public-runtime.d.ts +5 -2
  61. package/dist/public-runtime.d.ts.map +1 -1
  62. package/dist/public-runtime.js +8 -1
  63. package/dist/public-runtime.js.map +1 -1
  64. package/dist/rag/embedding.d.ts +5 -1
  65. package/dist/rag/embedding.d.ts.map +1 -1
  66. package/dist/rag/embedding.js +22 -7
  67. package/dist/rag/embedding.js.map +1 -1
  68. package/dist/runtime/query/abandon-turn.d.ts.map +1 -1
  69. package/dist/runtime/query/abandon-turn.js +9 -0
  70. package/dist/runtime/query/abandon-turn.js.map +1 -1
  71. package/dist/runtime/query/compact-session.d.ts +10 -3
  72. package/dist/runtime/query/compact-session.d.ts.map +1 -1
  73. package/dist/runtime/query/compact-session.js +24 -14
  74. package/dist/runtime/query/compact-session.js.map +1 -1
  75. package/dist/runtime/query/guard.d.ts.map +1 -1
  76. package/dist/runtime/query/guard.js +12 -2
  77. package/dist/runtime/query/guard.js.map +1 -1
  78. package/dist/runtime/query/index.d.ts.map +1 -1
  79. package/dist/runtime/query/index.js +2 -0
  80. package/dist/runtime/query/index.js.map +1 -1
  81. package/dist/runtime/query/iteration/index.d.ts +3 -0
  82. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  83. package/dist/runtime/query/iteration/index.js +46 -11
  84. package/dist/runtime/query/iteration/index.js.map +1 -1
  85. package/dist/runtime/query/iteration/phases/advisory.js +2 -2
  86. package/dist/runtime/query/iteration/phases/advisory.js.map +1 -1
  87. package/dist/runtime/query/iteration/phases/compaction.d.ts.map +1 -1
  88. package/dist/runtime/query/iteration/phases/compaction.js +60 -5
  89. package/dist/runtime/query/iteration/phases/compaction.js.map +1 -1
  90. package/dist/runtime/query/iteration/phases/context.d.ts +2 -0
  91. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  92. package/dist/runtime/query/iteration/phases/context.js +1 -0
  93. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  94. package/dist/runtime/query/iteration/request-prefix.d.ts +21 -0
  95. package/dist/runtime/query/iteration/request-prefix.d.ts.map +1 -0
  96. package/dist/runtime/query/iteration/request-prefix.js +111 -0
  97. package/dist/runtime/query/iteration/request-prefix.js.map +1 -0
  98. package/dist/runtime/query/prepare-turn.d.ts.map +1 -1
  99. package/dist/runtime/query/prepare-turn.js +1 -1
  100. package/dist/runtime/query/prepare-turn.js.map +1 -1
  101. package/dist/runtime/query/review-policy.d.ts +11 -3
  102. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  103. package/dist/runtime/query/review-policy.js +54 -3
  104. package/dist/runtime/query/review-policy.js.map +1 -1
  105. package/dist/sandbox/exec-stdin.d.ts +21 -0
  106. package/dist/sandbox/exec-stdin.d.ts.map +1 -0
  107. package/dist/sandbox/exec-stdin.js +40 -0
  108. package/dist/sandbox/exec-stdin.js.map +1 -0
  109. package/dist/sandbox/file-walk-program.js +1 -1
  110. package/dist/sandbox/file-walk.d.ts +12 -7
  111. package/dist/sandbox/file-walk.d.ts.map +1 -1
  112. package/dist/sandbox/file-walk.js +13 -4
  113. package/dist/sandbox/file-walk.js.map +1 -1
  114. package/dist/sandbox/ignore-matcher.d.ts +3 -0
  115. package/dist/sandbox/ignore-matcher.d.ts.map +1 -1
  116. package/dist/sandbox/ignore-matcher.js +8 -2
  117. package/dist/sandbox/ignore-matcher.js.map +1 -1
  118. package/dist/sandbox/ignore-source.d.ts.map +1 -1
  119. package/dist/sandbox/ignore-source.js +52 -8
  120. package/dist/sandbox/ignore-source.js.map +1 -1
  121. package/dist/sandbox/index.d.ts +3 -2
  122. package/dist/sandbox/index.d.ts.map +1 -1
  123. package/dist/sandbox/index.js +2 -1
  124. package/dist/sandbox/index.js.map +1 -1
  125. package/dist/sandbox/limit-error.d.ts +7 -0
  126. package/dist/sandbox/limit-error.d.ts.map +1 -0
  127. package/dist/sandbox/limit-error.js +13 -0
  128. package/dist/sandbox/limit-error.js.map +1 -0
  129. package/dist/sandbox/provider/local.d.ts +1 -0
  130. package/dist/sandbox/provider/local.d.ts.map +1 -1
  131. package/dist/sandbox/provider/local.js +52 -13
  132. package/dist/sandbox/provider/local.js.map +1 -1
  133. package/dist/session/paths.d.ts +6 -0
  134. package/dist/session/paths.d.ts.map +1 -1
  135. package/dist/session/paths.js +7 -0
  136. package/dist/session/paths.js.map +1 -1
  137. package/dist/session-query/index.d.ts +1 -0
  138. package/dist/session-query/index.d.ts.map +1 -1
  139. package/dist/session-query/index.js +26 -15
  140. package/dist/session-query/index.js.map +1 -1
  141. package/dist/store/budget/ledger.d.ts +15 -1
  142. package/dist/store/budget/ledger.d.ts.map +1 -1
  143. package/dist/store/budget/ledger.js +80 -1
  144. package/dist/store/budget/ledger.js.map +1 -1
  145. package/dist/store/evidence/disk.js +3 -1
  146. package/dist/store/evidence/disk.js.map +1 -1
  147. package/dist/store/evidence/index-page.d.ts +1 -0
  148. package/dist/store/evidence/index-page.d.ts.map +1 -1
  149. package/dist/store/evidence/index-page.js +8 -0
  150. package/dist/store/evidence/index-page.js.map +1 -1
  151. package/dist/store/evidence/source-text.d.ts +1 -1
  152. package/dist/store/memory/operation-lock.d.ts.map +1 -1
  153. package/dist/store/memory/operation-lock.js +15 -1
  154. package/dist/store/memory/operation-lock.js.map +1 -1
  155. package/dist/store/session-log/core.d.ts.map +1 -1
  156. package/dist/store/session-log/core.js +23 -0
  157. package/dist/store/session-log/core.js.map +1 -1
  158. package/dist/tools/builtins/atomic-write-file.d.ts +2 -0
  159. package/dist/tools/builtins/atomic-write-file.d.ts.map +1 -1
  160. package/dist/tools/builtins/atomic-write-file.js +37 -8
  161. package/dist/tools/builtins/atomic-write-file.js.map +1 -1
  162. package/dist/tools/builtins/computer-use-image.d.ts +9 -0
  163. package/dist/tools/builtins/computer-use-image.d.ts.map +1 -1
  164. package/dist/tools/builtins/computer-use-image.js +21 -0
  165. package/dist/tools/builtins/computer-use-image.js.map +1 -1
  166. package/dist/tools/builtins/computer-use.d.ts +1 -9
  167. package/dist/tools/builtins/computer-use.d.ts.map +1 -1
  168. package/dist/tools/builtins/computer-use.js +2 -22
  169. package/dist/tools/builtins/computer-use.js.map +1 -1
  170. package/dist/tools/builtins/read-file.d.ts.map +1 -1
  171. package/dist/tools/builtins/read-file.js +20 -12
  172. package/dist/tools/builtins/read-file.js.map +1 -1
  173. package/dist/tools/defineTool.d.ts.map +1 -1
  174. package/dist/tools/defineTool.js +4 -3
  175. package/dist/tools/defineTool.js.map +1 -1
  176. package/dist/tools/tool-is-available.d.ts +4 -0
  177. package/dist/tools/tool-is-available.d.ts.map +1 -0
  178. package/dist/tools/tool-is-available.js +8 -0
  179. package/dist/tools/tool-is-available.js.map +1 -0
  180. package/dist/toolsets/manager.d.ts +7 -3
  181. package/dist/toolsets/manager.d.ts.map +1 -1
  182. package/dist/toolsets/manager.js +7 -3
  183. package/dist/toolsets/manager.js.map +1 -1
  184. package/dist/types/common/index.d.ts +26 -0
  185. package/dist/types/common/index.d.ts.map +1 -1
  186. package/dist/types/common/index.js +17 -1
  187. package/dist/types/common/index.js.map +1 -1
  188. package/dist/types/hitl/index.d.ts +11 -0
  189. package/dist/types/hitl/index.d.ts.map +1 -1
  190. package/dist/types/hitl/index.js.map +1 -1
  191. package/dist/types/rag/embedding.d.ts +4 -0
  192. package/dist/types/rag/embedding.d.ts.map +1 -1
  193. package/dist/types/sandbox/index.d.ts +32 -2
  194. package/dist/types/sandbox/index.d.ts.map +1 -1
  195. package/dist/types/sandbox/index.js.map +1 -1
  196. package/dist/types/session/checkpoint.d.ts +4 -0
  197. package/dist/types/session/checkpoint.d.ts.map +1 -1
  198. package/dist/types/session/checkpoint.js +2 -0
  199. package/dist/types/session/checkpoint.js.map +1 -1
  200. package/dist/types/session/events.d.ts +49 -0
  201. package/dist/types/session/events.d.ts.map +1 -1
  202. package/dist/types/session/events.js.map +1 -1
  203. package/dist/types/session/records.d.ts +44 -6
  204. package/dist/types/session/records.d.ts.map +1 -1
  205. package/dist/types/session/records.js +10 -0
  206. package/dist/types/session/records.js.map +1 -1
  207. package/dist/utils/cost.d.ts +32 -0
  208. package/dist/utils/cost.d.ts.map +1 -1
  209. package/dist/utils/cost.js +101 -8
  210. package/dist/utils/cost.js.map +1 -1
  211. package/package.json +2 -2
  212. package/src/authorization/protected-paths.ts +7 -0
  213. package/src/authorization/readonly-commands.ts +85 -3
  214. package/src/authorization/shell-paths.ts +141 -3
  215. package/src/bridge/acp/permission.ts +6 -0
  216. package/src/bridge/acp/server.ts +20 -1
  217. package/src/compaction/context-window.ts +11 -0
  218. package/src/compaction/manual.ts +23 -8
  219. package/src/compaction/plan.ts +11 -5
  220. package/src/compaction/retained-images.ts +130 -0
  221. package/src/compaction/token-estimate.ts +86 -8
  222. package/src/compaction/tool-result-editing.ts +20 -8
  223. package/src/constants/acp/index.ts +2 -0
  224. package/src/index.ts +2 -0
  225. package/src/manager/session/turn-recorder.ts +31 -7
  226. package/src/pricing/catalogue.generated.ts +353 -21
  227. package/src/pricing/rates.source.json +254 -26
  228. package/src/provider/attribution.ts +1 -1
  229. package/src/public-runtime.ts +22 -0
  230. package/src/rag/embedding.ts +23 -7
  231. package/src/runtime/query/abandon-turn.ts +9 -0
  232. package/src/runtime/query/compact-session.ts +50 -15
  233. package/src/runtime/query/guard.ts +13 -2
  234. package/src/runtime/query/index.ts +2 -0
  235. package/src/runtime/query/iteration/index.ts +46 -11
  236. package/src/runtime/query/iteration/phases/advisory.ts +2 -2
  237. package/src/runtime/query/iteration/phases/compaction.ts +77 -5
  238. package/src/runtime/query/iteration/phases/context.ts +3 -0
  239. package/src/runtime/query/iteration/request-prefix.ts +161 -0
  240. package/src/runtime/query/prepare-turn.ts +2 -1
  241. package/src/runtime/query/review-policy.ts +79 -11
  242. package/src/sandbox/exec-stdin.ts +54 -0
  243. package/src/sandbox/file-walk-program.ts +1 -1
  244. package/src/sandbox/file-walk.ts +25 -18
  245. package/src/sandbox/ignore-matcher.ts +13 -3
  246. package/src/sandbox/ignore-source.ts +52 -8
  247. package/src/sandbox/index.ts +8 -2
  248. package/src/sandbox/limit-error.ts +10 -0
  249. package/src/sandbox/provider/local.ts +56 -23
  250. package/src/session/paths.ts +9 -0
  251. package/src/session-query/index.ts +23 -14
  252. package/src/store/budget/ledger.ts +93 -2
  253. package/src/store/evidence/disk.ts +3 -1
  254. package/src/store/evidence/index-page.ts +11 -0
  255. package/src/store/memory/operation-lock.ts +19 -1
  256. package/src/store/session-log/core.ts +26 -0
  257. package/src/tools/builtins/atomic-write-file.ts +49 -7
  258. package/src/tools/builtins/computer-use-image.ts +20 -0
  259. package/src/tools/builtins/computer-use.ts +1 -20
  260. package/src/tools/builtins/read-file.ts +34 -12
  261. package/src/tools/defineTool.ts +4 -3
  262. package/src/tools/tool-is-available.ts +11 -0
  263. package/src/toolsets/manager.ts +7 -3
  264. package/src/types/common/index.ts +50 -1
  265. package/src/types/hitl/index.ts +11 -0
  266. package/src/types/rag/embedding.ts +7 -0
  267. package/src/types/sandbox/index.ts +31 -1
  268. package/src/types/session/checkpoint.ts +2 -0
  269. package/src/types/session/events.ts +50 -0
  270. package/src/types/session/records.ts +15 -0
  271. package/src/utils/cost.ts +144 -8
@@ -86,7 +86,7 @@ export class SessionQuery {
86
86
 
87
87
  /** Every message compaction removed, one entry per pass, oldest first. */
88
88
  async shedHistory(): Promise<readonly ShedPass[]> {
89
- return shedPassesFrom(await this.records())
89
+ return this.shedPassesFrom(await this.records())
90
90
  }
91
91
 
92
92
  /**
@@ -98,7 +98,7 @@ export class SessionQuery {
98
98
  */
99
99
  async fullTranscript(messages?: readonly Message[]): Promise<readonly Message[]> {
100
100
  const records = await this.records()
101
- const shed = shedPassesFrom(records)
101
+ const shed = await this.shedPassesFrom(records)
102
102
  let surviving: readonly Message[]
103
103
  if (messages !== undefined) {
104
104
  surviving = messages
@@ -135,18 +135,27 @@ export class SessionQuery {
135
135
  registry.replay(await this.records())
136
136
  return registry.get<SessionStatusState>(SESSION_STATUS_READ_MODEL_ID)
137
137
  }
138
- }
139
138
 
140
- function shedPassesFrom(records: readonly SessionRecord[]): ShedPass[] {
141
- const passes: ShedPass[] = []
142
- for (const record of records) {
143
- if (record.type !== 'compaction_shed') continue
144
- passes.push({
145
- iteration: record.iteration,
146
- reason: record.reason,
147
- messages: record.messages,
148
- seq: record.seq,
149
- })
139
+ private async shedPassesFrom(records: readonly SessionRecord[]): Promise<ShedPass[]> {
140
+ const passes: ShedPass[] = []
141
+ for (const record of records) {
142
+ if (record.type !== 'compaction_shed') continue
143
+ let messages = record.messages
144
+ if (record.messagesSpill !== undefined) {
145
+ try {
146
+ const body: unknown = JSON.parse(await this.options.log.readSpill(record.messagesSpill))
147
+ if (!Array.isArray(body)) throw new Error('A shed message spill must hold an array.')
148
+ messages = body
149
+ } catch (cause) {
150
+ throw new SessionTranscriptUnavailableError({
151
+ reason: 'spill-unavailable',
152
+ throughSeq: record.seq,
153
+ cause,
154
+ })
155
+ }
156
+ }
157
+ passes.push({ iteration: record.iteration, reason: record.reason, messages, seq: record.seq })
158
+ }
159
+ return passes
150
160
  }
151
- return passes
152
161
  }
@@ -1,6 +1,7 @@
1
- import { EMPTY_TOKEN_USAGE } from '../../constants/limits.js'
2
- import { type TokenUsage, accumulateTokenUsage } from '../../types/common/index.js'
1
+ import { EMPTY_TOKEN_USAGE, ZERO_COST } from '../../constants/limits.js'
2
+ import { type CostInfo, type TokenUsage, accumulateTokenUsage } from '../../types/common/index.js'
3
3
  import type { SessionId, TurnId } from '../../types/ids/index.js'
4
+ import { CostInfoSchema } from '../../types/session/checkpoint.js'
4
5
  import type { TurnBudgetBinding } from '../../types/session/turn.js'
5
6
  import { entityIdPattern } from '../../utils/id-format.js'
6
7
  import { isEntityId } from '../../utils/id.js'
@@ -36,6 +37,9 @@ export interface SessionTokenBudgetAccountSnapshot {
36
37
  turn?: SessionTokenBudgetTurn
37
38
  /** Cumulative own usage, keyed by the bound turn's id; descendants never appear here. */
38
39
  usage: Record<string, TokenUsage>
40
+ cost?: CostInfo
41
+ pricedThroughTokens?: number
42
+ costLimitUsd?: number
39
43
  }
40
44
 
41
45
  export interface SessionTokenBudgetRequestSnapshot {
@@ -76,6 +80,7 @@ export interface SessionTokenBudgetSummary {
76
80
  limit: number
77
81
  ownTokens: number
78
82
  treeTokens: number
83
+ treeCost?: CostInfo
79
84
  reservedTokens: number
80
85
  /** null means unlimited; unlike Infinity this survives JSON serialization. */
81
86
  remainingTokens: number | null
@@ -154,6 +159,11 @@ function usageValue(value: unknown): TokenUsage {
154
159
  totalTokens: count(source.totalTokens, 'totalTokens'),
155
160
  cachedTokens: count(source.cachedTokens, 'cachedTokens'),
156
161
  cacheWriteTokens: count(source.cacheWriteTokens, 'cacheWriteTokens'),
162
+ ...(source.cacheTokensInPrompt === undefined
163
+ ? {}
164
+ : {
165
+ cacheTokensInPrompt: count(source.cacheTokensInPrompt, 'cacheTokensInPrompt'),
166
+ }),
157
167
  ...(source.reasoningTokens === undefined
158
168
  ? {}
159
169
  : { reasoningTokens: count(source.reasoningTokens, 'reasoningTokens') }),
@@ -177,6 +187,14 @@ function maxUsage(left: TokenUsage, right: TokenUsage): TokenUsage {
177
187
  totalTokens: Math.max(left.totalTokens, right.totalTokens),
178
188
  cachedTokens: Math.max(left.cachedTokens, right.cachedTokens),
179
189
  cacheWriteTokens: Math.max(left.cacheWriteTokens, right.cacheWriteTokens),
190
+ ...(left.cacheTokensInPrompt === undefined && right.cacheTokensInPrompt === undefined
191
+ ? {}
192
+ : {
193
+ cacheTokensInPrompt: Math.max(
194
+ left.cacheTokensInPrompt ?? 0,
195
+ right.cacheTokensInPrompt ?? 0,
196
+ ),
197
+ }),
180
198
  ...(left.reasoningTokens === undefined && right.reasoningTokens === undefined
181
199
  ? {}
182
200
  : { reasoningTokens: Math.max(left.reasoningTokens ?? 0, right.reasoningTokens ?? 0) }),
@@ -252,6 +270,15 @@ export function validateSessionTokenBudgetSnapshot(value: unknown): SessionToken
252
270
  settled: account.settled,
253
271
  ...(turn === undefined ? {} : { turn }),
254
272
  usage,
273
+ ...(account.costLimitUsd === undefined
274
+ ? {}
275
+ : { costLimitUsd: CostInfoSchema.shape.totalCost.parse(account.costLimitUsd) }),
276
+ ...(account.cost === undefined
277
+ ? {}
278
+ : {
279
+ cost: CostInfoSchema.parse(account.cost),
280
+ pricedThroughTokens: count(account.pricedThroughTokens, 'pricedThroughTokens'),
281
+ }),
255
282
  }
256
283
  })
257
284
  const byId = new Map(accounts.map((account) => [account.id, account]))
@@ -504,6 +531,68 @@ export class SessionTokenBudget {
504
531
  get treeTokens(): number {
505
532
  return this.totals(this.node).tree
506
533
  }
534
+ /** Dollar ceiling of this turn, inherited by requests in its descendants. */
535
+ setCostLimit(limit: number | undefined): void {
536
+ if (limit === undefined || limit <= 0 || this.node.costLimitUsd === limit) return
537
+ this.node.costLimitUsd = limit
538
+ this.persist()
539
+ }
540
+
541
+ ancestorCostStop(): 'cost_limit' | 'cost_unmeasurable' | undefined {
542
+ let parentId = this.node.parentId
543
+ while (parentId !== undefined) {
544
+ const parent = this.requireAccount(parentId)
545
+ if (parent.costLimitUsd !== undefined) {
546
+ const spend = this.costOfAccounts(this.descendants(parent))
547
+ if (spend.totalCost >= parent.costLimitUsd) return 'cost_limit'
548
+ if (spend.unpricedTokens > 0) return 'cost_unmeasurable'
549
+ }
550
+ parentId = parent.parentId
551
+ }
552
+ return undefined
553
+ }
554
+
555
+ get treeCost(): CostInfo | undefined {
556
+ const ids = this.descendants(this.node)
557
+ return ids.size > 1 ? this.costOfAccounts(ids) : undefined
558
+ }
559
+
560
+ private costOfAccounts(ids: ReadonlySet<string>): CostInfo {
561
+ const total = { ...ZERO_COST }
562
+ for (const id of ids) {
563
+ const account = this.requireAccount(id)
564
+ const cost = account.cost ?? ZERO_COST
565
+ total.totalCost += cost.totalCost
566
+ total.cacheDiscount += cost.cacheDiscount
567
+ total.unpricedTokens += cost.unpricedTokens
568
+ if (cost.includedTokens !== undefined) {
569
+ total.includedTokens = (total.includedTokens ?? 0) + cost.includedTokens
570
+ }
571
+ if (!this.hasRequest(account)) {
572
+ const ownTokens = Object.values(account.usage).reduce(
573
+ (sum, usage) => sum + usage.totalTokens,
574
+ 0,
575
+ )
576
+ total.unpricedTokens += Math.max(0, ownTokens - (account.pricedThroughTokens ?? 0))
577
+ }
578
+ }
579
+ return total
580
+ }
581
+
582
+ get recordedCost(): { cost: CostInfo; tokens: number } | undefined {
583
+ const { cost, pricedThroughTokens } = this.node
584
+ return cost && pricedThroughTokens !== undefined
585
+ ? { cost, tokens: pricedThroughTokens }
586
+ : undefined
587
+ }
588
+
589
+ recordCost(cost: CostInfo, accountedTokens: number): void {
590
+ if (accountedTokens < (this.node.pricedThroughTokens ?? 0)) return
591
+ this.node.cost = { ...cost }
592
+ this.node.pricedThroughTokens = accountedTokens
593
+ this.persist()
594
+ }
595
+
507
596
  /** This account's request is still awaiting its final receipt; descendants are independent. */
508
597
  get hasInFlightRequest(): boolean {
509
598
  return this.hasRequest(this.node)
@@ -724,7 +813,9 @@ export class SessionTokenBudget {
724
813
  summary(): SessionTokenBudgetSummary {
725
814
  const totals = this.totals(this.node)
726
815
  const descendants = this.descendants(this.node)
816
+ const treeCost = descendants.size > 1 ? this.costOfAccounts(descendants) : undefined
727
817
  return {
818
+ ...(treeCost ? { treeCost } : {}),
728
819
  limit: this.limit,
729
820
  ownTokens: totals.own,
730
821
  treeTokens: totals.tree,
@@ -449,7 +449,9 @@ function createSource(
449
449
  }
450
450
  const { page, cacheHit } = indexed
451
451
  const matches: SessionTextEvidenceMatch[] = []
452
- const unavailable: string[] = []
452
+ const unavailable = page.unavailableShedSeqs
453
+ .filter((seq) => input.seq === undefined || input.seq === seq)
454
+ .map((seq) => `Text record ${seq} is available only in the full transcript.`)
453
455
  let partial = false
454
456
  let excludedToolResults = 0
455
457
  let excludedSummaries = 0
@@ -45,6 +45,7 @@ export type IndexPosition = z.infer<typeof positionSchema>
45
45
  export interface IndexPage {
46
46
  start: IndexPosition
47
47
  entries: IndexEntry[]
48
+ unavailableShedSeqs: number[]
48
49
  next: IndexPosition | null
49
50
  records: number
50
51
  }
@@ -154,6 +155,7 @@ export async function indexPage(
154
155
  let buffered = Buffer.alloc(0)
155
156
  let readOffset = offset
156
157
  const entries: IndexEntry[] = []
158
+ const unavailableShedSeqs: number[] = []
157
159
  while (offset < size && records < 64 && entries.length < 64) {
158
160
  budget.signal?.throwIfAborted()
159
161
  let newline = buffered.indexOf(10)
@@ -176,6 +178,14 @@ export async function indexPage(
176
178
  (offset === 0 && record.type !== 'session_started')
177
179
  )
178
180
  throw new Error('Session log identity or record sequence is invalid.')
181
+ if (
182
+ record.type === 'compaction_shed' &&
183
+ record.messagesSpill !== undefined &&
184
+ Array.isArray(record.messages) &&
185
+ record.messages.length === 0
186
+ ) {
187
+ unavailableShedSeqs.push(seq + 1)
188
+ }
179
189
  const parts = recordTexts(record)
180
190
  if (textIndex > parts.length) throw new Error('Invalid textual part position.')
181
191
  const hash = digest(raw)
@@ -212,6 +222,7 @@ export async function indexPage(
212
222
  const page: IndexPage = {
213
223
  start,
214
224
  entries,
225
+ unavailableShedSeqs,
215
226
  records,
216
227
  next: offset < size ? { offset, seq, textIndex } : null,
217
228
  }
@@ -122,11 +122,16 @@ async function inspect(path: string, env: Resolved): Promise<Inspection | undefi
122
122
  return { stats: before, content: '', pid: undefined, staleReason: undefined }
123
123
  const content = await readFile(path, 'utf8').catch((error: NodeJS.ErrnoException) => {
124
124
  if (error.code === 'ENOENT') return undefined
125
+ // Windows can deny reads while another handle still holds the lock file.
126
+ // Treat an unreadable owner as unverifiable, so it cannot be broken.
127
+ if (error.code === 'EACCES' || error.code === 'EPERM' || error.code === 'EBUSY') return null
125
128
  throw error
126
129
  })
127
130
  if (content === undefined) return undefined
128
131
  const after = await lstat(path).catch(() => undefined)
129
132
  if (!after || after.dev !== before.dev || after.ino !== before.ino) return undefined
133
+ if (content === null)
134
+ return { stats: before, content: '', pid: undefined, staleReason: undefined }
130
135
 
131
136
  const owner = parseOwner(content)
132
137
  if (owner) {
@@ -167,7 +172,20 @@ async function createOwned(
167
172
  try {
168
173
  handle = await open(path, 'wx', 0o600)
169
174
  } catch (error) {
170
- if ((error as NodeJS.ErrnoException).code === 'EEXIST') return undefined
175
+ const code = (error as NodeJS.ErrnoException).code
176
+ if (code === 'EEXIST') return undefined
177
+ // Windows reports an exclusive create over a file another process still
178
+ // holds open (or is deleting) as a sharing error, not EEXIST. When the
179
+ // path is there, it is occupied; otherwise the error is real.
180
+ if (code === 'EACCES' || code === 'EPERM' || code === 'EBUSY') {
181
+ if (
182
+ await lstat(path).then(
183
+ () => true,
184
+ () => false,
185
+ )
186
+ )
187
+ return undefined
188
+ }
171
189
  throw error
172
190
  }
173
191
  const owner = `${JSON.stringify({
@@ -976,6 +976,7 @@ export class SessionLogCore implements SessionLog {
976
976
  type !== 'message_replaced' &&
977
977
  type !== 'message_edited' &&
978
978
  type !== 'compaction' &&
979
+ type !== 'compaction_shed' &&
979
980
  type !== 'turn_completed'
980
981
  )
981
982
  return candidate
@@ -984,6 +985,31 @@ export class SessionLogCore implements SessionLog {
984
985
  // single large one never sits inline and bloats the log.
985
986
  const spillAbove = type === 'compaction' ? this.#compactionSpillAbove : this.#spillAbove
986
987
  if (size <= spillAbove) return candidate
988
+ if (type === 'compaction_shed') {
989
+ if (!Array.isArray(candidate.messages) || candidate.messagesSpill !== undefined)
990
+ return candidate
991
+ const messages = candidate.messages as Message[]
992
+ const messagesSpill = await this.#spills.write(
993
+ `shed:${String(candidate.id)}`,
994
+ 'messages',
995
+ JSON.stringify(messages),
996
+ )
997
+ // Keep the exact searchable text and tool pairing inline when they fit.
998
+ const projected = messages.map((message) => {
999
+ if (message.role === 'tool' && Array.isArray(message.content)) {
1000
+ return {
1001
+ ...message,
1002
+ content: message.content.filter((block) => block.type === 'text'),
1003
+ }
1004
+ }
1005
+ if (message.role === 'user') return { ...message, attachments: undefined }
1006
+ return message
1007
+ })
1008
+ const record = { ...candidate, messages: projected, messagesSpill }
1009
+ return Buffer.byteLength(`${JSON.stringify(record)}\n`, 'utf8') <= this.#spillAbove
1010
+ ? record
1011
+ : { ...record, messages: [] }
1012
+ }
987
1013
  if (type === 'turn_completed') {
988
1014
  if (typeof candidate.result !== 'string') return candidate
989
1015
  const ref = await this.#spillOrLose(
@@ -1,6 +1,15 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { lstatSync, realpathSync } from 'node:fs'
3
- import { type FileHandle, mkdir, open, realpath, rename, stat, unlink } from 'node:fs/promises'
2
+ import { constants, lstatSync, realpathSync } from 'node:fs'
3
+ import {
4
+ type FileHandle,
5
+ access,
6
+ mkdir,
7
+ open,
8
+ realpath,
9
+ rename,
10
+ stat,
11
+ unlink,
12
+ } from 'node:fs/promises'
4
13
  import nodePath, { basename, dirname, join, sep } from 'node:path'
5
14
 
6
15
  /** A write refused because its path runs through a symbolic link or out of its root. */
@@ -71,6 +80,25 @@ function assertNoLinkBelow(anchor: string, file: string): void {
71
80
  }
72
81
  }
73
82
 
83
+ async function writableMode(filePath: string): Promise<number | undefined> {
84
+ const existing = await stat(filePath).catch((error: NodeJS.ErrnoException) => {
85
+ if (error.code !== 'ENOENT') throw error
86
+ return undefined
87
+ })
88
+ if (existing === undefined) return undefined
89
+
90
+ const mode = existing.mode & 0o7777
91
+ // A privileged process can pass W_OK even when every write bit is clear.
92
+ if ((mode & 0o222) === 0) {
93
+ throw Object.assign(new Error(`EACCES: permission denied, file is read-only: ${filePath}`), {
94
+ code: 'EACCES',
95
+ path: filePath,
96
+ })
97
+ }
98
+ await access(filePath, constants.W_OK)
99
+ return mode
100
+ }
101
+
74
102
  /**
75
103
  * Commit a complete file body without exposing a truncated destination.
76
104
  *
@@ -92,12 +120,20 @@ export async function atomicWriteFile(
92
120
  if (anchor !== undefined) assertNoLinkBelow(anchor, requestedPath)
93
121
  const filePath =
94
122
  anchor === undefined ? await realpath(requestedPath).catch(() => requestedPath) : requestedPath
123
+ return atomicWriteResolvedFile(filePath, content, hooks)
124
+ }
125
+
126
+ /** Commit at a path already resolved by the caller's containment policy. */
127
+ export async function atomicWriteResolvedFile(
128
+ filePath: string,
129
+ content: string | Buffer,
130
+ hooks: AtomicWriteOptions = {},
131
+ ): Promise<void> {
95
132
  const directory = dirname(filePath)
133
+ const existingMode = await writableMode(filePath)
96
134
  await mkdir(directory, { recursive: true })
97
135
 
98
- const existingMode = await stat(filePath)
99
- .then((value) => value.mode)
100
- .catch(() => undefined)
136
+ const preservedMode = hooks.mode === undefined ? existingMode : undefined
101
137
  const tempPath = join(
102
138
  directory,
103
139
  `.${basename(filePath)}.namzu-${process.pid}-${randomUUID()}.tmp`,
@@ -106,13 +142,19 @@ export async function atomicWriteFile(
106
142
  let committed = false
107
143
 
108
144
  try {
109
- handle = await open(tempPath, 'wx', hooks.mode ?? existingMode ?? 0o666)
145
+ handle = await open(tempPath, 'wx', preservedMode === undefined ? (hooks.mode ?? 0o666) : 0o600)
110
146
  await handle.writeFile(content, 'utf-8')
147
+ // Creation applies the umask. Set the retained bits after writing, which
148
+ // can clear special mode bits on some filesystems.
149
+ if (preservedMode !== undefined) await handle.chmod(preservedMode)
111
150
  await handle.sync()
112
151
  await handle.close()
113
152
  handle = undefined
114
153
  await hooks.beforeCommit?.()
115
- if (anchor !== undefined) assertNoLinkBelow(anchor, filePath)
154
+ if (hooks.refuseLinksBelow !== undefined) assertNoLinkBelow(hooks.refuseLinksBelow, filePath)
155
+ if ((await writableMode(filePath)) !== existingMode) {
156
+ throw new Error(`File permissions changed before the write could commit: ${filePath}`)
157
+ }
116
158
  await rename(tempPath, filePath)
117
159
  committed = true
118
160
  await syncDirectory(directory)
@@ -52,6 +52,26 @@ export const HIGH_RES_SCREENSHOT_LIMITS: ScreenshotLimits = Object.freeze({
52
52
  maxTiles: 4784,
53
53
  })
54
54
 
55
+ /**
56
+ * The limits to fit a screenshot to for `model`: the high-resolution tier for
57
+ * a model known to read it (the 4.7 and later models of the vendor behind that
58
+ * tier, with or without a vendor prefix or a dated suffix), the standard tier for every
59
+ * other model, including one the table does not know. A wrong "high" costs a
60
+ * rejected tool result; a wrong "standard" only costs detail, so an unknown
61
+ * model gets the standard tier.
62
+ */
63
+ export function screenshotLimitsForModel(model: string | undefined): ScreenshotLimits {
64
+ if (model === undefined) return STANDARD_SCREENSHOT_LIMITS
65
+ const match = /claude-(?:opus|sonnet|haiku|fable)-(\d+)(?:[-.](\d{1,2})(?!\d))?/i.exec(model)
66
+ if (!match) return STANDARD_SCREENSHOT_LIMITS
67
+ const major = Number(match[1])
68
+ const minor = match[2] === undefined ? 0 : Number(match[2])
69
+ // A dated id such as `claude-sonnet-4-20250514` has no minor: the date is not one.
70
+ return major > 4 || (major === 4 && minor >= 7)
71
+ ? HIGH_RES_SCREENSHOT_LIMITS
72
+ : STANDARD_SCREENSHOT_LIMITS
73
+ }
74
+
55
75
  export interface ImageSize {
56
76
  readonly width: number
57
77
  readonly height: number
@@ -39,7 +39,6 @@ import {
39
39
  } from './computer-use-coordinates.js'
40
40
  import {
41
41
  type FittedImage,
42
- HIGH_RES_SCREENSHOT_LIMITS,
43
42
  STANDARD_SCREENSHOT_LIMITS,
44
43
  type ScreenshotLimits,
45
44
  cropAndFitPng,
@@ -55,25 +54,7 @@ export {
55
54
  } from './computer-use-image.js'
56
55
  export type { ImageSize, ScreenshotLimits } from './computer-use-image.js'
57
56
 
58
- /**
59
- * The limits to fit a screenshot to for `model`: the high-resolution tier for
60
- * a model known to read it (the 4.7 and later models of the vendor behind that
61
- * tier, with or without a vendor prefix or a dated suffix), the standard tier for every
62
- * other model, including one the table does not know. A wrong "high" costs a
63
- * rejected tool result; a wrong "standard" only costs detail, so an unknown
64
- * model gets the standard tier.
65
- */
66
- export function screenshotLimitsForModel(model: string | undefined): ScreenshotLimits {
67
- if (model === undefined) return STANDARD_SCREENSHOT_LIMITS
68
- const match = /claude-(?:opus|sonnet|haiku|fable)-(\d+)(?:[-.](\d{1,2})(?!\d))?/i.exec(model)
69
- if (!match) return STANDARD_SCREENSHOT_LIMITS
70
- const major = Number(match[1])
71
- const minor = match[2] === undefined ? 0 : Number(match[2])
72
- // A dated id such as `claude-sonnet-4-20250514` has no minor: the date is not one.
73
- return major > 4 || (major === 4 && minor >= 7)
74
- ? HIGH_RES_SCREENSHOT_LIMITS
75
- : STANDARD_SCREENSHOT_LIMITS
76
- }
57
+ export { screenshotLimitsForModel } from './computer-use-image.js'
77
58
 
78
59
  export const COMPUTER_USE_TOOL_NAME = 'computer_use' as const
79
60
 
@@ -7,6 +7,7 @@ import { defineTool } from '../defineTool.js'
7
7
  import { resolveWithinAnyReal, toolRoots } from '../paths.js'
8
8
  import { resolveRetainedOutput } from '../retained-output.js'
9
9
  import { looksBinary } from '../text-window.js'
10
+ import { toolIsAvailable } from '../tool-is-available.js'
10
11
  import { TEXT_MAX_INPUT_BYTES, readBoundedChunks, readBoundedFile } from './bounded-file-read.js'
11
12
  import { fingerprintContent } from './content-fingerprint.js'
12
13
  import {
@@ -89,6 +90,7 @@ export const ReadFileTool = defineTool({
89
90
  },
90
91
 
91
92
  async execute(input, context) {
93
+ const shellAvailable = toolIsAvailable(context, 'bash')
92
94
  // This session's own retained tool output lives on the host, outside the
93
95
  // roots and outside any sandbox. It is read here, as a plain window of text,
94
96
  // because the result that named it told the model to.
@@ -105,7 +107,7 @@ export const ReadFileTool = defineTool({
105
107
  )
106
108
  const media = await readMediaFile(buffer, input.path, input, context, true)
107
109
  if (media) return media
108
- const binaryGuidance = describeStructuredBinaryRead(input.path)
110
+ const binaryGuidance = describeStructuredBinaryRead(input.path, shellAvailable)
109
111
  if (binaryGuidance) {
110
112
  return {
111
113
  success: false,
@@ -124,7 +126,8 @@ export const ReadFileTool = defineTool({
124
126
  }
125
127
  }
126
128
  const content = buffer.toString('utf-8')
127
- if (looksBinary(content)) return unreadableAsText(input.path, buffer.length, true)
129
+ if (looksBinary(content))
130
+ return unreadableAsText(input.path, buffer.length, true, shellAvailable)
128
131
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
129
132
  if (!capped.ok) return refusedRead(input.path, buffer.length, capped.message, true)
130
133
  const rendered = capped.rendered
@@ -162,7 +165,7 @@ export const ReadFileTool = defineTool({
162
165
  )
163
166
  const media = await readMediaFile(buffer, filePath, input, context, false)
164
167
  if (media) return media
165
- const binaryGuidance = describeStructuredBinaryRead(filePath)
168
+ const binaryGuidance = describeStructuredBinaryRead(filePath, shellAvailable)
166
169
  if (binaryGuidance) {
167
170
  return {
168
171
  success: false,
@@ -180,7 +183,8 @@ export const ReadFileTool = defineTool({
180
183
  }
181
184
  }
182
185
  const content = buffer.toString('utf-8')
183
- if (looksBinary(content)) return unreadableAsText(filePath, buffer.length, false)
186
+ if (looksBinary(content))
187
+ return unreadableAsText(filePath, buffer.length, false, shellAvailable)
184
188
  const capped = renderCappedRead(content, buffer.length, input, capOptions(input, context))
185
189
  if (!capped.ok) return refusedRead(filePath, buffer.length, capped.message, false)
186
190
  const rendered = capped.rendered
@@ -337,10 +341,18 @@ function capOptions(
337
341
  * A file whose bytes are not text. The model gets a short note with the size
338
342
  * and the next step, never the numbered garbage a decode would produce.
339
343
  */
340
- function unreadableAsText(path: string, bytes: number, sandboxed: boolean) {
344
+ function unreadableAsText(
345
+ path: string,
346
+ bytes: number,
347
+ sandboxed: boolean,
348
+ shellAvailable: boolean,
349
+ ) {
350
+ const hint = shellAvailable
351
+ ? ' Inspect it with a shell command such as file or xxd, or use a tool made for its format.'
352
+ : ''
341
353
  return {
342
354
  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.`,
355
+ output: `This file is not readable as text (${humanBytes(bytes)} of binary or non-UTF-8 data).${hint}`,
344
356
  data: { path, binary: true, ...(sandboxed ? { sandboxed: true } : {}) },
345
357
  facts: { kind: 'read' as const, path, binary: true, bytes },
346
358
  }
@@ -463,17 +475,27 @@ function unchangedRead(
463
475
  }
464
476
  }
465
477
 
466
- function describeStructuredBinaryRead(path: string): string | null {
478
+ function describeStructuredBinaryRead(path: string, shellAvailable: boolean): string | null {
467
479
  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')
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)
471
486
  return null
472
487
  }
473
488
 
474
- function buildStructuredBinaryGuidance(path: string, format: string, extractor: string): string {
489
+ function buildStructuredBinaryGuidance(
490
+ path: string,
491
+ format: string,
492
+ extractor: string,
493
+ shellAvailable: boolean,
494
+ ): string {
495
+ const description = `The file "${path}" is a ${format} document package, not UTF-8 text.`
496
+ if (!shellAvailable) return description
475
497
  return [
476
- `The file "${path}" is a ${format} document package, not UTF-8 text.`,
498
+ description,
477
499
  'Do not use the read/cat tools as evidence for this raw file.',
478
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.`,
479
501
  'If extraction fails, report the exact filename and extraction error instead of claiming the attachment is unavailable.',
@@ -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
  : ''
@@ -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
+ }
@@ -540,9 +540,13 @@ export class ToolManager {
540
540
  /**
541
541
  * Put the tools that were loaded on request after the ones that are loaded
542
542
  * from the start, in the order they were loaded. A load then extends the
543
- * tools array of the previous request instead of reshaping it, so the
544
- * cached prefix survives it. The order comes from the receipts in the
545
- * history, so a compaction or a resume gives the same one.
543
+ * tools array of the previous request instead of reshaping it, so the tools
544
+ * the request already had keep their place. It is still a change to the
545
+ * tools block, which a provider reads before the system prompt and the
546
+ * messages: the request that carries a new tool re-reads those once, and
547
+ * only the unchanged start of the tools block is kept. The order comes
548
+ * from the receipts in the history, so a compaction or a resume gives the
549
+ * same one.
546
550
  */
547
551
  private loadedLast(tools: ToolDefinition[]): ToolDefinition[] {
548
552
  const order = this.revealOrder()