even-keel 0.2.2 → 0.3.0-rc.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 (251) hide show
  1. package/.claude-plugin/marketplace.json +12 -0
  2. package/CHANGELOG.md +20 -0
  3. package/README.md +5 -5
  4. package/dist/src/account/aws.js +76 -0
  5. package/dist/src/account/azure.js +36 -0
  6. package/dist/src/account/cloud-errors.js +72 -0
  7. package/dist/src/account/cloud.js +335 -0
  8. package/dist/src/account/credit.js +49 -7
  9. package/dist/src/account/gcloud.js +71 -0
  10. package/dist/src/account/homes.js +35 -1
  11. package/dist/src/account/keycheck.js +57 -4
  12. package/dist/src/account/management.js +41 -0
  13. package/dist/src/account/model.js +10 -2
  14. package/dist/src/account/network.js +8 -3
  15. package/dist/src/account/service-defaults.js +12 -3
  16. package/dist/src/account/share.js +12 -2
  17. package/dist/src/account/spend.js +155 -0
  18. package/dist/src/account/watcher.js +141 -18
  19. package/dist/src/agent/adapters.js +13 -2
  20. package/dist/src/agent/env.js +7 -0
  21. package/dist/src/agent/process.js +32 -6
  22. package/dist/src/agent/projectRules.js +3 -2
  23. package/dist/src/agent/scripted.js +305 -0
  24. package/dist/src/builtin/adapter.js +40 -0
  25. package/dist/src/builtin/control.js +165 -0
  26. package/dist/src/builtin/editor.js +69 -0
  27. package/dist/src/builtin/files.js +155 -0
  28. package/dist/src/builtin/links.js +25 -0
  29. package/dist/src/builtin/model.js +59 -0
  30. package/dist/src/builtin/routes.js +91 -0
  31. package/dist/src/builtin/source.js +239 -0
  32. package/dist/src/builtin/store.js +498 -0
  33. package/dist/src/chain/dispatcher.js +58 -8
  34. package/dist/src/chain/handover.js +21 -4
  35. package/dist/src/chain/launches.js +3 -3
  36. package/dist/src/chain/lists.js +10 -1
  37. package/dist/src/chain/log.js +3 -1
  38. package/dist/src/chain/maincheck.js +114 -10
  39. package/dist/src/chain/mainci.js +20 -4
  40. package/dist/src/chain/mainfix.js +12 -1
  41. package/dist/src/chain/milestone-sequence.js +40 -0
  42. package/dist/src/chain/milestones.js +3 -2
  43. package/dist/src/chain/order.js +20 -5
  44. package/dist/src/chain/prompts.js +14 -2
  45. package/dist/src/chain/relay.js +9 -3
  46. package/dist/src/chain/reviews.js +1 -1
  47. package/dist/src/chain/rules.js +2 -5
  48. package/dist/src/chain/snapshots.js +2 -0
  49. package/dist/src/chain/start.js +1 -1
  50. package/dist/src/chain/store.js +7 -0
  51. package/dist/src/ci/adapters.js +3 -1
  52. package/dist/src/ci/forgejo-profile.js +3 -24
  53. package/dist/src/ci/forgejo.js +2 -1
  54. package/dist/src/ci/github.js +10 -2
  55. package/dist/src/ci/gitlab.js +10 -3
  56. package/dist/src/ci/http.js +4 -0
  57. package/dist/src/ci/model.js +79 -6
  58. package/dist/src/ci/report.js +6 -3
  59. package/dist/src/ci/shared.js +9 -0
  60. package/dist/src/ci/verdict.js +18 -7
  61. package/dist/src/ci/watcher.js +95 -23
  62. package/dist/src/ci/wiring.js +15 -0
  63. package/dist/src/claude/adapter.js +26 -1
  64. package/dist/src/claude/calls.js +38 -0
  65. package/dist/src/claude/cli.js +36 -13
  66. package/dist/src/claude/instructions.js +42 -7
  67. package/dist/src/claude/oauth.js +67 -0
  68. package/dist/src/claude/sdk/host.js +7 -4
  69. package/dist/src/codex/cli.js +24 -16
  70. package/dist/src/codex/turns.js +6 -3
  71. package/dist/src/codex/window.js +14 -0
  72. package/dist/src/config-form.js +29 -3
  73. package/dist/src/config-store.js +20 -6
  74. package/dist/src/config.js +18 -2
  75. package/dist/src/copilot/cli.js +5 -9
  76. package/dist/src/demo/agent.js +97 -0
  77. package/dist/src/demo/model.js +6 -0
  78. package/dist/src/demo/scenario.js +139 -0
  79. package/dist/src/demo/service.js +155 -0
  80. package/dist/src/event-log/log.js +96 -0
  81. package/dist/src/event-log/model.js +1 -0
  82. package/dist/src/event-log/page-events.js +66 -0
  83. package/dist/src/event-log/watch.js +236 -0
  84. package/dist/src/events.js +57 -1
  85. package/dist/src/forgejo/adapter.js +48 -0
  86. package/dist/src/forgejo/api.js +81 -0
  87. package/dist/src/forgejo/model.js +57 -0
  88. package/dist/src/forgejo/profile.js +24 -0
  89. package/dist/src/forgejo/source.js +242 -0
  90. package/dist/src/forgejo/trust.js +45 -0
  91. package/dist/src/git/branches.js +88 -0
  92. package/dist/src/git/worktree.js +12 -0
  93. package/dist/src/jira/model.js +11 -4
  94. package/dist/src/jira/source.js +42 -7
  95. package/dist/src/limits/model.js +48 -3
  96. package/dist/src/limits/usage.js +60 -5
  97. package/dist/src/linear/model.js +11 -2
  98. package/dist/src/linear/source.js +5 -6
  99. package/dist/src/notice/en.js +156 -5
  100. package/dist/src/notice/kinds.js +26 -0
  101. package/dist/src/opencode/adapter.js +2 -2
  102. package/dist/src/opencode/cli.js +28 -21
  103. package/dist/src/opencode/home.js +7 -2
  104. package/dist/src/opencode/transcript.js +2 -1
  105. package/dist/src/opencode/window.js +54 -0
  106. package/dist/src/packages/gateway.js +40 -1
  107. package/dist/src/packages/launch.js +5 -2
  108. package/dist/src/packages/service.js +1 -1
  109. package/dist/src/profiles/control.js +1 -0
  110. package/dist/src/profiles/model.js +2 -2
  111. package/dist/src/profiles/service.js +46 -4
  112. package/dist/src/profiles/store.js +10 -5
  113. package/dist/src/projects/add.js +6 -1
  114. package/dist/src/projects/branch-control.js +86 -0
  115. package/dist/src/projects/branch-move.js +39 -0
  116. package/dist/src/projects/branch.js +13 -0
  117. package/dist/src/projects/check.js +16 -23
  118. package/dist/src/review/events.js +1 -1
  119. package/dist/src/review/wiring.js +19 -2
  120. package/dist/src/server-request.js +25 -4
  121. package/dist/src/server-response.js +140 -0
  122. package/dist/src/server.js +48 -110
  123. package/dist/src/service/accounts.js +105 -17
  124. package/dist/src/service/chain.js +68 -50
  125. package/dist/src/service/cleanup.js +105 -0
  126. package/dist/src/service/demo.js +45 -0
  127. package/dist/src/service/hosting.js +99 -10
  128. package/dist/src/service/stats.js +3 -3
  129. package/dist/src/service/trackers.js +3 -0
  130. package/dist/src/service.js +92 -10
  131. package/dist/src/sessions/ask.js +19 -3
  132. package/dist/src/sessions/boot.js +7 -0
  133. package/dist/src/sessions/chat.js +14 -3
  134. package/dist/src/sessions/keepwarm.js +1 -1
  135. package/dist/src/sessions/lingering.js +34 -8
  136. package/dist/src/sessions/monitor.js +16 -1
  137. package/dist/src/sessions/protection.js +10 -8
  138. package/dist/src/sessions/rare.js +130 -0
  139. package/dist/src/sessions/tail.js +4 -0
  140. package/dist/src/sessions/transcript.js +6 -2
  141. package/dist/src/settings/defaults.js +1 -0
  142. package/dist/src/settings/registry.js +39 -1
  143. package/dist/src/settings/store.js +14 -5
  144. package/dist/src/shown-work.js +22 -0
  145. package/dist/src/stats/base-sql.js +7 -1
  146. package/dist/src/stats/checkpoint.js +7 -4
  147. package/dist/src/stats/model.js +1 -1
  148. package/dist/src/stats/reader.js +41 -21
  149. package/dist/src/stats/rules-reader.js +4 -2
  150. package/dist/src/stats/tally-schema.js +1 -1
  151. package/dist/src/storage/copy.js +7 -3
  152. package/dist/src/storage/database.js +167 -1
  153. package/dist/src/storage/migrations.js +40 -1
  154. package/dist/src/storage/owner.js +2 -0
  155. package/dist/src/storage/schema.js +1 -1
  156. package/dist/src/taskmcp/args.js +95 -0
  157. package/dist/src/taskmcp/calls.js +346 -0
  158. package/dist/src/taskmcp/server.js +77 -0
  159. package/dist/src/taskmcp/tools.js +99 -0
  160. package/dist/src/tracker/adapters.js +3 -1
  161. package/dist/src/tracker/card.js +7 -5
  162. package/dist/src/tracker/closes.js +6 -0
  163. package/dist/src/tracker/control.js +21 -12
  164. package/dist/src/tracker/editor.js +55 -0
  165. package/dist/src/tracker/health.js +5 -0
  166. package/dist/src/tracker/link.js +40 -5
  167. package/dist/src/tracker/model.js +0 -2
  168. package/dist/src/tracker/questions.js +10 -3
  169. package/dist/src/tracker/readers.js +5 -3
  170. package/dist/src/tracker/source.js +4 -0
  171. package/dist/src/tracker/start.js +4 -1
  172. package/dist/src/tracker/trackers.js +20 -10
  173. package/dist/src/updates/updater.js +2 -2
  174. package/dist/tally/src/builtin-tasks.js +45 -0
  175. package/dist/tally/src/catalogue.js +70 -0
  176. package/dist/tally/src/classify.js +1 -0
  177. package/dist/tally/src/collect.js +27 -10
  178. package/dist/tally/src/copilot.js +1 -0
  179. package/dist/tally/src/db.js +53 -23
  180. package/dist/tally/src/migrations/10-rework-label.sql +73 -0
  181. package/dist/tally/src/migrations/11-catalogue-prices.sql +53 -0
  182. package/dist/tally/src/migrations/12-key-spends.sql +30 -0
  183. package/dist/tally/src/migrations.js +1 -1
  184. package/dist/tally/src/opencode.js +1 -0
  185. package/dist/tally/src/parse.js +3 -0
  186. package/dist/tally/src/rollout.js +2 -1
  187. package/dist/tally/src/rule-hook-size.js +2 -1
  188. package/dist/tally/src/rule-hook.js +3 -0
  189. package/dist/web/assets/ConfirmDialog-CT1w8fds.css +1 -0
  190. package/dist/web/assets/ConfirmDialog-DtrqXMLY.js +7 -0
  191. package/dist/web/assets/DescriptionEditor-D8PUeuQ6.js +216 -0
  192. package/dist/web/assets/Loader-D4ik19jr.css +1 -0
  193. package/dist/web/assets/Loader-mgoVDIvZ.js +12 -0
  194. package/dist/web/assets/ProjectPackages-DnCW8kXc.js +1 -0
  195. package/dist/web/assets/TaskCard-Bjnnsxah.js +3 -0
  196. package/dist/web/assets/TaskCard-f7aXQS6c.css +1 -0
  197. package/dist/web/assets/TranscriptWindow-BEAdgN2M.js +4 -0
  198. package/dist/web/assets/chatKeys-7ClMP73F.css +1 -0
  199. package/dist/web/assets/chatKeys-Doxn3auX.js +1 -0
  200. package/dist/web/assets/description-C-o9LBbp.css +1 -0
  201. package/dist/web/assets/feedLine-qIhoKONX.js +1 -0
  202. package/dist/web/assets/index-ernY0hZ5.css +1 -0
  203. package/dist/web/assets/index-srs3Jx9s.js +24 -0
  204. package/dist/web/assets/lib-DZ3lmyI6.js +18 -0
  205. package/dist/web/assets/overview-B_Cnubfu.css +1 -0
  206. package/dist/web/assets/overview-hxpvjWJS.js +1 -0
  207. package/dist/web/assets/packageGroups-DMT_PhT3.css +1 -0
  208. package/dist/web/assets/packageGroups-DWLFjsUs.js +8 -0
  209. package/dist/web/assets/state-DZUHccAT.css +1 -0
  210. package/dist/web/assets/state-ky_dNYYi.js +3 -0
  211. package/dist/web/assets/useFileDrop-4efYr2eq.js +1 -0
  212. package/dist/web/assets/useModels-1WRBMBb2.css +1 -0
  213. package/dist/web/assets/useModels-C_U0wgab.js +4 -0
  214. package/dist/web/assets/useRowFocus-BjMFkowJ.js +1 -0
  215. package/dist/web/assets/useRowFocus-BsvvWNh2.css +1 -0
  216. package/dist/web/index.html +18 -8
  217. package/even-keel.config.example.json +3 -1
  218. package/package.json +20 -4
  219. package/plugins/checkpoint/README.md +1 -1
  220. package/plugins/forgejo/.claude-plugin/plugin.json +7 -0
  221. package/plugins/forgejo/.mcp.json +13 -0
  222. package/plugins/forgejo/README.md +23 -0
  223. package/plugins/forgejo/skills/task/SKILL.md +55 -0
  224. package/plugins/gitlab/.claude-plugin/plugin.json +1 -1
  225. package/plugins/gitlab/skills/task/SKILL.md +1 -1
  226. package/plugins/huly/.claude-plugin/plugin.json +1 -1
  227. package/plugins/huly/skills/task/SKILL.md +1 -1
  228. package/plugins/jira/.claude-plugin/plugin.json +1 -1
  229. package/plugins/jira/skills/task/SKILL.md +1 -1
  230. package/plugins/linear/.claude-plugin/plugin.json +1 -1
  231. package/plugins/linear/skills/task/SKILL.md +1 -1
  232. package/plugins/tasks/.claude-plugin/plugin.json +9 -0
  233. package/plugins/tasks/.mcp.json +8 -0
  234. package/plugins/tasks/README.md +21 -0
  235. package/plugins/tasks/skills/split/SKILL.md +29 -0
  236. package/plugins/tasks/skills/task/SKILL.md +52 -0
  237. package/service/EvenKeelTray.cs +4 -20
  238. package/tally/tally.config.json +1 -0
  239. package/dist/web/assets/Loader-CRe-GCoI.js +0 -31
  240. package/dist/web/assets/Loader-DJJTBsaF.css +0 -1
  241. package/dist/web/assets/TaskCard-Br2QIllc.css +0 -1
  242. package/dist/web/assets/TaskCard-C2xeaHWD.js +0 -2
  243. package/dist/web/assets/TranscriptWindow-COL_WTrF.js +0 -4
  244. package/dist/web/assets/feedLine-D0lnFyBZ.js +0 -1
  245. package/dist/web/assets/index-DQje9Nfo.js +0 -25
  246. package/dist/web/assets/index-mDBlgk2Y.css +0 -1
  247. package/dist/web/assets/media-BlW-XXN0.js +0 -1
  248. package/dist/web/assets/media-DR8nAbPy.css +0 -1
  249. package/dist/web/assets/rolldown-runtime-XKyaHtl9.js +0 -1
  250. package/dist/web/assets/useModels-1oIk0mDX.css +0 -1
  251. package/dist/web/assets/useModels-DRW63oka.js +0 -15
