@north-light/cli 0.3.671 → 0.3.673

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 (51) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/execution-start.d.ts +1 -1
  4. package/dist/api/dto/nodes.d.ts +2 -0
  5. package/dist/core/pool-credential-store.d.ts +4 -0
  6. package/dist/core/pool-credential-store.js +1 -1
  7. package/dist/core/runtime/provider-credential-gate.d.ts +2 -2
  8. package/dist/core/runtime/provider-credential-gate.js +2 -2
  9. package/dist/core/runtime/runner/blaxel/image-build.d.ts +3 -0
  10. package/dist/core/runtime/runner/blaxel/image-build.js +5 -5
  11. package/dist/core/runtime/runner/machine/call.d.ts +5 -0
  12. package/dist/core/runtime/runner/machine/call.js +2 -2
  13. package/dist/core/runtime/runner/machine/ops.d.ts +2 -1
  14. package/dist/core/runtime/spawn.d.ts +2 -0
  15. package/dist/core/runtime/spawn.js +2 -2
  16. package/dist/core/subscription-state.d.ts +2 -0
  17. package/dist/core/subscription-state.js +1 -1
  18. package/dist/daemon/api/handlers/broker-ops.d.ts +12 -1
  19. package/dist/daemon/api/handlers/broker-ops.js +1 -1
  20. package/dist/daemon/api/handlers/execution-start.d.ts +9 -1
  21. package/dist/daemon/api/handlers/execution-start.js +2 -2
  22. package/dist/daemon/api/handlers/nodes.js +1 -1
  23. package/dist/daemon/machine-link/holder.js +4 -4
  24. package/package.json +3 -3
  25. package/packages/crouter-api/dist/api/contract.js +1 -1
  26. package/packages/crouter-api/dist/core/pool-credential-store.js +44 -25
  27. package/packages/crouter-api/dist/core/review/document.js +143 -0
  28. package/packages/crouter-api/dist/core/review/project.js +45 -0
  29. package/packages/crouter-api/dist/core/runtime/launch-recipe.js +45 -0
  30. package/packages/crouter-api/dist/core/runtime/provider-credential-gate.js +4 -4
  31. package/packages/crouter-api/dist/core/runtime/runner/blaxel/image-build.js +13 -5
  32. package/packages/crouter-api/dist/core/runtime/runner/blaxel/release-image.js +96 -0
  33. package/packages/crouter-api/dist/core/runtime/runner/blaxel/runner.js +170 -0
  34. package/packages/crouter-api/dist/core/runtime/runner/machine/call.js +11 -2
  35. package/packages/crouter-api/dist/core/runtime/spawn.js +88 -3
  36. package/packages/crouter-api/dist/core/runtime/stop-signals.js +46 -0
  37. package/packages/crouter-api/dist/core/secrets/blaxel-launch.js +104 -0
  38. package/packages/crouter-api/dist/core/subscription-state.js +18 -2
  39. package/packages/crouter-api/dist/daemon/api/handlers/broker-ops.js +701 -0
  40. package/packages/crouter-api/dist/daemon/api/handlers/execution-start.js +120 -0
  41. package/packages/crouter-api/dist/daemon/api/handlers/node-records.js +113 -0
  42. package/packages/crouter-api/dist/daemon/api/handlers/telemetry-record.js +34 -0
  43. package/packages/crouter-api/dist/daemon/machine-link/holder.js +1 -1
  44. package/packages/crouter-api/dist/daemon/review/companion.js +29 -0
  45. package/packages/crouter-api/dist/daemon/review/deliver.js +13 -0
  46. package/packages/crouter-api/dist/daemon/review/finish.js +170 -0
  47. package/packages/crouter-api/package.json +1 -1
  48. package/packages/crouter-identity/package.json +1 -1
  49. package/packages/crouter-plugin/package.json +3 -3
  50. package/runtime.lock.json +14 -14
  51. package/scripts/sandbox-start.mjs +8 -1
@@ -40,7 +40,17 @@ import { awaitBrokerViewSocket } from './view-socket.js';
40
40
  import { readLogSnapshot } from '../events/read.js';
41
41
  import { transition } from './lifecycle.js';
42
42
  import { beginBootFaultAttempt } from '../canvas/recovery.js';
