omnicell-router 0.8.2 → 0.10.0

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 (400) hide show
  1. package/README.md +26 -7
  2. package/README.zh-CN.md +18 -5
  3. package/backend/dist/auth/api-keys.js +11 -0
  4. package/backend/dist/auth/key-models.d.ts +36 -0
  5. package/backend/dist/auth/key-models.js +99 -0
  6. package/backend/dist/capture/recorder.d.ts +4 -10
  7. package/backend/dist/capture/recorder.js +6 -58
  8. package/backend/dist/cli/clients/activity.js +2 -0
  9. package/backend/dist/cli/clients/base.d.ts +36 -11
  10. package/backend/dist/cli/clients/base.js +31 -15
  11. package/backend/dist/cli/clients/claude.d.ts +9 -0
  12. package/backend/dist/cli/clients/claude.js +6 -0
  13. package/backend/dist/cli/clients/codex.d.ts +78 -0
  14. package/backend/dist/cli/clients/codex.js +475 -57
  15. package/backend/dist/cli/clients/core-adapters.d.ts +1 -1
  16. package/backend/dist/cli/clients/core-adapters.js +1 -1
  17. package/backend/dist/cli/clients/dsh.d.ts +8 -0
  18. package/backend/dist/cli/clients/dsh.js +5 -0
  19. package/backend/dist/cli/clients/follow-catalog-sync.d.ts +62 -0
  20. package/backend/dist/cli/clients/follow-catalog-sync.js +435 -0
  21. package/backend/dist/cli/clients/grok.d.ts +15 -1
  22. package/backend/dist/cli/clients/grok.js +16 -2
  23. package/backend/dist/cli/clients/index.d.ts +13 -1
  24. package/backend/dist/cli/clients/index.js +97 -19
  25. package/backend/dist/cli/clients/kimi.d.ts +6 -0
  26. package/backend/dist/cli/clients/kimi.js +3 -0
  27. package/backend/dist/cli/clients/launcher.d.ts +1 -1
  28. package/backend/dist/cli/clients/model-meta.js +6 -3
  29. package/backend/dist/cli/clients/omp.d.ts +6 -0
  30. package/backend/dist/cli/clients/omp.js +3 -0
  31. package/backend/dist/cli/clients/openclaw.d.ts +6 -0
  32. package/backend/dist/cli/clients/openclaw.js +3 -0
  33. package/backend/dist/cli/clients/opencode.d.ts +8 -0
  34. package/backend/dist/cli/clients/opencode.js +8 -2
  35. package/backend/dist/cli/clients/pi.d.ts +6 -0
  36. package/backend/dist/cli/clients/pi.js +3 -0
  37. package/backend/dist/cli/clients/reserved.js +2 -0
  38. package/backend/dist/cli/clients/update-check.d.ts +37 -0
  39. package/backend/dist/cli/clients/update-check.js +309 -0
  40. package/backend/dist/cli/clients/workbuddy.d.ts +19 -0
  41. package/backend/dist/cli/clients/workbuddy.js +66 -0
  42. package/backend/dist/cli/index.js +5 -4
  43. package/backend/dist/cli/paths.js +8 -0
  44. package/backend/dist/cli/types.d.ts +101 -16
  45. package/backend/dist/config/comments-en.js +34 -25
  46. package/backend/dist/config/comments-zh.js +33 -24
  47. package/backend/dist/config/defaults.d.ts +280 -22
  48. package/backend/dist/config/defaults.js +279 -21
  49. package/backend/dist/config/env.d.ts +10 -0
  50. package/backend/dist/config/env.js +3 -2
  51. package/backend/dist/config/index.d.ts +22 -1
  52. package/backend/dist/config/index.js +218 -43
  53. package/backend/dist/config/migrations/v0-to-v1.d.ts +2 -2
  54. package/backend/dist/config/migrations/v10-to-v11.d.ts +38 -0
  55. package/backend/dist/config/migrations/v10-to-v11.js +43 -0
  56. package/backend/dist/config/migrations/v4-to-v5.d.ts +36 -0
  57. package/backend/dist/config/migrations/v4-to-v5.js +42 -0
  58. package/backend/dist/config/migrations/v5-to-v6.d.ts +27 -0
  59. package/backend/dist/config/migrations/v5-to-v6.js +29 -0
  60. package/backend/dist/config/migrations/v6-to-v7.d.ts +45 -0
  61. package/backend/dist/config/migrations/v6-to-v7.js +97 -0
  62. package/backend/dist/config/migrations/v7-to-v8.d.ts +36 -0
  63. package/backend/dist/config/migrations/v7-to-v8.js +43 -0
  64. package/backend/dist/config/migrations/v8-to-v9.d.ts +38 -0
  65. package/backend/dist/config/migrations/v8-to-v9.js +43 -0
  66. package/backend/dist/config/migrations/v9-to-v10.d.ts +51 -0
  67. package/backend/dist/config/migrations/v9-to-v10.js +71 -0
  68. package/backend/dist/config/runtime.js +1 -1
  69. package/backend/dist/config/schema.d.ts +3 -3
  70. package/backend/dist/config/schema.js +18 -4
  71. package/backend/dist/config/types.d.ts +221 -41
  72. package/backend/dist/egress-proxy/asset-download.d.ts +54 -0
  73. package/backend/dist/egress-proxy/asset-download.js +420 -0
  74. package/backend/dist/egress-proxy/manual-node-spec.d.ts +92 -0
  75. package/backend/dist/egress-proxy/manual-node-spec.js +408 -0
  76. package/backend/dist/egress-proxy/mihomo-binary.d.ts +54 -0
  77. package/backend/dist/egress-proxy/mihomo-binary.js +278 -0
  78. package/backend/dist/egress-proxy/mihomo-client.d.ts +94 -0
  79. package/backend/dist/egress-proxy/mihomo-client.js +308 -0
  80. package/backend/dist/egress-proxy/mihomo-config.d.ts +40 -0
  81. package/backend/dist/egress-proxy/mihomo-config.js +161 -0
  82. package/backend/dist/egress-proxy/mihomo-geo.d.ts +87 -0
  83. package/backend/dist/egress-proxy/mihomo-geo.js +213 -0
  84. package/backend/dist/egress-proxy/mihomo-logs.d.ts +43 -0
  85. package/backend/dist/egress-proxy/mihomo-logs.js +84 -0
  86. package/backend/dist/egress-proxy/mihomo-pac.d.ts +37 -0
  87. package/backend/dist/egress-proxy/mihomo-pac.js +75 -0
  88. package/backend/dist/egress-proxy/mihomo-rules-import.d.ts +43 -0
  89. package/backend/dist/egress-proxy/mihomo-rules-import.js +193 -0
  90. package/backend/dist/egress-proxy/mihomo-sidecar.d.ts +81 -0
  91. package/backend/dist/egress-proxy/mihomo-sidecar.js +637 -0
  92. package/backend/dist/forward-proxy/egress.d.ts +50 -11
  93. package/backend/dist/forward-proxy/egress.js +63 -17
  94. package/backend/dist/forward-proxy/h2-forward.js +42 -15
  95. package/backend/dist/forward-proxy/index.d.ts +11 -8
  96. package/backend/dist/forward-proxy/index.js +27 -60
  97. package/backend/dist/forward-proxy/interceptor.d.ts +3 -2
  98. package/backend/dist/forward-proxy/interceptor.js +4 -4
  99. package/backend/dist/forward-proxy/relay.js +3 -3
  100. package/backend/dist/forward-proxy/rules.d.ts +4 -4
  101. package/backend/dist/forward-proxy/rules.js +25 -4
  102. package/backend/dist/forward-proxy/server.d.ts +12 -16
  103. package/backend/dist/forward-proxy/server.js +237 -171
  104. package/backend/dist/harness/host/hosts.js +3 -2
  105. package/backend/dist/index.js +59 -19
  106. package/backend/dist/ingress-proxy/access-log.d.ts +176 -0
  107. package/backend/dist/ingress-proxy/access-log.js +774 -0
  108. package/backend/dist/ingress-proxy/ca-inventory.d.ts +106 -0
  109. package/backend/dist/ingress-proxy/ca-inventory.js +525 -0
  110. package/backend/dist/ingress-proxy/ca-trust.d.ts +96 -0
  111. package/backend/dist/ingress-proxy/ca-trust.js +315 -0
  112. package/backend/dist/ingress-proxy/ca.d.ts +104 -0
  113. package/backend/dist/ingress-proxy/ca.js +273 -0
  114. package/backend/dist/ingress-proxy/data-dir.d.ts +28 -0
  115. package/backend/dist/ingress-proxy/data-dir.js +45 -0
  116. package/backend/dist/ingress-proxy/egress.d.ts +151 -0
  117. package/backend/dist/ingress-proxy/egress.js +364 -0
  118. package/backend/dist/ingress-proxy/h2-forward.d.ts +66 -0
  119. package/backend/dist/ingress-proxy/h2-forward.js +561 -0
  120. package/backend/dist/ingress-proxy/index.d.ts +24 -0
  121. package/backend/dist/ingress-proxy/index.js +144 -0
  122. package/backend/dist/ingress-proxy/interceptor.d.ts +25 -0
  123. package/backend/dist/ingress-proxy/interceptor.js +52 -0
  124. package/backend/dist/ingress-proxy/ordered-relay.d.ts +29 -0
  125. package/backend/dist/ingress-proxy/ordered-relay.js +46 -0
  126. package/backend/dist/ingress-proxy/relay.d.ts +54 -0
  127. package/backend/dist/ingress-proxy/relay.js +188 -0
  128. package/backend/dist/ingress-proxy/rules.d.ts +195 -0
  129. package/backend/dist/ingress-proxy/rules.js +348 -0
  130. package/backend/dist/ingress-proxy/server.d.ts +153 -0
  131. package/backend/dist/ingress-proxy/server.js +2065 -0
  132. package/backend/dist/ingress-proxy/sni.d.ts +35 -0
  133. package/backend/dist/ingress-proxy/sni.js +124 -0
  134. package/backend/dist/ingress-proxy/status.d.ts +32 -0
  135. package/backend/dist/ingress-proxy/status.js +15 -0
  136. package/backend/dist/ingress-proxy/system-proxy.d.ts +112 -0
  137. package/backend/dist/ingress-proxy/system-proxy.js +481 -0
  138. package/backend/dist/ingress-proxy/traffic-delete.d.ts +21 -0
  139. package/backend/dist/ingress-proxy/traffic-delete.js +64 -0
  140. package/backend/dist/ingress-proxy/traffic-delete.worker.d.ts +44 -0
  141. package/backend/dist/ingress-proxy/traffic-delete.worker.js +228 -0
  142. package/backend/dist/ingress-proxy/traffic-files.d.ts +10 -0
  143. package/backend/dist/ingress-proxy/traffic-files.js +10 -0
  144. package/backend/dist/ingress-proxy/upstream-tls.d.ts +46 -0
  145. package/backend/dist/ingress-proxy/upstream-tls.js +105 -0
  146. package/backend/dist/ingress-proxy/ws-frames.d.ts +45 -0
  147. package/backend/dist/ingress-proxy/ws-frames.js +153 -0
  148. package/backend/dist/ir/adapters/anthropic-messages-stream.js +6 -1
  149. package/backend/dist/ir/adapters/anthropic-messages.js +12 -5
  150. package/backend/dist/ir/adapters/google-gemini-stream.js +7 -2
  151. package/backend/dist/ir/adapters/google-gemini.js +5 -2
  152. package/backend/dist/ir/adapters/openai-chat-stream.js +5 -1
  153. package/backend/dist/ir/adapters/openai-chat.d.ts +25 -0
  154. package/backend/dist/ir/adapters/openai-chat.js +50 -6
  155. package/backend/dist/ir/adapters/openai-responses-output.d.ts +1 -0
  156. package/backend/dist/ir/adapters/openai-responses-output.js +67 -21
  157. package/backend/dist/ir/adapters/openai-responses-stream.d.ts +13 -0
  158. package/backend/dist/ir/adapters/openai-responses-stream.js +34 -1
  159. package/backend/dist/ir/adapters/openai-responses.d.ts +92 -1
  160. package/backend/dist/ir/adapters/openai-responses.js +163 -12
  161. package/backend/dist/ir/capabilities.js +4 -0
  162. package/backend/dist/ir/media.d.ts +20 -0
  163. package/backend/dist/ir/media.js +41 -0
  164. package/backend/dist/ir/tool-identity.d.ts +35 -0
  165. package/backend/dist/ir/tool-identity.js +40 -0
  166. package/backend/dist/ir/types.d.ts +9 -1
  167. package/backend/dist/ir/validate.d.ts +24 -0
  168. package/backend/dist/ir/validate.js +113 -63
  169. package/backend/dist/local/build-jobs.d.ts +66 -0
  170. package/backend/dist/local/build-jobs.js +243 -0
  171. package/backend/dist/local/detect.d.ts +32 -0
  172. package/backend/dist/local/detect.js +145 -0
  173. package/backend/dist/local/draft-match.d.ts +58 -0
  174. package/backend/dist/local/draft-match.js +124 -0
  175. package/backend/dist/local/engine-runtime.d.ts +522 -0
  176. package/backend/dist/local/engine-runtime.js +1 -0
  177. package/backend/dist/local/engines.d.ts +241 -0
  178. package/backend/dist/local/engines.js +651 -0
  179. package/backend/dist/local/gguf.d.ts +35 -0
  180. package/backend/dist/local/gguf.js +314 -0
  181. package/backend/dist/local/hf.d.ts +120 -0
  182. package/backend/dist/local/hf.js +304 -0
  183. package/backend/dist/local/install.d.ts +90 -0
  184. package/backend/dist/local/install.js +421 -0
  185. package/backend/dist/local/llamacpp.d.ts +55 -0
  186. package/backend/dist/local/llamacpp.js +177 -0
  187. package/backend/dist/local/local-provider.d.ts +81 -0
  188. package/backend/dist/local/local-provider.js +301 -0
  189. package/backend/dist/local/machine-stats.d.ts +87 -0
  190. package/backend/dist/local/machine-stats.js +332 -0
  191. package/backend/dist/local/model-store.d.ts +347 -0
  192. package/backend/dist/local/model-store.js +1215 -0
  193. package/backend/dist/local/part-sweep.d.ts +32 -0
  194. package/backend/dist/local/part-sweep.js +156 -0
  195. package/backend/dist/local/plan.d.ts +65 -0
  196. package/backend/dist/local/plan.js +146 -0
  197. package/backend/dist/local/resources.d.ts +49 -0
  198. package/backend/dist/local/resources.js +64 -0
  199. package/backend/dist/local/run-stats.d.ts +95 -0
  200. package/backend/dist/local/run-stats.js +195 -0
  201. package/backend/dist/local/runner.d.ts +235 -0
  202. package/backend/dist/local/runner.js +1392 -0
  203. package/backend/dist/local/settings.d.ts +79 -0
  204. package/backend/dist/local/settings.js +180 -0
  205. package/backend/dist/local/strata-catalog.d.ts +30 -0
  206. package/backend/dist/local/strata-catalog.js +511 -0
  207. package/backend/dist/local/strata-drafting.d.ts +46 -0
  208. package/backend/dist/local/strata-drafting.js +265 -0
  209. package/backend/dist/local/strata.d.ts +278 -0
  210. package/backend/dist/local/strata.js +1392 -0
  211. package/backend/dist/local/tar.d.ts +20 -0
  212. package/backend/dist/local/tar.js +367 -0
  213. package/backend/dist/local/transport.d.ts +35 -0
  214. package/backend/dist/local/transport.js +89 -0
  215. package/backend/dist/local/tune.d.ts +58 -0
  216. package/backend/dist/local/tune.js +324 -0
  217. package/backend/dist/observability/http-exchange.d.ts +2 -2
  218. package/backend/dist/opencode/catalog/auto-pull.d.ts +14 -3
  219. package/backend/dist/opencode/catalog/auto-pull.js +284 -77
  220. package/backend/dist/opencode/catalog/ocr-store.d.ts +7 -6
  221. package/backend/dist/opencode/catalog/ocr-store.js +4 -2
  222. package/backend/dist/opencode/catalog/overrides-store.d.ts +15 -4
  223. package/backend/dist/opencode/catalog/overrides-store.js +28 -19
  224. package/backend/dist/opencode/catalog/reasoning-declaration.d.ts +35 -0
  225. package/backend/dist/opencode/catalog/reasoning-declaration.js +66 -0
  226. package/backend/dist/opencode/catalog/repository.js +28 -5
  227. package/backend/dist/opencode/catalog/sources/models-dev.d.ts +3 -3
  228. package/backend/dist/opencode/catalog/sources/models-dev.js +42 -14
  229. package/backend/dist/opencode/catalog/types.d.ts +42 -12
  230. package/backend/dist/opencode/catalog/types.js +38 -1
  231. package/backend/dist/opencode/credentials/def-materialize.js +27 -21
  232. package/backend/dist/opencode/credentials/ocr-store.js +11 -2
  233. package/backend/dist/opencode/credentials/sync.js +12 -3
  234. package/backend/dist/opencode/credentials/types.d.ts +31 -4
  235. package/backend/dist/opencode/credentials/types.js +25 -0
  236. package/backend/dist/opencode/migrate/engine.d.ts +20 -0
  237. package/backend/dist/opencode/migrate/engine.js +71 -0
  238. package/backend/dist/opencode/migrate/migrator.d.ts +11 -0
  239. package/backend/dist/opencode/migrate/migrator.js +6 -0
  240. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.d.ts +6 -0
  241. package/backend/dist/opencode/migrate/steps/overrides-v1-to-v2.js +31 -0
  242. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.d.ts +6 -0
  243. package/backend/dist/opencode/migrate/steps/providers-v1-to-v2.js +62 -0
  244. package/backend/dist/opencode/probe.d.ts +21 -4
  245. package/backend/dist/opencode/probe.js +34 -10
  246. package/backend/dist/opencode/provider-def-adapters.d.ts +12 -11
  247. package/backend/dist/opencode/provider-def-adapters.js +43 -27
  248. package/backend/dist/opencode/provider-defs.d.ts +10 -16
  249. package/backend/dist/opencode/provider-defs.js +45 -45
  250. package/backend/dist/opencode/user-config.d.ts +23 -26
  251. package/backend/dist/opencode/user-config.js +95 -77
  252. package/backend/dist/pipeline/directives.d.ts +9 -4
  253. package/backend/dist/pipeline/directives.js +14 -10
  254. package/backend/dist/pipeline/orchestrator.d.ts +42 -13
  255. package/backend/dist/pipeline/orchestrator.js +514 -172
  256. package/backend/dist/plugins/builtin/model-gateway.js +38 -12
  257. package/backend/dist/plugins/environment-ack.d.ts +51 -0
  258. package/backend/dist/plugins/environment-ack.js +81 -0
  259. package/backend/dist/plugins/gateways.d.ts +6 -6
  260. package/backend/dist/plugins/gateways.js +2 -2
  261. package/backend/dist/plugins/host.d.ts +100 -16
  262. package/backend/dist/plugins/host.js +637 -99
  263. package/backend/dist/plugins/install-run.d.ts +27 -0
  264. package/backend/dist/plugins/install-run.js +99 -0
  265. package/backend/dist/plugins/manifest.d.ts +84 -32
  266. package/backend/dist/plugins/manifest.js +149 -45
  267. package/backend/dist/plugins/market-install.d.ts +18 -0
  268. package/backend/dist/plugins/market-install.js +111 -0
  269. package/backend/dist/plugins/market-source.d.ts +100 -0
  270. package/backend/dist/plugins/market-source.js +449 -0
  271. package/backend/dist/plugins/market-updates.d.ts +70 -0
  272. package/backend/dist/plugins/market-updates.js +97 -0
  273. package/backend/dist/plugins/market.d.ts +677 -0
  274. package/backend/dist/plugins/market.js +2113 -0
  275. package/backend/dist/plugins/source-index.d.ts +155 -0
  276. package/backend/dist/plugins/source-index.js +217 -0
  277. package/backend/dist/plugins/types.d.ts +402 -37
  278. package/backend/dist/projects/worktrees.d.ts +88 -0
  279. package/backend/dist/projects/worktrees.js +220 -0
  280. package/backend/dist/providers/boot-direct.d.ts +41 -7
  281. package/backend/dist/providers/boot-direct.js +284 -44
  282. package/backend/dist/providers/compat/tool-markup-recovery.js +31 -6
  283. package/backend/dist/providers/dial-wire.d.ts +17 -0
  284. package/backend/dist/providers/dial-wire.js +49 -0
  285. package/backend/dist/providers/executors/dispatch.d.ts +17 -7
  286. package/backend/dist/providers/executors/dispatch.js +28 -9
  287. package/backend/dist/providers/executors/openai-chat.js +14 -2
  288. package/backend/dist/providers/executors/plugin-adapter.d.ts +23 -1
  289. package/backend/dist/providers/executors/plugin-adapter.js +59 -3
  290. package/backend/dist/providers/member-match.d.ts +32 -9
  291. package/backend/dist/providers/member-match.js +65 -21
  292. package/backend/dist/providers/model-resolution.d.ts +62 -0
  293. package/backend/dist/providers/model-resolution.js +62 -0
  294. package/backend/dist/providers/price-order.d.ts +51 -0
  295. package/backend/dist/providers/price-order.js +54 -0
  296. package/backend/dist/providers/protocols-field.d.ts +24 -0
  297. package/backend/dist/providers/protocols-field.js +66 -0
  298. package/backend/dist/providers/provider-takedown.d.ts +5 -2
  299. package/backend/dist/providers/registry.d.ts +87 -26
  300. package/backend/dist/providers/registry.js +232 -121
  301. package/backend/dist/providers/selection.d.ts +91 -0
  302. package/backend/dist/providers/selection.js +158 -0
  303. package/backend/dist/providers/virtual-meta.d.ts +33 -2
  304. package/backend/dist/providers/virtual-meta.js +74 -18
  305. package/backend/dist/quota/cli-login.d.ts +25 -4
  306. package/backend/dist/quota/cli-login.js +38 -6
  307. package/backend/dist/quota/coverage-generation.d.ts +24 -0
  308. package/backend/dist/quota/coverage-generation.js +29 -0
  309. package/backend/dist/quota/declarations.js +8 -4
  310. package/backend/dist/quota/engine.js +2 -2
  311. package/backend/dist/quota/prober.d.ts +43 -2
  312. package/backend/dist/quota/prober.js +97 -22
  313. package/backend/dist/ratelimit/rate-limiter.d.ts +1 -1
  314. package/backend/dist/resilience/error-classifier.js +29 -0
  315. package/backend/dist/router/index.d.ts +1 -1
  316. package/backend/dist/router/index.js +17 -1
  317. package/backend/dist/router/layer2-decision.d.ts +1 -1
  318. package/backend/dist/router/layer2-decision.js +2 -2
  319. package/backend/dist/routes/console.js +1043 -405
  320. package/backend/dist/routes/environments.js +1 -1
  321. package/backend/dist/routes/local-models.d.ts +2 -0
  322. package/backend/dist/routes/local-models.js +1414 -0
  323. package/backend/dist/routes/mihomo.d.ts +2 -2
  324. package/backend/dist/routes/mihomo.js +20 -11
  325. package/backend/dist/routes/projects.js +121 -0
  326. package/backend/dist/server.js +409 -15
  327. package/backend/dist/session/session-manager.d.ts +42 -5
  328. package/backend/dist/session/session-manager.js +64 -11
  329. package/backend/dist/session/session-row.d.ts +29 -8
  330. package/backend/dist/session/session-row.js +18 -13
  331. package/backend/dist/snapshot/bundle.d.ts +40 -0
  332. package/backend/dist/snapshot/bundle.js +177 -0
  333. package/backend/dist/snapshot/handoff/compress.d.ts +46 -0
  334. package/backend/dist/snapshot/handoff/compress.js +77 -0
  335. package/backend/dist/snapshot/handoff/index.d.ts +119 -0
  336. package/backend/dist/snapshot/handoff/index.js +160 -0
  337. package/backend/dist/snapshot/handoff/jsonl-writer.d.ts +78 -0
  338. package/backend/dist/snapshot/handoff/jsonl-writer.js +175 -0
  339. package/backend/dist/snapshot/handoff/opencode-writer.d.ts +51 -0
  340. package/backend/dist/snapshot/handoff/opencode-writer.js +214 -0
  341. package/backend/dist/snapshot/handoff/summarize.d.ts +39 -0
  342. package/backend/dist/snapshot/handoff/summarize.js +118 -0
  343. package/backend/dist/snapshot/handoff/transcript.d.ts +71 -0
  344. package/backend/dist/snapshot/handoff/transcript.js +167 -0
  345. package/backend/dist/snapshot/media-fs.d.ts +10 -0
  346. package/backend/dist/snapshot/media-fs.js +50 -0
  347. package/backend/dist/snapshot/media.d.ts +32 -0
  348. package/backend/dist/snapshot/media.js +87 -0
  349. package/backend/dist/snapshot/store.d.ts +226 -0
  350. package/backend/dist/snapshot/store.js +887 -0
  351. package/backend/dist/snapshot/tree.d.ts +112 -0
  352. package/backend/dist/snapshot/tree.js +207 -0
  353. package/backend/dist/snapshot/types.d.ts +212 -0
  354. package/backend/dist/snapshot/types.js +14 -0
  355. package/backend/dist/snapshot/view.d.ts +19 -0
  356. package/backend/dist/snapshot/view.js +57 -0
  357. package/backend/dist/snapshot/write-worker.d.ts +67 -0
  358. package/backend/dist/snapshot/write-worker.js +129 -0
  359. package/backend/dist/surfaces/anthropic.js +4 -1
  360. package/backend/dist/surfaces/body-admission.d.ts +344 -0
  361. package/backend/dist/surfaces/body-admission.js +818 -0
  362. package/backend/dist/surfaces/chat-pipeline.js +8 -0
  363. package/backend/dist/surfaces/decision-pipeline.js +10 -7
  364. package/backend/dist/surfaces/gateway-catalog.d.ts +26 -0
  365. package/backend/dist/surfaces/gateway-catalog.js +202 -0
  366. package/backend/dist/surfaces/gateway-chat.d.ts +7 -11
  367. package/backend/dist/surfaces/gateway-chat.js +50 -12
  368. package/backend/dist/surfaces/ocr-headers.d.ts +6 -4
  369. package/backend/dist/surfaces/ocr-headers.js +11 -7
  370. package/backend/dist/surfaces/systemone.js +1 -1
  371. package/backend/dist/surfaces/transport-fastify.js +32 -5
  372. package/backend/dist/surfaces/transport-node-http.d.ts +51 -6
  373. package/backend/dist/surfaces/transport-node-http.js +76 -16
  374. package/backend/dist/surfaces/types.d.ts +11 -3
  375. package/backend/dist/trace/persist.js +21 -1
  376. package/backend/dist/trace/tracker.d.ts +35 -3
  377. package/backend/dist/trace/tracker.js +23 -0
  378. package/backend/dist/types/openai.d.ts +8 -0
  379. package/backend/dist/types/router.d.ts +17 -6
  380. package/backend/dist/types/router.js +14 -2
  381. package/backend/dist/utils/client-families.d.ts +66 -0
  382. package/backend/dist/utils/client-families.js +127 -0
  383. package/backend/dist/utils/event-ring.d.ts +1 -1
  384. package/backend/dist/utils/event-ring.js +1 -1
  385. package/backend/dist/utils/proxy-node.js +1 -1
  386. package/backend/dist/utils/proxy.d.ts +135 -11
  387. package/backend/dist/utils/proxy.js +144 -29
  388. package/backend/dist/utils/run-command.d.ts +21 -1
  389. package/backend/dist/utils/run-command.js +64 -4
  390. package/backend/dist/utils/server-liveness.d.ts +28 -0
  391. package/backend/dist/utils/server-liveness.js +32 -0
  392. package/backend/dist/utils/session-file.d.ts +28 -0
  393. package/backend/dist/utils/session-file.js +34 -0
  394. package/frontend/dist/assets/antigravity.color-DXFfVr6X.svg +39 -0
  395. package/frontend/dist/assets/gemini-cli.color-BfquLd1p.svg +1 -0
  396. package/frontend/dist/assets/index-CTZNvn1d.js +1707 -0
  397. package/frontend/dist/assets/{index-DxZ9MHKB.css → index-CqDSOPQ0.css} +1 -1
  398. package/frontend/dist/index.html +2 -2
  399. package/package.json +3 -1
  400. package/frontend/dist/assets/index-55VVwfFQ.js +0 -1521
