@octopi-agent/engine 0.102.10 → 0.121.15

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 (321) hide show
  1. package/dist/builtin-model-info.js +28 -7
  2. package/dist/config-admin/agent-presets.d.ts +32 -0
  3. package/dist/config-admin/agent-presets.js +133 -0
  4. package/dist/config-admin/console-access-key.d.ts +46 -0
  5. package/dist/config-admin/console-access-key.js +47 -0
  6. package/dist/config-admin/discover.d.ts +33 -4
  7. package/dist/config-admin/discover.js +101 -6
  8. package/dist/config-admin/env.d.ts +11 -0
  9. package/dist/config-admin/env.js +41 -0
  10. package/dist/config-admin/error-copy.d.ts +106 -0
  11. package/dist/config-admin/error-copy.js +287 -0
  12. package/dist/config-admin/i18n.d.ts +21 -0
  13. package/dist/config-admin/i18n.js +19 -0
  14. package/dist/config-admin/index.d.ts +8 -2
  15. package/dist/config-admin/index.js +4 -1
  16. package/dist/config-admin/model-presets.d.ts +14 -0
  17. package/dist/config-admin/model-presets.js +595 -70
  18. package/dist/config-admin/onboarding-apply.d.ts +83 -0
  19. package/dist/config-admin/onboarding-apply.js +259 -0
  20. package/dist/config-admin/onboarding.d.ts +160 -0
  21. package/dist/config-admin/onboarding.js +298 -0
  22. package/dist/config-admin/password-policy.d.ts +24 -0
  23. package/dist/config-admin/password-policy.js +31 -0
  24. package/dist/config-admin/redact.d.ts +42 -9
  25. package/dist/config-admin/redact.js +69 -5
  26. package/dist/config-schema/agent.d.ts +5 -1
  27. package/dist/config-schema/agent.js +20 -2
  28. package/dist/config-schema/browser.d.ts +62 -0
  29. package/dist/config-schema/browser.js +89 -0
  30. package/dist/config-schema/context.d.ts +7 -2
  31. package/dist/config-schema/context.js +6 -3
  32. package/dist/config-schema/engine.d.ts +86 -7
  33. package/dist/config-schema/engine.js +9 -2
  34. package/dist/config-schema/governance.d.ts +12 -1
  35. package/dist/config-schema/governance.js +10 -2
  36. package/dist/config-schema/models.d.ts +12 -8
  37. package/dist/config-schema/models.js +16 -1
  38. package/dist/config-schema/run.d.ts +4 -0
  39. package/dist/config-schema/run.js +10 -0
  40. package/dist/config-schema/shared.d.ts +1 -0
  41. package/dist/config-schema/shared.js +4 -2
  42. package/dist/config-schema/substrate.d.ts +5 -0
  43. package/dist/config-schema/substrate.js +8 -0
  44. package/dist/config.d.ts +116 -10
  45. package/dist/config.js +109 -13
  46. package/dist/file-mode.d.ts +67 -0
  47. package/dist/file-mode.js +182 -0
  48. package/dist/fork-child.d.ts +82 -0
  49. package/dist/fork-child.js +123 -0
  50. package/dist/harness/activation/delegated-run.d.ts +42 -0
  51. package/dist/harness/activation/delegated-run.js +71 -0
  52. package/dist/harness/activation/dispatcher.js +4 -0
  53. package/dist/harness/activation/index.d.ts +1 -0
  54. package/dist/harness/activation/run-backend.d.ts +92 -0
  55. package/dist/harness/activation/run-backend.js +16 -0
  56. package/dist/harness/activation/run-protocol.d.ts +392 -0
  57. package/dist/harness/activation/run-protocol.js +19 -0
  58. package/dist/harness/activation/runtime.d.ts +33 -0
  59. package/dist/harness/activation/runtime.js +119 -28
  60. package/dist/harness/activation/types.d.ts +19 -2
  61. package/dist/harness/agent/builder.d.ts +12 -0
  62. package/dist/harness/agent/builder.js +78 -22
  63. package/dist/harness/agent/config-bridge.d.ts +10 -1
  64. package/dist/harness/agent/config-bridge.js +15 -3
  65. package/dist/harness/agent/registered-tool-adapter.d.ts +27 -0
  66. package/dist/harness/agent/registered-tool-adapter.js +67 -0
  67. package/dist/harness/agent/wire-agent-builder.d.ts +2 -0
  68. package/dist/harness/agent/wire-agent-builder.js +9 -2
  69. package/dist/harness/capabilities/document/backends/plain.js +2 -1
  70. package/dist/harness/capabilities/document/legacy/factory.js +3 -2
  71. package/dist/harness/collaboration/autonomous-subsystem/audit/reader.d.ts +17 -0
  72. package/dist/harness/collaboration/autonomous-subsystem/audit/reader.js +66 -36
  73. package/dist/harness/collaboration/autonomous-subsystem/audit/writer.d.ts +6 -2
  74. package/dist/harness/collaboration/autonomous-subsystem/audit/writer.js +27 -7
  75. package/dist/harness/collaboration/autonomous-subsystem/boundary/validator.js +13 -0
  76. package/dist/harness/collaboration/autonomous-subsystem/loader.js +1 -0
  77. package/dist/harness/collaboration/autonomous-subsystem/runtime.d.ts +11 -0
  78. package/dist/harness/collaboration/autonomous-subsystem/runtime.js +17 -0
  79. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.d.ts +13 -3
  80. package/dist/harness/collaboration/autonomous-subsystem/sense/engine.js +48 -39
  81. package/dist/harness/collaboration/autonomous-subsystem/think/executor.js +3 -0
  82. package/dist/harness/collaboration/autonomous-subsystem/types.d.ts +4 -0
  83. package/dist/harness/collaboration/delegation/child-run.d.ts +9 -0
  84. package/dist/harness/collaboration/delegation/child-run.js +34 -2
  85. package/dist/harness/collaboration/delegation/registry-types.d.ts +2 -0
  86. package/dist/harness/collaboration/delegation/service.d.ts +9 -4
  87. package/dist/harness/collaboration/delegation/service.js +33 -12
  88. package/dist/harness/collaboration/delegation/store.d.ts +2 -0
  89. package/dist/harness/collaboration/delegation/store.js +1 -0
  90. package/dist/harness/collaboration/delegation/types.d.ts +11 -0
  91. package/dist/harness/collaboration/delegation/wiring.d.ts +2 -0
  92. package/dist/harness/collaboration/delegation/wiring.js +1 -0
  93. package/dist/harness/context/capabilities/compact/engine.d.ts +44 -5
  94. package/dist/harness/context/capabilities/compact/engine.js +127 -39
  95. package/dist/harness/context/capabilities/compact/index.d.ts +2 -1
  96. package/dist/harness/context/capabilities/compact/index.js +1 -1
  97. package/dist/harness/context/capabilities/compact/types.d.ts +59 -9
  98. package/dist/harness/context/capabilities/summary/gate.d.ts +19 -2
  99. package/dist/harness/context/capabilities/summary/gate.js +53 -6
  100. package/dist/harness/context/capabilities/summary/registry.js +20 -0
  101. package/dist/harness/context/capabilities/summary/tool-binding.js +16 -12
  102. package/dist/harness/context/capabilities/summary/tool-bindings.d.ts +13 -0
  103. package/dist/harness/context/capabilities/summary/tool-bindings.js +22 -0
  104. package/dist/harness/context/capabilities/summary/types.d.ts +16 -0
  105. package/dist/harness/context/constitution/default-agents.md +85 -0
  106. package/dist/harness/context/context-size-ledger.js +8 -1
  107. package/dist/harness/context/default-context-engine.d.ts +100 -6
  108. package/dist/harness/context/default-context-engine.js +382 -89
  109. package/dist/harness/context/index.d.ts +2 -1
  110. package/dist/harness/context/index.js +1 -0
  111. package/dist/harness/context/layer-health.d.ts +4 -0
  112. package/dist/harness/context/layer-health.js +4 -0
  113. package/dist/harness/context/layer-types.d.ts +57 -0
  114. package/dist/harness/context/layer-types.js +73 -1
  115. package/dist/harness/context/layers.d.ts +3 -0
  116. package/dist/harness/context/layers.js +13 -6
  117. package/dist/harness/context/prefix-fingerprint.d.ts +46 -0
  118. package/dist/harness/context/prefix-fingerprint.js +52 -0
  119. package/dist/harness/context/summarize.js +18 -0
  120. package/dist/harness/context/system-prompt-assembler.d.ts +2 -0
  121. package/dist/harness/context/system-prompt-assembler.js +5 -2
  122. package/dist/harness/context/tool-result-aging.d.ts +104 -16
  123. package/dist/harness/context/tool-result-aging.js +211 -57
  124. package/dist/harness/context/types.d.ts +71 -4
  125. package/dist/harness/context/types.js +25 -1
  126. package/dist/harness/extension/execution-environment/effect-policy.d.ts +4 -3
  127. package/dist/harness/extension/execution-environment/effect-policy.js +2 -2
  128. package/dist/harness/extension/execution-environment/privileged-exec.js +4 -1
  129. package/dist/harness/extension/execution-environment/workspace.js +1 -1
  130. package/dist/harness/extension/plugin-ecosystem/channel-types.d.ts +27 -1
  131. package/dist/harness/extension/plugin-ecosystem/channel-types.js +11 -2
  132. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.d.ts +12 -0
  133. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.js +25 -0
  134. package/dist/harness/extension/plugin-ecosystem/commands/builtin.js +28 -1
  135. package/dist/harness/extension/plugin-ecosystem/index.d.ts +1 -0
  136. package/dist/harness/extension/plugin-ecosystem/index.js +1 -0
  137. package/dist/harness/extension/plugin-ecosystem/plugins/api.d.ts +168 -1
  138. package/dist/harness/extension/plugin-ecosystem/plugins/api.js +156 -15
  139. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.d.ts +95 -0
  140. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-instances.js +170 -0
  141. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.d.ts +178 -0
  142. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-kinds.js +314 -0
  143. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.d.ts +40 -5
  144. package/dist/harness/extension/plugin-ecosystem/plugins/contribution-registry.js +45 -26
  145. package/dist/harness/extension/plugin-ecosystem/plugins/index.d.ts +1 -1
  146. package/dist/harness/extension/plugin-ecosystem/plugins/loader.d.ts +11 -1
  147. package/dist/harness/extension/plugin-ecosystem/plugins/loader.js +42 -76
  148. package/dist/harness/extension/plugin-ecosystem/plugins/manager.d.ts +30 -1
  149. package/dist/harness/extension/plugin-ecosystem/plugins/manager.js +46 -0
  150. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.d.ts +9 -0
  151. package/dist/harness/extension/plugin-ecosystem/plugins/manifest.js +19 -14
  152. package/dist/harness/extension/plugin-ecosystem/plugins/staging.d.ts +3 -1
  153. package/dist/harness/extension/plugin-ecosystem/plugins/staging.js +1 -1
  154. package/dist/harness/extension/plugin-ecosystem/tools/browser-types.d.ts +333 -0
  155. package/dist/harness/extension/plugin-ecosystem/tools/browser-types.js +16 -0
  156. package/dist/harness/extension/plugin-ecosystem/tools/browser.d.ts +64 -0
  157. package/dist/harness/extension/plugin-ecosystem/tools/browser.js +692 -0
  158. package/dist/harness/extension/plugin-ecosystem/tools/builtin.d.ts +0 -37
  159. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +108 -4
  160. package/dist/harness/extension/plugin-ecosystem/tools/delegation.js +18 -0
  161. package/dist/harness/extension/plugin-ecosystem/tools/file-edit.js +34 -0
  162. package/dist/harness/extension/plugin-ecosystem/tools/file-search.d.ts +0 -6
  163. package/dist/harness/extension/plugin-ecosystem/tools/file-search.js +57 -4
  164. package/dist/harness/extension/plugin-ecosystem/tools/git-tools.js +81 -13
  165. package/dist/harness/extension/plugin-ecosystem/tools/http.js +5 -0
  166. package/dist/harness/extension/plugin-ecosystem/tools/knowledge.js +13 -7
  167. package/dist/harness/extension/plugin-ecosystem/tools/package-tools.js +126 -14
  168. package/dist/harness/extension/plugin-ecosystem/tools/platform.d.ts +1 -1
  169. package/dist/harness/extension/plugin-ecosystem/tools/platform.js +44 -5
  170. package/dist/harness/extension/plugin-ecosystem/tools/tool-bus.js +10 -24
  171. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.d.ts +7 -0
  172. package/dist/harness/extension/plugin-ecosystem/tools/tool-set.js +4 -0
  173. package/dist/harness/governance/credentials/db.d.ts +9 -0
  174. package/dist/harness/governance/credentials/db.js +122 -31
  175. package/dist/harness/governance/credentials/store.d.ts +68 -7
  176. package/dist/harness/governance/credentials/store.js +177 -64
  177. package/dist/harness/governance/credentials/types.d.ts +13 -2
  178. package/dist/harness/governance/index.d.ts +1 -0
  179. package/dist/harness/governance/index.js +1 -0
  180. package/dist/harness/governance/registry/db.d.ts +32 -0
  181. package/dist/harness/governance/registry/db.js +142 -0
  182. package/dist/harness/governance/registry/index.d.ts +9 -0
  183. package/dist/harness/governance/registry/index.js +9 -0
  184. package/dist/harness/governance/registry/service.d.ts +381 -0
  185. package/dist/harness/governance/registry/service.js +825 -0
  186. package/dist/harness/governance/registry/types.d.ts +77 -0
  187. package/dist/harness/governance/registry/types.js +7 -0
  188. package/dist/harness/governance/security/default-security-guard.d.ts +3 -0
  189. package/dist/harness/governance/security/default-security-guard.js +12 -1
  190. package/dist/harness/governance/security/risk-evaluator.d.ts +13 -3
  191. package/dist/harness/governance/security/risk-evaluator.js +307 -21
  192. package/dist/harness/governance/security/shell-parser-treesitter.js +12 -4
  193. package/dist/harness/governance/session-acl/tool-rights.d.ts +1 -0
  194. package/dist/harness/index.d.ts +5 -3
  195. package/dist/harness/index.js +2 -2
  196. package/dist/harness/knowledge/boot-config.d.ts +2 -0
  197. package/dist/harness/knowledge/boot-config.js +2 -0
  198. package/dist/harness/knowledge/client.d.ts +53 -7
  199. package/dist/harness/knowledge/client.js +77 -20
  200. package/dist/harness/knowledge/db.d.ts +16 -0
  201. package/dist/harness/knowledge/db.js +107 -41
  202. package/dist/harness/knowledge/engine-thread.js +5 -7
  203. package/dist/harness/knowledge/grounding.js +4 -1
  204. package/dist/harness/knowledge/http-app.d.ts +15 -0
  205. package/dist/harness/knowledge/http-app.js +82 -21
  206. package/dist/harness/knowledge/http-bridge.d.ts +15 -0
  207. package/dist/harness/knowledge/http-bridge.js +19 -0
  208. package/dist/harness/knowledge/knowledge-serve-child.js +2 -3
  209. package/dist/harness/knowledge/query-service.d.ts +12 -2
  210. package/dist/harness/knowledge/query-service.js +75 -41
  211. package/dist/harness/knowledge/query-worker-client.d.ts +5 -1
  212. package/dist/harness/knowledge/query-worker-client.js +4 -1
  213. package/dist/harness/knowledge/query-worker.js +5 -3
  214. package/dist/harness/knowledge/read-http.d.ts +2 -0
  215. package/dist/harness/knowledge/read-http.js +9 -2
  216. package/dist/harness/knowledge/retriever.d.ts +1 -1
  217. package/dist/harness/knowledge/retriever.js +1 -2
  218. package/dist/harness/knowledge/serve.d.ts +6 -1
  219. package/dist/harness/knowledge/serve.js +5 -6
  220. package/dist/harness/knowledge/source-store.d.ts +101 -5
  221. package/dist/harness/knowledge/source-store.js +297 -71
  222. package/dist/harness/knowledge/start-service-process.d.ts +27 -8
  223. package/dist/harness/knowledge/start-service-process.js +49 -90
  224. package/dist/harness/knowledge/tenant-gate.d.ts +81 -0
  225. package/dist/harness/knowledge/tenant-gate.js +167 -0
  226. package/dist/harness/knowledge/writer-service.d.ts +18 -2
  227. package/dist/harness/knowledge/writer-service.js +80 -16
  228. package/dist/harness/knowledge/writer-worker-client.d.ts +9 -2
  229. package/dist/harness/knowledge/writer-worker-client.js +20 -3
  230. package/dist/harness/knowledge/writer-worker.js +11 -4
  231. package/dist/harness/memory/backfill-trigger.d.ts +10 -3
  232. package/dist/harness/memory/backfill-trigger.js +19 -19
  233. package/dist/harness/memory/cognition-seeds.d.ts +45 -0
  234. package/dist/harness/memory/cognition-seeds.js +67 -0
  235. package/dist/harness/memory/cognition.d.ts +12 -3
  236. package/dist/harness/memory/cognition.js +55 -35
  237. package/dist/harness/memory/conceptualizer.d.ts +11 -1
  238. package/dist/harness/memory/conceptualizer.js +10 -1
  239. package/dist/harness/memory/context-slice.d.ts +42 -0
  240. package/dist/harness/memory/context-slice.js +197 -0
  241. package/dist/harness/memory/health-probe.d.ts +8 -2
  242. package/dist/harness/memory/health-probe.js +10 -13
  243. package/dist/harness/memory/index.d.ts +5 -1
  244. package/dist/harness/memory/index.js +3 -1
  245. package/dist/harness/memory/sqlite/agent-db.d.ts +1 -0
  246. package/dist/harness/memory/sqlite/agent-db.js +9 -8
  247. package/dist/harness/memory/sqlite/cognition-store.d.ts +26 -3
  248. package/dist/harness/memory/sqlite/cognition-store.js +103 -45
  249. package/dist/harness/memory/sqlite/memory-store.js +4 -0
  250. package/dist/harness/memory/sqlite/sqlite-vec.d.ts +24 -1
  251. package/dist/harness/memory/sqlite/sqlite-vec.js +37 -1
  252. package/dist/harness/memory/types.d.ts +18 -2
  253. package/dist/harness/observability/observer/hub.d.ts +10 -0
  254. package/dist/harness/observability/observer/hub.js +95 -2
  255. package/dist/harness/run/agent/agent.js +3 -2
  256. package/dist/harness/run/concurrency/tool-validator.js +4 -3
  257. package/dist/harness/run/reliability/run-agent.d.ts +22 -0
  258. package/dist/harness/run/reliability/run-agent.js +79 -10
  259. package/dist/harness/run/run-host.d.ts +302 -0
  260. package/dist/harness/run/run-host.js +978 -0
  261. package/dist/harness/run/run-scope.d.ts +11 -0
  262. package/dist/harness/run/run-scope.js +19 -1
  263. package/dist/harness/run/runner.d.ts +149 -22
  264. package/dist/harness/run/runner.js +352 -35
  265. package/dist/harness/session/in-memory-store.js +13 -1
  266. package/dist/harness/session/schedules/service.d.ts +10 -2
  267. package/dist/harness/session/schedules/service.js +13 -2
  268. package/dist/harness/session/tasks/tools.js +12 -0
  269. package/dist/harness/session/types.d.ts +10 -14
  270. package/dist/harness/shared/events/agent-event-map.d.ts +29 -0
  271. package/dist/harness/shared/types/agent-definition.d.ts +6 -0
  272. package/dist/index.d.ts +3 -2
  273. package/dist/index.js +2 -1
  274. package/dist/integration/agent-runtime/channel-message-source.d.ts +3 -1
  275. package/dist/integration/agent-runtime/channel-message-source.js +4 -3
  276. package/dist/integration/browser/camoufox.d.ts +40 -0
  277. package/dist/integration/browser/camoufox.js +80 -0
  278. package/dist/integration/browser/index.d.ts +91 -0
  279. package/dist/integration/browser/index.js +110 -0
  280. package/dist/integration/browser/install.d.ts +47 -0
  281. package/dist/integration/browser/install.js +214 -0
  282. package/dist/integration/browser/playwright.d.ts +224 -0
  283. package/dist/integration/browser/playwright.js +925 -0
  284. package/dist/integration/browser/service.d.ts +41 -0
  285. package/dist/integration/browser/service.js +181 -0
  286. package/dist/integration/browser/stealth.d.ts +42 -0
  287. package/dist/integration/browser/stealth.js +104 -0
  288. package/dist/integration/providers/anthropic-message-normalize.d.ts +20 -0
  289. package/dist/integration/providers/anthropic-message-normalize.js +48 -0
  290. package/dist/integration/providers/anthropic.js +27 -2
  291. package/dist/integration/providers/fetch-timeout.d.ts +17 -0
  292. package/dist/integration/providers/fetch-timeout.js +24 -0
  293. package/dist/integration/providers/openai.d.ts +8 -0
  294. package/dist/integration/providers/openai.js +41 -1
  295. package/dist/integration/providers/wire-dump-diff.js +2 -1
  296. package/dist/integration/providers/wire-dump.d.ts +56 -2
  297. package/dist/integration/providers/wire-dump.js +119 -6
  298. package/dist/integration/storage/archive-manager.d.ts +14 -2
  299. package/dist/integration/storage/archive-manager.js +24 -8
  300. package/dist/integration/storage/atomic-tmp.d.ts +12 -0
  301. package/dist/integration/storage/atomic-tmp.js +36 -0
  302. package/dist/integration/storage/jsonl.d.ts +9 -0
  303. package/dist/integration/storage/jsonl.js +137 -38
  304. package/dist/integration/storage/session-index.d.ts +5 -0
  305. package/dist/integration/storage/session-index.js +25 -4
  306. package/dist/integration/tools/assemble.d.ts +50 -0
  307. package/dist/integration/tools/assemble.js +137 -0
  308. package/dist/paths.d.ts +18 -0
  309. package/dist/paths.js +36 -0
  310. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +3 -1
  311. package/dist/subsystems/cognition-steward/conceptualize/handler.js +74 -5
  312. package/dist/subsystems/cognition-steward/consolidate/SUBSYSTEM.md +3 -2
  313. package/dist/subsystems/cognition-steward/consolidate/config.yaml +11 -2
  314. package/dist/subsystems/cognition-steward/consolidate/handler.d.ts +6 -3
  315. package/dist/subsystems/cognition-steward/consolidate/handler.js +266 -28
  316. package/dist/subsystems/memory-steward/backfill/handler.js +3 -2
  317. package/dist/subsystems/memory-steward/govern/config.yaml +6 -1
  318. package/dist/subsystems/wisdom-steward/attribute/config.yaml +5 -1
  319. package/dist/subsystems/wisdom-steward/formation/config.yaml +3 -0
  320. package/dist/subsystems/wisdom-steward/govern/config.yaml +6 -1
  321. package/package.json +5 -3
