@tonyclaw/agent-inspector 3.1.32 → 4.0.2

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 +241 -120
  3. package/.output/server/_ssr/index.mjs +1 -1
  4. package/.output/server/_ssr/{router-oXUk3MBR.mjs → router-BBY_zWRK.mjs} +91 -3
  5. package/.output/server/index.mjs +1 -1
  6. package/.output/ui/assets/{CompareDrawer-BtfPSpkV.js → CompareDrawer-rtNElN-B.js} +1 -1
  7. package/.output/ui/assets/{InspectorPet-D9DPPQ3n.js → InspectorPet-QaAiuF3d.js} +1 -1
  8. package/.output/ui/assets/{ProxyViewerContainer-Buu8vkCK.js → ProxyViewerContainer-6twNZHwl.js} +4 -4
  9. package/.output/ui/assets/{ReplayDialog-BER-QzpD.js → ReplayDialog-B7KlziO2.js} +1 -1
  10. package/.output/ui/assets/{RequestAnatomy-C8Zwxrr7.js → RequestAnatomy-2XVFBrW4.js} +1 -1
  11. package/.output/ui/assets/{ResponseView-DDpKdYk6.js → ResponseView-BULgzLVB.js} +1 -1
  12. package/.output/ui/assets/{StreamingChunkSequence-sMPGG7Sw.js → StreamingChunkSequence-DSkvkbns.js} +1 -1
  13. package/.output/ui/assets/{_sessionId-e4IheHnP.js → _sessionId-D2dmJi3G.js} +1 -1
  14. package/.output/ui/assets/{_sessionId-C5Uv72Fx.js → _sessionId-DcS0s1Mr.js} +1 -1
  15. package/.output/ui/assets/{index-B__qT0Yd.js → index-B0TN1KKO.js} +2 -2
  16. package/.output/ui/assets/{index-Be3bTCzi.js → index-Bva1zHEs.js} +1 -1
  17. package/.output/ui/assets/{index-C9q__p8J.js → index-BzBExOxu.js} +1 -1
  18. package/.output/ui/assets/{index-CtB0deSZ.js → index-k6sRQz55.js} +1 -1
  19. package/.output/ui/assets/{json-viewer-Db0AFp-7.js → json-viewer-CWM4tY-j.js} +1 -1
  20. package/.output/ui/assets/{jszip.min-DkY0Ym_q.js → jszip.min-BkWvRFlo.js} +1 -1
  21. package/.output/ui/index.html +1 -1
  22. package/package.json +8 -13
  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 -1397
  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 -253
  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,731 +0,0 @@