@@ -0,0 +1,2113 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import JSON5 from 'json5';
4
+ import { safeWriteJson } from '../cli/clients/base.js';
5
+ import { compiledSnapshotExe } from '../cli/paths.js';
6
+ import { githubHeaders } from '../harness/common/github.js';
7
+ import { DEFAULT_REGISTRY_SYNC_INTERVAL_MS, PLUGIN_REGISTRY_MAX_BYTES, REGISTRY_SYNC_RETRY_MS } from '../config/defaults.js';
8
+ import { filterSourceIndex, sourceEntriesOf, readSourceIndex, writeSourceIndex, } from './source-index.js';
9
+ import { egressEndpointUrl, fetchViaProxy } from '../utils/proxy.js';
10
+ import { compareVersions } from '../utils/semver.js';
11
+ import { PLUGIN_PACKAGE_MAX_BYTES } from '../config/defaults.js';
12
+ import { listInstalledPlugins, pluginsRoot } from './host.js';
13
+ import { pluginEngineCompatibility, validatePluginManifest } from './manifest.js';
14
+ const DEFAULT_INSTALL_METHOD = 'release';
15
+ const GITHUB_REPO_RE = /^([\w.-]+)\/([\w.-]+?)(?:\.git)?$/;
16
+ /**
17
+ * `owner/repo`, from what an operator would reasonably paste. Full URLs, clone
18
+ * lines and `github:` prefixes are accepted; a path below the repo is NOT — a
19
+ * registry entry names a repository, and the directory inside it is `subdir`.
20
+ * This is the market's own narrow reader: the harness marketplace's parser
21
+ * tolerates deeper links because it also names an extension directory, and
22
+ * borrowing it here would silently accept a spelling this registry cannot use.
23
+ */
24
+ export function normalizeRepo(value) {
25
+ const trimmed = value.trim().replace(/\/+$/, '');
26
+ const stripped = trimmed
27
+ .replace(/^git@github\.com:/i, '')
28
+ .replace(/^(?:https?:\/\/)?(?:www\.)?github\.com\//i, '')
29
+ .replace(/^github:/i, '');
30
+ const match = GITHUB_REPO_RE.exec(stripped);
31
+ return match ? `${match[1]}/${match[2]}` : undefined;
32
+ }
33
+ /** A registry entry as the market uses it, or undefined when unusable. */
34
+ export function normalizeEntry(raw) {
35
+ if (typeof raw === 'string') {
36
+ const repo = normalizeRepo(raw);
37
+ return repo ? { repo, method: DEFAULT_INSTALL_METHOD } : undefined;
38
+ }
39
+ if (!raw || typeof raw !== 'object')
40
+ return undefined;
41
+ const repo = typeof raw.repo === 'string' ? normalizeRepo(raw.repo) : undefined;
42
+ if (!repo)
43
+ return undefined;
44
+ const ref = typeof raw.ref === 'string' && raw.ref.trim() ? raw.ref.trim() : undefined;
45
+ const rawSubdir = typeof raw.subdir === 'string' ? raw.subdir.trim() : '';
46
+ // A subdir is joined into a raw.githubusercontent path: refuse anything that
47
+ // could climb out of the repository instead of normalizing it into validity.
48
+ // The absolute-path test runs on the RAW value — trimming the leading slash
49
+ // first would turn `/etc` into the legitimate-looking `etc`.
50
+ if (rawSubdir && (rawSubdir.startsWith('/') || /^[A-Za-z]:/.test(rawSubdir)))
51
+ return undefined;
52
+ const subdir = rawSubdir.replace(/^\/+|\/+$/g, '');
53
+ if (subdir.split('/').some((s) => s === '.' || s === '..'))
54
+ return undefined;
55
+ // An unknown method is REFUSED, never defaulted: `method` changes where the
56
+ // bytes come from, and silently treating a typo'd `'source'`/`'tag'` as
57
+ // `release` would build the wrong thing without ever saying so.
58
+ let method = DEFAULT_INSTALL_METHOD;
59
+ if (raw.method !== undefined) {
60
+ if (raw.method !== 'code' && raw.method !== 'release')
61
+ return undefined;
62
+ method = raw.method;
63
+ }
64
+ return { repo, method, ...(ref ? { ref } : {}), ...(subdir ? { subdir } : {}) };
65
+ }
66
+ /**
67
+ * Strip `//` and block comments OUTSIDE string literals. A registry written as
68
+ * a JSON5 document carries prose above the array (and often inline notes beside
69
+ * an entry); searching the raw text for `plugins = [` would happily start on a
70
+ * sentence that mentions a bracket. JSON5 tolerates comments, so this pass is
71
+ * only about making the SEARCH honest — the parsed text keeps them.
72
+ */
73
+ function stripComments(text) {
74
+ let out = '';
75
+ let i = 0;
76
+ let quote;
77
+ while (i < text.length) {
78
+ const ch = text[i];
79
+ if (quote) {
80
+ out += ch;
81
+ if (ch === '\\') {
82
+ out += text[i + 1] ?? '';
83
+ i += 2;
84
+ continue;
85
+ }
86
+ if (ch === quote)
87
+ quote = undefined;
88
+ i += 1;
89
+ continue;
90
+ }
91
+ if (ch === '"' || ch === "'" || ch === '`') {
92
+ quote = ch;
93
+ out += ch;
94
+ i += 1;
95
+ continue;
96
+ }
97
+ if (ch === '/' && text[i + 1] === '/') {
98
+ while (i < text.length && text[i] !== '\n')
99
+ i += 1;
100
+ continue;
101
+ }
102
+ if (ch === '/' && text[i + 1] === '*') {
103
+ const end = text.indexOf('*/', i + 2);
104
+ i = end < 0 ? text.length : end + 2;
105
+ // A newline keeps a stripped block comment from gluing two tokens.
106
+ out += '\n';
107
+ continue;
108
+ }
109
+ out += ch;
110
+ i += 1;
111
+ }
112
+ return out;
113
+ }
114
+ /** The `[ … ]` literal starting at `start` (a `[`), bracket-matched with string
115
+ * awareness — a repository name or a comment cannot unbalance it. */
116
+ function arrayLiteralAt(text, start) {
117
+ let depth = 0;
118
+ let quote;
119
+ for (let i = start; i < text.length; i += 1) {
120
+ const ch = text[i];
121
+ if (quote) {
122
+ if (ch === '\\')
123
+ i += 1;
124
+ else if (ch === quote)
125
+ quote = undefined;
126
+ continue;
127
+ }
128
+ if (ch === '"' || ch === "'" || ch === '`')
129
+ quote = ch;
130
+ else if (ch === '[')
131
+ depth += 1;
132
+ else if (ch === ']') {
133
+ depth -= 1;
134
+ if (depth === 0)
135
+ return text.slice(start, i + 1);
136
+ }
137
+ }
138
+ return undefined;
139
+ }
140
+ /**
141
+ * Extract the `plugins` array out of a registry document.
142
+ *
143
+ * The registry is `registry.json` — in the checkout, in `<ocrHome>/plugins/`,
144
+ * and at whatever URL a remote pull reads — and it is DATA, never imported: the
145
+ * backend never reaches outside its own `rootDir`, and a packaged host has no
146
+ * checkout to load from. JSON5 does the parsing, so comments, single quotes and
147
+ * trailing commas are still fine; plain JSON is a subset of it.
148
+ *
149
+ * Three shapes are accepted, in order: a JSON object carrying `plugins`, an
150
+ * assigned array (`export const plugins = [ … ]`, or `export default [ … ]`),
151
+ * and a bare array. The ASSIGNMENT match is anchored to the start of a line so
152
+ * a sentence in the header comment can never be mistaken for it.
153
+ *
154
+ * The OBJECT branch parses the raw text, not the trimmed raw text: a `.json`
155
+ * file whose first line is a `//` header comment must still be recognized as a
156
+ * document, and stripping comments before this decision is what makes that
157
+ * work (`whole.startsWith('{')` on the raw text silently sent it down the TS
158
+ * path and threw "no `plugins` array found").
159
+ */
160
+ export function parseRegistryText(text) {
161
+ if (!text.trim())
162
+ return [];
163
+ const code = stripComments(text);
164
+ const whole = code.trim();
165
+ // A JSON document is the whole thing; the two array shapes need a search.
166
+ if (whole.startsWith('{')) {
167
+ const parsed = JSON5.parse(whole);
168
+ return Array.isArray(parsed.plugins) ? parsed.plugins : [];
169
+ }
170
+ const assigned = /^[ \t]*(?:export\s+(?:const|let|var)\s+)?(plugins|default)\s*(?::[^=[]*)?=\s*\[/m.exec(code);
171
+ if (assigned) {
172
+ const literal = arrayLiteralAt(code, assigned.index + assigned[0].length - 1);
173
+ if (!literal)
174
+ throw new Error('the `plugins` array is not closed');
175
+ const parsed = JSON5.parse(literal);
176
+ return Array.isArray(parsed) ? parsed : [];
177
+ }
178
+ const bareStart = code.search(/^[ \t]*\[/m);
179
+ if (bareStart >= 0) {
180
+ const literal = arrayLiteralAt(code, code.indexOf('[', bareStart));
181
+ if (literal) {
182
+ const parsed = JSON5.parse(literal);
183
+ return Array.isArray(parsed) ? parsed : [];
184
+ }
185
+ }
186
+ throw new Error('no `plugins` array found');
187
+ }
188
+ /** The registry file candidates, most specific first.
189
+ *
190
+ * The checkout tier is REPO-relative: this module sits at
191
+ * `<root>/backend/{src|dist}/plugins/`, so three levels up is the tree the
192
+ * registry is authored in. Inside a `bun build --compile` snapshot that walk
193
+ * lands on the virtual embedded FS (`B:\~BUN\root\…` on Windows) and names
194
+ * paths that cannot exist — two dead entries in the "tried" list that only
195
+ * teach the operator to hunt on a drive they do not own. A packaged host has
196
+ * no checkout by definition (ADR-0032: no release ships one), so the tier is
197
+ * omitted there and the list names exactly what was reachable.
198
+ *
199
+ * Every candidate is named `registry.json`: the checkout file, the OCR-home
200
+ * snapshot a remote pull writes, and the remote document itself are ONE format,
201
+ * so there is no second spelling for an operator to guess at. */
202
+ export function registryCandidates(opts = {}) {
203
+ const override = process.env.OCR_PLUGIN_REGISTRY?.trim();
204
+ const list = [];
205
+ if (override)
206
+ list.push(path.resolve(override));
207
+ list.push(registryFilePath());
208
+ const packaged = opts.packaged ?? compiledSnapshotExe();
209
+ if (!packaged) {
210
+ const here = path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
211
+ list.push(path.resolve(here, '../../../plugins/registry.json'));
212
+ }
213
+ return list;
214
+ }
215
+ /** Read the registry from the first candidate that exists. */
216
+ function readRegistry() {
217
+ const tried = registryCandidates();
218
+ const override = process.env.OCR_PLUGIN_REGISTRY?.trim();
219
+ for (const file of tried) {
220
+ if (!fs.existsSync(file))
221
+ continue;
222
+ let entries;
223
+ try {
224
+ entries = parseRegistryText(fs.readFileSync(file, 'utf8'))
225
+ .map(normalizeEntry)
226
+ .filter((e) => e !== undefined);
227
+ }
228
+ catch (err) {
229
+ return {
230
+ problem: {
231
+ code: 'malformed-registry',
232
+ message: `cannot read the plugin registry at ${file}: ${err instanceof Error ? err.message : String(err)}`,
233
+ tried,
234
+ },
235
+ };
236
+ }
237
+ const origin = override && path.resolve(override) === file
238
+ ? 'env'
239
+ : file.startsWith(pluginsRoot() + path.sep)
240
+ ? 'home'
241
+ : 'repo';
242
+ // One repository may legitimately be listed twice (two plugins in one repo)
243
+ // only when the entries differ; an exact duplicate is one card, not two.
244
+ const seen = new Set();
245
+ entries = entries.filter((e) => {
246
+ const key = `${e.repo}#${e.ref ?? ''}#${e.subdir ?? ''}`;
247
+ if (seen.has(key))
248
+ return false;
249
+ seen.add(key);
250
+ return true;
251
+ });
252
+ if (entries.length === 0) {
253
+ return { problem: { code: 'empty-registry', message: `${file} declares no plugin repositories`, tried } };
254
+ }
255
+ return { source: { file, origin }, entries };
256
+ }
257
+ return {
258
+ problem: {
259
+ code: 'no-registry',
260
+ message: 'no plugin registry found — create plugins/registry.json in the OmniCellRouter checkout, or <ocrHome>/plugins/registry.json, or point OCR_PLUGIN_REGISTRY at one',
261
+ tried,
262
+ },
263
+ };
264
+ }
265
+ // ---------------------------------------------------------------------------
266
+ // Upstream reads
267
+ // ---------------------------------------------------------------------------
268
+ /** A marketplace read is idempotent and the console is waiting on it, so the
269
+ * budget is seconds — not the harness market's 30 s browse policy. */
270
+ const FETCH_TIMEOUT_MS = 12_000;
271
+ const REPO_META_TIMEOUT_MS = 8_000;
272
+ /** How long one card's upstream answer is reused before the next read re-fetches
273
+ * it.
274
+ *
275
+ * TEN MINUTES was the first guess and it is too short for what the data is: a
276
+ * plugin's manifest, release assets and star count move over DAYS. Every cold
277
+ * console visit inside that window costs one GitHub round trip per card (eight
278
+ * cards = eight requests against a small anonymous budget), to learn nothing.
279
+ *
280
+ * THIRTY MINUTES keeps a stale-tolerance an operator can live with — a version
281
+ * published ten minutes ago is not something this page must know before they
282
+ * ask — while cutting the steady-state request rate to a third. The console's
283
+ * Refresh button still forces a re-read at any moment, and `stale` is reported
284
+ * when a re-read fails, so the answer is never silently old. */
285
+ export const MARKET_CACHE_TTL_MS = 30 * 60_000;
286
+ /**
287
+ * Bump when a change to HOW a row is composed makes previously cached rows
288
+ * WRONG — not merely old.
289
+ *
290
+ * The first case, and the reason this exists: scanned entries used to hard-code
291
+ * `method: 'code'`, then learned to resolve `auto` → release-or-source. Every
292
+ * row cached before that change states a method the current rule would not
293
+ * produce, so it must be re-read instead of served.
294
+ *
295
+ * Contrast with a TTL-only change (30 → 60 minutes): that makes rows older, not
296
+ * wrong, so it bumps nothing.
297
+ */
298
+ export const CACHE_RULE_VERSION = 2;
299
+ const MIME_BY_EXT = {
300
+ png: 'image/png',
301
+ jpg: 'image/jpeg',
302
+ jpeg: 'image/jpeg',
303
+ webp: 'image/webp',
304
+ svg: 'image/svg+xml',
305
+ };
306
+ /** The logo MIME for a file name, or undefined when the format is not one the
307
+ * console renders. ONE table: the installed-plugin logo route serves the same
308
+ * formats and must answer the same types. */
309
+ export function logoMimeFor(filename) {
310
+ return MIME_BY_EXT[path.extname(filename).replace(/^\./, '').toLowerCase()];
311
+ }
312
+ /** The git ref a repository read is pinned to. The registry's `ref` when it
313
+ * names one, else the repository's DEFAULT BRANCH (read from the same API
314
+ * answer that carries stars/pushed_at — never assumed to be `main`). */
315
+ function effectiveRef(entry, defaultBranch) {
316
+ return entry.ref ?? defaultBranch ?? 'main';
317
+ }
318
+ /**
319
+ * `?ref=` for the contents endpoint, or `''` for the repository's default
320
+ * branch.
321
+ *
322
+ * The parameter is NOT optional decoration: without it the contents endpoint
323
+ * ALWAYS answers the default branch, so an entry pinned with `ref: 'v0.8.0'`
324
+ * would describe the tip of `main`. It is appended only when a ref is KNOWN —
325
+ * an entry that pins nothing passes no ref and lets GitHub answer its own
326
+ * default, which is also why an unresolvable `ref` must 404 loudly rather than
327
+ * quietly describe a different tree.
328
+ */
329
+ function refQuery(ref) {
330
+ return ref ? `?ref=${encodeURIComponent(ref)}` : '';
331
+ }
332
+ /** One file inside a repository, through the GitHub API (base64 `content`).
333
+ * The API is used instead of raw.githubusercontent because the raw host is
334
+ * unreachable on some networks while the API answers, and because a market
335
+ * read then spends the SAME 60/hour budget as the stars/last-push read from
336
+ * one host instead of splitting it across two.
337
+ *
338
+ * `ref` selects the TREE the file is read from — the entry's pin, else the
339
+ * default branch — so a pinned registry entry and a `code` build name the same
340
+ * source. `limit` bounds the DECODED body: the contents endpoint already
341
+ * refuses files above 1 MiB with no `content`, and this keeps a hostile/odd
342
+ * answer to the size a card can actually use. */
343
+ async function fetchRepoFile(entry, repoPath, transport, ref, limit = 2 * 1024 * 1024,
344
+ /** An EXPLICIT token. `null` = anonymous; omitted = the market's saved one.
345
+ * The distinction matters: a source with no token must not silently inherit
346
+ * another source's secret. */
347
+ token) {
348
+ const path = entry.subdir ? `${entry.subdir}/${repoPath}` : repoPath;
349
+ const api = await fetchJsonWithHeaders(transport, `https://api.github.com/repos/${entry.repo}/contents/${path}${refQuery(ref)}`, marketAuthHeaders(token), FETCH_TIMEOUT_MS);
350
+ if (!api.ok)
351
+ return { ok: false, status: api.status, error: api.error };
352
+ if (typeof api.value.content !== 'string')
353
+ return { ok: false, error: 'no content in the GitHub answer' };
354
+ const bytes = Buffer.from(api.value.content, 'base64');
355
+ if (bytes.byteLength > limit)
356
+ return { ok: false, error: `the file exceeds the ${Math.round(limit / 1024)} KiB cap` };
357
+ return { ok: true, value: bytes };
358
+ }
359
+ const PLUGIN_MARKET_SETTINGS_FILE = 'market.json';
360
+ const DEFAULT_MARKET_SETTINGS = { egress: 'direct', sources: [], registrySync: true };
361
+ /**
362
+ * The TOKEN a row authenticates with, resolved from the row's KEY.
363
+ *
364
+ * The key is `<repo>` or `<repo>@<subdir>` — exactly what a scanned entry carries
365
+ * (`originLabel` names the source only for display, so a renamed label must not
366
+ * break the lookup). A row whose key matches a configured source uses THAT row's
367
+ * token; everything else is a registry entry, whose scope is the env tier.
368
+ *
369
+ * `null` therefore means "a source with no token": anonymous, which is what a
370
+ * public source IS — never "borrow the registry's env token".
371
+ */
372
+ function tokenForRowKey(key, settings) {
373
+ const sources = (settings ?? readMarketSettings()).sources;
374
+ if (sources.length === 0)
375
+ return undefined;
376
+ for (const source of sources) {
377
+ for (const repo of reposForSource(source.target)) {
378
+ if (key === repo || key.startsWith(`${repo}@`))
379
+ return source.token ?? null;
380
+ }
381
+ }
382
+ // A literal scope did not answer: an OWNER or GLOB may still cover this repo.
383
+ return tokenForOwnerScopedRow(key, settings);
384
+ }
385
+ /**
386
+ * Whether a source OWNER is a user account or an organization.
387
+ *
388
+ * The answer picks the listing endpoint, and the two are not interchangeable:
389
+ * `/users/{owner}/repos` returns PUBLIC repositories only, while
390
+ * `/orgs/{org}/repos` returns every repository the token can see. Asking the
391
+ * wrong one is silent — a private repository is simply absent from the answer.
392
+ *
393
+ * `GET /users/{owner}` answers for both kinds; on a failed read we fall back to
394
+ * `user`, the endpoint that exists for every account, so an unreachable owner
395
+ * produces a listing error with a message rather than a wrong endpoint choice.
396
+ */
397
+ async function ownerKind(owner, transport, token) {
398
+ const res = await fetchJsonWithHeaders(transport, `https://api.github.com/users/${owner}`, marketAuthHeaders(token), REPO_META_TIMEOUT_MS);
399
+ return res.ok && res.value.type === 'Organization' ? 'org' : 'user';
400
+ }
401
+ /** The concrete repository names one source target covers, for a LITERAL scope.
402
+ * A bare owner or a glob cannot be answered without a listing (that is the
403
+ * scan's job), so they are matched by the `owner/` prefix below instead. */
404
+ function reposForSource(target) {
405
+ const [owner, pattern] = target.split('/');
406
+ if (!owner || !pattern || /[*?]/.test(pattern))
407
+ return [];
408
+ return [`${owner}/${pattern}`];
409
+ }
410
+ /** Does `key` belong to a source whose scope is an OWNER or a GLOB? Used only as
411
+ * a fallback for shapes `reposForSource` cannot enumerate. */
412
+ function tokenForOwnerScopedRow(key, settings) {
413
+ const sources = (settings ?? readMarketSettings()).sources;
414
+ for (const source of sources) {
415
+ const [owner, pattern] = source.target.split('/');
416
+ if (!owner)
417
+ continue;
418
+ // Only the shapes `reposForSource` cannot name: a bare owner, `owner/*`, or
419
+ // a glob in the repo half. A literal `owner/repo` was already answered.
420
+ if (pattern && !/[*?]/.test(pattern))
421
+ continue;
422
+ if (key.toLowerCase().startsWith(`${owner.toLowerCase()}/`))
423
+ return source.token ?? null;
424
+ }
425
+ return undefined;
426
+ }
427
+ export function marketSettingsPath() {
428
+ return path.join(pluginsRoot(), PLUGIN_MARKET_SETTINGS_FILE);
429
+ }
430
+ /**
431
+ * The ONE remote registry this gateway pulls: the official list in the OCR
432
+ * gateway's own repository (ADR-0037 §12).
433
+ *
434
+ * A constant rather than a setting on purpose — see `MarketSettings.registrySync`
435
+ * for why the URL is not operator-editable. It is the raw file under the default
436
+ * branch, which is also what `plugins/registry.json` is in the checkout, so what
437
+ * a packaged install pulls is the same document a source run reads.
438
+ */
439
+ export const OFFICIAL_REGISTRY_URL = 'https://raw.githubusercontent.com/kenlin8827/omnicell-router/main/plugins/registry.json';
440
+ // ---------------------------------------------------------------------------
441
+ // Remote registry sync (ADR-0037 §12)
442
+ // ---------------------------------------------------------------------------
443
+ /** `<pluginsRoot>/registry.json` — the file a successful pull overwrites, and
444
+ * the registry tier that reads it. ONE definition: the sync writes it and the
445
+ * candidate list reads it, and a second spelling would let a pull land where
446
+ * nothing looks. */
447
+ export function registryFilePath() {
448
+ return path.join(pluginsRoot(), 'registry.json');
449
+ }
450
+ const REGISTRY_SYNC_STATE_FILE = 'registry-sync.json';
451
+ function registrySyncStatePath() {
452
+ return path.join(pluginsRoot(), REGISTRY_SYNC_STATE_FILE);
453
+ }
454
+ export function registrySyncState() {
455
+ const file = registryFilePath();
456
+ try {
457
+ const raw = JSON.parse(fs.readFileSync(registrySyncStatePath(), 'utf8'));
458
+ return { ...raw, file };
459
+ }
460
+ catch {
461
+ return { file };
462
+ }
463
+ }
464
+ function writeRegistrySyncState(state) {
465
+ try {
466
+ safeWriteJson(registrySyncStatePath(), state);
467
+ }
468
+ catch {
469
+ // A state write failure must never fail a pull that already landed.
470
+ }
471
+ }
472
+ /**
473
+ * Validate a pulled document WITHOUT touching the local file.
474
+ *
475
+ * The rules that matter are asymmetric with the hand-edited tiers: a MALFORMED
476
+ * local registry is an error the operator must fix, while a malformed REMOTE
477
+ * answer is something they cannot fix and must never cost them the list they
478
+ * already have. So a pull is accepted only when it parses AND yields at least
479
+ * one usable entry; anything else leaves the existing file exactly as it was.
480
+ */
481
+ function validateRemoteRegistry(text) {
482
+ let entries;
483
+ try {
484
+ entries = parseRegistryText(text)
485
+ .map(normalizeEntry)
486
+ .filter((e) => e !== undefined);
487
+ }
488
+ catch {
489
+ return undefined;
490
+ }
491
+ // An empty or unusable document is refused on purpose: a truncated CDN answer,
492
+ // a 200 serving an HTML error page that happens to parse, or a repository that
493
+ // emptied its list mid-edit would otherwise WIPE the operator's curation.
494
+ return entries.length > 0 ? entries : undefined;
495
+ }
496
+ let registrySyncInFlight;
497
+ /**
498
+ * Pull the official registry and, on success, overwrite
499
+ * `<pluginsRoot>/registry.json`.
500
+ *
501
+ * SWR, in the operator's words: a successful fetch REPLACES the local file, and
502
+ * a failed one is swallowed — the previously synced (or hand-written) file keeps
503
+ * serving. The only trace of a failure is `lastError` in the sync state, which
504
+ * the console shows, because a sync that silently stopped working is otherwise
505
+ * indistinguishable from one that works.
506
+ *
507
+ * The URL is `OFFICIAL_REGISTRY_URL`, never an argument: see
508
+ * `MarketSettings.registrySync` for why it is not configurable.
509
+ *
510
+ * Nothing here throws. A pull that fails is not a market failure.
511
+ */
512
+ export async function syncRemoteRegistry(deps = {}) {
513
+ const settings = readMarketSettings();
514
+ const url = OFFICIAL_REGISTRY_URL;
515
+ const state = registrySyncState();
516
+ // Explicitly turned off: no pull, no timer, no state churn.
517
+ if (!settings.registrySync)
518
+ return state;
519
+ // An explicit `OCR_PLUGIN_REGISTRY` names the registry the operator wants
520
+ // read; pulling would write a file that tier can never shadow, so the pull is
521
+ // skipped instead of doing invisible work.
522
+ if (process.env.OCR_PLUGIN_REGISTRY?.trim())
523
+ return state;
524
+ // One pull at a time: a console refresh racing the boot tick must not spend
525
+ // two requests on the same ETag.
526
+ if (registrySyncInFlight)
527
+ return registrySyncInFlight;
528
+ const now = Date.now();
529
+ // A verdict recorded for a DIFFERENT URL says nothing about this one (the URL
530
+ // is a constant now, so this only matters after a move): a stale failure must
531
+ // not throttle the first pull of the new document, and a stale ETag must not
532
+ // be revalidated against it.
533
+ const sameUrl = state.url === url;
534
+ const lastError = sameUrl ? state.lastError : undefined;
535
+ const etag = sameUrl ? state.etag : undefined;
536
+ const syncedAt = sameUrl && state.syncedAt ? Date.parse(state.syncedAt) : 0;
537
+ const failedAt = sameUrl && state.lastErrorAt ? Date.parse(state.lastErrorAt) : 0;
538
+ const wait = lastError ? REGISTRY_SYNC_RETRY_MS : registrySyncIntervalMs();
539
+ const lastAttempt = lastError ? failedAt : syncedAt;
540
+ if (!deps.force && lastAttempt && now - lastAttempt < wait)
541
+ return state;
542
+ registrySyncInFlight = (async () => {
543
+ let transport;
544
+ try {
545
+ transport = marketTransport(settings, deps.fetchImpl);
546
+ }
547
+ catch (err) {
548
+ // The operator asked for `proxy` with no endpoint. Nothing to fetch, and
549
+ // nothing the market page should shout about: the file still serves.
550
+ const next = {
551
+ ...state,
552
+ url,
553
+ lastError: err instanceof Error ? err.message : String(err),
554
+ lastErrorAt: new Date(now).toISOString(),
555
+ };
556
+ writeRegistrySyncState(next);
557
+ return { ...next, file: registryFilePath() };
558
+ }
559
+ try {
560
+ const res = await transport(url, {
561
+ // The registry is a curated list, not a per-repo card: it rides the
562
+ // ENV token tier (a public registry needs none), never a source's PAT.
563
+ headers: {
564
+ ...marketAuthHeaders(undefined),
565
+ 'User-Agent': 'OmniCellRouter/plugin-market',
566
+ ...(etag ? { 'If-None-Match': etag } : {}),
567
+ },
568
+ signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
569
+ });
570
+ if (res.status === 304) {
571
+ const next = {
572
+ ...state,
573
+ url,
574
+ syncedAt: new Date(now).toISOString(),
575
+ lastError: undefined,
576
+ lastErrorAt: undefined,
577
+ };
578
+ writeRegistrySyncState(next);
579
+ return { ...next, file: registryFilePath() };
580
+ }
581
+ if (!res.ok)
582
+ throw new Error(`HTTP ${res.status}`);
583
+ const text = await res.text();
584
+ if (Buffer.byteLength(text, 'utf8') > PLUGIN_REGISTRY_MAX_BYTES) {
585
+ throw new Error(`the registry document exceeds the ${Math.round(PLUGIN_REGISTRY_MAX_BYTES / 1024)} KiB cap`);
586
+ }
587
+ if (!validateRemoteRegistry(text)) {
588
+ throw new Error('the registry document has no usable plugin entry');
589
+ }
590
+ // Atomic in place: the reader must never observe a half-written registry
591
+ // (a torn file would read as `malformed-registry` and blank the market).
592
+ const target = registryFilePath();
593
+ fs.mkdirSync(path.dirname(target), { recursive: true });
594
+ const tmp = `${target}.tmp.${process.pid}.${now}`;
595
+ fs.writeFileSync(tmp, text, 'utf8');
596
+ fs.renameSync(tmp, target);
597
+ const next = {
598
+ url,
599
+ file: target,
600
+ syncedAt: new Date(now).toISOString(),
601
+ ...(res.headers.get('etag') ? { etag: res.headers.get('etag') } : {}),
602
+ };
603
+ writeRegistrySyncState(next);
604
+ return next;
605
+ }
606
+ catch (err) {
607
+ // SILENT by contract: keep the file, record why for the console.
608
+ const next = {
609
+ ...state,
610
+ url,
611
+ lastError: err instanceof Error ? err.message : String(err),
612
+ lastErrorAt: new Date(now).toISOString(),
613
+ };
614
+ writeRegistrySyncState(next);
615
+ return { ...next, file: registryFilePath() };
616
+ }
617
+ })().finally(() => {
618
+ registrySyncInFlight = undefined;
619
+ });
620
+ return registrySyncInFlight;
621
+ }
622
+ /** How often a due pull is re-attempted. One function, so the lazy read path and
623
+ * the background tick cannot drift into two cadences. */
624
+ function registrySyncIntervalMs() {
625
+ return DEFAULT_REGISTRY_SYNC_INTERVAL_MS;
626
+ }
627
+ /** A GitHub owner name: what an org URL and an `owner/repo` share. Refuses
628
+ * anything that is not ONE path component, because it is joined into an API
629
+ * URL. */
630
+ export function normalizeOrgName(raw) {
631
+ if (typeof raw !== 'string')
632
+ return undefined;
633
+ const value = raw.trim().replace(/^https?:\/\/(?:www\.)?github\.com\//i, '').replace(/\/+$/, '');
634
+ return /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/.test(value) ? value : undefined;
635
+ }
636
+ /**
637
+ * Normalize a source TARGET, or undefined when it cannot be one.
638
+ *
639
+ * Three accepted shapes, all anchored on one owner:
640
+ * `owner` every repository of that owner
641
+ * `owner/repo` one repository
642
+ * `owner/pattern*` repositories matching a shell glob
643
+ *
644
+ * The glob lives in the REPO half only — an owner pattern would let one row
645
+ * match another org's repositories, which is never what a single row means.
646
+ */
647
+ export function normalizeSourceTarget(raw) {
648
+ if (typeof raw !== 'string')
649
+ return undefined;
650
+ const value = raw
651
+ .trim()
652
+ .replace(/^https?:\/\/(?:www\.)?github\.com\//i, '')
653
+ .replace(/^git@github\.com:/i, '')
654
+ .replace(/\/+$/, '')
655
+ .replace(/\.git$/i, '');
656
+ if (!value)
657
+ return undefined;
658
+ const parts = value.split('/');
659
+ if (parts.length === 1)
660
+ return normalizeOrgName(parts[0]);
661
+ if (parts.length !== 2)
662
+ return undefined;
663
+ const owner = normalizeOrgName(parts[0]);
664
+ if (!owner)
665
+ return undefined;
666
+ const repo = parts[1];
667
+ // A repo half may be a literal name or a glob with `*` / `?`.
668
+ if (!/^[A-Za-z0-9._*-]+$/.test(repo) || repo === '.' || repo === '..')
669
+ return undefined;
670
+ return `${owner}/${repo}`;
671
+ }
672
+ /** Whether a concrete repository name matches a normalized target. */
673
+ function sourceMatches(target, fullName) {
674
+ const [owner, pattern] = target.split('/');
675
+ const [repoOwner, repoName] = fullName.split('/');
676
+ if (!owner || owner.toLowerCase() !== (repoOwner ?? '').toLowerCase())
677
+ return false;
678
+ // A bare owner (or `owner/*`) is every repository it owns.
679
+ if (!pattern || pattern === '*')
680
+ return true;
681
+ if (!/[*?]/.test(pattern))
682
+ return pattern.toLowerCase() === (repoName ?? '').toLowerCase();
683
+ const re = new RegExp(`^${pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`, 'i');
684
+ return re.test(repoName ?? '');
685
+ }
686
+ function normalizeSourceRow(raw) {
687
+ if (!raw || typeof raw !== 'object')
688
+ return undefined;
689
+ const row = raw;
690
+ const target = normalizeSourceTarget(row.target);
691
+ if (!target)
692
+ return undefined;
693
+ const token = typeof row.token === 'string' && row.token.trim() ? row.token.trim() : undefined;
694
+ const label = typeof row.label === 'string' && row.label.trim() ? row.label.trim() : undefined;
695
+ return {
696
+ target,
697
+ ...(token ? { token } : {}),
698
+ ...(label ? { label } : {}),
699
+ ...(typeof row.addedAt === 'string' ? { addedAt: row.addedAt } : {}),
700
+ };
701
+ }
702
+ /** The operator's setting, defaulting `direct` + no sources when the file is
703
+ * absent or unreadable. A corrupt value degrades to the default (never throws):
704
+ * the market is a read surface and a half-written file must not brick it. */
705
+ export function readMarketSettings() {
706
+ try {
707
+ const raw = JSON.parse(fs.readFileSync(marketSettingsPath(), 'utf8'));
708
+ const fromSources = Array.isArray(raw?.sources)
709
+ ? raw.sources.map(normalizeSourceRow).filter((v) => v !== undefined)
710
+ : [];
711
+ const legacy = Array.isArray(raw?.discoveryOrgs)
712
+ ? raw.discoveryOrgs
713
+ .map((org) => normalizeSourceRow({ target: org }))
714
+ .filter((v) => v !== undefined)
715
+ : [];
716
+ // Dedupe by target: a legacy row that already came across as a source must
717
+ // not scan the same owner twice.
718
+ const seen = new Set();
719
+ const sources = [...fromSources, ...legacy].filter((row) => {
720
+ const key = row.target.toLowerCase();
721
+ if (seen.has(key))
722
+ return false;
723
+ seen.add(key);
724
+ return true;
725
+ });
726
+ return {
727
+ egress: raw?.egress === 'proxy' ? 'proxy' : DEFAULT_MARKET_SETTINGS.egress,
728
+ sources,
729
+ registrySync: raw?.registrySync !== false,
730
+ };
731
+ }
732
+ catch {
733
+ return { ...DEFAULT_MARKET_SETTINGS, sources: [] };
734
+ }
735
+ }
736
+ /** Persist the market setting and answer the merged value. */
737
+ export function writeMarketSettings(next) {
738
+ const current = readMarketSettings();
739
+ // An explicit value wins; omitted keeps what was stored. `egress` has always
740
+ // been a two-state enum with `direct` as its floor, so an unrecognized value
741
+ // degrades to `direct` (the field is never "unset").
742
+ const egress = next.egress === undefined ? current.egress : next.egress === 'proxy' ? 'proxy' : 'direct';
743
+ // `undefined` keeps the stored list; an array REPLACES it (the console sends
744
+ // the whole list, and an empty array is a deliberate "scan nothing").
745
+ const sources = Array.isArray(next.sources)
746
+ ? next.sources.map(normalizeSourceRow).filter((v) => v !== undefined)
747
+ : current.sources;
748
+ // A switch, not a tri-state: anything but an explicit `false` is the default
749
+ // (ON), so a hand-edited `"no"` cannot silently disable the official list.
750
+ const registrySync = next.registrySync === undefined ? current.registrySync : next.registrySync !== false;
751
+ const stored = { egress, sources, registrySync };
752
+ const file = marketSettingsPath();
753
+ fs.mkdirSync(path.dirname(file), { recursive: true });
754
+ fs.writeFileSync(file, `${JSON.stringify(stored, null, 2)}\n`, 'utf8');
755
+ return stored;
756
+ }
757
+ /** Add ONE source. A duplicate target is refused: two rows for the same owner
758
+ * would scan it twice and report its repositories as duplicates. `label` is
759
+ * REQUIRED (see `requireSourceLabel`): it is what the source's cards print. */
760
+ export function addMarketSource(input) {
761
+ const target = normalizeSourceTarget(input.target);
762
+ if (!target)
763
+ throw new Error(`'${input.target}' is not owner, owner/repo or owner/pattern*`);
764
+ const label = requireSourceLabel(input.label);
765
+ const current = readMarketSettings();
766
+ if (current.sources.some((source) => source.target.toLowerCase() === target.toLowerCase())) {
767
+ throw new Error(`'${target}' is already a source`);
768
+ }
769
+ const row = {
770
+ target,
771
+ label,
772
+ ...(typeof input.token === 'string' && input.token.trim() ? { token: input.token.trim() } : {}),
773
+ addedAt: new Date().toISOString(),
774
+ };
775
+ return writeMarketSettings({
776
+ egress: current.egress,
777
+ registrySync: current.registrySync,
778
+ sources: [...current.sources, row],
779
+ });
780
+ }
781
+ /** Remove ONE source by its target (the row's identity, since targets are
782
+ * unique). Idempotent: removing an unknown target is not an error. */
783
+ export function removeMarketSource(target) {
784
+ const normalized = normalizeSourceTarget(target) ?? target;
785
+ const current = readMarketSettings();
786
+ return writeMarketSettings({
787
+ egress: current.egress,
788
+ registrySync: current.registrySync,
789
+ sources: current.sources.filter((source) => source.target.toLowerCase() !== normalized.toLowerCase()),
790
+ });
791
+ }
792
+ /**
793
+ * Drop the index entries a removed source ALONE justified (ADR-0037 §9).
794
+ *
795
+ * `forgetSourceOutcome` forgets the row's VERDICT and keeps its entries on
796
+ * purpose, because one repository can be visible to two overlapping sources —
797
+ * but an entry NO remaining source's scope can reach is a card backed by
798
+ * nothing: it would keep offering a plugin whose only source was deleted,
799
+ * attributed to a row the drawer no longer lists. Only those are dropped. An
800
+ * entry a remaining scope still matches is KEPT, which is why the prune tests
801
+ * SCOPE rather than attribution (`via`): a rename or a shared label cannot be
802
+ * trusted to say which source found an entry.
803
+ *
804
+ * Removing the LAST source clears the index instead of leaving a
805
+ * "ready, zero entries" one. `builtAt` is never re-stamped — no scan ran.
806
+ */
807
+ export function pruneSourceIndexForRemovedSource(remaining) {
808
+ // Scope, not attribution: `via` is a display label a rename or a shared label
809
+ // can misstate, while a scope a source still holds is a fact about reach.
810
+ filterSourceIndex((entry) => remaining.some((row) => sourceMatches(row.target, entry.repo)));
811
+ }
812
+ /**
813
+ * The display name a source row MUST carry (ADR-0037 §9/§11).
814
+ *
815
+ * `label` is REQUIRED: it is what a scanned card prints instead of a generic
816
+ * "source" badge, so a row without one leaves its cards unattributable. The
817
+ * label is ALSO what `relabelSourceEntries` matches on when that display name
818
+ * changes, so a nameless row could not have its cards re-labelled at all.
819
+ * Absent or blank is refused; any other value is the operator's to choose.
820
+ */
821
+ export function requireSourceLabel(raw) {
822
+ const label = typeof raw === 'string' ? raw.trim() : '';
823
+ if (!label)
824
+ throw new Error('body.label is required — give this source a name to show on its cards');
825
+ return label;
826
+ }
827
+ /**
828
+ * Edit ONE source IN PLACE (ADR-0037 §11), including its SCOPE.
829
+ *
830
+ * `target` identifies the row being edited and `nextTarget` is the scope it
831
+ * should carry afterwards. Renaming is a REAL verb rather than "remove + add",
832
+ * because the two differ in what they preserve: `addedAt` and an untouched
833
+ * `token` survive, and a scope typo is one field away from the row it belongs to
834
+ * instead of a delete the operator has to remember to follow with an add
835
+ * (whose token they can no longer see, so they could not retype it).
836
+ *
837
+ * The rules that make the rename safe:
838
+ *
839
+ * - a new scope is normalized and REFUSED when it is unusable — a typo must
840
+ * not be silently dropped, since that would leave the operator scanning
841
+ * something other than what they asked for;
842
+ * - colliding with ANOTHER row is refused: two rows for one scope scan it
843
+ * twice and report its repositories as duplicates;
844
+ * - re-saving the SAME scope is not a collision, so a label-only edit keeps
845
+ * working.
846
+ *
847
+ * The other fields follow the console's mask rule:
848
+ *
849
+ * - `label` is REQUIRED on every edit (`requireSourceLabel`), so it is always
850
+ * sent and can never be cleared — there is no fallback name to fall back to;
851
+ * - `token` — the VALUE never reaches the console, so a form can only ever say
852
+ * "keep", "replace" or "clear", never "this is the current one":
853
+ * `undefined` keeps what is stored, `null` / `''` CLEARS it (anonymous,
854
+ * public repositories only), a string replaces it.
855
+ */
856
+ export function updateMarketSource(input) {
857
+ const identity = normalizeSourceTarget(input.target) ?? input.target;
858
+ const current = readMarketSettings();
859
+ const row = current.sources.find((source) => source.target.toLowerCase() === identity.toLowerCase());
860
+ if (!row)
861
+ throw new Error(`'${identity}' is not a configured source`);
862
+ let nextTarget = row.target;
863
+ if (input.nextTarget !== undefined) {
864
+ const normalized = normalizeSourceTarget(input.nextTarget);
865
+ if (!normalized) {
866
+ throw new Error(`'${input.nextTarget}' is not owner, owner/repo or owner/pattern*`);
867
+ }
868
+ const collides = current.sources.some((source) => source !== row && source.target.toLowerCase() === normalized.toLowerCase());
869
+ if (collides)
870
+ throw new Error(`'${normalized}' is already a source`);
871
+ nextTarget = normalized;
872
+ }
873
+ // A label is REQUIRED, so `null` / `''` (the old "clear it" spelling) is a
874
+ // refusal here too: there is no fallback name to fall back TO.
875
+ const label = requireSourceLabel(input.label);
876
+ const nextToken = input.token === undefined ? row.token : typeof input.token === 'string' && input.token.trim() ? input.token : undefined;
877
+ const updated = {
878
+ target: nextTarget,
879
+ label,
880
+ ...(nextToken ? { token: nextToken.trim() } : {}),
881
+ ...(row.addedAt ? { addedAt: row.addedAt } : {}),
882
+ };
883
+ return writeMarketSettings({
884
+ egress: current.egress,
885
+ registrySync: current.registrySync,
886
+ sources: current.sources.map((source) => (source === row ? updated : source)),
887
+ });
888
+ }
889
+ export function describeMarketSources(sources) {
890
+ return sources.map((row) => ({
891
+ target: row.target,
892
+ ...(row.label ? { label: row.label } : {}),
893
+ ...(row.addedAt ? { addedAt: row.addedAt } : {}),
894
+ authenticated: Boolean(row.token),
895
+ ...(row.token ? { hint: `${row.token.slice(0, 12)}…${row.token.slice(-4)}` } : {}),
896
+ }));
897
+ }
898
+ /**
899
+ * The transport for one market read, honouring the OPERATOR'S choice.
900
+ *
901
+ * `direct` dials the runtime's own fetch. `proxy` dials the operator's effective
902
+ * outbound endpoint, resolved by the ONE resolver every other proxied call uses
903
+ * (`utils/proxy.ts` — `proxy.url` in manual mode, the Clash mixed port in mihomo
904
+ * mode) and dialed through `fetchViaProxy`. There is no third "guess" leg: the
905
+ * model-scoped provider/model split is never consulted, because a market read is
906
+ * console traffic, not a provider call.
907
+ *
908
+ * `proxy` with no usable endpoint REFUSES (`OutboundEgressRefusedError`'s
909
+ * message) rather than falling back to direct — the operator asked to keep this
910
+ * traffic off their real address, and a silent direct dial is the leak that
911
+ * choice was meant to prevent.
912
+ */
913
+ function marketTransport(settings, fetchImpl) {
914
+ if (settings.egress !== 'proxy')
915
+ return fetchImpl ?? fetch;
916
+ const endpoint = marketEgressProxy(settings);
917
+ return ((input, init) => {
918
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
919
+ return fetchViaProxy(url, init ?? {}, endpoint);
920
+ });
921
+ }
922
+ /**
923
+ * The outbound endpoint a `proxy` market read dials, resolved the same way
924
+ * `marketTransport` resolves it.
925
+ *
926
+ * A source build is a SEPARATE process (`git clone`), so it cannot ride the
927
+ * `fetch` transport above. It gets this URL instead, through the child's
928
+ * environment — otherwise the card would read through the operator's proxy and
929
+ * the clone would dial direct, which is exactly the leak `egress: 'proxy'`
930
+ * exists to prevent. Refusing here (rather than falling back to direct) keeps
931
+ * that promise for the build too.
932
+ */
933
+ function marketEgressProxy(settings) {
934
+ if (settings.egress !== 'proxy') {
935
+ throw new Error('market egress endpoint requested for a direct market setting');
936
+ }
937
+ const endpoint = egressEndpointUrl();
938
+ if (!endpoint) {
939
+ throw new Error('the plugin market is set to use the outbound proxy, but no usable proxy endpoint is configured — enable `proxy.enabled` with a valid URL (or a mihomo core), or set the market to direct');
940
+ }
941
+ return endpoint;
942
+ }
943
+ /**
944
+ * The CONCRETE credential a row's `git clone` must present (ADR-0037 §8).
945
+ *
946
+ * `tokenForRowKey` answers the three scopes the market reads with:
947
+ *
948
+ * - a string — that SOURCE row's own token;
949
+ * - `null` — a source that carries NO token: anonymous, and the clone must be
950
+ * anonymous too (a source row never inherits the env token);
951
+ * - `undefined` — a registry row, whose scope is the env tier.
952
+ *
953
+ * A clone cannot express the third case as "no credential", so it is resolved
954
+ * to `GITHUB_TOKEN` here — the same token the card's own reads carried.
955
+ */
956
+ export function rowAuthToken(key, settings) {
957
+ const resolved = tokenForRowKey(key, settings);
958
+ if (resolved === null)
959
+ return undefined;
960
+ return resolved ?? envGithubToken();
961
+ }
962
+ async function readCapped(res, cap) {
963
+ const declared = Number(res.headers.get('content-length') ?? '');
964
+ if (Number.isFinite(declared) && declared > cap)
965
+ return undefined;
966
+ if (!res.body)
967
+ return new Uint8Array(await res.arrayBuffer());
968
+ const reader = res.body.getReader();
969
+ const chunks = [];
970
+ let total = 0;
971
+ for (;;) {
972
+ const { done, value } = await reader.read();
973
+ if (done)
974
+ break;
975
+ total += value.byteLength;
976
+ if (total > cap) {
977
+ await reader.cancel().catch(() => undefined);
978
+ return undefined;
979
+ }
980
+ chunks.push(value);
981
+ }
982
+ const out = new Uint8Array(total);
983
+ let offset = 0;
984
+ for (const chunk of chunks) {
985
+ out.set(chunk, offset);
986
+ offset += chunk.byteLength;
987
+ }
988
+ return out;
989
+ }
990
+ /**
991
+ * Auth headers for ONE market read (ADR-0037 §8).
992
+ *
993
+ * A market read never has "a credential of its own": the TOKEN IS A FIELD OF THE
994
+ * SOURCE a row came from, and the registry itself has none. So the caller always
995
+ * names the scope:
996
+ *
997
+ * - a string — that SOURCE row's own token;
998
+ * - `null` — ANONYMOUS, deliberately not "inherits something": a source with no
999
+ * token scans PUBLIC repositories only, and a row that claims no source must
1000
+ * not silently borrow another row's secret;
1001
+ * - omitted — the committed registry, whose only lever is `GITHUB_TOKEN`
1002
+ * (the env tier that predates the console source list).
1003
+ */
1004
+ function marketAuthHeaders(token) {
1005
+ const base = githubHeaders();
1006
+ // `githubHeaders()` adds `GITHUB_TOKEN`; an explicit scope replaces it, and an
1007
+ // anonymous read must not carry it at all.
1008
+ const resolved = token === undefined ? envGithubToken() : (token ?? undefined);
1009
+ if (!resolved) {
1010
+ delete base.Authorization;
1011
+ return base;
1012
+ }
1013
+ return { ...base, Authorization: `Bearer ${resolved}` };
1014
+ }
1015
+ /** The env tier, kept out of the source model: `GITHUB_TOKEN` is ambient
1016
+ * configuration for the REGISTRY's own reads, not a stored credential. */
1017
+ function envGithubToken() {
1018
+ const env = process.env.GITHUB_TOKEN?.trim();
1019
+ return env || undefined;
1020
+ }
1021
+ async function fetchText(transport, url, timeoutMs = FETCH_TIMEOUT_MS,
1022
+ /** The scope this read authenticates with: a source row's token, `null` for
1023
+ * anonymous, omitted for the registry (env tier only). */
1024
+ token) {
1025
+ try {
1026
+ const res = await transport(url, {
1027
+ headers: marketAuthHeaders(token),
1028
+ signal: AbortSignal.timeout(timeoutMs),
1029
+ });
1030
+ if (!res.ok)
1031
+ return { ok: false, status: res.status, error: `HTTP ${res.status}` };
1032
+ return { ok: true, value: await res.text() };
1033
+ }
1034
+ catch (err) {
1035
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1036
+ }
1037
+ }
1038
+ async function fetchJson(transport, url, timeoutMs = FETCH_TIMEOUT_MS, token) {
1039
+ const text = await fetchText(transport, url, timeoutMs, token);
1040
+ if (!text.ok)
1041
+ return text;
1042
+ try {
1043
+ return { ok: true, value: JSON.parse(text.value) };
1044
+ }
1045
+ catch {
1046
+ return { ok: false, error: 'the answer is not JSON' };
1047
+ }
1048
+ }
1049
+ /** `fetchJson` with CALLER-CHOSEN headers — the source scan names each row's own
1050
+ * token explicitly (`marketAuthHeaders(token)`), including `null` for one with
1051
+ * no token at all. */
1052
+ async function fetchJsonWithHeaders(transport, url, headers, timeoutMs = FETCH_TIMEOUT_MS) {
1053
+ try {
1054
+ const res = await transport(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
1055
+ if (!res.ok)
1056
+ return { ok: false, status: res.status, error: `HTTP ${res.status}` };
1057
+ return { ok: true, value: (await res.json()) };
1058
+ }
1059
+ catch (err) {
1060
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1061
+ }
1062
+ }
1063
+ /**
1064
+ * Read a BINARY body (a release asset, a committed zip, a logo).
1065
+ *
1066
+ * Authentication here is not symmetric with the JSON reads, and getting it wrong
1067
+ * is silent: GitHub redirects a private release asset to
1068
+ * `objects.githubusercontent.com`, and that host REJECTS a request carrying an
1069
+ * `Authorization` header. So the token is sent on the FIRST hop only and stripped
1070
+ * when the request is re-issued against the redirect target. `fetch(...,
1071
+ * {redirect: 'manual'})` is what makes that possible — the default `follow`
1072
+ * would replay our headers, token included, onto the storage host.
1073
+ */
1074
+ async function fetchBytes(transport, url, cap, timeoutMs = FETCH_TIMEOUT_MS,
1075
+ /** The scope this download authenticates with — same three cases as
1076
+ * `marketAuthHeaders`, and the SOURCE's own token here, because the package
1077
+ * lives in that source's repository. */
1078
+ token) {
1079
+ const auth = marketAuthHeaders(token);
1080
+ const hasAuth = typeof auth.Authorization === 'string';
1081
+ try {
1082
+ let res = await transport(url, {
1083
+ headers: { ...auth, 'User-Agent': 'OmniCellRouter/plugin-market' },
1084
+ // MANUAL so the redirect can be followed without replaying the token.
1085
+ redirect: 'manual',
1086
+ signal: AbortSignal.timeout(timeoutMs),
1087
+ });
1088
+ // Follow exactly one redirect chain, dropping the token from the first
1089
+ // hop that leaves the GitHub API host.
1090
+ let hops = 0;
1091
+ while (res.status >= 300 && res.status < 400 && hops < 5) {
1092
+ const location = res.headers.get('location');
1093
+ if (!location)
1094
+ break;
1095
+ const next = new URL(location, url);
1096
+ const sameHost = next.hostname === new URL(url).hostname;
1097
+ const headers = {
1098
+ ...(hasAuth && sameHost ? { Authorization: auth.Authorization } : {}),
1099
+ 'User-Agent': 'OmniCellRouter/plugin-market',
1100
+ };
1101
+ res = await transport(next.toString(), {
1102
+ headers,
1103
+ redirect: 'manual',
1104
+ signal: AbortSignal.timeout(timeoutMs),
1105
+ });
1106
+ hops += 1;
1107
+ }
1108
+ if (!res.ok)
1109
+ return { ok: false, status: res.status, error: `HTTP ${res.status}` };
1110
+ const bytes = await readCapped(res, cap);
1111
+ if (!bytes)
1112
+ return { ok: false, error: `the answer exceeds the ${Math.round(cap / 1024)} KiB cap` };
1113
+ return { ok: true, value: bytes };
1114
+ }
1115
+ catch (err) {
1116
+ return { ok: false, error: err instanceof Error ? err.message : String(err) };
1117
+ }
1118
+ }
1119
+ const PLUGIN_SOURCES_FILE = 'sources.json';
1120
+ export function pluginSourcesPath() {
1121
+ return path.join(pluginsRoot(), PLUGIN_SOURCES_FILE);
1122
+ }
1123
+ /** Every recorded source, keyed by plugin id. A corrupt or absent file degrades
1124
+ * to empty (an installed plugin then simply reads as unmonitored) instead of
1125
+ * failing. */
1126
+ export function readPluginSources() {
1127
+ try {
1128
+ const raw = JSON.parse(fs.readFileSync(pluginSourcesPath(), 'utf8'));
1129
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
1130
+ return {};
1131
+ return raw;
1132
+ }
1133
+ catch {
1134
+ return {};
1135
+ }
1136
+ }
1137
+ /** Record (or refresh) one plugin's provenance. Best effort: a failed write
1138
+ * must never fail the install that just succeeded. */
1139
+ export function recordPluginSource(id, record) {
1140
+ try {
1141
+ const all = readPluginSources();
1142
+ all[id] = record;
1143
+ fs.mkdirSync(pluginsRoot(), { recursive: true });
1144
+ safeWriteJson(pluginSourcesPath(), all);
1145
+ }
1146
+ catch {
1147
+ // Provenance is an optimisation for the updates panel, not correctness: a
1148
+ // market row still matches an installed id by its manifest id without it.
1149
+ }
1150
+ }
1151
+ /** Forget a plugin's provenance — an uninstall leaves nothing behind. */
1152
+ export function forgetPluginSource(id) {
1153
+ try {
1154
+ const all = readPluginSources();
1155
+ if (!(id in all))
1156
+ return;
1157
+ delete all[id];
1158
+ if (Object.keys(all).length === 0) {
1159
+ fs.rmSync(pluginSourcesPath(), { force: true });
1160
+ return;
1161
+ }
1162
+ safeWriteJson(pluginSourcesPath(), all);
1163
+ }
1164
+ catch {
1165
+ // same best-effort rule as `recordPluginSource`.
1166
+ }
1167
+ }
1168
+ /**
1169
+ * The background pull (ADR-0037 §12).
1170
+ *
1171
+ * The lazy read path already keeps the official registry fresh, but "lazy" means
1172
+ * a gateway can sit idle for a week and serve nothing new to a console that never
1173
+ * opens the market page — while the update badge, an upgrade, and an install all
1174
+ * read the same row set. One process-level timer closes that gap.
1175
+ *
1176
+ * It is armed only while the operator has NOT opted out (`registrySync`), so a
1177
+ * gateway told to phone nowhere opens no connection and arms no timer.
1178
+ * `unref()`s so it can never hold the process open, and calls the SAME
1179
+ * `syncRemoteRegistry` the read path calls — so a tick, a Refresh and a boot read
1180
+ * are one operation, one ETag, one in-flight guard.
1181
+ */
1182
+ export class RegistrySyncScheduler {
1183
+ tickIntervalMs;
1184
+ timer = null;
1185
+ constructor(tickIntervalMs = DEFAULT_REGISTRY_SYNC_INTERVAL_MS) {
1186
+ this.tickIntervalMs = tickIntervalMs;
1187
+ }
1188
+ /** Start the loop; a no-op while the official pull is opted out. */
1189
+ start() {
1190
+ this.reconcile();
1191
+ }
1192
+ /** Arm or disarm to match the CURRENT setting. Idempotent; call it after the
1193
+ * operator flips the switch so a running gateway reacts without a restart. */
1194
+ reconcile() {
1195
+ const configured = readMarketSettings().registrySync;
1196
+ if (configured && !this.timer) {
1197
+ this.timer = setInterval(() => {
1198
+ // Swallowed on purpose: a failed pull keeps the local file, and
1199
+ // `syncRemoteRegistry` records the reason for the console.
1200
+ void syncRemoteRegistry();
1201
+ }, this.tickIntervalMs);
1202
+ this.timer.unref?.();
1203
+ }
1204
+ else if (!configured && this.timer) {
1205
+ clearInterval(this.timer);
1206
+ this.timer = null;
1207
+ }
1208
+ }
1209
+ stop() {
1210
+ if (this.timer)
1211
+ clearInterval(this.timer);
1212
+ this.timer = null;
1213
+ }
1214
+ }
1215
+ let registrySyncScheduler = null;
1216
+ /** The process-wide scheduler (one timer per gateway, started at boot). */
1217
+ export function startRegistrySyncScheduler() {
1218
+ if (!registrySyncScheduler)
1219
+ registrySyncScheduler = new RegistrySyncScheduler();
1220
+ registrySyncScheduler.start();
1221
+ return registrySyncScheduler;
1222
+ }
1223
+ function cacheDir() {
1224
+ return path.join(pluginsRoot(), 'market-cache');
1225
+ }
1226
+ function cacheKey(entry) {
1227
+ const id = `${entry.repo}${entry.subdir ? `@${entry.subdir}` : ''}${entry.ref ? `#${entry.ref}` : ''}`;
1228
+ return id.replace(/[^A-Za-z0-9_.-]+/g, '__');
1229
+ }
1230
+ function readCachedRow(entry) {
1231
+ try {
1232
+ const raw = JSON.parse(fs.readFileSync(path.join(cacheDir(), `${cacheKey(entry)}.json`), 'utf8'));
1233
+ if (!raw || typeof raw.fetchedAt !== 'number' || !raw.row)
1234
+ return undefined;
1235
+ // A row written by an OLDER rule states an answer the current rule would not
1236
+ // produce. Treating it as a miss costs one re-read; serving it would keep a
1237
+ // wrong method on the card until the TTL ran out.
1238
+ if (raw.ruleVersion !== CACHE_RULE_VERSION)
1239
+ return undefined;
1240
+ return raw;
1241
+ }
1242
+ catch {
1243
+ return undefined;
1244
+ }
1245
+ }
1246
+ function writeCachedRow(entry, cached) {
1247
+ try {
1248
+ safeWriteJson(path.join(cacheDir(), `${cacheKey(entry)}.json`), { ...cached, ruleVersion: CACHE_RULE_VERSION });
1249
+ }
1250
+ catch {
1251
+ // A cache write failure must never fail the read: the console still gets a
1252
+ // fresh row, it just does not survive the next restart.
1253
+ }
1254
+ }
1255
+ /** The cached logo of one normalized entry, with its MIME. */
1256
+ function cachedLogo(entry) {
1257
+ const cached = readCachedRow(entry);
1258
+ if (!cached?.logoFile)
1259
+ return undefined;
1260
+ const mime = logoMimeFor(cached.logoFile);
1261
+ if (!mime)
1262
+ return undefined;
1263
+ try {
1264
+ return { bytes: fs.readFileSync(path.join(cacheDir(), cached.logoFile)), mime };
1265
+ }
1266
+ catch {
1267
+ return undefined;
1268
+ }
1269
+ }
1270
+ /** The cached logo for a row key (`<repo>@<subdir>`), as the logo route asks.
1271
+ * Cache keys are the repository identity, not the install METHOD, so the method
1272
+ * is irrelevant here — `release` is the neutral filler. */
1273
+ export function cachedLogoForKey(key) {
1274
+ const at = key.indexOf('@');
1275
+ const repo = normalizeRepo(at >= 0 ? key.slice(0, at) : key);
1276
+ if (!repo)
1277
+ return undefined;
1278
+ const subdir = at >= 0 ? key.slice(at + 1) : undefined;
1279
+ return cachedLogo({ repo, method: DEFAULT_INSTALL_METHOD, ...(subdir ? { subdir } : {}) });
1280
+ }
1281
+ /**
1282
+ * Resolve what this repository publishes for installation.
1283
+ *
1284
+ * A release asset is the distribution channel a plugin repository controls
1285
+ * (it survives a source refactor and needs no build step on the gateway), and a
1286
+ * committed zip is the low-ceremony alternative. Both are keyed on the manifest
1287
+ * id, so a repository holding several plugins publishes one zip per id rather
1288
+ * than an ambiguous "the zip".
1289
+ *
1290
+ * THE VERSION REPORTED HERE IS THE ONE THAT WOULD ACTUALLY BE INSTALLED, not
1291
+ * whatever the repository tip happens to say. The two can disagree — a
1292
+ * repository whose `main` has moved to 0.9.0 while its newest RELEASE is still
1293
+ * the 0.8.0 package — and reporting the tip would offer an "update" that
1294
+ * installs 0.8.0 again (an endless prompt). For a release asset the tag is the
1295
+ * version (`v0.8.0` → `0.8.0`); a tag that carries no version falls back to the
1296
+ * manifest of the ref the asset was built from, then to the default branch.
1297
+ */
1298
+ async function resolvePackage(entry, manifest, transport, defaultBranch, token) {
1299
+ // `code` publishes nothing: the bytes are BUILT at install time from the
1300
+ // repository source, so there is no URL to hand the card and no download to
1301
+ // pre-resolve. The card says so instead of pretending a release exists.
1302
+ //
1303
+ // `auto` (a SCANNED entry) skips this branch on purpose: nobody declared how
1304
+ // it installs, so try the published package FIRST and fall through to the
1305
+ // `code` sentence only when there is none. That keeps one repository's install
1306
+ // identical whether a registry or a scan named it, and keeps git + bun off a
1307
+ // plugin that ships a ready-made zip.
1308
+ if (entry.method === 'code') {
1309
+ const sub = entry.subdir ? `/${entry.subdir}` : '';
1310
+ return {
1311
+ error: `installs from SOURCE (method: 'code') — ${entry.repo}${sub} is cloned at ${entry.ref ?? defaultBranch ?? 'its default branch'} and built with git + bun on this machine; nothing is downloaded`,
1312
+ };
1313
+ }
1314
+ const wanted = `${manifest.id}.zip`;
1315
+ const release = await fetchJson(transport, `https://api.github.com/repos/${entry.repo}/releases/latest`, REPO_META_TIMEOUT_MS, token);
1316
+ if (release.ok) {
1317
+ const assets = (release.value.assets ?? []).filter((a) => typeof a.browser_download_url === 'string');
1318
+ const picked = assets.find((a) => a.name?.toLowerCase() === wanted)
1319
+ ?? assets.find((a) => a.name?.toLowerCase().endsWith('.zip'));
1320
+ if (picked?.browser_download_url) {
1321
+ const tag = typeof release.value.tag_name === 'string' ? release.value.tag_name : undefined;
1322
+ const tagged = tag ? versionFromTag(tag) : undefined;
1323
+ // A version-shaped tag IS the truth: it names the tree the asset was
1324
+ // built from. Anything else (a rolling `latest` tag, a codename) falls
1325
+ // back to what the source at that ref declares.
1326
+ const version = tagged ?? (await versionAtRef(entry, transport, tag, token)) ?? manifest.version;
1327
+ return { pkg: { url: picked.browser_download_url, version, kind: 'release' } };
1328
+ }
1329
+ }
1330
+ const ref = effectiveRef(entry, defaultBranch);
1331
+ const repoZipPath = entry.subdir ? `${entry.subdir}/${wanted}` : wanted;
1332
+ const committed = `https://github.com/${entry.repo}/raw/${ref}/${repoZipPath}`;
1333
+ const probe = await fetchBytes(transport, committed, 1024, REPO_META_TIMEOUT_MS, token);
1334
+ // A committed zip travels with its ref, so the manifest read from that ref IS
1335
+ // the version in the zip.
1336
+ if (probe.ok)
1337
+ return { pkg: { url: committed, version: manifest.version, kind: 'repo' } };
1338
+ // Nothing published: an `auto` row falls back to a source build, which is the
1339
+ // honest answer for a repository that ships only a tree (and matches what a
1340
+ // registry entry would have had to declare as `method: 'code'`).
1341
+ if (entry.method === 'auto') {
1342
+ const sub = entry.subdir ? `/${entry.subdir}` : '';
1343
+ return {
1344
+ error: `installs from SOURCE — ${entry.repo}${sub} publishes no release zip and commits none, so it is cloned at ${entry.ref ?? defaultBranch ?? 'its default branch'} and built with git + bun on this machine`,
1345
+ };
1346
+ }
1347
+ return {
1348
+ error: `no installable package: ${entry.repo} publishes no release asset named ${wanted} and commits no ${wanted} — ` +
1349
+ 'the plugin author must attach the packaged zip to a release (or commit it), or install the .zip by hand',
1350
+ };
1351
+ }
1352
+ /** The version a release TAG states (`v0.8.0` / `0.8.0`), or undefined for a
1353
+ * tag that is not version-shaped (`latest`, `nightly`, a codename). */
1354
+ function versionFromTag(tag) {
1355
+ const trimmed = tag.trim().replace(/^v/i, '');
1356
+ return /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(trimmed) ? trimmed : undefined;
1357
+ }
1358
+ /** The `plugin.json` version at ONE ref, or undefined when it cannot be read. */
1359
+ async function versionAtRef(entry, transport, ref, token) {
1360
+ const bytes = await fetchRepoFile(entry, 'plugin.json', transport, ref, undefined, token);
1361
+ if (!bytes.ok)
1362
+ return undefined;
1363
+ try {
1364
+ const parsed = JSON.parse(new TextDecoder().decode(bytes.value));
1365
+ return typeof parsed.version === 'string' && parsed.version.trim() ? parsed.version.trim() : undefined;
1366
+ }
1367
+ catch {
1368
+ return undefined;
1369
+ }
1370
+ }
1371
+ /**
1372
+ * The 404/403 tail for a repository the market could not read.
1373
+ *
1374
+ * GitHub does not distinguish "private and you cannot see it" from "does not
1375
+ * exist" — both answer 404 to an anonymous request, deliberately. So the hint
1376
+ * names BOTH possibilities and, crucially, says what to do when a token is
1377
+ * already configured: a token that cannot read the repository is a SCOPE problem
1378
+ * (fine-grained tokens list repositories explicitly), not a missing token.
1379
+ */
1380
+ function privateRepoHint(key) {
1381
+ const token = tokenForRowKey(key);
1382
+ if (token === null) {
1383
+ return 'no such repository, or it is PRIVATE and this SOURCE carries no token — add one to the source, or use GITHUB_TOKEN for a registry entry';
1384
+ }
1385
+ if (token === undefined) {
1386
+ return 'no such repository, or it is PRIVATE and no GITHUB_TOKEN is configured — a registry repository has no source of its own, so it reads with the environment token';
1387
+ }
1388
+ return 'no such repository, or it is private and the source token cannot read it — a fine-grained token must list this repository explicitly';
1389
+ }
1390
+ /** Read one repository into a market row. Never throws. `staleFallback` is true
1391
+ * when an upstream read failed and the LAST GOOD cached row answered instead —
1392
+ * the caller reports it as `stale`, which is a different sentence from "the
1393
+ * plugin is gone". */
1394
+ async function fetchRow(entry, installed, fetchedAt, transport, sources) {
1395
+ const base = {
1396
+ key: `${entry.repo}${entry.subdir ? `@${entry.subdir}` : ''}`,
1397
+ repo: entry.repo,
1398
+ ...(entry.ref ? { ref: entry.ref } : {}),
1399
+ ...(entry.subdir ? { subdir: entry.subdir } : {}),
1400
+ url: `https://github.com/${entry.repo}${entry.subdir ? `/tree/${entry.ref ?? 'HEAD'}/${entry.subdir}` : ''}`,
1401
+ // The card states the CONCRETE method. An `auto` entry has no declared method,
1402
+ // so it reports what `resolvePackage` actually found below: a published asset
1403
+ // (`release`), a committed zip (`release`), or a source build (`code`).
1404
+ method: entry.method === 'auto' ? 'release' : entry.method,
1405
+ ...(entry.origin ? { origin: entry.origin } : {}),
1406
+ ...(entry.originLabel ? { originLabel: entry.originLabel } : {}),
1407
+ stars: null,
1408
+ fetchedAt,
1409
+ };
1410
+ // Every read for THIS row authenticates as its own scope: a scanned row uses
1411
+ // the source's token (or none at all), a registry row uses the env tier. No
1412
+ // global credential exists to fall back to.
1413
+ const token = tokenForRowKey(base.key);
1414
+ // Repository metadata is ENRICHMENT: stars, the last-push date and the
1415
+ // default branch a file read is pinned to. A repository whose API read fails
1416
+ // is still a valid card.
1417
+ const meta = await fetchJson(transport, `https://api.github.com/repos/${entry.repo}`, REPO_META_TIMEOUT_MS, token);
1418
+ let defaultBranch;
1419
+ if (meta.ok) {
1420
+ if (typeof meta.value.stargazers_count === 'number')
1421
+ base.stars = meta.value.stargazers_count;
1422
+ if (typeof meta.value.pushed_at === 'string')
1423
+ base.updatedAt = meta.value.pushed_at;
1424
+ if (typeof meta.value.default_branch === 'string')
1425
+ defaultBranch = meta.value.default_branch;
1426
+ }
1427
+ // The manifest describes the ref the entry names. `defaultBranch` is not
1428
+ // needed for this read: omitting `ref` lets GitHub answer its own default,
1429
+ // and a pinned entry must NOT be described by `main`'s file.
1430
+ const manifestBytes = await fetchRepoFile(entry, 'plugin.json', transport, entry.ref, undefined, token);
1431
+ if (!manifestBytes.ok) {
1432
+ const cached = readCachedRow(entry);
1433
+ if (cached) {
1434
+ return {
1435
+ row: { ...cached.row, fetchedAt: cached.fetchedAt },
1436
+ ...(cached.logoFile ? { logoFile: cached.logoFile } : {}),
1437
+ staleFallback: true,
1438
+ };
1439
+ }
1440
+ return {
1441
+ row: {
1442
+ ...base,
1443
+ error: manifestBytes.status === 404 || manifestBytes.status === 403
1444
+ ? // GitHub answers 404 (not 403) for a PRIVATE repository the token
1445
+ // cannot see, so the two are one sentence with an actionable tail:
1446
+ // without this, a customer's mis-scoped token reads as "this plugin
1447
+ // does not exist" and there is nothing to fix.
1448
+ `cannot read ${entry.repo} — ${privateRepoHint(base.key)}`
1449
+ : `cannot read plugin.json: ${manifestBytes.error}`,
1450
+ },
1451
+ };
1452
+ }
1453
+ let manifest;
1454
+ try {
1455
+ const parsed = JSON.parse(new TextDecoder().decode(manifestBytes.value));
1456
+ // The LOADER's validator, so a marketplace card can never offer a package
1457
+ // this host would refuse to load (or the packager would refuse to build).
1458
+ validatePluginManifest(parsed, 'plugin.json');
1459
+ manifest = parsed;
1460
+ }
1461
+ catch (err) {
1462
+ return {
1463
+ row: { ...base, error: `invalid plugin.json: ${err instanceof Error ? err.message : String(err)}` },
1464
+ };
1465
+ }
1466
+ const row = {
1467
+ ...base,
1468
+ id: manifest.id,
1469
+ name: manifest.name,
1470
+ version: manifest.version,
1471
+ apiVersion: manifest.apiVersion,
1472
+ ...(manifest.description ? { description: manifest.description } : {}),
1473
+ ...(manifest.changelog?.length ? { changelog: manifest.changelog } : {}),
1474
+ ...(manifest.presets?.length ? { presets: manifest.presets } : {}),
1475
+ };
1476
+ const parts = manifest.parts?.length
1477
+ ? manifest.parts
1478
+ : manifest.type
1479
+ ? [{ type: manifest.type, wires: manifest.wires, hosts: manifest.hosts }]
1480
+ : [];
1481
+ if (parts.length > 0)
1482
+ row.types = parts.map((p) => p.type);
1483
+ const wires = parts.flatMap((p) => p.wires ?? []);
1484
+ if (wires.length > 0)
1485
+ row.wires = [...new Set(wires)];
1486
+ const hosts = parts.flatMap((p) => p.hosts ?? []);
1487
+ if (hosts.length > 0)
1488
+ row.hosts = [...new Set(hosts)];
1489
+ row.compatible = pluginEngineCompatibility(manifest).compatible;
1490
+ // Logo: cached beside the row and served by the market's own route, so a card
1491
+ // grid never re-fetches a brand mark from GitHub.
1492
+ let logoFile;
1493
+ if (typeof manifest.logo === 'string' && manifest.logo.trim()) {
1494
+ const rel = manifest.logo.trim().replace(/^\.\//, '');
1495
+ const mime = logoMimeFor(rel);
1496
+ const safeRel = !rel.startsWith('/')
1497
+ && !/^[A-Za-z]:/.test(rel)
1498
+ && !rel.split('/').some((s) => s === '..' || s === '.');
1499
+ if (mime && safeRel) {
1500
+ const fetched = await fetchRepoFile(entry, rel, transport, entry.ref, 1024 * 1024, token);
1501
+ if (fetched.ok) {
1502
+ logoFile = `${cacheKey(entry)}.logo${path.extname(rel).toLowerCase()}`;
1503
+ try {
1504
+ fs.mkdirSync(cacheDir(), { recursive: true });
1505
+ fs.writeFileSync(path.join(cacheDir(), logoFile), fetched.value);
1506
+ row.logo = true;
1507
+ }
1508
+ catch {
1509
+ logoFile = undefined;
1510
+ }
1511
+ }
1512
+ }
1513
+ }
1514
+ if (!logoFile) {
1515
+ // A failed re-fetch reuses the previous mark rather than dropping it.
1516
+ const cached = readCachedRow(entry);
1517
+ if (cached?.logoFile && fs.existsSync(path.join(cacheDir(), cached.logoFile))) {
1518
+ logoFile = cached.logoFile;
1519
+ row.logo = true;
1520
+ }
1521
+ }
1522
+ const pkg = await resolvePackage(entry, manifest, transport, defaultBranch, token);
1523
+ if (pkg.pkg)
1524
+ row.package = pkg.pkg;
1525
+ else if (pkg.error)
1526
+ row.packageError = pkg.error;
1527
+ // The card's version is what an install WOULD LAND, so a `release` row states
1528
+ // the release asset's version rather than the repository tip's (see
1529
+ // `resolvePackage`). `code` has no pre-resolved package: its latest IS the ref
1530
+ // the manifest was read from, which `row.version` already carries.
1531
+ if (pkg.pkg?.version)
1532
+ row.version = pkg.pkg.version;
1533
+ // A row installs from SOURCE when it declared `code`, or when it is `auto` and
1534
+ // nothing was published — `resolvePackage` leaves `package` unset in both
1535
+ // cases. That is the ONE predicate the card and the install verb share, so a
1536
+ // scanned plugin that ships a zip goes down the release arithmetic and only a
1537
+ // tree-only repository is treated as a build.
1538
+ const buildsFromSource = entry.method === 'code' || (entry.method === 'auto' && !pkg.pkg);
1539
+ if (buildsFromSource) {
1540
+ if (entry.method === 'auto')
1541
+ row.method = 'code';
1542
+ const { sourceBuildReady, isVersionRef } = await import('./market-source.js');
1543
+ row.buildReady = sourceBuildReady();
1544
+ row.codeBranch = entry.ref ?? defaultBranch ?? 'main';
1545
+ // A PINNED `code` entry describes one fixed release, but its upgrade follows
1546
+ // the default branch — read here, once, so the monitor compares against what
1547
+ // an upgrade would actually land instead of the pin it already has.
1548
+ if (entry.ref && row.codeBranch !== defaultBranch) {
1549
+ const tip = defaultBranch ? await versionAtRef(entry, transport, defaultBranch) : undefined;
1550
+ if (tip)
1551
+ row.upgradeVersion = tip;
1552
+ }
1553
+ // Tags whose name is a version (`v0.8.0` / `0.8.0`). A repository that
1554
+ // never tagged anything answers an empty list, and the card then offers only
1555
+ // "latest source" — which is the honest set of choices it actually has.
1556
+ const tags = await fetchJson(transport, `https://api.github.com/repos/${entry.repo}/tags?per_page=100`, REPO_META_TIMEOUT_MS, token);
1557
+ if (tags.ok && Array.isArray(tags.value)) {
1558
+ row.codeTags = tags.value
1559
+ .map((tag) => (typeof tag.name === 'string' ? tag.name.trim() : ''))
1560
+ .filter((name) => isVersionRef(name))
1561
+ .sort((a, b) => compareVersions(b, a));
1562
+ }
1563
+ }
1564
+ const state = installedState(row, installed, sources);
1565
+ if (state)
1566
+ row.installed = state;
1567
+ return { row, ...(logoFile ? { logoFile } : {}) };
1568
+ }
1569
+ /**
1570
+ * The installed package a market row describes, or undefined.
1571
+ *
1572
+ * TWO identities, because a plugin has two:
1573
+ *
1574
+ * - the SOURCE LEDGER (`sources.json`) — written at market install time and
1575
+ * keyed by the repository. It is the only evidence that a repository is the
1576
+ * ORIGIN of an installed plugin, and it survives a dev-tree install (which
1577
+ * has no packaged zip to compare bytes against);
1578
+ * - the MANIFEST ID — the plugin's own identity. It is the fallback for an
1579
+ * install that predates the ledger, and the reason a package the operator
1580
+ * uploaded by hand still reads as installed on the matching card.
1581
+ *
1582
+ * Repository wins when both answer: the ledger says where the bytes came from,
1583
+ * while an id match only says the two are the same plugin.
1584
+ */
1585
+ function installedFor(repo, installed, sources, manifestId) {
1586
+ for (const [id, record] of Object.entries(sources)) {
1587
+ if (record.repo !== repo)
1588
+ continue;
1589
+ const view = installed.find((candidate) => candidate.id === id);
1590
+ if (view)
1591
+ return view;
1592
+ }
1593
+ return manifestId ? installed.find((candidate) => candidate.id === manifestId) : undefined;
1594
+ }
1595
+ /** Compose the "is it installed, and is there an update" half of a row from the
1596
+ * LIVE plugin list (never cached: a plugin installed a minute ago must show as
1597
+ * installed on a card whose manifest answer is nine minutes old). */
1598
+ function installedState(row, installed, sources) {
1599
+ if (!row.version)
1600
+ return undefined;
1601
+ const existing = installedFor(row.repo, installed, sources, row.id);
1602
+ if (!existing)
1603
+ return undefined;
1604
+ return {
1605
+ version: existing.version,
1606
+ loaded: existing.loaded,
1607
+ disabled: existing.disabled === true,
1608
+ incompatible: existing.incompatible === true,
1609
+ updateAvailable: compareVersions(row.version, existing.version) > 0,
1610
+ };
1611
+ }
1612
+ /**
1613
+ * The whole market, from cache when fresh.
1614
+ *
1615
+ * A row is cached for `MARKET_CACHE_TTL_MS`; a FORCED refresh (the console's
1616
+ * Refresh verb) re-reads every row. A row whose upstream read failed falls back
1617
+ * to its last cached copy and reports `stale`, which is the difference between
1618
+ * "this plugin is gone" and "this gateway could not reach GitHub".
1619
+ */
1620
+ export async function loadMarket(deps = {}) {
1621
+ const settings = readMarketSettings();
1622
+ // SWR over the OFFICIAL registry (ADR-0037 §12), before anything reads the
1623
+ // file: a due pull replaces `<pluginsRoot>/registry.json` and the read below
1624
+ // sees it as if it had been authored by hand.
1625
+ //
1626
+ // AWAITED only when the read would otherwise have nothing: a first install
1627
+ // (no local snapshot yet) or an explicit `refresh` (the console's Refresh
1628
+ // verb, which promises a re-read). Every other due pull runs BEHIND the read —
1629
+ // a gateway that cannot reach GitHub must not make the market page wait for
1630
+ // the timeout on every visit, and the snapshot already on disk is exactly what
1631
+ // SWR means to serve.
1632
+ if (settings.registrySync) {
1633
+ const bootstrap = deps.refresh === true || !fs.existsSync(registryFilePath());
1634
+ const pull = syncRemoteRegistry({ ...deps, force: deps.refresh === true });
1635
+ if (bootstrap)
1636
+ await pull;
1637
+ // A background pull still carries a failure to `registry-sync.json`, which
1638
+ // the read below picks up. Nothing here rethrows: a pull that fails is not a
1639
+ // market failure.
1640
+ else
1641
+ void pull;
1642
+ }
1643
+ const registrySync = settings.registrySync
1644
+ ? { ...registrySyncState(), url: OFFICIAL_REGISTRY_URL }
1645
+ : undefined;
1646
+ // A `proxy` setting with no endpoint refuses the whole read with its own
1647
+ // sentence, instead of showing an empty market that reads as "no plugins".
1648
+ let transport;
1649
+ try {
1650
+ transport = marketTransport(settings, deps.fetchImpl);
1651
+ }
1652
+ catch (err) {
1653
+ return {
1654
+ egress: settings.egress,
1655
+ problem: { code: 'egress-unavailable', message: err instanceof Error ? err.message : String(err), tried: [] },
1656
+ rows: [],
1657
+ stale: false,
1658
+ ...(registrySync ? { registrySync } : {}),
1659
+ };
1660
+ }
1661
+ const registry = readRegistry();
1662
+ // THE SCANNED HALF IS INDEPENDENT OF THE OFFICIAL ONE (ADR-0037 §9): a
1663
+ // missing, malformed or empty registry file must not erase cards a source
1664
+ // scan produced — those cards were read from repositories that have nothing
1665
+ // to do with the curated list. The problem stays REPORTED beside the grid;
1666
+ // only an empty UNION leaves the page with nothing but the explanation.
1667
+ const scannedEntries = sourceEntriesOf(readSourceIndex());
1668
+ if ('problem' in registry && scannedEntries.length === 0) {
1669
+ return {
1670
+ egress: settings.egress,
1671
+ problem: registry.problem,
1672
+ rows: [],
1673
+ stale: false,
1674
+ ...(registrySync ? { registrySync } : {}),
1675
+ };
1676
+ }
1677
+ // THE MARKET IS TWO REGISTRIES MERGED (ADR-0037 §9): the committed one (whose
1678
+ // rows are OFFICIAL) plus the index a scan produced (whose rows are SOURCES).
1679
+ //
1680
+ // A repository present in BOTH appears ONCE and reads as `official` — it is in
1681
+ // the curated list, which is the stronger fact. The scanned row still exists in
1682
+ // the index; it simply does not become a second card.
1683
+ const officialEntries = 'problem' in registry ? [] : registry.entries.map((entry) => ({ ...entry, origin: 'official' }));
1684
+ const officialKeys = new Set('problem' in registry
1685
+ ? []
1686
+ : registry.entries.map((entry) => `${entry.repo}${entry.subdir ? `@${entry.subdir}` : ''}`));
1687
+ const mergedEntries = [
1688
+ ...officialEntries,
1689
+ // ...and the ones ONLY a scan found.
1690
+ ...scannedEntries.filter((entry) => !officialKeys.has(`${entry.repo}${entry.subdir ? `@${entry.subdir}` : ''}`)),
1691
+ ];
1692
+ const installed = listInstalledPlugins();
1693
+ const sources = readPluginSources();
1694
+ const now = Date.now();
1695
+ let stale = false;
1696
+ // A cached row must NOT pin the state it was cached with: the install half is
1697
+ // composed live on every read, or a plugin installed a minute ago would keep
1698
+ // reading as "not installed" until the row's cache expired.
1699
+ const withLiveState = (row) => {
1700
+ const { installed: _cached, ...rest } = row;
1701
+ const live = installedState(rest, installed, sources);
1702
+ return live ? { ...rest, installed: live } : rest;
1703
+ };
1704
+ // PROVENANCE is a property of the ENTRY, not of the manifest answer it was read
1705
+ // with — so it is composed live on every read for the same reason the install
1706
+ // state is. A row cached thirty minutes ago carries the `originLabel` of the
1707
+ // scan that produced it, and serving that verbatim kept a renamed (or newly
1708
+ // labelled) source's OLD name on every card until the TTL ran out, because a
1709
+ // cache hit never reaches `fetchRow` and therefore never sees the new entry.
1710
+ // The entry is the current truth: it is rebuilt from `market.json` and
1711
+ // `source-index.json` on this very read.
1712
+ const withEntryProvenance = (row, entry) => {
1713
+ const { origin: _origin, originLabel: _originLabel, ...rest } = row;
1714
+ return {
1715
+ ...rest,
1716
+ ...(entry.origin ? { origin: entry.origin } : {}),
1717
+ ...(entry.originLabel ? { originLabel: entry.originLabel } : {}),
1718
+ };
1719
+ };
1720
+ const rows = await Promise.all(mergedEntries.map(async (entry) => {
1721
+ const cached = readCachedRow(entry);
1722
+ // An `auto` entry is cached like any other: its resolved method rides in
1723
+ // the row (`resolvePackage` rewrites `row.method` to a CONCRETE value), and
1724
+ // `CACHE_RULE_VERSION` — not a per-read bypass — is what invalidates a row
1725
+ // produced by an older rule. The earlier bypass made every read of a
1726
+ // scanned plugin a full GitHub re-read (up to 5 calls per card), which is
1727
+ // a far worse trade than a rule-version stamp.
1728
+ if (!deps.refresh && cached && now - cached.fetchedAt < MARKET_CACHE_TTL_MS) {
1729
+ return { ...withLiveState(withEntryProvenance(cached.row, entry)), fetchedAt: cached.fetchedAt };
1730
+ }
1731
+ const { row, logoFile, staleFallback } = await fetchRow(entry, installed, now, transport, sources);
1732
+ if (staleFallback) {
1733
+ stale = true;
1734
+ // The live install state still applies: a row served from the last good
1735
+ // cache must read as installed if the operator installed it since — and
1736
+ // its provenance must read as the entry says it is, for the same reason.
1737
+ return withLiveState(withEntryProvenance(row, entry));
1738
+ }
1739
+ if (!row.error)
1740
+ writeCachedRow(entry, { fetchedAt: now, row, ...(logoFile ? { logoFile } : {}) });
1741
+ return row;
1742
+ }));
1743
+ // SAME-ID COLLISION (ADR-0037 §12). Two repositories can declare one plugin
1744
+ // `id`, and the id is the INSTALL identity — so the second one to land would
1745
+ // silently replace the first, with its provenance rewritten. The market is the
1746
+ // only place both are visible at once, so it is where the collision is marked:
1747
+ // every row that shares its id with another row names the other repository and
1748
+ // exposes `conflict`, which the console renders as a disabled Install.
1749
+ const byId = new Map();
1750
+ for (const row of rows) {
1751
+ if (!row.id)
1752
+ continue;
1753
+ const bucket = byId.get(row.id);
1754
+ if (bucket)
1755
+ bucket.push(row);
1756
+ else
1757
+ byId.set(row.id, [row]);
1758
+ }
1759
+ for (const row of rows) {
1760
+ if (!row.id)
1761
+ continue;
1762
+ const peers = byId.get(row.id);
1763
+ if (!peers || peers.length < 2)
1764
+ continue;
1765
+ row.conflict = { id: row.id, repos: peers.map((peer) => peer.repo) };
1766
+ }
1767
+ return {
1768
+ egress: settings.egress,
1769
+ ...('source' in registry ? { registry: registry.source } : {}),
1770
+ ...('problem' in registry ? { problem: registry.problem } : {}),
1771
+ rows,
1772
+ fetchedAt: now,
1773
+ stale,
1774
+ ...(registrySync ? { registrySync } : {}),
1775
+ };
1776
+ }
1777
+ /** ONE row by repository (the install verb's resolver). */
1778
+ export async function findMarketRow(repo, deps = {}) {
1779
+ const normalized = normalizeRepo(repo);
1780
+ if (!normalized)
1781
+ return undefined;
1782
+ const snapshot = await loadMarket(deps);
1783
+ return snapshot.rows.find((row) => row.repo === normalized);
1784
+ }
1785
+ /** ONE row's installable bytes, by either method — what the install verb takes.
1786
+ *
1787
+ * `release` downloads the published zip. `code` builds one from the repository
1788
+ * source (ADR-0037 §4a) and answers the version the built manifest declares,
1789
+ * so the console can say what actually landed instead of what the branch held
1790
+ * ten minutes ago. Both answers feed the SAME `installPluginBytes` pipeline.
1791
+ *
1792
+ * `upgrade` is the difference between "install what this card describes" and
1793
+ * "move this plugin to the repository's tip": a `code` entry pinned in the
1794
+ * registry rebuilds its PIN for an install, but follows the default branch for
1795
+ * an upgrade (see the `buildRef` note below). */
1796
+ export async function prepareMarketPackage(row, deps = {}) {
1797
+ if (row.method === 'code') {
1798
+ // Looked up lazily so a `release`-only host never loads the build module
1799
+ // (and its `bun`/`git` assumptions) at all.
1800
+ const { buildPackageFromSource, gatewayBackendDir } = await import('./market-source.js');
1801
+ const settings = readMarketSettings();
1802
+ const defaultBranch = await resolveDefaultBranch(row, deps);
1803
+ // AN UPGRADE MOVES TO THE REPOSITORY'S TIP, not to the ref the registry
1804
+ // happens to name. A `code` entry pinned to `ref: 'v0.8.0'` describes a
1805
+ // FIXED release for browsing; an upgrade to that same pin would rebuild the
1806
+ // identical version forever. So the caller's explicit ref (the console's
1807
+ // version picker) wins, and with no ref the build follows the default
1808
+ // branch. The registry pin still decides which version the CARD describes.
1809
+ const buildRef = deps.ref ?? (deps.upgrade ? defaultBranch : row.ref);
1810
+ // The clone authenticates as the SAME scope that read the card, and leaves
1811
+ // on the SAME leg. A private source's token is the only credential any of
1812
+ // its reads has (ADR-0037 §8), and a `git` child is a process the market
1813
+ // does not otherwise reach — without this it dials anonymously and direct.
1814
+ const token = rowAuthToken(row.key, settings);
1815
+ let egressProxy;
1816
+ if (settings.egress === 'proxy') {
1817
+ // A refused endpoint is a refusal, not a silent direct build — unless the
1818
+ // clone runs on the test seam, where there is no proxy to resolve.
1819
+ try {
1820
+ egressProxy = marketEgressProxy(settings);
1821
+ }
1822
+ catch (err) {
1823
+ return { error: err instanceof Error ? err.message : String(err) };
1824
+ }
1825
+ }
1826
+ const built = await buildPackageFromSource(row.repo, {
1827
+ ...(buildRef ? { ref: buildRef } : {}),
1828
+ ...(row.subdir ? { subdir: row.subdir } : {}),
1829
+ ...(token ? { token } : {}),
1830
+ ...(egressProxy ? { egressProxy } : {}),
1831
+ // A source tree with no release has no "latest release" to name — its
1832
+ // default branch IS the latest version.
1833
+ defaultBranch,
1834
+ backendDir: gatewayBackendDir(),
1835
+ });
1836
+ if ('error' in built)
1837
+ return { error: built.error };
1838
+ return { bytes: built.zip, version: built.version };
1839
+ }
1840
+ if (!row.package)
1841
+ return { error: row.packageError ?? 'this repository publishes no installable package' };
1842
+ // The SAME leg the rows were read over: an install must not leave the machine
1843
+ // on a route the operator did not choose for this feature.
1844
+ let transport;
1845
+ try {
1846
+ transport = marketTransport(readMarketSettings(), deps.fetchImpl);
1847
+ }
1848
+ catch (err) {
1849
+ return { error: err instanceof Error ? err.message : String(err) };
1850
+ }
1851
+ // The package lives in the SOURCE's repository, so the download authenticates
1852
+ // as that source — a private source install would otherwise 404 at the last
1853
+ // step after the card read successfully.
1854
+ const fetched = await fetchBytes(transport, row.package.url, PLUGIN_PACKAGE_MAX_BYTES, 60_000, tokenForRowKey(row.key));
1855
+ if (!fetched.ok)
1856
+ return { error: `package download failed: ${fetched.error}` };
1857
+ if (fetched.value.byteLength > PLUGIN_PACKAGE_MAX_BYTES) {
1858
+ return { error: `package exceeds the ${Math.round(PLUGIN_PACKAGE_MAX_BYTES / 1024 / 1024)} MiB cap` };
1859
+ }
1860
+ return { bytes: fetched.value };
1861
+ }
1862
+ /** The default branch a `code` build pins to. Read through the SAME transport,
1863
+ * because a repository behind the egress proxy is behind it for the build too. */
1864
+ async function resolveDefaultBranch(row, deps) {
1865
+ try {
1866
+ const transport = marketTransport(readMarketSettings(), deps.fetchImpl);
1867
+ const meta = await fetchJson(transport, `https://api.github.com/repos/${row.repo}`, REPO_META_TIMEOUT_MS,
1868
+ // A private source's repository metadata needs the same scope its card did.
1869
+ tokenForRowKey(row.key));
1870
+ if (meta.ok && typeof meta.value.default_branch === 'string' && meta.value.default_branch) {
1871
+ return meta.value.default_branch;
1872
+ }
1873
+ }
1874
+ catch {
1875
+ // No transport / no answer: `main` is GitHub's own initial default and the
1876
+ // build's own error names the ref it tried, so a guess costs one clear
1877
+ // sentence rather than a card that cannot say anything.
1878
+ }
1879
+ return 'main';
1880
+ }
1881
+ /**
1882
+ * Build the index from what the configured SOURCES can see
1883
+ * (ADR-0037 §9).
1884
+ *
1885
+ * `GET /user/repos` returns REPOSITORY metadata — never file contents — so
1886
+ * "is this a plugin?" cannot be answered from the listing. Every candidate gets
1887
+ * one `plugin.json` read; that is the N+1 the caller must expect, and the reason
1888
+ * the result is an INDEX rather than something recomputed per page load.
1889
+ *
1890
+ * Failures are counted, never fatal: a repository that cannot be read (rate
1891
+ * limit, deleted, network) increments `skipped` and the run continues, because a
1892
+ * discovery that dies on one bad repository is worse than an index that reports
1893
+ * what it could see.
1894
+ */
1895
+ export async function discoverFromSources(deps = {}) {
1896
+ const settings = readMarketSettings();
1897
+ if (settings.sources.length === 0) {
1898
+ return { error: 'no source is configured — add owner, owner/repo or owner/pattern* under Plugin sources' };
1899
+ }
1900
+ let transport;
1901
+ try {
1902
+ transport = marketTransport(settings, deps.fetchImpl);
1903
+ }
1904
+ catch (err) {
1905
+ return { error: err instanceof Error ? err.message : String(err) };
1906
+ }
1907
+ const byRepo = new Map();
1908
+ const seen = new Set();
1909
+ const perSource = [];
1910
+ let skipped = 0;
1911
+ for (const source of settings.sources) {
1912
+ // A source names its OWN token. ABSENT = anonymous, which is the whole
1913
+ // point of making the token a field of the source: a public owner needs no
1914
+ // secret. `null` is passed so the helper does NOT fall back to the market's
1915
+ // primary token — inheriting it would make the scan depend on which other
1916
+ // source happened to be configured first.
1917
+ const token = source.token ?? null;
1918
+ const [owner, pattern] = source.target.split('/');
1919
+ const repos = [];
1920
+ let sourceError;
1921
+ if (!pattern || /[*?]/.test(pattern)) {
1922
+ // OWNER (or owner/pattern*): list the owner's repositories, then filter.
1923
+ // A literal owner/repo needs no listing at all — it is one known name, so
1924
+ // it costs one manifest read instead of a listing plus a read.
1925
+ //
1926
+ // WHICH ENDPOINT. An OWNER can be a user or an organization, and the two
1927
+ // endpoints are NOT interchangeable:
1928
+ //
1929
+ // GET /users/{user}/repos lists PUBLIC repositories only — its `type`
1930
+ // accepts all/owner/member and has NO private
1931
+ // (docs: "Lists public repositories").
1932
+ // GET /orgs/{org}/repos lists what the token can SEE, private
1933
+ // included when it is scoped to them.
1934
+ //
1935
+ // So an organization MUST be listed through `/orgs`, or a fine-grained
1936
+ // token scoped to private plugin repositories silently finds nothing but
1937
+ // the public ones and reports a "clean" scan. A USER keeps `/users`, which
1938
+ // is the correct endpoint for an account and honours the same token.
1939
+ const kind = await ownerKind(owner, transport, token);
1940
+ const listing = kind === 'org' ? 'orgs' : 'users';
1941
+ for (let page = 1; page <= 20; page += 1) {
1942
+ const res = await fetchJsonWithHeaders(transport, `https://api.github.com/${listing}/${owner}/repos?per_page=100&page=${page}&type=all`, marketAuthHeaders(token), REPO_META_TIMEOUT_MS);
1943
+ if (!res.ok) {
1944
+ if (page === 1) {
1945
+ sourceError =
1946
+ res.status === 404
1947
+ ? `'${owner}' not found, or the token cannot see it`
1948
+ : res.status === 401
1949
+ ? 'token rejected by GitHub (401) — expired or revoked'
1950
+ : `cannot list ${owner}: ${res.error}`;
1951
+ }
1952
+ break;
1953
+ }
1954
+ const batch = Array.isArray(res.value) ? res.value : [];
1955
+ if (batch.length === 0)
1956
+ break;
1957
+ for (const repo of batch) {
1958
+ const full = typeof repo.full_name === 'string' ? repo.full_name : '';
1959
+ if (full && sourceMatches(source.target, full))
1960
+ repos.push(full);
1961
+ }
1962
+ }
1963
+ }
1964
+ else {
1965
+ repos.push(source.target);
1966
+ }
1967
+ if (sourceError) {
1968
+ perSource.push({ target: source.target, ...(source.label ? { label: source.label } : {}), authenticated: Boolean(source.token), scanned: 0, found: 0, notPlugins: 0, error: sourceError });
1969
+ continue;
1970
+ }
1971
+ let found = 0;
1972
+ let notPlugins = 0;
1973
+ let unauthorized = 0;
1974
+ let forbidden = 0;
1975
+ const forbiddenRepos = [];
1976
+ const candidates = [];
1977
+ for (const full of repos) {
1978
+ if (!full.includes('/')) {
1979
+ skipped += 1;
1980
+ continue;
1981
+ }
1982
+ // Already claimed by an earlier source: no second manifest read.
1983
+ if (seen.has(full))
1984
+ continue;
1985
+ seen.add(full);
1986
+ candidates.push(full);
1987
+ }
1988
+ // CONCURRENCY: one manifest read per candidate is the whole cost of a sync.
1989
+ // Serially, an owner with 80 repositories took 40 s — long enough for the
1990
+ // console's request to give up while the backend was still working.
1991
+ const CONCURRENCY = 8;
1992
+ /** How many 403'd repositories are NAMED on the row. Enough to see the shape
1993
+ * of the problem without turning a 200-repository source into a wall. */
1994
+ const FORBIDDEN_LIST_LIMIT = 8;
1995
+ let cursor = 0;
1996
+ const worker = async () => {
1997
+ for (;;) {
1998
+ const index = cursor;
1999
+ cursor += 1;
2000
+ const full = candidates[index];
2001
+ if (!full)
2002
+ return;
2003
+ const manifest = await fetchRepoFile({ repo: full, method: 'release' }, 'plugin.json', transport, undefined, undefined, token);
2004
+ if (!manifest.ok) {
2005
+ // THREE different answers, and collapsing them lies:
2006
+ //
2007
+ // 404 — readable, simply not a plugin (no manifest at the root).
2008
+ // 401 — the token itself was rejected (expired / revoked).
2009
+ // 403 — the repository is VISIBLE in the listing but the token may not
2010
+ // read its contents. A fine-grained PAT can see a repository's
2011
+ // name while `Contents` sits at No access, so this is a
2012
+ // PERMISSION answer; counting it as "not a plugin" told the
2013
+ // operator a plugin repository had no manifest.
2014
+ // else — rate limit / network / server: genuinely skipped.
2015
+ if (manifest.status === 404)
2016
+ notPlugins += 1;
2017
+ else if (manifest.status === 401) {
2018
+ // The source's credential is unusable for EVERY repository here; keep
2019
+ // the manifest-read count honest and let the run continue so the other
2020
+ // rows still answer.
2021
+ unauthorized += 1;
2022
+ }
2023
+ else if (manifest.status === 403) {
2024
+ forbidden += 1;
2025
+ if (forbiddenRepos.length < FORBIDDEN_LIST_LIMIT)
2026
+ forbiddenRepos.push(full);
2027
+ }
2028
+ else
2029
+ skipped += 1;
2030
+ continue;
2031
+ }
2032
+ try {
2033
+ const parsed = JSON.parse(new TextDecoder().decode(manifest.value));
2034
+ validatePluginManifest(parsed, 'plugin.json');
2035
+ found += 1;
2036
+ if (!byRepo.has(full)) {
2037
+ byRepo.set(full, {
2038
+ id: parsed.id,
2039
+ ...(parsed.name ? { name: parsed.name } : {}),
2040
+ ...(parsed.version ? { version: parsed.version } : {}),
2041
+ ...(parsed.description ? { description: parsed.description } : {}),
2042
+ via: source.label ?? source.target,
2043
+ });
2044
+ }
2045
+ }
2046
+ catch {
2047
+ // A BROKEN manifest is not a plugin anyone can install.
2048
+ }
2049
+ }
2050
+ };
2051
+ await Promise.all(Array.from({ length: Math.min(CONCURRENCY, candidates.length) }, () => worker()));
2052
+ // An unusable credential is a SOURCE-level fact, not a per-repository one:
2053
+ // when every read was rejected with 401 the row must say so once, not count
2054
+ // repositories that were never readable.
2055
+ const credentialRejected = unauthorized > 0 && unauthorized === candidates.length;
2056
+ perSource.push({
2057
+ target: source.target,
2058
+ ...(source.label ? { label: source.label } : {}),
2059
+ authenticated: Boolean(source.token),
2060
+ scanned: candidates.length,
2061
+ found,
2062
+ notPlugins,
2063
+ ...(forbidden > 0 ? { forbidden } : {}),
2064
+ ...(credentialRejected
2065
+ ? { error: 'GitHub rejected this source\u2019s token (401) on every read \u2014 it may be expired or revoked' }
2066
+ : {}),
2067
+ ...(forbiddenRepos.length > 0 ? { forbiddenRepos } : {}),
2068
+ });
2069
+ }
2070
+ // EVERY source failing is a refusal, not an empty index: zero rows would read
2071
+ // as "you have no plugins" when the truth is "we could not ask".
2072
+ if (perSource.length > 0 && perSource.every((row) => row.error)) {
2073
+ return {
2074
+ error: `no source could be read — ${perSource.map((row) => `${row.label ?? row.target}: ${row.error}`).join('; ')}`,
2075
+ perSource,
2076
+ };
2077
+ }
2078
+ const entries = [...byRepo.entries()].map(([repo, agg]) => ({
2079
+ repo,
2080
+ id: agg.id,
2081
+ ok: true,
2082
+ via: agg.via,
2083
+ ...(agg.name ? { name: agg.name } : {}),
2084
+ ...(agg.version ? { version: agg.version } : {}),
2085
+ ...(agg.description ? { description: agg.description } : {}),
2086
+ }));
2087
+ const scanned = perSource.reduce((sum, row) => sum + row.scanned, 0);
2088
+ return {
2089
+ index: writeSourceIndex({
2090
+ source: settings.sources.some((row) => row.token) ? 'file' : 'env',
2091
+ sourceCount: settings.sources.length,
2092
+ scanned,
2093
+ skipped,
2094
+ notPlugins: perSource.reduce((sum, row) => sum + row.notPlugins, 0),
2095
+ ...(() => {
2096
+ // A 403 is kept OUT of `notPlugins`: those repositories were never read,
2097
+ // so the console must not claim they have no manifest.
2098
+ const forbidden = perSource.reduce((sum, row) => sum + (row.forbidden ?? 0), 0);
2099
+ return forbidden > 0 ? { forbidden } : {};
2100
+ })(),
2101
+ // The per-source outcome rides WITH the index: a row's reachability is
2102
+ // read from the scan that produced the list, so the console needs no
2103
+ // second, differently-scoped probe to answer "can this row read?".
2104
+ sources: perSource,
2105
+ entries,
2106
+ }),
2107
+ perSource,
2108
+ };
2109
+ }
2110
+ /** The market cache directory (tests point OCR_HOME at a sandbox). */
2111
+ export function marketCacheDir() {
2112
+ return cacheDir();
2113
+ }