@cortexkit/common-auth 0.11.8 → 0.13.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.
Files changed (43) hide show
  1. package/README.md +2 -2
  2. package/dist/auth-menu/accounts.d.ts +11 -2
  3. package/dist/auth-menu/accounts.js +12 -26
  4. package/dist/claustrum/enrollment.d.ts +26 -0
  5. package/dist/claustrum/enrollment.js +108 -0
  6. package/dist/claustrum/index.d.ts +1 -1
  7. package/dist/claustrum/index.js +1 -1
  8. package/dist/commands/builtins.js +123 -102
  9. package/dist/commands/model.d.ts +42 -1
  10. package/dist/commands/pi.d.ts +2 -1
  11. package/dist/commands/pi.js +40 -12
  12. package/dist/commands/seam.js +3 -0
  13. package/dist/fs/atomic-write.d.ts +13 -0
  14. package/dist/fs/atomic-write.js +52 -0
  15. package/dist/opencode2/index.d.ts +2 -2
  16. package/dist/opencode2/index.js +1 -1
  17. package/dist/opencode2/integration.d.ts +45 -11
  18. package/dist/opencode2/integration.js +58 -9
  19. package/dist/quota/format.d.ts +46 -0
  20. package/dist/quota/format.js +138 -0
  21. package/dist/quota/index.d.ts +2 -0
  22. package/dist/quota/index.js +1 -0
  23. package/dist/store/attribution.js +1 -0
  24. package/dist/store/errors.d.ts +2 -2
  25. package/dist/store/identity.js +2 -0
  26. package/dist/store/index.d.ts +2 -1
  27. package/dist/store/mutate.d.ts +22 -2
  28. package/dist/store/mutate.js +140 -34
  29. package/dist/store/pool.d.ts +9 -2
  30. package/dist/store/pool.js +4 -0
  31. package/dist/store/publication.d.ts +47 -0
  32. package/dist/store/publication.js +304 -0
  33. package/dist/store/pull.js +6 -1
  34. package/dist/store/refresh.js +2 -0
  35. package/dist/store/reserved.d.ts +3 -0
  36. package/dist/store/reserved.js +13 -0
  37. package/dist/store/rows.d.ts +62 -13
  38. package/dist/store/rows.js +331 -42
  39. package/dist/store/runtime.js +13 -1
  40. package/dist/store/schema.d.ts +18 -0
  41. package/dist/store/schema.js +58 -2
  42. package/dist/store/torn.js +1 -1
  43. package/package.json +1 -1
