@aiworker/web 1.22.2 → 1.23.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/bin/cli.js +7 -0
  2. package/dist/assets/{CodeMirrorCommentWidgets-CSICpWQD.js → CodeMirrorCommentWidgets-teB3HmBT.js} +1 -1
  3. package/dist/assets/DiffView-DC9RX3MF.js +4 -0
  4. package/dist/assets/{DirtyBranchSwitchDialog-C22HdWj4.js → DirtyBranchSwitchDialog-DwPkzXsS.js} +1 -1
  5. package/dist/assets/FilesView-BFZkuu4O.js +13 -0
  6. package/dist/assets/{GitView-VQQkYuUw.js → GitView-B_x52MHY.js} +4 -4
  7. package/dist/assets/{JsonTreeView-6lrhwD3q.js → JsonTreeView-cmAzUTiw.js} +1 -1
  8. package/dist/assets/{LinearIssuesView-Ba6Q9569.js → LinearIssuesView-Dehh5afm.js} +1 -1
  9. package/dist/assets/MarkdownImageGallery-DgNOqqhE.js +1 -0
  10. package/dist/assets/MarkdownRendererImpl-DusmMZ_p.js +12 -0
  11. package/dist/assets/OnboardingScreen-B8fm1H4m.js +1 -0
  12. package/dist/assets/{PatchDiff-BzcZPlOq.js → PatchDiff-BVr7gJU0.js} +1 -1
  13. package/dist/assets/PierreDiffViewer-DzLt-nel.js +161 -0
  14. package/dist/assets/PlanView-BmQUYT_z.js +5 -0
  15. package/dist/assets/SettingsView-ChWmAcZT.js +28 -0
  16. package/dist/assets/{SettingsWindow-DDQYaKWQ.js → SettingsWindow-Dy3M6ZB9.js} +1 -1
  17. package/dist/assets/SymbolsNerdFontMono-Regular-aK5vsLov.woff2 +0 -0
  18. package/dist/assets/{ToolOutputDialog-iYF8Y2bz.js → ToolOutputDialog-cTl_eLIH.js} +5 -5
  19. package/dist/assets/{ToolPartDiffPreview-CdjbOVMM.js → ToolPartDiffPreview-C_3iYNJQ.js} +1 -1
  20. package/dist/assets/{VirtualizedFileDiff-fFFm2QgH.js → VirtualizedFileDiff-CAWthkoy.js} +4 -4
  21. package/dist/assets/WalkthroughView-C7AHOpCA.js +4 -0
  22. package/dist/assets/{computeVirtualFileMetrics-CzgLum_K.js → computeVirtualFileMetrics-BkiDSlTW.js} +2 -2
  23. package/dist/assets/contextPanelEmbeddedChat-BdA6bdky.js +1 -0
  24. package/dist/assets/de-DJsQr-p7.js +10 -0
  25. package/dist/assets/es-BuYMlA9g.js +16 -0
  26. package/dist/assets/fr-ePDay33C.js +14 -0
  27. package/dist/assets/ghostty-vt-DdA0Zryv.wasm +0 -0
  28. package/dist/assets/index-BD8ILbxF.js +40 -0
  29. package/dist/assets/{index-Bl3LSbjn.js → index-n6O3hklM.js} +1 -1
  30. package/dist/assets/index-zhgg-SDz.css +1 -0
  31. package/dist/assets/{isDiffPlainText-Dx-dB_8l.js → isDiffPlainText-GMdPz-71.js} +1 -1
  32. package/dist/assets/{isFilePlainText-CWFPwmnU.js → isFilePlainText-BVuH1zH9.js} +1 -1
  33. package/dist/assets/ja-BzR9xOY_.js +16 -0
  34. package/dist/assets/ko-BEjHAm14.js +16 -0
  35. package/dist/assets/main-BydQ1tr_.js +930 -0
  36. package/dist/assets/{main-DnBAoktx.js → main-D3ZDQglc.js} +2 -2
  37. package/dist/assets/markdownCore-Cb2MdZnV.js +5 -0
  38. package/dist/assets/{miniChat-BKyvLseN.js → miniChat-d01k801U.js} +2 -2
  39. package/dist/assets/{mobile-DKjeFgMN.js → mobile-D7VV-Ufz.js} +2 -2
  40. package/dist/assets/patchFileDiff-CdztVMz0.js +13 -0
  41. package/dist/assets/pl-rQmpxNIF.js +16 -0
  42. package/dist/assets/pt-BR-CorbsSW-.js +16 -0
  43. package/dist/assets/renderElectronMiniChatApp-BGG9UIlh.js +2 -0
  44. package/dist/assets/renderMobileApp-BRP3J1iv.js +25 -0
  45. package/dist/assets/runtimeEndpointReset-BhT_-c52.js +41 -0
  46. package/dist/assets/scheduledTasksApi-BEuUF_cj.js +1 -0
  47. package/dist/assets/{shikiHighlight-TEQCmzW8.js → shikiHighlight-BzXUjlby.js} +1 -1
  48. package/dist/assets/surface-COKb77Ua.js +1 -0
  49. package/dist/assets/tr-CoAMXPtI.js +7 -0
  50. package/dist/assets/uk-YlAX0rRU.js +16 -0
  51. package/dist/assets/{useAppFontEffects-D7sNpuL2.js → useAppFontEffects-Cwyhjfl5.js} +141 -140
  52. package/dist/assets/useGitComparison-BCZVefdE.js +1 -0
  53. package/dist/assets/useInlineCommentController-DDkpBEU8.js +2 -0
  54. package/dist/assets/useRootScrollLock-CwjoWuC4.js +1 -0
  55. package/dist/assets/{vendor-base-ui-BeMD8X_w.js → vendor-base-ui-BY_5qla_.js} +1 -1
  56. package/dist/assets/{vendor-codemirror-language-data-Dp3KMRQG.js → vendor-codemirror-language-data-Cb1YnICj.js} +2 -2
  57. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  58. package/dist/assets/vendor-zod-B6551dwG.js +39 -0
  59. package/dist/assets/{web-components-_mNEMjFY.js → web-components-LV3vjTxy.js} +1 -1
  60. package/dist/assets/zh-CN-DDYg0Jl7.js +16 -0
  61. package/dist/assets/zh-TW-CQKaCayr.js +16 -0
  62. package/dist/index.html +5 -43
  63. package/dist/mini-chat.html +4 -4
  64. package/dist/mobile.html +4 -4
  65. package/package.json +2 -3
  66. package/server/index.d.ts +15 -0
  67. package/server/index.js +48 -22
  68. package/server/lib/agent-memory/runtime.js +7 -2
  69. package/server/lib/agent-memory/runtime.test.js +22 -0
  70. package/server/lib/data-dir-migration.js +40 -0
  71. package/server/lib/data-dir-migration.test.js +59 -0
  72. package/server/lib/event-stream/DOCUMENTATION.md +3 -0
  73. package/server/lib/event-stream/global-hub.js +29 -4
  74. package/server/lib/event-stream/global-hub.test.js +22 -0
  75. package/server/lib/event-stream/global-ws-bridge.js +15 -18
  76. package/server/lib/event-stream/protocol.js +21 -7
  77. package/server/lib/event-stream/runtime.js +9 -6
  78. package/server/lib/event-stream/runtime.test.js +72 -12
  79. package/server/lib/fs/DOCUMENTATION.md +3 -0
  80. package/server/lib/fs/routes.js +31 -0
  81. package/server/lib/fs/routes.test.js +110 -1
  82. package/server/lib/git/DOCUMENTATION.md +39 -6
  83. package/server/lib/git/routes.js +45 -12
  84. package/server/lib/git/routes.test.js +78 -0
  85. package/server/lib/git/service.js +343 -202
  86. package/server/lib/git/service.test.js +496 -25
  87. package/server/lib/github/DOCUMENTATION.md +5 -0
  88. package/server/lib/github/routes.js +2 -2
  89. package/server/lib/inherited-env.js +16 -9
  90. package/server/lib/inherited-env.test.js +8 -9
  91. package/server/lib/message-queue/DOCUMENTATION.md +11 -1
  92. package/server/lib/message-queue/runtime.js +13 -0
  93. package/server/lib/message-queue/runtime.test.js +31 -1
  94. package/server/lib/network-defaults.js +23 -0
  95. package/server/lib/network-defaults.test.js +52 -0
  96. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  97. package/server/lib/notifications/emitter-runtime.js +4 -3
  98. package/server/lib/opencode/DOCUMENTATION.md +35 -5
  99. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  100. package/server/lib/opencode/env-runtime.js +5 -1
  101. package/server/lib/opencode/env-runtime.test.js +72 -0
  102. package/server/lib/opencode/feature-routes-runtime.js +17 -1
  103. package/server/lib/opencode/lifecycle.js +4 -3
  104. package/server/lib/opencode/lifecycle.test.js +29 -0
  105. package/server/lib/opencode/managed-plugin-config.js +1 -1
  106. package/server/lib/opencode/openchamber-routes.js +64 -4
  107. package/server/lib/opencode/openchamber-routes.test.js +128 -1
  108. package/server/lib/opencode/proxy.js +33 -0
  109. package/server/lib/opencode/routes.js +5 -3
  110. package/server/lib/opencode/settings-files.js +214 -0
  111. package/server/lib/opencode/settings-helpers.js +88 -41
  112. package/server/lib/opencode/settings-helpers.test.js +176 -1
  113. package/server/lib/opencode/settings-registry.json +750 -0
  114. package/server/lib/opencode/settings-runtime.js +175 -27
  115. package/server/lib/opencode/settings-runtime.test.js +321 -7
  116. package/server/lib/project-context/DOCUMENTATION.md +38 -4
  117. package/server/lib/project-context/routes.http.test.js +18 -0
  118. package/server/lib/project-context/routes.js +15 -0
  119. package/server/lib/project-context/runtime.js +256 -25
  120. package/server/lib/project-context/runtime.test.js +160 -3
  121. package/server/lib/projects/DOCUMENTATION.md +77 -0
  122. package/server/lib/projects/project-config.js +179 -17
  123. package/server/lib/projects/project-config.test.js +97 -0
  124. package/server/lib/projects/project-id.js +43 -0
  125. package/server/lib/projects/project-setup.js +409 -0
  126. package/server/lib/projects/project-setup.test.js +557 -0
  127. package/server/lib/projects/routes.js +59 -0
  128. package/server/lib/quota/DOCUMENTATION.md +31 -1
  129. package/server/lib/quota/providers/cline-pass.js +125 -0
  130. package/server/lib/quota/providers/cline-pass.test.js +103 -0
  131. package/server/lib/quota/providers/index.js +7 -0
  132. package/server/lib/quota/providers/neuralwatt.js +3 -6
  133. package/server/lib/quota/providers/neuralwatt.test.js +7 -7
  134. package/server/lib/quota/providers/ollama-cloud.js +31 -0
  135. package/server/lib/quota/providers/ollama-cloud.test.js +33 -1
  136. package/server/lib/quota/providers/opencode-go.js +1 -1
  137. package/server/lib/quota/providers/opencode-go.test.js +26 -1
  138. package/server/lib/quota/providers/openrouter.js +119 -24
  139. package/server/lib/quota/providers/openrouter.test.js +330 -0
  140. package/server/lib/relay/DOCUMENTATION.md +75 -0
  141. package/server/lib/relay/cross-compat.test.js +26 -0
  142. package/server/lib/relay/downstream-scheduler.js +154 -0
  143. package/server/lib/relay/downstream-scheduler.test.js +162 -0
  144. package/server/lib/relay/e2ee.js +10 -8
  145. package/server/lib/relay/flow-control.test.js +177 -0
  146. package/server/lib/relay/host-client.js +44 -8
  147. package/server/lib/relay/host-client.test.js +14 -0
  148. package/server/lib/relay/tunnel-codec.js +9 -0
  149. package/server/lib/relay/tunnel-host.js +66 -17
  150. package/server/lib/scheduled-tasks/DOCUMENTATION.md +9 -1
  151. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +28 -0
  152. package/server/lib/scheduled-tasks/runtime.js +12 -2
  153. package/server/lib/scheduled-tasks/runtime.test.js +53 -0
  154. package/server/lib/session-assist/DOCUMENTATION.md +131 -66
  155. package/server/lib/session-assist/context.js +127 -0
  156. package/server/lib/session-assist/context.test.js +132 -0
  157. package/server/lib/session-assist/prompt.js +54 -0
  158. package/server/lib/session-assist/runtime.js +117 -267
  159. package/server/lib/session-assist/runtime.test.js +203 -0
  160. package/server/lib/session-goal/runtime.js +4 -9
  161. package/server/lib/small-model/DOCUMENTATION.md +3 -2
  162. package/server/lib/small-model/call.js +9 -4
  163. package/server/lib/small-model/call.test.js +29 -0
  164. package/server/lib/small-model/index.js +5 -10
  165. package/server/lib/small-model/runtime-providers.js +15 -7
  166. package/server/lib/small-model/runtime-providers.test.js +7 -1
  167. package/server/lib/terminal/DOCUMENTATION.md +4 -4
  168. package/server/lib/terminal/runtime.js +11 -6
  169. package/server/lib/terminal/runtime.test.js +20 -13
  170. package/server/lib/walkthrough/DOCUMENTATION.md +49 -20
  171. package/server/lib/walkthrough/model-settings.js +8 -12
  172. package/server/lib/walkthrough/pr-source.test.js +21 -0
  173. package/server/lib/walkthrough/prompt.js +3 -1
  174. package/server/lib/walkthrough/pull-request.js +7 -4
  175. package/server/lib/walkthrough/pull-request.test.js +16 -0
  176. package/server/lib/walkthrough/routes.js +19 -0
  177. package/server/lib/walkthrough/routes.test.js +26 -0
  178. package/server/lib/walkthrough/sources.js +36 -4
  179. package/server/opencode-worktree-readiness.test.js +130 -0
  180. package/dist/assets/DiffView-hDBKesA_.js +0 -4
  181. package/dist/assets/FilesView-CdWzeOp9.js +0 -17
  182. package/dist/assets/MarkdownImageGallery-Czv_mhvS.js +0 -1
  183. package/dist/assets/MarkdownRendererImpl-BrMcswiy.js +0 -12
  184. package/dist/assets/OnboardingScreen-ChxQoAkx.js +0 -1
  185. package/dist/assets/PierreDiffViewer-BchBtZlp.js +0 -157
  186. package/dist/assets/PlanView-DyDt_nZ_.js +0 -5
  187. package/dist/assets/SettingsView-BKf5xBsP.js +0 -28
  188. package/dist/assets/WalkthroughView-DOeCsMju.js +0 -4
  189. package/dist/assets/contextPanelEmbeddedChat-C0ZLAepL.js +0 -1
  190. package/dist/assets/de-B5JaA3SA.js +0 -10
  191. package/dist/assets/es-EPIH88ii.js +0 -16
  192. package/dist/assets/fr-CAMfxUdZ.js +0 -14
  193. package/dist/assets/index-DF5kMP-i.js +0 -39
  194. package/dist/assets/index-Dl3xbAB_.css +0 -1
  195. package/dist/assets/ja-CifOE1VN.js +0 -16
  196. package/dist/assets/ko-BBDyAyYQ.js +0 -16
  197. package/dist/assets/main-MhSaOZoB.js +0 -930
  198. package/dist/assets/markdownCore-BrBwOOMn.js +0 -3
  199. package/dist/assets/patchFileDiff-o8ms1me8.js +0 -10
  200. package/dist/assets/pl-DgEHYfFM.js +0 -16
  201. package/dist/assets/pt-BR-DuWHojUw.js +0 -16
  202. package/dist/assets/renderElectronMiniChatApp-CDgBwwCS.js +0 -2
  203. package/dist/assets/renderMobileApp-DJIKIK1r.js +0 -25
  204. package/dist/assets/runtimeEndpointReset-CYJ9O_xX.js +0 -17
  205. package/dist/assets/scheduledTasksApi-D8yamh1b.js +0 -1
  206. package/dist/assets/tr-D5m2yIWL.js +0 -7
  207. package/dist/assets/uk-D_q60oog.js +0 -16
  208. package/dist/assets/useInlineCommentController-Brz_cLcQ.js +0 -2
  209. package/dist/assets/useRootScrollLock-lXEnWlaU.js +0 -1
  210. package/dist/assets/vendor-ghostty-web-CrxinGGH.js +0 -13
  211. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  212. package/dist/assets/vendor-zod-CK21ihK-.js +0 -39
  213. package/dist/assets/zh-CN-D8QvsVeg.js +0 -16
  214. package/dist/assets/zh-TW-B9t7rQQO.js +0 -16
  215. package/server/lib/mcp-reconnect/DOCUMENTATION.md +0 -55
  216. package/server/lib/mcp-reconnect/runtime.js +0 -122
  217. package/server/lib/mcp-reconnect/runtime.test.js +0 -140
