@harperfast/harper 5.2.0-beta.4 → 5.2.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 (320) hide show
  1. package/bin/backup.ts +169 -0
  2. package/bin/cliOperations.ts +92 -73
  3. package/bin/copyDb.ts +21 -4
  4. package/bin/harper.ts +43 -55
  5. package/bin/help.ts +216 -0
  6. package/components/Application.ts +236 -46
  7. package/components/ApplicationScope.ts +26 -0
  8. package/components/EntryHandler.ts +410 -105
  9. package/components/RuntimeModuleTracker.ts +189 -0
  10. package/components/Scope.ts +120 -30
  11. package/components/componentLoader.ts +177 -25
  12. package/components/deployLifecycle.ts +119 -33
  13. package/components/mcp/toolRegistry.ts +10 -0
  14. package/components/mcp/tools/application.ts +12 -5
  15. package/components/mcp/tools/operations.ts +9 -0
  16. package/components/mcp/tools/schemas/operationDescriptions.ts +3 -0
  17. package/components/mcp/tools/schemas/operations.ts +9 -0
  18. package/components/operations.js +5 -6
  19. package/components/operationsValidation.js +32 -2
  20. package/components/scopeMount.ts +150 -0
  21. package/config/configUtils.ts +12 -9
  22. package/config-root.schema.json +14 -0
  23. package/dataLayer/backupManifest.ts +102 -0
  24. package/dataLayer/blobBackup.ts +286 -0
  25. package/dataLayer/harperBridge/ResourceBridge.ts +69 -5
  26. package/dataLayer/hdbInfoController.ts +8 -0
  27. package/dataLayer/restoreMarker.ts +276 -0
  28. package/dataLayer/rocksdbBackup.ts +1100 -0
  29. package/dataLayer/schemaDescribe.ts +2 -1
  30. package/dist/bin/backup.d.ts +9 -0
  31. package/dist/bin/backup.js +192 -0
  32. package/dist/bin/backup.js.map +1 -0
  33. package/dist/bin/cliOperations.d.ts +13 -0
  34. package/dist/bin/cliOperations.js +89 -70
  35. package/dist/bin/cliOperations.js.map +1 -1
  36. package/dist/bin/copyDb.js +13 -2
  37. package/dist/bin/copyDb.js.map +1 -1
  38. package/dist/bin/harper.d.ts +13 -0
  39. package/dist/bin/harper.js +45 -56
  40. package/dist/bin/harper.js.map +1 -1
  41. package/dist/bin/help.d.ts +8 -0
  42. package/dist/bin/help.js +192 -0
  43. package/dist/bin/help.js.map +1 -0
  44. package/dist/components/Application.d.ts +16 -1
  45. package/dist/components/Application.js +210 -38
  46. package/dist/components/Application.js.map +1 -1
  47. package/dist/components/ApplicationScope.d.ts +7 -0
  48. package/dist/components/ApplicationScope.js +22 -0
  49. package/dist/components/ApplicationScope.js.map +1 -1
  50. package/dist/components/EntryHandler.d.ts +4 -4
  51. package/dist/components/EntryHandler.js +386 -95
  52. package/dist/components/EntryHandler.js.map +1 -1
  53. package/dist/components/RuntimeModuleTracker.d.ts +11 -0
  54. package/dist/components/RuntimeModuleTracker.js +189 -0
  55. package/dist/components/RuntimeModuleTracker.js.map +1 -0
  56. package/dist/components/Scope.d.ts +38 -1
  57. package/dist/components/Scope.js +117 -28
  58. package/dist/components/Scope.js.map +1 -1
  59. package/dist/components/componentLoader.d.ts +2 -6
  60. package/dist/components/componentLoader.js +160 -18
  61. package/dist/components/componentLoader.js.map +1 -1
  62. package/dist/components/deployLifecycle.d.ts +6 -2
  63. package/dist/components/deployLifecycle.js +109 -31
  64. package/dist/components/deployLifecycle.js.map +1 -1
  65. package/dist/components/mcp/toolRegistry.d.ts +7 -0
  66. package/dist/components/mcp/toolRegistry.js +10 -0
  67. package/dist/components/mcp/toolRegistry.js.map +1 -1
  68. package/dist/components/mcp/tools/application.js +11 -5
  69. package/dist/components/mcp/tools/application.js.map +1 -1
  70. package/dist/components/mcp/tools/operations.js +9 -0
  71. package/dist/components/mcp/tools/operations.js.map +1 -1
  72. package/dist/components/mcp/tools/schemas/operationDescriptions.js +2 -0
  73. package/dist/components/mcp/tools/schemas/operationDescriptions.js.map +1 -1
  74. package/dist/components/mcp/tools/schemas/operations.js +9 -0
  75. package/dist/components/mcp/tools/schemas/operations.js.map +1 -1
  76. package/dist/components/operations.js +6 -6
  77. package/dist/components/operations.js.map +1 -1
  78. package/dist/components/operationsValidation.js +34 -2
  79. package/dist/components/operationsValidation.js.map +1 -1
  80. package/dist/components/scopeMount.d.ts +86 -0
  81. package/dist/components/scopeMount.js +131 -0
  82. package/dist/components/scopeMount.js.map +1 -0
  83. package/dist/config/configUtils.js +13 -9
  84. package/dist/config/configUtils.js.map +1 -1
  85. package/dist/dataLayer/backupManifest.d.ts +26 -0
  86. package/dist/dataLayer/backupManifest.js +97 -0
  87. package/dist/dataLayer/backupManifest.js.map +1 -0
  88. package/dist/dataLayer/blobBackup.d.ts +87 -0
  89. package/dist/dataLayer/blobBackup.js +282 -0
  90. package/dist/dataLayer/blobBackup.js.map +1 -0
  91. package/dist/dataLayer/harperBridge/ResourceBridge.d.ts +3 -0
  92. package/dist/dataLayer/harperBridge/ResourceBridge.js +45 -5
  93. package/dist/dataLayer/harperBridge/ResourceBridge.js.map +1 -1
  94. package/dist/dataLayer/hdbInfoController.js +4 -0
  95. package/dist/dataLayer/hdbInfoController.js.map +1 -1
  96. package/dist/dataLayer/restoreMarker.d.ts +122 -0
  97. package/dist/dataLayer/restoreMarker.js +261 -0
  98. package/dist/dataLayer/restoreMarker.js.map +1 -0
  99. package/dist/dataLayer/rocksdbBackup.d.ts +127 -0
  100. package/dist/dataLayer/rocksdbBackup.js +1039 -0
  101. package/dist/dataLayer/rocksdbBackup.js.map +1 -0
  102. package/dist/dataLayer/schemaDescribe.js +2 -1
  103. package/dist/dataLayer/schemaDescribe.js.map +1 -1
  104. package/dist/resources/DatabaseTransaction.d.ts +55 -0
  105. package/dist/resources/DatabaseTransaction.js +282 -109
  106. package/dist/resources/DatabaseTransaction.js.map +1 -1
  107. package/dist/resources/ResourceInterface.d.ts +8 -5
  108. package/dist/resources/ResourceInterface.js.map +1 -1
  109. package/dist/resources/Resources.js +22 -4
  110. package/dist/resources/Resources.js.map +1 -1
  111. package/dist/resources/Table.d.ts +6 -5
  112. package/dist/resources/Table.js +114 -37
  113. package/dist/resources/Table.js.map +1 -1
  114. package/dist/resources/analytics/write.js +6 -6
  115. package/dist/resources/analytics/write.js.map +1 -1
  116. package/dist/resources/blob.d.ts +8 -1
  117. package/dist/resources/blob.js +31 -14
  118. package/dist/resources/blob.js.map +1 -1
  119. package/dist/resources/databases.d.ts +59 -1
  120. package/dist/resources/databases.js +386 -41
  121. package/dist/resources/databases.js.map +1 -1
  122. package/dist/resources/jsResource.d.ts +4 -26
  123. package/dist/resources/jsResource.js +5 -59
  124. package/dist/resources/jsResource.js.map +1 -1
  125. package/dist/resources/models/Models.d.ts +11 -1
  126. package/dist/resources/models/Models.js +10 -1
  127. package/dist/resources/models/Models.js.map +1 -1
  128. package/dist/resources/models/backendRegistry.d.ts +9 -0
  129. package/dist/resources/models/backendRegistry.js +10 -0
  130. package/dist/resources/models/backendRegistry.js.map +1 -1
  131. package/dist/resources/models/openaiStream.d.ts +16 -1
  132. package/dist/resources/models/openaiStream.js +113 -21
  133. package/dist/resources/models/openaiStream.js.map +1 -1
  134. package/dist/resources/models/v1/chatCompletions.d.ts +54 -0
  135. package/dist/resources/models/v1/chatCompletions.js +115 -0
  136. package/dist/resources/models/v1/chatCompletions.js.map +1 -0
  137. package/dist/resources/models/v1/embeddings.d.ts +11 -0
  138. package/dist/resources/models/v1/embeddings.js +71 -0
  139. package/dist/resources/models/v1/embeddings.js.map +1 -0
  140. package/dist/resources/models/v1/errors.d.ts +54 -0
  141. package/dist/resources/models/v1/errors.js +130 -0
  142. package/dist/resources/models/v1/errors.js.map +1 -0
  143. package/dist/resources/models/v1/index.d.ts +36 -0
  144. package/dist/resources/models/v1/index.js +75 -0
  145. package/dist/resources/models/v1/index.js.map +1 -0
  146. package/dist/resources/models/v1/models.d.ts +26 -0
  147. package/dist/resources/models/v1/models.js +44 -0
  148. package/dist/resources/models/v1/models.js.map +1 -0
  149. package/dist/resources/models/v1/translation.d.ts +133 -0
  150. package/dist/resources/models/v1/translation.js +298 -0
  151. package/dist/resources/models/v1/translation.js.map +1 -0
  152. package/dist/resources/roles.d.ts +1 -1
  153. package/dist/resources/roles.js +54 -7
  154. package/dist/resources/roles.js.map +1 -1
  155. package/dist/resources/transaction.js +0 -3
  156. package/dist/resources/transaction.js.map +1 -1
  157. package/dist/security/jsLoader.js +84 -33
  158. package/dist/security/jsLoader.js.map +1 -1
  159. package/dist/security/role.js +4 -0
  160. package/dist/security/role.js.map +1 -1
  161. package/dist/security/superUserGuard.d.ts +7 -0
  162. package/dist/security/superUserGuard.js +23 -0
  163. package/dist/security/superUserGuard.js.map +1 -0
  164. package/dist/security/tokenAuthentication.d.ts +0 -1
  165. package/dist/security/tokenAuthentication.js +6 -2
  166. package/dist/security/tokenAuthentication.js.map +1 -1
  167. package/dist/security/user.d.ts +6 -1
  168. package/dist/security/user.js +23 -1
  169. package/dist/security/user.js.map +1 -1
  170. package/dist/server/REST.js +25 -9
  171. package/dist/server/REST.js.map +1 -1
  172. package/dist/server/fastifyRoutes.js +15 -1
  173. package/dist/server/fastifyRoutes.js.map +1 -1
  174. package/dist/server/http.d.ts +23 -2
  175. package/dist/server/http.js +99 -12
  176. package/dist/server/http.js.map +1 -1
  177. package/dist/server/itc/serverHandlers.js +7 -1
  178. package/dist/server/itc/serverHandlers.js.map +1 -1
  179. package/dist/server/jobs/jobProcess.js +20 -1
  180. package/dist/server/jobs/jobProcess.js.map +1 -1
  181. package/dist/server/jobs/jobRunner.js +10 -0
  182. package/dist/server/jobs/jobRunner.js.map +1 -1
  183. package/dist/server/jobs/jobs.js +11 -0
  184. package/dist/server/jobs/jobs.js.map +1 -1
  185. package/dist/server/middlewareChain.d.ts +10 -1
  186. package/dist/server/middlewareChain.js +81 -21
  187. package/dist/server/middlewareChain.js.map +1 -1
  188. package/dist/server/operationsServer.d.ts +0 -2
  189. package/dist/server/operationsServer.js.map +1 -1
  190. package/dist/server/serverHelpers/multipartParser.js +9 -0
  191. package/dist/server/serverHelpers/multipartParser.js.map +1 -1
  192. package/dist/server/serverHelpers/operationAuthorizationState.d.ts +2 -0
  193. package/dist/server/serverHelpers/operationAuthorizationState.js +13 -0
  194. package/dist/server/serverHelpers/operationAuthorizationState.js.map +1 -0
  195. package/dist/server/serverHelpers/registeredOperations.d.ts +3 -2
  196. package/dist/server/serverHelpers/registeredOperations.js +14 -13
  197. package/dist/server/serverHelpers/registeredOperations.js.map +1 -1
  198. package/dist/server/serverHelpers/serverHandlers.js +27 -7
  199. package/dist/server/serverHelpers/serverHandlers.js.map +1 -1
  200. package/dist/server/serverHelpers/serverUtilities.d.ts +1 -1
  201. package/dist/server/serverHelpers/serverUtilities.js +21 -7
  202. package/dist/server/serverHelpers/serverUtilities.js.map +1 -1
  203. package/dist/server/static.js +68 -21
  204. package/dist/server/static.js.map +1 -1
  205. package/dist/server/storageReclamation.d.ts +17 -0
  206. package/dist/server/storageReclamation.js +90 -6
  207. package/dist/server/storageReclamation.js.map +1 -1
  208. package/dist/server/threads/socketRouter.js +20 -0
  209. package/dist/server/threads/socketRouter.js.map +1 -1
  210. package/dist/server/threads/threadServer.js +12 -0
  211. package/dist/server/threads/threadServer.js.map +1 -1
  212. package/dist/sqlEngine/diff/differential.js +7 -3
  213. package/dist/sqlEngine/diff/differential.js.map +1 -1
  214. package/dist/sqlTranslator/index.js +6 -1
  215. package/dist/sqlTranslator/index.js.map +1 -1
  216. package/dist/upgrade/upgradePrompt.d.ts +2 -2
  217. package/dist/upgrade/upgradePrompt.js +22 -3
  218. package/dist/upgrade/upgradePrompt.js.map +1 -1
  219. package/dist/utility/OperationFunctionCaller.js +25 -6
  220. package/dist/utility/OperationFunctionCaller.js.map +1 -1
  221. package/dist/utility/errors/commonErrors.d.ts +1 -0
  222. package/dist/utility/errors/commonErrors.js +1 -0
  223. package/dist/utility/errors/commonErrors.js.map +1 -1
  224. package/dist/utility/hdbTerms.d.ts +13 -1
  225. package/dist/utility/hdbTerms.js +13 -1
  226. package/dist/utility/hdbTerms.js.map +1 -1
  227. package/dist/utility/install/installer.js +32 -0
  228. package/dist/utility/install/installer.js.map +1 -1
  229. package/dist/utility/logging/harper_logger.d.ts +47 -0
  230. package/dist/utility/logging/harper_logger.js +803 -38
  231. package/dist/utility/logging/harper_logger.js.map +1 -1
  232. package/dist/utility/operation_authorization.js +13 -3
  233. package/dist/utility/operation_authorization.js.map +1 -1
  234. package/npm-shrinkwrap.json +198 -193
  235. package/package.json +12 -7
  236. package/resources/DESIGN.md +2 -0
  237. package/resources/DatabaseTransaction.ts +310 -104
  238. package/resources/ResourceInterface.ts +8 -5
  239. package/resources/Resources.ts +22 -4
  240. package/resources/Table.ts +341 -263
  241. package/resources/analytics/write.ts +22 -20
  242. package/resources/blob.ts +31 -14
  243. package/resources/databases.ts +387 -46
  244. package/resources/jsResource.ts +5 -62
  245. package/resources/models/Models.ts +14 -1
  246. package/resources/models/backendRegistry.ts +10 -0
  247. package/resources/models/openaiStream.ts +131 -19
  248. package/resources/models/v1/chatCompletions.ts +128 -0
  249. package/resources/models/v1/embeddings.ts +70 -0
  250. package/resources/models/v1/errors.ts +141 -0
  251. package/resources/models/v1/index.ts +72 -0
  252. package/resources/models/v1/models.ts +53 -0
  253. package/resources/models/v1/translation.ts +362 -0
  254. package/resources/roles.ts +67 -7
  255. package/resources/transaction.ts +0 -3
  256. package/security/jsLoader.ts +84 -30
  257. package/security/role.ts +7 -0
  258. package/security/superUserGuard.ts +20 -0
  259. package/security/tokenAuthentication.ts +6 -3
  260. package/security/user.ts +26 -1
  261. package/server/DESIGN.md +61 -34
  262. package/server/REST.ts +25 -9
  263. package/server/fastifyRoutes.ts +20 -1
  264. package/server/http.ts +100 -13
  265. package/server/itc/serverHandlers.js +7 -1
  266. package/server/jobs/jobProcess.ts +18 -1
  267. package/server/jobs/jobRunner.ts +10 -0
  268. package/server/jobs/jobs.ts +11 -0
  269. package/server/middlewareChain.ts +79 -20
  270. package/server/operationsServer.ts +0 -2
  271. package/server/serverHelpers/multipartParser.ts +9 -0
  272. package/server/serverHelpers/operationAuthorizationState.ts +11 -0
  273. package/server/serverHelpers/registeredOperations.ts +19 -15
  274. package/server/serverHelpers/serverHandlers.js +28 -7
  275. package/server/serverHelpers/serverUtilities.ts +29 -7
  276. package/server/static.ts +87 -23
  277. package/server/storageReclamation.ts +104 -8
  278. package/server/threads/socketRouter.ts +20 -0
  279. package/server/threads/threadServer.js +11 -0
  280. package/sqlTranslator/index.ts +6 -1
  281. package/static/defaultConfig.yaml +3 -0
  282. package/studio/web/assets/{Chat-DK3GlWEb.js → Chat-aApwhRmz.js} +2 -2
  283. package/studio/web/assets/{Chat-DK3GlWEb.js.map → Chat-aApwhRmz.js.map} +1 -1
  284. package/studio/web/assets/{FloatingChat-fBcC1Ew_.js → FloatingChat-sC0H91n9.js} +4 -4
  285. package/studio/web/assets/{FloatingChat-fBcC1Ew_.js.map → FloatingChat-sC0H91n9.js.map} +1 -1
  286. package/studio/web/assets/{apiToken-DJo1nakA.js → apiToken-DZ8JhHOI.js} +2 -2
  287. package/studio/web/assets/{apiToken-DJo1nakA.js.map → apiToken-DZ8JhHOI.js.map} +1 -1
  288. package/studio/web/assets/{applications-BDfH8urd.js → applications-9SEVLIO5.js} +2 -2
  289. package/studio/web/assets/{applications-BDfH8urd.js.map → applications-9SEVLIO5.js.map} +1 -1
  290. package/studio/web/assets/{index-BHo3c2Gk.js → index-Dy3uDGXb.js} +6 -6
  291. package/studio/web/assets/index-Dy3uDGXb.js.map +1 -0
  292. package/studio/web/assets/{index.lazy-BTo0y6UM.js → index.lazy-CN1zq4I4.js} +4 -4
  293. package/studio/web/assets/{index.lazy-BTo0y6UM.js.map → index.lazy-CN1zq4I4.js.map} +1 -1
  294. package/studio/web/assets/{notifications-CMxvWNnz.js → notifications-BFAF07xr.js} +2 -2
  295. package/studio/web/assets/{notifications-CMxvWNnz.js.map → notifications-BFAF07xr.js.map} +1 -1
  296. package/studio/web/assets/{notifications-D3GoB26g.js → notifications-CKlYVvVN.js} +2 -2
  297. package/studio/web/assets/{notifications-D3GoB26g.js.map → notifications-CKlYVvVN.js.map} +1 -1
  298. package/studio/web/assets/{profile-Doj5FVDE.js → profile-A1zhEdFG.js} +2 -2
  299. package/studio/web/assets/{profile-Doj5FVDE.js.map → profile-A1zhEdFG.js.map} +1 -1
  300. package/studio/web/assets/{setComponentFile-yinsqJy0.js → setComponentFile-SEtBt_GV.js} +2 -2
  301. package/studio/web/assets/{setComponentFile-yinsqJy0.js.map → setComponentFile-SEtBt_GV.js.map} +1 -1
  302. package/studio/web/assets/{setup-DJwR0BHd.js → setup-BisINqdH.js} +2 -2
  303. package/studio/web/assets/{setup-DJwR0BHd.js.map → setup-BisINqdH.js.map} +1 -1
  304. package/studio/web/assets/{status-Br_AbsJs.js → status-BuQoCc7l.js} +2 -2
  305. package/studio/web/assets/{status-Br_AbsJs.js.map → status-BuQoCc7l.js.map} +1 -1
  306. package/studio/web/assets/{swagger-ui-react-02XH5sVf.js → swagger-ui-react-CAi_s1PC.js} +2 -2
  307. package/studio/web/assets/{swagger-ui-react-02XH5sVf.js.map → swagger-ui-react-CAi_s1PC.js.map} +1 -1
  308. package/studio/web/assets/{tsMode-D1DMKY7h.js → tsMode-DT74tlkM.js} +2 -2
  309. package/studio/web/assets/{tsMode-D1DMKY7h.js.map → tsMode-DT74tlkM.js.map} +1 -1
  310. package/studio/web/assets/{useEntityRestURL-DtRblRgw.js → useEntityRestURL-CGRGc1n7.js} +2 -2
  311. package/studio/web/assets/{useEntityRestURL-DtRblRgw.js.map → useEntityRestURL-CGRGc1n7.js.map} +1 -1
  312. package/studio/web/index.html +1 -1
  313. package/upgrade/upgradePrompt.ts +22 -3
  314. package/utility/OperationFunctionCaller.ts +24 -3
  315. package/utility/errors/commonErrors.ts +2 -0
  316. package/utility/hdbTerms.ts +13 -1
  317. package/utility/install/installer.ts +37 -0
  318. package/utility/logging/harper_logger.ts +786 -41
  319. package/utility/operation_authorization.ts +31 -3
  320. package/studio/web/assets/index-BHo3c2Gk.js.map +0 -1