1
- import { randomUUID } from "node:crypto";
2
- import {
3
- closeSync,
4
- type Dirent,
5
- existsSync,
6
- mkdirSync,
7
- openSync,
8
- readFileSync,
9
- readdirSync,
10
- realpathSync,
11
- renameSync,
12
- rmSync,
13
- statSync,
14
- writeFileSync,
15
- } from "node:fs";
16
- import { createServer } from "node:net";
17
- import { homedir } from "node:os";
18
- import { join, posix, win32 } from "node:path";
19
- import { z } from "zod";
20
- import {
21
- ensurePrivateDirectorySync,
22
- PRIVATE_FILE_MODE,
23
- securePrivateFileSync,
24
- } from "../proxy/privateDataPath";
25
- import {
26
- InstanceRecordSchema,
27
- instanceRegistryError,
28
- instanceRegistrySuccess,
29
- type InstanceRecord,
30
- type InstanceRegistryResult,
31
- validateInstanceName,
32
- } from "./instanceModel";
33
-
34
- export {
35
- createInstanceRecord,
36
- INSTANCE_OUTPUT_SCHEMA_VERSION,
37
- INSTANCE_RECORD_SCHEMA_VERSION,
38
- InstanceLaunchSchema,
39
- InstanceRecordSchema,
40
- instanceRegistryError,
41
- instanceRegistrySuccess,
42
- MAX_INSTANCE_NAME_LENGTH,
43
- normalizeInstanceBasePath,
44
- rotateInstanceLaunch,
45
- toInstanceRecordOutput,
46
- validateInstanceName,
47
- } from "./instanceModel";
48
- export type {
49
- CreateInstanceRecordInput,
50
- InstanceIdentityFactory,
51
- InstanceLaunch,
52
- InstanceRecord,
53
- InstanceRecordOutput,
54
- InstanceRegistryError,
55
- InstanceRegistryErrorCode,
56
- InstanceRegistryResult,
57
- } from "./instanceModel";
58
-
59
- export const AGENT_INSPECTOR_INSTANCES_DIR_ENV = "AGENT_INSPECTOR_INSTANCES_DIR";
60
- export const DEFAULT_NAMED_INSTANCE_PUBLIC_PORT = 9530;
61
- export const NAMED_INSTANCE_PORT_STEP = 3;
62
- export const NAMED_INSTANCE_UPSTREAM_OFFSET = 2;
63
- export const DEFAULT_INSTANCE_LOCK_TIMEOUT_MS = 10_000;
64
- export const DEFAULT_INSTANCE_LOCK_STALE_MS = 30_000;
65
-
66
- const INSTANCE_RECORD_FILE_NAME = "instance.json";
67
- const ROOT_LOCK_DIRECTORY_NAME = ".allocation.lock";
68
- const INSTANCE_LOCK_DIRECTORY_NAME = ".mutation.lock";
69
- const LOCK_OWNER_FILE_NAME = "owner.json";
70
- const DEFAULT_LOCK_RETRY_MS = 50;
71
-
72
- type InstanceRootEnv = Readonly<Record<string, string | undefined>>;
73
-
74
- export type InstancePaths = {
75
- root: string;
76
- instanceDir: string;
77
- dataDir: string;
78
- recordPath: string;
79
- lockPath: string;
80
- };
81
-
82
- export function getInstancesRoot(
83
- env: InstanceRootEnv = process.env,
84
- platform: typeof process.platform = process.platform,
85
- ): string {
86
- const pathApi = platform === "win32" ? win32 : posix;
87
- const explicitRoot = env[AGENT_INSPECTOR_INSTANCES_DIR_ENV];
88
- if (explicitRoot !== undefined && explicitRoot.trim().length > 0) {
89
- return pathApi.isAbsolute(explicitRoot) ? explicitRoot : pathApi.resolve(explicitRoot);
90
- }
91
-
92
- if (platform === "win32") {
93
- const localAppData = env["LOCALAPPDATA"];
94
- if (localAppData !== undefined && localAppData.trim().length > 0) {
95
- return win32.join(localAppData, "agent-inspector", "instances");
96
- }
97
- const userProfile = env["USERPROFILE"];
98
- const fallback =
99
- userProfile !== undefined && userProfile.trim().length > 0 ? userProfile : homedir();
100
- return win32.join(fallback, ".agent-inspector", "instances");
101
- }
102
-
103
- const home = env["HOME"];
104
- const base = home !== undefined && home.trim().length > 0 ? home : homedir();
105
- return posix.join(base, ".agent-inspector", "instances");
106
- }
107
-
108
- export function getInstancePaths(
109
- root: string,
110
- rawName: string,
111
- ): InstanceRegistryResult<InstancePaths> {
112
- const name = validateInstanceName(rawName);
113
- if (name.kind === "error") return name;
114
- const instanceDir = join(root, name.value);
115
- return instanceRegistrySuccess({
116
- root,
117
- instanceDir,
118
- dataDir: join(instanceDir, "data"),
119
- recordPath: join(instanceDir, INSTANCE_RECORD_FILE_NAME),
120
- lockPath: join(instanceDir, INSTANCE_LOCK_DIRECTORY_NAME),
121
- });
122
- }
123
-
124
- export function ensureInstancesRoot(root = getInstancesRoot()): InstanceRegistryResult<string> {
125
- return ensurePrivateDirectorySync(root)
126
- ? instanceRegistrySuccess(root)
127
- : instanceRegistryError(
128
- "registry_io",
129
- `Cannot create or secure the private instance registry at ${root}.`,
130
- );
131
- }
132
-
133
- function nodeErrorCode(error: unknown): string | null {
134
- if (typeof error !== "object" || error === null) return null;
135
- const descriptor = Object.getOwnPropertyDescriptor(error, "code");
136
- return typeof descriptor?.value === "string" ? descriptor.value : null;
137
- }
138
-
139
- function readRecordFile(recordPath: string): InstanceRegistryResult<InstanceRecord> {
140
- let parsedJson: unknown;
141
- try {
142
- parsedJson = JSON.parse(readFileSync(recordPath, "utf8"));
143
- } catch {
144
- return instanceRegistryError(
145
- "record_invalid",
146
- `Instance record ${recordPath} is unreadable or is not valid JSON.`,
147
- );
148
- }
149
-
150
- const parsed = InstanceRecordSchema.safeParse(parsedJson);
151
- return parsed.success
152
- ? instanceRegistrySuccess(parsed.data)
153
- : instanceRegistryError(
154
- "record_invalid",
155
- `Instance record ${recordPath} does not match schema version 1: ${parsed.error.issues[0]?.message ?? "invalid record"}.`,
156
- );
157
- }
158
-
159
- export function readInstanceRecord(
160
- root: string,
161
- rawName: string,
162
- ): InstanceRegistryResult<InstanceRecord | null> {
163
- const paths = getInstancePaths(root, rawName);
164
- if (paths.kind === "error") return paths;
165
- if (!existsSync(paths.value.recordPath)) return instanceRegistrySuccess(null);
166
- return readRecordFile(paths.value.recordPath);
167
- }
168
-
169
- export function listInstanceRecords(
170
- root: string,
171
- ): InstanceRegistryResult<readonly InstanceRecord[]> {
172
- if (!existsSync(root)) return instanceRegistrySuccess([]);
173
-
174
- let entries: Dirent<string>[];
175
- try {
176
- entries = readdirSync(root, { withFileTypes: true });
177
- } catch {
178
- return instanceRegistryError("registry_io", `Cannot read the instance registry at ${root}.`);
179
- }
180
-
181
- const records: InstanceRecord[] = [];
182
- const names = new Set<string>();
183
- for (const entry of entries) {
184
- if (!entry.isDirectory()) continue;
185
- const recordPath = join(root, entry.name, INSTANCE_RECORD_FILE_NAME);
186
- if (!existsSync(recordPath)) continue;
187
- const record = readRecordFile(recordPath);
188
- if (record.kind === "error") return record;
189
- const expectedName = validateInstanceName(entry.name);
190
- if (
191
- expectedName.kind === "error" ||
192
- record.value.name !== expectedName.value ||
193
- names.has(record.value.name)
194
- ) {
195
- return instanceRegistryError(
196
- "record_invalid",
197
- `Instance directory ${entry.name} does not uniquely match its saved normalized name.`,
198
- );
199
- }
200
- names.add(record.value.name);
201
- records.push(record.value);
202
- }
203
- records.sort((left, right) => left.name.localeCompare(right.name));
204
- return instanceRegistrySuccess(records);
205
- }
206
-
207
- function cleanupFile(path: string): void {
208
- try {
209
- rmSync(path, { force: true });
210
- } catch {
211
- // Best effort: a failed atomic write must not hide the original error.
212
- }
213
- }
214
-
215
- export function writeInstanceRecord(
216
- root: string,
217
- record: InstanceRecord,
218
- ): InstanceRegistryResult<InstanceRecord> {
219
- const validated = InstanceRecordSchema.safeParse(record);
220
- if (!validated.success) {
221
- return instanceRegistryError(
222
- "record_invalid",
223
- `Cannot save instance record: ${validated.error.issues[0]?.message ?? "invalid record"}.`,
224
- );
225
- }
226
- const paths = getInstancePaths(root, validated.data.name);
227
- if (paths.kind === "error") return paths;
228
- const rootResult = ensureInstancesRoot(root);
229
- if (rootResult.kind === "error") return rootResult;
230
- if (!ensurePrivateDirectorySync(paths.value.instanceDir)) {
231
- return instanceRegistryError(
232
- "registry_io",
233
- `Cannot create or secure the private directory for instance ${validated.data.name}.`,
234
- );
235
- }
236
- if (!ensurePrivateDirectorySync(validated.data.dataDir)) {
237
- return instanceRegistryError(
238
- "registry_io",
239
- `Cannot create or secure the data directory for instance ${validated.data.name}.`,
240
- );
241
- }
242
-
243
- const temporaryPath = join(
244
- paths.value.instanceDir,
245
- `.${INSTANCE_RECORD_FILE_NAME}.${String(process.pid)}.${randomUUID()}.tmp`,
246
- );
247
- let descriptor: number | null = null;
248
- try {
249
- descriptor = openSync(temporaryPath, "wx", PRIVATE_FILE_MODE);
250
- writeFileSync(descriptor, `${JSON.stringify(validated.data, null, 2)}\n`, "utf8");
251
- closeSync(descriptor);
252
- descriptor = null;
253
- if (!securePrivateFileSync(temporaryPath)) {
254
- cleanupFile(temporaryPath);
255
- return instanceRegistryError(
256
- "registry_io",
257
- `Cannot secure the saved record for instance ${validated.data.name}.`,
258
- );
259
- }
260
- renameSync(temporaryPath, paths.value.recordPath);
261
- return instanceRegistrySuccess(validated.data);
262
- } catch {
263
- if (descriptor !== null) {
264
- try {
265
- closeSync(descriptor);
266
- } catch {
267
- // The original write error remains the actionable failure.
268
- }
269
- }
270
- cleanupFile(temporaryPath);
271
- return instanceRegistryError(
272
- "registry_io",
273
- `Cannot atomically save the record for instance ${validated.data.name}.`,
274
- );
275
- }
276
- }
277
-
278
- const InstanceLockOwnerSchema = z
279
- .object({
280
- schemaVersion: z.literal(1),
281
- pid: z.number().int().positive(),
282
- token: z.string().min(8),
283
- createdAt: z.string().datetime(),
284
- })
285
- .strict();
286
-
287
- type InstanceLockOwner = z.infer<typeof InstanceLockOwnerSchema>;
288
-
289
- export type InstanceLockHandle = {
290
- path: string;
291
- release: () => InstanceRegistryResult<void>;
292
- };
293
-
294
- export type InstanceLockOptions = {
295
- timeoutMs?: number;
296
- retryDelayMs?: number;
297
- staleAfterMs?: number;
298
- pid?: number;
299
- now?: () => number;
300
- sleep?: (milliseconds: number) => Promise<void>;
301
- isProcessAlive?: (pid: number) => boolean;
302
- createToken?: () => string;
303
- };
304
-
305
- function defaultSleep(milliseconds: number): Promise<void> {
306
- return new Promise((resolveSleep) => {
307
- setTimeout(resolveSleep, milliseconds);
308
- });
309
- }
310
-
311
- function defaultIsProcessAlive(pid: number): boolean {
312
- if (pid === process.pid) return true;
313
- try {
314
- process.kill(pid, 0);
315
- return true;
316
- } catch (error) {
317
- return nodeErrorCode(error) !== "ESRCH";
318
- }
319
- }
320
-
321
- function readLockOwner(lockPath: string): InstanceLockOwner | null {
322
- try {
323
- const raw: unknown = JSON.parse(readFileSync(join(lockPath, LOCK_OWNER_FILE_NAME), "utf8"));
324
- const parsed = InstanceLockOwnerSchema.safeParse(raw);
325
- return parsed.success ? parsed.data : null;
326
- } catch {
327
- return null;
328
- }
329
- }
330
-
331
- function lockCreatedAt(lockPath: string, owner: InstanceLockOwner | null): number | null {
332
- if (owner !== null) return Date.parse(owner.createdAt);
333
- try {
334
- return statSync(lockPath).mtimeMs;
335
- } catch {
336
- return null;
337
- }
338
- }
339
-
340
- function recoverStaleLock(
341
- lockPath: string,
342
- staleAfterMs: number,
343
- now: number,
344
- isProcessAlive: (pid: number) => boolean,
345
- ): boolean {
346
- const owner = readLockOwner(lockPath);
347
- const createdAt = lockCreatedAt(lockPath, owner);
348
- if (createdAt === null || now - createdAt < staleAfterMs) return false;
349
- if (owner !== null && isProcessAlive(owner.pid)) return false;
350
-
351
- const recoveredPath = `${lockPath}.stale-${randomUUID()}`;
352
- try {
353
- renameSync(lockPath, recoveredPath);
354
- rmSync(recoveredPath, { recursive: true, force: true });
355
- return true;
356
- } catch {
357
- return false;
358
- }
359
- }
360
-
361
- function releaseDirectoryLock(lockPath: string, token: string): InstanceRegistryResult<void> {
362
- if (!existsSync(lockPath)) return instanceRegistrySuccess(undefined);
363
- const owner = readLockOwner(lockPath);
364
- if (owner === null || owner.token !== token) {
365
- return instanceRegistryError(
366
- "lock_not_owned",
367
- `Lifecycle lock ${lockPath} is no longer owned by this command.`,
368
- );
369
- }
370
- try {
371
- rmSync(lockPath, { recursive: true, force: true });
372
- return instanceRegistrySuccess(undefined);
373
- } catch {
374
- return instanceRegistryError("registry_io", `Cannot release lifecycle lock ${lockPath}.`);
375
- }
376
- }
377
-
378
- async function acquireDirectoryLock(
379
- lockPath: string,
380
- options: InstanceLockOptions,
381
- ): Promise<InstanceRegistryResult<InstanceLockHandle>> {
382
- const timeoutMs = options.timeoutMs ?? DEFAULT_INSTANCE_LOCK_TIMEOUT_MS;
383
- const retryDelayMs = options.retryDelayMs ?? DEFAULT_LOCK_RETRY_MS;
384
- const staleAfterMs = options.staleAfterMs ?? DEFAULT_INSTANCE_LOCK_STALE_MS;
385
- const pid = options.pid ?? process.pid;
386
- const now = options.now ?? Date.now;
387
- const sleep = options.sleep ?? defaultSleep;
388
- const isProcessAlive = options.isProcessAlive ?? defaultIsProcessAlive;
389
- const createToken = options.createToken ?? randomUUID;
390
- const startedAt = now();
391
-
392
- while (now() - startedAt <= timeoutMs) {
393
- const token = createToken();
394
- try {
395
- mkdirSync(lockPath, { mode: 0o700 });
396
- } catch (error) {
397
- if (nodeErrorCode(error) !== "EEXIST") {
398
- return instanceRegistryError("registry_io", `Cannot acquire lifecycle lock ${lockPath}.`);
399
- }
400
-
401
- if (recoverStaleLock(lockPath, staleAfterMs, now(), isProcessAlive)) continue;
402
- if (now() - startedAt >= timeoutMs) break;
403
- await sleep(retryDelayMs);
404
- continue;
405
- }
406
-
407
- try {
408
- if (!ensurePrivateDirectorySync(lockPath)) {
409
- rmSync(lockPath, { recursive: true, force: true });
410
- return instanceRegistryError("registry_io", `Cannot secure lifecycle lock ${lockPath}.`);
411
- }
412
- const owner: InstanceLockOwner = {
413
- schemaVersion: 1,
414
- pid,
415
- token,
416
- createdAt: new Date(now()).toISOString(),
417
- };
418
- const ownerPath = join(lockPath, LOCK_OWNER_FILE_NAME);
419
- writeFileSync(ownerPath, `${JSON.stringify(owner)}\n`, {
420
- encoding: "utf8",
421
- flag: "wx",
422
- mode: PRIVATE_FILE_MODE,
423
- });
424
- if (!securePrivateFileSync(ownerPath)) {
425
- rmSync(lockPath, { recursive: true, force: true });
426
- return instanceRegistryError("registry_io", `Cannot secure lifecycle lock ${lockPath}.`);
427
- }
428
- return instanceRegistrySuccess({
429
- path: lockPath,
430
- release: () => releaseDirectoryLock(lockPath, token),
431
- });
432
- } catch {
433
- try {
434
- rmSync(lockPath, { recursive: true, force: true });
435
- } catch {
436
- // The registry error remains actionable even if cleanup is deferred.
437
- }
438
- return instanceRegistryError("registry_io", `Cannot acquire lifecycle lock ${lockPath}.`);
439
- }
440
- }
441
-
442
- return instanceRegistryError(
443
- "lock_timeout",
444
- `Timed out waiting for lifecycle lock ${lockPath}; retry after the other command finishes.`,
445
- );
446
- }
447
-
448
- export async function acquireRegistryLock(
449
- root: string,
450
- options: InstanceLockOptions = {},
451
- ): Promise<InstanceRegistryResult<InstanceLockHandle>> {
452
- const ensured = ensureInstancesRoot(root);
453
- return ensured.kind === "error"
454
- ? ensured
455
- : acquireDirectoryLock(join(root, ROOT_LOCK_DIRECTORY_NAME), options);
456
- }
457
-
458
- export async function acquireInstanceLock(
459
- root: string,
460
- rawName: string,
461
- options: InstanceLockOptions = {},
462
- ): Promise<InstanceRegistryResult<InstanceLockHandle>> {
463
- const paths = getInstancePaths(root, rawName);
464
- if (paths.kind === "error") return paths;
465
- const ensured = ensureInstancesRoot(root);
466
- if (ensured.kind === "error") return ensured;
467
- if (!ensurePrivateDirectorySync(paths.value.instanceDir)) {
468
- return instanceRegistryError(
469
- "registry_io",
470
- `Cannot create or secure the private directory for instance ${rawName}.`,
471
- );
472
- }
473
- return acquireDirectoryLock(paths.value.lockPath, options);
474
- }
475
-
476
- type LockedOperation<T> = () => InstanceRegistryResult<T> | Promise<InstanceRegistryResult<T>>;
477
-
478
- async function runWithLock<T>(
479
- acquired: Promise<InstanceRegistryResult<InstanceLockHandle>>,
480
- operation: LockedOperation<T>,
481
- ): Promise<InstanceRegistryResult<T>> {
482
- const lock = await acquired;
483
- if (lock.kind === "error") return lock;
484
-
485
- let result: InstanceRegistryResult<T>;
486
- try {
487
- result = await operation();
488
- } catch {
489
- result = instanceRegistryError("registry_io", "The lifecycle registry operation failed.");
490
- }
491
- const released = lock.value.release();
492
- return released.kind === "error" && result.kind === "success" ? released : result;
493
- }
494
-
495
- export function withRegistryLock<T>(
496
- root: string,
497
- operation: LockedOperation<T>,
498
- options: InstanceLockOptions = {},
499
- ): Promise<InstanceRegistryResult<T>> {
500
- return runWithLock(acquireRegistryLock(root, options), operation);
501
- }
502
-
503
- type PathApi = typeof win32;
504
-
505
- export type CanonicalDataDirectory = {
506
- path: string;
507
- comparisonKey: string;
508
- };
509
-
510
- export type CanonicalizeDataDirectoryOptions = {
511
- platform?: typeof process.platform;
512
- cwd?: string;
513
- realpath?: (path: string) => string;
514
- };
515
-
516
- function pathApiForPlatform(platform: typeof process.platform): PathApi {
517
- return platform === "win32" ? win32 : posix;
518
- }
519
-
520
- function resolveRealPathWithMissingTail(
521
- absolutePath: string,
522
- pathApi: PathApi,
523
- realpath: (path: string) => string,
524
- ): string {
525
- let current = absolutePath;
526
- const missingSegments: string[] = [];
527
- while (true) {
528
- try {
529
- return pathApi.join(realpath(current), ...missingSegments.reverse());
530
- } catch {
531
- const parent = pathApi.dirname(current);
532
- if (parent === current) return absolutePath;
533
- missingSegments.push(pathApi.basename(current));
534
- current = parent;
535
- }
536
- }
537
- }
538
-
539
- export function canonicalizeDataDirectory(
540
- rawPath: string,
541
- options: CanonicalizeDataDirectoryOptions = {},
542
- ): InstanceRegistryResult<CanonicalDataDirectory> {
543
- if (rawPath.trim().length === 0 || rawPath.includes("\u0000")) {
544
- return instanceRegistryError("data_dir_invalid", "Instance data directory cannot be empty.");
545
- }
546
-
547
- const platform = options.platform ?? process.platform;
548
- const pathApi = pathApiForPlatform(platform);
549
- const cwd = options.cwd ?? process.cwd();
550
- const absolutePath = pathApi.resolve(cwd, rawPath);
551
- const resolvedPath = resolveRealPathWithMissingTail(
552
- absolutePath,
553
- pathApi,
554
- options.realpath ?? realpathSync.native,
555
- );
556
- const normalizedPath = pathApi.normalize(resolvedPath);
557
- const root = pathApi.parse(normalizedPath).root;
558
- const withoutTrailingSeparator =
559
- normalizedPath === root ? normalizedPath : normalizedPath.replace(/[\\/]+$/u, "");
560
- return instanceRegistrySuccess({
561
- path: withoutTrailingSeparator,
562
- comparisonKey:
563
- platform === "win32" ? withoutTrailingSeparator.toLowerCase() : withoutTrailingSeparator,
564
- });
565
- }
566
-
567
- export function validateDataDirectoryAssignment(
568
- rawPath: string,
569
- records: readonly InstanceRecord[],
570
- excludeName?: string,
571
- options: CanonicalizeDataDirectoryOptions = {},
572
- ): InstanceRegistryResult<CanonicalDataDirectory> {
573
- const candidate = canonicalizeDataDirectory(rawPath, options);
574
- if (candidate.kind === "error") return candidate;
575
- const normalizedExcludedName = excludeName?.toLowerCase();
576
-
577
- for (const record of records) {
578
- if (record.name === normalizedExcludedName) continue;
579
- const registered = canonicalizeDataDirectory(record.dataDir, options);
580
- if (registered.kind === "error") {
581
- return instanceRegistryError(
582
- "data_dir_conflict",
583
- `Cannot safely compare the data directory registered to instance ${record.name}.`,
584
- );
585
- }
586
- if (registered.value.comparisonKey === candidate.value.comparisonKey) {
587
- return instanceRegistryError(
588
- "data_dir_conflict",
589
- `Data directory ${candidate.value.path} is already assigned to instance ${record.name}; named instances cannot share data.`,
590
- );
591
- }
592
- }
593
- return candidate;
594
- }
595
-
596
- export type InstancePortPair = {
597
- publicPort: number;
598
- upstreamPort: number;
599
- };
600
-
601
- export type PortAvailabilityCheck = (port: number, host: string) => boolean | Promise<boolean>;
602
-
603
- export type PlanInstancePortsOptions = {
604
- records: readonly InstanceRecord[];
605
- requestedPublicPort?: number;
606
- requestedUpstreamPort?: number;
607
- excludeName?: string;
608
- publicHost?: string;
609
- isPortAvailable?: PortAvailabilityCheck;
610
- };
611
-
612
- function validPort(port: number): boolean {
613
- return Number.isInteger(port) && port >= 1 && port <= 65_535;
614
- }
615
-
616
- function registeredPortOwner(
617
- pair: InstancePortPair,
618
- records: readonly InstanceRecord[],
619
- excludeName: string | undefined,
620
- ): string | null {
621
- const excluded = excludeName?.toLowerCase();
622
- for (const record of records) {
623
- if (record.name === excluded) continue;
624
- const occupied = new Set([record.publicPort, record.upstreamPort]);
625
- if (occupied.has(pair.publicPort) || occupied.has(pair.upstreamPort)) return record.name;
626
- }
627
- return null;
628
- }
629
-
630
- export function isPortAvailableByBinding(port: number, host: string): Promise<boolean> {
631
- return new Promise((resolveAvailability) => {
632
- const server = createServer();
633
- let settled = false;
634
- const finish = (available: boolean): void => {
635
- if (settled) return;
636
- settled = true;
637
- server.removeAllListeners();
638
- resolveAvailability(available);
639
- };
640
- server.once("error", () => finish(false));
641
- server.once("listening", () => {
642
- server.close((error) => finish(error === undefined));
643
- });
644
- server.unref();
645
- try {
646
- server.listen({ port, host, exclusive: true });
647
- } catch {
648
- finish(false);
649
- }
650
- });
651
- }
652
-
653
- async function pairIsAvailable(
654
- pair: InstancePortPair,
655
- publicHost: string,
656
- check: PortAvailabilityCheck,
657
- ): Promise<{ available: boolean; conflictingPort: number | null }> {
658
- if (!(await check(pair.publicPort, publicHost))) {
659
- return { available: false, conflictingPort: pair.publicPort };
660
- }
661
- if (!(await check(pair.upstreamPort, "127.0.0.1"))) {
662
- return { available: false, conflictingPort: pair.upstreamPort };
663
- }
664
- return { available: true, conflictingPort: null };
665
- }
666
-
667
- export async function planInstancePorts(
668
- options: PlanInstancePortsOptions,
669
- ): Promise<InstanceRegistryResult<InstancePortPair>> {
670
- const check = options.isPortAvailable ?? isPortAvailableByBinding;
671
- const publicHost = options.publicHost ?? "127.0.0.1";
672
-
673
- if (options.requestedPublicPort === undefined && options.requestedUpstreamPort !== undefined) {
674
- return instanceRegistryError(
675
- "port_invalid",
676
- "An explicit upstream port requires an explicit public port.",
677
- );
678
- }
679
-
680
- if (options.requestedPublicPort !== undefined) {
681
- const pair = {
682
- publicPort: options.requestedPublicPort,
683
- upstreamPort:
684
- options.requestedUpstreamPort ??
685
- options.requestedPublicPort + NAMED_INSTANCE_UPSTREAM_OFFSET,
686
- };
687
- if (
688
- !validPort(pair.publicPort) ||
689
- !validPort(pair.upstreamPort) ||
690
- pair.publicPort === pair.upstreamPort
691
- ) {
692
- return instanceRegistryError(
693
- "port_invalid",
694
- "Public and upstream ports must be different integers from 1 to 65535.",
695
- );
696
- }
697
- const owner = registeredPortOwner(pair, options.records, options.excludeName);
698
- if (owner !== null) {
699
- return instanceRegistryError(
700
- "port_conflict",
701
- `Requested port pair ${String(pair.publicPort)}/${String(pair.upstreamPort)} overlaps instance ${owner}.`,
702
- );
703
- }
704
- const availability = await pairIsAvailable(pair, publicHost, check);
705
- return availability.available
706
- ? instanceRegistrySuccess(pair)
707
- : instanceRegistryError(
708
- "port_conflict",
709
- `Port ${String(availability.conflictingPort)} already has a listener; no process was terminated.`,
710
- );
711
- }
712
-
713
- for (
714
- let publicPort = DEFAULT_NAMED_INSTANCE_PUBLIC_PORT;
715
- publicPort + NAMED_INSTANCE_UPSTREAM_OFFSET <= 65_535;
716
- publicPort += NAMED_INSTANCE_PORT_STEP
717
- ) {
718
- const pair = {
719
- publicPort,
720
- upstreamPort: publicPort + NAMED_INSTANCE_UPSTREAM_OFFSET,
721
- };
722
- if (registeredPortOwner(pair, options.records, options.excludeName) !== null) continue;
723
- const availability = await pairIsAvailable(pair, publicHost, check);
724
- if (availability.available) return instanceRegistrySuccess(pair);
725
- }
726
-
727
- return instanceRegistryError(
728
- "port_exhausted",
729
- `No available named-instance port pair was found from ${String(DEFAULT_NAMED_INSTANCE_PUBLIC_PORT)} through 65535.`,
730
- );
731
- }