@@ -5,12 +5,30 @@ import {
5
5
  buildResult,
6
6
  toUsageWindow,
7
7
  toNumber,
8
+ asObject,
8
9
  formatMoney
9
10
  } from '../utils/index.js';
10
11
 
11
12
  export const providerId = 'openrouter';
12
13
  export const providerName = 'OpenRouter';
13
- const aliases = ['openrouter'];
14
+ export const aliases = ['openrouter'];
15
+ const OPENROUTER_QUOTA_URL = 'https://openrouter.ai/api/v1/key';
16
+ const PERIOD_SECONDS = { daily: 86400, weekly: 604800, monthly: 30 * 86400 };
17
+
18
+ export const resolveResetAt = (limitReset, nowMs) => {
19
+ const now = new Date(nowMs);
20
+ const y = now.getUTCFullYear();
21
+ const m = now.getUTCMonth();
22
+ const d = now.getUTCDate();
23
+
24
+ if (limitReset === 'daily') return Date.UTC(y, m, d + 1);
25
+ if (limitReset === 'weekly') {
26
+ const dow = now.getUTCDay();
27
+ return Date.UTC(y, m, d + ((8 - dow) % 7 || 7));
28
+ }
29
+ if (limitReset === 'monthly') return Date.UTC(y, m + 1, 1);
30
+ return null;
31
+ };
14
32
 
