@zyro-sec/core 1.0.2 → 1.0.3

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 (1086) hide show
  1. package/AGENTS.md +7 -7
  2. package/README.md +3 -3
  3. package/bunfig.toml +2 -2
  4. package/drizzle.config.ts +10 -10
  5. package/package.json +8 -8
  6. package/perf/location.bench.ts +44 -44
  7. package/perf/location.ts +140 -140
  8. package/perf/session.bench.ts +22 -22
  9. package/perf/snapshot.bench.ts +67 -67
  10. package/perf/snapshot.ts +423 -423
  11. package/schema.json +2763 -2763
  12. package/script/build.ts +44 -44
  13. package/script/fix-node-pty.ts +28 -28
  14. package/script/generate-api-skill.ts +361 -361
  15. package/script/migration.ts +216 -216
  16. package/script/models-snapshot.ts +82 -82
  17. package/script/pack.ts +5 -5
  18. package/script/snapshot-parity-compare.ts +22 -22
  19. package/script/snapshot-parity-run.sh +20 -20
  20. package/script/snapshot-parity.ts +710 -710
  21. package/script/test.ts +53 -53
  22. package/script/update-models-snapshot.ts +14 -14
  23. package/script/wellknown-server.ts +112 -112
  24. package/src/account/sql.ts +36 -36
  25. package/src/agent.ts +115 -115
  26. package/src/aisdk-native.ts +397 -397
  27. package/src/aisdk.ts +1063 -1063
  28. package/src/app.ts +31 -31
  29. package/src/artifact.ts +617 -617
  30. package/src/automation/author.ts +10 -10
  31. package/src/automation/code.ts +269 -269
  32. package/src/automation/event.ts +35 -35
  33. package/src/automation/shell.ts +82 -82
  34. package/src/automation/sql.ts +50 -50
  35. package/src/automation.ts +1293 -1293
  36. package/src/blob-store.ts +115 -115
  37. package/src/bus.ts +909 -909
  38. package/src/codemode/api.ts +44 -44
  39. package/src/codemode/bun.ts +550 -550
  40. package/src/codemode/catalog.ts +177 -177
  41. package/src/codemode/diffs.ts +134 -134
  42. package/src/codemode/execution.ts +9 -9
  43. package/src/codemode/fetch.ts +179 -179
  44. package/src/codemode/instructions.ts +169 -169
  45. package/src/codemode/job.ts +144 -144
  46. package/src/codemode/path.ts +45 -45
  47. package/src/codemode/tool.ts +564 -564
  48. package/src/command.ts +109 -109
  49. package/src/config/discovery.ts +183 -183
  50. package/src/config/integration.ts +134 -134
  51. package/src/config/managed.ts +6 -6
  52. package/src/config/markdown.ts +123 -123
  53. package/src/config/normalize.ts +870 -870
  54. package/src/config/plugin/agent.ts +192 -192
  55. package/src/config/plugin/command.ts +229 -229
  56. package/src/config/plugin/compaction.ts +27 -27
  57. package/src/config/plugin/compatibility.ts +94 -94
  58. package/src/config/plugin/entry-observer.ts +79 -79
  59. package/src/config/plugin/formatter.ts +76 -76
  60. package/src/config/plugin/image.ts +29 -29
  61. package/src/config/plugin/instruction.ts +260 -260
  62. package/src/config/plugin/location-watcher.ts +22 -22
  63. package/src/config/plugin/mcp.ts +57 -57
  64. package/src/config/plugin/policy.ts +117 -117
  65. package/src/config/plugin/provider.ts +274 -274
  66. package/src/config/plugin/reference.ts +67 -67
  67. package/src/config/plugin/session-search.ts +21 -21
  68. package/src/config/plugin/shell.ts +20 -20
  69. package/src/config/plugin/skill-file.ts +62 -62
  70. package/src/config/plugin/skill-scan.ts +46 -46
  71. package/src/config/plugin/skill.ts +202 -202
  72. package/src/config/plugin/snapshot.ts +21 -21
  73. package/src/config/plugin/source.ts +194 -194
  74. package/src/config/plugin/tool-output.ts +24 -24
  75. package/src/config/plugin/websearch.ts +19 -19
  76. package/src/config/plugin/worktree.ts +35 -35
  77. package/src/config/variable.ts +84 -84
  78. package/src/config/watch.ts +73 -73
  79. package/src/config.ts +574 -574
  80. package/src/console-access.ts +22 -22
  81. package/src/credential/sql.ts +14 -14
  82. package/src/credential.ts +350 -350
  83. package/src/database/batch.ts +21 -21
  84. package/src/database/database.ts +126 -126
  85. package/src/database/drizzle/README.md +35 -35
  86. package/src/database/drizzle/effect-sqlite/driver.ts +78 -78
  87. package/src/database/drizzle/effect-sqlite/index.ts +4 -4
  88. package/src/database/drizzle/effect-sqlite/session.ts +252 -252
  89. package/src/database/drizzle/index.ts +5 -5
  90. package/src/database/drizzle/internal/drizzle-utils.ts +147 -147
  91. package/src/database/drizzle/sqlite-core/effect/count.ts +58 -58
  92. package/src/database/drizzle/sqlite-core/effect/db.ts +243 -243
  93. package/src/database/drizzle/sqlite-core/effect/delete.ts +261 -261
  94. package/src/database/drizzle/sqlite-core/effect/index.ts +10 -10
  95. package/src/database/drizzle/sqlite-core/effect/insert.ts +340 -340
  96. package/src/database/drizzle/sqlite-core/effect/query.ts +198 -198
  97. package/src/database/drizzle/sqlite-core/effect/raw.ts +49 -49
  98. package/src/database/drizzle/sqlite-core/effect/select.ts +278 -278
  99. package/src/database/drizzle/sqlite-core/effect/session.ts +421 -421
  100. package/src/database/drizzle/sqlite-core/effect/update.ts +402 -402
  101. package/src/database/drizzle.ts +1 -1
  102. package/src/database/migration/20260127222353_familiar_lady_ursula.ts +109 -109
  103. package/src/database/migration/20260211171708_add_project_commands.ts +13 -13
  104. package/src/database/migration/20260213144116_wakeful_the_professor.ts +25 -25
  105. package/src/database/migration/20260225215848_workspace.ts +21 -21
  106. package/src/database/migration/20260227213759_add_session_workspace_id.ts +14 -14
  107. package/src/database/migration/20260228203230_blue_harpoon.ts +32 -32
  108. package/src/database/migration/20260303231226_add_workspace_fields.ts +17 -17
  109. package/src/database/migration/20260309230000_move_org_to_state.ts +17 -17
  110. package/src/database/migration/20260312043431_session_message_cursor.ts +18 -18
  111. package/src/database/migration/20260323234822_events.ts +28 -28
  112. package/src/database/migration/20260410174513_workspace-name.ts +34 -34
  113. package/src/database/migration/20260413175956_chief_energizer.ts +26 -26
  114. package/src/database/migration/20260423070820_add_icon_url_override.ts +16 -16
  115. package/src/database/migration/20260427172553_slow_nightmare.ts +32 -32
  116. package/src/database/migration/20260428004200_add_session_path.ts +13 -13
  117. package/src/database/migration/20260501142318_next_venus.ts +14 -14
  118. package/src/database/migration/20260504145000_add_sync_owner.ts +13 -13
  119. package/src/database/migration/20260507164347_add_workspace_time.ts +13 -13
  120. package/src/database/migration/20260510033149_session_usage.ts +58 -58
  121. package/src/database/migration/20260511000411_data_migration_state.ts +18 -18
  122. package/src/database/migration/20260511173437_session-metadata.ts +18 -18
  123. package/src/database/migration/20260601010001_normalize_storage_paths.ts +24 -24
  124. package/src/database/migration/20260601202201_amazing_prowler.ts +13 -13
  125. package/src/database/migration/20260602002951_lowly_union_jack.ts +26 -26
  126. package/src/database/migration/20260602182828_add_project_directories.ts +22 -22
  127. package/src/database/migration/20260603001617_session_message_projection_indexes.ts +21 -21
  128. package/src/database/migration/20260603040000_session_message_projection_order.ts +21 -21
  129. package/src/database/migration/20260603141458_session_input_inbox.ts +27 -27
  130. package/src/database/migration/20260603160727_jittery_ezekiel_stane.ts +22 -22
  131. package/src/database/migration/20260604172448_event_sourced_session_input.ts +49 -49
  132. package/src/database/migration/20260605003541_add_session_context_snapshot.ts +23 -23
  133. package/src/database/migration/20260605042240_add_context_epoch_agent.ts +13 -13
  134. package/src/database/migration/20260611035744_credential.ts +27 -27
  135. package/src/database/migration/20260611192811_lush_chimera.ts +27 -27
  136. package/src/database/migration/20260612174303_project_dir_strategy.ts +31 -31
  137. package/src/database/migration/20260622142730_simplify_session_context_epoch.ts +15 -15
  138. package/src/database/migration/20260622170816_reset_v2_session_state.ts +17 -17
  139. package/src/database/migration/20260622202450_simplify_session_input.ts +19 -19
  140. package/src/database/migration/20260804233008_loose_psylocke.ts +173 -173
  141. package/src/database/migration/20260805200742_import_legacy_credentials.ts +109 -109
  142. package/src/database/migration/20260808023530_workspace_domain.ts +22 -22
  143. package/src/database/migration/20260811161259_execution_claim_attempts.ts +13 -13
  144. package/src/database/migration/20260812181746_session_inbox.ts +30 -30
  145. package/src/database/migration/20260812213948_worktree.ts +35 -35
  146. package/src/database/migration/20260819222447_session_viewed_state.ts +15 -15
  147. package/src/database/migration/20260823191254_nullable_workspace_binding.ts +27 -27
  148. package/src/database/migration/20260910120000_clear_v1_session_permission.ts +13 -13
  149. package/src/database/migration/20260923013825_project_time_active.ts +14 -14
  150. package/src/database/migration/20261007190000_azure_cli_external_credential.ts +21 -21
  151. package/src/database/migration/20261010180456_project_time_archived.ts +13 -13
  152. package/src/database/migration/20261024002554_session_allowance.ts +13 -13
  153. package/src/database/migration/20261024175301_drop_session_allowance.ts +13 -13
  154. package/src/database/migration/20261025123711_blob.ts +36 -36
  155. package/src/database/migration/20261025154125_drop_session_pending.ts +16 -16
  156. package/src/database/migration/20261026223005_schedule.ts +38 -38
  157. package/src/database/migration/20261029002625_session_part.ts +30 -30
  158. package/src/database/migration/20261029073502_session_time_busy.ts +13 -13
  159. package/src/database/migration/20261029165540_schedule_checks.ts +16 -16
  160. package/src/database/migration/20261030054400_job.ts +60 -60
  161. package/src/database/migration/20261116043204_automation.ts +83 -83
  162. package/src/database/migration/20261116181958_automation_event_position.ts +13 -13
  163. package/src/database/migration/20261116213417_automation_active_index.ts +16 -16
  164. package/src/database/migration/20261119211416_machine.ts +18 -18
  165. package/src/database/migration/20261120004954_machine-key.ts +14 -14
  166. package/src/database/migration.gen.ts +132 -132
  167. package/src/database/migration.ts +155 -155
  168. package/src/database/path.ts +98 -98
  169. package/src/database/schema.gen.ts +363 -363
  170. package/src/database/schema.sql.ts +10 -10
  171. package/src/database/sqlite.bun.ts +17 -17
  172. package/src/database/sqlite.node.ts +25 -25
  173. package/src/database/sqlite.workerd.ts +227 -227
  174. package/src/database/storage-failure.ts +58 -58
  175. package/src/database/v1-migration.bun.ts +1234 -1234
  176. package/src/database/v1-migration.noop.ts +11 -11
  177. package/src/database/v1-migration.ts +2 -2
  178. package/src/effect/app-node-builder.ts +30 -30
  179. package/src/effect/app-node-platform.ts +71 -71
  180. package/src/effect/client-tls/client-tls.bun.ts +8 -8
  181. package/src/effect/client-tls/client-tls.node.ts +17 -17
  182. package/src/effect/client-tls/client-tls.ts +12 -12
  183. package/src/effect/client-tls/client-tls.workerd.ts +8 -8
  184. package/src/effect/keyed-mutex.ts +45 -45
  185. package/src/effect/websocket-constructor.ts +81 -81
  186. package/src/environment/driver.ts +68 -68
  187. package/src/environment/environment.ts +152 -152
  188. package/src/environment/environments.ts +78 -78
  189. package/src/environment/exec-defaults.ts +200 -200
  190. package/src/environment/files.ts +79 -79
  191. package/src/environment/index.ts +34 -34
  192. package/src/environment/local.ts +101 -101
  193. package/src/environment/memory.ts +186 -186
  194. package/src/environment/path.ts +68 -68
  195. package/src/environment/unavailable.ts +17 -17
  196. package/src/event/sql.ts +26 -26
  197. package/src/event-logger.ts +19 -19
  198. package/src/file-access.ts +352 -352
  199. package/src/file-mutation.ts +185 -185
  200. package/src/file-retention.ts +23 -23
  201. package/src/file-write.ts +110 -110
  202. package/src/filesystem/fff.bun.ts +15 -15
  203. package/src/filesystem/fff.node.ts +12 -12
  204. package/src/filesystem/fff.ts +67 -67
  205. package/src/filesystem/fff.workerd.ts +12 -12
  206. package/src/filesystem/file-watch.ts +164 -164
  207. package/src/filesystem/location-watcher-policy.ts +64 -64
  208. package/src/filesystem/location-watcher.ts +108 -108
  209. package/src/filesystem/protected.ts +31 -31
  210. package/src/filesystem/search.ts +251 -251
  211. package/src/filesystem/watcher-binding.ts +14 -14
  212. package/src/filesystem/watcher.ts +282 -282
  213. package/src/filesystem.ts +270 -270
  214. package/src/flag/resolve.ts +66 -66
  215. package/src/flag.ts +64 -64
  216. package/src/form.ts +370 -370
  217. package/src/formatter/builtins.ts +294 -294
  218. package/src/formatter.ts +108 -108
  219. package/src/generate.ts +397 -397
  220. package/src/git.ts +1609 -1609
  221. package/src/github-copilot/models.ts +289 -289
  222. package/src/image/notice.ts +8 -8
  223. package/src/image/photon-normalize.ts +148 -148
  224. package/src/image/photon-wasm.bun.ts +4 -4
  225. package/src/image/photon-wasm.node.ts +4 -4
  226. package/src/image/photon-wasm.workerd.ts +4 -4
  227. package/src/image/photon-worker.ts +26 -26
  228. package/src/image/photon.ts +156 -156
  229. package/src/image.ts +95 -95
  230. package/src/instance/service.ts +21 -21
  231. package/src/instance.ts +191 -191
  232. package/src/instruction-discovery.ts +165 -165
  233. package/src/instructions/agent.ts +50 -50
  234. package/src/instructions/builtins.ts +103 -103
  235. package/src/instructions/index.ts +287 -287
  236. package/src/integration/connection.ts +26 -26
  237. package/src/integration.ts +869 -869
  238. package/src/job/list.ts +160 -160
  239. package/src/job/recovery.ts +51 -51
  240. package/src/job/sql.ts +27 -27
  241. package/src/job.ts +766 -766
  242. package/src/kv/sql.ts +9 -9
  243. package/src/kv.ts +92 -92
  244. package/src/location-activity.ts +130 -130
  245. package/src/location-lifecycle.ts +97 -97
  246. package/src/location-service-map.ts +50 -50
  247. package/src/location-services.ts +125 -125
  248. package/src/location.ts +44 -44
  249. package/src/machine/driver.ts +487 -487
  250. package/src/machine/frames.ts +133 -133
  251. package/src/machine/identity.ts +187 -187
  252. package/src/machine/index.ts +4 -4
  253. package/src/machine/instructions.ts +61 -61
  254. package/src/machine/iroh-binding.ts +18 -18
  255. package/src/machine/iroh.ts +157 -157
  256. package/src/machine/join.ts +54 -54
  257. package/src/machine/link.ts +313 -313
  258. package/src/machine/machines.ts +280 -280
  259. package/src/machine/noise.ts +326 -326
  260. package/src/machine/sql.ts +13 -13
  261. package/src/machine/wire.ts +140 -140
  262. package/src/machine/worker-client.ts +276 -276
  263. package/src/managed-policy.ts +65 -65
  264. package/src/markdown.d.ts +4 -4
  265. package/src/mcp/client.ts +1198 -1198
  266. package/src/mcp/connection.ts +292 -292
  267. package/src/mcp/event-stream.ts +34 -34
  268. package/src/mcp/index.ts +1349 -1349
  269. package/src/mcp/instructions.ts +108 -108
  270. package/src/mcp/oauth.ts +665 -665
  271. package/src/mcp/pool.ts +386 -386
  272. package/src/mcp/socket-client.ts +86 -86
  273. package/src/mcp/stdio.ts +227 -227
  274. package/src/mime.ts +75 -75
  275. package/src/modal/models.ts +150 -150
  276. package/src/model-resolver.ts +639 -639
  277. package/src/model-retry.ts +134 -134
  278. package/src/model.ts +373 -373
  279. package/src/models-dev/v1.ts +203 -203
  280. package/src/models-dev.ts +899 -899
  281. package/src/node-ffi.d.ts +18 -18
  282. package/src/oauth/page.ts +260 -260
  283. package/src/oauth/redirect.ts +42 -42
  284. package/src/pentest/mcp-catalog.ts +175 -144
  285. package/src/permission/policy.ts +240 -240
  286. package/src/permission/saved.ts +140 -140
  287. package/src/permission/sql.ts +20 -20
  288. package/src/permission.ts +419 -419
  289. package/src/persistent-pty/binary.bun.ts +85 -85
  290. package/src/persistent-pty/binary.node.ts +5 -5
  291. package/src/persistent-pty/binary.workerd.ts +5 -5
  292. package/src/persistent-pty/daemon.ts +750 -750
  293. package/src/persistent-pty/index.ts +661 -661
  294. package/src/persistent-pty/pty-binding.ts +6 -6
  295. package/src/persistent-pty.ts +1 -1
  296. package/src/plugin/agent.ts +235 -235
  297. package/src/plugin/command/automation.txt +7 -7
  298. package/src/plugin/command/initialize.txt +65 -65
  299. package/src/plugin/command/review.txt +100 -100
  300. package/src/plugin/command.ts +113 -113
  301. package/src/plugin/fork-notice.ts +30 -30
  302. package/src/plugin/goal/continuation.txt +13 -13
  303. package/src/plugin/goal/judge.txt +20 -20
  304. package/src/plugin/goal/kickoff.txt +13 -13
  305. package/src/plugin/goal/reminder.txt +9 -9
  306. package/src/plugin/goal.ts +501 -501
  307. package/src/plugin/home-memory.ts +155 -155
  308. package/src/plugin/hooks.ts +108 -108
  309. package/src/plugin/host.ts +770 -770
  310. package/src/plugin/identity.ts +31 -31
  311. package/src/plugin/instance.ts +45 -45
  312. package/src/plugin/internal.ts +360 -360
  313. package/src/plugin/mcp-codemode-defaults.ts +41 -41
  314. package/src/plugin/mcp-skill.ts +171 -171
  315. package/src/plugin/models-dev.ts +128 -128
  316. package/src/plugin/module.ts +186 -186
  317. package/src/plugin/optimize.ts +97 -97
  318. package/src/plugin/plan.ts +52 -52
  319. package/src/plugin/promise.ts +3 -3
  320. package/src/plugin/provider/amazon-bedrock.ts +121 -121
  321. package/src/plugin/provider/azure.ts +568 -568
  322. package/src/plugin/provider/cerebras.ts +16 -16
  323. package/src/plugin/provider/chatgpt.ts +594 -594
  324. package/src/plugin/provider/claude-agent/aisdk.ts +36 -36
  325. package/src/plugin/provider/claude-agent/claude/accounts.ts +104 -104
  326. package/src/plugin/provider/claude-agent/claude/agent-sdk.ts +1 -1
  327. package/src/plugin/provider/claude-agent/claude/agent-sdk.workerd.ts +4 -4
  328. package/src/plugin/provider/claude-agent/claude/claude-folder-worker.ts +10 -10
  329. package/src/plugin/provider/claude-agent/claude/fork.ts +34 -34
  330. package/src/plugin/provider/claude-agent/claude/io.ts +88 -88
  331. package/src/plugin/provider/claude-agent/claude/probe.ts +124 -124
  332. package/src/plugin/provider/claude-agent/claude/query-options.ts +143 -143
  333. package/src/plugin/provider/claude-agent/claude/sdk.ts +17 -17
  334. package/src/plugin/provider/claude-agent/claude/session.ts +162 -162
  335. package/src/plugin/provider/claude-agent/claude/sessions.ts +508 -508
  336. package/src/plugin/provider/claude-agent/claude/status.ts +66 -66
  337. package/src/plugin/provider/claude-agent/claude/websearch.ts +96 -96
  338. package/src/plugin/provider/claude-agent/index.ts +63 -63
  339. package/src/plugin/provider/claude-agent/instructions.ts +54 -54
  340. package/src/plugin/provider/claude-agent/integration.ts +62 -62
  341. package/src/plugin/provider/claude-agent/language-model/claude-agent-error.ts +49 -49
  342. package/src/plugin/provider/claude-agent/language-model/claude-agent-language-model.ts +112 -112
  343. package/src/plugin/provider/claude-agent/language-model/convert-claude-stream.ts +139 -139
  344. package/src/plugin/provider/claude-agent/language-model/convert-to-claude-message.ts +55 -55
  345. package/src/plugin/provider/claude-agent/language-model/request-kind.ts +5 -5
  346. package/src/plugin/provider/claude-agent/language-model/system-prompt.ts +28 -28
  347. package/src/plugin/provider/claude-agent/language-model/usage.ts +58 -58
  348. package/src/plugin/provider/claude-agent/provider.ts +178 -178
  349. package/src/plugin/provider/claude-agent/session.ts +61 -61
  350. package/src/plugin/provider/claude-agent/sync/catch-up.ts +21 -21
  351. package/src/plugin/provider/claude-agent/sync/checkpoints.ts +41 -41
  352. package/src/plugin/provider/claude-agent/sync/decide.ts +58 -58
  353. package/src/plugin/provider/claude-agent/sync/fingerprint.ts +117 -117
  354. package/src/plugin/provider/claude-agent/sync/record.ts +42 -42
  355. package/src/plugin/provider/claude-agent/tools/hooks.ts +23 -23
  356. package/src/plugin/provider/claude-agent/tools/names.ts +30 -30
  357. package/src/plugin/provider/claude-agent/tools/pending.ts +72 -72
  358. package/src/plugin/provider/claude-agent/tools/result.ts +110 -110
  359. package/src/plugin/provider/claude-agent/tools/server.ts +34 -34
  360. package/src/plugin/provider/claude-agent/websearch.ts +57 -57
  361. package/src/plugin/provider/cloudflare-ai-gateway.ts +68 -68
  362. package/src/plugin/provider/cloudflare-workers-ai.ts +70 -70
  363. package/src/plugin/provider/configured.ts +18 -18
  364. package/src/plugin/provider/credential-settings.ts +77 -77
  365. package/src/plugin/provider/databricks.ts +31 -31
  366. package/src/plugin/provider/digitalocean.ts +197 -197
  367. package/src/plugin/provider/dynamic.ts +19 -19
  368. package/src/plugin/provider/github-copilot.ts +646 -646
  369. package/src/plugin/provider/gitlab.ts +496 -496
  370. package/src/plugin/provider/google-vertex.ts +231 -231
  371. package/src/plugin/provider/kilo.ts +17 -17
  372. package/src/plugin/provider/llmgateway.ts +27 -27
  373. package/src/plugin/provider/lmstudio.ts +52 -52
  374. package/src/plugin/provider/local.ts +240 -240
  375. package/src/plugin/provider/modal.ts +72 -72
  376. package/src/plugin/provider/neon.ts +12 -12
  377. package/src/plugin/provider/nvidia.ts +22 -22
  378. package/src/plugin/provider/ollama.ts +92 -92
  379. package/src/plugin/provider/openai-context-caps.ts +52 -52
  380. package/src/plugin/provider/openai-subscription-models.ts +59 -59
  381. package/src/plugin/provider/openai.ts +447 -447
  382. package/src/plugin/provider/opencode-artifacts.ts +216 -216
  383. package/src/plugin/provider/opencode-watches.ts +753 -753
  384. package/src/plugin/provider/opencode.ts +883 -883
  385. package/src/plugin/provider/openrouter.ts +30 -30
  386. package/src/plugin/provider/poe.ts +176 -176
  387. package/src/plugin/provider/prompt-cache-key.ts +37 -37
  388. package/src/plugin/provider/refresh.ts +80 -80
  389. package/src/plugin/provider/sap-ai-core.ts +39 -39
  390. package/src/plugin/provider/sdk-factory.ts +24 -24
  391. package/src/plugin/provider/snowflake-cortex.ts +266 -266
  392. package/src/plugin/provider/vllm.ts +34 -34
  393. package/src/plugin/provider/xai.ts +236 -236
  394. package/src/plugin/provider/zenmux.ts +21 -21
  395. package/src/plugin/provider.ts +64 -64
  396. package/src/plugin/sdk.ts +44 -44
  397. package/src/plugin/service.ts +42 -42
  398. package/src/plugin/skill/opencode/api/agent.md +18 -18
  399. package/src/plugin/skill/opencode/api/automation.md +63 -63
  400. package/src/plugin/skill/opencode/api/blob.md +10 -10
  401. package/src/plugin/skill/opencode/api/command.md +12 -12
  402. package/src/plugin/skill/opencode/api/form.md +22 -22
  403. package/src/plugin/skill/opencode/api/generate.md +96 -96
  404. package/src/plugin/skill/opencode/api/info.md +11 -11
  405. package/src/plugin/skill/opencode/api/location.md +17 -17
  406. package/src/plugin/skill/opencode/api/model.md +22 -22
  407. package/src/plugin/skill/opencode/api/permission.md +13 -13
  408. package/src/plugin/skill/opencode/api/project.md +29 -29
  409. package/src/plugin/skill/opencode/api/provider.md +18 -18
  410. package/src/plugin/skill/opencode/api/session.md +313 -313
  411. package/src/plugin/skill/opencode/api/skill.md +12 -12
  412. package/src/plugin/skill/opencode/api/vcs.md +60 -60
  413. package/src/plugin/skill/opencode/api/worktree.md +49 -49
  414. package/src/plugin/skill/opencode/api.md +119 -119
  415. package/src/plugin/skill/opencode/api.ts +40 -40
  416. package/src/plugin/skill/opencode-api.md +17 -17
  417. package/src/plugin/skill/opencode.md +154 -154
  418. package/src/plugin/skill/report.md +152 -152
  419. package/src/plugin/skill.ts +111 -111
  420. package/src/plugin/source-directory.ts +33 -33
  421. package/src/plugin/supervisor.ts +288 -288
  422. package/src/plugin/system-prompt/AGENTS.md +5 -5
  423. package/src/plugin/system-prompt/anthropic.txt +2 -2
  424. package/src/plugin/system-prompt/gpt-6.2.txt +71 -71
  425. package/src/plugin/system-prompt/gpt-astra.txt +46 -46
  426. package/src/plugin/system-prompt/gpt.txt +40 -40
  427. package/src/plugin/system-prompt/kimi.txt +96 -96
  428. package/src/plugin/system-prompt/meta.txt +56 -56
  429. package/src/plugin/system-prompt/trinity.txt +98 -98
  430. package/src/plugin/tool-input-repair.ts +232 -232
  431. package/src/plugin/update.ts +87 -87
  432. package/src/plugin/vcs/git.ts +802 -802
  433. package/src/plugin/vcs/hg.ts +234 -234
  434. package/src/plugin/verbosity.ts +58 -58
  435. package/src/plugin/warming.ts +224 -224
  436. package/src/plugin/websearch/exa.ts +69 -69
  437. package/src/plugin/websearch/firecrawl.ts +71 -71
  438. package/src/plugin/websearch/index.ts +13 -13
  439. package/src/plugin/websearch/mcp.ts +69 -69
  440. package/src/plugin/websearch/parallel.ts +90 -90
  441. package/src/plugin/websearch/provider.ts +44 -44
  442. package/src/plugin/websearch/tavily.ts +73 -73
  443. package/src/plugin/websearch/tinyfish.ts +131 -131
  444. package/src/plugin.ts +320 -320
  445. package/src/project/icon.ts +167 -167
  446. package/src/project/schema.ts +25 -25
  447. package/src/project/sql.ts +63 -63
  448. package/src/project.ts +536 -536
  449. package/src/provider.ts +553 -553
  450. package/src/pty/protocol.ts +37 -37
  451. package/src/pty/pty.bun.ts +44 -44
  452. package/src/pty/pty.node.ts +34 -34
  453. package/src/pty/pty.ts +25 -25
  454. package/src/pty/pty.workerd.ts +9 -9
  455. package/src/pty/ticket.ts +74 -74
  456. package/src/pty.ts +311 -311
  457. package/src/push/crypto.ts +39 -39
  458. package/src/push/list.ts +380 -380
  459. package/src/push/sender.ts +185 -185
  460. package/src/push/watcher.ts +169 -169
  461. package/src/reference/instructions.ts +82 -82
  462. package/src/reference.ts +129 -129
  463. package/src/repository-cache.ts +251 -251
  464. package/src/repository.ts +205 -205
  465. package/src/ripgrep/binary.ts +166 -166
  466. package/src/ripgrep.ts +311 -311
  467. package/src/rpc.ts +288 -288
  468. package/src/schema.ts +39 -39
  469. package/src/session/affinity.ts +8 -8
  470. package/src/session/background-result.ts +5 -5
  471. package/src/session/background.ts +125 -125
  472. package/src/session/blob.ts +503 -503
  473. package/src/session/command.ts +38 -38
  474. package/src/session/compaction-background.ts +55 -55
  475. package/src/session/compaction-subagents.ts +103 -103
  476. package/src/session/compaction.ts +1320 -1320
  477. package/src/session/context.ts +296 -296
  478. package/src/session/cwd-instructions.ts +147 -147
  479. package/src/session/cwd-store.ts +66 -66
  480. package/src/session/cwd.ts +75 -75
  481. package/src/session/diff.ts +149 -149
  482. package/src/session/environment.ts +33 -33
  483. package/src/session/error.ts +105 -105
  484. package/src/session/event.ts +2 -2
  485. package/src/session/execution/restart.ts +558 -558
  486. package/src/session/execution/subagent-report.ts +203 -203
  487. package/src/session/execution.ts +241 -241
  488. package/src/session/generate.ts +78 -78
  489. package/src/session/history.ts +405 -405
  490. package/src/session/inbox.ts +625 -625
  491. package/src/session/info.ts +62 -62
  492. package/src/session/instruction-entry.ts +171 -171
  493. package/src/session/instruction-state.ts +277 -277
  494. package/src/session/instructions.ts +126 -126
  495. package/src/session/message-updater.ts +497 -497
  496. package/src/session/message.ts +2 -2
  497. package/src/session/model-request.ts +474 -474
  498. package/src/session/model-transport.ts +571 -571
  499. package/src/session/move.ts +199 -199
  500. package/src/session/projector.ts +1197 -1197
  501. package/src/session/prompt.ts +253 -253
  502. package/src/session/recent-text.ts +93 -93
  503. package/src/session/revert.ts +112 -112
  504. package/src/session/run-coordinator.ts +198 -198
  505. package/src/session/runner/index.ts +46 -46
  506. package/src/session/runner/live-tool-metadata.ts +41 -41
  507. package/src/session/runner/llm.ts +481 -481
  508. package/src/session/runner/max-steps.ts +16 -16
  509. package/src/session/runner/model.ts +138 -138
  510. package/src/session/runner/prompt/system.txt +16 -16
  511. package/src/session/runner/publish-llm-event.ts +642 -642
  512. package/src/session/runner/retry.ts +78 -78
  513. package/src/session/runner/step.ts +401 -401
  514. package/src/session/runner/to-llm-message.ts +341 -341
  515. package/src/session/schema.ts +9 -9
  516. package/src/session/search-build.ts +116 -116
  517. package/src/session/search-index.ts +552 -552
  518. package/src/session/search.ts +672 -672
  519. package/src/session/session.ts +407 -407
  520. package/src/session/shell.ts +35 -35
  521. package/src/session/skill.ts +16 -16
  522. package/src/session/sql.ts +215 -215
  523. package/src/session/stats.ts +463 -463
  524. package/src/session/store.ts +323 -323
  525. package/src/session/stored.ts +44 -44
  526. package/src/session/subagent-completion.ts +95 -95
  527. package/src/session/subagent-depth.ts +21 -21
  528. package/src/session/subagent-job.ts +61 -61
  529. package/src/session/synthetic.ts +49 -49
  530. package/src/session/system-prompt.ts +28 -28
  531. package/src/session/title.ts +174 -174
  532. package/src/session/to-session-error.ts +179 -179
  533. package/src/session/transfer.ts +369 -369
  534. package/src/session/usage.ts +64 -64
  535. package/src/session.ts +602 -602
  536. package/src/shared-cache.ts +103 -103
  537. package/src/shell/parse.ts +645 -645
  538. package/src/shell/permissions.ts +60 -60
  539. package/src/shell/result.ts +115 -115
  540. package/src/shell/scan.ts +2585 -2585
  541. package/src/shell/select.ts +241 -241
  542. package/src/shell.ts +1274 -1274
  543. package/src/skill/discovery.ts +205 -205
  544. package/src/skill/instructions.ts +84 -84
  545. package/src/skill.ts +277 -277
  546. package/src/snapshot.ts +248 -248
  547. package/src/state.ts +271 -271
  548. package/src/tool/AGENTS.md +71 -71
  549. package/src/tool/html-markdown.ts +651 -651
  550. package/src/tool/http-body.ts +30 -30
  551. package/src/tool/mcp.ts +177 -177
  552. package/src/tool/model-policy.ts +38 -38
  553. package/src/tool/patch-grammar.txt +19 -19
  554. package/src/tool/patch.txt +33 -33
  555. package/src/tool/plugin/artifact.ts +171 -171
  556. package/src/tool/plugin/automation.ts +246 -246
  557. package/src/tool/plugin/cd.ts +103 -103
  558. package/src/tool/plugin/edit.ts +371 -371
  559. package/src/tool/plugin/file-diff.ts +42 -42
  560. package/src/tool/plugin/glob.ts +123 -123
  561. package/src/tool/plugin/grep.ts +152 -152
  562. package/src/tool/plugin/image-generate.ts +396 -396
  563. package/src/tool/plugin/machine.ts +36 -36
  564. package/src/tool/plugin/mcp-events.ts +72 -72
  565. package/src/tool/plugin/mcp-resource.ts +100 -100
  566. package/src/tool/plugin/opencode.ts +316 -316
  567. package/src/tool/plugin/patch.ts +358 -358
  568. package/src/tool/plugin/question.ts +130 -130
  569. package/src/tool/plugin/read.ts +413 -413
  570. package/src/tool/plugin/session-interrupt.ts +63 -63
  571. package/src/tool/plugin/session-search.ts +99 -99
  572. package/src/tool/plugin/shell.ts +594 -594
  573. package/src/tool/plugin/skill.ts +74 -74
  574. package/src/tool/plugin/subagent.ts +269 -269
  575. package/src/tool/plugin/todo.ts +83 -83
  576. package/src/tool/plugin/video-generate.ts +403 -403
  577. package/src/tool/plugin/webfetch.ts +214 -214
  578. package/src/tool/plugin/websearch.ts +196 -196
  579. package/src/tool/plugin/write.ts +72 -72
  580. package/src/tool/read-filesystem.ts +350 -350
  581. package/src/tool/runtime.ts +311 -311
  582. package/src/tool/search.ts +34 -34
  583. package/src/tool/todowrite.txt +7 -7
  584. package/src/tool-output.ts +220 -220
  585. package/src/tool.ts +579 -579
  586. package/src/usage-limits.ts +192 -192
  587. package/src/util/canonical-json.ts +11 -11
  588. package/src/util/error-summary.ts +33 -33
  589. package/src/util/git-executable.ts +59 -59
  590. package/src/util/lazy.ts +11 -11
  591. package/src/util/slug.ts +74 -74
  592. package/src/util/token.ts +5 -5
  593. package/src/util/which.ts +37 -37
  594. package/src/util/wildcard.ts +15 -15
  595. package/src/v1/config/agent.ts +69 -69
  596. package/src/v1/config/command.ts +13 -13
  597. package/src/v1/config/mcp.ts +69 -69
  598. package/src/v1/config/migrate.ts +269 -269
  599. package/src/v1/config/permission.ts +42 -42
  600. package/src/v1/config/plugin.ts +9 -9
  601. package/src/v1/config/provider-options.ts +59 -59
  602. package/src/v1/config/provider.ts +113 -113
  603. package/src/variant.ts +699 -699
  604. package/src/vcs/patch.ts +106 -106
  605. package/src/vcs.ts +262 -262
  606. package/src/video-generation.ts +344 -344
  607. package/src/voice.ts +194 -194
  608. package/src/websearch.ts +239 -239
  609. package/src/wellknown/plugin.ts +36 -36
  610. package/src/wellknown.ts +230 -230
  611. package/src/workspace/driver.ts +89 -89
  612. package/src/workspace/sql.ts +11 -11
  613. package/src/workspace.ts +566 -566
  614. package/src/worktree/directory.ts +16 -16
  615. package/src/worktree/git.ts +39 -39
  616. package/src/worktree/sql.ts +21 -21
  617. package/src/worktree/strategies.ts +74 -74
  618. package/src/worktree.ts +357 -357
  619. package/test/config/fixture/skills/first-source/first/SKILL.md +6 -6
  620. package/test/config/fixture/skills/second-source/second/SKILL.md +6 -6
  621. package/test/fixture/app-execution-alias.ts +17 -17
  622. package/test/fixture/codemode.ts +63 -63
  623. package/test/fixture/config-nodes.ts +40 -40
  624. package/test/fixture/durable-object-storage.ts +58 -58
  625. package/test/fixture/effect-flock-worker.ts +60 -60
  626. package/test/fixture/env.ts +22 -22
  627. package/test/fixture/environment.ts +52 -52
  628. package/test/fixture/event-server.ts +65 -65
  629. package/test/fixture/flock-worker.ts +72 -72
  630. package/test/fixture/git.ts +86 -86
  631. package/test/fixture/global.ts +26 -26
  632. package/test/fixture/held-stdio.cjs +36 -36
  633. package/test/fixture/html-markdown.ts +7 -7
  634. package/test/fixture/link-v1-transcript.json +27 -27
  635. package/test/fixture/location.ts +27 -27
  636. package/test/fixture/lock-worker.ts +53 -53
  637. package/test/fixture/machine-v2.json +66 -66
  638. package/test/fixture/machine-worker.ts +284 -284
  639. package/test/fixture/mcp-echo.ts +14 -14
  640. package/test/fixture/mcp-legacy-silent.ts +22 -22
  641. package/test/fixture/mcp-modern-stdio.ts +15 -15
  642. package/test/fixture/mcp-output-schema.ts +63 -63
  643. package/test/fixture/mcp-prompts.ts +29 -29
  644. package/test/fixture/mcp-timeout.ts +32 -32
  645. package/test/fixture/mcp-union-output-schema.ts +41 -41
  646. package/test/fixture/mcp.ts +44 -44
  647. package/test/fixture/models.ts +6 -6
  648. package/test/fixture/native/2.0.14-media.json +22 -22
  649. package/test/fixture/noise-xx-vectors.json +75 -75
  650. package/test/fixture/persistent-pty-daemon.ts +347 -347
  651. package/test/fixture/persistent-pty.ts +9 -9
  652. package/test/fixture/photon-crash-worker.ts +10 -10
  653. package/test/fixture/photon-exit.ts +29 -29
  654. package/test/fixture/photon-hang-worker.ts +2 -2
  655. package/test/fixture/policy.ts +98 -98
  656. package/test/fixture/prompt-location.ts +33 -33
  657. package/test/fixture/pty-windows.ts +69 -69
  658. package/test/fixture/selector.ts +12 -12
  659. package/test/fixture/shell-daemon.ts +122 -122
  660. package/test/fixture/spawn.ts +24 -24
  661. package/test/fixture/sqlite-node-client.ts +100 -100
  662. package/test/fixture/target-environment.ts +58 -58
  663. package/test/fixture/tmpdir.ts +44 -44
  664. package/test/fixture/v1-config/attachment.ts +25 -25
  665. package/test/fixture/v1-config/config.ts +182 -182
  666. package/test/fixture/v1-config/formatter.ts +13 -13
  667. package/test/fixture/v1-config/layout.ts +6 -6
  668. package/test/fixture/v1-config/lsp.ts +80 -80
  669. package/test/fixture/v1-config/server.ts +19 -19
  670. package/test/fixture/v1-config/skills.ts +13 -13
  671. package/test/fixtures/recordings/session-runner/openai-chat-streams-text.json +27 -27
  672. package/test/lib/clock.ts +43 -43
  673. package/test/lib/effect.ts +80 -80
  674. package/test/lib/environment-conformance.ts +204 -204
  675. package/test/lib/eventually.ts +20 -20
  676. package/test/lib/image.ts +7 -7
  677. package/test/lib/instructions.ts +47 -47
  678. package/test/lib/permission.ts +12 -12
  679. package/test/lib/project.ts +26 -26
  680. package/test/lib/session-message.ts +26 -26
  681. package/test/lib/tool.ts +102 -102
  682. package/test/lib/websearch.ts +63 -63
  683. package/test/lib/websocket-server.ts +73 -73
  684. package/test/plugin/fixture.ts +174 -174
  685. package/test/plugin/fixtures/greeting.ts +14 -14
  686. package/test/plugin/fixtures/models-dev-reasoning.json +811 -811
  687. package/test/plugin/fixtures/models-dev.json +92 -92
  688. package/test/plugin/fixtures/provider-factory.ts +9 -9
  689. package/test/plugin/host.ts +540 -540
  690. package/test/plugin/provider/claude-agent/fixtures/marker.pdf +68 -68
  691. package/test/plugin/provider/claude-agent/fixtures/recordings/api-error.jsonl +16 -16
  692. package/test/plugin/provider/claude-agent/fixtures/recordings/controls.jsonl +107 -107
  693. package/test/plugin/provider/claude-agent/fixtures/recordings/max-steps.jsonl +133 -133
  694. package/test/plugin/provider/claude-agent/fixtures/recordings/startup-logged-out.jsonl +4 -4
  695. package/test/plugin/provider/claude-agent/fixtures/recordings/startup.jsonl +52 -52
  696. package/test/plugin/provider/claude-agent/fixtures/recordings/sync.jsonl +73 -73
  697. package/test/plugin/provider/claude-agent/fixtures/recordings/text-cancel.jsonl +37 -37
  698. package/test/plugin/provider/claude-agent/fixtures/recordings/text-resume.jsonl +21 -21
  699. package/test/plugin/provider/claude-agent/fixtures/recordings/text.jsonl +35 -35
  700. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-abort.jsonl +62 -62
  701. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-cancel.jsonl +63 -63
  702. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-continue.jsonl +58 -58
  703. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-media.jsonl +80 -80
  704. package/test/plugin/provider/claude-agent/fixtures/recordings/tools-waiting-cancel.jsonl +58 -58
  705. package/test/plugin/provider/claude-agent/fixtures/recordings/tools.jsonl +74 -74
  706. package/test/plugin/provider/claude-agent/fixtures/recordings/utility.jsonl +28 -28
  707. package/test/plugin/provider/claude-agent/fixtures/recordings/websearch.jsonl +13 -13
  708. package/test/plugin/provider/claude-agent/lib/fake-claude.ts +411 -411
  709. package/test/plugin/provider/claude-agent/lib/fake-io.ts +20 -20
  710. package/test/plugin/provider/claude-agent/lib/recorder.ts +61 -61
  711. package/test/plugin/provider/claude-agent/lib/sessions.ts +126 -126
  712. package/test/plugin/provider/claude-agent/lib/tools.ts +95 -95
  713. package/test/plugin/websearch-fixture.ts +63 -63
  714. package/test/preload.ts +2 -2
  715. package/test/session-sql.types.ts +25 -25
  716. package/tsconfig.build.json +11 -11
  717. package/tsconfig.json +18 -18
  718. package/tsconfig.tests.json +13 -13
  719. package/test/agent.test.ts +0 -224
  720. package/test/aisdk-native.test.ts +0 -590
  721. package/test/aisdk.test.ts +0 -1259
  722. package/test/app.test.ts +0 -6
  723. package/test/artifact.test.ts +0 -216
  724. package/test/automation-event.test.ts +0 -688
  725. package/test/automation-shell.test.ts +0 -293
  726. package/test/automation.test.ts +0 -1950
  727. package/test/blob-store.test.ts +0 -37
  728. package/test/boot-work.test.ts +0 -215
  729. package/test/browser-attach.test.ts +0 -150
  730. package/test/browser-idle.test.ts +0 -107
  731. package/test/bus-session-routing.test.ts +0 -334
  732. package/test/bus-unpersisted.test.ts +0 -50
  733. package/test/bus.test.ts +0 -1347
  734. package/test/catalog.test.ts +0 -704
  735. package/test/codemode/catalog.test.ts +0 -339
  736. package/test/codemode/diffs.test.ts +0 -90
  737. package/test/codemode/instructions.test.ts +0 -123
  738. package/test/codemode-execute-options.test.ts +0 -172
  739. package/test/codemode-script-diffs.test.ts +0 -131
  740. package/test/codemode.test.ts +0 -132
  741. package/test/command.test.ts +0 -71
  742. package/test/config/agent.test.ts +0 -847
  743. package/test/config/command-subagent.test.ts +0 -165
  744. package/test/config/command.test.ts +0 -628
  745. package/test/config/compaction.test.ts +0 -184
  746. package/test/config/config.test.ts +0 -2113
  747. package/test/config/discovery.test.ts +0 -150
  748. package/test/config/entry-observer.test.ts +0 -51
  749. package/test/config/image.test.ts +0 -78
  750. package/test/config/markdown.test.ts +0 -129
  751. package/test/config/model.test.ts +0 -28
  752. package/test/config/normalization.test.ts +0 -854
  753. package/test/config/overlay.test.ts +0 -205
  754. package/test/config/policy.test.ts +0 -432
  755. package/test/config/provider-options.test.ts +0 -55
  756. package/test/config/provider.test.ts +0 -1338
  757. package/test/config/reload.test.ts +0 -526
  758. package/test/config/session-search.test.ts +0 -61
  759. package/test/config/shell.test.ts +0 -42
  760. package/test/config/skill.test.ts +0 -602
  761. package/test/config/snapshot.test.ts +0 -61
  762. package/test/config/tool-output.test.ts +0 -59
  763. package/test/config/watch.test.ts +0 -53
  764. package/test/config/websearch.test.ts +0 -45
  765. package/test/credential-refresh.test.ts +0 -113
  766. package/test/credential.test.ts +0 -271
  767. package/test/database-drizzle.test.ts +0 -228
  768. package/test/database-migration.test.ts +0 -783
  769. package/test/database.test.ts +0 -39
  770. package/test/effect/cross-spawn-spawner.test.ts +0 -522
  771. package/test/effect/keyed-mutex.test.ts +0 -73
  772. package/test/effect/layer-node/layer-node-types.test.ts +0 -230
  773. package/test/effect/layer-node/layer-node.test.ts +0 -467
  774. package/test/effect/layer-node/node-build.test.ts +0 -148
  775. package/test/effect/observability.test.ts +0 -141
  776. package/test/effect-app-node-platform.test.ts +0 -86
  777. package/test/effect-simplification-types.test.ts +0 -12
  778. package/test/environment.test.ts +0 -154
  779. package/test/environments.test.ts +0 -406
  780. package/test/event-logger.test.ts +0 -50
  781. package/test/file-access-path.test.ts +0 -336
  782. package/test/file-access.test.ts +0 -178
  783. package/test/file-mutation.test.ts +0 -244
  784. package/test/filesystem/file-watch.test.ts +0 -213
  785. package/test/filesystem/filesystem.test.ts +0 -383
  786. package/test/filesystem/location-watcher-policy.test.ts +0 -70
  787. package/test/filesystem/search.test.ts +0 -385
  788. package/test/filesystem/watcher.test.ts +0 -719
  789. package/test/flag.test.ts +0 -203
  790. package/test/form.test.ts +0 -357
  791. package/test/formatter-target-environment.test.ts +0 -138
  792. package/test/formatter.test.ts +0 -350
  793. package/test/generate.test.ts +0 -752
  794. package/test/git.test.ts +0 -666
  795. package/test/github-copilot/models.test.ts +0 -167
  796. package/test/image-photon.test.ts +0 -177
  797. package/test/instance-vanilla.test.ts +0 -124
  798. package/test/instruction-discovery.test.ts +0 -804
  799. package/test/instruction-state.test.ts +0 -537
  800. package/test/instructions/builtins.test.ts +0 -83
  801. package/test/instructions/index.test.ts +0 -248
  802. package/test/integration-refresh.test.ts +0 -118
  803. package/test/integration.test.ts +0 -716
  804. package/test/job.test.ts +0 -968
  805. package/test/kv.test.ts +0 -81
  806. package/test/location-activity.test.ts +0 -315
  807. package/test/location-filesystem.test.ts +0 -332
  808. package/test/location-layer.test.ts +0 -784
  809. package/test/location-missing-project.test.ts +0 -71
  810. package/test/location-retain.test.ts +0 -98
  811. package/test/location.test.ts +0 -46
  812. package/test/logging.test.ts +0 -14
  813. package/test/machine-frames.test.ts +0 -768
  814. package/test/machine-instructions.test.ts +0 -135
  815. package/test/machine-join.test.ts +0 -223
  816. package/test/machine-link.test.ts +0 -527
  817. package/test/machine-noise.test.ts +0 -429
  818. package/test/machine-path.test.ts +0 -1202
  819. package/test/machine.test.ts +0 -786
  820. package/test/machines.test.ts +0 -730
  821. package/test/mcp-attach.test.ts +0 -403
  822. package/test/mcp-events.test.ts +0 -299
  823. package/test/mcp-import-boundary.test.ts +0 -44
  824. package/test/mcp-instructions.test.ts +0 -221
  825. package/test/mcp-oauth.test.ts +0 -1289
  826. package/test/mcp-skills.test.ts +0 -274
  827. package/test/mcp-socket-client.test.ts +0 -210
  828. package/test/mcp-stdio.test.ts +0 -145
  829. package/test/mcp.test.ts +0 -4196
  830. package/test/mime.test.ts +0 -80
  831. package/test/modal/models.test.ts +0 -137
  832. package/test/model-free.test.ts +0 -120
  833. package/test/model-plugins.test.ts +0 -469
  834. package/test/model-resolver.test.ts +0 -1695
  835. package/test/model.test.ts +0 -16
  836. package/test/models.test.ts +0 -1404
  837. package/test/network-guard.test.ts +0 -56
  838. package/test/npm-config.test.ts +0 -42
  839. package/test/npm.test.ts +0 -545
  840. package/test/oauth-page.test.ts +0 -15
  841. package/test/opencode-api-skill.test.ts +0 -16
  842. package/test/patch.test.ts +0 -509
  843. package/test/permission.test.ts +0 -1179
  844. package/test/persistent-pty-daemon.test.ts +0 -337
  845. package/test/persistent-pty-session.test.ts +0 -295
  846. package/test/plugin/automation.test.ts +0 -124
  847. package/test/plugin/command.test.ts +0 -137
  848. package/test/plugin/goal-watchdog.test.ts +0 -212
  849. package/test/plugin/goal.test.ts +0 -609
  850. package/test/plugin/home-memory.test.ts +0 -131
  851. package/test/plugin/host-model.test.ts +0 -34
  852. package/test/plugin/identity.test.ts +0 -60
  853. package/test/plugin/internal-flag.test.ts +0 -101
  854. package/test/plugin/mcp-codemode-defaults.test.ts +0 -124
  855. package/test/plugin/models-dev.test.ts +0 -1406
  856. package/test/plugin/module.test.ts +0 -494
  857. package/test/plugin/optimize.test.ts +0 -343
  858. package/test/plugin/permission-assert.test.ts +0 -94
  859. package/test/plugin/plan.test.ts +0 -162
  860. package/test/plugin/promise-tool-cancel.test.ts +0 -279
  861. package/test/plugin/promise-tool.test.ts +0 -227
  862. package/test/plugin/provider/claude-agent/claude/accounts.test.ts +0 -326
  863. package/test/plugin/provider/claude-agent/claude/branches.test.ts +0 -300
  864. package/test/plugin/provider/claude-agent/claude/probe.test.ts +0 -99
  865. package/test/plugin/provider/claude-agent/claude/recorder.test.ts +0 -19
  866. package/test/plugin/provider/claude-agent/claude/session.test.ts +0 -30
  867. package/test/plugin/provider/claude-agent/claude/sessions.test.ts +0 -490
  868. package/test/plugin/provider/claude-agent/claude/status.test.ts +0 -67
  869. package/test/plugin/provider/claude-agent/claude/sync.test.ts +0 -70
  870. package/test/plugin/provider/claude-agent/claude/tools.test.ts +0 -382
  871. package/test/plugin/provider/claude-agent/language-model/convert.test.ts +0 -95
  872. package/test/plugin/provider/claude-agent/language-model/error.test.ts +0 -94
  873. package/test/plugin/provider/claude-agent/plugin.test.ts +0 -651
  874. package/test/plugin/provider/claude-agent/sync/sync.test.ts +0 -213
  875. package/test/plugin/provider/claude-agent/tools/tools.test.ts +0 -85
  876. package/test/plugin/provider/claude-agent/websearch.test.ts +0 -106
  877. package/test/plugin/provider-amazon-bedrock.test.ts +0 -225
  878. package/test/plugin/provider-azure.test.ts +0 -793
  879. package/test/plugin/provider-cerebras.test.ts +0 -62
  880. package/test/plugin/provider-chatgpt.test.ts +0 -1278
  881. package/test/plugin/provider-cloudflare-ai-gateway.test.ts +0 -160
  882. package/test/plugin/provider-cloudflare-workers-ai.test.ts +0 -158
  883. package/test/plugin/provider-databricks.test.ts +0 -45
  884. package/test/plugin/provider-digitalocean.test.ts +0 -322
  885. package/test/plugin/provider-dynamic.test.ts +0 -179
  886. package/test/plugin/provider-github-copilot.test.ts +0 -806
  887. package/test/plugin/provider-gitlab-oauth.test.ts +0 -407
  888. package/test/plugin/provider-gitlab.test.ts +0 -546
  889. package/test/plugin/provider-google-vertex.test.ts +0 -288
  890. package/test/plugin/provider-kilo.test.ts +0 -66
  891. package/test/plugin/provider-llmgateway.test.ts +0 -72
  892. package/test/plugin/provider-lmstudio.test.ts +0 -487
  893. package/test/plugin/provider-nvidia.test.ts +0 -84
  894. package/test/plugin/provider-ollama.test.ts +0 -312
  895. package/test/plugin/provider-openai-context-caps.test.ts +0 -80
  896. package/test/plugin/provider-openai.test.ts +0 -447
  897. package/test/plugin/provider-opencode-artifacts.test.ts +0 -236
  898. package/test/plugin/provider-opencode-watches.test.ts +0 -1103
  899. package/test/plugin/provider-opencode.test.ts +0 -2590
  900. package/test/plugin/provider-openrouter.test.ts +0 -83
  901. package/test/plugin/provider-poe.test.ts +0 -360
  902. package/test/plugin/provider-sap-ai-core.test.ts +0 -138
  903. package/test/plugin/provider-snowflake-cortex.test.ts +0 -294
  904. package/test/plugin/provider-vllm.test.ts +0 -382
  905. package/test/plugin/provider-xai.test.ts +0 -92
  906. package/test/plugin/provider-zenmux.test.ts +0 -100
  907. package/test/plugin/session-compact.test.ts +0 -52
  908. package/test/plugin/session-instructions.test.ts +0 -197
  909. package/test/plugin/session-list.test.ts +0 -52
  910. package/test/plugin/session-remove.test.ts +0 -61
  911. package/test/plugin/skill.test.ts +0 -81
  912. package/test/plugin/supervisor-reload.test.ts +0 -401
  913. package/test/plugin/supervisor.test.ts +0 -485
  914. package/test/plugin/tool-input-repair-integration.test.ts +0 -296
  915. package/test/plugin/tool-input-repair.test.ts +0 -457
  916. package/test/plugin/vcs-init.test.ts +0 -48
  917. package/test/plugin/verbosity.test.ts +0 -163
  918. package/test/plugin/warming.test.ts +0 -314
  919. package/test/plugin/websearch.test.ts +0 -368
  920. package/test/plugin/worktree.test.ts +0 -52
  921. package/test/plugin-failure.test.ts +0 -305
  922. package/test/plugin.test.ts +0 -756
  923. package/test/preload.test.ts +0 -32
  924. package/test/process/process.test.ts +0 -340
  925. package/test/project-activate.test.ts +0 -144
  926. package/test/project-icon.test.ts +0 -198
  927. package/test/project.test.ts +0 -754
  928. package/test/provider.test.ts +0 -92
  929. package/test/pty/info-schema.test.ts +0 -23
  930. package/test/pty/protocol.test.ts +0 -27
  931. package/test/pty/pty-session.test.ts +0 -224
  932. package/test/pty/pty-windows.test.ts +0 -41
  933. package/test/pty/ticket.test.ts +0 -76
  934. package/test/push-list.test.ts +0 -257
  935. package/test/push-sender.test.ts +0 -235
  936. package/test/push-watcher.test.ts +0 -359
  937. package/test/reference-instructions.test.ts +0 -112
  938. package/test/reference.test.ts +0 -209
  939. package/test/repository-cache.test.ts +0 -235
  940. package/test/repository.test.ts +0 -89
  941. package/test/ripgrep.test.ts +0 -253
  942. package/test/rpc-handler-errors.test.ts +0 -62
  943. package/test/session-activation.test.ts +0 -75
  944. package/test/session-archive.test.ts +0 -81
  945. package/test/session-background.test.ts +0 -97
  946. package/test/session-checkpoint-transport.test.ts +0 -168
  947. package/test/session-compact.test.ts +0 -171
  948. package/test/session-compaction-transport.test.ts +0 -131
  949. package/test/session-compaction.test.ts +0 -1871
  950. package/test/session-create.test.ts +0 -1643
  951. package/test/session-cwd-instructions.test.ts +0 -304
  952. package/test/session-cwd.test.ts +0 -484
  953. package/test/session-diff.test.ts +0 -207
  954. package/test/session-environment.test.ts +0 -30
  955. package/test/session-error.test.ts +0 -434
  956. package/test/session-execution.test.ts +0 -2298
  957. package/test/session-generate.test.ts +0 -502
  958. package/test/session-instructions.test.ts +0 -378
  959. package/test/session-list.test.ts +0 -72
  960. package/test/session-live-tool-metadata.test.ts +0 -43
  961. package/test/session-log.test.ts +0 -123
  962. package/test/session-model-request-hooks.test.ts +0 -270
  963. package/test/session-model-request.test.ts +0 -243
  964. package/test/session-model-transport-live.test.ts +0 -329
  965. package/test/session-model-transport.test.ts +0 -1109
  966. package/test/session-move.test.ts +0 -671
  967. package/test/session-native-compaction.test.ts +0 -425
  968. package/test/session-native.test.ts +0 -359
  969. package/test/session-owned.test.ts +0 -1073
  970. package/test/session-projector.test.ts +0 -2797
  971. package/test/session-prompt.test.ts +0 -1549
  972. package/test/session-remove.test.ts +0 -117
  973. package/test/session-revert.test.ts +0 -121
  974. package/test/session-run-coordinator.test.ts +0 -711
  975. package/test/session-runner-message.test.ts +0 -1574
  976. package/test/session-runner-recorded.test.ts +0 -288
  977. package/test/session-runner-retry.test.ts +0 -130
  978. package/test/session-runner-tool-events.test.ts +0 -662
  979. package/test/session-runner.test.ts +0 -7859
  980. package/test/session-search-build.test.ts +0 -214
  981. package/test/session-search-index.test.ts +0 -524
  982. package/test/session-search.test.ts +0 -375
  983. package/test/session-shell.test.ts +0 -437
  984. package/test/session-skill.test.ts +0 -228
  985. package/test/session-stats.test.ts +0 -429
  986. package/test/session-step.test.ts +0 -435
  987. package/test/session-store.test.ts +0 -543
  988. package/test/session-system-prompt.test.ts +0 -8
  989. package/test/session-title.test.ts +0 -767
  990. package/test/session-tool-progress.test.ts +0 -159
  991. package/test/session-usage.test.ts +0 -24
  992. package/test/session-view.test.ts +0 -218
  993. package/test/session-wait.test.ts +0 -41
  994. package/test/shared-cache.test.ts +0 -161
  995. package/test/shared-schema.test.ts +0 -187
  996. package/test/shell-cleanup.test.ts +0 -52
  997. package/test/shell-daemon.test.ts +0 -663
  998. package/test/shell-parse-compatibility.test.ts +0 -451
  999. package/test/shell-parse-parity.test.ts +0 -170
  1000. package/test/shell-parse-syntax.test.ts +0 -201
  1001. package/test/shell-parse.test.ts +0 -251
  1002. package/test/shell-restart.test.ts +0 -268
  1003. package/test/shell-result.test.ts +0 -65
  1004. package/test/shell-retention.test.ts +0 -162
  1005. package/test/shell-scan/adversarial.test.ts +0 -112
  1006. package/test/shell-scan/arithmetic.test.ts +0 -143
  1007. package/test/shell-scan/bash-safety.test.ts +0 -291
  1008. package/test/shell-scan/bash-syntax.test.ts +0 -361
  1009. package/test/shell-scan/closure.test.ts +0 -47
  1010. package/test/shell-scan/compound-parity.test.ts +0 -131
  1011. package/test/shell-scan/generated.test.ts +0 -201
  1012. package/test/shell-scan/oracle.test.ts +0 -762
  1013. package/test/shell-scan/parity-regressions.test.ts +0 -146
  1014. package/test/shell-scan/powershell-runtime.test.ts +0 -604
  1015. package/test/shell-scan/powershell-safety.test.ts +0 -470
  1016. package/test/shell-scan/powershell-syntax.test.ts +0 -177
  1017. package/test/shell-scan/redirect.test.ts +0 -168
  1018. package/test/shell-scan/scan.test.ts +0 -496
  1019. package/test/shell.test.ts +0 -140
  1020. package/test/skill/instructions.test.ts +0 -216
  1021. package/test/skill-discovery.test.ts +0 -154
  1022. package/test/skill.test.ts +0 -297
  1023. package/test/snapshot.test.ts +0 -488
  1024. package/test/sqlite-bundle.test.ts +0 -53
  1025. package/test/sqlite-interrupt.test.ts +0 -86
  1026. package/test/sqlite-node.test.ts +0 -80
  1027. package/test/sqlite-workerd.test.ts +0 -111
  1028. package/test/state-group.test.ts +0 -138
  1029. package/test/state-replay.test.ts +0 -207
  1030. package/test/state.test.ts +0 -679
  1031. package/test/storage-failure.test.ts +0 -88
  1032. package/test/subagent-completion.test.ts +0 -170
  1033. package/test/subagent-idle-e2e.test.ts +0 -825
  1034. package/test/subagent-lifetime.test.ts +0 -146
  1035. package/test/subagent-report.test.ts +0 -834
  1036. package/test/tool/file-diff.test.ts +0 -45
  1037. package/test/tool-automation.test.ts +0 -345
  1038. package/test/tool-cd.test.ts +0 -372
  1039. package/test/tool-edit.test.ts +0 -888
  1040. package/test/tool-execute.test.ts +0 -1077
  1041. package/test/tool-html-markdown-budget.test.ts +0 -68
  1042. package/test/tool-image-generate.test.ts +0 -547
  1043. package/test/tool-machine.test.ts +0 -84
  1044. package/test/tool-mcp-events.test.ts +0 -90
  1045. package/test/tool-media-target-environment.test.ts +0 -213
  1046. package/test/tool-model-policy.test.ts +0 -289
  1047. package/test/tool-opencode.test.ts +0 -303
  1048. package/test/tool-output.test.ts +0 -334
  1049. package/test/tool-patch-target-environment.test.ts +0 -239
  1050. package/test/tool-patch.test.ts +0 -1265
  1051. package/test/tool-question.test.ts +0 -260
  1052. package/test/tool-read-filesystem.test.ts +0 -833
  1053. package/test/tool-read.test.ts +0 -1341
  1054. package/test/tool-registry.test.ts +0 -1662
  1055. package/test/tool-schema.test.ts +0 -538
  1056. package/test/tool-search-target-environment.test.ts +0 -103
  1057. package/test/tool-search.test.ts +0 -411
  1058. package/test/tool-session-search.test.ts +0 -178
  1059. package/test/tool-shell-target-environment.test.ts +0 -193
  1060. package/test/tool-shell.test.ts +0 -2650
  1061. package/test/tool-skill.test.ts +0 -203
  1062. package/test/tool-subagent.test.ts +0 -1046
  1063. package/test/tool-target-environment.test.ts +0 -183
  1064. package/test/tool-todo.test.ts +0 -75
  1065. package/test/tool-video-generate.test.ts +0 -227
  1066. package/test/tool-webfetch.test.ts +0 -737
  1067. package/test/tool-websearch.test.ts +0 -482
  1068. package/test/tool-write.test.ts +0 -440
  1069. package/test/usage-limits.test.ts +0 -210
  1070. package/test/util/effect-flock.test.ts +0 -331
  1071. package/test/util/error-summary.test.ts +0 -19
  1072. package/test/util/flock.test.ts +0 -326
  1073. package/test/util/fs-util.test.ts +0 -50
  1074. package/test/util/git-executable.test.ts +0 -80
  1075. package/test/util/which.test.ts +0 -99
  1076. package/test/v1-migration.test.ts +0 -1508
  1077. package/test/variant.test.ts +0 -575
  1078. package/test/vcs-hg.test.ts +0 -239
  1079. package/test/vcs.test.ts +0 -1396
  1080. package/test/video-generation.test.ts +0 -146
  1081. package/test/voice.test.ts +0 -332
  1082. package/test/websearch.test.ts +0 -593
  1083. package/test/wellknown.test.ts +0 -132
  1084. package/test/worker-client.test.ts +0 -529
  1085. package/test/workspace.test.ts +0 -828
  1086. package/test/worktree.test.ts +0 -944
