@sleep2agi/commhub-server 0.9.0-preview.27 → 0.9.0-preview.271

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 (446) hide show
  1. package/README.md +120 -3
  2. package/bin/commhub.ts +93 -9
  3. package/build-info.json +7 -0
  4. package/package.json +10 -8
  5. package/src/ack-create-request-transport.test.ts +182 -0
  6. package/src/ack-create-request.test.ts +52 -8
  7. package/src/admin-delete-network-http.test.ts +229 -0
  8. package/src/admin-networks-http.test.ts +88 -0
  9. package/src/adoption-candidates-http.test.ts +140 -0
  10. package/src/adoption-candidates.ts +158 -0
  11. package/src/agent-access-batch.test.ts +210 -0
  12. package/src/agent-access.ts +585 -0
  13. package/src/agent-acl-groups-http.test.ts +247 -0
  14. package/src/agent-acl-http.test.ts +691 -0
  15. package/src/agent-acl-slice3-http.test.ts +885 -0
  16. package/src/agent-department-grants.test.ts +129 -0
  17. package/src/agent-department-http.test.ts +215 -0
  18. package/src/agent-groups-perf.test.ts +223 -0
  19. package/src/agent-notice.ts +48 -0
  20. package/src/agent-team-whoami-http.test.ts +98 -0
  21. package/src/agent-teams-http.test.ts +330 -0
  22. package/src/agent-teams.ts +244 -0
  23. package/src/alias-baseline-2571.test.ts +162 -0
  24. package/src/alias-baseline.ts +113 -0
  25. package/src/alias-filter.test.ts +72 -0
  26. package/src/alias-filter.ts +42 -0
  27. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  28. package/src/api-host-supervisors-fallback.test.ts +6 -7
  29. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  30. package/src/api-nodes-shape.test.ts +131 -4
  31. package/src/auth-abuse-counters.test.ts +144 -0
  32. package/src/auth-abuse-counters.ts +122 -0
  33. package/src/auth-layer-shape.test.ts +105 -0
  34. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  35. package/src/auth-sessions-http.test.ts +260 -0
  36. package/src/auth-validate.test.ts +5 -1
  37. package/src/auth-weak-password-login.test.ts +176 -0
  38. package/src/auth.ts +641 -68
  39. package/src/backfill-node-ids-2664.test.ts +128 -0
  40. package/src/binding-generation-http.test.ts +141 -0
  41. package/src/blocked-exit-on-reply.test.ts +122 -0
  42. package/src/broadcast-fanout-2721.test.ts +149 -0
  43. package/src/broadcast-fanout.ts +117 -0
  44. package/src/build-commit-report-http.test.ts +128 -0
  45. package/src/build-info.test.ts +60 -0
  46. package/src/build-info.ts +85 -0
  47. package/src/chain-attempt-dedup.test.ts +447 -0
  48. package/src/clip.test.ts +36 -0
  49. package/src/clip.ts +48 -0
  50. package/src/clone-node.test.ts +269 -0
  51. package/src/clone-node.ts +289 -0
  52. package/src/codex-config-flags.ts +77 -0
  53. package/src/codex-fork-contract.ts +23 -0
  54. package/src/codex-fork-migration.test.ts +38 -0
  55. package/src/commhub-bin-args.test.ts +85 -0
  56. package/src/config-apply-validate.test.ts +188 -1
  57. package/src/config-apply-validate.ts +222 -3
  58. package/src/cors-origins.test.ts +73 -0
  59. package/src/create-node-blocked-gate.test.ts +365 -0
  60. package/src/create-node-error-domain.test.ts +127 -0
  61. package/src/create-node-network-id.test.ts +91 -0
  62. package/src/create-node-tool-schema.test.ts +49 -0
  63. package/src/create-node-unicode-name.test.ts +126 -0
  64. package/src/create-node-validate.test.ts +199 -7
  65. package/src/create-node-validate.ts +232 -15
  66. package/src/create-node-workdir.test.ts +298 -0
  67. package/src/create-node.ts +88 -23
  68. package/src/daemon-provider-snapshots.test.ts +453 -0
  69. package/src/daemon-provider-snapshots.ts +327 -0
  70. package/src/daemon-token-owner-http.test.ts +346 -0
  71. package/src/dashboard-slash-routing-http.test.ts +109 -0
  72. package/src/db-adapter-guard.test.ts +148 -0
  73. package/src/db-adapter-translate.test.ts +128 -0
  74. package/src/db-adapter.ts +377 -91
  75. package/src/db-timestamp.test.ts +38 -0
  76. package/src/db-timestamp.ts +15 -0
  77. package/src/db.ts +1298 -153
  78. package/src/delivered-without-push.test.ts +140 -0
  79. package/src/department-groups-http.test.ts +209 -0
  80. package/src/department-groups-sync-http.test.ts +328 -0
  81. package/src/department-groups.ts +434 -0
  82. package/src/department-heads-http.test.ts +350 -0
  83. package/src/department-heads.ts +226 -0
  84. package/src/departments-agent-count.test.ts +139 -0
  85. package/src/departments-http.test.ts +185 -0
  86. package/src/departments-mcp-error-domain.test.ts +135 -0
  87. package/src/departments-mcp.test.ts +128 -0
  88. package/src/departments.ts +318 -0
  89. package/src/desktop-message-seam.test.ts +150 -0
  90. package/src/desktop-message.test.ts +368 -0
  91. package/src/dm-file-scope-http.test.ts +227 -0
  92. package/src/empty-node-sweeper.test.ts +104 -0
  93. package/src/empty-node-sweeper.ts +88 -0
  94. package/src/env-transport-gate-http.test.ts +240 -0
  95. package/src/env-transport-gate.ts +80 -0
  96. package/src/env-transport-policy.ts +56 -0
  97. package/src/etag-of.test.ts +57 -0
  98. package/src/event-loop-lag.test.ts +180 -0
  99. package/src/event-loop-lag.ts +201 -0
  100. package/src/expiry-counters.test.ts +187 -0
  101. package/src/expiry-counters.ts +227 -0
  102. package/src/expiry-evidence-db.test.ts +103 -0
  103. package/src/ext-token-shared.test.ts +60 -0
  104. package/src/ext-validation-regression.test.ts +10 -17
  105. package/src/external-schedule-edits-http.test.ts +321 -0
  106. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  107. package/src/external-schedule-edits.ts +327 -0
  108. package/src/file-download-authz-dev-open.test.ts +1 -1
  109. package/src/file-download-authz.test.ts +25 -4
  110. package/src/file-download-date-bucket.test.ts +1 -1
  111. package/src/file-network-scope-dev-open.test.ts +1 -1
  112. package/src/file-network-scope.test.ts +7 -6
  113. package/src/group-membership-events-http.test.ts +264 -0
  114. package/src/group-messages-http.test.ts +483 -0
  115. package/src/group-messages.ts +297 -0
  116. package/src/health-anon-readers.ts +67 -0
  117. package/src/health-host-disk-2756.test.ts +71 -0
  118. package/src/health-identity-root.test.ts +98 -0
  119. package/src/health-redaction.test.ts +1599 -7
  120. package/src/health-status-reasons.test.ts +84 -0
  121. package/src/host-supervisor-identity-http.test.ts +152 -0
  122. package/src/host-supervisor-identity.ts +92 -0
  123. package/src/host-supervisors-daemon-version.test.ts +137 -0
  124. package/src/http-gzip.test.ts +94 -0
  125. package/src/http-gzip.ts +112 -0
  126. package/src/hub-catalog-read-http.test.ts +664 -0
  127. package/src/hub-provider-config.test.ts +166 -0
  128. package/src/hub-provider-config.ts +202 -0
  129. package/src/hub-timestamp.test.ts +38 -0
  130. package/src/hub-timestamp.ts +27 -0
  131. package/src/human-dm.ts +215 -0
  132. package/src/human-inbox.ts +42 -0
  133. package/src/inbox-caller.ts +49 -0
  134. package/src/inbox-count-sse.test.ts +318 -0
  135. package/src/inbox-count.ts +29 -0
  136. package/src/index.ts +6 -2
  137. package/src/license-state.test.ts +105 -0
  138. package/src/license-state.ts +48 -0
  139. package/src/lifecycle-error-domain.test.ts +149 -0
  140. package/src/list-ack-error-domain.test.ts +108 -0
  141. package/src/list-host-supervisors.test.ts +15 -4
  142. package/src/list-tasks-omit-default.test.ts +84 -0
  143. package/src/list-tasks-since-last.test.ts +100 -0
  144. package/src/list-tasks-since.test.ts +104 -0
  145. package/src/mcp-context-cost-http.test.ts +127 -0
  146. package/src/mcp-inflight.test.ts +92 -0
  147. package/src/mcp-inflight.ts +38 -0
  148. package/src/mcp-projects-events-http.test.ts +168 -0
  149. package/src/mcp-route-label-http.test.ts +120 -0
  150. package/src/mcp-write-network-resolution.test.ts +21 -0
  151. package/src/member-audit-network-id-http.test.ts +93 -0
  152. package/src/member-presence-http.test.ts +210 -0
  153. package/src/messages-ack-by-agent-http.test.ts +142 -0
  154. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  155. package/src/migrate-sqlite-to-pg.ts +263 -0
  156. package/src/model-auth-notify-http.test.ts +181 -0
  157. package/src/model-auth-notify.ts +116 -0
  158. package/src/network-name-http.test.ts +75 -0
  159. package/src/network-quota-config.test.ts +100 -0
  160. package/src/network-rules-http.test.ts +169 -0
  161. package/src/network-rules.ts +129 -0
  162. package/src/network-scope.ts +222 -3
  163. package/src/network-token-membership-http.test.ts +186 -0
  164. package/src/node-alias-control.ts +12 -0
  165. package/src/node-attrs.test.ts +47 -2
  166. package/src/node-caller-identity-http.test.ts +1108 -0
  167. package/src/node-config-last-update.test.ts +126 -0
  168. package/src/node-config-last-update.ts +107 -0
  169. package/src/node-create-request-status-http.test.ts +105 -0
  170. package/src/node-daemon-bindings.test.ts +142 -0
  171. package/src/node-daemon-bindings.ts +135 -0
  172. package/src/node-failure-alert.test.ts +150 -0
  173. package/src/node-failure-alert.ts +177 -0
  174. package/src/node-files-transport.test.ts +350 -0
  175. package/src/node-health-codex-login.test.ts +120 -0
  176. package/src/node-health-dispatch-http.test.ts +373 -0
  177. package/src/node-health-guard-origin.test.ts +98 -0
  178. package/src/node-health-guard.ts +121 -0
  179. package/src/node-health-passthrough.test.ts +115 -0
  180. package/src/node-health-store.ts +101 -0
  181. package/src/node-id-alias.test.ts +190 -0
  182. package/src/node-identity-conflict-http.test.ts +269 -0
  183. package/src/node-identity-conflict.ts +142 -0
  184. package/src/node-identity-mismatch.test.ts +74 -0
  185. package/src/node-in-flight-tasks.ts +31 -0
  186. package/src/node-lifecycle-controllable.test.ts +64 -0
  187. package/src/node-lifecycle-controllable.ts +53 -0
  188. package/src/node-lifecycle-read-http.test.ts +257 -0
  189. package/src/node-lifecycle-read.ts +124 -0
  190. package/src/node-logs-transport.test.ts +266 -0
  191. package/src/node-peer-allowlist.test.ts +114 -0
  192. package/src/node-permissions-http.test.ts +901 -0
  193. package/src/node-permissions.ts +496 -0
  194. package/src/node-request-retention.test.ts +281 -0
  195. package/src/node-request-retention.ts +120 -0
  196. package/src/node-secret-rest-http.test.ts +190 -0
  197. package/src/node-secret-vault-inject.test.ts +132 -0
  198. package/src/node-security-write-gate.test.ts +72 -0
  199. package/src/node-serviceability.test.ts +86 -0
  200. package/src/node-serviceability.ts +124 -0
  201. package/src/node-session-control-http.test.ts +310 -0
  202. package/src/node-session-control.ts +258 -0
  203. package/src/node-skills-transport.test.ts +212 -0
  204. package/src/node-token-identity.ts +35 -0
  205. package/src/node-token-ownership.ts +51 -0
  206. package/src/node-token-privilege-http.test.ts +224 -0
  207. package/src/node-token-usage.test.ts +90 -0
  208. package/src/node-token-usage.ts +164 -0
  209. package/src/not-found-api-http.test.ts +67 -0
  210. package/src/observer-avatar-http.test.ts +103 -10
  211. package/src/observer-push.test.ts +76 -0
  212. package/src/opencode-catalog-report-http.test.ts +139 -0
  213. package/src/opencode-v2-catalog.test.ts +268 -0
  214. package/src/opencode-v2-catalog.ts +356 -0
  215. package/src/package-version-consistency.test.ts +25 -0
  216. package/src/parent-infer.test.ts +82 -0
  217. package/src/parent-infer.ts +110 -0
  218. package/src/parent-source-marker.test.ts +70 -0
  219. package/src/parent-source-orphan.test.ts +121 -0
  220. package/src/password-network-tokens.ts +25 -0
  221. package/src/peer-reply-atomic.test.ts +462 -0
  222. package/src/peer-reply-capability.test.ts +70 -0
  223. package/src/pg-worker.ts +87 -0
  224. package/src/poll-pacing.test.ts +74 -0
  225. package/src/poll-pacing.ts +123 -0
  226. package/src/probe-provider-error-domain.test.ts +145 -0
  227. package/src/project-dir-warn-clear-http.test.ts +132 -0
  228. package/src/project-viewer-can-http.test.ts +116 -0
  229. package/src/provider-skill-error-domain.test.ts +130 -0
  230. package/src/provider-tools-shape.test.ts +165 -0
  231. package/src/push.test.ts +20 -10
  232. package/src/push.ts +373 -9
  233. package/src/redact-tokens.test.ts +86 -0
  234. package/src/redact-tokens.ts +43 -0
  235. package/src/rejection-counters.test.ts +72 -0
  236. package/src/rejection-counters.ts +173 -0
  237. package/src/rename.ts +38 -10
  238. package/src/reply-target-derivation.test.ts +96 -0
  239. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  240. package/src/report-status-host-schema.test.ts +235 -0
  241. package/src/report-status-resume-id-handover.test.ts +184 -0
  242. package/src/report-status-secret-keys.test.ts +140 -0
  243. package/src/require-explicit-test-db.ts +9 -0
  244. package/src/requirement-due-reminders-http.test.ts +620 -0
  245. package/src/requirement-due-reminders.ts +416 -0
  246. package/src/requirement-events-http.test.ts +318 -0
  247. package/src/requirement-events.test.ts +45 -0
  248. package/src/requirement-events.ts +144 -0
  249. package/src/requirement-notify.ts +165 -0
  250. package/src/requirement-participant-notify-http.test.ts +313 -0
  251. package/src/requirement-tag-ops-http.test.ts +454 -0
  252. package/src/requirement-tag-tree-http.test.ts +275 -0
  253. package/src/requirement-tag-tree.ts +127 -0
  254. package/src/requirement-tags.ts +102 -0
  255. package/src/requirements-abandoned-http.test.ts +236 -0
  256. package/src/requirements-assignee-drift.test.ts +154 -0
  257. package/src/requirements-comment-http.test.ts +174 -0
  258. package/src/requirements-completed-at-migration.test.ts +70 -0
  259. package/src/requirements-errors-mcp-http.test.ts +164 -0
  260. package/src/requirements-errors.ts +158 -0
  261. package/src/requirements-etag-http.test.ts +91 -0
  262. package/src/requirements-http.test.ts +709 -0
  263. package/src/requirements-last-event-http.test.ts +349 -0
  264. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  265. package/src/requirements-list-slim-http.test.ts +324 -0
  266. package/src/requirements-mcp.test.ts +180 -0
  267. package/src/requirements-migrate.ts +283 -0
  268. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  269. package/src/requirements-people-http.test.ts +114 -0
  270. package/src/requirements-people-mcp-http.test.ts +231 -0
  271. package/src/requirements-people.ts +196 -0
  272. package/src/requirements-priority-lowest.test.ts +114 -0
  273. package/src/requirements-projects-network-echo.test.ts +57 -0
  274. package/src/requirements-projects-parent-http.test.ts +123 -0
  275. package/src/requirements-search-http.test.ts +182 -0
  276. package/src/requirements-search.test.ts +32 -0
  277. package/src/requirements-search.ts +145 -0
  278. package/src/requirements-seq-http.test.ts +193 -0
  279. package/src/requirements-seq-migration.test.ts +63 -0
  280. package/src/requirements-start-date.test.ts +125 -0
  281. package/src/requirements-stats-http.test.ts +357 -0
  282. package/src/requirements-stats.ts +195 -0
  283. package/src/requirements-status-participants-http.test.ts +222 -0
  284. package/src/requirements-upgrade-e2e.test.ts +126 -0
  285. package/src/requirements-upgrade-migration.test.ts +98 -0
  286. package/src/requirements.ts +2205 -0
  287. package/src/resolve-port.test.ts +57 -0
  288. package/src/resolve-port.ts +44 -0
  289. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  290. package/src/rest-alias-network-fallback.test.ts +60 -0
  291. package/src/rest-alias-network-fallback.ts +65 -0
  292. package/src/rest-explicit-columns-http.test.ts +266 -0
  293. package/src/rest-identity.test.ts +130 -0
  294. package/src/rest-identity.ts +141 -0
  295. package/src/rest-projections.ts +72 -0
  296. package/src/rest-read-network-real-chain.test.ts +97 -0
  297. package/src/rest-write-network-resolution.test.ts +133 -0
  298. package/src/restart-readiness-http.test.ts +121 -0
  299. package/src/restricted-files.ts +76 -0
  300. package/src/retention-first-sweep-quiet.test.ts +31 -0
  301. package/src/retention.test.ts +100 -40
  302. package/src/retention.ts +423 -104
  303. package/src/route-callers-http.test.ts +120 -0
  304. package/src/route-timing.test.ts +218 -0
  305. package/src/route-timing.ts +262 -0
  306. package/src/rules-file-duplicate-alias.test.ts +234 -0
  307. package/src/rules-file-session-target.test.ts +207 -0
  308. package/src/rules-file-transport.test.ts +271 -0
  309. package/src/runtime-label.test.ts +22 -0
  310. package/src/runtime-label.ts +21 -0
  311. package/src/runtime-readiness.ts +90 -0
  312. package/src/schedule-agent-mcp-http.test.ts +486 -0
  313. package/src/schedule-agent.ts +252 -0
  314. package/src/schedule-starved.test.ts +92 -0
  315. package/src/schedule-starved.ts +114 -0
  316. package/src/scheduled-backoff-http.test.ts +203 -0
  317. package/src/scheduled-backoff.ts +64 -0
  318. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  319. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  320. package/src/scheduled-failure-code.test.ts +73 -0
  321. package/src/scheduled-failure-code.ts +105 -0
  322. package/src/scheduled-failures-http.test.ts +279 -0
  323. package/src/scheduled-failures.ts +425 -0
  324. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  325. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  326. package/src/scheduled-offline.test.ts +131 -0
  327. package/src/scheduled-offline.ts +66 -0
  328. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  329. package/src/scheduled-outcome-guidance.ts +9 -0
  330. package/src/scheduled-reply-unread-http.test.ts +212 -0
  331. package/src/scheduled-requirement-wake-http.test.ts +289 -0
  332. package/src/scheduled-requirement-wake.ts +125 -0
  333. package/src/scheduled-run-terminal.test.ts +290 -0
  334. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  335. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  336. package/src/scheduled-stuck-http.test.ts +316 -0
  337. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  338. package/src/scheduled-stuck.ts +219 -0
  339. package/src/scheduled-tasks-http.test.ts +679 -0
  340. package/src/scheduled-tasks.ts +959 -0
  341. package/src/scheduled-work-outcome-http.test.ts +154 -0
  342. package/src/scheduled-work-outcome.ts +50 -0
  343. package/src/scoped-secrets.ts +167 -0
  344. package/src/secret-echo-negative-control.test.ts +118 -0
  345. package/src/send-dedup-request-id.test.ts +229 -0
  346. package/src/send-reply-agent-warning.test.ts +38 -38
  347. package/src/send-reply-alias-optional.test.ts +131 -0
  348. package/src/send-reply-attachments.test.ts +28 -7
  349. package/src/send_dedup.test.ts +54 -0
  350. package/src/send_dedup.ts +52 -6
  351. package/src/serve-error.test.ts +73 -0
  352. package/src/serve-error.ts +56 -0
  353. package/src/server.ts +4963 -377
  354. package/src/session-task-on-dispatch.ts +14 -0
  355. package/src/session-token-ownership-http.test.ts +122 -0
  356. package/src/shared/codex-inventory.ts +41 -0
  357. package/src/shared/daemon-provider-login.ts +31 -0
  358. package/src/shared/daemon-provider-snapshot.ts +52 -0
  359. package/src/shared/external-schedule-contract.ts +60 -0
  360. package/src/shared/node-name.test.ts +62 -0
  361. package/src/shared/node-name.ts +161 -0
  362. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  363. package/src/shared/provider-application.ts +29 -0
  364. package/src/shared/provider-collection.ts +14 -0
  365. package/src/shared/provider-initialization.ts +8 -0
  366. package/src/shared/reserved-env-drift.test.ts +10 -0
  367. package/src/shared/scoped-secret-contract.ts +5 -0
  368. package/src/shared/task-content-limit-drift.test.ts +28 -0
  369. package/src/shared/task-content-limit.ts +25 -0
  370. package/src/side-thread-command-transport.test.ts +312 -0
  371. package/src/side-thread-command-transport.ts +318 -0
  372. package/src/side-thread-http-integration.test.ts +233 -0
  373. package/src/side-thread-http.ts +504 -0
  374. package/src/side-thread-production.test.ts +72 -0
  375. package/src/side-thread-production.ts +118 -0
  376. package/src/side-thread.test.ts +1067 -0
  377. package/src/side-thread.ts +2499 -0
  378. package/src/skillhub-http.test.ts +144 -0
  379. package/src/sqlite-close-checkpoint.test.ts +78 -0
  380. package/src/start-node.test.ts +265 -0
  381. package/src/start-request-error-domain.test.ts +182 -0
  382. package/src/start-skill-error-domain.test.ts +122 -0
  383. package/src/stats-versions-http.test.ts +65 -0
  384. package/src/status-alias-filter-http.test.ts +106 -0
  385. package/src/status-alias-resolver-http.test.ts +163 -0
  386. package/src/status-alias-resolver.ts +19 -0
  387. package/src/status-node-id-filter-http.test.ts +161 -0
  388. package/src/status-read-cache-http.test.ts +229 -0
  389. package/src/status-read-cache.ts +129 -0
  390. package/src/stop-delete-node.test.ts +567 -1
  391. package/src/task-access-http.test.ts +407 -0
  392. package/src/task-access.ts +420 -0
  393. package/src/task-activity.ts +60 -0
  394. package/src/task-auth-origin-http.test.ts +93 -0
  395. package/src/task-auth-origin.test.ts +24 -0
  396. package/src/task-auth-origin.ts +7 -0
  397. package/src/task-consumption.test.ts +508 -0
  398. package/src/task-diagnostic-http.test.ts +149 -0
  399. package/src/task-diagnostic.test.ts +115 -0
  400. package/src/task-diagnostic.ts +118 -0
  401. package/src/task-expiry-notice-http.test.ts +298 -0
  402. package/src/task-expiry-notice.ts +318 -0
  403. package/src/task-idempotency-mcp.test.ts +148 -0
  404. package/src/task-idempotency.test.ts +76 -0
  405. package/src/task-idempotency.ts +81 -0
  406. package/src/task-late-replies.ts +54 -0
  407. package/src/task-late-reply-http.test.ts +227 -0
  408. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  409. package/src/task-lifecycle-watcher.test.ts +209 -0
  410. package/src/task-lifecycle-watcher.ts +109 -0
  411. package/src/task-network-resolution-http.test.ts +140 -0
  412. package/src/task-not-found-error-domain.test.ts +114 -0
  413. package/src/task-offline-delivery-2668.test.ts +119 -0
  414. package/src/task-offline-delivery.ts +81 -0
  415. package/src/task-orphan-http.test.ts +287 -0
  416. package/src/task-orphan.ts +119 -0
  417. package/src/task-queue-ahead-http.test.ts +309 -0
  418. package/src/task-queue-ahead-scale.test.ts +236 -0
  419. package/src/task-queue-ahead.ts +186 -0
  420. package/src/task-rejection-log-http.test.ts +160 -0
  421. package/src/task-rejection-log.ts +61 -0
  422. package/src/task-sender-http.test.ts +143 -0
  423. package/src/task-stale-open-http.test.ts +292 -0
  424. package/src/task-stale-open.ts +103 -0
  425. package/src/tasks-pagination-http.test.ts +141 -0
  426. package/src/team-rules-status-http.test.ts +90 -0
  427. package/src/team-rules-status.test.ts +59 -0
  428. package/src/team-rules-status.ts +72 -0
  429. package/src/tmux-allowlist.test.ts +48 -0
  430. package/src/tool-audience-http.test.ts +248 -0
  431. package/src/tool-audience.ts +130 -0
  432. package/src/tools-list-json-schema.test.ts +94 -0
  433. package/src/tools.ts +4340 -386
  434. package/src/update-node-config-error-domain.test.ts +107 -0
  435. package/src/uploads-http.test.ts +6 -4
  436. package/src/uploads.ts +23 -4
  437. package/src/user-avatar-http.test.ts +74 -0
  438. package/src/user-avatar-image.ts +160 -0
  439. package/src/user-avatar-migration.test.ts +25 -0
  440. package/src/user-avatar-upload-http.test.ts +353 -0
  441. package/src/user-inbox-by-agent-http.test.ts +189 -0
  442. package/src/user-inbox-netid-notnull.test.ts +122 -0
  443. package/src/user-inbox-read-http.test.ts +223 -0
  444. package/src/user-inbox-schema.test.ts +54 -0
  445. package/src/version-stats.test.ts +66 -0
  446. package/src/version-stats.ts +109 -0
