@qvac/core 0.4.1 → 0.6.0

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 (417) hide show
  1. package/CHANGELOG.md +262 -1
  2. package/README.md +1 -1
  3. package/dist-lib/lib/api/agents.js +3 -2
  4. package/dist-lib/lib/api/app-config.d.ts +1 -1
  5. package/dist-lib/lib/api/app-config.js +54 -15
  6. package/dist-lib/lib/api/attachments.d.ts +6 -5
  7. package/dist-lib/lib/api/attachments.js +4 -2
  8. package/dist-lib/lib/api/chat.d.ts +7 -3
  9. package/dist-lib/lib/api/chat.js +4 -4
  10. package/dist-lib/lib/api/chunks.js +3 -3
  11. package/dist-lib/lib/api/config.js +2 -2
  12. package/dist-lib/lib/api/current-mesh.d.ts +3 -4
  13. package/dist-lib/lib/api/current-mesh.js +9 -4
  14. package/dist-lib/lib/api/custom-models.d.ts +8 -1
  15. package/dist-lib/lib/api/custom-models.js +53 -16
  16. package/dist-lib/lib/api/devices.d.ts +14 -5
  17. package/dist-lib/lib/api/devices.js +14 -9
  18. package/dist-lib/lib/api/diagnostics.d.ts +1 -0
  19. package/dist-lib/lib/api/diagnostics.js +1 -1
  20. package/dist-lib/lib/api/effective-ctx-size.d.ts +6 -1
  21. package/dist-lib/lib/api/effective-ctx-size.js +5 -3
  22. package/dist-lib/lib/api/execution.js +9 -2
  23. package/dist-lib/lib/api/files.js +2 -1
  24. package/dist-lib/lib/api/index.d.ts +7 -1
  25. package/dist-lib/lib/api/index.js +101 -101
  26. package/dist-lib/lib/api/instrument.js +29 -20
  27. package/dist-lib/lib/api/knowledge.d.ts +6 -5
  28. package/dist-lib/lib/api/knowledge.js +8 -6
  29. package/dist-lib/lib/api/local-files.js +1 -1
  30. package/dist-lib/lib/api/logs.js +6 -3
  31. package/dist-lib/lib/api/members.js +22 -13
  32. package/dist-lib/lib/api/mesh.d.ts +7 -2
  33. package/dist-lib/lib/api/mesh.js +10 -5
  34. package/dist-lib/lib/api/model-download.js +1 -1
  35. package/dist-lib/lib/api/network.d.ts +1 -0
  36. package/dist-lib/lib/api/network.js +1 -1
  37. package/dist-lib/lib/api/notifications.js +23 -13
  38. package/dist-lib/lib/api/rag.d.ts +6 -1
  39. package/dist-lib/lib/api/rag.js +20 -11
  40. package/dist-lib/lib/api/range.d.ts +2 -2
  41. package/dist-lib/lib/api/sync.js +1 -1
  42. package/dist-lib/lib/api/tool-activity.js +7 -3
  43. package/dist-lib/lib/api/tool-configs.js +2 -4
  44. package/dist-lib/lib/api/upload-frames.d.ts +7 -8
  45. package/dist-lib/lib/api/upload-frames.js +2 -1
  46. package/dist-lib/lib/api/watchable.d.ts +6 -1
  47. package/dist-lib/lib/api/watchable.js +23 -14
  48. package/dist-lib/lib/assistant/fetch-body.js +4 -2
  49. package/dist-lib/lib/assistant/harness.d.ts +72 -24
  50. package/dist-lib/lib/assistant/harness.js +53 -15
  51. package/dist-lib/lib/assistant/history.d.ts +9 -7
  52. package/dist-lib/lib/assistant/history.js +77 -42
  53. package/dist-lib/lib/assistant/message.d.ts +5 -3
  54. package/dist-lib/lib/assistant/message.js +4 -2
  55. package/dist-lib/lib/assistant/skill-encode.d.ts +3 -1
  56. package/dist-lib/lib/assistant/skill-encode.js +52 -62
  57. package/dist-lib/lib/assistant-client.js +7 -4
  58. package/dist-lib/lib/assistant-tree.js +36 -11
  59. package/dist-lib/lib/assistant.d.ts +37 -12
  60. package/dist-lib/lib/assistant.js +977 -373
  61. package/dist-lib/lib/audio-format.d.ts +1 -1
  62. package/dist-lib/lib/audio-format.js +1 -1
  63. package/dist-lib/lib/chat-title.js +9 -4
  64. package/dist-lib/lib/client.js +3 -2
  65. package/dist-lib/lib/collabora/convert.d.ts +2 -2
  66. package/dist-lib/lib/collabora/convert.js +6 -3
  67. package/dist-lib/lib/collabora/entry.js +9 -5
  68. package/dist-lib/lib/collabora/protocol.d.ts +2 -2
  69. package/dist-lib/lib/collabora/protocol.js +14 -7
  70. package/dist-lib/lib/collabora/worker.js +14 -7
  71. package/dist-lib/lib/compaction.d.ts +5 -6
  72. package/dist-lib/lib/compaction.js +14 -7
  73. package/dist-lib/lib/constants.d.ts +2 -0
  74. package/dist-lib/lib/constants.js +4 -0
  75. package/dist-lib/lib/core/account-recovery.d.ts +4 -3
  76. package/dist-lib/lib/core/account-recovery.js +7 -4
  77. package/dist-lib/lib/core/agent.d.ts +0 -1
  78. package/dist-lib/lib/core/agent.js +18 -16
  79. package/dist-lib/lib/core/approval-rules.d.ts +7 -6
  80. package/dist-lib/lib/core/approval-rules.js +12 -6
  81. package/dist-lib/lib/core/archived-mesh.d.ts +7 -5
  82. package/dist-lib/lib/core/archived-mesh.js +25 -22
  83. package/dist-lib/lib/core/async-iterable.js +10 -5
  84. package/dist-lib/lib/core/attachment-link.d.ts +2 -2
  85. package/dist-lib/lib/core/audio-attachment.js +1 -1
  86. package/dist-lib/lib/core/blind-peers.d.ts +2 -2
  87. package/dist-lib/lib/core/chat-activity.d.ts +2 -2
  88. package/dist-lib/lib/core/chat-activity.js +42 -21
  89. package/dist-lib/lib/core/chat-group.d.ts +8 -6
  90. package/dist-lib/lib/core/chat-group.js +17 -10
  91. package/dist-lib/lib/core/chat-order.d.ts +11 -9
  92. package/dist-lib/lib/core/chat-order.js +1 -3
  93. package/dist-lib/lib/core/chat-search.d.ts +4 -4
  94. package/dist-lib/lib/core/chat-search.js +38 -24
  95. package/dist-lib/lib/core/chat.d.ts +20 -14
  96. package/dist-lib/lib/core/chat.js +42 -28
  97. package/dist-lib/lib/core/chunk.d.ts +20 -24
  98. package/dist-lib/lib/core/chunk.js +34 -22
  99. package/dist-lib/lib/core/collections.d.ts +69 -0
  100. package/dist-lib/lib/core/collections.js +69 -0
  101. package/dist-lib/lib/core/contract/activity.d.ts +8 -2
  102. package/dist-lib/lib/core/contract/activity.js +39 -11
  103. package/dist-lib/lib/core/contract/agents.js +3 -2
  104. package/dist-lib/lib/core/contract/approval-rules.js +1 -1
  105. package/dist-lib/lib/core/contract/attestations.js +1 -1
  106. package/dist-lib/lib/core/contract/chat-group.js +1 -1
  107. package/dist-lib/lib/core/contract/chat.js +1 -1
  108. package/dist-lib/lib/core/contract/chunks.js +16 -9
  109. package/dist-lib/lib/core/contract/compute.js +2 -1
  110. package/dist-lib/lib/core/contract/devices.js +10 -6
  111. package/dist-lib/lib/core/contract/grant-order.d.ts +5 -0
  112. package/dist-lib/lib/core/contract/grant-order.js +20 -0
  113. package/dist-lib/lib/core/contract/index.d.ts +1 -1
  114. package/dist-lib/lib/core/contract/index.js +27 -2
  115. package/dist-lib/lib/core/contract/indexing.js +3 -3
  116. package/dist-lib/lib/core/contract/invites.d.ts +16 -0
  117. package/dist-lib/lib/core/contract/invites.js +256 -0
  118. package/dist-lib/lib/core/contract/joined-meshes.js +22 -22
  119. package/dist-lib/lib/core/contract/knowledge.js +5 -5
  120. package/dist-lib/lib/core/contract/members.d.ts +15 -0
  121. package/dist-lib/lib/core/contract/members.js +116 -31
  122. package/dist-lib/lib/core/contract/mesh-kind.d.ts +6 -0
  123. package/dist-lib/lib/core/contract/mesh-kind.js +49 -0
  124. package/dist-lib/lib/core/contract/seal.js +1 -1
  125. package/dist-lib/lib/core/contract/seed-defaults.js +1 -3
  126. package/dist-lib/lib/core/contract/tool-activity.js +5 -5
  127. package/dist-lib/lib/core/contract/tool-configs.js +1 -2
  128. package/dist-lib/lib/core/contract/writers.d.ts +13 -0
  129. package/dist-lib/lib/core/contract/writers.js +181 -24
  130. package/dist-lib/lib/core/departures.js +16 -8
  131. package/dist-lib/lib/core/device-attestation.d.ts +5 -0
  132. package/dist-lib/lib/core/device-attestation.js +24 -0
  133. package/dist-lib/lib/core/device-invites.d.ts +2 -0
  134. package/dist-lib/lib/core/device-invites.js +29 -7
  135. package/dist-lib/lib/core/devices.d.ts +2 -1
  136. package/dist-lib/lib/core/devices.js +52 -2
  137. package/dist-lib/lib/core/document-attachment.d.ts +20 -11
  138. package/dist-lib/lib/core/document-attachment.js +10 -5
  139. package/dist-lib/lib/core/files/attachments.d.ts +2 -5
  140. package/dist-lib/lib/core/files/attachments.js +6 -3
  141. package/dist-lib/lib/core/files/index.d.ts +44 -52
  142. package/dist-lib/lib/core/files/index.js +142 -93
  143. package/dist-lib/lib/core/files/knowledge.d.ts +2 -5
  144. package/dist-lib/lib/core/files/local-index.js +9 -5
  145. package/dist-lib/lib/core/files/preview/image.d.ts +0 -1
  146. package/dist-lib/lib/core/files/preview/image.js +9 -6
  147. package/dist-lib/lib/core/files/preview/index.d.ts +8 -11
  148. package/dist-lib/lib/core/files/preview/index.js +20 -15
  149. package/dist-lib/lib/core/files/processing/claims.d.ts +6 -5
  150. package/dist-lib/lib/core/files/processing/claims.js +16 -8
  151. package/dist-lib/lib/core/files/processing/document.d.ts +21 -50
  152. package/dist-lib/lib/core/files/processing/index.d.ts +18 -13
  153. package/dist-lib/lib/core/files/processing/index.js +65 -37
  154. package/dist-lib/lib/core/files/processing/ownership.d.ts +8 -1
  155. package/dist-lib/lib/core/files/processing/ownership.js +1 -1
  156. package/dist-lib/lib/core/files/processing/protocol.d.ts +19 -19
  157. package/dist-lib/lib/core/files/processing/protocol.js +5 -5
  158. package/dist-lib/lib/core/files/processing/settle.d.ts +10 -7
  159. package/dist-lib/lib/core/files/processing/settle.js +22 -11
  160. package/dist-lib/lib/core/files/processing/source.js +14 -8
  161. package/dist-lib/lib/core/files/processing/state.d.ts +13 -11
  162. package/dist-lib/lib/core/files/processing/state.js +19 -12
  163. package/dist-lib/lib/core/files/rag/build.d.ts +2 -2
  164. package/dist-lib/lib/core/files/rag/build.js +2 -1
  165. package/dist-lib/lib/core/files/rag/document-types.d.ts +4 -6
  166. package/dist-lib/lib/core/files/rag/index.d.ts +10 -13
  167. package/dist-lib/lib/core/files/rag/index.js +3 -2
  168. package/dist-lib/lib/core/files/rag/load.d.ts +10 -9
  169. package/dist-lib/lib/core/files/rag/load.js +26 -13
  170. package/dist-lib/lib/core/files/rag/policy.js +2 -1
  171. package/dist-lib/lib/core/files/rag/produce.js +33 -19
  172. package/dist-lib/lib/core/files/rag/retrieval/full-text.d.ts +5 -3
  173. package/dist-lib/lib/core/files/rag/retrieval/full-text.js +30 -10
  174. package/dist-lib/lib/core/files/records/chunks.js +4 -2
  175. package/dist-lib/lib/core/files/records/knowledge.d.ts +10 -11
  176. package/dist-lib/lib/core/files/records/knowledge.js +9 -8
  177. package/dist-lib/lib/core/files/records/linkage.js +6 -3
  178. package/dist-lib/lib/core/files/records/output.d.ts +5 -4
  179. package/dist-lib/lib/core/files/records/output.js +8 -4
  180. package/dist-lib/lib/core/files/records/reclaim.js +41 -25
  181. package/dist-lib/lib/core/files/records/routing.d.ts +4 -6
  182. package/dist-lib/lib/core/files/records/routing.js +15 -8
  183. package/dist-lib/lib/core/files/records/source.d.ts +5 -4
  184. package/dist-lib/lib/core/files/records/source.js +20 -14
  185. package/dist-lib/lib/core/files/records/sweep.js +1 -3
  186. package/dist-lib/lib/core/files/store/blob.d.ts +10 -10
  187. package/dist-lib/lib/core/files/store/blob.js +25 -19
  188. package/dist-lib/lib/core/files/store/index.d.ts +1 -6
  189. package/dist-lib/lib/core/files/store/index.js +4 -4
  190. package/dist-lib/lib/core/files/store/inline.d.ts +2 -2
  191. package/dist-lib/lib/core/files/store/inline.js +6 -3
  192. package/dist-lib/lib/core/files/store/reference.d.ts +6 -9
  193. package/dist-lib/lib/core/files/store/reference.js +25 -17
  194. package/dist-lib/lib/core/files/store/server.d.ts +7 -6
  195. package/dist-lib/lib/core/files/store/server.js +22 -11
  196. package/dist-lib/lib/core/files/store/sweep.js +13 -7
  197. package/dist-lib/lib/core/files/upload-input.d.ts +4 -12
  198. package/dist-lib/lib/core/files/upload-input.js +10 -5
  199. package/dist-lib/lib/core/files/upload.d.ts +27 -24
  200. package/dist-lib/lib/core/files/upload.js +74 -51
  201. package/dist-lib/lib/core/fs-drives.js +4 -2
  202. package/dist-lib/lib/core/grant-expiry.d.ts +11 -0
  203. package/dist-lib/lib/core/grant-expiry.js +66 -0
  204. package/dist-lib/lib/core/handoff-channel.d.ts +2 -1
  205. package/dist-lib/lib/core/handoff-channel.js +36 -15
  206. package/dist-lib/lib/core/harness-loan.js +35 -17
  207. package/dist-lib/lib/core/helpers/index.d.ts +2 -1
  208. package/dist-lib/lib/core/helpers/index.js +11 -6
  209. package/dist-lib/lib/core/hosted-agents.js +19 -12
  210. package/dist-lib/lib/core/id.js +1 -1
  211. package/dist-lib/lib/core/identity.d.ts +1 -0
  212. package/dist-lib/lib/core/identity.js +11 -3
  213. package/dist-lib/lib/core/image/cache-sweep.d.ts +12 -10
  214. package/dist-lib/lib/core/image/cache-sweep.js +11 -6
  215. package/dist-lib/lib/core/image/normalize.d.ts +6 -0
  216. package/dist-lib/lib/core/image/normalize.js +12 -2
  217. package/dist-lib/lib/core/image/sniff.js +42 -21
  218. package/dist-lib/lib/core/inference-calls-receiver.js +7 -4
  219. package/dist-lib/lib/core/invite-grants.d.ts +20 -0
  220. package/dist-lib/lib/core/invite-grants.js +46 -0
  221. package/dist-lib/lib/core/invite.d.ts +3 -0
  222. package/dist-lib/lib/core/invite.js +6 -3
  223. package/dist-lib/lib/core/local/files.js +20 -19
  224. package/dist-lib/lib/core/local/index.d.ts +70 -45
  225. package/dist-lib/lib/core/local/index.js +157 -126
  226. package/dist-lib/lib/core/membership.d.ts +15 -2
  227. package/dist-lib/lib/core/membership.js +95 -20
  228. package/dist-lib/lib/core/mesh-seed-handoff.d.ts +12 -4
  229. package/dist-lib/lib/core/mesh-seed-handoff.js +23 -5
  230. package/dist-lib/lib/core/mesh.d.ts +57 -30
  231. package/dist-lib/lib/core/mesh.js +232 -78
  232. package/dist-lib/lib/core/migrations/agent-catalog.js +3 -2
  233. package/dist-lib/lib/core/migrations/agent-indexes.js +3 -3
  234. package/dist-lib/lib/core/migrations/device-indexes.d.ts +2 -0
  235. package/dist-lib/lib/core/migrations/device-indexes.js +7 -0
  236. package/dist-lib/lib/core/migrations/file-index.js +7 -4
  237. package/dist-lib/lib/core/migrations/index.d.ts +4 -3
  238. package/dist-lib/lib/core/migrations/index.js +3 -1
  239. package/dist-lib/lib/core/migrations/membership.js +9 -4
  240. package/dist-lib/lib/core/migrations/seal.js +3 -2
  241. package/dist-lib/lib/core/min-version.js +4 -2
  242. package/dist-lib/lib/core/next-frame.d.ts +5 -4
  243. package/dist-lib/lib/core/next-frame.js +6 -3
  244. package/dist-lib/lib/core/notification.d.ts +5 -1
  245. package/dist-lib/lib/core/notification.js +89 -77
  246. package/dist-lib/lib/core/ota-config.js +2 -1
  247. package/dist-lib/lib/core/pdf/rasterize.d.ts +18 -0
  248. package/dist-lib/lib/core/pdf/rasterize.js +57 -0
  249. package/dist-lib/lib/core/prompt-history.js +4 -2
  250. package/dist-lib/lib/core/range.d.ts +4 -4
  251. package/dist-lib/lib/core/range.js +12 -6
  252. package/dist-lib/lib/core/rank.d.ts +5 -4
  253. package/dist-lib/lib/core/rank.js +2 -1
  254. package/dist-lib/lib/core/send.d.ts +8 -5
  255. package/dist-lib/lib/core/send.js +9 -3
  256. package/dist-lib/lib/core/skill-overlay-receiver.js +7 -4
  257. package/dist-lib/lib/core/skill-secrets.js +16 -9
  258. package/dist-lib/lib/core/sync/chunks.js +2 -1
  259. package/dist-lib/lib/core/sync/devices.js +3 -1
  260. package/dist-lib/lib/core/sync/files.d.ts +2 -4
  261. package/dist-lib/lib/core/sync/files.js +28 -20
  262. package/dist-lib/lib/core/sync/index.d.ts +2 -5
  263. package/dist-lib/lib/core/sync/index.js +33 -17
  264. package/dist-lib/lib/core/sync-status.js +10 -7
  265. package/dist-lib/lib/core/system-info.js +4 -2
  266. package/dist-lib/lib/core/tool-activity.d.ts +4 -3
  267. package/dist-lib/lib/core/tool-activity.js +1 -1
  268. package/dist-lib/lib/core/tool-configs.js +12 -7
  269. package/dist-lib/lib/core.d.ts +107 -45
  270. package/dist-lib/lib/core.js +1765 -595
  271. package/dist-lib/lib/credential-pusher.d.ts +12 -17
  272. package/dist-lib/lib/credential-pusher.js +61 -42
  273. package/dist-lib/lib/custom-model-pusher.d.ts +7 -3
  274. package/dist-lib/lib/custom-model-pusher.js +15 -7
  275. package/dist-lib/lib/custom-model-task.d.ts +1 -0
  276. package/dist-lib/lib/custom-model-task.js +12 -0
  277. package/dist-lib/lib/deadline.js +4 -2
  278. package/dist-lib/lib/diagnostics.d.ts +1 -5
  279. package/dist-lib/lib/frame-readable.d.ts +3 -0
  280. package/dist-lib/lib/frame-readable.js +3 -0
  281. package/dist-lib/lib/fs-drive-bridge.js +24 -14
  282. package/dist-lib/lib/fs-grants.js +13 -8
  283. package/dist-lib/lib/guards.d.ts +3 -0
  284. package/dist-lib/lib/guards.js +9 -0
  285. package/dist-lib/lib/inference-calls.d.ts +28 -23
  286. package/dist-lib/lib/inference-calls.js +25 -13
  287. package/dist-lib/lib/integrations/mcp-providers.d.ts +2 -2
  288. package/dist-lib/lib/integrations/setup-routes.d.ts +2 -2
  289. package/dist-lib/lib/knowledge-search.d.ts +6 -5
  290. package/dist-lib/lib/knowledge-search.js +26 -18
  291. package/dist-lib/lib/kv-cache-reclaim.js +4 -2
  292. package/dist-lib/lib/kv-cache.js +8 -4
  293. package/dist-lib/lib/legacy-core-domain.d.ts +42 -42
  294. package/dist-lib/lib/log-buffer.js +2 -1
  295. package/dist-lib/lib/log.js +25 -15
  296. package/dist-lib/lib/mesh-scoped-engine.js +14 -4
  297. package/dist-lib/lib/model-catalog-revision.js +6 -3
  298. package/dist-lib/lib/model-clamp.js +6 -3
  299. package/dist-lib/lib/model-context.d.ts +8 -3
  300. package/dist-lib/lib/model-context.js +13 -5
  301. package/dist-lib/lib/model-download-status.js +4 -2
  302. package/dist-lib/lib/model-download.d.ts +12 -4
  303. package/dist-lib/lib/model-download.js +200 -103
  304. package/dist-lib/lib/model-idle-pusher.d.ts +10 -0
  305. package/dist-lib/lib/model-idle-pusher.js +41 -0
  306. package/dist-lib/lib/oauth/browser-connect.d.ts +10 -8
  307. package/dist-lib/lib/oauth/browser-connect.js +33 -20
  308. package/dist-lib/lib/oauth/client.d.ts +2 -2
  309. package/dist-lib/lib/oauth/flow-core.js +23 -9
  310. package/dist-lib/lib/oauth/flow.d.ts +1 -3
  311. package/dist-lib/lib/oauth/flow.js +9 -5
  312. package/dist-lib/lib/oauth/keys.d.ts +4 -4
  313. package/dist-lib/lib/oauth/keys.js +18 -12
  314. package/dist-lib/lib/oauth/loopback.d.ts +2 -2
  315. package/dist-lib/lib/oauth/loopback.js +147 -107
  316. package/dist-lib/lib/oauth/loopback.stub.d.ts +2 -2
  317. package/dist-lib/lib/oauth/loopback.stub.js +1 -1
  318. package/dist-lib/lib/oauth/pkce.d.ts +4 -2
  319. package/dist-lib/lib/oauth/pkce.js +10 -0
  320. package/dist-lib/lib/oauth/providers.js +5 -5
  321. package/dist-lib/lib/oauth/redirect-types.d.ts +12 -7
  322. package/dist-lib/lib/oauth/register.js +3 -2
  323. package/dist-lib/lib/oauth/registry.d.ts +2 -2
  324. package/dist-lib/lib/oauth/registry.js +2 -1
  325. package/dist-lib/lib/oauth/resolve.d.ts +30 -10
  326. package/dist-lib/lib/oauth/resolve.js +12 -6
  327. package/dist-lib/lib/oauth/token-exchange-core.d.ts +12 -4
  328. package/dist-lib/lib/oauth/token-exchange-core.js +1 -1
  329. package/dist-lib/lib/oauth/types.d.ts +12 -12
  330. package/dist-lib/lib/oauth.d.ts +4 -5
  331. package/dist-lib/lib/oauth.js +2 -3
  332. package/dist-lib/lib/reconnecting-watch.d.ts +1 -1
  333. package/dist-lib/lib/reconnecting-watch.js +6 -6
  334. package/dist-lib/lib/retry-budget.js +6 -3
  335. package/dist-lib/lib/run-notices.d.ts +2 -0
  336. package/dist-lib/lib/run-notices.js +7 -3
  337. package/dist-lib/lib/run-transcript.d.ts +2 -4
  338. package/dist-lib/lib/run-transcript.js +4 -2
  339. package/dist-lib/lib/skill-readiness.d.ts +1 -0
  340. package/dist-lib/lib/skill-readiness.js +17 -2
  341. package/dist-lib/lib/skill-types.d.ts +16 -16
  342. package/dist-lib/lib/suspend-lifecycle.d.ts +4 -4
  343. package/dist-lib/lib/suspend-lifecycle.js +10 -5
  344. package/dist-lib/lib/task.d.ts +5 -1
  345. package/dist-lib/lib/task.js +29 -12
  346. package/dist-lib/lib/unref.d.ts +3 -2
  347. package/dist-lib/lib/unref.js +2 -1
  348. package/dist-lib/lib/wav-duration.js +10 -5
  349. package/dist-lib/lib/write-queue.d.ts +5 -4
  350. package/dist-lib/lib/write-queue.js +2 -1
  351. package/dist-lib/schema/build.js +16 -8
  352. package/dist-lib/schema/config.d.ts +3 -4
  353. package/dist-lib/schema/config.js +1 -1
  354. package/dist-lib/schema/content.d.ts +18 -2
  355. package/dist-lib/schema/content.js +4 -1
  356. package/dist-lib/schema/engine.d.ts +3 -2
  357. package/dist-lib/schema/engine.js +192 -12
  358. package/dist-lib/schema/field-order.js +22 -11
  359. package/dist-lib/schema/indexes.d.ts +22 -0
  360. package/dist-lib/schema/{helpers.js → indexes.js} +19 -57
  361. package/dist-lib/schema/local.d.ts +3 -2
  362. package/dist-lib/schema/local.js +9 -3
  363. package/dist-lib/schema/media-kind.d.ts +8 -0
  364. package/dist-lib/schema/media-kind.js +52 -0
  365. package/dist-lib/schema/qvac.d.ts +12 -9
  366. package/dist-lib/schema/qvac.js +132 -7
  367. package/dist-lib/spec/bind.js +21 -0
  368. package/dist-lib/spec/calls.js +7 -0
  369. package/dist-lib/spec/capabilities.d.ts +18 -4
  370. package/dist-lib/spec/config/hyperconf/index.js +1 -1
  371. package/dist-lib/spec/hrpc/hrpc.json +93 -2
  372. package/dist-lib/spec/hrpc/index.js +89 -5
  373. package/dist-lib/spec/hrpc/messages.js +1568 -941
  374. package/dist-lib/spec/hyperschema/index.js +1568 -941
  375. package/dist-lib/spec/hyperschema/schema.json +531 -1
  376. package/dist-lib/spec/hyperschema/types.d.ts +145 -1
  377. package/dist-lib/spec/local/hyperdb/index.js +1 -1
  378. package/dist-lib/spec/local/hyperdb/messages.js +92 -20
  379. package/dist-lib/spec/local/hyperschema/index.js +47 -11
  380. package/dist-lib/spec/local/hyperschema/schema.json +32 -1
  381. package/dist-lib/spec/local/hyperschema/types.d.ts +7 -1
  382. package/dist-lib/spec/mesh/hyperdb/db.json +131 -3
  383. package/dist-lib/spec/mesh/hyperdb/index.js +548 -5
  384. package/dist-lib/spec/mesh/hyperdb/messages.js +2444 -893
  385. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +37 -1
  386. package/dist-lib/spec/mesh/hyperdispatch/index.js +104 -2
  387. package/dist-lib/spec/mesh/hyperdispatch/messages.js +1035 -11
  388. package/dist-lib/spec/mesh/hyperschema/index.js +1035 -11
  389. package/dist-lib/spec/mesh/hyperschema/schema.json +553 -1
  390. package/dist-lib/spec/mesh/hyperschema/types.d.ts +143 -1
  391. package/package.json +11 -5
  392. package/tui/app.mjs +2624 -986
  393. package/tui/boot.mjs +17 -46
  394. package/tui/index.mjs +10 -5
  395. package/tui/lib/boot-timing.mjs +8 -8
  396. package/tui/lib/busy-words.mjs +21 -22
  397. package/tui/lib/export.mjs +100 -32
  398. package/tui/lib/knowledge-command.mjs +64 -19
  399. package/tui/lib/knowledge-import.mjs +52 -18
  400. package/tui/lib/render.mjs +65 -33
  401. package/tui/lib/save-file.mjs +30 -13
  402. package/tui/lib/select.mjs +23 -5
  403. package/tui/lib/selection.mjs +6 -4
  404. package/tui/lib/setup.mjs +11 -19
  405. package/tui/lib/sidebar.mjs +23 -13
  406. package/tui/lib/splash.mjs +6 -7
  407. package/tui/lib/upload-frames.mjs +1 -2
  408. package/tui/lib/usage.mjs +13 -9
  409. package/tui/lib/wrap.mjs +35 -6
  410. package/tui/main.mjs +54 -78
  411. package/worker/assistant-sidecar.mjs +5 -10
  412. package/worker/stow-entry.mjs +7 -4
  413. package/dist-lib/lib/custom-model-source.d.ts +0 -15
  414. package/dist-lib/lib/custom-model-source.js +0 -46
  415. package/dist-lib/lib/oauth/common.d.ts +0 -38
  416. package/dist-lib/lib/oauth/common.js +0 -34
  417. package/dist-lib/schema/helpers.d.ts +0 -32
