@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,1180 +0,0 @@
1
- import type { CapturedLog } from "../contracts";
2
- import { listCandidates } from "../knowledge/candidateStore";
3
- import type { KnowledgeCandidate } from "../knowledge/types";
4
- import type { Alert } from "../lib/alertContract";
5
- import type { InspectorGroup } from "../lib/groupContract";
6
- import type { ProviderConfig } from "../lib/providerContract";
7
- import type { InspectorRun } from "../lib/runContract";
8
- import { listAlerts } from "../proxy/alerts";
9
- import { listGroups } from "../proxy/groupStore";
10
- import { getProviders } from "../proxy/providers";
11
- import { listRuns } from "../proxy/runStore";
12
- import {
13
- getLogById,
14
- listLogsPage,
15
- type ListLogsPageOptions,
16
- type ListLogsPageResult,
17
- } from "../proxy/store";
18
-
19
- export type PiAgentEvidenceSource = "log" | "knowledge" | "alert" | "run" | "group" | "provider";
20
-
21
- export type PiAgentCountEntry = {
22
- value: string;
23
- count: number;
24
- };
25
-
26
- export type PiAgentRetrievalSummary = {
27
- matchedLogs: number;
28
- knowledgeMatched: number;
29
- failures: number;
30
- pending: number;
31
- sessions: number;
32
- models: PiAgentCountEntry[];
33
- providers: PiAgentCountEntry[];
34
- latency: {
35
- count: number;
36
- minMs: number | null;
37
- maxMs: number | null;
38
- averageMs: number | null;
39
- };
40
- tokens: {
41
- input: number;
42
- output: number;
43
- total: number;
44
- };
45
- sourceCounts: Record<PiAgentEvidenceSource, number>;
46
- };
47
-
48
- export type PiAgentQueryStats = {
49
- scannedLogs: number;
50
- hydratedLogs: number;
51
- matchedLogs: number;
52
- scannedKnowledge: number;
53
- matchedKnowledge: number;
54
- returnedEvidence: number;
55
- truncated: boolean;
56
- durationMs: number;
57
- };
58
-
59
- export type PiAgentEvidence = {
60
- source: PiAgentEvidenceSource;
61
- id: string;
62
- logId?: number;
63
- knowledgeId?: string;
64
- logIds?: number[];
65
- timestamp?: string;
66
- sessionId?: string;
67
- model?: string;
68
- providerName?: string;
69
- path?: string;
70
- status?: number | string | null;
71
- elapsedMs?: number;
72
- inputTokens?: number;
73
- outputTokens?: number;
74
- score: number;
75
- matchedFields: string[];
76
- excerpt: string;
77
- entityType?: string;
78
- title?: string;
79
- knowledgeType?: string;
80
- tags?: string[];
81
- };
82
-
83
- export type PiAgentRetrievalResult = {
84
- summary: PiAgentRetrievalSummary;
85
- queryStats: PiAgentQueryStats;
86
- evidence: PiAgentEvidence[];
87
- };
88
-
89
- export type PiAgentRetrievalLimits = {
90
- scanPageSize: number;
91
- maxScannedLogs: number;
92
- maxHydratedLogs: number;
93
- maxEvidence: number;
94
- maxExcerptChars: number;
95
- maxKnowledgeCandidates: number;
96
- maxAuxiliaryRecords: number;
97
- };
98
-
99
- export type PiAgentRetrievalInput = {
100
- question: string;
101
- sessionId?: string;
102
- recentUserQuestion?: string;
103
- limits?: Partial<PiAgentRetrievalLimits>;
104
- };
105
-
106
- export type PiAgentRetrievalDependencies = {
107
- listLogPage: (options: ListLogsPageOptions) => Promise<ListLogsPageResult>;
108
- getLog: (id: number) => Promise<CapturedLog | null>;
109
- listKnowledgeCandidates: () => KnowledgeCandidate[];
110
- listInspectorAlerts: () => Promise<Alert[]>;
111
- listInspectorRuns: () => InspectorRun[];
112
- listInspectorGroups: () => InspectorGroup[];
113
- listInspectorProviders: () => ProviderConfig[];
114
- };
115
-
116
- type QueryIntents = {
117
- failure: boolean;
118
- pending: boolean;
119
- performance: boolean;
120
- tokens: boolean;
121
- tools: boolean;
122
- sessions: boolean;
123
- overview: boolean;
124
- };
125
-
126
- type QueryPlan = {
127
- phrase: string;
128
- terms: string[];
129
- intents: QueryIntents;
130
- };
131
-
132
- type SearchField = {
133
- name: string;
134
- text: string;
135
- weight: number;
136
- };
137
-
138
- type ScoreResult = {
139
- score: number;
140
- matchedFields: string[];
141
- };
142
-
143
- type RankedLog = ScoreResult & {
144
- log: CapturedLog;
145
- };
146
-
147
- type ScanResult = {
148
- logs: CapturedLog[];
149
- total: number;
150
- truncated: boolean;
151
- };
152
-
153
- type SourceCandidate = {
154
- evidence: PiAgentEvidence;
155
- sortTimestamp: string;
156
- };
157
-
158
- const DEFAULT_LIMITS: PiAgentRetrievalLimits = {
159
- scanPageSize: 250,
160
- maxScannedLogs: 20_000,
161
- maxHydratedLogs: 48,
162
- maxEvidence: 16,
163
- maxExcerptChars: 720,
164
- maxKnowledgeCandidates: 5_000,
165
- maxAuxiliaryRecords: 1_000,
166
- };
167
-
168
- const MAX_LIMITS: PiAgentRetrievalLimits = {
169
- scanPageSize: 1_000,
170
- maxScannedLogs: 100_000,
171
- maxHydratedLogs: 100,
172
- maxEvidence: 30,
173
- maxExcerptChars: 1_200,
174
- maxKnowledgeCandidates: 20_000,
175
- maxAuxiliaryRecords: 5_000,
176
- };
177
-
178
- const ENGLISH_STOP_WORDS = new Set([
179
- "a",
180
- "an",
181
- "and",
182
- "are",
183
- "be",
184
- "did",
185
- "do",
186
- "does",
187
- "for",
188
- "from",
189
- "how",
190
- "i",
191
- "in",
192
- "is",
193
- "it",
194
- "me",
195
- "of",
196
- "on",
197
- "or",
198
- "the",
199
- "this",
200
- "to",
201
- "was",
202
- "were",
203
- "what",
204
- "when",
205
- "where",
206
- "which",
207
- "who",
208
- "why",
209
- "with",
210
- ]);
211
-
212
- const REFERENTIAL_MARKERS = [
213
- "which one",
214
- "that one",
215
- "the former",
216
- "the latter",
217
- "it",
218
- "哪个",
219
- "那个",
220
- "其中",
221
- "它",
222
- "这个",
223
- "上述",
224
- ];
225
-
226
- const INTENT_ALIASES = {
227
- failure: [
228
- "error",
229
- "fail",
230
- "failed",
231
- "failure",
232
- "exception",
233
- "timeout",
234
- "错误",
235
- "失败",
236
- "异常",
237
- "超时",
238
- "报错",
239
- ],
240
- pending: [
241
- "pending",
242
- "hang",
243
- "hung",
244
- "stuck",
245
- "unfinished",
246
- "未完成",
247
- "没结束",
248
- "卡住",
249
- "挂起",
250
- "无响应",
251
- ],
252
- performance: [
253
- "slow",
254
- "slowest",
255
- "latency",
256
- "performance",
257
- "duration",
258
- "耗时",
259
- "延迟",
260
- "性能",
261
- "最慢",
262
- "响应时间",
263
- ],
264
- tokens: ["token", "tokens", "cost", "usage", "消耗", "用量", "费用"],
265
- tools: ["tool", "tools", "function call", "工具", "调用了什么"],
266
- sessions: ["session", "sessions", "conversation", "会话", "对话"],
267
- overview: [
268
- "overview",
269
- "summary",
270
- "overall",
271
- "aggregate",
272
- "statistics",
273
- "概览",
274
- "汇总",
275
- "总体",
276
- "整体",
277
- "统计",
278
- "情况",
279
- ],
280
- } satisfies Record<keyof QueryIntents, readonly string[]>;
281
-
282
- const SENSITIVE_KEY_PATTERN =
283
- /^(?:raw[-_]?headers?|headers?|authorization|proxy[-_]?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|password|passwd|secret|cookie|set[-_]?cookie)$/i;
284
-
285
- async function defaultListAlerts(): Promise<Alert[]> {
286
- const result = await listAlerts({ limit: 200, scanLimit: 2_000 });
287
- return result.alerts;
288
- }
289
-
290
- const DEFAULT_DEPENDENCIES: PiAgentRetrievalDependencies = {
291
- listLogPage: listLogsPage,
292
- getLog: getLogById,
293
- listKnowledgeCandidates: listCandidates,
294
- listInspectorAlerts: defaultListAlerts,
295
- listInspectorRuns: listRuns,
296
- listInspectorGroups: listGroups,
297
- listInspectorProviders: getProviders,
298
- };
299
-
300
- function clampLimit(value: number | undefined, fallback: number, maximum: number): number {
301
- if (value === undefined || !Number.isInteger(value) || value < 1) return fallback;
302
- return Math.min(value, maximum);
303
- }
304
-
305
- function resolveLimits(input: Partial<PiAgentRetrievalLimits> | undefined): PiAgentRetrievalLimits {
306
- return {
307
- scanPageSize: clampLimit(
308
- input?.scanPageSize,
309
- DEFAULT_LIMITS.scanPageSize,
310
- MAX_LIMITS.scanPageSize,
311
- ),
312
- maxScannedLogs: clampLimit(
313
- input?.maxScannedLogs,
314
- DEFAULT_LIMITS.maxScannedLogs,
315
- MAX_LIMITS.maxScannedLogs,
316
- ),
317
- maxHydratedLogs: clampLimit(
318
- input?.maxHydratedLogs,
319
- DEFAULT_LIMITS.maxHydratedLogs,
320
- MAX_LIMITS.maxHydratedLogs,
321
- ),
322
- maxEvidence: clampLimit(input?.maxEvidence, DEFAULT_LIMITS.maxEvidence, MAX_LIMITS.maxEvidence),
323
- maxExcerptChars: clampLimit(
324
- input?.maxExcerptChars,
325
- DEFAULT_LIMITS.maxExcerptChars,
326
- MAX_LIMITS.maxExcerptChars,
327
- ),
328
- maxKnowledgeCandidates: clampLimit(
329
- input?.maxKnowledgeCandidates,
330
- DEFAULT_LIMITS.maxKnowledgeCandidates,
331
- MAX_LIMITS.maxKnowledgeCandidates,
332
- ),
333
- maxAuxiliaryRecords: clampLimit(
334
- input?.maxAuxiliaryRecords,
335
- DEFAULT_LIMITS.maxAuxiliaryRecords,
336
- MAX_LIMITS.maxAuxiliaryRecords,
337
- ),
338
- };
339
- }
340
-
341
- function replaceControlCharacters(value: string): string {
342
- let output = "";
343
- for (const character of value) {
344
- const code = character.charCodeAt(0);
345
- output += code <= 31 || (code >= 127 && code <= 159) ? " " : character;
346
- }
347
- return output;
348
- }
349
-
350
- function normalizeSearchText(value: string): string {
351
- return replaceControlCharacters(value)
352
- .normalize("NFKC")
353
- .toLocaleLowerCase()
354
- .replace(/\s+/g, " ")
355
- .trim();
356
- }
357
-
358
- function hasCjk(value: string): boolean {
359
- return /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u.test(value);
360
- }
361
-
362
- function appendCjkTerms(segment: string, output: Set<string>): void {
363
- const characters = [...segment];
364
- if (characters.length > 1) output.add(segment);
365
- for (const size of [2, 3]) {
366
- for (let index = 0; index + size <= characters.length; index += 1) {
367
- output.add(characters.slice(index, index + size).join(""));
368
- if (output.size >= 64) return;
369
- }
370
- }
371
- }
372
-
373
- function extractTerms(value: string): string[] {
374
- const output = new Set<string>();
375
- for (const match of value.matchAll(/[\p{L}\p{N}][\p{L}\p{N}_.:/-]*/gu)) {
376
- const token = match[0];
377
- if (token.length < 2 || hasCjk(token) || ENGLISH_STOP_WORDS.has(token)) continue;
378
- output.add(token);
379
- if (output.size >= 64) return [...output];
380
- }
381
- for (const match of value.matchAll(
382
- /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu,
383
- )) {
384
- appendCjkTerms(match[0], output);
385
- if (output.size >= 64) break;
386
- }
387
- return [...output];
388
- }
389
-
390
- function hasAlias(value: string, aliases: readonly string[]): boolean {
391
- return aliases.some((alias) => value.includes(alias));
392
- }
393
-
394
- function isReferential(value: string): boolean {
395
- return REFERENTIAL_MARKERS.some((marker) => value.includes(marker));
396
- }
397
-
398
- function buildQueryPlan(input: PiAgentRetrievalInput): QueryPlan {
399
- const current = normalizeSearchText(input.question.slice(0, 4_000));
400
- const previous = normalizeSearchText(input.recentUserQuestion?.slice(0, 2_000) ?? "");
401
- const retrievalText =
402
- isReferential(current) && previous !== "" ? `${current} ${previous}` : current;
403
- const terms = extractTerms(retrievalText);
404
- return {
405
- phrase: current.length >= 2 && current.length <= 240 ? current : "",
406
- terms,
407
- intents: {
408
- failure: hasAlias(retrievalText, INTENT_ALIASES.failure),
409
- pending: hasAlias(retrievalText, INTENT_ALIASES.pending),
410
- performance: hasAlias(retrievalText, INTENT_ALIASES.performance),
411
- tokens: hasAlias(retrievalText, INTENT_ALIASES.tokens),
412
- tools: hasAlias(retrievalText, INTENT_ALIASES.tools),
413
- sessions: hasAlias(retrievalText, INTENT_ALIASES.sessions),
414
- overview: current === "" || hasAlias(retrievalText, INTENT_ALIASES.overview),
415
- },
416
- };
417
- }
418
-
419
- function scoreFields(query: QueryPlan, fields: readonly SearchField[]): ScoreResult {
420
- let score = 0;
421
- const matchedFields = new Set<string>();
422
- for (const field of fields) {
423
- const normalized = normalizeSearchText(field.text);
424
- if (normalized === "") continue;
425
- let matched = false;
426
- if (query.phrase !== "" && normalized.includes(query.phrase)) {
427
- score += field.weight * 3;
428
- matched = true;
429
- }
430
- let termMatches = 0;
431
- for (const term of query.terms) {
432
- if (normalized.includes(term)) termMatches += 1;
433
- if (termMatches >= 4) break;
434
- }
435
- if (termMatches > 0) {
436
- score += field.weight * termMatches;
437
- matched = true;
438
- }
439
- if (matched) matchedFields.add(field.name);
440
- }
441
- return { score, matchedFields: [...matchedFields] };
442
- }
443
-
444
- function addScore(result: ScoreResult, score: number, field: string): void {
445
- result.score += score;
446
- if (!result.matchedFields.includes(field)) result.matchedFields.push(field);
447
- }
448
-
449
- function isFailedLog(log: CapturedLog): boolean {
450
- const hasError = log.error !== undefined && log.error !== null && log.error.trim() !== "";
451
- return (log.responseStatus !== null && log.responseStatus >= 400) || hasError;
452
- }
453
-
454
- function scoreLogMetadata(log: CapturedLog, query: QueryPlan): ScoreResult {
455
- const result = scoreFields(query, [
456
- { name: "sessionId", text: log.sessionId ?? "", weight: 14 },
457
- { name: "model", text: log.model ?? "", weight: 12 },
458
- { name: "providerName", text: log.providerName ?? "", weight: 11 },
459
- { name: "path", text: log.path, weight: 9 },
460
- { name: "error", text: log.error ?? "", weight: 13 },
461
- { name: "warnings", text: log.warnings?.join(" ") ?? "", weight: 10 },
462
- { name: "responseStatus", text: log.responseStatus?.toString() ?? "pending", weight: 8 },
463
- { name: "apiFormat", text: log.apiFormat, weight: 5 },
464
- { name: "project", text: log.clientProjectFolder ?? "", weight: 4 },
465
- ]);
466
-
467
- if (query.intents.failure && isFailedLog(log)) addScore(result, 24, "failure");
468
- if (query.intents.failure && (log.warnings?.length ?? 0) > 0) {
469
- addScore(result, 12, "warnings");
470
- }
471
- if (query.intents.pending && log.responseStatus === null) addScore(result, 28, "pending");
472
- if (query.intents.performance && log.elapsedMs !== null) {
473
- addScore(result, 4 + Math.min(18, Math.log2(Math.max(1, log.elapsedMs))), "elapsedMs");
474
- }
475
- if (query.intents.tokens && (log.inputTokens !== null || log.outputTokens !== null)) {
476
- addScore(result, 8, "tokens");
477
- }
478
- if (query.intents.tools) addScore(result, 1, "toolTraceCandidate");
479
- if (query.intents.sessions && log.sessionId !== null) addScore(result, 3, "sessionId");
480
- if (query.intents.overview) addScore(result, 1, "overviewScope");
481
- return result;
482
- }
483
-
484
- function scoreHydratedLog(log: CapturedLog, query: QueryPlan): ScoreResult {
485
- const metadata = scoreLogMetadata(log, query);
486
- const bodies = scoreFields(query, [
487
- { name: "requestBody", text: log.rawRequestBody ?? "", weight: 9 },
488
- { name: "responseBody", text: log.responseText ?? "", weight: 8 },
489
- ]);
490
- for (const field of bodies.matchedFields) {
491
- if (!metadata.matchedFields.includes(field)) metadata.matchedFields.push(field);
492
- }
493
- metadata.score += bodies.score;
494
- return metadata;
495
- }
496
-
497
- function compareRankedLogs(left: RankedLog, right: RankedLog): number {
498
- return (
499
- right.score - left.score ||
500
- right.log.timestamp.localeCompare(left.log.timestamp) ||
501
- right.log.id - left.log.id
502
- );
503
- }
504
-
505
- async function scanLogs(
506
- input: PiAgentRetrievalInput,
507
- limits: PiAgentRetrievalLimits,
508
- dependencies: PiAgentRetrievalDependencies,
509
- ): Promise<ScanResult> {
510
- const logsById = new Map<number, CapturedLog>();
511
- let offset = 0;
512
- let knownTotal = 0;
513
- let truncated = false;
514
- while (offset < limits.maxScannedLogs) {
515
- const limit = Math.min(limits.scanPageSize, limits.maxScannedLogs - offset);
516
- let page: ListLogsPageResult;
517
- try {
518
- page = await dependencies.listLogPage({
519
- sessionId: input.sessionId,
520
- offset,
521
- limit,
522
- includeBodies: false,
523
- });
524
- } catch {
525
- truncated = true;
526
- break;
527
- }
528
- knownTotal = page.total;
529
- for (const log of page.logs) logsById.set(log.id, log);
530
- offset += page.logs.length;
531
- if (page.logs.length === 0 || offset >= page.total) break;
532
- }
533
- if (knownTotal > logsById.size) truncated = true;
534
- return {
535
- logs: [...logsById.values()],
536
- total: Math.max(knownTotal, logsById.size),
537
- truncated,
538
- };
539
- }
540
-
541
- async function readLogSafely(
542
- id: number,
543
- dependencies: PiAgentRetrievalDependencies,
544
- ): Promise<CapturedLog | null> {
545
- try {
546
- return await dependencies.getLog(id);
547
- } catch {
548
- return null;
549
- }
550
- }
551
-
552
- async function hydrateRankedLogs(
553
- ranked: readonly RankedLog[],
554
- query: QueryPlan,
555
- limits: PiAgentRetrievalLimits,
556
- dependencies: PiAgentRetrievalDependencies,
557
- ): Promise<{ ranked: RankedLog[]; hydrated: number }> {
558
- const hydrationPool = ranked.slice(0, limits.maxHydratedLogs);
559
- const hydratedById = new Map<number, RankedLog>();
560
- let hydrated = 0;
561
- for (let offset = 0; offset < hydrationPool.length; offset += 8) {
562
- const batch = hydrationPool.slice(offset, offset + 8);
563
- const logs = await Promise.all(
564
- batch.map(async (candidate) => readLogSafely(candidate.log.id, dependencies)),
565
- );
566
- for (const log of logs) {
567
- if (log === null) continue;
568
- hydrated += 1;
569
- hydratedById.set(log.id, { log, ...scoreHydratedLog(log, query) });
570
- }
571
- }
572
- return {
573
- ranked: ranked
574
- .map((candidate) => hydratedById.get(candidate.log.id) ?? candidate)
575
- .sort(compareRankedLogs),
576
- hydrated,
577
- };
578
- }
579
-
580
- function sanitizeUnknown(value: unknown, depth = 0): unknown {
581
- if (depth > 6) return "[bounded]";
582
- if (value === null || typeof value === "boolean" || typeof value === "number") return value;
583
- if (typeof value === "string") return sanitizeText(value);
584
- if (Array.isArray(value))
585
- return value.slice(0, 40).map((item) => sanitizeUnknown(item, depth + 1));
586
- if (typeof value !== "object") return String(value);
587
-
588
- const output: Record<string, unknown> = {};
589
- for (const [key, child] of Object.entries(value).slice(0, 60)) {
590
- if (SENSITIVE_KEY_PATTERN.test(key)) continue;
591
- output[key] = sanitizeUnknown(child, depth + 1);
592
- }
593
- return output;
594
- }
595
-
596
- function sanitizeText(value: string): string {
597
- return replaceControlCharacters(value)
598
- .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "[REDACTED]")
599
- .replace(/\bsk-[A-Za-z0-9_-]{6,}/gi, "[REDACTED]")
600
- .replace(
601
- /\b(?:raw[-_]?headers?|headers?|authorization|proxy[-_]?authorization|x[-_]?api[-_]?key|api[-_]?key|access[-_]?token|refresh[-_]?token|password|passwd|secret|cookie|set[-_]?cookie)\b\s*[=:]\s*(?:"[^"]*"|'[^']*'|[^\s,;}]+)/gi,
602
- "[REDACTED]",
603
- )
604
- .replace(
605
- /\b(?:rawheaders|headers|authorization|proxy-authorization|x-api-key|apikey|api_key|access_token|refresh_token)\b/gi,
606
- "[sensitive-field]",
607
- )
608
- .replace(/\s+/g, " ")
609
- .trim();
610
- }
611
-
612
- export function sanitizePiAgentEvidenceText(value: string): string {
613
- try {
614
- const parsed: unknown = JSON.parse(value);
615
- return sanitizeText(JSON.stringify(sanitizeUnknown(parsed)));
616
- } catch {
617
- return sanitizeText(value);
618
- }
619
- }
620
-
621
- function excerptAroundTerms(value: string, query: QueryPlan, maxLength: number): string {
622
- const sanitized = sanitizePiAgentEvidenceText(value);
623
- if (sanitized.length <= maxLength) return sanitized;
624
- const normalized = normalizeSearchText(sanitized);
625
- const anchors = query.phrase === "" ? query.terms : [query.phrase, ...query.terms];
626
- let matchIndex = -1;
627
- for (const anchor of anchors) {
628
- matchIndex = normalized.indexOf(anchor);
629
- if (matchIndex >= 0) break;
630
- }
631
- const start = matchIndex < 0 ? 0 : Math.max(0, matchIndex - Math.floor(maxLength / 3));
632
- const end = Math.min(sanitized.length, start + maxLength);
633
- return `${start > 0 ? "…" : ""}${sanitized.slice(start, end)}${end < sanitized.length ? "…" : ""}`;
634
- }
635
-
636
- function firstMatchingBody(log: CapturedLog, matchedFields: readonly string[]): string | null {
637
- if (matchedFields.includes("requestBody") && log.rawRequestBody !== null) {
638
- return log.rawRequestBody;
639
- }
640
- if (matchedFields.includes("responseBody") && log.responseText !== null) {
641
- return log.responseText;
642
- }
643
- if (log.error !== undefined && log.error !== null && log.error.trim() !== "") return log.error;
644
- if (log.warnings !== undefined && log.warnings.length > 0) return log.warnings.join(" | ");
645
- return null;
646
- }
647
-
648
- function logExcerpt(
649
- log: CapturedLog,
650
- candidate: RankedLog,
651
- query: QueryPlan,
652
- maxLength: number,
653
- ): string {
654
- const body = firstMatchingBody(log, candidate.matchedFields);
655
- if (body !== null) return excerptAroundTerms(body, query, maxLength);
656
- const metadata = [
657
- `Log ${String(log.id)}`,
658
- `session ${log.sessionId ?? "unknown"}`,
659
- `model ${log.model ?? "unknown"}`,
660
- `provider ${log.providerName ?? "unknown"}`,
661
- `path ${log.path}`,
662
- `status ${log.responseStatus?.toString() ?? "pending"}`,
663
- `elapsed ${log.elapsedMs?.toString() ?? "unknown"} ms`,
664
- ].join(" · ");
665
- return excerptAroundTerms(metadata, query, maxLength);
666
- }
667
-
668
- function logEvidence(
669
- candidate: RankedLog,
670
- query: QueryPlan,
671
- maxExcerptChars: number,
672
- ): PiAgentEvidence {
673
- const log = candidate.log;
674
- return {
675
- source: "log",
676
- id: String(log.id),
677
- logId: log.id,
678
- timestamp: log.timestamp,
679
- sessionId: log.sessionId ?? undefined,
680
- model: log.model ?? undefined,
681
- providerName: log.providerName ?? undefined,
682
- path: log.path,
683
- status: log.responseStatus,
684
- elapsedMs: log.elapsedMs ?? undefined,
685
- inputTokens: log.inputTokens ?? undefined,
686
- outputTokens: log.outputTokens ?? undefined,
687
- score: Math.round(candidate.score * 100) / 100,
688
- matchedFields: candidate.matchedFields,
689
- excerpt: logExcerpt(log, candidate, query, maxExcerptChars),
690
- entityType: "log",
691
- title: `Log #${String(log.id)}`,
692
- };
693
- }
694
-
695
- function safeMetadataText(value: Record<string, unknown>): string {
696
- return sanitizeText(JSON.stringify(sanitizeUnknown(value)));
697
- }
698
-
699
- function scoreKnowledge(candidate: KnowledgeCandidate, query: QueryPlan): ScoreResult {
700
- const result = scoreFields(query, [
701
- { name: "knowledgeId", text: candidate.id, weight: 10 },
702
- { name: "title", text: candidate.title, weight: 12 },
703
- { name: "content", text: candidate.content, weight: 9 },
704
- { name: "tags", text: candidate.tags.join(" "), weight: 8 },
705
- { name: "knowledgeType", text: candidate.type, weight: 6 },
706
- { name: "knowledgeStatus", text: candidate.status, weight: 5 },
707
- { name: "sessionId", text: candidate.sessionId, weight: 10 },
708
- { name: "logIds", text: candidate.logIds.join(" "), weight: 4 },
709
- ]);
710
- if (query.intents.failure && candidate.status === "failed") {
711
- addScore(result, 12, "knowledgeStatus");
712
- }
713
- if (query.intents.overview) addScore(result, 1, "overviewScope");
714
- return result;
715
- }
716
-
717
- function knowledgeEvidence(
718
- candidate: KnowledgeCandidate,
719
- score: ScoreResult,
720
- query: QueryPlan,
721
- maxExcerptChars: number,
722
- ): PiAgentEvidence {
723
- return {
724
- source: "knowledge",
725
- id: candidate.id,
726
- knowledgeId: candidate.id,
727
- logIds: candidate.logIds,
728
- timestamp: candidate.updatedAt,
729
- sessionId: candidate.sessionId,
730
- status: candidate.status,
731
- score: Math.round(score.score * 100) / 100,
732
- matchedFields: score.matchedFields,
733
- excerpt: excerptAroundTerms(
734
- `${candidate.title}. ${candidate.content}. Tags: ${candidate.tags.join(", ")}`,
735
- query,
736
- maxExcerptChars,
737
- ),
738
- entityType: "knowledge-candidate",
739
- title: sanitizeText(candidate.title),
740
- knowledgeType: candidate.type,
741
- tags: candidate.tags
742
- .map(sanitizeText)
743
- .filter((tag) => tag !== "")
744
- .slice(0, 20),
745
- };
746
- }
747
-
748
- function scoreAlert(alert: Alert, query: QueryPlan): ScoreResult {
749
- const result = scoreFields(query, [
750
- { name: "alertId", text: alert.id, weight: 9 },
751
- { name: "title", text: alert.title, weight: 11 },
752
- { name: "message", text: alert.message, weight: 10 },
753
- { name: "category", text: alert.category, weight: 8 },
754
- { name: "severity", text: alert.severity, weight: 7 },
755
- { name: "sessionId", text: alert.sessionIds.join(" "), weight: 9 },
756
- { name: "providerName", text: alert.provider ?? "", weight: 8 },
757
- { name: "model", text: alert.model ?? "", weight: 8 },
758
- { name: "metadata", text: safeMetadataText(alert.metadata), weight: 3 },
759
- ]);
760
- if (query.intents.failure) addScore(result, alert.severity === "critical" ? 18 : 10, "alert");
761
- if (query.intents.performance && alert.category === "slow-response") {
762
- addScore(result, 16, "category");
763
- }
764
- if (query.intents.overview) addScore(result, 1, "overviewScope");
765
- return result;
766
- }
767
-
768
- function alertEvidence(
769
- alert: Alert,
770
- score: ScoreResult,
771
- query: QueryPlan,
772
- maxExcerptChars: number,
773
- ): PiAgentEvidence {
774
- return {
775
- source: "alert",
776
- id: alert.id,
777
- logIds: alert.logIds,
778
- timestamp: alert.lastSeenAt,
779
- sessionId: alert.sessionIds[0],
780
- model: alert.model ?? undefined,
781
- providerName: alert.provider ?? undefined,
782
- status: alert.status,
783
- score: Math.round(score.score * 100) / 100,
784
- matchedFields: score.matchedFields,
785
- excerpt: excerptAroundTerms(`${alert.title}. ${alert.message}`, query, maxExcerptChars),
786
- entityType: alert.category,
787
- title: sanitizeText(alert.title),
788
- };
789
- }
790
-
791
- function scoreRun(run: InspectorRun, query: QueryPlan): ScoreResult {
792
- const result = scoreFields(query, [
793
- { name: "runId", text: run.id, weight: 10 },
794
- { name: "sessionId", text: run.sessionId, weight: 11 },
795
- { name: "title", text: run.title, weight: 10 },
796
- { name: "task", text: run.task ?? "", weight: 9 },
797
- { name: "project", text: run.project ?? "", weight: 7 },
798
- { name: "agent", text: run.agent ?? "", weight: 7 },
799
- { name: "status", text: run.status, weight: 7 },
800
- { name: "tags", text: run.tags.join(" "), weight: 7 },
801
- { name: "metadata", text: safeMetadataText(run.metadata), weight: 3 },
802
- ]);
803
- if (query.intents.failure && run.status === "failed") addScore(result, 18, "status");
804
- if (query.intents.pending && (run.status === "created" || run.status === "running")) {
805
- addScore(result, 14, "status");
806
- }
807
- if (query.intents.overview) addScore(result, 1, "overviewScope");
808
- return result;
809
- }
810
-
811
- function runEvidence(
812
- run: InspectorRun,
813
- score: ScoreResult,
814
- query: QueryPlan,
815
- maxExcerptChars: number,
816
- ): PiAgentEvidence {
817
- return {
818
- source: "run",
819
- id: run.id,
820
- timestamp: run.updatedAt,
821
- sessionId: run.sessionId,
822
- status: run.status,
823
- score: Math.round(score.score * 100) / 100,
824
- matchedFields: score.matchedFields,
825
- excerpt: excerptAroundTerms(
826
- `${run.title}. ${run.task ?? ""} Project: ${run.project ?? "unknown"}. Agent: ${run.agent ?? "unknown"}`,
827
- query,
828
- maxExcerptChars,
829
- ),
830
- entityType: "run",
831
- title: sanitizeText(run.title),
832
- tags: run.tags
833
- .map(sanitizeText)
834
- .filter((tag) => tag !== "")
835
- .slice(0, 20),
836
- };
837
- }
838
-
839
- function groupSessions(group: InspectorGroup): string[] {
840
- return [...new Set(group.members.map((member) => member.sessionId))];
841
- }
842
-
843
- function scoreGroup(group: InspectorGroup, query: QueryPlan): ScoreResult {
844
- const result = scoreFields(query, [
845
- { name: "groupId", text: group.id, weight: 10 },
846
- { name: "title", text: group.title, weight: 10 },
847
- { name: "task", text: group.task ?? "", weight: 9 },
848
- { name: "project", text: group.project ?? "", weight: 7 },
849
- { name: "status", text: group.status, weight: 7 },
850
- { name: "tags", text: group.tags.join(" "), weight: 7 },
851
- { name: "sessionId", text: groupSessions(group).join(" "), weight: 9 },
852
- { name: "metadata", text: safeMetadataText(group.metadata), weight: 3 },
853
- ]);
854
- if (query.intents.failure && group.status === "failed") addScore(result, 18, "status");
855
- if (query.intents.pending && (group.status === "created" || group.status === "running")) {
856
- addScore(result, 14, "status");
857
- }
858
- if (query.intents.overview) addScore(result, 1, "overviewScope");
859
- return result;
860
- }
861
-
862
- function groupEvidence(
863
- group: InspectorGroup,
864
- score: ScoreResult,
865
- query: QueryPlan,
866
- maxExcerptChars: number,
867
- ): PiAgentEvidence {
868
- return {
869
- source: "group",
870
- id: group.id,
871
- timestamp: group.updatedAt,
872
- sessionId: groupSessions(group)[0],
873
- status: group.status,
874
- score: Math.round(score.score * 100) / 100,
875
- matchedFields: score.matchedFields,
876
- excerpt: excerptAroundTerms(
877
- `${group.title}. ${group.task ?? ""} Project: ${group.project ?? "unknown"}. Members: ${String(group.members.length)}`,
878
- query,
879
- maxExcerptChars,
880
- ),
881
- entityType: "group",
882
- title: sanitizeText(group.title),
883
- tags: group.tags
884
- .map(sanitizeText)
885
- .filter((tag) => tag !== "")
886
- .slice(0, 20),
887
- };
888
- }
889
-
890
- function scoreProvider(provider: ProviderConfig, query: QueryPlan): ScoreResult {
891
- const result = scoreFields(query, [
892
- { name: "providerId", text: provider.id, weight: 10 },
893
- { name: "providerName", text: provider.name, weight: 12 },
894
- { name: "model", text: provider.models.join(" "), weight: 10 },
895
- { name: "providerSource", text: provider.source ?? "", weight: 5 },
896
- { name: "apiFormat", text: provider.format ?? "", weight: 5 },
897
- ]);
898
- if (query.intents.overview) addScore(result, 1, "overviewScope");
899
- return result;
900
- }
901
-
902
- function providerEvidence(
903
- provider: ProviderConfig,
904
- score: ScoreResult,
905
- query: QueryPlan,
906
- maxExcerptChars: number,
907
- ): PiAgentEvidence {
908
- return {
909
- source: "provider",
910
- id: provider.id,
911
- timestamp: provider.updatedAt,
912
- providerName: provider.name,
913
- status: "configured",
914
- score: Math.round(score.score * 100) / 100,
915
- matchedFields: score.matchedFields,
916
- excerpt: excerptAroundTerms(
917
- `Provider ${provider.name}. Models: ${provider.models.join(", ") || "none"}. Source: ${provider.source ?? "unknown"}. Format: ${provider.format ?? "mixed"}.`,
918
- query,
919
- maxExcerptChars,
920
- ),
921
- entityType: "provider",
922
- title: sanitizeText(provider.name),
923
- };
924
- }
925
-
926
- function readSyncStore<T>(reader: () => T[]): T[] {
927
- try {
928
- return reader();
929
- } catch {
930
- return [];
931
- }
932
- }
933
-
934
- async function readAlertsStore(reader: () => Promise<Alert[]>): Promise<Alert[]> {
935
- try {
936
- return await reader();
937
- } catch {
938
- return [];
939
- }
940
- }
941
-
942
- function sessionMatches(
943
- candidateSessionIds: readonly string[],
944
- sessionId: string | undefined,
945
- ): boolean {
946
- return sessionId === undefined || candidateSessionIds.includes(sessionId);
947
- }
948
-
949
- function collectKnowledgeCandidates(
950
- candidates: readonly KnowledgeCandidate[],
951
- input: PiAgentRetrievalInput,
952
- query: QueryPlan,
953
- limits: PiAgentRetrievalLimits,
954
- ): SourceCandidate[] {
955
- const output: SourceCandidate[] = [];
956
- for (const candidate of candidates.slice(0, limits.maxKnowledgeCandidates)) {
957
- if (!sessionMatches([candidate.sessionId], input.sessionId)) continue;
958
- const score = scoreKnowledge(candidate, query);
959
- if (score.score <= 0) continue;
960
- output.push({
961
- evidence: knowledgeEvidence(candidate, score, query, limits.maxExcerptChars),
962
- sortTimestamp: candidate.updatedAt,
963
- });
964
- }
965
- return output;
966
- }
967
-
968
- function collectAlertCandidates(
969
- alerts: readonly Alert[],
970
- input: PiAgentRetrievalInput,
971
- query: QueryPlan,
972
- limits: PiAgentRetrievalLimits,
973
- ): SourceCandidate[] {
974
- const output: SourceCandidate[] = [];
975
- for (const alert of alerts.slice(0, limits.maxAuxiliaryRecords)) {
976
- if (!sessionMatches(alert.sessionIds, input.sessionId)) continue;
977
- const score = scoreAlert(alert, query);
978
- if (score.score <= 0) continue;
979
- output.push({
980
- evidence: alertEvidence(alert, score, query, limits.maxExcerptChars),
981
- sortTimestamp: alert.lastSeenAt,
982
- });
983
- }
984
- return output;
985
- }
986
-
987
- function collectRunCandidates(
988
- runs: readonly InspectorRun[],
989
- input: PiAgentRetrievalInput,
990
- query: QueryPlan,
991
- limits: PiAgentRetrievalLimits,
992
- ): SourceCandidate[] {
993
- const output: SourceCandidate[] = [];
994
- for (const run of runs.slice(0, limits.maxAuxiliaryRecords)) {
995
- if (!sessionMatches([run.sessionId], input.sessionId)) continue;
996
- const score = scoreRun(run, query);
997
- if (score.score <= 0) continue;
998
- output.push({
999
- evidence: runEvidence(run, score, query, limits.maxExcerptChars),
1000
- sortTimestamp: run.updatedAt,
1001
- });
1002
- }
1003
- return output;
1004
- }
1005
-
1006
- function collectGroupCandidates(
1007
- groups: readonly InspectorGroup[],
1008
- input: PiAgentRetrievalInput,
1009
- query: QueryPlan,
1010
- limits: PiAgentRetrievalLimits,
1011
- ): SourceCandidate[] {
1012
- const output: SourceCandidate[] = [];
1013
- for (const group of groups.slice(0, limits.maxAuxiliaryRecords)) {
1014
- const sessions = groupSessions(group);
1015
- if (!sessionMatches(sessions, input.sessionId)) continue;
1016
- const score = scoreGroup(group, query);
1017
- if (score.score <= 0) continue;
1018
- output.push({
1019
- evidence: groupEvidence(group, score, query, limits.maxExcerptChars),
1020
- sortTimestamp: group.updatedAt,
1021
- });
1022
- }
1023
- return output;
1024
- }
1025
-
1026
- function collectProviderCandidates(
1027
- providers: readonly ProviderConfig[],
1028
- input: PiAgentRetrievalInput,
1029
- query: QueryPlan,
1030
- limits: PiAgentRetrievalLimits,
1031
- ): SourceCandidate[] {
1032
- if (input.sessionId !== undefined) return [];
1033
- const output: SourceCandidate[] = [];
1034
- for (const provider of providers.slice(0, limits.maxAuxiliaryRecords)) {
1035
- const score = scoreProvider(provider, query);
1036
- if (score.score <= 0) continue;
1037
- output.push({
1038
- evidence: providerEvidence(provider, score, query, limits.maxExcerptChars),
1039
- sortTimestamp: provider.updatedAt,
1040
- });
1041
- }
1042
- return output;
1043
- }
1044
-
1045
- function countValues(values: readonly (string | null | undefined)[]): PiAgentCountEntry[] {
1046
- const counts = new Map<string, number>();
1047
- for (const value of values) {
1048
- if (value === null || value === undefined || value.trim() === "") continue;
1049
- counts.set(value, (counts.get(value) ?? 0) + 1);
1050
- }
1051
- return [...counts.entries()]
1052
- .map(([value, count]) => ({ value, count }))
1053
- .sort((left, right) => right.count - left.count || left.value.localeCompare(right.value));
1054
- }
1055
-
1056
- function sourceCounts(
1057
- candidates: readonly SourceCandidate[],
1058
- ): Record<PiAgentEvidenceSource, number> {
1059
- const counts: Record<PiAgentEvidenceSource, number> = {
1060
- log: 0,
1061
- knowledge: 0,
1062
- alert: 0,
1063
- run: 0,
1064
- group: 0,
1065
- provider: 0,
1066
- };
1067
- for (const candidate of candidates) {
1068
- counts[candidate.evidence.source] += 1;
1069
- }
1070
- return counts;
1071
- }
1072
-
1073
- function summarize(
1074
- logs: readonly RankedLog[],
1075
- candidates: readonly SourceCandidate[],
1076
- ): PiAgentRetrievalSummary {
1077
- const matchedLogs = logs
1078
- .filter((candidate) => candidate.score > 0)
1079
- .map((candidate) => candidate.log);
1080
- const latencies = matchedLogs
1081
- .map((log) => log.elapsedMs)
1082
- .filter((value): value is number => value !== null && Number.isFinite(value));
1083
- const latencyTotal = latencies.reduce((sum, value) => sum + value, 0);
1084
- const input = matchedLogs.reduce((sum, log) => sum + (log.inputTokens ?? 0), 0);
1085
- const output = matchedLogs.reduce((sum, log) => sum + (log.outputTokens ?? 0), 0);
1086
- const counts = sourceCounts(candidates);
1087
- return {
1088
- matchedLogs: matchedLogs.length,
1089
- knowledgeMatched: counts.knowledge,
1090
- failures: matchedLogs.filter(isFailedLog).length,
1091
- pending: matchedLogs.filter((log) => log.responseStatus === null).length,
1092
- sessions: new Set(
1093
- matchedLogs
1094
- .map((log) => log.sessionId)
1095
- .filter((sessionId): sessionId is string => sessionId !== null),
1096
- ).size,
1097
- models: countValues(matchedLogs.map((log) => log.model)),
1098
- providers: countValues(matchedLogs.map((log) => log.providerName)),
1099
- latency: {
1100
- count: latencies.length,
1101
- minMs: latencies.length > 0 ? Math.min(...latencies) : null,
1102
- maxMs: latencies.length > 0 ? Math.max(...latencies) : null,
1103
- averageMs:
1104
- latencies.length > 0 ? Math.round((latencyTotal / latencies.length) * 100) / 100 : null,
1105
- },
1106
- tokens: { input, output, total: input + output },
1107
- sourceCounts: counts,
1108
- };
1109
- }
1110
-
1111
- function compareSourceCandidates(left: SourceCandidate, right: SourceCandidate): number {
1112
- return (
1113
- right.evidence.score - left.evidence.score ||
1114
- right.sortTimestamp.localeCompare(left.sortTimestamp) ||
1115
- left.evidence.id.localeCompare(right.evidence.id)
1116
- );
1117
- }
1118
-
1119
- export async function retrievePiAgentEvidence(
1120
- input: PiAgentRetrievalInput,
1121
- dependencies: PiAgentRetrievalDependencies = DEFAULT_DEPENDENCIES,
1122
- ): Promise<PiAgentRetrievalResult> {
1123
- const startedAt = Date.now();
1124
- const limits = resolveLimits(input.limits);
1125
- const query = buildQueryPlan(input);
1126
- const [scan, alerts] = await Promise.all([
1127
- scanLogs(input, limits, dependencies),
1128
- readAlertsStore(dependencies.listInspectorAlerts),
1129
- ]);
1130
- const knowledge = readSyncStore(dependencies.listKnowledgeCandidates);
1131
- const runs = readSyncStore(dependencies.listInspectorRuns);
1132
- const groups = readSyncStore(dependencies.listInspectorGroups);
1133
- const providers = readSyncStore(dependencies.listInspectorProviders);
1134
-
1135
- const metadataRanked = scan.logs
1136
- .map((log): RankedLog => ({ log, ...scoreLogMetadata(log, query) }))
1137
- .sort(compareRankedLogs);
1138
- const hydrated = await hydrateRankedLogs(metadataRanked, query, limits, dependencies);
1139
- const matchedLogs = hydrated.ranked.filter((candidate) => candidate.score > 0);
1140
- const logCandidates: SourceCandidate[] = matchedLogs.map((candidate) => ({
1141
- evidence: logEvidence(candidate, query, limits.maxExcerptChars),
1142
- sortTimestamp: candidate.log.timestamp,
1143
- }));
1144
- const auxiliaryCandidates = [
1145
- ...collectKnowledgeCandidates(knowledge, input, query, limits),
1146
- ...collectAlertCandidates(alerts, input, query, limits),
1147
- ...collectRunCandidates(runs, input, query, limits),
1148
- ...collectGroupCandidates(groups, input, query, limits),
1149
- ...collectProviderCandidates(providers, input, query, limits),
1150
- ];
1151
- const allCandidates = [...logCandidates, ...auxiliaryCandidates].sort(compareSourceCandidates);
1152
- const evidence = allCandidates
1153
- .slice(0, limits.maxEvidence)
1154
- .map((candidate) => candidate.evidence);
1155
- const matchedKnowledge = auxiliaryCandidates.filter(
1156
- (candidate) => candidate.evidence.source === "knowledge",
1157
- ).length;
1158
- const boundedSource =
1159
- knowledge.length > limits.maxKnowledgeCandidates ||
1160
- alerts.length > limits.maxAuxiliaryRecords ||
1161
- runs.length > limits.maxAuxiliaryRecords ||
1162
- groups.length > limits.maxAuxiliaryRecords ||
1163
- providers.length > limits.maxAuxiliaryRecords;
1164
- const truncated = scan.truncated || boundedSource || allCandidates.length > limits.maxEvidence;
1165
-
1166
- return {
1167
- summary: summarize(hydrated.ranked, allCandidates),
1168
- queryStats: {
1169
- scannedLogs: scan.logs.length,
1170
- hydratedLogs: hydrated.hydrated,
1171
- matchedLogs: matchedLogs.length,
1172
- scannedKnowledge: Math.min(knowledge.length, limits.maxKnowledgeCandidates),
1173
- matchedKnowledge,
1174
- returnedEvidence: evidence.length,
1175
- truncated,
1176
- durationMs: Math.max(0, Date.now() - startedAt),
1177
- },
1178
- evidence,
1179
- };
1180
- }