@@ -0,0 +1,138 @@
1
+ // The one quota wording every surface shows: the command menu's dialogs on
2
+ // OpenCode and Pi, the terminal auth menu, and the plugins' sidebars. Each of
3
+ // them calls `formatQuota` (or `quotaTextParts` for one line per window), so
4
+ // the wording cannot drift between plugins or between a dialog and a sidebar.
5
+ //
6
+ // The rules: a window is named by its length (`5h`, `7d`), or, for a window
7
+ // that binds only one model family, by the label the plugin stored it under.
8
+ // Every figure is "% left". A window the provider did not report (an absence
9
+ // record or a retirement tombstone) is left out rather than written as "not
10
+ // reported". A reset is a short time from now (`resets 2h`). A reading older
11
+ // than fifteen minutes says how old it is (`checked 3h ago`).
12
+ //
13
+ // Like the rest of this module it reads no clock: `now` is a parameter.
14
+ import { ALL_SCOPE } from './map.js';
15
+ /** A reading older than this is marked with its age. */
16
+ export const QUOTA_STALE_AFTER_MS = 15 * 60_000;
17
+ /** What `formatQuota` returns when there is no reading at all. */
18
+ export const NO_QUOTA_READING = 'no quota reading yet';
19
+ /**
20
+ * What `formatQuota` returns when the provider answered but reported no
21
+ * limit for any window (every window is an absence record or a tombstone).
22
+ */
23
+ export const NO_LIMITS_REPORTED = 'no limits reported';
24
+ /**
25
+ * A length or a time span in its largest whole-ish unit: `45m`, `5h`, `3d`.
26
+ * Spans under an hour are minutes, under a day hours, otherwise days, each
27
+ * rounded to the nearest unit and never shown as zero.
28
+ */
29
+ function shortSpan(ms) {
30
+ const minutes = Math.max(1, Math.round(ms / 60_000));
31
+ if (minutes < 60)
32
+ return `${minutes}m`;
33
+ const hours = Math.round(minutes / 60);
34
+ if (hours < 24)
35
+ return `${hours}h`;
36
+ return `${Math.max(1, Math.round(minutes / 1440))}d`;
37
+ }
38
+ /** A stored window length in minutes as its exact name: `5h`, `7d`, `90m`. */
39
+ function lengthName(minutes) {
40
+ if (minutes % 1440 === 0)
41
+ return `${minutes / 1440}d`;
42
+ if (minutes % 60 === 0)
43
+ return `${minutes / 60}h`;
44
+ return `${minutes}m`;
45
+ }
46
+ /**
47
+ * The name a window is shown under. A general window (scope `all`) is named
48
+ * by its stored length; a model-scoped window keeps the label the plugin
49
+ * stored it under, which already names the model (`seven_day_opus`). A
50
+ * general window stored without a length (a snapshot from before lengths
51
+ * were recorded) falls back to its label.
52
+ */
53
+ export function quotaWindowName(limit) {
54
+ if (limit.scope !== ALL_SCOPE || limit.windowMinutes === undefined)
55
+ return limit.label;
56
+ return lengthName(limit.windowMinutes);
57
+ }
58
+ function percentLeft(remaining) {
59
+ return `${Math.round(Math.min(100, Math.max(0, remaining)))}% left`;
60
+ }
61
+ function resetText(resetsAt, now) {
62
+ if (resetsAt === undefined)
63
+ return '';
64
+ const at = Date.parse(resetsAt);
65
+ // A reset already passed says nothing about the future; leave it out.
66
+ if (!Number.isFinite(at) || at <= now)
67
+ return '';
68
+ return `, resets ${shortSpan(at - now)}`;
69
+ }
70
+ /** Shortest window first, so `5h` reads before `7d`; unknown lengths last. */
71
+ function displayOrder(left, right) {
72
+ const l = left.windowMinutes;
73
+ const r = right.windowMinutes;
74
+ if (l !== undefined && r !== undefined && l !== r)
75
+ return l - r;
76
+ if ((l === undefined) !== (r === undefined))
77
+ return l === undefined ? 1 : -1;
78
+ if (left.scope !== right.scope) {
79
+ if (left.scope === ALL_SCOPE)
80
+ return -1;
81
+ if (right.scope === ALL_SCOPE)
82
+ return 1;
83
+ return left.scope < right.scope ? -1 : 1;
84
+ }
85
+ return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
86
+ }
87
+ /**
88
+ * The pieces of a quota text, in order: one per reported window
89
+ * (`5h 58% left, resets 2h`), then the credit budget when there is one, then
90
+ * `checked 3h ago` when the oldest piece shown is stale. Empty when nothing
91
+ * was reported; `formatQuota` turns that into a sentence. A caller printing
92
+ * one line per window (the terminal auth menu) uses these directly.
93
+ */
94
+ export function quotaTextParts(quota, options) {
95
+ if (!quota)
96
+ return [];
97
+ const { now } = options;
98
+ const full = (options.form ?? 'full') === 'full';
99
+ const parts = [];
100
+ const times = [];
101
+ const readings = quota.limits
102
+ .filter((limit) => limit.kind === 'reading' && limit.remainingPercent !== undefined)
103
+ .sort(displayOrder);
104
+ for (const limit of readings) {
105
+ times.push(limit.checkedAt);
106
+ parts.push(`${quotaWindowName(limit)} ${percentLeft(limit.remainingPercent ?? 0)}${full ? resetText(limit.resetsAt, now) : ''}`);
107
+ }
108
+ const budget = quota.budget;
109
+ if (budget) {
110
+ times.push(budget.checkedAt);
111
+ const figure = budget.reached
112
+ ? 'credits spent'
113
+ : budget.remainingPercent !== undefined
114
+ ? `credits ${percentLeft(budget.remainingPercent)}`
115
+ : 'credits available';
116
+ parts.push(`${figure}${full ? resetText(budget.resetsAt, now) : ''}`);
117
+ }
118
+ if (times.length > 0) {
119
+ const age = now - Math.min(...times);
120
+ if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS))
121
+ parts.push(`checked ${shortSpan(age)} ago`);
122
+ }
123
+ return parts;
124
+ }
125
+ /**
126
+ * A row's quota as one line: `5h 58% left · 7d 90% left` in the compact
127
+ * form, with `, resets 2h` after each window in the full form. With nothing
128
+ * reported it is `NO_QUOTA_READING`, or `NO_LIMITS_REPORTED` when the
129
+ * provider answered without a limit for any window.
130
+ */
131
+ export function formatQuota(quota, options) {
132
+ const parts = quotaTextParts(quota, options);
133
+ if (parts.length > 0)
134
+ return parts.join(' · ');
135
+ return quota && quota.limits.length > 0
136
+ ? NO_LIMITS_REPORTED
137
+ : NO_QUOTA_READING;
138
+ }
@@ -1,5 +1,7 @@
1
1
  export type { QuotaCodec } from './codec.js';
2
2
  export { quotaCodec } from './codec.js';
