@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
@@ -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.
@@ -107,6 +112,28 @@ export interface TokenUsage {
107
112
  * provider reported nothing, a pending answer, or a hit.
108
113
  */
109
114
  cacheMiss?: CacheMiss
115
+
116
+ /**
117
+ * The request shape the driver actually put on the wire for this call, when
118
+ * it can say: a driver that drops a field after the backend refused it
119
+ * reports what remained. Per call, never summed. Absent means the driver
120
+ * does not report it, not that nothing was sent.
121
+ */
122
+ requestShape?: RequestWireShape
123
+ }
124
+
125
+ /** What a driver sent for one call, as far as the prompt cache is concerned. See {@link TokenUsage.requestShape}. */
126
+ export interface RequestWireShape {
127
+ /** A cache key naming the conversation was sent. */
128
+ cacheKey: boolean
129
+ /** A session header naming the conversation was sent. */
130
+ sessionHeader: boolean
131
+ /**
132
+ * True while the backend's refusal of the `developer` role is in force for the driver
133
+ * (it is process-wide), so it is true on every request made under it, whether or not
134
+ * that request had guidance to send. Absent or false otherwise.
135
+ */
136
+ developerRefused?: boolean
110
137
  }
111
138
 
112
139
  /** A prompt-cache miss as the provider explains it. See {@link TokenUsage.cacheMiss}. */
@@ -133,6 +160,12 @@ export function accumulateTokenUsage(current: TokenUsage, addition: TokenUsage):
133
160
  totalTokens: current.totalTokens + addition.totalTokens,
134
161
  cachedTokens: current.cachedTokens + addition.cachedTokens,
135
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
+ : {}),
136
169
  // Summed only when at least one side reported it. Coercing absent to
137
170
  // zero would turn 'this driver does not tell us' into 'it spent none',
138
171
  // and a turn mixing a reporting driver with a silent one would read as
@@ -147,7 +180,7 @@ export function accumulateTokenUsage(current: TokenUsage, addition: TokenUsage):
147
180
  ? { reportedCostUsd: (current.reportedCostUsd ?? 0) + (addition.reportedCostUsd ?? 0) }
148
181
  : {}),
149
182
  // `fullPromptTokens`, `cacheTtlMs`, `cacheWriteTtlTokens`, `speed`, `serviceTier`,
150
- // `inferenceGeo` and `cacheMiss` are per-call facts and are deliberately
183
+ // `inferenceGeo`, `cacheMiss` and `requestShape` are per-call facts and are deliberately
151
184
  // not carried into a sum.
152
185
  }
153
186
  }
@@ -180,6 +213,17 @@ export function mergeTokenUsage(current: TokenUsage, next: TokenUsage): TokenUsa
180
213
  totalTokens: Math.max(current.totalTokens, next.totalTokens, promptTokens + completionTokens),
181
214
  cachedTokens: Math.max(current.cachedTokens, next.cachedTokens),
182
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
+ : {}),
183
227
  ...(current.fullPromptTokens !== undefined || next.fullPromptTokens !== undefined
184
228
  ? { fullPromptTokens: Math.max(current.fullPromptTokens ?? 0, next.fullPromptTokens ?? 0) }
185
229
  : {}),
@@ -212,10 +256,15 @@ export function mergeTokenUsage(current: TokenUsage, next: TokenUsage): TokenUsa
212
256
  ...(next.cacheMiss !== undefined || current.cacheMiss !== undefined
213
257
  ? { cacheMiss: next.cacheMiss ?? current.cacheMiss }
214
258
  : {}),
259
+ ...(next.requestShape !== undefined || current.requestShape !== undefined
260
+ ? { requestShape: next.requestShape ?? current.requestShape }
261
+ : {}),
215
262
  }
216
263
  }
217
264
 