@@ -9,6 +9,8 @@ const OPENAI_RESPONSES_URL = 'https://api.openai.com/v1/responses';
9
9
  const OPENAI_OUT_OF_MONEY = 'insufficient_quota';
10
10
  // Models of the list that take no text input through `/v1/responses`.
11
11
  const NOT_TEXT = /tts|transcribe|audio|realtime|search|image|embedding/;
12
+ const OPENROUTER_MODELS_URL = 'https://openrouter.ai/api/v1/models';
13
+ const OPENROUTER_CHAT_URL = 'https://openrouter.ai/api/v1/chat/completions';
12
14
  /**
13
15
  * Asks Anthropic whether the key can pay again: one output token from the cheapest model the key lists (a Haiku, else
14
16
  * the newest one) — a fraction of a cent. The models list alone costs nothing but answers even with no credit.
@@ -18,7 +20,10 @@ export function checkCredit(key, timeoutMs, fetchImpl = fetch) {
18
20
  modelsUrl: MODELS_URL,
19
21
  url: MESSAGES_URL,
20
22
  headers: { 'x-api-key': key, 'anthropic-version': API_VERSION, 'content-type': 'application/json' },
21
- pick: (ids) => ids.find((id) => id.includes('haiku')) ?? ids[0] ?? null,
23
+ pick: (models) => {
24
+ const ids = models.map((model) => model.id);
25
+ return ids.find((id) => id.includes('haiku')) ?? ids[0] ?? null;
26
+ },
22
27
  body: (model) => ({ model, max_tokens: 1, messages: [{ role: 'user', content: '.' }] }),
23
28
  empty: (status, text) => status === 400 && (text.toLowerCase().includes(OUT_OF_CREDIT) || isSpendingLimit(text)),
24
29
  }, timeoutMs, fetchImpl);
@@ -33,14 +38,51 @@ export function checkOpenAiCredit(key, timeoutMs, fetchImpl = fetch) {
33
38
  modelsUrl: OPENAI_MODELS_URL,
34
39
  url: OPENAI_RESPONSES_URL,
35
40
  headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
36
- pick: (ids) => {
37
- const text = ids.filter((id) => id.startsWith('gpt-') && !NOT_TEXT.test(id));
41
+ pick: (models) => {
42
+ const text = models.map((model) => model.id).filter((id) => id.startsWith('gpt-') && !NOT_TEXT.test(id));
38
43
  return text.find((id) => id.includes('nano')) ?? text.find((id) => id.includes('mini')) ?? null;
39
44
  },
40
45
  body: (model) => ({ model, input: '.', max_output_tokens: 16, store: false }),
41
46
  empty: (status, text) => status === 429 && text.includes(OPENAI_OUT_OF_MONEY),
42
47
  }, timeoutMs, fetchImpl);
43
48
  }
49
+ /**
50
+ * The same question to OpenRouter for an OpenCode key (BTN-843): one output token from the cheapest paid text model it
51
+ * lists — a free one answers even with no money, and `openrouter/auto` has no price (`-1`). A key out of money answers
52
+ * 402; its balance itself only a management key may read.
53
+ */
54
+ export function checkOpenRouterCredit(key, timeoutMs, fetchImpl = fetch) {
55
+ return askCredit({
56
+ modelsUrl: OPENROUTER_MODELS_URL,
57
+ url: OPENROUTER_CHAT_URL,
58
+ headers: { authorization: `Bearer ${key}`, 'content-type': 'application/json' },
59
+ pick: cheapestPaidText,
60
+ body: (model) => ({ model, max_tokens: 1, messages: [{ role: 'user', content: '.' }] }),
61
+ empty: (status) => status === 402,
62
+ }, timeoutMs, fetchImpl);
63
+ }
64
+ function cheapestPaidText(models) {
65
+ let best = null;
66
+ for (const model of models) {
67
+ const architecture = record(model.architecture);
68
+ if (!listHas(architecture.input_modalities, 'text') || !listHas(architecture.output_modalities, 'text'))
69
+ continue;
70
+ const pricing = record(model.pricing);
71
+ const prices = [pricing.prompt, pricing.completion, pricing.request ?? '0'].map(Number);
72
+ if (prices.some((price) => !Number.isFinite(price) || price < 0))
73
+ continue;
74
+ const price = prices.reduce((sum, each) => sum + each, 0);
75
+ if (price > 0 && (best === null || price < best.price))
76
+ best = { id: model.id, price };
77
+ }
78
+ return best?.id ?? null;
79
+ }
80
+ function record(value) {
81
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : {};
82
+ }
83
+ function listHas(value, item) {
84
+ return Array.isArray(value) && value.includes(item);
85
+ }
44
86
  async function askCredit(ask, timeoutMs, fetchImpl) {
45
87
  try {
46
88
  const listed = await fetchImpl(ask.modelsUrl, { headers: ask.headers, signal: AbortSignal.timeout(timeoutMs) });
@@ -48,7 +90,7 @@ async function askCredit(ask, timeoutMs, fetchImpl) {
48
90
  await listed.body?.cancel();
49
91
  return { state: 'unknown', reason: `models HTTP ${listed.status}` };
50
92
  }
51
- const model = ask.pick(modelIds(await listed.json()));
93
+ const model = ask.pick(listedModels(await listed.json()));
52
94
  if (model === null)
53
95
  return { state: 'unknown', reason: 'the key lists no models' };
54
96
  const response = await fetchImpl(ask.url, {
@@ -68,9 +110,9 @@ async function askCredit(ask, timeoutMs, fetchImpl) {
68
110
  return { state: 'unknown', reason: error instanceof Error ? error.message : String(error) };
69
111
  }
70
112
  }
71
- function modelIds(body) {
72
- const data = body?.data;
73
- return Array.isArray(data) ? data.map((model) => model?.id).filter((id) => typeof id === 'string') : [];
113
+ function listedModels(body) {
114
+ const data = record(body).data;
115
+ return Array.isArray(data) ? data.map(record).filter((model) => typeof model.id === 'string') : [];
74
116
  }
75
117
  /**
76
118
  * The credit of the API accounts whose session of a current task stopped on it: checked once per interval while the
@@ -0,0 +1,71 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { currentUser } from './aws.js';
5
+ const ADC_FILE = 'application_default_credentials.json';
6
+ /** The gcloud configuration folder where Google's auth library looks for ADC: `CLOUDSDK_CONFIG` moves it. */
7
+ export function gcloudDir(env, platform = process.platform) {
8
+ if (env.CLOUDSDK_CONFIG !== undefined && env.CLOUDSDK_CONFIG !== '')
9
+ return env.CLOUDSDK_CONFIG;
10
+ if (platform === 'win32')
11
+ return join(env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), 'gcloud');
12
+ return join(homedir(), '.config', 'gcloud');
13
+ }
14
+ /** The Google Cloud credentials of the user Even Keel runs as, for the Vertex form (BTN-823). */
15
+ export function readGcloud(env) {
16
+ const dir = gcloudDir(env);
17
+ const adcFile = join(dir, ADC_FILE);
18
+ const adc = readJson(adcFile);
19
+ const projects = new Set(configProjects(dir));
20
+ if (typeof adc?.quota_project_id === 'string' && adc.quota_project_id !== '')
21
+ projects.add(adc.quota_project_id);
22
+ return {
23
+ user: currentUser(),
24
+ home: homedir(),
25
+ adcFile,
26
+ adcType: typeof adc?.type === 'string' ? adc.type : null,
27
+ environmentFile: env.GOOGLE_APPLICATION_CREDENTIALS || null,
28
+ projects: [...projects],
29
+ };
30
+ }
31
+ /**
32
+ * Whether the credentials file in effect holds a user's sign-in, which an organization's session policy may expire:
33
+ * the account's key file, else the service's `GOOGLE_APPLICATION_CREDENTIALS`, else the ADC file. A service account
34
+ * or a Workload Identity Federation config is not, nor a missing file.
35
+ */
36
+ export function userCredentials(env, keyFile) {
37
+ const file = keyFile ?? (env.GOOGLE_APPLICATION_CREDENTIALS || join(gcloudDir(env), ADC_FILE));
38
+ return readJson(file)?.type === 'authorized_user';
39
+ }
40
+ /** The `project` of every gcloud configuration (`configurations/config_<name>`), as the CLI's own wizard offers them. */
41
+ function configProjects(dir) {
42
+ let names;
43
+ try {
44
+ names = readdirSync(join(dir, 'configurations')).filter((name) => name.startsWith('config_')).sort();
45
+ }
46
+ catch {
47
+ return [];
48
+ }
49
+ const projects = [];
50
+ for (const name of names) {
51
+ let text;
52
+ try {
53
+ text = readFileSync(join(dir, 'configurations', name), 'utf8');
54
+ }
55
+ catch {
56
+ continue;
57
+ }
58
+ for (const match of text.matchAll(/^project\s*=\s*(\S+)/gm))
59
+ projects.push(match[1]);
60
+ }
61
+ return projects;
62
+ }
63
+ function readJson(file) {
64
+ try {
65
+ const value = JSON.parse(readFileSync(file, 'utf8'));
66
+ return typeof value === 'object' && value !== null ? value : null;
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ }
@@ -9,6 +9,9 @@ import { fail } from '../notice/notice.js';
9
9
  import { keyOf, keyVendor, replaceKey, writeKey } from '../opencode/home.js';
10
10
  import { OPENCODE } from '../opencode/name.js';
11
11
  import { samePath } from '../paths.js';
12
+ import { shortLivedProfile } from './aws.js';
13
+ import { userCredentials } from './gcloud.js';
14
+ import { cloudEnv, cloudOf } from './cloud.js';
12
15
  import { KeychainCredentials, keychainService } from './keychain.js';
13
16
  import { CODEX_ACCOUNT, folderName, GLOBAL_ACCOUNT, parseCredentialTimes } from './model.js';
14
17
  import { API_KEY_VARIABLE, shareConfig } from './share.js';
@@ -85,8 +88,18 @@ export class AccountHomes {
85
88
  ...codex.map((name) => this.home(CODEX, name)),
86
89
  ...openCode.map((name) => this.home(OPENCODE, name)),
87
90
  ...copilot.map((name) => this.home(COPILOT, name)),
91
+ ...(this.demo !== null && existsSync(this.demo.dir) ? [this.demo] : []),
88
92
  ];
89
93
  }
94
+ demo = null;
95
+ /**
96
+ * The demo's account folder (BTN-776): listed while it exists, so the chain finds the demo project's account the way
97
+ * it finds any. No project but the demo's names it: an account is always named in a project's settings.
98
+ */
99
+ setDemo(home) {
100
+ this.demo = home;
101
+ this.forget();
102
+ }
90
103
  find(key) {
91
104
  return this.list().find((home) => home.key === key);
92
105
  }
@@ -179,6 +192,24 @@ export class AccountHomes {
179
192
  writeFileSync(join(home.dir, '.claude.json'), JSON.stringify(approved, null, 2));
180
193
  return home;
181
194
  }
195
+ /**
196
+ * A cloud account (BTN-822): a Claude folder whose `settings.json` `env` holds the whole connection, its secrets kept
197
+ * there as an API account's key is. Named like an API account, after the cloud when the name is blank.
198
+ */
199
+ addCloud(name, connection) {
200
+ const home = this.home(CLAUDE, folderName(name.trim() === '' ? connection.cloud : name, this.taken()));
201
+ mkdirSync(home.dir, { recursive: true });
202
+ this.forget();
203
+ writeFileSync(join(home.dir, 'settings.json'), JSON.stringify({ env: cloudEnv(connection) }, null, 2));
204
+ return home;
205
+ }
206
+ /** The cloud a Claude folder's `settings.json` connects to; null for any other folder. */
207
+ cloudOf(home) {
208
+ if (home.agent !== CLAUDE)
209
+ return null;
210
+ const env = objectOf(readObject(join(home.dir, 'settings.json')).env);
211
+ return cloudOf(env, (profile) => shortLivedProfile(this.env, profile), (keyFile) => userCredentials(this.env, keyFile));
212
+ }
182
213
  /**
183
214
  * The trimmed key that may take the place of the folder's own (BTN-418): of the right form, into a folder that holds its
184
215
  * key itself — not the agent's own folder, not one with `apiKeyHelper` — and of the provider of the key it holds.
@@ -308,7 +339,10 @@ export function assertApiKey(key, agent = CLAUDE) {
308
339
  * a classic `ghp_` is refused by the CLI.
309
340
  */
310
341
  const COPILOT_TOKEN = /^(github_pat_|gho_|ghu_)/;
311
- /** Whose key an API account of the agent holds: Codex's is OpenAI's, OpenCode's either, by its prefix, Copilot's GitHub's. */
342
+ /**
343
+ * Whose key an API account of the agent holds: Codex's is OpenAI's, OpenCode's Anthropic's, OpenAI's or OpenRouter's, by
344
+ * its prefix, Copilot's GitHub's.
345
+ */
312
346
  export function keyProvider(agent, key) {
313
347
  if (agent === COPILOT)
314
348
  return 'github';
@@ -2,7 +2,22 @@ const MODELS_URL = 'https://api.anthropic.com/v1/models?limit=1';
2
2
  const OPENAI_MODELS_URL = 'https://api.openai.com/v1/models';
3
3
  const OPENAI_ME_URL = 'https://api.openai.com/v1/me';
4
4
  const GITHUB_USER_URL = 'https://api.github.com/user';
5
+ /**
6
+ * Describes the key that asks, for free: whether it works, what it has spent (`usage`, BTN-860) and what is left of its
7
+ * own limit (BTN-847).
8
+ */
9
+ export const OPENROUTER_KEY_URL = 'https://openrouter.ai/api/v1/key';
5
10
  const API_VERSION = '2023-06-01';
11
+ const LIMIT_RESETS = ['daily', 'weekly', 'monthly'];
12
+ /** The key's own limit from the `data` of `GET /api/v1/key`; null — the key has none, or the answer does not tell it. */
13
+ export function openRouterLimit(data) {
14
+ if (typeof data !== 'object' || data === null)
15
+ return null;
16
+ const { limit, limit_remaining: remaining, limit_reset: reset } = data;
17
+ if (typeof limit !== 'number' || !Number.isFinite(limit) || typeof remaining !== 'number' || !Number.isFinite(remaining))
18
+ return null;
19
+ return { remaining, limit, reset: LIMIT_RESETS.find((each) => each === reset) ?? null };
20
+ }
6
21
  /** Asks Anthropic whether it takes the key: the models list costs no tokens. 401 and 403 are a refused key. */
7
22
  export function checkApiKey(key, timeoutMs, fetchImpl = fetch) {
8
23
  return askModels(MODELS_URL, { 'x-api-key': key, 'anthropic-version': API_VERSION }, timeoutMs, fetchImpl, 'anthropic-organization-id');
@@ -19,6 +34,17 @@ export async function checkOpenAiKey(key, timeoutMs, fetchImpl = fetch) {
19
34
  const me = await askModels(OPENAI_ME_URL, headers, timeoutMs, fetchImpl, 'openai-organization');
20
35
  return me.state === 'ok' && me.organization !== undefined ? me : verdict;
21
36
  }
37
+ /**
38
+ * Whether OpenRouter takes an OpenCode account's key (BTN-843): `/api/v1/key` describes the key for free, its own limit
39
+ * too (BTN-847). OpenRouter has no organization header.
40
+ */
41
+ export async function checkOpenRouterKey(key, timeoutMs, fetchImpl = fetch) {
42
+ return askModels(OPENROUTER_KEY_URL, { authorization: `Bearer ${key}` }, timeoutMs, fetchImpl, undefined, async (response) => {
43
+ const body = await response.json();
44
+ const limit = openRouterLimit(typeof body === 'object' && body !== null ? body.data : null);
45
+ return limit === null ? {} : { limit };
46
+ });
47
+ }
22
48
  /**
23
49
  * Whether GitHub takes a Copilot account's token (BTN-215): `/user` answers any valid token for free. Whether it may make
24
50
  * Copilot requests is not asked — only a session shows that.
@@ -26,7 +52,9 @@ export async function checkOpenAiKey(key, timeoutMs, fetchImpl = fetch) {
26
52
  export function checkGitHubToken(key, timeoutMs, fetchImpl = fetch) {
27
53
  return askModels(GITHUB_USER_URL, { authorization: `Bearer ${key}`, accept: 'application/vnd.github+json', 'user-agent': 'even-keel' }, timeoutMs, fetchImpl);
28
54
  }
29
- async function askModels(url, headers, timeoutMs, fetchImpl, organizationHeader) {
55
+ async function askModels(url, headers, timeoutMs, fetchImpl, organizationHeader,
56
+ /** What a working key's answer tells besides; without it the body is dropped unread, and an unreadable one tells nothing. */
57
+ describe) {
30
58
  let response;
31
59
  try {
32
60
  response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs) });
@@ -34,10 +62,12 @@ async function askModels(url, headers, timeoutMs, fetchImpl, organizationHeader)
34
62
  catch (error) {
35
63
  return { state: 'unknown', reason: error instanceof Error ? error.message : String(error) };
36
64
  }
37
- await response.body?.cancel();
65
+ const told = response.ok && describe !== undefined ? await describe(response).catch(() => ({})) : {};
66
+ if (!(response.ok && describe !== undefined))
67
+ await response.body?.cancel();
38
68
  if (response.ok) {
39
69
  const organization = organizationHeader === undefined ? '' : (response.headers.get(organizationHeader)?.trim() ?? '');
40
- return organization === '' ? { state: 'ok' } : { state: 'ok', organization };
70
+ return organization === '' ? { state: 'ok', ...told } : { state: 'ok', organization, ...told };
41
71
  }
42
72
  if (response.status === 401 || response.status === 403)
43
73
  return { state: 'rejected' };
@@ -47,6 +77,7 @@ async function askModels(url, headers, timeoutMs, fetchImpl, organizationHeader)
47
77
  export class KeyChecks {
48
78
  intervalMs;
49
79
  checked = new Map();
80
+ limits = new Map();
50
81
  constructor(intervalMs) {
51
82
  this.intervalMs = intervalMs;
52
83
  }
@@ -54,14 +85,36 @@ export class KeyChecks {
54
85
  const last = this.checked.get(key);
55
86
  return last === undefined || now.getTime() - last.at >= this.intervalMs;
56
87
  }
88
+ /** True when the verdict or the key's limit changed. */
57
89
  note(key, verdict, now) {
58
- const rejected = verdict.state === 'unknown' ? (this.checked.get(key)?.rejected ?? false) : verdict.state === 'rejected';
90
+ const before = this.rejected(key);
91
+ const rejected = verdict.state === 'unknown' ? before : verdict.state === 'rejected';
59
92
  this.checked.set(key, { at: now.getTime(), rejected });
93
+ const limitChanged = verdict.state !== 'unknown' && this.noteLimit(key, verdict.state === 'ok' ? (verdict.limit ?? null) : null, now);
94
+ return rejected !== before || limitChanged;
95
+ }
96
+ /**
97
+ * A key's limit read between two checks, by a read of its spend (`readOpenRouterKey`); null — the key has none. The
98
+ * next check stays where it was. True when the limit changed.
99
+ */
100
+ noteLimit(key, limit, now) {
101
+ const before = this.limits.get(key);
102
+ const changed = limit === null ? before !== undefined :
103
+ before === undefined || before.remaining !== limit.remaining || before.limit !== limit.limit || before.reset !== limit.reset;
104
+ if (limit === null)
105
+ this.limits.delete(key);
106
+ else
107
+ this.limits.set(key, { ...limit, at: now.toISOString() });
108
+ return changed;
60
109
  }
61
110
  rejected(key) {
62
111
  return this.checked.get(key)?.rejected ?? false;
63
112
  }
113
+ limit(key) {
114
+ return this.limits.get(key) ?? null;
115
+ }
64
116
  forget(key) {
65
117
  this.checked.delete(key);
118
+ this.limits.delete(key);
66
119
  }
67
120
  }
@@ -0,0 +1,41 @@
1
+ /** Tells the account's credits bought and used, only to a management key: the key a session runs on gets 403. */
2
+ const OPENROUTER_CREDITS_URL = 'https://openrouter.ai/api/v1/credits';
3
+ /** The account's balance, `total_credits` less `total_usage`; 401 and 403 are a key that is no management key. */
4
+ export async function readOpenRouterBalance(key, timeoutMs, fetchImpl = fetch) {
5
+ let response;
6
+ try {
7
+ response = await fetchImpl(OPENROUTER_CREDITS_URL, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(timeoutMs) });
8
+ }
9
+ catch (error) {
10
+ return { state: 'unknown', reason: error instanceof Error ? error.message : String(error) };
11
+ }
12
+ if (!response.ok) {
13
+ await response.body?.cancel();
14
+ if (response.status === 401 || response.status === 403)
15
+ return { state: 'rejected' };
16
+ return { state: 'unknown', reason: `HTTP ${response.status}` };
17
+ }
18
+ const body = await response.json().catch(() => null);
19
+ const data = typeof body === 'object' && body !== null ? body.data : null;
20
+ const { total_credits: credits, total_usage: usage } = typeof data === 'object' && data !== null ? data : {};
21
+ if (typeof credits !== 'number' || !Number.isFinite(credits) || typeof usage !== 'number' || !Number.isFinite(usage)) {
22
+ return { state: 'unknown', reason: 'no credits in the answer' };
23
+ }
24
+ return { state: 'ok', usd: Math.round((credits - usage) * 1e6) / 1e6 };
25
+ }
26
+ /**
27
+ * The management key of each OpenRouter account, kept out of the account's folder that its sessions read (BTN-868).
28
+ * Keyed by the account folder's key; table `management_keys` (step 37, `docs/storage.md`).
29
+ */
30
+ export async function loadManagementKeys(db) {
31
+ const { rows } = await db.query('select account, key from management_keys order by account');
32
+ return new Map(rows.map((row) => [row.account, row.key]));
33
+ }
34
+ /** Starts its write at the call: see `Writes`. */
35
+ export async function saveManagementKey(db, account, key, at) {
36
+ await db.query(`insert into management_keys (account, key, saved_at) values ($1, $2, $3)
37
+ on conflict (account) do update set key = excluded.key, saved_at = excluded.saved_at`, [account, key, at.toISOString()]);
38
+ }
39
+ export async function forgetManagementKey(db, account) {
40
+ await db.query('delete from management_keys where account = $1', [account]);
41
+ }
@@ -39,9 +39,17 @@ export function parseAuthStatus(text) {
39
39
  export function isApiKey(status) {
40
40
  return status?.authMethod === 'api_key' || status?.authMethod === 'api_key_helper';
41
41
  }
42
- /** An API account has no e-mail: its folder key stands in for it wherever an account is told apart by e-mail. */
42
+ /** A cloud account (BTN-822): the CLI says `third_party` for a folder whose `settings.json` turns a cloud on. */
43
+ export function isCloud(status) {
44
+ return status?.authMethod === 'third_party';
45
+ }
46
+ /** A key or a cloud pays per token: no plan limits, no claude.ai sign-in to renew or sign out of. */
47
+ export function paysPerToken(status) {
48
+ return isApiKey(status) || isCloud(status);
49
+ }
50
+ /** An API or cloud account has no e-mail: its folder key stands in for it wherever an account is told apart by e-mail. */
43
51
  export function withIdentity(status, key) {
44
- return status.loggedIn && status.email === null && isApiKey(status) ? { ...status, email: key } : status;
52
+ return status.loggedIn && status.email === null && paysPerToken(status) ? { ...status, email: key } : status;
45
53
  }
46
54
  export function cleanOutput(raw) {
47
55
  return stripAnsi(raw).replace(/\r\n?/g, '\n');
@@ -1,14 +1,19 @@
1
1
  import { CODEX } from '../codex/name.js';
2
2
  import { COPILOT } from '../copilot/name.js';
3
+ import { keyVendor } from '../opencode/home.js';
3
4
  import { OPENCODE } from '../opencode/name.js';
4
5
  const CLAUDE_API = 'https://api.anthropic.com';
5
6
  const OPENAI_API = 'https://api.openai.com';
6
7
  const OPENCODE_API = 'https://opencode.ai';
7
8
  const GITHUB_API = 'https://api.github.com';
8
- /** The API the agent's sign-in renews its tokens against: account calls wait until it answers (EKR-15). */
9
- export function providerUrl(agent) {
9
+ const OPENROUTER_API = 'https://openrouter.ai';
10
+ /**
11
+ * The API the agent's sign-in renews its tokens against: account calls wait until it answers (EKR-15). An OpenCode
12
+ * folder on an OpenRouter key, `key`, talks only to OpenRouter (BTN-843).
13
+ */
14
+ export function providerUrl(agent, key = null) {
10
15
  if (agent === OPENCODE)
11
- return OPENCODE_API;
16
+ return key !== null && keyVendor(key) === 'openrouter' ? OPENROUTER_API : OPENCODE_API;
12
17
  if (agent === COPILOT)
13
18
  return GITHUB_API;
14
19
  return agent === CODEX ? OPENAI_API : CLAUDE_API;
@@ -1,17 +1,26 @@
1
- import { checkCredit, checkOpenAiCredit } from './credit.js';
2
- import { checkApiKey, checkGitHubToken, checkOpenAiKey } from './keycheck.js';
1
+ import { checkCredit, checkOpenAiCredit, checkOpenRouterCredit } from './credit.js';
2
+ import { checkApiKey, checkGitHubToken, checkOpenAiKey, checkOpenRouterKey } from './keycheck.js';
3
3
  export const KEY_CHECK_MS = 60 * 60_000;
4
4
  export const KEY_CHECK_TIMEOUT_MS = 15_000;
5
5
  export const CREDIT_CHECK_MS = 5 * 60_000;
6
+ /** The OpenRouter key's `usage` is read before a turn too: a short wait, a missed read only moves the growth on (BTN-860). */
7
+ export const KEY_SPEND_TIMEOUT_MS = 5_000;
8
+ /** How long after the last turn a growth of `usage` still goes to its session, and how often the key is read meanwhile. */
9
+ export const KEY_SPEND_TAIL_MS = 10 * 60_000;
10
+ export const KEY_SPEND_POLL_MS = 60_000;
6
11
  /**
7
12
  * The key and credit checks by whose key it is (`keyProvider`). GitHub has no way to ask about a token's AI credits: a
8
13
  * Copilot account waits out spent credit by its monthly allowance instead (`Agent.keyUsage`, BTN-341).
9
14
  */
10
- export const KEY_CHECKS = { anthropic: checkApiKey, openai: checkOpenAiKey, github: checkGitHubToken };
15
+ export const KEY_CHECKS = { anthropic: checkApiKey, openai: checkOpenAiKey, openrouter: checkOpenRouterKey, github: checkGitHubToken };
11
16
  export const CREDIT_CHECKS = {
12
17
  anthropic: checkCredit,
13
18
  openai: checkOpenAiCredit,
19
+ openrouter: checkOpenRouterCredit,
14
20
  github: async () => ({ state: 'unknown', reason: 'GitHub does not tell the AI credits of a token' }),
15
21
  };
22
+ /** The check turn of a new cloud account: the CLI gives up resolving AWS credentials after 60 s itself. */
23
+ export const CLOUD_CHECK_TIMEOUT_MS = 120_000;
24
+ export const CLOUD_CHECK_PROMPT = 'This is a connection check. Reply with the single word OK and use no tools.';
16
25
  export const APP_POLL_MS = 5_000;
17
26
  export const LOGIN_TIMEOUT_MS = 10 * 60_000;
@@ -1,5 +1,6 @@
1
1
  import { copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, rmdirSync, symlinkSync, unlinkSync, writeFileSync, } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
+ import { cloudOf, isCloudVariable } from './cloud.js';
3
4
  import { pathKey, sameSpelling } from '../paths.js';
4
5
  import { projectDirName } from '../sessions/paths.js';
5
6
  const PROJECT_KEYS = [
@@ -18,12 +19,21 @@ const LINKED_DIRS = ['agents', 'commands', 'hooks', 'output-styles'];
18
19
  const OWN_SKILLS = new Set(['synced', '.trash']);
19
20
  export const API_KEY_VARIABLE = 'ANTHROPIC_API_KEY';
20
21
  const COPIED_FILES = ['CLAUDE.md', join('plugins', 'installed_plugins.json'), join('plugins', 'known_marketplaces.json')];
21
- /** The global settings win, except the folder's own API key: it is what makes an API account (`docs/accounts.md`). */
22
+ /**
23
+ * The global settings win, except the folder's own API key and cloud connection: they are what makes an API or a cloud
24
+ * account (`docs/accounts.md`). A cloud folder takes none of the cloud's variables from the global settings.
25
+ */
22
26
  export function mergeSettings(global, folder) {
23
27
  const merged = { ...folder, ...global };
24
- const key = objectOf(folder?.env)[API_KEY_VARIABLE];
28
+ const own = objectOf(folder?.env);
29
+ const key = own[API_KEY_VARIABLE];
25
30
  if (typeof key === 'string')
26
31
  merged.env = { ...objectOf(global.env), [API_KEY_VARIABLE]: key };
32
+ if (cloudOf(own) !== null) {
33
+ const shared = Object.fromEntries(Object.entries(objectOf(merged.env ?? global.env)).filter(([name]) => !isCloudVariable(name)));
34
+ const cloud = Object.fromEntries(Object.entries(own).filter(([name]) => isCloudVariable(name)));
35
+ merged.env = { ...shared, ...cloud };
36
+ }
27
37
  if (folder?.apiKeyHelper !== undefined)
28
38
  merged.apiKeyHelper = folder.apiKeyHelper;
29
39
  return merged;
@@ -0,0 +1,155 @@
1
+ import { OPENROUTER_KEY_URL, openRouterLimit } from './keycheck.js';
2
+ /**
3
+ * Reads an OpenRouter key's description of itself, which any key may read (BTN-860, BTN-847); `null` — no answer, an
4
+ * error or a body that is no description.
5
+ */
6
+ export async function readOpenRouterKey(key, timeoutMs, fetchImpl = fetch) {
7
+ try {
8
+ const response = await fetchImpl(OPENROUTER_KEY_URL, { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(timeoutMs) });
9
+ if (!response.ok) {
10
+ await response.body?.cancel();
11
+ return null;
12
+ }
13
+ const body = await response.json();
14
+ const data = typeof body === 'object' && body !== null ? body.data : undefined;
15
+ if (typeof data !== 'object' || data === null)
16
+ return null;
17
+ const usage = data.usage;
18
+ return { usage: typeof usage === 'number' && Number.isFinite(usage) ? usage : null, limit: openRouterLimit(data) };
19
+ }
20
+ catch {
21
+ return null;
22
+ }
23
+ }
24
+ /**
25
+ * The real spend of the sessions on a key that tells it (BTN-860, `docs/tally.md`, "Cost"): the key is read before each
26
+ * turn, at each turn's end and during a tail after the last turn, and the growth between two reads goes to the session
27
+ * that ran in between, or to the last one while its tail lasts. Two sessions in one interval, or busy at once, cannot
28
+ * be told apart: both are marked shared and keep only the estimate by price.
29
+ */
30
+ export class KeySpend {
31
+ options;
32
+ meters = new Map();
33
+ shared = new Set();
34
+ constructor(options) {
35
+ this.options = options;
36
+ }
37
+ /** Reads the key before a turn starts, so what was spent before goes to whoever spent it. */
38
+ async beforeTurn(account) {
39
+ if (!this.options.metered(account))
40
+ return;
41
+ await this.read(account, this.meter(account));
42
+ }
43
+ /** One tick of the session monitor: every session it sees, of every account. */
44
+ observe(entries) {
45
+ const now = this.options.now();
46
+ const busyOf = new Map();
47
+ for (const entry of entries) {
48
+ if (!this.options.metered(entry.account))
49
+ continue;
50
+ const busy = busyOf.get(entry.account) ?? new Set();
51
+ if (entry.busy)
52
+ busy.add(entry.sessionId);
53
+ busyOf.set(entry.account, busy);
54
+ }
55
+ for (const account of this.meters.keys())
56
+ if (!busyOf.has(account) && this.options.metered(account))
57
+ busyOf.set(account, new Set());
58
+ for (const [account, busy] of busyOf) {
59
+ if (busy.size === 0 && !this.meters.has(account))
60
+ continue;
61
+ const meter = this.meter(account);
62
+ // Busy before any read of the key: the turn began before the service started or with its read failed, and
63
+ // the spend up to the first read is lost, so the session keeps the estimate (BTN-871).
64
+ if (busy.size > 1 || (busy.size > 0 && meter.usage === null))
65
+ this.markShared(account, busy);
66
+ for (const sessionId of busy)
67
+ meter.ran.add(sessionId);
68
+ const ended = [...meter.busy].some((sessionId) => !busy.has(sessionId));
69
+ meter.busy = busy;
70
+ if (ended) {
71
+ meter.endedAt = now;
72
+ void this.read(account, meter);
73
+ }
74
+ else if (busy.size === 0 && meter.endedAt !== null) {
75
+ if (now - meter.endedAt > this.options.tailMs) {
76
+ meter.endedAt = null;
77
+ meter.last = null;
78
+ }
79
+ else if (now - meter.triedAt >= this.options.pollMs)
80
+ void this.read(account, meter);
81
+ }
82
+ }
83
+ }
84
+ /** Every read asked for so far has been made. */
85
+ async settled() {
86
+ await Promise.all([...this.meters.values()].map((meter) => meter.reads));
87
+ }
88
+ meter(account) {
89
+ let meter = this.meters.get(account);
90
+ if (meter === undefined) {
91
+ meter = { usage: null, ran: new Set(), busy: new Set(), last: null, endedAt: null, triedAt: 0, reads: Promise.resolve(), queued: null };
92
+ this.meters.set(account, meter);
93
+ }
94
+ return meter;
95
+ }
96
+ read(account, meter) {
97
+ if (meter.queued !== null)
98
+ return meter.queued;
99
+ const queued = meter.reads.then(async () => {
100
+ meter.queued = null;
101
+ const owners = meter.ran;
102
+ meter.ran = new Set(meter.busy);
103
+ meter.triedAt = this.options.now();
104
+ const usage = await this.options.read(account).catch(() => null);
105
+ if (usage === null) {
106
+ for (const sessionId of owners)
107
+ meter.ran.add(sessionId);
108
+ return;
109
+ }
110
+ this.settle(account, meter, owners, usage);
111
+ });
112
+ meter.queued = queued;
113
+ meter.reads = queued;
114
+ return queued;
115
+ }
116
+ settle(account, meter, ran, usage) {
117
+ const owners = ran.size > 0 ? ran : meter.last === null ? new Set() : new Set([meter.last]);
118
+ const growth = meter.usage === null ? 0 : usage - meter.usage;
119
+ meter.usage = usage;
120
+ if (owners.size > 1) {
121
+ this.markShared(account, owners);
122
+ meter.last = null;
123
+ return;
124
+ }
125
+ const [owner] = owners;
126
+ if (owner === undefined)
127
+ return;
128
+ meter.last = owner;
129
+ if (growth > 0 && !this.shared.has(owner)) {
130
+ this.options.onSpend({ sessionId: owner, account, usd: growth, shared: false, at: new Date(this.options.now()).toISOString() });
131
+ }
132
+ }
133
+ markShared(account, sessions) {
134
+ for (const sessionId of sessions) {
135
+ if (this.shared.has(sessionId))
136
+ continue;
137
+ this.shared.add(sessionId);
138
+ this.options.onSpend({ sessionId, account, usd: 0, shared: true, at: new Date(this.options.now()).toISOString() });
139
+ }
140
+ }
141
+ }
142
+ /**
143
+ * Adds a growth to the session's row of `key_spends` (step 35, `docs/storage.md`): the sum grows in SQL, so a write
144
+ * behind never loses another. Starts its write at the call: see `Writes`.
145
+ */
146
+ export async function saveKeySpend(db, growth) {
147
+ await db.query(`insert into key_spends (session_id, account, usd, shared, reads, first_at, last_at) values ($1, $2, $3, $4, 1, $5, $5)
148
+ on conflict (session_id) do update set usd = key_spends.usd + excluded.usd, shared = key_spends.shared or excluded.shared,
149
+ reads = key_spends.reads + 1, last_at = excluded.last_at`, [growth.sessionId, growth.account, growth.usd, growth.shared, growth.at]);
150
+ }
151
+ export async function readKeySpends(db) {
152
+ const { rows } = await db.query('select session_id, account, usd, shared, first_at, last_at from key_spends order by first_at, session_id');
153
+ const iso = (value) => new Date(value).toISOString();
154
+ return rows.map((row) => ({ sessionId: row.session_id, account: row.account, usd: Number(row.usd), shared: row.shared, firstAt: iso(row.first_at), lastAt: iso(row.last_at) }));
155
+ }