3
+ export type { QuotaTextForm, QuotaTextOptions } from './format.js';
4
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
3
5
  export type { CreditBudgetCleared, CreditBudgetEntry, CreditBudgetReading, QuotaAbsentEntry, QuotaEntry, QuotaMap, QuotaReadingEntry, QuotaRetiredEntry, } from './map.js';
4
6
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
5
7
  export type { ObservedBudget, ObservedPair, ObservedReading, QuotaObservation, } from './merge.js';
@@ -1,4 +1,5 @@
1
1
  export { quotaCodec } from './codec.js';
2
+ export { formatQuota, NO_LIMITS_REPORTED, NO_QUOTA_READING, QUOTA_STALE_AFTER_MS, quotaTextParts, quotaWindowName, } from './format.js';
2
3
  export { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, emptyQuotaMap, isQuotaMap, } from './map.js';
3
4
  export { isQuotaObservation, mergeQuotaObservation, QuotaCodecError, } from './merge.js';
4
5
  export { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from './projection.js';
@@ -16,6 +16,7 @@ export async function recordQuota(rt, id, attribution, observation) {
16
16
  if (!isCredentialEpoch(attribution?.credentialEpoch))
17
17
  throw refusal('pull', id, 'invalid-input', 'the credential epoch the reading was issued for must be a positive safe integer');
18
18
  await withTransaction(ctx, locks, progress, { operation: 'pull', rowId: id }, async (tx) => {
19
+ tx.assertNotStaged(id);
19
20
  const row = tx.row(id);
20
21
  if (!row)
21
22
  throw unknownRow('pull', id);
@@ -1,6 +1,6 @@
1
1
  import type { StoredCredential } from './schema.js';
2
2
  /** Every library operation that can fail, as named in the failure value. */
3
- export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull';
3
+ export type PoolOperation = 'initialize' | 'add' | 'replace' | 'rotate' | 'disable' | 'enable' | 'remove' | 'reorder' | 'updateSettings' | 'recordIdentity' | 'updateProviderState' | 'refresh' | 'pull' | 'publishRoster';
4
4
  /**
5
5
  * How far an operation got before it failed.
6
6
  *
@@ -19,7 +19,7 @@ export type PoolFailurePhase = 'before-first-write' | 'after-first-write' | 'pul
19
19
  * lock outcomes (a wait that ran out, and a lease found lost); the rest are
20
20
  * refusals and failures of the operation itself.
21
21
  */
22
- export type PoolFailureKind = 'lock-contention' | 'lock-ownership' | 'pending-migration' | 'load-error' | 'unknown-row' | 'invalid-row' | 'invalid-input' | 'id-exists' | 'id-removed' | 'type-mismatch' | 'no-credential' | 'row-disabled' | 'row-protected' | 'duplicate-identity' | 'identity-mismatch' | 'identity-contradicted' | 'endpoint-mismatch' | 'row-key-changed' | 'invalid-order' | 'refresh-stamp-ahead' | 'unbound-credential' | 'attribution' | 'provider' | 'pull' | 'invalid-quota' | 'invalid-provider-state' | 'after-persist-hook' | 'unexpected';
22
+ export type PoolFailureKind = 'lock-contention' | 'lock-ownership' | 'pending-migration' | 'load-error' | 'snapshot-contended' | 'publication-sync' | 'publication-incomplete' | 'unknown-row' | 'invalid-row' | 'invalid-input' | 'id-exists' | 'id-removed' | 'type-mismatch' | 'no-credential' | 'row-disabled' | 'row-protected' | 'row-staged' | 'credential-exists' | 'publication-mismatch' | 'duplicate-identity' | 'identity-mismatch' | 'identity-contradicted' | 'endpoint-mismatch' | 'row-key-changed' | 'invalid-order' | 'refresh-stamp-ahead' | 'unbound-credential' | 'attribution' | 'provider' | 'pull' | 'invalid-quota' | 'invalid-provider-state' | 'after-persist-hook' | 'unexpected';
23
23
  /**
24
24
  * The single failure value of every store operation. `committed` is present
25
25
  * only when the operation had already written a credential to the state file
@@ -8,6 +8,7 @@ export const DUPLICATE_IDENTITY_REASON = 'duplicate-identity';
8
8
  */
9
9
  export function countUnknownIdentityRows(rows) {
10
10
  return rows.filter((row) => row.invalid === undefined &&
11
+ !row.staged &&
11
12
  row.type === 'oauth' &&
12
13
  row.enabled &&
13
14
  row.credential !== undefined &&
@@ -57,6 +58,7 @@ export function disableIdentityDuplicates(tx, identity) {
57
58
  const holders = tx
58
59
  .rows()
59
60
  .filter((row) => row.invalid === undefined &&
61
+ !row.staged &&
60
62
  row.type === 'oauth' &&
61
63
  row.enabled &&
62
64
  row.identity === identity);
@@ -8,11 +8,12 @@ export type { OpenPoolStoreOptions, PoolLoad, PoolStore, } from './pool.js';
8
8
  export { openPoolStore } from './pool.js';
9
9
  export type { ProviderStateMutator, RowTransitionMutator, UpdateProviderStateResult, } from './provider-state.js';
10
10
  export { DECLINE_TRANSITION } from './provider-state.js';
11
+ export type { PublicationReceipt, PublishOptions, PublishPlan, PublishResult, } from './publication.js';
11
12
  export type { PullHook, PullRequest } from './pull.js';
12
13
  export type { ProviderRefresh, ProviderRefreshResult, RefreshOptions, RefreshOutcome, } from './refresh.js';
13
14
  export type { LockEvent, PoolLockOptions, PoolLockSpec, } from './refresh-lock.js';
14
15
  export { POOL_LOCK_DEFAULTS } from './refresh-lock.js';
15
- export type { AddInput, AddResult, CredentialWriteInput, FailureHook, RemoveOptions, RemoveResult, RemoveView, ReorderOptions, ReorderResult, RowOperationOptions, RowToggleOptions, RowTransitionOptions, RowTransitionResult, RowWriteOptions, } from './rows.js';
16
+ export type { AddInput, AddOptions, AddResult, CredentialWriteInput, FailureHook, ProtectFn, ProtectView, RemoveOptions, RemoveResult, RemoveView, ReorderOptions, ReorderResult, RowOperationOptions, RowProjection, RowToggleOptions, RowTransitionOptions, RowTransitionResult, RowWriteOptions, } from './rows.js';
16
17
  export type { PullReason } from './runtime.js';
17
18
  export type { ApiKeyCredential, CredentialStampStatus, OAuthCredential, PoolCredential, PoolRow, ProviderStateCodec, ProviderStateDrop, ProviderStateReplacement, QuotaCodec, RotateCredential, StoredCredential, } from './schema.js';
18
19
  export { fingerprintOf, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, PROVIDER_STATE_KEY, REFRESH_STAMP_TOLERANCE_MS, rowLockKey, } from './schema.js';
@@ -31,6 +31,7 @@ export interface StoreContext {
31
31
  * `OpenPoolStoreOptions.requireCredentialStamps`).
32
32
  */
33
33
  requireCredentialStamps?: boolean;
34
+ requireRemovedFingerprint?: boolean;
34
35
  }
35
36
  export interface Snapshot {
36
37
  configExists: boolean;
@@ -48,8 +49,14 @@ export type ReadResult = ({
48
49
  status: 'error';
49
50
  file: 'config' | 'state';
50
51
  reason: string;
52
+ kind?: 'snapshot-contended';
53
+ retryable?: true;
51
54
  };
52
- /** Reads and classifies both files. Never writes. */
55
+ /**
56
+ * Validate config/state/config bytes without locks. Roster replacement writes
57
+ * config before deleting old state credentials. Re-read a changed config so an
58
+ * old roster cannot be paired with state from which its accounts were removed.
59
+ */
53
60
  export declare function readPool(ctx: StoreContext): Promise<ReadResult>;
54
61
  /** The refusal for a pool that is not ready, as a failure value. */
55
62
  export declare function notReadyError(result: Exclude<ReadResult, {
@@ -58,6 +65,8 @@ export declare function notReadyError(result: Exclude<ReadResult, {
58
65
  /** What an operation has written so far; decides the failure phase. */
59
66
  export interface Progress {
60
67
  writes: number;
68
+ /** The roster config was renamed into place, or its committed receipt was found. */
69
+ publicationDecided?: true;
61
70
  /** The credential the operation's state write put on disk, once it has. */
62
71
  committed?: StoredCredential;
63
72
  }
@@ -89,6 +98,9 @@ export declare class Transaction {
89
98
  */
90
99
  rows(): PoolRow[];
91
100
  row(id: string): PoolRow | undefined;
101
+ /** Read the config marker, or an orphan's stamp; never use a caller's reservation. */
102
+ reservation(id: string): unknown;
103
+ assertNotStaged(id: string): void;
92
104
  roster(): unknown[];
93
105
  /** The first roster row with this id (the one the pool loads). */
94
106
  rosterRow(id: string): Record<string, unknown> | undefined;
@@ -126,9 +138,17 @@ export declare class Transaction {
126
138
  */
127
139
  commitConfig(options?: {
128
140
  counted?: boolean;
141
+ durable?: boolean;
142
+ publicationDecision?: boolean;
129
143
  }): Promise<void>;
130
144
  /** Writes the state: every unrecognised top-level and per-row key kept. */
131
- commitState(committed?: StoredCredential): Promise<void>;
145
+ commitState(committed?: StoredCredential, options?: {
146
+ durable?: boolean;
147
+ }): Promise<void>;
148
+ assertAll(): Promise<void>;
149
+ syncState(): Promise<void>;
150
+ markPublicationDecision(): void;
151
+ syncConfig(): Promise<void>;
132
152
  private write;
133
153
  }
134
154
  /** What `initializePool` did. */
@@ -1,21 +1,26 @@
1
1
  import { readFile } from 'node:fs/promises';
2
- import { writeJsonAtomic } from '../fs/atomic-write.js';
2
+ import { setTimeout as snapshotDelay } from 'node:timers/promises';
3
+ import { AtomicSyncError, syncJsonFile, writeJsonAtomic, writeJsonAtomicTracked, } from '../fs/atomic-write.js';
3
4
  import { LockContentionError, LockOwnershipError } from '../fs/with-lock.js';
4
5
  import { PoolOperationError, } from './errors.js';
5
6
  import { callFailureHook } from './hooks.js';
6
7
  import { LockStack, } from './refresh-lock.js';
7
- import { classifyConfig, classifyState, ensureEntries, entryIn, isRecord, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, retireEpochsIn, rosterOf, rosterRowIn, setEntryIn, } from './schema.js';
8
+ import { assertNotReserved } from './reserved.js';
9
+ import { CREDENTIAL_STAMP_KEY, classifyConfig, classifyState, ensureEntries, entryIn, isRecord, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, retireEpochsIn, rosterOf, rosterRowIn, setEntryIn, } from './schema.js';
8
10
  import { completeTornRows, loadRows } from './torn.js';
9
- async function readJson(path) {
10
- let text;
11
+ async function readText(path) {
11
12
  try {
12
- text = await readFile(path, 'utf8');
13
+ return await readFile(path, 'utf8');
13
14
  }
14
15
  catch (error) {
15
16
  if (error.code === 'ENOENT')
16
- return { exists: false };
17
+ return undefined;
17
18
  throw error;
18
19
  }
20
+ }
21
+ function parseFile(text) {
22
+ if (text === undefined)
23
+ return { exists: false };
19
24
  try {
20
25
  return { exists: true, value: JSON.parse(text) };
21
26
  }
@@ -23,30 +28,60 @@ async function readJson(path) {
23
28
  return { exists: true, parseError };
24
29
  }
25
30
  }
26
- /** Reads and classifies both files. Never writes. */
31
+ /**
32
+ * Validate config/state/config bytes without locks. Roster replacement writes
33
+ * config before deleting old state credentials. Re-read a changed config so an
34
+ * old roster cannot be paired with state from which its accounts were removed.
35
+ */
27
36
  export async function readPool(ctx) {
28
- const config = classifyConfig(await readJson(ctx.configPath));
29
- if (config.status === 'error')
30
- return { status: 'error', file: 'config', reason: config.reason };
31
- const state = classifyState(await readJson(ctx.statePath));
32
- if (state.status === 'error')
33
- return { status: 'error', file: 'state', reason: state.reason };
34
- if (config.status === 'pending-migration')
35
- return { status: 'pending-migration', config: config.config };
37
+ for (let attempt = 0; attempt < 3; attempt++) {
38
+ const configText = await readText(ctx.configPath);
39
+ const stateText = await readText(ctx.statePath);
40
+ const checkedConfigText = await readText(ctx.configPath);
41
+ if (configText !== checkedConfigText) {
42
+ if (attempt < 2)
43
+ await snapshotDelay(2 + Math.floor(Math.random() * 4));
44
+ continue;
45
+ }
46
+ const config = classifyConfig(parseFile(configText));
47
+ if (config.status === 'error')
48
+ return { status: 'error', file: 'config', reason: config.reason };
49
+ const state = classifyState(parseFile(stateText));
50
+ if (state.status === 'error')
51
+ return { status: 'error', file: 'state', reason: state.reason };
52
+ if (config.status === 'pending-migration')
53
+ return { status: 'pending-migration', config: config.config };
54
+ return {
55
+ status: 'ready',
56
+ configExists: config.exists,
57
+ stateExists: state.exists,
58
+ config: config.config,
59
+ state: state.state,
60
+ rows: loadRows(config.config, state.state, ctx.codec, {
61
+ requireCredentialStamps: ctx.requireCredentialStamps === true,
62
+ ...(ctx.providerState ? { providerState: ctx.providerState } : {}),
63
+ }),
64
+ };
65
+ }
36
66
  return {
37
- status: 'ready',
38
- configExists: config.exists,
39
- stateExists: state.exists,
40
- config: config.config,
41
- state: state.state,
42
- rows: loadRows(config.config, state.state, ctx.codec, {
43
- requireCredentialStamps: ctx.requireCredentialStamps === true,
44
- ...(ctx.providerState ? { providerState: ctx.providerState } : {}),
45
- }),
67
+ status: 'error',
68
+ file: 'config',
69
+ kind: 'snapshot-contended',
70
+ retryable: true,
71
+ reason: 'The store was changing; retry the operation once writes settle.',
46
72
  };
47
73
  }
48
74
  /** The refusal for a pool that is not ready, as a failure value. */
49
75
  export function notReadyError(result, operation, rowId, phase = 'before-first-write') {
76
+ if (result.status === 'error' && result.kind === 'snapshot-contended')
77
+ return new PoolOperationError({
78
+ operation,
79
+ ...(rowId !== undefined ? { rowId } : {}),
80
+ phase,
81
+ kind: 'snapshot-contended',
82
+ retryable: true,
83
+ message: result.reason,
84
+ });
50
85
  return new PoolOperationError({
51
86
  operation,
52
87
  ...(rowId !== undefined ? { rowId } : {}),
@@ -99,6 +134,20 @@ export class Transaction {
99
134
  row(id) {
100
135
  return this.rows().find((row) => row.id === id);
101
136
  }
137
+ /** Read the config marker, or an orphan's stamp; never use a caller's reservation. */
138
+ reservation(id) {
139
+ if (this.rosterRow(id)) {
140
+ const entry = this.entry(id);
141
+ return entry && Object.hasOwn(entry, 'staged') ? entry.staged : undefined;
142
+ }
143
+ const stamp = this.stateAccount(id)?.[CREDENTIAL_STAMP_KEY];
144
+ return isRecord(stamp) && Object.hasOwn(stamp, 'staged')
145
+ ? stamp.staged
146
+ : undefined;
147
+ }
148
+ assertNotStaged(id) {
149
+ assertNotReserved(this.info.operation, id, this.reservation(id));
150
+ }
102
151
  roster() {
103
152
  if (!Array.isArray(this.config.accounts))
104
153
  this.config.accounts = [];
@@ -200,9 +249,6 @@ export class Transaction {
200
249
  configurable: true,
201
250
  });
202
251
  }
203
- else {
204
- this.ctx.removedIds.add(id);
205
- }
206
252
  }
207
253
  const pool = this.config[POOL_KEY];
208
254
  const next = {
@@ -215,31 +261,68 @@ export class Transaction {
215
261
  [POOL_ROWS_KEY]: kept,
216
262
  },
217
263
  };
218
- await this.write(this.ctx.configPath, next, 'config', options.counted ?? true);
264
+ await this.write(this.ctx.configPath, next, 'config', options.counted ?? true, options.durable ?? false, () => {
265
+ if (options.publicationDecision)
266
+ this.markPublicationDecision();
267
+ for (const id of dropped)
268
+ this.ctx.removedIds.add(id);
269
+ this.config = next;
270
+ });
219
271
  this.config = next;
220
272
  }
221
273
  /** Writes the state: every unrecognised top-level and per-row key kept. */
222
- async commitState(committed) {
274
+ async commitState(committed, options = {}) {
223
275
  const next = {
224
276
  ...this.state,
225
277
  version: LEGACY_STORE_VERSION,
226
278
  accounts: isRecord(this.state.accounts) ? this.state.accounts : {},
227
279
  };
228
- await this.write(this.ctx.statePath, next, 'state');
280
+ await this.write(this.ctx.statePath, next, 'state', true, options.durable ?? false);
229
281
  this.state = next;
230
282
  if (committed)
231
283
  this.progress.committed = committed;
232
284
  }
233
- async write(path, value, file, counted = true) {
234
- await writeJsonAtomic(path, value, {
285
+ async assertAll() {
286
+ await this.locks.assertAll();
287
+ }
288
+ async syncState() {
289
+ await this.assertAll();
290
+ try {
291
+ if (this.snapshot.stateExists)
292
+ await syncJsonFile(this.ctx.statePath);
293
+ }
294
+ catch (cause) {
295
+ throw new PoolOperationError({
296
+ operation: this.info.operation,
297
+ rowId: this.info.rowId,
298
+ phase: 'before-first-write',
299
+ kind: 'publication-sync',
300
+ retryable: true,
301
+ message: 'Publication sync failed before the decision; nothing was written. Retry the same plan.',
302
+ cause,
303
+ });
304
+ }
305
+ }
306
+ markPublicationDecision() {
307
+ this.progress.publicationDecided = true;
308
+ }
309
+ async syncConfig() {
310
+ await this.assertAll();
311
+ await syncJsonFile(this.ctx.configPath);
312
+ }
313
+ async write(path, value, file, counted = true, durable = false, onRenamed) {
314
+ await writeJsonAtomicTracked(path, value, {
315
+ durable,
235
316
  beforeRename: async () => {
236
317
  await this.ctx.onStep?.(`before-${file}-write`, this.info);
237
318
  // Ownership is proved immediately before the rename, on every lease.
238
319
  await this.locks.assertAll();
239
320
  },
321
+ }, () => {
322
+ if (counted)
323
+ this.progress.writes++;
324
+ onRenamed?.();
240
325
  });
241
- if (counted)
242
- this.progress.writes++;
243
326
  await this.ctx.onStep?.(`after-${file}-write`, this.info);
244
327
  }
245
328
  }
@@ -304,6 +387,9 @@ export async function withTransaction(ctx, locks, progress, info, fn, options =
304
387
  if (result.status !== 'ready')
305
388
  throw notReadyError(result, info.operation, info.rowId, progress.writes > 0 ? 'after-first-write' : 'before-first-write');
306
389
  const tx = new Transaction(ctx, result, locks, progress, info);
390
+ if (info.rowId !== undefined &&
391
+ !['add', 'remove', 'pull', 'publishRoster', 'enable', 'disable'].includes(info.operation))
392
+ tx.assertNotStaged(info.rowId);
307
393
  if (options.completeTorn ?? true)
308
394
  await tx.completeTorn();
309
395
  return await fn(tx);
@@ -320,6 +406,26 @@ export function toFailure(error, operation, rowId, progress) {
320
406
  ? 'after-first-write'
321
407
  : 'before-first-write';
322
408
  const committed = phase === 'after-first-write' ? progress.committed : undefined;
409
+ if (operation === 'publishRoster' && progress.publicationDecided)
410
+ return new PoolOperationError({
411
+ operation,
412
+ ...(rowId !== undefined ? { rowId } : {}),
413
+ phase,
414
+ kind: 'publication-incomplete',
415
+ retryable: true,
416
+ message: 'The publication may already be decided. Replay the same plan or check publication(operationId).',
417
+ cause: error,
418
+ });
419
+ if (operation === 'publishRoster' && error instanceof AtomicSyncError)
420
+ return new PoolOperationError({
421
+ operation,
422
+ ...(rowId !== undefined ? { rowId } : {}),
423
+ phase,
424
+ kind: 'publication-sync',
425
+ retryable: true,
426
+ message: 'Publication sync failed before the decision; nothing was written. Retry the same plan.',
427
+ cause: error,
428
+ });
323
429
  if (error instanceof PoolOperationError) {
324
430
  if (error.phase === phase &&
325
431
  error.rowId === rowId &&
@@ -3,10 +3,11 @@ import type { PoolOperationError } from './errors.js';
3
3
  import type { PoolLogger } from './hooks.js';
4
4
  import { type HoldPoint, type InitializeOutcome, type StoreContext } from './mutate.js';
5
5
  import { type ProviderStateMutator, type UpdateProviderStateResult } from './provider-state.js';
6
+ import { type PublicationReceipt, type PublishOptions, type PublishPlan, type PublishResult } from './publication.js';
6
7
  import { type PullHook } from './pull.js';
7
8
  import { type ProviderRefresh, type RefreshOptions, type RefreshOutcome } from './refresh.js';
8
9
  import { type LockEnvironment, type PoolLockOptions, type PoolLockSpec } from './refresh-lock.js';
9
- import { type AddInput, type AddResult, type CredentialWriteInput, type RemoveOptions, type RemoveResult, type ReorderOptions, type ReorderResult, type RowOperationOptions, type RowToggleOptions, type RowTransitionOptions, type RowTransitionResult, type RowWriteOptions } from './rows.js';
10
+ import { type AddInput, type AddOptions, type AddResult, type CredentialWriteInput, type RemoveOptions, type RemoveResult, type ReorderOptions, type ReorderResult, type RowOperationOptions, type RowToggleOptions, type RowTransitionOptions, type RowTransitionResult, type RowWriteOptions } from './rows.js';
10
11
  import { type PoolCredential, type PoolRow, type ProviderStateCodec, type QuotaCodec, type RotateCredential, type StoredCredential } from './schema.js';
11
12
  import { type SettingsMutator, type SettingsRead, type UpdateSettingsOptions, type UpdateSettingsResult } from './settings.js';
12
13
  export interface OpenPoolStoreOptions {
@@ -39,6 +40,8 @@ export interface OpenPoolStoreOptions {
39
40
  * without writing; `remove(id)` explicitly discards the orphan.
40
41
  */
41
42
  requireCredentialStamps?: boolean;
43
+ /** Require an exact secret fingerprint for every roster-publication removal. */
44
+ requireRemovedFingerprint?: boolean;
42
45
  /** Injected clock for leases, refresh stamps and `addedAt`. */
43
46
  now?: () => number;
44
47
  /**
@@ -75,6 +78,8 @@ export type PoolLoad = {
75
78
  status: 'error';
76
79
  file: 'config' | 'state';
77
80
  reason: string;
81
+ kind?: 'snapshot-contended';
82
+ retryable?: true;
78
83
  };
79
84
  export interface PoolStore {
80
85
  /** Reads the pool and fires first-reading pulls; never writes a file itself. */
@@ -99,7 +104,9 @@ export interface PoolStore {
99
104
  * held (see `Attribution`), and an id that held `Number.MAX_SAFE_INTEGER`
100
105
  * refuses (`id-removed`) before writing.
101
106
  */
102
- add(input: AddInput, options?: RowOperationOptions): Promise<AddResult>;
107
+ add(input: AddInput, options?: AddOptions): Promise<AddResult>;
108
+ publishRoster(plan: PublishPlan, options?: PublishOptions): Promise<PublishResult>;
109
+ publication(operationId: string): Promise<PublicationReceipt | undefined>;
103
110
  /**
104
111
  * Gives a row a new credential and a new credential epoch. Since 0.6.0 the
105
112
  * row's provider state is whatever `ProviderStateCodec.onReplace` returns;
@@ -1,6 +1,7 @@
1
1
  import { recordQuota } from './attribution.js';
2
2
  import { initializePool, readPool, } from './mutate.js';
3
3
  import { updateProviderStateRow, } from './provider-state.js';
4
+ import { publication, publishRoster, } from './publication.js';
4
5
  import { PullScheduler } from './pull.js';
5
6
  import { refreshRow, } from './refresh.js';
6
7
  import { POOL_LOCK_DEFAULTS, } from './refresh-lock.js';
@@ -62,6 +63,7 @@ export function openPoolStore(options) {
62
63
  },
63
64
  removedIds: memory.removedIds,
64
65
  requireCredentialStamps: options.requireCredentialStamps === true,
66
+ requireRemovedFingerprint: options.requireRemovedFingerprint === true,
65
67
  ...(options.logger ? { logger: options.logger } : {}),
66
68
  ...(options.onStep ? { onStep: options.onStep } : {}),
67
69
  ...(options.hold ? { hold: options.hold } : {}),
@@ -98,6 +100,8 @@ export function openPoolStore(options) {
98
100
  return { status: await initializePool(ctx, input.dropKeys ?? []) };
99
101
  },
100
102
  add: (input, callOptions) => addRow(rt, input, callOptions),
103
+ publishRoster: (plan, callOptions) => publishRoster(rt, plan, callOptions),
104
+ publication: (operationId) => publication(rt, operationId),
101
105
  replace: (id, credential, input, callOptions) => replaceRow(rt, id, credential, input, callOptions),
102
106
  rotate: (id, credential, input, callOptions) => rotateRow(rt, id, credential, input, callOptions),
103
107
  updateProviderState: (id, fence, mutator, callOptions) => updateProviderStateRow(rt, id, fence, mutator, callOptions),
@@ -0,0 +1,47 @@
1
+ import type { Attribution } from './attribution.js';
2
+ import type { PoolLockSpec } from './refresh-lock.js';
3
+ import { type FailureHook, type ProtectFn } from './rows.js';
4
+ import { type StoreRuntime } from './runtime.js';
5
+ export interface PublishPlan {
6
+ operationId: string;
7
+ remove: Array<{
8
+ id: string;
9
+ attribution: Attribution;
10
+ fingerprint?: string;
11
+ }>;
12
+ finalize: Array<{
13
+ id: string;
14
+ attribution: Attribution;
15
+ reservation: string;
16
+ enabled: boolean;
17
+ disabledReason?: string;
18
+ }>;
19
+ order: string[];
20
+ }
21
+ export interface PublicationReceipt {
22
+ operationId: string;
23
+ planDigest: string;
24
+ phase: 'committed' | 'cleaned';
25
+ removed: Array<{
26
+ id: string;
27
+ credentialEpoch: number;
28
+ }>;
29
+ finalized: Array<{
30
+ id: string;
31
+ credentialEpoch: number;
32
+ reservation: string;
33
+ enabled: boolean;
34
+ }>;
35
+ }
36
+ export interface PublishOptions {
37
+ protect?: ProtectFn;
38
+ extraLocks?: PoolLockSpec[];
39
+ providerLock?: PoolLockSpec;
40
+ onFailure?: FailureHook;
41
+ }
42
+ export interface PublishResult {
43
+ outcome: 'published' | 'cleaned' | 'already-cleaned';
44
+ receipt: PublicationReceipt;
45
+ }
46
+ export declare function publication(rt: StoreRuntime, operationId: string): Promise<PublicationReceipt | undefined>;
47
+ export declare function publishRoster(rt: StoreRuntime, plan: PublishPlan, options?: PublishOptions): Promise<PublishResult>;