43
- import { headlessBrokerHost } from './host.js';
43
+ import { headlessBrokerHost, brokerLaunchJson } from './host.js';
44
+ import { openDb, withCanvasWrite } from '../canvas/db.js';
45
+ import { warmNodeRepos } from '../graph/reader.js';
46
+ import { mintNodeToken } from '../canvas/node-tokens.js';
47
+ import { personIdAsync } from '../canvas/person.js';
48
+ import { recordLaunch } from '../canvas/canvas.js';
49
+ import { setExecutionLaunchJson } from '../canvas/executions.js';
50
+ import { acceptedRelease, remoteMachineEnvironmentOf } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
51
+ import { enqueueMachineCall, awaitMachineCall } from './runner/machine/call.js';
52
+ import { MachineLostError, MachineOfflineError } from './runner/machine/ops.js';
53
+ import { isDrained } from '../../daemon/drain.js';
44
54
  import { ensureDaemon } from '../../daemon/manage.js';
45
55
  import { readConfig } from '../config.js';
46
56
  import { modelRequestFromConfig, unregisteredConcreteModel, unroutableConcreteModel } from '../model-routes.js';
@@ -260,6 +270,72 @@ export function resolveSpawner(parent, ctxNodeId, root) {
260
270
  }
261
271
  return spawner;
262
272
  }
