@cortexkit/opencode-openai-auth 1.3.0 → 1.5.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/dist/bin.js +8 -8
- package/dist/{codex-request-B9D0e97Q.d.ts → codex-request-BjGT9yWg.d.ts} +36 -28
- package/dist/index-2p3gcjsa.js +69 -0
- package/dist/{index-m3ctrabv.js → index-2rw81dtm.js} +1 -1
- package/dist/index-2yszc75z.js +2 -0
- package/dist/{index-gn2b097f.js → index-3y453wg4.js} +7 -7
- package/dist/{index-bc89akak.js → index-4w0nsq5s.js} +1 -1
- package/dist/index-6fdmqk6p.js +90 -0
- package/dist/{index-xwvze96g.js → index-7vkn2e46.js} +1 -1
- package/dist/{index-2pgkrebq.js → index-djnfq652.js} +2 -2
- package/dist/{index-tddr876f.js → index-e416r885.js} +2 -2
- package/dist/index-fztcacjr.js +65 -0
- package/dist/index-gmmakhbt.js +2 -0
- package/dist/{index-ftkhhr6d.js → index-krcqvyqf.js} +1 -1
- package/dist/index-mhfja8yr.js +2 -0
- package/dist/index.d.ts +11 -3
- package/dist/index.js +1 -1
- package/dist/{model-BdITTmeb.d.ts → model-BMq5SCUB.d.ts} +1 -1
- package/dist/{port-file-DbHIVC9a.d.ts → port-file-CjMFUWcX.d.ts} +1 -1
- package/dist/{protocol-MysYPAho.d.ts → protocol-BC3ndToM.d.ts} +1 -1
- package/dist/rpc/port-file.d.ts +1 -1
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +1 -1
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +3 -3
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/{sidebar-state-CVSok7zv.d.ts → sidebar-state-DfYyqiOH.d.ts} +55 -7
- package/dist/sidebar-state.d.ts +2 -2
- package/dist/sidebar-state.js +1 -1
- package/dist/token-util-ed4az5gg.js +1 -0
- package/dist/{token-z6qq7a1d.js → token-ycw7dyev.js} +1 -1
- package/dist/tui-preferences.js +1 -1
- package/dist/tui.d.ts +30 -3
- package/dist/v2/server.d.ts +2 -2
- package/dist/v2/server.js +2 -2
- package/package.json +5 -5
- package/src/tui-compiled/raw/shared/0332701351b3eeec-format.js +50 -5
- package/src/tui-compiled/raw/shared/0f77ebc3c914c9c6-custody.js +70 -1
- package/src/tui-compiled/raw/shared/169b2b4bf30909bc-consumer.js +104 -62
- package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +45 -1
- package/src/tui-compiled/raw/shared/30f5bc480f31f51c-roster.js +172 -43
- package/src/tui-compiled/raw/shared/375d9cca2def037d-private-files.js +49 -3
- package/src/tui-compiled/raw/shared/39c3cb05738fcf6d-projection.js +3 -1
- package/src/tui-compiled/raw/shared/42ae93ab554fcec2-open-url.js +7 -9
- package/src/tui-compiled/raw/shared/4825e03209d6ae3e-with-lock.js +2 -0
- package/src/tui-compiled/raw/shared/4f36d333d081d040-merge.js +17 -3
- package/src/tui-compiled/raw/shared/754d6017f8e419cf-builtins.js +95 -13
- package/src/tui-compiled/raw/shared/81dddd203f1b92a3-quota-writer.js +253 -0
- package/src/tui-compiled/raw/shared/905bffc0220f43d0-map.js +31 -6
- package/src/tui-compiled/raw/shared/abd062d633e29fd2-pool-routing.js +116 -12
- package/src/tui-compiled/raw/shared/b9588ad4725c1d10-enrollment.js +27 -0
- package/src/tui-compiled/raw/shared/bfbdd0f9aae56b47-pool-quota.js +15 -3
- package/src/tui-compiled/raw/shared/d0f0b6be200311af-insula.js +64 -2
- package/src/tui-compiled/raw/shared/d5a8f1061ee2f114-index.js +2 -2
- package/src/tui-compiled/raw/shared/dbc61cd405941828-accounts.js +5 -4
- package/src/tui-compiled/raw/shared/dc9290c2a7552ba6-watch.js +2 -1
- package/src/tui-compiled/raw/shared/e8d3c8da776ef9cd-index.js +2 -1
- package/src/tui-compiled/raw/sidebar-state.js +32 -3
- package/src/tui-compiled/raw/tui/v2-dialog.js +2 -1
- package/src/tui-compiled/raw/tui.tsx +170 -26
- package/src/tui-compiled/runtime/shared/0332701351b3eeec-format.js +50 -5
- package/src/tui-compiled/runtime/shared/0f77ebc3c914c9c6-custody.js +70 -1
- package/src/tui-compiled/runtime/shared/169b2b4bf30909bc-consumer.js +104 -62
- package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +45 -1
- package/src/tui-compiled/runtime/shared/30f5bc480f31f51c-roster.js +172 -43
- package/src/tui-compiled/runtime/shared/375d9cca2def037d-private-files.js +49 -3
- package/src/tui-compiled/runtime/shared/39c3cb05738fcf6d-projection.js +3 -1
- package/src/tui-compiled/runtime/shared/42ae93ab554fcec2-open-url.js +7 -9
- package/src/tui-compiled/runtime/shared/4825e03209d6ae3e-with-lock.js +2 -0
- package/src/tui-compiled/runtime/shared/4f36d333d081d040-merge.js +17 -3
- package/src/tui-compiled/runtime/shared/754d6017f8e419cf-builtins.js +95 -13
- package/src/tui-compiled/runtime/shared/81dddd203f1b92a3-quota-writer.js +253 -0
- package/src/tui-compiled/runtime/shared/905bffc0220f43d0-map.js +31 -6
- package/src/tui-compiled/runtime/shared/abd062d633e29fd2-pool-routing.js +116 -12
- package/src/tui-compiled/runtime/shared/b9588ad4725c1d10-enrollment.js +27 -0
- package/src/tui-compiled/runtime/shared/bfbdd0f9aae56b47-pool-quota.js +15 -3
- package/src/tui-compiled/runtime/shared/d0f0b6be200311af-insula.js +64 -2
- package/src/tui-compiled/runtime/shared/d5a8f1061ee2f114-index.js +2 -2
- package/src/tui-compiled/runtime/shared/dbc61cd405941828-accounts.js +5 -4
- package/src/tui-compiled/runtime/shared/dc9290c2a7552ba6-watch.js +2 -1
- package/src/tui-compiled/runtime/shared/e8d3c8da776ef9cd-index.js +2 -1
- package/src/tui-compiled/runtime/sidebar-state.js +32 -3
- package/src/tui-compiled/runtime/tui/v2-dialog.js +2 -1
- package/src/tui-compiled/runtime/tui.js +350 -219
- package/dist/index-1mbgsxsr.js +0 -2
- package/dist/index-4v2fs42x.js +0 -65
- package/dist/index-8x1aj7q3.js +0 -2
- package/dist/index-ex6nx3mq.js +0 -2
- package/dist/index-psjyexj3.js +0 -69
- package/dist/index-tn8x5tz8.js +0 -90
- package/dist/token-util-cf0nyh7n.js +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { lstat, readFile, rename, unlink } from "node:fs/promises";
|
|
3
|
-
import {
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
5
|
export const windowsPrivateFiles = process.platform === 'win32';
|
|
5
6
|
const migrationNotices = new Set();
|
|
6
7
|
function ioCode(detail) {
|
|
@@ -20,8 +21,51 @@ let backend;
|
|
|
20
21
|
export function setPrivateFilesBackendForTest(api) {
|
|
21
22
|
backend = api ? Promise.resolve(api) : undefined;
|
|
22
23
|
}
|
|
24
|
+
/** The fixed `reason` of a refusal because the Windows native addon did not load. */
|
|
25
|
+
export const PRIVATE_FILES_UNAVAILABLE_REASON = 'native-addon-unavailable';
|
|
26
|
+
function privateFilesUnavailable(cause) {
|
|
27
|
+
return Object.assign(new Error('Windows private-files native addon is unavailable', { cause }), {
|
|
28
|
+
code: 'ERR_PRIVATE_FILES_UNAVAILABLE',
|
|
29
|
+
reason: PRIVATE_FILES_UNAVAILABLE_REASON,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function isUnavailable(api, error) {
|
|
33
|
+
return (error instanceof api.PrivateFilesUnavailableError ||
|
|
34
|
+
error?.code ===
|
|
35
|
+
'ERR_PRIVATE_FILES_UNAVAILABLE');
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Importing @cortexkit/private-files succeeds even when its Windows addon
|
|
39
|
+
* cannot load: the package loads the addon on first use, and some of its
|
|
40
|
+
* checks then report the failure as an ordinary refusal such as
|
|
41
|
+
* `unsupported-filesystem`. So prove the addon loads before handing the
|
|
42
|
+
* package out. Verifying a path that does not exist loads the addon first and
|
|
43
|
+
* then fails harmlessly; only the package's own "unavailable" error means the
|
|
44
|
+
* addon is missing.
|
|
45
|
+
*/
|
|
46
|
+
async function assertNativeAddonLoads(api) {
|
|
47
|
+
try {
|
|
48
|
+
await api.verifyPrivatePath(join(tmpdir(), `.common-auth-private-files-probe-${randomUUID()}`), 'file');
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (isUnavailable(api, error))
|
|
52
|
+
throw privateFilesUnavailable(error);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Load the package once per process. On Windows a failed import or addon load
|
|
57
|
+
* is kept, so every later private-file operation refuses at once with
|
|
58
|
+
* ERR_PRIVATE_FILES_UNAVAILABLE. There is no fallback to permission bits:
|
|
59
|
+
* they do not protect files on Windows.
|
|
60
|
+
*/
|
|
23
61
|
function loadBackend() {
|
|
24
|
-
backend ??= import("@cortexkit/private-files")
|
|
62
|
+
backend ??= import("@cortexkit/private-files").then(async (api) => {
|
|
63
|
+
if (windowsPrivateFiles)
|
|
64
|
+
await assertNativeAddonLoads(api);
|
|
65
|
+
return api;
|
|
66
|
+
}, (cause) => {
|
|
67
|
+
throw windowsPrivateFiles ? privateFilesUnavailable(cause) : cause;
|
|
68
|
+
});
|
|
25
69
|
return backend;
|
|
26
70
|
}
|
|
27
71
|
export class PrivateFileError extends Error {
|
|
@@ -38,7 +82,9 @@ export class PrivateFileError extends Error {
|
|
|
38
82
|
orphanPath;
|
|
39
83
|
constructor(path, stage, cause) {
|
|
40
84
|
const detail = cause;
|
|
41
|
-
super(
|
|
85
|
+
super(detail?.code === 'ERR_PRIVATE_FILES_UNAVAILABLE'
|
|
86
|
+
? `Private file refused at ${stage}: ${path} (${PRIVATE_FILES_UNAVAILABLE_REASON}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.`
|
|
87
|
+
: `Private file refused at ${stage}: ${path} (${detail?.reason ?? detail?.code ?? 'io-error'}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
|
|
42
88
|
this.path = path;
|
|
43
89
|
this.stage = stage;
|
|
44
90
|
this.name = 'PrivateFileError';
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
// scope, orders the result the way the primitives expect, and carries each
|
|
7
7
|
// entry's (scope, label) so a decision names the limit it judged rather than
|
|
8
8
|
// the position it occupied.
|
|
9
|
-
import { ALL_SCOPE, readQuotaCounters, } from "./905bffc0220f43d0-map.js";
|
|
9
|
+
import { ALL_SCOPE, isQuotaCredits, readQuotaCounters, } from "./905bffc0220f43d0-map.js";
|
|
10
10
|
function project(entry) {
|
|
11
11
|
if (entry.kind === 'retired') {
|
|
12
12
|
return {
|
|
@@ -95,12 +95,14 @@ export function projectQuota(map, scope = ALL_SCOPE) {
|
|
|
95
95
|
: undefined;
|
|
96
96
|
const budget = map?.budget?.kind === 'reading' ? projectBudget(map.budget) : undefined;
|
|
97
97
|
const counters = readQuotaCounters(map?.counters);
|
|
98
|
+
const credits = isQuotaCredits(map?.credits) ? map.credits : undefined;
|
|
98
99
|
return {
|
|
99
100
|
scope,
|
|
100
101
|
limits,
|
|
101
102
|
...(checkedAt === undefined ? {} : { checkedAt }),
|
|
102
103
|
...(budget === undefined ? {} : { budget }),
|
|
103
104
|
...(counters === undefined ? {} : { counters }),
|
|
105
|
+
...(credits === undefined ? {} : { credits }),
|
|
104
106
|
};
|
|
105
107
|
}
|
|
106
108
|
/**
|
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
spawn as defaultSpawn
|
|
4
|
-
} from "node:child_process";
|
|
5
|
-
export function openUrl(url, platform = process.platform, execFileSync = defaultExecFileSync, spawn = defaultSpawn) {
|
|
1
|
+
import { spawn as defaultSpawn } from "node:child_process";
|
|
2
|
+
export function openUrl(url, platform = process.platform, spawn = defaultSpawn) {
|
|
6
3
|
try {
|
|
7
4
|
if (platform === "win32") {
|
|
8
5
|
const command = `Start-Process '${url.replaceAll("'", "''")}'`, encodedCommand = Buffer.from(command, "utf16le").toString("base64"), child = spawn("powershell.exe", [
|
|
@@ -17,11 +14,12 @@ export function openUrl(url, platform = process.platform, execFileSync = default
|
|
|
17
14
|
child.unref();
|
|
18
15
|
return child.pid !== void 0;
|
|
19
16
|
}
|
|
20
|
-
|
|
21
|
-
stdio: "ignore"
|
|
22
|
-
timeout: 3000
|
|
17
|
+
const child = spawn(platform === "darwin" ? "open" : "xdg-open", [url], {
|
|
18
|
+
stdio: "ignore"
|
|
23
19
|
});
|
|
24
|
-
|
|
20
|
+
child.on("error", () => {});
|
|
21
|
+
child.unref();
|
|
22
|
+
return child.pid !== void 0;
|
|
25
23
|
} catch {
|
|
26
24
|
return !1;
|
|
27
25
|
}
|
|
@@ -21,6 +21,7 @@ export class LockOwnershipError extends Error {
|
|
|
21
21
|
export async function withLock(target, options, fn) {
|
|
22
22
|
const started = performance.now();
|
|
23
23
|
for (;;) {
|
|
24
|
+
options.signal?.throwIfAborted();
|
|
24
25
|
const lock = await acquireRefreshFileLock({
|
|
25
26
|
path: target,
|
|
26
27
|
name: options.name,
|
|
@@ -33,6 +34,7 @@ export async function withLock(target, options, fn) {
|
|
|
33
34
|
});
|
|
34
35
|
if (lock) {
|
|
35
36
|
try {
|
|
37
|
+
options.signal?.throwIfAborted();
|
|
36
38
|
return await fn(lock);
|
|
37
39
|
}
|
|
38
40
|
finally {
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// no entry gets an absence record. A pair outside the coverage is never
|
|
12
12
|
// touched, so a header-shaped partial observation (which covers only what it
|
|
13
13
|
// carries) cannot erase a family limit or the budget.
|
|
14
|
-
import { ALL_SCOPE, decodeQuotaMap, entryTime, isQuotaCounters, limitKey, } from "./905bffc0220f43d0-map.js";
|
|
14
|
+
import { ALL_SCOPE, decodeQuotaMap, entryTime, isQuotaCounters, isQuotaCredits, limitKey, } from "./905bffc0220f43d0-map.js";
|
|
15
15
|
/** Thrown by `mergeQuotaObservation` when either argument is malformed. */
|
|
16
16
|
export class QuotaCodecError extends TypeError {
|
|
17
17
|
constructor(message) {
|
|
@@ -84,7 +84,8 @@ export function isQuotaObservation(value) {
|
|
|
84
84
|
if (!coverage.every(isObservedPair))
|
|
85
85
|
return false;
|
|
86
86
|
return ((value.budget === undefined || isObservedBudget(value.budget)) &&
|
|
87
|
-
(value.counters === undefined || isQuotaCounters(value.counters))
|
|
87
|
+
(value.counters === undefined || isQuotaCounters(value.counters)) &&
|
|
88
|
+
(value.credits === undefined || isQuotaCredits(value.credits)));
|
|
88
89
|
}
|
|
89
90
|
function compareEntries(left, right) {
|
|
90
91
|
if (left.scope !== right.scope)
|
|
@@ -110,6 +111,17 @@ function mergeCounters(stored, observed) {
|
|
|
110
111
|
}
|
|
111
112
|
return counters.size === 0 ? undefined : Object.fromEntries(counters);
|
|
112
113
|
}
|
|
114
|
+
// Credits merge like a single counter: the newer record wins, an equal time
|
|
115
|
+
// applies (the observation applied last wins), and an observation without
|
|
116
|
+
// credits leaves the stored record alone.
|
|
117
|
+
function mergeCredits(stored, observed) {
|
|
118
|
+
if (observed === undefined)
|
|
119
|
+
return stored;
|
|
120
|
+
if (stored !== undefined && observed.checkedAt < stored.checkedAt) {
|
|
121
|
+
return stored;
|
|
122
|
+
}
|
|
123
|
+
return { ...observed };
|
|
124
|
+
}
|
|
113
125
|
/**
|
|
114
126
|
* Applies `observation` to `stored` (undefined for a row with no map yet) and
|
|
115
127
|
* returns the new map. Pure: neither argument is modified. Throws
|
|
@@ -166,13 +178,15 @@ export function mergeQuotaObservation(stored, observation) {
|
|
|
166
178
|
: { scope, label: pair.label, kind: 'retired', retiredAt: at });
|
|
167
179
|
}
|
|
168
180
|
// Keys this module does not recognise are carried over untouched.
|
|
169
|
-
const { limits: _limits, budget: _budget, counters: _counters, ...unknownKeys } = base;
|
|
181
|
+
const { limits: _limits, budget: _budget, counters: _counters, credits: _credits, ...unknownKeys } = base;
|
|
170
182
|
const budget = mergeBudget(base.budget, observation.budget, at);
|
|
171
183
|
const counters = mergeCounters(base.counters, observation.counters);
|
|
184
|
+
const credits = mergeCredits(base.credits, observation.credits);
|
|
172
185
|
return {
|
|
173
186
|
...unknownKeys,
|
|
174
187
|
limits: [...entries.values()].sort(compareEntries),
|
|
175
188
|
...(budget === undefined ? {} : { budget }),
|
|
176
189
|
...(counters === undefined ? {} : { counters }),
|
|
190
|
+
...(credits === undefined ? {} : { credits }),
|
|
177
191
|
};
|
|
178
192
|
}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// the same locks as any other writer of those files.
|
|
5
5
|
import { formatQuota, isQuotaMap, projectQuota, quotaWindowName, } from "./d5a8f1061ee2f114-index.js";
|
|
6
6
|
import { DEFAULT_FORMER_MAIN_ID, orderForPlacement, resolveRoutingMode, } from "./3e7d45a77c6ad4d5-index.js";
|
|
7
|
-
import { projectFailure, } from "./94820e324f2b4c09-seam.js";
|
|
7
|
+
import { CommandError, projectFailure, } from "./94820e324f2b4c09-seam.js";
|
|
8
8
|
/** `disabledReason` recorded when the user disables an account from the menu. */
|
|
9
9
|
export const MENU_DISABLED_REASON = 'disabled from the command menu';
|
|
10
10
|
function isRecord(value) {
|
|
@@ -65,13 +65,16 @@ function addedText(name, result) {
|
|
|
65
65
|
function failureMessage(error) {
|
|
66
66
|
return projectFailure(error).text;
|
|
67
67
|
}
|
|
68
|
-
async function snapshot(
|
|
68
|
+
async function snapshot(options) {
|
|
69
|
+
const { store } = options;
|
|
69
70
|
const load = await store.read();
|
|
70
71
|
const read = await store.readSettings();
|
|
72
|
+
const vault = await options.routing?.vaultOrder?.();
|
|
71
73
|
return {
|
|
72
74
|
load,
|
|
73
75
|
rows: distinctRows(load),
|
|
74
76
|
settings: read.status === 'error' ? {} : read.settings,
|
|
77
|
+
...(vault ? { vault } : {}),
|
|
75
78
|
};
|
|
76
79
|
}
|
|
77
80
|
function accountView(row, options) {
|
|
@@ -323,6 +326,73 @@ function quotaSection(options, snap) {
|
|
|
323
326
|
},
|
|
324
327
|
};
|
|
325
328
|
}
|
|
329
|
+
/**
|
|
330
|
+
* Sets the vault order. The roster's own refusal of the list (`invalid-order`:
|
|
331
|
+
* an account left out, which it counts without naming) is shown with its own
|
|
332
|
+
* message; any other failure is projected as usual. The kind is read from
|
|
333
|
+
* the error object so the menu does not import the vault client.
|
|
334
|
+
*/
|
|
335
|
+
async function reorderVault(vault, order) {
|
|
336
|
+
try {
|
|
337
|
+
return await vault.reorder(order);
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
if (error instanceof Error &&
|
|
341
|
+
error.name === 'ClaustrumConsumerError' &&
|
|
342
|
+
error.kind === 'invalid-order')
|
|
343
|
+
throw new CommandError('vault-invalid-order', error.message, {
|
|
344
|
+
cause: error,
|
|
345
|
+
});
|
|
346
|
+
throw error;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
function invalidVaultOrder(message) {
|
|
350
|
+
return new CommandError('vault-invalid-order', message);
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* How the Routing section names vault accounts: by label, since route ids
|
|
354
|
+
* are long and opaque. A typed entry may be a label or a route id, and must
|
|
355
|
+
* name exactly one account. Refusals quote only the entry the user typed.
|
|
356
|
+
*/
|
|
357
|
+
function vaultNames(vault) {
|
|
358
|
+
const rows = vault.rows.map((row) => ({
|
|
359
|
+
id: row.id,
|
|
360
|
+
label: row.label.trim() || row.id,
|
|
361
|
+
}));
|
|
362
|
+
const matches = (entry) => rows.filter((row) => row.id === entry || row.label === entry);
|
|
363
|
+
return {
|
|
364
|
+
ids: rows.map((row) => row.id),
|
|
365
|
+
nameOf: (id) => rows.find((row) => row.id === id)?.label ?? id,
|
|
366
|
+
/**
|
|
367
|
+
* What the order input starts with for an account: its label when
|
|
368
|
+
* typing that label back names this account alone, else its route id
|
|
369
|
+
* (two accounts sharing a label, or a label with a comma or line break
|
|
370
|
+
* in it, either of which would split it into two entries).
|
|
371
|
+
*/
|
|
372
|
+
entryOf: (id) => {
|
|
373
|
+
const row = rows.find((entry) => entry.id === id);
|
|
374
|
+
return row && !/[,\n]/.test(row.label) && matches(row.label).length === 1
|
|
375
|
+
? row.label
|
|
376
|
+
: id;
|
|
377
|
+
},
|
|
378
|
+
/** The route ids the typed entries name, in order; refuses before any write. */
|
|
379
|
+
resolve: (entries) => {
|
|
380
|
+
const ids = [];
|
|
381
|
+
for (const entry of entries) {
|
|
382
|
+
const found = matches(entry);
|
|
383
|
+
if (found.length === 0)
|
|
384
|
+
throw invalidVaultOrder(`"${entry}" is not a vault account.`);
|
|
385
|
+
if (found.length > 1)
|
|
386
|
+
throw invalidVaultOrder(`"${entry}" matches more than one vault account; enter those accounts by route id.`);
|
|
387
|
+
const id = found[0].id;
|
|
388
|
+
if (ids.includes(id))
|
|
389
|
+
throw invalidVaultOrder(`"${entry}" names an account already in the order.`);
|
|
390
|
+
ids.push(id);
|
|
391
|
+
}
|
|
392
|
+
return ids;
|
|
393
|
+
},
|
|
394
|
+
};
|
|
395
|
+
}
|
|
326
396
|
function routingSection(options, snap) {
|
|
327
397
|
const { store, extraLocks } = options;
|
|
328
398
|
const locks = extraLocks ? { extraLocks } : {};
|
|
@@ -336,14 +406,18 @@ function routingSection(options, snap) {
|
|
|
336
406
|
? raw
|
|
337
407
|
: 'ordered';
|
|
338
408
|
const resolved = resolveRoutingMode(current);
|
|
339
|
-
|
|
409
|
+
// In vault mode routing tries the vault accounts, so their order is the
|
|
410
|
+
// one shown and set here; the pool roster's order is not used.
|
|
411
|
+
const vault = snap.vault ? vaultNames(snap.vault) : undefined;
|
|
412
|
+
const ids = vault ? vault.ids : snap.rows.map((row) => row.id);
|
|
413
|
+
const nameOf = (id) => (vault ? vault.nameOf(id) : id);
|
|
340
414
|
const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
|
|
341
415
|
const label = choices.find((choice) => choice.value === current)?.label ?? current;
|
|
342
416
|
const lines = [`Mode: ${label}`];
|
|
343
417
|
if (ids.length > 0)
|
|
344
|
-
lines.push(
|
|
418
|
+
lines.push(`${vault ? 'Vault account order' : 'Roster order'}: ${ids.map(nameOf).join(', ')}`);
|
|
345
419
|
if (resolved.mode === 'ordered' && tried.join() !== ids.join())
|
|
346
|
-
lines.push(`Tried in order: ${tried.join(', ')}`);
|
|
420
|
+
lines.push(`Tried in order: ${tried.map(nameOf).join(', ')}`);
|
|
347
421
|
const actions = [
|
|
348
422
|
{
|
|
349
423
|
id: 'mode',
|
|
@@ -371,19 +445,27 @@ function routingSection(options, snap) {
|
|
|
371
445
|
{
|
|
372
446
|
kind: 'text',
|
|
373
447
|
id: 'order',
|
|
374
|
-
label:
|
|
375
|
-
|
|
448
|
+
label: vault
|
|
449
|
+
? 'Vault accounts, first to last, separated by commas'
|
|
450
|
+
: 'Account ids, first to last',
|
|
451
|
+
value: vault ? ids.map(vault.entryOf).join(', ') : ids.join(', '),
|
|
376
452
|
required: true,
|
|
377
453
|
},
|
|
378
454
|
],
|
|
379
455
|
run: async ({ values }) => {
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
const
|
|
456
|
+
const text = String(values.order);
|
|
457
|
+
// A vault label may contain spaces, so vault entries are separated by
|
|
458
|
+
// commas or line breaks, not spaces; pool ids never contain spaces.
|
|
459
|
+
const entries = text
|
|
460
|
+
.split(vault ? /[,\n]+/ : /[\s,]+/)
|
|
461
|
+
.map((entry) => entry.trim())
|
|
462
|
+
.filter((entry) => entry.length > 0);
|
|
463
|
+
const result = snap.vault && vault
|
|
464
|
+
? await reorderVault(snap.vault, vault.resolve(entries))
|
|
465
|
+
: await store.reorder(entries, locks);
|
|
384
466
|
return result.outcome === 'unchanged'
|
|
385
467
|
? 'The order is unchanged.'
|
|
386
|
-
: `Order set to ${result.ids.join(', ')}.`;
|
|
468
|
+
: `Order set to ${result.ids.map(nameOf).join(', ')}.`;
|
|
387
469
|
},
|
|
388
470
|
});
|
|
389
471
|
return {
|
|
@@ -524,7 +606,7 @@ function limitsSection(options, snap) {
|
|
|
524
606
|
}
|
|
525
607
|
/** The four built-in sections, in their fixed order, from one read of the store. */
|
|
526
608
|
export async function builtinSections(options) {
|
|
527
|
-
const snap = await snapshot(options
|
|
609
|
+
const snap = await snapshot(options);
|
|
528
610
|
return [
|
|
529
611
|
accountsSection(options, snap),
|
|
530
612
|
quotaSection(options, snap),
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { createLogger } from "./cc9e0702a752cea7-index.js";
|
|
3
|
+
import { isQuotaObservation } from "./d5a8f1061ee2f114-index.js";
|
|
4
|
+
import { applyVaultQuota, mutateVaultRoster, } from "./30f5bc480f31f51c-roster.js";
|
|
5
|
+
// Every consumer of the same file shares one mailbox and one lock waiter.
|
|
6
|
+
const writers = new Map();
|
|
7
|
+
const logger = createLogger('claustrum');
|
|
8
|
+
const COALESCE_MS = 100;
|
|
9
|
+
function writerFor(path) {
|
|
10
|
+
const key = resolve(path);
|
|
11
|
+
let writer = writers.get(key);
|
|
12
|
+
if (!writer) {
|
|
13
|
+
writer = {
|
|
14
|
+
path: key,
|
|
15
|
+
pending: new Map(),
|
|
16
|
+
listeners: new Set(),
|
|
17
|
+
wake: new Set(),
|
|
18
|
+
abort: new AbortController(),
|
|
19
|
+
failures: 0,
|
|
20
|
+
draining: false,
|
|
21
|
+
order: 0,
|
|
22
|
+
};
|
|
23
|
+
writers.set(key, writer);
|
|
24
|
+
}
|
|
25
|
+
return writer;
|
|
26
|
+
}
|
|
27
|
+
/** Retain the shared writer; the last consumer's close drains it. */
|
|
28
|
+
export function retainVaultQuotaWriter(path, listener) {
|
|
29
|
+
const writer = writerFor(path);
|
|
30
|
+
writer.listeners.add(listener);
|
|
31
|
+
let released;
|
|
32
|
+
return () => (released ??= (() => {
|
|
33
|
+
writer.listeners.delete(listener);
|
|
34
|
+
return writer.listeners.size ? Promise.resolve() : drainVaultQuota(path);
|
|
35
|
+
})());
|
|
36
|
+
}
|
|
37
|
+
// Split one observation into its independently dated parts: each rate-limit
|
|
38
|
+
// window (scope and label), each covered-but-unread window, the budget, each
|
|
39
|
+
// counter and the credits record. The mailbox keeps the newest of each part on
|
|
40
|
+
// its own, so a later observation that carries only some parts can't erase an
|
|
41
|
+
// older but still newest reading of another part, which is how
|
|
42
|
+
// mergeQuotaObservation treats them on disk. Each key also carries the
|
|
43
|
+
// receipt's identity, so the identity fence still applies to every part.
|
|
44
|
+
function fields(publication) {
|
|
45
|
+
const result = new Map();
|
|
46
|
+
const { observation } = publication;
|
|
47
|
+
const witness = JSON.stringify([
|
|
48
|
+
publication.routeId,
|
|
49
|
+
publication.receipt?.credentialId,
|
|
50
|
+
publication.receipt?.accountIdentitySource,
|
|
51
|
+
publication.receipt?.expectedAccountIdentity,
|
|
52
|
+
]);
|
|
53
|
+
const add = (key, at, part) => result.set(`${witness}:${key}`, {
|
|
54
|
+
at,
|
|
55
|
+
order: 0,
|
|
56
|
+
publication: { ...publication, observation: part },
|
|
57
|
+
});
|
|
58
|
+
const keyFor = (scope, label) => JSON.stringify([scope ?? 'all', label]);
|
|
59
|
+
const read = new Set();
|
|
60
|
+
for (const reading of observation.readings ?? []) {
|
|
61
|
+
const key = keyFor(reading.scope, reading.label);
|
|
62
|
+
read.add(key);
|
|
63
|
+
add(key, observation.checkedAt, {
|
|
64
|
+
checkedAt: observation.checkedAt,
|
|
65
|
+
readings: [{ ...reading }],
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
for (const pair of observation.coverage ?? []) {
|
|
69
|
+
const key = keyFor(pair.scope, pair.label);
|
|
70
|
+
if (!read.has(key))
|
|
71
|
+
add(key, observation.checkedAt, {
|
|
72
|
+
checkedAt: observation.checkedAt,
|
|
73
|
+
coverage: [{ ...pair }],
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
if (observation.budget)
|
|
77
|
+
add('budget', observation.checkedAt, {
|
|
78
|
+
checkedAt: observation.checkedAt,
|
|
79
|
+
budget: { ...observation.budget },
|
|
80
|
+
});
|
|
81
|
+
for (const [name, counter] of Object.entries(observation.counters ?? {})) {
|
|
82
|
+
add(`counter:${name}`, counter.checkedAt, {
|
|
83
|
+
checkedAt: observation.checkedAt,
|
|
84
|
+
counters: { [name]: { ...counter } },
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
if (observation.credits)
|
|
88
|
+
add('credits', observation.credits.checkedAt, {
|
|
89
|
+
checkedAt: observation.checkedAt,
|
|
90
|
+
credits: { ...observation.credits },
|
|
91
|
+
});
|
|
92
|
+
// Even an empty observation can bind an account proved by its receipt.
|
|
93
|
+
if (!result.size)
|
|
94
|
+
add('empty', observation.checkedAt, { checkedAt: observation.checkedAt });
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
/** Enqueue without filesystem work; each quota field retains its own receipt fence. */
|
|
98
|
+
export function enqueueVaultQuota(path, publication) {
|
|
99
|
+
if (!isQuotaObservation(publication.observation))
|
|
100
|
+
return Promise.resolve(false);
|
|
101
|
+
const writer = writerFor(path);
|
|
102
|
+
const account = JSON.stringify([
|
|
103
|
+
publication.accountIdentity ?? null,
|
|
104
|
+
publication.accountIdentity === undefined ? publication.routeId : null,
|
|
105
|
+
]);
|
|
106
|
+
const pending = writer.pending.get(account) ?? new Map();
|
|
107
|
+
for (const [key, field] of fields(publication)) {
|
|
108
|
+
const previous = pending.get(key);
|
|
109
|
+
if (!previous || field.at >= previous.at) {
|
|
110
|
+
field.order = ++writer.order;
|
|
111
|
+
// A covered disappearance after an unflushed reading is a retirement,
|
|
112
|
+
// not an absence. Retain just enough history to preserve that distinction.
|
|
113
|
+
if (field.publication.observation.coverage)
|
|
114
|
+
field.priorReading = previous?.publication.observation.readings
|
|
115
|
+
? previous.publication
|
|
116
|
+
: previous?.priorReading;
|
|
117
|
+
pending.set(key, field);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (pending.size)
|
|
121
|
+
writer.pending.set(account, pending);
|
|
122
|
+
for (const listener of writer.listeners)
|
|
123
|
+
listener(publication);
|
|
124
|
+
schedule(writer, COALESCE_MS);
|
|
125
|
+
return Promise.resolve(true);
|
|
126
|
+
}
|
|
127
|
+
function orderedFields(pending) {
|
|
128
|
+
// Equal observation times are last-enqueue-wins even across different
|
|
129
|
+
// credentials or account-only readings. Map insertion order cannot prove it.
|
|
130
|
+
return [...pending.values()]
|
|
131
|
+
.flatMap((account) => [...account.values()])
|
|
132
|
+
.sort((a, b) => a.order - b.order);
|
|
133
|
+
}
|
|
134
|
+
/** Overlay uncommitted observations when a consumer reloads the durable roster. */
|
|
135
|
+
export function pendingVaultQuota(path, roster) {
|
|
136
|
+
const writer = writers.get(resolve(path));
|
|
137
|
+
if (writer) {
|
|
138
|
+
for (const field of orderedFields(writer.pending)) {
|
|
139
|
+
if (field.priorReading)
|
|
140
|
+
roster = applyVaultQuota(roster, field.priorReading).roster;
|
|
141
|
+
roster = applyVaultQuota(roster, field.publication).roster;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return roster;
|
|
145
|
+
}
|
|
146
|
+
function schedule(writer, delay) {
|
|
147
|
+
if (writer.running ||
|
|
148
|
+
writer.timer ||
|
|
149
|
+
!writer.pending.size ||
|
|
150
|
+
writer.abort.signal.aborted)
|
|
151
|
+
return;
|
|
152
|
+
writer.timer = setTimeout(() => {
|
|
153
|
+
writer.timer = undefined;
|
|
154
|
+
flush(writer);
|
|
155
|
+
}, delay);
|
|
156
|
+
if (!writer.draining)
|
|
157
|
+
writer.timer.unref?.();
|
|
158
|
+
}
|
|
159
|
+
function flush(writer) {
|
|
160
|
+
if (writer.running || writer.abort.signal.aborted)
|
|
161
|
+
return;
|
|
162
|
+
const batch = new Map([...writer.pending].map(([account, pending]) => [
|
|
163
|
+
account,
|
|
164
|
+
new Map(pending),
|
|
165
|
+
]));
|
|
166
|
+
writer.running = (async () => {
|
|
167
|
+
try {
|
|
168
|
+
await mutateVaultRoster(writer.path, (current) => {
|
|
169
|
+
let next = current;
|
|
170
|
+
for (const field of orderedFields(batch)) {
|
|
171
|
+
if (field.priorReading)
|
|
172
|
+
next = applyVaultQuota(next, field.priorReading).roster;
|
|
173
|
+
next = applyVaultQuota(next, field.publication).roster;
|
|
174
|
+
}
|
|
175
|
+
return { ...(next !== current && { next }), result: undefined };
|
|
176
|
+
}, { signal: writer.abort.signal });
|
|
177
|
+
for (const [account, fields] of batch) {
|
|
178
|
+
const pending = writer.pending.get(account);
|
|
179
|
+
for (const [key, field] of fields) {
|
|
180
|
+
// A newer enqueue must survive completion of an older flush.
|
|
181
|
+
if (pending?.get(key) === field)
|
|
182
|
+
pending.delete(key);
|
|
183
|
+
}
|
|
184
|
+
if (!pending?.size)
|
|
185
|
+
writer.pending.delete(account);
|
|
186
|
+
}
|
|
187
|
+
writer.failures = 0;
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
if (!writer.abort.signal.aborted && writer.failures++ === 0) {
|
|
191
|
+
logger.warn('vault quota publication delayed; retrying', {
|
|
192
|
+
error: error instanceof Error ? error.message : String(error),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
// Keep the batch in the mailbox, including any fresher fields enqueued meanwhile.
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
writer.running = undefined;
|
|
199
|
+
for (const wake of writer.wake)
|
|
200
|
+
wake();
|
|
201
|
+
const backoff = writer.failures
|
|
202
|
+
? Math.min(5_000, 100 * 2 ** Math.min(writer.failures, 6)) *
|
|
203
|
+
(0.5 + Math.random())
|
|
204
|
+
: COALESCE_MS;
|
|
205
|
+
schedule(writer, backoff);
|
|
206
|
+
}
|
|
207
|
+
})();
|
|
208
|
+
}
|
|
209
|
+
/** Wait at most timeoutMs for detached publication; shutdown loss is acceptable. */
|
|
210
|
+
export async function drainVaultQuota(path, timeoutMs = 1_000) {
|
|
211
|
+
const key = resolve(path);
|
|
212
|
+
const writer = writers.get(key);
|
|
213
|
+
if (!writer)
|
|
214
|
+
return;
|
|
215
|
+
writer.draining = true;
|
|
216
|
+
clearTimeout(writer.timer);
|
|
217
|
+
writer.timer = undefined;
|
|
218
|
+
let deadline;
|
|
219
|
+
let wake;
|
|
220
|
+
const drained = new Promise((done) => {
|
|
221
|
+
wake = () => {
|
|
222
|
+
if (!writer.pending.size || writer.abort.signal.aborted)
|
|
223
|
+
done();
|
|
224
|
+
};
|
|
225
|
+
writer.wake.add(wake);
|
|
226
|
+
wake();
|
|
227
|
+
});
|
|
228
|
+
try {
|
|
229
|
+
if (writer.pending.size)
|
|
230
|
+
flush(writer);
|
|
231
|
+
await Promise.race([
|
|
232
|
+
drained,
|
|
233
|
+
new Promise((done) => {
|
|
234
|
+
deadline = setTimeout(done, Math.max(0, timeoutMs));
|
|
235
|
+
}),
|
|
236
|
+
]);
|
|
237
|
+
}
|
|
238
|
+
finally {
|
|
239
|
+
clearTimeout(deadline);
|
|
240
|
+
if (wake)
|
|
241
|
+
writer.wake.delete(wake);
|
|
242
|
+
writer.draining = false;
|
|
243
|
+
// A still-open consumer owns the mailbox, so another consumer's disposal
|
|
244
|
+
// must not discard its observations or stop its retries.
|
|
245
|
+
if (!writer.listeners.size) {
|
|
246
|
+
writer.abort.abort();
|
|
247
|
+
clearTimeout(writer.timer);
|
|
248
|
+
writer.pending.clear();
|
|
249
|
+
if (writers.get(key) === writer)
|
|
250
|
+
writers.delete(key);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|