@@ -91,6 +91,19 @@ export class Models implements ModelsContract {
91
91
  }
92
92
 
93
93
  async embed(input: string | string[], opts: EmbedOpts = {}): Promise<Float32Array[]> {
94
+ return (await this.embedWithUsage(input, opts)).vectors;
95
+ }
96
+
97
+ /**
98
+ * `embed()` plus the result-level `usage` the winning backend reported (all
99
+ * built-in embedding backends provide it). Internal path for callers that must
100
+ * surface usage on the wire — the `/v1/embeddings` gateway — without changing
101
+ * the public `embed()` contract. Not part of the stable models API.
102
+ */
103
+ async embedWithUsage(
104
+ input: string | string[],
105
+ opts: EmbedOpts = {}
106
+ ): Promise<{ vectors: Float32Array[]; usage?: TokenUsage }> {
94
107
  const { accounting, signal } = resolveCallContext(opts.signal);
95
108
  const startedAt = performance.now();
96
109
  const resolved = resolveCandidates('embedding', opts.model, buildRequires('embed', opts.requires, false));
@@ -118,7 +131,7 @@ export class Models implements ModelsContract {
118
131
  // success row followed by a failure row from the catch (duplicate).
119
132
  if (result.status !== 'completed') throw new ModelPendingNotSupportedError(backend.name);
120
133
  this.#record(backend, 'embed', opts.model, accounting, undefined, result, attemptStart);
121
- return result.output;
134
+ return { vectors: result.output, usage: result.usage };
122
135
  } catch (err) {
123
136
  this.#recordFailure(backend, 'embed', opts.model, accounting, undefined, attemptStart, err);
124
137
  if (!hasError) {
@@ -39,6 +39,16 @@ export function getBackend(kind: ModelKind, logicalName: string): ModelBackend |
39
39
  return (kind === 'embedding' ? embedding : generative).get(logicalName);
40
40
  }
41
41
 
42
+ /**
43
+ * Enumerate all registrations for `kind` as `{logicalName, backend}` pairs. Used by
44
+ * `GET /v1/models` (#631) to advertise selectable model names; `logicalName` is what a
45
+ * caller passes as `opts.model`, not the backend's own `.name`.
46
+ */
47
+ export function listBackends(kind: ModelKind): Array<{ logicalName: string; backend: ModelBackend }> {
48
+ const map = kind === 'embedding' ? embedding : generative;
49
+ return [...map.entries()].map(([logicalName, backend]) => ({ logicalName, backend }));
50
+ }
51
+
42
52
  /**
43
53
  * Resolve the embedding backend mapped to `logicalName` (default: `'default'`).
44
54
  * Throws `ModelBackendNotFoundError` if no backend is mapped.
@@ -21,6 +21,68 @@ export interface OpenAIStreamOptions {
21
21
  model?: string;
22
22
  /** Reuse a caller-supplied completion id across all chunks; one is generated when omitted. */
23
23
  id?: string;
24
+ /**
25
+ * Map a mid-stream backend error to an OpenAI error body for a final `data: {error}`
26
+ * SSE frame. Lets the v1 gateway reuse its `toOpenAIError` mapping without this generic
27
+ * formatter depending on the v1 layer. When omitted, a generic server_error body is emitted.
28
+ */
29
+ formatError?: (err: unknown) => OpenAIErrorFrameBody;
30
+ }
31
+
32
+ // Bounds on per-stream tool-call assembly. The backend supplies both the call ids and the
33
+ // argument fields, and this runs on a public HTTP path, so neither can be unbounded. Overflow
34
+ // terminates the stream through the same sanitized error-frame path as any backend failure.
35
+ const MAX_TOOL_CALLS_PER_STREAM = 256;
36
+ const MAX_TOOL_ARGUMENT_KEYS = 1024;
37
+ // Cumulative serialized-character budget across the WHOLE stream's assembly (ids, names,
38
+ // and every argument value as it arrives, plus per-entry JSON syntax so the count is an
39
+ // upper bound on `JSON.stringify(arguments)`, not just the raw content). Call/key counts
40
+ // alone don't bound memory — one key can hold an arbitrarily large value, and the final
41
+ // JSON.stringify duplicates the retained allocation — so the budget is charged per delta
42
+ // (O(delta), no re-serialization of the accumulator) and monotonically: replacing an
43
+ // existing key charges the new value too, so churn cannot smuggle unbounded values under
44
+ // a stable key count. The SSE frame that flushes the calls adds only a bounded constant
45
+ // envelope per call plus string-escaping of the arguments blob (< 2x), so the frame size
46
+ // is bounded by a small multiple of this budget.
47
+ const MAX_TOOL_ASSEMBLY_CHARS = 1_048_576;
48
+
49
+ /** Signals that a stream exceeded the tool-assembly bounds; surfaced as an SSE error frame. */
50
+ class ToolAssemblyOverflowError extends Error {
51
+ statusCode = 502;
52
+ }
53
+
54
+ /**
55
+ * Merge `source` into `target`, returning the keys added and the serialized characters
56
+ * charged. Charging over-approximates `JSON.stringify(target).length`: each first add
57
+ * charges the key plus 4 chars of JSON syntax (`"key":` quotes and colon, plus the
58
+ * comma/brace share), and every assignment — replacements included — charges the
59
+ * serialized value. Since a replacement's earlier charge is never refunded, the
60
+ * cumulative total stays an upper bound on the retained serialization while keeping
61
+ * accumulation O(delta), not O(total).
62
+ */
63
+ function assignCountingNewKeys(target: object, source: object): { addedKeys: number; addedChars: number } {
64
+ let addedKeys = 0;
65
+ let addedChars = 0;
66
+ for (const key in source) {
67
+ if (!(key in target)) {
68
+ addedKeys++;
69
+ addedChars += key.length + 4;
70
+ }
71
+ const value = (source as Record<string, unknown>)[key];
72
+ // `?? ''`: JSON.stringify returns undefined for undefined/function/symbol values —
73
+ // impossible from JSON.parse but reachable from a custom backend's crafted object.
74
+ addedChars += (JSON.stringify(value) ?? '').length;
75
+ (target as Record<string, unknown>)[key] = value;
76
+ }
77
+ return { addedKeys, addedChars };
78
+ }
79
+
80
+ /** OpenAI streaming error body (`{ message, type, code, param }` under an `error` key). */
81
+ export interface OpenAIErrorFrameBody {
82
+ message: string;
83
+ type: string;
84
+ code: string | null;
85
+ param: string | null;
24
86
  }
25
87
 
26
88
  interface OpenAIToolCallDelta {
@@ -46,7 +108,7 @@ interface OpenAIChunk {
46
108
 
47
109
  /** SSE message envelope consumed by Harper's `text/event-stream` serializer. */
48
110
  export interface OpenAIStreamMessage {
49
- data: OpenAIChunk | string;
111
+ data: OpenAIChunk | { error: OpenAIErrorFrameBody } | string;
50
112
  }
51
113
 
52
114
  /**
@@ -71,7 +133,8 @@ export async function* openaiStream(
71
133
  // Emitting incremental fragments would corrupt the OpenAI client's concatenation
72
134
  // (`{"a":1}` + `{"b":2}` → invalid JSON) — Harper's already-buffered upstream model
73
135
  // means we cannot faithfully reproduce per-token argument fragments anyway.
74
- const toolAssembly = new Map<string, { index: number; name?: string; arguments: object }>();
136
+ const toolAssembly = new Map<string, { index: number; name?: string; arguments: object; argumentCount: number }>();
137
+ let assemblyChars = 0;
75
138
 
76
139
  const chunk = (delta: OpenAIDelta, finish: OpenAIFinishReason | null): OpenAIStreamMessage => ({
77
140
  data: {
@@ -83,26 +146,75 @@ export async function* openaiStream(
83
146
  },
84
147
  });
85
148
 
86
- for await (const token of tokens) {
87
- if (token.deltaContent !== undefined) {
88
- const delta: OpenAIDelta = {};
89
- if (!roleSent) {
90
- delta.role = 'assistant';
91
- roleSent = true;
149
+ try {
150
+ for await (const token of tokens) {
151
+ if (token.deltaContent !== undefined) {
152
+ const delta: OpenAIDelta = {};
153
+ if (!roleSent) {
154
+ delta.role = 'assistant';
155
+ roleSent = true;
156
+ }
157
+ delta.content = token.deltaContent;
158
+ yield chunk(delta, null);
92
159
  }
93
- delta.content = token.deltaContent;
94
- yield chunk(delta, null);
95
- }
96
- if (token.deltaToolCalls) {
97
- for (const incoming of token.deltaToolCalls) {
98
- if (!incoming.id) continue;
99
- const existing = toolAssembly.get(incoming.id) ?? { index: toolAssembly.size, arguments: {} };
100
- if (incoming.name) existing.name = incoming.name;
101
- if (incoming.arguments) existing.arguments = { ...existing.arguments, ...incoming.arguments };
102
- toolAssembly.set(incoming.id, existing);
160
+ if (token.deltaToolCalls) {
161
+ for (const incoming of token.deltaToolCalls) {
162
+ if (!incoming.id) continue;
163
+ let existing = toolAssembly.get(incoming.id);
164
+ if (!existing) {
165
+ // Cap distinct calls per stream: ids come from the backend, and an
166
+ // unbounded map on a public HTTP path is a memory risk.
167
+ if (toolAssembly.size >= MAX_TOOL_CALLS_PER_STREAM) {
168
+ throw new ToolAssemblyOverflowError(`stream exceeded ${MAX_TOOL_CALLS_PER_STREAM} tool calls`);
169
+ }
170
+ // Null-prototype: arguments come from JSON.parse, so a field literally
171
+ // named `__proto__` is an own property. Object.assign uses [[Set]], which
172
+ // on an ordinary object would hit Object.prototype's inherited `__proto__`
173
+ // setter and silently drop the field (the previous spread did not).
174
+ existing = { index: toolAssembly.size, arguments: Object.create(null), argumentCount: 0 };
175
+ toolAssembly.set(incoming.id, existing);
176
+ // + 96: the flush frame's fixed per-call envelope (index/id/type/function
177
+ // syntax and the argument object's braces), so 256 calls of envelope are
178
+ // inside the budget too, not on top of it.
179
+ assemblyChars += incoming.id.length + 96;
180
+ }
181
+ if (incoming.name && incoming.name !== existing.name) {
182
+ assemblyChars += incoming.name.length;
183
+ existing.name = incoming.name;
184
+ }
185
+ // Guard the contract (`ToolCall.arguments` is an object): a string would be
186
+ // assigned index-wise, inflating the field count from characters.
187
+ if (incoming.arguments && typeof incoming.arguments === 'object') {
188
+ // Mutate rather than re-spread — spreading copied every previously
189
+ // accumulated property on each partial delta (O(n²) as fields grow) — and
190
+ // count only newly-introduced keys so the bound check stays O(delta) too.
191
+ const { addedKeys, addedChars } = assignCountingNewKeys(existing.arguments, incoming.arguments);
192
+ existing.argumentCount += addedKeys;
193
+ assemblyChars += addedChars;
194
+ if (existing.argumentCount > MAX_TOOL_ARGUMENT_KEYS) {
195
+ throw new ToolAssemblyOverflowError(`tool call arguments exceeded ${MAX_TOOL_ARGUMENT_KEYS} fields`);
196
+ }
197
+ }
198
+ if (assemblyChars > MAX_TOOL_ASSEMBLY_CHARS) {
199
+ throw new ToolAssemblyOverflowError(
200
+ `stream tool-call assembly exceeded ${MAX_TOOL_ASSEMBLY_CHARS} serialized characters`
201
+ );
202
+ }
203
+ }
103
204
  }
205
+ if (token.finishReason) finishReason = token.finishReason;
104
206
  }
105
- if (token.finishReason) finishReason = token.finishReason;
207
+ } catch (err) {
208
+ // The backend can throw partway through the stream (Models#wrapStream re-throws
209
+ // mid-stream backend errors). Headers/200 are already flushed, so this can't be an
210
+ // HTTP error status — emit a final OpenAI-shaped `data: {error}` frame so SDK clients
211
+ // see a parseable error (matching the non-streaming path) instead of an abrupt socket
212
+ // close. OpenAI terminates the stream on error and sends no `[DONE]`, so we do the same.
213
+ const error = opts.formatError
214
+ ? opts.formatError(err)
215
+ : { message: 'Internal server error', type: 'server_error', code: null, param: null };
216
+ yield { data: { error } };
217
+ return;
106
218
  }
107
219
 
108
220
  if (toolAssembly.size > 0) {
@@ -0,0 +1,128 @@
1
+ /**
2
+ * `POST /v1/chat/completions` — OpenAI-compatible chat endpoint (#631).
3
+ *
4
+ * SSE serving-path note: the OpenAI SDK sends `Accept: application/json` for
5
+ * ALL requests including streaming ones (`client.ts:1160` in the SDK source).
6
+ * Harper's REST layer dispatches `Accept: text/event-stream` as CONNECT, and
7
+ * everything else as the HTTP method. So `stream: true` from an OpenAI SDK
8
+ * client reaches this `post()` handler, NOT `connect()`. We detect the `stream`
9
+ * flag in the body and return `{ body: Readable }` which REST.ts bypasses
10
+ * serialisation on (REST.ts:165-193) — exactly like any SSE resource response,
11
+ * but initiated from `post()` rather than `connect()`.
12
+ */
13
+
14
+ import type { Readable } from 'node:stream';
15
+ import { contentTypes } from '../../../server/serverHelpers/contentTypes.ts';
16
+ import { Resource } from '../../Resource.ts';
17
+ import { models } from '../Models.ts';
18
+ import { openaiStream } from '../openaiStream.ts';
19
+ import { toOpenAIError, badRequest, authorizeV1Request } from './errors.ts';
20
+ import {
21
+ translateMessages,
22
+ translateTools,
23
+ toGenerateInput,
24
+ toGenerateOpts,
25
+ toChatCompletion,
26
+ validateChatRequest,
27
+ } from './translation.ts';
28
+ import type { OAIChatRequest } from './translation.ts';
29
+
30
+ type SseHandler = { serializeStream: (iterable: AsyncIterable<unknown>) => Readable };
31
+ const sseHandler = contentTypes.get('text/event-stream') as SseHandler;
32
+
33
+ // @ts-ignore — Resource base class is not typed for static dispatch; pattern mirrors login.ts
34
+ export class V1ChatCompletions extends Resource {
35
+ // Reserve this fixed route: a later app registration at the same path becomes a
36
+ // loud conflict (ErrorResource) instead of silently replacing the gateway and its
37
+ // super_user gate. See Resources.set.
38
+ static reservedPath = true;
39
+
40
+ static async post(_target: unknown, body: unknown, request: unknown) {
41
+ const authError = authorizeV1Request(request as any);
42
+ if (authError) return authError;
43
+
44
+ // REST.ts passes `request.data` directly, which is the (unawaited) streaming
45
+ // JSON deserializer's Promise — awaiting here is a no-op for callers (e.g.
46
+ // unit tests) that already pass a plain object. A malformed JSON body rejects
47
+ // this promise, which is a client error, not a 500.
48
+ try {
49
+ body = await body;
50
+ } catch (err) {
51
+ return badRequest(`Could not parse request body: ${err instanceof Error ? err.message : 'invalid JSON'}`);
52
+ }
53
+ if (!body || typeof body !== 'object' || Array.isArray(body)) {
54
+ return badRequest('Request body must be a JSON object');
55
+ }
56
+ const req = body as OAIChatRequest;
57
+
58
+ // Validate the nested wire shapes before mapping: the mappers assume well-formed
59
+ // input, so an unvalidated `messages:[null]` / `tools:[{}]` would throw a TypeError
60
+ // and surface as an RFC 9457 500 instead of an OpenAI 400.
61
+ const invalid = validateChatRequest(req);
62
+ if (invalid) return badRequest(invalid);
63
+
64
+ const model = typeof req.model === 'string' ? req.model : 'default';
65
+
66
+ try {
67
+ const messages = translateMessages(req.messages);
68
+ // tool_choice: 'none' means "do not call tools" — the only faithful way to honor
69
+ // that against a returns-tool-calls backend is to not offer the tools at all.
70
+ // 'required'/named selection are rejected in validateChatRequest.
71
+ const tools = req.tool_choice === 'none' || !req.tools?.length ? undefined : translateTools(req.tools);
72
+ const input = toGenerateInput(messages, tools);
73
+ const opts = toGenerateOpts(req);
74
+ if (req.stream) {
75
+ const tokenStream = models.generateStream(input, opts);
76
+ // serializeStream wraps the async iterable in a Node Readable so REST.ts
77
+ // can return it without re-serialising. The `body` presence on the return
78
+ // value skips REST.ts's own serialize() call (REST.ts:165-193).
79
+ // formatError reuses the non-streaming error mapping so a mid-stream backend
80
+ // failure reaches the client as an OpenAI-shaped SSE error frame.
81
+ const readable = sseHandler.serializeStream(
82
+ openaiStream(tokenStream, { model, formatError: (err) => toOpenAIError(err).data.error })
83
+ );
84
+ return {
85
+ status: 200,
86
+ headers: {
87
+ 'Content-Type': 'text/event-stream',
88
+ 'Cache-Control': 'no-cache',
89
+ 'X-Accel-Buffering': 'no',
90
+ },
91
+ body: readable,
92
+ };
93
+ }
94
+
95
+ const result = await models.generate(input, opts);
96
+ return toChatCompletion(result, model);
97
+ } catch (err) {
98
+ return toOpenAIError(err);
99
+ }
100
+ }
101
+
102
+ /**
103
+ * A client that sends an explicit `Accept: text/event-stream` with its POST is
104
+ * dispatched by REST as CONNECT (REST.ts), not POST. The OpenAI SDK happens to send
105
+ * `Accept: application/json` even when streaming, but other valid SSE clients do not.
106
+ *
107
+ * Without this override the request reached `Resource`'s default `connect`, whose
108
+ * instance path returns `subscribe()` — an empty `IterableEventQueue` — so the client
109
+ * got a 200 SSE response that stayed open forever emitting nothing, rather than an
110
+ * error it could act on.
111
+ *
112
+ * REST passes `null` as the CONNECT body (`resource.connect(target, null, request)`),
113
+ * so the parsed body is taken off the request and handed to the same `post()`
114
+ * implementation — one code path, identical validation and error shaping.
115
+ *
116
+ * `connect` is also reachable from the WebSocket handler with a different signature
117
+ * (`resourceRequest, incomingMessages, request`), where there is no `request.data`;
118
+ * that case is rejected as a client error rather than returning an envelope the WS
119
+ * path would fail to iterate.
120
+ */
121
+ static async connect(target: unknown, _data: unknown, request: unknown) {
122
+ const data = (request as { data?: unknown })?.data;
123
+ if (data === undefined) {
124
+ return badRequest('This endpoint requires a JSON request body; WebSocket connections are not supported');
125
+ }
126
+ return this.post(target, data, request);
127
+ }
128
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `POST /v1/embeddings` — OpenAI-compatible embedding endpoint (#631).
3
+ *
4
+ * Maps OpenAI's `{ model, input }` request body to `scope.models.embed()` and
5
+ * returns `{ object: 'list', data: [...], model, usage }` per the OpenAI wire spec.
6
+ */
7
+
8
+ import { Resource } from '../../Resource.ts';
9
+ import { models } from '../Models.ts';
10
+ import { toOpenAIError, badRequest, authorizeV1Request } from './errors.ts';
11
+ import { toEmbedOpts, toEmbedResponse } from './translation.ts';
12
+
13
+ // Cap batched input, matching OpenAI's own 2048-item limit. The endpoint is
14
+ // super_user-only and off by default, so this is a sanity bound (avoid an
15
+ // unbounded fan-out to the backend), not a security control.
16
+ const MAX_EMBEDDING_INPUTS = 2048;
17
+
18
+ // @ts-ignore — Resource base class is not typed for static dispatch; pattern mirrors login.ts
19
+ export class V1Embeddings extends Resource {
20
+ // Reserve this fixed route: a later app registration at the same path becomes a
21
+ // loud conflict (ErrorResource) instead of silently replacing the gateway and its
22
+ // super_user gate. See Resources.set.
23
+ static reservedPath = true;
24
+
25
+ static async post(_target: unknown, body: Record<string, unknown>, request: unknown) {
26
+ const authError = authorizeV1Request(request as any);
27
+ if (authError) return authError;
28
+
29
+ // REST.ts passes `request.data` directly, which is the (unawaited) streaming
30
+ // JSON deserializer's Promise — awaiting here is a no-op for callers (e.g.
31
+ // unit tests) that already pass a plain object. A malformed JSON body rejects
32
+ // this promise, which is a client error, not a 500 (matches chatCompletions).
33
+ try {
34
+ body = await body;
35
+ } catch (err) {
36
+ return badRequest(`Could not parse request body: ${err instanceof Error ? err.message : 'invalid JSON'}`);
37
+ }
38
+ if (!body || typeof body !== 'object' || Array.isArray(body))
39
+ return badRequest('Request body must be a JSON object');
40
+ const raw = body as Record<string, unknown>;
41
+
42
+ // Mirrors validateChatRequest: a non-string model would silently invoke the
43
+ // configured default rather than being rejected.
44
+ if (raw.model !== undefined && typeof raw.model !== 'string') return badRequest("'model' must be a string");
45
+
46
+ const input = raw.input;
47
+ if (input === undefined || input === null) return badRequest("'input' is required");
48
+ if (typeof input !== 'string' && !Array.isArray(input)) {
49
+ return badRequest("'input' must be a string or array of strings");
50
+ }
51
+ if (Array.isArray(input) && !input.every((v) => typeof v === 'string')) {
52
+ return badRequest("'input' array elements must be strings");
53
+ }
54
+ if (Array.isArray(input) && input.length > MAX_EMBEDDING_INPUTS) {
55
+ return badRequest(`'input' array must not exceed ${MAX_EMBEDDING_INPUTS} items`);
56
+ }
57
+
58
+ const model = typeof raw.model === 'string' ? raw.model : 'default';
59
+ const opts = toEmbedOpts(raw as any);
60
+
61
+ try {
62
+ // embedWithUsage, not embed(): the public facade drops the result-level usage
63
+ // backends report, and OpenAI clients read real token counts off the response.
64
+ const { vectors, usage } = await models.embedWithUsage(input as string | string[], opts);
65
+ return toEmbedResponse(vectors, model, usage);
66
+ } catch (err) {
67
+ return toOpenAIError(err);
68
+ }
69
+ }
70
+ }
@@ -0,0 +1,141 @@
1
+ /**
2
+ * OpenAI error envelope helpers for the `/v1/*` gateway (#631).
3
+ *
4
+ * Harper's REST layer serialises uncaught errors as RFC 9457 Problem Details.
5
+ * Resources that need the OpenAI `{ error: { message, type, code, param } }`
6
+ * shape must catch errors themselves and call `toOpenAIError()` / `badRequest()`.
7
+ */
8
+
9
+ import { ModelBackendNotFoundError } from '../backendRegistry.ts';
10
+ import { ModelCapabilityError } from '../Models.ts';
11
+ import harperLogger from '../../../utility/logging/harper_logger.ts';
12
+
13
+ type OpenAIErrorType =
14
+ 'invalid_request_error' | 'server_error' | 'authentication_error' | 'permission_error' | 'api_error';
15
+
16
+ export interface OpenAIErrorBody {
17
+ message: string;
18
+ type: OpenAIErrorType;
19
+ code: string | null;
20
+ param: string | null;
21
+ }
22
+
23
+ /** HTTP response payload from a gateway error; resource methods return this directly. */
24
+ export interface OpenAIErrorResponse {
25
+ status: number;
26
+ headers: { 'Content-Type': 'application/json' };
27
+ data: { error: OpenAIErrorBody };
28
+ }
29
+
30
+ /**
31
+ * Map any thrown value to an OpenAI error envelope. Uses `statusCode` when
32
+ * present (Harper's `ClientError` / `ServerError` convention). Falls back to
33
+ * `500 server_error`. `ModelBackendNotFoundError` maps to `404 model_not_found`.
34
+ */
35
+ export function toOpenAIError(err: unknown): OpenAIErrorResponse {
36
+ let status = 500;
37
+ let type: OpenAIErrorType = 'server_error';
38
+ let code: string | null = null;
39
+
40
+ if (err instanceof ModelBackendNotFoundError) {
41
+ status = 404;
42
+ type = 'invalid_request_error';
43
+ code = 'model_not_found';
44
+ } else if (err instanceof ModelCapabilityError) {
45
+ // Caller-driven mismatch (e.g. `tools` or streaming against a backend that
46
+ // doesn't support it): the request is what's wrong, not the server. It extends
47
+ // ServerError (statusCode 500), so this must precede the statusCode branch —
48
+ // falling through would report a generic sanitized 500 for a client-actionable
49
+ // condition. The message is safe to pass through: it names only the backend and
50
+ // the capability the caller asked for.
51
+ status = 400;
52
+ type = 'invalid_request_error';
53
+ code = 'capability_unsupported';
54
+ } else if (err instanceof Error && typeof (err as any).statusCode === 'number') {
55
+ status = (err as any).statusCode;
56
+ if (status === 401) {
57
+ type = 'authentication_error';
58
+ } else if (status === 403) {
59
+ // OpenAI semantics: 401 = bad/missing credentials, 403 = valid credentials
60
+ // lacking permission (matches authorizeV1Request's own 403 envelope).
61
+ type = 'permission_error';
62
+ } else if (status < 500) {
63
+ type = 'invalid_request_error';
64
+ } else {
65
+ type = 'server_error';
66
+ }
67
+ }
68
+
69
+ // 5xx messages stay generic: internal error strings (backend stack details, file
70
+ // paths) don't belong in a wire response. The real error goes to the log. 4xx
71
+ // messages are client-actionable and pass through.
72
+ let message: string;
73
+ if (status >= 500) {
74
+ harperLogger.error('v1 gateway error', err);
75
+ message = 'Internal server error';
76
+ } else {
77
+ message = err instanceof Error ? err.message : 'Bad request';
78
+ }
79
+
80
+ return {
81
+ status,
82
+ headers: { 'Content-Type': 'application/json' },
83
+ data: { error: { message, type, code, param: null } },
84
+ };
85
+ }
86
+
87
+ /** Convenience for early request-body validation failures. */
88
+ export function badRequest(message: string): OpenAIErrorResponse {
89
+ return {
90
+ status: 400,
91
+ headers: { 'Content-Type': 'application/json' },
92
+ data: { error: { message, type: 'invalid_request_error', code: null, param: null } },
93
+ };
94
+ }
95
+
96
+ /**
97
+ * Gate for the `/v1/*` handlers, since overriding the static `get`/`post` methods
98
+ * bypasses Resource's `transactional()` wrapper and its default `allowRead`/`allowCreate`
99
+ * checks (Resource.ts:685-733, 426-435) never run for these endpoints.
100
+ *
101
+ * Mirrors Resource's default gate (super_user-only) rather than introducing a new
102
+ * permission — see PR discussion for whether a dedicated `/v1/*` permission should
103
+ * replace this later.
104
+ *
105
+ * Returns an OpenAI-shape error response when access should be denied, or `null`
106
+ * when the request may proceed.
107
+ */
108
+ export function authorizeV1Request(request: {
109
+ user?: { role?: { permission?: { super_user?: boolean } } };
110
+ }): OpenAIErrorResponse | null {
111
+ const user = request?.user;
112
+ if (!user) {
113
+ return {
114
+ status: 401,
115
+ headers: { 'Content-Type': 'application/json' },
116
+ data: {
117
+ error: {
118
+ message: 'You must provide valid credentials to access this endpoint.',
119
+ type: 'authentication_error' as const,
120
+ code: null,
121
+ param: null,
122
+ },
123
+ },
124
+ };
125
+ }
126
+ if (!user.role?.permission?.super_user) {
127
+ return {
128
+ status: 403,
129
+ headers: { 'Content-Type': 'application/json' },
130
+ data: {
131
+ error: {
132
+ message: 'You do not have permission to access this endpoint.',
133
+ type: 'permission_error' as const,
134
+ code: null,
135
+ param: null,
136
+ },
137
+ },
138
+ };
139
+ }
140
+ return null;
141
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * `/v1/*` OpenAI-compatible gateway (#631).
3
+ *
4
+ * Registers three REST resources on the REST port:
5
+ * POST /v1/embeddings → V1Embeddings
6
+ * POST /v1/chat/completions → V1ChatCompletions
7
+ * GET /v1/models → V1Models
8
+ *
9
+ * Off by default, and `defaultConfig.yaml` deliberately ships no `modelsGateway`
10
+ * block: with the key absent the root loader skips the component before resolving
11
+ * it, so none of this module graph is imported on an instance that does not use
12
+ * the gateway. Opt in by adding the block to `harperdb-config.yaml` with
13
+ * `enabled: true`, or via `set_configuration` (`modelsGateway_enabled`).
14
+ * `enabled: false` is honored too, for an instance that wants the block present
15
+ * but inert — that costs the import, which is why it is not the shipped default.
16
+ *
17
+ * Example (opt in). `rest` is required: these are REST-served resources and the
18
+ * gateway deliberately does not force REST to start (see `handleApplication`).
19
+ * Without it the resources register but every `/v1/*` path 404s.
20
+ *
21
+ * ```yaml
22
+ * rest: true
23
+ * modelsGateway:
24
+ * enabled: true
25
+ * models:
26
+ * generative:
27
+ * default:
28
+ * backend: ollama
29
+ * model: llama3.2
30
+ * ```
31
+ *
32
+ * All three endpoints require `super_user` permission. Anonymous or
33
+ * insufficient-privilege requests receive a well-formed OpenAI error envelope.
34
+ */
35
+
36
+ import type { Scope } from '../../../components/Scope.ts';
37
+ import harperLogger from '../../../utility/logging/harper_logger.ts';
38
+ import { getConfigObj } from '../../../config/configUtils.ts';
39
+ import { V1Embeddings } from './embeddings.ts';
40
+ import { V1ChatCompletions } from './chatCompletions.ts';
41
+ import { V1Models } from './models.ts';
42
+
43
+ export function handleApplication(scope: Scope): void {
44
+ if (!scope.options.get(['enabled'])) return;
45
+ // These resources are served by REST's middleware chain, so the instance must also
46
+ // have a `rest`/`REST` config section — the gateway deliberately does NOT force REST
47
+ // to start. Doing so requires reaching into REST's module state before application
48
+ // configs have loaded, which silently discards an app's own `rest` options (webSocket,
49
+ // urlPath/host, middleware ordering). Core has no supported way yet for a component to
50
+ // declare "I serve REST resources"; that gap is tracked separately.
51
+ //
52
+ // Warn rather than fail: an app loaded later may still declare `rest`, so absence here
53
+ // is not conclusive. But defaultConfig ships no `rest` section, so enabling the gateway
54
+ // alone yields three registered resources and a 404 on every /v1 path — worth a line in
55
+ // the log instead of silence.
56
+ const rootConfig = getConfigObj() as Record<string, unknown> | undefined;
57
+ if (rootConfig && !rootConfig.rest && !rootConfig.REST) {
58
+ harperLogger.warn(
59
+ 'modelsGateway is enabled but no `rest` section is configured; /v1/* endpoints are only served when REST is active'
60
+ );
61
+ }
62
+ // Explicit protocol visibility: these are REST-only wire-protocol endpoints. Without a
63
+ // policy, the shared registry matches them for every protocol lookup — WS dispatch could
64
+ // reach V1ChatCompletions.connect() and then fail iterating its non-iterable badRequest
65
+ // envelope, and they would surface through MQTT/GraphQL/MCP enumeration too. `sse` stays
66
+ // enabled for chat only: an explicit `Accept: text/event-stream` POST is dispatched via
67
+ // the sse lookup (REST.ts) and is a supported streaming client shape (see connect()).
68
+ const restOnly = { rest: true, sse: false, ws: false, mqtt: false, graphql: false, mcp: false };
69
+ scope.resources.set('v1/models', V1Models, restOnly);
70
+ scope.resources.set('v1/embeddings', V1Embeddings, restOnly);
71
+ scope.resources.set('v1/chat/completions', V1ChatCompletions, { ...restOnly, sse: true });
72
+ }