15
33
  export const isConfigured = () => {
16
34
  const auth = readAuthFile();
@@ -33,13 +51,16 @@ export const fetchQuota = async () => {
33
51
  });
34
52
  }
35
53
 
54
+ const timeoutSignal = AbortSignal.timeout(15_000);
55
+
36
56
  try {
37
- const response = await fetch('https://openrouter.ai/api/v1/credits', {
57
+ const response = await fetch(OPENROUTER_QUOTA_URL, {
38
58
  method: 'GET',
39
59
  headers: {
40
60
  Authorization: `Bearer ${apiKey}`,
41
- 'Content-Type': 'application/json'
42
- }
61
+ 'Accept-Encoding': 'identity'
62
+ },
63
+ signal: timeoutSignal
43
64
  });
44
65
 
45
66
  if (!response.ok) {
@@ -48,45 +69,119 @@ export const fetchQuota = async () => {
48
69
  providerName,
49
70
  ok: false,
50
71
  configured: true,
51
- error: `API error: ${response.status}`
72
+ error: response.status === 401 || response.status === 403
73
+ ? 'Session expired — please re-authenticate with OpenRouter'
74
+ : `API error: ${response.status}`
52
75
  });
53
76
  }
54
77
 
55
78
  const payload = await response.json();
56
- const credits = payload?.data ?? {};
57
- const totalCredits = toNumber(credits.total_credits);
58
- const totalUsage = toNumber(credits.total_usage);
59
- const remaining = totalCredits !== null && totalUsage !== null
60
- ? Math.max(0, totalCredits - totalUsage)
61
- : null;
62
- let valueLabel = null;
63
- if (remaining !== null && totalUsage !== null) {
64
- valueLabel = `$${formatMoney(remaining)} left · $${formatMoney(totalUsage)} spent`;
79
+ const data = asObject(payload?.data);
80
+
81
+ if (data === null) {
82
+ return buildResult({
83
+ providerId,
84
+ providerName,
85
+ ok: false,
86
+ configured: true,
87
+ error: 'No quota data in response'
88
+ });
89
+ }
90
+
91
+ if (data.is_management_key === true) {
92
+ return buildResult({
93
+ providerId,
94
+ providerName,
95
+ ok: false,
96
+ configured: true,
97
+ error: 'Management key configured — quota needs an inference API key'
98
+ });
65
99
  }
66
100
 
67
- const windows = {
68
- credits: toUsageWindow({
69
- usedPercent: null,
70
- windowSeconds: null,
71
- resetAt: null,
72
- valueLabel
73
- })
74
- };
101
+ const limit = toNumber(data.limit);
102
+ const limitRemaining = toNumber(data.limit_remaining);
103
+ if (limit !== null && limitRemaining === null) {
104
+ return buildResult({
105
+ providerId,
106
+ providerName,
107
+ ok: false,
108
+ configured: true,
109
+ error: 'No quota data in response'
110
+ });
111
+ }
112
+
113
+ const usageMonthly = toNumber(data.usage_monthly);
114
+ if (limit === null && usageMonthly === null) {
115
+ return buildResult({
116
+ providerId,
117
+ providerName,
118
+ ok: false,
119
+ configured: true,
120
+ error: 'No quota data in response'
121
+ });
122
+ }
123
+
124
+ const nowMs = Date.now();
125
+ let windowKey;
126
+ let windowSeconds;
127
+ let resetAt;
128
+ let usedPercent;
129
+ let valueLabel;
130
+
131
+ if (limit === null) {
132
+ windowKey = 'monthly';
133
+ windowSeconds = PERIOD_SECONDS.monthly;
134
+ resetAt = resolveResetAt('monthly', nowMs);
135
+ usedPercent = null;
136
+ valueLabel = `$${formatMoney(usageMonthly)} spent`;
137
+ } else {
138
+ const used = Math.max(0, limit - limitRemaining);
139
+ const percent = limit > 0 ? (used / limit) * 100 : null;
140
+ usedPercent = percent === null ? null : Math.min(100, percent);
141
+ valueLabel = `$${formatMoney(used)} / $${formatMoney(limit)}`;
142
+
143
+ if (Object.hasOwn(PERIOD_SECONDS, data.limit_reset)) {
144
+ windowKey = data.limit_reset;
145
+ windowSeconds = PERIOD_SECONDS[data.limit_reset];
146
+ resetAt = resolveResetAt(data.limit_reset, nowMs);
147
+ } else {
148
+ windowKey = 'credits';
149
+ windowSeconds = null;
150
+ resetAt = null;
151
+ }
152
+ }
75
153
 
76
154
  return buildResult({
77
155
  providerId,
78
156
  providerName,
79
157
  ok: true,
80
158
  configured: true,
81
- usage: { windows }
159
+ usage: {
160
+ windows: {
161
+ [windowKey]: toUsageWindow({
162
+ usedPercent,
163
+ windowSeconds,
164
+ resetAt,
165
+ valueLabel
166
+ })
167
+ }
168
+ }
82
169
  });
83
170
  } catch (error) {
171
+ const isTimeout = error instanceof DOMException && (
172
+ error.name === 'TimeoutError' || (error.name === 'AbortError' && timeoutSignal.aborted)
173
+ );
174
+ const isParseError = error instanceof SyntaxError;
84
175
  return buildResult({
85
176
  providerId,
86
177
  providerName,
87
178
  ok: false,
88
179
  configured: true,
89
- error: error instanceof Error ? error.message : 'Request failed'
180
+ error: isTimeout
181
+ ? 'Request timed out'
182
+ : isParseError
183
+ ? 'Invalid response from provider'
184
+ : (error instanceof Error ? error.message : 'Request failed')
90
185
  });
91
186
  }
92
187
  };