273
+ /** Launch a just-born node on its remote machine in two transactions: the node and execution rows are committed (as a birth always does), then one
274
+ * transaction renders the start data, mints the token and queues the `start` call; the call is awaited after that commit. The bundle's network work
275
+ * (GitHub token, blob store) runs before that transaction opens. 'failed': nothing started, the caller freezes the node for the lifecycle tick to wake.
276
+ * 'uncertain': the call was sent and its answer lost, so the Mac may have a broker: the execution stays launching and the node stays active, and the
277
+ * tick's `status` of that execution decides (the machine runner's rule). 'full': the daemon is drained or at its broker cap, so nothing was begun. */
278
+ async function startOnMachine(meta, environmentId, inv) {
279
+ // Loaded here: the handlers import the runtime that imports this module.
280
+ const { buildStartBundle } = await import('../../daemon/api/handlers/execution-start.js');
281
+ const { renderCarriedStart } = await import('../../daemon/api/handlers/broker-ops.js');
282
+ // The checks reviveNode makes before it begins an execution: a drained daemon starts nothing, and the execution cap is enforced by the insert.
283
+ if (await isDrained())
284
+ return 'full';
285
+ let executionId;
286
+ try {
287
+ executionId = await beginExecution(meta.node_id, { daemonEpoch: boundFleet().epoch(), cap: brokerThresholdsForDaemon().automaticReviveCap, runner: 'machine', release: acceptedRelease() });
288
+ }
289
+ catch (error) {
290
+ if (error instanceof ExecutionCapReached)
291
+ return 'full';
292
+ emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
293
+ return 'failed';
294
+ }
295
+ let callId;
296
+ try {
297
+ inv.env = { ...inv.env, CRTR_EXECUTION_ID: executionId };
298
+ const launchJson = await brokerLaunchJson(meta.node_id, inv, meta.cwd);
299
+ await setExecutionLaunchJson(executionId, launchJson);
300
+ const execId = executionId;
301
+ await warmNodeRepos(await openDb(), meta.node_id);
302
+ const sub = meta.sub ?? await personIdAsync();
303
+ const bundle = await buildStartBundle({ nodeId: meta.node_id, app: meta.grantee ?? 'app:terminal', sub, launchJson, runner: 'machine' });
304
+ callId = await withCanvasWrite(async (db) => {
305
+ // The reader is built here, after the goal and every birth write have landed, so the rendered bearings see them.
306
+ const start = await renderCarriedStart(meta.node_id);
307
+ const nodeToken = await mintNodeToken(db, execId, meta.node_id, new Date().toISOString());
308
+ return await enqueueMachineCall(environmentId, 'start', {
309
+ executionId: execId, nodeId: meta.node_id, attempt: 1, sandboxName: null, release: acceptedRelease(), launchJson, cwd: meta.cwd, resuming: false,
310
+ nodeToken, bundle, start,
311
+ });
312
+ });
313
+ }
314
+ catch (error) {
315
+ emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
316
+ await abortExecution(executionId, { reason: 'launch_failed' });
317
+ return 'failed';
318
+ }
319
+ try {
320
+ await awaitMachineCall(environmentId, 'start', callId);
321
+ }
322
+ catch (error) {
323
+ emitEvent({ level: 'warn', event: 'broker.create_start_failed', node_id: meta.node_id, error });
324
+ // Sent and unanswered (the link dropped, or the lease ran out): the Mac may have spawned the broker, so the execution and its token stay.
325
+ if (error instanceof MachineLostError || (error instanceof MachineOfflineError && error.sent))
326
+ return 'uncertain';
327
+ await abortExecution(executionId, { reason: 'launch_failed' });
328
+ return 'failed';
329
+ }
330
+ // The Mac has confirmed the start: a failure to record it must not end a running execution.
331
+ try {
332
+ await recordLaunch(meta.node_id, new Date().toISOString());
333
+ }
334
+ catch (error) {
335
+ emitEvent({ level: 'warn', event: 'broker.create_start_record_failed', node_id: meta.node_id, error });
336
+ }
337
+ return 'started';
338
+ }
263
339
  export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCreated) {
264
340
  try {
265
341
  ensureDaemon();
@@ -486,9 +562,18 @@ export async function spawnChildPrepared(opts, beforeBrokerLaunch, afterNodeCrea
486
562
  // dormant with its goal kept, and the node-lifecycle lane wakes it through `reviveNode`, the one launch path that chooses the
487
563
  // Blaxel or machine runner and runs the bill check.
488
564
  if (await remoteEnvironmentOf(meta.profile_id ?? null) !== null) {
489
- await setFrozen(meta.node_id, new Date().toISOString());
565
+ const frozenAt = new Date().toISOString();
566
+ // A create that asked to start, for a node on a machine this control plane reaches over a link: the start call carries everything the
567
+ // Mac needs, so the node is never left dormant for the lifecycle tick to wake.
568
+ const machine = opts.start === true ? await remoteMachineEnvironmentOf(meta.profile_id ?? null) : null;
569
+ if (machine !== null) {
570
+ const started = await startOnMachine(meta, machine, inv);
571
+ if (started === 'started' || started === 'uncertain')
572
+ return { node: meta, frozen: false, window: null, session: null };
573
+ }
574
+ await setFrozen(meta.node_id, frozenAt);
490
575
  emitEvent({ level: 'info', event: 'broker.frozen', node_id: meta.node_id, fields: { reason: 'remote_environment' } });
491
- return { node: await getNode(meta.node_id), frozen: true, window: null, session: null };
576
+ return { node: { ...meta, frozen_at: frozenAt }, frozen: true, window: null, session: null };
492
577
  }
493
578
  const slot = await fleet.reserveSlot(meta.node_id);
494
579
  // The slot is held while the launcher measures the app's memory; a denial gives it back before freezing.
@@ -0,0 +1,46 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { jobDir } from '../canvas/paths.js';
4
+ const SIGNALS = ['pushedFinal'];
5
+ function signalPath(nodeId, signal) {
6
+ return join(jobDir(nodeId), `.${signal}`);
7
+ }
8
+ /** Which broker process a marker belongs to. `broker.ts` exports
9
+ * `CRTR_BROKER_PID` into its own env, so inside a broker this IS `process.pid`
10
+ * and every crtr command it spawns inherits the same value. Both the write and
11
+ * the read side go through this so a marker written by a command is recognized
12
+ * by the broker that consumes it — and so neither side is thrown off by an
13
+ * outer broker's pid leaking in through the environment. */
14
+ function brokerIdentity() {
15
+ return process.env['CRTR_BROKER_PID'] ?? String(process.pid);
16
+ }
17
+ /** Record a successful command outcome for this broker process. The stophook
18
+ * consumes the marker at settlement, so no broker-side canvas read is needed to
19
+ * recognize the command the node itself just completed. */
20
+ export function markStopSignal(nodeId, signal, identity = brokerIdentity()) {
21
+ mkdirSync(jobDir(nodeId), { recursive: true });
22
+ writeFileSync(signalPath(nodeId, signal), identity);
23
+ }
24
+ /** Consume command outcomes from this broker's just-settled turn. Markers from
25
+ * an earlier crashed broker are discarded rather than bleeding into its successor. */
26
+ export function consumeStopSignals(nodeId, identity = brokerIdentity()) {
27
+ const signals = { pushedFinal: false };
28
+ for (const signal of SIGNALS) {
29
+ const path = signalPath(nodeId, signal);
30
+ if (!existsSync(path))
31
+ continue;
32
+ const brokerPid = readFileSync(path, 'utf8').trim();
33
+ rmSync(path, { force: true });
34
+ if (brokerPid === identity)
35
+ signals[signal] = true;
36
+ }
37
+ return signals;
38
+ }
39
+ /** Discard any marker left by an earlier run of this same broker — a run that
40
+ * errored or was interrupted returns before settlement consumes its markers, and
41
+ * the pid stamp cannot tell those apart from the current run's. Called when a new
42
+ * user-directed run begins, never on an in-run retry. */
43
+ export function clearStopSignals(nodeId) {
44
+ for (const signal of SIGNALS)
45
+ rmSync(signalPath(nodeId, signal), { force: true });
46
+ }
@@ -0,0 +1,104 @@
1
+ // The control plane's `BlaxelRunnerDeps.launchContext` (design-fleet, Components: Runner; C-D4): what a Blaxel `start` needs beyond the execution —
2
+ // the environment's image and memory, the API url, a signed release URL with its sha256, and the environment's opened secrets.
3
+ // Daemon-only: it reads the database and the secrets key.
4
+ import { createHash, createHmac } from 'node:crypto';
5
+ import { openDb } from '../canvas/db.js';
6
+ import { blobStore } from '../blobs/index.js';
7
+ import { environmentOfNode, packagesTokenFor } from '../../daemon/api/environment-of.js';
8
+ import { EnvironmentImagePending } from '../../daemon/reconcilers/node-lifecycle/remote-wake.js';
9
+ import { resolveEnvironmentImage } from '../../daemon/reconcilers/recipe-image.js';
10
+ import { parseReleaseImagePointer, releaseImageKey } from '../runtime/runner/blaxel/release-image.js';
11
+ import { environmentSecrets } from './environment-secrets.js';
12
+ import { environmentOwnerProfile, profileInApp } from './environment-owner.js';
13
+ export const BASE_IMAGE = 'blaxel/base-image:latest';
14
+ /** How long the signed release URL stays valid. */
15
+ export const RELEASE_URL_TTL_S = 15 * 60;
16
+ /** The sandbox image a launch starts from: the environment's recipe image when it has one; otherwise the release's own image (`releaseImage`, from the pointer object
17
+ * beside the release) when the release was published with one; otherwise the stock image, whose bootstrap installs the release at boot. */
18
+ export function launchImage(environment, releaseImage) {
19
+ if (environment.state === 'image')
20
+ return environment.ref;
21
+ return releaseImage ?? BASE_IMAGE;
22
+ }
23
+ export function releaseSignerFromEnv(env = process.env) {
24
+ const need = (name) => { const v = env[name]; if (!v)
25
+ throw new Error(`${name} is required to sign release URLs`); return v; };
26
+ return { bucket: need('CRTR_R2_BUCKET'), endpoint: need('CRTR_R2_ENDPOINT'), accessKeyId: need('CRTR_R2_ACCESS_KEY_ID'), secretAccessKey: need('CRTR_R2_SECRET_ACCESS_KEY') };
27
+ }
28
+ const sha256hex = (data) => createHash('sha256').update(data).digest('hex');
29
+ const hmac = (key, data) => createHmac('sha256', key).update(data).digest();
30
+ const encode = (value) => encodeURIComponent(value).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
31
+ /** A SigV4 query-signed GET (path style, region `auto`) of `key`, valid `ttlS` seconds from `now`. */
32
+ export function presignGet(signer, key, ttlS, now = new Date()) {
33
+ const base = new URL(signer.endpoint);
34
+ const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, '');
35
+ const date = amzDate.slice(0, 8);
36
+ const scope = `${date}/auto/s3/aws4_request`;
37
+ const path = `/${encode(signer.bucket)}/${key.split('/').map(encode).join('/')}`;
38
+ const query = [
39
+ ['X-Amz-Algorithm', 'AWS4-HMAC-SHA256'], ['X-Amz-Credential', `${signer.accessKeyId}/${scope}`], ['X-Amz-Date', amzDate],
40
+ ['X-Amz-Expires', String(ttlS)], ['X-Amz-SignedHeaders', 'host'],
41
+ ];
42
+ const canonicalQuery = query.sort(([a], [b]) => a < b ? -1 : 1).map(([k, v]) => `${encode(k)}=${encode(v)}`).join('&');
43
+ const request = ['GET', path, canonicalQuery, `host:${base.host}\n`, 'host', 'UNSIGNED-PAYLOAD'].join('\n');
44
+ const toSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256hex(request)].join('\n');
45
+ const signingKey = hmac(hmac(hmac(hmac(`AWS4${signer.secretAccessKey}`, date), 'auto'), 's3'), 'aws4_request');
46
+ const signature = createHmac('sha256', signingKey).update(toSign).digest('hex');
47
+ return `${base.origin}${path}?${canonicalQuery}&X-Amz-Signature=${signature}`;
48
+ }
49
+ /** Reads the control plane's settings from the environment: `CRTR_PUBLIC_API_URL` (where a sandbox reaches `/v1`) and the four `CRTR_R2_*` variables. */
50
+ export function blaxelLaunchDepsFromEnv(env = process.env) {
51
+ const apiUrl = env['CRTR_PUBLIC_API_URL'];
52
+ if (!apiUrl || !/^https?:\/\//.test(apiUrl))
53
+ throw new Error('CRTR_PUBLIC_API_URL must be an http(s) URL for the Blaxel runner');
54
+ return { apiUrl, signer: releaseSignerFromEnv(env) };
55
+ }
56
+ async function defaultReleaseSha(version) {
57
+ const bytes = await (await blobStore()).get(`releases/${version}/runtime.tar.gz.sha256`);
58
+ return bytes === null ? null : bytes.toString('utf8');
59
+ }
60
+ async function defaultReleaseImage(version) {
61
+ const bytes = await (await blobStore()).get(releaseImageKey(version));
62
+ return bytes === null ? null : bytes.toString('utf8');
63
+ }
64
+ export function createBlaxelLaunchContext(deps) {
65
+ return async (input) => {
66
+ const db = await openDb();
67
+ const node = await db.prepare('SELECT profile_id, grantee FROM node_rows WHERE node_id = ?').get(input.nodeId);
68
+ if (node === undefined)
69
+ throw new Error(`no node ${input.nodeId}`);
70
+ if (node.profile_id === null)
71
+ throw new Error(`node ${input.nodeId} has no profile, so it has no person`);
72
+ const person = await db.prepare('SELECT person FROM profiles WHERE id = ?').get(node.profile_id);
73
+ if (person === undefined)
74
+ throw new Error(`profile ${node.profile_id} has no row`);
75
+ const app = node.grantee ?? 'app:terminal';
76
+ const environmentId = await environmentOfNode(node.profile_id);
77
+ const image = await resolveEnvironmentImage(environmentId);
78
+ if (image.state === 'pending')
79
+ throw new EnvironmentImagePending(environmentId, image.error);
80
+ const environment = await db.prepare('SELECT memory_mb FROM environments WHERE object = ?').get(environmentId);
81
+ if (environment === undefined)
82
+ throw new Error(`no environment ${environmentId}`);
83
+ // The environment's owner is an app or a profile object; a profile's identity is `profile:<profile id>`.
84
+ const ownerProfile = await environmentOwnerProfile(environmentId);
85
+ const ownerInApp = ownerProfile !== null && await profileInApp(ownerProfile, app);
86
+ const sha = ((await (deps.releaseSha ?? defaultReleaseSha)(input.release)) ?? '').trim().split(/\s+/)[0] ?? '';
87
+ if (!/^[0-9a-f]{64}$/.test(sha))
88
+ throw new Error(`release ${input.release} has no sha256 object (releases/${input.release}/runtime.tar.gz.sha256)`);
89
+ // Only an environment with no recipe image can use the release image, so only then is the pointer read.
90
+ const pointer = image.state === 'base' ? await (deps.releaseImage ?? defaultReleaseImage)(input.release) : null;
91
+ const releaseImage = pointer === null ? null : parseReleaseImagePointer(pointer, input.release, sha);
92
+ const packagesToken = await packagesTokenFor(environmentId);
93
+ const secrets = await environmentSecrets({ person: person.person, app, ownerProfile, ownerProfileInApp: ownerInApp, includeDeployment: false });
94
+ return {
95
+ image: launchImage(image, releaseImage),
96
+ memoryMb: Number(environment.memory_mb),
97
+ apiUrl: deps.apiUrl,
98
+ releaseUrl: presignGet(deps.signer, `releases/${input.release}/runtime.tar.gz`, RELEASE_URL_TTL_S, deps.now?.()),
99
+ releaseSha256: sha,
100
+ // Profile rows merge last, so a profile's own NODE_AUTH_TOKEN wins.
101
+ secrets: packagesToken !== null ? { NODE_AUTH_TOKEN: packagesToken, ...secrets } : secrets,
102
+ };
103
+ };
104
+ }
@@ -52,9 +52,8 @@ function toPublic(person, provider, r, cooldowns = []) {
52
52
  const entry = { label: row.label, refresh, access, expires: r.expires, rateLimitedUntil: row.authFailure || !row.lastRateLimitedAt ? row.rateLimitedUntil : Math.min(row.rateLimitedUntil, row.lastRateLimitedAt + MAX_RATE_LIMIT_COOLDOWN_MS), lastAttemptAt: row.lastAttemptAt, lastRateLimitedAt: row.lastRateLimitedAt, ...(row.authFailure ? { authFailure: row.authFailure } : {}), ...(r.vendor_account_id ? { accountId: r.vendor_account_id } : {}), ...(r.client_id ? { clientId: r.client_id } : {}), ...(cooldowns.length ? { modelCooldowns: Object.fromEntries(cooldowns.map((cooldown) => [cooldown.family, cooldown.lastRateLimitedAt ? Math.min(cooldown.rateLimitedUntil, cooldown.lastRateLimitedAt + MAX_RATE_LIMIT_COOLDOWN_MS) : cooldown.rateLimitedUntil])) } : {}) };
53
53
  return { row, entry };
54
54
  }
55
- async function loadCooldowns(db, person, provider) {
55
+ function groupCooldowns(rows) {
56
56
  const out = new Map();
57
- const rows = await db.prepare('SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family').all(person, provider);
58
57
  for (const r of rows) {
59
58
  const list = out.get(r.account_id) ?? [];
60
59
  list.push({ family: r.family, rateLimitedUntil: r.rate_limited_until, lastRateLimitedAt: r.last_rate_limited_at });
@@ -62,12 +61,29 @@ async function loadCooldowns(db, person, provider) {
62
61
  }
63
62
  return out;
64
63
  }
64
+ async function loadCooldowns(db, person, provider) {
65
+ return groupCooldowns(await db.prepare('SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? AND provider_id=? ORDER BY family').all(person, provider));
66
+ }
65
67
  /** The person's accounts at one provider in pool order, tokens opened. `forUpdate` row-locks them. */
66
68
  async function loadPool(db, person, provider, forUpdate = false) {
67
69
  const rows = await db.prepare(`SELECT ${COLUMNS} FROM model_accounts WHERE person=? AND provider_id=? ORDER BY position${forUpdate ? ' FOR UPDATE' : ''}`).all(person, provider);
68
70
  const cooldowns = await loadCooldowns(db, person, provider);
69
71
  return rows.map((r) => toPublic(person, provider, r, cooldowns.get(r.id)));
70
72
  }
73
+ /** Every managed provider's pool for the person in two statements (accounts, cooldowns), tokens opened. A provider with no account is absent. */
74
+ export async function readAllSubscriptionPools() {
75
+ const person = await personIdAsync();
76
+ const db = await openDb();
77
+ const rows = await db.prepare(`SELECT provider_id,${COLUMNS} FROM model_accounts WHERE person=? ORDER BY provider_id,position`).all(person);
78
+ const cooldowns = groupCooldowns(await db.prepare('SELECT account_id,family,rate_limited_until,last_rate_limited_at FROM model_account_cooldowns WHERE person=? ORDER BY family').all(person));
79
+ const pools = new Map();
80
+ for (const r of rows) {
81
+ const list = pools.get(r.provider_id) ?? [];
82
+ list.push(toPublic(person, r.provider_id, r, cooldowns.get(r.id)).entry);
83
+ pools.set(r.provider_id, list);
84
+ }
85
+ return pools;
86
+ }
71
87
  /** One account by 1-based position or label, row-locked. */
72
88
  async function lockedAccount(db, person, provider, ref) {
73
89
  const needle = ref.trim().toLowerCase();