@tonyclaw/agent-inspector 4.0.1 → 4.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 (373) hide show
  1. package/.output/backend/nitro.json +1 -1
  2. package/.output/cli.js +193 -110
  3. package/.output/server/_ssr/index.mjs +1 -1
  4. package/.output/server/_ssr/{router-CTHqmroT.mjs → router-ChILzhmz.mjs} +92 -4
  5. package/.output/server/index.mjs +1 -1
  6. package/.output/ui/assets/{CompareDrawer-L3n4J-Or.js → CompareDrawer-Co3cUF_I.js} +1 -1
  7. package/.output/ui/assets/{InspectorPet-D5o_3OZS.js → InspectorPet-jFcrL37X.js} +1 -1
  8. package/.output/ui/assets/{ProxyViewerContainer-Ocagx75S.js → ProxyViewerContainer-BPzt_VpM.js} +4 -4
  9. package/.output/ui/assets/{ReplayDialog-Bk7x1h-y.js → ReplayDialog-C6O_zuwI.js} +1 -1
  10. package/.output/ui/assets/{RequestAnatomy-U4lzL7Sc.js → RequestAnatomy-Ca6NvB7L.js} +1 -1
  11. package/.output/ui/assets/{ResponseView-LOWfvBLK.js → ResponseView-BzqKcveJ.js} +1 -1
  12. package/.output/ui/assets/{StreamingChunkSequence-DPfsrrXQ.js → StreamingChunkSequence-9pCZIsS_.js} +1 -1
  13. package/.output/ui/assets/{_sessionId-0MlWS-CO.js → _sessionId-BMP3KVGR.js} +1 -1
  14. package/.output/ui/assets/{_sessionId-OdX2Jvt1.js → _sessionId-y4eRoT1H.js} +1 -1
  15. package/.output/ui/assets/{index-Ea-c8hPg.js → index-CH5w-haG.js} +1 -1
  16. package/.output/ui/assets/{index-zVVS53Hd.js → index-CmocEhyU.js} +1 -1
  17. package/.output/ui/assets/{index-Du4qNOOt.js → index-DT8sMJ_n.js} +2 -2
  18. package/.output/ui/assets/{index-gvFj_9K6.js → index-bfsbIRZa.js} +1 -1
  19. package/.output/ui/assets/{json-viewer-C1WAMzg3.js → json-viewer-BfFOSDG5.js} +1 -1
  20. package/.output/ui/assets/{jszip.min-B8AKu2zm.js → jszip.min-BkbVkOsp.js} +1 -1
  21. package/.output/ui/index.html +1 -1
  22. package/package.json +5 -10
  23. package/src/assets/IDE/claudecode-color.svg +0 -1
  24. package/src/assets/IDE/codex-color.svg +0 -1
  25. package/src/assets/IDE/opencode.svg +0 -1
  26. package/src/assets/IDE/xiaomimimo.svg +0 -1
  27. package/src/assets/favicon.svg +0 -21
  28. package/src/assets/logos/alibaba.svg +0 -1
  29. package/src/assets/logos/anthropic.svg +0 -1
  30. package/src/assets/logos/claude-code.svg +0 -4
  31. package/src/assets/logos/deepseek.svg +0 -1
  32. package/src/assets/logos/minimax.jpeg +0 -0
  33. package/src/assets/logos/openai.svg +0 -1
  34. package/src/assets/logos/opencode.svg +0 -4
  35. package/src/assets/logos/qwen.webp +0 -0
  36. package/src/assets/logos/zhipuai.svg +0 -219
  37. package/src/backend/router.tsx +0 -36
  38. package/src/backend/routes/$.ts +0 -26
  39. package/src/backend/routes/__root.ts +0 -4
  40. package/src/backend/routes/api/-instances.ts +0 -7
  41. package/src/backend/routes/api/alerts.summary.ts +0 -28
  42. package/src/backend/routes/api/alerts.ts +0 -70
  43. package/src/backend/routes/api/config.paths.ts +0 -14
  44. package/src/backend/routes/api/config.ts +0 -73
  45. package/src/backend/routes/api/ecosystem.packages.$packageId.help.ts +0 -11
  46. package/src/backend/routes/api/ecosystem.packages.$packageId.install.ts +0 -11
  47. package/src/backend/routes/api/ecosystem.packages.$packageId.runner-presets.ts +0 -11
  48. package/src/backend/routes/api/ecosystem.packages.$packageId.upgrade.ts +0 -11
  49. package/src/backend/routes/api/ecosystem.packages.ts +0 -21
  50. package/src/backend/routes/api/ecosystem.recipes.$recipeId.run.ts +0 -11
  51. package/src/backend/routes/api/ecosystem.tasks.$taskId.ts +0 -16
  52. package/src/backend/routes/api/ecosystem.tasks.ts +0 -12
  53. package/src/backend/routes/api/groups.$groupId.evidence.ts +0 -55
  54. package/src/backend/routes/api/groups.$groupId.sessions.ts +0 -50
  55. package/src/backend/routes/api/groups.$groupId.ts +0 -93
  56. package/src/backend/routes/api/groups.ts +0 -79
  57. package/src/backend/routes/api/health.ts +0 -22
  58. package/src/backend/routes/api/instances.$name.connection.ts +0 -12
  59. package/src/backend/routes/api/instances.$name.restart.ts +0 -23
  60. package/src/backend/routes/api/instances.$name.start.ts +0 -18
  61. package/src/backend/routes/api/instances.$name.stop.ts +0 -23
  62. package/src/backend/routes/api/instances.$name.ts +0 -12
  63. package/src/backend/routes/api/instances.ts +0 -16
  64. package/src/backend/routes/api/knowledge.candidates.$candidateId.promote.ts +0 -32
  65. package/src/backend/routes/api/knowledge.candidates.$candidateId.ts +0 -50
  66. package/src/backend/routes/api/knowledge.candidates.ts +0 -10
  67. package/src/backend/routes/api/knowledge.project-context.ts +0 -29
  68. package/src/backend/routes/api/knowledge.search.ts +0 -62
  69. package/src/backend/routes/api/knowledge.sessions.$sessionId.candidates.ts +0 -26
  70. package/src/backend/routes/api/logs.$id.body.ts +0 -58
  71. package/src/backend/routes/api/logs.$id.chunks.ts +0 -37
  72. package/src/backend/routes/api/logs.$id.replay.ts +0 -297
  73. package/src/backend/routes/api/logs.$id.ts +0 -23
  74. package/src/backend/routes/api/logs.import.ts +0 -39
  75. package/src/backend/routes/api/logs.stream.ts +0 -174
  76. package/src/backend/routes/api/logs.ts +0 -214
  77. package/src/backend/routes/api/mcp.ts +0 -25
  78. package/src/backend/routes/api/models.ts +0 -10
  79. package/src/backend/routes/api/pi-agent.ts +0 -29
  80. package/src/backend/routes/api/providers.$providerId.model-metadata.ts +0 -173
  81. package/src/backend/routes/api/providers.$providerId.test.log.ts +0 -342
  82. package/src/backend/routes/api/providers.$providerId.ts +0 -111
  83. package/src/backend/routes/api/providers.export.ts +0 -44
  84. package/src/backend/routes/api/providers.import.ts +0 -81
  85. package/src/backend/routes/api/providers.scan.ts +0 -28
  86. package/src/backend/routes/api/providers.ts +0 -102
  87. package/src/backend/routes/api/runs.$runId.evidence.ts +0 -55
  88. package/src/backend/routes/api/runs.$runId.ts +0 -50
  89. package/src/backend/routes/api/runs.ts +0 -62
  90. package/src/backend/routes/api/runtime.ts +0 -46
  91. package/src/backend/routes/api/sessions.ts +0 -51
  92. package/src/backend/routes/api/storage.ts +0 -56
  93. package/src/backend/routes/livez.ts +0 -13
  94. package/src/backend/routes/metrics.ts +0 -14
  95. package/src/backend/routes/proxy/$.ts +0 -15
  96. package/src/backend/routes/readyz.ts +0 -18
  97. package/src/backend/start.ts +0 -10
  98. package/src/cli/alias.ts +0 -431
  99. package/src/cli/detect-tools.ts +0 -123
  100. package/src/cli/doctor.ts +0 -836
  101. package/src/cli/instance.ts +0 -1071
  102. package/src/cli/instanceApi.ts +0 -213
  103. package/src/cli/instanceArgs.ts +0 -301
  104. package/src/cli/instanceControl.ts +0 -191
  105. package/src/cli/instanceModel.ts +0 -276
  106. package/src/cli/instanceRegistry.ts +0 -731
  107. package/src/cli/networkHints.ts +0 -170
  108. package/src/cli/onboard.ts +0 -1668
  109. package/src/cli/onboardTarget.ts +0 -228
  110. package/src/cli/rustBackendPackage.ts +0 -458
  111. package/src/cli/startupOutput.ts +0 -16
  112. package/src/cli/templates/codex-skill-onboard.ts +0 -320
  113. package/src/cli/templates/command-onboard.ts +0 -25
  114. package/src/cli/templates/skill-onboard.ts +0 -625
  115. package/src/cli.ts +0 -1433
  116. package/src/components/OnboardingBanner.tsx +0 -115
  117. package/src/components/ProxyViewer.tsx +0 -2259
  118. package/src/components/ProxyViewerContainer.tsx +0 -1076
  119. package/src/components/alerts/AlertsDialog.tsx +0 -615
  120. package/src/components/clients/ClientLogo.tsx +0 -175
  121. package/src/components/ecosystem/AgentLabDialog.tsx +0 -947
  122. package/src/components/errors/SafeErrorBoundary.tsx +0 -201
  123. package/src/components/groups/GroupsDialog.tsx +0 -1304
  124. package/src/components/inspector-pet/InspectorPet.tsx +0 -398
  125. package/src/components/inspector-pet/InspectorPetCrab3D.tsx +0 -455
  126. package/src/components/inspector-pet/inspectorPetLogic.ts +0 -272
  127. package/src/components/pi-agent/PiAgentPanel.tsx +0 -446
  128. package/src/components/pi-agent/piAgentChatLogic.ts +0 -273
  129. package/src/components/providers/ImportWizardDialog.tsx +0 -281
  130. package/src/components/providers/ProviderCard.tsx +0 -347
  131. package/src/components/providers/ProviderForm.tsx +0 -1183
  132. package/src/components/providers/ProviderLogo.tsx +0 -122
  133. package/src/components/providers/ProviderTestResultsView.tsx +0 -734
  134. package/src/components/providers/ProvidersPanel.tsx +0 -714
  135. package/src/components/providers/SettingsDialog.tsx +0 -1042
  136. package/src/components/providers/providerFormCapabilities.ts +0 -36
  137. package/src/components/proxy-viewer/AgentTraceSummary.tsx +0 -902
  138. package/src/components/proxy-viewer/AnswerMarkdown.tsx +0 -51
  139. package/src/components/proxy-viewer/ApplicationBar.tsx +0 -123
  140. package/src/components/proxy-viewer/CompareDrawer.tsx +0 -984
  141. package/src/components/proxy-viewer/ConversationGroup.tsx +0 -208
  142. package/src/components/proxy-viewer/ConversationGroupList.tsx +0 -652
  143. package/src/components/proxy-viewer/ConversationHeader.tsx +0 -429
  144. package/src/components/proxy-viewer/LiveConnectionStatus.tsx +0 -186
  145. package/src/components/proxy-viewer/LogEntry.tsx +0 -1419
  146. package/src/components/proxy-viewer/LogEntryHeader.tsx +0 -596
  147. package/src/components/proxy-viewer/ProviderLogoStack.tsx +0 -57
  148. package/src/components/proxy-viewer/RawExportWarning.tsx +0 -77
  149. package/src/components/proxy-viewer/ReplayDialog.tsx +0 -636
  150. package/src/components/proxy-viewer/RequestToolsPanel.tsx +0 -299
  151. package/src/components/proxy-viewer/ResponseView.tsx +0 -202
  152. package/src/components/proxy-viewer/SessionLoadProgressBar.tsx +0 -61
  153. package/src/components/proxy-viewer/StreamingChunkSequence.tsx +0 -265
  154. package/src/components/proxy-viewer/ThreadConnector.tsx +0 -165
  155. package/src/components/proxy-viewer/ToolTraceEvents.tsx +0 -64
  156. package/src/components/proxy-viewer/TurnGroup.tsx +0 -383
  157. package/src/components/proxy-viewer/TurnGroupList.tsx +0 -156
  158. package/src/components/proxy-viewer/accessibility.ts +0 -8
  159. package/src/components/proxy-viewer/anatomy/RequestAnatomy.tsx +0 -887
  160. package/src/components/proxy-viewer/anatomy/SegmentBar.tsx +0 -222
  161. package/src/components/proxy-viewer/anatomy/contextIntelligence.ts +0 -737
  162. package/src/components/proxy-viewer/anatomy/sessionContextSummary.ts +0 -268
  163. package/src/components/proxy-viewer/anatomy/tokenEstimate.ts +0 -53
  164. package/src/components/proxy-viewer/anatomy/types.ts +0 -41
  165. package/src/components/proxy-viewer/anatomy/useAnatomyJump.ts +0 -114
  166. package/src/components/proxy-viewer/bodyHydration.ts +0 -123
  167. package/src/components/proxy-viewer/cacheTrend.ts +0 -50
  168. package/src/components/proxy-viewer/diff/DiffView.tsx +0 -321
  169. package/src/components/proxy-viewer/diff/computeDiff.ts +0 -178
  170. package/src/components/proxy-viewer/diff/index.ts +0 -3
  171. package/src/components/proxy-viewer/formats/anthropic/ContentBlocks.tsx +0 -194
  172. package/src/components/proxy-viewer/formats/anthropic/ResponseView.tsx +0 -81
  173. package/src/components/proxy-viewer/formats/anthropic/thinkingExtract.ts +0 -21
  174. package/src/components/proxy-viewer/formats/index.tsx +0 -47
  175. package/src/components/proxy-viewer/formats/openai/ResponseView.tsx +0 -442
  176. package/src/components/proxy-viewer/index.ts +0 -9
  177. package/src/components/proxy-viewer/lazy.ts +0 -41
  178. package/src/components/proxy-viewer/liveConnectionState.ts +0 -158
  179. package/src/components/proxy-viewer/log-formats/anthropic.ts +0 -191
  180. package/src/components/proxy-viewer/log-formats/index.ts +0 -23
  181. package/src/components/proxy-viewer/log-formats/openai.ts +0 -256
  182. package/src/components/proxy-viewer/log-formats/types.ts +0 -40
  183. package/src/components/proxy-viewer/log-formats/unknown.ts +0 -18
  184. package/src/components/proxy-viewer/logEntryVisibility.ts +0 -73
  185. package/src/components/proxy-viewer/logFocus.ts +0 -54
  186. package/src/components/proxy-viewer/proxyViewerContainerLogic.ts +0 -124
  187. package/src/components/proxy-viewer/proxyViewerLogic.ts +0 -488
  188. package/src/components/proxy-viewer/replayComparison.ts +0 -131
  189. package/src/components/proxy-viewer/requestDiff.ts +0 -277
  190. package/src/components/proxy-viewer/requestTools.ts +0 -220
  191. package/src/components/proxy-viewer/useCopyFeedback.ts +0 -38
  192. package/src/components/proxy-viewer/useKeyboardNavigation.ts +0 -232
  193. package/src/components/proxy-viewer/viewerState.ts +0 -176
  194. package/src/components/ui/badge.tsx +0 -47
  195. package/src/components/ui/button.tsx +0 -47
  196. package/src/components/ui/collapsible.tsx +0 -21
  197. package/src/components/ui/confirm-dialog.tsx +0 -51
  198. package/src/components/ui/crab-logo.tsx +0 -45
  199. package/src/components/ui/crab-variants.tsx +0 -467
  200. package/src/components/ui/dialog.tsx +0 -130
  201. package/src/components/ui/icon-trigger.ts +0 -2
  202. package/src/components/ui/json-viewer-bulk.ts +0 -132
  203. package/src/components/ui/json-viewer.tsx +0 -508
  204. package/src/components/ui/scroll-area.tsx +0 -54
  205. package/src/components/ui/select.tsx +0 -178
  206. package/src/components/ui/separator.tsx +0 -28
  207. package/src/components/ui/tabs.tsx +0 -88
  208. package/src/components/ui/tooltip.tsx +0 -51
  209. package/src/components/ui/transient-toast.tsx +0 -105
  210. package/src/contracts/anthropic.ts +0 -230
  211. package/src/contracts/index.ts +0 -59
  212. package/src/contracts/json.ts +0 -37
  213. package/src/contracts/log.ts +0 -139
  214. package/src/contracts/openai.ts +0 -267
  215. package/src/index.css +0 -11
  216. package/src/knowledge/candidateStore.ts +0 -94
  217. package/src/knowledge/distiller.ts +0 -98
  218. package/src/knowledge/openclawClient.ts +0 -161
  219. package/src/knowledge/openclawGatewayClient.ts +0 -249
  220. package/src/knowledge/openclawMarkdown.ts +0 -146
  221. package/src/knowledge/redactor.ts +0 -80
  222. package/src/knowledge/types.ts +0 -83
  223. package/src/lib/alertContract.ts +0 -76
  224. package/src/lib/apiClient.ts +0 -166
  225. package/src/lib/apiFormat.ts +0 -29
  226. package/src/lib/backendImplementation.ts +0 -16
  227. package/src/lib/basePath.ts +0 -107
  228. package/src/lib/browserRuntimeContract.ts +0 -124
  229. package/src/lib/browserRuntimeResolver.ts +0 -333
  230. package/src/lib/chunkLoadRecovery.ts +0 -83
  231. package/src/lib/claudeCodeStrip.ts +0 -98
  232. package/src/lib/clipboard.ts +0 -67
  233. package/src/lib/codingAgentEndpoints.ts +0 -54
  234. package/src/lib/ecosystemContract.ts +0 -130
  235. package/src/lib/export-logs.ts +0 -287
  236. package/src/lib/groupContract.ts +0 -166
  237. package/src/lib/instanceContract.ts +0 -239
  238. package/src/lib/jsonFile.ts +0 -46
  239. package/src/lib/logImportContract.ts +0 -12
  240. package/src/lib/managedInstance.ts +0 -112
  241. package/src/lib/mask.ts +0 -4
  242. package/src/lib/objectUtils.ts +0 -22
  243. package/src/lib/piAgentContract.ts +0 -102
  244. package/src/lib/providerContract.ts +0 -125
  245. package/src/lib/providerImportContract.ts +0 -27
  246. package/src/lib/providerModelMetadata.ts +0 -458
  247. package/src/lib/providerTestContract.ts +0 -170
  248. package/src/lib/providerTestPrompt.ts +0 -100
  249. package/src/lib/publicBasePathContext.ts +0 -137
  250. package/src/lib/resourceLimits.ts +0 -345
  251. package/src/lib/runContract.ts +0 -164
  252. package/src/lib/runtimeConfig.ts +0 -43
  253. package/src/lib/safeDiagnostic.ts +0 -38
  254. package/src/lib/safeFetch.ts +0 -508
  255. package/src/lib/serverPort.ts +0 -47
  256. package/src/lib/sessionInfoContract.ts +0 -78
  257. package/src/lib/sessionUrl.ts +0 -46
  258. package/src/lib/ssrfGuard.ts +0 -133
  259. package/src/lib/stopReason.ts +0 -130
  260. package/src/lib/themeMode.ts +0 -41
  261. package/src/lib/timeDisplay.ts +0 -22
  262. package/src/lib/toolTrace.ts +0 -290
  263. package/src/lib/uiScale.ts +0 -117
  264. package/src/lib/unknown.ts +0 -27
  265. package/src/lib/upstreamUrl.ts +0 -150
  266. package/src/lib/useAlerts.ts +0 -82
  267. package/src/lib/useGroupEvidence.ts +0 -37
  268. package/src/lib/useGroups.ts +0 -32
  269. package/src/lib/useOnboarding.ts +0 -93
  270. package/src/lib/useProviders.ts +0 -30
  271. package/src/lib/useStripConfig.ts +0 -154
  272. package/src/lib/useThemeMode.ts +0 -40
  273. package/src/lib/useUiScale.ts +0 -52
  274. package/src/lib/utils.ts +0 -78
  275. package/src/mcp/currentContext.ts +0 -65
  276. package/src/mcp/instanceHandlers.ts +0 -151
  277. package/src/mcp/loopback.ts +0 -88
  278. package/src/mcp/mode.ts +0 -75
  279. package/src/mcp/previewExtractor.ts +0 -233
  280. package/src/mcp/server.ts +0 -2274
  281. package/src/mcp/toolHandlers.ts +0 -1533
  282. package/src/proxy/alerts.ts +0 -664
  283. package/src/proxy/chunkStorage.ts +0 -123
  284. package/src/proxy/config.ts +0 -218
  285. package/src/proxy/constants.ts +0 -66
  286. package/src/proxy/dataDir.ts +0 -147
  287. package/src/proxy/ecosystemExecutionConfirmation.ts +0 -114
  288. package/src/proxy/ecosystemExecutionRoute.ts +0 -116
  289. package/src/proxy/ecosystemRegistry.ts +0 -296
  290. package/src/proxy/ecosystemTasks.ts +0 -415
  291. package/src/proxy/evidenceAnalysis.ts +0 -526
  292. package/src/proxy/evidenceExporter.ts +0 -235
  293. package/src/proxy/formats/anthropic/anthropicProvider.ts +0 -75
  294. package/src/proxy/formats/anthropic/handler.ts +0 -75
  295. package/src/proxy/formats/anthropic/index.ts +0 -13
  296. package/src/proxy/formats/anthropic/register.ts +0 -4
  297. package/src/proxy/formats/anthropic/schemas.ts +0 -6
  298. package/src/proxy/formats/anthropic/stream.ts +0 -205
  299. package/src/proxy/formats/handler.ts +0 -46
  300. package/src/proxy/formats/index.ts +0 -13
  301. package/src/proxy/formats/jsonSchema.ts +0 -2
  302. package/src/proxy/formats/openai/alibabaProvider.ts +0 -34
  303. package/src/proxy/formats/openai/codexMetadata.ts +0 -61
  304. package/src/proxy/formats/openai/handler.ts +0 -133
  305. package/src/proxy/formats/openai/index.ts +0 -33
  306. package/src/proxy/formats/openai/provider.ts +0 -50
  307. package/src/proxy/formats/openai/register.ts +0 -4
  308. package/src/proxy/formats/openai/schemas.ts +0 -25
  309. package/src/proxy/formats/openai/stream.ts +0 -600
  310. package/src/proxy/formats/openai/zhipuProvider.ts +0 -31
  311. package/src/proxy/formats/providerAdapter.ts +0 -50
  312. package/src/proxy/formats/providerRegistry.ts +0 -51
  313. package/src/proxy/formats/providers/index.ts +0 -3
  314. package/src/proxy/formats/registry.ts +0 -65
  315. package/src/proxy/groupEvidenceExporter.ts +0 -371
  316. package/src/proxy/groupStore.ts +0 -336
  317. package/src/proxy/handler.ts +0 -729
  318. package/src/proxy/identityProxy.ts +0 -1842
  319. package/src/proxy/jsonlRecovery.ts +0 -554
  320. package/src/proxy/logBodyChunks.ts +0 -91
  321. package/src/proxy/logFinalizer.ts +0 -777
  322. package/src/proxy/logFinalizer.worker.ts +0 -24
  323. package/src/proxy/logImportUpload.ts +0 -128
  324. package/src/proxy/logImporter.ts +0 -813
  325. package/src/proxy/logIndex.ts +0 -663
  326. package/src/proxy/logSearch.ts +0 -122
  327. package/src/proxy/logger.ts +0 -537
  328. package/src/proxy/openaiOrphanToolStrip.ts +0 -142
  329. package/src/proxy/platformCommands.ts +0 -258
  330. package/src/proxy/privateDataPath.ts +0 -419
  331. package/src/proxy/providerImporters.ts +0 -578
  332. package/src/proxy/providerScanStore.ts +0 -87
  333. package/src/proxy/providerSecretStore.ts +0 -216
  334. package/src/proxy/providers.ts +0 -998
  335. package/src/proxy/rawStreamCapture.ts +0 -342
  336. package/src/proxy/runFailures.ts +0 -94
  337. package/src/proxy/runStore.ts +0 -214
  338. package/src/proxy/runtimeAdmission.ts +0 -55
  339. package/src/proxy/runtimeHealth.ts +0 -221
  340. package/src/proxy/runtimeMetrics.ts +0 -149
  341. package/src/proxy/runtimeShutdown.ts +0 -157
  342. package/src/proxy/schemas.ts +0 -112
  343. package/src/proxy/sessionArchive.ts +0 -479
  344. package/src/proxy/sessionInfo.ts +0 -266
  345. package/src/proxy/sessionProcess.ts +0 -194
  346. package/src/proxy/sessionRuntime.ts +0 -121
  347. package/src/proxy/sessionSupervisor.ts +0 -305
  348. package/src/proxy/sessionWorkerEntry.ts +0 -26
  349. package/src/proxy/shutdownCoordinator.ts +0 -90
  350. package/src/proxy/socketTracker.ts +0 -639
  351. package/src/proxy/sqliteLogIndex.ts +0 -733
  352. package/src/proxy/storageLifecycle.ts +0 -432
  353. package/src/proxy/store.ts +0 -1773
  354. package/src/proxy/streamTiming.ts +0 -31
  355. package/src/proxy/toolSchemaWarnings.ts +0 -529
  356. package/src/proxy/uiAssetServer.ts +0 -106
  357. package/src/proxy/upstream.ts +0 -127
  358. package/src/services/alerts.ts +0 -12
  359. package/src/services/groups.ts +0 -119
  360. package/src/services/piAgent.ts +0 -421
  361. package/src/services/piAgentRetrieval.ts +0 -1180
  362. package/src/services/result.ts +0 -17
  363. package/src/services/runs.ts +0 -76
  364. package/src/ui/bootstrap.ts +0 -167
  365. package/src/ui/index.html +0 -38
  366. package/src/ui/logsStreamClient.ts +0 -20
  367. package/src/ui/main.tsx +0 -13
  368. package/src/ui/public/runtime-config.js +0 -2
  369. package/src/ui/router.tsx +0 -13
  370. package/src/ui/routes/__root.tsx +0 -69
  371. package/src/ui/routes/index.tsx +0 -35
  372. package/src/ui/routes/session/$sessionId.tsx +0 -50
  373. package/src/ui/runtimeDiscovery.ts +0 -50
