tryflop 0.0.1 → 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/src/payer.js ADDED
@@ -0,0 +1,834 @@
1
+ // The payer: everything that moves money, one operation at a time (SPEC.md, both diagrams).
2
+ // - ask(): validate, join or answer a repeated question, queue (≤ 8 waiting), then in the queue:
3
+ // preflight → open a batch (LongSession; the payer lock may be busy: wait ≤ 2 min) → a turn through the
4
+ // GuardedJournal (local limits) → answered / failed (not charged) / unknown (never re-sent).
5
+ // - The batch settles 60 s after the last answer, 330 s after its channel opened, on settle(), when another
6
+ // model is asked, after an unknown turn, or at stop(). Settling takes minutes and holds the queue.
7
+ // - housekeeping (at start, every 60 s, every 30 s while a payment is unresolved, never during a batch):
8
+ // reconcile the journal, copy answers it kept into the log, mark requests of a dead process unknown,
9
+ // refund orphaned channels past their window.
10
+ // status() and result() read without waiting for the queue.
11
+ import { appendFileSync, readFileSync } from 'node:fs';
12
+ import { u8aToHex } from '@polkadot/util';
13
+ import { join } from 'node:path';
14
+ import { DIRECT, MAX_BATCH_SECONDS } from './shared/config.js';
15
+ import { formatFlop, PLANCK_PER_FLOP, toPlanck } from './shared/units.js';
16
+ import { readClaimRecord } from './claim.js';
17
+ import { requestDone, sessionProblem } from './flop-core.js';
18
+ import { dayTotal, GuardedJournal, LimitError, readLedger } from './guard.js';
19
+ import { turnOutcome, userMessage } from './outcome.js';
20
+ import { fingerprint, newRequestId, RequestLog } from './requests.js';
21
+
22
+ export const TIMINGS = Object.freeze({
23
+ queueMax: 8,
24
+ lockWaitMs: 120_000,
25
+ lockRetryMs: 5_000,
26
+ dedupWindowMs: 900_000,
27
+ /** A repeat of a question whose failed attempt had bought a channel waits this long: its retry buys another. */
28
+ retryCooldownMs: 60_000,
29
+ staleWaitsMs: Object.freeze([10_000, 20_000, 40_000]),
30
+ housekeepingMs: 60_000,
31
+ frozenHousekeepingMs: 30_000,
32
+ /** The official MCP client closes stdin, sends SIGTERM 2 s later and SIGKILL 2 s after that (client/stdio, 2.4.0). */
33
+ shutdownGraceMs: 3_000,
34
+ });
35
+ /** Below the cheapest channel measured (0.59 FLOP for 600 s, 23 Nov): a cap left under it buys nothing. */
36
+ const MIN_LEFT_PLANCK = PLANCK_PER_FLOP / 2n;
37
+ /**
38
+ * tryflop's own wallet pays its network fees itself: it never locks this much in a channel (DIRECT.feeMinPlanck, the
39
+ * minimum the session key's fee money may fall to on the flop-mcp route: the existential deposit plus a few fees).
40
+ */
41
+ export const WALLET_FEE_RESERVE_PLANCK = DIRECT.feeMinPlanck;
42
+ /** Below this a wallet cannot buy even the cheapest channel measured and still pay its fees. */
43
+ export const WALLET_MIN_BUY_PLANCK = MIN_LEFT_PLANCK + WALLET_FEE_RESERVE_PLANCK;
44
+
45
+ /**
46
+ * @typedef {{ status: 'answered'|'failed'|'refused'|'unknown', reason: string, message: string, requestId?: string,
47
+ * answer?: string, paidPlanck?: bigint, channel?: string, miner?: string, model?: string, replayed?: boolean, settlesBy?: number }} AskResult
48
+ * @typedef {{ prompt: string, model?: string, maxFlop?: string, maxTokens: number, system?: string, miner?: string }} AskInput
49
+ * miner: only this allowlisted miner (by id) may answer (tryflop's daily run tries them one at a time)
50
+ */
51
+
52
+ /** A short, single-line message for logs and status (never a stack). @param {unknown} error */
53
+ const brief = (error) => String(/** @type {any} */ (error)?.message ?? error).replace(/\s+/g, ' ').slice(0, 200);
54
+
55
+ /** @param {string} reason @param {string} message @returns {AskResult} */
56
+ const refused = (reason, message) => ({ status: 'refused', reason, message });
57
+
58
+ /** @param {number} pid */
59
+ function processAlive(pid) {
60
+ try {
61
+ process.kill(pid, 0);
62
+ return true;
63
+ } catch (error) {
64
+ return /** @type {any} */ (error).code === 'EPERM';
65
+ }
66
+ }
67
+
68
+ export class Payer {
69
+ /**
70
+ * @param {{ adapter: typeof import('./flop-node.js'), home: import('./home.js').Home, settings: import('./home.js').Settings,
71
+ * key: { address: string, pair: import('@polkadot/keyring/types').KeyringPair }, network: import('./shared/config.js').NetworkConfig,
72
+ * payersRoot: string, clock: { now(): number, sleep(ms: number, signal?: AbortSignal): Promise<unknown>, setTimer(ms: number, fn: () => void): () => void },
73
+ * log: (line: string) => void, isAlive?: (pid: number) => boolean, own?: boolean,
74
+ * miners?: readonly import('./shared/config.js').Miner[], run?: { maxChannels: number, budgetPlanck: bigint } }} deps
75
+ * own: tryflop's route: `key` is the wallet itself and `settings.owner` its address; it pays its own fees, and no
76
+ * session is read (SPEC.md "Asking as the wallet itself"). miners: who may be paid (default: the network's list).
77
+ * run: a daily run's caps, checked at each purchase: at most `maxChannels` channels and `budgetPlanck` in all
78
+ */
79
+ constructor({ adapter, home, settings, key, network, payersRoot, clock, log, isAlive = processAlive, own = false, miners, run }) {
80
+ if (own && settings.owner !== key.address) throw new Error('tryflop pays from its own wallet: the owner must be the wallet');
81
+ this.own = own;
82
+ this.miners = miners ?? network.miners;
83
+ this.run = run;
84
+ /** Channels this payer bought (counted when the SDK journals a purchase, right before it is broadcast). */
85
+ this.channelsAllowed = 0;
86
+ /** When this payer started: a daily run's own spend is what the ledger shows from here on. */
87
+ this.startedAt = clock.now();
88
+ this.adapter = adapter;
89
+ this.home = home;
90
+ this.settings = settings;
91
+ this.key = key;
92
+ this.network = network;
93
+ this.payersRoot = payersRoot;
94
+ this.clock = clock;
95
+ this.log = log;
96
+ this.isAlive = isAlive;
97
+ this.requests = new RequestLog({ file: home.requestsFile, answersDir: home.answersDir, now: () => clock.now() });
98
+ /** @type {Promise<unknown>} */
99
+ this.tail = Promise.resolve();
100
+ this.waiting = 0;
101
+ /** @type {Map<string, { promise: Promise<AskResult>, requestId: string, signal?: AbortSignal }>} */
102
+ this.inflight = new Map();
103
+ /** @type {any} */
104
+ this.batch = undefined;
105
+ /** @type {any} */
106
+ this.settlingBatch = undefined;
107
+ /** @type {Promise<any> | undefined} */
108
+ this.settlePromise = undefined;
109
+ this.frozen = false;
110
+ this.stopping = false;
111
+ /** @type {Map<string, { ready: boolean, checkedAt: number, problem?: string }>} */
112
+ this.minerChecks = new Map();
113
+ /** @type {any} */
114
+ this.api = undefined;
115
+ /** @type {Promise<any> | undefined} */
116
+ this.connecting = undefined;
117
+ /** @type {Promise<any> | undefined} */
118
+ this.closing = undefined;
119
+ this.connection = 'not connected yet';
120
+ /** @type {(() => void) | undefined} */
121
+ this.cancelHousekeeping = undefined;
122
+ }
123
+
124
+ /** Run `op` after every money operation queued before it. @template T @param {() => Promise<T>} op @returns {Promise<T>} */
125
+ enqueue(op) {
126
+ const run = this.tail.then(op);
127
+ this.tail = run.catch(() => {});
128
+ return run;
129
+ }
130
+
131
+ /** The chain connection: one per process, shared by everyone who needs it while it is being made. */
132
+ ensureApi() {
133
+ if (this.api) return Promise.resolve(this.api);
134
+ if (!this.connecting) {
135
+ this.connecting = this.adapter.connect(this.network).then((api) => {
136
+ this.api = api;
137
+ this.connection = 'ok';
138
+ return api;
139
+ }, (error) => {
140
+ this.connection = brief(error);
141
+ throw error;
142
+ }).finally(() => { this.connecting = undefined; });
143
+ }
144
+ return this.connecting;
145
+ }
146
+
147
+ /** Connect (a failure is kept for status and retried later), then the first housekeeping. */
148
+ async start() {
149
+ await this.ensureApi().catch((error) => this.log(`connect: ${brief(error)}`));
150
+ await this.housekeep();
151
+ }
152
+
153
+ // ── Asking ────────────────────────────────────────────────────────────────────────────────
154
+
155
+ /**
156
+ * @param {AskInput} input
157
+ * @param {{ signal?: AbortSignal, progress?: (message: string) => void }} [options]
158
+ * @returns {Promise<AskResult>}
159
+ */
160
+ ask(input, { signal, progress = () => {} } = {}) {
161
+ const ceiling = this.settings.maxFlopPerAsk;
162
+ let maxPlanck = ceiling;
163
+ if (input.maxFlop !== undefined) {
164
+ let wanted;
165
+ try {
166
+ wanted = toPlanck(input.maxFlop);
167
+ } catch {
168
+ wanted = -1n;
169
+ }
170
+ if (wanted <= 0n || wanted > ceiling) {
171
+ return Promise.resolve(refused('max_flop', `max_flop must be more than 0 and at most ${formatFlop(ceiling)} FLOP (maxFlopPerAsk in config.json). Nothing was bought.`));
172
+ }
173
+ maxPlanck = wanted;
174
+ }
175
+ // The model first, then the miners that serve it: when no model is named, the default model's own miners
176
+ // are the only ones tried, so an outage of the default can never quietly buy another model's answer. A named
177
+ // miner (tryflop's daily run picks them one at a time) is the only one tried, with its own model.
178
+ if (input.miner !== undefined && !this.miners.some((m) => m.id === input.miner)) {
179
+ return Promise.resolve(refused('model_unknown', `No allowlisted Flop miner is called "${String(input.miner).slice(0, 40)}". Nothing was bought.`));
180
+ }
181
+ const named = input.miner === undefined ? undefined : this.miners.find((m) => m.id === input.miner);
182
+ const model = named?.model ?? input.model ?? this.miners[0]?.model;
183
+ const miners = named ? [named] : model === undefined ? [] : this.miners.filter((m) => m.model === model);
184
+ if (!miners.length) {
185
+ const models = [...new Set(this.miners.map((m) => m.model))].join(', ') || 'none';
186
+ return Promise.resolve(refused('model_unknown', `No allowlisted Flop miner serves ${model === undefined ? 'any model' : `"${model}"`}. Models available: ${models}. Nothing was bought.`));
187
+ }
188
+ const print = fingerprint({ model, system: input.system, maxTokens: input.maxTokens, prompt: input.prompt });
189
+ const joined = this.inflight.get(print);
190
+ // A call whose own client cancelled it is not joined: the new ask must not inherit "cancelled".
191
+ if (joined && !joined.signal?.aborted) return joined.promise;
192
+ const earlier = this.requests.recent(print, TIMINGS.dedupWindowMs);
193
+ if (earlier?.status === 'answered' && earlier.answer !== undefined) {
194
+ const minutes = Math.max(1, Math.round((this.clock.now() - (earlier.finishedAt ?? earlier.at)) / 60_000));
195
+ return Promise.resolve({
196
+ status: 'answered', reason: 'repeat', requestId: earlier.id, answer: earlier.answer, paidPlanck: 0n, channel: earlier.channel,
197
+ miner: earlier.miner, model, replayed: true,
198
+ message: `The same question was answered ${minutes} minute(s) ago; this is that answer, not bought again.`,
199
+ });
200
+ }
201
+ if (earlier?.status === 'unknown') {
202
+ return Promise.resolve({
203
+ status: 'unknown', reason: 'repeat_unknown', requestId: earlier.id,
204
+ message: `${userMessage({ kind: 'unknown', reason: 'turn_unknown' }, { requestId: earlier.id })} This exact question was asked recently, so it was not sent again.`,
205
+ });
206
+ }
207
+ // Another call's request still waiting here (this process, its client cancelled it) never blocks this
208
+ // ask: that call is dropped before anything is bought when its turn comes.
209
+ const queuedHere = this.inflight.get(print);
210
+ const cancelledHere = earlier?.status === 'queued' && queuedHere?.requestId === earlier.id && queuedHere.signal?.aborted === true;
211
+ if (!cancelledHere && (earlier?.status === 'running' || earlier?.status === 'queued')) {
212
+ return Promise.resolve(refused('running_elsewhere', `This exact question is being asked right now (request ${earlier.id}), maybe in another Claude session. Nothing new was bought; call flop_result with that id.`));
213
+ }
214
+ // A question whose last attempt failed AFTER buying a channel is not retried at once: each retry can buy
215
+ // another channel (run of 24 Nov 10:03 UTC: one question, three channels). A failed attempt that bought
216
+ // nothing never waits: retrying it is free.
217
+ // The newest FAILED-AND-PAID attempt of this exact question, by its finish time: a lookup by start time
218
+ // would miss one that waited minutes, and one that picks any record could be shadowed by a later failure
219
+ // that spent nothing (security reviews of 24 Nov).
220
+ const lastFailure = this.requests.recentPaidFailure(print, TIMINGS.retryCooldownMs);
221
+ // A clean miner refusal keeps the channel open (long-session.js: "the channel serves on"), so a retry that
222
+ // would join that very batch costs nothing and must not wait: the wait and the 60 s idle close end
223
+ // together, and waiting would let the close take the channel first (review, 24 Nov). The exception is
224
+ // tied to that batch only — this process's own attempt, same model, still open and still able to take a
225
+ // turn, same channel when both name one — so it can never let a purchase through (security review).
226
+ const batchTakesThisRetry = Boolean(this.batch) && !this.batch.ending && this.batch.model === model && !this.batchPastDeadline();
227
+ const retryReusesThisChannel = lastFailure?.reason === 'turn_refused'
228
+ && lastFailure.pid === process.pid
229
+ && batchTakesThisRetry
230
+ && (lastFailure.channel === undefined || this.batch.channel === lastFailure.channel);
231
+ if (lastFailure && !retryReusesThisChannel) {
232
+ const since = this.clock.now() - /** @type {number} */ (lastFailure.finishedAt);
233
+ if (since < TIMINGS.retryCooldownMs) {
234
+ const seconds = Math.ceil((TIMINGS.retryCooldownMs - since) / 1000);
235
+ return Promise.resolve(refused('retry_soon', `This exact question failed ${Math.max(1, Math.round(since / 1000))} second(s) ago and that attempt had already bought a channel, so asking again right away can buy another one. Nothing was bought now; try again in ${seconds} seconds, or call flop_result with ${lastFailure.id}.`));
236
+ }
237
+ }
238
+ if (this.stopping) return Promise.resolve(refused('stopping', 'The connector is shutting down. Nothing was bought.'));
239
+ if (this.waiting >= TIMINGS.queueMax) return Promise.resolve(refused('busy', 'Too many questions are already waiting. Nothing was bought; try again in a minute.'));
240
+
241
+ const requestId = newRequestId(this.clock.now());
242
+ this.requests.start({ id: requestId, fingerprint: print, model, promptChars: input.prompt.length, pid: process.pid, status: 'queued' });
243
+ this.waiting += 1;
244
+ const run = this.enqueue(async () => {
245
+ this.waiting -= 1;
246
+ return this.askOp({ ...input, model }, { requestId, maxPlanck, miners, signal, progress });
247
+ }).catch((error) => {
248
+ this.log(`ask ${requestId}: unexpected ${brief(error)}`);
249
+ this.requests.finish(requestId, { status: 'unknown', reason: 'internal error' });
250
+ return /** @type {AskResult} */ ({ status: 'unknown', reason: 'internal', requestId, message: userMessage({ kind: 'unknown', reason: 'internal' }, { requestId }) });
251
+ }).finally(() => {
252
+ // Only this call's own entry: a newer ask for the same question may already have replaced it.
253
+ if (this.inflight.get(print)?.requestId === requestId) this.inflight.delete(print);
254
+ });
255
+ this.inflight.set(print, { promise: run, requestId, signal });
256
+ return run;
257
+ }
258
+
259
+ /**
260
+ * @param {AskInput & { model: string }} input
261
+ * @param {{ requestId: string, maxPlanck: bigint, miners: any[], signal?: AbortSignal, progress: (m: string) => void }} context
262
+ * @returns {Promise<AskResult>}
263
+ */
264
+ async askOp(input, { requestId, maxPlanck, miners, signal, progress }) {
265
+ /** @param {AskResult} result @param {object} [extra] */
266
+ const end = (result, extra = {}) => {
267
+ if (result.status === 'answered') {
268
+ this.requests.finish(requestId, { status: 'answered', answer: result.answer, paidPlanck: result.paidPlanck, channel: result.channel, miner: result.miner, replayed: result.replayed });
269
+ } else {
270
+ this.requests.finish(requestId, { status: result.status === 'refused' ? 'refused' : result.status, reason: result.reason, ...(result.paidPlanck ? { paidPlanck: result.paidPlanck } : {}), ...extra });
271
+ }
272
+ return { requestId, ...result };
273
+ };
274
+ if (signal?.aborted) return end(refused('cancelled', 'Cancelled before anything was bought.'));
275
+ if (this.stopping) return end(refused('stopping', 'The connector is shutting down. Nothing was bought.'));
276
+ this.requests.update(requestId, { status: 'running' });
277
+ // A batch that ended in an unknown turn cannot serve again: close it before serving anyone (L2).
278
+ const cancelled = () => end(refused('cancelled', 'Cancelled before anything was bought for this question.'));
279
+ // A question for a named miner (tryflop's daily run) never goes to a batch open on another one.
280
+ const otherMiner = input.miner !== undefined && this.batch && this.batch.miner.id !== input.miner;
281
+ if (this.batch && (this.batch.ending || this.batch.model !== input.model || this.batchPastDeadline() || otherMiner)) await this.settleOp();
282
+ if (signal?.aborted) return cancelled();
283
+ if (!this.batch) {
284
+ const opened = await this.openBatchFor(input.model, miners, { signal, progress });
285
+ if (opened) return end(opened);
286
+ }
287
+ const batch = this.batch;
288
+ if (signal?.aborted) {
289
+ this.armIdle(batch); // a batch opened for nothing still closes on its own
290
+ return cancelled();
291
+ }
292
+ batch.lastActivityAt = this.clock.now();
293
+ batch.cancelIdle?.();
294
+ const turnInput = { model: batch.slug, prompt: input.prompt, system: input.system, maxTokens: input.maxTokens };
295
+
296
+ for (let attempt = 0; ; attempt += 1) {
297
+ batch.guard.begin(requestId, maxPlanck);
298
+ progress('Waiting for the miner\'s answer…');
299
+ try {
300
+ const turn = await this.adapter.runTurn(batch.session, turnInput, requestId);
301
+ const { reserved } = batch.guard.end();
302
+ this.noteSpends(batch, reserved);
303
+ return end(this.answered(batch, turn, reserved.reduce((sum, r) => sum + r.amount, 0n)));
304
+ } catch (error) {
305
+ const { reserved, started } = batch.guard.end();
306
+ this.noteSpends(batch, reserved);
307
+ const state = batch.guard.state();
308
+ const statusOf = (/** @type {string} */ tx) => state.entries.find((e) => e.txHash === tx)?.status;
309
+ const unresolvedSpend = reserved.some((r) => ['pending', 'ambiguous'].includes(String(statusOf(r.txHash))));
310
+ const outcome = turnOutcome(error, {
311
+ started, unresolvedSpend, journalDone: requestDone(state, requestId), staleRetriesLeft: TIMINGS.staleWaitsMs.length - attempt,
312
+ });
313
+ if (outcome.kind === 'answered') {
314
+ // The SDK journal holds the verified answer: its replay buys nothing (a 0 limit makes sure).
315
+ batch.guard.begin(requestId, 0n);
316
+ try {
317
+ const turn = await this.adapter.runTurn(batch.session, turnInput, requestId);
318
+ return end(this.answered(batch, { ...turn, replayed: true }, reserved.reduce((sum, r) => sum + r.amount, 0n)));
319
+ } finally {
320
+ batch.guard.end();
321
+ }
322
+ }
323
+ if (outcome.kind === 'retry') {
324
+ progress('Flop\'s chain is running behind; waiting before trying again (nothing was signed)…');
325
+ await this.clock.sleep(TIMINGS.staleWaitsMs[attempt], signal).catch(() => {});
326
+ if (signal?.aborted) {
327
+ this.armIdle(batch);
328
+ return cancelled();
329
+ }
330
+ continue;
331
+ }
332
+ const committed = reserved.filter((r) => statusOf(r.txHash) === 'succeeded');
333
+ const boughtUnservedPlanck = committed.filter((r) => r.kind === 'open').reduce((sum, r) => sum + r.amount, 0n);
334
+ // A channel this attempt bought that is already recorded as unusable: the batch has nothing left to serve with.
335
+ const opened = new Set(committed.filter((r) => r.kind === 'open').map((r) => r.channel));
336
+ const boughtOrphaned = state.channels.some((c) => opened.has(c.channel) && c.state === 'orphaned');
337
+ const clockSkewMs = outcome.reason === 'stale_head' ? await this.clockSkew() : 0;
338
+ if (outcome.kind === 'failed') {
339
+ // The per-batch guard refused a second purchase in this batch, so the batch has nothing to serve with: the next question settles it first and starts a new one.
340
+ // The same when the channel it bought cannot serve: without this, the next question would
341
+ // be refused as a second purchase in a batch that cannot serve (review, 26 Nov).
342
+ if (outcome.reason === 'per_batch' || boughtOrphaned) batch.ending = true;
343
+ this.armIdle(batch);
344
+ // An answer that was not charged may still have bought a channel. The SDK may keep it for the next
345
+ // question or not, and records which only later, so the message states both endings and promises
346
+ // neither (SPEC.md).
347
+ return end({ status: 'failed', reason: outcome.reason, paidPlanck: committed.reduce((s, r) => s + r.amount, 0n), message: userMessage(outcome, { requestId, clockSkewMs, boughtUnservedPlanck, boughtOrphaned }) });
348
+ }
349
+ batch.ending = true; // this batch cannot serve again: the next question closes it first
350
+ void this.settleBatch(batch);
351
+ const message = userMessage(outcome, { requestId, clockSkewMs, boughtUnservedPlanck, boughtOrphaned });
352
+ return end({ status: 'unknown', reason: outcome.reason, message }, { reason: outcome.reason });
353
+ }
354
+ }
355
+ }
356
+
357
+ /** @returns {AskResult} */
358
+ answered(batch, turn, paidPlanck) {
359
+ batch.answered.add(turn.channelId);
360
+ batch.channel = turn.channelId;
361
+ this.armIdle(batch);
362
+ const settlesBy = this.settlesBy(batch);
363
+ const bought = paidPlanck > 0n ? `This question bought a channel (${formatFlop(paidPlanck)} FLOP escrow); questions in the next few minutes share it.` : 'It used the channel already bought for this batch (no new cost).';
364
+ return {
365
+ status: 'answered', reason: 'answered', answer: turn.answer, paidPlanck, channel: turn.channelId, miner: batch.miner.id, model: batch.slug,
366
+ replayed: Boolean(turn.replayed), settlesBy, message: bought,
367
+ };
368
+ }
369
+
370
+ /** Remember the batch's purchases: a new channel restarts the 330 s clock. */
371
+ noteSpends(batch, reserved) {
372
+ const state = batch.guard.state();
373
+ for (const spend of reserved) {
374
+ if (spend.kind !== 'open') continue;
375
+ // A purchase that failed at finality never took any FLOP.
376
+ if (state.entries.find((e) => e.txHash === spend.txHash)?.status === 'failed') continue;
377
+ batch.bought.add(spend.channel);
378
+ // The window runs from the open on chain; the spend was signed just before it (M1).
379
+ batch.channelOpenedAt = spend.at;
380
+ batch.cancelDeadline?.();
381
+ const left = Math.max(0, spend.at + MAX_BATCH_SECONDS * 1000 - this.clock.now());
382
+ batch.cancelDeadline = this.clock.setTimer(left, () => { void this.settleBatch(batch); });
383
+ }
384
+ }
385
+
386
+ batchPastDeadline() {
387
+ const b = this.batch;
388
+ return Boolean(b?.channelOpenedAt) && this.clock.now() >= b.channelOpenedAt + MAX_BATCH_SECONDS * 1000;
389
+ }
390
+
391
+ settlesBy(batch) {
392
+ const idle = batch.lastActivityAt + this.settings.idleSettleSeconds * 1000;
393
+ return batch.channelOpenedAt ? Math.min(idle, batch.channelOpenedAt + MAX_BATCH_SECONDS * 1000) : idle;
394
+ }
395
+
396
+ armIdle(batch) {
397
+ batch.lastActivityAt = this.clock.now();
398
+ const armedAt = batch.lastActivityAt;
399
+ batch.cancelIdle?.();
400
+ batch.cancelIdle = this.clock.setTimer(this.settings.idleSettleSeconds * 1000, () => {
401
+ void this.enqueue(async () => {
402
+ if (this.batch !== batch) return null;
403
+ if (batch.lastActivityAt !== armedAt) { this.armIdle(batch); return null; }
404
+ return this.settleOp();
405
+ });
406
+ });
407
+ }
408
+
409
+ async clockSkew() {
410
+ try {
411
+ const { timestampMs } = await this.adapter.finalizedInfo(await this.ensureApi());
412
+ return this.clock.now() - timestampMs;
413
+ } catch {
414
+ return 0;
415
+ }
416
+ }
417
+
418
+ /**
419
+ * PREFLIGHT and OPENING_BATCH. Returns a refusal, or undefined with this.batch set.
420
+ * @param {string} model @param {any[]} miners @param {{ signal?: AbortSignal, progress: (m: string) => void }} options
421
+ * @returns {Promise<AskResult | undefined>}
422
+ */
423
+ async openBatchFor(model, miners, { signal, progress }) {
424
+ let api;
425
+ try {
426
+ api = await this.ensureApi();
427
+ } catch (error) {
428
+ return refused('network', `Flop's network could not be reached (${brief(error)}). Nothing was bought.`);
429
+ }
430
+ const { owner } = this.settings;
431
+ if (this.own) {
432
+ progress('Checking the wallet…');
433
+ let free;
434
+ try {
435
+ free = await this.adapter.freeBalance(api, owner);
436
+ } catch (error) {
437
+ return refused('network', `Flop's chain could not be read (${brief(error)}). Nothing was bought; try again.`);
438
+ }
439
+ if (free < WALLET_MIN_BUY_PLANCK) {
440
+ return refused('no_flop', `The wallet ${owner} holds ${formatFlop(free)} FLOP; buying an answer needs at least ${formatFlop(WALLET_MIN_BUY_PLANCK)} (a channel plus network fees). Nothing was bought; the daily run claims Flop's free test FLOP for it.`);
441
+ }
442
+ if (this.run && this.channelsAllowed >= this.run.maxChannels) {
443
+ return refused('per_run', `This run already bought its ${this.run.maxChannels} channel(s). Nothing more was bought.`);
444
+ }
445
+ } else {
446
+ progress('Checking your spending limit…');
447
+ let problem;
448
+ let fees;
449
+ try {
450
+ problem = sessionProblem(await this.adapter.readSession(api, owner, this.key.address), { minLeftPlanck: MIN_LEFT_PLANCK });
451
+ fees = await this.adapter.freeBalance(api, this.key.address);
452
+ } catch (error) {
453
+ return refused('network', `Flop's chain could not be read (${brief(error)}). Nothing was bought; try again.`);
454
+ }
455
+ const SESSION_REASON = { missing: 'session_missing', inactive: 'session_inactive', too_broad: 'session_too_broad', cap_used: 'cap_used' };
456
+ if (problem) return refused(SESSION_REASON[problem], this.sessionMessage(problem));
457
+ if (fees < DIRECT.feeMinPlanck) {
458
+ return refused('fees', `The session key holds ${formatFlop(fees)} FLOP for network fees (it needs at least ${formatFlop(DIRECT.feeMinPlanck)}). Send it 0.5 FLOP from your wallet: ${this.key.address}. Nothing was bought.`);
459
+ }
460
+ }
461
+ try {
462
+ const today = dayTotal(readLedger(this.home.ledgerFile), this.clock.now());
463
+ if (today >= this.settings.maxFlopPerDay) {
464
+ return refused('per_day', `Today's limit on this computer (${formatFlop(this.settings.maxFlopPerDay)} FLOP, maxFlopPerDay in config.json) is used up. Nothing was bought.`);
465
+ }
466
+ } catch (error) {
467
+ return refused('ledger_damaged', `${brief(error)} Nothing was bought.`);
468
+ }
469
+ progress('Checking the miner…');
470
+ let chosen;
471
+ for (const miner of miners) {
472
+ try {
473
+ const identity = await this.adapter.readInfoProof(miner, this.network.genesis);
474
+ // The channel is pinned to the proof's model hash and, since SDK 0.10.0, that model's chain price sets
475
+ // every turn's cost: a miner proving another model (name or registry hash) than its listed one is not
476
+ // ready for this one. What the miner wrote goes to the log only: miner text never reaches Claude raw.
477
+ const proved = identity.modelIdentity;
478
+ const hash = proved?.modelHash instanceof Uint8Array ? u8aToHex(proved.modelHash) : undefined;
479
+ if (proved?.requestedSlug !== miner.model || hash !== miner.modelHash) {
480
+ this.log(`miner ${miner.id}: readiness proof names model ${JSON.stringify(String(proved?.requestedSlug).slice(0, 80))} ${hash ?? '(no hash)'}, not ${miner.model} ${miner.modelHash}`);
481
+ throw new Error(`its readiness proof names another model than ${miner.model}`);
482
+ }
483
+ this.minerChecks.set(miner.id, { ready: true, checkedAt: this.clock.now() });
484
+ chosen = { miner, ...identity };
485
+ break;
486
+ } catch (error) {
487
+ this.minerChecks.set(miner.id, { ready: false, checkedAt: this.clock.now(), problem: brief(error) });
488
+ }
489
+ }
490
+ if (!chosen) {
491
+ const why = miners.map((m) => `${m.id}: ${this.minerChecks.get(m.id)?.problem ?? 'not ready'}`).join('; ');
492
+ return refused('no_miner', `No Flop miner for ${model} is ready right now (${why}). Nothing was bought; try again later.`);
493
+ }
494
+
495
+ const guard = new GuardedJournal(this.adapter.openJournal(this.home, this.network.genesis, owner, this.payersRoot), {
496
+ ledgerFile: this.home.ledgerFile, maxPerDayPlanck: this.settings.maxFlopPerDay, now: () => this.clock.now(),
497
+ // A run's channels are counted once the SDK journaled the purchase: AFTER its own pre-sign checks (a stale
498
+ // finalized head refuses inside prepare, after beforeSpend), so a refused attempt never uses up the run's one
499
+ // channel before the stale-head retry (push-gate review, 27 Nov). Journaled counts even if its outcome is unknown.
500
+ onReserved: (kind) => { if (kind === 'open') this.channelsAllowed += 1; },
501
+ });
502
+ /** @param {'open'|'topUp'} kind */
503
+ const beforeSpendOwn = async (kind) => {
504
+ // The wallet's free balance, fresh, right before this purchase: the guard compares the exact amount with it.
505
+ // A failed read throws, so nothing is signed (fail closed).
506
+ const free = await this.adapter.freeBalance(api, owner);
507
+ const runLeft = this.runLeftPlanck(guard);
508
+ if (kind === 'open' && free - WALLET_FEE_RESERVE_PLANCK < MIN_LEFT_PLANCK) {
509
+ throw new LimitError('wallet_balance', `The wallet holds ${formatFlop(free)} FLOP, too little for a channel and its network fees.`);
510
+ }
511
+ guard.setChainLimits({ capLeftPlanck: free - WALLET_FEE_RESERVE_PLANCK, perTxPlanck: DIRECT.maxChannelPlanck, dailyLeftPlanck: runLeft, own: true });
512
+ };
513
+ /** @param {'open'|'topUp'} kind */
514
+ const beforeSpend = async (kind) => {
515
+ if (this.own) return beforeSpendOwn(kind);
516
+ const view = await this.adapter.readSession(api, owner, this.key.address);
517
+ // The 0.5 FLOP floor is for buying a NEW channel. A top-up keeps a channel this batch already bought
518
+ // serving; held to the floor, it could not. The guard below still checks its exact amount (review, 26 Nov).
519
+ const now = sessionProblem(view, { minLeftPlanck: kind === 'open' ? MIN_LEFT_PLANCK : 0n });
520
+ // Worded like the chain's own refusals, so the shared classifier reads them (nothing is sent).
521
+ if (now === 'missing') throw new Error('flopSessionKeys.SessionNotFound: the spending limit for this key is gone');
522
+ if (now === 'inactive') throw new Error('flopSessionKeys.SessionExpired: the spending limit for this key has ended');
523
+ if (now === 'too_broad') throw new Error('flopSessionKeys.PalletNotAllowed: the spending limit allows more than compute payments');
524
+ if (now === 'cap_used') throw new Error('flopSessionKeys.SpendingCapExceeded: less than 0.5 FLOP of the spending limit is left');
525
+ // The exact terms the chain will enforce, fresh, for the guarded journal's check of the exact amount
526
+ // (it refuses before the SDK broadcasts anything above them; one read covers one purchase).
527
+ guard.setChainLimits({
528
+ capLeftPlanck: view.capPlanck - view.spentPlanck,
529
+ perTxPlanck: view.perTxPlanck,
530
+ // Not dailyCap - epochSpent: the chain clears epochSpent only on the session's next payment, so an
531
+ // ended epoch still stores yesterday's number (flop-core.dailyLeftPlanck explains).
532
+ dailyLeftPlanck: view.dailyLeftPlanck,
533
+ });
534
+ };
535
+ // One batch buys at most one channel — the rule the agent app enforces with onePurchasePerBatch, which
536
+ // cannot be used here as it stands: it latches on the ATTEMPT, and a purchase this connector's own limits
537
+ // refuse before signing leaves the batch with nothing, still open and allowed to try again (a nearly used
538
+ // spending limit, a used-up day). This counts what the batch actually BOUGHT, so any second purchase in a
539
+ // batch is refused before it is signed, whatever asked for it (review of b3f21b5, 24 Nov).
540
+ const beforeSpendOnce = async (kind) => {
541
+ if (kind === 'open' && (this.batch?.bought.size ?? 0) > 0) {
542
+ throw new LimitError('per_batch', 'This batch already bought its channel, and one batch buys at most one; a second channel was not bought.');
543
+ }
544
+ // A daily run's hard cap on channels, at the purchase itself (the SDK calls this right before it journals and
545
+ // signs); a channel counts once the SDK journals its purchase (onReserved above).
546
+ if (kind === 'open' && this.run && this.channelsAllowed >= this.run.maxChannels) {
547
+ throw new LimitError('per_run', `This run may buy ${this.run.maxChannels} channel(s) and already did; no more was bought.`);
548
+ }
549
+ await beforeSpend(kind); // the session (or wallet) check and the fresh limits, for this purchase
550
+ };
551
+ const deadline = this.clock.now() + TIMINGS.lockWaitMs;
552
+ for (;;) {
553
+ try {
554
+ const session = await this.adapter.openBatch({
555
+ api, owner, sessionPair: this.key.pair, journal: guard, miner: chosen.miner, enclaveKey: chosen.enclaveKey,
556
+ modelIdentity: chosen.modelIdentity, budgetPlanck: this.budgetFor(), beforeSpend: beforeSpendOnce, own: this.own,
557
+ });
558
+ this.batch = {
559
+ session, guard, model, slug: chosen.modelIdentity.requestedSlug, miner: chosen.miner, answered: new Set(), bought: new Set(), ending: false,
560
+ channel: undefined, channelOpenedAt: undefined, lastActivityAt: this.clock.now(), openedAt: this.clock.now(),
561
+ };
562
+ return undefined;
563
+ } catch (error) {
564
+ const locked = /** @type {any} */ (error)?.code === 'JOURNAL_LOCKED';
565
+ if (locked && this.clock.now() < deadline && !signal?.aborted && !this.stopping) {
566
+ progress('Another Claude session is paying with this wallet; waiting for it…');
567
+ await this.clock.sleep(TIMINGS.lockRetryMs);
568
+ continue;
569
+ }
570
+ if (locked) return refused('busy', 'Another Claude session on this computer has been paying with this wallet for over 2 minutes (or a crashed run left its lock behind; flop_status shows the lock folder). Nothing was bought; try again in a few minutes.');
571
+ this.log(`open batch: ${brief(error)}`);
572
+ return refused('open_failed', 'Flop\'s chain did not let the batch start (the miner or its model is not admitted right now). Nothing was bought; try again later.');
573
+ }
574
+ }
575
+ }
576
+
577
+ /**
578
+ * What the SDK's own lifetime budget is set to for the next batch. flop-mcp: maxFlopTotal (config.json). tryflop: what
579
+ * the ledger shows was ever reserved (the journal's never-decreasing debit, counted the same way) plus what this run
580
+ * or this day may still spend, so the SDK itself refuses an escrow above that before it calls beforeSpend.
581
+ */
582
+ budgetFor() {
583
+ if (!this.own) return this.settings.maxFlopTotal;
584
+ const lines = readLedger(this.home.ledgerFile);
585
+ const voided = new Set(lines.filter((l) => 'void' in l).map((l) => l.txHash));
586
+ let ever = 0n;
587
+ for (const line of lines) if (!('void' in line) && !voided.has(line.txHash)) ever += BigInt(line.amount);
588
+ return ever + this.runLeftPlanck();
589
+ }
590
+
591
+ /**
592
+ * What may still be spent now: the day's local limit minus the ledger's last 24 h, and for a daily run also its own
593
+ * budget minus what it reserved. @param {GuardedJournal} [guard]
594
+ */
595
+ runLeftPlanck(guard) {
596
+ void guard;
597
+ const now = this.clock.now();
598
+ const lines = readLedger(this.home.ledgerFile);
599
+ const dayLeft = this.settings.maxFlopPerDay - dayTotal(lines, now);
600
+ if (!this.run) return dayLeft > 0n ? dayLeft : 0n;
601
+ const voided = new Set(lines.filter((l) => 'void' in l).map((l) => l.txHash));
602
+ let runSpent = 0n;
603
+ for (const line of lines) {
604
+ if (!('void' in line) && !voided.has(line.txHash) && line.at >= this.startedAt) runSpent += BigInt(line.amount);
605
+ }
606
+ const runLeft = this.run.budgetPlanck - runSpent;
607
+ const left = runLeft < dayLeft ? runLeft : dayLeft;
608
+ return left > 0n ? left : 0n;
609
+ }
610
+
611
+ /** @param {'missing'|'inactive'|'too_broad'|'cap_used'} problem */
612
+ sessionMessage(problem) {
613
+ const address = this.key.address;
614
+ return {
615
+ missing: `Your wallet has not given this connector's key a spending limit yet. In your wallet, grant ${address} a limit for compute only (ComputeChannel). Nothing was bought.`,
616
+ inactive: `The spending limit your wallet gave this connector's key (${address}) has ended (expired or revoked). Grant a new one from your wallet. Nothing was bought.`,
617
+ too_broad: `The spending limit on this connector's key allows more than compute payments, so the connector will not use it. Grant ${address} a limit for compute only (ComputeChannel). Nothing was bought.`,
618
+ cap_used: 'Less than 0.5 FLOP of your spending limit is left. Grant a new limit from your wallet. Nothing was bought.',
619
+ }[problem];
620
+ }
621
+
622
+ // ── Settling ──────────────────────────────────────────────────────────────────────────────
623
+
624
+ /** Settle `batch` when its turn in the queue comes, unless it is no longer the open one (timers, unknown turns). */
625
+ settleBatch(batch) {
626
+ return this.enqueue(() => (this.batch === batch ? this.settleOp() : Promise.resolve(null)));
627
+ }
628
+
629
+ /** Settle whatever batch is open (flop_settle); a settle already queued or running is joined. */
630
+ settle() {
631
+ if (this.closing) return this.closing;
632
+ if (!this.settlePromise) {
633
+ this.settlePromise = this.enqueue(() => this.settleOp()).finally(() => { this.settlePromise = undefined; });
634
+ }
635
+ return this.settlePromise;
636
+ }
637
+
638
+ /** @returns {Promise<{ status: 'nothing'|'settled'|'left_for_refund'|'unknown', channel?: string, message: string }>} */
639
+ settleOp() {
640
+ const batch = this.batch;
641
+ if (!batch) return Promise.resolve({ status: /** @type {const} */ ('nothing'), message: 'No batch is open, so there is nothing to settle.' });
642
+ this.closing = this.closeBatch(batch).finally(() => { this.closing = undefined; });
643
+ return this.closing;
644
+ }
645
+
646
+ /** @returns {Promise<{ status: 'nothing'|'settled'|'left_for_refund'|'unknown', channel?: string, message: string }>} */
647
+ async closeBatch(batch) {
648
+ this.batch = undefined;
649
+ batch.cancelIdle?.();
650
+ batch.cancelDeadline?.();
651
+ this.settlingBatch = batch;
652
+ let summary;
653
+ try {
654
+ summary = await this.adapter.closeBatch(batch.session);
655
+ } catch (error) {
656
+ this.log(`settle: ${brief(error)}`);
657
+ return { status: 'unknown', channel: batch.channel, message: 'The batch\'s close could not be confirmed; flop_status shows what Flop\'s chain says.' };
658
+ } finally {
659
+ this.settlingBatch = undefined;
660
+ }
661
+ this.frozen = summary.unresolved.length > 0;
662
+ const served = [...batch.answered];
663
+ if (!served.length) {
664
+ const bought = [...batch.bought];
665
+ if (!bought.length) return { status: 'nothing', message: 'The batch bought nothing that needed settling.' };
666
+ return { status: 'left_for_refund', channel: bought[0], message: `The channel bought for this batch (${bought[0]}) served no answer; its escrow comes back to your wallet after its window (the connector asks for it).` };
667
+ }
668
+ const channel = batch.channel;
669
+ if (summary.closed.includes(channel)) return { status: 'settled', channel, message: `Settled on Flop's chain: channel ${channel}.` };
670
+ return { status: 'left_for_refund', channel, message: `Channel ${channel} was not settled by the miner; its unused escrow comes back to your wallet after the channel's window (the connector asks for it).` };
671
+ }
672
+
673
+ // ── Housekeeping ──────────────────────────────────────────────────────────────────────────
674
+
675
+ /** Run one housekeeping pass in the queue (and schedule the next). */
676
+ housekeep() {
677
+ return this.enqueue(() => this.housekeepOp());
678
+ }
679
+
680
+ scheduleHousekeeping() {
681
+ this.cancelHousekeeping?.();
682
+ this.cancelHousekeeping = undefined;
683
+ if (this.stopping) return;
684
+ this.cancelHousekeeping = this.clock.setTimer(this.frozen ? TIMINGS.frozenHousekeepingMs : TIMINGS.housekeepingMs, () => { void this.housekeep(); });
685
+ }
686
+
687
+ async housekeepOp() {
688
+ try {
689
+ if (this.stopping || this.batch) return;
690
+ // Requests of a process that is gone: never sent (queued) or unknown (running). Needs no lock.
691
+ for (const request of this.requests.unresolved()) {
692
+ if (request.pid === undefined || this.isAlive(request.pid)) continue;
693
+ if (request.status === 'queued') this.requests.finish(request.id, { status: 'refused', reason: 'the connector stopped before this question was sent' });
694
+ if (request.status === 'running') this.requests.finish(request.id, { status: 'unknown', reason: 'the connector stopped in the middle of this question' });
695
+ }
696
+ const api = await this.ensureApi();
697
+ const journal = this.adapter.openJournal(this.home, this.network.genesis, this.settings.owner, this.payersRoot);
698
+ try {
699
+ const report = await this.adapter.recoverJournal(api, journal, this.requests.unresolved().map((r) => r.id));
700
+ this.frozen = report.unresolved.length > 0;
701
+ for (const [id, found] of Object.entries(report.answers)) {
702
+ this.requests.finish(id, { status: 'answered', answer: found.answer, channel: found.channelId, replayed: true });
703
+ }
704
+ } catch (error) {
705
+ if (/** @type {any} */ (error)?.code === 'JOURNAL_LOCKED') return; // another session is paying: next time
706
+ this.log(`housekeeping (journal): ${brief(error)}`); // the refunds below still run
707
+ }
708
+ for (const refund of await this.adapter.refundOrphans(api, this.key.pair, journal)) {
709
+ if (refund.outcome === 'refunded' || refund.outcome === 'unknown') {
710
+ appendFileSync(join(this.home.dir, 'refunds.jsonl'), `${JSON.stringify({ channel: refund.channel, at: this.clock.now(), confirmed: refund.outcome === 'refunded' })}\n`, { mode: 0o600 });
711
+ }
712
+ if (refund.outcome === 'failed' || refund.outcome === 'unknown') this.log(`refund ${refund.channel}: ${refund.outcome}`);
713
+ }
714
+ } catch (error) {
715
+ this.log(`housekeeping: ${brief(error)}`);
716
+ } finally {
717
+ this.scheduleHousekeeping();
718
+ }
719
+ }
720
+
721
+ /** Channels the connector sent a timeout refund for: channel → confirmed (true) or not (false). */
722
+ refundedChannels() {
723
+ /** @type {Map<string, boolean>} */
724
+ const refunds = new Map();
725
+ try {
726
+ for (const line of readFileSync(join(this.home.dir, 'refunds.jsonl'), 'utf8').split('\n').filter(Boolean)) {
727
+ const { channel, confirmed } = JSON.parse(line);
728
+ refunds.set(channel, refunds.get(channel) === true || confirmed !== false);
729
+ }
730
+ } catch {
731
+ // no refunds yet
732
+ }
733
+ return refunds;
734
+ }
735
+
736
+ // ── Reading ───────────────────────────────────────────────────────────────────────────────
737
+
738
+ /** claim.json as `flop-mcp claim` left it, or the problem reading it (never "never claimed" for a damaged file). */
739
+ claimRecord() {
740
+ try {
741
+ const { claim, forward } = readClaimRecord(this.home.claimFile);
742
+ return { claim, forward };
743
+ } catch (error) {
744
+ return { problem: brief(error) };
745
+ }
746
+ }
747
+
748
+ /** @param {unknown} requestId */
749
+ result(requestId) {
750
+ return this.requests.get(requestId);
751
+ }
752
+
753
+ async status() {
754
+ const { settings } = this;
755
+ let usedToday;
756
+ let committedTotal = 0n;
757
+ let ledgerProblem;
758
+ try {
759
+ const lines = readLedger(this.home.ledgerFile);
760
+ usedToday = dayTotal(lines, this.clock.now());
761
+ const voided = new Set(lines.filter((l) => 'void' in l).map((l) => l.txHash));
762
+ for (const line of lines) if (!('void' in line) && !voided.has(line.txHash)) committedTotal += BigInt(line.amount);
763
+ } catch (error) {
764
+ ledgerProblem = brief(error);
765
+ }
766
+ const open = this.batch ?? this.settlingBatch;
767
+ /** @type {any} */
768
+ const report = {
769
+ own: this.own,
770
+ network: this.network.name, sandbox: process.env.FLOP_MCP_SANDBOX ?? 'none', keyAddress: this.key.address, owner: settings.owner, payersRoot: this.payersRoot,
771
+ connection: this.connection, session: null, sessionProblem: null, feeMoneyPlanck: undefined,
772
+ limits: { perAskPlanck: settings.maxFlopPerAsk, perDayPlanck: settings.maxFlopPerDay, usedTodayPlanck: usedToday, totalPlanck: settings.maxFlopTotal, committedPlanck: committedTotal, ledgerProblem },
773
+ batch: open ? { state: this.batch ? 'open' : 'settling', channel: open.channel, settlesBy: this.batch ? this.settlesBy(open) : undefined } : { state: 'idle' },
774
+ frozen: this.frozen,
775
+ // On a network whose faucet takes this key's own signed claim (testnet), where `flop-mcp claim` stands.
776
+ faucet: this.network.quickGrant?.signed ? this.claimRecord() : undefined,
777
+ ownerBalancePlanck: undefined,
778
+ miners: this.miners.map((m) => ({ id: m.id, model: m.model, ...(this.minerChecks.get(m.id) ?? { ready: false, checkedAt: 0, problem: 'not checked yet' }) })),
779
+ channels: [],
780
+ };
781
+ let api;
782
+ try {
783
+ api = await this.ensureApi();
784
+ } catch {
785
+ report.connection = this.connection; // why it failed
786
+ return report;
787
+ }
788
+ report.connection = this.connection; // a fresh process (flop-mcp status) connects just now
789
+ try {
790
+ if (this.own) {
791
+ // The wallet is the owner: no session to read, and its fee money is its own balance.
792
+ report.ownerBalancePlanck = await this.adapter.freeBalance(api, settings.owner);
793
+ } else {
794
+ report.session = await this.adapter.readSession(api, settings.owner, this.key.address);
795
+ report.sessionProblem = sessionProblem(report.session, { minLeftPlanck: MIN_LEFT_PLANCK });
796
+ report.feeMoneyPlanck = await this.adapter.freeBalance(api, this.key.address);
797
+ report.ownerBalancePlanck = await this.adapter.freeBalance(api, settings.owner);
798
+ }
799
+ const refunded = this.refundedChannels();
800
+ const served = [...new Set([...this.requests.all().values()].filter((r) => r.status === 'answered' && r.channel).map((r) => String(r.channel)))].slice(-5);
801
+ for (const channel of served) {
802
+ let outcome;
803
+ if (this.batch?.answered.has(channel)) outcome = 'open';
804
+ else if (this.settlingBatch?.answered.has(channel)) outcome = 'settling';
805
+ else {
806
+ const state = await this.adapter.channelState(api, channel);
807
+ const refund = refunded.get(channel);
808
+ const closedOutcome = refund === undefined ? 'settled' : refund ? 'refunded' : 'closed';
809
+ outcome = state === 'Closed' || state === 'gone' ? closedOutcome : state === 'Open' ? 'waiting_refund' : 'unknown';
810
+ }
811
+ report.channels.push({ channel, outcome });
812
+ }
813
+ } catch (error) {
814
+ report.connection = brief(error);
815
+ }
816
+ return report;
817
+ }
818
+
819
+ // ── Stopping ──────────────────────────────────────────────────────────────────────────────
820
+
821
+ /** Stop taking questions; give an open batch the grace period to start its close; then let go. @param {number} [graceMs] */
822
+ async stop(graceMs = TIMINGS.shutdownGraceMs) {
823
+ this.stopping = true;
824
+ this.cancelHousekeeping?.();
825
+ this.cancelHousekeeping = undefined;
826
+ if (this.batch) void this.settleBatch(this.batch);
827
+ const cancelWait = new AbortController();
828
+ await Promise.race([this.tail, this.clock.sleep(graceMs, cancelWait.signal).catch(() => {})]);
829
+ cancelWait.abort();
830
+ this.batch?.cancelIdle?.();
831
+ this.batch?.cancelDeadline?.();
832
+ await this.api?.disconnect?.().catch(() => {});
833
+ }
834
+ }