@@ -0,0 +1,330 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ vi.mock('../../opencode/auth.js', () => ({
4
+ readAuthFile: () => ({ openrouter: { key: 'test-token' } }),
5
+ }));
6
+
7
+ import { fetchQuota, resolveResetAt } from './openrouter.js';
8
+
9
+ afterEach(() => {
10
+ vi.unstubAllGlobals();
11
+ });
12
+
13
+ const mockResponse = (body, init = {}) => ({
14
+ ok: true,
15
+ status: 200,
16
+ json: async () => body,
17
+ ...init,
18
+ });
19
+
20
+ // Documented payload shape from https://openrouter.ai/docs/api_reference/limits
21
+ const DOCUMENTED_PAYLOAD = {
22
+ data: {
23
+ label: 'Default',
24
+ limit: 30,
25
+ limit_remaining: 25,
26
+ limit_reset: 'monthly',
27
+ include_byok_in_limit: false,
28
+ usage: 5,
29
+ usage_daily: 1,
30
+ usage_weekly: 3,
31
+ usage_monthly: 5,
32
+ byok_usage: 0,
33
+ byok_usage_daily: 0,
34
+ byok_usage_weekly: 0,
35
+ byok_usage_monthly: 0,
36
+ is_free_tier: false,
37
+ is_management_key: false,
38
+ is_provisioning_key: false,
39
+ creator_user_id: 'user-fixture',
40
+ expires_at: null,
41
+ rate_limit: null
42
+ }
43
+ };
44
+
45
+ const expectMonthlyReset = (resetAt) => {
46
+ expect(resetAt).toEqual(expect.any(Number));
47
+ const resetDate = new Date(resetAt);
48
+ expect(resetDate.getUTCDate()).toBe(1);
49
+ expect(resetDate.getUTCHours()).toBe(0);
50
+ expect(resetAt - Date.now()).toBeGreaterThan(0);
51
+ expect(resetAt - Date.now()).toBeLessThanOrEqual(31 * 86400 * 1000);
52
+ };
53
+
54
+ describe('OpenRouter quota provider', () => {
55
+ it('builds a monthly window from the documented payload', async () => {
56
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse(DOCUMENTED_PAYLOAD)));
57
+
58
+ const result = await fetchQuota();
59
+ const window = result.usage.windows.monthly;
60
+
61
+ expect(result.ok).toBe(true);
62
+ expect(result.providerId).toBe('openrouter');
63
+ expect(window.usedPercent).toBeCloseTo(16.6667, 3);
64
+ expect(window.valueLabel).toBe('$5.00 / $30.00');
65
+ expect(window.windowSeconds).toBe(30 * 86400);
66
+ expectMonthlyReset(window.resetAt);
67
+ });
68
+
69
+ it('uses the daily window and preserves the observed funded-key values', async () => {
70
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
71
+ data: {
72
+ usage: 3.17561396,
73
+ usage_daily: 0.0000018,
74
+ usage_weekly: 0.0000018,
75
+ usage_monthly: 3.17561396,
76
+ limit: 30,
77
+ limit_remaining: 29.9999982,
78
+ limit_reset: 'daily',
79
+ is_free_tier: true,
80
+ is_management_key: false,
81
+ include_byok_in_limit: false,
82
+ byok_usage: 0
83
+ }
84
+ })));
85
+
86
+ const result = await fetchQuota();
87
+ const window = result.usage.windows.daily;
88
+
89
+ expect(window).toBeDefined();
90
+ expect(window.windowSeconds).toBe(86400);
91
+ expect(window.valueLabel).toBe('$0.00 / $30.00');
92
+ expect(window.usedPercent).toBeLessThan(0.001);
93
+ expect(window.resetAt % 86400000).toBe(0);
94
+ expect(window.resetAt - Date.now()).toBeGreaterThan(0);
95
+ expect(window.resetAt - Date.now()).toBeLessThanOrEqual(86400000);
96
+ });
97
+
98
+ it('builds a monthly unlimited window from null limit fields', async () => {
99
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
100
+ data: {
101
+ limit: null,
102
+ limit_remaining: null,
103
+ limit_reset: null,
104
+ usage_monthly: 3.17561396,
105
+ is_management_key: false
106
+ }
107
+ })));
108
+
109
+ const result = await fetchQuota();
110
+ const window = result.usage.windows.monthly;
111
+
112
+ expect(window.usedPercent).toBeNull();
113
+ expect(window.valueLabel).toBe('$3.18 spent');
114
+ expect(window.windowSeconds).toBe(30 * 86400);
115
+ expectMonthlyReset(window.resetAt);
116
+ });
117
+
118
+ it('uses a credits window for a lifetime cap', async () => {
119
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
120
+ data: { limit: 30, limit_remaining: 25, limit_reset: null, usage_monthly: 5 }
121
+ })));
122
+
123
+ const result = await fetchQuota();
124
+ const window = result.usage.windows.credits;
125
+
126
+ expect(window).toBeDefined();
127
+ expect(window.resetAt).toBeNull();
128
+ expect(window.windowSeconds).toBeNull();
129
+ });
130
+
131
+ it('uses a credits window for an unrecognized reset period', async () => {
132
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
133
+ data: { limit: 30, limit_remaining: 25, limit_reset: 'yearly', usage_monthly: 5 }
134
+ })));
135
+
136
+ const result = await fetchQuota();
137
+ const window = result.usage.windows.credits;
138
+
139
+ expect(window).toBeDefined();
140
+ expect(window.resetAt).toBeNull();
141
+ expect(window.windowSeconds).toBeNull();
142
+ });
143
+
144
+ it('builds a weekly window from a weekly limit', async () => {
145
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
146
+ data: { limit: 30, limit_remaining: 25, limit_reset: 'weekly', usage_monthly: 5 }
147
+ })));
148
+
149
+ const result = await fetchQuota();
150
+ const window = result.usage.windows.weekly;
151
+
152
+ expect(window).toBeDefined();
153
+ expect(window.windowSeconds).toBe(604800);
154
+ expect(new Date(window.resetAt).getUTCDay()).toBe(1);
155
+ expect(window.resetAt - Date.now()).toBeGreaterThan(0);
156
+ expect(window.resetAt - Date.now()).toBeLessThanOrEqual(7 * 86400 * 1000);
157
+ });
158
+
159
+ it('ignores BYOK usage when calculating the quota label and percent', async () => {
160
+ const withByokPayload = {
161
+ ...DOCUMENTED_PAYLOAD,
162
+ data: {
163
+ ...DOCUMENTED_PAYLOAD.data,
164
+ include_byok_in_limit: true,
165
+ byok_usage_monthly: 100,
166
+ byok_usage: 100
167
+ }
168
+ };
169
+ const fetchMock = vi.fn()
170
+ .mockResolvedValueOnce(mockResponse(DOCUMENTED_PAYLOAD))
171
+ .mockResolvedValueOnce(mockResponse(withByokPayload));
172
+ vi.stubGlobal('fetch', fetchMock);
173
+
174
+ const withoutByok = await fetchQuota();
175
+ const withByok = await fetchQuota();
176
+
177
+ expect(withByok.usage.windows.monthly.valueLabel)
178
+ .toBe(withoutByok.usage.windows.monthly.valueLabel);
179
+ expect(withByok.usage.windows.monthly.usedPercent)
180
+ .toBe(withoutByok.usage.windows.monthly.usedPercent);
181
+ });
182
+
183
+ it('rejects management keys with a specific error', async () => {
184
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
185
+ data: { is_management_key: true }
186
+ })));
187
+
188
+ const result = await fetchQuota();
189
+
190
+ expect(result.ok).toBe(false);
191
+ expect(result.configured).toBe(true);
192
+ expect(result.usage).toBeNull();
193
+ expect(result.error).toBe('Management key configured — quota needs an inference API key');
194
+ });
195
+
196
+ it.each([401, 403])('maps %s to a session-expired error', async (status) => {
197
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status }));
198
+
199
+ const result = await fetchQuota();
200
+
201
+ expect(result.ok).toBe(false);
202
+ expect(result.error).toBe('Session expired — please re-authenticate with OpenRouter');
203
+ });
204
+
205
+ it('reports invalid-response on JSON parse failure', async () => {
206
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
207
+ ok: true,
208
+ status: 200,
209
+ json: async () => { throw new SyntaxError('Unexpected token'); },
210
+ }));
211
+
212
+ const result = await fetchQuota();
213
+
214
+ expect(result.ok).toBe(false);
215
+ expect(result.error).toBe('Invalid response from provider');
216
+ });
217
+
218
+ it('reports a normalized timeout error', async () => {
219
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new DOMException('The operation timed out.', 'TimeoutError')));
220
+
221
+ const result = await fetchQuota();
222
+
223
+ expect(result.ok).toBe(false);
224
+ expect(result.error).toBe('Request timed out');
225
+ });
226
+
227
+ it('returns no-quota-data when data is missing', async () => {
228
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({})));
229
+
230
+ const result = await fetchQuota();
231
+
232
+ expect(result.ok).toBe(false);
233
+ expect(result.configured).toBe(true);
234
+ expect(result.error).toBe('No quota data in response');
235
+ expect(result.usage).toBeNull();
236
+ });
237
+
238
+ it('returns no-quota-data when data is empty', async () => {
239
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({ data: {} })));
240
+
241
+ const result = await fetchQuota();
242
+
243
+ expect(result.ok).toBe(false);
244
+ expect(result.configured).toBe(true);
245
+ expect(result.error).toBe('No quota data in response');
246
+ expect(result.usage).toBeNull();
247
+ });
248
+
249
+ it.each([null, []])('returns no-quota-data when data is %s', async (data) => {
250
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({ data })));
251
+
252
+ const result = await fetchQuota();
253
+
254
+ expect(result.ok).toBe(false);
255
+ expect(result.configured).toBe(true);
256
+ expect(result.usage).toBeNull();
257
+ expect(result.error).toBe('No quota data in response');
258
+ });
259
+
260
+ it('returns no-quota-data when a limit has no remaining value', async () => {
261
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
262
+ data: { limit: 30, limit_remaining: null, usage_monthly: 5 }
263
+ })));
264
+
265
+ const result = await fetchQuota();
266
+
267
+ expect(result.ok).toBe(false);
268
+ expect(result.error).toBe('No quota data in response');
269
+ });
270
+
271
+ it('keeps a zero limit valid with a null percent', async () => {
272
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
273
+ data: { limit: 0, limit_remaining: 0, limit_reset: 'monthly', usage_monthly: 0 }
274
+ })));
275
+
276
+ const result = await fetchQuota();
277
+ const window = result.usage.windows.monthly;
278
+
279
+ expect(result.ok).toBe(true);
280
+ expect(window.usedPercent).toBeNull();
281
+ expect(window.valueLabel).toBe('$0.00 / $0.00');
282
+ });
283
+
284
+ it('requests the key endpoint and never the credits endpoint', async () => {
285
+ const fetchMock = vi.fn().mockResolvedValue(mockResponse(DOCUMENTED_PAYLOAD));
286
+ vi.stubGlobal('fetch', fetchMock);
287
+
288
+ await fetchQuota();
289
+
290
+ const requestedUrl = fetchMock.mock.calls[0][0];
291
+ expect(requestedUrl).toBe('https://openrouter.ai/api/v1/key');
292
+ expect(requestedUrl).not.toContain('/api/v1/credits');
293
+ });
294
+
295
+ it('resolves daily reset at the next UTC day across year boundaries', () => {
296
+ expect(resolveResetAt('daily', Date.UTC(2024, 11, 31, 23, 59))).toBe(Date.UTC(2025, 0, 1));
297
+ });
298
+
299
+ it('resolves weekly reset from Sunday to the next Monday', () => {
300
+ expect(resolveResetAt('weekly', Date.UTC(2024, 0, 7, 12))).toBe(Date.UTC(2024, 0, 8));
301
+ });
302
+
303
+ it('resolves weekly reset from Monday to the following Monday', () => {
304
+ expect(resolveResetAt('weekly', Date.UTC(2024, 0, 8, 12))).toBe(Date.UTC(2024, 0, 15));
305
+ });
306
+
307
+ it('resolves weekly reset from Wednesday to the next Monday', () => {
308
+ expect(resolveResetAt('weekly', Date.UTC(2024, 0, 10, 12))).toBe(Date.UTC(2024, 0, 15));
309
+ });
310
+
311
+ it('resolves monthly reset from January 31 to February 1', () => {
312
+ expect(resolveResetAt('monthly', Date.UTC(2024, 0, 31, 12))).toBe(Date.UTC(2024, 1, 1));
313
+ });
314
+
315
+ it('resolves monthly reset across December to January', () => {
316
+ expect(resolveResetAt('monthly', Date.UTC(2024, 11, 31, 23, 59))).toBe(Date.UTC(2025, 0, 1));
317
+ });
318
+
319
+ it('clamps percent at 100 while leaving the money label unclamped', async () => {
320
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(mockResponse({
321
+ data: { limit: 30, limit_remaining: -1, limit_reset: 'monthly', usage_monthly: 31 }
322
+ })));
323
+
324
+ const result = await fetchQuota();
325
+ const window = result.usage.windows.monthly;
326
+
327
+ expect(window.usedPercent).toBe(100);
328
+ expect(window.valueLabel).toBe('$31.00 / $30.00');
329
+ });
330
+ });
@@ -25,6 +25,7 @@ Host side (`packages/web/server/lib/relay/`):
25
25
  - `host-client.js` — the long-lived connection manager: one outbound control connection to the relay, a per-client data connection for each connected device, reconnect/backoff, and the E2EE responder handshake per connection.