@@ -0,0 +1,10 @@
1
+ import type { Harness } from './assistant.ts';
2
+ import type { openLocalStore } from './core/local/index.ts';
3
+ type LocalStore = Awaited<ReturnType<typeof openLocalStore>>;
4
+ interface Logger {
5
+ warn(...args: unknown[]): void;
6
+ }
7
+ export type ModelIdleTarget = Pick<Harness, 'setModelIdleTimeout'>;
8
+ export type ModelIdleSource = Pick<LocalStore, 'get' | 'watch' | 'unwatch'>;
9
+ export declare function startModelIdlePusher(harness: ModelIdleTarget, state: ModelIdleSource, logger?: Logger | null): () => Promise<void>;
10
+ export {};
@@ -0,0 +1,41 @@
1
+ import ScopeLock from 'scope-lock';
2
+ import { MODEL_IDLE_UNLOAD_KEY, MODEL_IDLE_UNLOAD_MINUTES } from './constants.js';
3
+ import { errorMessage } from './guards.js';
4
+ export function startModelIdlePusher(harness, state, logger) {
5
+ const lock = new ScopeLock({ debounce: true });
6
+ let disposed = false;
7
+ let pushed = null;
8
+ const push = async () => {
9
+ const ms = idleUnloadMs(await state.get(MODEL_IDLE_UNLOAD_KEY));
10
+ if (disposed || ms === pushed) {
11
+ return;
12
+ }
13
+ await harness.setModelIdleTimeout?.(ms);
14
+ pushed = ms;
15
+ };
16
+ const schedule = async () => {
17
+ if (disposed || !(await lock.lock()))
18
+ return;
19
+ try {
20
+ await push();
21
+ }
22
+ catch (err) {
23
+ logger?.warn('model-idle-pusher', 'push failed', errorMessage(err));
24
+ }
25
+ finally {
26
+ lock.unlock();
27
+ }
28
+ };
29
+ const listener = () => void schedule();
30
+ state.watch(listener);
31
+ void schedule();
32
+ return async () => {
33
+ disposed = true;
34
+ state.unwatch(listener);
35
+ lock.destroy();
36
+ await lock.flush();
37
+ };
38
+ }
39
+ function idleUnloadMs(value) {
40
+ return typeof value === 'number' && MODEL_IDLE_UNLOAD_MINUTES.includes(value) ? value * 60_000 : 0;
41
+ }
@@ -1,8 +1,10 @@
1
- export declare function waitForOAuthCallback(opts: {
2
- port: number;
3
- state: string;
4
- timeoutMs?: number;
5
- onListening?: () => void;
6
- }): Promise<{
7
- code: string;
8
- }>;
1
+ export interface WaitForOAuthCallbackOptions {
2
+ readonly port: number;
3
+ readonly state: string;
4
+ readonly timeoutMs?: number;
5
+ readonly onListening?: () => void;
6
+ }
7
+ export interface OAuthCallbackCode {
8
+ readonly code: string;
9
+ }
10
+ export declare function waitForOAuthCallback(opts: WaitForOAuthCallbackOptions): Promise<OAuthCallbackCode>;
@@ -1,18 +1,19 @@
1
1
  import { createServer } from 'http';