@@ -1,737 +0,0 @@
1
- import { isPlainRecord, safeGetOwnProperty } from "../../../lib/objectUtils";
2
- import type { ProviderConfig } from "../../../lib/providerContract";
3
- import { resolveProviderContextWindow } from "../../../lib/providerModelMetadata";
4
- import { countCharacters, estimateTokens } from "./tokenEstimate";
5
- import type { AnatomyRole, AnatomySegment } from "./types";
6
-
7
- export type ContextRiskLevel = "unknown" | "ok" | "watch" | "danger";
8
-
9
- export type ContextWindowSource = "request" | "provider" | "model-rule" | "unknown";
10
-
11
- export type ContextHealthLevel = "ok" | "optimizable" | "risk";
12
-
13
- export type ContextWindow = {
14
- tokens: number | null;
15
- label: string;
16
- source: ContextWindowSource;
17
- };
18
-
19
- export type RoleUsage = {
20
- role: AnatomyRole;
21
- label: string;
22
- tokens: number;
23
- percent: number;
24
- };
25
-
26
- export type ContextDiagnostic = {
27
- kind: "duplicate" | "history-bloat" | "tool-schema" | "system-heavy";
28
- severity: "watch" | "danger";
29
- title: string;
30
- detail: string;
31
- };
32
-
33
- export type DuplicateContextSegment = {
34
- role: AnatomyRole;
35
- label: string;
36
- path: string;
37
- tokens: number;
38
- characters: number;
39
- };
40
-
41
- export type DuplicateContextGroup = {
42
- key: string;
43
- count: number;
44
- totalTokens: number;
45
- repeatedTokens: number;
46
- preview: string;
47
- firstLabel: string;
48
- segments: DuplicateContextSegment[];
49
- };
50
-
51
- export type ContextHealth = {
52
- level: ContextHealthLevel;
53
- opportunityCount: number;
54
- reclaimableTokens: number;
55
- };
56
-
57
- export type ContextIntelligence = {
58
- model: string | null;
59
- contextWindow: ContextWindow;
60
- estimatedInputTokens: number;
61
- outputReserveTokens: number | null;
62
- windowUsedTokens: number | null;
63
- remainingInputTokens: number | null;
64
- remainingAfterReserveTokens: number | null;
65
- usagePercent: number | null;
66
- riskLevel: ContextRiskLevel;
67
- roleUsages: RoleUsage[];
68
- largestRole: RoleUsage | null;
69
- diagnostics: ContextDiagnostic[];
70
- duplicateGroups: DuplicateContextGroup[];
71
- health: ContextHealth;
72
- };
73
-
74
- type MatchMode = "prefix" | "includes";
75
-
76
- type ModelContextRule = {
77
- family: string;
78
- tokens: number;
79
- mode: MatchMode;
80
- patterns: readonly string[];
81
- };
82
-
83
- type DuplicateCandidate = {
84
- role: AnatomyRole;
85
- label: string;
86
- path: string;
87
- tokens: number;
88
- characters: number;
89
- text: string;
90
- };
91
-
92
- const WATCH_USAGE_PERCENT = 0.75;
93
- const DANGER_USAGE_PERCENT = 0.9;
94
- const LONG_TOOL_SCHEMA_TOKENS = 8_000;
95
- const LARGE_ROLE_PERCENT = 0.35;
96
- const DUPLICATE_MIN_TOKENS = 40;
97
- const DUPLICATE_MIN_CHARS = 160;
98
- const DUPLICATE_NESTED_MAX_DEPTH = 5;
99
- const DUPLICATE_NESTED_MAX_CANDIDATES_PER_SEGMENT = 8;
100
- const HISTORY_BLOAT_SEGMENTS = 18;
101
- const HISTORY_BLOAT_TOKENS = 60_000;
102
- const HISTORY_BLOAT_PERCENT = 0.7;
103
- const SYSTEM_HEAVY_TOKENS = 3_000;
104
- const SYSTEM_HEAVY_PERCENT = 0.3;
105
- const DUPLICATE_PREVIEW_CHARS = 160;
106
- const DUPLICATE_NESTED_FIELD_NAMES = new Set([
107
- "answer",
108
- "body",
109
- "content",
110
- "data",
111
- "error",
112
- "message",
113
- "markdown",
114
- "output",
115
- "response",
116
- "result",
117
- "stderr",
118
- "stdout",
119
- "text",
120
- "transcript",
121
- ]);
122
-
123
- const EXPLICIT_CONTEXT_WINDOW_FIELDS = [
124
- "context_window",
125
- "contextWindow",
126
- "context_length",
127
- "contextLength",
128
- "max_context_length",
129
- "maxContextLength",
130
- "max_input_tokens",
131
- "maxInputTokens",
132
- ] as const;
133
-
134
- const OUTPUT_RESERVE_FIELDS = [
135
- "max_tokens",
136
- "maxTokens",
137
- "max_completion_tokens",
138
- "maxCompletionTokens",
139
- "max_output_tokens",
140
- "maxOutputTokens",
141
- ] as const;
142
-
143
- const MODEL_CONTEXT_RULES: readonly ModelContextRule[] = [
144
- {
145
- family: "OpenAI GPT-4.1",
146
- tokens: 1_047_576,
147
- mode: "prefix",
148
- patterns: ["gpt-4.1"],
149
- },
150
- {
151
- family: "OpenAI GPT-4o",
152
- tokens: 128_000,
153
- mode: "prefix",
154
- patterns: ["gpt-4o"],
155
- },
156
- {
157
- family: "OpenAI o-series",
158
- tokens: 128_000,
159
- mode: "prefix",
160
- patterns: ["o1", "o3", "o4"],
161
- },
162
- {
163
- family: "Anthropic Claude",
164
- tokens: 200_000,
165
- mode: "prefix",
166
- patterns: ["claude-"],
167
- },
168
- {
169
- family: "DeepSeek V4",
170
- tokens: 1_048_576,
171
- mode: "prefix",
172
- patterns: ["deepseek-v4-pro", "deepseek-v4-flash"],
173
- },
174
- {
175
- family: "DeepSeek",
176
- tokens: 64_000,
177
- mode: "prefix",
178
- patterns: ["deepseek-"],
179
- },
180
- {
181
- family: "MiniMax M3",
182
- tokens: 1_048_576,
183
- mode: "includes",
184
- patterns: ["minimax-m3"],
185
- },
186
- {
187
- family: "MiniMax M2.7",
188
- tokens: 204_800,
189
- mode: "includes",
190
- patterns: ["minimax-m2.7"],
191
- },
192
- {
193
- family: "MiniMax M2.5/M2.1",
194
- tokens: 196_608,
195
- mode: "includes",
196
- patterns: ["minimax-m2.5", "minimax-m2.1"],
197
- },
198
- {
199
- family: "GLM-5.2",
200
- tokens: 1_048_576,
201
- mode: "prefix",
202
- patterns: ["glm-5.2"],
203
- },
204
- {
205
- family: "GLM-5",
206
- tokens: 202_752,
207
- mode: "prefix",
208
- patterns: ["glm-5", "glm-5.1"],
209
- },
210
- ];
211
-
212
- const ROLE_LABELS: Record<AnatomyRole, string> = {
213
- system: "System",
214
- user: "User messages",
215
- assistant: "Assistant messages",
216
- tool: "Tool results",
217
- tools: "Tool definitions",
218
- };
219
-
220
- function readPositiveInteger(value: unknown): number | null {
221
- if (typeof value === "number") {
222
- if (Number.isFinite(value) && value > 0) return Math.floor(value);
223
- return null;
224
- }
225
-
226
- if (typeof value === "string") {
227
- const parsed = Number(value);
228
- if (Number.isFinite(parsed) && parsed > 0) return Math.floor(parsed);
229
- }
230
-
231
- return null;
232
- }
233
-
234
- function readPositiveIntegerField(parsed: unknown, fields: readonly string[]): number | null {
235
- for (const field of fields) {
236
- const value = readPositiveInteger(safeGetOwnProperty(parsed, field));
237
- if (value !== null) return value;
238
- }
239
- return null;
240
- }
241
-
242
- export function readRequestModel(parsed: unknown): string | null {
243
- const value = safeGetOwnProperty(parsed, "model");
244
- if (typeof value !== "string") return null;
245
- const trimmed = value.trim();
246
- return trimmed === "" ? null : trimmed;
247
- }
248
-
249
- function matchesRule(model: string, rule: ModelContextRule): boolean {
250
- switch (rule.mode) {
251
- case "prefix":
252
- return rule.patterns.some((pattern) => model.startsWith(pattern));
253
- case "includes":
254
- return rule.patterns.some((pattern) => model.includes(pattern));
255
- }
256
- }
257
-
258
- export function resolveContextWindow(
259
- model: string | null,
260
- parsed: unknown,
261
- providers: readonly ProviderConfig[] = [],
262
- ): ContextWindow {
263
- const explicitWindow = readPositiveIntegerField(parsed, EXPLICIT_CONTEXT_WINDOW_FIELDS);
264
- if (explicitWindow !== null) {
265
- return {
266
- tokens: explicitWindow,
267
- label: "Request metadata",
268
- source: "request",
269
- };
270
- }
271
-
272
- const providerWindow = resolveProviderContextWindow(model, providers);
273
- if (providerWindow !== null) {
274
- return {
275
- tokens: providerWindow.tokens,
276
- label: `${providerWindow.providerName} config`,
277
- source: "provider",
278
- };
279
- }
280
-
281
- if (model === null) {
282
- return {
283
- tokens: null,
284
- label: "Unknown model",
285
- source: "unknown",
286
- };
287
- }
288
-
289
- const normalized = model.trim().toLowerCase().replace(/\s+/g, "-");
290
- for (const rule of MODEL_CONTEXT_RULES) {
291
- if (matchesRule(normalized, rule)) {
292
- return {
293
- tokens: rule.tokens,
294
- label: `${rule.family} local rule`,
295
- source: "model-rule",
296
- };
297
- }
298
- }
299
-
300
- return {
301
- tokens: null,
302
- label: "No local rule",
303
- source: "unknown",
304
- };
305
- }
306
-
307
- function clampPercent(value: number): number {
308
- if (value < 0) return 0;
309
- if (value > 1) return 1;
310
- return value;
311
- }
312
-
313
- function riskLevel(usagePercent: number | null): ContextRiskLevel {
314
- if (usagePercent === null) return "unknown";
315
- if (usagePercent >= DANGER_USAGE_PERCENT) return "danger";
316
- if (usagePercent >= WATCH_USAGE_PERCENT) return "watch";
317
- return "ok";
318
- }
319
-
320
- function sumSegments(segments: readonly AnatomySegment[], role: AnatomyRole): number {
321
- return segments
322
- .filter((segment) => segment.role === role)
323
- .reduce((sum, segment) => sum + segment.size, 0);
324
- }
325
-
326
- function buildRoleUsages(segments: readonly AnatomySegment[], total: number): RoleUsage[] {
327
- const roles: AnatomyRole[] = ["system", "user", "assistant", "tool", "tools"];
328
- return roles
329
- .map((role) => {
330
- const tokens = sumSegments(segments, role);
331
- return {
332
- role,
333
- label: ROLE_LABELS[role],
334
- tokens,
335
- percent: total > 0 ? tokens / total : 0,
336
- };
337
- })
338
- .filter((usage) => usage.tokens > 0)
339
- .sort((a, b) => b.tokens - a.tokens);
340
- }
341
-
342
- function normalizeDuplicateText(text: string): string {
343
- return text.replace(/\s+/g, " ").trim().toLowerCase();
344
- }
345
-
346
- function duplicatePreview(text: string): string {
347
- const singleLine = text.replace(/\s+/g, " ").trim();
348
- if (singleLine.length <= DUPLICATE_PREVIEW_CHARS) return singleLine;
349
- return `${singleLine.slice(0, DUPLICATE_PREVIEW_CHARS - 3)}...`;
350
- }
351
-
352
- function duplicateSegmentRef(candidate: DuplicateCandidate): DuplicateContextSegment {
353
- return {
354
- role: candidate.role,
355
- label: candidate.label,
356
- path: candidate.path,
357
- tokens: candidate.tokens,
358
- characters: candidate.characters,
359
- };
360
- }
361
-
362
- function duplicateCandidateFromSegment(segment: AnatomySegment): DuplicateCandidate {
363
- return {
364
- role: segment.role,
365
- label: segment.label,
366
- path: segment.path,
367
- tokens: segment.size,
368
- characters: segment.characters,
369
- text: segment.text,
370
- };
371
- }
372
-
373
- function jsonLikeText(text: string): boolean {
374
- const trimmed = text.trim();
375
- return trimmed.startsWith("{") || trimmed.startsWith("[");
376
- }
377
-
378
- function parseJsonLikeText(text: string): unknown | null {
379
- if (!jsonLikeText(text)) return null;
380
- try {
381
- const parsed: unknown = JSON.parse(text);
382
- return parsed;
383
- } catch {
384
- return null;
385
- }
386
- }
387
-
388
- function normalizePathFieldName(field: string): string {
389
- return field.toLowerCase().replace(/[^a-z0-9]/g, "");
390
- }
391
-
392
- function lastNamedPathField(path: readonly string[]): string | null {
393
- for (let index = path.length - 1; index >= 0; index -= 1) {
394
- const field = path[index] ?? "";
395
- if (field.startsWith("[") && field.endsWith("]")) continue;
396
- return field;
397
- }
398
- return null;
399
- }
400
-
401
- function nestedDuplicateFieldPath(path: readonly string[]): boolean {
402
- const field = lastNamedPathField(path);
403
- if (field === null) return false;
404
- return DUPLICATE_NESTED_FIELD_NAMES.has(normalizePathFieldName(field));
405
- }
406
-
407
- function formatNestedDuplicatePath(path: readonly string[]): string {
408
- return path
409
- .map((part) => (part.startsWith("[") ? part : `.${part}`))
410
- .join("")
411
- .replace(/^\./, "");
412
- }
413
-
414
- function duplicateCandidateFromNestedText(
415
- segment: AnatomySegment,
416
- text: string,
417
- path: readonly string[],
418
- ): DuplicateCandidate | null {
419
- const characters = countCharacters(text);
420
- if (characters < DUPLICATE_MIN_CHARS) return null;
421
- const tokens = estimateTokens(text);
422
- if (tokens < DUPLICATE_MIN_TOKENS) return null;
423
- return {
424
- role: segment.role,
425
- label: `${segment.label} ${formatNestedDuplicatePath(path)}`,
426
- path: segment.path,
427
- tokens,
428
- characters,
429
- text,
430
- };
431
- }
432
-
433
- function collectNestedDuplicateCandidates({
434
- value,
435
- segment,
436
- path,
437
- depth,
438
- candidates,
439
- }: {
440
- value: unknown;
441
- segment: AnatomySegment;
442
- path: readonly string[];
443
- depth: number;
444
- candidates: DuplicateCandidate[];
445
- }): void {
446
- if (candidates.length >= DUPLICATE_NESTED_MAX_CANDIDATES_PER_SEGMENT) return;
447
- if (depth > DUPLICATE_NESTED_MAX_DEPTH) return;
448
-
449
- if (typeof value === "string") {
450
- if (!nestedDuplicateFieldPath(path)) return;
451
- const candidate = duplicateCandidateFromNestedText(segment, value, path);
452
- if (candidate !== null) candidates.push(candidate);
453
- return;
454
- }
455
-
456
- if (Array.isArray(value)) {
457
- value.forEach((item, index) =>
458
- collectNestedDuplicateCandidates({
459
- value: item,
460
- segment,
461
- path: [...path, `[${String(index)}]`],
462
- depth: depth + 1,
463
- candidates,
464
- }),
465
- );
466
- return;
467
- }
468
-
469
- if (!isPlainRecord(value)) return;
470
- Object.entries(value).forEach(([key, child]) =>
471
- collectNestedDuplicateCandidates({
472
- value: child,
473
- segment,
474
- path: [...path, key],
475
- depth: depth + 1,
476
- candidates,
477
- }),
478
- );
479
- }
480
-
481
- function duplicateCandidatesForSegment(segment: AnatomySegment): DuplicateCandidate[] {
482
- const segmentCandidate = duplicateCandidateFromSegment(segment);
483
- const parsed = parseJsonLikeText(segment.text);
484
- if (parsed === null) return [segmentCandidate];
485
-
486
- const candidates: DuplicateCandidate[] = [];
487
- collectNestedDuplicateCandidates({
488
- value: parsed,
489
- segment,
490
- path: [],
491
- depth: 0,
492
- candidates,
493
- });
494
-
495
- const normalizedSegment = normalizeDuplicateText(segment.text);
496
- const seen = new Set([normalizedSegment]);
497
- const uniqueNested = candidates.filter((candidate) => {
498
- const normalized = normalizeDuplicateText(candidate.text);
499
- if (normalized === "") return false;
500
- if (seen.has(normalized)) return false;
501
- seen.add(normalized);
502
- return true;
503
- });
504
-
505
- return [segmentCandidate, ...uniqueNested];
506
- }
507
-
508
- function duplicateContextGroups(segments: readonly AnatomySegment[]): DuplicateContextGroup[] {
509
- type DuplicateBucket = {
510
- tokens: number;
511
- candidates: DuplicateCandidate[];
512
- };
513
-
514
- const buckets = new Map<string, DuplicateBucket>();
515
- for (const segment of segments) {
516
- const candidates = duplicateCandidatesForSegment(segment);
517
- for (const candidate of candidates) {
518
- if (candidate.tokens < DUPLICATE_MIN_TOKENS) continue;
519
- if (candidate.characters < DUPLICATE_MIN_CHARS) continue;
520
- const normalized = normalizeDuplicateText(candidate.text);
521
- if (normalized === "") continue;
522
- const existing = buckets.get(normalized);
523
- if (existing === undefined) {
524
- buckets.set(normalized, {
525
- tokens: candidate.tokens,
526
- candidates: [candidate],
527
- });
528
- continue;
529
- }
530
- buckets.set(normalized, {
531
- tokens: existing.tokens + candidate.tokens,
532
- candidates: [...existing.candidates, candidate],
533
- });
534
- }
535
- }
536
-
537
- const groups: DuplicateContextGroup[] = [];
538
- for (const bucket of buckets.values()) {
539
- if (bucket.candidates.length < 2) continue;
540
- const firstCandidate = bucket.candidates[0] ?? null;
541
- if (firstCandidate === null) continue;
542
- const repeatedTokens = bucket.tokens - firstCandidate.tokens;
543
- groups.push({
544
- key: `${firstCandidate.path}:${firstCandidate.label}:${String(
545
- bucket.candidates.length,
546
- )}:${String(bucket.tokens)}`,
547
- count: bucket.candidates.length,
548
- totalTokens: bucket.tokens,
549
- repeatedTokens,
550
- preview: duplicatePreview(firstCandidate.text),
551
- firstLabel: firstCandidate.label,
552
- segments: bucket.candidates.map(duplicateSegmentRef),
553
- });
554
- }
555
-
556
- return groups.sort(
557
- (left, right) =>
558
- right.repeatedTokens - left.repeatedTokens || right.totalTokens - left.totalTokens,
559
- );
560
- }
561
-
562
- function duplicateDiagnostic(
563
- duplicateGroups: readonly DuplicateContextGroup[],
564
- ): ContextDiagnostic | null {
565
- if (duplicateGroups.length === 0) return null;
566
-
567
- const repeatedGroups = duplicateGroups.length;
568
- const repeatedSegments = duplicateGroups.reduce((sum, group) => sum + group.count, 0);
569
- const repeatedTokens = duplicateGroups.reduce((sum, group) => sum + group.repeatedTokens, 0);
570
-
571
- return {
572
- kind: "duplicate",
573
- severity: repeatedTokens >= LONG_TOOL_SCHEMA_TOKENS ? "danger" : "watch",
574
- title: "Duplicate context",
575
- detail: `${String(repeatedSegments)} repeated blocks across ${String(
576
- repeatedGroups,
577
- )} group${repeatedGroups === 1 ? "" : "s"}, ~${String(repeatedTokens)} repeated tokens.`,
578
- };
579
- }
580
-
581
- function duplicateReclaimableTokens(duplicateGroups: readonly DuplicateContextGroup[]): number {
582
- return duplicateGroups.reduce((sum, group) => sum + group.repeatedTokens, 0);
583
- }
584
-
585
- function diagnosticsForRolePressure(
586
- roleUsages: readonly RoleUsage[],
587
- total: number,
588
- messageSegmentCount: number,
589
- ): ContextDiagnostic[] {
590
- const diagnostics: ContextDiagnostic[] = [];
591
- const toolUsage = roleUsages.find((usage) => usage.role === "tools") ?? null;
592
- if (
593
- toolUsage !== null &&
594
- (toolUsage.tokens >= LONG_TOOL_SCHEMA_TOKENS ||
595
- (toolUsage.percent >= LARGE_ROLE_PERCENT && toolUsage.tokens >= SYSTEM_HEAVY_TOKENS))
596
- ) {
597
- diagnostics.push({
598
- kind: "tool-schema",
599
- severity: toolUsage.tokens >= LONG_TOOL_SCHEMA_TOKENS ? "danger" : "watch",
600
- title: "Large tool schema",
601
- detail: `Tool definitions take ${Math.round(toolUsage.percent * 100)}% of request context.`,
602
- });
603
- }
604
-
605
- const systemUsage = roleUsages.find((usage) => usage.role === "system") ?? null;
606
- if (
607
- systemUsage !== null &&
608
- systemUsage.tokens >= SYSTEM_HEAVY_TOKENS &&
609
- systemUsage.percent >= SYSTEM_HEAVY_PERCENT
610
- ) {
611
- diagnostics.push({
612
- kind: "system-heavy",
613
- severity: "watch",
614
- title: "Large system prompt",
615
- detail: `System instructions take ${Math.round(systemUsage.percent * 100)}% of request context.`,
616
- });
617
- }
618
-
619
- const historyTokens = roleUsages
620
- .filter((usage) => usage.role === "user" || usage.role === "assistant" || usage.role === "tool")
621
- .reduce((sum, usage) => sum + usage.tokens, 0);
622
- const historyPercent = total > 0 ? historyTokens / total : 0;
623
- if (
624
- messageSegmentCount >= HISTORY_BLOAT_SEGMENTS &&
625
- (historyTokens >= HISTORY_BLOAT_TOKENS || historyPercent >= HISTORY_BLOAT_PERCENT)
626
- ) {
627
- diagnostics.push({
628
- kind: "history-bloat",
629
- severity: historyPercent >= 0.85 ? "danger" : "watch",
630
- title: "Conversation history growth",
631
- detail: `${String(messageSegmentCount)} message blocks take ${Math.round(
632
- historyPercent * 100,
633
- )}% of request context.`,
634
- });
635
- }
636
-
637
- return diagnostics;
638
- }
639
-
640
- function contextHealth({
641
- risk,
642
- contextWindow,
643
- diagnostics,
644
- duplicateGroups,
645
- }: {
646
- risk: ContextRiskLevel;
647
- contextWindow: ContextWindow;
648
- diagnostics: readonly ContextDiagnostic[];
649
- duplicateGroups: readonly DuplicateContextGroup[];
650
- }): ContextHealth {
651
- const diagnosticKinds = new Set(diagnostics.map((diagnostic) => diagnostic.kind));
652
- let opportunityCount = diagnosticKinds.size;
653
- if (risk === "watch" || risk === "danger") opportunityCount += 1;
654
- if (contextWindow.source === "unknown") opportunityCount += 1;
655
-
656
- const hasDangerDiagnostic = diagnostics.some((diagnostic) => diagnostic.severity === "danger");
657
- const level: ContextHealthLevel =
658
- risk === "danger" || hasDangerDiagnostic ? "risk" : opportunityCount > 0 ? "optimizable" : "ok";
659
-
660
- return {
661
- level,
662
- opportunityCount,
663
- reclaimableTokens: duplicateReclaimableTokens(duplicateGroups),
664
- };
665
- }
666
-
667
- export function analyzeContextIntelligence({
668
- segments,
669
- inputTokens,
670
- parsed,
671
- model,
672
- providers = [],
673
- }: {
674
- segments: readonly AnatomySegment[];
675
- inputTokens: number | null;
676
- parsed: unknown;
677
- model: string | null;
678
- providers?: readonly ProviderConfig[];
679
- }): ContextIntelligence {
680
- const totalEstimatedTokens = segments.reduce((sum, segment) => sum + segment.size, 0);
681
- const requestModel = model ?? readRequestModel(parsed);
682
- const estimatedInputTokens = inputTokens ?? totalEstimatedTokens;
683
- const outputReserveTokens = readPositiveIntegerField(parsed, OUTPUT_RESERVE_FIELDS);
684
- const contextWindow = resolveContextWindow(requestModel, parsed, providers);
685
- const reservedTokens = outputReserveTokens ?? 0;
686
- const windowUsedTokens =
687
- contextWindow.tokens === null ? null : estimatedInputTokens + reservedTokens;
688
- const remainingInputTokens =
689
- contextWindow.tokens === null ? null : contextWindow.tokens - estimatedInputTokens;
690
- const remainingAfterReserveTokens =
691
- contextWindow.tokens === null
692
- ? null
693
- : contextWindow.tokens - estimatedInputTokens - reservedTokens;
694
- const usagePercent =
695
- contextWindow.tokens === null || windowUsedTokens === null
696
- ? null
697
- : clampPercent(windowUsedTokens / contextWindow.tokens);
698
- const roleUsages = buildRoleUsages(segments, totalEstimatedTokens);
699
- const largestRole = roleUsages[0] ?? null;
700
- const messageSegmentCount = segments.filter((segment) => segment.role !== "tools").length;
701
- const duplicateGroups = duplicateContextGroups(segments);
702
- const duplicate = duplicateDiagnostic(duplicateGroups);
703
- const diagnostics = diagnosticsForRolePressure(
704
- roleUsages,
705
- totalEstimatedTokens,
706
- messageSegmentCount,
707
- );
708
- if (duplicate !== null) diagnostics.unshift(duplicate);
709
- const risk = riskLevel(usagePercent);
710
-
711
- return {
712
- model: requestModel,
713
- contextWindow,
714
- estimatedInputTokens,
715
- outputReserveTokens,
716
- windowUsedTokens,
717
- remainingInputTokens,
718
- remainingAfterReserveTokens,
719
- usagePercent,
720
- riskLevel: risk,
721
- roleUsages,
722
- largestRole,
723
- diagnostics,
724
- duplicateGroups,
725
- health: contextHealth({
726
- risk,
727
- contextWindow,
728
- diagnostics,
729
- duplicateGroups,
730
- }),
731
- };
732
- }
733
-
734
- export const CONTEXT_USAGE_THRESHOLDS = {
735
- watch: WATCH_USAGE_PERCENT,
736
- danger: DANGER_USAGE_PERCENT,
737
- } as const;