@sleep2agi/commhub-server 0.9.0-preview.28 → 0.9.0-preview.280

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 (479) 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 +215 -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 +888 -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 +228 -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/all-status-cache.test.ts +31 -0
  28. package/src/all-status-cache.ts +37 -0
  29. package/src/anet-variant-real-daemon-http.test.ts +184 -0
  30. package/src/api-host-supervisors-can-create-nodes.test.ts +350 -0
  31. package/src/api-host-supervisors-fallback.test.ts +6 -7
  32. package/src/api-host-supervisors-runtime-readiness.test.ts +195 -0
  33. package/src/api-nodes-shape.test.ts +131 -4
  34. package/src/auth-abuse-counters.test.ts +144 -0
  35. package/src/auth-abuse-counters.ts +122 -0
  36. package/src/auth-layer-shape.test.ts +105 -0
  37. package/src/auth-password-change-cli-tokens-http.test.ts +423 -0
  38. package/src/auth-sessions-http.test.ts +260 -0
  39. package/src/auth-validate.test.ts +5 -1
  40. package/src/auth-weak-password-login.test.ts +176 -0
  41. package/src/auth.ts +641 -68
  42. package/src/backfill-node-ids-2664.test.ts +128 -0
  43. package/src/binding-generation-http.test.ts +141 -0
  44. package/src/blocked-exit-on-reply.test.ts +122 -0
  45. package/src/broadcast-fanout-2721.test.ts +149 -0
  46. package/src/broadcast-fanout.ts +117 -0
  47. package/src/build-commit-report-http.test.ts +218 -0
  48. package/src/build-info.test.ts +60 -0
  49. package/src/build-info.ts +85 -0
  50. package/src/chain-attempt-dedup.test.ts +447 -0
  51. package/src/clip.test.ts +36 -0
  52. package/src/clip.ts +48 -0
  53. package/src/clone-node.test.ts +269 -0
  54. package/src/clone-node.ts +289 -0
  55. package/src/codex-config-flags.ts +77 -0
  56. package/src/codex-fork-contract.ts +23 -0
  57. package/src/codex-fork-migration.test.ts +38 -0
  58. package/src/commhub-bin-args.test.ts +85 -0
  59. package/src/config-apply-sec1.test.ts +37 -0
  60. package/src/config-apply-validate.test.ts +188 -1
  61. package/src/config-apply-validate.ts +226 -3
  62. package/src/contracts/session-project-create.ts +14 -0
  63. package/src/contracts/session-source-delivery.ts +16 -0
  64. package/src/contracts/session-source-directory.ts +54 -0
  65. package/src/contracts/session-source-evidence.ts +72 -0
  66. package/src/contracts/session-source-execution.ts +24 -0
  67. package/src/contracts/session-source-transport.ts +18 -0
  68. package/src/cors-origins.test.ts +73 -0
  69. package/src/create-node-blocked-gate.test.ts +365 -0
  70. package/src/create-node-error-domain.test.ts +127 -0
  71. package/src/create-node-network-id.test.ts +91 -0
  72. package/src/create-node-tool-schema.test.ts +59 -0
  73. package/src/create-node-unicode-name.test.ts +126 -0
  74. package/src/create-node-validate.test.ts +199 -7
  75. package/src/create-node-validate.ts +232 -15
  76. package/src/create-node-workdir.test.ts +298 -0
  77. package/src/create-node.ts +88 -23
  78. package/src/daemon-provider-snapshots.test.ts +453 -0
  79. package/src/daemon-provider-snapshots.ts +327 -0
  80. package/src/daemon-token-owner-http.test.ts +346 -0
  81. package/src/dashboard-slash-routing-http.test.ts +109 -0
  82. package/src/db-adapter-guard.test.ts +148 -0
  83. package/src/db-adapter-translate.test.ts +128 -0
  84. package/src/db-adapter.ts +377 -91
  85. package/src/db-timestamp.test.ts +38 -0
  86. package/src/db-timestamp.ts +15 -0
  87. package/src/db.ts +1334 -154
  88. package/src/delivered-without-push.test.ts +140 -0
  89. package/src/department-groups-http.test.ts +209 -0
  90. package/src/department-groups-sync-http.test.ts +328 -0
  91. package/src/department-groups.ts +434 -0
  92. package/src/department-heads-http.test.ts +350 -0
  93. package/src/department-heads.ts +226 -0
  94. package/src/departments-agent-count.test.ts +139 -0
  95. package/src/departments-http.test.ts +185 -0
  96. package/src/departments-mcp-error-domain.test.ts +135 -0
  97. package/src/departments-mcp.test.ts +128 -0
  98. package/src/departments.ts +318 -0
  99. package/src/desktop-message-seam.test.ts +150 -0
  100. package/src/desktop-message.test.ts +368 -0
  101. package/src/dm-file-scope-http.test.ts +227 -0
  102. package/src/empty-node-sweeper.test.ts +104 -0
  103. package/src/empty-node-sweeper.ts +88 -0
  104. package/src/env-transport-gate-http.test.ts +240 -0
  105. package/src/env-transport-gate.ts +80 -0
  106. package/src/env-transport-policy.ts +56 -0
  107. package/src/etag-of.test.ts +57 -0
  108. package/src/event-loop-lag.test.ts +180 -0
  109. package/src/event-loop-lag.ts +201 -0
  110. package/src/expiry-counters.test.ts +187 -0
  111. package/src/expiry-counters.ts +227 -0
  112. package/src/expiry-evidence-db.test.ts +103 -0
  113. package/src/ext-token-shared.test.ts +60 -0
  114. package/src/ext-validation-regression.test.ts +10 -17
  115. package/src/external-schedule-edits-http.test.ts +321 -0
  116. package/src/external-schedule-edits-timestamps.test.ts +64 -0
  117. package/src/external-schedule-edits.ts +327 -0
  118. package/src/file-download-authz-dev-open.test.ts +1 -1
  119. package/src/file-download-authz.test.ts +25 -4
  120. package/src/file-download-date-bucket.test.ts +1 -1
  121. package/src/file-network-scope-dev-open.test.ts +1 -1
  122. package/src/file-network-scope.test.ts +7 -6
  123. package/src/group-membership-events-http.test.ts +264 -0
  124. package/src/group-messages-http.test.ts +483 -0
  125. package/src/group-messages.ts +297 -0
  126. package/src/health-anon-readers.ts +67 -0
  127. package/src/health-host-disk-2756.test.ts +71 -0
  128. package/src/health-identity-root.test.ts +98 -0
  129. package/src/health-redaction.test.ts +1599 -7
  130. package/src/health-status-reasons.test.ts +84 -0
  131. package/src/host-supervisor-identity-http.test.ts +152 -0
  132. package/src/host-supervisor-identity.ts +92 -0
  133. package/src/host-supervisors-daemon-version.test.ts +137 -0
  134. package/src/http-gzip.test.ts +94 -0
  135. package/src/http-gzip.ts +112 -0
  136. package/src/hub-catalog-read-http.test.ts +664 -0
  137. package/src/hub-provider-config.test.ts +166 -0
  138. package/src/hub-provider-config.ts +202 -0
  139. package/src/hub-timestamp.test.ts +38 -0
  140. package/src/hub-timestamp.ts +27 -0
  141. package/src/human-dm.ts +215 -0
  142. package/src/human-inbox.ts +42 -0
  143. package/src/inbox-caller.ts +49 -0
  144. package/src/inbox-count-sse.test.ts +318 -0
  145. package/src/inbox-count.ts +29 -0
  146. package/src/index.ts +6 -2
  147. package/src/license-state.test.ts +105 -0
  148. package/src/license-state.ts +48 -0
  149. package/src/lifecycle-error-domain.test.ts +149 -0
  150. package/src/list-ack-error-domain.test.ts +108 -0
  151. package/src/list-host-supervisors.test.ts +15 -4
  152. package/src/list-tasks-omit-default.test.ts +84 -0
  153. package/src/list-tasks-since-last.test.ts +100 -0
  154. package/src/list-tasks-since.test.ts +104 -0
  155. package/src/mcp-context-cost-http.test.ts +127 -0
  156. package/src/mcp-inflight.test.ts +92 -0
  157. package/src/mcp-inflight.ts +38 -0
  158. package/src/mcp-projects-events-http.test.ts +168 -0
  159. package/src/mcp-route-label-http.test.ts +120 -0
  160. package/src/mcp-write-network-resolution.test.ts +21 -0
  161. package/src/member-audit-network-id-http.test.ts +93 -0
  162. package/src/member-presence-http.test.ts +210 -0
  163. package/src/messages-ack-by-agent-http.test.ts +142 -0
  164. package/src/migrate-sqlite-to-pg.test.ts +47 -0
  165. package/src/migrate-sqlite-to-pg.ts +263 -0
  166. package/src/model-auth-notify-http.test.ts +181 -0
  167. package/src/model-auth-notify.ts +116 -0
  168. package/src/network-name-http.test.ts +75 -0
  169. package/src/network-quota-config.test.ts +100 -0
  170. package/src/network-rules-http.test.ts +169 -0
  171. package/src/network-rules.ts +129 -0
  172. package/src/network-scope.ts +222 -3
  173. package/src/network-token-membership-http.test.ts +186 -0
  174. package/src/node-alias-control.ts +12 -0
  175. package/src/node-attrs.test.ts +47 -2
  176. package/src/node-caller-identity-http.test.ts +1108 -0
  177. package/src/node-config-last-update.test.ts +126 -0
  178. package/src/node-config-last-update.ts +107 -0
  179. package/src/node-create-request-status-http.test.ts +105 -0
  180. package/src/node-daemon-bindings.test.ts +142 -0
  181. package/src/node-daemon-bindings.ts +135 -0
  182. package/src/node-failure-alert.test.ts +150 -0
  183. package/src/node-failure-alert.ts +177 -0
  184. package/src/node-files-transport.test.ts +350 -0
  185. package/src/node-health-codex-login.test.ts +120 -0
  186. package/src/node-health-dispatch-http.test.ts +373 -0
  187. package/src/node-health-guard-origin.test.ts +98 -0
  188. package/src/node-health-guard.ts +121 -0
  189. package/src/node-health-passthrough.test.ts +115 -0
  190. package/src/node-health-store.ts +101 -0
  191. package/src/node-id-alias.test.ts +190 -0
  192. package/src/node-identity-conflict-http.test.ts +269 -0
  193. package/src/node-identity-conflict.ts +142 -0
  194. package/src/node-identity-mismatch.test.ts +74 -0
  195. package/src/node-in-flight-tasks.ts +31 -0
  196. package/src/node-lifecycle-controllable.test.ts +64 -0
  197. package/src/node-lifecycle-controllable.ts +53 -0
  198. package/src/node-lifecycle-read-http.test.ts +257 -0
  199. package/src/node-lifecycle-read.ts +126 -0
  200. package/src/node-logs-transport.test.ts +266 -0
  201. package/src/node-peer-allowlist.test.ts +114 -0
  202. package/src/node-permissions-http.test.ts +901 -0
  203. package/src/node-permissions.ts +496 -0
  204. package/src/node-request-retention.test.ts +281 -0
  205. package/src/node-request-retention.ts +120 -0
  206. package/src/node-secret-rest-http.test.ts +190 -0
  207. package/src/node-secret-vault-inject.test.ts +132 -0
  208. package/src/node-security-write-gate.test.ts +72 -0
  209. package/src/node-serviceability.test.ts +86 -0
  210. package/src/node-serviceability.ts +124 -0
  211. package/src/node-session-control-http.test.ts +398 -0
  212. package/src/node-session-control.ts +316 -0
  213. package/src/node-skills-transport.test.ts +212 -0
  214. package/src/node-token-identity.ts +35 -0
  215. package/src/node-token-ownership.ts +51 -0
  216. package/src/node-token-privilege-http.test.ts +224 -0
  217. package/src/node-token-usage.test.ts +128 -0
  218. package/src/node-token-usage.ts +228 -0
  219. package/src/not-found-api-http.test.ts +67 -0
  220. package/src/observer-avatar-http.test.ts +103 -10
  221. package/src/observer-push.test.ts +76 -0
  222. package/src/opencode-catalog-report-http.test.ts +139 -0
  223. package/src/opencode-v2-catalog.test.ts +282 -0
  224. package/src/opencode-v2-catalog.ts +357 -0
  225. package/src/package-self-contained.test.ts +32 -0
  226. package/src/package-version-consistency.test.ts +25 -0
  227. package/src/parent-infer.test.ts +82 -0
  228. package/src/parent-infer.ts +110 -0
  229. package/src/parent-source-marker.test.ts +70 -0
  230. package/src/parent-source-orphan.test.ts +121 -0
  231. package/src/password-network-tokens.ts +25 -0
  232. package/src/peer-reply-atomic.test.ts +462 -0
  233. package/src/peer-reply-capability.test.ts +70 -0
  234. package/src/pg-worker.ts +87 -0
  235. package/src/poll-pacing.test.ts +74 -0
  236. package/src/poll-pacing.ts +123 -0
  237. package/src/probe-provider-error-domain.test.ts +145 -0
  238. package/src/project-dir-warn-clear-http.test.ts +132 -0
  239. package/src/project-viewer-can-http.test.ts +116 -0
  240. package/src/provider-skill-error-domain.test.ts +130 -0
  241. package/src/provider-tools-shape.test.ts +165 -0
  242. package/src/push.test.ts +20 -10
  243. package/src/push.ts +373 -9
  244. package/src/redact-tokens.test.ts +86 -0
  245. package/src/redact-tokens.ts +43 -0
  246. package/src/rejection-counters.test.ts +72 -0
  247. package/src/rejection-counters.ts +173 -0
  248. package/src/rename.ts +38 -10
  249. package/src/reply-target-derivation.test.ts +96 -0
  250. package/src/report-status-handover-capabilities-http.test.ts +124 -0
  251. package/src/report-status-host-schema.test.ts +272 -0
  252. package/src/report-status-resume-id-handover.test.ts +184 -0
  253. package/src/report-status-secret-keys.test.ts +140 -0
  254. package/src/require-explicit-test-db.ts +9 -0
  255. package/src/requirement-due-reminders-http.test.ts +620 -0
  256. package/src/requirement-due-reminders.ts +416 -0
  257. package/src/requirement-events-http.test.ts +318 -0
  258. package/src/requirement-events.test.ts +45 -0
  259. package/src/requirement-events.ts +144 -0
  260. package/src/requirement-notify.ts +165 -0
  261. package/src/requirement-participant-notify-http.test.ts +313 -0
  262. package/src/requirement-tag-ops-http.test.ts +454 -0
  263. package/src/requirement-tag-tree-http.test.ts +275 -0
  264. package/src/requirement-tag-tree.ts +127 -0
  265. package/src/requirement-tags.ts +102 -0
  266. package/src/requirements-abandoned-http.test.ts +236 -0
  267. package/src/requirements-assignee-drift.test.ts +154 -0
  268. package/src/requirements-comment-http.test.ts +174 -0
  269. package/src/requirements-completed-at-migration.test.ts +70 -0
  270. package/src/requirements-errors-mcp-http.test.ts +164 -0
  271. package/src/requirements-errors.ts +158 -0
  272. package/src/requirements-etag-http.test.ts +91 -0
  273. package/src/requirements-http.test.ts +709 -0
  274. package/src/requirements-last-event-http.test.ts +349 -0
  275. package/src/requirements-list-mcp-slim-http.test.ts +155 -0
  276. package/src/requirements-list-slim-http.test.ts +324 -0
  277. package/src/requirements-mcp.test.ts +180 -0
  278. package/src/requirements-migrate.ts +283 -0
  279. package/src/requirements-owner-strict-mcp-http.test.ts +145 -0
  280. package/src/requirements-people-http.test.ts +114 -0
  281. package/src/requirements-people-mcp-http.test.ts +231 -0
  282. package/src/requirements-people.ts +196 -0
  283. package/src/requirements-priority-lowest.test.ts +114 -0
  284. package/src/requirements-projects-network-echo.test.ts +57 -0
  285. package/src/requirements-projects-parent-http.test.ts +123 -0
  286. package/src/requirements-search-http.test.ts +182 -0
  287. package/src/requirements-search.test.ts +32 -0
  288. package/src/requirements-search.ts +145 -0
  289. package/src/requirements-seq-http.test.ts +193 -0
  290. package/src/requirements-seq-migration.test.ts +63 -0
  291. package/src/requirements-start-date.test.ts +125 -0
  292. package/src/requirements-stats-http.test.ts +357 -0
  293. package/src/requirements-stats.ts +195 -0
  294. package/src/requirements-status-participants-http.test.ts +222 -0
  295. package/src/requirements-upgrade-e2e.test.ts +126 -0
  296. package/src/requirements-upgrade-migration.test.ts +98 -0
  297. package/src/requirements.ts +2205 -0
  298. package/src/resolve-port.test.ts +57 -0
  299. package/src/resolve-port.ts +44 -0
  300. package/src/rest-alias-network-fallback-http.test.ts +123 -0
  301. package/src/rest-alias-network-fallback.test.ts +60 -0
  302. package/src/rest-alias-network-fallback.ts +65 -0
  303. package/src/rest-explicit-columns-http.test.ts +266 -0
  304. package/src/rest-identity.test.ts +130 -0
  305. package/src/rest-identity.ts +141 -0
  306. package/src/rest-projections.ts +72 -0
  307. package/src/rest-read-network-real-chain.test.ts +97 -0
  308. package/src/rest-write-network-resolution.test.ts +133 -0
  309. package/src/restart-readiness-http.test.ts +121 -0
  310. package/src/restricted-files.ts +76 -0
  311. package/src/retention-first-sweep-quiet.test.ts +31 -0
  312. package/src/retention.test.ts +100 -40
  313. package/src/retention.ts +423 -104
  314. package/src/route-callers-http.test.ts +120 -0
  315. package/src/route-timing.test.ts +218 -0
  316. package/src/route-timing.ts +262 -0
  317. package/src/rules-file-duplicate-alias.test.ts +234 -0
  318. package/src/rules-file-session-target.test.ts +207 -0
  319. package/src/rules-file-transport.test.ts +280 -0
  320. package/src/runtime-label.test.ts +22 -0
  321. package/src/runtime-label.ts +21 -0
  322. package/src/runtime-readiness.ts +90 -0
  323. package/src/schedule-agent-mcp-http.test.ts +486 -0
  324. package/src/schedule-agent.ts +252 -0
  325. package/src/schedule-starved.test.ts +92 -0
  326. package/src/schedule-starved.ts +114 -0
  327. package/src/scheduled-backoff-http.test.ts +203 -0
  328. package/src/scheduled-backoff.ts +64 -0
  329. package/src/scheduled-doorbell-nodeless-session.test.ts +134 -0
  330. package/src/scheduled-failure-backoff-2622.test.ts +145 -0
  331. package/src/scheduled-failure-code.test.ts +73 -0
  332. package/src/scheduled-failure-code.ts +105 -0
  333. package/src/scheduled-failures-http.test.ts +279 -0
  334. package/src/scheduled-failures.ts +425 -0
  335. package/src/scheduled-noprogress-backoff-2622.test.ts +163 -0
  336. package/src/scheduled-offline-backoff-probe.test.ts +56 -0
  337. package/src/scheduled-offline.test.ts +131 -0
  338. package/src/scheduled-offline.ts +66 -0
  339. package/src/scheduled-outcome-guidance-http.test.ts +139 -0
  340. package/src/scheduled-outcome-guidance.ts +9 -0
  341. package/src/scheduled-reply-unread-http.test.ts +212 -0
  342. package/src/scheduled-requirement-wake-http.test.ts +289 -0
  343. package/src/scheduled-requirement-wake.ts +125 -0
  344. package/src/scheduled-run-terminal.test.ts +290 -0
  345. package/src/scheduled-skip-blocking-task.test.ts +120 -0
  346. package/src/scheduled-skip-path-backoff-2622.test.ts +98 -0
  347. package/src/scheduled-stuck-http.test.ts +316 -0
  348. package/src/scheduled-stuck-notice-cap.test.ts +80 -0
  349. package/src/scheduled-stuck.ts +219 -0
  350. package/src/scheduled-tasks-http.test.ts +679 -0
  351. package/src/scheduled-tasks.ts +964 -0
  352. package/src/scheduled-work-outcome-http.test.ts +154 -0
  353. package/src/scheduled-work-outcome.ts +50 -0
  354. package/src/scoped-secrets.ts +167 -0
  355. package/src/secret-echo-negative-control.test.ts +118 -0
  356. package/src/send-dedup-request-id.test.ts +229 -0
  357. package/src/send-reply-agent-warning.test.ts +38 -38
  358. package/src/send-reply-alias-optional.test.ts +131 -0
  359. package/src/send-reply-attachments.test.ts +28 -7
  360. package/src/send_dedup.test.ts +54 -0
  361. package/src/send_dedup.ts +52 -6
  362. package/src/serve-error.test.ts +73 -0
  363. package/src/serve-error.ts +56 -0
  364. package/src/server.ts +5033 -377
  365. package/src/session-fork-store.test.ts +43 -0
  366. package/src/session-fork-store.ts +51 -0
  367. package/src/session-project-attach-migration.test.ts +22 -0
  368. package/src/session-project-attach-native.test.ts +121 -0
  369. package/src/session-project-create-http.test.ts +407 -0
  370. package/src/session-project-create-native.test.ts +290 -0
  371. package/src/session-project-create.ts +159 -0
  372. package/src/session-source-admission-store.ts +58 -0
  373. package/src/session-source-create.test.ts +155 -0
  374. package/src/session-source-create.ts +97 -0
  375. package/src/session-source-delivery.ts +109 -0
  376. package/src/session-source-directory-http.test.ts +192 -0
  377. package/src/session-source-evidence.test.ts +898 -0
  378. package/src/session-source-evidence.ts +191 -0
  379. package/src/session-source-execution.ts +87 -0
  380. package/src/session-source-grant.test.ts +117 -0
  381. package/src/session-source-grant.ts +78 -0
  382. package/src/session-source-issuer.test.ts +250 -0
  383. package/src/session-source-issuer.ts +164 -0
  384. package/src/session-source-transport.ts +375 -0
  385. package/src/session-task-on-dispatch.ts +14 -0
  386. package/src/session-token-ownership-http.test.ts +122 -0
  387. package/src/shared/codex-inventory.ts +41 -0
  388. package/src/shared/daemon-provider-login.ts +31 -0
  389. package/src/shared/daemon-provider-snapshot.ts +52 -0
  390. package/src/shared/external-schedule-contract.ts +60 -0
  391. package/src/shared/node-name.test.ts +62 -0
  392. package/src/shared/node-name.ts +161 -0
  393. package/src/shared/probe-host-allowlist-drift.test.ts +45 -0
  394. package/src/shared/provider-application.ts +29 -0
  395. package/src/shared/provider-collection.ts +14 -0
  396. package/src/shared/provider-initialization.ts +8 -0
  397. package/src/shared/reserved-env-drift.test.ts +10 -0
  398. package/src/shared/scoped-secret-contract.ts +5 -0
  399. package/src/shared/task-content-limit-drift.test.ts +28 -0
  400. package/src/shared/task-content-limit.ts +25 -0
  401. package/src/side-thread-command-transport.test.ts +312 -0
  402. package/src/side-thread-command-transport.ts +318 -0
  403. package/src/side-thread-http-integration.test.ts +233 -0
  404. package/src/side-thread-http.ts +504 -0
  405. package/src/side-thread-production.test.ts +72 -0
  406. package/src/side-thread-production.ts +118 -0
  407. package/src/side-thread.test.ts +1067 -0
  408. package/src/side-thread.ts +2499 -0
  409. package/src/skillhub-http.test.ts +144 -0
  410. package/src/sqlite-close-checkpoint.test.ts +78 -0
  411. package/src/start-node.test.ts +265 -0
  412. package/src/start-request-error-domain.test.ts +182 -0
  413. package/src/start-skill-error-domain.test.ts +122 -0
  414. package/src/stats-versions-http.test.ts +65 -0
  415. package/src/status-alias-filter-http.test.ts +106 -0
  416. package/src/status-alias-resolver-http.test.ts +163 -0
  417. package/src/status-alias-resolver.ts +19 -0
  418. package/src/status-node-id-filter-http.test.ts +161 -0
  419. package/src/status-node-secrets-capable-http.test.ts +44 -0
  420. package/src/status-read-cache-http.test.ts +229 -0
  421. package/src/status-read-cache.ts +129 -0
  422. package/src/stop-delete-node.test.ts +567 -1
  423. package/src/task-access-http.test.ts +407 -0
  424. package/src/task-access.ts +420 -0
  425. package/src/task-activity.ts +60 -0
  426. package/src/task-auth-origin-http.test.ts +93 -0
  427. package/src/task-auth-origin.test.ts +24 -0
  428. package/src/task-auth-origin.ts +7 -0
  429. package/src/task-consumption.test.ts +512 -0
  430. package/src/task-diagnostic-http.test.ts +149 -0
  431. package/src/task-diagnostic.test.ts +115 -0
  432. package/src/task-diagnostic.ts +118 -0
  433. package/src/task-expiry-notice-http.test.ts +298 -0
  434. package/src/task-expiry-notice.ts +318 -0
  435. package/src/task-idempotency-mcp.test.ts +148 -0
  436. package/src/task-idempotency.test.ts +76 -0
  437. package/src/task-idempotency.ts +81 -0
  438. package/src/task-late-replies.ts +54 -0
  439. package/src/task-late-reply-http.test.ts +227 -0
  440. package/src/task-lifecycle-watcher-busy.test.ts +114 -0
  441. package/src/task-lifecycle-watcher.test.ts +209 -0
  442. package/src/task-lifecycle-watcher.ts +109 -0
  443. package/src/task-network-resolution-http.test.ts +140 -0
  444. package/src/task-not-found-error-domain.test.ts +117 -0
  445. package/src/task-offline-delivery-2668.test.ts +119 -0
  446. package/src/task-offline-delivery.ts +81 -0
  447. package/src/task-orphan-http.test.ts +287 -0
  448. package/src/task-orphan.ts +119 -0
  449. package/src/task-queue-ahead-http.test.ts +309 -0
  450. package/src/task-queue-ahead-scale.test.ts +236 -0
  451. package/src/task-queue-ahead.ts +186 -0
  452. package/src/task-rejection-log-http.test.ts +160 -0
  453. package/src/task-rejection-log.ts +61 -0
  454. package/src/task-sender-http.test.ts +143 -0
  455. package/src/task-stale-open-http.test.ts +292 -0
  456. package/src/task-stale-open.ts +103 -0
  457. package/src/tasks-pagination-http.test.ts +141 -0
  458. package/src/team-rules-status-http.test.ts +90 -0
  459. package/src/team-rules-status.test.ts +59 -0
  460. package/src/team-rules-status.ts +72 -0
  461. package/src/tmux-allowlist.test.ts +48 -0
  462. package/src/token-usage-http.test.ts +156 -0
  463. package/src/tool-audience-http.test.ts +266 -0
  464. package/src/tool-audience.ts +130 -0
  465. package/src/tools-list-json-schema.test.ts +94 -0
  466. package/src/tools.ts +4530 -471
  467. package/src/update-node-config-error-domain.test.ts +107 -0
  468. package/src/uploads-http.test.ts +6 -4
  469. package/src/uploads.ts +23 -4
  470. package/src/user-avatar-http.test.ts +74 -0
  471. package/src/user-avatar-image.ts +160 -0
  472. package/src/user-avatar-migration.test.ts +25 -0
  473. package/src/user-avatar-upload-http.test.ts +353 -0
  474. package/src/user-inbox-by-agent-http.test.ts +189 -0
  475. package/src/user-inbox-netid-notnull.test.ts +122 -0
  476. package/src/user-inbox-read-http.test.ts +223 -0
  477. package/src/user-inbox-schema.test.ts +54 -0
  478. package/src/version-stats.test.ts +66 -0
  479. package/src/version-stats.ts +109 -0