26
26
  - `host-lock.js` — the per-machine host claim. Every local instance sharing the data dir shares the relay identity (same serverId), so concurrent relay hosts evict each other at the relay worker (`4001: Control replaced`) and paired devices land on whichever local process won last. The claim file (`<data-dir>/relay-host.lock`, `{ pid }`) makes this deterministic: `service.js` only starts the host when no LIVE process holds the claim (stale claims from dead pids are ignored), goes to `standby` otherwise, and a 30s watcher both takes over when the claimant dies and stands down when another process claims. A standby watcher waits a 2-minute grace after the claim frees before taking over, so a cleanly restarting host (app update/relaunch) — which reclaims at boot with no wait — always wins the restart window over a bystander instance. Explicit user intent — creating a pairing link or hitting `/relay/enable` — force-claims; the previous holder's watcher sees the takeover and backs off instead of fighting. Instances created with `allowPassiveHost: false` (dev servers via `AIWORKER_RELAY_HOST=off`, the Electron dev shell via `AIWORKER_ELECTRON_DEV`; `AIWORKER_RELAY_HOST=on` overrides) never start the host passively at all — boot, demand reconcile, and watcher takeover leave them in `standby`; only explicit enable/pairing hosts there. The claim is cooperative (the relay worker still enforces the single host slot); it only decides which process keeps retrying.
