@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
@@ -0,0 +1,130 @@
1
+ import type { Message, MessageAttachment, ToolResultBlock } from '../types/message/index.js'
2
+ import { findRetainedIndices } from './retention.js'
3
+ import {
4
+ estimateMessagesTokensForModel,
5
+ estimateRichContentTokens,
6
+ estimateTextTokens,
7
+ } from './token-estimate.js'
8
+
9
+ const MAX_RETAINED_IMAGES = 16
10
+ const MAX_RETAINED_IMAGE_BYTES = 8 * 1024 * 1024
11
+
12
+ type RichBlock = MessageAttachment | Exclude<ToolResultBlock, { type: 'text' }>
13
+
14
+ function isImage(block: RichBlock): boolean {
15
+ return block.type === 'stored' ? block.kind === 'image' : block.type !== 'document'
16
+ }
17
+
18
+ function label(text: string): string {
19
+ return text.replace(/\s+/g, ' ').trim().slice(0, 100)
20
+ }
21
+
22
+ export function compactedImageMarker(block: RichBlock, source: string): string {
23
+ const name = 'name' in block && block.name ? ` "${label(block.name)}"` : ''
24
+ return `[image omitted by compaction: ${label(source)}${name} (${label(block.mediaType)})]`
25
+ }
26
+
27
+ /**
28
+ * Fit images around the retained text and the summary. Keep a small recent
29
+ * set, including when a single tool call returned a batch of images.
30
+ * Replacements leave the producing call, caption and result ID in place.
31
+ */
32
+ export function fitRetainedImages(
33
+ messages: Message[],
34
+ tokenLimit: number,
35
+ model?: string,
36
+ tail?: { readonly start: number; readonly tokens: number },
37
+ ): Message[] {
38
+ const items: {
39
+ index: number
40
+ itemIndex: number
41
+ block: RichBlock
42
+ tokens: number
43
+ marker: string
44
+ tool: boolean
45
+ }[] = []
46
+ const tools = new Map<string, string>()
47
+ let newestUser = -1
48
+ for (const [index, message] of messages.entries()) {
49
+ if (message.role === 'user') newestUser = index
50
+ if (message.role === 'assistant') {
51
+ for (const call of message.toolCalls ?? []) tools.set(call.id, call.function.name)
52
+ }
53
+ const tool = message.role === 'tool'
54
+ const blocks =
55
+ message.role === 'user' ? message.attachments : tool ? message.content : undefined
56
+ if (!Array.isArray(blocks)) continue
57
+ for (const [itemIndex, block] of (
58
+ blocks as readonly (RichBlock | { type: 'text' })[]
59
+ ).entries()) {
60
+ if (block.type === 'text' || !isImage(block)) continue
61
+ if ('modelOmission' in block && block.modelOmission) continue
62
+ const source = tool ? (tools.get(message.toolCallId) ?? 'tool result') : 'user attachment'
63
+ items.push({
64
+ index,
65
+ itemIndex,
66
+ block,
67
+ tokens: estimateRichContentTokens(block, model, tool),
68
+ marker: compactedImageMarker(block, source),
69
+ tool,
70
+ })
71
+ }
72
+ }
73
+ if (items.length === 0) return messages
74
+
75
+ let promptTokens = estimateMessagesTokensForModel(messages, model)
76
+ let tailTokens = tail ? estimateMessagesTokensForModel(messages.slice(tail.start), model) : 0
77
+ let count = items.length
78
+ let bytes = items.reduce((sum, { block }) => sum + ('data' in block ? block.data.length : 0), 0)
79
+ const retained = findRetainedIndices(messages)
80
+ const omitted = new Map<number, Map<number, string>>()
81
+ // Old tool observations go first. Within the latest user turn, keep the
82
+ // newest observations regardless of which role supplied them.
83
+ const priority = (item: (typeof items)[number]) =>
84
+ item.index >= newestUser ? 2 : item.tool ? 0 : 1
85
+ for (const item of [...items].sort((a, b) => priority(a) - priority(b))) {
86
+ if (retained.has(item.index)) continue
87
+ const overTail = tail && tailTokens > tail.tokens
88
+ const overPrompt =
89
+ promptTokens > tokenLimit || count > MAX_RETAINED_IMAGES || bytes > MAX_RETAINED_IMAGE_BYTES
90
+ if (!overPrompt && !overTail) break
91
+ if (overTail && !overPrompt && item.index < tail.start) continue
92
+ let blocks = omitted.get(item.index)
93
+ if (!blocks) {
94
+ blocks = new Map()
95
+ omitted.set(item.index, blocks)
96
+ }
97
+ blocks.set(item.itemIndex, item.marker)
98
+ const saved = item.tokens - estimateTextTokens(`\n${item.marker}`)
99
+ promptTokens -= saved
100
+ if (tail && item.index >= tail.start) tailTokens -= saved
101
+ if ('data' in item.block) bytes -= item.block.data.length
102
+ count--
103
+ }
104
+ if (omitted.size === 0) return messages
105
+
106
+ return messages.map((message, index) => {
107
+ const blocks = omitted.get(index)
108
+ if (!blocks) return message
109
+ if (message.role === 'tool' && typeof message.content !== 'string') {
110
+ return {
111
+ ...message,
112
+ content: message.content.map((block, itemIndex): ToolResultBlock => {
113
+ const marker = blocks.get(itemIndex)
114
+ return marker ? { type: 'text', text: marker } : block
115
+ }),
116
+ }
117
+ }
118
+ if (message.role === 'user') {
119
+ const { attachments, ...rest } = message
120
+ const kept = attachments?.filter((_, itemIndex) => !blocks.has(itemIndex)) ?? []
121
+ const markers = attachments?.flatMap((_, itemIndex) => blocks.get(itemIndex) ?? []) ?? []
122
+ return {
123
+ ...rest,
124
+ content: [message.content, ...markers].filter(Boolean).join('\n'),
125
+ ...(kept.length > 0 ? { attachments: kept } : {}),
126
+ }
127
+ }
128
+ return message
129
+ })
130
+ }
@@ -1,4 +1,10 @@
1
+ import { Buffer } from 'node:buffer'
1
2
  import { CHARS_PER_TOKEN } from '../constants/limits.js'
