@pi-unipi/unipi 3.0.0-alpha.2 → 3.0.0-alpha.21

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 (359) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +8 -11
  3. package/docs/prefix-cache-architecture.md +14 -0
  4. package/package.json +22 -24
  5. package/packages/ask-user/README.md +55 -107
  6. package/packages/ask-user/ask-ui.ts +306 -732
  7. package/packages/ask-user/clipboard.ts +50 -0
  8. package/packages/ask-user/config.ts +74 -78
  9. package/packages/ask-user/package.json +2 -2
  10. package/packages/ask-user/questions.ts +151 -0
  11. package/packages/ask-user/skills/ask-user/SKILL.md +59 -133
  12. package/packages/ask-user/tools.ts +198 -432
  13. package/packages/autocomplete/package.json +1 -1
  14. package/packages/autocomplete/src/constants.ts +38 -43
  15. package/packages/autocomplete/src/sorting.ts +8 -0
  16. package/packages/background-tasks/package.json +2 -2
  17. package/packages/background-tasks/src/config.ts +0 -73
  18. package/packages/background-tasks/src/index.ts +20 -16
  19. package/packages/background-tasks/src/registry.ts +1 -171
  20. package/packages/background-tasks/src/types.ts +0 -32
  21. package/packages/btw/README.md +13 -56
  22. package/packages/btw/extensions/btw.ts +403 -1796
  23. package/packages/btw/package.json +5 -2
  24. package/packages/btw/skills/btw/SKILL.md +7 -143
  25. package/packages/compactor/README.md +56 -287
  26. package/packages/compactor/package.json +5 -9
  27. package/packages/compactor/skills/compactor/SKILL.md +13 -20
  28. package/packages/compactor/src/card.ts +90 -0
  29. package/packages/compactor/src/commands/index.ts +73 -130
  30. package/packages/compactor/src/compaction/compact-args.ts +5 -3
  31. package/packages/compactor/src/compaction/filter-noise.ts +1 -1
  32. package/packages/compactor/src/compaction/hooks.ts +487 -311
  33. package/packages/compactor/src/compaction/source.ts +178 -0
  34. package/packages/compactor/src/compaction/summarize.ts +586 -52
  35. package/packages/compactor/src/config/manager.ts +130 -127
  36. package/packages/compactor/src/config/schema.ts +32 -48
  37. package/packages/compactor/src/index.ts +40 -431
  38. package/packages/compactor/src/info-screen.ts +44 -190
  39. package/packages/compactor/src/session/recall-blocks.ts +1 -1
  40. package/packages/compactor/src/stats.ts +76 -0
  41. package/packages/compactor/src/tools/context-budget.ts +17 -34
  42. package/packages/compactor/src/tools/ctx-doctor.ts +45 -36
  43. package/packages/compactor/src/tools/register.ts +29 -269
  44. package/packages/compactor/src/types.ts +47 -186
  45. package/packages/core/README.md +25 -0
  46. package/packages/core/child-agent.ts +1 -0
  47. package/packages/core/command-echo.ts +63 -0
  48. package/packages/core/compaction-context.ts +41 -0
  49. package/packages/core/constants.ts +8 -38
  50. package/packages/core/events.ts +0 -53
  51. package/packages/core/fusion-status.ts +4 -0
  52. package/packages/core/global.d.ts +10 -0
  53. package/packages/core/harness-messages.ts +392 -0
  54. package/packages/core/index.ts +14 -0
  55. package/packages/core/kanboard-status.ts +49 -0
  56. package/packages/core/long-horizon-owner-status.ts +46 -0
  57. package/packages/core/model-cache.ts +81 -7
  58. package/packages/core/package.json +6 -3
  59. package/packages/core/src/attach/detect.ts +163 -0
  60. package/packages/core/src/child-agent/child-args.ts +31 -0
  61. package/packages/core/src/child-agent/delivery.ts +41 -0
  62. package/packages/core/src/child-agent/index.ts +5 -0
  63. package/packages/core/src/child-agent/readers.ts +203 -0
  64. package/packages/core/src/child-agent/runtime.ts +584 -0
  65. package/packages/core/src/evidence.ts +78 -0
  66. package/packages/core/src/hints/browser.ts +278 -0
  67. package/packages/core/src/hints/crab-data.ts +19 -0
  68. package/packages/core/src/hints/index.ts +865 -0
  69. package/packages/core/src/hints/lines.ts +607 -0
  70. package/packages/core/src/hints/store.ts +120 -0
  71. package/packages/core/src/jev/chatter.ts +24 -0
  72. package/packages/core/src/jev/settings.ts +177 -14
  73. package/packages/core/src/package-colors.ts +2 -0
  74. package/packages/core/src/settings/catalog.ts +39 -15
  75. package/packages/core/src/settings/engine.ts +48 -2
  76. package/packages/core/src/settings/hub.ts +83 -20
  77. package/packages/core/src/settings/open.ts +49 -0
  78. package/packages/core/src/settings/schema.ts +27 -7
  79. package/packages/core/src/tui/hub-kit.ts +18 -5
  80. package/packages/core/src/tui/kit.ts +198 -0
  81. package/packages/core/src/tui/progress.ts +73 -0
  82. package/packages/core/src/turn/arbiter.ts +290 -0
  83. package/packages/footer/README.md +4 -6
  84. package/packages/footer/package.json +3 -3
  85. package/packages/footer/src/glance-editor.ts +19 -11
  86. package/packages/footer/src/help.ts +1 -1
  87. package/packages/footer/src/index.ts +36 -3
  88. package/packages/footer/src/presets.ts +3 -4
  89. package/packages/footer/src/rendering/icons.ts +0 -20
  90. package/packages/footer/src/segments/compactor.ts +52 -142
  91. package/packages/footer/src/segments/status-ext.ts +0 -1
  92. package/packages/fusion/README.md +14 -4
  93. package/packages/fusion/package.json +4 -3
  94. package/packages/fusion/src/child-args.ts +1 -0
  95. package/packages/fusion/src/index.ts +161 -8
  96. package/packages/fusion/src/pi-settings.ts +57 -0
  97. package/packages/fusion/src/picker.ts +186 -51
  98. package/packages/fusion/src/preset.ts +56 -2
  99. package/packages/fusion/src/prompts.ts +1 -1
  100. package/packages/fusion/src/sidekick-runtime.ts +1 -420
  101. package/packages/fusion/src/tools.ts +107 -128
  102. package/packages/fusion/src/transcript.ts +27 -85
  103. package/packages/info-screen/package.json +2 -2
  104. package/packages/input-shortcuts/README.md +18 -30
  105. package/packages/input-shortcuts/package.json +2 -2
  106. package/packages/input-shortcuts/src/burst.ts +88 -0
  107. package/packages/input-shortcuts/src/chord-overlay.ts +20 -70
  108. package/packages/input-shortcuts/src/cleared-input.ts +97 -0
  109. package/packages/input-shortcuts/src/index.ts +99 -193
  110. package/packages/input-shortcuts/src/last-response.ts +40 -0
  111. package/packages/input-shortcuts/src/registers.ts +8 -23
  112. package/packages/input-shortcuts/src/types.ts +4 -16
  113. package/packages/input-shortcuts/src/undo-redo.ts +59 -47
  114. package/packages/kanboard/README.md +51 -47
  115. package/packages/kanboard/index.ts +293 -55
  116. package/packages/kanboard/package.json +8 -8
  117. package/packages/kanboard/skills/kanboard/SKILL.md +61 -27
  118. package/packages/kanboard/src/badges.ts +93 -0
  119. package/packages/kanboard/src/bin.ts +4 -2
  120. package/packages/kanboard/src/commands.ts +218 -84
  121. package/packages/kanboard/src/debug.ts +20 -0
  122. package/packages/kanboard/src/guard.ts +267 -109
  123. package/packages/kanboard/src/monitor.ts +330 -0
  124. package/packages/kanboard/src/notice-buffer.ts +74 -0
  125. package/packages/kanboard/src/progress.ts +27 -0
  126. package/packages/kanboard/src/reminders.ts +234 -0
  127. package/packages/kanboard/src/settings.ts +69 -15
  128. package/packages/kanboard/src/shapes.ts +5 -0
  129. package/packages/long-horizon/index.ts +190 -13
  130. package/packages/long-horizon/package.json +3 -3
  131. package/packages/long-horizon/src/commands.ts +103 -7
  132. package/packages/long-horizon/src/compaction-brief.ts +35 -0
  133. package/packages/long-horizon/src/engine/continuation.ts +84 -15
  134. package/packages/long-horizon/src/engine/goal-state.ts +64 -13
  135. package/packages/long-horizon/src/engine/nudge-stash.ts +71 -0
  136. package/packages/long-horizon/src/engine/ralph.ts +3 -2
  137. package/packages/long-horizon/src/engine/runaway.ts +68 -11
  138. package/packages/long-horizon/src/engine/verifier.ts +19 -0
  139. package/packages/long-horizon/src/gate.ts +37 -12
  140. package/packages/long-horizon/src/judge/resolve.ts +1 -0
  141. package/packages/long-horizon/src/owner.ts +35 -2
  142. package/packages/long-horizon/src/progress.ts +87 -0
  143. package/packages/long-horizon/src/prompts/goal.ts +1 -1
  144. package/packages/long-horizon/src/runtime.ts +172 -18
  145. package/packages/long-horizon/src/settings.ts +54 -39
  146. package/packages/long-horizon/src/tools/goal.ts +6 -0
  147. package/packages/long-horizon/src/tools/graph.ts +1 -1
  148. package/packages/long-horizon/src/tools/swarm.ts +3 -3
  149. package/packages/mcp/package.json +2 -2
  150. package/packages/memory/commands.ts +7 -2
  151. package/packages/memory/index.ts +210 -32
  152. package/packages/memory/package.json +3 -3
  153. package/packages/memory/save-session.ts +264 -0
  154. package/packages/memory/settings.ts +17 -0
  155. package/packages/memory/tools.ts +253 -203
  156. package/packages/notify/package.json +2 -2
  157. package/packages/skill-registry/README.md +53 -16
  158. package/packages/skill-registry/index.ts +230 -0
  159. package/packages/skill-registry/package.json +19 -8
  160. package/packages/skill-registry/src/editor.ts +206 -0
  161. package/packages/skill-registry/src/judge.ts +289 -0
  162. package/packages/skill-registry/src/registry.ts +87 -0
  163. package/packages/skill-registry/src/settings.ts +259 -0
  164. package/packages/skill-registry/src/vault.ts +80 -0
  165. package/packages/subagents/README.md +39 -119
  166. package/packages/subagents/package.json +6 -13
  167. package/packages/subagents/skills/subagents/SKILL.md +18 -42
  168. package/packages/subagents/src/agents.ts +213 -0
  169. package/packages/subagents/src/cards.ts +182 -0
  170. package/packages/subagents/src/index.ts +609 -1084
  171. package/packages/subagents/src/manager.ts +429 -0
  172. package/packages/subagents/src/profiles.ts +130 -0
  173. package/packages/subagents/src/transcript.ts +154 -0
  174. package/packages/subagents/src/ui.ts +389 -0
  175. package/packages/unipi/bundled.js +39756 -45569
  176. package/packages/unipi/index.ts +55 -10
  177. package/packages/updater/package.json +2 -2
  178. package/packages/utility/README.md +76 -69
  179. package/packages/utility/package.json +2 -2
  180. package/packages/utility/skills/image/SKILL.md +37 -0
  181. package/packages/utility/skills/utility/SKILL.md +17 -60
  182. package/packages/utility/src/answer/extract.ts +128 -0
  183. package/packages/utility/src/answer/index.ts +213 -0
  184. package/packages/utility/src/answer/reply.ts +133 -0
  185. package/packages/utility/src/answer/web.ts +167 -0
  186. package/packages/utility/src/attach/index.ts +205 -0
  187. package/packages/utility/src/commands.ts +38 -142
  188. package/packages/utility/src/diagnostics/engine.ts +50 -5
  189. package/packages/utility/src/image/index.ts +33 -0
  190. package/packages/utility/src/image/models.ts +221 -0
  191. package/packages/{image/src → utility/src/image}/recognize.ts +2 -2
  192. package/packages/utility/src/image/settings.ts +178 -0
  193. package/packages/{image/src/image-source.ts → utility/src/image/source.ts} +1 -1
  194. package/packages/utility/src/image/tools.ts +168 -0
  195. package/packages/utility/src/image/transports.ts +186 -0
  196. package/packages/utility/src/index.ts +68 -389
  197. package/packages/utility/src/lifecycle/cleanup.ts +116 -311
  198. package/packages/utility/src/rename/gate.ts +102 -0
  199. package/packages/utility/src/rename/index.ts +191 -0
  200. package/packages/utility/src/rename/session.ts +170 -0
  201. package/packages/utility/src/render/delegated.ts +285 -0
  202. package/packages/utility/src/render/harness.ts +683 -0
  203. package/packages/utility/src/render/parse.ts +156 -0
  204. package/packages/utility/src/render/pi-settings.ts +38 -0
  205. package/packages/utility/src/render/reply-bg.ts +307 -0
  206. package/packages/utility/src/render/simple.ts +724 -0
  207. package/packages/utility/src/render/spacing.ts +235 -0
  208. package/packages/utility/src/render/styled.ts +251 -0
  209. package/packages/utility/src/render/tools.ts +353 -0
  210. package/packages/utility/src/settings.ts +166 -233
  211. package/packages/utility/src/types.ts +1 -222
  212. package/packages/watchdog/index.ts +17 -6
  213. package/packages/watchdog/package.json +3 -3
  214. package/packages/watchdog/src/config.ts +3 -2
  215. package/packages/web-api/package.json +2 -2
  216. package/packages/workflow/README.md +3 -0
  217. package/packages/workflow/index.ts +0 -2
  218. package/packages/workflow/package.json +2 -2
  219. package/packages/workflow/src/permission/decide.ts +6 -4
  220. package/packages/workflow/src/permission/index.ts +17 -7
  221. package/packages/workflow/src/permission/settings.ts +39 -4
  222. package/packages/workflow/src/plan/index.ts +19 -4
  223. package/packages/background-tasks/extensions/delegate-child.ts +0 -1
  224. package/packages/background-tasks/src/context-parent-snapshot.ts +0 -142
  225. package/packages/background-tasks/src/context-token-budget.ts +0 -903
  226. package/packages/background-tasks/src/context-visible-conversation-v2.ts +0 -551
  227. package/packages/background-tasks/src/delegate/artifacts.ts +0 -487
  228. package/packages/background-tasks/src/delegate/budget.ts +0 -415
  229. package/packages/background-tasks/src/delegate/hook-contract-evidence.json +0 -18
  230. package/packages/background-tasks/src/delegate/hook-contract.ts +0 -154
  231. package/packages/background-tasks/src/delegate/launch.ts +0 -484
  232. package/packages/background-tasks/src/delegate/result-package.ts +0 -459
  233. package/packages/background-tasks/src/delegate/runner.ts +0 -430
  234. package/packages/background-tasks/src/delegate/seed.ts +0 -423
  235. package/packages/background-tasks/src/delegate/types.ts +0 -323
  236. package/packages/background-tasks/src/delegate-child-extension.ts +0 -978
  237. package/packages/background-tasks/src/delegate-extension.ts +0 -654
  238. package/packages/background-tasks/src/fixtures/delegate-context-incident.json +0 -17
  239. package/packages/compactor/skills/compactor-detail/SKILL.md +0 -116
  240. package/packages/compactor/skills/compactor-doctor/SKILL.md +0 -71
  241. package/packages/compactor/skills/compactor-stats/SKILL.md +0 -51
  242. package/packages/compactor/src/compaction/build-sections.ts +0 -76
  243. package/packages/compactor/src/compaction/extract/goals.ts +0 -36
  244. package/packages/compactor/src/compaction/extract/preferences.ts +0 -40
  245. package/packages/compactor/src/compaction/format.ts +0 -53
  246. package/packages/compactor/src/compaction/merge.ts +0 -143
  247. package/packages/compactor/src/config/presets.ts +0 -160
  248. package/packages/compactor/src/executor/executor.ts +0 -233
  249. package/packages/compactor/src/executor/runtime.ts +0 -115
  250. package/packages/compactor/src/security/evaluator.ts +0 -89
  251. package/packages/compactor/src/security/policy.ts +0 -96
  252. package/packages/compactor/src/security/scanner.ts +0 -65
  253. package/packages/compactor/src/session/auto-inject.ts +0 -60
  254. package/packages/compactor/src/session/db.ts +0 -325
  255. package/packages/compactor/src/session/extract.ts +0 -144
  256. package/packages/compactor/src/session/resume-inject.ts +0 -64
  257. package/packages/compactor/src/session/snapshot.ts +0 -327
  258. package/packages/compactor/src/tools/ctx-batch-execute.ts +0 -41
  259. package/packages/compactor/src/tools/ctx-execute-file.ts +0 -23
  260. package/packages/compactor/src/tools/ctx-execute.ts +0 -23
  261. package/packages/compactor/src/tools/ctx-stats.ts +0 -96
  262. package/packages/image/README.md +0 -99
  263. package/packages/image/package.json +0 -61
  264. package/packages/image/skills/image/SKILL.md +0 -76
  265. package/packages/image/src/generate.ts +0 -256
  266. package/packages/image/src/index.ts +0 -135
  267. package/packages/image/src/models.ts +0 -519
  268. package/packages/image/src/openai-images-api.ts +0 -282
  269. package/packages/image/src/register-providers.ts +0 -209
  270. package/packages/image/src/settings.ts +0 -173
  271. package/packages/image/src/tools.ts +0 -326
  272. package/packages/input-shortcuts/src/clipboard.ts +0 -119
  273. package/packages/kanboard/src/runner.ts +0 -817
  274. package/packages/skill-registry/skills/auto/SKILL.md +0 -465
  275. package/packages/skill-registry/skills/brainstorm/SKILL.md +0 -219
  276. package/packages/skill-registry/skills/chore-create/SKILL.md +0 -315
  277. package/packages/skill-registry/skills/chore-execute/SKILL.md +0 -314
  278. package/packages/skill-registry/skills/consolidate/SKILL.md +0 -142
  279. package/packages/skill-registry/skills/consultant/SKILL.md +0 -97
  280. package/packages/skill-registry/skills/debug/SKILL.md +0 -228
  281. package/packages/skill-registry/skills/document/SKILL.md +0 -120
  282. package/packages/skill-registry/skills/fix/SKILL.md +0 -212
  283. package/packages/skill-registry/skills/gather-context/SKILL.md +0 -145
  284. package/packages/skill-registry/skills/plan/SKILL.md +0 -231
  285. package/packages/skill-registry/skills/quick-fix/SKILL.md +0 -135
  286. package/packages/skill-registry/skills/quick-work/SKILL.md +0 -110
  287. package/packages/skill-registry/skills/research/SKILL.md +0 -251
  288. package/packages/skill-registry/skills/review-work/SKILL.md +0 -187
  289. package/packages/skill-registry/skills/scan-issues/SKILL.md +0 -195
  290. package/packages/skill-registry/skills/work/SKILL.md +0 -218
  291. package/packages/skill-registry/skills/worktree-create/SKILL.md +0 -69
  292. package/packages/skill-registry/skills/worktree-list/SKILL.md +0 -78
  293. package/packages/skill-registry/skills/worktree-merge/SKILL.md +0 -89
  294. package/packages/subagents/agents/delegate.md +0 -14
  295. package/packages/subagents/agents/oracle.md +0 -78
  296. package/packages/subagents/agents/researcher.md +0 -52
  297. package/packages/subagents/agents/reviewer.md +0 -80
  298. package/packages/subagents/agents/scout.md +0 -50
  299. package/packages/subagents/agents/worker.md +0 -59
  300. package/packages/subagents/prompts/council.md +0 -48
  301. package/packages/subagents/prompts/gather-context-and-clarify.md +0 -13
  302. package/packages/subagents/prompts/parallel-cleanup.md +0 -59
  303. package/packages/subagents/prompts/parallel-research.md +0 -50
  304. package/packages/subagents/prompts/parallel-review.md +0 -54
  305. package/packages/subagents/prompts/review-loop.md +0 -43
  306. package/packages/subagents/skills/council-mode/SKILL.md +0 -230
  307. package/packages/subagents/skills/subagents/references/constraints-and-recipes.md +0 -259
  308. package/packages/subagents/skills/subagents/references/execution-controls.md +0 -454
  309. package/packages/subagents/skills/subagents/references/management-authoring-rpc.md +0 -161
  310. package/packages/subagents/skills/subagents/references/multi-lane-orchestration.md +0 -39
  311. package/packages/subagents/skills/subagents/references/prompting-and-roles.md +0 -267
  312. package/packages/subagents/src/acceptance.ts +0 -331
  313. package/packages/subagents/src/agent-manager.ts +0 -405
  314. package/packages/subagents/src/agent-memory.ts +0 -300
  315. package/packages/subagents/src/agent-overrides.ts +0 -183
  316. package/packages/subagents/src/agent-runner.ts +0 -271
  317. package/packages/subagents/src/async-runner.ts +0 -422
  318. package/packages/subagents/src/authority-policy.ts +0 -47
  319. package/packages/subagents/src/budgets.ts +0 -285
  320. package/packages/subagents/src/child-safety.ts +0 -140
  321. package/packages/subagents/src/config.ts +0 -249
  322. package/packages/subagents/src/conversation-viewer.ts +0 -281
  323. package/packages/subagents/src/core-compat.ts +0 -94
  324. package/packages/subagents/src/custom-agents.ts +0 -343
  325. package/packages/subagents/src/file-system-retry.ts +0 -50
  326. package/packages/subagents/src/fleet-data.ts +0 -105
  327. package/packages/subagents/src/fleet-view.ts +0 -322
  328. package/packages/subagents/src/foreground-detach.ts +0 -59
  329. package/packages/subagents/src/fork-context.ts +0 -285
  330. package/packages/subagents/src/global.d.ts +0 -7
  331. package/packages/subagents/src/guide.ts +0 -129
  332. package/packages/subagents/src/mission-state.ts +0 -133
  333. package/packages/subagents/src/mission-store.ts +0 -436
  334. package/packages/subagents/src/output-limits.ts +0 -142
  335. package/packages/subagents/src/parity-types.ts +0 -315
  336. package/packages/subagents/src/pi-args.ts +0 -167
  337. package/packages/subagents/src/result-files.ts +0 -232
  338. package/packages/subagents/src/result-watcher.ts +0 -221
  339. package/packages/subagents/src/retained-children.ts +0 -176
  340. package/packages/subagents/src/run-fanout-budget.ts +0 -356
  341. package/packages/subagents/src/scheduled-runs.ts +0 -349
  342. package/packages/subagents/src/schemas.ts +0 -263
  343. package/packages/subagents/src/slash-commands.ts +0 -80
  344. package/packages/subagents/src/supervisor-channel.ts +0 -249
  345. package/packages/subagents/src/tool-handler.ts +0 -1144
  346. package/packages/subagents/src/types.ts +0 -238
  347. package/packages/subagents/src/widget.ts +0 -457
  348. package/packages/subagents/src/workflow-script.ts +0 -737
  349. package/packages/subagents/src/workflow-worker.ts +0 -384
  350. package/packages/subagents/src/worktree.ts +0 -614
  351. package/packages/utility/src/analytics/collector.ts +0 -293
  352. package/packages/utility/src/info-screen.ts +0 -80
  353. package/packages/utility/src/lifecycle/process.ts +0 -162
  354. package/packages/utility/src/prefix-cache.ts +0 -263
  355. package/packages/utility/src/skill-discovery.ts +0 -542
  356. package/packages/utility/src/tools/env.ts +0 -113
  357. package/packages/utility/src/tui/name-badge-state.ts +0 -315
  358. package/packages/utility/src/tui/name-badge.ts +0 -109
  359. /package/packages/{subagents/src → core/src/child-agent}/pi-spawn.ts +0 -0