27
27
  - `tunnel-host.js` — the per-connection dispatcher: decrypts tunnel frames and forwards HTTP/SSE/WS to the local server over loopback, then streams responses back. Enforces a path allowlist and never injects credentials.
28
+ - `downstream-scheduler.js` owns end-client delivery credit and round-robin transmission across response streams. It selects plaintext frames before encryption.
28
29
  - `e2ee.js`, `tunnel-codec.js` — host-side (JS) mirrors of the shared crypto and framing (see "Two implementations" below).
29
30
 
30
31
  Client side (`packages/ui/src/lib/relay/`):
@@ -47,8 +48,75 @@ The host dispatcher restricts tunneled traffic to explicit path allowlists (one
47
48
 
48
49
  Request bodies crossing the tunnel are buffered on the host and forwarded to loopback only once the client's `StreamEnd` frame arrives (bodies above ~512 KB stream live instead). A body whose frames were lost in transit therefore never reaches the loopback server as an empty/truncated chunked body — the host aborts the stream and the client sees an ambiguous transport failure it can retry, instead of the loopback server's bare `400` ("Failed to send message (400)" from the mobile app).
49
50
 
51
+ ## Downstream flow control
52
+
53
+ `hello` and `ready` negotiate `flowControl: true` independently of `batch`.
54
+ When either peer omits the flag, the host keeps the legacy transmission path.
55
+ This capability controls host-to-client traffic only. Uploads retain their
56
+ existing request-body behavior. The Cloudflare broker needs no changes.
57
+
58
+ The client sends encrypted `DeliveryAck` frames on stream zero. Their payload is
59
+ an eight-byte unsigned big-endian cumulative count of received raw tunnel-frame
60
+ bytes on nonzero streams, including the five-byte frame header. Batch envelopes,
61
+ encryption overhead and stream-zero keepalives are excluded. The count resets
62
+ with each handshake. ACKs cover complete frames and include late frames for
63
+ cancelled streams, since those frames still consumed credit. The host rejects
64
+ duplicate, regressing, partial-frame or beyond-sent acknowledgements.
65
+
66
+ The client acknowledges after decoding and dispatching transport data, without
67
+ waiting for React rendering. It coalesces acknowledgements by byte count with a
68
+ short timer for the tail. Keepalives and ACK processing never await downstream
69
+ credit, which would deadlock the channel.
70
+
71
+ The scheduler starts with a small byte window. A backlogged sender can grow its
72
+ window when ACK latency stays near the best observed round trip, and reduces it
73
+ when delivery delay rises. Sparse traffic cannot inflate the window for a later
74
+ bulk burst. The window has a hard upper bound; a sudden bandwidth drop can still
75
+ delay bytes already sent, but cannot create an unlimited network backlog.
76
+
77
+ HTTP bodies and WS messages are sliced into small frames. The scheduler rotates
78
+ streams, preserves each stream's order, and batches selected frames before the
79
+ serialized encryption step. Producers offer a bounded group of slices and await
80
+ transmission before reading more. The legacy timed batcher remains in use only
81
+ without negotiated flow control.
82
+
83
+ HTTP/SSE backpressure reaches the loopback response reader. Node's `ws` pauses
84
+ loopback socket reads while output is waiting. Bun's `ws` shim cannot pause, so
85
+ the dispatcher instead enforces a connection-wide pending WS byte/message cap
86
+ and explicitly aborts the offending substream on overflow. It never silently
87
+ discards deltas. WS output messages are serialized through their last fragment,
88
+ and the close frame follows pending output. Cancellation releases queued work;
89
+ channel teardown releases all producers and acknowledgement state.
90
+
91
+ Regression coverage lives in `downstream-scheduler.test.js`, `flow-control.test.js`
92
+ and `cross-compat.test.js`. The end-to-end fixture uses the real client, host,
93
+ crypto and loopback requests with a byte-paced relay leg. It compares delivery
94
+ ordering, queue growth and a concurrent small response, including both legacy
95
+ fallback directions, unbatched operation, cancellation and fragmented WS output.
96
+ It does not replace a physical iOS/LTE check.
97
+
50
98
  ## Authentication model
51
99
 
100
+ ### Self-reported app diagnostics
101
+
102
+ Host-control, host-data and client upgrades include optional `appId`,
103
+ `appVersion` and `platform` query parameters. AiWorker sends `aiworker`,
104
+ the local package version and the local runtime. Client platforms use the
105
+ existing presence values: `desktop` for Electron, `vscode`, `ios`, `android`
106
+ and `web` for browsers, including hosted mobile. Hosts use
107
+ `AIWORKER_RUNTIME`, defaulting to `web`, so SSH hosts report `ssh-remote`.
108
+ These labels describe the connecting process, not its remote target.
109
+
110
+ These fields are diagnostics only, outside the signed auth payload. Older
111
+ relays ignore them and older apps remain connectable. The hosted relay groups
112
+ missing or invalid fields as `unknown`. Its analytics count host-control and
113
+ client connections separately, including reconnects, and show labels as
114
+ self-reported, never as verified app identity. Host-data sockets are excluded.
115
+ App diagnostics are written on connection, without per-app traffic counters.
116
+ No credentials, device names or application contents are added to diagnostics.
117
+
118
+ ### Access checks
119
+
52
120
  - The tunnel is **transport only**. The AiWorker server still authenticates every tunneled request exactly as it authenticates a direct remote client. The relay path grants reachability, not authorization.
53
121
  - Clients carry their normal credential. HTTP and SSE requests authenticate with the client's bearer token (a header). **WebSocket upgrades cannot send headers**, so they authenticate with a short-lived URL-scoped token minted beforehand and passed as a query parameter. This asymmetry is important when adding new WebSocket features (see the skill).
54
122
  - The host authenticates itself to the relay with a signed handshake using its long-lived signing key.
@@ -87,6 +155,13 @@ The E2EE and framing logic exists twice: TypeScript in `packages/ui/src/lib/rela
87
155
 
88
156
  ## Runtime integration (client)
89
157
 
158
+ Client keepalive liveness comes from received frames only. Outbound HTTP retries
159
+ cannot suppress a probe of a silent peer. Any valid inbound traffic, including a
160
+ Pong, clears the probe deadline. Terminal relay close codes retain their error
161
+ for the lifetime of that client: subsequent HTTP requests and WS opens fail
162
+ immediately rather than waiting for a reconnect that will never be scheduled.
163
+ Transient failures still use the existing reconnect/backoff path.
164
+
90
165
  Relay mode plugs into the existing client transport layer rather than a parallel path: `runtime-switch` activates the tunnel singleton, `runtime-fetch` routes runtime requests through it, `runtime-url`/`runtime-socket` yield tunnel-backed URLs and sockets, and `runtime-auth` mints the URL-scoped token through the tunnel. Direct-URL connections and the Electron realtime-proxy path are unaffected.
91
166
 
92
167
  ## Design invariants (do not regress)
@@ -12,16 +12,42 @@ import {
12
12
  decodeTunnelFrame as jsDecode,
13
13
  encodeFrameBatch as jsEncodeBatch,
14
14
  encodeTunnelFrame as jsEncode,
15
+ decodeDeliveryAck,
15
16
  } from './tunnel-codec.js';
16
17
  import {
17
18
  decodeFrameBatch as tsDecodeBatch,
18
19
  decodeTunnelFrame as tsDecode,
19
20
  encodeFrameBatch as tsEncodeBatch,
20
21
  encodeTunnelFrame as tsEncode,
22
+ encodeDeliveryAck,
21
23
  } from '../../../../ui/src/lib/relay/tunnel-codec.ts';
22
24
  import { TunnelFrameType as TsFrameType } from '../../../../ui/src/lib/relay/protocol.ts';
23
25
 
24
26
  describe('relay JS-host <-> TS-client cross compatibility', () => {
27
+ it('negotiates flow control independently of batching, with legacy fallback on either side', async () => {
28
+ const keys = await generateEcdhKeyPair();
29
+ const pub = await exportPublicKeyJwk(keys.publicKey);
30
+ for (const batch of [false, true]) {
31
+ for (const clientFlow of [false, true]) {
32
+ for (const hostFlow of [false, true]) {
33
+ const client = await createClientHandshake(pub, { batch, flowControl: clientFlow });
34
+ const host = createHostHandshake(keys.privateKey, { batch, flowControl: hostFlow });
35
+ const ready = await host.handleText(client.helloText);
36
+ const established = await client.handleText(ready.replyText);
37
+ expect(ready.flowControl).toBe(clientFlow && hostFlow);
38
+ expect(established.flowControl).toBe(clientFlow && hostFlow);
39
+ expect(established.batch).toBe(batch);
40
+ expect((await host.handleText(client.helloText)).text).toBe(ready.replyText);
41
+ }
42
+ }
43
+ }
44
+ expect(JsFrameType).toEqual(TsFrameType);
45
+ for (const bytes of [0, 8197, 2 ** 32 + 17, Number.MAX_SAFE_INTEGER]) {
46
+ expect(decodeDeliveryAck(encodeDeliveryAck(bytes))).toBe(bytes);
47
+ }
48
+ expect(() => decodeDeliveryAck(new Uint8Array(7))).toThrow();
49
+ expect(() => decodeDeliveryAck(new Uint8Array(8).fill(255))).toThrow();
50
+ });
25
51
  it('completes a handshake and exchanges frames both ways', async () => {
26
52
  const hostKeys = await generateEcdhKeyPair();
27
53
  const hostPubJwk = await exportPublicKeyJwk(hostKeys.publicKey);