3
+ import {
4
+ pngSize,
5
+ screenshotLimitsForModel,
6
+ screenshotTargetSize,
7
+ } from '../tools/builtins/computer-use-image.js'
2
8
  import type { Message, MessageAttachment, ToolResultBlock } from '../types/message/index.js'
3
9
 
4
10
  // Heuristic allowances, not provider billing formulas or upper bounds. Encoded
@@ -8,10 +14,68 @@ const IMAGE_TOKENS = 1_024
8
14
  const DOCUMENT_TOKENS = 4_096
9
15
  const OMITTED_IMAGE_TOKENS = 64
10
16
 
11
- function richTokens(block: Exclude<ToolResultBlock, { type: 'text' }> | MessageAttachment): number {
12
- if (block.type === 'stored') return block.kind === 'image' ? IMAGE_TOKENS : DOCUMENT_TOKENS
17
+ export function estimateRichContentTokens(
18
+ block: Exclude<ToolResultBlock, { type: 'text' }> | MessageAttachment,
19
+ model = '',
20
+ toolResult = false,
21
+ ): number {
22
+ const id = model.toLowerCase().split('/').at(-1) ?? ''
23
+ const limits = screenshotLimitsForModel(model)
24
+ const gemini = /^gemini-[34](?:[.-]|$)/.test(id)
25
+ const modernPatches = /^(?:gpt-6-astra|gpt-5\.[456])(?:[.-]|$)/.test(id)
26
+ const widePatches = /^gpt-5\.2(?:-|$)/.test(id)
27
+ let tileCost = 0
28
+ if (/^gpt-5(?:\.1)?(?:-20|$)/.test(id)) tileCost = 140
29
+ if (/^gpt-4o-mini(?:-|$)/.test(id)) tileCost = 5667
30
+ if (/^gpt-4(?:o|\.1)(?:-20|$)/.test(id)) tileCost = 170
31
+
32
+ let visualLimit = IMAGE_TOKENS
33
+ if (id.startsWith('claude-')) visualLimit = limits.maxTiles
34
+ if (gemini) visualLimit = 1120
35
+ if (modernPatches) visualLimit = 3000
36
+ if (widePatches) visualLimit = 7373
37
+ if (tileCost) visualLimit = Math.ceil(4.5 * tileCost)
38
+ if (block.type === 'stored') return block.kind === 'image' ? visualLimit : DOCUMENT_TOKENS
13
39
  if (block.type === 'document') return DOCUMENT_TOKENS
14
- return block.modelOmission ? OMITTED_IMAGE_TOKENS : IMAGE_TOKENS
40
+ if (block.modelOmission) return OMITTED_IMAGE_TOKENS
41
+ // Read just the PNG header. Other raster formats use the model allowance.
42
+ if (
43
+ gemini ||
44
+ block.mediaType !== 'image/png' ||
45
+ block.data.length < 32 ||
46
+ !block.data.startsWith('iVBORw0KGgo')
47
+ )
48
+ return visualLimit
49
+ const header = Buffer.from(block.data.slice(0, 32), 'base64')
50
+ if (header.length < 24 || header.toString('ascii', 12, 16) !== 'IHDR') return visualLimit
51
+ const { width, height } = pngSize(header)
52
+ if (!width || !height) return visualLimit
53
+ if (modernPatches || widePatches) {
54
+ let edge = 2048
55
+ let patchLimit = widePatches ? 6144 : 2500
56
+ // Tool observations use high detail. Recent families can use original
57
+ // resolution by default for pasted images.
58
+ if (!toolResult && /^gpt-5\.5(?:-|$)/.test(id)) {
59
+ edge = 6000
60
+ patchLimit = 10_000
61
+ }
62
+ if (!toolResult && /^(?:gpt-6-astra|gpt-5\.6)(?:-|$)/.test(id)) {
63
+ edge = 65_535
64
+ patchLimit = 30_000
65
+ }
66
+ const scale = Math.min(1, edge / Math.max(width, height))
67
+ const patches = Math.ceil((width * scale) / 32) * Math.ceil((height * scale) / 32)
68
+ return Math.ceil(1.2 * Math.min(patchLimit, patches))
69
+ }
70
+ if (tileCost) {
71
+ const scale = Math.min(1, 2048 / Math.max(width, height), 768 / Math.min(width, height))
72
+ return (
73
+ Math.floor(tileCost / 2) +
74
+ tileCost * Math.ceil((width * scale) / 512) * Math.ceil((height * scale) / 512)
75
+ )
76
+ }
77
+ const sized = screenshotTargetSize(width, height, limits)
78
+ return Math.ceil(sized.width / 28) * Math.ceil(sized.height / 28)
15
79
  }
16
80
 
17
81
  /**
@@ -19,11 +83,15 @@ function richTokens(block: Exclude<ToolResultBlock, { type: 'text' }> | MessageA
19
83
  *
20
84
  * Text and tool inputs use the existing characters-per-token approximation.
21
85
  * Images and documents have an explicit allowance independent of compression
22
- * and of whether the bytes are inline or stored externally. Without dimensions,
23
- * page counts and a provider tokenizer their exact cost is unknown. In
86
+ * and fall back to an allowance for legacy stored images and formats without
87
+ * cheaply available dimensions. Exact costs depend on the serving model. In
24
88
  * particular, serialized base64 is never treated as model-visible prose.
25
89
  */
26
90
  export function estimateMessageTokens(message: Message): number {
91
+ return estimateMessageTokensForModel(message)
92
+ }
93
+
94
+ export function estimateMessageTokensForModel(message: Message, model?: string): number {
27
95
  let chars = 0
28
96
  let rich = 0
29
97
  if (typeof message.content === 'string') chars += message.content.length
@@ -31,7 +99,7 @@ export function estimateMessageTokens(message: Message): number {
31
99
  for (const block of message.content) {
32
100
  if (block.type === 'text') chars += block.text.length
33
101
  else {
34
- rich += richTokens(block)
102
+ rich += estimateRichContentTokens(block, model, message.role === 'tool')
35
103
  if (block.type === 'document') chars += block.name?.length ?? 0
36
104
  }
37
105
  }
@@ -43,7 +111,7 @@ export function estimateMessageTokens(message: Message): number {
43
111
  }
44
112
  if (message.role === 'user') {
45
113
  for (const attachment of message.attachments ?? []) {
46
- rich += richTokens(attachment)
114
+ rich += estimateRichContentTokens(attachment, model)
47
115
  if (attachment.type === 'document' || attachment.type === 'stored') {
48
116
  chars += attachment.name?.length ?? 0
49
117
  }
@@ -58,5 +126,15 @@ export function estimateTextTokens(text: string): number {
58
126
  }
59
127
 
60
128
  export function estimateMessagesTokens(messages: readonly Message[]): number {
61
- return messages.reduce((total, message) => total + estimateMessageTokens(message), 0)
129
+ return estimateMessagesTokensForModel(messages)
130
+ }
131
+
132
+ export function estimateMessagesTokensForModel(
133
+ messages: readonly Message[],
134
+ model?: string,
135
+ ): number {
136
+ return messages.reduce(
137
+ (total, message) => total + estimateMessageTokensForModel(message, model),
138
+ 0,
139
+ )
62
140
  }
@@ -5,6 +5,7 @@ import {
5
5
  } from '../runtime/query/tool-output-budget.js'
6
6
  import { toolResultToText } from '../types/message/content.js'
7
7
  import type { Message, ToolMessage, ToolResultBlock } from '../types/message/index.js'
8
+ import { compactedImageMarker } from './retained-images.js'
8
9
  import { findRetainedIndices } from './retention.js'
9
10
  import { estimateMessageTokens } from './token-estimate.js'
10
11
 
@@ -143,6 +144,21 @@ export function clearToolResult(
143
144
  toolName: string,
144
145
  ): { readonly message: ToolMessage; readonly charsReclaimed: number } {
145
146
  const size = measureContent(tool.content)
147
+ if (
148
+ typeof tool.content !== 'string' &&
149
+ tool.content.some((block) => block.type === 'image' && !block.modelOmission)
150
+ ) {
151
+ const content = tool.content.map(
152
+ (block): ToolResultBlock =>
153
+ block.type === 'image' && !block.modelOmission
154
+ ? { type: 'text', text: compactedImageMarker(block, toolName) }
155
+ : block,
156
+ )
157
+ return {
158
+ message: { ...tool, content },
159
+ charsReclaimed: Math.max(0, size - measureContent(content)),
160
+ }
161
+ }
146
162
  const content = clearedPlaceholder(tool.content, toolName, size)
147
163
  return { message: { ...tool, content }, charsReclaimed: Math.max(0, size - content.length) }
148
164
  }
@@ -209,17 +225,13 @@ export function clearStaleToolResults(
209
225
  const toolName = toolNameByCallId.get(tool.toolCallId) ?? 'unknown'
210
226
  if (preserve.has(toolName)) return msg
211
227
 
212
- const size = measureContent(tool.content)
213
228
  if (estimateMessageTokens(tool) * CHARS_PER_TOKEN < minChars) return msg
214
229
 
215
- const content = clearedPlaceholder(tool.content, toolName, size)
216
- if (estimateMessageTokens({ ...tool, content }) >= estimateMessageTokens(tool)) return msg
230
+ const cleared = clearToolResult(tool, toolName)
231
+ if (estimateMessageTokens(cleared.message) >= estimateMessageTokens(tool)) return msg
217
232
  clearedCount++
218
- charsReclaimed += size - content.length
219
- return {
220
- ...tool,
221
- content,
222
- } satisfies ToolMessage
233
+ charsReclaimed += cleared.charsReclaimed
234
+ return cleared.message
223
235
  })
224
236
 
225
237
  return { messages: edited, clearedCount, charsReclaimed: Math.max(0, charsReclaimed) }
@@ -50,6 +50,8 @@ export type AcpMethod = (typeof ACP_METHODS)[keyof typeof ACP_METHODS]
50
50
  export const ACP_CLIENT_NOTIFICATIONS = {
51
51
  SESSION_UPDATE: 'session/update',
52
52
  TASK_UPDATE: 'namzu/tasks/update',
53
+ /** The agent takes back a request it made (an approval the person no longer needs to answer). */
54
+ CANCEL_REQUEST: '$/cancel_request',
53
55
  } as const
54
56
 
55
57
  /**
package/src/index.ts CHANGED
@@ -72,3 +72,5 @@ export type {
72
72
  MonitorEvent,
73
73
  StartJobParams,
74
74
  } from './runtime/jobs/registry.js'
75
+
76
+ export { hasGitCheckoutMarker } from './sandbox/ignore-matcher.js'
@@ -420,6 +420,10 @@ export class TurnRecorder {
420
420
  : this.#turn.costInfo
421
421
  }
422
422
 
423
+ get treeCostInfo(): CostInfo {
424
+ return this.budget?.treeCost ?? this.costInfo
425
+ }
426
+
423
427
  get currentIteration(): number {
424
428
  return this.#turn.currentIteration
425
429
  }
@@ -565,15 +569,23 @@ export class TurnRecorder {
565
569
  this.#turn.tokenUsage = accumulateTokenUsage(this.#turn.tokenUsage, counted)
566
570
  // What the provider says it charged wins over a rate card; the card is
567
571
  // the fallback for a call that reported nothing.
568
- if (hasReportedCost(usage)) {
572
+ if (usage.billingRoute === 'subscription') {
573
+ this.#turn.costInfo = {
574
+ ...this.#turn.costInfo,
575
+ includedTokens: (this.#turn.costInfo.includedTokens ?? 0) + usage.totalTokens,
576
+ }
577
+ } else if (hasReportedCost(usage)) {
569
578
  this.#turn.costInfo = accumulateReportedCost(this.#turn.costInfo, usage.reportedCostUsd)
570
- return
579
+ } else {
580
+ const pricing = this.#resolvePricing(servedBy)
581
+ const pricedUsage =
582
+ servedBy.providerId === 'anthropic' ? usage : { ...usage, inferenceGeo: undefined }
583
+ this.#turn.costInfo =
584
+ pricing === undefined
585
+ ? accumulateUnpricedCost(this.#turn.costInfo, usage)
586
+ : accumulateCost(this.#turn.costInfo, pricedUsage, pricing)
571
587
  }
572
- const pricing = this.#resolvePricing(servedBy)
573
- this.#turn.costInfo =
574
- pricing === undefined
575
- ? accumulateUnpricedCost(this.#turn.costInfo, usage)
576
- : accumulateCost(this.#turn.costInfo, usage, pricing)
588
+ this.budget?.recordCost(this.#turn.costInfo, this.#turn.tokenUsage.totalTokens)
577
589
  }
578
590
 
579
591
  /**
@@ -618,6 +630,18 @@ export class TurnRecorder {
618
630
  this.#turn.costInfo = { ...costInfo }
619
631
  this.#turn.currentIteration = currentIteration
620
632
  this.budget?.recordUsage(tokenUsage)
633
+ const recorded = this.budget?.recordedCost
634
+ if (recorded && recorded.tokens >= tokenUsage.totalTokens) {
635
+ const measured = this.tokenUsage
636
+ this.#turn.costInfo = {
637
+ ...recorded.cost,
638
+ unpricedTokens:
639
+ recorded.cost.unpricedTokens + Math.max(0, measured.totalTokens - recorded.tokens),
640
+ }
641
+ this.#turn.tokenUsage = measured
642
+ } else {
643
+ this.budget?.recordCost(costInfo, tokenUsage.totalTokens)
644
+ }
621
645
  this.#syncBudget()
622
646
  }
623
647