@jagilber-org/index-server 1.19.1

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 (360) hide show
  1. package/CHANGELOG.md +1218 -0
  2. package/CODE_OF_CONDUCT.md +49 -0
  3. package/CONTRIBUTING.md +75 -0
  4. package/LICENSE +21 -0
  5. package/README.md +523 -0
  6. package/SECURITY.md +50 -0
  7. package/dist/config/configUtils.d.ts +11 -0
  8. package/dist/config/configUtils.js +87 -0
  9. package/dist/config/dashboardConfig.d.ts +45 -0
  10. package/dist/config/dashboardConfig.js +63 -0
  11. package/dist/config/defaultValues.d.ts +61 -0
  12. package/dist/config/defaultValues.js +70 -0
  13. package/dist/config/dirConstants.d.ts +17 -0
  14. package/dist/config/dirConstants.js +28 -0
  15. package/dist/config/featureConfig.d.ts +61 -0
  16. package/dist/config/featureConfig.js +121 -0
  17. package/dist/config/runtimeConfig.d.ts +145 -0
  18. package/dist/config/runtimeConfig.js +334 -0
  19. package/dist/config/serverConfig.d.ts +90 -0
  20. package/dist/config/serverConfig.js +164 -0
  21. package/dist/dashboard/analytics/AnalyticsEngine.d.ts +142 -0
  22. package/dist/dashboard/analytics/AnalyticsEngine.js +373 -0
  23. package/dist/dashboard/analytics/BusinessIntelligence.d.ts +187 -0
  24. package/dist/dashboard/analytics/BusinessIntelligence.js +594 -0
  25. package/dist/dashboard/client/admin.html +2150 -0
  26. package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/chunk-SP2CHFBE.mjs +1 -0
  27. package/dist/dashboard/client/chunks/mermaid-layout-elk.esm.min/render-T6MDALS3.mjs +27 -0
  28. package/dist/dashboard/client/css/admin.css +1466 -0
  29. package/dist/dashboard/client/js/admin.boot.js +359 -0
  30. package/dist/dashboard/client/js/admin.config.js +196 -0
  31. package/dist/dashboard/client/js/admin.embeddings.js +425 -0
  32. package/dist/dashboard/client/js/admin.graph.js +583 -0
  33. package/dist/dashboard/client/js/admin.instances.js +120 -0
  34. package/dist/dashboard/client/js/admin.instructions.js +552 -0
  35. package/dist/dashboard/client/js/admin.logs.js +113 -0
  36. package/dist/dashboard/client/js/admin.maintenance.js +354 -0
  37. package/dist/dashboard/client/js/admin.messaging.js +635 -0
  38. package/dist/dashboard/client/js/admin.monitor.js +181 -0
  39. package/dist/dashboard/client/js/admin.overview.js +221 -0
  40. package/dist/dashboard/client/js/admin.performance.js +61 -0
  41. package/dist/dashboard/client/js/admin.sessions.js +293 -0
  42. package/dist/dashboard/client/js/admin.sqlite.js +366 -0
  43. package/dist/dashboard/client/js/admin.utils.js +49 -0
  44. package/dist/dashboard/client/js/chart.umd.js +14 -0
  45. package/dist/dashboard/client/js/elk.bundled.js +6696 -0
  46. package/dist/dashboard/client/js/marked.umd.js +74 -0
  47. package/dist/dashboard/client/js/mermaid.min.js +3022 -0
  48. package/dist/dashboard/client/mermaid-layout-elk.esm.min.mjs +1 -0
  49. package/dist/dashboard/export/DataExporter.d.ts +169 -0
  50. package/dist/dashboard/export/DataExporter.js +737 -0
  51. package/dist/dashboard/export/exporters/csvExporter.d.ts +11 -0
  52. package/dist/dashboard/export/exporters/csvExporter.js +46 -0
  53. package/dist/dashboard/export/exporters/exportTypes.d.ts +89 -0
  54. package/dist/dashboard/export/exporters/exportTypes.js +5 -0
  55. package/dist/dashboard/export/exporters/jsonExporter.d.ts +7 -0
  56. package/dist/dashboard/export/exporters/jsonExporter.js +22 -0
  57. package/dist/dashboard/export/exporters/xmlExporter.d.ts +17 -0
  58. package/dist/dashboard/export/exporters/xmlExporter.js +175 -0
  59. package/dist/dashboard/integration/APIIntegration.d.ts +41 -0
  60. package/dist/dashboard/integration/APIIntegration.js +95 -0
  61. package/dist/dashboard/security/SecurityMonitor.d.ts +167 -0
  62. package/dist/dashboard/security/SecurityMonitor.js +559 -0
  63. package/dist/dashboard/server/AdminPanel.d.ts +183 -0
  64. package/dist/dashboard/server/AdminPanel.js +792 -0
  65. package/dist/dashboard/server/AdminPanelConfig.d.ts +42 -0
  66. package/dist/dashboard/server/AdminPanelConfig.js +80 -0
  67. package/dist/dashboard/server/AdminPanelState.d.ts +47 -0
  68. package/dist/dashboard/server/AdminPanelState.js +214 -0
  69. package/dist/dashboard/server/ApiRoutes.d.ts +17 -0
  70. package/dist/dashboard/server/ApiRoutes.js +149 -0
  71. package/dist/dashboard/server/DashboardServer.d.ts +49 -0
  72. package/dist/dashboard/server/DashboardServer.js +159 -0
  73. package/dist/dashboard/server/FileMetricsStorage.d.ts +49 -0
  74. package/dist/dashboard/server/FileMetricsStorage.js +195 -0
  75. package/dist/dashboard/server/HttpTransport.d.ts +23 -0
  76. package/dist/dashboard/server/HttpTransport.js +116 -0
  77. package/dist/dashboard/server/InstanceManager.d.ts +53 -0
  78. package/dist/dashboard/server/InstanceManager.js +284 -0
  79. package/dist/dashboard/server/KnowledgeStore.d.ts +35 -0
  80. package/dist/dashboard/server/KnowledgeStore.js +105 -0
  81. package/dist/dashboard/server/LeaderElection.d.ts +81 -0
  82. package/dist/dashboard/server/LeaderElection.js +268 -0
  83. package/dist/dashboard/server/MetricsCollector.d.ts +200 -0
  84. package/dist/dashboard/server/MetricsCollector.js +803 -0
  85. package/dist/dashboard/server/SessionPersistenceManager.d.ts +88 -0
  86. package/dist/dashboard/server/SessionPersistenceManager.js +457 -0
  87. package/dist/dashboard/server/ThinClient.d.ts +64 -0
  88. package/dist/dashboard/server/ThinClient.js +237 -0
  89. package/dist/dashboard/server/WebSocketManager.d.ts +161 -0
  90. package/dist/dashboard/server/WebSocketManager.js +463 -0
  91. package/dist/dashboard/server/httpLifecycle.d.ts +17 -0
  92. package/dist/dashboard/server/httpLifecycle.js +35 -0
  93. package/dist/dashboard/server/legacyDashboardHtml.d.ts +9 -0
  94. package/dist/dashboard/server/legacyDashboardHtml.js +618 -0
  95. package/dist/dashboard/server/legacyDashboardStyles.d.ts +5 -0
  96. package/dist/dashboard/server/legacyDashboardStyles.js +490 -0
  97. package/dist/dashboard/server/metricsAggregation.d.ts +252 -0
  98. package/dist/dashboard/server/metricsAggregation.js +206 -0
  99. package/dist/dashboard/server/metricsSerializer.d.ts +25 -0
  100. package/dist/dashboard/server/metricsSerializer.js +195 -0
  101. package/dist/dashboard/server/routes/admin.routes.d.ts +16 -0
  102. package/dist/dashboard/server/routes/admin.routes.js +596 -0
  103. package/dist/dashboard/server/routes/alerts.routes.d.ts +7 -0
  104. package/dist/dashboard/server/routes/alerts.routes.js +93 -0
  105. package/dist/dashboard/server/routes/api.feedback.routes.d.ts +73 -0
  106. package/dist/dashboard/server/routes/api.feedback.routes.js +171 -0
  107. package/dist/dashboard/server/routes/api.instructions.routes.d.ts +101 -0
  108. package/dist/dashboard/server/routes/api.instructions.routes.js +213 -0
  109. package/dist/dashboard/server/routes/api.usage.routes.d.ts +57 -0
  110. package/dist/dashboard/server/routes/api.usage.routes.js +374 -0
  111. package/dist/dashboard/server/routes/embeddings.routes.d.ts +6 -0
  112. package/dist/dashboard/server/routes/embeddings.routes.js +246 -0
  113. package/dist/dashboard/server/routes/graph.routes.d.ts +6 -0
  114. package/dist/dashboard/server/routes/graph.routes.js +280 -0
  115. package/dist/dashboard/server/routes/index.d.ts +38 -0
  116. package/dist/dashboard/server/routes/index.js +194 -0
  117. package/dist/dashboard/server/routes/instances.routes.d.ts +6 -0
  118. package/dist/dashboard/server/routes/instances.routes.js +35 -0
  119. package/dist/dashboard/server/routes/instructions.routes.d.ts +8 -0
  120. package/dist/dashboard/server/routes/instructions.routes.js +336 -0
  121. package/dist/dashboard/server/routes/knowledge.routes.d.ts +6 -0
  122. package/dist/dashboard/server/routes/knowledge.routes.js +82 -0
  123. package/dist/dashboard/server/routes/logs.routes.d.ts +6 -0
  124. package/dist/dashboard/server/routes/logs.routes.js +164 -0
  125. package/dist/dashboard/server/routes/messaging.routes.d.ts +16 -0
  126. package/dist/dashboard/server/routes/messaging.routes.js +293 -0
  127. package/dist/dashboard/server/routes/metrics.routes.d.ts +10 -0
  128. package/dist/dashboard/server/routes/metrics.routes.js +346 -0
  129. package/dist/dashboard/server/routes/scripts.routes.d.ts +9 -0
  130. package/dist/dashboard/server/routes/scripts.routes.js +84 -0
  131. package/dist/dashboard/server/routes/sqlite.routes.d.ts +9 -0
  132. package/dist/dashboard/server/routes/sqlite.routes.js +569 -0
  133. package/dist/dashboard/server/routes/status.routes.d.ts +7 -0
  134. package/dist/dashboard/server/routes/status.routes.js +183 -0
  135. package/dist/dashboard/server/routes/synthetic.routes.d.ts +7 -0
  136. package/dist/dashboard/server/routes/synthetic.routes.js +195 -0
  137. package/dist/dashboard/server/routes/tools.routes.d.ts +6 -0
  138. package/dist/dashboard/server/routes/tools.routes.js +46 -0
  139. package/dist/dashboard/server/routes/usage.routes.d.ts +6 -0
  140. package/dist/dashboard/server/routes/usage.routes.js +25 -0
  141. package/dist/dashboard/server/wsInit.d.ts +16 -0
  142. package/dist/dashboard/server/wsInit.js +35 -0
  143. package/dist/externalClientLib.d.ts +1 -0
  144. package/dist/externalClientLib.js +2 -0
  145. package/dist/minimal/index.d.ts +1 -0
  146. package/dist/minimal/index.js +140 -0
  147. package/dist/models/SessionPersistence.d.ts +115 -0
  148. package/dist/models/SessionPersistence.js +66 -0
  149. package/dist/models/instruction.d.ts +45 -0
  150. package/dist/models/instruction.js +2 -0
  151. package/dist/perf/benchmark.d.ts +1 -0
  152. package/dist/perf/benchmark.js +50 -0
  153. package/dist/portableClientWrapper.d.ts +1 -0
  154. package/dist/portableClientWrapper.js +2 -0
  155. package/dist/schemas/index.d.ts +128 -0
  156. package/dist/schemas/index.js +371 -0
  157. package/dist/scripts/runPerformanceBaseline.d.ts +1 -0
  158. package/dist/scripts/runPerformanceBaseline.js +17 -0
  159. package/dist/server/handshakeManager.d.ts +25 -0
  160. package/dist/server/handshakeManager.js +472 -0
  161. package/dist/server/index-server.d.ts +56 -0
  162. package/dist/server/index-server.js +822 -0
  163. package/dist/server/registry.d.ts +44 -0
  164. package/dist/server/registry.js +236 -0
  165. package/dist/server/sdkServer.d.ts +8 -0
  166. package/dist/server/sdkServer.js +299 -0
  167. package/dist/server/shutdownGuard.d.ts +41 -0
  168. package/dist/server/shutdownGuard.js +52 -0
  169. package/dist/server/thin-client.d.ts +22 -0
  170. package/dist/server/thin-client.js +111 -0
  171. package/dist/server/transport.d.ts +41 -0
  172. package/dist/server/transport.js +312 -0
  173. package/dist/server/transportFactory.d.ts +21 -0
  174. package/dist/server/transportFactory.js +429 -0
  175. package/dist/services/atomicFs.d.ts +22 -0
  176. package/dist/services/atomicFs.js +103 -0
  177. package/dist/services/auditLog.d.ts +38 -0
  178. package/dist/services/auditLog.js +142 -0
  179. package/dist/services/autoBackup.d.ts +14 -0
  180. package/dist/services/autoBackup.js +171 -0
  181. package/dist/services/autoSplit.d.ts +32 -0
  182. package/dist/services/autoSplit.js +113 -0
  183. package/dist/services/backupZip.d.ts +25 -0
  184. package/dist/services/backupZip.js +110 -0
  185. package/dist/services/bootstrapGating.d.ts +123 -0
  186. package/dist/services/bootstrapGating.js +221 -0
  187. package/dist/services/canonical.d.ts +23 -0
  188. package/dist/services/canonical.js +65 -0
  189. package/dist/services/categoryRules.d.ts +7 -0
  190. package/dist/services/categoryRules.js +37 -0
  191. package/dist/services/classificationService.d.ts +42 -0
  192. package/dist/services/classificationService.js +168 -0
  193. package/dist/services/embeddingService.d.ts +62 -0
  194. package/dist/services/embeddingService.js +259 -0
  195. package/dist/services/errors.d.ts +22 -0
  196. package/dist/services/errors.js +31 -0
  197. package/dist/services/featureFlags.d.ts +25 -0
  198. package/dist/services/featureFlags.js +89 -0
  199. package/dist/services/features.d.ts +13 -0
  200. package/dist/services/features.js +35 -0
  201. package/dist/services/handlers/instructions.add.d.ts +1 -0
  202. package/dist/services/handlers/instructions.add.js +496 -0
  203. package/dist/services/handlers/instructions.groom.d.ts +1 -0
  204. package/dist/services/handlers/instructions.groom.js +523 -0
  205. package/dist/services/handlers/instructions.import.d.ts +1 -0
  206. package/dist/services/handlers/instructions.import.js +173 -0
  207. package/dist/services/handlers/instructions.patch.d.ts +1 -0
  208. package/dist/services/handlers/instructions.patch.js +167 -0
  209. package/dist/services/handlers/instructions.query.d.ts +163 -0
  210. package/dist/services/handlers/instructions.query.js +522 -0
  211. package/dist/services/handlers/instructions.reload.d.ts +1 -0
  212. package/dist/services/handlers/instructions.reload.js +13 -0
  213. package/dist/services/handlers/instructions.remove.d.ts +1 -0
  214. package/dist/services/handlers/instructions.remove.js +118 -0
  215. package/dist/services/handlers/instructions.shared.d.ts +31 -0
  216. package/dist/services/handlers/instructions.shared.js +124 -0
  217. package/dist/services/handlers.activation.d.ts +1 -0
  218. package/dist/services/handlers.activation.js +203 -0
  219. package/dist/services/handlers.bootstrap.d.ts +1 -0
  220. package/dist/services/handlers.bootstrap.js +38 -0
  221. package/dist/services/handlers.dashboardConfig.d.ts +34 -0
  222. package/dist/services/handlers.dashboardConfig.js +108 -0
  223. package/dist/services/handlers.diagnostics.d.ts +1 -0
  224. package/dist/services/handlers.diagnostics.js +64 -0
  225. package/dist/services/handlers.feedback.d.ts +15 -0
  226. package/dist/services/handlers.feedback.js +378 -0
  227. package/dist/services/handlers.gates.d.ts +1 -0
  228. package/dist/services/handlers.gates.js +46 -0
  229. package/dist/services/handlers.graph.d.ts +53 -0
  230. package/dist/services/handlers.graph.js +231 -0
  231. package/dist/services/handlers.help.d.ts +1 -0
  232. package/dist/services/handlers.help.js +119 -0
  233. package/dist/services/handlers.instructionSchema.d.ts +1 -0
  234. package/dist/services/handlers.instructionSchema.js +227 -0
  235. package/dist/services/handlers.instructions.d.ts +8 -0
  236. package/dist/services/handlers.instructions.js +14 -0
  237. package/dist/services/handlers.instructionsDiagnostics.d.ts +1 -0
  238. package/dist/services/handlers.instructionsDiagnostics.js +14 -0
  239. package/dist/services/handlers.integrity.d.ts +1 -0
  240. package/dist/services/handlers.integrity.js +35 -0
  241. package/dist/services/handlers.manifest.d.ts +1 -0
  242. package/dist/services/handlers.manifest.js +24 -0
  243. package/dist/services/handlers.messaging.d.ts +12 -0
  244. package/dist/services/handlers.messaging.js +203 -0
  245. package/dist/services/handlers.metrics.d.ts +1 -0
  246. package/dist/services/handlers.metrics.js +43 -0
  247. package/dist/services/handlers.promote.d.ts +1 -0
  248. package/dist/services/handlers.promote.js +306 -0
  249. package/dist/services/handlers.prompt.d.ts +1 -0
  250. package/dist/services/handlers.prompt.js +7 -0
  251. package/dist/services/handlers.search.d.ts +69 -0
  252. package/dist/services/handlers.search.js +645 -0
  253. package/dist/services/handlers.testPrimitive.d.ts +1 -0
  254. package/dist/services/handlers.testPrimitive.js +5 -0
  255. package/dist/services/handlers.trace.d.ts +1 -0
  256. package/dist/services/handlers.trace.js +31 -0
  257. package/dist/services/handlers.usage.d.ts +1 -0
  258. package/dist/services/handlers.usage.js +11 -0
  259. package/dist/services/hotScore.d.ts +137 -0
  260. package/dist/services/hotScore.js +244 -0
  261. package/dist/services/indexContext.d.ts +117 -0
  262. package/dist/services/indexContext.js +968 -0
  263. package/dist/services/indexLoader.d.ts +44 -0
  264. package/dist/services/indexLoader.js +921 -0
  265. package/dist/services/indexRepository.d.ts +32 -0
  266. package/dist/services/indexRepository.js +71 -0
  267. package/dist/services/indexingService.d.ts +1 -0
  268. package/dist/services/indexingService.js +2 -0
  269. package/dist/services/instructions.dispatcher.d.ts +1 -0
  270. package/dist/services/instructions.dispatcher.js +231 -0
  271. package/dist/services/logPrefix.d.ts +1 -0
  272. package/dist/services/logPrefix.js +30 -0
  273. package/dist/services/logger.d.ts +52 -0
  274. package/dist/services/logger.js +268 -0
  275. package/dist/services/manifestManager.d.ts +82 -0
  276. package/dist/services/manifestManager.js +200 -0
  277. package/dist/services/messaging/agentMailbox.d.ts +60 -0
  278. package/dist/services/messaging/agentMailbox.js +353 -0
  279. package/dist/services/messaging/messagingPersistence.d.ts +20 -0
  280. package/dist/services/messaging/messagingPersistence.js +111 -0
  281. package/dist/services/messaging/messagingTypes.d.ts +150 -0
  282. package/dist/services/messaging/messagingTypes.js +66 -0
  283. package/dist/services/ownershipService.d.ts +1 -0
  284. package/dist/services/ownershipService.js +38 -0
  285. package/dist/services/performanceBaseline.d.ts +19 -0
  286. package/dist/services/performanceBaseline.js +210 -0
  287. package/dist/services/preflight.d.ts +12 -0
  288. package/dist/services/preflight.js +79 -0
  289. package/dist/services/promptReviewService.d.ts +44 -0
  290. package/dist/services/promptReviewService.js +101 -0
  291. package/dist/services/responseEnvelope.d.ts +6 -0
  292. package/dist/services/responseEnvelope.js +25 -0
  293. package/dist/services/seedBootstrap.d.ts +34 -0
  294. package/dist/services/seedBootstrap.js +427 -0
  295. package/dist/services/storage/factory.d.ts +17 -0
  296. package/dist/services/storage/factory.js +35 -0
  297. package/dist/services/storage/hashUtils.d.ts +11 -0
  298. package/dist/services/storage/hashUtils.js +35 -0
  299. package/dist/services/storage/index.d.ts +12 -0
  300. package/dist/services/storage/index.js +18 -0
  301. package/dist/services/storage/jsonFileStore.d.ts +32 -0
  302. package/dist/services/storage/jsonFileStore.js +241 -0
  303. package/dist/services/storage/migrationEngine.d.ts +35 -0
  304. package/dist/services/storage/migrationEngine.js +93 -0
  305. package/dist/services/storage/sqliteMessageStore.d.ts +53 -0
  306. package/dist/services/storage/sqliteMessageStore.js +146 -0
  307. package/dist/services/storage/sqliteSchema.d.ts +12 -0
  308. package/dist/services/storage/sqliteSchema.js +122 -0
  309. package/dist/services/storage/sqliteStore.d.ts +41 -0
  310. package/dist/services/storage/sqliteStore.js +339 -0
  311. package/dist/services/storage/sqliteUsageStore.d.ts +35 -0
  312. package/dist/services/storage/sqliteUsageStore.js +94 -0
  313. package/dist/services/storage/types.d.ts +171 -0
  314. package/dist/services/storage/types.js +12 -0
  315. package/dist/services/toolHandlers.d.ts +23 -0
  316. package/dist/services/toolHandlers.js +50 -0
  317. package/dist/services/toolRegistry.d.ts +20 -0
  318. package/dist/services/toolRegistry.js +490 -0
  319. package/dist/services/toolRegistry.zod.d.ts +10 -0
  320. package/dist/services/toolRegistry.zod.js +323 -0
  321. package/dist/services/tracing.d.ts +26 -0
  322. package/dist/services/tracing.js +260 -0
  323. package/dist/services/usageBuckets.d.ts +161 -0
  324. package/dist/services/usageBuckets.js +364 -0
  325. package/dist/services/validationService.d.ts +38 -0
  326. package/dist/services/validationService.js +125 -0
  327. package/dist/utils/BufferRing.d.ts +203 -0
  328. package/dist/utils/BufferRing.js +551 -0
  329. package/dist/utils/BufferRingExamples.d.ts +55 -0
  330. package/dist/utils/BufferRingExamples.js +188 -0
  331. package/dist/utils/envUtils.d.ts +42 -0
  332. package/dist/utils/envUtils.js +80 -0
  333. package/dist/utils/memoryMonitor.d.ts +83 -0
  334. package/dist/utils/memoryMonitor.js +275 -0
  335. package/dist/versioning/schemaVersion.d.ts +6 -0
  336. package/dist/versioning/schemaVersion.js +93 -0
  337. package/package.json +134 -0
  338. package/schemas/README.md +13 -0
  339. package/schemas/feedback-entry.schema.json +27 -0
  340. package/schemas/graph-export-v2.schema.json +60 -0
  341. package/schemas/index-server.code-schema.json +38477 -0
  342. package/schemas/instruction.schema.json +262 -0
  343. package/schemas/json-schema/SessionPersistence-persisted-admin-session.schema.json +54 -0
  344. package/schemas/json-schema/SessionPersistence-persisted-session-history-entry.schema.json +51 -0
  345. package/schemas/json-schema/SessionPersistence-persisted-web-socket-connection.schema.json +54 -0
  346. package/schemas/json-schema/SessionPersistence-session-persistence-config.schema.json +110 -0
  347. package/schemas/json-schema/SessionPersistence-session-persistence-data.schema.json +229 -0
  348. package/schemas/json-schema/SessionPersistence-session-persistence-manifest.schema.json +109 -0
  349. package/schemas/json-schema/SessionPersistence-session-persistence-metadata.schema.json +55 -0
  350. package/schemas/json-schema/instruction-audience-scope.schema.json +14 -0
  351. package/schemas/json-schema/instruction-content-type.schema.json +17 -0
  352. package/schemas/json-schema/instruction-instruction-entry.schema.json +206 -0
  353. package/schemas/json-schema/instruction-requirement-level.schema.json +16 -0
  354. package/schemas/manifest.json +78 -0
  355. package/schemas/manifest.schema.json +33 -0
  356. package/schemas/usage-batch.schema.json +16 -0
  357. package/schemas/usage-buckets.schema.json +30 -0
  358. package/schemas/usage-event.schema.json +17 -0
  359. package/scripts/copy-dashboard-assets.mjs +170 -0
  360. package/scripts/setup-hooks.cjs +28 -0
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ClassificationService = void 0;
7
+ const schemaVersion_1 = require("../versioning/schemaVersion");
8
+ const crypto_1 = __importDefault(require("crypto"));
9
+ class ClassificationService {
10
+ /**
11
+ * Normalize an instruction entry by filling governance defaults, deriving scope fields,
12
+ * computing hashes, and canonicalizing text fields.
13
+ * @param entry - Raw instruction entry to normalize
14
+ * @returns A fully normalized {@link NormalizedInstruction} with all governance defaults applied
15
+ */
16
+ normalize(entry) {
17
+ const now = new Date().toISOString();
18
+ const trimmedTitle = entry.title.trim();
19
+ const trimmedBody = entry.body.trim();
20
+ // Derive structured scope fields from legacy category prefixes if not already present
21
+ let workspaceId = entry.workspaceId;
22
+ let userId = entry.userId;
23
+ const teamIds = entry.teamIds ? [...entry.teamIds] : [];
24
+ const otherCats = [];
25
+ for (const cRaw of entry.categories) {
26
+ const c = cRaw.toLowerCase();
27
+ if (c.startsWith('scope:workspace:')) {
28
+ if (!workspaceId)
29
+ workspaceId = c.substring('scope:workspace:'.length);
30
+ continue;
31
+ }
32
+ if (c.startsWith('scope:user:')) {
33
+ if (!userId)
34
+ userId = c.substring('scope:user:'.length);
35
+ continue;
36
+ }
37
+ if (c.startsWith('scope:team:')) {
38
+ const tid = c.substring('scope:team:'.length);
39
+ if (tid && !teamIds.includes(tid))
40
+ teamIds.push(tid);
41
+ continue;
42
+ }
43
+ otherCats.push(cRaw);
44
+ }
45
+ // Governance defaults
46
+ const version = entry.version || '1.0.0';
47
+ const status = entry.status || (entry.requirement === 'deprecated' ? 'deprecated' : 'approved');
48
+ const owner = entry.owner || 'unowned';
49
+ const priorityTier = entry.priorityTier || this.computePriorityTier(entry.priority, entry.requirement);
50
+ const classification = entry.classification || 'internal';
51
+ const lastReviewedAt = entry.lastReviewedAt || now;
52
+ const reviewIntervalDays = entry.reviewIntervalDays ?? this.reviewIntervalDays(priorityTier, entry.requirement);
53
+ const nextReviewDue = entry.nextReviewDue || new Date(Date.now() + reviewIntervalDays * 86400_000).toISOString();
54
+ const changeLog = entry.changeLog && entry.changeLog.length ? entry.changeLog : [{ version, changedAt: entry.createdAt || now, summary: 'initial import' }];
55
+ const semanticSummary = entry.semanticSummary || this.deriveSummary(entry.body);
56
+ const contentType = entry.contentType || 'instruction'; // Default to 'instruction' for backward compatibility
57
+ const norm = {
58
+ ...entry,
59
+ title: trimmedTitle,
60
+ body: trimmedBody,
61
+ categories: Array.from(new Set(otherCats.map(c => c.toLowerCase()))).sort(),
62
+ updatedAt: entry.updatedAt || now,
63
+ createdAt: entry.createdAt || now,
64
+ // Guarantee schemaVersion presence (tests/assertions now rely on dispatcher list action output)
65
+ schemaVersion: entry.schemaVersion || schemaVersion_1.SCHEMA_VERSION,
66
+ // Compute hash from canonical (trimmed) body to ensure stability across innocuous whitespace differences
67
+ sourceHash: entry.sourceHash && entry.sourceHash.length === 64 ? entry.sourceHash : this.computeHash(trimmedBody),
68
+ riskScore: this.computeRisk(entry),
69
+ workspaceId,
70
+ userId,
71
+ teamIds: teamIds.length ? teamIds : undefined,
72
+ version,
73
+ status,
74
+ owner,
75
+ priorityTier,
76
+ classification,
77
+ lastReviewedAt,
78
+ nextReviewDue,
79
+ reviewIntervalDays,
80
+ changeLog: changeLog,
81
+ supersedes: entry.supersedes,
82
+ semanticSummary,
83
+ contentType
84
+ };
85
+ return norm;
86
+ }
87
+ /**
88
+ * Validate an instruction entry for required fields and logical consistency.
89
+ * @param entry - Instruction entry to validate
90
+ * @returns Array of human-readable issue strings; empty when the entry is valid
91
+ */
92
+ validate(entry) {
93
+ const issues = [];
94
+ if (!entry.id)
95
+ issues.push('missing id');
96
+ if (!entry.title)
97
+ issues.push('missing title');
98
+ if (!entry.body)
99
+ issues.push('missing body');
100
+ if (entry.requirement === 'deprecated' && !entry.deprecatedBy)
101
+ issues.push('deprecated requires deprecatedBy');
102
+ return issues;
103
+ }
104
+ /**
105
+ * Compute a numeric risk score for an instruction entry (higher = riskier).
106
+ * Score is derived from priority and requirement level.
107
+ * @param entry - Instruction entry to score
108
+ * @returns Numeric risk score
109
+ */
110
+ computeRisk(entry) {
111
+ const base = 100 - Math.min(Math.max(entry.priority, 1), 100);
112
+ const reqWeight = this.requirementWeight(entry.requirement);
113
+ return base + reqWeight;
114
+ }
115
+ requirementWeight(r) {
116
+ switch (r) {
117
+ case 'mandatory': return 50;
118
+ case 'critical': return 60;
119
+ case 'recommended': return 20;
120
+ case 'optional': return 5;
121
+ case 'deprecated': return -30;
122
+ default: return 0;
123
+ }
124
+ }
125
+ /**
126
+ * Compute a SHA-256 hex digest of the given content string.
127
+ * @param content - UTF-8 string to hash
128
+ * @returns 64-character hex-encoded SHA-256 digest
129
+ */
130
+ computeHash(content) { return crypto_1.default.createHash('sha256').update(content, 'utf8').digest('hex'); }
131
+ computePriorityTier(priority, requirement) {
132
+ // Lower numeric is higher importance
133
+ if (priority <= 20 || requirement === 'mandatory' || requirement === 'critical')
134
+ return 'P1';
135
+ if (priority <= 40)
136
+ return 'P2';
137
+ if (priority <= 70)
138
+ return 'P3';
139
+ return 'P4';
140
+ }
141
+ reviewIntervalDays(tier, requirement) {
142
+ // Shorter intervals for higher criticality
143
+ if (tier === 'P1' || requirement === 'mandatory' || requirement === 'critical')
144
+ return 30;
145
+ if (tier === 'P2')
146
+ return 60;
147
+ if (tier === 'P3')
148
+ return 90;
149
+ return 120;
150
+ }
151
+ // Public helper for schema migration - computes review interval
152
+ /**
153
+ * Compute the recommended review interval in days for a given priority tier and requirement level.
154
+ * @param tier - Priority tier (`'P1'`–`'P4'`; P1 is highest priority)
155
+ * @param requirement - Requirement level for the instruction
156
+ * @returns Number of days until the next review should occur
157
+ */
158
+ computeReviewIntervalDays(tier, requirement) {
159
+ return this.reviewIntervalDays(tier, requirement);
160
+ }
161
+ deriveSummary(body) {
162
+ const trimmed = body.trim();
163
+ const firstLine = trimmed.split(/\r?\n/)[0];
164
+ // Keep it short (~160 chars)
165
+ return firstLine.length > 160 ? firstLine.slice(0, 157) + '...' : firstLine;
166
+ }
167
+ }
168
+ exports.ClassificationService = ClassificationService;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Embedding Service for Semantic Search
3
+ *
4
+ * Lazy-loaded embedding model — zero startup cost.
5
+ * Model is loaded only on first embedText() call via dynamic import.
6
+ * Vectors cached to disk for cross-instance sharing.
7
+ *
8
+ * Key design:
9
+ * - cosineSimilarity, isStale, load/saveCachedEmbeddings are pure functions (no model needed)
10
+ * - embedText and getInstructionEmbeddings trigger lazy model load
11
+ * - Uses @huggingface/transformers (optional dep) via dynamic ESM import
12
+ */
13
+ import { InstructionEntry } from '../models/instruction';
14
+ /**
15
+ * Cosine similarity between two vectors.
16
+ * Pure math — no dependencies, no model needed.
17
+ */
18
+ export declare function cosineSimilarity(a: Float32Array, b: Float32Array): number;
19
+ /**
20
+ * Check if cached embeddings are stale (index has changed since last embed).
21
+ */
22
+ export declare function isStale(indexHash: string, embeddingHash: string): boolean;
23
+ /**
24
+ * Persisted embedding cache format (backwards-compatible: entryHashes is optional).
25
+ */
26
+ export interface EmbeddingCacheData {
27
+ indexHash: string;
28
+ modelName?: string;
29
+ /** Per-entry content hashes for incremental invalidation (required for v2+). */
30
+ entryHashes?: Record<string, string>;
31
+ embeddings: Record<string, number[]>;
32
+ }
33
+ /**
34
+ * Load cached embeddings from disk.
35
+ * Returns null if file doesn't exist or is invalid.
36
+ */
37
+ export declare function loadCachedEmbeddings(filePath: string): EmbeddingCacheData | null;
38
+ /**
39
+ * Save embeddings to disk for cross-instance sharing.
40
+ */
41
+ export declare function saveCachedEmbeddings(filePath: string, data: EmbeddingCacheData): void;
42
+ /**
43
+ * Embed a single text string into a vector.
44
+ * Triggers lazy model loading on first call.
45
+ */
46
+ export declare function embedText(text: string, modelName: string, cacheDir: string, device?: string, localOnly?: boolean): Promise<Float32Array>;
47
+ /** Signature for the embed function (injectable for testing). */
48
+ export type EmbedFn = (text: string, modelName: string, cacheDir: string, device: string, localOnly: boolean) => Promise<Float32Array>;
49
+ /**
50
+ * Get or compute embeddings for all index instructions.
51
+ * Uses disk cache when available and fresh.
52
+ *
53
+ * Incremental update: when the index hash changes (instructions added/modified),
54
+ * only entries whose sourceHash differs from the cached value are recomputed.
55
+ * This reduces cold-recompute from O(all entries) to O(delta entries).
56
+ *
57
+ * Concurrency lock: concurrent cache-miss requests share a single in-flight computation
58
+ * rather than each independently recomputing the full index.
59
+ *
60
+ * @param embedFn - Injectable embed function (defaults to module embedText; override in tests).
61
+ */
62
+ export declare function getInstructionEmbeddings(instructions: InstructionEntry[], indexHash: string, embeddingPath: string, modelName: string, cacheDir: string, device?: string, localOnly?: boolean, embedFn?: EmbedFn): Promise<Record<string, Float32Array>>;
@@ -0,0 +1,259 @@
1
+ "use strict";
2
+ /**
3
+ * Embedding Service for Semantic Search
4
+ *
5
+ * Lazy-loaded embedding model — zero startup cost.
6
+ * Model is loaded only on first embedText() call via dynamic import.
7
+ * Vectors cached to disk for cross-instance sharing.
8
+ *
9
+ * Key design:
10
+ * - cosineSimilarity, isStale, load/saveCachedEmbeddings are pure functions (no model needed)
11
+ * - embedText and getInstructionEmbeddings trigger lazy model load
12
+ * - Uses @huggingface/transformers (optional dep) via dynamic ESM import
13
+ */
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.cosineSimilarity = cosineSimilarity;
19
+ exports.isStale = isStale;
20
+ exports.loadCachedEmbeddings = loadCachedEmbeddings;
21
+ exports.saveCachedEmbeddings = saveCachedEmbeddings;
22
+ exports.embedText = embedText;
23
+ exports.getInstructionEmbeddings = getInstructionEmbeddings;
24
+ const fs_1 = __importDefault(require("fs"));
25
+ const path_1 = __importDefault(require("path"));
26
+ const logger_1 = require("./logger");
27
+ // Lazy model state — never loaded at import time
28
+ let pipeline = null;
29
+ let extractor = null;
30
+ let modelLoading = null;
31
+ // Concurrency lock for index embedding computation — prevents N concurrent cache-miss
32
+ // requests from each independently computing embeddings for all index entries.
33
+ let indexEmbeddingComputing = null;
34
+ /**
35
+ * Cosine similarity between two vectors.
36
+ * Pure math — no dependencies, no model needed.
37
+ */
38
+ function cosineSimilarity(a, b) {
39
+ let dot = 0;
40
+ let normA = 0;
41
+ let normB = 0;
42
+ for (let i = 0; i < a.length; i++) {
43
+ dot += a[i] * b[i];
44
+ normA += a[i] * a[i];
45
+ normB += b[i] * b[i];
46
+ }
47
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
48
+ if (denom === 0)
49
+ return 0;
50
+ return dot / denom;
51
+ }
52
+ /**
53
+ * Check if cached embeddings are stale (index has changed since last embed).
54
+ */
55
+ function isStale(indexHash, embeddingHash) {
56
+ return indexHash !== embeddingHash;
57
+ }
58
+ /**
59
+ * Load cached embeddings from disk.
60
+ * Returns null if file doesn't exist or is invalid.
61
+ */
62
+ function loadCachedEmbeddings(filePath) {
63
+ try {
64
+ if (!fs_1.default.existsSync(filePath))
65
+ return null;
66
+ const raw = fs_1.default.readFileSync(filePath, 'utf-8');
67
+ const data = JSON.parse(raw);
68
+ if (!data || typeof data.indexHash !== 'string' || typeof data.embeddings !== 'object')
69
+ return null;
70
+ return data;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ /**
77
+ * Save embeddings to disk for cross-instance sharing.
78
+ */
79
+ function saveCachedEmbeddings(filePath, data) {
80
+ const dir = path_1.default.dirname(filePath);
81
+ if (!fs_1.default.existsSync(dir)) {
82
+ fs_1.default.mkdirSync(dir, { recursive: true });
83
+ }
84
+ fs_1.default.writeFileSync(filePath, JSON.stringify(data), 'utf-8');
85
+ }
86
+ // Helper: dynamic ESM import (same pattern as sdkServer.ts)
87
+ const dynamicImport = (specifier) => (Function('m', 'return import(m);'))(specifier);
88
+ /**
89
+ * Lazily initialize the embedding model.
90
+ * Only called on first semantic search request — never at import/startup time.
91
+ *
92
+ * @param device - 'cpu' (default WASM), 'cuda' (NVIDIA GPU), 'dml' (DirectML/Windows GPU)
93
+ * @param localOnly - When true, disables remote model downloads (model must already be cached)
94
+ */
95
+ async function ensureModel(modelName, cacheDir, device = 'cpu', localOnly = false) {
96
+ if (extractor) {
97
+ (0, logger_1.logInfo)('[embeddingService] Embedding model already loaded, skipping init');
98
+ return;
99
+ }
100
+ if (modelLoading) {
101
+ (0, logger_1.logInfo)('[embeddingService] Embedding model load in progress, waiting...');
102
+ await modelLoading;
103
+ return;
104
+ }
105
+ modelLoading = (async () => {
106
+ try {
107
+ // Validate requested device against available ONNX Runtime providers
108
+ const resolvedDevice = await resolveDevice(device);
109
+ (0, logger_1.logInfo)(`[embeddingService] Loading embedding model: ${modelName} (device=${resolvedDevice}, localOnly=${localOnly})`);
110
+ const transformers = await dynamicImport('@huggingface/transformers');
111
+ // Apply localOnly setting — block remote downloads when set
112
+ if (localOnly && transformers.env) {
113
+ transformers.env.allowRemoteModels = false;
114
+ }
115
+ pipeline = transformers.pipeline;
116
+ const pipelineOpts = {
117
+ cache_dir: cacheDir,
118
+ quantized: true,
119
+ };
120
+ // Set device: 'cpu' uses default WASM; 'cuda'/'dml' use GPU execution providers
121
+ if (resolvedDevice !== 'cpu') {
122
+ pipelineOpts.device = resolvedDevice;
123
+ }
124
+ extractor = await pipeline('feature-extraction', modelName, pipelineOpts);
125
+ (0, logger_1.logInfo)(`[embeddingService] Embedding model loaded successfully (device=${resolvedDevice})`);
126
+ }
127
+ catch (err) {
128
+ modelLoading = null;
129
+ throw err;
130
+ }
131
+ })();
132
+ await modelLoading;
133
+ }
134
+ /**
135
+ * Check available ONNX Runtime execution providers and resolve the best device.
136
+ * Falls back to dml → cpu if the requested provider is not available.
137
+ */
138
+ async function resolveDevice(requested) {
139
+ if (requested === 'cpu')
140
+ return 'cpu';
141
+ try {
142
+ const ort = await dynamicImport('onnxruntime-node');
143
+ if (typeof ort.listSupportedBackends === 'function') {
144
+ const backends = ort.listSupportedBackends();
145
+ const available = backends.map((b) => b.name);
146
+ (0, logger_1.logInfo)(`[embeddingService] ONNX Runtime backends available: [${available.join(', ')}]`);
147
+ if (available.includes(requested))
148
+ return requested;
149
+ // Requested provider not available — try fallback chain
150
+ if (requested === 'cuda' && available.includes('dml')) {
151
+ (0, logger_1.logWarn)(`[embeddingService] CUDA provider not available (onnxruntime-node does not bundle CUDA). Falling back to DML.`);
152
+ (0, logger_1.logWarn)(`[embeddingService] To enable CUDA: install CUDA Toolkit + cuDNN, then copy onnxruntime_providers_cuda.dll into node_modules/onnxruntime-node/bin/`);
153
+ return 'dml';
154
+ }
155
+ (0, logger_1.logWarn)(`[embeddingService] ${requested} provider not available. Available: [${available.join(', ')}]. Falling back to cpu.`);
156
+ return 'cpu';
157
+ }
158
+ }
159
+ catch {
160
+ (0, logger_1.logWarn)(`[embeddingService] Could not probe ONNX Runtime backends; using requested device '${requested}' as-is.`);
161
+ }
162
+ return requested;
163
+ }
164
+ /**
165
+ * Embed a single text string into a vector.
166
+ * Triggers lazy model loading on first call.
167
+ */
168
+ async function embedText(text, modelName, cacheDir, device = 'cpu', localOnly = false) {
169
+ const start = performance.now();
170
+ await ensureModel(modelName, cacheDir, device, localOnly);
171
+ const output = await extractor(text, { pooling: 'mean', normalize: true });
172
+ const vec = new Float32Array(output.data);
173
+ (0, logger_1.logInfo)(`[embeddingService] embedText completed in ${(performance.now() - start).toFixed(1)}ms (${text.substring(0, 60)}${text.length > 60 ? '...' : ''})`);
174
+ return vec;
175
+ }
176
+ /**
177
+ * Get or compute embeddings for all index instructions.
178
+ * Uses disk cache when available and fresh.
179
+ *
180
+ * Incremental update: when the index hash changes (instructions added/modified),
181
+ * only entries whose sourceHash differs from the cached value are recomputed.
182
+ * This reduces cold-recompute from O(all entries) to O(delta entries).
183
+ *
184
+ * Concurrency lock: concurrent cache-miss requests share a single in-flight computation
185
+ * rather than each independently recomputing the full index.
186
+ *
187
+ * @param embedFn - Injectable embed function (defaults to module embedText; override in tests).
188
+ */
189
+ async function getInstructionEmbeddings(instructions, indexHash, embeddingPath, modelName, cacheDir, device = 'cpu', localOnly = false, embedFn = embedText) {
190
+ // Full cache hit: same index hash and model — return immediately without locking.
191
+ const cached = loadCachedEmbeddings(embeddingPath);
192
+ if (cached && !isStale(indexHash, cached.indexHash) && cached.modelName === modelName) {
193
+ const entryCount = Object.keys(cached.embeddings).length;
194
+ (0, logger_1.logInfo)(`[embeddingService] Embedding cache HIT: ${entryCount} entries from ${embeddingPath} (model=${modelName})`);
195
+ const result = {};
196
+ for (const [id, vec] of Object.entries(cached.embeddings)) {
197
+ result[id] = new Float32Array(vec);
198
+ }
199
+ return result;
200
+ }
201
+ // Concurrency lock: if another call is already computing, wait for it.
202
+ if (indexEmbeddingComputing) {
203
+ (0, logger_1.logInfo)('[embeddingService] Embedding computation already in progress, waiting...');
204
+ return await indexEmbeddingComputing;
205
+ }
206
+ // Model changed -> cannot reuse any cached entries.
207
+ const modelChanged = !!cached && cached.modelName !== modelName;
208
+ const existingEmbeddings = (!modelChanged && cached?.embeddings) ? cached.embeddings : {};
209
+ const existingHashes = (!modelChanged && cached?.entryHashes) ? cached.entryHashes : {};
210
+ // Determine which entries need (re)computation.
211
+ const currentIds = new Set(instructions.map(i => i.id));
212
+ const toCompute = instructions.filter(inst => {
213
+ const cachedHash = existingHashes[inst.id];
214
+ return !cachedHash || cachedHash !== inst.sourceHash || !existingEmbeddings[inst.id];
215
+ });
216
+ const reuseCount = instructions.length - toCompute.length;
217
+ const missReason = !cached ? 'no cache'
218
+ : modelChanged ? `model changed (${cached.modelName} -> ${modelName})`
219
+ : toCompute.length === instructions.length ? 'index stale (no hashes to reuse)'
220
+ : `incremental (${toCompute.length} new/changed, ${reuseCount} reused)`;
221
+ (0, logger_1.logInfo)(`[embeddingService] Embedding cache MISS (${missReason}). Computing embeddings for ${toCompute.length}/${instructions.length} instructions`);
222
+ indexEmbeddingComputing = (async () => {
223
+ try {
224
+ const embeddings = { ...existingEmbeddings };
225
+ const entryHashes = { ...existingHashes };
226
+ for (const inst of toCompute) {
227
+ const text = `${inst.title} ${inst.semanticSummary || inst.body}`;
228
+ embeddings[inst.id] = Array.from(await embedFn(text, modelName, cacheDir, device, localOnly));
229
+ if (inst.sourceHash)
230
+ entryHashes[inst.id] = inst.sourceHash;
231
+ }
232
+ // Prune deleted instructions from cache.
233
+ for (const id of Object.keys(embeddings)) {
234
+ if (!currentIds.has(id)) {
235
+ delete embeddings[id];
236
+ delete entryHashes[id];
237
+ }
238
+ }
239
+ // Persist updated cache.
240
+ try {
241
+ saveCachedEmbeddings(embeddingPath, { indexHash, modelName, entryHashes, embeddings });
242
+ (0, logger_1.logInfo)('[embeddingService] Embeddings cached to disk');
243
+ }
244
+ catch (err) {
245
+ (0, logger_1.logWarn)(`[embeddingService] Failed to cache embeddings: ${err instanceof Error ? err.message : 'unknown'}`);
246
+ }
247
+ // Return as Float32Arrays.
248
+ const result = {};
249
+ for (const [id, vec] of Object.entries(embeddings)) {
250
+ result[id] = new Float32Array(vec);
251
+ }
252
+ return result;
253
+ }
254
+ finally {
255
+ indexEmbeddingComputing = null;
256
+ }
257
+ })();
258
+ return await indexEmbeddingComputing;
259
+ }
@@ -0,0 +1,22 @@
1
+ export interface SemanticRpcErrorShape<TData extends Record<string, unknown> | undefined = Record<string, unknown>> {
2
+ code: number;
3
+ message: string;
4
+ data: TData;
5
+ __semantic: true;
6
+ }
7
+ /**
8
+ * Throw a structured JSON-RPC-compatible semantic error object.
9
+ * The thrown value is a plain object (not an Error instance) so that downstream
10
+ * serialization layers can pass it through without losing custom properties.
11
+ * @param code - JSON-RPC error code (e.g. -32602 for invalid params)
12
+ * @param message - Human-readable error message
13
+ * @param data - Optional additional data attached to the error
14
+ * @throws Always throws the constructed {@link SemanticRpcErrorShape}
15
+ */
16
+ export declare function semanticError<TData extends Record<string, unknown> | undefined = Record<string, unknown>>(code: number, message: string, data?: TData): never;
17
+ /**
18
+ * Type-guard that tests whether an unknown value is a semantic RPC error object.
19
+ * @param e - Value to inspect
20
+ * @returns `true` if `e` is a {@link SemanticRpcErrorShape}, `false` otherwise
21
+ */
22
+ export declare function isSemanticError(e: unknown): e is SemanticRpcErrorShape<Record<string, unknown>>;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.semanticError = semanticError;
4
+ exports.isSemanticError = isSemanticError;
5
+ /**
6
+ * Throw a structured JSON-RPC-compatible semantic error object.
7
+ * The thrown value is a plain object (not an Error instance) so that downstream
8
+ * serialization layers can pass it through without losing custom properties.
9
+ * @param code - JSON-RPC error code (e.g. -32602 for invalid params)
10
+ * @param message - Human-readable error message
11
+ * @param data - Optional additional data attached to the error
12
+ * @throws Always throws the constructed {@link SemanticRpcErrorShape}
13
+ */
14
+ function semanticError(code, message, data) {
15
+ const err = { code, message, data: (data === undefined ? {} : data), __semantic: true };
16
+ // Throw plain object so downstream passes through as-is.
17
+ // (Stack trace not required for semantic validation errors.)
18
+ // eslint-disable-next-line no-throw-literal
19
+ throw err;
20
+ }
21
+ /**
22
+ * Type-guard that tests whether an unknown value is a semantic RPC error object.
23
+ * @param e - Value to inspect
24
+ * @returns `true` if `e` is a {@link SemanticRpcErrorShape}, `false` otherwise
25
+ */
26
+ function isSemanticError(e) {
27
+ if (!e || typeof e !== 'object')
28
+ return false;
29
+ const maybe = e;
30
+ return maybe.__semantic === true && Number.isSafeInteger(maybe.code) && typeof maybe.message === 'string';
31
+ }
@@ -0,0 +1,25 @@
1
+ export type FeatureFlag = 'response_envelope_v1' | 'tools_extended' | 'tools_admin';
2
+ interface FlagConfig {
3
+ [k: string]: boolean;
4
+ }
5
+ /**
6
+ * Check whether a feature flag is currently enabled.
7
+ * @param flag - Feature flag name to evaluate
8
+ * @returns `true` if the flag is enabled, `false` otherwise
9
+ */
10
+ export declare function flagEnabled(flag: FeatureFlag): boolean;
11
+ /** Return a shallow copy of the current flag configuration map.
12
+ * @returns Object mapping flag names to their boolean values
13
+ */
14
+ export declare function dumpFlags(): {
15
+ [k: string]: boolean;
16
+ };
17
+ /**
18
+ * Replace the in-memory flag cache and persist the new values to the flags file.
19
+ * @param newFlags - Complete flag configuration to apply
20
+ * @returns Shallow copy of the resulting flag configuration after the update
21
+ */
22
+ export declare function updateFlags(newFlags: FlagConfig): {
23
+ [k: string]: boolean;
24
+ };
25
+ export {};
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.flagEnabled = flagEnabled;
7
+ exports.dumpFlags = dumpFlags;
8
+ exports.updateFlags = updateFlags;
9
+ // Simple feature flag loader: environment variables + optional JSON file.
10
+ // Precedence: explicit env var (INDEX_SERVER_FLAG_<UPPER>) > JSON file > default (false)
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const runtimeConfig_1 = require("../config/runtimeConfig");
14
+ let cache = null;
15
+ let lastFilePath = null;
16
+ let lastConfigIdentity = null;
17
+ function ensureConfigSync() {
18
+ const cfg = (0, runtimeConfig_1.getRuntimeConfig)();
19
+ if (lastConfigIdentity !== cfg) {
20
+ cache = null;
21
+ lastFilePath = null;
22
+ lastConfigIdentity = cfg;
23
+ }
24
+ return cfg;
25
+ }
26
+ function loadFile() {
27
+ const cfg = ensureConfigSync();
28
+ const file = cfg.featureFlags.file || path_1.default.join(process.cwd(), 'flags.json');
29
+ lastFilePath = file;
30
+ if (!fs_1.default.existsSync(file))
31
+ return {};
32
+ try {
33
+ const raw = JSON.parse(fs_1.default.readFileSync(file, 'utf8'));
34
+ if (raw && typeof raw === 'object') {
35
+ const out = {};
36
+ for (const [k, v] of Object.entries(raw)) {
37
+ if (typeof v === 'boolean')
38
+ out[k] = v;
39
+ }
40
+ return out;
41
+ }
42
+ }
43
+ catch { /* ignore */ }
44
+ return {};
45
+ }
46
+ function load() {
47
+ const cfg = ensureConfigSync();
48
+ if (cache)
49
+ return cache;
50
+ const base = loadFile();
51
+ // Overlay env-derived namespace captured in runtime config
52
+ for (const [flagName, rawValue] of Object.entries(cfg.featureFlags.envNamespace)) {
53
+ const v = String(rawValue).toLowerCase();
54
+ if (['1', 'true', 'yes', 'on', 'enabled'].includes(v))
55
+ base[flagName] = true;
56
+ else if (['0', 'false', 'no', 'off', 'disabled'].includes(v))
57
+ base[flagName] = false;
58
+ }
59
+ cache = base;
60
+ return cache;
61
+ }
62
+ /**
63
+ * Check whether a feature flag is currently enabled.
64
+ * @param flag - Feature flag name to evaluate
65
+ * @returns `true` if the flag is enabled, `false` otherwise
66
+ */
67
+ function flagEnabled(flag) {
68
+ const cfg = load();
69
+ return !!cfg[flag];
70
+ }
71
+ /** Return a shallow copy of the current flag configuration map.
72
+ * @returns Object mapping flag names to their boolean values
73
+ */
74
+ function dumpFlags() { return { ...load() }; }
75
+ /**
76
+ * Replace the in-memory flag cache and persist the new values to the flags file.
77
+ * @param newFlags - Complete flag configuration to apply
78
+ * @returns Shallow copy of the resulting flag configuration after the update
79
+ */
80
+ function updateFlags(newFlags) {
81
+ cache = { ...newFlags };
82
+ try {
83
+ const cfg = ensureConfigSync();
84
+ const file = lastFilePath || cfg.featureFlags.file || path_1.default.join(process.cwd(), 'flags.json');
85
+ fs_1.default.writeFileSync(file, JSON.stringify(cache, null, 2));
86
+ }
87
+ catch { /* ignore write errors */ }
88
+ return dumpFlags();
89
+ }
@@ -0,0 +1,13 @@
1
+ export declare function hasFeature(name: string): boolean;
2
+ export declare function incrementCounter(name: string, by?: number): void;
3
+ export declare function getCounters(): {
4
+ [x: string]: number;
5
+ };
6
+ export declare function featureStatus(): {
7
+ features: string[];
8
+ counters: {
9
+ [x: string]: number;
10
+ };
11
+ env: string[];
12
+ };
13
+ export declare function enableFeature(name: string): void;