@@ -1,1320 +1,1320 @@
1
- export * as SessionCompaction from "./compaction.js"
2
-
3
- import {
4
- ai,
5
- AIError,
6
- type ContentPart,
7
- InvalidProviderOutputError,
8
- isContextOverflowFailure,
9
- LLMClient,
10
- LLMEvent,
11
- type LLMRequest,
12
- Message,
13
- type ToolEntry,
14
- UnknownProviderError,
15
- type Usage,
16
- } from "@zyro-sec/ai/effect"
17
- import type { StreamOptions } from "@zyro-sec/ai/route"
18
- import type { SessionCompactionResult } from "@zyro-sec/plugin/effect/session"
19
- import type { SessionError } from "@zyro-sec/schema/session-error"
20
- import { makeLocationNode } from "@zyro-sec/util/effect/app-node"
21
- import { Cause, Clock, Context, DateTime, Effect, Exit, Fiber, Layer, Result, Scope, Stream } from "effect"
22
- import { Agent } from "../agent.js"
23
- import { Bus } from "../bus.js"
24
- import { Database } from "../database/database.js"
25
- import { llmClient } from "../effect/app-node-platform.js"
26
- import { Flag } from "../flag.js"
27
- import { Job } from "../job.js"
28
- import { Model } from "../model.js"
29
- import { State } from "../state.js"
30
- import { Token } from "../util/token.js"
31
- import { SessionCompactionBackground } from "./compaction-background.js"
32
- import { SessionCompactionSubagents } from "./compaction-subagents.js"
33
- import type { SessionContext } from "./context.js"
34
- import { SessionEvent } from "./event.js"
35
- import { SessionHistory } from "./history.js"
36
- import type { SessionMessage } from "./message.js"
37
- import { SessionModelRequest } from "./model-request.js"
38
- import { SessionRunnerModel } from "./runner/model.js"
39
- import { SessionRunnerRetry } from "./runner/retry.js"
40
- import { toLLMMessages } from "./runner/to-llm-message.js"
41
- import { SessionRecentText } from "./recent-text.js"
42
- import { SessionStore } from "./store.js"
43
- import { contentFilterError, toSessionError } from "./to-session-error.js"
44
- import { SessionUsage } from "./usage.js"
45
-
46
- export type Settings = {
47
- auto: boolean
48
- /** Room kept free below the model's limits before compacting: a share such as "20%", or tokens. Unset keeps 15%, and at least 16k, free. */
49
- buffer?: number | string
50
- /** Tokens of recent conversation kept verbatim beside the summary. */
51
- keep: number
52
- /** Summarize in the background as the context nears the threshold, so automatic compaction can swap it in. */
53
- background: boolean
54
- }
55
-
56
- export type Editor = {
57
- configure: (settings: Partial<Settings>) => void
58
- }
59
-
60
- /** A prompt's size: `measured` is what the provider reported at the latest response, `estimated` is the text since. */
61
- export type Estimate = { readonly measured: number; readonly estimated: number }
62
-
63
- export type Trigger =
64
- /** `overflow`: the provider just rejected this context as too long. `estimate` is `estimatePrompt(context)`. */
65
- | { readonly reason: "auto" | "overflow"; readonly context: SessionContext.Loaded; readonly estimate?: Estimate }
66
- /** `inputID` is the `/compact` inbox item, whose message shows the outcome. */
67
- | { readonly reason: "manual"; readonly context: SessionContext.Loaded; readonly inputID: SessionMessage.ID }
68
-
69
- export type Outcome =
70
- /** Only `auto` skips: the context fits, or automatic compaction is off. */
71
- | { readonly status: "skipped" }
72
- | { readonly status: "completed" }
73
- | { readonly status: "failed"; readonly error: SessionError.Error }
74
-
75
- export interface Interface extends State.Transformable<Editor> {
76
- readonly compact: (trigger: Trigger) => Effect.Effect<Outcome>
77
- /**
78
- * Starts a background summary when the context nears the threshold. Never waits for it. Loads `context` only when
79
- * background summaries are on. `estimate`, when given, is `estimatePrompt` of the loaded context.
80
- */
81
- readonly precompute: <E>(
82
- context: Effect.Effect<SessionContext.Loaded, E>,
83
- estimate?: Estimate,
84
- ) => Effect.Effect<void, E>
85
- }
86
-
87
- export class Service extends Context.Service<Service, Interface>()("@zyro-sec/SessionCompaction") {}
88
-
89
- /**
90
- * A summary fills `text`, and references the messages it keeps verbatim with `metadata.keepID`; history
91
- * rebuilds their text from that. A native compaction fills `native.messages` with its replacement window.
92
- */
93
- type Result = {
94
- readonly text: string
95
- readonly native?: SessionMessage.Native
96
- readonly metadata?: Record<string, unknown>
97
- }
98
-
99
- type Failure = {
100
- readonly error: SessionError.Error
101
- }
102
-
103
- type Prepared = Effect.Success<ReturnType<SessionModelRequest.Interface["compaction"]>>
104
-
105
- type Streamed = {
106
- readonly text: string
107
- }
108
-
109
- /** A summary run off the critical path: it covers only `messages`, streams no deltas, and bills into `usage`. */
110
- type Background = {
111
- readonly messages: ReadonlyArray<SessionMessage.Info>
112
- readonly usage: (usage: SessionUsage.Recorded) => void
113
- }
114
-
115
- /** A background summary of everything before `keepID`, held until automatic compaction is due. */
116
- type Precomputed = {
117
- readonly firstID: SessionMessage.ID | undefined
118
- readonly keepID: SessionMessage.ID
119
- /** The longest tail since `keepID` that compaction still accepts beside this summary. */
120
- readonly tailLimit: number
121
- /** Background summaries that failed since the last compaction, this one included once it has. */
122
- readonly failures: number
123
- readonly usage: SessionUsage.Recorded[]
124
- readonly fiber: Fiber.Fiber<Result, Failure>
125
- }
126
-
127
- const NOTHING_TO_COMPACT: Failure = { error: { type: "compaction.unavailable", message: "Nothing to compact yet" } }
128
- /** After each "too long" rejection, the next attempt aims at this share of the first rejected request's size. */
129
- const SHRINK_STEPS = [0.85, 0.7, 0.5, 0.35]
130
- // The least of the window kept free for the last reply before compaction and for the summary itself.
131
- const RESERVE_MIN = 16_000
132
- /**
133
- * Share of the window kept free before automatic compaction. Above `RESERVE_MIN`, the margin between it and
134
- * `summaryRoom` absorbs a large step past the trigger, so the whole conversation still goes out unchanged and reuses
135
- * the cache. Single steps grew by up to ~22k tokens at p99 in real sessions.
136
- */
137
- const RESERVE_SHARE = 0.15
138
- /** A common window size, assumed for the compaction request when the model's window is unknown. */
139
- const UNKNOWN_WINDOW = 200_000
140
- /** A summary gets at least this much output, or the room left if less, even when the estimate margin leaves less. */
141
- const SUMMARY_OUTPUT_FLOOR = 32_000
142
- /**
143
- * How far one exchange of a summary transcript is shortened, in the order the levels apply: whole; tool outputs cut;
144
- * tool outputs left out and tool inputs cut; only the user's text, cut; omitted.
145
- */
146
- const OUTPUTS_CLIPPED = 1
147
- const OUTPUTS_REMOVED = 2
148
- const USER_ONLY = 3
149
- const OMITTED = 4
150
- const TRANSCRIPT_LEVELS = [0, OUTPUTS_CLIPPED, OUTPUTS_REMOVED, USER_ONLY, OMITTED]
151
- /** Characters kept, from the start and end, of a cut tool input, tool output, or user message. */
152
- const TRANSCRIPT_CLIP = 2_000
153
- const IMAGE_TOKEN_ESTIMATE = 1_500
154
- const PDF_TOKEN_ESTIMATE = 2_000
155
- /**
156
- * Tokens before the ceiling at which a background summary starts. Writing one takes 30–60 s, and in that time the
157
- * conversation grows by a few thousand tokens at the median but by 25k or more one time in twenty, when large file
158
- * reads arrive together. How far ahead to start depends on that growth, not on the window, so the lead is fixed.
159
- */
160
- const PRECOMPUTE_LEAD = 60_000
161
- /** Prompt caches expire this long after their last use unless the model sets `cache.ttl`. */
162
- const CACHE_LIFETIME = 5 * 60_000
163
- /** A background summary starts only while this much of the latest response's cache lifetime is left. */
164
- const CACHE_MARGIN = 30_000
165
- /**
166
- * The most text a swapped-in summary keeps verbatim beside it, and the tail at which a held summary is replaced, as a
167
- * share of the budget. Tails are usually far shorter; the limit is there for bursts of large tool inputs or pasted
168
- * text. At 40%, a swapped-in context stays under about two thirds of the budget even with Claude's tokenizer, so the
169
- * next cycle keeps room; a longer tail makes compaction summarize from scratch instead.
170
- */
171
- const PRECOMPUTED_TAIL_SHARE = 0.4
172
- /** Failed background summaries after which no new one starts until the next compaction. */
173
- const PRECOMPUTE_MAX_FAILURES = 2
174
-
175
- const SUMMARY_TEMPLATE = `You MUST use this format for your response (you may omit sections that aren't applicable). Do not include the <template> tags in your response.
176
- <template>
177
- ## Objective
178
- - [one or two brief sentences describing what the user is trying to accomplish]
179
-
180
- ## Requirements
181
- - [constraints, preferences, requirements, and scope boundaries stated by the user, or "(none)"]
182
-
183
- ## Decisions
184
- - [decisions already made and why, or "(none)"]
185
-
186
- ## Work State
187
- Break the objective into smaller goals and report which are completed, which are being worked on, and which are blocked.
188
- ### Completed
189
- - [goals that have been completed; otherwise "(none)"]
190
-
191
- ### Active
192
- - [goals currently being worked on; otherwise "(none)"]
193
-
194
- ### Blocked
195
- - [anything blocking progress, and why; otherwise "(none)"]
196
-
197
- ## Next Move
198
- 1. [ordered list of next actions, or "(none)"]
199
-
200
- ## Relevant Files
201
- List the files and directories, other than the current working directory, that another agent would need to open to continue this work. Include at most 15, most important first. Do not list every file that was read or changed. Include paths outside the current working directory when relevant. If none, write "(none)".
202
- - \`[file or directory path]\`: [brief reason it matters]
203
-
204
- ## Important Context
205
- - [facts the next agent cannot continue without and cannot easily find on its own; or "(none)"]
206
- </template>`
207
-
208
- const SUMMARY_RULES = `Rules:
209
- - Keep each section concise. Use terse, single-line bullets, not prose paragraphs or nested lists.
210
- - Prefer short references over detailed restatement. It is fine to leave out information the next agent can recover from the code or the files listed above.
211
- - Preserve exact file paths, symbols, commands, error strings, URLs, and identifiers.
212
- - Carry forward only user questions or requests that remain unanswered or require further action. Do not repeat ones that newer history has answered or resolved. Preserve exact wording when carrying one forward.
213
- - Preserve consequential workflow state, including whether changes are uncommitted, committed, pushed, under review, or merged.
214
- - Do not mention the summary process or that context was compacted.`
215
-
216
- /** `jobs`: the `compaction_jobs` flag, under which the checkpoint lists the session's subagents and background jobs itself. */
217
- export const buildPrompt = (update: boolean, legacy = false, jobs = false) => {
218
- const shared = [
219
- `Summarize only what the user and the assistant said and did. Leave out instructions and setup the assistant was given rather than told by the user: repository conventions, instruction files such as AGENTS.md, and environment details like ${jobs ? "this session's ID" : "the session ID"}. The next agent receives current versions of all of these separately.`,
220
- SUMMARY_TEMPLATE,
221
- SUMMARY_RULES,
222
- "Do not continue the task or call tools.",
223
- "Return only the structured summary in the requested format. Do not include a preamble, explanation, or other commentary.",
224
- ]
225
- if (!update) {
226
- return [
227
- "You MUST summarize the conversation above into a structured summary that will be given to another agent to resume the work.",
228
- ...shared,
229
- ].join("\n\n")
230
- }
231
- return [
232
- "Update the existing checkpoint in the conversation above into one consolidated summary.",
233
- // Before #48058 (Sep 2026), summaries kept nearly everything: every file touched, per-edit changelogs,
234
- // restated AGENTS.md conventions, and an "Additional Context" section that grew on every update. The
235
- // preserve-first update prompt would carry that detail forward indefinitely, so a checkpoint from that
236
- // template is rewritten once at the current level of detail. The rewrite uses the new headings, so later
237
- // updates skip this. Remove once no session still in use has a latest checkpoint older than #48058.
238
- ...(legacy
239
- ? [
240
- "The existing checkpoint was written with an earlier format that recorded far more detail than this one asks for. Rewrite it at the level of detail described below rather than carrying its detail forward. Keep its requirements, decisions, and open questions; they came from earlier conversation with the user.",
241
- ]
242
- : []),
243
- "Newer history always takes precedence over the existing checkpoint. Preserve previous information unless newer history clearly contradicts, supersedes, resolves, or makes it stale. If something is no longer relevant to continuing the work, you may remove it.",
244
- "Incorporate newer requirements, decisions, progress, and context. Reconcile Work State and Next Move: move completed work out of Active, remove resolved blockers and answered questions, and preserve unresolved or pending work.",
245
- `Return only the updated Markdown sections. Do not reproduce the ${jobs ? "`<conversation-checkpoint>`, `<summary>`, `<recent-context>`, `<subagents>`, or `<background-work>`" : "`<conversation-checkpoint>`, `<summary>`, or `<recent-context>`"} wrapper tags from the previous checkpoint.`,
246
- ...shared,
247
- ].join("\n\n")
248
- }
249
-
250
- const NUDGE =
251
- "The previous response did not fill in the required summary template. Do not call tools. Return the summary as text using the exact section headings from the template."
252
-
253
- /** Summaries written with the previous template carry this catch-all heading. */
254
- const LEGACY_HEADING = "## Additional Context"
255
-
256
- export const layer = Layer.effect(
257
- Service,
258
- Effect.gen(function* () {
259
- const agents = yield* Agent.Service
260
- const bus = yield* Bus.Service
261
- const flags = yield* Flag.Service
262
- const jobs = yield* Job.Service
263
- const llm = yield* LLMClient.Service
264
- const catalog = yield* Model.Service
265
- const models = yield* SessionRunnerModel.Service
266
- const db = (yield* Database.Service).db
267
- const requests = yield* SessionModelRequest.Service
268
- const store = yield* SessionStore.Service
269
-
270
- const scope = yield* Scope.Scope
271
- const precomputed = new Map<SessionContext.Loaded["session"]["id"], Precomputed>()
272
-
273
- const state = State.create<Settings, Editor>({
274
- name: "session-compaction",
275
- initial: () => ({ auto: true, keep: 15_000, background: true }),
276
- editor: (settings) => ({
277
- configure: (update) => {
278
- Object.assign(settings, update)
279
- },
280
- }),
281
- })
282
-
283
- /** The model that writes the summary, and the request size it aims for. */
284
- const selectModel = Effect.fnUntraced(function* (
285
- context: SessionContext.Loaded,
286
- buffer: Settings["buffer"],
287
- native: boolean,
288
- ) {
289
- const agent = native ? undefined : yield* agents.get(Agent.ID.make("compaction"))
290
- const model =
291
- (agent?.model &&
292
- (yield* models
293
- .resolve({ ...context.session, model: agent.model }, catalog.available, {
294
- kind: "compaction",
295
- agent: agent.id,
296
- })
297
- .pipe(Effect.orElseSucceed(() => undefined)))) ??
298
- context.model
299
- const ceiling = calculateCeiling(model.limit, buffer)
300
- // An unknown window never triggers auto compaction, but the compaction request still needs a size to aim for.
301
- const cap = Number.isFinite(ceiling)
302
- ? ceiling
303
- : calculateCeiling({ ...model.limit, context: UNKNOWN_WINDOW }, buffer)
304
- return { context: model === context.model ? context : { ...context, model }, cap }
305
- })
306
-
307
- const compact = Effect.fn("SessionCompaction.compact")(function* (trigger: Trigger): Effect.fn.Return<Outcome> {
308
- const settings = state.get()
309
- const context = trigger.context
310
-
311
- // Only the user compacts when automatic compaction is off, overflow included.
312
- if (trigger.reason !== "manual" && !settings.auto) return { status: "skipped" }
313
- if (
314
- trigger.reason === "auto" &&
315
- !due(context, calculateCeiling(context.model.limit, settings.buffer), trigger.estimate)
316
- )
317
- return { status: "skipped" }
318
- const held = precomputed.get(context.session.id)
319
- precomputed.delete(context.session.id)
320
- const native = context.model.compaction?.type === "native"
321
- const model = yield* selectModel(context, settings.buffer, native)
322
- // The provider just rejected this context, so the estimate ran low; the first attempt already aims below it.
323
- const budget =
324
- trigger.reason === "overflow"
325
- ? Math.min(model.cap, Math.floor(total(trigger.estimate ?? estimatePrompt(context)) * SHRINK_STEPS[0]))
326
- : model.cap
327
-
328
- const selected = model.context === context ? trigger : { ...trigger, context: model.context }
329
- // The runner opened the manual compaction's message when it delivered the `/compact` item. An automatic one
330
- // opens here, before any wait, so a background summary still being written shows as a running compaction.
331
- if (trigger.reason !== "manual")
332
- yield* bus.publish(SessionEvent.Compaction.Started, { sessionID: context.session.id, reason: "auto" })
333
- const swapped = held ? yield* usePrecomputed(selected, held, budget, native) : undefined
334
- const compaction = swapped
335
- ? Effect.succeed(swapped)
336
- : native
337
- ? compactNatively(selected, budget, settings.keep)
338
- : summarize(selected, budget, settings.keep)
339
- return yield* compaction.pipe(
340
- Effect.matchEffect({
341
- onSuccess: (result) => publish(selected, result),
342
- onFailure: (failure) => publish(selected, failure),
343
- }),
344
- )
345
- })
346
-
347
- /**
348
- * Once the context is within `PRECOMPUTE_LEAD` of the ceiling, summarizes everything before the latest response
349
- * in the background. That is the prefix the provider just processed, so the summary request reads it from the
350
- * prompt cache. The summary is held, not applied: swapping it in now would rewrite the prefix and throw away the
351
- * cache for every step until compaction is actually due. One summary is held per Session until compaction takes
352
- * it, or until it fails or falls too far behind, when a newer response replaces it.
353
- *
354
- * On a small window the lead is at most half the room the cycle started with, so the summary still covers more
355
- * than the previous one.
356
- */
357
- const precompute = Effect.fn("SessionCompaction.precompute")(function* <E>(
358
- load: Effect.Effect<SessionContext.Loaded, E>,
359
- given?: Estimate,
360
- ) {
361
- const settings = state.get()
362
- if (!settings.background || !settings.auto) return
363
- const context = yield* load
364
- if (context.model.compaction?.type === "native") return
365
- // An unknown window has an infinite ceiling, which this never reaches. Past the ceiling it still starts: at the
366
- // end of a turn, the next prompt then swaps it in instead of waiting for a summary.
367
- const ceiling = calculateCeiling(context.model.limit, settings.buffer)
368
- const estimate = given ?? estimatePrompt(context)
369
- const first = context.messages.find((message) => hasMeasuredPrompt(message, context.model.ref))
370
- const cycleStart = first?.type === "assistant" && first.tokens ? promptTokens(first.tokens) : 0
371
- if (total(estimate) < ceiling - Math.min(PRECOMPUTE_LEAD, (ceiling - cycleStart) / 2)) return
372
-
373
- const anchorIndex = context.messages.findLastIndex((message) => hasMeasuredPrompt(message, context.model.ref))
374
- const anchor = context.messages[anchorIndex]
375
- if (anchorIndex <= 0 || anchor?.type !== "assistant" || !anchor.tokens) return
376
-
377
- const sessionID = context.session.id
378
- const existing = precomputed.get(sessionID)
379
- const exit = existing?.fiber.pollUnsafe()
380
- const failed = exit !== undefined && Exit.isFailure(exit)
381
- const failures = (existing?.failures ?? 0) + (failed ? 1 : 0)
382
- if (existing) {
383
- const index = heldIndex(existing, context)
384
- if (index >= 0 && !failed && tailTokens(context, index) <= existing.tailLimit) return
385
- // Summarizing up to the same response again would repeat the same request.
386
- if (index >= 0 && (existing.keepID === anchor.id || failures >= PRECOMPUTE_MAX_FAILURES)) return
387
- yield* Effect.logInfo("background compaction replaced", {
388
- sessionID,
389
- keepID: existing.keepID,
390
- reason: index < 0 ? "history changed" : failed ? "failed" : "fell behind",
391
- })
392
- yield* Fiber.interrupt(existing.fiber)
393
- precomputed.delete(sessionID)
394
- }
395
- // After a model switch nothing is cached for the new model yet; wait until its first response has written it.
396
- if (anchor.model.id !== context.model.ref.id || anchor.model.variant !== context.model.ref.variant) return
397
- // The same once the latest response is older than the cache lifetime, as when the user comes back from a
398
- // break: the summary would write the whole prefix again, at the same time as the next request.
399
- const age = (yield* Clock.currentTimeMillis) - DateTime.toEpochMillis(anchor.time.created)
400
- if (age > cacheLifetime(context.model.cache?.ttl) - CACHE_MARGIN) return
401
-
402
- const model = yield* selectModel(context, settings.buffer, false)
403
- const usage: SessionUsage.Recorded[] = []
404
- const fiber = yield* summarize({ reason: "auto", context: model.context }, model.cap, settings.keep, {
405
- messages: context.messages.slice(0, anchorIndex),
406
- usage: (recorded) => usage.push(recorded),
407
- }).pipe(
408
- Effect.tapCause((cause) =>
409
- Cause.hasInterruptsOnly(cause)
410
- ? Effect.void
411
- : Effect.logWarning("background compaction failed", { sessionID, keepID: anchor.id, cause }),
412
- ),
413
- Effect.withSpan("SessionCompaction.background", {
414
- attributes: { "session.id": sessionID, "compaction.keep_id": anchor.id },
415
- }),
416
- Effect.forkIn(scope),
417
- )
418
- precomputed.set(sessionID, {
419
- firstID: context.messages[0]?.id,
420
- keepID: anchor.id,
421
- tailLimit: tailLimit(model.cap),
422
- failures,
423
- usage,
424
- fiber,
425
- })
426
- })
427
-
428
- /**
429
- * The held summary plus everything since it, kept verbatim, when it still describes this conversation and that
430
- * tail is short. Waits for a summary still being written. Undefined, after stopping the background work, when it
431
- * cannot be used; compaction then summarizes as usual. A summary is plain text, so it serves any model, but a
432
- * session that switched to native compaction compacts natively.
433
- */
434
- const usePrecomputed = Effect.fnUntraced(function* (
435
- trigger: Trigger,
436
- held: Precomputed,
437
- budget: number,
438
- native: boolean,
439
- ): Effect.fn.Return<Result | undefined> {
440
- const context = trigger.context
441
- const index = heldIndex(held, context)
442
- if (native || index < 0 || tailTokens(context, index) > tailLimit(budget)) {
443
- yield* Effect.logInfo("background compaction discarded", {
444
- sessionID: context.session.id,
445
- keepID: held.keepID,
446
- reason: native ? "native compaction" : index < 0 ? "history changed" : "tail too long",
447
- })
448
- yield* Fiber.interrupt(held.fiber)
449
- return undefined
450
- }
451
-
452
- const pending = held.fiber.pollUnsafe() === undefined
453
- const waitStarted = yield* Clock.currentTimeMillis
454
- const exit = yield* Fiber.await(held.fiber).pipe(Effect.onInterrupt(() => Fiber.interrupt(held.fiber)))
455
- yield* Effect.annotateCurrentSpan({
456
- "compaction.background.pending": pending,
457
- "compaction.background.wait_ms": (yield* Clock.currentTimeMillis) - waitStarted,
458
- "compaction.background.failed": Exit.isFailure(exit),
459
- })
460
- if (Exit.isFailure(exit)) return undefined
461
- // Background calls were billed as they finished; the compaction's message still shows what it cost.
462
- held.usage.forEach((usage) => addSpent(context.session.id, usage))
463
- return { ...exit.value, metadata: { keepID: held.keepID, ...exit.value.metadata } }
464
- })
465
-
466
- const due = (context: SessionContext.Loaded, ceiling: number, estimate?: Estimate) => {
467
- const messages = context.messages
468
- // A compaction just completed; let the runner rebuild the request from it first.
469
- const last = messages.at(-1)
470
- if (last?.type === "compaction" && last.status === "completed") return false
471
- // An encrypted native window estimates as nothing, so wait for a response to measure it.
472
- const measured = messages.findLastIndex((message) => hasMeasuredPrompt(message, context.model.ref))
473
- if (measured < messages.findLastIndex(SessionHistory.isNativeCompaction)) return false
474
- return total(estimate ?? estimatePrompt(context)) >= ceiling
475
- }
476
-
477
- /**
478
- * first: [E1 … E8][E9 E10] → [S1 + "E9 E10"]
479
- * again: [S1 + "E9 E10"][E11 … E18][E19] → [S2 + "E19"] S2 covers the whole current conversation
480
- *
481
- * The model is sent the whole conversation, including the tail kept beside the summary, then the summary prompt.
482
- * Keeping the normal request's prefix intact lets the summary reuse its prompt cache:
483
- *
484
- * [system][S1 + "E9 E10"][E11 … E18][E19][prompt] plus one nudge if the reply skips the template
485
- *
486
- * Later requests open with the checkpoint as one user message:
487
- *
488
- * <conversation-checkpoint>
489
- * <summary>S2</summary>
490
- * <recent-context>E19</recent-context>
491
- * </conversation-checkpoint>
492
- * [new messages…]
493
- *
494
- * E = one exchange: a user message and the replies to it. S = a summary. [S + "…"] = one checkpoint: a summary
495
- * plus the newest `keep` tokens of messages, referenced by their first message and sent as text.
496
- */
497
- const summarize = Effect.fnUntraced(function* (
498
- trigger: Trigger,
499
- budget: number,
500
- keep: number,
501
- background?: Background,
502
- ): Effect.fn.Return<Result, Failure> {
503
- const context = trigger.context
504
- const messages = background?.messages ?? context.messages
505
- const split = splitConversation(messages, keep)
506
- if (split === undefined) return yield* Effect.fail(NOTHING_TO_COMPACT)
507
- // A background summary covers all of its messages; what follows them is kept when it is swapped in.
508
- const keepID = background ? undefined : split.keepID
509
-
510
- const previous = previousCompaction(messages)
511
- const prompt = buildPrompt(
512
- previous !== undefined,
513
- previous?.summary.includes(LEGACY_HEADING) ?? false,
514
- yield* flags.enabled("compaction_jobs"),
515
- )
516
- const headings = SUMMARY_TEMPLATE.split("\n").filter((line) => line.startsWith("##"))
517
- const filled = (text: string) => text.split("\n").some((line) => headings.includes(line.trim()))
518
- const prepared = yield* prepare(context, messages, budget)
519
- // Size the unchanged request with the number that decided to compact: the last response's count plus an
520
- // estimate of what came after it. Characters overstate a conversation whose old reasoning the provider drops.
521
- // A hook can still make this request larger than that count; the provider then rejects it and it is resent as
522
- // text. An overflow already proved the count low, so it keeps the character estimate.
523
- const measured = trigger.reason === "overflow" ? undefined : measuredPrompt({ ...context, messages })
524
-
525
- // Hooks saw the request without the summary prompt, so it is appended here. A reply that ignores the
526
- // template gets one reminder before it counts as a failure.
527
- const send = (request: LLMRequest, size?: Estimate) =>
528
- Effect.gen(function* () {
529
- const prompted = fitOutput(
530
- { ...request, messages: [...request.messages, Message.user(prompt)] },
531
- context.model.limit,
532
- size && { ...size, estimated: size.estimated + Token.estimate(prompt) },
533
- )
534
- const reply = yield* stream(context, prompted, prepared.options, background)
535
- if (filled(reply.text)) return reply
536
-
537
- const nudged = fitOutput(
538
- { ...prompted, messages: [...prompted.messages, Message.user(NUDGE)] },
539
- context.model.limit,
540
- size && { ...size, estimated: size.estimated + Token.estimate(prompt) + Token.estimate(NUDGE) },
541
- )
542
- const retry = yield* stream(context, nudged, prepared.options, background)
543
- if (filled(retry.text)) return retry
544
- return yield* Effect.fail<Failure>({
545
- error: {
546
- type: "compaction.failed",
547
- message: retry.text.trim()
548
- ? "Compaction summary did not match the required template"
549
- : "Compaction produced no summary",
550
- },
551
- })
552
- })
553
-
554
- const overhead = Token.estimate(prompt) + Token.estimate(NUDGE)
555
- // Automatic compaction starts past the ceiling, so the whole conversation is sent unchanged while the window can
556
- // still fit the summary. Below that, the history before the tail is sent instead, as before: unchanged when it fits,
557
- // which still reuses the cache for that shorter prefix, and as text otherwise. Dropping exchanges to make room
558
- // for the tail would leave them in neither the summary nor the tail. Where 15% of the window is under
559
- // `RESERVE_MIN`, the ceiling equals `summaryRoom`, so automatic compaction always takes this fallback.
560
- const fit =
561
- trigger.reason === "overflow"
562
- ? budget
563
- : Math.max(budget, summaryRoom(context.model.limit, prepared.request.maxTokens))
564
- const result = yield* deliver(
565
- trigger,
566
- prepared,
567
- budget - overhead,
568
- send,
569
- {
570
- fit: fit - overhead,
571
- history: withoutTail(prepared.request, keepID),
572
- measured,
573
- // The provider just rejected this conversation, so sending it unchanged again would be rejected too.
574
- text: trigger.reason === "overflow",
575
- },
576
- background,
577
- )
578
- if (!keepID) return result
579
- // A compaction hook may choose its own kept range.
580
- return { ...result, metadata: { keepID, ...result.metadata } }
581
- })
582
-
583
- /**
584
- * endpoint: [window] → [U U][item] the provider picks which messages to keep
585
- * trigger: [window][compaction_trigger] → [item]
586
- * → [U U][item] we add the newest user messages within `keep`
587
- *
588
- * Later requests open with that replacement window in place of the history it covers:
589
- *
590
- * [U U][item][new messages…]
591
- *
592
- * window = the previous compaction and everything since. item = one encrypted compaction item, which only
593
- * replays on the model that made it. U = a user message as typed.
594
- */
595
- const compactNatively = Effect.fnUntraced(function* (
596
- trigger: Trigger,
597
- budget: number,
598
- keep: number,
599
- ): Effect.fn.Return<Result, Failure> {
600
- const context = trigger.context
601
- if (!context.messages.some(SessionRecentText.messageToText)) return yield* Effect.fail(NOTHING_TO_COMPACT)
602
- const unsupported = (message: string) =>
603
- Effect.fail<Failure>({ error: { type: "provider.unsupported-operation", message } })
604
- const prepared = yield* prepare(context, context.messages, budget, "session")
605
-
606
- const toResult = (window: ReadonlyArray<Message>, usage: Usage | undefined) =>
607
- spend(context.session.id, usage && SessionUsage.record(usage, context.model.cost)).pipe(
608
- Effect.as<Result>({
609
- text: "",
610
- // Plain JSON, not the schema encoder: provider metadata can hold undefined entries, which it rejects.
611
- native: { messages: JSON.parse(JSON.stringify(window)) },
612
- }),
613
- )
614
-
615
- const send = (request: LLMRequest) => {
616
- if (ai.canCompact(request, { mechanism: "trigger" })) {
617
- return Effect.gen(function* () {
618
- const history = yield* SessionHistory.load(db, context.session.id, "local").pipe(Effect.orDie)
619
- const retained = recentUserMessages(history, context.model, keep)
620
- const response = yield* llm.compact(request, { ...prepared.options, mechanism: "trigger" })
621
- return yield* toResult([...retained, Message.assistant(response.checkpoint)], response.usage)
622
- })
623
- }
624
- if (ai.canCompact(request)) {
625
- return llm
626
- .compact(request, { mechanism: "endpoint", http: prepared.options.http })
627
- .pipe(Effect.flatMap((response) => toResult(response.replacement, response.usage)))
628
- }
629
- return unsupported(`Native compaction is not supported for ${request.model.provider}/${request.model.route.id}`)
630
- }
631
-
632
- return yield* deliver(trigger, prepared, budget, send)
633
- })
634
-
635
- /**
636
- * Sends the request as-is if it is estimated to fit `shrink.fit`, else `shrink.history` as-is if it fits `target`,
637
- * and otherwise `shrink.history` as text aimed at `target` (see `flattenAndDropOldest`). `shrink.measured`, when
638
- * given, sizes the unchanged request until the provider rejects it; after that it is only sent as text.
639
- * Limits and estimates can be wrong, so until the provider rejects something as too long, a request that cannot
640
- * be made to fit is sent whole: unchanged, or as text once its media has to go. A "too long" rejection means the
641
- * estimate ran low, so the next attempts aim at 85%, 70%, 50%, then 35% of the first rejected request's estimate,
642
- * each shortening the transcript again from scratch, and a rejection after those gives up. A "payload too large"
643
- * rejection is about bytes, which inline media almost always accounts for, so one on the unchanged request resends
644
- * it as text, which carries no media, without counting; one on text counts as "too long". Other provider errors
645
- * resend the same request under the session's retry policy. A `Failure` from `send` is a reply that cannot be
646
- * used, and is never retried.
647
- */
648
- const deliver = Effect.fnUntraced(function* (
649
- trigger: Trigger,
650
- prepared: Prepared,
651
- target: number,
652
- send: (request: LLMRequest, size?: Estimate) => Effect.Effect<Result, AIError | Failure>,
653
- shrink: {
654
- readonly fit: number
655
- readonly history: LLMRequest
656
- readonly measured?: Estimate
657
- readonly text?: boolean
658
- } = {
659
- fit: target,
660
- history: prepared.request,
661
- },
662
- background?: Background,
663
- ): Effect.fn.Return<Result, Failure> {
664
- const context = trigger.context
665
- if (prepared.event.result) return yield* fromHook(context, prepared.event.result, background)
666
-
667
- const policy = yield* SessionRunnerRetry.policy(context.session.id)
668
- let rejections = 0
669
- let rejected: number | undefined
670
- let asText = shrink.text ?? false
671
- let fit = shrink.fit
672
-
673
- while (true) {
674
- const measured = rejections === 0 ? shrink.measured : undefined
675
- const unchanged = asText
676
- ? undefined
677
- : (measured ? total(measured) : estimateRequest(prepared.request)) <= fit
678
- ? prepared.request
679
- : estimateRequest(shrink.history) <= target
680
- ? shrink.history
681
- : undefined
682
- const request =
683
- unchanged ??
684
- flattenAndDropOldest(shrink.history, context, target) ??
685
- (rejections > 0
686
- ? undefined
687
- : asText
688
- ? flattenAndDropOldest(shrink.history, context, Number.POSITIVE_INFINITY)
689
- : shrink.history)
690
- if (!request) {
691
- return yield* Effect.fail<Failure>({
692
- error: {
693
- type: "compaction.failed",
694
- message:
695
- "The compaction request cannot be reduced further without losing the latest exchange or checkpoint",
696
- },
697
- })
698
- }
699
-
700
- const size = request === prepared.request ? measured : undefined
701
- const attempt = yield* Effect.result(send(request, size))
702
- if (Result.isSuccess(attempt)) return attempt.success
703
- const cause = attempt.failure
704
- if (!(cause instanceof AIError)) return yield* Effect.fail(cause)
705
- const error = toSessionError(cause)
706
- const tooLarge = cause.reason._tag === "InvalidRequest" && cause.reason.classification === "payload-too-large"
707
-
708
- if (tooLarge && (request === prepared.request || request === shrink.history)) {
709
- asText = true
710
- continue
711
- }
712
-
713
- if (tooLarge || isContextOverflowFailure(cause)) {
714
- const step = SHRINK_STEPS[rejections]
715
- if (step === undefined) return yield* Effect.fail<Failure>({ error })
716
- rejected ??= size ? total(size) : estimateRequest(request)
717
- // The characters can still say a rejected request fits, so the conversation or the history before the tail
718
- // only goes out again as text.
719
- if (size || request === shrink.history) asText = true
720
- target = Math.floor(rejected * step)
721
- fit = target
722
- rejections++
723
- continue
724
- }
725
-
726
- const decision = yield* policy({
727
- cause,
728
- error,
729
- agent: context.agent.id,
730
- model: context.model.ref,
731
- hook: prepared.retry,
732
- retry: SessionRunnerRetry.isRetryable(cause),
733
- })
734
- if (!decision.retry) return yield* Effect.fail<Failure>({ error })
735
- yield* Effect.sleep(decision.delay)
736
- }
737
- })
738
-
739
- /**
740
- * History that has to change is sent as text rather than as edited messages: `[previous compaction][transcript]`,
741
- * the conversation since that compaction as one text message. A previous summary always stays in front, while
742
- * its verbatim recent part becomes the oldest transcript entry; a previous native window stays exactly as the
743
- * provider made it. The transcript has no tool definitions, which the summary does not need and which no longer
744
- * share a cached prefix, and leaves out reasoning, media, and instruction updates.
745
- *
746
- * When the whole transcript does not fit, exchanges are shortened oldest first, one level at a time, until it
747
- * does (see `flattenMessage` for the levels): every exchange reaches a level before any reaches the next, so
748
- * detail is lost from the oldest history first and whole exchanges are omitted only as a last resort. The newest
749
- * exchange is never omitted; undefined when the transcript cannot fit even so.
750
- */
751
- const flattenAndDropOldest = (request: LLMRequest, context: SessionContext.Loaded, target: number) => {
752
- const previous = previousCompaction(context.messages)
753
- const end =
754
- request.messages.findLastIndex(
755
- (message) =>
756
- (previous !== undefined && message.id === previous.id) ||
757
- message.content.some((part) => part.type === "compaction"),
758
- ) + 1
759
- const summary = previous !== undefined && !SessionHistory.isNativeCompaction(previous) ? previous : undefined
760
- // TODO: Read the previous summary from the hooked request once it no longer merges summary and recent into one
761
- // message. Until then it is rebuilt from storage, which drops a compaction hook's edits to that message.
762
- const lead = summary
763
- ? toLLMMessages([{ ...summary, metadata: { ...summary.metadata, recent: "" } }], context.model.ref)
764
- : request.messages.slice(0, end)
765
- const recent = summary ? SessionRecentText.kept(summary) : ""
766
-
767
- // A user message and everything after it, up to the next one, is one exchange. Each is rendered at every level
768
- // once, so shortening is running arithmetic over these sizes. The previous summary's recent part is already
769
- // shortened text: whole until it is omitted.
770
- const exchanges = [
771
- ...(recent ? [TRANSCRIPT_LEVELS.map((level) => (level === OMITTED ? "" : recent))] : []),
772
- ...request.messages
773
- .slice(end)
774
- .reduce<Message[][]>((groups, message) => {
775
- if (message.role === "user" || groups.length === 0) groups.push([message])
776
- else groups[groups.length - 1].push(message)
777
- return groups
778
- }, [])
779
- .map((group) =>
780
- TRANSCRIPT_LEVELS.map((level) =>
781
- group
782
- .map((message) => flattenMessage(message, level))
783
- .filter(Boolean)
784
- .join("\n"),
785
- ),
786
- )
787
- .filter((renders) => renders[0]),
788
- ]
789
- if (exchanges.length === 0) return undefined
790
- const note = (omitted: number) =>
791
- omitted ? `[${omitted} older ${omitted === 1 ? "exchange" : "exchanges"} omitted]\n\n` : ""
792
- const size = (text: string) => (text ? Token.estimate(text) + 1 : 0)
793
- // Room for the longest possible note is set aside before choosing what to keep.
794
- const room =
795
- target -
796
- estimateRequest({ system: request.system, tools: [], messages: lead }) -
797
- Token.estimate(note(exchanges.length))
798
-
799
- const levels = exchanges.map(() => 0)
800
- let total = exchanges.reduce((sum, renders) => sum + size(renders[0]), 0)
801
- const newest = exchanges.length - 1
802
- for (const level of TRANSCRIPT_LEVELS.slice(1)) {
803
- for (let index = 0; index < exchanges.length && total > room; index++) {
804
- // The newest exchange is what the summary most needs; it is shortened but never left out.
805
- if (index === newest && !exchanges[index][level]) continue
806
- total += size(exchanges[index][level]) - size(exchanges[index][levels[index]])
807
- levels[index] = level
808
- }
809
- }
810
- if (total > room) return undefined
811
-
812
- // Includes exchanges with no user text, which are already gone at `USER_ONLY`.
813
- const omitted = levels.filter((level, index) => !exchanges[index][level]).length
814
- const text = exchanges
815
- .map((renders, index) => renders[levels[index]])
816
- .filter(Boolean)
817
- .join("\n\n")
818
- return { ...request, tools: [], messages: [...lead, Message.user(note(omitted) + text)] }
819
- }
820
-
821
- const stream = (
822
- context: SessionContext.Loaded,
823
- request: LLMRequest,
824
- options: StreamOptions,
825
- background?: Background,
826
- ) => {
827
- const sessionID = context.session.id
828
- const unusable = (error: SessionError.Error) => Effect.fail<Failure>({ error })
829
-
830
- return llm.stream(request, options).pipe(
831
- Stream.runFoldEffect(
832
- (): Streamed => ({ text: "" }),
833
- (streamed, event): Effect.Effect<Streamed, AIError | Failure> => {
834
- if (LLMEvent.is.textDelta(event)) {
835
- const next = { ...streamed, text: streamed.text + event.text }
836
- if (background) return Effect.succeed(next)
837
- return bus.publish(SessionEvent.Compaction.Delta, { sessionID, text: event.text }).pipe(Effect.as(next))
838
- }
839
-
840
- if (LLMEvent.is.stepFinish(event)) {
841
- return spend(sessionID, SessionUsage.record(event.usage, context.model.cost), background?.usage).pipe(
842
- Effect.as(streamed),
843
- )
844
- }
845
-
846
- if (!LLMEvent.is.finish(event)) return Effect.succeed(streamed)
847
- switch (event.reason.normalized) {
848
- case "unknown":
849
- return Effect.fail(
850
- new AIError({
851
- reason: new InvalidProviderOutputError({
852
- message: "The provider response ended with an unknown finish reason.",
853
- classification: "incomplete-stream",
854
- }),
855
- }),
856
- )
857
- case "error":
858
- return Effect.fail(
859
- new AIError({ reason: new UnknownProviderError({ message: "Compaction generation failed" }) }),
860
- )
861
- case "length":
862
- return unusable({
863
- type: "compaction.failed",
864
- message: "Compaction summary reached the output token limit",
865
- })
866
- case "content-filter":
867
- return unusable(contentFilterError("Compaction summary was blocked by the provider", event.reason))
868
- default:
869
- return Effect.succeed(streamed)
870
- }
871
- },
872
- ),
873
- )
874
- }
875
-
876
- /**
877
- * The conversation as the runner would send it, after request hooks.
878
- *
879
- * The output limit leaves room for `budget`, the most `deliver` sends. The request prepared here can be larger
880
- * when the conversation overshot the threshold, and is only shrunk to fit after hooks have seen it, so sizing the
881
- * output to it would leave next to no room. A prompt the estimate undersells is rejected and shrunk like any
882
- * other.
883
- */
884
- const prepare = (
885
- context: SessionContext.Loaded,
886
- messages: ReadonlyArray<SessionMessage.Info>,
887
- budget: number,
888
- webSocket?: "session",
889
- ) => {
890
- const base = transcript(context, messages)
891
- return requests.compaction({
892
- session: context.session,
893
- agent: context.agent.id,
894
- model: context.model,
895
- tools: context.tools,
896
- system: base.system,
897
- messages: base.messages,
898
- webSocket,
899
- inputTokens: { measured: budget, estimated: 0 },
900
- })
901
- }
902
-
903
- /** A request hook supplied the summary itself, so no model call happens. */
904
- const fromHook = (context: SessionContext.Loaded, supplied: SessionCompactionResult, background?: Background) => {
905
- const usage = supplied.tokens && {
906
- tokens: supplied.tokens,
907
- cost: SessionUsage.calculateCost(context.model.cost, supplied.tokens),
908
- }
909
- return spend(context.session.id, usage, background?.usage).pipe(
910
- Effect.as<Result>({
911
- text: supplied.summary,
912
- native: supplied.native,
913
- metadata: supplied.metadata,
914
- }),
915
- )
916
- }
917
-
918
- /**
919
- * Each model call is billed as soon as it finishes, so failed and interrupted compactions are billed too. The
920
- * compaction's message shows the total across all of its calls. A session never runs two compactions at once;
921
- * a background summary keeps its own total until a compaction takes it.
922
- */
923
- const spent = new Map<SessionContext.Loaded["session"]["id"], SessionUsage.Recorded>()
924
- const addSpent = (sessionID: SessionContext.Loaded["session"]["id"], usage: SessionUsage.Recorded) => {
925
- const total = spent.get(sessionID)
926
- spent.set(sessionID, total ? SessionUsage.add(total, usage) : usage)
927
- }
928
- const spend = (
929
- sessionID: SessionContext.Loaded["session"]["id"],
930
- usage: SessionUsage.Recorded | undefined,
931
- record = (recorded: SessionUsage.Recorded) => addSpent(sessionID, recorded),
932
- ) =>
933
- Effect.gen(function* () {
934
- if (!usage) return
935
- record(usage)
936
- yield* bus.publish(SessionEvent.UsageRecorded, { sessionID, source: "compaction", ...usage })
937
- })
938
-
939
- const publish = Effect.fnUntraced(function* (
940
- trigger: Trigger,
941
- outcome: Result | Failure,
942
- ): Effect.fn.Return<Outcome> {
943
- const context = trigger.context
944
- const sessionID = context.session.id
945
- const reason = trigger.reason === "manual" ? "manual" : "auto"
946
- const usage = spent.get(sessionID)
947
-
948
- if ("error" in outcome) {
949
- yield* bus.publish(SessionEvent.Compaction.Failed, {
950
- sessionID,
951
- reason,
952
- inputID: trigger.reason === "manual" ? trigger.inputID : undefined,
953
- error: outcome.error,
954
- ...usage,
955
- })
956
- return { status: "failed", error: outcome.error }
957
- }
958
-
959
- // Read when the compaction lands, not when its summary was written: a background summary may predate them.
960
- const lists = (yield* flags.enabled("compaction_jobs"))
961
- ? {
962
- subagents: yield* SessionCompactionSubagents.collect(store, jobs, sessionID),
963
- background: yield* SessionCompactionBackground.collect(jobs, sessionID),
964
- }
965
- : {}
966
- const listed = Object.fromEntries(Object.entries(lists).filter(([, items]) => items.length > 0))
967
- const metadata = Object.keys(listed).length > 0 ? { ...listed, ...outcome.metadata } : outcome.metadata
968
-
969
- yield* bus.publish(
970
- SessionEvent.Compaction.Ended,
971
- {
972
- sessionID,
973
- reason,
974
- model: context.model.ref,
975
- native: outcome.native,
976
- text: outcome.text,
977
- ...usage,
978
- },
979
- { metadata },
980
- )
981
- return { status: "completed" }
982
- })
983
-
984
- return Service.of({
985
- transform: state.transform,
986
- reload: state.reload,
987
- // A manual compaction settles through its `/compact` inbox item, which the runner owns.
988
- compact: (trigger) =>
989
- compact(trigger).pipe(
990
- Effect.onInterrupt(() =>
991
- trigger.reason === "manual"
992
- ? Effect.void
993
- : publish(trigger, { error: { type: "compaction.interrupted", message: "Compaction was interrupted" } }),
994
- ),
995
- Effect.ensuring(Effect.sync(() => spent.delete(trigger.context.session.id))),
996
- ),
997
- precompute,
998
- })
999
- }),
1000
- )
1001
-
1002
- export const node = makeLocationNode({
1003
- service: Service,
1004
- layer,
1005
- deps: [
1006
- Agent.node,
1007
- Bus.node,
1008
- Database.node,
1009
- Flag.node,
1010
- Job.node,
1011
- llmClient,
1012
- Model.node,
1013
- SessionModelRequest.node,
1014
- SessionRunnerModel.node,
1015
- SessionStore.node,
1016
- ],
1017
- })
1018
-
1019
- /**
1020
- * Where the messages kept beside a held summary start, or -1 when the summary no longer describes this
1021
- * conversation: a compaction or revert since replaced its start.
1022
- */
1023
- const heldIndex = (held: Precomputed, context: SessionContext.Loaded) => {
1024
- if (held.firstID !== context.messages[0]?.id) return -1
1025
- return context.messages.findIndex((message) => message.id === held.keepID)
1026
- }
1027
-
1028
- /** Estimated text a swapped-in summary keeps verbatim: every message from `index` on. */
1029
- const tailTokens = (context: SessionContext.Loaded, index: number) =>
1030
- Token.estimate(context.messages.slice(index).map(SessionRecentText.messageToText).filter(Boolean).join("\n\n"))
1031
-
1032
- const tailLimit = (budget: number) => Math.floor(budget * PRECOMPUTED_TAIL_SHARE)
1033
-
1034
- const promptTokens = (tokens: { input: number; cache: { read: number; write: number } }) =>
1035
- tokens.input + tokens.cache.read + tokens.cache.write
1036
-
1037
- const DURATION_UNITS = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }
1038
-
1039
- /** Milliseconds a prompt cache entry lives, from a `cache.ttl` such as "5m" or "1h". */
1040
- const cacheLifetime = (ttl: string | undefined) => {
1041
- const match = ttl?.match(/^(\d+)(ms|s|m|h|d)$/)
1042
- return match ? Number(match[1]) * DURATION_UNITS[match[2] as keyof typeof DURATION_UNITS] : CACHE_LIFETIME
1043
- }
1044
-
1045
- /** History loads from the latest completed compaction, so a previous one is always the first message. */
1046
- const previousCompaction = (messages: ReadonlyArray<SessionMessage.Info>) => {
1047
- const [first] = messages
1048
- return first?.type === "compaction" && first.status === "completed" ? first : undefined
1049
- }
1050
-
1051
- const transcript = (context: SessionContext.Loaded, messages: ReadonlyArray<SessionMessage.Info>) =>
1052
- SessionModelRequest.baseTranscript({
1053
- agent: context.agent.info,
1054
- model: context.model,
1055
- tools: context.tools,
1056
- initial: context.initial,
1057
- messages,
1058
- })
1059
-
1060
- /**
1061
- * The newest messages within `keep` tokens, from `keepID` on, are kept verbatim beside the summary.
1062
- * Undefined when there is nothing to compact.
1063
- */
1064
- const splitConversation = (messages: ReadonlyArray<SessionMessage.Info>, keep: number) => {
1065
- const entries = messages.flatMap((message) => {
1066
- const text = SessionRecentText.messageToText(message)
1067
- return text ? [{ message, text }] : []
1068
- })
1069
- if (entries.length === 0) return undefined
1070
-
1071
- const first = entries[recentStart(entries, keep, previousCompaction(messages))]
1072
- return {
1073
- keepID: first?.message.id,
1074
- }
1075
- }
1076
-
1077
- /** The request without the retained tail, which starts at the message with ID `from`. */
1078
- const withoutTail = (request: LLMRequest, from: SessionMessage.ID | undefined) => {
1079
- const index = from === undefined ? -1 : request.messages.findIndex((message) => message.id === from)
1080
- if (index < 0) return request
1081
- return { ...request, messages: request.messages.slice(0, index) }
1082
- }
1083
-
1084
- const recentStart = (
1085
- entries: ReadonlyArray<{ readonly message: SessionMessage.Info; readonly text: string }>,
1086
- keep: number,
1087
- previous: SessionMessage.CompactionCompleted | undefined,
1088
- ) => {
1089
- // The tail is sent as text and each message carries its own tool calls and results, so it can start at any
1090
- // message. One token more per message covers the separator between them and rounding, so the joined text stays
1091
- // within `keep`. A newest message larger than `keep` on its own is summarized with the rest.
1092
- const start = oldestToDrop(entries, (entry) => Token.estimate(entry.text) + 1, keep)
1093
- if (start > 0) return start
1094
-
1095
- // Everything fits. Keep only the latest exchange rather than duplicating the whole conversation beside the summary.
1096
- const latestUser = entries.findLastIndex((entry) => entry.message.type === "user")
1097
- if (latestUser > 0) return latestUser
1098
-
1099
- // One exchange, nothing older. Summarize it all and keep nothing, unless a previous summary already
1100
- // kept recent text, in which case keep everything and summarize only the summary before it.
1101
- return previous && SessionRecentText.kept(previous) ? 0 : entries.length
1102
- }
1103
-
1104
- const oldestToDrop = <T>(items: ReadonlyArray<T>, size: (item: T) => number, budget: number) => {
1105
- let total = 0
1106
- let start = items.length
1107
- while (start > 0) {
1108
- const next = total + size(items[start - 1])
1109
- if (next > budget) break
1110
- total = next
1111
- start--
1112
- }
1113
- return start
1114
- }
1115
-
1116
- /** One request message as transcript lines at a shortening level. Empty for what that level leaves out. */
1117
- const flattenMessage = (message: Message, level: number) => {
1118
- if (message.role === "system" || level === OMITTED) return ""
1119
- if (level >= USER_ONLY && message.role !== "user") return ""
1120
- return message.content
1121
- .flatMap((part) => {
1122
- if (part.type === "text") {
1123
- if (!part.text) return []
1124
- const text = level >= USER_ONLY ? clip(part.text) : part.text
1125
- return [`[${message.role === "user" ? "User" : "Assistant"}]: ${text}`]
1126
- }
1127
- if (level >= USER_ONLY) return []
1128
- if (part.type === "media") return [`[${part.media.mediaType} omitted]`]
1129
- if (part.type === "tool-call") {
1130
- const input = JSON.stringify(part.input) ?? ""
1131
- return [`[Assistant tool call]: ${part.name}(${level >= OUTPUTS_REMOVED ? clip(input) : input})`]
1132
- }
1133
- if (part.type !== "tool-result") return []
1134
- const result = part.result
1135
- const label = result.type === "error" ? "Tool error" : "Tool result"
1136
- if (level >= OUTPUTS_REMOVED) return [`[${label} omitted]`]
1137
- const output =
1138
- result.type === "content"
1139
- ? SessionRecentText.serializeToolContent(result.value)
1140
- : typeof result.value === "string"
1141
- ? result.value
1142
- : (JSON.stringify(result.value) ?? "")
1143
- return [`[${label}]: ${level >= OUTPUTS_CLIPPED ? clip(output) : output}`]
1144
- })
1145
- .join("\n")
1146
- }
1147
-
1148
- /** `value` cut to `TRANSCRIPT_CLIP` characters from its start and end, never splitting a surrogate pair. */
1149
- const clip = (value: string) => {
1150
- if (value.length <= TRANSCRIPT_CLIP) return value
1151
- const chars = Array.from(value)
1152
- if (chars.length <= TRANSCRIPT_CLIP) return value
1153
- const half = TRANSCRIPT_CLIP / 2
1154
- const omitted = chars.length - TRANSCRIPT_CLIP
1155
- return `${chars.slice(0, half).join("")}\n[… ${omitted} characters omitted …]\n${chars.slice(-half).join("")}`
1156
- }
1157
-
1158
- /** The newest whole, real user messages within `keep` tokens: no synthetic guidance, no half of an attachment. */
1159
- export const recentUserMessages = (
1160
- messages: ReadonlyArray<SessionMessage.Info>,
1161
- model: Pick<SessionContext.Loaded["model"], "ref" | "capabilities">,
1162
- keep: number,
1163
- ) => {
1164
- const users = messages
1165
- .filter((message) => message.type === "user")
1166
- .map((message) => ({ ...message, skills: undefined }))
1167
- const sendable = SessionModelRequest.boundImages(
1168
- SessionModelRequest.unsupportedParts(toLLMMessages(users, model.ref), model.capabilities),
1169
- )
1170
- return sendable.slice(oldestToDrop(sendable, estimateMessage, keep))
1171
- }
1172
-
1173
- const total = (estimate: Estimate) => estimate.measured + estimate.estimated
1174
-
1175
- export const estimateContext = (context: SessionContext.Loaded) => total(estimatePrompt(context))
1176
-
1177
- /** The size of the prompt `context` sends. */
1178
- export const estimatePrompt = (context: SessionContext.Loaded): Estimate => {
1179
- const anchorIndex = context.messages.findLastIndex((message) => hasMeasuredPrompt(message, context.model.ref))
1180
- const anchor = context.messages[anchorIndex]
1181
- const base = transcript(context, context.messages.slice(Math.max(0, anchorIndex)))
1182
- // TODO: Pass compaction history the runner has already shaped. This and `recentUserMessages` repeat the
1183
- // runner's unsupported-media and image-budget passes; here the image budget only sees images since the anchor,
1184
- // so image-heavy sessions can estimate high.
1185
- const sent = SessionModelRequest.boundImages(
1186
- SessionModelRequest.unsupportedParts(base.messages, context.model.capabilities),
1187
- )
1188
- // The anchor's usage covers its own output, but not its local tool results, which the provider never saw.
1189
- const unmeasured = sent.filter((message) => message.role !== "assistant" || message.id !== anchor?.id)
1190
-
1191
- if (anchor?.type !== "assistant" || !anchor.tokens)
1192
- return {
1193
- measured: 0,
1194
- estimated: estimateRequest({ system: base.system, tools: context.tools.definitions, messages: unmeasured }),
1195
- }
1196
-
1197
- const tokens = anchor.tokens
1198
- return {
1199
- measured: tokens.input + tokens.cache.read + tokens.cache.write + tokens.output + tokens.reasoning,
1200
- estimated: unmeasured.reduce((sum, message) => sum + estimateMessage(message), 0),
1201
- }
1202
- }
1203
-
1204
- /**
1205
- * The largest request the model takes while leaving room for its reply: `RESERVE_SHARE` of the window, or
1206
- * `RESERVE_MIN` when that is more. A summary request that must be shrunk is aimed at the same size. A window too small
1207
- * to give up `RESERVE_MIN` keeps `RESERVE_SHARE`.
1208
- */
1209
- const calculateCeiling = (limit: SessionContext.Loaded["model"]["limit"], buffer: Settings["buffer"]) => {
1210
- // With no window at all, only a provider rejection can limit the request.
1211
- const window = inputWindow(limit)
1212
- if (window <= 0) return Number.POSITIVE_INFINITY
1213
- const tokens = typeof buffer === "string" ? Math.round((window * Number.parseFloat(buffer)) / 100) : buffer
1214
- // A buffer that leaves no room, such as one set for a larger model, is ignored.
1215
- if (tokens !== undefined && tokens < window) return window - tokens
1216
- return window - Math.max(Math.floor(window * RESERVE_SHARE), window >= 2 * RESERVE_MIN ? RESERVE_MIN : 0)
1217
- }
1218
-
1219
- /**
1220
- * The largest summary request that leaves `RESERVE_MIN` of the window for the summary, or less when the request
1221
- * cannot generate that much. Zero for an unknown window.
1222
- */
1223
- const summaryRoom = (limit: SessionContext.Loaded["model"]["limit"], output = RESERVE_MIN) =>
1224
- Math.max(0, inputWindow(limit) - Math.min(RESERVE_MIN, output))
1225
-
1226
- /**
1227
- * The largest prompt the model takes, or 0 when unknown. Unknown limits are reported as 0, and an unknown input limit
1228
- * falls back to the context window. The context window also holds the reply, so an input limit above it, as some
1229
- * catalogs and config overrides report, cannot be used in full.
1230
- */
1231
- const inputWindow = (limit: SessionContext.Loaded["model"]["limit"]) =>
1232
- limit.input && limit.context ? Math.min(limit.input, limit.context) : limit.input || limit.context
1233
-
1234
- /**
1235
- * Another provider's count may describe a native window this model cannot replay. History then holds the original
1236
- * messages that window stood for, which the count leaves out, so only the current provider's counts are trusted.
1237
- */
1238
- const hasMeasuredPrompt = (message: SessionMessage.Info, model: SessionContext.Loaded["model"]["ref"]) =>
1239
- message.type === "assistant" &&
1240
- message.model.providerID === model.providerID &&
1241
- !message.error &&
1242
- message.tokens !== undefined &&
1243
- promptTokens(message.tokens) > 0
1244
-
1245
- /** The prompt size, only while the model, variant and agent that were measured still match; they shape the request. */
1246
- const measuredPrompt = (context: SessionContext.Loaded) => {
1247
- const anchor = context.messages.findLast((message) => hasMeasuredPrompt(message, context.model.ref))
1248
- if (
1249
- anchor?.type !== "assistant" ||
1250
- anchor.model.id !== context.model.ref.id ||
1251
- anchor.model.variant !== context.model.ref.variant ||
1252
- anchor.agent !== context.agent.id
1253
- )
1254
- return undefined
1255
- return estimatePrompt(context)
1256
- }
1257
-
1258
- /**
1259
- * `prepare` sizes the output limit for a request of `budget` tokens, but `deliver` can send a larger one when it
1260
- * cannot shrink the conversation further. Lower the limit to the room the request being sent leaves in the window,
1261
- * so the input and the requested output never exceed the window by our own estimate.
1262
- *
1263
- * The limit leaves the same margin for a low estimate that primary requests do. `deliver` aims at about 90% of the
1264
- * window, so that margin alone would cut a summary near its target to the minimum; there it still gets up to
1265
- * `SUMMARY_OUTPUT_FLOOR` of the room left without the margin.
1266
- */
1267
- const fitOutput = (request: LLMRequest, limit: SessionContext.Loaded["model"]["limit"], size?: Estimate) => {
1268
- const current = request.maxTokens
1269
- if (current === undefined) return request
1270
- const input = size ?? { measured: 0, estimated: estimateRequest(request) }
1271
- const maxTokens = Math.min(
1272
- current,
1273
- Math.max(
1274
- SessionModelRequest.outputLimit(limit, input),
1275
- Math.min(SUMMARY_OUTPUT_FLOOR, SessionModelRequest.outputLimit(limit, { measured: total(input), estimated: 0 })),
1276
- ),
1277
- )
1278
- if (maxTokens === current) return request
1279
- return { ...request, maxTokens }
1280
- }
1281
-
1282
- const estimateRequest = (request: Pick<LLMRequest, "system" | "tools" | "messages">) =>
1283
- request.system.reduce((sum, part) => sum + Token.estimate(part.text), 0) +
1284
- request.tools.reduce((sum, tool) => sum + estimateTool(tool), 0) +
1285
- request.messages.reduce((sum, message) => sum + estimateMessage(message), 0)
1286
-
1287
- /** Only what providers receive; `metadata` and `native` stay local. */
1288
- const estimateTool = (tool: ToolEntry): number => {
1289
- if (tool.type === "tool") return Token.estimate(tool.name + tool.description + JSON.stringify(tool.inputSchema))
1290
- return (
1291
- Token.estimate(tool.name + (tool.description ?? "")) +
1292
- tool.tools.reduce((sum, entry) => sum + estimateTool(entry), 0)
1293
- )
1294
- }
1295
-
1296
- const estimateMessage = (message: Message) => message.content.reduce((sum, part) => sum + estimatePart(part), 0)
1297
-
1298
- const estimatePart = (part: ContentPart): number => {
1299
- // An encrypted native compaction has no locally measurable size.
1300
- if (part.type === "compaction") return Token.estimate(part.text ?? "")
1301
- if (part.type === "effort") return 0
1302
- if (part.type === "text" || part.type === "reasoning") return Token.estimate(part.text)
1303
- if (part.type === "media") return estimateMedia(part.media.mediaType)
1304
- if (part.type === "tool-call") return Token.estimate(part.name + (JSON.stringify(part.input) ?? ""))
1305
-
1306
- if (part.result.type === "content")
1307
- return part.result.value.reduce(
1308
- (sum, content) => sum + (content.type === "text" ? Token.estimate(content.text) : estimateMedia(content.mime)),
1309
- 0,
1310
- )
1311
- const value = part.result.value
1312
- return Token.estimate(typeof value === "string" ? value : (JSON.stringify(value) ?? ""))
1313
- }
1314
-
1315
- const estimateMedia = (mime: string) => {
1316
- const type = mime.toLowerCase()
1317
- if (type.startsWith("image/")) return IMAGE_TOKEN_ESTIMATE
1318
- if (type === "application/pdf") return PDF_TOKEN_ESTIMATE
1319
- return 0
1320
- }
1
+ export * as SessionCompaction from "./compaction.js"
2
+
3
+ import {
4
+ ai,
5
+ AIError,
6
+ type ContentPart,
7
+ InvalidProviderOutputError,
8
+ isContextOverflowFailure,
9
+ LLMClient,
10
+ LLMEvent,
11
+ type LLMRequest,
12
+ Message,
13
+ type ToolEntry,
14
+ UnknownProviderError,
15
+ type Usage,
16
+ } from "@zyro-sec/ai/effect"
17
+ import type { StreamOptions } from "@zyro-sec/ai/route"
18
+ import type { SessionCompactionResult } from "@zyro-sec/plugin/effect/session"
19
+ import type { SessionError } from "@zyro-sec/schema/session-error"
20
+ import { makeLocationNode } from "@zyro-sec/util/effect/app-node"
21
+ import { Cause, Clock, Context, DateTime, Effect, Exit, Fiber, Layer, Result, Scope, Stream } from "effect"
22
+ import { Agent } from "../agent.js"
23
+ import { Bus } from "../bus.js"
24
+ import { Database } from "../database/database.js"
25
+ import { llmClient } from "../effect/app-node-platform.js"
26
+ import { Flag } from "../flag.js"
27
+ import { Job } from "../job.js"
28
+ import { Model } from "../model.js"
29
+ import { State } from "../state.js"
30
+ import { Token } from "../util/token.js"
31
+ import { SessionCompactionBackground } from "./compaction-background.js"
32
+ import { SessionCompactionSubagents } from "./compaction-subagents.js"
33
+ import type { SessionContext } from "./context.js"
34
+ import { SessionEvent } from "./event.js"
35
+ import { SessionHistory } from "./history.js"
36
+ import type { SessionMessage } from "./message.js"
37
+ import { SessionModelRequest } from "./model-request.js"
38
+ import { SessionRunnerModel } from "./runner/model.js"
39
+ import { SessionRunnerRetry } from "./runner/retry.js"
40
+ import { toLLMMessages } from "./runner/to-llm-message.js"
41
+ import { SessionRecentText } from "./recent-text.js"
42
+ import { SessionStore } from "./store.js"
43
+ import { contentFilterError, toSessionError } from "./to-session-error.js"
44
+ import { SessionUsage } from "./usage.js"
45
+
46
+ export type Settings = {
47
+ auto: boolean
48
+ /** Room kept free below the model's limits before compacting: a share such as "20%", or tokens. Unset keeps 15%, and at least 16k, free. */
49
+ buffer?: number | string
50
+ /** Tokens of recent conversation kept verbatim beside the summary. */
51
+ keep: number
52
+ /** Summarize in the background as the context nears the threshold, so automatic compaction can swap it in. */
53
+ background: boolean
54
+ }
55
+
56
+ export type Editor = {
57
+ configure: (settings: Partial<Settings>) => void
58
+ }
59
+
60
+ /** A prompt's size: `measured` is what the provider reported at the latest response, `estimated` is the text since. */
61
+ export type Estimate = { readonly measured: number; readonly estimated: number }
62
+
63
+ export type Trigger =
64
+ /** `overflow`: the provider just rejected this context as too long. `estimate` is `estimatePrompt(context)`. */
65
+ | { readonly reason: "auto" | "overflow"; readonly context: SessionContext.Loaded; readonly estimate?: Estimate }
66
+ /** `inputID` is the `/compact` inbox item, whose message shows the outcome. */
67
+ | { readonly reason: "manual"; readonly context: SessionContext.Loaded; readonly inputID: SessionMessage.ID }
68
+
69
+ export type Outcome =
70
+ /** Only `auto` skips: the context fits, or automatic compaction is off. */
71
+ | { readonly status: "skipped" }
72
+ | { readonly status: "completed" }
73
+ | { readonly status: "failed"; readonly error: SessionError.Error }
74
+
75
+ export interface Interface extends State.Transformable<Editor> {
76
+ readonly compact: (trigger: Trigger) => Effect.Effect<Outcome>
77
+ /**
78
+ * Starts a background summary when the context nears the threshold. Never waits for it. Loads `context` only when
79
+ * background summaries are on. `estimate`, when given, is `estimatePrompt` of the loaded context.
80
+ */
81
+ readonly precompute: <E>(
82
+ context: Effect.Effect<SessionContext.Loaded, E>,
83
+ estimate?: Estimate,
84
+ ) => Effect.Effect<void, E>
85
+ }
86
+
87
+ export class Service extends Context.Service<Service, Interface>()("@zyro-sec/SessionCompaction") {}
88
+
89
+ /**
90
+ * A summary fills `text`, and references the messages it keeps verbatim with `metadata.keepID`; history
91
+ * rebuilds their text from that. A native compaction fills `native.messages` with its replacement window.
92
+ */
93
+ type Result = {
94
+ readonly text: string
95
+ readonly native?: SessionMessage.Native
96
+ readonly metadata?: Record<string, unknown>
97
+ }
98
+
99
+ type Failure = {
100
+ readonly error: SessionError.Error
101
+ }
102
+
103
+ type Prepared = Effect.Success<ReturnType<SessionModelRequest.Interface["compaction"]>>
104
+
105
+ type Streamed = {
106
+ readonly text: string
107
+ }
108
+
109
+ /** A summary run off the critical path: it covers only `messages`, streams no deltas, and bills into `usage`. */
110
+ type Background = {
111
+ readonly messages: ReadonlyArray<SessionMessage.Info>
112
+ readonly usage: (usage: SessionUsage.Recorded) => void
113
+ }
114
+
115
+ /** A background summary of everything before `keepID`, held until automatic compaction is due. */
116
+ type Precomputed = {
117
+ readonly firstID: SessionMessage.ID | undefined
118
+ readonly keepID: SessionMessage.ID
119
+ /** The longest tail since `keepID` that compaction still accepts beside this summary. */
120
+ readonly tailLimit: number
121
+ /** Background summaries that failed since the last compaction, this one included once it has. */
122
+ readonly failures: number
123
+ readonly usage: SessionUsage.Recorded[]
124
+ readonly fiber: Fiber.Fiber<Result, Failure>
125
+ }
126
+
127
+ const NOTHING_TO_COMPACT: Failure = { error: { type: "compaction.unavailable", message: "Nothing to compact yet" } }
128
+ /** After each "too long" rejection, the next attempt aims at this share of the first rejected request's size. */
129
+ const SHRINK_STEPS = [0.85, 0.7, 0.5, 0.35]
130
+ // The least of the window kept free for the last reply before compaction and for the summary itself.
131
+ const RESERVE_MIN = 16_000
132
+ /**
133
+ * Share of the window kept free before automatic compaction. Above `RESERVE_MIN`, the margin between it and
134
+ * `summaryRoom` absorbs a large step past the trigger, so the whole conversation still goes out unchanged and reuses
135
+ * the cache. Single steps grew by up to ~22k tokens at p99 in real sessions.
136
+ */
137
+ const RESERVE_SHARE = 0.15
138
+ /** A common window size, assumed for the compaction request when the model's window is unknown. */
139
+ const UNKNOWN_WINDOW = 200_000
140
+ /** A summary gets at least this much output, or the room left if less, even when the estimate margin leaves less. */
141
+ const SUMMARY_OUTPUT_FLOOR = 32_000
142
+ /**
143
+ * How far one exchange of a summary transcript is shortened, in the order the levels apply: whole; tool outputs cut;
144
+ * tool outputs left out and tool inputs cut; only the user's text, cut; omitted.
145
+ */
146
+ const OUTPUTS_CLIPPED = 1
147
+ const OUTPUTS_REMOVED = 2
148
+ const USER_ONLY = 3
149
+ const OMITTED = 4
150
+ const TRANSCRIPT_LEVELS = [0, OUTPUTS_CLIPPED, OUTPUTS_REMOVED, USER_ONLY, OMITTED]
151
+ /** Characters kept, from the start and end, of a cut tool input, tool output, or user message. */
152
+ const TRANSCRIPT_CLIP = 2_000
153
+ const IMAGE_TOKEN_ESTIMATE = 1_500
154
+ const PDF_TOKEN_ESTIMATE = 2_000
155
+ /**
156
+ * Tokens before the ceiling at which a background summary starts. Writing one takes 30–60 s, and in that time the
157
+ * conversation grows by a few thousand tokens at the median but by 25k or more one time in twenty, when large file
158
+ * reads arrive together. How far ahead to start depends on that growth, not on the window, so the lead is fixed.
159
+ */
160
+ const PRECOMPUTE_LEAD = 60_000
161
+ /** Prompt caches expire this long after their last use unless the model sets `cache.ttl`. */
162
+ const CACHE_LIFETIME = 5 * 60_000
163
+ /** A background summary starts only while this much of the latest response's cache lifetime is left. */
164
+ const CACHE_MARGIN = 30_000
165
+ /**
166
+ * The most text a swapped-in summary keeps verbatim beside it, and the tail at which a held summary is replaced, as a
167
+ * share of the budget. Tails are usually far shorter; the limit is there for bursts of large tool inputs or pasted
168
+ * text. At 40%, a swapped-in context stays under about two thirds of the budget even with Claude's tokenizer, so the
169
+ * next cycle keeps room; a longer tail makes compaction summarize from scratch instead.
170
+ */
171
+ const PRECOMPUTED_TAIL_SHARE = 0.4
172
+ /** Failed background summaries after which no new one starts until the next compaction. */
173
+ const PRECOMPUTE_MAX_FAILURES = 2
174
+
175
+ const SUMMARY_TEMPLATE = `You MUST use this format for your response (you may omit sections that aren't applicable). Do not include the <template> tags in your response.
176
+ <template>
177
+ ## Objective
178
+ - [one or two brief sentences describing what the user is trying to accomplish]
179
+
180
+ ## Requirements
181
+ - [constraints, preferences, requirements, and scope boundaries stated by the user, or "(none)"]
182
+
183
+ ## Decisions
184
+ - [decisions already made and why, or "(none)"]
185
+
186
+ ## Work State
187
+ Break the objective into smaller goals and report which are completed, which are being worked on, and which are blocked.
188
+ ### Completed
189
+ - [goals that have been completed; otherwise "(none)"]
190
+
191
+ ### Active
192
+ - [goals currently being worked on; otherwise "(none)"]
193
+
194
+ ### Blocked
195
+ - [anything blocking progress, and why; otherwise "(none)"]
196
+
197
+ ## Next Move
198
+ 1. [ordered list of next actions, or "(none)"]
199
+
200
+ ## Relevant Files
201
+ List the files and directories, other than the current working directory, that another agent would need to open to continue this work. Include at most 15, most important first. Do not list every file that was read or changed. Include paths outside the current working directory when relevant. If none, write "(none)".
202
+ - \`[file or directory path]\`: [brief reason it matters]
203
+
204
+ ## Important Context
205
+ - [facts the next agent cannot continue without and cannot easily find on its own; or "(none)"]
206
+ </template>`
207
+
208
+ const SUMMARY_RULES = `Rules:
209
+ - Keep each section concise. Use terse, single-line bullets, not prose paragraphs or nested lists.
210
+ - Prefer short references over detailed restatement. It is fine to leave out information the next agent can recover from the code or the files listed above.
211
+ - Preserve exact file paths, symbols, commands, error strings, URLs, and identifiers.
212
+ - Carry forward only user questions or requests that remain unanswered or require further action. Do not repeat ones that newer history has answered or resolved. Preserve exact wording when carrying one forward.
213
+ - Preserve consequential workflow state, including whether changes are uncommitted, committed, pushed, under review, or merged.
214
+ - Do not mention the summary process or that context was compacted.`
215
+
216
+ /** `jobs`: the `compaction_jobs` flag, under which the checkpoint lists the session's subagents and background jobs itself. */
217
+ export const buildPrompt = (update: boolean, legacy = false, jobs = false) => {
218
+ const shared = [
219
+ `Summarize only what the user and the assistant said and did. Leave out instructions and setup the assistant was given rather than told by the user: repository conventions, instruction files such as AGENTS.md, and environment details like ${jobs ? "this session's ID" : "the session ID"}. The next agent receives current versions of all of these separately.`,
220
+ SUMMARY_TEMPLATE,
221
+ SUMMARY_RULES,
222
+ "Do not continue the task or call tools.",
223
+ "Return only the structured summary in the requested format. Do not include a preamble, explanation, or other commentary.",
224
+ ]
225
+ if (!update) {
226
+ return [
227
+ "You MUST summarize the conversation above into a structured summary that will be given to another agent to resume the work.",
228
+ ...shared,
229
+ ].join("\n\n")
230
+ }
231
+ return [
232
+ "Update the existing checkpoint in the conversation above into one consolidated summary.",
233
+ // Before #48058 (Sep 2026), summaries kept nearly everything: every file touched, per-edit changelogs,
234
+ // restated AGENTS.md conventions, and an "Additional Context" section that grew on every update. The
235
+ // preserve-first update prompt would carry that detail forward indefinitely, so a checkpoint from that
236
+ // template is rewritten once at the current level of detail. The rewrite uses the new headings, so later
237
+ // updates skip this. Remove once no session still in use has a latest checkpoint older than #48058.
238
+ ...(legacy
239
+ ? [
240
+ "The existing checkpoint was written with an earlier format that recorded far more detail than this one asks for. Rewrite it at the level of detail described below rather than carrying its detail forward. Keep its requirements, decisions, and open questions; they came from earlier conversation with the user.",
241
+ ]
242
+ : []),
243
+ "Newer history always takes precedence over the existing checkpoint. Preserve previous information unless newer history clearly contradicts, supersedes, resolves, or makes it stale. If something is no longer relevant to continuing the work, you may remove it.",
244
+ "Incorporate newer requirements, decisions, progress, and context. Reconcile Work State and Next Move: move completed work out of Active, remove resolved blockers and answered questions, and preserve unresolved or pending work.",
245
+ `Return only the updated Markdown sections. Do not reproduce the ${jobs ? "`<conversation-checkpoint>`, `<summary>`, `<recent-context>`, `<subagents>`, or `<background-work>`" : "`<conversation-checkpoint>`, `<summary>`, or `<recent-context>`"} wrapper tags from the previous checkpoint.`,
246
+ ...shared,
247
+ ].join("\n\n")
248
+ }
249
+
250
+ const NUDGE =
251
+ "The previous response did not fill in the required summary template. Do not call tools. Return the summary as text using the exact section headings from the template."
252
+
253
+ /** Summaries written with the previous template carry this catch-all heading. */
254
+ const LEGACY_HEADING = "## Additional Context"
255
+
256
+ export const layer = Layer.effect(
257
+ Service,
258
+ Effect.gen(function* () {
259
+ const agents = yield* Agent.Service
260
+ const bus = yield* Bus.Service
261
+ const flags = yield* Flag.Service
262
+ const jobs = yield* Job.Service
263
+ const llm = yield* LLMClient.Service
264
+ const catalog = yield* Model.Service
265
+ const models = yield* SessionRunnerModel.Service
266
+ const db = (yield* Database.Service).db
267
+ const requests = yield* SessionModelRequest.Service
268
+ const store = yield* SessionStore.Service
269
+
270
+ const scope = yield* Scope.Scope
271
+ const precomputed = new Map<SessionContext.Loaded["session"]["id"], Precomputed>()
272
+
273
+ const state = State.create<Settings, Editor>({
274
+ name: "session-compaction",
275
+ initial: () => ({ auto: true, keep: 15_000, background: true }),
276
+ editor: (settings) => ({
277
+ configure: (update) => {
278
+ Object.assign(settings, update)
279
+ },
280
+ }),
281
+ })
282
+
283
+ /** The model that writes the summary, and the request size it aims for. */
284
+ const selectModel = Effect.fnUntraced(function* (
285
+ context: SessionContext.Loaded,
286
+ buffer: Settings["buffer"],
287
+ native: boolean,
288
+ ) {
289
+ const agent = native ? undefined : yield* agents.get(Agent.ID.make("compaction"))
290
+ const model =
291
+ (agent?.model &&
292
+ (yield* models
293
+ .resolve({ ...context.session, model: agent.model }, catalog.available, {
294
+ kind: "compaction",
295
+ agent: agent.id,
296
+ })
297
+ .pipe(Effect.orElseSucceed(() => undefined)))) ??
298
+ context.model
299
+ const ceiling = calculateCeiling(model.limit, buffer)
300
+ // An unknown window never triggers auto compaction, but the compaction request still needs a size to aim for.
301
+ const cap = Number.isFinite(ceiling)
302
+ ? ceiling
303
+ : calculateCeiling({ ...model.limit, context: UNKNOWN_WINDOW }, buffer)
304
+ return { context: model === context.model ? context : { ...context, model }, cap }
305
+ })
306
+
307
+ const compact = Effect.fn("SessionCompaction.compact")(function* (trigger: Trigger): Effect.fn.Return<Outcome> {
308
+ const settings = state.get()
309
+ const context = trigger.context
310
+
311
+ // Only the user compacts when automatic compaction is off, overflow included.
312
+ if (trigger.reason !== "manual" && !settings.auto) return { status: "skipped" }
313
+ if (
314
+ trigger.reason === "auto" &&
315
+ !due(context, calculateCeiling(context.model.limit, settings.buffer), trigger.estimate)
316
+ )
317
+ return { status: "skipped" }
318
+ const held = precomputed.get(context.session.id)
319
+ precomputed.delete(context.session.id)
320
+ const native = context.model.compaction?.type === "native"
321
+ const model = yield* selectModel(context, settings.buffer, native)
322
+ // The provider just rejected this context, so the estimate ran low; the first attempt already aims below it.
323
+ const budget =
324
+ trigger.reason === "overflow"
325
+ ? Math.min(model.cap, Math.floor(total(trigger.estimate ?? estimatePrompt(context)) * SHRINK_STEPS[0]))
326
+ : model.cap
327
+
328
+ const selected = model.context === context ? trigger : { ...trigger, context: model.context }
329
+ // The runner opened the manual compaction's message when it delivered the `/compact` item. An automatic one
330
+ // opens here, before any wait, so a background summary still being written shows as a running compaction.
331
+ if (trigger.reason !== "manual")
332
+ yield* bus.publish(SessionEvent.Compaction.Started, { sessionID: context.session.id, reason: "auto" })
333
+ const swapped = held ? yield* usePrecomputed(selected, held, budget, native) : undefined
334
+ const compaction = swapped
335
+ ? Effect.succeed(swapped)
336
+ : native
337
+ ? compactNatively(selected, budget, settings.keep)
338
+ : summarize(selected, budget, settings.keep)
339
+ return yield* compaction.pipe(
340
+ Effect.matchEffect({
341
+ onSuccess: (result) => publish(selected, result),
342
+ onFailure: (failure) => publish(selected, failure),
343
+ }),
344
+ )
345
+ })
346
+
347
+ /**
348
+ * Once the context is within `PRECOMPUTE_LEAD` of the ceiling, summarizes everything before the latest response
349
+ * in the background. That is the prefix the provider just processed, so the summary request reads it from the
350
+ * prompt cache. The summary is held, not applied: swapping it in now would rewrite the prefix and throw away the
351
+ * cache for every step until compaction is actually due. One summary is held per Session until compaction takes
352
+ * it, or until it fails or falls too far behind, when a newer response replaces it.
353
+ *
354
+ * On a small window the lead is at most half the room the cycle started with, so the summary still covers more
355
+ * than the previous one.
356
+ */
357
+ const precompute = Effect.fn("SessionCompaction.precompute")(function* <E>(
358
+ load: Effect.Effect<SessionContext.Loaded, E>,
359
+ given?: Estimate,
360
+ ) {
361
+ const settings = state.get()
362
+ if (!settings.background || !settings.auto) return
363
+ const context = yield* load
364
+ if (context.model.compaction?.type === "native") return
365
+ // An unknown window has an infinite ceiling, which this never reaches. Past the ceiling it still starts: at the
366
+ // end of a turn, the next prompt then swaps it in instead of waiting for a summary.
367
+ const ceiling = calculateCeiling(context.model.limit, settings.buffer)
368
+ const estimate = given ?? estimatePrompt(context)
369
+ const first = context.messages.find((message) => hasMeasuredPrompt(message, context.model.ref))
370
+ const cycleStart = first?.type === "assistant" && first.tokens ? promptTokens(first.tokens) : 0
371
+ if (total(estimate) < ceiling - Math.min(PRECOMPUTE_LEAD, (ceiling - cycleStart) / 2)) return
372
+
373
+ const anchorIndex = context.messages.findLastIndex((message) => hasMeasuredPrompt(message, context.model.ref))
374
+ const anchor = context.messages[anchorIndex]
375
+ if (anchorIndex <= 0 || anchor?.type !== "assistant" || !anchor.tokens) return
376
+
377
+ const sessionID = context.session.id
378
+ const existing = precomputed.get(sessionID)
379
+ const exit = existing?.fiber.pollUnsafe()
380
+ const failed = exit !== undefined && Exit.isFailure(exit)
381
+ const failures = (existing?.failures ?? 0) + (failed ? 1 : 0)
382
+ if (existing) {
383
+ const index = heldIndex(existing, context)
384
+ if (index >= 0 && !failed && tailTokens(context, index) <= existing.tailLimit) return
385
+ // Summarizing up to the same response again would repeat the same request.
386
+ if (index >= 0 && (existing.keepID === anchor.id || failures >= PRECOMPUTE_MAX_FAILURES)) return
387
+ yield* Effect.logInfo("background compaction replaced", {
388
+ sessionID,
389
+ keepID: existing.keepID,
390
+ reason: index < 0 ? "history changed" : failed ? "failed" : "fell behind",
391
+ })
392
+ yield* Fiber.interrupt(existing.fiber)
393
+ precomputed.delete(sessionID)
394
+ }
395
+ // After a model switch nothing is cached for the new model yet; wait until its first response has written it.
396
+ if (anchor.model.id !== context.model.ref.id || anchor.model.variant !== context.model.ref.variant) return
397
+ // The same once the latest response is older than the cache lifetime, as when the user comes back from a
398
+ // break: the summary would write the whole prefix again, at the same time as the next request.
399
+ const age = (yield* Clock.currentTimeMillis) - DateTime.toEpochMillis(anchor.time.created)
400
+ if (age > cacheLifetime(context.model.cache?.ttl) - CACHE_MARGIN) return
401
+
402
+ const model = yield* selectModel(context, settings.buffer, false)
403
+ const usage: SessionUsage.Recorded[] = []
404
+ const fiber = yield* summarize({ reason: "auto", context: model.context }, model.cap, settings.keep, {
405
+ messages: context.messages.slice(0, anchorIndex),
406
+ usage: (recorded) => usage.push(recorded),
407
+ }).pipe(
408
+ Effect.tapCause((cause) =>
409
+ Cause.hasInterruptsOnly(cause)
410
+ ? Effect.void
411
+ : Effect.logWarning("background compaction failed", { sessionID, keepID: anchor.id, cause }),
412
+ ),
413
+ Effect.withSpan("SessionCompaction.background", {
414
+ attributes: { "session.id": sessionID, "compaction.keep_id": anchor.id },
415
+ }),
416
+ Effect.forkIn(scope),
417
+ )
418
+ precomputed.set(sessionID, {
419
+ firstID: context.messages[0]?.id,
420
+ keepID: anchor.id,
421
+ tailLimit: tailLimit(model.cap),
422
+ failures,
423
+ usage,
424
+ fiber,
425
+ })
426
+ })
427
+
428
+ /**
429
+ * The held summary plus everything since it, kept verbatim, when it still describes this conversation and that
430
+ * tail is short. Waits for a summary still being written. Undefined, after stopping the background work, when it
431
+ * cannot be used; compaction then summarizes as usual. A summary is plain text, so it serves any model, but a
432
+ * session that switched to native compaction compacts natively.
433
+ */
434
+ const usePrecomputed = Effect.fnUntraced(function* (
435
+ trigger: Trigger,
436
+ held: Precomputed,
437
+ budget: number,
438
+ native: boolean,
439
+ ): Effect.fn.Return<Result | undefined> {
440
+ const context = trigger.context
441
+ const index = heldIndex(held, context)
442
+ if (native || index < 0 || tailTokens(context, index) > tailLimit(budget)) {
443
+ yield* Effect.logInfo("background compaction discarded", {
444
+ sessionID: context.session.id,
445
+ keepID: held.keepID,
446
+ reason: native ? "native compaction" : index < 0 ? "history changed" : "tail too long",
447
+ })
448
+ yield* Fiber.interrupt(held.fiber)
449
+ return undefined
450
+ }
451
+
452
+ const pending = held.fiber.pollUnsafe() === undefined
453
+ const waitStarted = yield* Clock.currentTimeMillis
454
+ const exit = yield* Fiber.await(held.fiber).pipe(Effect.onInterrupt(() => Fiber.interrupt(held.fiber)))
455
+ yield* Effect.annotateCurrentSpan({
456
+ "compaction.background.pending": pending,
457
+ "compaction.background.wait_ms": (yield* Clock.currentTimeMillis) - waitStarted,
458
+ "compaction.background.failed": Exit.isFailure(exit),
459
+ })
460
+ if (Exit.isFailure(exit)) return undefined
461
+ // Background calls were billed as they finished; the compaction's message still shows what it cost.
462
+ held.usage.forEach((usage) => addSpent(context.session.id, usage))
463
+ return { ...exit.value, metadata: { keepID: held.keepID, ...exit.value.metadata } }
464
+ })
465
+
466
+ const due = (context: SessionContext.Loaded, ceiling: number, estimate?: Estimate) => {
467
+ const messages = context.messages
468
+ // A compaction just completed; let the runner rebuild the request from it first.
469
+ const last = messages.at(-1)
470
+ if (last?.type === "compaction" && last.status === "completed") return false
471
+ // An encrypted native window estimates as nothing, so wait for a response to measure it.
472
+ const measured = messages.findLastIndex((message) => hasMeasuredPrompt(message, context.model.ref))
473
+ if (measured < messages.findLastIndex(SessionHistory.isNativeCompaction)) return false
474
+ return total(estimate ?? estimatePrompt(context)) >= ceiling
475
+ }
476
+
477
+ /**
478
+ * first: [E1 … E8][E9 E10] → [S1 + "E9 E10"]
479
+ * again: [S1 + "E9 E10"][E11 … E18][E19] → [S2 + "E19"] S2 covers the whole current conversation
480
+ *
481
+ * The model is sent the whole conversation, including the tail kept beside the summary, then the summary prompt.
482
+ * Keeping the normal request's prefix intact lets the summary reuse its prompt cache:
483
+ *
484
+ * [system][S1 + "E9 E10"][E11 … E18][E19][prompt] plus one nudge if the reply skips the template
485
+ *
486
+ * Later requests open with the checkpoint as one user message:
487
+ *
488
+ * <conversation-checkpoint>
489
+ * <summary>S2</summary>
490
+ * <recent-context>E19</recent-context>
491
+ * </conversation-checkpoint>
492
+ * [new messages…]
493
+ *
494
+ * E = one exchange: a user message and the replies to it. S = a summary. [S + "…"] = one checkpoint: a summary
495
+ * plus the newest `keep` tokens of messages, referenced by their first message and sent as text.
496
+ */
497
+ const summarize = Effect.fnUntraced(function* (
498
+ trigger: Trigger,
499
+ budget: number,
500
+ keep: number,
501
+ background?: Background,
502
+ ): Effect.fn.Return<Result, Failure> {
503
+ const context = trigger.context
504
+ const messages = background?.messages ?? context.messages
505
+ const split = splitConversation(messages, keep)
506
+ if (split === undefined) return yield* Effect.fail(NOTHING_TO_COMPACT)
507
+ // A background summary covers all of its messages; what follows them is kept when it is swapped in.
508
+ const keepID = background ? undefined : split.keepID
509
+
510
+ const previous = previousCompaction(messages)
511
+ const prompt = buildPrompt(
512
+ previous !== undefined,
513
+ previous?.summary.includes(LEGACY_HEADING) ?? false,
514
+ yield* flags.enabled("compaction_jobs"),
515
+ )
516
+ const headings = SUMMARY_TEMPLATE.split("\n").filter((line) => line.startsWith("##"))
517
+ const filled = (text: string) => text.split("\n").some((line) => headings.includes(line.trim()))
518
+ const prepared = yield* prepare(context, messages, budget)
519
+ // Size the unchanged request with the number that decided to compact: the last response's count plus an
520
+ // estimate of what came after it. Characters overstate a conversation whose old reasoning the provider drops.
521
+ // A hook can still make this request larger than that count; the provider then rejects it and it is resent as
522
+ // text. An overflow already proved the count low, so it keeps the character estimate.
523
+ const measured = trigger.reason === "overflow" ? undefined : measuredPrompt({ ...context, messages })
524
+
525
+ // Hooks saw the request without the summary prompt, so it is appended here. A reply that ignores the
526
+ // template gets one reminder before it counts as a failure.
527
+ const send = (request: LLMRequest, size?: Estimate) =>
528
+ Effect.gen(function* () {
529
+ const prompted = fitOutput(
530
+ { ...request, messages: [...request.messages, Message.user(prompt)] },
531
+ context.model.limit,
532
+ size && { ...size, estimated: size.estimated + Token.estimate(prompt) },
533
+ )
534
+ const reply = yield* stream(context, prompted, prepared.options, background)
535
+ if (filled(reply.text)) return reply
536
+
537
+ const nudged = fitOutput(
538
+ { ...prompted, messages: [...prompted.messages, Message.user(NUDGE)] },
539
+ context.model.limit,
540
+ size && { ...size, estimated: size.estimated + Token.estimate(prompt) + Token.estimate(NUDGE) },
541
+ )
542
+ const retry = yield* stream(context, nudged, prepared.options, background)
543
+ if (filled(retry.text)) return retry
544
+ return yield* Effect.fail<Failure>({
545
+ error: {
546
+ type: "compaction.failed",
547
+ message: retry.text.trim()
548
+ ? "Compaction summary did not match the required template"
549
+ : "Compaction produced no summary",
550
+ },
551
+ })
552
+ })
553
+
554
+ const overhead = Token.estimate(prompt) + Token.estimate(NUDGE)
555
+ // Automatic compaction starts past the ceiling, so the whole conversation is sent unchanged while the window can
556
+ // still fit the summary. Below that, the history before the tail is sent instead, as before: unchanged when it fits,
557
+ // which still reuses the cache for that shorter prefix, and as text otherwise. Dropping exchanges to make room
558
+ // for the tail would leave them in neither the summary nor the tail. Where 15% of the window is under
559
+ // `RESERVE_MIN`, the ceiling equals `summaryRoom`, so automatic compaction always takes this fallback.
560
+ const fit =
561
+ trigger.reason === "overflow"
562
+ ? budget
563
+ : Math.max(budget, summaryRoom(context.model.limit, prepared.request.maxTokens))
564
+ const result = yield* deliver(
565
+ trigger,
566
+ prepared,
567
+ budget - overhead,
568
+ send,
569
+ {
570
+ fit: fit - overhead,
571
+ history: withoutTail(prepared.request, keepID),
572
+ measured,
573
+ // The provider just rejected this conversation, so sending it unchanged again would be rejected too.
574
+ text: trigger.reason === "overflow",
575
+ },
576
+ background,
577
+ )
578
+ if (!keepID) return result
579
+ // A compaction hook may choose its own kept range.
580
+ return { ...result, metadata: { keepID, ...result.metadata } }
581
+ })
582
+
583
+ /**
584
+ * endpoint: [window] → [U U][item] the provider picks which messages to keep
585
+ * trigger: [window][compaction_trigger] → [item]
586
+ * → [U U][item] we add the newest user messages within `keep`
587
+ *
588
+ * Later requests open with that replacement window in place of the history it covers:
589
+ *
590
+ * [U U][item][new messages…]
591
+ *
592
+ * window = the previous compaction and everything since. item = one encrypted compaction item, which only
593
+ * replays on the model that made it. U = a user message as typed.
594
+ */
595
+ const compactNatively = Effect.fnUntraced(function* (
596
+ trigger: Trigger,
597
+ budget: number,
598
+ keep: number,
599
+ ): Effect.fn.Return<Result, Failure> {
600
+ const context = trigger.context
601
+ if (!context.messages.some(SessionRecentText.messageToText)) return yield* Effect.fail(NOTHING_TO_COMPACT)
602
+ const unsupported = (message: string) =>
603
+ Effect.fail<Failure>({ error: { type: "provider.unsupported-operation", message } })
604
+ const prepared = yield* prepare(context, context.messages, budget, "session")
605
+
606
+ const toResult = (window: ReadonlyArray<Message>, usage: Usage | undefined) =>
607
+ spend(context.session.id, usage && SessionUsage.record(usage, context.model.cost)).pipe(
608
+ Effect.as<Result>({
609
+ text: "",
610
+ // Plain JSON, not the schema encoder: provider metadata can hold undefined entries, which it rejects.
611
+ native: { messages: JSON.parse(JSON.stringify(window)) },
612
+ }),
613
+ )
614
+
615
+ const send = (request: LLMRequest) => {
616
+ if (ai.canCompact(request, { mechanism: "trigger" })) {
617
+ return Effect.gen(function* () {
618
+ const history = yield* SessionHistory.load(db, context.session.id, "local").pipe(Effect.orDie)
619
+ const retained = recentUserMessages(history, context.model, keep)
620
+ const response = yield* llm.compact(request, { ...prepared.options, mechanism: "trigger" })
621
+ return yield* toResult([...retained, Message.assistant(response.checkpoint)], response.usage)
622
+ })
623
+ }
624
+ if (ai.canCompact(request)) {
625
+ return llm
626
+ .compact(request, { mechanism: "endpoint", http: prepared.options.http })
627
+ .pipe(Effect.flatMap((response) => toResult(response.replacement, response.usage)))
628
+ }
629
+ return unsupported(`Native compaction is not supported for ${request.model.provider}/${request.model.route.id}`)
630
+ }
631
+
632
+ return yield* deliver(trigger, prepared, budget, send)
633
+ })
634
+
635
+ /**
636
+ * Sends the request as-is if it is estimated to fit `shrink.fit`, else `shrink.history` as-is if it fits `target`,
637
+ * and otherwise `shrink.history` as text aimed at `target` (see `flattenAndDropOldest`). `shrink.measured`, when
638
+ * given, sizes the unchanged request until the provider rejects it; after that it is only sent as text.
639
+ * Limits and estimates can be wrong, so until the provider rejects something as too long, a request that cannot
640
+ * be made to fit is sent whole: unchanged, or as text once its media has to go. A "too long" rejection means the
641
+ * estimate ran low, so the next attempts aim at 85%, 70%, 50%, then 35% of the first rejected request's estimate,
642
+ * each shortening the transcript again from scratch, and a rejection after those gives up. A "payload too large"
643
+ * rejection is about bytes, which inline media almost always accounts for, so one on the unchanged request resends
644
+ * it as text, which carries no media, without counting; one on text counts as "too long". Other provider errors
645
+ * resend the same request under the session's retry policy. A `Failure` from `send` is a reply that cannot be
646
+ * used, and is never retried.
647
+ */
648
+ const deliver = Effect.fnUntraced(function* (
649
+ trigger: Trigger,
650
+ prepared: Prepared,
651
+ target: number,
652
+ send: (request: LLMRequest, size?: Estimate) => Effect.Effect<Result, AIError | Failure>,
653
+ shrink: {
654
+ readonly fit: number
655
+ readonly history: LLMRequest
656
+ readonly measured?: Estimate
657
+ readonly text?: boolean
658
+ } = {
659
+ fit: target,
660
+ history: prepared.request,
661
+ },
662
+ background?: Background,
663
+ ): Effect.fn.Return<Result, Failure> {
664
+ const context = trigger.context
665
+ if (prepared.event.result) return yield* fromHook(context, prepared.event.result, background)
666
+
667
+ const policy = yield* SessionRunnerRetry.policy(context.session.id)
668
+ let rejections = 0
669
+ let rejected: number | undefined
670
+ let asText = shrink.text ?? false
671
+ let fit = shrink.fit
672
+
673
+ while (true) {
674
+ const measured = rejections === 0 ? shrink.measured : undefined
675
+ const unchanged = asText
676
+ ? undefined
677
+ : (measured ? total(measured) : estimateRequest(prepared.request)) <= fit
678
+ ? prepared.request
679
+ : estimateRequest(shrink.history) <= target
680
+ ? shrink.history
681
+ : undefined
682
+ const request =
683
+ unchanged ??
684
+ flattenAndDropOldest(shrink.history, context, target) ??
685
+ (rejections > 0
686
+ ? undefined
687
+ : asText
688
+ ? flattenAndDropOldest(shrink.history, context, Number.POSITIVE_INFINITY)
689
+ : shrink.history)
690
+ if (!request) {
691
+ return yield* Effect.fail<Failure>({
692
+ error: {
693
+ type: "compaction.failed",
694
+ message:
695
+ "The compaction request cannot be reduced further without losing the latest exchange or checkpoint",
696
+ },
697
+ })
698
+ }
699
+
700
+ const size = request === prepared.request ? measured : undefined
701
+ const attempt = yield* Effect.result(send(request, size))
702
+ if (Result.isSuccess(attempt)) return attempt.success
703
+ const cause = attempt.failure
704
+ if (!(cause instanceof AIError)) return yield* Effect.fail(cause)
705
+ const error = toSessionError(cause)
706
+ const tooLarge = cause.reason._tag === "InvalidRequest" && cause.reason.classification === "payload-too-large"
707
+
708
+ if (tooLarge && (request === prepared.request || request === shrink.history)) {
709
+ asText = true
710
+ continue
711
+ }
712
+
713
+ if (tooLarge || isContextOverflowFailure(cause)) {
714
+ const step = SHRINK_STEPS[rejections]
715
+ if (step === undefined) return yield* Effect.fail<Failure>({ error })
716
+ rejected ??= size ? total(size) : estimateRequest(request)
717
+ // The characters can still say a rejected request fits, so the conversation or the history before the tail
718
+ // only goes out again as text.
719
+ if (size || request === shrink.history) asText = true
720
+ target = Math.floor(rejected * step)
721
+ fit = target
722
+ rejections++
723
+ continue
724
+ }
725
+
726
+ const decision = yield* policy({
727
+ cause,
728
+ error,
729
+ agent: context.agent.id,
730
+ model: context.model.ref,
731
+ hook: prepared.retry,
732
+ retry: SessionRunnerRetry.isRetryable(cause),
733
+ })
734
+ if (!decision.retry) return yield* Effect.fail<Failure>({ error })
735
+ yield* Effect.sleep(decision.delay)
736
+ }
737
+ })
738
+
739
+ /**
740
+ * History that has to change is sent as text rather than as edited messages: `[previous compaction][transcript]`,
741
+ * the conversation since that compaction as one text message. A previous summary always stays in front, while
742
+ * its verbatim recent part becomes the oldest transcript entry; a previous native window stays exactly as the
743
+ * provider made it. The transcript has no tool definitions, which the summary does not need and which no longer
744
+ * share a cached prefix, and leaves out reasoning, media, and instruction updates.
745
+ *
746
+ * When the whole transcript does not fit, exchanges are shortened oldest first, one level at a time, until it
747
+ * does (see `flattenMessage` for the levels): every exchange reaches a level before any reaches the next, so
748
+ * detail is lost from the oldest history first and whole exchanges are omitted only as a last resort. The newest
749
+ * exchange is never omitted; undefined when the transcript cannot fit even so.
750
+ */
751
+ const flattenAndDropOldest = (request: LLMRequest, context: SessionContext.Loaded, target: number) => {
752
+ const previous = previousCompaction(context.messages)
753
+ const end =
754
+ request.messages.findLastIndex(
755
+ (message) =>
756
+ (previous !== undefined && message.id === previous.id) ||
757
+ message.content.some((part) => part.type === "compaction"),
758
+ ) + 1
759
+ const summary = previous !== undefined && !SessionHistory.isNativeCompaction(previous) ? previous : undefined
760
+ // TODO: Read the previous summary from the hooked request once it no longer merges summary and recent into one
761
+ // message. Until then it is rebuilt from storage, which drops a compaction hook's edits to that message.
762
+ const lead = summary
763
+ ? toLLMMessages([{ ...summary, metadata: { ...summary.metadata, recent: "" } }], context.model.ref)
764
+ : request.messages.slice(0, end)
765
+ const recent = summary ? SessionRecentText.kept(summary) : ""
766
+
767
+ // A user message and everything after it, up to the next one, is one exchange. Each is rendered at every level
768
+ // once, so shortening is running arithmetic over these sizes. The previous summary's recent part is already
769
+ // shortened text: whole until it is omitted.
770
+ const exchanges = [
771
+ ...(recent ? [TRANSCRIPT_LEVELS.map((level) => (level === OMITTED ? "" : recent))] : []),
772
+ ...request.messages
773
+ .slice(end)
774
+ .reduce<Message[][]>((groups, message) => {
775
+ if (message.role === "user" || groups.length === 0) groups.push([message])
776
+ else groups[groups.length - 1].push(message)
777
+ return groups
778
+ }, [])
779
+ .map((group) =>
780
+ TRANSCRIPT_LEVELS.map((level) =>
781
+ group
782
+ .map((message) => flattenMessage(message, level))
783
+ .filter(Boolean)
784
+ .join("\n"),
785
+ ),
786
+ )
787
+ .filter((renders) => renders[0]),
788
+ ]
789
+ if (exchanges.length === 0) return undefined
790
+ const note = (omitted: number) =>
791
+ omitted ? `[${omitted} older ${omitted === 1 ? "exchange" : "exchanges"} omitted]\n\n` : ""
792
+ const size = (text: string) => (text ? Token.estimate(text) + 1 : 0)
793
+ // Room for the longest possible note is set aside before choosing what to keep.
794
+ const room =
795
+ target -
796
+ estimateRequest({ system: request.system, tools: [], messages: lead }) -
797
+ Token.estimate(note(exchanges.length))
798
+
799
+ const levels = exchanges.map(() => 0)
800
+ let total = exchanges.reduce((sum, renders) => sum + size(renders[0]), 0)
801
+ const newest = exchanges.length - 1
802
+ for (const level of TRANSCRIPT_LEVELS.slice(1)) {
803
+ for (let index = 0; index < exchanges.length && total > room; index++) {
804
+ // The newest exchange is what the summary most needs; it is shortened but never left out.
805
+ if (index === newest && !exchanges[index][level]) continue
806
+ total += size(exchanges[index][level]) - size(exchanges[index][levels[index]])
807
+ levels[index] = level
808
+ }
809
+ }
810
+ if (total > room) return undefined
811
+
812
+ // Includes exchanges with no user text, which are already gone at `USER_ONLY`.
813
+ const omitted = levels.filter((level, index) => !exchanges[index][level]).length
814
+ const text = exchanges
815
+ .map((renders, index) => renders[levels[index]])
816
+ .filter(Boolean)
817
+ .join("\n\n")
818
+ return { ...request, tools: [], messages: [...lead, Message.user(note(omitted) + text)] }
819
+ }
820
+
821
+ const stream = (
822
+ context: SessionContext.Loaded,
823
+ request: LLMRequest,
824
+ options: StreamOptions,
825
+ background?: Background,
826
+ ) => {
827
+ const sessionID = context.session.id
828
+ const unusable = (error: SessionError.Error) => Effect.fail<Failure>({ error })
829
+
830
+ return llm.stream(request, options).pipe(
831
+ Stream.runFoldEffect(
832
+ (): Streamed => ({ text: "" }),
833
+ (streamed, event): Effect.Effect<Streamed, AIError | Failure> => {
834
+ if (LLMEvent.is.textDelta(event)) {
835
+ const next = { ...streamed, text: streamed.text + event.text }
836
+ if (background) return Effect.succeed(next)
837
+ return bus.publish(SessionEvent.Compaction.Delta, { sessionID, text: event.text }).pipe(Effect.as(next))
838
+ }
839
+
840
+ if (LLMEvent.is.stepFinish(event)) {
841
+ return spend(sessionID, SessionUsage.record(event.usage, context.model.cost), background?.usage).pipe(
842
+ Effect.as(streamed),
843
+ )
844
+ }
845
+
846
+ if (!LLMEvent.is.finish(event)) return Effect.succeed(streamed)
847
+ switch (event.reason.normalized) {
848
+ case "unknown":
849
+ return Effect.fail(
850
+ new AIError({
851
+ reason: new InvalidProviderOutputError({
852
+ message: "The provider response ended with an unknown finish reason.",
853
+ classification: "incomplete-stream",
854
+ }),
855
+ }),
856
+ )
857
+ case "error":
858
+ return Effect.fail(
859
+ new AIError({ reason: new UnknownProviderError({ message: "Compaction generation failed" }) }),
860
+ )
861
+ case "length":
862
+ return unusable({
863
+ type: "compaction.failed",
864
+ message: "Compaction summary reached the output token limit",
865
+ })
866
+ case "content-filter":
867
+ return unusable(contentFilterError("Compaction summary was blocked by the provider", event.reason))
868
+ default:
869
+ return Effect.succeed(streamed)
870
+ }
871
+ },
872
+ ),
873
+ )
874
+ }
875
+
876
+ /**
877
+ * The conversation as the runner would send it, after request hooks.
878
+ *
879
+ * The output limit leaves room for `budget`, the most `deliver` sends. The request prepared here can be larger
880
+ * when the conversation overshot the threshold, and is only shrunk to fit after hooks have seen it, so sizing the
881
+ * output to it would leave next to no room. A prompt the estimate undersells is rejected and shrunk like any
882
+ * other.
883
+ */
884
+ const prepare = (
885
+ context: SessionContext.Loaded,
886
+ messages: ReadonlyArray<SessionMessage.Info>,
887
+ budget: number,
888
+ webSocket?: "session",
889
+ ) => {
890
+ const base = transcript(context, messages)
891
+ return requests.compaction({
892
+ session: context.session,
893
+ agent: context.agent.id,
894
+ model: context.model,
895
+ tools: context.tools,
896
+ system: base.system,
897
+ messages: base.messages,
898
+ webSocket,
899
+ inputTokens: { measured: budget, estimated: 0 },
900
+ })
901
+ }
902
+
903
+ /** A request hook supplied the summary itself, so no model call happens. */
904
+ const fromHook = (context: SessionContext.Loaded, supplied: SessionCompactionResult, background?: Background) => {
905
+ const usage = supplied.tokens && {
906
+ tokens: supplied.tokens,
907
+ cost: SessionUsage.calculateCost(context.model.cost, supplied.tokens),
908
+ }
909
+ return spend(context.session.id, usage, background?.usage).pipe(
910
+ Effect.as<Result>({
911
+ text: supplied.summary,
912
+ native: supplied.native,
913
+ metadata: supplied.metadata,
914
+ }),
915
+ )
916
+ }
917
+
918
+ /**
919
+ * Each model call is billed as soon as it finishes, so failed and interrupted compactions are billed too. The
920
+ * compaction's message shows the total across all of its calls. A session never runs two compactions at once;
921
+ * a background summary keeps its own total until a compaction takes it.
922
+ */
923
+ const spent = new Map<SessionContext.Loaded["session"]["id"], SessionUsage.Recorded>()
924
+ const addSpent = (sessionID: SessionContext.Loaded["session"]["id"], usage: SessionUsage.Recorded) => {
925
+ const total = spent.get(sessionID)
926
+ spent.set(sessionID, total ? SessionUsage.add(total, usage) : usage)
927
+ }
928
+ const spend = (
929
+ sessionID: SessionContext.Loaded["session"]["id"],
930
+ usage: SessionUsage.Recorded | undefined,
931
+ record = (recorded: SessionUsage.Recorded) => addSpent(sessionID, recorded),
932
+ ) =>
933
+ Effect.gen(function* () {
934
+ if (!usage) return
935
+ record(usage)
936
+ yield* bus.publish(SessionEvent.UsageRecorded, { sessionID, source: "compaction", ...usage })
937
+ })
938
+
939
+ const publish = Effect.fnUntraced(function* (
940
+ trigger: Trigger,
941
+ outcome: Result | Failure,
942
+ ): Effect.fn.Return<Outcome> {
943
+ const context = trigger.context
944
+ const sessionID = context.session.id
945
+ const reason = trigger.reason === "manual" ? "manual" : "auto"
946
+ const usage = spent.get(sessionID)
947
+
948
+ if ("error" in outcome) {
949
+ yield* bus.publish(SessionEvent.Compaction.Failed, {
950
+ sessionID,
951
+ reason,
952
+ inputID: trigger.reason === "manual" ? trigger.inputID : undefined,
953
+ error: outcome.error,
954
+ ...usage,
955
+ })
956
+ return { status: "failed", error: outcome.error }
957
+ }
958
+
959
+ // Read when the compaction lands, not when its summary was written: a background summary may predate them.
960
+ const lists = (yield* flags.enabled("compaction_jobs"))
961
+ ? {
962
+ subagents: yield* SessionCompactionSubagents.collect(store, jobs, sessionID),
963
+ background: yield* SessionCompactionBackground.collect(jobs, sessionID),
964
+ }
965
+ : {}
966
+ const listed = Object.fromEntries(Object.entries(lists).filter(([, items]) => items.length > 0))
967
+ const metadata = Object.keys(listed).length > 0 ? { ...listed, ...outcome.metadata } : outcome.metadata
968
+
969
+ yield* bus.publish(
970
+ SessionEvent.Compaction.Ended,
971
+ {
972
+ sessionID,
973
+ reason,
974
+ model: context.model.ref,
975
+ native: outcome.native,
976
+ text: outcome.text,
977
+ ...usage,
978
+ },
979
+ { metadata },
980
+ )
981
+ return { status: "completed" }
982
+ })
983
+
984
+ return Service.of({
985
+ transform: state.transform,
986
+ reload: state.reload,
987
+ // A manual compaction settles through its `/compact` inbox item, which the runner owns.
988
+ compact: (trigger) =>
989
+ compact(trigger).pipe(
990
+ Effect.onInterrupt(() =>
991
+ trigger.reason === "manual"
992
+ ? Effect.void
993
+ : publish(trigger, { error: { type: "compaction.interrupted", message: "Compaction was interrupted" } }),
994
+ ),
995
+ Effect.ensuring(Effect.sync(() => spent.delete(trigger.context.session.id))),
996
+ ),
997
+ precompute,
998
+ })
999
+ }),
1000
+ )
1001
+
1002
+ export const node = makeLocationNode({
1003
+ service: Service,
1004
+ layer,
1005
+ deps: [
1006
+ Agent.node,
1007
+ Bus.node,
1008
+ Database.node,
1009
+ Flag.node,
1010
+ Job.node,
1011
+ llmClient,
1012
+ Model.node,
1013
+ SessionModelRequest.node,
1014
+ SessionRunnerModel.node,
1015
+ SessionStore.node,
1016
+ ],
1017
+ })
1018
+
1019
+ /**
1020
+ * Where the messages kept beside a held summary start, or -1 when the summary no longer describes this
1021
+ * conversation: a compaction or revert since replaced its start.
1022
+ */
1023
+ const heldIndex = (held: Precomputed, context: SessionContext.Loaded) => {
1024
+ if (held.firstID !== context.messages[0]?.id) return -1
1025
+ return context.messages.findIndex((message) => message.id === held.keepID)
1026
+ }
1027
+
1028
+ /** Estimated text a swapped-in summary keeps verbatim: every message from `index` on. */
1029
+ const tailTokens = (context: SessionContext.Loaded, index: number) =>
1030
+ Token.estimate(context.messages.slice(index).map(SessionRecentText.messageToText).filter(Boolean).join("\n\n"))
1031
+
1032
+ const tailLimit = (budget: number) => Math.floor(budget * PRECOMPUTED_TAIL_SHARE)
1033
+
1034
+ const promptTokens = (tokens: { input: number; cache: { read: number; write: number } }) =>
1035
+ tokens.input + tokens.cache.read + tokens.cache.write
1036
+
1037
+ const DURATION_UNITS = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 }
1038
+
1039
+ /** Milliseconds a prompt cache entry lives, from a `cache.ttl` such as "5m" or "1h". */
1040
+ const cacheLifetime = (ttl: string | undefined) => {
1041
+ const match = ttl?.match(/^(\d+)(ms|s|m|h|d)$/)
1042
+ return match ? Number(match[1]) * DURATION_UNITS[match[2] as keyof typeof DURATION_UNITS] : CACHE_LIFETIME
1043
+ }
1044
+
1045
+ /** History loads from the latest completed compaction, so a previous one is always the first message. */
1046
+ const previousCompaction = (messages: ReadonlyArray<SessionMessage.Info>) => {
1047
+ const [first] = messages
1048
+ return first?.type === "compaction" && first.status === "completed" ? first : undefined
1049
+ }
1050
+
1051
+ const transcript = (context: SessionContext.Loaded, messages: ReadonlyArray<SessionMessage.Info>) =>
1052
+ SessionModelRequest.baseTranscript({
1053
+ agent: context.agent.info,
1054
+ model: context.model,
1055
+ tools: context.tools,
1056
+ initial: context.initial,
1057
+ messages,
1058
+ })
1059
+
1060
+ /**
1061
+ * The newest messages within `keep` tokens, from `keepID` on, are kept verbatim beside the summary.
1062
+ * Undefined when there is nothing to compact.
1063
+ */
1064
+ const splitConversation = (messages: ReadonlyArray<SessionMessage.Info>, keep: number) => {
1065
+ const entries = messages.flatMap((message) => {
1066
+ const text = SessionRecentText.messageToText(message)
1067
+ return text ? [{ message, text }] : []
1068
+ })
1069
+ if (entries.length === 0) return undefined
1070
+
1071
+ const first = entries[recentStart(entries, keep, previousCompaction(messages))]
1072
+ return {
1073
+ keepID: first?.message.id,
1074
+ }
1075
+ }
1076
+
1077
+ /** The request without the retained tail, which starts at the message with ID `from`. */
1078
+ const withoutTail = (request: LLMRequest, from: SessionMessage.ID | undefined) => {
1079
+ const index = from === undefined ? -1 : request.messages.findIndex((message) => message.id === from)
1080
+ if (index < 0) return request
1081
+ return { ...request, messages: request.messages.slice(0, index) }
1082
+ }
1083
+
1084
+ const recentStart = (
1085
+ entries: ReadonlyArray<{ readonly message: SessionMessage.Info; readonly text: string }>,
1086
+ keep: number,
1087
+ previous: SessionMessage.CompactionCompleted | undefined,
1088
+ ) => {
1089
+ // The tail is sent as text and each message carries its own tool calls and results, so it can start at any
1090
+ // message. One token more per message covers the separator between them and rounding, so the joined text stays
1091
+ // within `keep`. A newest message larger than `keep` on its own is summarized with the rest.
1092
+ const start = oldestToDrop(entries, (entry) => Token.estimate(entry.text) + 1, keep)
1093
+ if (start > 0) return start
1094
+
1095
+ // Everything fits. Keep only the latest exchange rather than duplicating the whole conversation beside the summary.
1096
+ const latestUser = entries.findLastIndex((entry) => entry.message.type === "user")
1097
+ if (latestUser > 0) return latestUser
1098
+
1099
+ // One exchange, nothing older. Summarize it all and keep nothing, unless a previous summary already
1100
+ // kept recent text, in which case keep everything and summarize only the summary before it.
1101
+ return previous && SessionRecentText.kept(previous) ? 0 : entries.length
1102
+ }
1103
+
1104
+ const oldestToDrop = <T>(items: ReadonlyArray<T>, size: (item: T) => number, budget: number) => {
1105
+ let total = 0
1106
+ let start = items.length
1107
+ while (start > 0) {
1108
+ const next = total + size(items[start - 1])
1109
+ if (next > budget) break
1110
+ total = next
1111
+ start--
1112
+ }
1113
+ return start
1114
+ }
1115
+
1116
+ /** One request message as transcript lines at a shortening level. Empty for what that level leaves out. */
1117
+ const flattenMessage = (message: Message, level: number) => {
1118
+ if (message.role === "system" || level === OMITTED) return ""
1119
+ if (level >= USER_ONLY && message.role !== "user") return ""
1120
+ return message.content
1121
+ .flatMap((part) => {
1122
+ if (part.type === "text") {
1123
+ if (!part.text) return []
1124
+ const text = level >= USER_ONLY ? clip(part.text) : part.text
1125
+ return [`[${message.role === "user" ? "User" : "Assistant"}]: ${text}`]
1126
+ }
1127
+ if (level >= USER_ONLY) return []
1128
+ if (part.type === "media") return [`[${part.media.mediaType} omitted]`]
1129
+ if (part.type === "tool-call") {
1130
+ const input = JSON.stringify(part.input) ?? ""
1131
+ return [`[Assistant tool call]: ${part.name}(${level >= OUTPUTS_REMOVED ? clip(input) : input})`]
1132
+ }
1133
+ if (part.type !== "tool-result") return []
1134
+ const result = part.result
1135
+ const label = result.type === "error" ? "Tool error" : "Tool result"
1136
+ if (level >= OUTPUTS_REMOVED) return [`[${label} omitted]`]
1137
+ const output =
1138
+ result.type === "content"
1139
+ ? SessionRecentText.serializeToolContent(result.value)
1140
+ : typeof result.value === "string"
1141
+ ? result.value
1142
+ : (JSON.stringify(result.value) ?? "")
1143
+ return [`[${label}]: ${level >= OUTPUTS_CLIPPED ? clip(output) : output}`]
1144
+ })
1145
+ .join("\n")
1146
+ }
1147
+
1148
+ /** `value` cut to `TRANSCRIPT_CLIP` characters from its start and end, never splitting a surrogate pair. */
1149
+ const clip = (value: string) => {
1150
+ if (value.length <= TRANSCRIPT_CLIP) return value
1151
+ const chars = Array.from(value)
1152
+ if (chars.length <= TRANSCRIPT_CLIP) return value
1153
+ const half = TRANSCRIPT_CLIP / 2
1154
+ const omitted = chars.length - TRANSCRIPT_CLIP
1155
+ return `${chars.slice(0, half).join("")}\n[… ${omitted} characters omitted …]\n${chars.slice(-half).join("")}`
1156
+ }
1157
+
1158
+ /** The newest whole, real user messages within `keep` tokens: no synthetic guidance, no half of an attachment. */
1159
+ export const recentUserMessages = (
1160
+ messages: ReadonlyArray<SessionMessage.Info>,
1161
+ model: Pick<SessionContext.Loaded["model"], "ref" | "capabilities">,
1162
+ keep: number,
1163
+ ) => {
1164
+ const users = messages
1165
+ .filter((message) => message.type === "user")
1166
+ .map((message) => ({ ...message, skills: undefined }))
1167
+ const sendable = SessionModelRequest.boundImages(
1168
+ SessionModelRequest.unsupportedParts(toLLMMessages(users, model.ref), model.capabilities),
1169
+ )
1170
+ return sendable.slice(oldestToDrop(sendable, estimateMessage, keep))
1171
+ }
1172
+
1173
+ const total = (estimate: Estimate) => estimate.measured + estimate.estimated
1174
+
1175
+ export const estimateContext = (context: SessionContext.Loaded) => total(estimatePrompt(context))
1176
+
1177
+ /** The size of the prompt `context` sends. */
1178
+ export const estimatePrompt = (context: SessionContext.Loaded): Estimate => {
1179
+ const anchorIndex = context.messages.findLastIndex((message) => hasMeasuredPrompt(message, context.model.ref))
1180
+ const anchor = context.messages[anchorIndex]
1181
+ const base = transcript(context, context.messages.slice(Math.max(0, anchorIndex)))
1182
+ // TODO: Pass compaction history the runner has already shaped. This and `recentUserMessages` repeat the
1183
+ // runner's unsupported-media and image-budget passes; here the image budget only sees images since the anchor,
1184
+ // so image-heavy sessions can estimate high.
1185
+ const sent = SessionModelRequest.boundImages(
1186
+ SessionModelRequest.unsupportedParts(base.messages, context.model.capabilities),
1187
+ )
1188
+ // The anchor's usage covers its own output, but not its local tool results, which the provider never saw.
1189
+ const unmeasured = sent.filter((message) => message.role !== "assistant" || message.id !== anchor?.id)
1190
+
1191
+ if (anchor?.type !== "assistant" || !anchor.tokens)
1192
+ return {
1193
+ measured: 0,
1194
+ estimated: estimateRequest({ system: base.system, tools: context.tools.definitions, messages: unmeasured }),
1195
+ }
1196
+
1197
+ const tokens = anchor.tokens
1198
+ return {
1199
+ measured: tokens.input + tokens.cache.read + tokens.cache.write + tokens.output + tokens.reasoning,
1200
+ estimated: unmeasured.reduce((sum, message) => sum + estimateMessage(message), 0),
1201
+ }
1202
+ }
1203
+
1204
+ /**
1205
+ * The largest request the model takes while leaving room for its reply: `RESERVE_SHARE` of the window, or
1206
+ * `RESERVE_MIN` when that is more. A summary request that must be shrunk is aimed at the same size. A window too small
1207
+ * to give up `RESERVE_MIN` keeps `RESERVE_SHARE`.
1208
+ */
1209
+ const calculateCeiling = (limit: SessionContext.Loaded["model"]["limit"], buffer: Settings["buffer"]) => {
1210
+ // With no window at all, only a provider rejection can limit the request.
1211
+ const window = inputWindow(limit)
1212
+ if (window <= 0) return Number.POSITIVE_INFINITY
1213
+ const tokens = typeof buffer === "string" ? Math.round((window * Number.parseFloat(buffer)) / 100) : buffer
1214
+ // A buffer that leaves no room, such as one set for a larger model, is ignored.
1215
+ if (tokens !== undefined && tokens < window) return window - tokens
1216
+ return window - Math.max(Math.floor(window * RESERVE_SHARE), window >= 2 * RESERVE_MIN ? RESERVE_MIN : 0)
1217
+ }
1218
+
1219
+ /**
1220
+ * The largest summary request that leaves `RESERVE_MIN` of the window for the summary, or less when the request
1221
+ * cannot generate that much. Zero for an unknown window.
1222
+ */
1223
+ const summaryRoom = (limit: SessionContext.Loaded["model"]["limit"], output = RESERVE_MIN) =>
1224
+ Math.max(0, inputWindow(limit) - Math.min(RESERVE_MIN, output))
1225
+
1226
+ /**
1227
+ * The largest prompt the model takes, or 0 when unknown. Unknown limits are reported as 0, and an unknown input limit
1228
+ * falls back to the context window. The context window also holds the reply, so an input limit above it, as some
1229
+ * catalogs and config overrides report, cannot be used in full.
1230
+ */
1231
+ const inputWindow = (limit: SessionContext.Loaded["model"]["limit"]) =>
1232
+ limit.input && limit.context ? Math.min(limit.input, limit.context) : limit.input || limit.context
1233
+
1234
+ /**
1235
+ * Another provider's count may describe a native window this model cannot replay. History then holds the original
1236
+ * messages that window stood for, which the count leaves out, so only the current provider's counts are trusted.
1237
+ */
1238
+ const hasMeasuredPrompt = (message: SessionMessage.Info, model: SessionContext.Loaded["model"]["ref"]) =>
1239
+ message.type === "assistant" &&
1240
+ message.model.providerID === model.providerID &&
1241
+ !message.error &&
1242
+ message.tokens !== undefined &&
1243
+ promptTokens(message.tokens) > 0
1244
+
1245
+ /** The prompt size, only while the model, variant and agent that were measured still match; they shape the request. */
1246
+ const measuredPrompt = (context: SessionContext.Loaded) => {
1247
+ const anchor = context.messages.findLast((message) => hasMeasuredPrompt(message, context.model.ref))
1248
+ if (
1249
+ anchor?.type !== "assistant" ||
1250
+ anchor.model.id !== context.model.ref.id ||
1251
+ anchor.model.variant !== context.model.ref.variant ||
1252
+ anchor.agent !== context.agent.id
1253
+ )
1254
+ return undefined
1255
+ return estimatePrompt(context)
1256
+ }
1257
+
1258
+ /**
1259
+ * `prepare` sizes the output limit for a request of `budget` tokens, but `deliver` can send a larger one when it
1260
+ * cannot shrink the conversation further. Lower the limit to the room the request being sent leaves in the window,
1261
+ * so the input and the requested output never exceed the window by our own estimate.
1262
+ *
1263
+ * The limit leaves the same margin for a low estimate that primary requests do. `deliver` aims at about 90% of the
1264
+ * window, so that margin alone would cut a summary near its target to the minimum; there it still gets up to
1265
+ * `SUMMARY_OUTPUT_FLOOR` of the room left without the margin.
1266
+ */
1267
+ const fitOutput = (request: LLMRequest, limit: SessionContext.Loaded["model"]["limit"], size?: Estimate) => {
1268
+ const current = request.maxTokens
1269
+ if (current === undefined) return request
1270
+ const input = size ?? { measured: 0, estimated: estimateRequest(request) }
1271
+ const maxTokens = Math.min(
1272
+ current,
1273
+ Math.max(
1274
+ SessionModelRequest.outputLimit(limit, input),
1275
+ Math.min(SUMMARY_OUTPUT_FLOOR, SessionModelRequest.outputLimit(limit, { measured: total(input), estimated: 0 })),
1276
+ ),
1277
+ )
1278
+ if (maxTokens === current) return request
1279
+ return { ...request, maxTokens }
1280
+ }
1281
+
1282
+ const estimateRequest = (request: Pick<LLMRequest, "system" | "tools" | "messages">) =>
1283
+ request.system.reduce((sum, part) => sum + Token.estimate(part.text), 0) +
1284
+ request.tools.reduce((sum, tool) => sum + estimateTool(tool), 0) +
1285
+ request.messages.reduce((sum, message) => sum + estimateMessage(message), 0)
1286
+
1287
+ /** Only what providers receive; `metadata` and `native` stay local. */
1288
+ const estimateTool = (tool: ToolEntry): number => {
1289
+ if (tool.type === "tool") return Token.estimate(tool.name + tool.description + JSON.stringify(tool.inputSchema))
1290
+ return (
1291
+ Token.estimate(tool.name + (tool.description ?? "")) +
1292
+ tool.tools.reduce((sum, entry) => sum + estimateTool(entry), 0)
1293
+ )
1294
+ }
1295
+
1296
+ const estimateMessage = (message: Message) => message.content.reduce((sum, part) => sum + estimatePart(part), 0)
1297
+
1298
+ const estimatePart = (part: ContentPart): number => {
1299
+ // An encrypted native compaction has no locally measurable size.
1300
+ if (part.type === "compaction") return Token.estimate(part.text ?? "")
1301
+ if (part.type === "effort") return 0
1302
+ if (part.type === "text" || part.type === "reasoning") return Token.estimate(part.text)
1303
+ if (part.type === "media") return estimateMedia(part.media.mediaType)
1304
+ if (part.type === "tool-call") return Token.estimate(part.name + (JSON.stringify(part.input) ?? ""))
1305
+
1306
+ if (part.result.type === "content")
1307
+ return part.result.value.reduce(
1308
+ (sum, content) => sum + (content.type === "text" ? Token.estimate(content.text) : estimateMedia(content.mime)),
1309
+ 0,
1310
+ )
1311
+ const value = part.result.value
1312
+ return Token.estimate(typeof value === "string" ? value : (JSON.stringify(value) ?? ""))
1313
+ }
1314
+
1315
+ const estimateMedia = (mime: string) => {
1316
+ const type = mime.toLowerCase()
1317
+ if (type.startsWith("image/")) return IMAGE_TOKEN_ESTIMATE
1318
+ if (type === "application/pdf") return PDF_TOKEN_ESTIMATE
1319
+ return 0
1320
+ }