@@ -0,0 +1,166 @@
1
+ // 2026-10-31 —— **本地直跑会看到 3 条红,那不是回归**。
2
+ // 这 7 条里有 3 条(HTTP 端点 / names-only 密钥 / daemon 队列)依赖
3
+ // `.github/workflows/hub-provider-core.yml` 里的容器环境(`tests/test907-hub-provider/run.sh`,
4
+ // `--network none` + 特定 host 映射);在仓外 `bun test src/hub-provider-config.test.ts`
5
+ // 会看到 `status: "failed"`(服务端 URL 走不到 secure transport)。
6
+ // ⇒ 按本仓规矩把环境依赖写在文件头:否则下一个人会把 3 条环境红当成自己改坏的。
7
+ // ⇒ 判定这条文件是否健康,看那套 Docker 测试,不看本地 bun test。
8
+
9
+ import './require-explicit-test-db';
10
+ import { afterAll, beforeEach, expect, test } from 'bun:test';
11
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import { db } from './db';
15
+ import { registerTools } from './tools';
16
+ import { vaultGet } from './vault';
17
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
18
+ import { reconcileProviderSnapshots, secureProviderTransport } from '../../agent-node/src/runtime/daemon-provider-snapshot';
19
+ import { DaemonProviderStore } from '../../agent-network/src/daemon-provider-store';
20
+ const net = 'net_hub907', user = 'u_hub907', daemonId = 'n_hub907', alias = 'daemon907', token = 'tok_hub907';
21
+ const root = mkdtempSync(join(tmpdir(), 'hub907-')), key = 'TEST-ONLY-shared-provider-key';
22
+ function cleanup() {
23
+ for (const t of ['daemon_provider_writes', 'daemon_provider_applications', 'daemon_provider_logins']) db.run(`DELETE FROM ${t} WHERE request_id IN (SELECT request_id FROM daemon_provider_snapshots WHERE network_id=?1)`, [net]);
24
+ for (const t of ['hub_provider_bindings', 'hub_provider_configs', 'network_secrets', 'daemon_provider_snapshots', 'nodes', 'api_tokens', 'network_members']) db.run(`DELETE FROM ${t} WHERE network_id=?1`, [net]);
25
+ db.run('DELETE FROM networks WHERE network_id=?1', [net]); db.run('DELETE FROM users WHERE user_id=?1', [user]);
26
+ }
27
+ beforeEach(() => {
28
+ cleanup(); rmSync(join(root, '.anet'), { recursive: true, force: true });
29
+ process.env.ANET_HUB_SECRET_VAULT_KEY = '42'.repeat(32);
30
+ db.run("INSERT INTO users(user_id,username,password_hash,role) VALUES(?1,?1,'x','user')", [user]);
31
+ db.run('INSERT INTO networks(network_id,network_name,owner_id) VALUES(?1,?1,?2)', [net, user]);
32
+ db.run("INSERT INTO network_members(user_id,network_id,role) VALUES(?1,?2,'owner')", [user, net]);
33
+ db.run('INSERT INTO nodes(node_id,node_name,alias,network_id,config_snapshot) VALUES(?1,?2,?2,?3,?4)', [daemonId, alias, net, JSON.stringify({ role: 'host_supervisor' })]);
34
+ db.run("INSERT INTO api_tokens(token_id,user_id,network_id,scope,name,token_hash) VALUES(?1,?2,?3,'network',?4,?5)", [token, user, net, `node:${alias}`, `hash_${token}`]);
35
+ const dir = join(root, '.anet/nodes', alias); mkdirSync(dir, { recursive: true, mode: 0o700 });
36
+ writeFileSync(join(dir, 'config.json'), JSON.stringify({ role: 'host_supervisor', node_id: daemonId, network_id: net }), { mode: 0o600 });
37
+ });
38
+ afterAll(() => { cleanup(); rmSync(root, { recursive: true, force: true }); });
39
+ function client(kind = 'human') {
40
+ const handlers: Record<string, any> = {}, server = new McpServer({ name: 'test907', version: '0' }) as any;
41
+ const tool = server.tool.bind(server), register = server.registerTool.bind(server);
42
+ server.tool = (name: string, desc: any, shape: any, handler: any) => { handlers[name] = handler; return tool(name, desc, shape, handler); };
43
+ server.registerTool = (name: string, config: any, handler: any) => { handlers[name] = handler; return register(name, config, handler); };
44
+ registerTools(server, undefined, kind === 'daemon' ? net : null, kind === 'anonymous' ? null : user, alias, kind === 'daemon', kind === 'daemon' ? token : null);
45
+ return async (name: string, args: any = {}) => JSON.parse((await handlers[name](args)).content[0].text);
46
+ }
47
+ const provider = () => ({ id: 'shared', label: 'Shared model', enabled: true, protocol: 'openai-responses', baseUrl: 'https://provider.example/v1', models: ['fixture-model'], key });
48
+ const save = (human: ReturnType<typeof client>, value = provider(), revision = 0) => human('daemon_provider_snapshot', { action: 'hub_put', id: value.id, network_id: net, revision, provider: value });
49
+ const bind = (human: ReturnType<typeof client>, target = daemonId, revision = 1) => human('daemon_provider_snapshot', { action: 'hub_bind', network_id: net, id: 'shared', revision, provider: { daemon_node_id: target, daemon_revision: 0, confirm: true } });
50
+ test('HTTP Hub and API endpoint support save, explicit bind and exact private-store readback', async () => {
51
+ expect(secureProviderTransport('http://hub907.example.test')).toBe(true);
52
+ expect(secureProviderTransport('ftp://hub907.example.test')).toBe(false);
53
+ expect(secureProviderTransport('http://user:password@hub907.example.test')).toBe(false);
54
+ const human = client(), daemon = client('daemon');
55
+ const config = { ...provider(), baseUrl: 'http://provider.example/v1' };
56
+ const saved = await save(human, config); expect(saved.ok).toBe(true);
57
+ expect(saved.provider.baseUrl).toBe(config.baseUrl);
58
+ const queued = await bind(human); expect(queued.ok).toBe(true);
59
+ await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId,
60
+ serverUrl: 'http://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
61
+ const receipt = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
62
+ expect(receipt.status).toBe('succeeded');
63
+ expect(receipt.snapshot.providers[0].runtimes[0].auth[0].baseUrl).toBe(config.baseUrl);
64
+ expect(JSON.stringify([saved, queued, receipt])).not.toContain(key);
65
+ const store = new DaemonProviderStore(join(root, '.anet/nodes', alias));
66
+ await store.withApiKey({ revision: 1, providerId: queued.provider_reference.daemon_provider_id, authId: 'hub_key', model: 'fixture-model' }, async actual => {
67
+ expect(actual.baseUrl).toBe(config.baseUrl); expect(actual.key).toBe(key);
68
+ }); // Exact synthetic key in local callback, no external model request.
69
+ for (const baseUrl of ['ftp://provider.example/v1', 'http://user:pass@provider.example/v1', 'http://provider.example/v1?key=secret']) {
70
+ expect(await save(human, { ...provider(), id: 'invalid', baseUrl })).toMatchObject({ ok: false, error: 'invalid_hub_provider' });
71
+ }
72
+ });
73
+ test('existing names-only vault key → Provider reference → actual daemon store, without re-entering key', async () => {
74
+ const human = client(), daemon = client('daemon');
75
+ expect(await human('upsert_network_secret', { network_id: net, key: 'SHARED_API_KEY', value: key })).toMatchObject({ ok: true });
76
+ const { key: ignored, ...config } = provider();
77
+ const saved = await save(human, { ...config, secretKeyRef: 'SHARED_API_KEY' } as any);
78
+ expect(saved.provider).toMatchObject({ secret_key_ref: 'SHARED_API_KEY', credential_present: true });
79
+ expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).toBe('SHARED_API_KEY');
80
+ const legacy = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net });
81
+ expect(legacy.providers[0].secret_key_ref).toBeUndefined(); // older strict client shape unchanged
82
+ const modern = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net, provider: { include_secret_refs: true } });
83
+ expect(modern.secret_reference_supported).toBe(true); expect(modern.providers[0].secret_key_ref).toBe('SHARED_API_KEY');
84
+ expect(JSON.stringify([saved, legacy, modern])).not.toContain(key);
85
+ const queued = await bind(human); expect(queued.ok).toBe(true);
86
+ await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId, serverUrl: 'https://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
87
+ const receipt = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
88
+ expect(receipt.status).toBe('succeeded'); expect(receipt.snapshot.providers[0].runtimes[0].auth[0].credential_present).toBe(true);
89
+ const store = new DaemonProviderStore(join(root, '.anet/nodes', alias));
90
+ await store.withApiKey({ revision: receipt.snapshot.revision, providerId: queued.provider_reference.daemon_provider_id, authId: 'hub_key', model: 'fixture-model' }, async profile => {
91
+ expect(profile.key).toBe(key); expect(profile.baseUrl).toBe(config.baseUrl);
92
+ }); // synthetic local callback only; no model/vendor request
93
+ expect(JSON.stringify(receipt)).not.toContain(key);
94
+ // Switching back to Provider-owned plaintext never changes the reusable named key.
95
+ await save(human, { ...provider(), key: 'TEST-ONLY-provider-specific' }, 1);
96
+ expect(vaultGet(net, 'SHARED_API_KEY')).toBe(key);
97
+ expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).not.toBe('SHARED_API_KEY');
98
+ });
99
+ test('missing or ambiguous references do not save; explicit ref replacement updates the stored reference', async () => {
100
+ const human = client(); const { key: ignored, ...config } = provider();
101
+ expect(await save(human, { ...config, secretKeyRef: 'MISSING_KEY' } as any)).toMatchObject({ ok: false, error: 'provider_secret_reference_missing' });
102
+ expect(await save(human, { ...provider(), secretKeyRef: 'SHARED_API_KEY' } as any)).toMatchObject({ ok: false, error: 'invalid_provider_secret_reference' });
103
+ await save(human);
104
+ await human('upsert_network_secret', { network_id: net, key: 'SECOND_API_KEY', value: 'TEST-ONLY-second-key' });
105
+ expect((await save(human, { ...config, secretKeyRef: 'SECOND_API_KEY' } as any, 1)).provider.secret_key_ref).toBe('SECOND_API_KEY');
106
+ expect(db.get<any>('SELECT secret_key_ref FROM hub_provider_configs WHERE network_id=?1', net).secret_key_ref).toBe('SECOND_API_KEY');
107
+ });
108
+ test('actual Hub tool atomically saves encrypted Provider; metadata read and conflict never echo key', async () => {
109
+ const human = client(); const result = await save(human); expect(result.ok).toBe(true);
110
+ expect(result.provider).toMatchObject({ id: 'shared', revision: 1, source: 'hub', credential_present: true, compatible_runtimes: ['codex-tui'] });
111
+ const read = await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: net }); expect(read.providers).toHaveLength(1);
112
+ // 2026-10-31 —— **精确键集**(#3171):客户端「可选模型」这一面直接消费这两个投影,
113
+ // 而多给一个键(尤其 secret_key_ref)在这条线上是最严重的那类改动。
114
+ //
115
+ // 2026-10-31 晚 —— 补齐到 7 键。原因是端点自己长出了三态自述(counts / source_table / state):
116
+ // 「providers 是空数组」与「全都禁用」在旧载荷里长得一模一样,读的人只能猜。
117
+ // 这条精确键集因此**当场变红**——而这正是它该做的事:让「多加一栏」必须是一次有意识的决定。
118
+ // 两个键的存在理由:state ∈ {configured, unconfigured, all_disabled}(空数组不是结论);
119
+ // source_table 说明读的是**哪张表**(本仓另有 MCP list_providers 读 providers 表,两者不同源)。
120
+ expect(Object.keys(read).sort()).toEqual([
121
+ "counts", "network_id", "ok", "providers", "source", "source_table", "state",
122
+ ]);
123
+ expect(["configured", "unconfigured", "all_disabled"]).toContain(read.state);
124
+ expect(read.source_table).toBe("hub_provider_configs");
125
+ expect(read.counts.providers).toBe(read.providers.length); // 计数与数组同源
126
+ // provider 视图实际 12 键(我第一版写了 6 个,漏了 baseUrl/enabled/models/protocol/updated_at/verification)
127
+ expect(Object.keys(result.provider).sort()).toEqual([
128
+ "baseUrl", "compatible_runtimes", "credential_present", "enabled", "id", "label",
129
+ "models", "protocol", "revision", "source", "updated_at", "verification",
130
+ ]);
131
+ expect(JSON.stringify([result, read])).not.toContain(key);
132
+ expect(await save(human)).toMatchObject({ ok: false, error: 'hub_provider_revision_conflict' });
133
+ const secret = db.get<any>('SELECT ciphertext FROM network_secrets WHERE network_id=?1', net);
134
+ expect(Buffer.from(secret.ciphertext).toString()).not.toContain(key);
135
+ });
136
+ test('Hub → actual daemon queue → pinned CLI store → redacted receipt, not runtime application', async () => {
137
+ const human = client(), daemon = client('daemon'); await save(human);
138
+ const queued = await bind(human); expect(queued.ok).toBe(true); expect(queued.status).toBe('pending');
139
+ expect(JSON.stringify(queued)).not.toContain(key);
140
+ await reconcileProviderSnapshots({ workDir: root, alias, networkId: net, daemonId, serverUrl: 'https://hub907.example.test', callCommHub: daemon, warn: message => console.warn(message) });
141
+ const read = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
142
+ expect(read.status).toBe('succeeded'); expect(read.snapshot.revision).toBe(1);
143
+ expect(read.snapshot.providers[0]).toMatchObject({ id: queued.provider_reference.daemon_provider_id, label: 'Hub · Shared model' });
144
+ expect(read.snapshot.providers[0].runtimes[0].auth[0]).toMatchObject({ id: 'hub_key', models: ['fixture-model'], application: 'not_applied', verification: 'not_checked' });
145
+ expect(JSON.stringify(read)).not.toContain(key);
146
+ });
147
+ test('scope/role boundaries: no node or anonymous writes, no viewer distribution or foreign daemon', async () => {
148
+ expect(await save(client('daemon'))).toMatchObject({ ok: false, error: 'user_token_required' });
149
+ expect(await save(client('anonymous'))).toMatchObject({ ok: false, error: 'user_token_required' });
150
+ const human = client(); await save(human);
151
+ expect(await human('daemon_provider_snapshot', { action: 'hub_read', id: 'hub', network_id: 'foreign' })).toMatchObject({ ok: false, error: 'provider_access_denied' });
152
+ expect(await bind(human, 'foreign')).toMatchObject({ ok: false, error: 'daemon_not_found' });
153
+ db.run("UPDATE network_members SET role='viewer' WHERE network_id=?1 AND user_id=?2", [net, user]);
154
+ expect(await bind(human)).toMatchObject({ ok: false, error: 'provider_access_denied' });
155
+ expect(await save(human)).toMatchObject({ ok: false, error: 'provider_owner_required' });
156
+ });
157
+ test('protocol mismatch never queues Codex; editing source cancels pending distribution, not installed copies', async () => {
158
+ const human = client(); await save(human, { ...provider(), protocol: 'openai-chat-completions' });
159
+ expect(await bind(human)).toMatchObject({ ok: false, error: 'runtime_protocol_not_supported' });
160
+ await save(human, provider(), 1);
161
+ const queued = await bind(human, daemonId, 2);
162
+ expect(queued.ok).toBe(true); await save(human, { ...provider(), enabled: false }, 2);
163
+ const read = await human('daemon_provider_snapshot', { action: 'read', id: queued.request_id, network_id: net });
164
+ expect(read).toMatchObject({ status: 'failed', error: 'hub_provider_source_changed' });
165
+ expect(db.get('SELECT request_id FROM daemon_provider_writes WHERE request_id=?1', queued.request_id)).toBeNull();
166
+ });
@@ -0,0 +1,202 @@
1
+ // #907: real network-scoped catalog + explicit dispatch; not a Provider proxy.
2
+ import { createHash } from 'node:crypto';
3
+ import { db } from './db';
4
+ import { getUserNetworkRole } from './auth';
5
+ import { vaultUpsert, vaultGet, vaultListKeys, VaultError } from './vault';
6
+ import { requestProviderWrite } from './daemon-provider-snapshots';
7
+ type Human = { userId?: string | null; isNode: boolean; networkId: string | null };
8
+ type Config = { id: string; label: string; enabled: boolean; protocol: 'openai-responses' | 'openai-chat-completions' | 'anthropic-messages'; baseUrl: string; models: string[] };
9
+ const denied = (error: string) => ({ ok: false as const, error });
10
+
11
+ /**
12
+ * 2026-10-31 —— **写侧错误的 HTTP 状态必须是穷尽表**(外部复核:三元式默认分支
13
+ * = 未映射与某个真实含义同值 ⇒ 口令字段;应改成 `Record<Code, number>`)。
14
+ *
15
+ * 原来 REST 路由里写的是:
16
+ * provider_owner_required ? 403 : revision_conflict ? 409 : access_denied ? 403 : 400
17
+ * ⇒ 新增一个错误码时它会**默认落到 400**,而 400 对某些码是错的(例如 vault 缺失应是 409/503)。
18
+ *
19
+ * 这里的码集合来自本文件里所有 `denied('...')` 与 VaultError 的 code;
20
+ * 测试会断言「映射键 == 码清单」,并且**码清单必须能在源码里逐个找到**(跨源,不是自说自话)。
21
+ */
22
+ export const PROVIDER_WRITE_ERROR_CODES = [
23
+ "user_token_required",
24
+ "provider_owner_required",
25
+ "provider_access_denied",
26
+ "invalid_revision",
27
+ "invalid_hub_provider",
28
+ "invalid_provider_key",
29
+ "invalid_provider_secret_reference",
30
+ "provider_secret_reference_missing",
31
+ "provider_key_required",
32
+ "hub_provider_revision_conflict",
33
+ "hub_provider_disabled",
34
+ "hub_provider_save_failed",
35
+ "vault_unavailable",
36
+ ] as const;
37
+ export type ProviderWriteErrorCode = (typeof PROVIDER_WRITE_ERROR_CODES)[number];
38
+ export const PROVIDER_WRITE_STATUS: Record<ProviderWriteErrorCode, number> = {
39
+ user_token_required: 401,
40
+ provider_owner_required: 403,
41
+ provider_access_denied: 403,
42
+ invalid_revision: 400,
43
+ invalid_hub_provider: 400,
44
+ invalid_provider_key: 400,
45
+ invalid_provider_secret_reference: 400,
46
+ provider_secret_reference_missing: 400,
47
+ provider_key_required: 400,
48
+ hub_provider_revision_conflict: 409,
49
+ hub_provider_disabled: 409,
50
+ hub_provider_save_failed: 500,
51
+ vault_unavailable: 503,
52
+ };
53
+ /**
54
+ * 码 → HTTP 状态。
55
+ *
56
+ * 2026-10-31 —— 参数类型从 `string` 收紧到 `ProviderWriteErrorCode`:
57
+ * 之前签名收 `string`,于是「表里加码、忘了加状态」在**调用点**不会被类型拦住
58
+ * (编译器只看见一个字符串)。而 `Record<ProviderWriteErrorCode, number>` 只在
59
+ * 「用类型化的键去索引」时才保证穷尽 —— 签名放宽就等于把穷尽性丢了。
60
+ *
61
+ * 兜底也改了方向:`?? 400` 会告诉客户端「你的请求不对」,而表里查不到的码是**我们**的缺陷
62
+ * ⇒ 归因指向了错误的行动方。现在兜底返回 500(服务端错误),并让测试断言它不被 400 顶替。
63
+ */
64
+ export function providerWriteStatus(code: ProviderWriteErrorCode): number {
65
+ return PROVIDER_WRITE_STATUS[code] ?? 500;
66
+ }
67
+ const idValid = (id: unknown) => typeof id === 'string' && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(id);
68
+ function auth(h: Human, write: boolean, owner = false) {
69
+ if (h.isNode || !h.userId || !h.networkId) return denied('user_token_required');
70
+ const role = getUserNetworkRole(h.userId, h.networkId);
71
+ if (!role || (owner && role !== 'owner') || (write && !['owner', 'admin'].includes(role))) return denied(owner ? 'provider_owner_required' : 'provider_access_denied');
72
+ return null;
73
+ }
74
+ function validConfig(value: any): value is Config {
75
+ if (!value || typeof value !== 'object' || Array.isArray(value)
76
+ || Object.keys(value).some(k => !['id', 'label', 'enabled', 'protocol', 'baseUrl', 'models', 'key', 'secretKeyRef'].includes(k))
77
+ || !idValid(value.id) || typeof value.label !== 'string' || !value.label.trim() || value.label.length > 100
78
+ || /[\x00-\x1f\x7f]/.test(value.label) || typeof value.enabled !== 'boolean'
79
+ || !['openai-responses', 'openai-chat-completions', 'anthropic-messages'].includes(value.protocol)
80
+ || typeof value.baseUrl !== 'string' || value.baseUrl.length > 2048
81
+ || !Array.isArray(value.models) || !value.models.length || value.models.length > 200
82
+ || new Set(value.models).size !== value.models.length
83
+ || value.models.some((m: unknown) => typeof m !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/.test(m))) return false;
84
+ try { const u = new URL(value.baseUrl); return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password && !u.search && !u.hash; }
85
+ catch { return false; }
86
+ }
87
+ type Row = { revision: number; config_json: string; secret_key_ref: string; updated_at: number };
88
+ function row(networkId: string, id: string) {
89
+ return db.get<Row>('SELECT revision,config_json,secret_key_ref,updated_at FROM hub_provider_configs WHERE network_id=?1 AND provider_id=?2', networkId, id);
90
+ }
91
+ function publicRow(networkId: string, stored: Row, exposeRef = false) {
92
+ const config = JSON.parse(stored.config_json) as Config;
93
+ return { ...config, ...(exposeRef ? { secret_key_ref: stored.secret_key_ref } : {}), revision: stored.revision, updated_at: stored.updated_at, source: 'hub',
94
+ credential_present: vaultListKeys(networkId).includes(stored.secret_key_ref), verification: 'not_checked',
95
+ compatible_runtimes: config.protocol === 'openai-responses' ? ['codex-tui'] : [] };
96
+ }
97
+ export function readHubProviders(h: Human, exposeRefs = false) {
98
+ const refusal = auth(h, false); if (refusal) return refusal;
99
+ const rows = db.all<Row>('SELECT revision,config_json,secret_key_ref,updated_at FROM hub_provider_configs WHERE network_id=?1 ORDER BY provider_id', h.networkId!);
100
+ // 2026-10-31 —— **这个端点的空数组也必须自报家门**(与 MCP list_providers 同一课)。
101
+ // 关键事实:两条「providers」读的是**不同的表** ——
102
+ // GET /api/providers → hub_provider_configs(网络自有的 provider 配置,本函数)
103
+ // MCP list_providers → providers / provider_models
104
+ // 于是「客户端没有可选模型」既可能是「这张表空」,也可能是「另一张表空」,
105
+ // 而两者在载荷里长得一模一样。⇒ 在 source 之外再说清 state 与「另一处叫什么」。
106
+ const otherSource = db.get<{ cnt: number }>(
107
+ 'SELECT COUNT(*) AS cnt FROM providers WHERE network_id=?1 AND enabled=1', h.networkId!);
108
+ const otherCount = otherSource?.cnt ?? 0;
109
+ // 2026-10-31 —— **闭集不许有死成员**:客户端 union 里写着
110
+ // "configured" | "unconfigured" | "all_disabled",而这个端点原来只产出前两个
111
+ // ⇒ all_disabled 是一格永远不会出现的状态,界面里那条分支也就永远跑不到
112
+ // (实测:本地 hub 建了一行 enabled:true 的 provider 之后,state 仍是 configured/空表是 unconfigured,
113
+ // 把 enabled 改成 false 依旧是 configured ⇒ 读的人会把「全都关了」看成「配置好了」)。
114
+ // 现在三态都可产出,并把「哪些算可用」用计数说清(客户端不必自己再数一遍)。
115
+ const parsed = rows.map(r => JSON.parse(r.config_json) as { enabled?: boolean; models?: string[] });
116
+ const enabledRows = parsed.filter(c => c.enabled === true);
117
+ const state = rows.length === 0 ? 'unconfigured' as const
118
+ : enabledRows.length === 0 ? 'all_disabled' as const
119
+ : 'configured' as const;
120
+ return { ok: true as const, network_id: h.networkId!, source: 'hub' as const,
121
+ // 读的是哪张表 —— 名字直接写出来,避免下一个人拿这个结果去解释另一个接口
122
+ source_table: 'hub_provider_configs' as const,
123
+ state,
124
+ counts: {
125
+ providers: rows.length,
126
+ providers_enabled: enabledRows.length,
127
+ providers_disabled: rows.length - enabledRows.length,
128
+ models_enabled: enabledRows.reduce((n, c) => n + (Array.isArray(c.models) ? c.models.length : 0), 0),
129
+ providers_without_models: enabledRows.filter(c => !Array.isArray(c.models) || c.models.length === 0).length,
130
+ providers_in_cli_registry: otherCount,
131
+ },
132
+ ...(state === 'all_disabled' ? {
133
+ hint: '这个网络里配置了 ' + rows.length + ' 个 provider,但**全部被禁用** ⇒ 客户端仍然没有可选模型。'
134
+ + '这不是「还没配置」,要做的是启用其中一个(或在确认无用后删除)。',
135
+ } : {}),
136
+ ...(state === 'unconfigured' ? {
137
+ hint: otherCount > 0
138
+ ? '本端点读 hub_provider_configs(网络自有 provider 配置),此处为空;但要给客户端选模型,还需要这里至少一行 —— CLI 注册表里的 ' + otherCount + ' 条不会自动出现在本端点。'
139
+ : '本端点读 hub_provider_configs,此处为空,且 CLI 注册表(providers)也是 0 条 ⇒ 客户端没有任何可选模型;需要管理员先录入第一行。',
140
+ } : {}),
141
+ ...(exposeRefs ? { secret_reference_supported: true } : {}), providers: rows.map(r => publicRow(h.networkId!, r, exposeRefs)) };
142
+ }
143
+ export function putHubProvider(h: Human, revision: number, input: unknown) {
144
+ // This operation stores/rotates a shared secret: same OWNER boundary as vault writes.
145
+ const refusal = auth(h, true, true); if (refusal) return refusal;
146
+ if (!Number.isSafeInteger(revision) || revision < 0 || revision >= Number.MAX_SAFE_INTEGER) return denied('invalid_revision');
147
+ if (!validConfig(input)) return denied('invalid_hub_provider');
148
+ const value = input as Config & { key?: string; secretKeyRef?: string };
149
+ if (value.key !== undefined && (typeof value.key !== 'string' || !value.key || value.key.length > 8192 || /[\s\x00-\x1f\x7f]/.test(value.key))) return denied('invalid_provider_key');
150
+ if (value.secretKeyRef !== undefined && (typeof value.secretKeyRef !== 'string' || !/^[A-Z][A-Z0-9_]{0,63}$/.test(value.secretKeyRef)
151
+ || value.key !== undefined)) return denied('invalid_provider_secret_reference');
152
+ if (value.secretKeyRef && !vaultListKeys(h.networkId!).includes(value.secretKeyRef)) return denied('provider_secret_reference_missing');
153
+ const old = row(h.networkId!, value.id);
154
+ if ((old?.revision ?? 0) !== revision) return denied('hub_provider_revision_conflict');
155
+ const previous = old ? JSON.parse(old.config_json) as Config : null;
156
+ if (!value.key && !value.secretKeyRef && (!old || previous?.baseUrl !== value.baseUrl || previous?.protocol !== value.protocol)) return denied('provider_key_required');
157
+ // A new plaintext key belongs to this Provider. Never overwrite a separately
158
+ // named shared key merely because the previous config referenced it.
159
+ const privateRef = `HUB_PROVIDER_${createHash('sha256').update(JSON.stringify([h.networkId, value.id])).digest('hex').slice(0, 32).toUpperCase()}`;
160
+ const ref = value.secretKeyRef ?? (value.key ? privateRef : old!.secret_key_ref);
161
+ const { key, secretKeyRef, ...config } = value;
162
+ try {
163
+ db.transaction(() => {
164
+ if ((row(h.networkId!, value.id)?.revision ?? 0) !== revision) throw new Error('hub_provider_revision_conflict');
165
+ if (key) vaultUpsert(h.networkId!, ref, key);
166
+ db.run(`INSERT INTO hub_provider_configs(network_id,provider_id,revision,config_json,secret_key_ref,updated_at) VALUES(?1,?2,?3,?4,?5,?6)
167
+ ON CONFLICT(network_id,provider_id) DO UPDATE SET revision=excluded.revision,config_json=excluded.config_json,secret_key_ref=excluded.secret_key_ref,updated_at=excluded.updated_at`,
168
+ [h.networkId!, value.id, revision + 1, JSON.stringify(config), ref, Date.now()]);
169
+ // Cancel still-pending dispatches when the source is edited/rotated/disabled.
170
+ // Already installed copies are NOT remotely revoked by this change.
171
+ db.run(`UPDATE daemon_provider_snapshots SET status='failed',error='hub_provider_source_changed'
172
+ WHERE status='pending' AND request_id IN (SELECT request_id FROM hub_provider_bindings WHERE network_id=?1 AND provider_id=?2)`, [h.networkId!, value.id]);
173
+ db.run(`DELETE FROM daemon_provider_writes WHERE request_id IN (SELECT b.request_id FROM hub_provider_bindings b
174
+ JOIN daemon_provider_snapshots s ON s.request_id=b.request_id WHERE b.network_id=?1 AND b.provider_id=?2 AND s.status!='pending')`, [h.networkId!, value.id]);
175
+ });
176
+ return { ok: true as const, network_id: h.networkId!, provider: publicRow(h.networkId!, row(h.networkId!, value.id)!, secretKeyRef !== undefined) };
177
+ } catch (error) { return denied(error instanceof VaultError ? error.code : 'hub_provider_save_failed'); }
178
+ }
179
+ export function bindHubProvider(h: Human, input: { id: string; revision: number; daemon_node_id: string; daemon_revision: number; confirm: boolean }) {
180
+ const refusal = auth(h, true); if (refusal) return refusal;
181
+ if (!input || !idValid(input.id) || input.confirm !== true || !Number.isSafeInteger(input.revision)
182
+ || !Number.isSafeInteger(input.daemon_revision) || input.daemon_revision < 0) return denied('invalid_hub_provider_binding');
183
+ const stored = row(h.networkId!, input.id);
184
+ if (!stored || stored.revision !== input.revision) return denied('hub_provider_revision_conflict');
185
+ const config = JSON.parse(stored.config_json) as Config;
186
+ if (!config.enabled) return denied('hub_provider_disabled');
187
+ // Never silently treat Chat Completions/Anthropic as Codex Responses.
188
+ if (config.protocol !== 'openai-responses') return denied('runtime_protocol_not_supported');
189
+ const targetId = `hub_${createHash('sha256').update(JSON.stringify([h.networkId, input.id])).digest('hex').slice(0, 24)}`;
190
+ try {
191
+ const key = vaultGet(h.networkId!, stored.secret_key_ref); if (!key) return denied('provider_key_missing');
192
+ const queued = requestProviderWrite(h, input.daemon_node_id, input.daemon_revision, { id: targetId,
193
+ label: `Hub · ${config.label}`.slice(0, 100), enabled: true, runtimes: [{ runtime: 'codex-tui', auth: [
194
+ { id: 'hub_key', kind: 'api_key', models: config.models, baseUrl: config.baseUrl, key },
195
+ ] }] });
196
+ if (!queued.ok) return queued;
197
+ db.run(`INSERT INTO hub_provider_bindings(request_id,network_id,provider_id,provider_revision,daemon_node_id,daemon_provider_id,created_at)
198
+ VALUES(?1,?2,?3,?4,?5,?6,?7)`, [queued.request_id, h.networkId!, input.id, input.revision, input.daemon_node_id, targetId, Date.now()]);
199
+ return { ...queued, daemon_node_id: input.daemon_node_id,
200
+ provider_reference: { network_id: h.networkId!, id: input.id, revision: input.revision, daemon_provider_id: targetId } };
201
+ } catch (error) { return denied(error instanceof VaultError ? error.code : 'hub_provider_binding_failed'); }
202
+ }
@@ -0,0 +1,38 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { parseHubTimestamp } from "./hub-timestamp";
3
+
4
+ const RAW = "2026-08-30 21:11:24"; // sessions.last_seen_at 的真实取值
5
+ const TRUE_UTC = Date.UTC(2026, 7, 30, 21, 11, 24);
6
+
7
+ describe("parseHubTimestamp (#1650)", () => {
8
+ test("🔴 非 UTC 时区下也必须解出同一个 UTC 时刻", () => {
9
+ // `bun test` 把测试进程时区固定成 UTC(getTimezoneOffset() === 0)。
10
+ // 在 UTC 下,「补 Z」和「不补 Z」解析出**同一个数** —— 这个函数存在的那个
11
+ // 缺陷在测试进程里**结构上不可见**。所以这一条必须开 TZ≠UTC 的子进程。
12
+ // 实测:去掉补 Z,本文件其余各条**全绿**。
13
+ const child = `import { parseHubTimestamp } from ${JSON.stringify(import.meta.dir + "/hub-timestamp.ts")};
14
+ process.stdout.write(new Date().getTimezoneOffset() + "," + parseHubTimestamp(${JSON.stringify(RAW)}));`;
15
+ const r = Bun.spawnSync(["bun", "-e", child], { env: { ...process.env, TZ: "Asia/Shanghai" } });
16
+ const [offset, parsed] = r.stdout.toString().trim().split(",");
17
+ // 🔴 先断言控制生效:子进程真的不在 UTC。否则 TZ 被忽略时这条又变成空测试。
18
+ expect(Number(offset)).not.toBe(0);
19
+ expect(parsed).toBe(String(TRUE_UTC));
20
+ });
21
+
22
+ test("已带 Z / ±HH:MM 的串不再追加时区", () => {
23
+ expect(parseHubTimestamp("2026-08-30T21:11:24Z")).toBe(TRUE_UTC);
24
+ expect(parseHubTimestamp("2026-08-30T22:11:24+01:00")).toBe(TRUE_UTC);
25
+ });
26
+
27
+ test("拿不到就返回 null,不返回一个看起来合理的数", () => {
28
+ for (const bad of [undefined, null, "", " ", 0, 1788124284000, {}, [], "2026-08-30", "垃圾"]) {
29
+ expect(parseHubTimestamp(bad as unknown)).toBeNull();
30
+ }
31
+ });
32
+
33
+ test("🔴 INTEGER 列(epoch 毫秒)不归它管 —— 传数字必须返回 null,而不是悄悄接受", () => {
34
+ // external_schedule_edits.* 是 INTEGER。如果有人把本函数用在那儿,
35
+ // 应当立刻拿到 null 而不是一个错的时刻。
36
+ expect(parseHubTimestamp(TRUE_UTC)).toBeNull();
37
+ });
38
+ });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * #1650 — hub 的 TEXT 时间戳列是 SQLite `datetime('now')` 写的,
3
+ * 形如 `2026-08-30 21:11:24`:**UTC,但不带任何时区标记**。
4
+ *
5
+ * 🔴 `new Date(raw)` / `Date.parse(raw)` 对这种串按**本地时间**解析(ES 规范:
6
+ * 带时间的形式无偏移时视为本地时间),误差恰好等于主机时区偏移,**而且不报错**:
7
+ *
8
+ * TZ=UTC 误差 0h
9
+ * TZ=Asia/Shanghai 误差 -8h (看起来更陈旧)
10
+ * TZ=America/Los_Angeles 误差 +7h (看起来更新鲜 ← 朝好的一侧错)
11
+ *
12
+ * 🔴 **只对 TEXT 列用它。** 同一个字段名在不同表里可能是不同类型:
13
+ * sessions.last_seen_at / licenses.expires_at → TEXT(要用本函数)
14
+ * external_schedule_edits.expires_at 等 4 列 → INTEGER(epoch 毫秒,直接 new Date 就对)
15
+ * 按字段名判会判错 —— 见 #1650 里的更正。
16
+ *
17
+ * 与 agent-network 侧的同名函数是**有意的重复**:server 包不依赖 agent-network,
18
+ * 仓里也没有共享 lib。两边各自带测试。
19
+ */
20
+ export function parseHubTimestamp(raw: unknown): number | null {
21
+ if (typeof raw !== "string") return null;
22
+ const t = raw.trim();
23
+ if (!/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/.test(t)) return null;
24
+ const hasZone = /([Zz]|[+-]\d{2}:?\d{2})$/.test(t);
25
+ const ms = Date.parse(t.replace(" ", "T") + (hasZone ? "" : "Z"));
26
+ return Number.isFinite(ms) ? ms : null;
27
+ }