2
2
  import { URL } from 'url';
3
- import { CALLBACK_PATH, DEFAULT_TIMEOUT_MS } from './common.js';
3
+ import { OAUTH_CALLBACK_PATH, OAUTH_WAIT_FOR_CODE_TIMEOUT_MS } from './keys.js';
4
4
  export function waitForOAuthCallback(opts) {
5
- const { port, state, timeoutMs = DEFAULT_TIMEOUT_MS, onListening } = opts;
5
+ const { port, state, timeoutMs = OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, onListening } = opts;
6
6
  return new Promise((resolve, reject) => {
7
7
  let settled = false;
8
- const respond = (res, status, body = '', close = false) => {
8
+ const respond = (res, status, { body = '', close = false } = {}) => {
9
9
  const headers = { 'Content-Type': 'text/html; charset=utf-8' };
10
- if (close)
10
+ if (close) {
11
11
  headers.Connection = 'close';
12
+ }
12
13
  res.writeHead(status, headers);
13
14
  res.end(body);
14
15
  };
15
- const settle = (err, result, res) => {
16
+ const settle = (outcome, res) => {
16
17
  if (settled)
17
18
  return;
18
19
  settled = true;
@@ -22,37 +23,49 @@ export function waitForOAuthCallback(opts) {
22
23
  server.closeAllConnections?.();
23
24
  };
24
25
  const socket = res?.socket;
25
- if (socket)
26
+ if (socket) {
26
27
  socket.once('close', close);
27
- else
28
+ }
29
+ else {
28
30
  close();
29
- if (err)
30
- reject(err);
31
- else
32
- resolve(result);
31
+ }
32
+ if ('error' in outcome) {
33
+ reject(outcome.error);
34
+ }
35
+ else {
36
+ resolve(outcome);
37
+ }
33
38
  };
34
39
  const server = createServer((req, res) => {
35
40
  const url = new URL(req.url ?? '/', `http://127.0.0.1:${port}`);
36
- if (url.pathname !== CALLBACK_PATH)
37
- return respond(res, 404, 'Not found');
38
- if (url.searchParams.get('state') !== state)
41
+ if (url.pathname !== OAUTH_CALLBACK_PATH) {
42
+ return respond(res, 404, { body: 'Not found' });
43
+ }
44
+ if (url.searchParams.get('state') !== state) {
39
45
  return respond(res, 204);
46
+ }
40
47
  const error = url.searchParams.get('error');
41
48
  const code = url.searchParams.get('code');
42
49
  if (error) {
43
- respond(res, 200, '<html><body><p>Authorization failed. You can close this tab.</p></body></html>', true);
44
- settle(new Error(`OAuth error: ${error}`), undefined, res);
50
+ respond(res, 200, {
51
+ body: '<html><body><p>Authorization failed. You can close this tab.</p></body></html>',
52
+ close: true
53
+ });
54
+ settle({ error: new Error(`OAuth error: ${error}`) }, res);
45
55
  }
46
56
  else if (code) {
47
- respond(res, 200, '<html><body><p>You can close this tab.</p></body></html>', true);
48
- settle(null, { code }, res);
57
+ respond(res, 200, {
58
+ body: '<html><body><p>You can close this tab.</p></body></html>',
59
+ close: true
60
+ });
61
+ settle({ code }, res);
49
62
  }
50
63
  else {
51
64
  respond(res, 204);
52
65
  }
53
66
  });
54
- const timer = setTimeout(() => settle(new Error('OAuth callback timed out')), timeoutMs);
55
- server.once('error', (err) => settle(err));
67
+ const timer = setTimeout(() => settle({ error: new Error('OAuth callback timed out') }), timeoutMs);
68
+ server.once('error', (err) => settle({ error: err }));
56
69
  server.listen(port, '127.0.0.1', () => onListening?.());
57
70
  });
58
71
  }
@@ -1,9 +1,9 @@
1
1
  import { type OAuthRuntimeFlowDeps } from './flow-core.ts';
2
2
  import { isTokenExpired } from './token-exchange-core.ts';
3
3
  import type { OAuthProviderConfig, OAuthRuntime, OAuthTokens } from './types.ts';
4
- export type OAuthClient = {
4
+ export interface OAuthClient {
5
5
  readonly runOAuthFlow: (config: OAuthProviderConfig, deps: OAuthRuntimeFlowDeps) => Promise<OAuthTokens>;
6
6
  readonly refreshOAuthTokens: (config: OAuthProviderConfig, refreshToken: string) => Promise<OAuthTokens>;
7
- };
7
+ }
8
8
  export declare function createOAuthClient(runtime: OAuthRuntime): OAuthClient;
9
9
  export { isTokenExpired };
@@ -1,9 +1,9 @@
1
1
  import { generateRuntimePkceChallenge } from './pkce-runtime.js';
2
2
  import { resolveDynamicClientId } from './register.js';
3
3
  import { exchangeCodeWithFetch } from './token-exchange-core.js';
4
- function buildAuthParams(config, clientId, redirectUri, state, pkce) {
4
+ function buildAuthParams(config, { clientId, redirectUri, state, pkce }) {
5
5
  const params = new URLSearchParams({
6
- ...(config.extraAuthParams ?? {}),
6
+ ...config.extraAuthParams,
7
7
  client_id: clientId,
8
8
  redirect_uri: redirectUri,
9
9
  response_type: 'code',
@@ -11,25 +11,39 @@ function buildAuthParams(config, clientId, redirectUri, state, pkce) {
11
11
  code_challenge: pkce.challenge,
12
12
  code_challenge_method: 'S256'
13
13
  });
14
- if (config.scopes.length > 0)
14
+ if (config.scopes.length > 0) {
15
15
  params.set('scope', config.scopes.join(' '));
16
+ }
16
17
  return params;
17
18
  }
18
19
  export async function runOAuthFlowWithRuntime(config, deps, runtime) {
19
20
  const openUrl = deps.openUrl ??
20
21
  (() => Promise.reject(new Error('OAuth browser launcher is unavailable; inject openUrl or createRedirect')));
21
- const redirect = await deps.createRedirect({ port: config.port, credentialKey: config.credentialKey }, { openUrl });
22
+ const pkce = await generateRuntimePkceChallenge(runtime);
23
+ const state = runtime.randomBase64Url(16);
24
+ const redirect = await deps.createRedirect({ port: config.port, credentialKey: config.credentialKey, state }, { openUrl });
22
25
  try {
23
26
  const clientId = config.dynamicRegistration && !config.clientId
24
27
  ? await resolveDynamicClientId(config, redirect.redirectUri, deps, runtime.fetch)
25
28
  : config.clientId;
26
- const pkce = await generateRuntimePkceChallenge(runtime);
27
- const state = runtime.randomBase64Url(16);
28
- const authParams = buildAuthParams(config, clientId, redirect.redirectUri, state, pkce);
29
+ const authParams = buildAuthParams(config, {
30
+ clientId,
31
+ redirectUri: redirect.redirectUri,
32
+ state,
33
+ pkce
34
+ });
29
35
  const callback = await redirect.authorize(`${config.authUrl}?${authParams.toString()}`, deps.timeoutMs, state);
30
- if (callback.state !== state)
36
+ if (callback.state !== state) {
31
37
  throw new Error('OAuth state mismatch (possible CSRF)');
32
- return exchangeCodeWithFetch(config, clientId, redirect.redirectUri, callback.code, pkce.verifier, deps, runtime.fetch);
38
+ }
39
+ return exchangeCodeWithFetch(config, {
40
+ clientId,
41
+ redirectUri: redirect.redirectUri,
42
+ code: callback.code,
43
+ verifier: pkce.verifier,
44
+ deps,
45
+ fetchImpl: runtime.fetch
46
+ });
33
47
  }
34
48
  finally {
35
49
  redirect.close();
@@ -1,5 +1,3 @@
1
1
  import type { OAuthFlowDeps, OAuthProviderConfig, OAuthTokens } from './types.ts';
2
- export declare function cancelOAuthFlow(target: {
3
- credentialKey: string;
4
- }): Promise<boolean>;
2
+ export declare function cancelOAuthFlow(target: Pick<OAuthProviderConfig, 'credentialKey'>): Promise<boolean>;
5
3
  export declare function runOAuthFlow(config: OAuthProviderConfig, deps?: OAuthFlowDeps): Promise<OAuthTokens>;
@@ -1,4 +1,4 @@
1
- import { abortOAuthLoopback, startOAuthLoopback } from '#oauth-loopback';
1
+ import { abortOAuthLoopback, openOAuthLoopback } from '#oauth-loopback';
2
2
  import { randomBase64Url, sha256Base64Url } from '@qvac/core/oauth/runtime/crypto';
3
3
  import defaultFetch from '@qvac/core/oauth/runtime/fetch';
4
4
  import { runOAuthFlowWithRuntime } from './flow-core.js';
@@ -6,12 +6,15 @@ export function cancelOAuthFlow(target) {
6
6
  return abortOAuthLoopback(target.credentialKey);
7
7
  }
8
8
  const loopbackRedirect = async (target, deps) => {
9
- const loopback = await startOAuthLoopback(target.port, target.credentialKey);
9
+ const loopback = await openOAuthLoopback(target.port, {
10
+ credentialKey: target.credentialKey,
11
+ state: target.state
12
+ });
10
13
  return {
11
14
  redirectUri: loopback.redirectUri,
12
- async authorize(authUrl, timeoutMs, expectedState) {
13
- const callback = loopback.waitForCode(timeoutMs, expectedState);
14
- callback.catch(() => undefined);
15
+ async authorize(authUrl, timeoutMs) {
16
+ const callback = loopback.waitForCode(timeoutMs);
17
+ callback.catch(noop);
15
18
  await deps.openUrl(authUrl);
16
19
  return callback;
17
20
  },
@@ -21,3 +24,4 @@ const loopbackRedirect = async (target, deps) => {
21
24
  export function runOAuthFlow(config, deps = {}) {
22
25
  return runOAuthFlowWithRuntime(config, { ...deps, createRedirect: deps.createRedirect ?? loopbackRedirect }, { fetch: defaultFetch, randomBase64Url, sha256Base64Url });
23
26
  }
27
+ function noop() { }
@@ -4,7 +4,7 @@ export type OAuthKeySpec = SkillOAuthConfig & {
4
4
  readonly credentialKey: string;
5
5
  readonly provider: string;
6
6
  };
7
- type OAuthConfigLike = {
7
+ interface OAuthConfigLike {
8
8
  readonly stateKey?: string | null | undefined;
9
9
  readonly authUrl?: string | null | undefined;
10
10
  readonly tokenUrl?: string | null | undefined;
@@ -14,12 +14,12 @@ type OAuthConfigLike = {
14
14
  readonly registrationEndpoint?: string | null | undefined;
15
15
  readonly port?: number | null | undefined;
16
16
  readonly sharedIosSession?: boolean | null | undefined;
17
- };
18
- export type OAuthRouteLike = {
17
+ }
18
+ export interface OAuthRouteLike {
19
19
  readonly credentialKey?: string | null | undefined;
20
20
  readonly provider?: string | null | undefined;
21
21
  readonly oauth?: OAuthConfigLike | null | undefined;
22
- };
22
+ }
23
23
  export declare function specFromRoute(route: OAuthRouteLike): OAuthKeySpec | null;
24
24
  export declare const OAUTH_CALLBACK_PATH = "/callback";
25
25
  export declare const OAUTH_WAIT_FOR_CODE_TIMEOUT_MS = 120000;
@@ -18,27 +18,33 @@ function httpsUrl(value) {
18
18
  function portOf(value) {
19
19
  if (value === undefined || value === null)
20
20
  return null;
21
- return Number.isInteger(value) && value >= 0 && value <= 65535
21
+ return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 65535
22
22
  ? value
23
23
  : null;
24
24
  }
25
25
  export function specFromRoute(route) {
26
26
  const oauth = route.oauth;
27
- if (!oauth)
27
+ if (!oauth) {
28
28
  return null;
29
+ }
29
30
  const tokenAuth = tokenAuthOf(oauth.tokenAuth);
30
31
  const authUrl = httpsUrl(oauth.authUrl);
31
32
  const tokenUrl = httpsUrl(oauth.tokenUrl);
32
- if (!route.credentialKey || !oauth.stateKey || !authUrl || !tokenUrl || !tokenAuth)
33
+ if (!route.credentialKey || !oauth.stateKey || !authUrl || !tokenUrl || !tokenAuth) {
33
34
  return null;
34
- if (oauth.stateKey === route.credentialKey)
35
+ }
36
+ if (oauth.stateKey === route.credentialKey) {
35
37
  return null;
36
- if (oauth.port !== undefined && oauth.port !== null && portOf(oauth.port) === null)
38
+ }
39
+ if (oauth.port !== undefined && oauth.port !== null && portOf(oauth.port) === null) {
37
40
  return null;
38
- if (oauth.registrationEndpoint && !httpsUrl(oauth.registrationEndpoint))
41
+ }
42
+ if (oauth.registrationEndpoint && !httpsUrl(oauth.registrationEndpoint)) {
39
43
  return null;
40
- if (oauth.registrationEndpoint && tokenAuth !== 'pkce-only')
44
+ }
45
+ if (oauth.registrationEndpoint && tokenAuth !== 'pkce-only') {
41
46
  return null;
47
+ }
42
48
  const extraParams = stringRecord(oauth.extraAuthParams);
43
49
  const port = portOf(oauth.port);
44
50
  return {
@@ -49,16 +55,16 @@ export function specFromRoute(route) {
49
55
  tokenUrl,
50
56
  tokenAuth,
51
57
  scopes: stringList(oauth.scopes),
52
- ...(extraParams ? { extraAuthParams: extraParams } : {}),
53
- ...(oauth.registrationEndpoint ? { registrationEndpoint: oauth.registrationEndpoint } : {}),
54
- ...(port !== null ? { port } : {}),
55
- ...(oauth.sharedIosSession === true ? { sharedIosSession: true } : {})
58
+ extraAuthParams: extraParams ?? undefined,
59
+ registrationEndpoint: oauth.registrationEndpoint || undefined,
60
+ port: port ?? undefined,
61
+ sharedIosSession: oauth.sharedIosSession === true || undefined
56
62
  };
57
63
  }
58
64
  function stringRecord(value) {
59
65
  if (!value || typeof value !== 'object' || Array.isArray(value))
60
66
  return null;
61
- const entries = Object.entries(value).filter(([, item]) => typeof item === 'string');
67
+ const entries = Object.entries(value).filter((entry) => typeof entry[1] === 'string');
62
68
  return entries.length > 0 ? Object.fromEntries(entries) : null;
63
69
  }
64
70
  function stringList(value) {
@@ -1,3 +1,3 @@
1
- import type { OAuthLoopbackServer } from './redirect-types.ts';
1
+ import type { OAuthLoopbackServer, OAuthLoopbackTarget } from './redirect-types.ts';
2
2
  export declare function abortOAuthLoopback(credentialKey: string): Promise<boolean>;
3
- export declare function startOAuthLoopback(port: number, credentialKey: string): Promise<OAuthLoopbackServer>;
3
+ export declare function openOAuthLoopback(port: number, target: OAuthLoopbackTarget): Promise<OAuthLoopbackServer>;
@@ -1,132 +1,172 @@
1
1
  import { createServer } from 'http';
2
2
  import { OAUTH_CALLBACK_PATH, OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, oauthRedirectUri } from './keys.js';
3
- const activeLoopbacks = new Set();
4
- function closeServer(server) {
5
- return new Promise((resolve) => {
6
- if (!server.listening) {
7
- resolve();
8
- return;
9
- }
10
- server.closeAllConnections?.();
11
- server.close(() => resolve());
12
- });
13
- }
14
- async function abortMatching(matches, reason) {
15
- await Promise.all(matches.map((handle) => handle.abort(reason)));
16
- return matches.length > 0;
3
+ const DONE_PAGE = '<html><body><p>Authorization complete. You may close this tab.</p>' +
4
+ '<script>window.close();</script></body></html>';
5
+ const STALE_PAGE = '<html><body><p>This sign-in link is from an earlier attempt. ' +
6
+ 'You can close this tab.</p></body></html>';
7
+ const loopbacks = new Set();
8
+ export async function abortOAuthLoopback(credentialKey) {
9
+ return abortFor(credentialKey, new Error('OAuth flow cancelled'));
17
10
  }
18
11
  function abortFor(credentialKey, reason) {
19
- return abortMatching([...activeLoopbacks].filter((handle) => handle.credentialKey === credentialKey), reason);
20
- }
21
- export function abortOAuthLoopback(credentialKey) {
22
- return abortFor(credentialKey, new Error('OAuth flow cancelled'));
12
+ const pending = [...loopbacks]
13
+ .flatMap((loopback) => [...loopback.waiters.values()])
14
+ .filter((waiter) => waiter.credentialKey === credentialKey && waiter.settled === null);
15
+ for (const waiter of pending) {
16
+ settle(waiter, { ok: false, error: reason });
17
+ }
18
+ return pending.length > 0;
23
19
  }
24
- export async function startOAuthLoopback(port, credentialKey) {
20
+ export async function openOAuthLoopback(port, target) {
25
21
  if (!Number.isInteger(port) || port < 0 || port > 65535) {
26
22
  throw new Error(`OAuth loopback port must be an integer in [0, 65535], got ${port}`);
27
23
  }
28
- await abortFor(credentialKey, new Error('OAuth loopback superseded by a new connect attempt'));
29
- if (port !== 0) {
30
- await abortMatching([...activeLoopbacks].filter((handle) => handle.port === port), new Error('OAuth loopback superseded by a new connect attempt on the same port'));
24
+ abortFor(target.credentialKey, new Error('OAuth loopback superseded by a new connect attempt'));
25
+ const loopback = acquire(port);
26
+ if (loopback.waiters.has(target.state)) {
27
+ throw new Error(`OAuth loopback on port ${port} already has a flow on state ${target.state}`);
28
+ }
29
+ const waiter = { credentialKey: target.credentialKey, deliver: null, settled: null };
30
+ loopback.waiters.set(target.state, waiter);
31
+ let bound;
32
+ try {
33
+ bound = await loopback.ready;
34
+ }
35
+ catch (error) {
36
+ release(loopback, target.state);
37
+ throw error;
31
38
  }
32
- let resolveCode = null;
33
- let rejectCode = null;
34
- let abortedReason = null;
35
- let expectedState = null;
36
- const rejectWaiter = (error) => {
37
- const reject = rejectCode;
38
- resolveCode = null;
39
- rejectCode = null;
40
- reject?.(error);
39
+ let released = false;
40
+ return {
41
+ redirectUri: oauthRedirectUri(bound.port),
42
+ waitForCode(timeoutMs = OAUTH_WAIT_FOR_CODE_TIMEOUT_MS) {
43
+ if (waiter.settled) {
44
+ return promiseFor(waiter.settled);
45
+ }
46
+ if (waiter.deliver) {
47
+ throw new Error('OAuth loopback is already waiting for this code');
48
+ }
49
+ return new Promise((resolve, reject) => {
50
+ const timer = globalThis.setTimeout(() => settle(waiter, { ok: false, error: new Error('OAuth callback timed out') }), timeoutMs);
51
+ waiter.deliver = (settlement) => {
52
+ globalThis.clearTimeout(timer);
53
+ if (settlement.ok) {
54
+ resolve(settlement.result);
55
+ }
56
+ else {
57
+ reject(settlement.error);
58
+ }
59
+ };
60
+ });
61
+ },
62
+ close() {
63
+ if (released)
64
+ return;
65
+ released = true;
66
+ settle(waiter, { ok: false, error: new Error('OAuth loopback closed') });
67
+ release(loopback, target.state);
68
+ }
41
69
  };
42
- const settle = (error, code, state) => {
43
- const resolve = resolveCode;
44
- const reject = rejectCode;
45
- resolveCode = null;
46
- rejectCode = null;
47
- if (error)
48
- reject?.(new Error(`OAuth error: ${error}`));
49
- else if (code && state)
50
- resolve?.({ code, state });
51
- else
52
- reject?.(new Error('OAuth callback missing code or state'));
70
+ }
71
+ function acquire(port) {
72
+ const existing = port === 0 ? undefined : [...loopbacks].find((l) => l.requestedPort === port);
73
+ if (existing && !existing.teardown) {
74
+ return existing;
75
+ }
76
+ const settled = existing?.teardown ?? Promise.resolve();
77
+ if (existing) {
78
+ loopbacks.delete(existing);
79
+ }
80
+ const waiters = new Map();
81
+ const loopback = {
82
+ requestedPort: port,
83
+ waiters,
84
+ ready: settled.then(() => listen(port, waiters)),
85
+ teardown: null
53
86
  };
54
- const server = createServer((request, response) => {
55
- const url = new URL(request.url ?? '/', 'http://127.0.0.1');
56
- if (url.pathname !== OAUTH_CALLBACK_PATH) {
57
- response.writeHead(404, { 'Content-Type': 'text/plain' });
58
- response.end('Not found');
59
- return;
60
- }
61
- const code = url.searchParams.get('code');
62
- const state = url.searchParams.get('state');
63
- const error = url.searchParams.get('error');
64
- if (expectedState !== null && state !== expectedState) {
65
- response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
66
- response.end('<html><body><p>This sign-in link is from an earlier attempt. ' +
67
- 'You can close this tab.</p></body></html>');
68
- return;
69
- }
70
- response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
71
- response.end('<html><body><p>Authorization complete. You may close this tab.</p>' +
72
- '<script>window.close();</script></body></html>');
73
- settle(error, code, state);
74
- response.on('close', () => server.close());
87
+ loopbacks.add(loopback);
88
+ return loopback;
89
+ }
90
+ function release(loopback, state) {
91
+ loopback.waiters.delete(state);
92
+ if (loopback.waiters.size > 0) {
93
+ return;
94
+ }
95
+ const teardown = loopback.ready.then(closeServer, () => undefined);
96
+ loopback.teardown = teardown;
97
+ teardown.then(() => loopbacks.delete(loopback));
98
+ }
99
+ function closeServer(bound) {
100
+ return new Promise((resolve) => {
101
+ bound.server.closeAllConnections?.();
102
+ bound.server.close(() => resolve());
75
103
  });
104
+ }
105
+ function listen(port, waiters) {
76
106
  return new Promise((resolve, reject) => {
77
- let listenSettled = false;
78
- const onError = (error) => {
79
- if (listenSettled)
107
+ const server = createServer((request, response) => {
108
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
109
+ if (url.pathname !== OAUTH_CALLBACK_PATH) {
110
+ respond(response, 404, { contentType: 'text/plain', body: 'Not found' });
80
111
  return;
81
- listenSettled = true;
82
- server.removeListener('listening', onListening);
83
- reject(error.code === 'EADDRINUSE'
112
+ }
113
+ const state = url.searchParams.get('state');
114
+ if (state === null) {
115
+ respond(response, 200, { contentType: 'text/html; charset=utf-8', body: STALE_PAGE });
116
+ return;
117
+ }
118
+ const waiter = waiters.get(state);
119
+ if (!waiter || waiter.settled) {
120
+ respond(response, 200, { contentType: 'text/html; charset=utf-8', body: STALE_PAGE });
121
+ return;
122
+ }
123
+ respond(response, 200, { contentType: 'text/html; charset=utf-8', body: DONE_PAGE });
124
+ settle(waiter, callbackSettlement(url.searchParams, state));
125
+ });
126
+ let listening = false;
127
+ server.on('error', (error) => {
128
+ if (listening)
129
+ return;
130
+ reject('code' in error && error.code === 'EADDRINUSE'
84
131
  ? new Error(`OAuth loopback port ${port} is already in use by another process`)
85
132
  : error);
86
- };
87
- const onListening = () => {
88
- if (listenSettled)
89
- return;
90
- listenSettled = true;
91
- server.removeListener('error', onError);
133
+ });
134
+ server.once('listening', () => {
135
+ listening = true;
92
136
  const address = server.address();
93
137
  if (typeof address !== 'object' || !address) {
94
138
  server.close();
95
139
  reject(new Error('OAuth loopback bound to no address'));
96
140
  return;
97
141
  }
98
- const handle = {
99
- credentialKey,
100
- port: address.port,
101
- abort: (reason) => {
102
- abortedReason = reason;
103
- rejectWaiter(reason);
104
- return closeServer(server);
105
- }
106
- };
107
- activeLoopbacks.add(handle);
108
- server.once('close', () => activeLoopbacks.delete(handle));
109
- resolve({
110
- redirectUri: oauthRedirectUri(address.port),
111
- waitForCode(timeoutMs = OAUTH_WAIT_FOR_CODE_TIMEOUT_MS, expected) {
112
- if (abortedReason)
113
- throw abortedReason;
114
- expectedState = expected ?? null;
115
- return new Promise((resolveWait, rejectWait) => {
116
- resolveCode = resolveWait;
117
- rejectCode = rejectWait;
118
- const timeout = globalThis.setTimeout(() => {
119
- server.close();
120
- rejectWait(new Error('OAuth callback timed out'));
121
- }, timeoutMs);
122
- server.once('close', () => globalThis.clearTimeout(timeout));
123
- });
124
- },
125
- close: () => server.close()
126
- });
127
- };
128
- server.once('error', onError);
129
- server.once('listening', onListening);
142
+ resolve({ server, port: address.port });
143
+ });
130
144
  server.listen(port, '127.0.0.1');
131
145
  });
132
146
  }
147
+ function callbackSettlement(params, state) {
148
+ const error = params.get('error');
149
+ if (error) {
150
+ return { ok: false, error: new Error(`OAuth error: ${error}`) };
151
+ }
152
+ const code = params.get('code');
153
+ if (!code) {
154
+ return { ok: false, error: new Error('OAuth callback missing code') };
155
+ }
156
+ return { ok: true, result: { code, state } };
157
+ }
158
+ function settle(waiter, settlement) {
159
+ if (waiter.settled)
160
+ return;
161
+ waiter.settled = settlement;
162
+ const deliver = waiter.deliver;
163
+ waiter.deliver = null;
164
+ deliver?.(settlement);
165
+ }
166
+ function promiseFor(settlement) {
167
+ return settlement.ok ? Promise.resolve(settlement.result) : Promise.reject(settlement.error);
168
+ }
169
+ function respond(response, status, { contentType, body }) {
170
+ response.writeHead(status, { 'Content-Type': contentType, Connection: 'close' });
171
+ response.end(body);
172
+ }