opencode-account-quota 0.0.0-stage → 0.1.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.
package/server.js ADDED
@@ -0,0 +1,617 @@
1
+ // Server half of Account Quota (S07, S08, S15). index.js builds the shipped plugin with the contract from
2
+ // rpc.js; the HOST lab builds the same plugin with synthetic readers through createPlugin(), and node tests
3
+ // pass a stand-in contract because only the host resolves "@opencode/plugin/rpc". There is no test switch,
4
+ // no configurable endpoint and no way for a client to name anything beyond a reference from this inventory.
5
+ import { INTEGRATION as CLAUDE, STEP_EVENTS, createState, createTurns, invalidates, loginsOf, soleRow } from "./claude.js"
6
+ import { inventorySnapshot, isAccountReference, isRef } from "./inventory.js"
7
+ import { KEY, ROUTING_KEY, parseRouting, parseStored, proposal, reconcile, routingProposal } from "./preferences.js"
8
+ import { decideRoute } from "./routing.js"
9
+ import { TURN_END, USAGE_FRESHNESS, createCache, freshness, usageFreshness, validSample } from "./rules.js"
10
+
11
+ const nativeEvents = ["credential.updated", "credential.switched", "integration.updated"]
12
+ const ROUTE_EVENTS = ["session.step.started", "session.execution.started", "session.execution.succeeded", "session.execution.failed"]
13
+ // 2.4.1 publishes it (rotation plan O1); its own subscription, in case an older host refuses the type.
14
+ const SELECTED = ["session.model.selected"]
15
+ const scope = "personal-server"
16
+ const maxRef = 200
17
+ const maxListed = 64
18
+ const maxReads = 2 // external reads in flight for the whole server (S01 §11)
19
+ const backoff = (failures) => Math.min(15 * 60_000, 15_000 * 2 ** (failures - 1))
20
+ // An unbounded Retry-After would leave the account unable to refresh for days, until OpenCode restarts.
21
+ const maxWait = 60 * 60_000
22
+ // Route decisions (rotation plan §4): a decision reads at most the origin once and two candidates, one after the other,
23
+ // and is abandoned after `decisionMs` (an initial value to rehearse, not a provider promise).
24
+ const decisionMs = 5_000
25
+ // How long a snapshot waits at most for a Claude step end still being attributed, so a read made at a turn end (the
26
+ // TUI reads just before evaluating its notice) carries that turn's usage.
27
+ const attributionMs = 500
28
+ const decisionBudget = { origin: 1, candidates: 2 }
29
+ const keepDecisions = 64
30
+ const createRouting = () => ({ sessions: new Map(), seen: [], models: new Map(), checks: new Map() })
31
+
32
+ // A server loads one instance per location, all in this process. They share the revision, the event fan-out,
33
+ // the measurement cache, reads in flight and the single preference writer: that is the personal-server scope.
34
+ // There is no global event counter: a read is kept or dropped by checking its own reference, never because some
35
+ // other account changed meanwhile.
36
+ const shared = (globalThis[Symbol.for("account-quota.server.v6")] ??= {
37
+ revision: 0,
38
+ emitters: new Set(),
39
+ timer: undefined,
40
+ lock: Promise.resolve(),
41
+ cache: createCache(),
42
+ inflight: new Map(),
43
+ failuresInRow: new Map(),
44
+ reading: 0,
45
+ waiting: [],
46
+ stop: new AbortController(),
47
+ claude: createState(),
48
+ })
49
+ // A hot reload can reuse an older v6 object; upgrade it in place so existing instances keep the same scheduler.
50
+ shared.until ??= new Map()
51
+ shared.epochs ??= new Map()
52
+ shared.routing ??= createRouting()
53
+ shared.routing.checks ??= new Map()
54
+
55
+ const integrations = new Set(["openai", "deepseek", "anthropic", "claude-agent"])
56
+
57
+ // Claude's passive usage (E02) is dropped as soon as it can no longer be attributed to the single profile; a step
58
+ // end whose checks are still running when this happens records nothing.
59
+ function forgetClaude() {
60
+ shared.claude.generation += 1
61
+ shared.cache.forget(CLAUDE)
62
+ }
63
+
64
+ // Coalesces simultaneous native events (each location receives the same global event) into one revision.
65
+ export function invalidate() {
66
+ if (shared.timer !== undefined) return
67
+ shared.timer = setTimeout(() => {
68
+ shared.timer = undefined
69
+ shared.revision += 1
70
+ for (const emit of shared.emitters) emit(shared.revision)
71
+ }, 25)
72
+ }
73
+
74
+ // One writer per server: every preference write runs after the previous one and re-reads the stored revision,
75
+ // so two clients with the same revision cannot both succeed, whatever their location.
76
+ function exclusive(task) {
77
+ const run = shared.lock.then(task)
78
+ shared.lock = run.catch(() => {})
79
+ return run
80
+ }
81
+
82
+ // At most `maxReads` reads in flight for the whole server; the rest wait in order. A read whose server stopped
83
+ // while it waited is never started: it settles at once and hands its turn on, so nothing is left pending.
84
+ // A read whose every requester has given up while it waited (`wanted()` false: a route decision that expired) is not
85
+ // started either: work that already expired is never sent.
86
+ function limited(signal, task, wanted = () => true) {
87
+ return new Promise((resolve, reject) => {
88
+ const start = () => {
89
+ if (signal.aborted || !wanted()) {
90
+ reject(signal.aborted ? { reason: "unknown" } : { expired: true })
91
+ if (shared.reading < maxReads) shared.waiting.shift()?.()
92
+ return
93
+ }
94
+ shared.reading += 1
95
+ Promise.resolve().then(task).then(resolve, reject).finally(() => {
96
+ shared.reading -= 1
97
+ shared.waiting.shift()?.()
98
+ })
99
+ }
100
+ if (shared.reading < maxReads) start()
101
+ else shared.waiting.push(start)
102
+ })
103
+ }
104
+
105
+ // The native row of exactly this saved connection, read again from the inventory: still listed once under its
106
+ // integration, with the same login method and no pending sign-in. Anything else (removed, replaced, signed out,
107
+ // unreadable) is undefined. Used by readers bound to one login before its credential is touched and after the answer.
108
+ async function liveRow(ctx, integrationID, connectionID, method) {
109
+ try {
110
+ const info = (await ctx.integration.list())?.data?.find((item) => item?.id === integrationID)
111
+ const rows = Array.isArray(info?.connections) ? info.connections.filter((row) => row?.type === "credential" && row.id === connectionID) : []
112
+ const row = rows.length === 1 ? rows[0] : undefined
113
+ return row && row.method === method && row.status?.status !== "needs_auth" ? row : undefined
114
+ } catch {
115
+ return undefined
116
+ }
117
+ }
118
+
119
+ function bounded(snapshot) {
120
+ const fits =
121
+ snapshot.integrations.length <= maxListed &&
122
+ snapshot.integrations.every((item) => isRef(item.id) && item.connections.length <= maxListed)
123
+ if (!fits) return { ...snapshot, inventory: "unavailable", integrations: [] }
124
+ const clip = (label) => (label.length <= maxRef ? label : label.slice(0, maxRef - 1) + "…")
125
+ return {
126
+ ...snapshot,
127
+ integrations: snapshot.integrations.map((item) => ({
128
+ ...item,
129
+ connections: item.connections.map((connection) => ({ ...connection, label: clip(connection.label) })),
130
+ })),
131
+ }
132
+ }
133
+
134
+ async function readPreferences(ctx) {
135
+ try {
136
+ return parseStored(await ctx.storage.get(KEY))
137
+ } catch {
138
+ return { state: "unavailable" }
139
+ }
140
+ }
141
+
142
+ // Measurements of one connection as the DTO carries them: no account fields, no raw payloads.
143
+ function measured(integrationID, connectionID) {
144
+ const { samples, failures } = shared.cache.list()
145
+ const own = (item) => item.integrationID === integrationID && item.connectionID === connectionID
146
+ const strip = ({ integrationID: _i, connectionID: _c, ...rest }) => rest
147
+ let mine = samples.filter(own)
148
+ // Claude's two sources (passive turns, manual /usage) share one cache: the most recent sample of each window wins.
149
+ if (integrationID === CLAUDE) {
150
+ const newest = new Map()
151
+ for (const s of mine) {
152
+ const key = JSON.stringify([s.window, s.scope])
153
+ if (!newest.has(key) || newest.get(key).observedAt < s.observedAt) newest.set(key, s)
154
+ }
155
+ mine = [...newest.values()]
156
+ }
157
+ const list = mine.slice(0, 16).map(strip)
158
+ const failure = failures.filter(own).sort((a, b) => b.at - a.at)[0]
159
+ return { ...(list.length > 0 ? { samples: list } : {}), ...(failure ? { failure: strip(failure) } : {}) }
160
+ }
161
+
162
+ // Personal-server authorization (user decision, S01 §1): every saved credential natively listed by this
163
+ // server is visible to its clients. Nothing from the request widens or narrows that set. `passive` names the
164
+ // integrations measured from the user's own turns (Claude, E02, with its option on): flagged in the DTO, and their
165
+ // data is shown only there and only while the inventory still has one signed-in profile to attribute it to.
166
+ // `usage` is the usage freshness of the location instance answering (seconds), which the DTO carries for its TUI.
167
+ // `stored` is the readPreferences() result a caller already holds; without it the preferences are read here.
168
+ export async function readServer(ctx, readers = new Map(), passive = new Set(), usage = USAGE_FRESHNESS, stored) {
169
+ const revision = shared.revision
170
+ stored ??= await readPreferences(ctx)
171
+ const preferences = stored.state === "available"
172
+ ? { state: "available", revision: stored.value.revision, mode: stored.value.mode, threshold: stored.value.threshold, minimums: stored.value.minimums }
173
+ : { state: stored.state }
174
+ let listed
175
+ try {
176
+ listed = (await ctx.integration.list())?.data
177
+ } catch {
178
+ listed = undefined
179
+ }
180
+ const base = { revision, scope, usageFreshnessSeconds: usageFreshness(usage), preferences }
181
+ if (!Array.isArray(listed)) return { snapshot: { ...inventorySnapshot(), schema: 2, ...base }, native: new Map() }
182
+ const kept = []
183
+ for (const info of listed) {
184
+ if (!integrations.has(info?.id) || !Array.isArray(info.connections)) continue
185
+ const saved = info.connections.filter((row) => row?.type === "credential" && isRef(row.id))
186
+ if (saved.length === 0 && !info.connections.some(row => row?.type === "env")) continue
187
+ kept.push({ info, saved })
188
+ }
189
+ // The active connection of every listed integration, asked at once; one that cannot be read does not hold the others.
190
+ const actives = await Promise.all(kept.map(async ({ info }) => {
191
+ try {
192
+ return (await ctx.integration.connection.active(info.id)) ?? null
193
+ } catch {
194
+ return { type: "unreadable" }
195
+ }
196
+ }))
197
+ const reads = []
198
+ const native = new Map()
199
+ for (const [i, { info, saved }] of kept.entries()) {
200
+ reads.push({ integrationID: info.id, connections: info.connections, active: actives[i] })
201
+ native.set(info.id, saved)
202
+ }
203
+ const inventory = inventorySnapshot(reads)
204
+ // None, several or a login waiting for a sign-in: nothing left to attribute Claude's data to.
205
+ if (passive.has(CLAUDE) && !soleRow(loginsOf(listed))) forgetClaude()
206
+ const order = stored.state === "available" ? stored.value.order : {}
207
+ inventory.integrations = inventory.integrations.map((item) => {
208
+ const ids = reconcile(order[item.id], item.connections.map((c) => c.id))
209
+ const connections = ids.map((id) => item.connections.find((c) => c.id === id))
210
+ const manual = readers.get(item.id)?.manual === true ? { manual: true } : {}
211
+ const flag = passive.has(item.id) ? { passive: true } : {}
212
+ const shown = item.id !== CLAUDE || passive.has(CLAUDE)
213
+ return { ...item, refreshable: readers.has(item.id), ...manual, ...flag,
214
+ connections: connections.map((c) => ({ ...c, ...(shown ? measured(item.id, c.id) : {}) })) }
215
+ })
216
+ return { snapshot: bounded({ ...inventory, schema: 2, ...base }), native }
217
+ }
218
+
219
+ async function refresh(ctx, readers, input, call, now) {
220
+ const unknown = () => call.error("not_found", "Unknown account reference.", {})
221
+ // An explicit Refresh says so with `manual: true`; the reads started by opening the view never do.
222
+ const { manual, ...reference } = input !== null && typeof input === "object" ? input : {}
223
+ if (!isAccountReference(reference) || (manual !== undefined && manual !== true)) return unknown()
224
+ const { integrationID, connectionID } = reference
225
+ const { snapshot, native } = await readServer(ctx, readers)
226
+ const shown = snapshot.integrations
227
+ .find((item) => item.id === integrationID)
228
+ ?.connections.find((item) => item.id === connectionID)
229
+ const row = shown ? native.get(integrationID)?.find((item) => item.id === connectionID) : undefined
230
+ if (!row) return unknown()
231
+ const reader = readers.get(integrationID)
232
+ // A manual reader answers only an explicit Refresh. A reader bound to one login does not read a connection that
233
+ // waits for a sign-in: the native state already says Reconnect required. Active or not makes no difference.
234
+ if (!reader || (reader.manual && manual !== true) || (reader.bound && shown.reconnectRequired)) {
235
+ return { revision: snapshot.revision, status: "unsupported" }
236
+ }
237
+ const status = await schedule(ctx, reader, integrationID, row, now)
238
+ return { revision: status === "deferred" ? snapshot.revision : shared.revision, status }
239
+ }
240
+
241
+ // One read of one connection through the shared scheduler: shared while in flight (same connection and source),
242
+ // deferred while a failure's wait runs, at most `maxReads` at once for the server, never retried by itself.
243
+ // Resolves to "read", "failed" or "deferred" and never rejects, so callers that ask for several accounts at once
244
+ // get one answer per account and one failure cannot cancel the others.
245
+ // `until` is the instant after which a route decision no longer wants this read; a user, the view or anyone else that
246
+ // leaves it out wants it whatever the time. A read that waited past every requester's deadline resolves "expired"
247
+ // without starting, recording a failure or a retry wait.
248
+ function schedule(ctx, reader, integrationID, row, now, until = Infinity) {
249
+ const connectionID = row.id
250
+ const ref = { integrationID, connectionID, source: reader.source }
251
+ const key = JSON.stringify([integrationID, connectionID, reader.source])
252
+ let run = shared.inflight.get(key)
253
+ if (run) shared.until.set(key, Math.max(shared.until.get(key) ?? -Infinity, until))
254
+ if (!run) {
255
+ const last = shared.cache.list().failures.find((f) => JSON.stringify([f.integrationID, f.connectionID, f.source]) === key)
256
+ if (last?.retryAt > now()) return Promise.resolve("deferred")
257
+ const { signal } = shared.stop
258
+ // The reader gets this connection and a resolver bound to it, never the active one by default. A reader bound
259
+ // to one login (`bound`) gets the row as listed when its turn comes: one removed, replaced or signed out while
260
+ // it waited in the queue is not resolved and nothing is sent for it.
261
+ run = limited(signal, async () => {
262
+ const live = reader.bound ? await liveRow(ctx, integrationID, connectionID, row.method) : row
263
+ if (!live) throw { reason: "changed" }
264
+ const result = await reader.read({ ctx, connection: live, resolve: () => ctx.integration.connection.resolve(live), signal })
265
+ // The answer belongs to the reference it was asked for, never to whichever account is active when it
266
+ // arrives. The reader already checked that the same login (method and account) is still behind the
267
+ // reference; here the reference itself must still be listed the same way. Another account becoming active
268
+ // meanwhile changes neither, so its reading stays with it.
269
+ if (reader.bound && !signal.aborted && !(await liveRow(ctx, integrationID, connectionID, row.method))) throw { reason: "changed" }
270
+ return result
271
+ }, () => now() < (shared.until.get(key) ?? Infinity))
272
+ .then(async (result) => {
273
+ if (signal.aborted) return "failed"
274
+ // One sample or several (one per window), recorded together or not at all.
275
+ const samples = [result].flat().map((sample) => ({ ...sample, ...ref }))
276
+ // A reader that may answer "no data" (Claude /usage without plan rows): what was held for it is withdrawn.
277
+ if (samples.length === 0 && reader.empty === true && Array.isArray(result)) {
278
+ if (integrationID === CLAUDE) forgetClaude()
279
+ shared.failuresInRow.delete(key)
280
+ return "read"
281
+ }
282
+ if (samples.length === 0 ||!samples.every(validSample) || !samples.map((s) => shared.cache.record(s)).every(Boolean)) {
283
+ throw { reason: "invalid" }
284
+ }
285
+ shared.failuresInRow.delete(key)
286
+ return "read"
287
+ })
288
+ .catch((error) => {
289
+ if (signal.aborted) return "failed"
290
+ if (error?.expired === true) return "expired"
291
+ const failures = (shared.failuresInRow.get(key) ?? 0) + 1
292
+ shared.failuresInRow.set(key, failures)
293
+ const at = now()
294
+ const wait = Math.min(maxWait, Math.max(Number.isFinite(error?.retryAfter) ? error.retryAfter : 0, backoff(failures)))
295
+ shared.cache.fail(ref, at, typeof error?.reason === "string" ? error.reason : "unknown", at + wait)
296
+ return "failed"
297
+ })
298
+ .finally(() => {
299
+ if (shared.inflight.get(key) === run) {
300
+ shared.inflight.delete(key)
301
+ shared.until.delete(key)
302
+ }
303
+ invalidate()
304
+ })
305
+ shared.inflight.set(key, run)
306
+ shared.until.set(key, until)
307
+ }
308
+ // Someone who still wants the data (a user's Refresh that arrived just as an expired decision's queued read gave up)
309
+ // asks again: it gets a read of its own, never the decision's "expired".
310
+ return run.then((status) => (status === "expired" && now() < until ? schedule(ctx, reader, integrationID, row, now, until) : status))
311
+ }
312
+
313
+ async function savePreferences(ctx, input, call) {
314
+ return exclusive(async () => {
315
+ const unavailable = () => call.error("unavailable", "Preferences are unavailable.", {})
316
+ const stored = await readPreferences(ctx)
317
+ if (stored.state !== "available") return unavailable()
318
+ const { snapshot } = await readServer(ctx, undefined, undefined, undefined, stored)
319
+ if (snapshot.inventory !== "available") return unavailable()
320
+ const next = proposal(input, stored.value, snapshot.integrations)
321
+ if (next.error === "conflict") return call.error("conflict", "Preferences changed. Reload before saving.", {})
322
+ if (next.error) return call.error("invalid", "Invalid preferences.", {})
323
+ await ctx.storage.set(KEY, next.value)
324
+ invalidate()
325
+ return { revision: next.value.revision }
326
+ })
327
+ }
328
+
329
+ async function readRouting(ctx) {
330
+ try {
331
+ return parseRouting(await ctx.storage.get(ROUTING_KEY))
332
+ } catch {
333
+ return { state: "unavailable" }
334
+ }
335
+ }
336
+
337
+ // Same single writer as the priorities, under its own key and revision: saving one never rewrites the other.
338
+ async function saveRouting(ctx, input, call) {
339
+ return exclusive(async () => {
340
+ const unavailable = () => call.error("unavailable", "Route order is unavailable.", {})
341
+ const stored = await readRouting(ctx)
342
+ if (stored.state !== "available") return unavailable()
343
+ const { snapshot } = await readServer(ctx)
344
+ if (snapshot.inventory !== "available") return unavailable()
345
+ const next = routingProposal(input, stored.value, snapshot.integrations)
346
+ if (next.error === "conflict") return call.error("conflict", "Route order changed. Reload before saving.", {})
347
+ if (next.error) return call.error("invalid", "Invalid route order.", {})
348
+ await ctx.storage.set(ROUTING_KEY, next.value)
349
+ invalidate()
350
+ return { revision: next.value.revision }
351
+ })
352
+ }
353
+
354
+ // What a client may see of a decision: statuses, reasons and row indexes. No account data, no samples.
355
+ const short = (text) => text.slice(0, 120)
356
+ const decisionView = (d) => ({
357
+ at: d.at, kind: d.kind, reads: d.reads,
358
+ ...(d.target !== undefined ? { target: d.target } : {}), ...(d.reason ? { reason: short(d.reason) } : {}),
359
+ ...(d.trigger ? { trigger: short(d.trigger) } : {}), ...(d.manual ? { manual: true } : {}),
360
+ rows: d.rows.slice(0, 64).map((r) => ({ status: r.status, ...(r.reason ? { reason: short(r.reason) } : {}) })),
361
+ })
362
+
363
+ async function routingView(ctx, input) {
364
+ const stored = await readRouting(ctx)
365
+ const base = stored.state === "available"
366
+ ? { state: "available", revision: stored.value.revision, targets: stored.value.targets }
367
+ : { state: stored.state }
368
+ const sessionID = input?.sessionID
369
+ const state = isRef(sessionID) ? shared.routing.sessions.get(sessionID) : undefined
370
+ if (!state) return { ...base, ...(isRef(sessionID) ? { session: { mode: "off", paid: false } } : {}) }
371
+ return { ...base, session: { mode: state.mode, paid: state.paid, ...(state.decision ? { decision: decisionView(state.decision) } : {}) } }
372
+ }
373
+
374
+ // Only a root session this server can read. `preview` watches the session's own turn ends; there is no automatic mode
375
+ // in this build. Turning a session off cancels its pending decision; a read it started may still feed the cache.
376
+ // The session keeps the usage freshness (`usage`, seconds), readers and passive integrations of the location instance
377
+ // that set its mode: the TUI asks the session's own location, so its decisions use that location's options whichever
378
+ // instance receives the turn end.
379
+ async function setSessionRouting(ctx, input, call, usage, readers, passive) {
380
+ const invalid = () => call.error("invalid", "Invalid routing mode.", {})
381
+ if (!input || typeof input !== "object" || Object.keys(input).length !== 3 || !isRef(input.sessionID) ||
382
+ !["off", "preview"].includes(input.mode) || typeof input.paid !== "boolean") return invalid()
383
+ let info
384
+ try {
385
+ info = await ctx.session.get({ sessionID: input.sessionID })
386
+ } catch {
387
+ info = undefined
388
+ }
389
+ if (!info || info.parentID !== undefined) return call.error("not_found", "Unknown session.", {})
390
+ const sessions = shared.routing.sessions
391
+ const prior = sessions.get(input.sessionID)
392
+ if (prior) prior.generation += 1
393
+ if (input.mode === "off") sessions.delete(input.sessionID)
394
+ else {
395
+ if (info.model) rememberModel(input.sessionID, info.model)
396
+ sessions.set(input.sessionID, { mode: input.mode, paid: input.paid, location: info.location, freshness: usageFreshness(usage),
397
+ readers, passive, generation: prior?.generation ?? 0, decision: prior?.decision })
398
+ while (sessions.size > keepDecisions) sessions.delete(sessions.keys().next().value)
399
+ }
400
+ invalidate()
401
+ return { mode: input.mode, paid: input.mode === "off" ? false : input.paid }
402
+ }
403
+
404
+ // Credential events per integration (an integration update names none, so it counts for all of them).
405
+ const credentialEpoch = (integrationID) => (shared.epochs.get(integrationID) ?? 0) + (shared.epochs.get("*") ?? 0)
406
+ function noteCredential(event) {
407
+ const id = event?.type === "integration.updated" ? "*" : event?.data?.integrationID
408
+ if (isRef(id)) shared.epochs.set(id, (shared.epochs.get(id) ?? 0) + 1)
409
+ }
410
+
411
+ // The host's model reference, never a prompt or a message. A failed turn may not start a step.
412
+ function rememberModel(sessionID, model) {
413
+ if (!isRef(sessionID)) return
414
+ const models = shared.routing.models
415
+ models.delete(sessionID)
416
+ if (!isRef(model?.providerID) || !isRef(model?.id)) return
417
+ models.set(sessionID, { providerID: model.providerID, modelID: model.id, ...(isRef(model.variant) ? { variant: model.variant } : {}) })
418
+ while (models.size > keepDecisions) models.delete(models.keys().next().value)
419
+ }
420
+
421
+ // One decision per (session, turn end), whichever location instance received it first. A new turn, a model selected
422
+ // meanwhile, turning the session off, the deadline or the plugin unloading abandon it: its result is then dropped.
423
+ // Each loop evaluates the current data again; it stops at the first destination or when no allowed read is left.
424
+ async function decideTurn(ctx, readers, passive, event, now) {
425
+ const sessionID = event?.data?.sessionID
426
+ const state = isRef(sessionID) ? shared.routing.sessions.get(sessionID) : undefined
427
+ if (!state || !isRef(event.id)) return
428
+ const key = JSON.stringify([sessionID, event.id])
429
+ if (shared.routing.seen.includes(key)) return
430
+ shared.routing.seen.push(key)
431
+ if (shared.routing.seen.length > keepDecisions) shared.routing.seen.shift()
432
+ const generation = ++state.generation
433
+ const deadline = now() + decisionMs
434
+ const { signal } = shared.stop
435
+ const current = () => !signal.aborted && shared.routing.sessions.get(sessionID) === state && state.generation === generation && now() < deadline
436
+ // A Claude step end being attributed for this session finishes first, within the deadline; nothing else is awaited.
437
+ const check = shared.routing.checks.get(sessionID)
438
+ if (check) {
439
+ let timer
440
+ await Promise.race([check.catch(() => {}), new Promise((resolve) => (timer = setTimeout(resolve, Math.max(0, deadline - now()))))])
441
+ clearTimeout(timer)
442
+ }
443
+ // The session's own location decides how long data stays fresh and which readers and passive data count, not the
444
+ // first instance to receive the event.
445
+ const ttl = freshness(state.freshness)
446
+ readers = state.readers ?? readers
447
+ passive = state.passive ?? passive
448
+ const visited = new Set()
449
+ const discarded = new Set()
450
+ const budget = { ...decisionBudget }
451
+ const readable = new Set([...readers].filter(([, reader]) => !reader.manual).map(([id]) => id))
452
+ let reads = 0
453
+ let decision
454
+ let catalog
455
+ for (;;) {
456
+ if (!current()) return
457
+ const { snapshot, native } = await readServer(ctx, readers, passive)
458
+ const routing = await readRouting(ctx)
459
+ if (!current()) return
460
+ if (snapshot.inventory !== "available" || snapshot.preferences.state !== "available" || routing.state !== "available") {
461
+ decision = { kind: "keep", reason: "Preferences unavailable", rows: [] }
462
+ break
463
+ }
464
+ const selection = shared.routing.models.get(sessionID)
465
+ const targets = routing.value.targets
466
+ if (catalog === undefined && state.location && targets.some((t) => !t.modelID && t.variant && t.providerID === selection?.providerID && t.variant !== selection.variant)) {
467
+ // All locations receive turn events; check a floating model's effort in the watched session's own catalog.
468
+ try { catalog = (await ctx.model.list({ location: state.location })).data ?? [] } catch { catalog = [] }
469
+ if (!current()) return
470
+ }
471
+ decision = decideRoute({
472
+ selection, targets, catalog, integrations: snapshot.integrations,
473
+ threshold: snapshot.preferences.threshold, minimums: snapshot.preferences.minimums, now: now(), readable, visited, discarded,
474
+ budget, paid: state.paid, ttl,
475
+ })
476
+ if (decision.kind !== "needRead") break
477
+ const { integrationID, connectionID, purpose } = decision.read
478
+ const row = native.get(integrationID)?.find((item) => item.id === connectionID)
479
+ const reader = readers.get(integrationID)
480
+ visited.add(JSON.stringify([integrationID, connectionID]))
481
+ budget[purpose] -= 1
482
+ if (!row || !reader || reader.manual) continue
483
+ reads += 1
484
+ const epoch = credentialEpoch(integrationID)
485
+ const status = await schedule(ctx, reader, integrationID, row, now, deadline)
486
+ // A reader not bound to one login (DeepSeek) is checked here: a key replaced (same ID, credential event meanwhile)
487
+ // or removed during the read does not lend its balance to the reference.
488
+ if (status === "read" && !reader.bound &&
489
+ (credentialEpoch(integrationID) !== epoch || !(await liveRow(ctx, integrationID, connectionID, row.method)))) {
490
+ discarded.add(JSON.stringify([integrationID, connectionID]))
491
+ shared.cache.forget(integrationID, connectionID)
492
+ }
493
+ }
494
+ if (!current()) return
495
+ state.decision = { ...decision, at: now(), reads }
496
+ invalidate()
497
+ }
498
+
499
+ // `experimental` readers exist only when the user sets the plugin option `experimentalCodexUsage: true` (E06); they
500
+ // are off by default and nothing else turns them on. Claude's passive usage (E02) exists only with the plugin option
501
+ // `experimentalClaudeUsage: true`: then, and only then, the server also listens to the step events of the user's own
502
+ // turns, and the manual `claude` reader (Claude Code `/usage`, explicit `r` or `a`) is offered. `usageFreshnessSeconds`
503
+ // (rules.js: 1–3600, else 150) sets how long ChatGPT and Claude Code usage stays fresh for this location. `system`
504
+ // ({ env, home }) stands in for the process environment and home folder in node tests.
505
+ export function createPlugin({ contract, readers = {}, experimental = {}, claude: claudeReader, now = Date.now, system }) {
506
+ return {
507
+ id: "account-quota",
508
+ async setup(ctx) {
509
+ const enabled = ctx.options?.experimentalCodexUsage === true
510
+ const claude = ctx.options?.experimentalClaudeUsage === true
511
+ // Per location instance, never in `shared`: it travels in this instance's snapshot (view, notices, Route order
512
+ // preview) and with the sessions this instance sets to watch (coordinator).
513
+ const usage = usageFreshness(ctx.options?.usageFreshnessSeconds)
514
+ const passive = new Set(claude ? [CLAUDE] : [])
515
+ const byIntegration = new Map(Object.entries({ ...readers, ...(enabled ? experimental : {}),
516
+ ...(claude && claudeReader ? { [CLAUDE]: claudeReader } : {}) }))
517
+ const registration = await ctx.rpc.register(contract, {
518
+ snapshot: async () => {
519
+ if (claude && shared.routing.checks.size > 0) {
520
+ let timer
521
+ await Promise.race([Promise.allSettled([...shared.routing.checks.values()]),
522
+ new Promise((resolve) => (timer = setTimeout(resolve, attributionMs)))])
523
+ clearTimeout(timer)
524
+ }
525
+ return (await readServer(ctx, byIntegration, passive, usage)).snapshot
526
+ },
527
+ refresh: async (input, call) => refresh(ctx, byIntegration, input, call, now),
528
+ savePreferences: async (input, call) => savePreferences(ctx, input, call),
529
+ routingView: async (input) => routingView(ctx, input),
530
+ saveRouting: async (input, call) => saveRouting(ctx, input, call),
531
+ setSessionRouting: async (input, call) => setSessionRouting(ctx, input, call, usage, byIntegration, passive),
532
+ })
533
+ // Another project may keep these sessions alive when this location reloads its plugin options.
534
+ for (const state of shared.routing.sessions.values()) {
535
+ if (!ctx.location?.directory || state.location?.directory !== ctx.location.directory) continue
536
+ state.readers = byIntegration
537
+ state.passive = passive
538
+ if (state.freshness !== usage) {
539
+ state.freshness = usage
540
+ state.generation++
541
+ }
542
+ }
543
+ const emit = (revision) => {
544
+ registration.events.emit("changed", { revision }).catch(() => {})
545
+ }
546
+ shared.emitters.add(emit)
547
+ const stop = new AbortController()
548
+ void (async () => {
549
+ for await (const event of ctx.event.subscribe({ types: nativeEvents, signal: stop.signal })) {
550
+ noteCredential(event)
551
+ if (claude && invalidates(event)) forgetClaude()
552
+ invalidate()
553
+ }
554
+ })().catch(() => {})
555
+ if (claude) {
556
+ // A separate subscription: if the host refused these event types, the native ones above still work.
557
+ const observe = createTurns({ state: shared.claude, cache: shared.cache, now, system })
558
+ void (async () => {
559
+ for await (const event of ctx.event.subscribe({ types: STEP_EVENTS, signal: stop.signal })) {
560
+ // Another location instance already attributes this event: its check must not be replaced by an empty one.
561
+ if (shared.claude.seen.has(event?.id)) continue
562
+ const check = observe(ctx, event).then((recorded) => recorded && invalidate(), () => {})
563
+ // A route decision of this session waits for this attribution (and only this one) within its deadline.
564
+ const sessionID = event?.data?.sessionID
565
+ if (event?.type === "session.step.ended" && isRef(sessionID)) {
566
+ shared.routing.checks.set(sessionID, check)
567
+ void check.finally(() => shared.routing.checks.get(sessionID) === check && shared.routing.checks.delete(sessionID))
568
+ }
569
+ }
570
+ })().catch(() => {})
571
+ }
572
+ // Route decisions (R4): only sessions set to `preview` are evaluated, at their own final turn results. A turn
573
+ // that starts or a model selected meanwhile abandons the pending decision. Its own subscription, so a host that
574
+ // refuses these types leaves everything above working.
575
+ void (async () => {
576
+ for await (const event of ctx.event.subscribe({ types: ROUTE_EVENTS, signal: stop.signal })) {
577
+ if (event.type === "session.step.started") rememberModel(event.data?.sessionID, event.data?.model)
578
+ const state = shared.routing.sessions.get(event?.data?.sessionID)
579
+ if (!state) continue
580
+ if (event.type === "session.execution.started") state.generation += 1
581
+ else if (TURN_END.has(event.type)) void decideTurn(ctx, byIntegration, passive, event, now).catch(() => {})
582
+ }
583
+ })().catch(() => {})
584
+ void (async () => {
585
+ for await (const event of ctx.event.subscribe({ types: SELECTED, signal: stop.signal })) {
586
+ const state = shared.routing.sessions.get(event?.data?.sessionID)
587
+ if (state) state.generation += 1
588
+ rememberModel(event?.data?.sessionID, event?.data?.model)
589
+ }
590
+ })().catch(() => {})
591
+ return async () => {
592
+ stop.abort()
593
+ shared.emitters.delete(emit)
594
+ if (shared.emitters.size === 0) {
595
+ // Last instance gone: cancel reads and forget measurements; only preferences outlive a reload.
596
+ clearTimeout(shared.timer)
597
+ shared.timer = undefined
598
+ shared.stop.abort()
599
+ shared.stop = new AbortController()
600
+ // Reads still waiting for a slot settle now without starting; those in flight end with their signal.
601
+ for (const start of shared.waiting.splice(0)) start()
602
+ shared.inflight.clear()
603
+ shared.until.clear()
604
+ shared.failuresInRow.clear()
605
+ shared.cache.clear()
606
+ // Session modes, decisions and the models seen go too: a reload keeps only the stored preferences.
607
+ shared.routing = createRouting()
608
+ // Step ends still being checked record nothing.
609
+ shared.claude.generation += 1
610
+ shared.claude.steps.clear()
611
+ shared.claude.seen.clear()
612
+ }
613
+ await registration.dispose()
614
+ }
615
+ },
616
+ }
617
+ }
package/sync.js ADDED
@@ -0,0 +1,60 @@
1
+ // Single-flight snapshot loader for the TUI (B02.4). Events are live only and may be lost (S08), so every
2
+ // invalidation (open, `changed`, reconnect, location change) schedules one more read. A response is applied
3
+ // only if nothing was invalidated while it was in flight, so an older read never replaces a newer state.
4
+ export function createLoader({ read, apply, fail }) {
5
+ let target
6
+ let key
7
+ let running = false
8
+ let dirty = false
9
+ let idle = []
10
+
11
+ async function pump() {
12
+ while (dirty) {
13
+ dirty = false
14
+ const request = target
15
+ try {
16
+ const value = await read(request)
17
+ if (!dirty) apply(value)
18
+ } catch (error) {
19
+ if (!dirty) fail(error)
20
+ }
21
+ }
22
+ running = false
23
+ const settled = idle
24
+ idle = []
25
+ for (const resolve of settled) resolve()
26
+ }
27
+
28
+ return {
29
+ // Resolves once a read that started after this call has been applied or has failed.
30
+ invalidate(next) {
31
+ if (next !== undefined) {
32
+ const nextKey = JSON.stringify(next)
33
+ if (nextKey !== key) {
34
+ key = nextKey
35
+ target = next
36
+ }
37
+ }
38
+ if (target === undefined) return Promise.resolve()
39
+ dirty = true
40
+ const done = new Promise((resolve) => idle.push(resolve))
41
+ if (!running) {
42
+ running = true
43
+ void pump()
44
+ }
45
+ return done
46
+ },
47
+ }
48
+ }
49
+
50
+ // Every location instance announces the same change with the same revision, and a client hears all locations: only
51
+ // the first copy counts. An event without a revision always counts, so no notice is ever lost; so does a lower one
52
+ // (a restarted server).
53
+ export function createDedupe() {
54
+ let last
55
+ return (revision) => {
56
+ if (revision !== undefined && revision === last) return false
57
+ last = revision
58
+ return true
59
+ }
60
+ }