218
265
  export interface CostInfo {
266
+ /** Tokens covered by a subscription plan. */
267
+ includedTokens?: number
219
268
  /**
220
269
  * The input rate this total was accumulated at — present only when ONE rate
221
270
  * card describes the whole total.
@@ -188,6 +188,17 @@ export interface ResumeContext {
188
188
  readonly transcript: () => readonly Message[]
189
189
  /** The turn's cancellation signal, when it has one. */
190
190
  readonly signal?: AbortSignal
191
+ /**
192
+ * Resolves when the person wrote a message to this turn, and for no other
193
+ * reason; the supplied signal ends the wait and releases its listener. Present
194
+ * only when the host has a live message box for the turn.
195
+ *
196
+ * A handler that puts a question to a person reads it: a message that arrives
197
+ * while the question is open (or was already waiting when it would be asked)
198
+ * closes the question, so the turn never carries on beside a request nobody
199
+ * will answer. The message itself is delivered in the turn's usual way.
200
+ */
201
+ readonly waitForOperator?: (signal: AbortSignal) => Promise<void>
191
202
  /**
192
203
  * The script files a shell line launches that the agent wrote, or that came
193
204
  * into being during the session, read now. Absent when the host keeps no
@@ -31,6 +31,13 @@ export interface EmbeddingConfig {
31
31
  * loud.
32
32
  */
33
33
  export interface HttpEmbeddingConfig extends EmbeddingConfig {
34
+ /** Let the server choose the vector width and omit dimensions from the request. */
35
+ useModelDimensions?: boolean
36
+ /** Override the HTTP transport, for example to connect directly to a local server. */
37
+ fetch?: (
38
+ url: string,
39
+ init: RequestInit,
40
+ ) => Promise<Pick<Response, 'ok' | 'status' | 'text' | 'json'>>
34
41
  apiKey: string
35
42
  /** Root of an embeddings API; `/embeddings` is appended. */
36
43
  baseUrl: string
@@ -128,6 +128,11 @@ export interface SandboxExecResult {
128
128
  // ---------------------------------------------------------------------------
129
129
 
130
130
  export interface SandboxExecOptions {
131
+ /**
132
+ * Maximum combined stdout and stderr bytes accepted by the host.
133
+ * The host rejects with `SandboxLimitError` when output exceeds it.
134
+ */
135
+ maxOutputBytes?: number
131
136
  readonly timeout?: number
132
137
  readonly env?: Record<string, string>
133
138
  readonly cwd?: string
@@ -178,6 +183,25 @@ export interface SandboxExecOptions {
178
183
  * returns an explicit unsupported error before running the command.
179
184
  */
180
185
  readonly signal?: AbortSignal
186
+ /**
187
+ * Text to give the command on its standard input; stdin is closed once it
188
+ * has been written, so a program that reads to the end sees end-of-file.
189
+ *
190
+ * **Who honours it.** The agent-backed backends in `@namzu/sandbox`
191
+ * (Firecracker microVMs and Kubernetes pods) carry it on the wire request
192
+ * the guest agent already accepts, under the same abort, timeout and
193
+ * output rules as the rest of `exec`. A backend without a guest agent (the
194
+ * in-process local sandbox, the Docker and ACI HTTP workers, the local
195
+ * virtual computer) **refuses** a call that carries it, before anything
196
+ * runs, with a {@link SandboxExecStdinError}; it never drops the input and
197
+ * runs the command on an empty stdin. A detached Kubernetes exec refuses
198
+ * it too.
199
+ *
200
+ * Bounded: the UTF-8 encoding may be at most
201
+ * {@link SANDBOX_EXEC_STDIN_MAX_BYTES} bytes. Larger input is refused
202
+ * before it is sent; stage a big document with `writeFile` instead.
203
+ */
204
+ readonly stdin?: string
181
205
  }
182
206
 
183
207
  // ---------------------------------------------------------------------------
@@ -345,6 +369,12 @@ export interface SandboxTcpConnectOptions {
345
369
  * file.
346
370
  */
347
371
  export interface SandboxReadFileOptions {
372
+ /**
373
+ * Maximum bytes in the requested file slice. A larger slice is refused
374
+ * with `SandboxLimitError`. A backend that cannot enforce this limit
375
+ * must refuse the operation.
376
+ */
377
+ readonly maxBytes?: number
348
378
  /** First byte to read. Defaults to 0. */
349
379
  readonly offset?: number
350
380
  /**
@@ -358,7 +388,7 @@ export interface SandboxReadFileOptions {
358
388
  * asked for 4 MiB, got 1 MiB and was told nothing would read the short
359
389
  * answer as the end of its range. The agent-backed backends cap it at
360
390
  * `NAMZU_AGENT_READ_FILE_RANGE_BYTES` (1 MiB by default), because one
361
- * range is one wire frame there; a provider reading from local disk has
391
+ * range without `maxBytes` is one wire frame there; a provider reading from local disk has
362
392
  * no such ceiling. A caller that wants more than a frame's worth in one
363
393
  * call iterates {@link Sandbox.readFileStream} instead, which is not
364
394
  * capped.
@@ -78,6 +78,7 @@ export const TokenUsageSchema = z
78
78
  totalTokens: count,
79
79
  cachedTokens: count,
80
80
  cacheWriteTokens: count,
81
+ cacheTokensInPrompt: count.optional(),
81
82
  reasoningTokens: count.optional(),
82
83
  cacheTtlMs: count.optional(),
83
84
  cacheWriteTtlTokens: z
@@ -94,6 +95,7 @@ export const CostInfoSchema = z
94
95
  totalCost: z.number().nonnegative(),
95
96
  cacheDiscount: z.number(),
96
97
  unpricedTokens: count,
98
+ includedTokens: count.optional(),
97
99
  })
98
100
  .strict()
99
101
 
@@ -26,6 +26,49 @@ import type { MessageStopReason, StopReason } from './stop-reason.js'
26
26
  import type { SubSessionKind } from './sub-session.js'
27
27
  import type { LiveTurnSettlement, Origin, TurnBudgetBinding, TurnConfigSnapshot } from './turn.js'
28
28
 
29
+ /**
30
+ * Where a request's start differs from the previous request of its
31
+ * conversation, without any of its content. A provider cache reads a request
32
+ * from its start (model, tools, system text, then each message), so the first
33
+ * thing that moved is where the cache can no longer be read.
34
+ *
35
+ * Every field is a hash; none can be turned back into text.
36
+ */
37
+ export interface RequestPrefixDigest {
38
+ /** Hash of the model name. */
39
+ model: string
40
+ /** Hash of the tools as sent, in order. */
41
+ tools: string
42
+ /** Hash of the leading system messages. */
43
+ system: string
44
+ /** Hash of the settings that are not part of the start but can still move a cache (effort, speed, tool choice). */
45
+ params: string
46
+ /** One 6-character hash per message after the leading system run, in order, concatenated. */
47
+ items: string
48
+ /**
49
+ * What the driver reports it sent after the backend's refusals, when it reports it:
50
+ * whether a cache key and a session header named the conversation, and whether the
51
+ * backend's refusal of the `developer` role is in force (true on every request made
52
+ * under it, whether or not that request had guidance). Absent for a driver that does
53
+ * not say; never assumed from what was asked for.
54
+ */
55
+ cacheKey?: boolean
56
+ sessionHeader?: boolean
57
+ developerRefused?: boolean
58
+ /**
59
+ * Which of the above moved since the previous request of this conversation in this
60
+ * process (`wire` is the three reported fields together). Absent for the first request
61
+ * of the process, including the first after a restart or resume: there is nothing to compare with.
62
+ */
63
+ changed?: ('model' | 'tools' | 'system' | 'params' | 'wire')[]
64
+ /**
65
+ * The index of the first earlier message that this request does not repeat in place
66
+ * (the previous request's own request-only notes, which no request repeats, do not count).
67
+ * Absent when every earlier message is still where it was.
68
+ */
69
+ firstChangedItem?: number
70
+ }
71
+
29
72
  /**
30
73
  * Live events of a session: the stream a host listens to while a turn runs.
31
74
  *
@@ -944,6 +987,7 @@ type CoreSessionEvent =
944
987
  }
945
988
  | {
946
989
  type: 'token_usage_updated'
990
+ billingRoute?: TokenUsage['billingRoute']
947
991
  /** Aggregate tree spend, distinct from this turn's own usage. */
948
992
  budget?: SessionTokenBudgetSummary
949
993
  sessionId: SessionId
@@ -963,6 +1007,12 @@ type CoreSessionEvent =
963
1007
  * shows it should do so quietly; a miss after an edit is ordinary.
964
1008
  */
965
1009
  cacheMiss?: { reason: string; missedTokens?: number }
1010
+ /**
1011
+ * What this request's start was, as hashes, and what moved since the
1012
+ * request before it: the record that says where a fall in the cached
1013
+ * share began. Optional; an older reader ignores it.
1014
+ */
1015
+ requestPrefix?: RequestPrefixDigest
966
1016
  /**
967
1017
  * How large the CONTEXT is right now, and how large it may get.
968
1018
  *
@@ -189,6 +189,7 @@ const tokenBudgetSummary = z
189
189
  limit: z.number().nonnegative(),
190
190
  ownTokens: count,
191
191
  treeTokens: count,
192
+ treeCost: CostInfoSchema.optional(),
192
193
  reservedTokens: count,
193
194
  remainingTokens: z.number().nullable(),
194
195
  inFlightRequests: count,
@@ -999,6 +1000,17 @@ export const SessionRecordSchema = z
999
1000
  message: `${r.type} happens only inside a turn and must carry turnId`,
1000
1001
  })
1001
1002
  }
1003
+ if (
1004
+ r.type === 'compaction_shed' &&
1005
+ r.messagesSpill !== undefined &&
1006
+ (!Array.isArray(r.messages) || !spill.safeParse(r.messagesSpill).success)
1007
+ ) {
1008
+ context.addIssue({
1009
+ code: z.ZodIssueCode.custom,
1010
+ path: ['messagesSpill'],
1011
+ message: 'Invalid shed message spill or inline projection.',
1012
+ })
1013
+ }
1002
1014
  if (
1003
1015
  r.type === 'tool_completed' &&
1004
1016
  r.inputFailure !== undefined &&
@@ -1163,6 +1175,9 @@ export type SessionEventRecord<T extends PersistedSessionEventType = PersistedSe
1163
1175
  readonly structuredOutputSpill?: z.infer<typeof structuredResultSpill>
1164
1176
  }
1165
1177
  : unknown) &
1178
+ (T extends 'compaction_shed'
1179
+ ? { readonly messagesSpill?: z.infer<typeof spill> }
1180
+ : unknown) &
1166
1181
  (T extends TurnBoundSessionEventType ? { readonly turnId: TurnId } : unknown)
1167
1182
  : never
1168
1183
 
package/src/utils/cost.ts CHANGED
@@ -28,6 +28,27 @@ export interface CacheRates {
28
28
  * a quietly wrong total.
29
29
  */
30
30
  readonly writeCostPer1M?: number
31
+ /**
32
+ * What a write costs when the entry was asked to live for one hour
33
+ * (`TokenUsage.cacheWriteTtlTokens.oneHour`, or `cacheTtlMs` of one hour
34
+ * when the vendor gives no split). Absent means the vendor has no separate
35
+ * price and every write is charged at {@link CacheRates.writeCostPer1M}.
36
+ */
37
+ readonly writeCostPer1MOneHour?: number
38
+ }
39
+
40
+ export interface LongContextRates {
41
+ /** A prompt of more than this many tokens is priced at the rates below. */
42
+ readonly aboveInputTokens: number
43
+ readonly inputCostPer1M: number
44
+ readonly outputCostPer1M: number
45
+ readonly cacheReadCostPer1M: number
46
+ /** Falls back to the base cache-write rate when omitted. */
47
+ readonly cacheWriteCostPer1M?: number
48
+ /** Falls back to the base one-hour cache-write rate when omitted. */
49
+ readonly cacheWriteCostPer1MOneHour?: number
50
+ /** Published fast-mode multiplier for this tier. */
51
+ readonly fastMultiplier?: number
31
52
  }
32
53
 
33
54
  export interface ModelPricing {
@@ -48,6 +69,18 @@ export interface ModelPricing {
48
69
  * charged at the standard rate, which would under-report it.
49
70
  */
50
71
  fastMultiplier?: number
72
+ /**
73
+ * A higher rate card the vendor applies to the whole of any request whose
74
+ * prompt is longer than `aboveInputTokens`, including cache reads and
75
+ * writes. Absent means one rate card at every length.
76
+ */
77
+ longContext?: LongContextRates
78
+ /**
79
+ * The vendor's multiple of every rate on this card when the call ran with
80
+ * US-only inference (`TokenUsage.inferenceGeo === 'us'`). Absent means no
81
+ * published surcharge for this model.
82
+ */
83
+ usMultiplier?: number
51
84
  /**
52
85
  * What the vendor charges per 1,000 hosted web searches
53
86
  * (`TokenUsage.webSearchRequests`). Absent means no published search price:
@@ -97,7 +130,9 @@ function priceTokens(usage: TokenUsage, pricing: ModelPricing): Priced {
97
130
  return { cost: 0, cacheDiscount: 0, unpriced: usage.totalTokens }
98
131
  }
99
132
  if (usage.speed === 'fast') {
100
- const multiplier = pricing.fastMultiplier
133
+ const multiplier = usesLongContext(usage, pricing)
134
+ ? pricing.longContext?.fastMultiplier
135
+ : pricing.fastMultiplier
101
136
  if (multiplier === undefined) {
102
137
  return { cost: 0, cacheDiscount: 0, unpriced: usage.totalTokens }
103
138
  }
@@ -111,7 +146,66 @@ function priceTokens(usage: TokenUsage, pricing: ModelPricing): Priced {
111
146
  return priceStandard(usage, pricing)
112
147
  }
113
148
 
114
- function priceStandard(usage: TokenUsage, pricing: ModelPricing): Priced {
149
+ function countPromptTokens(usage: TokenUsage, cache: CacheRates | undefined): number {
150
+ if (usage.cacheTokensInPrompt !== undefined) return usage.promptTokens
151
+ return (
152
+ usage.fullPromptTokens ??
153
+ usage.promptTokens +
154
+ (cache?.promptIncludesCacheReads === false ? usage.cachedTokens : 0) +
155
+ usage.cacheWriteTokens
156
+ )
157
+ }
158
+
159
+ /** Cache-write tokens split into the one-hour entry and the rest. */
160
+ function splitWrites(usage: TokenUsage): { oneHour: number; rest: number } {
161
+ const total = usage.cacheWriteTokens
162
+ const split = usage.cacheWriteTtlTokens
163
+ if (split !== undefined) {
164
+ const oneHour = Math.min(Math.max(split.oneHour ?? 0, 0), total)
165
+ return { oneHour, rest: total - oneHour }
166
+ }
167
+ return usage.cacheTtlMs === 3_600_000 ? { oneHour: total, rest: 0 } : { oneHour: 0, rest: total }
168
+ }
169
+
170
+ function priceStandard(usage: TokenUsage, basePricing: ModelPricing): Priced {
171
+ const priced = priceStandardTokens(usage, basePricing)
172
+ const us = basePricing.usMultiplier
173
+ if (us === undefined || usage.inferenceGeo !== 'us') return priced
174
+ return {
175
+ cost: priced.cost * us,
176
+ cacheDiscount: priced.cacheDiscount * us,
177
+ unpriced: priced.unpriced,
178
+ }
179
+ }
180
+
181
+ function usesLongContext(usage: TokenUsage, pricing: ModelPricing): boolean {
182
+ return (
183
+ pricing.longContext !== undefined &&
184
+ countPromptTokens(usage, pricing.cache) > pricing.longContext.aboveInputTokens
185
+ )
186
+ }
187
+
188
+ function priceStandardTokens(usage: TokenUsage, basePricing: ModelPricing): Priced {
189
+ const tier = basePricing.longContext
190
+ const pricing: ModelPricing =
191
+ tier && usesLongContext(usage, basePricing)
192
+ ? {
193
+ ...basePricing,
194
+ inputCostPer1M: tier.inputCostPer1M,
195
+ outputCostPer1M: tier.outputCostPer1M,
196
+ ...(basePricing.cache
197
+ ? {
198
+ cache: {
199
+ ...basePricing.cache,
200
+ readCostPer1M: tier.cacheReadCostPer1M,
201
+ writeCostPer1M: tier.cacheWriteCostPer1M ?? basePricing.cache.writeCostPer1M,
202
+ writeCostPer1MOneHour:
203
+ tier.cacheWriteCostPer1MOneHour ?? basePricing.cache.writeCostPer1MOneHour,
204
+ },
205
+ }
206
+ : {}),
207
+ }
208
+ : basePricing
115
209
  const perMillion = (tokens: number, rate: number) => (tokens / 1_000_000) * rate
116
210
 
117
211
  const cache = pricing.cache
@@ -128,18 +222,23 @@ function priceStandard(usage: TokenUsage, pricing: ModelPricing): Priced {
128
222
  // Never negative: a driver that reports more cached tokens than prompt
129
223
  // tokens is contradicting itself, and clamping keeps that from turning into
130
224
  // a credit on the bill.
131
- const billableInput = cache.promptIncludesCacheReads
132
- ? Math.max(0, usage.promptTokens - usage.cachedTokens)
133
- : usage.promptTokens
225
+ const cacheInPrompt =
226
+ usage.cacheTokensInPrompt ?? (cache.promptIncludesCacheReads ? usage.cachedTokens : 0)
227
+ const billableInput = Math.max(0, usage.promptTokens - cacheInPrompt)
134
228
 
135
229
  const writesRated = cache.writeCostPer1M !== undefined
230
+ const writes = splitWrites(usage)
231
+ const writeCost = writesRated
232
+ ? perMillion(writes.rest, cache.writeCostPer1M as number) +
233
+ perMillion(writes.oneHour, cache.writeCostPer1MOneHour ?? (cache.writeCostPer1M as number))
234
+ : 0
136
235
 
137
236
  return {
138
237
  cost:
139
238
  perMillion(billableInput, pricing.inputCostPer1M) +
140
239
  perMillion(usage.completionTokens, pricing.outputCostPer1M) +
141
240
  perMillion(usage.cachedTokens, cache.readCostPer1M) +
142
- (writesRated ? perMillion(usage.cacheWriteTokens, cache.writeCostPer1M as number) : 0),
241
+ writeCost,
143
242
  // Reported, not subtracted. The saving is already inside `cost` — the
144
243
  // reads were charged at the read rate rather than the input rate — so
145
244
  // taking it off again would double-count it. This field was previously
@@ -151,6 +250,8 @@ function priceStandard(usage: TokenUsage, pricing: ModelPricing): Priced {
151
250
  }
152
251
 
153
252
  export function calculateCost(usage: TokenUsage, pricing: ModelPricing): CostInfo {
253
+ if (usage.billingRoute === 'subscription')
254
+ return { ...ZERO_COST, includedTokens: usage.totalTokens }
154
255
  const priced = priceUsage(usage, pricing)
155
256
  return {
156
257
  inputCostPer1M: pricing.inputCostPer1M,
@@ -180,6 +281,7 @@ function isFresh(current: CostInfo): boolean {
180
281
  return (
181
282
  current.totalCost === 0 &&
182
283
  current.unpricedTokens === 0 &&
284
+ current.includedTokens === undefined &&
183
285
  current.inputCostPer1M === undefined &&
184
286
  current.outputCostPer1M === undefined
185
287
  )
@@ -221,11 +323,20 @@ export function accumulateCost(
221
323
  additionalUsage: TokenUsage,
222
324
  pricing: ModelPricing,
223
325
  ): CostInfo {
326
+ if (additionalUsage.billingRoute === 'subscription') {
327
+ return {
328
+ totalCost: current.totalCost,
329
+ cacheDiscount: current.cacheDiscount,
330
+ unpricedTokens: current.unpricedTokens,
331
+ includedTokens: (current.includedTokens ?? 0) + additionalUsage.totalTokens,
332
+ }
333
+ }
224
334
  const priced = priceUsage(additionalUsage, pricing)
225
335
  const rates = priced.unpriced > 0 ? {} : ratesFor(current, pricing)
226
336
  return {
227
337
  ...rates,
228
338
  totalCost: current.totalCost + priced.cost,
339
+ ...includedUsage(current),
229
340
  cacheDiscount: current.cacheDiscount + priced.cacheDiscount,
230
341
  unpricedTokens: current.unpricedTokens + priced.unpriced,
231
342
  }
@@ -247,6 +358,7 @@ export function accumulateUnpricedCost(current: CostInfo, additionalUsage: Token
247
358
  totalCost: current.totalCost,
248
359
  cacheDiscount: current.cacheDiscount,
249
360
  unpricedTokens: current.unpricedTokens + additionalUsage.totalTokens,
361
+ ...includedUsage(current),
250
362
  }
251
363
  }
252
364
 
@@ -262,11 +374,16 @@ export function accumulateUnpricedCost(current: CostInfo, additionalUsage: Token
262
374
  export function accumulateReportedCost(current: CostInfo, reportedCostUsd: number): CostInfo {
263
375
  return {
264
376
  totalCost: current.totalCost + reportedCostUsd,
377
+ ...includedUsage(current),
265
378
  cacheDiscount: current.cacheDiscount,
266
379
  unpricedTokens: current.unpricedTokens,
267
380
  }
268
381
  }
269
382
 
383
+ function includedUsage(cost: CostInfo): Pick<CostInfo, 'includedTokens'> {
384
+ return cost.includedTokens === undefined ? {} : { includedTokens: cost.includedTokens }
385
+ }
386
+
270
387
  /** Whether a usage frame carries a usable vendor-reported cost. */
271
388
  export function hasReportedCost(
272
389
  usage: TokenUsage,
@@ -274,10 +391,22 @@ export function hasReportedCost(
274
391
  return Number.isFinite(usage.reportedCostUsd) && (usage.reportedCostUsd as number) >= 0
275
392
  }
276
393
 
394
+ /**
395
+ * Round half up on the decimal digits, not on the binary float:
396
+ * `(0.995).toFixed(2)` is `'0.99'` because 0.995 is stored as 0.99499999...
397
+ * The tiny relative nudge brings a value that is a decimal tie in the vendor's
398
+ * rate card back onto it.
399
+ */
400
+ function roundDecimal(usd: number, digits: number): string {
401
+ const scale = 10 ** digits
402
+ return (Math.round(usd * scale * (1 + Number.EPSILON * 8)) / scale).toFixed(digits)
403
+ }
404
+
277
405
  export function formatCost(usd: number): string {
278
406
  if (usd === 0) return '$0.00'
279
- if (usd < 0.01) return `$${usd.toFixed(4)}`
280
- return `$${usd.toFixed(2)}`
407
+ if (usd > 0 && usd < 0.0001) return '<$0.0001'
408
+ if (usd < 0.01) return `$${roundDecimal(usd, 4)}`
409
+ return `$${roundDecimal(usd, 2)}`
281
410
  }
282
411
 
283
412
  /**
@@ -290,6 +419,13 @@ export function formatCost(usd: number): string {
290
419
  * to follow.
291
420
  */
292
421
  export function describeCost(cost: CostInfo): string {
422
+ if (cost.includedTokens !== undefined) {
423
+ const plan = `included in your plan (${cost.includedTokens.toLocaleString('en-US')} tokens)`
424
+ const { includedTokens: _included, ...metered } = cost
425
+ return cost.totalCost === 0 && cost.unpricedTokens === 0
426
+ ? plan
427
+ : `${describeCost(metered)} + ${plan}`
428
+ }
293
429
  if (cost.unpricedTokens === 0) return formatCost(cost.totalCost)
294
430
  if (cost.totalCost === 0) {
295
431
  return `unknown (${cost.unpricedTokens} tokens at no known rate)`