@@ -1,903 +0,0 @@
1
- /**
2
- * Shared, dependency-free size arithmetic for prompt budgeting.
3
- *
4
- * Fusion and delegate both use the same pure estimator, but they pass distinct
5
- * scope profiles. Fusion may use a calibrated family rate only for measured
6
- * large prompts that remain in the calibration domain. Delegate uses a stricter
7
- * byte-ceiling profile because its 8,192-token floor is too small for relaxed
8
- * rates.
9
- *
10
- * Calibration basis: 882 real large Fusion prompts. The observed floors are
11
- * 2.047 B/tok for Anthropic and 3.400 B/tok for Codex. The shipped rates apply
12
- * a 15% haircut and add a provisional 512-token affine intercept. The
13
- * low-whitespace gate below is a corpus-derived heuristic proxy for dense ASCII
14
- * token density; it is not a tokenizer bound or guarantee.
15
- */
16
-
17
- export const TOKEN_BUDGET_CALIBRATION_VERSION =
18
- 'pi-background-tasks.input-token-calibration.v1' as const;
19
- export const TOKEN_BUDGET_RATE_SCALE = 100;
20
- export const TOKEN_BUDGET_PROVENANCE_SCALE = 1000;
21
- export const TOKEN_BUDGET_HAIRCUT_BASIS_POINTS = 1500;
22
- export const TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES = 50 * 1024;
23
- export const TOKEN_BUDGET_CONSERVATIVE_RATE_X100 = 200;
24
- export const TOKEN_BUDGET_PROVABLE_RATE_X100 = 100;
25
- export const TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100 = TOKEN_BUDGET_PROVABLE_RATE_X100;
26
- export const TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100 = TOKEN_BUDGET_CONSERVATIVE_RATE_X100;
27
- export const TOKEN_BUDGET_AFFINE_F_TOKENS = 512;
28
- export const TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE = 10_000;
29
- /**
30
- * Floor of the observed large-prompt calibration corpus, scaled by
31
- * TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE and rounded down. The gate threshold is
32
- * deliberately below this value; it catches near-zero-whitespace OOD payloads
33
- * without claiming to bound tokenizer density.
34
- */
35
- export const TOKEN_BUDGET_CALIBRATION_CORPUS_MIN_WHITESPACE_FRACTION_X10000 = 18;
36
- export const TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000 = 10;
37
-
38
- export const TOKEN_BUDGET_FAMILIES = ['anthropic', 'openai-codex', 'unknown'] as const;
39
- export type TokenBudgetFamily = (typeof TOKEN_BUDGET_FAMILIES)[number];
40
-
41
- export const TOKEN_BUDGET_SEGMENT_KINDS = [
42
- 'known_text',
43
- 'known_json',
44
- 'unknown_output_contract',
45
- ] as const;
46
- export type TokenBudgetSegmentKind = (typeof TOKEN_BUDGET_SEGMENT_KINDS)[number];
47
-
48
- export type TokenBudgetEstimatorScope =
49
- | 'fusion'
50
- | 'delegate_launch'
51
- | 'delegate'
52
- | 'conservative';
53
- export type TokenBudgetDominantByteClass =
54
- | 'normal'
55
- | 'dense_ascii'
56
- | 'multibyte'
57
- | 'unknown_output_contract';
58
-
59
- export interface TokenBudgetCalibrationProvenance {
60
- n: number;
61
- observed_min_bpt_x1000: number | null;
62
- median_bpt_x1000: number | null;
63
- max_bpt_x1000: number | null;
64
- corpus_sha256: string | null;
65
- corpus_date: string;
66
- haircut_basis_points: number;
67
- backed: boolean;
68
- byte_level_bpe: boolean;
69
- }
70
-
71
- export interface TokenBudgetFamilyCalibration {
72
- family: TokenBudgetFamily;
73
- rate_bytes_per_token_x100: number;
74
- affine_f_tokens: number;
75
- provenance: TokenBudgetCalibrationProvenance;
76
- }
77
-
78
- const ANTHROPIC_PROVENANCE: TokenBudgetCalibrationProvenance = Object.freeze({
79
- n: 85,
80
- observed_min_bpt_x1000: 2047,
81
- median_bpt_x1000: 2217,
82
- max_bpt_x1000: 2481,
83
- corpus_sha256: 'sha256:large-fusion-prompts-2026-08-02',
84
- corpus_date: '2026-08-02',
85
- haircut_basis_points: TOKEN_BUDGET_HAIRCUT_BASIS_POINTS,
86
- backed: true,
87
- byte_level_bpe: true,
88
- });
89
-
90
- const OPENAI_CODEX_PROVENANCE: TokenBudgetCalibrationProvenance = Object.freeze({
91
- n: 797,
92
- observed_min_bpt_x1000: 3400,
93
- median_bpt_x1000: 3721,
94
- max_bpt_x1000: 4526,
95
- corpus_sha256: 'sha256:large-fusion-prompts-2026-08-02',
96
- corpus_date: '2026-08-02',
97
- haircut_basis_points: TOKEN_BUDGET_HAIRCUT_BASIS_POINTS,
98
- backed: true,
99
- byte_level_bpe: true,
100
- });
101
-
102
- const UNKNOWN_PROVENANCE: TokenBudgetCalibrationProvenance = Object.freeze({
103
- n: 0,
104
- observed_min_bpt_x1000: null,
105
- median_bpt_x1000: null,
106
- max_bpt_x1000: null,
107
- corpus_sha256: null,
108
- corpus_date: 'unbacked',
109
- haircut_basis_points: TOKEN_BUDGET_HAIRCUT_BASIS_POINTS,
110
- backed: false,
111
- byte_level_bpe: true,
112
- });
113
-
114
- export const TOKEN_BUDGET_FAMILY_CALIBRATIONS: Readonly<
115
- Record<TokenBudgetFamily, TokenBudgetFamilyCalibration>
116
- > = Object.freeze({
117
- anthropic: Object.freeze({
118
- family: 'anthropic',
119
- rate_bytes_per_token_x100: 173,
120
- affine_f_tokens: TOKEN_BUDGET_AFFINE_F_TOKENS,
121
- provenance: ANTHROPIC_PROVENANCE,
122
- }),
123
- 'openai-codex': Object.freeze({
124
- family: 'openai-codex',
125
- rate_bytes_per_token_x100: 289,
126
- affine_f_tokens: TOKEN_BUDGET_AFFINE_F_TOKENS,
127
- provenance: OPENAI_CODEX_PROVENANCE,
128
- }),
129
- unknown: Object.freeze({
130
- family: 'unknown',
131
- rate_bytes_per_token_x100: 100,
132
- affine_f_tokens: TOKEN_BUDGET_AFFINE_F_TOKENS,
133
- provenance: UNKNOWN_PROVENANCE,
134
- }),
135
- });
136
-
137
- const MODEL_OVERRIDES: Readonly<Record<string, TokenBudgetFamily>> = Object.freeze({
138
- 'anthropic/claude-opus-5': 'anthropic',
139
- 'anthropic/claude-fable-5': 'anthropic',
140
- 'openai-codex/gpt-5.6-sol': 'openai-codex',
141
- 'openai-codex/gpt-5.6-terra': 'openai-codex',
142
- 'openai-codex/gpt-5.5': 'openai-codex',
143
- 'openai-codex/gpt-5.4-mini': 'openai-codex',
144
- });
145
- const PROVIDER_DEFAULTS: Readonly<Record<string, TokenBudgetFamily>> = Object.freeze({
146
- anthropic: 'anthropic',
147
- 'openai-codex': 'openai-codex',
148
- });
149
-
150
- export interface TokenBudgetRouteLike {
151
- provider: string;
152
- model: string;
153
- }
154
-
155
- export interface ResolvedTokenBudgetFamily {
156
- family: TokenBudgetFamily;
157
- provider: string;
158
- model: string;
159
- qualified_id: string;
160
- backed: boolean;
161
- resolution: 'model_override' | 'known_provider_unbacked_model' | 'unknown_provider_floor';
162
- }
163
-
164
- export function resolveTokenBudgetFamily(route: TokenBudgetRouteLike): ResolvedTokenBudgetFamily {
165
- const qualified = `${route.provider}/${route.model}`;
166
- const overridden = MODEL_OVERRIDES[qualified];
167
- if (overridden !== undefined) {
168
- return {
169
- family: overridden,
170
- provider: route.provider,
171
- model: route.model,
172
- qualified_id: qualified,
173
- backed: true,
174
- resolution: 'model_override',
175
- };
176
- }
177
- const providerDefault = PROVIDER_DEFAULTS[route.provider];
178
- if (providerDefault !== undefined) {
179
- return {
180
- family: providerDefault,
181
- provider: route.provider,
182
- model: route.model,
183
- qualified_id: qualified,
184
- backed: false,
185
- resolution: 'known_provider_unbacked_model',
186
- };
187
- }
188
- return {
189
- family: 'unknown',
190
- provider: route.provider,
191
- model: route.model,
192
- qualified_id: qualified,
193
- backed: false,
194
- resolution: 'unknown_provider_floor',
195
- };
196
- }
197
-
198
- export interface TokenBudgetSegment {
199
- kind: TokenBudgetSegmentKind;
200
- bytes: number;
201
- multibyteBytes?: number | undefined;
202
- denseBytes?: number | undefined;
203
- asciiWhitespaceBytes?: number | undefined;
204
- }
205
-
206
- export interface TokenBudgetByteClassBreakdown {
207
- total_bytes: number;
208
- normal_bytes: number;
209
- multibyte_bytes: number;
210
- dense_bytes: number;
211
- unknown_output_contract_bytes: number;
212
- }
213
-
214
- export interface TokenBudgetPromptProfile extends TokenBudgetByteClassBreakdown {
215
- concrete_known_bytes: number;
216
- ascii_whitespace_bytes: number;
217
- whitespace_fraction_x10000: number | null;
218
- whitespace_fraction_scale: typeof TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE;
219
- whitespace_fraction_available: boolean;
220
- dominant_byte_class: TokenBudgetDominantByteClass;
221
- }
222
-
223
- export interface TokenBudgetDenseAsciiGate {
224
- heuristic: 'low_whitespace_fraction_proxy_not_tokenizer_bound';
225
- corpus_min_whitespace_fraction_x10000: number;
226
- threshold_whitespace_fraction_x10000: number;
227
- measured_whitespace_fraction_x10000: number | null;
228
- evaluated: boolean;
229
- out_of_distribution: boolean;
230
- decision: 'not_evaluated' | 'calibrated_allowed' | 'conservative_fallback';
231
- reason: 'prompt_below_large_prompt_floor' | 'multibyte_or_non_ascii_dominant' | 'whitespace_fraction_unavailable' | 'below_threshold' | 'at_or_above_threshold' | null;
232
- }
233
-
234
- export interface TokenBudgetRateBucketEstimate {
235
- rate_bytes_per_token_x100: number;
236
- bytes: number;
237
- tokens: number;
238
- byte_classes: readonly TokenBudgetDominantByteClass[];
239
- }
240
-
241
- export interface TokenBudgetAdvisoryEstimate {
242
- multibyte_provable_rate_bytes_per_token_x100: typeof TOKEN_BUDGET_PROVABLE_RATE_X100;
243
- multibyte_provable_tokens: number;
244
- input_tokens_if_multibyte_used_provable_ceiling: number;
245
- rate_buckets: readonly TokenBudgetRateBucketEstimate[];
246
- }
247
-
248
- export interface TokenBudgetPerSegmentEstimate extends TokenBudgetByteClassBreakdown {
249
- kind: TokenBudgetSegmentKind;
250
- ascii_whitespace_bytes: number;
251
- normal_rate_bytes_per_token_x100: number;
252
- normal_tokens: number;
253
- multibyte_rate_bytes_per_token_x100: typeof TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100;
254
- multibyte_tokens: number;
255
- multibyte_provable_tokens: number;
256
- dense_tokens: number;
257
- unknown_output_contract_tokens: number;
258
- tokens: number;
259
- }
260
-
261
- export interface TokenBudgetRateSource {
262
- calibration_version: typeof TOKEN_BUDGET_CALIBRATION_VERSION;
263
- family: TokenBudgetFamily;
264
- configured_rate_bytes_per_token_x100: number;
265
- effective_rate_bytes_per_token_x100: number;
266
- conservative_rate_bytes_per_token_x100: number;
267
- delegate_conservative_rate_bytes_per_token_x100: typeof TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100;
268
- affine_f_tokens: number;
269
- scope: TokenBudgetEstimatorScope;
270
- source:
271
- | 'calibrated_large_window'
272
- | 'conservative_small_prompt'
273
- | 'conservative_capacity_guard'
274
- | 'conservative_dense_ascii_whitespace_gate'
275
- | 'delegate_conservative'
276
- | 'explicit_conservative'
277
- | 'unknown_provider_floor'
278
- | 'unbacked_model_floor';
279
- backed: boolean;
280
- provenance: TokenBudgetCalibrationProvenance;
281
- model_resolution: ResolvedTokenBudgetFamily['resolution'] | 'family_direct';
282
- scope_guard_min_bytes: typeof TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES;
283
- calibration_applied: boolean;
284
- prompt_profile: TokenBudgetPromptProfile;
285
- dense_ascii_gate: TokenBudgetDenseAsciiGate;
286
- dominant_byte_class: TokenBudgetDominantByteClass;
287
- warning: string | null;
288
- }
289
-
290
- export interface EstimateInputTokensInput {
291
- family: TokenBudgetFamily;
292
- segments: readonly TokenBudgetSegment[];
293
- allowedInputTokens?: number | undefined;
294
- scope?: TokenBudgetEstimatorScope | undefined;
295
- calibrationBacked?: boolean | undefined;
296
- familyResolution?: ResolvedTokenBudgetFamily['resolution'] | 'family_direct' | undefined;
297
- }
298
-
299
- export interface EstimateInputTokensResult {
300
- tokens: number;
301
- fixed_tokens: number;
302
- perSegment: readonly TokenBudgetPerSegmentEstimate[];
303
- byte_class_breakdown: TokenBudgetByteClassBreakdown;
304
- rate_buckets: readonly TokenBudgetRateBucketEstimate[];
305
- advisory: TokenBudgetAdvisoryEstimate;
306
- rateSource: TokenBudgetRateSource;
307
- }
308
-
309
- function assertSafeNonNegativeInteger(value: number, label: string): void {
310
- if (!Number.isSafeInteger(value) || value < 0) {
311
- throw new TypeError(`${label} must be a non-negative safe integer`);
312
- }
313
- }
314
-
315
- function assertPositiveInteger(value: number, label: string): void {
316
- if (!Number.isSafeInteger(value) || value <= 0) {
317
- throw new TypeError(`${label} must be a positive safe integer`);
318
- }
319
- }
320
-
321
- function calibrationFor(family: TokenBudgetFamily): TokenBudgetFamilyCalibration {
322
- return TOKEN_BUDGET_FAMILY_CALIBRATIONS[family];
323
- }
324
-
325
- function ceilDiv(numerator: number, denominator: number): number {
326
- assertSafeNonNegativeInteger(numerator, 'division numerator');
327
- assertPositiveInteger(denominator, 'division denominator');
328
- if (numerator === 0) return 0;
329
- return Math.floor((numerator - 1) / denominator) + 1;
330
- }
331
-
332
- function tokensAtRate(bytes: number, rateBytesPerTokenX100: number): number {
333
- assertSafeNonNegativeInteger(bytes, 'bytes');
334
- assertPositiveInteger(rateBytesPerTokenX100, 'rateBytesPerTokenX100');
335
- return ceilDiv(bytes * TOKEN_BUDGET_RATE_SCALE, rateBytesPerTokenX100);
336
- }
337
-
338
- function conservativeFusionRate(configured: number): number {
339
- return Math.min(configured, TOKEN_BUDGET_CONSERVATIVE_RATE_X100);
340
- }
341
-
342
- interface NormalizedTokenBudgetSegment {
343
- kind: TokenBudgetSegmentKind;
344
- bytes: number;
345
- multibyteBytes: number;
346
- denseBytes: number;
347
- asciiWhitespaceBytes: number;
348
- whitespaceKnown: boolean;
349
- }
350
-
351
- function normalizeSegment(
352
- segment: TokenBudgetSegment,
353
- index: number,
354
- ): NormalizedTokenBudgetSegment {
355
- assertSafeNonNegativeInteger(segment.bytes, `segments[${String(index)}].bytes`);
356
- const denseBytes = segment.denseBytes ?? 0;
357
- assertSafeNonNegativeInteger(denseBytes, `segments[${String(index)}].denseBytes`);
358
- if (segment.kind === 'unknown_output_contract') {
359
- if (segment.multibyteBytes !== undefined) {
360
- throw new TypeError(
361
- `segments[${String(index)}].multibyteBytes must not be set for unknown_output_contract`,
362
- );
363
- }
364
- if (segment.asciiWhitespaceBytes !== undefined) {
365
- throw new TypeError(
366
- `segments[${String(index)}].asciiWhitespaceBytes must not be set for unknown_output_contract`,
367
- );
368
- }
369
- if (denseBytes !== 0) {
370
- throw new TypeError(
371
- `segments[${String(index)}].denseBytes must be zero for unknown_output_contract`,
372
- );
373
- }
374
- return {
375
- kind: segment.kind,
376
- bytes: segment.bytes,
377
- multibyteBytes: 0,
378
- denseBytes,
379
- asciiWhitespaceBytes: 0,
380
- whitespaceKnown: true,
381
- };
382
- }
383
- if (segment.kind !== 'known_text' && segment.kind !== 'known_json') {
384
- throw new TypeError(`segments[${String(index)}].kind is not supported`);
385
- }
386
- if (segment.multibyteBytes === undefined) {
387
- throw new TypeError(`segments[${String(index)}].multibyteBytes is required`);
388
- }
389
- assertSafeNonNegativeInteger(segment.multibyteBytes, `segments[${String(index)}].multibyteBytes`);
390
- if (segment.multibyteBytes + denseBytes > segment.bytes) {
391
- throw new TypeError(
392
- `segments[${String(index)}] byte classes exceed segment byte length`,
393
- );
394
- }
395
- const whitespaceKnown = segment.asciiWhitespaceBytes !== undefined;
396
- const asciiWhitespaceBytes = segment.asciiWhitespaceBytes ?? 0;
397
- assertSafeNonNegativeInteger(
398
- asciiWhitespaceBytes,
399
- `segments[${String(index)}].asciiWhitespaceBytes`,
400
- );
401
- if (asciiWhitespaceBytes > segment.bytes - segment.multibyteBytes) {
402
- throw new TypeError(
403
- `segments[${String(index)}].asciiWhitespaceBytes exceeds ASCII byte length`,
404
- );
405
- }
406
- return {
407
- kind: segment.kind,
408
- bytes: segment.bytes,
409
- multibyteBytes: segment.multibyteBytes,
410
- denseBytes,
411
- asciiWhitespaceBytes,
412
- whitespaceKnown,
413
- };
414
- }
415
-
416
- function addBreakdown(
417
- target: TokenBudgetByteClassBreakdown,
418
- delta: TokenBudgetByteClassBreakdown,
419
- ): void {
420
- target.total_bytes += delta.total_bytes;
421
- target.normal_bytes += delta.normal_bytes;
422
- target.multibyte_bytes += delta.multibyte_bytes;
423
- target.dense_bytes += delta.dense_bytes;
424
- target.unknown_output_contract_bytes += delta.unknown_output_contract_bytes;
425
- }
426
-
427
- function dominantByteClass(breakdown: TokenBudgetByteClassBreakdown): TokenBudgetDominantByteClass {
428
- const entries: Array<{ byteClass: TokenBudgetDominantByteClass; bytes: number; order: number }> = [
429
- { byteClass: 'dense_ascii', bytes: breakdown.dense_bytes, order: 0 },
430
- { byteClass: 'multibyte', bytes: breakdown.multibyte_bytes, order: 1 },
431
- { byteClass: 'unknown_output_contract', bytes: breakdown.unknown_output_contract_bytes, order: 2 },
432
- { byteClass: 'normal', bytes: breakdown.normal_bytes, order: 3 },
433
- ];
434
- entries.sort((left, right) => right.bytes - left.bytes || left.order - right.order);
435
- return entries[0]?.byteClass ?? 'normal';
436
- }
437
-
438
- function profileForSegments(
439
- segments: readonly NormalizedTokenBudgetSegment[],
440
- breakdown: TokenBudgetByteClassBreakdown,
441
- ): TokenBudgetPromptProfile {
442
- let asciiWhitespaceBytes = 0;
443
- let whitespaceKnown = true;
444
- for (const segment of segments) {
445
- if (segment.kind === 'unknown_output_contract') continue;
446
- asciiWhitespaceBytes += segment.asciiWhitespaceBytes;
447
- if (!segment.whitespaceKnown) whitespaceKnown = false;
448
- }
449
- const concreteKnownBytes = breakdown.total_bytes - breakdown.unknown_output_contract_bytes;
450
- const whitespaceFraction =
451
- whitespaceKnown && concreteKnownBytes > 0
452
- ? Math.floor((asciiWhitespaceBytes * TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE) / concreteKnownBytes)
453
- : null;
454
- return {
455
- ...breakdown,
456
- concrete_known_bytes: concreteKnownBytes,
457
- ascii_whitespace_bytes: asciiWhitespaceBytes,
458
- whitespace_fraction_x10000: whitespaceFraction,
459
- whitespace_fraction_scale: TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE,
460
- whitespace_fraction_available: whitespaceKnown,
461
- dominant_byte_class: dominantByteClass(breakdown),
462
- };
463
- }
464
-
465
- function denseAsciiGate(profile: TokenBudgetPromptProfile): TokenBudgetDenseAsciiGate {
466
- const base = {
467
- heuristic: 'low_whitespace_fraction_proxy_not_tokenizer_bound' as const,
468
- corpus_min_whitespace_fraction_x10000:
469
- TOKEN_BUDGET_CALIBRATION_CORPUS_MIN_WHITESPACE_FRACTION_X10000,
470
- threshold_whitespace_fraction_x10000:
471
- TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000,
472
- measured_whitespace_fraction_x10000: profile.whitespace_fraction_x10000,
473
- };
474
- if (profile.concrete_known_bytes < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES) {
475
- return {
476
- ...base,
477
- evaluated: false,
478
- out_of_distribution: false,
479
- decision: 'not_evaluated',
480
- reason: 'prompt_below_large_prompt_floor',
481
- };
482
- }
483
- if (profile.normal_bytes === 0 || profile.multibyte_bytes > profile.normal_bytes) {
484
- return {
485
- ...base,
486
- evaluated: false,
487
- out_of_distribution: false,
488
- decision: 'not_evaluated',
489
- reason: 'multibyte_or_non_ascii_dominant',
490
- };
491
- }
492
- if (!profile.whitespace_fraction_available || profile.whitespace_fraction_x10000 === null) {
493
- return {
494
- ...base,
495
- evaluated: true,
496
- out_of_distribution: true,
497
- decision: 'conservative_fallback',
498
- reason: 'whitespace_fraction_unavailable',
499
- };
500
- }
501
- if (profile.whitespace_fraction_x10000 < TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000) {
502
- return {
503
- ...base,
504
- evaluated: true,
505
- out_of_distribution: true,
506
- decision: 'conservative_fallback',
507
- reason: 'below_threshold',
508
- };
509
- }
510
- return {
511
- ...base,
512
- evaluated: true,
513
- out_of_distribution: false,
514
- decision: 'calibrated_allowed',
515
- reason: 'at_or_above_threshold',
516
- };
517
- }
518
-
519
- function rateSourceWarning(input: {
520
- source: TokenBudgetRateSource['source'];
521
- family: TokenBudgetFamily;
522
- profile: TokenBudgetPromptProfile;
523
- gate: TokenBudgetDenseAsciiGate;
524
- scope: TokenBudgetEstimatorScope;
525
- }): string | null {
526
- if (input.source === 'unknown_provider_floor') {
527
- return `unknown provider family uses the provable 1.00 B/tok floor; no calibration backs ${input.family}`;
528
- }
529
- if (input.source === 'unbacked_model_floor') {
530
- return `model is not in the exact calibration backing set for family ${input.family}; using the provable 1.00 B/tok floor`;
531
- }
532
- if (input.source === 'delegate_conservative') {
533
- return 'delegate launch/runtime uses the provable 1.00 B/tok profile when the prompt or route is below the backed large-prompt calibration domain';
534
- }
535
- if (input.source === 'explicit_conservative') {
536
- return 'explicit conservative scope uses the provable 1.00 B/tok profile';
537
- }
538
- if (input.source === 'conservative_small_prompt') {
539
- return `calibrated rate withheld because measured prompt bytes ${String(input.profile.concrete_known_bytes)} are below the ${String(TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES)}-byte calibration floor; using conservative profile`;
540
- }
541
- if (input.source === 'conservative_capacity_guard') {
542
- return `calibrated rate withheld because route capacity evaluated at the conservative rate cannot hold the ${String(TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES)}-byte calibration floor`;
543
- }
544
- if (input.source === 'conservative_dense_ascii_whitespace_gate') {
545
- if (input.gate.reason === 'whitespace_fraction_unavailable') {
546
- return 'calibrated rate withheld because known-text whitespace bytes were not supplied; provide asciiWhitespaceBytes from a one-pass UTF-8 measurement to use calibrated rates';
547
- }
548
- return `calibrated rate withheld because whitespace fraction ${String(input.gate.measured_whitespace_fraction_x10000 ?? 0)}/${String(TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE)} is below the dense-ASCII gate ${String(TOKEN_BUDGET_DENSE_ASCII_WHITESPACE_THRESHOLD_X10000)}/${String(TOKEN_BUDGET_WHITESPACE_FRACTION_SCALE)}; this is a heuristic token-density proxy, not a bound`;
549
- }
550
- return null;
551
- }
552
-
553
- function effectiveRateSource(input: {
554
- family: TokenBudgetFamily;
555
- allowedInputTokens: number | undefined;
556
- scope: TokenBudgetEstimatorScope;
557
- profile: TokenBudgetPromptProfile;
558
- calibrationBacked: boolean;
559
- familyResolution: ResolvedTokenBudgetFamily['resolution'] | 'family_direct';
560
- }): TokenBudgetRateSource {
561
- const calibration = calibrationFor(input.family);
562
- const configured = calibration.rate_bytes_per_token_x100;
563
- const familyBacked = calibration.provenance.backed;
564
- const backed = familyBacked && input.calibrationBacked;
565
- const conservativeRate = conservativeFusionRate(configured);
566
- const gate = denseAsciiGate(input.profile);
567
- let source: TokenBudgetRateSource['source'];
568
- let effective: number;
569
- let calibrationApplied = false;
570
-
571
- if (!backed) {
572
- source = input.familyResolution === 'known_provider_unbacked_model'
573
- ? 'unbacked_model_floor'
574
- : 'unknown_provider_floor';
575
- effective = TOKEN_BUDGET_PROVABLE_RATE_X100;
576
- } else if (
577
- input.scope === 'delegate' ||
578
- (input.scope === 'delegate_launch' &&
579
- (input.profile.concrete_known_bytes < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES ||
580
- (input.allowedInputTokens !== undefined &&
581
- Math.floor(
582
- (input.allowedInputTokens * TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100) /
583
- TOKEN_BUDGET_RATE_SCALE,
584
- ) < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES)))
585
- ) {
586
- source = 'delegate_conservative';
587
- effective = Math.min(configured, TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100);
588
- } else if (input.scope === 'conservative') {
589
- source = 'explicit_conservative';
590
- effective = Math.min(configured, TOKEN_BUDGET_PROVABLE_RATE_X100);
591
- } else if (input.profile.concrete_known_bytes < TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES) {
592
- source = 'conservative_small_prompt';
593
- effective = conservativeRate;
594
- } else if (
595
- input.allowedInputTokens !== undefined &&
596
- Math.floor((input.allowedInputTokens * conservativeRate) / TOKEN_BUDGET_RATE_SCALE) <
597
- TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES
598
- ) {
599
- assertSafeNonNegativeInteger(input.allowedInputTokens, 'allowedInputTokens');
600
- source = 'conservative_capacity_guard';
601
- effective = conservativeRate;
602
- } else if (gate.out_of_distribution) {
603
- source = 'conservative_dense_ascii_whitespace_gate';
604
- effective = conservativeRate;
605
- } else {
606
- source = 'calibrated_large_window';
607
- effective = configured;
608
- calibrationApplied = true;
609
- }
610
-
611
- const dominant = gate.out_of_distribution && input.profile.normal_bytes >= input.profile.multibyte_bytes
612
- ? 'dense_ascii'
613
- : input.profile.dominant_byte_class;
614
- const rateSourceInput = {
615
- source,
616
- family: input.family,
617
- profile: input.profile,
618
- gate,
619
- scope: input.scope,
620
- };
621
- return {
622
- calibration_version: TOKEN_BUDGET_CALIBRATION_VERSION,
623
- family: input.family,
624
- configured_rate_bytes_per_token_x100: configured,
625
- effective_rate_bytes_per_token_x100: effective,
626
- conservative_rate_bytes_per_token_x100: conservativeRate,
627
- delegate_conservative_rate_bytes_per_token_x100: TOKEN_BUDGET_DELEGATE_CONSERVATIVE_RATE_X100,
628
- affine_f_tokens: calibration.affine_f_tokens,
629
- scope: input.scope,
630
- source,
631
- backed,
632
- provenance: calibration.provenance,
633
- model_resolution: input.familyResolution,
634
- scope_guard_min_bytes: TOKEN_BUDGET_LARGE_PROMPT_MIN_BYTES,
635
- calibration_applied: calibrationApplied,
636
- prompt_profile: { ...input.profile, dominant_byte_class: dominant },
637
- dense_ascii_gate: gate,
638
- dominant_byte_class: dominant,
639
- warning: rateSourceWarning(rateSourceInput),
640
- };
641
- }
642
-
643
- interface MutableRateBucket {
644
- rate: number;
645
- bytes: number;
646
- classes: TokenBudgetDominantByteClass[];
647
- }
648
-
649
- function addBucket(
650
- buckets: Map<number, MutableRateBucket>,
651
- rate: number,
652
- bytes: number,
653
- byteClass: TokenBudgetDominantByteClass,
654
- ): void {
655
- if (bytes === 0) return;
656
- const existing = buckets.get(rate);
657
- if (existing === undefined) {
658
- buckets.set(rate, { rate, bytes, classes: [byteClass] });
659
- return;
660
- }
661
- existing.bytes += bytes;
662
- if (!existing.classes.includes(byteClass)) existing.classes.push(byteClass);
663
- }
664
-
665
- function finalizeBuckets(buckets: Map<number, MutableRateBucket>): TokenBudgetRateBucketEstimate[] {
666
- return [...buckets.values()]
667
- .sort((left, right) => left.rate - right.rate)
668
- .map((bucket) => ({
669
- rate_bytes_per_token_x100: bucket.rate,
670
- bytes: bucket.bytes,
671
- tokens: tokensAtRate(bucket.bytes, bucket.rate),
672
- byte_classes: [...bucket.classes].sort(),
673
- }));
674
- }
675
-
676
- function bucketTokenTotal(buckets: readonly TokenBudgetRateBucketEstimate[]): number {
677
- return buckets.reduce((sum, bucket) => sum + bucket.tokens, 0);
678
- }
679
-
680
- export function estimateInputTokens(input: EstimateInputTokensInput): EstimateInputTokensResult {
681
- const scope = input.scope ?? 'fusion';
682
- const normalized: NormalizedTokenBudgetSegment[] = [];
683
- const total: TokenBudgetByteClassBreakdown = {
684
- total_bytes: 0,
685
- normal_bytes: 0,
686
- multibyte_bytes: 0,
687
- dense_bytes: 0,
688
- unknown_output_contract_bytes: 0,
689
- };
690
- for (const [index, rawSegment] of input.segments.entries()) {
691
- const segment = normalizeSegment(rawSegment, index);
692
- const unknownBytes = segment.kind === 'unknown_output_contract' ? segment.bytes : 0;
693
- const normalBytes =
694
- segment.kind === 'unknown_output_contract'
695
- ? 0
696
- : segment.bytes - segment.multibyteBytes - segment.denseBytes;
697
- const breakdown: TokenBudgetByteClassBreakdown = {
698
- total_bytes: segment.bytes,
699
- normal_bytes: normalBytes,
700
- multibyte_bytes: segment.multibyteBytes,
701
- dense_bytes: segment.denseBytes,
702
- unknown_output_contract_bytes: unknownBytes,
703
- };
704
- addBreakdown(total, breakdown);
705
- normalized.push(segment);
706
- }
707
- if (input.allowedInputTokens !== undefined) {
708
- assertSafeNonNegativeInteger(input.allowedInputTokens, 'allowedInputTokens');
709
- }
710
- const profile = profileForSegments(normalized, total);
711
- const rateSource = effectiveRateSource({
712
- family: input.family,
713
- allowedInputTokens: input.allowedInputTokens,
714
- scope,
715
- profile,
716
- calibrationBacked: input.calibrationBacked ?? true,
717
- familyResolution: input.familyResolution ?? 'family_direct',
718
- });
719
-
720
- const perSegment: TokenBudgetPerSegmentEstimate[] = [];
721
- const fatalBuckets = new Map<number, MutableRateBucket>();
722
- const advisoryBuckets = new Map<number, MutableRateBucket>();
723
- let multibyteAdvisoryTotal = 0;
724
-
725
- for (const segment of normalized) {
726
- const unknownBytes = segment.kind === 'unknown_output_contract' ? segment.bytes : 0;
727
- const normalBytes =
728
- segment.kind === 'unknown_output_contract'
729
- ? 0
730
- : segment.bytes - segment.multibyteBytes - segment.denseBytes;
731
- const normalRate =
732
- segment.kind === 'unknown_output_contract'
733
- ? TOKEN_BUDGET_PROVABLE_RATE_X100
734
- : rateSource.effective_rate_bytes_per_token_x100;
735
- const normalTokens = tokensAtRate(normalBytes, normalRate);
736
- const unknownTokens = tokensAtRate(unknownBytes, TOKEN_BUDGET_PROVABLE_RATE_X100);
737
- const multibyteTokens = tokensAtRate(segment.multibyteBytes, TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100);
738
- const multibyteProvableTokens = tokensAtRate(segment.multibyteBytes, TOKEN_BUDGET_PROVABLE_RATE_X100);
739
- const denseTokens = tokensAtRate(segment.denseBytes, TOKEN_BUDGET_PROVABLE_RATE_X100);
740
- const tokens = normalTokens + unknownTokens + multibyteTokens + denseTokens;
741
- const breakdown: TokenBudgetByteClassBreakdown = {
742
- total_bytes: segment.bytes,
743
- normal_bytes: normalBytes,
744
- multibyte_bytes: segment.multibyteBytes,
745
- dense_bytes: segment.denseBytes,
746
- unknown_output_contract_bytes: unknownBytes,
747
- };
748
- addBucket(fatalBuckets, normalRate, normalBytes, 'normal');
749
- addBucket(fatalBuckets, TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100, segment.multibyteBytes, 'multibyte');
750
- addBucket(fatalBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, segment.denseBytes, 'dense_ascii');
751
- addBucket(fatalBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, unknownBytes, 'unknown_output_contract');
752
- addBucket(advisoryBuckets, normalRate, normalBytes, 'normal');
753
- addBucket(advisoryBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, segment.multibyteBytes, 'multibyte');
754
- addBucket(advisoryBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, segment.denseBytes, 'dense_ascii');
755
- addBucket(advisoryBuckets, TOKEN_BUDGET_PROVABLE_RATE_X100, unknownBytes, 'unknown_output_contract');
756
- multibyteAdvisoryTotal += multibyteProvableTokens;
757
- perSegment.push({
758
- kind: segment.kind,
759
- ...breakdown,
760
- ascii_whitespace_bytes: segment.asciiWhitespaceBytes,
761
- normal_rate_bytes_per_token_x100: normalRate,
762
- normal_tokens: normalTokens,
763
- multibyte_rate_bytes_per_token_x100: TOKEN_BUDGET_MULTIBYTE_FATAL_RATE_X100,
764
- multibyte_tokens: multibyteTokens,
765
- multibyte_provable_tokens: multibyteProvableTokens,
766
- dense_tokens: denseTokens,
767
- unknown_output_contract_tokens: unknownTokens,
768
- tokens,
769
- });
770
- }
771
- const rateBuckets = finalizeBuckets(fatalBuckets);
772
- const advisoryRateBuckets = finalizeBuckets(advisoryBuckets);
773
- const variableTokenTotal = bucketTokenTotal(rateBuckets);
774
- return {
775
- tokens: variableTokenTotal + rateSource.affine_f_tokens,
776
- fixed_tokens: rateSource.affine_f_tokens,
777
- perSegment,
778
- byte_class_breakdown: total,
779
- rate_buckets: rateBuckets,
780
- advisory: {
781
- multibyte_provable_rate_bytes_per_token_x100: TOKEN_BUDGET_PROVABLE_RATE_X100,
782
- multibyte_provable_tokens: multibyteAdvisoryTotal,
783
- input_tokens_if_multibyte_used_provable_ceiling:
784
- bucketTokenTotal(advisoryRateBuckets) + rateSource.affine_f_tokens,
785
- rate_buckets: advisoryRateBuckets,
786
- },
787
- rateSource,
788
- };
789
- }
790
-
791
- export function utf8ByteLength(value: string): number {
792
- return Buffer.byteLength(value, 'utf8');
793
- }
794
-
795
- function isAsciiWhitespace(byte: number): boolean {
796
- return byte === 0x20 || (byte >= 0x09 && byte <= 0x0d);
797
- }
798
-
799
- export function utf8ByteClassBreakdown(value: string): {
800
- bytes: number;
801
- multibyteBytes: number;
802
- denseBytes: 0;
803
- asciiWhitespaceBytes: number;
804
- } {
805
- const bytes = Buffer.from(value, 'utf8');
806
- let multibyteBytes = 0;
807
- let asciiWhitespaceBytes = 0;
808
- for (const byte of bytes) {
809
- if (byte >= 0x80) multibyteBytes += 1;
810
- else if (isAsciiWhitespace(byte)) asciiWhitespaceBytes += 1;
811
- }
812
- return { bytes: bytes.length, multibyteBytes, denseBytes: 0, asciiWhitespaceBytes };
813
- }
814
-
815
- export function knownTextSegment(value: string): TokenBudgetSegment {
816
- const breakdown = utf8ByteClassBreakdown(value);
817
- return {
818
- kind: 'known_text',
819
- bytes: breakdown.bytes,
820
- multibyteBytes: breakdown.multibyteBytes,
821
- denseBytes: breakdown.denseBytes,
822
- asciiWhitespaceBytes: breakdown.asciiWhitespaceBytes,
823
- };
824
- }
825
-
826
- export function knownJsonSegment(value: string): TokenBudgetSegment {
827
- const breakdown = utf8ByteClassBreakdown(value);
828
- return {
829
- kind: 'known_json',
830
- bytes: breakdown.bytes,
831
- multibyteBytes: breakdown.multibyteBytes,
832
- denseBytes: breakdown.denseBytes,
833
- asciiWhitespaceBytes: breakdown.asciiWhitespaceBytes,
834
- };
835
- }
836
-
837
- export function unknownOutputContractSegment(bytes: number): TokenBudgetSegment {
838
- assertSafeNonNegativeInteger(bytes, 'unknown output contract bytes');
839
- return { kind: 'unknown_output_contract', bytes, denseBytes: 0 };
840
- }
841
-
842
- export function tokenUpperBound(utf8Bytes: number): number {
843
- return estimateInputTokens({
844
- family: 'unknown',
845
- scope: 'conservative',
846
- calibrationBacked: false,
847
- segments: [{ kind: 'known_text', bytes: utf8Bytes, multibyteBytes: 0, denseBytes: 0 }],
848
- }).tokens;
849
- }
850
-
851
- export function maxKnownTextBytesForTokens(input: {
852
- family: TokenBudgetFamily;
853
- allowedInputTokens: number;
854
- scope?: TokenBudgetEstimatorScope | undefined;
855
- calibrationBacked?: boolean | undefined;
856
- familyResolution?: ResolvedTokenBudgetFamily['resolution'] | 'family_direct' | undefined;
857
- }): number {
858
- assertSafeNonNegativeInteger(input.allowedInputTokens, 'allowedInputTokens');
859
- const rate = effectiveRateSource({
860
- family: input.family,
861
- allowedInputTokens: input.allowedInputTokens,
862
- scope: input.scope ?? 'fusion',
863
- profile: profileForSegments([], {
864
- total_bytes: 0,
865
- normal_bytes: 0,
866
- multibyte_bytes: 0,
867
- dense_bytes: 0,
868
- unknown_output_contract_bytes: 0,
869
- }),
870
- calibrationBacked: input.calibrationBacked ?? true,
871
- familyResolution: input.familyResolution ?? 'family_direct',
872
- });
873
- const variableTokens = input.allowedInputTokens - rate.affine_f_tokens;
874
- if (variableTokens <= 0) return 0;
875
- return Math.floor((variableTokens * rate.effective_rate_bytes_per_token_x100) / TOKEN_BUDGET_RATE_SCALE);
876
- }
877
-
878
- export interface RouteReserves {
879
- reservedOutputTokens: number;
880
- framingReserveTokens: number;
881
- safetyReserveTokens: number;
882
- }
883
-
884
- /**
885
- * Usable input tokens for one route.
886
- *
887
- * Returns a signed value. A caller that requires a minimum must check it and
888
- * fail loudly; this helper never clamps, never substitutes a default window, and
889
- * never silently returns zero for an unusable route.
890
- */
891
- export function allowedInputTokens(contextWindowTokens: number, reserves: RouteReserves): number {
892
- return (
893
- contextWindowTokens -
894
- reserves.reservedOutputTokens -
895
- reserves.framingReserveTokens -
896
- reserves.safetyReserveTokens
897
- );
898
- }
899
-
900
- /** True only for a positive, finite, integral context window. */
901
- export function isUsableContextWindow(value: number): boolean {
902
- return Number.isFinite(value) && Number.isInteger(value) && value > 0;
903
- }