@@ -0,0 +1,59 @@
1
+ // #2211 — the four states, as decisions rather than as prose.
2
+ //
3
+ // The point of these cases is that "behind" and "failed" are different words:
4
+ // v1 injects at full start, so a node that simply has not restarted is `outdated`.
5
+ // Calling that `failed` would send someone to debug a node that is doing fine.
6
+ import { describe, expect, test } from "bun:test";
7
+ import { deriveTeamRulesView } from "./team-rules-status";
8
+
9
+ const report = (o: Record<string, unknown>) => o as any;
10
+
11
+ describe("deriveTeamRulesView (#2211)", () => {
12
+ test("a node that never attempted is omitted entirely (not reported as null state)", () => {
13
+ expect(deriveTeamRulesView(null, 3)).toBeNull();
14
+ expect(deriveTeamRulesView(undefined, 3)).toBeNull();
15
+ expect(deriveTeamRulesView(report({}), 3)).toBeNull();
16
+ });
17
+
18
+ test("applied revision equals the network's current revision → current", () => {
19
+ const v = deriveTeamRulesView(report({ revision: 3, status: "injected", at: "2026-10-24T12:00:00Z" }), 3)!;
20
+ expect(v).toMatchObject({ state: "current", applied_revision: 3, current_revision: 3 });
21
+ });
22
+
23
+ test("behind the current revision → outdated, with the reason kept for context", () => {
24
+ const v = deriveTeamRulesView(report({ revision: 2, status: "unchanged" }), 3)!;
25
+ expect(v.state).toBe("outdated");
26
+ expect(v.applied_revision).toBe(2);
27
+ expect(v.current_revision).toBe(3);
28
+ });
29
+
30
+ test("an error is failed even when it also happens to carry the current revision", () => {
31
+ const v = deriveTeamRulesView(report({ revision: 3, status: "error", reason: "expected exactly one BEGIN" }), 3)!;
32
+ expect(v.state).toBe("failed");
33
+ expect(v.reason).toBe("expected exactly one BEGIN");
34
+ });
35
+
36
+ test("skipped with no revision (disabled / hub unreachable) → never, reason preserved", () => {
37
+ const v = deriveTeamRulesView(report({ revision: null, status: "skipped", reason: "hub_timeout" }), 3)!;
38
+ expect(v).toMatchObject({ state: "never", applied_revision: null, reason: "hub_timeout" });
39
+ });
40
+
41
+ test("the network lost its rules but the node still carries a block → outdated", () => {
42
+ const v = deriveTeamRulesView(report({ revision: 4, status: "injected" }), null)!;
43
+ expect(v.state).toBe("outdated");
44
+ expect(v.current_revision).toBeNull();
45
+ });
46
+
47
+ test("a hub rollback (node ahead of the current revision) is not called current", () => {
48
+ const v = deriveTeamRulesView(report({ revision: 5, status: "injected" }), 3)!;
49
+ expect(v.state).toBe("outdated");
50
+ });
51
+
52
+ test("malformed input never throws and never fabricates a revision", () => {
53
+ const v = deriveTeamRulesView(report({ revision: "3" as any, status: 42 as any, reason: 7 as any }), 3);
54
+ expect(v).not.toBeNull();
55
+ expect(v!.state).toBe("never");
56
+ expect(v!.applied_revision).toBeNull();
57
+ expect(v!.reason).toBeNull();
58
+ });
59
+ });
@@ -0,0 +1,72 @@
1
+ // #2211 — turn "what the node last did" into one word an operator can act on.
2
+ //
3
+ // The node reports `team_rules: { revision, status, reason?, at }` on every status
4
+ // report (agent-node .156). The Hub knows the network's current revision. This module
5
+ // is the pure comparison between the two — no database, no HTTP, so the rules are
6
+ // testable before any wiring exists.
7
+ //
8
+ // The four states are deliberately about *the node being behind*, not about a failed
9
+ // push: v1 injects at full start, so a node that has not restarted since a rule change
10
+ // is `outdated`, not `failed`. Calling that "failed" would blame the wrong side.
11
+ //
12
+ // current — applied revision equals the network's current revision
13
+ // outdated — this node has not picked up the current revision yet (restart needed)
14
+ // failed — the last attempt ended in an error; `reason` says why
15
+ // never — this node has never attempted an injection (or the rules are empty and
16
+ // it has nothing to apply)
17
+ //
18
+ // Unknown input never throws: a malformed report degrades to `never` with the reason
19
+ // preserved, because a status line is not worth a 500.
20
+
21
+ export type TeamRulesState = "current" | "outdated" | "failed" | "never";
22
+
23
+ export type TeamRulesReportIn = {
24
+ revision?: number | null;
25
+ status?: string | null;
26
+ reason?: string | null;
27
+ at?: string | null;
28
+ };
29
+
30
+ export type TeamRulesView = {
31
+ state: TeamRulesState;
32
+ applied_revision: number | null;
33
+ current_revision: number | null;
34
+ status: string | null;
35
+ reason: string | null;
36
+ at: string | null;
37
+ };
38
+
39
+ /**
40
+ * @param report what the node last reported (null/undefined = it never reported)
41
+ * @param currentRevision the network's current `network_rules.revision` (null when no row)
42
+ */
43
+ export function deriveTeamRulesView(
44
+ report: TeamRulesReportIn | null | undefined,
45
+ currentRevision: number | null,
46
+ ): TeamRulesView | null {
47
+ if (!report || (report.revision == null && !report.status)) return null;
48
+
49
+ const applied = typeof report.revision === "number" && Number.isFinite(report.revision) ? report.revision : null;
50
+ const current = typeof currentRevision === "number" && Number.isFinite(currentRevision) ? currentRevision : null;
51
+ const status = typeof report.status === "string" ? report.status : null;
52
+ const reason = typeof report.reason === "string" && report.reason ? report.reason : null;
53
+ const at = typeof report.at === "string" && report.at ? report.at : null;
54
+
55
+ let state: TeamRulesState;
56
+ if (status === "error") {
57
+ state = "failed";
58
+ } else if (applied == null) {
59
+ // attempted but nothing was applied (disabled / skipped with no revision)
60
+ state = "never";
61
+ } else if (current == null) {
62
+ // the network has no rules row (revision absent) but the node carries a block
63
+ state = "outdated";
64
+ } else if (applied === current) {
65
+ state = "current";
66
+ } else {
67
+ // behind (usual case) or ahead after a Hub rollback — either way it does not match
68
+ state = "outdated";
69
+ }
70
+
71
+ return { state, applied_revision: applied, current_revision: current, status, reason, at };
72
+ }
@@ -0,0 +1,48 @@
1
+ // 2026-10-31 —— tmux 端点允许清单的方向钉点。
2
+ //
3
+ // 为什么单独钉:这是本仓少见的「不匹配 ⇒ 拒绝」路径,判据错了不会报错,
4
+ // 只会**静默锁死**(fail-closed),而锁死的成因里有一类是字符串形态不一致:
5
+ // allowlist 人手写 IPv4(1.2.3.4),socket 在双栈监听下给 IPv4-mapped IPv6(::ffff:1.2.3.4)
6
+ // ⇒ 同一台机器在两个字符串下被判成两回事。
7
+ //
8
+ // 反向也要钉(must-fire):清单里有的公网 IP **必须**被放行——
9
+ // 否则「一律拒绝」的实现也能通过所有「拒绝」断言,而那是另一种坏法。
10
+ import { describe, expect, test } from "bun:test";
11
+ import { ipAllowedBy, normalizeRequestIp } from "./server.js";
12
+
13
+ const NONE: ReadonlySet<string> = new Set();
14
+
15
+ describe("tmux allowlist: 空清单的落点与两个方向的判别力", () => {
16
+ test("空清单 = 只允许本机(最严侧),而不是「谁都行」", () => {
17
+ expect(ipAllowedBy("127.0.0.1", NONE)).toBe(true);
18
+ expect(ipAllowedBy("::1", NONE)).toBe(true);
19
+ expect(ipAllowedBy("::ffff:127.0.0.1", NONE)).toBe(true);
20
+ expect(ipAllowedBy("8.8.8.8", NONE)).toBe(false);
21
+ // 拿不到地址时(无 X-Forwarded-For / 无 socket 信息)也是拒绝,不是放行
22
+ expect(ipAllowedBy("unknown", NONE)).toBe(false);
23
+ expect(ipAllowedBy("", NONE)).toBe(false);
24
+ });
25
+
26
+ test("清单里有的必须被放行(否则「一律拒绝」也能骗过上面那条)", () => {
27
+ const set = new Set(["1.2.3.4"]);
28
+ expect(ipAllowedBy("1.2.3.4", set)).toBe(true);
29
+ expect(ipAllowedBy("1.2.3.5", set)).toBe(false);
30
+ expect(ipAllowedBy("1.2.3.40", set)).toBe(false); // 前缀不算命中
31
+ });
32
+
33
+ test("IPv4-mapped IPv6 与 IPv4 是同一个主机(这一条就是那个静默锁死的补丁)", () => {
34
+ const set = new Set(["1.2.3.4"]);
35
+ expect(ipAllowedBy("::ffff:1.2.3.4", set)).toBe(true);
36
+ expect(normalizeRequestIp("::FFFF:1.2.3.4")).toBe("1.2.3.4");
37
+ // 对称:人手写成 mapped 形式,普通 IPv4 请求也要命中
38
+ const mapped = new Set([normalizeRequestIp("::ffff:5.6.7.8")]);
39
+ expect(ipAllowedBy("5.6.7.8", mapped)).toBe(true);
40
+ });
41
+
42
+ test("不做子串/前缀匹配:只有整串相等才算", () => {
43
+ const set = new Set(["10.0.0.1"]);
44
+ expect(ipAllowedBy("10.0.0.10", set)).toBe(false);
45
+ expect(ipAllowedBy("110.0.0.1", set)).toBe(false);
46
+ expect(normalizeRequestIp(" 10.0.0.1 ")).toBe("10.0.0.1");
47
+ });
48
+ });
@@ -0,0 +1,156 @@
1
+ // #3952/#3950 —— `GET /api/token-usage` 的 HTTP 面。
2
+ //
3
+ // 这个端点存在的理由是「人能看见节点消耗了多少 token」,所以它必须钉住四条:
4
+ //
5
+ // ① 节点令牌看不到(node 不是人 —— 与 catalog 读接口同一条边界);
6
+ // ② 别的网络的成员看不到本网络的用量(network 隔离);
7
+ // ③ **cache 不进 total**(实测 cache.read 可以是 total 的几百倍,
8
+ // 一旦混算,排行会变成「谁最老」而不是「谁用得最多」);
9
+ // ④ 空窗口要能分清「没人上报」与「用量为 0」—— 两者在表上同形。
10
+ //
11
+ // 另外钉住覆盖率的分母:只有 1 行时,读表的人不该把它读成「只有 1 台在干活」。
12
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
13
+ import { mkdtempSync, rmSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { join } from "node:path";
16
+
17
+ const PRIVATE_DB_DIR = mkdtempSync(join(tmpdir(), "anet-token-usage-"));
18
+ process.env.COMMHUB_DB ||= join(PRIVATE_DB_DIR, "hub.db");
19
+
20
+ let server: ReturnType<typeof Bun.serve>;
21
+ let base = "";
22
+ let ownerToken = "", strangerToken = "", nodeToken = "";
23
+ let ownerNet = "", strangerNet = "";
24
+ // 路径写成字面量常量:`scripts/report-rest-visibility.py` 用「测试里出现带引号的完整路径」
25
+ // 判断这条路由有没有被请求过;模板串里拼参数会让它记成「从未被请求」。
26
+ const TOKEN_USAGE = "/api/token-usage";
27
+
28
+ const get = async (path: string, token?: string) => {
29
+ const headers: Record<string, string> = {};
30
+ if (token) headers.Authorization = `Bearer ${token}`;
31
+ const r = await fetch(`${base}${path}`, { headers });
32
+ const text = await r.text();
33
+ let body: any = null;
34
+ try { body = JSON.parse(text); } catch { body = null; }
35
+ return { status: r.status, body, text };
36
+ };
37
+
38
+ beforeAll(async () => {
39
+ const { db } = await import("./db.js");
40
+ // 建表发生在 node-token-usage 模块被 import 时(刻意的:只要 import 了它,表就一定在)。
41
+ // 不先 import 就直接 INSERT ⇒ "no such table",而那个错误看起来像"迁移没跑"。
42
+ await import("./node-token-usage.js");
43
+ const { register, createNetworkTokenForNode } = await import("./auth.js");
44
+ const stamp = Date.now();
45
+
46
+ const owner = register(`tu_owner_${stamp}`, "TuOwner-Strong-1!");
47
+ const stranger = register(`tu_stranger_${stamp}`, "TuStranger-Strong-1!");
48
+ expect(owner.ok && stranger.ok).toBe(true);
49
+ ownerToken = owner.token!;
50
+ strangerToken = stranger.token!;
51
+ ownerNet = owner.network_id!;
52
+ strangerNet = stranger.network_id!;
53
+
54
+ const ownerUserId = db.get<{ user_id: string }>(
55
+ "SELECT user_id FROM users WHERE username = ?1", `tu_owner_${stamp}`)!.user_id;
56
+ const nodeTok = createNetworkTokenForNode(ownerUserId, ownerNet, "tu-node", "n_tu_test");
57
+ expect(nodeTok.ok).toBe(true);
58
+ nodeToken = nodeTok.token!;
59
+
60
+ // 两行用量:一行大(cache 远大于 body),一行小。
61
+ const now = new Date();
62
+ const hour = `${now.toISOString().slice(0, 13)}`;
63
+ db.run(
64
+ `INSERT INTO node_token_usage (network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens)
65
+ VALUES (?1, 'n_tu_a', ?2, 'm1', 1000, 500, 900000)`,
66
+ [ownerNet, hour],
67
+ );
68
+ db.run(
69
+ `INSERT INTO node_token_usage (network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens)
70
+ VALUES (?1, 'n_tu_b', ?2, 'm2', 10, 5, 100)`,
71
+ [ownerNet, hour],
72
+ );
73
+ // 另一个网络的行:绝不能出现在 owner 的读数里。
74
+ db.run(
75
+ `INSERT INTO node_token_usage (network_id, node_id, hour, model, input_tokens, output_tokens, cache_read_tokens)
76
+ VALUES (?1, 'n_tu_x', ?2, 'mx', 77777, 77777, 77777)`,
77
+ [strangerNet, hour],
78
+ );
79
+
80
+ // 覆盖率分母靠 sessions.version 判定:一台 >= .180(会报),一台旧版(不会报)。
81
+ db.run(
82
+ `INSERT INTO sessions (resume_id, alias, node_id, network_id, status, version)
83
+ VALUES ('tu-s1', 'tu-capable', 'n_tu_a', ?1, 'idle', '2.5.0-preview.181')`,
84
+ [ownerNet],
85
+ );
86
+ db.run(
87
+ `INSERT INTO sessions (resume_id, alias, node_id, network_id, status, version)
88
+ VALUES ('tu-s2', 'tu-old', 'n_tu_b', ?1, 'idle', '2.5.0-preview.164')`,
89
+ [ownerNet],
90
+ );
91
+
92
+ // 用 bootServer 而不是 app.fetch:server.ts 只导出 bootServer(没有默认导出的 handler)。
93
+ const mod: any = await import("./server.js");
94
+ server = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
95
+ base = `http://127.0.0.1:${server.port}`;
96
+ });
97
+
98
+ afterAll(() => {
99
+ server?.stop(true);
100
+ rmSync(PRIVATE_DB_DIR, { recursive: true, force: true });
101
+ });
102
+
103
+ describe("#3952 /api/token-usage", () => {
104
+ test("本人网络:拿得到两行,且 total = input + output(cache 不进 total)", async () => {
105
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}&since_hours=24`, ownerToken);
106
+ expect(r.status).toBe(200);
107
+ const nodes = r.body.nodes as any[];
108
+ expect(nodes.length).toBe(2);
109
+ expect(r.body.totals.input_tokens).toBe(1010);
110
+ expect(r.body.totals.output_tokens).toBe(505);
111
+ expect(r.body.totals.total_tokens).toBe(1515);
112
+ // 镜像:cache 单列存在,且**不等于** total —— 混算的话这里会相等
113
+ expect(r.body.totals.cache_read_tokens).toBe(900100);
114
+ expect(r.body.totals.cache_read_tokens).not.toBe(r.body.totals.total_tokens);
115
+ // 别的网络的行不在里面
116
+ expect(nodes.every((n: any) => n.node_id !== "n_tu_x")).toBe(true);
117
+ });
118
+
119
+ test("不传 network_id:唯一所属网络时自动回退(与 /api/providers 同口径)", async () => {
120
+ // 上一版这里 400 network_required,而同一页的 /api/providers 会给 200 ——
121
+ // 同一台 hub 上相邻两个端点对同一个用户给不同答案,客户端被迫多写分支。
122
+ const r = await get(`${TOKEN_USAGE}?since_hours=24`, ownerToken);
123
+ expect(r.status).toBe(200);
124
+ expect(r.body.network_id).toBe(ownerNet);
125
+ // 镜像:既然回退了,就必须回退到**自己的**网络,而不是任意一个
126
+ expect(r.body.network_id).not.toBe(strangerNet);
127
+ });
128
+
129
+ test("节点令牌看不到(user_token_required,不是 404 也不是空表)", async () => {
130
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}`, nodeToken);
131
+ expect(r.status).toBe(403);
132
+ expect(r.body.error).toBe("user_token_required");
133
+ });
134
+
135
+ test("别的网络的成员看不到(not a member,且不泄漏行数)", async () => {
136
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}`, strangerToken);
137
+ expect(r.status).toBe(403);
138
+ expect(r.body.nodes).toBeUndefined();
139
+ });
140
+
141
+ test("没令牌:401 而不是空表", async () => {
142
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}`);
143
+ expect(r.status).toBe(401);
144
+ });
145
+
146
+ test("覆盖率分母:capable 只数 >= .180,不等于会话总数", async () => {
147
+ const r = await get(`${TOKEN_USAGE}?network_id=${ownerNet}&since_hours=24`, ownerToken);
148
+ expect(r.status).toBe(200);
149
+ const cov = r.body.coverage;
150
+ expect(cov.reporting_nodes).toBe(2);
151
+ expect(cov.capable_nodes).toBe(1);
152
+ expect(cov.sessions_with_version).toBe(2);
153
+ // 镜像:分母比分子大 ⇒ 这个字段不是把 reporting_nodes 复制了一遍
154
+ expect(cov.sessions_with_version).toBeGreaterThan(cov.capable_nodes);
155
+ });
156
+ });
@@ -0,0 +1,266 @@
1
+ // #478 —— tools/list 按调用者给(tool-audience.ts)。钉住:
2
+ // 1. 每个注册的工具都在 TOOL_AUDIENCE 里归了类(新工具忘了归类 → 红),表里也没有已经不存在的工具;
3
+ // 2. 兼容回放:对每种调用者(节点:正常 / 只读 / 受限 / enforce 开关;人:owner / member / viewer),把每个工具都真调一次 ——
4
+ // 今天调得通的(不是那几种「不看参数就拒」的错误),一定还在它的列表里(协议工具在 opt-in 的列表里);
5
+ // 列表里藏起来的,调用一定回那几种拒绝之一。tools/call 不受影响(只滤列表)。
6
+ // 3. 每种角色的 tools/list 字节数(打印 before / after),各有上限(#476 的总上限仍管「全部工具」)。
7
+ // 跑法:cd server && COMMHUB_DB=/tmp/x.db bun test src/tool-audience-http.test.ts(PG 在 tests/test2123-hub-postgres-ladder 里注册)
8
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9
+ import { mkdtempSync, rmSync } from "fs";
10
+ import { join } from "path";
11
+ import { tmpdir } from "os";
12
+ import { register, createNetworkTokenForNode } from "./auth.js";
13
+ import { db } from "./db.js";
14
+ import { TOOL_AUDIENCE } from "./tool-audience.js";
15
+
16
+ const DIR = mkdtempSync(join(tmpdir(), "anet-tool-audience-"));
17
+ let BASE = "";
18
+ let hub: any = null;
19
+ const PW = "ToolAudiencePassw0rd!x";
20
+ let NET = "";
21
+ const T: Record<string, string> = {};
22
+
23
+ /** 处理函数里「不看参数就拒」的错误码(用户令牌调节点工具 / 节点令牌调人的工具 / #487 的拒绝)。 */
24
+ const REFUSALS = new Set(["network_token_required", "node_token_required", "caller_not_a_daemon", "user_token_required", "node_token_cannot_browse_files", "node_token_cannot_read_logs", "node_permission_denied"]);
25
+
26
+ async function rpc(token: string, method: string, params: unknown, headers: Record<string, string> = {}) {
27
+ const res = await fetch(`${BASE}/mcp`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26", ...headers }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }) });
28
+ const raw = await res.text();
29
+ const line = raw.split("\n").filter(x => x.startsWith("data:")).at(-1);
30
+ return { json: line ? JSON.parse(line.slice(5)) : JSON.parse(raw), bytes: 0 };
31
+ }
32
+ async function listTools(token: string, all = false): Promise<{ names: string[]; bytes: number; tools: any[] }> {
33
+ const { json } = await rpc(token, "tools/list", {}, all ? { "X-Anet-Tools": "all" } : {});
34
+ const tools = json.result.tools as any[];
35
+ return { names: tools.map(t => t.name), bytes: Buffer.byteLength(JSON.stringify({ tools }), "utf8"), tools };
36
+ }
37
+
38
+ // 参数:按 inputSchema 生成;名字认得的用真值;schema 有格式要求的给合法值(不给 → -32602,测试会让你补)。
39
+ const OVERRIDES: Record<string, Record<string, unknown>> = {
40
+ get_skill: { skill_id: "skill_probe" },
41
+ review_skill: { skill_id: "skill_probe" },
42
+ mark_tasks_runtime_submitted: { task_ids: ["task_probe"] },
43
+ mark_tasks_consumed: { task_ids: ["task_probe"] },
44
+ upsert_network_secret: { key: "PROBE_KEY" },
45
+ update_provider: { provider_id: "prov_probe" },
46
+ schedule_batch_interval: { schedule_ids: ["sched_probe"], every_seconds: 60 },
47
+ select_opencode_session_model: { session_id: "ses_probe", model: { providerID: "stub", id: "model" } },
48
+ };
49
+ function fill(schema: any, key: string, ctx: Record<string, unknown>): unknown {
50
+ if (!schema) return "probe";
51
+ if (ctx[key] !== undefined) return ctx[key];
52
+ if (schema.enum) return schema.enum[0];
53
+ if (schema.anyOf) return fill(schema.anyOf.find((s: any) => s.type !== "null") ?? schema.anyOf[0], key, ctx);
54
+ const t = Array.isArray(schema.type) ? schema.type.find((x: string) => x !== "null") : schema.type;
55
+ if (t === "string") return schema.minLength && schema.minLength > 5 ? "p".repeat(schema.minLength) : "probe";
56
+ if (t === "integer" || t === "number") return schema.minimum ?? 1;
57
+ if (t === "boolean") return false;
58
+ if (t === "array") return [];
59
+ if (t === "object") { const o: Record<string, unknown> = {}; for (const k of schema.required ?? []) o[k] = fill(schema.properties?.[k], k, ctx); return o; }
60
+ return "probe";
61
+ }
62
+ let ALL_TOOLS: any[] = [];
63
+ const argsFor = (tool: any) => ({ ...(fill(tool.inputSchema, "", { network_id: NET, alias: "probe-victim", new_alias: "probe-victim", node_id: "node_ta_victim" }) as object), ...(OVERRIDES[tool.name] ?? {}) });
64
+ async function callOutcome(token: string, tool: any): Promise<{ refused: boolean; schema: boolean; code: string }> {
65
+ const { json } = await rpc(token, "tools/call", { name: tool.name, arguments: argsFor(tool) });
66
+ if (json.error) return { refused: false, schema: json.error.code === -32602, code: `rpc:${json.error.code}` };
67
+ const text = String(json.result?.content?.[0]?.text ?? "");
68
+ if (/^MCP error -32602/.test(text)) return { refused: false, schema: true, code: "schema" };
69
+ let body: any = null;
70
+ try { body = JSON.parse(text); } catch {}
71
+ const code = body && body.ok === false ? String(body.error) : "ok";
72
+ // 受限成员的闸(agent_access_restricted)跑在处理函数前面,看传的 network_id;对节点 / 协议工具,处理函数后面还有一道
73
+ // 不看参数的 network_token_required(用户令牌换哪个网络都过不去),所以这时它也算拒。对「两边都能用」的工具不算。
74
+ const masked = code === "agent_access_restricted" && (TOOL_AUDIENCE[tool.name] === "node" || TOOL_AUDIENCE[tool.name] === "protocol");
75
+ return { refused: REFUSALS.has(code) || masked, schema: false, code };
76
+ }
77
+
78
+ beforeAll(async () => {
79
+ process.env.COMMHUB_DB ||= join(DIR, "hub.db");
80
+ process.env.COMMHUB_UPLOADS_DIR = join(DIR, "uploads");
81
+ process.env.HOST = "127.0.0.1";
82
+ delete process.env.COMMHUB_NODE_PERMISSIONS;
83
+ const owner = register(`ta_owner_${Date.now()}`, PW, undefined, "Owner");
84
+ NET = owner.network_id!;
85
+ T.owner = owner.token!;
86
+ const mod: any = await import("./server.js");
87
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
88
+ BASE = `http://127.0.0.1:${hub.port}`;
89
+ const mk = async (k: string, role: string) => {
90
+ const username = `ta_${k}_${Date.now()}`;
91
+ await fetch(`${BASE}/api/admin/users`, { method: "POST", headers: { Authorization: `Bearer ${T.owner}`, "Content-Type": "application/json" }, body: JSON.stringify({ username, password: PW, network_id: NET, role }) });
92
+ T[k] = (await (await fetch(`${BASE}/api/auth/login`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password: PW }) })).json()).token;
93
+ };
94
+ await mk("member", "member");
95
+ await mk("viewer", "viewer");
96
+ for (const mode of ["normal", "readonly", "restricted"]) {
97
+ T[`node_${mode}`] = createNetworkTokenForNode(owner.user!.user_id, NET, `ta-${mode}`, `node_ta_${mode}`).token!;
98
+ db.run("UPDATE nodes SET permission_mode = ?1 WHERE node_id = ?2", [mode, `node_ta_${mode}`]);
99
+ }
100
+ createNetworkTokenForNode(owner.user!.user_id, NET, "probe-victim", "node_ta_victim");
101
+ // 没有身份的调用者 = 不过滤:用 owner 的「全部」作为全集(owner 是用户令牌,协议工具对它不列;全集取并集)。
102
+ const a = await listTools(T.node_normal, true);
103
+ const b = await listTools(T.owner);
104
+ const byName = new Map([...a.tools, ...b.tools].map(t => [t.name, t]));
105
+ ALL_TOOLS = [...byName.values()];
106
+ }, 60_000);
107
+
108
+ afterAll(() => {
109
+ delete process.env.COMMHUB_NODE_PERMISSIONS;
110
+ try { hub?.stop?.(true); } catch {}
111
+ try { rmSync(DIR, { recursive: true, force: true }); } catch {}
112
+ });
113
+
114
+ describe("every tool is classified", () => {
115
+ test("registry == TOOL_AUDIENCE (no unclassified tool, no stale entry)", async () => {
116
+ const registered = ALL_TOOLS.map(t => t.name).sort();
117
+ expect(registered.length).toBeGreaterThan(70);
118
+ expect(registered.filter(n => !TOOL_AUDIENCE[n])).toEqual([]);
119
+ expect(Object.keys(TOOL_AUDIENCE).filter(n => !registered.includes(n))).toEqual([]);
120
+ });
121
+ });
122
+
123
+ test("create_node source_ref fails MCP validation without minting or enqueueing", async () => {
124
+ const count = (table: string) => db.get<{ n: number }>(`SELECT COUNT(*) AS n FROM ${table}`)!.n;
125
+ const before = [count("node_create_requests"), count("api_tokens")];
126
+ const base = { daemon_node_id: "daemon_source_fixture", network_id: NET,
127
+ node_spec: { name: "source-fixture", runtime: "opencode-cli" } };
128
+ for (const source_ref of ["src_fixture", null, "", {}]) {
129
+ for (const args of [{ ...base, source_ref }, { ...base, node_spec: { ...base.node_spec, source_ref } }]) {
130
+ const { json } = await rpc(T.owner, "tools/call", { name: "create_node", arguments: args });
131
+ const text = String(json.result?.content?.[0]?.text ?? "");
132
+ expect(json.error?.code === -32602 || /^MCP error -32602/.test(text)).toBe(true);
133
+ }
134
+ }
135
+ expect([count("node_create_requests"), count("api_tokens")]).toEqual(before);
136
+ const ordinary = await rpc(T.owner, "tools/call", { name: "create_node", arguments: base });
137
+ expect(JSON.parse(ordinary.json.result.content[0].text).error).toBe("daemon_not_found");
138
+ });
139
+
140
+ describe("compat replay: nothing callable today disappears from the list", () => {
141
+ const cases: Array<[string, string, string | null]> = [
142
+ ["node (normal, log)", "node_normal", null], ["node (readonly)", "node_readonly", null], ["node (restricted)", "node_restricted", null],
143
+ ["node (normal, enforce)", "node_normal", "enforce"], ["owner", "owner", null], ["member", "member", null], ["viewer", "viewer", null],
144
+ ];
145
+ for (const [label, key, flag] of cases) {
146
+ test(label, async () => {
147
+ if (flag) process.env.COMMHUB_NODE_PERMISSIONS = flag; else delete process.env.COMMHUB_NODE_PERMISSIONS;
148
+ try {
149
+ const isNode = key.startsWith("node_");
150
+ const listed = new Set((await listTools(T[key], isNode)).names);
151
+ // 「调得通 ⇒ 列着」,等价于「藏起来的 ⇒ 一定是那几种拒绝」。
152
+ const lost: string[] = [], schema: string[] = [];
153
+ for (const tool of ALL_TOOLS) {
154
+ const out = await callOutcome(T[key], tool);
155
+ if (out.schema) schema.push(tool.name);
156
+ if (!out.refused && !listed.has(tool.name)) lost.push(`${tool.name}(${out.code})`);
157
+ }
158
+ expect(schema).toEqual([]); // 每个工具都真跑到了处理函数(否则判不出能不能用)
159
+ expect(lost).toEqual([]);
160
+ } finally { delete process.env.COMMHUB_NODE_PERMISSIONS; }
161
+ }, 120_000);
162
+ }
163
+ });
164
+
165
+ describe("what each caller sees", () => {
166
+ test("node: no human-only tools; protocol tools only with X-Anet-Tools: all; user: no node / protocol tools", async () => {
167
+ const node = new Set((await listTools(T.node_normal)).names);
168
+ const nodeAll = new Set((await listTools(T.node_normal, true)).names);
169
+ const user = new Set((await listTools(T.owner)).names);
170
+ for (const [name, a] of Object.entries(TOOL_AUDIENCE)) {
171
+ expect([name, node.has(name)]).toEqual([name, a === "both" || a === "node"]);
172
+ expect([name, nodeAll.has(name)]).toEqual([name, a !== "user"]);
173
+ expect([name, user.has(name)]).toEqual([name, a === "both" || a === "user"]);
174
+ }
175
+ // ?tools=all is the same switch for clients that cannot set headers
176
+ const viaQuery = await fetch(`${BASE}/mcp?tools=all`, { method: "POST", headers: { Authorization: `Bearer ${T.node_normal}`, "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": "2025-03-26" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list", params: {} }) });
177
+ const raw = await viaQuery.text();
178
+ const parsed = JSON.parse(raw.split("\n").filter(x => x.startsWith("data:")).at(-1)!.slice(5));
179
+ expect(parsed.result.tools.length).toBe(nodeAll.size);
180
+ });
181
+
182
+ test("node modes: readonly / restricted drop broadcast + node writes + human-only; enforce drops human-only for normal nodes", async () => {
183
+ const ro = new Set((await listTools(T.node_readonly)).names);
184
+ for (const n of ["broadcast", "update_node_config", "create_node", "clone_node", "upsert_provider"]) expect([n, ro.has(n)]).toEqual([n, false]);
185
+ for (const n of ["send_task", "requirements_update", "report_status", "get_all_status"]) expect([n, ro.has(n)]).toEqual([n, true]); // 看参数才拒的照列
186
+ expect(new Set((await listTools(T.node_normal)).names).has("upsert_provider")).toBe(true); // log 模式:调得通,照列
187
+ process.env.COMMHUB_NODE_PERMISSIONS = "enforce";
188
+ try { expect(new Set((await listTools(T.node_normal)).names).has("upsert_provider")).toBe(false); } finally { delete process.env.COMMHUB_NODE_PERMISSIONS; }
189
+ });
190
+
191
+ test("a hidden tool still answers tools/call exactly as before (only the list changes)", async () => {
192
+ const p = await rpc(T.node_normal, "tools/call", { name: "projects_create", arguments: { network_id: NET, name: "示例项目" } });
193
+ expect(JSON.parse(p.json.result.content[0].text).error).toBe("user_token_required");
194
+ const r = await rpc(T.owner, "tools/call", { name: "report_status", arguments: argsFor(ALL_TOOLS.find(t => t.name === "report_status")) });
195
+ expect(JSON.parse(r.json.result.content[0].text).error).toBe("network_token_required");
196
+ const g = await rpc(T.node_normal, "tools/call", { name: "get_config_update", arguments: {} });
197
+ expect(JSON.parse(g.json.result.content[0].text).ok).toBe(true); // 协议工具默认不列,但照常能调
198
+ });
199
+ });
200
+
201
+ describe("bytes per role (#476 ceilings stay meaningful per role)", () => {
202
+ // 全部工具(= 改动前每个调用者拿到的)71–72 KB;改动后按角色。改数字时在 PR 里写为什么。
203
+ // 量出来(#478 合入时):全部 74 个工具 71,559 B;节点 52 个 57,632 B(−19%);人 56 个 54,780 B(−23%)。留 ~1.5 KB 余量。
204
+ // Board #625 adds 2 human tools + 2 hidden daemon protocol tools. Measured:
205
+ // all 78 / 73,969 B; user 58 / 56,615 B; node remains 52 / 58,320 B.
206
+ // Board #733 adds 7 node-only schedule_* tools (user list unchanged). Measured before → after on the same run:
207
+ // node 52 / 58,836 B → 59 / 61,607 B (+2,771 B, ~396 B per tool of which ~180 B is SDK per-tool overhead —
208
+ // $schema + execution — after trimming schemas to bare field names; values are validated server-side);
209
+ // all 78 / 74,485 B → 85 / 77,256 B; user 58 / 56,834 B → 58 / 56,834 B. main had 164 B node headroom left,
210
+ // so any new node tool needs this; ceilings keep the same ~400–750 B margin.
211
+ // Review follow-up: descriptions / schemas cut further → node 59 / 61,100 B, all 85 / 76,749 B (−507 B each),
212
+ // leaving ≥ 700 B node margin even with #2488 (+116 B) merged.
213
+ // Board #822 adds confirmed fork fields, not tools. Same-image main 102dd0f2 → candidate:
214
+ // all 87 / 77,646 B → 78,976 B (+1,330); node 61 / 61,986 B → 62,368 B (+382);
215
+ // user 58 / 56,950 B → 57,163 B (+213). start_node adds 213 B, report_status 169 B;
216
+ // hidden pull/ack schemas account for the remaining 948 B. Keep strict receipt validation
217
+ // and unchanged audiences; budget only this measured addition (~130/520 B node/all margin).
218
+ // Board #654 adds report_status adoption_candidates (node-only schema, no new tool).
219
+ // Same tree, field removed → restored: all 87 / 79,078 B → 79,591 B (+513);
220
+ // node 61 / 62,433 B → 62,946 B (+513); user 58 / 57,228 B unchanged
221
+ // (report_status is not on the user list). Budget only this measured addition
222
+ // (~154/509 B node/all margin).
223
+ // #906 plus Hub #938 clone_node (all 91 / 81,228 B; node 62 / 63,281 B;
224
+ // user 60 / 58,169 B). OpenCode V2 catalog adds 2 user tools and 2 protocol
225
+ // tools. Measured on this combined tree: all 95 / 85,069 B; node 62 / 63,281 B
226
+ // unchanged (protocol tools stay off the node list); user 62 / 59,409 B.
227
+ // Ceilings keep about 400 B and nothing else.
228
+ // #1894(2026-10-23):新增一个 `departments` MCP 工具(list/create/update/delete/
229
+ // assign_agent 合并成一个,尽量小)。实测 node 64,112 B / user 60,117 B,比原上限
230
+ // 分别高 412 / 279 B —— 这是有意的功能增长(组织架构可由 Agent 直接调),不是文案偷偷变长。
231
+ // 留约 400 B 余量;再要加工具时请先合并动作或砍描述,别连续抬上限。
232
+ // #2204(2026-10-25):标签管理给 MCP。为了**不抬上限**,做了两件事:
233
+ // ① 合并成一个工具 `requirement_tags`(action 分派 list/rename/merge/delete/color/reparent),
234
+ // 而不是 list + op 两个(照 #1894 `departments` 的先例);
235
+ // ② 砍掉一批冗长描述里重复的解释性从句(每条约 20–100 B,信息点全部保留)。
236
+ // 实测(含新工具):all 97 / 86,020 B;node 64 / 64,464 B;user 64 / 59,680 B —— 三个上限**一个都没动**。
237
+ // 下次再加工具,请先合并动作或砍描述,不要直接改这三个数。
238
+ //
239
+ // #3294(2026-10-31):report_status 新增 `build_commit`(节点侧的字节标识)。
240
+ // 第一次跑就撞上限:node 64,540 > 64,500(+40 B,全部来自那一句 describe)。
241
+ // 按上面那条规矩**不抬上限**,把描述从
242
+ // "Build commit (hex, 7–40), from the packaged build-info.json"(63 字符)
243
+ // 压到 "Build commit (hex)"(19 字符)⇒ node 64,497 B,余量 **3 B**。
244
+ // ⚠️ 3 B 不是「刚好」,是**陷阱**:下一个人加一个字段名就会撞墙,而这条测试的失败会
245
+ // 读成「谁又把描述写长了」。所以下面把余量打出来,余量低于 100 B 时大声说一句。
246
+ const CEILINGS = { node: 64_500, user: 60_500, all: 86_500 } as const;
247
+ const MARGIN_FLOOR = 100;
248
+ test("node / user / all", async () => {
249
+ const node = await listTools(T.node_normal);
250
+ const user = await listTools(T.owner);
251
+ const all = { bytes: Buffer.byteLength(JSON.stringify({ tools: ALL_TOOLS }), "utf8"), names: ALL_TOOLS.map(t => t.name) };
252
+ console.log(`tools/list bytes — all ${all.names.length} tools ${all.bytes} B; node ${node.names.length} tools ${node.bytes} B (−${Math.round(100 - node.bytes / all.bytes * 100)}%); user ${user.names.length} tools ${user.bytes} B (−${Math.round(100 - user.bytes / all.bytes * 100)}%)`);
253
+ expect(node.bytes).toBeLessThanOrEqual(CEILINGS.node);
254
+ expect(user.bytes).toBeLessThanOrEqual(CEILINGS.user);
255
+ expect(all.bytes).toBeLessThanOrEqual(CEILINGS.all);
256
+ // 余量也是读数:只报「没超」时,余量从 400 B 掉到 3 B 这件事是看不见的,
257
+ // 下一个人撞墙时才知道上限早就被吃干了。
258
+ const margins = { node: CEILINGS.node - node.bytes, user: CEILINGS.user - user.bytes, all: CEILINGS.all - all.bytes };
259
+ console.log(`margin B — node ${margins.node}; user ${margins.user}; all ${margins.all}`);
260
+ for (const [role, m] of Object.entries(margins)) {
261
+ if (m < MARGIN_FLOOR) {
262
+ console.log(`::warning::${role} 的 tools/list 余量只剩 ${m} B(< ${MARGIN_FLOOR})—— 下一次加字段会先撞这里,请先砍描述或合并动作`);
263
+ }
264
+ }
265
+ });
266
+ });