@@ -0,0 +1,825 @@
1
+ /**
2
+ * RegistryService — 租户与定义面服务(arch/multi-tenancy.md)。
3
+ *
4
+ * 核心原则:**租户内是「引用」,跨租户是「集成」**——租户内自由(互委派/共 session/
5
+ * 共挂载),跨租户一律不穿透。所有权锚=tenantId;ownerUserId=管理归属;visibility
6
+ * 决定租户内可见性。
7
+ *
8
+ * Q12:单机起步(gateway 进程内 + registry.db),API 按服务化契约设计——分布式时
9
+ * 迁 C 机服务、调用面不变。
10
+ */
11
+ import { randomBytes, randomUUID, scrypt as scryptCb, timingSafeEqual } from 'node:crypto';
12
+ import { promisify } from 'node:util';
13
+ const scryptAsync = promisify(scryptCb);
14
+ /** M3 等耗时路径的固定盐(防时序枚举;非凭据,公开无害) */
15
+ const DUMMY_SALT = 'octopi-dummy-salt-for-constant-time-auth';
16
+ import { RegistryDatabase } from './db.js';
17
+ const VISIBILITIES = ['private', 'tenant'];
18
+ const SESSION_POLICIES = ['per-user', 'per-chat', 'per-message'];
19
+ /** 保留字:platform 域哨兵不是真实租户(arch/multi-tenancy.md §6)——不得注册为租户 id */
20
+ const RESERVED_TENANT_IDS = new Set(['platform']);
21
+ export class RegistryService {
22
+ db;
23
+ constructor(db) {
24
+ this.db = db;
25
+ }
26
+ /**
27
+ * 创建 RegistryService
28
+ *
29
+ * @param options - 透传 RegistryDatabase 选项(dbPath/wal/busyTimeoutMs)
30
+ */
31
+ static async create(options) {
32
+ return new RegistryService(await RegistryDatabase.create(options));
33
+ }
34
+ close() {
35
+ this.db.close();
36
+ }
37
+ /**
38
+ * 注册用户(一用户=一租户策略):建 tenant + user(1:1)。
39
+ * 首个注册用户为平台 admin(Q13)。
40
+ *
41
+ * @param input - name(用户名/租户名,全局唯一)
42
+ * @returns 新建的 tenant 与 user
43
+ */
44
+ registerUser(input) {
45
+ const name = requireNonEmpty(input.name, 'user name');
46
+ const now = Date.now();
47
+ const tenantId = randomUUID();
48
+ const userId = randomUUID();
49
+ const isFirst = this.countUsers() === 0;
50
+ const raw = this.db.raw;
51
+ raw.exec('BEGIN');
52
+ try {
53
+ raw
54
+ .prepare('INSERT INTO tenants (tenant_id, name, created_at) VALUES (?, ?, ?)')
55
+ .run(tenantId, name, now);
56
+ raw
57
+ .prepare('INSERT INTO users (user_id, tenant_id, name, is_platform_admin, created_at) VALUES (?, ?, ?, ?, ?)')
58
+ .run(userId, tenantId, name, isFirst ? 1 : 0, now);
59
+ raw.exec('COMMIT');
60
+ }
61
+ catch (err) {
62
+ raw.exec('ROLLBACK');
63
+ throw err;
64
+ }
65
+ return {
66
+ tenant: { tenantId, name, createdAt: now },
67
+ user: { userId, tenantId, name, isPlatformAdmin: isFirst, createdAt: now },
68
+ };
69
+ }
70
+ /**
71
+ * 查询用户
72
+ *
73
+ * @param userId - 用户 id
74
+ */
75
+ getUser(userId) {
76
+ const row = this.db.raw
77
+ .prepare('SELECT user_id, tenant_id, name, is_platform_admin, created_at FROM users WHERE user_id = ?')
78
+ .get(userId);
79
+ if (!row)
80
+ return null;
81
+ return {
82
+ userId: row.user_id,
83
+ tenantId: row.tenant_id,
84
+ name: row.name,
85
+ isPlatformAdmin: row.is_platform_admin === 1,
86
+ createdAt: row.created_at,
87
+ };
88
+ }
89
+ /**
90
+ * 按用户名查询(MVP 登录面:token 会话 + 名称直登,口令/SSO 属 P3)。
91
+ *
92
+ * @param name - 用户名(全局唯一)
93
+ */
94
+ getUserByName(name) {
95
+ const row = this.db.raw
96
+ .prepare('SELECT user_id, tenant_id, name, is_platform_admin, created_at FROM users WHERE name = ?')
97
+ .get(name);
98
+ if (!row)
99
+ return null;
100
+ return {
101
+ userId: row.user_id,
102
+ tenantId: row.tenant_id,
103
+ name: row.name,
104
+ isPlatformAdmin: row.is_platform_admin === 1,
105
+ createdAt: row.created_at,
106
+ };
107
+ }
108
+ /**
109
+ * 创建 agent。所有权锚=tenantId;owner 须属于该租户。
110
+ *
111
+ * @param input - 租户/owner/名称/定义/可见性
112
+ */
113
+ createAgent(input) {
114
+ const name = requireNonEmpty(input.name, 'agent name');
115
+ const visibility = input.visibility ?? 'private';
116
+ if (!VISIBILITIES.includes(visibility)) {
117
+ throw new Error(`registry_invalid_visibility: ${visibility}`);
118
+ }
119
+ if (input.definition !== undefined) {
120
+ requireJson(input.definition);
121
+ }
122
+ this.requireTenant(input.tenantId);
123
+ const owner = this.getUser(input.ownerUserId);
124
+ if (!owner)
125
+ throw new Error(`registry_user_not_found: ${input.ownerUserId}`);
126
+ if (owner.tenantId !== input.tenantId) {
127
+ // 跨租户不可拥有/管理 agent(§8 同一性:管理关系也不出租户)
128
+ throw new Error('registry_cross_tenant_owner: owner must belong to the agent tenant');
129
+ }
130
+ const now = Date.now();
131
+ const record = {
132
+ agentId: randomUUID(),
133
+ tenantId: input.tenantId,
134
+ ownerUserId: input.ownerUserId,
135
+ visibility,
136
+ name,
137
+ definition: input.definition ?? '{}',
138
+ homeRef: input.homeRef ?? null,
139
+ createdAt: now,
140
+ updatedAt: now,
141
+ };
142
+ this.db.raw
143
+ .prepare('INSERT INTO agents (agent_id, tenant_id, owner_user_id, visibility, name, definition, home_ref, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')
144
+ .run(record.agentId, record.tenantId, record.ownerUserId, record.visibility, record.name, record.definition, record.homeRef, record.createdAt, record.updatedAt);
145
+ return record;
146
+ }
147
+ /**
148
+ * 列出 viewer 可见的 agent:private=仅 owner;tenant=租户共享。
149
+ *
150
+ * @param input - 租户与查看者
151
+ */
152
+ listAgents(input) {
153
+ const rows = this.db.raw
154
+ .prepare('SELECT * FROM agents WHERE tenant_id = ? AND (visibility = ? OR owner_user_id = ?) ORDER BY created_at')
155
+ .all(input.tenantId, 'tenant', input.viewerUserId);
156
+ return rows.map(rowToAgent);
157
+ }
158
+ /**
159
+ * 查询知识源定义(不做可见性过滤——管理面)。
160
+ *
161
+ * @param sourceId - 知识面行 id(knowledge.db id)
162
+ */
163
+ getKnowledgeSource(sourceId) {
164
+ const row = this.db.raw
165
+ .prepare('SELECT * FROM knowledge_sources WHERE source_id = ?')
166
+ .get(sourceId);
167
+ return row ? rowToSource(row) : null;
168
+ }
169
+ /**
170
+ * 列知识源定义(T3b 管理面):platform 库 + 本租户库;平台 admin 全量。
171
+ *
172
+ * @param input - 调用方租户 / admin
173
+ */
174
+ listKnowledgeSources(input) {
175
+ const rows = input.isPlatformAdmin
176
+ ? this.db.raw
177
+ .prepare('SELECT * FROM knowledge_sources ORDER BY created_at')
178
+ .all()
179
+ : this.db.raw
180
+ .prepare(`SELECT * FROM knowledge_sources
181
+ WHERE scope = 'platform' OR tenant_id = ?
182
+ ORDER BY created_at`)
183
+ .all(input.viewerTenantId);
184
+ return rows.map(rowToSource);
185
+ }
186
+ /**
187
+ * 知识源写权限断言(platform 库=平台 admin;tenant 库=本租户)。返回记录供调用方使用。
188
+ *
189
+ * @param input - sourceId + 调用方租户/admin
190
+ */
191
+ assertKnowledgeSourceAccess(input) {
192
+ const source = this.requireSource(input.sourceId);
193
+ if (source.scope === 'platform') {
194
+ if (!input.isPlatformAdmin) {
195
+ throw new Error('registry_forbidden: platform sources are managed by platform admin');
196
+ }
197
+ }
198
+ else if (source.tenantId !== input.viewerTenantId) {
199
+ throw new Error('registry_cross_tenant: source belongs to another tenant');
200
+ }
201
+ return source;
202
+ }
203
+ /**
204
+ * 查询 agent(不做可见性过滤——调用方按需用 listAgents)。
205
+ *
206
+ * @param agentId - agent id
207
+ */
208
+ getAgent(agentId) {
209
+ const row = this.db.raw.prepare('SELECT * FROM agents WHERE agent_id = ?').get(agentId);
210
+ return row ? rowToAgent(row) : null;
211
+ }
212
+ /**
213
+ * 列出全部 agent(宿主管理面:启动装载 / 对账;租户过滤的可见列表用 listAgents)。
214
+ */
215
+ listAllAgents() {
216
+ const rows = this.db.raw
217
+ .prepare('SELECT * FROM agents ORDER BY created_at')
218
+ .all();
219
+ return rows.map(rowToAgent);
220
+ }
221
+ /**
222
+ * 租户是否存在(渠道锚启动校验用)。
223
+ *
224
+ * @param tenantId - 租户 id
225
+ */
226
+ hasTenant(tenantId) {
227
+ return this.db.raw.prepare('SELECT 1 FROM tenants WHERE tenant_id = ?').get(tenantId) !== undefined;
228
+ }
229
+ /**
230
+ * 更新 agent(写权限:owner 或平台 admin)。
231
+ *
232
+ * @param input - agentId + viewerUserId + 变更补丁
233
+ */
234
+ updateAgent(input) {
235
+ const record = this.requireAgent(input.agentId);
236
+ this.requireManageAuth(record, input.viewerUserId);
237
+ const patch = input.patch;
238
+ if (patch.definition !== undefined)
239
+ requireJson(patch.definition);
240
+ if (patch.visibility !== undefined && !VISIBILITIES.includes(patch.visibility)) {
241
+ throw new Error(`registry_invalid_visibility: ${patch.visibility}`);
242
+ }
243
+ const updated = {
244
+ ...record,
245
+ name: patch.name !== undefined ? requireNonEmpty(patch.name, 'agent name') : record.name,
246
+ definition: patch.definition ?? record.definition,
247
+ visibility: patch.visibility ?? record.visibility,
248
+ homeRef: patch.homeRef !== undefined ? patch.homeRef : record.homeRef,
249
+ updatedAt: Date.now(),
250
+ };
251
+ this.db.raw
252
+ .prepare('UPDATE agents SET name = ?, definition = ?, visibility = ?, home_ref = ?, updated_at = ? WHERE agent_id = ?')
253
+ .run(updated.name, updated.definition, updated.visibility, updated.homeRef, updated.updatedAt, updated.agentId);
254
+ return updated;
255
+ }
256
+ /**
257
+ * 删除 agent(写权限:owner 或平台 admin)。
258
+ *
259
+ * @param input - agentId + viewerUserId
260
+ * @returns 是否删除了记录
261
+ */
262
+ deleteAgent(input) {
263
+ const record = this.requireAgent(input.agentId);
264
+ this.requireManageAuth(record, input.viewerUserId);
265
+ // 幽灵绑定防线(评审 MIN-12):agent 消失后 bindings 行若留存,命中者会永久走
266
+ // 「绑定指向不可跑 agent」的弃收路径——删除时一并清掉,不留配置漂移
267
+ this.db.raw.prepare('DELETE FROM bindings WHERE agent_id = ?').run(record.agentId);
268
+ const res = this.db.raw.prepare('DELETE FROM agents WHERE agent_id = ?').run(record.agentId);
269
+ return res.changes > 0;
270
+ }
271
+ /**
272
+ * 创建渠道绑定(路由真相源)。agent 须属于同租户(挂载/绑定不出租户)。
273
+ *
274
+ * @param input - 租户/平台/身份/agent/会话策略
275
+ */
276
+ createBinding(input) {
277
+ const platform = requireNonEmpty(input.platform, 'platform');
278
+ const identity = requireNonEmpty(input.identity, 'identity');
279
+ const sessionPolicy = input.sessionPolicy ?? 'per-user';
280
+ if (!SESSION_POLICIES.includes(sessionPolicy)) {
281
+ throw new Error(`registry_invalid_session_policy: ${sessionPolicy}`);
282
+ }
283
+ // UNIQUE(tenant_id, platform, identity) 撞约束前先出干净错误(裸 SQLite 错不可读;
284
+ // 换目标走 updateBinding,不走删了重建)
285
+ const existing = this.resolveBinding({ tenantId: input.tenantId, platform, identity });
286
+ if (existing) {
287
+ throw new Error(`registry_binding_exists: ${platform}:${identity} already bound to ${existing.agentId}`);
288
+ }
289
+ const agent = this.requireAgent(input.agentId);
290
+ if (agent.tenantId !== input.tenantId) {
291
+ throw new Error('registry_cross_tenant_binding: binding must stay within one tenant');
292
+ }
293
+ const binding = {
294
+ bindingId: randomUUID(),
295
+ tenantId: input.tenantId,
296
+ platform,
297
+ identity,
298
+ agentId: input.agentId,
299
+ sessionPolicy,
300
+ createdAt: Date.now(),
301
+ };
302
+ try {
303
+ this.db.raw
304
+ .prepare('INSERT INTO bindings (binding_id, tenant_id, platform, identity, agent_id, session_policy, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
305
+ .run(binding.bindingId, binding.tenantId, binding.platform, binding.identity, binding.agentId, binding.sessionPolicy, binding.createdAt);
306
+ }
307
+ catch (err) {
308
+ // 预检(registry_binding_exists)是 TOCTOU:并发下仍会撞 UNIQUE(tenant_id,platform,identity)——
309
+ // 在此转成同一分类的干净错误,HTTP 面状态码不依赖 SQLite 文本(评审 MIN-7)
310
+ if (err instanceof Error && err.message.includes('UNIQUE constraint failed')) {
311
+ throw new Error(`registry_binding_exists: ${binding.platform}:${binding.identity} is already bound (concurrent create)`);
312
+ }
313
+ throw err;
314
+ }
315
+ return binding;
316
+ }
317
+ /**
318
+ * 解析渠道绑定(§2.3 ② 绑定解析)。
319
+ *
320
+ * @param input - 租户/平台/身份
321
+ */
322
+ resolveBinding(input) {
323
+ const row = this.db.raw
324
+ .prepare('SELECT * FROM bindings WHERE tenant_id = ? AND platform = ? AND identity = ?')
325
+ .get(input.tenantId, input.platform, input.identity);
326
+ return row ? rowToBinding(row) : null;
327
+ }
328
+ /**
329
+ * 创建挂载(租户内 consumer→source)。source 须为 platform 公共或同租户私有。
330
+ *
331
+ * @param input - 租户/消费方/资产
332
+ */
333
+ createMount(input) {
334
+ const source = this.requireSource(input.sourceId);
335
+ const sameTenant = source.scope === 'tenant' && source.tenantId === input.tenantId;
336
+ const isPlatform = source.scope === 'platform';
337
+ if (!sameTenant && !isPlatform) {
338
+ // 挂载不出租户:跨租户共享唯一合法形态=platform 公共库(§6)
339
+ throw new Error('registry_cross_tenant_mount: only platform sources may cross tenants');
340
+ }
341
+ const mount = {
342
+ mountId: randomUUID(),
343
+ tenantId: input.tenantId,
344
+ consumerType: input.consumerType,
345
+ consumerId: requireNonEmpty(input.consumerId, 'consumer id'),
346
+ sourceType: input.sourceType,
347
+ sourceId: input.sourceId,
348
+ agentRef: input.consumerType === 'session' ? requireNonEmpty(input.agentRef ?? '', 'agent ref') : (input.agentRef ?? null),
349
+ createdAt: Date.now(),
350
+ };
351
+ this.db.raw
352
+ .prepare('INSERT INTO mounts (mount_id, tenant_id, consumer_type, consumer_id, source_type, source_id, agent_ref, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)')
353
+ .run(mount.mountId, mount.tenantId, mount.consumerType, mount.consumerId, mount.sourceType, mount.sourceId, mount.agentRef, mount.createdAt);
354
+ return mount;
355
+ }
356
+ /**
357
+ * 可见知识源集合(§6 检索上下文):挂载库 ∪ 本租户公共 ∪ platform 公共。
358
+ *
359
+ * @param input - 租户 + 消费方
360
+ */
361
+ listVisibleSources(input) {
362
+ const rows = this.db.raw
363
+ .prepare(`SELECT DISTINCT ks.* FROM knowledge_sources ks
364
+ WHERE ks.scope = 'platform'
365
+ OR ks.tenant_id = ?
366
+ OR ks.source_id IN (
367
+ SELECT m.source_id FROM mounts m
368
+ WHERE m.tenant_id = ? AND m.consumer_type = ? AND m.consumer_id = ?
369
+ )`)
370
+ .all(input.tenantId, input.tenantId, input.consumerType, input.consumerId);
371
+ return rows.map(rowToSource);
372
+ }
373
+ /**
374
+ * 创建知识源(platform 公共 / tenant 私有)。
375
+ *
376
+ * @param input - scope/tenantId/name
377
+ */
378
+ createKnowledgeSource(input) {
379
+ const name = requireNonEmpty(input.name, 'source name');
380
+ if (input.scope === 'tenant') {
381
+ if (!input.tenantId)
382
+ throw new Error('registry_source_tenant_required: tenant scope needs tenantId');
383
+ if (RESERVED_TENANT_IDS.has(input.tenantId)) {
384
+ throw new Error(`registry_reserved_tenant: "${input.tenantId}" is reserved (platform domain sentinel)`);
385
+ }
386
+ this.requireTenant(input.tenantId);
387
+ }
388
+ const source = {
389
+ sourceId: (input.sourceId ?? randomUUID()),
390
+ scope: input.scope,
391
+ tenantId: input.scope === 'tenant' ? input.tenantId : null,
392
+ name,
393
+ createdAt: Date.now(),
394
+ };
395
+ this.db.raw
396
+ .prepare('INSERT INTO knowledge_sources (source_id, scope, tenant_id, name, created_at) VALUES (?, ?, ?, ?, ?)')
397
+ .run(source.sourceId, source.scope, source.tenantId, source.name, source.createdAt);
398
+ return source;
399
+ }
400
+ /**
401
+ * 删除知识源定义(连带删除其挂载)。platform 库仅平台 admin;tenant 库限本租户。
402
+ *
403
+ * @param input - sourceId + 调用方租户/admin
404
+ * @returns 是否删除了记录
405
+ */
406
+ deleteKnowledgeSource(input) {
407
+ const source = this.assertKnowledgeSourceAccess(input);
408
+ this.db.raw.prepare('DELETE FROM mounts WHERE source_id = ?').run(source.sourceId);
409
+ const res = this.db.raw.prepare('DELETE FROM knowledge_sources WHERE source_id = ?').run(source.sourceId);
410
+ return Number(res.changes ?? 0) > 0;
411
+ }
412
+ /**
413
+ * 列挂载(按消费方或资产过滤;租户收口——platform 库挂载可见,他租户挂载不出界)。
414
+ *
415
+ * @param input - 租户 + 过滤条件
416
+ */
417
+ listMounts(input) {
418
+ const clauses = ['m.tenant_id = ?'];
419
+ const params = [input.tenantId];
420
+ if (input.consumerType) {
421
+ clauses.push('m.consumer_type = ?');
422
+ params.push(input.consumerType);
423
+ }
424
+ if (input.consumerId) {
425
+ clauses.push('m.consumer_id = ?');
426
+ params.push(input.consumerId);
427
+ }
428
+ if (input.sourceId) {
429
+ clauses.push('m.source_id = ?');
430
+ params.push(input.sourceId);
431
+ }
432
+ const rows = this.db.raw
433
+ .prepare(`SELECT * FROM mounts m WHERE ${clauses.join(' AND ')} ORDER BY m.created_at`)
434
+ .all(...params);
435
+ return rows.map(rowToMount);
436
+ }
437
+ /**
438
+ * 查询挂载(管理面)。
439
+ *
440
+ * @param mountId - 挂载 id
441
+ */
442
+ getMount(mountId) {
443
+ const row = this.db.raw
444
+ .prepare('SELECT * FROM mounts WHERE mount_id = ?')
445
+ .get(mountId);
446
+ return row ? rowToMount(row) : null;
447
+ }
448
+ /**
449
+ * 删除挂载(租户收口:本租户挂载才可删)。
450
+ *
451
+ * @param input - mountId + 调用方租户
452
+ * @returns 是否删除了记录
453
+ */
454
+ deleteMount(input) {
455
+ const row = this.db.raw
456
+ .prepare('SELECT tenant_id FROM mounts WHERE mount_id = ?')
457
+ .get(input.mountId);
458
+ if (!row)
459
+ return false;
460
+ if (row.tenant_id !== input.tenantId) {
461
+ throw new Error('registry_cross_tenant: mount belongs to another tenant');
462
+ }
463
+ const res = this.db.raw.prepare('DELETE FROM mounts WHERE mount_id = ?').run(input.mountId);
464
+ return Number(res.changes ?? 0) > 0;
465
+ }
466
+ /**
467
+ * 签发会话 token(MVP 鉴权:token 会话;企业 SSO 属 P3)。
468
+ *
469
+ * @param userId - 用户 id
470
+ * @param ttlMs - 可选有效期(毫秒);缺省不过期(兼容存量语义)
471
+ * @returns 不透明 token(存储于 registry.db auth_tokens)
472
+ */
473
+ issueToken(userId, ttlMs) {
474
+ if (!this.getUser(userId))
475
+ throw new Error(`registry_user_not_found: ${userId}`);
476
+ const token = randomUUID();
477
+ const now = Date.now();
478
+ this.db.raw
479
+ .prepare('INSERT INTO auth_tokens (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)')
480
+ .run(token, userId, now, ttlMs ? now + ttlMs : null);
481
+ return token;
482
+ }
483
+ /**
484
+ * 解析会话 token → 用户(过期 token 视为无效并顺手清除)。
485
+ *
486
+ * @param token - Bearer token
487
+ */
488
+ resolveToken(token) {
489
+ if (!token.trim())
490
+ return null;
491
+ const row = this.db.raw.prepare('SELECT user_id, expires_at FROM auth_tokens WHERE token = ?').get(token);
492
+ if (!row)
493
+ return null;
494
+ if (row.expires_at != null && row.expires_at < Date.now()) {
495
+ this.revokeToken(token); // 过期条目不留账面(防无限堆积)
496
+ return null;
497
+ }
498
+ return this.getUser(row.user_id);
499
+ }
500
+ /**
501
+ * 撤销会话 token。
502
+ *
503
+ * @param token - Bearer token
504
+ * @returns 是否撤销了记录
505
+ */
506
+ revokeToken(token) {
507
+ return this.db.raw.prepare('DELETE FROM auth_tokens WHERE token = ?').run(token).changes > 0;
508
+ }
509
+ /**
510
+ * 设置/更新用户密码(scrypt + 随机盐;节点内置,不引第三方依赖)。
511
+ *
512
+ * 异步 scrypt 走线程池,不阻塞事件循环(评审 M5)。
513
+ *
514
+ * @param userId - 用户 id
515
+ * @param password - 明文密码(两遍确认等 UX 由调用方负责)
516
+ * @throws registry_user_not_found 用户不存在
517
+ */
518
+ async setUserPassword(userId, password) {
519
+ if (!this.getUser(userId))
520
+ throw new Error(`registry_user_not_found: ${userId}`);
521
+ if (!password)
522
+ throw new Error('registry_password_required');
523
+ const salt = randomBytes(16).toString('hex');
524
+ const hash = (await scryptAsync(password, salt, 32)).toString('hex');
525
+ this.db.raw
526
+ .prepare('UPDATE users SET password_hash = ?, password_salt = ? WHERE user_id = ?')
527
+ .run(hash, salt, userId);
528
+ }
529
+ /**
530
+ * 用户是否已设密码(路由层据此决定是否强制验密)。
531
+ *
532
+ * @param userId - 用户 id
533
+ */
534
+ hasPassword(userId) {
535
+ const row = this.db.raw
536
+ .prepare('SELECT password_hash FROM users WHERE user_id = ?')
537
+ .get(userId);
538
+ return Boolean(row?.password_hash);
539
+ }
540
+ /**
541
+ * 密码登录校验(product-onboarding.md §6:身份 = (tenant, name) 二元组 + 密码)。
542
+ *
543
+ * tenant 显式给定时按二元组定位(多租户撞名消歧);缺省按用户名唯一定位
544
+ * (registerUser 一用户一租户的形态)。返回 null 的一切路径**等耗时**(评审 M3:
545
+ * 未知用户/无密码用户也跑一次等价 KDF,抹平时序侧信道);比较用 timingSafeEqual。
546
+ * 无密码用户返回 null——免密语义只属于 loopback 名登录兼容路径。
547
+ *
548
+ * @param input - 用户名 + 明文密码(可选组织/租户名)
549
+ * @returns 校验通过的用户;失败 null
550
+ */
551
+ async authenticate(input) {
552
+ const row = input.tenant
553
+ ? this.db.raw
554
+ .prepare(`SELECT u.user_id AS user_id FROM users u JOIN tenants t ON t.tenant_id = u.tenant_id
555
+ WHERE t.name = ? AND u.name = ?`)
556
+ .get(input.tenant, input.name)
557
+ : this.db.raw.prepare('SELECT user_id FROM users WHERE name = ?').get(input.name);
558
+ const cred = row
559
+ ? this.db.raw
560
+ .prepare('SELECT password_hash, password_salt FROM users WHERE user_id = ?')
561
+ .get(row.user_id)
562
+ : undefined;
563
+ if (!cred?.password_hash || !cred.password_salt) {
564
+ // 等耗时路径:对固定 dummy 盐跑同参 KDF(几十 ms),未知用户不再微秒返回
565
+ await scryptAsync(input.password, DUMMY_SALT, 32);
566
+ return null;
567
+ }
568
+ const hash = await scryptAsync(input.password, cred.password_salt, 32);
569
+ const expected = Buffer.from(cred.password_hash, 'hex');
570
+ if (hash.length !== expected.length || !timingSafeEqual(hash, expected))
571
+ return null;
572
+ return this.getUser(row.user_id);
573
+ }
574
+ /**
575
+ * 在既有租户内创建用户(②③部署模式的成员面;registerUser「一用户一租户」之外的补充入口)。
576
+ *
577
+ * 插入 + 设密同事务(m7 对称 registerUser):设密失败不留「无密码半用户」。
578
+ *
579
+ * @param input - tenantId + name + 可选 password / isPlatformAdmin
580
+ * @returns 新建用户
581
+ * @throws registry_tenant_not_found / registry_password 相关
582
+ */
583
+ async createUserInTenant(input) {
584
+ const name = requireNonEmpty(input.name, 'user name');
585
+ if (!this.hasTenant(input.tenantId))
586
+ throw new Error(`registry_tenant_not_found: ${input.tenantId}`);
587
+ const now = Date.now();
588
+ const userId = randomUUID();
589
+ this.db.raw.exec('BEGIN');
590
+ try {
591
+ this.db.raw
592
+ .prepare('INSERT INTO users (user_id, tenant_id, name, is_platform_admin, created_at) VALUES (?, ?, ?, ?, ?)')
593
+ .run(userId, input.tenantId, name, input.isPlatformAdmin ? 1 : 0, now);
594
+ if (input.password)
595
+ await this.setUserPassword(userId, input.password);
596
+ this.db.raw.exec('COMMIT');
597
+ }
598
+ catch (err) {
599
+ this.db.raw.exec('ROLLBACK');
600
+ throw err;
601
+ }
602
+ return {
603
+ userId,
604
+ tenantId: input.tenantId,
605
+ name,
606
+ isPlatformAdmin: Boolean(input.isPlatformAdmin),
607
+ createdAt: now,
608
+ };
609
+ }
610
+ /**
611
+ * 按 (tenantId, name) 取用户(部署模式播种的精确查找,M10;不做全局名碰撞误配)。
612
+ *
613
+ * @param tenantId - 租户 id
614
+ * @param name - 用户名
615
+ */
616
+ getUserInTenant(tenantId, name) {
617
+ const row = this.db.raw
618
+ .prepare('SELECT user_id FROM users WHERE tenant_id = ? AND name = ?')
619
+ .get(tenantId, name);
620
+ return row ? this.getUser(row.user_id) : null;
621
+ }
622
+ /**
623
+ * 幂等确保租户存在(部署模式播种用;registerUser「一用户一租户」之外的主机侧配置面)。
624
+ *
625
+ * @param name - 租户(组织)名
626
+ * @param explicitId - 显式租户 id(personal/②模式用 'default' = core DEFAULT_TENANT_ID 语义,
627
+ * 与 config agent 的 default 域同 ID 空间;缺省自生成 uuid)
628
+ * @returns 租户(已存在则返回既有;同 id 撞异名 fail-loud)
629
+ * @throws registry_tenant_id_conflict 显式 id 已被不同名占用
630
+ */
631
+ ensureTenant(name, explicitId) {
632
+ const tenantName = requireNonEmpty(name, 'tenant name');
633
+ const existing = this.db.raw.prepare('SELECT tenant_id, name, created_at FROM tenants WHERE name = ?').get(tenantName);
634
+ if (existing) {
635
+ return { tenantId: existing.tenant_id, name: existing.name, createdAt: existing.created_at };
636
+ }
637
+ if (explicitId) {
638
+ const byId = this.db.raw.prepare('SELECT tenant_id, name, created_at FROM tenants WHERE tenant_id = ?').get(explicitId);
639
+ if (byId) {
640
+ if (byId.name !== tenantName) {
641
+ throw new Error(`registry_tenant_id_conflict: id ${explicitId} 已被租户「${byId.name}」占用`);
642
+ }
643
+ return { tenantId: byId.tenant_id, name: byId.name, createdAt: byId.created_at };
644
+ }
645
+ }
646
+ const now = Date.now();
647
+ const tenantId = (explicitId ?? randomUUID());
648
+ this.db.raw.prepare('INSERT INTO tenants (tenant_id, name, created_at) VALUES (?, ?, ?)').run(tenantId, tenantName, now);
649
+ return { tenantId, name: tenantName, createdAt: now };
650
+ }
651
+ /**
652
+ * 列出租户内绑定(渠道路由真相源)。
653
+ *
654
+ * @param input - 租户
655
+ */
656
+ listBindings(input) {
657
+ const rows = this.db.raw
658
+ .prepare('SELECT * FROM bindings WHERE tenant_id = ? ORDER BY created_at')
659
+ .all(input.tenantId);
660
+ return rows.map(rowToBinding);
661
+ }
662
+ /**
663
+ * 查询单条绑定(管理面)。
664
+ *
665
+ * @param bindingId - 绑定 id
666
+ */
667
+ getBinding(bindingId) {
668
+ const row = this.db.raw.prepare('SELECT * FROM bindings WHERE binding_id = ?').get(bindingId);
669
+ return row ? rowToBinding(row) : null;
670
+ }
671
+ /**
672
+ * 更新绑定(换目标 agent / 会话策略)。绑定是租户资产:tenantId 域内可管;
673
+ * 换目标 agent 时重验租户内约束(与 createBinding 同闸)。
674
+ *
675
+ * @param input - bindingId + 租户域 + 变更补丁
676
+ */
677
+ updateBinding(input) {
678
+ const binding = this.requireBinding(input.bindingId, input.tenantId);
679
+ const patch = input.patch;
680
+ if (patch.sessionPolicy !== undefined && !SESSION_POLICIES.includes(patch.sessionPolicy)) {
681
+ throw new Error(`registry_invalid_session_policy: ${patch.sessionPolicy}`);
682
+ }
683
+ if (patch.agentId !== undefined) {
684
+ const agent = this.requireAgent(patch.agentId);
685
+ if (agent.tenantId !== binding.tenantId) {
686
+ throw new Error('registry_cross_tenant_binding: binding must stay within one tenant');
687
+ }
688
+ }
689
+ const nextAgent = patch.agentId ?? binding.agentId;
690
+ const nextPolicy = patch.sessionPolicy ?? binding.sessionPolicy;
691
+ this.db.raw
692
+ .prepare('UPDATE bindings SET agent_id = ?, session_policy = ? WHERE binding_id = ?')
693
+ .run(nextAgent, nextPolicy, binding.bindingId);
694
+ return { ...binding, agentId: nextAgent, sessionPolicy: nextPolicy };
695
+ }
696
+ /**
697
+ * 删除绑定(租户域内)。行不存在或不属本租户 = false(幂等重试不炸)。
698
+ *
699
+ * @param input - bindingId + 租户域
700
+ * @returns 是否删除了记录
701
+ */
702
+ deleteBinding(input) {
703
+ const binding = this.getBinding(input.bindingId);
704
+ if (!binding || binding.tenantId !== input.tenantId)
705
+ return false;
706
+ this.db.raw.prepare('DELETE FROM bindings WHERE binding_id = ?').run(input.bindingId);
707
+ return true;
708
+ }
709
+ requireBinding(bindingId, tenantId) {
710
+ const binding = this.getBinding(bindingId);
711
+ if (!binding || binding.tenantId !== tenantId) {
712
+ throw new Error(`registry_binding_not_found: ${bindingId}`);
713
+ }
714
+ return binding;
715
+ }
716
+ /**
717
+ * 同租户断言(§8 委派/参与边界的执行点):一组 agent 必须同属一个租户。
718
+ *
719
+ * @param agentIds - 参与 agent 列表
720
+ * @returns 共同租户 id
721
+ */
722
+ assertSameTenant(agentIds) {
723
+ if (agentIds.length === 0)
724
+ throw new Error('registry_empty_agent_set: need at least one agent');
725
+ const first = this.requireAgent(agentIds[0]);
726
+ for (const id of agentIds.slice(1)) {
727
+ const agent = this.requireAgent(id);
728
+ if (agent.tenantId !== first.tenantId) {
729
+ throw new Error('registry_cross_tenant_participation: agents must belong to one tenant');
730
+ }
731
+ }
732
+ return first.tenantId;
733
+ }
734
+ countUsers() {
735
+ const row = this.db.raw.prepare('SELECT COUNT(*) AS n FROM users').get();
736
+ return row.n;
737
+ }
738
+ requireTenant(tenantId) {
739
+ const row = this.db.raw.prepare('SELECT * FROM tenants WHERE tenant_id = ?').get(tenantId);
740
+ if (!row)
741
+ throw new Error(`registry_tenant_not_found: ${tenantId}`);
742
+ return { tenantId: row.tenant_id, name: row.name, createdAt: row.created_at };
743
+ }
744
+ requireAgent(agentId) {
745
+ const record = this.getAgent(agentId);
746
+ if (!record)
747
+ throw new Error(`registry_agent_not_found: ${agentId}`);
748
+ return record;
749
+ }
750
+ requireSource(sourceId) {
751
+ const row = this.db.raw.prepare('SELECT * FROM knowledge_sources WHERE source_id = ?').get(sourceId);
752
+ if (!row)
753
+ throw new Error(`registry_source_not_found: ${sourceId}`);
754
+ return rowToSource(row);
755
+ }
756
+ requireManageAuth(record, viewerUserId) {
757
+ const viewer = this.getUser(viewerUserId);
758
+ if (!viewer)
759
+ throw new Error(`registry_user_not_found: ${viewerUserId}`);
760
+ if (viewer.isPlatformAdmin)
761
+ return;
762
+ if (viewer.userId !== record.ownerUserId || viewer.tenantId !== record.tenantId) {
763
+ throw new Error('registry_forbidden: only the owner or a platform admin may manage this agent');
764
+ }
765
+ }
766
+ }
767
+ function requireNonEmpty(value, label) {
768
+ const trimmed = value.trim();
769
+ if (!trimmed)
770
+ throw new Error(`registry_invalid_${label.replace(/ /g, '_')}: must be non-empty`);
771
+ return trimmed;
772
+ }
773
+ function requireJson(value) {
774
+ try {
775
+ JSON.parse(value);
776
+ }
777
+ catch {
778
+ throw new Error('registry_invalid_definition: must be valid JSON text');
779
+ }
780
+ }
781
+ function rowToAgent(row) {
782
+ return {
783
+ agentId: row.agent_id,
784
+ tenantId: row.tenant_id,
785
+ ownerUserId: row.owner_user_id,
786
+ visibility: row.visibility,
787
+ name: row.name,
788
+ definition: row.definition,
789
+ homeRef: row.home_ref ?? null,
790
+ createdAt: row.created_at,
791
+ updatedAt: row.updated_at,
792
+ };
793
+ }
794
+ function rowToBinding(row) {
795
+ return {
796
+ bindingId: row.binding_id,
797
+ tenantId: row.tenant_id,
798
+ platform: row.platform,
799
+ identity: row.identity,
800
+ agentId: row.agent_id,
801
+ sessionPolicy: row.session_policy,
802
+ createdAt: row.created_at,
803
+ };
804
+ }
805
+ function rowToSource(row) {
806
+ return {
807
+ sourceId: row.source_id,
808
+ scope: row.scope,
809
+ tenantId: row.tenant_id ?? null,
810
+ name: row.name,
811
+ createdAt: row.created_at,
812
+ };
813
+ }
814
+ function rowToMount(row) {
815
+ return {
816
+ mountId: row.mount_id,
817
+ tenantId: row.tenant_id,
818
+ consumerType: row.consumer_type,
819
+ consumerId: row.consumer_id,
820
+ sourceType: row.source_type,
821
+ sourceId: row.source_id,
822
+ agentRef: row.agent_ref ?? null,
823
+ createdAt: row.created_at,
824
+ };
825
+ }