dsh-wtq-pool 1.2.3 → 1.3.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/CHANGELOG.md +21 -0
- package/LICENSE +21 -21
- package/README.en.md +11 -11
- package/README.md +13 -11
- package/lib/client.js +1 -8
- package/lib/index.js +1027 -245
- package/package.json +2 -7
- package/renderer/panel.css +2 -2
- package/renderer/panel.js +24 -25
package/lib/index.js
CHANGED
|
@@ -151,9 +151,9 @@ function writeOpenAIError(res, status, kind, message) {
|
|
|
151
151
|
* the token after it. The scheme rule in `REDACTIONS` covers those, and it runs
|
|
152
152
|
* on text the array scan has already cleared.
|
|
153
153
|
*/
|
|
154
|
-
const BARE_CREDENTIAL_KEYS = "access_?token|refresh_?token|id_?token|auth_?token|oauth_?token|api_?key|secret|token";
|
|
154
|
+
const BARE_CREDENTIAL_KEYS = "access_?token|refresh_?token|id_?token|auth_?token|oauth_?token|api_?key|secret|token|uid|uin|user[-_]?id|cookie|set-cookie";
|
|
155
155
|
/** Where a credential value begins, when that value is an array. */
|
|
156
|
-
const CREDENTIAL_ARRAY_OPEN = new RegExp(`(${`(?:\\\\{0,2}["']?)(?:${`${BARE_CREDENTIAL_KEYS}|authorization|x-ide-token|x-refresh-token|x-api-key|x-cloudide-token|cloud-ide-jwt|cosy-key|cosy-machinetoken|cosy-machineid|cosy-user|x-user-id|x-device-id|x-machine-id|x-uid`})(?:\\\\{0,2}["']?\\s*[:=]\\s*)`})\\\\?\\[`, "gi");
|
|
156
|
+
const CREDENTIAL_ARRAY_OPEN = new RegExp(`(${`(?:\\\\{0,2}["']?)\\b(?:${`${BARE_CREDENTIAL_KEYS}|authorization|x-ide-token|x-refresh-token|x-api-key|x-cloudide-token|cloud-ide-jwt|cosy-key|cosy-machinetoken|cosy-machineid|cosy-user|x-user-id|x-device-id|x-machine-id|x-uid`})(?:\\\\{0,2}["']?\\s*[:=]\\s*)`})\\\\?\\[`, "gi");
|
|
157
157
|
/**
|
|
158
158
|
* Credential shapes in any text that leaves this process.
|
|
159
159
|
*
|
|
@@ -191,7 +191,9 @@ const REDACTIONS = [
|
|
|
191
191
|
[/\beyJ[A-Za-z0-9_+/.=-]+(?:\.[A-Za-z0-9_+/.=-]+){0,2}/g, "[redacted token]"],
|
|
192
192
|
[/\b(qoder-oauth-token-)[A-Za-z0-9_+/.=-]+/g, "$1[redacted]"],
|
|
193
193
|
[/\b(rt_)[A-Za-z0-9_+/.=-]+/g, "$1[redacted]"],
|
|
194
|
-
[
|
|
194
|
+
[/\b((?:set-)?cookie\s*:\s*)[^\r\n]+/gi, "$1[redacted]"],
|
|
195
|
+
[/\b((?:set-)?cookie)\b((?:\\{0,2}["']?\s*[:=]\s*\\{0,2}))("(?:\\.|[^"\\])*"(?=\s*[,}]|$)|[^\r\n]+)/gi, "$1$2[redacted]"],
|
|
196
|
+
[new RegExp(`((?:\\\\{0,2}["']?)\\b(?:${BARE_CREDENTIAL_KEYS})(?:\\\\{0,2}["']?\\s*[:=]\\s*\\\\{0,2}["']?))[A-Za-z0-9_+/.=-]{6,}`, "gi"), "$1[redacted]"],
|
|
195
197
|
[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, "[account]"],
|
|
196
198
|
[/\b[A-Za-z]:[\\/][^\r\n"'<>|]*/g, "[redacted path]"],
|
|
197
199
|
[/\\\\[^\r\n"'<>|]+/g, "[redacted path]"],
|
|
@@ -325,8 +327,10 @@ function redactCredentialArrays(text) {
|
|
|
325
327
|
* Applied at the one place every gateway error passes through, so a new caller
|
|
326
328
|
* cannot introduce a second unredacted path.
|
|
327
329
|
*/
|
|
330
|
+
const REDACT_MAX_CHARS = 16384;
|
|
328
331
|
function redactSecrets(text) {
|
|
329
|
-
|
|
332
|
+
const raw = typeof text === "string" ? text : String(text);
|
|
333
|
+
let out = raw.length > REDACT_MAX_CHARS ? raw.slice(0, REDACT_MAX_CHARS) : raw;
|
|
330
334
|
out = redactCredentialArrays(out);
|
|
331
335
|
for (const [pattern, replacement] of REDACTIONS) out = out.replace(pattern, replacement);
|
|
332
336
|
return out;
|
|
@@ -1385,8 +1389,6 @@ const STREAM_IDLE_TIMEOUT_MS$1 = 3e5;
|
|
|
1385
1389
|
* real lifetime always replaces it in time.
|
|
1386
1390
|
*/
|
|
1387
1391
|
const ASSUMED_TOKEN_LIFETIME_MS = 36e5;
|
|
1388
|
-
/** Longest expiry `Date` can represent; anything past it is not a date. */
|
|
1389
|
-
const MAX_EXPIRY_MS$1 = 41024448e5;
|
|
1390
1392
|
/**
|
|
1391
1393
|
* Absolute expiry for a token the vendor issued, from its `expiresIn`.
|
|
1392
1394
|
*
|
|
@@ -1402,7 +1404,7 @@ function tokenExpiryMs(expiresInSec) {
|
|
|
1402
1404
|
const assumed = () => Date.now() + ASSUMED_TOKEN_LIFETIME_MS;
|
|
1403
1405
|
if (typeof expiresInSec !== "number" || !Number.isFinite(expiresInSec) || expiresInSec <= 0) return assumed();
|
|
1404
1406
|
const at = Date.now() + expiresInSec * 1e3;
|
|
1405
|
-
if (!Number.isFinite(at) || at >
|
|
1407
|
+
if (!Number.isFinite(at) || at > 41024448e5) return assumed();
|
|
1406
1408
|
return at;
|
|
1407
1409
|
}
|
|
1408
1410
|
/**
|
|
@@ -1850,8 +1852,8 @@ async function readErrorBody(response, limitBytes, signal, timeoutMs = ERROR_BOD
|
|
|
1850
1852
|
}
|
|
1851
1853
|
return text.length > limitBytes ? text.slice(0, limitBytes) : text;
|
|
1852
1854
|
}
|
|
1853
|
-
async function readEnvelope(response) {
|
|
1854
|
-
const text = await response.text();
|
|
1855
|
+
async function readEnvelope(response, signal) {
|
|
1856
|
+
const text = response.ok ? await response.text() : await readErrorBody(response, ERROR_BODY_LIMIT, signal);
|
|
1855
1857
|
if (isGatewayHtmlRejection(response.status, text)) throw Object.assign(new Error(gatewayRejectionText(response.status)), { kind: classifyUpstreamError(response.status, text) });
|
|
1856
1858
|
let parsed;
|
|
1857
1859
|
try {
|
|
@@ -3517,8 +3519,67 @@ const RENAME_RETRY_DELAYS_MS = [
|
|
|
3517
3519
|
200,
|
|
3518
3520
|
400
|
|
3519
3521
|
];
|
|
3522
|
+
/**
|
|
3523
|
+
* The work committed, but the lock file could not be removed.
|
|
3524
|
+
*
|
|
3525
|
+
* Callers that treat an acquisition failure as a reason to roll their own
|
|
3526
|
+
* change back must not do that here: the change is already on disk, and only
|
|
3527
|
+
* the bookkeeping file is left behind.
|
|
3528
|
+
*/
|
|
3529
|
+
var FileLockReleaseError = class extends Error {
|
|
3530
|
+
constructor(message) {
|
|
3531
|
+
super(message);
|
|
3532
|
+
this.name = "FileLockReleaseError";
|
|
3533
|
+
}
|
|
3534
|
+
};
|
|
3520
3535
|
const ABANDONED_RECLAIMS = /* @__PURE__ */ new Map();
|
|
3521
3536
|
/**
|
|
3537
|
+
* Locks this process failed to release, by resolved path.
|
|
3538
|
+
*
|
|
3539
|
+
* A holder that shares only reads blocks the write that would mark the lock
|
|
3540
|
+
* abandoned as well as the unlink. A sidecar records the same fact for other
|
|
3541
|
+
* processes; this map is the fallback when even creating a new file is denied.
|
|
3542
|
+
*/
|
|
3543
|
+
const ABANDONED_LOCKS = /* @__PURE__ */ new Map();
|
|
3544
|
+
function abandonedMarker(file, token) {
|
|
3545
|
+
return `${file}.abandoned.${token}`;
|
|
3546
|
+
}
|
|
3547
|
+
async function markAbandoned(file, token) {
|
|
3548
|
+
ABANDONED_LOCKS.set(resolve(file), token);
|
|
3549
|
+
try {
|
|
3550
|
+
await writeFile(abandonedMarker(file, token), JSON.stringify({
|
|
3551
|
+
token,
|
|
3552
|
+
createdAtMs: Date.now()
|
|
3553
|
+
}), {
|
|
3554
|
+
flag: "wx",
|
|
3555
|
+
mode: 384
|
|
3556
|
+
});
|
|
3557
|
+
} catch {}
|
|
3558
|
+
}
|
|
3559
|
+
async function hasAbandonedMarker(file, token) {
|
|
3560
|
+
try {
|
|
3561
|
+
await stat(abandonedMarker(file, token));
|
|
3562
|
+
return true;
|
|
3563
|
+
} catch {
|
|
3564
|
+
return false;
|
|
3565
|
+
}
|
|
3566
|
+
}
|
|
3567
|
+
async function cleanupAbandonedMarkers(file) {
|
|
3568
|
+
const directory = dirname(file);
|
|
3569
|
+
const prefix = `${basename(file)}.abandoned.`;
|
|
3570
|
+
let names;
|
|
3571
|
+
try {
|
|
3572
|
+
names = await readdir(directory);
|
|
3573
|
+
} catch {
|
|
3574
|
+
return;
|
|
3575
|
+
}
|
|
3576
|
+
for (const name of names) {
|
|
3577
|
+
if (!name.startsWith(prefix)) continue;
|
|
3578
|
+
await unlink(join(directory, name)).catch(() => {});
|
|
3579
|
+
}
|
|
3580
|
+
ABANDONED_LOCKS.delete(resolve(file));
|
|
3581
|
+
}
|
|
3582
|
+
/**
|
|
3522
3583
|
* Commit a complete temporary file over its target.
|
|
3523
3584
|
*
|
|
3524
3585
|
* Windows can report EPERM or EBUSY while another reader is between opening
|
|
@@ -3608,6 +3669,10 @@ async function lockState(file) {
|
|
|
3608
3669
|
owner = JSON.parse(text);
|
|
3609
3670
|
} catch {}
|
|
3610
3671
|
if (owner?.state === "abandoned") return "stale";
|
|
3672
|
+
if (typeof owner?.token === "string") {
|
|
3673
|
+
if (ABANDONED_LOCKS.get(resolve(file)) === owner.token) return "stale";
|
|
3674
|
+
if (await hasAbandonedMarker(file, owner.token)) return "stale";
|
|
3675
|
+
}
|
|
3611
3676
|
const fileAge = await stat(file).then((entry) => Date.now() - entry.mtimeMs, () => 0);
|
|
3612
3677
|
const ownerAlive = typeof owner?.pid === "number" ? processIsAlive(owner.pid) : void 0;
|
|
3613
3678
|
if (ownerAlive === false) return "stale";
|
|
@@ -3636,7 +3701,9 @@ async function createOwnedFile(file) {
|
|
|
3636
3701
|
});
|
|
3637
3702
|
return token;
|
|
3638
3703
|
} catch (error) {
|
|
3639
|
-
|
|
3704
|
+
const code = error.code;
|
|
3705
|
+
if (code === "EEXIST") return void 0;
|
|
3706
|
+
if (process.platform === "win32" && (code === "EPERM" || code === "EACCES")) return void 0;
|
|
3640
3707
|
throw error;
|
|
3641
3708
|
}
|
|
3642
3709
|
}
|
|
@@ -3650,6 +3717,10 @@ async function releaseOwnedFile(file, token) {
|
|
|
3650
3717
|
} catch (error) {
|
|
3651
3718
|
const code = error.code;
|
|
3652
3719
|
if (code === "ENOENT" || code === "ENOTDIR") return "missing";
|
|
3720
|
+
if (code === "EBUSY" || code === "EPERM" || code === "EACCES") {
|
|
3721
|
+
await markAbandoned(file, token);
|
|
3722
|
+
return "failed";
|
|
3723
|
+
}
|
|
3653
3724
|
}
|
|
3654
3725
|
if (owner !== void 0) {
|
|
3655
3726
|
if (owner.token !== token) return "replaced";
|
|
@@ -3667,7 +3738,10 @@ async function releaseOwnedFile(file, token) {
|
|
|
3667
3738
|
} catch {}
|
|
3668
3739
|
}
|
|
3669
3740
|
}
|
|
3670
|
-
if (Date.now() >= deadline)
|
|
3741
|
+
if (Date.now() >= deadline) {
|
|
3742
|
+
await markAbandoned(file, token);
|
|
3743
|
+
return "failed";
|
|
3744
|
+
}
|
|
3671
3745
|
await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
|
|
3672
3746
|
}
|
|
3673
3747
|
}
|
|
@@ -3684,6 +3758,14 @@ async function newestReclaimGeneration(lock) {
|
|
|
3684
3758
|
}
|
|
3685
3759
|
return generation;
|
|
3686
3760
|
}
|
|
3761
|
+
/**
|
|
3762
|
+
* Drop reclaim generations that are no longer fencing anything.
|
|
3763
|
+
*
|
|
3764
|
+
* Answers false when a terminal generation could not be removed. Creating the
|
|
3765
|
+
* next generation then would leave both files behind, and a filesystem that
|
|
3766
|
+
* keeps refusing the delete would grow one more on every retry. The caller
|
|
3767
|
+
* waits instead; the cleanup above succeeds once the deletion does.
|
|
3768
|
+
*/
|
|
3687
3769
|
async function cleanupTerminalReclaims(lock) {
|
|
3688
3770
|
const directory = dirname(lock);
|
|
3689
3771
|
const prefix = `${basename(lock)}.reclaim.`;
|
|
@@ -3691,13 +3773,14 @@ async function cleanupTerminalReclaims(lock) {
|
|
|
3691
3773
|
try {
|
|
3692
3774
|
names = await readdir(directory);
|
|
3693
3775
|
} catch {
|
|
3694
|
-
return;
|
|
3776
|
+
return true;
|
|
3695
3777
|
}
|
|
3696
3778
|
const claimNames = names.filter((name) => {
|
|
3697
3779
|
if (!name.startsWith(prefix)) return false;
|
|
3698
3780
|
return /^\d+$/.test(name.slice(prefix.length));
|
|
3699
3781
|
});
|
|
3700
3782
|
const claimNameSet = new Set(claimNames);
|
|
3783
|
+
let blocked = false;
|
|
3701
3784
|
for (const claimName of claimNames) {
|
|
3702
3785
|
const claim = join(directory, claimName);
|
|
3703
3786
|
const sidecars = names.filter((name) => name.startsWith(`${claimName}.abandoned.`));
|
|
@@ -3708,7 +3791,7 @@ async function cleanupTerminalReclaims(lock) {
|
|
|
3708
3791
|
owner = typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
3709
3792
|
} catch {}
|
|
3710
3793
|
const terminalState = owner?.state === "complete" || owner?.state === "abandoned";
|
|
3711
|
-
const rememberedAbandonment = ABANDONED_RECLAIMS.get(claim) === owner
|
|
3794
|
+
const rememberedAbandonment = owner?.token !== void 0 && ABANDONED_RECLAIMS.get(claim) === owner.token;
|
|
3712
3795
|
if (sidecars.length === 0 && !terminalState && !rememberedAbandonment) continue;
|
|
3713
3796
|
let claimRemoved = false;
|
|
3714
3797
|
try {
|
|
@@ -3718,7 +3801,10 @@ async function cleanupTerminalReclaims(lock) {
|
|
|
3718
3801
|
const code = error.code;
|
|
3719
3802
|
claimRemoved = code === "ENOENT" || code === "ENOTDIR";
|
|
3720
3803
|
}
|
|
3721
|
-
if (!claimRemoved)
|
|
3804
|
+
if (!claimRemoved) {
|
|
3805
|
+
blocked = true;
|
|
3806
|
+
continue;
|
|
3807
|
+
}
|
|
3722
3808
|
for (const sidecar of sidecars) await unlink(join(directory, sidecar)).catch(() => {});
|
|
3723
3809
|
for (const temporary of temporaryFiles) await unlink(join(directory, temporary)).catch(() => {});
|
|
3724
3810
|
ABANDONED_RECLAIMS.delete(claim);
|
|
@@ -3730,6 +3816,7 @@ async function cleanupTerminalReclaims(lock) {
|
|
|
3730
3816
|
if (claimNameSet.has(name.slice(0, abandoned))) continue;
|
|
3731
3817
|
await unlink(join(directory, name)).catch(() => {});
|
|
3732
3818
|
}
|
|
3819
|
+
return !blocked;
|
|
3733
3820
|
}
|
|
3734
3821
|
async function claimStaleReclaim(lock) {
|
|
3735
3822
|
const directory = dirname(lock);
|
|
@@ -3746,7 +3833,7 @@ async function claimStaleReclaim(lock) {
|
|
|
3746
3833
|
}).map((name) => join(directory, name));
|
|
3747
3834
|
for (const claim of claims) {
|
|
3748
3835
|
const claimName = basename(claim);
|
|
3749
|
-
if (names.some((name) => name.startsWith(`${claimName}.abandoned.`)))
|
|
3836
|
+
if (names.some((name) => name.startsWith(`${claimName}.abandoned.`))) return void 0;
|
|
3750
3837
|
let owner = {};
|
|
3751
3838
|
try {
|
|
3752
3839
|
const parsed = JSON.parse(await readFile(claim, "utf8"));
|
|
@@ -3757,9 +3844,20 @@ async function claimStaleReclaim(lock) {
|
|
|
3757
3844
|
continue;
|
|
3758
3845
|
}
|
|
3759
3846
|
}
|
|
3760
|
-
if (owner.state === "complete" || owner.state === "abandoned")
|
|
3761
|
-
if (ABANDONED_RECLAIMS.get(claim) === owner.token)
|
|
3847
|
+
if (owner.state === "complete" || owner.state === "abandoned") return void 0;
|
|
3848
|
+
if (owner.token !== void 0 && ABANDONED_RECLAIMS.get(claim) === owner.token) return void 0;
|
|
3762
3849
|
if (await lockState(claim) === "current") return void 0;
|
|
3850
|
+
try {
|
|
3851
|
+
await unlink(claim);
|
|
3852
|
+
} catch (error) {
|
|
3853
|
+
const code = error.code;
|
|
3854
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") return void 0;
|
|
3855
|
+
}
|
|
3856
|
+
for (const name of names) {
|
|
3857
|
+
if (!name.startsWith(`${claimName}.`) || !name.endsWith(".tmp")) continue;
|
|
3858
|
+
await unlink(join(directory, name)).catch(() => {});
|
|
3859
|
+
}
|
|
3860
|
+
ABANDONED_RECLAIMS.delete(claim);
|
|
3763
3861
|
}
|
|
3764
3862
|
const file = `${lock}.reclaim.${String(generation + 1).padStart(12, "0")}`;
|
|
3765
3863
|
const token = await createOwnedFile(file);
|
|
@@ -3829,42 +3927,46 @@ async function abandonReclaim(reclaim, cause) {
|
|
|
3829
3927
|
}
|
|
3830
3928
|
/** Run `work` while holding a lock file shared by every writer to the same document. */
|
|
3831
3929
|
async function withFileLock(lock, work) {
|
|
3832
|
-
await mkdir(dirname(lock), {
|
|
3930
|
+
await mkdir(dirname(lock), {
|
|
3931
|
+
recursive: true,
|
|
3932
|
+
mode: 448
|
|
3933
|
+
});
|
|
3833
3934
|
const deadline = Date.now() + FILE_LOCK_WAIT_MS;
|
|
3834
3935
|
let token;
|
|
3835
3936
|
while (token === void 0) {
|
|
3836
3937
|
token = await createOwnedFile(lock);
|
|
3837
3938
|
if (token !== void 0) break;
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3939
|
+
if (await lockState(lock) === "stale") {
|
|
3940
|
+
const reclaim = await cleanupTerminalReclaims(lock) ? await claimStaleReclaim(lock) : void 0;
|
|
3941
|
+
if (reclaim !== void 0) try {
|
|
3942
|
+
if (await newestReclaimGeneration(lock) === reclaim.generation && await lockState(lock) === "stale" && await newestReclaimGeneration(lock) === reclaim.generation) await unlink(lock).catch(() => {});
|
|
3943
|
+
} finally {
|
|
3843
3944
|
try {
|
|
3844
|
-
|
|
3845
|
-
}
|
|
3846
|
-
|
|
3847
|
-
await completeReclaim(reclaim);
|
|
3848
|
-
} catch (error) {
|
|
3849
|
-
await abandonReclaim(reclaim, error);
|
|
3850
|
-
}
|
|
3945
|
+
await completeReclaim(reclaim);
|
|
3946
|
+
} catch (error) {
|
|
3947
|
+
await abandonReclaim(reclaim, error);
|
|
3851
3948
|
}
|
|
3852
|
-
continue;
|
|
3853
3949
|
}
|
|
3854
3950
|
}
|
|
3855
3951
|
if (Date.now() >= deadline) throw new Error("timed out waiting for the credential document lock");
|
|
3856
3952
|
await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
|
|
3857
3953
|
}
|
|
3954
|
+
await cleanupAbandonedMarkers(lock);
|
|
3858
3955
|
await cleanupTerminalReclaims(lock);
|
|
3859
3956
|
try {
|
|
3860
3957
|
await work();
|
|
3861
3958
|
} catch (error) {
|
|
3862
3959
|
const released = await releaseOwnedFile(lock, token);
|
|
3863
|
-
if (released !== "released" && released !== "missing")
|
|
3960
|
+
if (released !== "released" && released !== "missing") {
|
|
3961
|
+
const wrapped = new Error("work failed and the credential document lock was not released", { cause: error });
|
|
3962
|
+
const code = error.code;
|
|
3963
|
+
if (code !== void 0) wrapped.code = code;
|
|
3964
|
+
throw wrapped;
|
|
3965
|
+
}
|
|
3864
3966
|
throw error;
|
|
3865
3967
|
}
|
|
3866
3968
|
const released = await releaseOwnedFile(lock, token);
|
|
3867
|
-
if (released !== "released" && released !== "missing") throw new
|
|
3969
|
+
if (released !== "released" && released !== "missing") throw new FileLockReleaseError("work completed but the credential document lock was not released");
|
|
3868
3970
|
}
|
|
3869
3971
|
//#endregion
|
|
3870
3972
|
//#region src/accounts.ts
|
|
@@ -3962,7 +4064,6 @@ function defaultDesktopAuthDirs(platform = process.platform, home = homedir(), e
|
|
|
3962
4064
|
* 8.64e15 `new Date(…).toISOString()` also throws, which failed the whole
|
|
3963
4065
|
* panel document rather than the one row.
|
|
3964
4066
|
*/
|
|
3965
|
-
const MAX_EXPIRY_MS = 41024448e5;
|
|
3966
4067
|
/**
|
|
3967
4068
|
* Normalize an expiry that may arrive in seconds or milliseconds.
|
|
3968
4069
|
*
|
|
@@ -3973,7 +4074,7 @@ const MAX_EXPIRY_MS = 41024448e5;
|
|
|
3973
4074
|
function expiryToMs(value) {
|
|
3974
4075
|
if (!Number.isFinite(value) || value <= 0) return 0;
|
|
3975
4076
|
const ms = value > 0xe8d4a51000 ? value : value * 1e3;
|
|
3976
|
-
return ms >
|
|
4077
|
+
return ms > 41024448e5 ? 0 : ms;
|
|
3977
4078
|
}
|
|
3978
4079
|
function optionalString$1(value) {
|
|
3979
4080
|
return typeof value === "string" && value !== "" ? value : void 0;
|
|
@@ -4192,20 +4293,31 @@ async function readDeletedSignInsFile(file) {
|
|
|
4192
4293
|
const entries = parsed?.entries;
|
|
4193
4294
|
if (entries === null || typeof entries !== "object" || Array.isArray(entries)) return tombstones;
|
|
4194
4295
|
for (const [id, value] of Object.entries(entries)) {
|
|
4195
|
-
const
|
|
4196
|
-
if (
|
|
4197
|
-
const digest = entry.tokenDigest;
|
|
4198
|
-
if (typeof digest !== "string" || digest === "") continue;
|
|
4199
|
-
const issued = entry.lastRefreshAtMs;
|
|
4200
|
-
const deletedAt = entry.deletedAtMs;
|
|
4201
|
-
tombstones.set(id, {
|
|
4202
|
-
tokenDigest: digest,
|
|
4203
|
-
lastRefreshAtMs: typeof issued === "number" && Number.isFinite(issued) ? issued : 0,
|
|
4204
|
-
deletedAtMs: typeof deletedAt === "number" && Number.isFinite(deletedAt) ? deletedAt : 0
|
|
4205
|
-
});
|
|
4296
|
+
const record = deletedSignInFrom(value);
|
|
4297
|
+
if (record !== void 0) tombstones.set(id, record);
|
|
4206
4298
|
}
|
|
4207
4299
|
return tombstones;
|
|
4208
4300
|
}
|
|
4301
|
+
function deletedSignInFrom(value) {
|
|
4302
|
+
const entry = value;
|
|
4303
|
+
if (entry === null || typeof entry !== "object") return void 0;
|
|
4304
|
+
const digest = entry.tokenDigest;
|
|
4305
|
+
if (typeof digest !== "string" || digest === "") return void 0;
|
|
4306
|
+
const issued = entry.lastRefreshAtMs;
|
|
4307
|
+
const deletedAt = entry.deletedAtMs;
|
|
4308
|
+
const nonce = entry.nonce;
|
|
4309
|
+
const alternates = Array.isArray(entry.alternates) ? entry.alternates.flatMap((alternate) => {
|
|
4310
|
+
const record = deletedSignInFrom(alternate);
|
|
4311
|
+
return record === void 0 ? [] : [record];
|
|
4312
|
+
}) : [];
|
|
4313
|
+
return {
|
|
4314
|
+
tokenDigest: digest,
|
|
4315
|
+
lastRefreshAtMs: typeof issued === "number" && Number.isFinite(issued) ? issued : 0,
|
|
4316
|
+
deletedAtMs: typeof deletedAt === "number" && Number.isFinite(deletedAt) ? deletedAt : 0,
|
|
4317
|
+
...typeof nonce === "string" && nonce !== "" ? { nonce } : {},
|
|
4318
|
+
...alternates.length > 0 ? { alternates } : {}
|
|
4319
|
+
};
|
|
4320
|
+
}
|
|
4209
4321
|
/**
|
|
4210
4322
|
* Whether `credential` is a sign-in the user made after deleting the account.
|
|
4211
4323
|
*
|
|
@@ -4230,6 +4342,98 @@ function endsTombstone(tombstone, credential) {
|
|
|
4230
4342
|
return isLiveAuthFile(credential.sourcePath);
|
|
4231
4343
|
}
|
|
4232
4344
|
/**
|
|
4345
|
+
* The tombstone that names a credential, under either of its pool keys.
|
|
4346
|
+
*
|
|
4347
|
+
* A key written by 1.2.3 for an identity-less sign-in is not the key this build
|
|
4348
|
+
* computes, so looking only at the current one let the client's snapshot bring
|
|
4349
|
+
* the account straight back after an upgrade. The record is returned with the
|
|
4350
|
+
* key it was stored under and whether that key is the current one: only a
|
|
4351
|
+
* current-key record may be released, and only by removing the entry that
|
|
4352
|
+
* actually holds it.
|
|
4353
|
+
*/
|
|
4354
|
+
function tombstoneOf(tombstones, credential, currentId = workbuddyAccountId(credential)) {
|
|
4355
|
+
const record = tombstones.get(currentId);
|
|
4356
|
+
if (record !== void 0) return {
|
|
4357
|
+
key: currentId,
|
|
4358
|
+
record,
|
|
4359
|
+
current: true
|
|
4360
|
+
};
|
|
4361
|
+
for (const previous of previousAccountIds(credential)) {
|
|
4362
|
+
const old = tombstones.get(previous);
|
|
4363
|
+
if (old !== void 0) return {
|
|
4364
|
+
key: previous,
|
|
4365
|
+
record: old,
|
|
4366
|
+
current: false
|
|
4367
|
+
};
|
|
4368
|
+
}
|
|
4369
|
+
}
|
|
4370
|
+
/**
|
|
4371
|
+
* Which of two deletes names the newer sign-in.
|
|
4372
|
+
*
|
|
4373
|
+
* A delete from a stale roster can arrive after another pool already deleted a
|
|
4374
|
+
* newer sign-in for the same account. The record naming the newer sign-in is
|
|
4375
|
+
* the one that still has to hold, whichever delete committed last: an older
|
|
4376
|
+
* record would let the newer sign-in back in as a re-login. Records that name
|
|
4377
|
+
* the same (or an undated) sign-in fall back to the later delete.
|
|
4378
|
+
*/
|
|
4379
|
+
function namesNewerSignIn(candidate, current) {
|
|
4380
|
+
if (candidate.lastRefreshAtMs > 0 && current.lastRefreshAtMs === 0) return true;
|
|
4381
|
+
if (candidate.lastRefreshAtMs === 0 && current.lastRefreshAtMs > 0) return false;
|
|
4382
|
+
if (candidate.lastRefreshAtMs > 0 && current.lastRefreshAtMs > 0 && candidate.lastRefreshAtMs !== current.lastRefreshAtMs) return candidate.lastRefreshAtMs > current.lastRefreshAtMs;
|
|
4383
|
+
return candidate.deletedAtMs > current.deletedAtMs;
|
|
4384
|
+
}
|
|
4385
|
+
function recordsOf(entry) {
|
|
4386
|
+
if (entry.alternates === void 0) return [entry];
|
|
4387
|
+
return [entry, ...entry.alternates.flatMap((record) => recordsOf(record))];
|
|
4388
|
+
}
|
|
4389
|
+
function withoutAlternates(record) {
|
|
4390
|
+
const { alternates: _ignored, ...bare } = record;
|
|
4391
|
+
return bare;
|
|
4392
|
+
}
|
|
4393
|
+
function sameDeletedSignIn(left, right) {
|
|
4394
|
+
if (left.nonce !== void 0 || right.nonce !== void 0) return left.nonce === right.nonce;
|
|
4395
|
+
return left.tokenDigest === right.tokenDigest && left.lastRefreshAtMs === right.lastRefreshAtMs && left.deletedAtMs === right.deletedAtMs;
|
|
4396
|
+
}
|
|
4397
|
+
function deletedSignInFromRecords(records) {
|
|
4398
|
+
if (records.length === 0) return void 0;
|
|
4399
|
+
const [primary, ...alternates] = records;
|
|
4400
|
+
const bare = withoutAlternates(primary);
|
|
4401
|
+
return alternates.length === 0 ? bare : {
|
|
4402
|
+
...bare,
|
|
4403
|
+
alternates: alternates.map(withoutAlternates)
|
|
4404
|
+
};
|
|
4405
|
+
}
|
|
4406
|
+
function mergeDeletedSignIns(existing, candidate) {
|
|
4407
|
+
if (existing === void 0) return withoutAlternates(candidate);
|
|
4408
|
+
const records = [...recordsOf(existing)];
|
|
4409
|
+
const bare = withoutAlternates(candidate);
|
|
4410
|
+
if (!records.some((record) => sameDeletedSignIn(record, bare))) records.push(bare);
|
|
4411
|
+
let primary = 0;
|
|
4412
|
+
for (let index = 1; index < records.length; index += 1) if (namesNewerSignIn(records[index], records[primary])) primary = index;
|
|
4413
|
+
const [chosen] = records.splice(primary, 1);
|
|
4414
|
+
return deletedSignInFromRecords([chosen, ...records]);
|
|
4415
|
+
}
|
|
4416
|
+
function dropDeletedSignIns(entry, targets) {
|
|
4417
|
+
const kept = recordsOf(entry).filter((record) => !targets.some((target) => sameDeletedSignIn(record, target)));
|
|
4418
|
+
if (kept.length === recordsOf(entry).length) return entry;
|
|
4419
|
+
return deletedSignInFromRecords(kept);
|
|
4420
|
+
}
|
|
4421
|
+
/**
|
|
4422
|
+
* Whether a tombstone still keeps this credential out of the pool.
|
|
4423
|
+
*
|
|
4424
|
+
* A record under the current key is judged by the re-login rule. A key written
|
|
4425
|
+
* by 1.2.3 cannot tell two same-nickname sign-ins apart, so it may only keep
|
|
4426
|
+
* the sign-in it was written for out: the token digest is the one fact that
|
|
4427
|
+
* belongs to the deleted session alone. That record is never released here,
|
|
4428
|
+
* because releasing it on another account's token would resurrect the deleted
|
|
4429
|
+
* row on the next scan.
|
|
4430
|
+
*/
|
|
4431
|
+
function tombstoneBlocks(entry, credential) {
|
|
4432
|
+
if (entry.current) return recordsOf(entry.record).some((record) => !endsTombstone(record, credential));
|
|
4433
|
+
const digest = tokenDigest(credential.accessToken);
|
|
4434
|
+
return recordsOf(entry.record).some((record) => digest === record.tokenDigest);
|
|
4435
|
+
}
|
|
4436
|
+
/**
|
|
4233
4437
|
* Whether `sourcePath` sits inside the directory the plugin writes into.
|
|
4234
4438
|
*
|
|
4235
4439
|
* A walk that escapes the root is not inside it, and `..` is how a path gets
|
|
@@ -4241,14 +4445,98 @@ function ownSignInPath(sourcePath, ownDir) {
|
|
|
4241
4445
|
return walked !== "" && !walked.startsWith("..") && !isAbsolute(walked);
|
|
4242
4446
|
}
|
|
4243
4447
|
function workbuddyAccountId(credential) {
|
|
4448
|
+
const stable = credential.uin ?? credential.uid ?? `${credential.nickname ?? ""}\u0000${credential.sourcePath}`;
|
|
4449
|
+
return createHash("sha256").update(`workbuddy\0${stable}`).digest("hex").slice(0, 16);
|
|
4450
|
+
}
|
|
4451
|
+
/**
|
|
4452
|
+
* The pool key a 1.2.3 build gave a credential with no vendor id.
|
|
4453
|
+
*
|
|
4454
|
+
* That build hashed the nickname alone, or the path when there was none. This
|
|
4455
|
+
* build hashes both so two sign-ins sharing one nickname stay two accounts,
|
|
4456
|
+
* which means an upgraded install still carries the old key in its settings and
|
|
4457
|
+
* its deleted-sign-in file. The pool answers to either key: a switch the user
|
|
4458
|
+
* turned off does not come back on, and a delete does not resurrect its row.
|
|
4459
|
+
*/
|
|
4460
|
+
function legacyWorkBuddyAccountId(credential) {
|
|
4244
4461
|
const stable = credential.uin ?? credential.uid ?? credential.nickname ?? `path:${credential.sourcePath}`;
|
|
4245
4462
|
return createHash("sha256").update(`workbuddy\0${stable}`).digest("hex").slice(0, 16);
|
|
4246
4463
|
}
|
|
4464
|
+
/**
|
|
4465
|
+
* The 1.2.3 key for a credential, when it differs from the current one.
|
|
4466
|
+
*
|
|
4467
|
+
* A vendor id hashes the same in both builds, so only a sign-in with no
|
|
4468
|
+
* identity has any older key to read. The current key is not repeated.
|
|
4469
|
+
*/
|
|
4470
|
+
function previousAccountIds(credential) {
|
|
4471
|
+
if ((credential.uin ?? credential.uid) !== void 0) return [];
|
|
4472
|
+
const previous = legacyWorkBuddyAccountId(credential);
|
|
4473
|
+
return previous === workbuddyAccountId(credential) ? [] : [previous];
|
|
4474
|
+
}
|
|
4247
4475
|
/** Human label; the nickname alone, so the pool reads as names rather than keys. */
|
|
4248
4476
|
function accountLabel(credential) {
|
|
4249
4477
|
return credential.nickname ?? "WorkBuddy";
|
|
4250
4478
|
}
|
|
4251
4479
|
/**
|
|
4480
|
+
* Collapse identity-less copies of one session.
|
|
4481
|
+
*
|
|
4482
|
+
* A sign-in with no uin/uid is keyed by its file, and an earlier build adopted
|
|
4483
|
+
* the desktop's superseded snapshot under a second path. Both copies carry one
|
|
4484
|
+
* session, so renewing either spends the other's refresh token. Copies sharing
|
|
4485
|
+
* a token are folded, and once the plugin owns an identity-less copy, the
|
|
4486
|
+
* desktop snapshot with the same domain and nickname stays folded even after a
|
|
4487
|
+
* renewal rotates the token away. That name-based half is migration-only: a
|
|
4488
|
+
* newer build does not adopt identity-less snapshots, and `foldSessionCopies`
|
|
4489
|
+
* only applies it where an own copy exists. The live file wins because the app
|
|
4490
|
+
* renews it, then the plugin's own copy, then the freshest snapshot.
|
|
4491
|
+
*/
|
|
4492
|
+
function foldSessionCopies(credentials, ownDir) {
|
|
4493
|
+
const isOwn = (credential) => ownSignInPath(credential.sourcePath, ownDir);
|
|
4494
|
+
const identityLess = (credential) => (credential.uin ?? credential.uid ?? "") === "";
|
|
4495
|
+
const tokenKey = (credential) => {
|
|
4496
|
+
if (!identityLess(credential)) return "";
|
|
4497
|
+
const token = credential.refreshToken || credential.accessToken;
|
|
4498
|
+
return token === "" ? "" : credential.domain + "\0" + token;
|
|
4499
|
+
};
|
|
4500
|
+
const nameKey = (credential) => {
|
|
4501
|
+
if (!identityLess(credential) || (credential.nickname ?? "") === "") return "";
|
|
4502
|
+
return credential.domain + "\0" + credential.nickname;
|
|
4503
|
+
};
|
|
4504
|
+
const copiedTokens = /* @__PURE__ */ new Set();
|
|
4505
|
+
for (const credential of credentials) {
|
|
4506
|
+
const key = tokenKey(credential);
|
|
4507
|
+
if (key !== "" && isOwn(credential)) copiedTokens.add(key);
|
|
4508
|
+
}
|
|
4509
|
+
const rankOf = (credential) => isLiveAuthFile(credential.sourcePath) ? 3 : ownSignInPath(credential.sourcePath, ownDir) ? 2 : 1;
|
|
4510
|
+
const best = /* @__PURE__ */ new Map();
|
|
4511
|
+
for (const credential of credentials) {
|
|
4512
|
+
const key = tokenKey(credential);
|
|
4513
|
+
if (key === "" || !copiedTokens.has(key)) continue;
|
|
4514
|
+
const current = best.get(key);
|
|
4515
|
+
if (current === void 0 || rankOf(credential) > rankOf(current) || rankOf(credential) === rankOf(current) && isFresher(credential, current, ownDir)) best.set(key, credential);
|
|
4516
|
+
}
|
|
4517
|
+
const ownedNames = /* @__PURE__ */ new Set();
|
|
4518
|
+
for (const credential of credentials) {
|
|
4519
|
+
const key = nameKey(credential);
|
|
4520
|
+
if (key !== "" && isOwn(credential)) ownedNames.add(key);
|
|
4521
|
+
}
|
|
4522
|
+
const bestOwned = /* @__PURE__ */ new Map();
|
|
4523
|
+
for (const credential of credentials) {
|
|
4524
|
+
const key = nameKey(credential);
|
|
4525
|
+
if (key === "" || !ownedNames.has(key) || !isOwn(credential)) continue;
|
|
4526
|
+
const current = bestOwned.get(key);
|
|
4527
|
+
if (current === void 0 || isFresher(credential, current, ownDir)) bestOwned.set(key, credential);
|
|
4528
|
+
}
|
|
4529
|
+
return credentials.filter((credential) => {
|
|
4530
|
+
const key = tokenKey(credential);
|
|
4531
|
+
if (key !== "" && copiedTokens.has(key) && best.get(key) !== credential) return false;
|
|
4532
|
+
const name = nameKey(credential);
|
|
4533
|
+
if (name === "" || !ownedNames.has(name)) return true;
|
|
4534
|
+
if (isLiveAuthFile(credential.sourcePath)) return true;
|
|
4535
|
+
if (isOwn(credential)) return bestOwned.get(name) === credential;
|
|
4536
|
+
return false;
|
|
4537
|
+
});
|
|
4538
|
+
}
|
|
4539
|
+
/**
|
|
4252
4540
|
* Whether a credential can no longer serve a request at all.
|
|
4253
4541
|
*
|
|
4254
4542
|
* Only a token that has already died AND that carries nothing to renew it with.
|
|
@@ -4529,8 +4817,12 @@ function ownSignInFile(directory, signIn) {
|
|
|
4529
4817
|
}
|
|
4530
4818
|
async function writeOwnSignInDocument(file, signIn, signal) {
|
|
4531
4819
|
signal?.throwIfAborted();
|
|
4532
|
-
await mkdir(dirname(file), {
|
|
4820
|
+
await mkdir(dirname(file), {
|
|
4821
|
+
recursive: true,
|
|
4822
|
+
mode: 448
|
|
4823
|
+
});
|
|
4533
4824
|
signal?.throwIfAborted();
|
|
4825
|
+
await removeAbandonedTemps(file);
|
|
4534
4826
|
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
4535
4827
|
try {
|
|
4536
4828
|
await writeFile(temporary, JSON.stringify({
|
|
@@ -4565,6 +4857,7 @@ async function writeOwnSignInDocument(file, signIn, signal) {
|
|
|
4565
4857
|
*/
|
|
4566
4858
|
async function renewOwnSignInFile(file, credential, previous, createIfMissing = false, beforeCommit) {
|
|
4567
4859
|
return await withSignInWriteLock(file, async () => {
|
|
4860
|
+
await removeAbandonedTemps(file);
|
|
4568
4861
|
let text;
|
|
4569
4862
|
try {
|
|
4570
4863
|
text = await readFile(file, "utf8");
|
|
@@ -4572,6 +4865,10 @@ async function renewOwnSignInFile(file, credential, previous, createIfMissing =
|
|
|
4572
4865
|
if (!createIfMissing || error.code !== "ENOENT") throw error;
|
|
4573
4866
|
if (beforeCommit !== void 0 && !await beforeCommit()) return false;
|
|
4574
4867
|
await writeOwnSignInDocument(file, ownSignInOf(credential));
|
|
4868
|
+
if (beforeCommit !== void 0 && !await beforeCommit()) {
|
|
4869
|
+
await unlink(file).catch(() => {});
|
|
4870
|
+
return false;
|
|
4871
|
+
}
|
|
4575
4872
|
return true;
|
|
4576
4873
|
}
|
|
4577
4874
|
const document = JSON.parse(text);
|
|
@@ -4698,7 +4995,9 @@ async function readArchivedCredentials(file) {
|
|
|
4698
4995
|
}
|
|
4699
4996
|
return stored;
|
|
4700
4997
|
}
|
|
4701
|
-
|
|
4998
|
+
/** How old a leftover write temp must be before another writer removes it. */
|
|
4999
|
+
const ABANDONED_TEMP_MAX_AGE_MS = 6e5;
|
|
5000
|
+
async function removeAbandonedTemps(file, minAgeMs = ABANDONED_TEMP_MAX_AGE_MS) {
|
|
4702
5001
|
const prefix = `${basename(file)}.`;
|
|
4703
5002
|
let names;
|
|
4704
5003
|
try {
|
|
@@ -4710,7 +5009,35 @@ async function removeAbandonedArchiveTemps(file) {
|
|
|
4710
5009
|
if (!name.startsWith(prefix) || !name.endsWith(".tmp")) continue;
|
|
4711
5010
|
const id = name.slice(prefix.length, -4);
|
|
4712
5011
|
if (!/^[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}$/iu.test(id)) continue;
|
|
4713
|
-
|
|
5012
|
+
const candidate = join(dirname(file), name);
|
|
5013
|
+
if (minAgeMs > 0) {
|
|
5014
|
+
const info = await stat(candidate).catch(() => void 0);
|
|
5015
|
+
if (info === void 0 || Date.now() - info.mtimeMs < minAgeMs) continue;
|
|
5016
|
+
}
|
|
5017
|
+
await unlink(candidate).catch(() => {});
|
|
5018
|
+
}
|
|
5019
|
+
}
|
|
5020
|
+
/**
|
|
5021
|
+
* Remove sign-in temps a crashed write left in the plugin's own directory.
|
|
5022
|
+
*
|
|
5023
|
+
* A private file is written as `<name>.info.<uuid>.tmp` and renamed into place.
|
|
5024
|
+
* A process killed between the two leaves a full token in that temp, and no
|
|
5025
|
+
* later write of the same account necessarily happens. The age floor keeps a
|
|
5026
|
+
* scan from removing a write another process is still preparing.
|
|
5027
|
+
*/
|
|
5028
|
+
async function removeAbandonedSignInTemps(directory) {
|
|
5029
|
+
let names;
|
|
5030
|
+
try {
|
|
5031
|
+
names = await readdir(directory);
|
|
5032
|
+
} catch {
|
|
5033
|
+
return;
|
|
5034
|
+
}
|
|
5035
|
+
for (const name of names) {
|
|
5036
|
+
if (!/^workbuddy-panel-.*\.info\.[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}\.tmp$/iu.test(name)) continue;
|
|
5037
|
+
const file = join(directory, name);
|
|
5038
|
+
const info = await stat(file).catch(() => void 0);
|
|
5039
|
+
if (info === void 0 || Date.now() - info.mtimeMs < ABANDONED_TEMP_MAX_AGE_MS) continue;
|
|
5040
|
+
await unlink(file).catch(() => {});
|
|
4714
5041
|
}
|
|
4715
5042
|
}
|
|
4716
5043
|
/**
|
|
@@ -4722,8 +5049,12 @@ async function removeAbandonedArchiveTemps(file) {
|
|
|
4722
5049
|
*/
|
|
4723
5050
|
async function writeArchivedCredentials(file, entries, signal) {
|
|
4724
5051
|
signal?.throwIfAborted();
|
|
4725
|
-
await mkdir(dirname(file), {
|
|
5052
|
+
await mkdir(dirname(file), {
|
|
5053
|
+
recursive: true,
|
|
5054
|
+
mode: 448
|
|
5055
|
+
});
|
|
4726
5056
|
signal?.throwIfAborted();
|
|
5057
|
+
await removeAbandonedTemps(file);
|
|
4727
5058
|
const body = JSON.stringify({
|
|
4728
5059
|
version: 1,
|
|
4729
5060
|
entries: [...entries].map(([id, credential]) => ({
|
|
@@ -4777,6 +5108,15 @@ var WorkBuddyAccountPool = class {
|
|
|
4777
5108
|
cursor = 0;
|
|
4778
5109
|
/** Sticky mode: conversation key → account id. Content stays out of memory. */
|
|
4779
5110
|
sticky = /* @__PURE__ */ new Map();
|
|
5111
|
+
/**
|
|
5112
|
+
* Account id → the order in which it last served. A readout only: the composer
|
|
5113
|
+
* shows the account a sticky conversation is on, and that account is the one
|
|
5114
|
+
* that just answered. A counter rather than a clock, because two acquires can
|
|
5115
|
+
* land in the same millisecond. Not persisted; after a restart the cursor
|
|
5116
|
+
* stands in.
|
|
5117
|
+
*/
|
|
5118
|
+
servedOrder = /* @__PURE__ */ new Map();
|
|
5119
|
+
servedCount = 0;
|
|
4780
5120
|
lastScanAtMs = 0;
|
|
4781
5121
|
preferredIds = /* @__PURE__ */ new Map();
|
|
4782
5122
|
/**
|
|
@@ -4850,6 +5190,14 @@ var WorkBuddyAccountPool = class {
|
|
|
4850
5190
|
*/
|
|
4851
5191
|
heldIds = /* @__PURE__ */ new Map();
|
|
4852
5192
|
/**
|
|
5193
|
+
* Account id → when an upstream 5xx cooldown ends.
|
|
5194
|
+
*
|
|
5195
|
+
* A 5xx is not a frequency wall, and reporting it as one on the next request
|
|
5196
|
+
* sent the user looking for a limit that never existed. Kept beside the
|
|
5197
|
+
* cooldown so `ineligible` can name the cause while the account is out.
|
|
5198
|
+
*/
|
|
5199
|
+
serverCooldowns = /* @__PURE__ */ new Map();
|
|
5200
|
+
/**
|
|
4853
5201
|
* Accounts the desktop client is signed into right now.
|
|
4854
5202
|
*
|
|
4855
5203
|
* The pool renews one of these into its own directory when the app's session
|
|
@@ -4945,15 +5293,61 @@ var WorkBuddyAccountPool = class {
|
|
|
4945
5293
|
this.logger?.info?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} has credits again; releasing the hold`);
|
|
4946
5294
|
}
|
|
4947
5295
|
/** True when a known balance has reached the floor set for this account. */
|
|
4948
|
-
reserveHolds(
|
|
4949
|
-
const floor = this.creditReserves
|
|
5296
|
+
reserveHolds(account) {
|
|
5297
|
+
const floor = this.storedValue(this.creditReserves, account);
|
|
4950
5298
|
if (floor === void 0 || floor <= 0) return false;
|
|
4951
|
-
const balance = this.creditBalances.get(
|
|
5299
|
+
const balance = this.creditBalances.get(account.id);
|
|
4952
5300
|
return balance !== void 0 && balance <= floor;
|
|
4953
5301
|
}
|
|
4954
5302
|
/** Whether this account was switched off on the panel. */
|
|
4955
5303
|
isDisabled(accountId) {
|
|
4956
|
-
|
|
5304
|
+
const account = this.accounts.find((item) => item.id === accountId);
|
|
5305
|
+
return account === void 0 ? this.disabledIds.has(accountId) : this.storedIdMatches(this.disabledIds, account);
|
|
5306
|
+
}
|
|
5307
|
+
/** The credit floor in force for one account. */
|
|
5308
|
+
creditReserve(accountId) {
|
|
5309
|
+
const account = this.accounts.find((item) => item.id === accountId);
|
|
5310
|
+
return account === void 0 ? this.creditReserves.get(accountId) : this.storedValue(this.creditReserves, account);
|
|
5311
|
+
}
|
|
5312
|
+
/**
|
|
5313
|
+
* Every key this account may still be recorded under in persisted settings.
|
|
5314
|
+
*
|
|
5315
|
+
* The panel writes by current id, so a toggle has to clear the older keys
|
|
5316
|
+
* too; otherwise an old entry stays behind and takes effect again the moment
|
|
5317
|
+
* the current one is removed. An old key shared with another row is not a key
|
|
5318
|
+
* for this account: settings already ignore it, and purging its archive entry
|
|
5319
|
+
* on delete would take the other row's copy with it.
|
|
5320
|
+
*/
|
|
5321
|
+
storedIds(accountId) {
|
|
5322
|
+
const account = this.accounts.find((item) => item.id === accountId);
|
|
5323
|
+
if (account === void 0) return [accountId];
|
|
5324
|
+
return [accountId, ...previousAccountIds(account.credential).filter((id) => this.legacyKeyUnique(account, id))];
|
|
5325
|
+
}
|
|
5326
|
+
/** Whether a stored id set names this account under any of its keys. */
|
|
5327
|
+
storedIdMatches(stored, account) {
|
|
5328
|
+
if (stored.has(account.id)) return true;
|
|
5329
|
+
return previousAccountIds(account.credential).some((id) => stored.has(id) && this.legacyKeyUnique(account, id));
|
|
5330
|
+
}
|
|
5331
|
+
/** A value stored under any of this account's keys; current wins. */
|
|
5332
|
+
storedValue(stored, account) {
|
|
5333
|
+
const current = stored.get(account.id);
|
|
5334
|
+
if (current !== void 0) return current;
|
|
5335
|
+
for (const id of previousAccountIds(account.credential)) {
|
|
5336
|
+
if (!this.legacyKeyUnique(account, id)) continue;
|
|
5337
|
+
const value = stored.get(id);
|
|
5338
|
+
if (value !== void 0) return value;
|
|
5339
|
+
}
|
|
5340
|
+
}
|
|
5341
|
+
/**
|
|
5342
|
+
* Whether a 1.2.3 key names this row and no other one.
|
|
5343
|
+
*
|
|
5344
|
+
* That key hashed a nickname alone, so two identity-less sign-ins can share
|
|
5345
|
+
* it. Applying it to both would switch off or remove an account the user
|
|
5346
|
+
* never touched; an ambiguous key is therefore ignored rather than guessed.
|
|
5347
|
+
*/
|
|
5348
|
+
legacyKeyUnique(account, key) {
|
|
5349
|
+
const claimants = this.accounts.filter((item) => item.id === key || previousAccountIds(item.credential).includes(key));
|
|
5350
|
+
return claimants.length === 1 && claimants[0]?.id === account.id;
|
|
4957
5351
|
}
|
|
4958
5352
|
/**
|
|
4959
5353
|
* Replace the permanent removal list.
|
|
@@ -5003,24 +5397,36 @@ var WorkBuddyAccountPool = class {
|
|
|
5003
5397
|
const deletingCredential = account.credential;
|
|
5004
5398
|
const sameCredential = (credential) => credential.accessToken === deletingCredential.accessToken && credential.refreshToken === deletingCredential.refreshToken;
|
|
5005
5399
|
const running = this.scanInflight;
|
|
5006
|
-
const
|
|
5007
|
-
if (
|
|
5008
|
-
const
|
|
5009
|
-
|
|
5400
|
+
const recorded = await this.rememberDeletedSignIn(account.id, account.credential);
|
|
5401
|
+
if (recorded === void 0) throw new Error("could not record the deleted sign-in");
|
|
5402
|
+
const rollbackTombstone = async () => {
|
|
5403
|
+
const drop = async () => await this.updateDeletedSignIns((tombstones) => {
|
|
5404
|
+
const current = tombstones.get(account.id);
|
|
5405
|
+
if (current === void 0) return true;
|
|
5406
|
+
const kept = dropDeletedSignIns(current, [recorded.written]);
|
|
5407
|
+
if (kept === void 0) tombstones.delete(account.id);
|
|
5408
|
+
else if (kept !== current) tombstones.set(account.id, kept);
|
|
5409
|
+
return true;
|
|
5410
|
+
}) === true;
|
|
5411
|
+
return await drop() || await drop();
|
|
5412
|
+
};
|
|
5413
|
+
const fail = async () => {
|
|
5414
|
+
if (!await rollbackTombstone()) this.logger?.error?.(`${LOG_PREFIX}: could not remove the tombstone of a failed delete for ${accountLogTag(account.label)}; the account stays hidden until the deleted sign-ins can be written again`);
|
|
5415
|
+
};
|
|
5010
5416
|
const settled = running === void 0 ? true : await raceWithTimeout(running.catch(() => {}), DELETE_SCAN_WAIT_MS);
|
|
5011
5417
|
const current = this.accounts.find((item) => item.id === account.id);
|
|
5012
5418
|
let replaced = current !== void 0 && (!this.ownsSignIn(account.id) || resolve(current.credential.sourcePath) !== resolve(ownedPath) || !sameCredential(current.credential));
|
|
5013
5419
|
if (current === void 0) {
|
|
5014
5420
|
const tombstone = (await this.loadDeletedSignIns())?.get(account.id);
|
|
5015
|
-
replaced = tombstone === void 0 ||
|
|
5421
|
+
replaced = tombstone === void 0 || !tombstoneBlocks({
|
|
5422
|
+
record: tombstone,
|
|
5423
|
+
current: true
|
|
5424
|
+
}, deletingCredential);
|
|
5016
5425
|
}
|
|
5017
5426
|
const onDisk = await readCredential(ownedPath);
|
|
5018
5427
|
if (!replaced) replaced = onDisk.kind === "sealed" || onDisk.kind === "unreadable" || onDisk.kind === "credential" && (workbuddyAccountId(onDisk.credential) !== account.id || !sameCredential(onDisk.credential));
|
|
5019
5428
|
if (replaced) {
|
|
5020
|
-
|
|
5021
|
-
knownTombstones.delete(account.id);
|
|
5022
|
-
await this.writeDeletedSignIns([account.id]);
|
|
5023
|
-
}
|
|
5429
|
+
await fail();
|
|
5024
5430
|
return false;
|
|
5025
5431
|
}
|
|
5026
5432
|
try {
|
|
@@ -5030,11 +5436,9 @@ var WorkBuddyAccountPool = class {
|
|
|
5030
5436
|
await unlink(ownedPath);
|
|
5031
5437
|
});
|
|
5032
5438
|
} catch (error) {
|
|
5033
|
-
|
|
5034
|
-
|
|
5035
|
-
|
|
5036
|
-
await this.writeDeletedSignIns([account.id]);
|
|
5037
|
-
}
|
|
5439
|
+
const code = error.code;
|
|
5440
|
+
if (!(error instanceof FileLockReleaseError) && code !== "ENOENT") {
|
|
5441
|
+
await fail();
|
|
5038
5442
|
this.rosterRevision += 1;
|
|
5039
5443
|
await this.rescan().catch((rescanError) => {
|
|
5040
5444
|
this.logger?.warn?.(`${LOG_PREFIX}: could not restore the roster after a failed delete: ${String(rescanError)}`);
|
|
@@ -5042,9 +5446,11 @@ var WorkBuddyAccountPool = class {
|
|
|
5042
5446
|
throw error;
|
|
5043
5447
|
}
|
|
5044
5448
|
}
|
|
5449
|
+
await removeAbandonedTemps(ownedPath, 0);
|
|
5045
5450
|
this.rosterRevision += 1;
|
|
5046
|
-
|
|
5047
|
-
|
|
5451
|
+
const archivedIds = this.storedIds(account.id);
|
|
5452
|
+
if (!settled) running.catch(() => {}).then(() => this.forgetArchived(archivedIds));
|
|
5453
|
+
await this.forgetArchived(archivedIds);
|
|
5048
5454
|
const remaining = this.accounts.find((item) => item.id === account.id);
|
|
5049
5455
|
if (remaining === void 0 || this.isOwnSignInPath(remaining.credential.sourcePath) && resolve(remaining.credential.sourcePath) === resolve(ownedPath)) this.forgetAccount(account.id);
|
|
5050
5456
|
return true;
|
|
@@ -5058,27 +5464,27 @@ var WorkBuddyAccountPool = class {
|
|
|
5058
5464
|
this.heldIds.delete(accountId);
|
|
5059
5465
|
this.signInTokens.delete(accountId);
|
|
5060
5466
|
this.refusedSignIns.delete(accountId);
|
|
5467
|
+
this.serverCooldowns.delete(accountId);
|
|
5061
5468
|
}
|
|
5062
5469
|
/**
|
|
5063
5470
|
* Record one deleted sign-in, so no later scan puts the account back.
|
|
5064
5471
|
*
|
|
5065
5472
|
* The file is written before the delete is reported: a tombstone that only
|
|
5066
5473
|
* lived in memory would be gone after a restart, and the snapshot it has to
|
|
5067
|
-
* hold off is still sitting in the client's directory.
|
|
5474
|
+
* hold off is still sitting in the client's directory. Answers undefined when
|
|
5475
|
+
* the record could not be written, so the delete can refuse to report success.
|
|
5068
5476
|
*/
|
|
5069
5477
|
async rememberDeletedSignIn(id, credential) {
|
|
5070
|
-
const
|
|
5071
|
-
if (tombstones === void 0) return false;
|
|
5072
|
-
const previous = tombstones.get(id);
|
|
5073
|
-
tombstones.set(id, {
|
|
5478
|
+
const written = {
|
|
5074
5479
|
tokenDigest: tokenDigest(credential.accessToken),
|
|
5075
5480
|
lastRefreshAtMs: credential.lastRefreshAtMs ?? 0,
|
|
5076
|
-
deletedAtMs: Date.now()
|
|
5481
|
+
deletedAtMs: Date.now(),
|
|
5482
|
+
nonce: randomUUID()
|
|
5483
|
+
};
|
|
5484
|
+
return await this.updateDeletedSignIns((tombstones) => {
|
|
5485
|
+
tombstones.set(id, mergeDeletedSignIns(tombstones.get(id), written));
|
|
5486
|
+
return { written };
|
|
5077
5487
|
});
|
|
5078
|
-
if (await this.writeDeletedSignIns()) return true;
|
|
5079
|
-
if (previous === void 0) tombstones.delete(id);
|
|
5080
|
-
else tombstones.set(id, previous);
|
|
5081
|
-
return false;
|
|
5082
5488
|
}
|
|
5083
5489
|
/**
|
|
5084
5490
|
* Read the tombstones, re-reading when the file changed underneath us.
|
|
@@ -5113,26 +5519,28 @@ var WorkBuddyAccountPool = class {
|
|
|
5113
5519
|
return this.deletedSignIns;
|
|
5114
5520
|
}
|
|
5115
5521
|
this.logger?.warn?.(`${LOG_PREFIX}: could not read the deleted sign-ins: ${String(error)}`);
|
|
5116
|
-
return
|
|
5522
|
+
return;
|
|
5117
5523
|
}
|
|
5118
5524
|
}
|
|
5119
5525
|
/**
|
|
5120
|
-
*
|
|
5121
|
-
*
|
|
5122
|
-
* What is on disk is merged in first, except for the ids this call is removing:
|
|
5123
|
-
* a second pool over the same data directory writes this same file, and writing
|
|
5124
|
-
* our map verbatim dropped a delete it had already recorded. The removals are the
|
|
5125
|
-
* other half of that: a re-login ends a tombstone and a failed delete rolls one
|
|
5126
|
-
* back, and a pure union put both straight back.
|
|
5526
|
+
* Read-modify-write the tombstone document under its file lock.
|
|
5127
5527
|
*
|
|
5128
|
-
*
|
|
5129
|
-
*
|
|
5528
|
+
* The change starts from what is on disk, never from the in-memory copy: a
|
|
5529
|
+
* second pool may have released a record this process still holds, and writing
|
|
5530
|
+
* the cached map back put that release in force again. `mutate` gets the current
|
|
5531
|
+
* records and answers whatever the caller needs; undefined means the document
|
|
5532
|
+
* could not be read or written, and nothing was persisted.
|
|
5130
5533
|
*/
|
|
5131
|
-
async
|
|
5132
|
-
const tombstones = this.deletedSignIns;
|
|
5534
|
+
async updateDeletedSignIns(mutate, signal) {
|
|
5133
5535
|
const file = this.deletedSignInsFile();
|
|
5134
|
-
if (
|
|
5135
|
-
|
|
5536
|
+
if (file === void 0) {
|
|
5537
|
+
const tombstones = this.deletedSignIns ?? /* @__PURE__ */ new Map();
|
|
5538
|
+
const answer = mutate(tombstones);
|
|
5539
|
+
this.deletedSignIns = tombstones;
|
|
5540
|
+
this.deletedSignInsStamp = MISSING_FILE_STAMP;
|
|
5541
|
+
return answer;
|
|
5542
|
+
}
|
|
5543
|
+
let answer;
|
|
5136
5544
|
let written = false;
|
|
5137
5545
|
try {
|
|
5138
5546
|
await withFileLock(`${file}.lock`, async () => {
|
|
@@ -5142,31 +5550,36 @@ var WorkBuddyAccountPool = class {
|
|
|
5142
5550
|
onDisk = await readDeletedSignInsFile(file);
|
|
5143
5551
|
} catch (error) {
|
|
5144
5552
|
if (error.code !== "ENOENT") {
|
|
5145
|
-
if (!signal?.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not
|
|
5553
|
+
if (!signal?.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not read the deleted sign-ins to update them: ${String(error)}`);
|
|
5146
5554
|
return;
|
|
5147
5555
|
}
|
|
5148
5556
|
onDisk = /* @__PURE__ */ new Map();
|
|
5149
5557
|
}
|
|
5150
5558
|
if (signal?.aborted) return;
|
|
5151
|
-
|
|
5152
|
-
|
|
5153
|
-
const ours = tombstones.get(id);
|
|
5154
|
-
if (ours === void 0 || entry.deletedAtMs > ours.deletedAtMs) tombstones.set(id, entry);
|
|
5155
|
-
}
|
|
5559
|
+
const result = mutate(onDisk);
|
|
5560
|
+
if (signal?.aborted) return;
|
|
5156
5561
|
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
5157
5562
|
try {
|
|
5158
5563
|
signal?.throwIfAborted();
|
|
5159
|
-
await mkdir(dirname(file), {
|
|
5564
|
+
await mkdir(dirname(file), {
|
|
5565
|
+
recursive: true,
|
|
5566
|
+
mode: 448
|
|
5567
|
+
});
|
|
5160
5568
|
signal?.throwIfAborted();
|
|
5569
|
+
await removeAbandonedTemps(file);
|
|
5161
5570
|
await writeFile(temporary, JSON.stringify({
|
|
5162
5571
|
version: 1,
|
|
5163
|
-
entries: Object.fromEntries(
|
|
5572
|
+
entries: Object.fromEntries(onDisk)
|
|
5164
5573
|
}, null, 2), { mode: 384 });
|
|
5165
5574
|
signal?.throwIfAborted();
|
|
5166
5575
|
await replaceFile(temporary, file);
|
|
5167
5576
|
const stamp = await signInFileStamp(file);
|
|
5168
|
-
|
|
5577
|
+
answer = result;
|
|
5169
5578
|
written = true;
|
|
5579
|
+
if (!signal?.aborted) {
|
|
5580
|
+
this.deletedSignIns = onDisk;
|
|
5581
|
+
this.deletedSignInsStamp = stamp;
|
|
5582
|
+
}
|
|
5170
5583
|
} catch (error) {
|
|
5171
5584
|
await unlink(temporary).catch(() => {});
|
|
5172
5585
|
if (!signal?.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not record the deleted sign-ins: ${String(error)}`);
|
|
@@ -5175,7 +5588,7 @@ var WorkBuddyAccountPool = class {
|
|
|
5175
5588
|
} catch (error) {
|
|
5176
5589
|
if (!signal?.aborted) this.logger?.warn?.(written ? `${LOG_PREFIX}: the deleted sign-ins were saved but their lock was not released: ${String(error)}` : `${LOG_PREFIX}: could not lock the deleted sign-ins: ${String(error)}`);
|
|
5177
5590
|
}
|
|
5178
|
-
return
|
|
5591
|
+
return answer;
|
|
5179
5592
|
}
|
|
5180
5593
|
deletedSignInsFile() {
|
|
5181
5594
|
const directory = this.dataPath?.();
|
|
@@ -5225,6 +5638,8 @@ var WorkBuddyAccountPool = class {
|
|
|
5225
5638
|
async adoptOrphanedSignIns(found, tornDown, sealedLiveIds, unknownLiveDirs, signal) {
|
|
5226
5639
|
const directory = ownSignInDir(this.dataPath?.() ?? "");
|
|
5227
5640
|
if (directory === "") return [];
|
|
5641
|
+
const latest = await this.loadDeletedSignIns(signal);
|
|
5642
|
+
if (latest === void 0) return [];
|
|
5228
5643
|
const liveIds = new Set(sealedLiveIds);
|
|
5229
5644
|
const ownedIds = /* @__PURE__ */ new Set();
|
|
5230
5645
|
for (const credential of found) {
|
|
@@ -5239,7 +5654,9 @@ var WorkBuddyAccountPool = class {
|
|
|
5239
5654
|
if (ownSignInPath(credential.sourcePath, directory)) continue;
|
|
5240
5655
|
const id = workbuddyAccountId(credential);
|
|
5241
5656
|
if (unknownLiveDirs.has(this.homeOf(credential)) || liveIds.has(id) || ownedIds.has(id) || tornDown.has(id)) continue;
|
|
5242
|
-
|
|
5657
|
+
const entry = tombstoneOf(latest, credential, id);
|
|
5658
|
+
if (entry !== void 0 && tombstoneBlocks(entry, credential)) continue;
|
|
5659
|
+
if ((credential.uin ?? credential.uid ?? "") === "") continue;
|
|
5243
5660
|
let file;
|
|
5244
5661
|
try {
|
|
5245
5662
|
file = await writeOwnSignIn(directory, {
|
|
@@ -5251,11 +5668,18 @@ var WorkBuddyAccountPool = class {
|
|
|
5251
5668
|
this.logger?.warn?.(`${LOG_PREFIX}: could not take over ${accountLogTag(accountLabel(credential))}: ${String(error)}`);
|
|
5252
5669
|
continue;
|
|
5253
5670
|
}
|
|
5254
|
-
|
|
5255
|
-
adopted.push({
|
|
5671
|
+
const adoptedCredential = {
|
|
5256
5672
|
...credential,
|
|
5257
5673
|
sourcePath: file
|
|
5258
|
-
}
|
|
5674
|
+
};
|
|
5675
|
+
const after = await this.loadDeletedSignIns(signal);
|
|
5676
|
+
const afterEntry = after === void 0 ? void 0 : tombstoneOf(after, adoptedCredential, id);
|
|
5677
|
+
if (after === void 0 || afterEntry !== void 0 && tombstoneBlocks(afterEntry, adoptedCredential)) {
|
|
5678
|
+
await unlink(file).catch(() => {});
|
|
5679
|
+
continue;
|
|
5680
|
+
}
|
|
5681
|
+
ownedIds.add(id);
|
|
5682
|
+
adopted.push(adoptedCredential);
|
|
5259
5683
|
}
|
|
5260
5684
|
return adopted;
|
|
5261
5685
|
}
|
|
@@ -5267,10 +5691,9 @@ var WorkBuddyAccountPool = class {
|
|
|
5267
5691
|
* directory is left alone - the desktop app owns its files.
|
|
5268
5692
|
*/
|
|
5269
5693
|
async renewOwnSignIn(previous, credential) {
|
|
5270
|
-
const
|
|
5271
|
-
const guard = async () => await this.deleteDidNotTake(credential, sinceMs);
|
|
5694
|
+
const guard = async () => await this.deleteDidNotTake(credential);
|
|
5272
5695
|
if (this.isOwnSignInPath(previous.sourcePath)) return await renewOwnSignInFile(previous.sourcePath, credential, previous, false, guard);
|
|
5273
|
-
if ((credential.uin ?? credential.uid ??
|
|
5696
|
+
if ((credential.uin ?? credential.uid ?? "") === "") return true;
|
|
5274
5697
|
const directory = ownSignInDir(this.dataPath?.() ?? "");
|
|
5275
5698
|
if (directory === "") return true;
|
|
5276
5699
|
const file = ownSignInFile(directory, ownSignInOf(credential));
|
|
@@ -5280,33 +5703,43 @@ var WorkBuddyAccountPool = class {
|
|
|
5280
5703
|
return written;
|
|
5281
5704
|
}
|
|
5282
5705
|
/**
|
|
5283
|
-
* Whether a delete
|
|
5706
|
+
* Whether a delete still stands against this sign-in.
|
|
5284
5707
|
*
|
|
5285
5708
|
* A delete records a tombstone, unlinks the file, and reports success. A
|
|
5286
|
-
* renewal
|
|
5287
|
-
*
|
|
5288
|
-
*
|
|
5289
|
-
*
|
|
5709
|
+
* renewal over the same sign-in used to race that: its rename landed after
|
|
5710
|
+
* the unlink, the file came back with a token issued after the tombstone, and
|
|
5711
|
+
* `endsTombstone` read the recreation as a re-login and cleared the record -
|
|
5712
|
+
* a deleted account came back.
|
|
5290
5713
|
*
|
|
5291
|
-
* The
|
|
5292
|
-
*
|
|
5293
|
-
*
|
|
5294
|
-
*
|
|
5295
|
-
*
|
|
5296
|
-
*
|
|
5714
|
+
* The token's issue time cannot order the two acts. A rotation that started
|
|
5715
|
+
* after the delete, from an account still held in memory, also mints a token
|
|
5716
|
+
* newer than the record. What is known instead is which sign-in a record
|
|
5717
|
+
* names: a current-key record names this exact account, and only a scan
|
|
5718
|
+
* releases it for a sign-in the user made after the delete - before that
|
|
5719
|
+
* account can be refreshed again. So the presence of the record is enough.
|
|
5720
|
+
* A 1.2.3 record cannot tell two sign-ins apart and stays digest-matched.
|
|
5297
5721
|
*
|
|
5298
5722
|
* The set is read under the lock a delete writes it with, so a delete that
|
|
5299
5723
|
* committed a moment ago is visible. Nothing blocking runs under that lock.
|
|
5300
5724
|
*/
|
|
5301
|
-
async deleteDidNotTake(credential
|
|
5725
|
+
async deleteDidNotTake(credential) {
|
|
5302
5726
|
const file = this.deletedSignInsFile();
|
|
5303
5727
|
if (file === void 0) return true;
|
|
5304
5728
|
if (!await stat(file).then(() => true, (error) => error.code !== "ENOENT")) return true;
|
|
5305
5729
|
let alive = true;
|
|
5306
|
-
|
|
5307
|
-
|
|
5308
|
-
|
|
5309
|
-
|
|
5730
|
+
try {
|
|
5731
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
5732
|
+
const tombstones = await this.loadDeletedSignIns();
|
|
5733
|
+
if (tombstones === void 0) {
|
|
5734
|
+
alive = false;
|
|
5735
|
+
return;
|
|
5736
|
+
}
|
|
5737
|
+
const entry = tombstoneOf(tombstones, credential);
|
|
5738
|
+
if (entry !== void 0 && (entry.current || tombstoneBlocks(entry, credential))) alive = false;
|
|
5739
|
+
});
|
|
5740
|
+
} catch (error) {
|
|
5741
|
+
if (!(error instanceof FileLockReleaseError)) throw error;
|
|
5742
|
+
}
|
|
5310
5743
|
return alive;
|
|
5311
5744
|
}
|
|
5312
5745
|
/**
|
|
@@ -5316,13 +5749,15 @@ var WorkBuddyAccountPool = class {
|
|
|
5316
5749
|
* of one document, and a delete that raced a scan's write would otherwise be
|
|
5317
5750
|
* overwritten by it.
|
|
5318
5751
|
*/
|
|
5319
|
-
async forgetArchived(
|
|
5752
|
+
async forgetArchived(ids) {
|
|
5320
5753
|
const file = this.archiveFile();
|
|
5321
5754
|
if (file === void 0) return;
|
|
5322
5755
|
const run = this.archiveQueue.then(async () => {
|
|
5323
5756
|
await withFileLock(`${file}.lock`, async () => {
|
|
5324
5757
|
const stored = await readArchivedCredentials(file);
|
|
5325
|
-
|
|
5758
|
+
let dropped = false;
|
|
5759
|
+
for (const id of ids) dropped = stored.delete(id) || dropped;
|
|
5760
|
+
if (!dropped) return;
|
|
5326
5761
|
await writeArchivedCredentials(file, stored);
|
|
5327
5762
|
});
|
|
5328
5763
|
});
|
|
@@ -5344,6 +5779,8 @@ var WorkBuddyAccountPool = class {
|
|
|
5344
5779
|
this.unknownLiveSignIn = false;
|
|
5345
5780
|
this.unknownLiveFiles = /* @__PURE__ */ new Set();
|
|
5346
5781
|
this.refreshBlockedIds = /* @__PURE__ */ new Set();
|
|
5782
|
+
this.serverCooldowns.clear();
|
|
5783
|
+
this.refreshInflight.clear();
|
|
5347
5784
|
}
|
|
5348
5785
|
/** Read after any scan already running, so a manual request gets a fresh snapshot. */
|
|
5349
5786
|
async rescan() {
|
|
@@ -5391,27 +5828,40 @@ var WorkBuddyAccountPool = class {
|
|
|
5391
5828
|
const file = this.archiveFile();
|
|
5392
5829
|
if (file === void 0 || credentials.length === 0) return;
|
|
5393
5830
|
const ownDir = ownSignInDir(this.dataPath?.() ?? "");
|
|
5831
|
+
let committed = false;
|
|
5832
|
+
let wrote = false;
|
|
5394
5833
|
const run = this.archiveQueue.then(async () => {
|
|
5395
5834
|
await withFileLock(`${file}.lock`, async () => {
|
|
5396
5835
|
if (signal?.aborted) return;
|
|
5397
5836
|
const stored = await readArchivedCredentials(file);
|
|
5398
5837
|
if (signal?.aborted) return;
|
|
5838
|
+
const tombstones = await this.loadDeletedSignIns(signal);
|
|
5839
|
+
if (tombstones === void 0) return;
|
|
5399
5840
|
let changed = false;
|
|
5400
5841
|
for (const credential of credentials) {
|
|
5401
5842
|
const id = workbuddyAccountId(credential);
|
|
5843
|
+
const entry = tombstoneOf(tombstones, credential, id);
|
|
5844
|
+
if (entry !== void 0 && (entry.current || tombstoneBlocks(entry, credential))) continue;
|
|
5402
5845
|
const previous = stored.get(id);
|
|
5403
5846
|
if (previous !== void 0 && !isFresher(credential, previous, ownDir)) continue;
|
|
5404
5847
|
stored.set(id, credential);
|
|
5405
5848
|
changed = true;
|
|
5406
5849
|
}
|
|
5407
|
-
if (changed)
|
|
5850
|
+
if (changed) {
|
|
5851
|
+
await writeArchivedCredentials(file, stored, signal);
|
|
5852
|
+
wrote = true;
|
|
5853
|
+
}
|
|
5854
|
+
committed = true;
|
|
5408
5855
|
});
|
|
5409
5856
|
});
|
|
5410
5857
|
this.archiveQueue = run.catch(() => {});
|
|
5411
5858
|
try {
|
|
5412
5859
|
await run;
|
|
5413
5860
|
} catch (error) {
|
|
5414
|
-
if (!signal?.aborted)
|
|
5861
|
+
if (!signal?.aborted) {
|
|
5862
|
+
const message = !committed ? "could not update the credential archive" : wrote ? "the credential archive was saved but its lock was not released" : "the credential archive is current but its lock was not released";
|
|
5863
|
+
this.logger?.warn?.(`${LOG_PREFIX}: ${message}: ${String(error)}`);
|
|
5864
|
+
}
|
|
5415
5865
|
}
|
|
5416
5866
|
}
|
|
5417
5867
|
/** Credentials the archive kept for a directory this walk can read. */
|
|
@@ -5421,7 +5871,7 @@ var WorkBuddyAccountPool = class {
|
|
|
5421
5871
|
try {
|
|
5422
5872
|
let stored = /* @__PURE__ */ new Map();
|
|
5423
5873
|
await withFileLock(`${file}.lock`, async () => {
|
|
5424
|
-
await
|
|
5874
|
+
await removeAbandonedTemps(file);
|
|
5425
5875
|
stored = await readArchivedCredentials(file);
|
|
5426
5876
|
});
|
|
5427
5877
|
return [...stored.values()].filter((credential) => homes.has(this.homeOf(credential)));
|
|
@@ -5447,8 +5897,10 @@ var WorkBuddyAccountPool = class {
|
|
|
5447
5897
|
const sealedFileIds = /* @__PURE__ */ new Map();
|
|
5448
5898
|
const unreadableFiles = /* @__PURE__ */ new Set();
|
|
5449
5899
|
const unavailableDirs = /* @__PURE__ */ new Set();
|
|
5900
|
+
const ownDir = ownSignInDir(this.dataPath?.() ?? "");
|
|
5450
5901
|
for (const dir of dirs) {
|
|
5451
5902
|
if (signal.aborted) return this.accounts;
|
|
5903
|
+
if (ownDir !== "" && resolve(dir) === resolve(ownDir)) await removeAbandonedSignInTemps(dir);
|
|
5452
5904
|
const read = await authFilesIn(dir);
|
|
5453
5905
|
if (signal.aborted) return this.accounts;
|
|
5454
5906
|
if (read.files === void 0) {
|
|
@@ -5478,28 +5930,52 @@ var WorkBuddyAccountPool = class {
|
|
|
5478
5930
|
return this.accounts;
|
|
5479
5931
|
}
|
|
5480
5932
|
const tornDown = /* @__PURE__ */ new Set();
|
|
5481
|
-
const
|
|
5933
|
+
const released = /* @__PURE__ */ new Map();
|
|
5482
5934
|
const held = [];
|
|
5483
5935
|
for (const credential of found) {
|
|
5484
5936
|
const id = workbuddyAccountId(credential);
|
|
5485
|
-
const
|
|
5486
|
-
if (
|
|
5937
|
+
const entry = tombstoneOf(tombstones, credential, id);
|
|
5938
|
+
if (entry === void 0) {
|
|
5487
5939
|
held.push(credential);
|
|
5488
5940
|
continue;
|
|
5489
5941
|
}
|
|
5490
|
-
if (
|
|
5942
|
+
if (tombstoneBlocks(entry, credential)) {
|
|
5491
5943
|
tornDown.add(id);
|
|
5492
5944
|
continue;
|
|
5493
5945
|
}
|
|
5494
|
-
|
|
5495
|
-
releasedIds.push(id);
|
|
5946
|
+
if (entry.current) released.set(entry.key, entry.record);
|
|
5496
5947
|
held.push(credential);
|
|
5497
5948
|
}
|
|
5498
5949
|
found.length = 0;
|
|
5499
5950
|
found.push(...held);
|
|
5500
|
-
for (const id of tombstones.keys()) tornDown.add(id);
|
|
5501
|
-
if (
|
|
5951
|
+
for (const id of tombstones.keys()) if (!released.has(id)) tornDown.add(id);
|
|
5952
|
+
if (released.size > 0) await this.updateDeletedSignIns((entries) => {
|
|
5953
|
+
for (const [id, record] of released) {
|
|
5954
|
+
const current = entries.get(id);
|
|
5955
|
+
if (current === void 0) continue;
|
|
5956
|
+
const kept = dropDeletedSignIns(current, recordsOf(record));
|
|
5957
|
+
if (kept === void 0) entries.delete(id);
|
|
5958
|
+
else if (kept !== current) entries.set(id, kept);
|
|
5959
|
+
}
|
|
5960
|
+
}, signal);
|
|
5961
|
+
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
5962
|
+
const latest = await this.loadDeletedSignIns(signal);
|
|
5502
5963
|
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
5964
|
+
if (latest === void 0) {
|
|
5965
|
+
this.lastScanAtMs = Date.now();
|
|
5966
|
+
return this.accounts;
|
|
5967
|
+
}
|
|
5968
|
+
const walkedIds = new Set(found.map((credential) => workbuddyAccountId(credential)));
|
|
5969
|
+
for (const id of latest.keys()) if (!walkedIds.has(id)) tornDown.add(id);
|
|
5970
|
+
for (let index = found.length - 1; index >= 0; index -= 1) {
|
|
5971
|
+
const credential = found[index];
|
|
5972
|
+
const id = workbuddyAccountId(credential);
|
|
5973
|
+
const entry = tombstoneOf(latest, credential, id);
|
|
5974
|
+
if (entry !== void 0 && tombstoneBlocks(entry, credential)) {
|
|
5975
|
+
tornDown.add(id);
|
|
5976
|
+
found.splice(index, 1);
|
|
5977
|
+
}
|
|
5978
|
+
}
|
|
5503
5979
|
const sealedLiveIds = new Set(sealedFileIds.values());
|
|
5504
5980
|
for (let index = found.length - 1; index >= 0; index -= 1) {
|
|
5505
5981
|
const credential = found[index];
|
|
@@ -5537,6 +6013,8 @@ var WorkBuddyAccountPool = class {
|
|
|
5537
6013
|
for (const credential of archived) {
|
|
5538
6014
|
const id = workbuddyAccountId(credential);
|
|
5539
6015
|
if (tornDown.has(id)) continue;
|
|
6016
|
+
const entry = tombstoneOf(latest, credential, id);
|
|
6017
|
+
if (entry !== void 0 && tombstoneBlocks(entry, credential)) continue;
|
|
5540
6018
|
if (!this.isOwnSignInPath(credential.sourcePath) && (sealedLiveIds.has(id) || sealedDirs.has(this.homeOf(credential)))) continue;
|
|
5541
6019
|
if (found.some((entry) => workbuddyAccountId(entry) === id && entry.accessToken === credential.accessToken)) continue;
|
|
5542
6020
|
found.push(credential);
|
|
@@ -5545,6 +6023,9 @@ var WorkBuddyAccountPool = class {
|
|
|
5545
6023
|
const home = this.homeOf(credential);
|
|
5546
6024
|
if (sealedDirs.has(home) || unavailableDirs.has(home)) refreshBlockedIds.add(workbuddyAccountId(credential));
|
|
5547
6025
|
}
|
|
6026
|
+
const folded = foldSessionCopies(found, ownSignInDir(this.dataPath?.() ?? ""));
|
|
6027
|
+
found.length = 0;
|
|
6028
|
+
found.push(...folded);
|
|
5548
6029
|
const byId = /* @__PURE__ */ new Map();
|
|
5549
6030
|
for (const account of this.accounts) byId.set(account.id, account);
|
|
5550
6031
|
for (const credential of found) {
|
|
@@ -5555,7 +6036,7 @@ var WorkBuddyAccountPool = class {
|
|
|
5555
6036
|
id,
|
|
5556
6037
|
label: accountLabel(credential),
|
|
5557
6038
|
credential,
|
|
5558
|
-
cooldownUntilMs: 0,
|
|
6039
|
+
cooldownUntilMs: Math.max(0, this.heldIds.get(id)?.until ?? 0),
|
|
5559
6040
|
modelCooldowns: Object.create(null),
|
|
5560
6041
|
modelBlocks: Object.create(null),
|
|
5561
6042
|
rateLimitHits: 0
|
|
@@ -5616,14 +6097,43 @@ var WorkBuddyAccountPool = class {
|
|
|
5616
6097
|
}
|
|
5617
6098
|
disambiguateLabels(ordered);
|
|
5618
6099
|
if (!sameDirs(this.scanDirsFor(this.authDirs), dirs) || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
6100
|
+
const tombstoneFile = this.deletedSignInsFile();
|
|
6101
|
+
const commit = () => {
|
|
6102
|
+
this.accounts = ordered;
|
|
6103
|
+
this.signInTokens = signInTokens;
|
|
6104
|
+
this.lastScanAtMs = Date.now();
|
|
6105
|
+
};
|
|
6106
|
+
if (tombstoneFile === void 0) {
|
|
6107
|
+
commit();
|
|
6108
|
+
return this.accounts;
|
|
6109
|
+
}
|
|
6110
|
+
let committed = false;
|
|
6111
|
+
try {
|
|
6112
|
+
await withFileLock(`${tombstoneFile}.lock`, async () => {
|
|
6113
|
+
const finalTombstones = await this.loadDeletedSignIns(signal);
|
|
6114
|
+
if (signal.aborted || !sameDirs(this.scanDirsFor(this.authDirs), dirs) || rosterRevision !== this.rosterRevision) return;
|
|
6115
|
+
if (finalTombstones === void 0) return;
|
|
6116
|
+
if (await signInFileStamp(tombstoneFile) !== this.deletedSignInsStamp) return;
|
|
6117
|
+
for (let index = ordered.length - 1; index >= 0; index -= 1) {
|
|
6118
|
+
const account = ordered[index];
|
|
6119
|
+
const entry = tombstoneOf(finalTombstones, account.credential, account.id);
|
|
6120
|
+
if (entry !== void 0 && tombstoneBlocks(entry, account.credential)) {
|
|
6121
|
+
ordered.splice(index, 1);
|
|
6122
|
+
this.forgetAccount(account.id);
|
|
6123
|
+
}
|
|
6124
|
+
}
|
|
6125
|
+
commit();
|
|
6126
|
+
committed = true;
|
|
6127
|
+
});
|
|
6128
|
+
} catch (error) {
|
|
6129
|
+
if (!signal.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not lock the deleted sign-ins for the final roster check: ${String(error)}`);
|
|
6130
|
+
}
|
|
6131
|
+
if (!committed && !signal.aborted) this.lastScanAtMs = Date.now();
|
|
5622
6132
|
return this.accounts;
|
|
5623
6133
|
}
|
|
5624
6134
|
/** All accounts, cooldown state included. */
|
|
5625
6135
|
list(region) {
|
|
5626
|
-
const kept = this.accounts.filter((account) => !this.removedIds
|
|
6136
|
+
const kept = this.accounts.filter((account) => !this.storedIdMatches(this.removedIds, account));
|
|
5627
6137
|
if (region === void 0) return kept;
|
|
5628
6138
|
return kept.filter((account) => regionOf(account.credential.domain) === region);
|
|
5629
6139
|
}
|
|
@@ -5636,11 +6146,12 @@ var WorkBuddyAccountPool = class {
|
|
|
5636
6146
|
* panel call an account available that the rotation would never pick.
|
|
5637
6147
|
*/
|
|
5638
6148
|
ineligible(account, now, modelId, region) {
|
|
5639
|
-
if (this.removedIds
|
|
5640
|
-
if (this.disabledIds
|
|
5641
|
-
if (this.reserveHolds(account
|
|
6149
|
+
if (this.storedIdMatches(this.removedIds, account)) return "removed";
|
|
6150
|
+
if (this.storedIdMatches(this.disabledIds, account)) return "switched off";
|
|
6151
|
+
if (this.reserveHolds(account)) return "under its credit reserve";
|
|
5642
6152
|
if (credentialUnusable(account.credential, now)) return "sign-in expired";
|
|
5643
6153
|
if (region !== void 0 && regionOf(account.credential.domain) !== region) return "other region";
|
|
6154
|
+
if ((this.serverCooldowns.get(account.id) ?? 0) > now) return "server";
|
|
5644
6155
|
if (account.cooldownUntilMs > now) {
|
|
5645
6156
|
const reason = this.heldIds.get(account.id)?.reason;
|
|
5646
6157
|
return reason === "session" ? "sign-in refused" : reason === "restricted" ? "restricted by the upstream" : "on hold";
|
|
@@ -5729,7 +6240,7 @@ var WorkBuddyAccountPool = class {
|
|
|
5729
6240
|
pool = eligibleNow();
|
|
5730
6241
|
}
|
|
5731
6242
|
if (pool.length === 0) return void 0;
|
|
5732
|
-
const preferredId = this.
|
|
6243
|
+
const preferredId = this.preferredIdFor(region);
|
|
5733
6244
|
const remaining = new Set(pool.map((account) => account.id));
|
|
5734
6245
|
while (remaining.size > 0) {
|
|
5735
6246
|
const account = pool.find((item) => item.id === preferredId) ?? this.pick(pool, conversationKey);
|
|
@@ -5738,7 +6249,10 @@ var WorkBuddyAccountPool = class {
|
|
|
5738
6249
|
await this.ensureFresh(account);
|
|
5739
6250
|
if (signal.aborted) return void 0;
|
|
5740
6251
|
const eligible = eligibleNow();
|
|
5741
|
-
if (eligible.includes(account))
|
|
6252
|
+
if (eligible.includes(account)) {
|
|
6253
|
+
this.servedOrder.set(account.id, ++this.servedCount);
|
|
6254
|
+
return account;
|
|
6255
|
+
}
|
|
5742
6256
|
pool = eligible.filter((item) => remaining.has(item.id));
|
|
5743
6257
|
}
|
|
5744
6258
|
}
|
|
@@ -5767,11 +6281,39 @@ var WorkBuddyAccountPool = class {
|
|
|
5767
6281
|
pickByExpiry(pool) {
|
|
5768
6282
|
return pickSoonestExpiry(pool, this.creditExpiries, Date.now());
|
|
5769
6283
|
}
|
|
5770
|
-
/**
|
|
6284
|
+
/**
|
|
6285
|
+
* Next account the panel may name as "next up". Does not move the cursor.
|
|
6286
|
+
*
|
|
6287
|
+
* Sticky has no single next account - it is per conversation - so it names
|
|
6288
|
+
* nothing rather than pointing at a guess. The composer readout uses
|
|
6289
|
+
* `readoutPreview`, which can name the account that served last instead.
|
|
6290
|
+
*/
|
|
5771
6291
|
preview(eligible) {
|
|
5772
6292
|
if (eligible.length === 0) return void 0;
|
|
5773
6293
|
if (this.distribution === "expiry") return this.pickByExpiry(eligible);
|
|
5774
6294
|
if (this.distribution === "priority") return eligible[0];
|
|
6295
|
+
if (this.distribution === "round-robin") return eligible[this.cursor % eligible.length];
|
|
6296
|
+
}
|
|
6297
|
+
/**
|
|
6298
|
+
* The account the composer readout names. Does not move the cursor.
|
|
6299
|
+
*
|
|
6300
|
+
* Round-robin names the account the next request takes. Sticky names the one
|
|
6301
|
+
* that served most recently, because the current conversation is most likely
|
|
6302
|
+
* on it; before the first turn the cursor stands in.
|
|
6303
|
+
*/
|
|
6304
|
+
readoutPreview(eligible) {
|
|
6305
|
+
if (eligible.length === 0) return void 0;
|
|
6306
|
+
if (this.distribution !== "sticky") return this.preview(eligible);
|
|
6307
|
+
let latest;
|
|
6308
|
+
let latestAt = -1;
|
|
6309
|
+
for (const account of eligible) {
|
|
6310
|
+
const servedAt = this.servedOrder.get(account.id) ?? -1;
|
|
6311
|
+
if (servedAt > latestAt) {
|
|
6312
|
+
latest = account;
|
|
6313
|
+
latestAt = servedAt;
|
|
6314
|
+
}
|
|
6315
|
+
}
|
|
6316
|
+
return latest ?? eligible[this.cursor % eligible.length];
|
|
5775
6317
|
}
|
|
5776
6318
|
/** Prefer one billing account per gateway; undefined restores automatic use. */
|
|
5777
6319
|
prefer(accountId, region) {
|
|
@@ -5779,6 +6321,32 @@ var WorkBuddyAccountPool = class {
|
|
|
5779
6321
|
else this.preferredIds.set(region, accountId);
|
|
5780
6322
|
}
|
|
5781
6323
|
/**
|
|
6324
|
+
* The stored preference for one region, translated from an older key.
|
|
6325
|
+
*
|
|
6326
|
+
* A preference saved before an identity change names a row that no rescan
|
|
6327
|
+
* produces any more. Leaving it untranslated meant the panel kept a selection
|
|
6328
|
+
* that could never be handed out, so automatic distribution silently served
|
|
6329
|
+
* another account while the panel named the old one.
|
|
6330
|
+
*/
|
|
6331
|
+
preferredIdFor(region) {
|
|
6332
|
+
const stored = this.preferredIds.get(region);
|
|
6333
|
+
if (stored === void 0) return void 0;
|
|
6334
|
+
if (this.accounts.some((account) => account.id === stored)) return stored;
|
|
6335
|
+
const claimants = this.accounts.filter((item) => (region === void 0 || regionOf(item.credential.domain) === region) && previousAccountIds(item.credential).includes(stored));
|
|
6336
|
+
return claimants.length === 1 && claimants[0] !== void 0 ? claimants[0].id : stored;
|
|
6337
|
+
}
|
|
6338
|
+
/**
|
|
6339
|
+
* The current id a stored preference resolves to.
|
|
6340
|
+
*
|
|
6341
|
+
* The panel and the composer show this rather than the raw settings value:
|
|
6342
|
+
* after an upgrade that value can still be a 1.2.3 key, and showing it made
|
|
6343
|
+
* the row read as "unavailable" while `acquire` had already translated it and
|
|
6344
|
+
* served another account.
|
|
6345
|
+
*/
|
|
6346
|
+
resolvedPreferredId(region) {
|
|
6347
|
+
return this.preferredIdFor(region);
|
|
6348
|
+
}
|
|
6349
|
+
/**
|
|
5782
6350
|
* Refresh one account after a session-dead upstream answer, ignoring the
|
|
5783
6351
|
* stored expiry: a revocation does not rewrite it. False when the access
|
|
5784
6352
|
* token is unchanged, so the caller stops retrying the same dead token.
|
|
@@ -5865,15 +6433,59 @@ var WorkBuddyAccountPool = class {
|
|
|
5865
6433
|
}
|
|
5866
6434
|
}
|
|
5867
6435
|
/**
|
|
6436
|
+
* Whether a refresh's rotated token still belongs to a sign-in on disk.
|
|
6437
|
+
*
|
|
6438
|
+
* The pool running the refresh need not be the one that deleted the sign-in,
|
|
6439
|
+
* so its roster cannot answer this. The file can: it holds the token the
|
|
6440
|
+
* refresh started from, the one it just minted, or something else (a re-login,
|
|
6441
|
+
* or nothing after the delete). Only the first two are still this pool's to
|
|
6442
|
+
* archive; anything else belongs to a session the user replaced or removed.
|
|
6443
|
+
*/
|
|
6444
|
+
async refreshedSignInIsOnDisk(previous, refreshed) {
|
|
6445
|
+
const read = await readCredential(refreshed.sourcePath);
|
|
6446
|
+
if (read.kind !== "credential") return false;
|
|
6447
|
+
return read.credential.accessToken === previous.accessToken || read.credential.accessToken === refreshed.accessToken || read.credential.refreshToken !== "" && read.credential.refreshToken === refreshed.refreshToken;
|
|
6448
|
+
}
|
|
6449
|
+
/**
|
|
6450
|
+
* Archive a rotated token only while its sign-in is still on disk.
|
|
6451
|
+
*
|
|
6452
|
+
* Checked under the tombstone lock so a delete cannot commit between the
|
|
6453
|
+
* check and the archive write: before the lock, its record blocks the write;
|
|
6454
|
+
* after it, the re-login has already replaced the file the check sees.
|
|
6455
|
+
* Answers whether the rotated token still belongs to a live sign-in; false
|
|
6456
|
+
* means the caller must not keep serving it.
|
|
6457
|
+
*/
|
|
6458
|
+
async archiveRefreshedCredential(previous, refreshed) {
|
|
6459
|
+
let kept = false;
|
|
6460
|
+
const archive = async () => {
|
|
6461
|
+
if (await this.refreshedSignInIsOnDisk(previous, refreshed)) {
|
|
6462
|
+
await this.archiveCredentials([refreshed]);
|
|
6463
|
+
kept = true;
|
|
6464
|
+
}
|
|
6465
|
+
};
|
|
6466
|
+
const file = this.deletedSignInsFile();
|
|
6467
|
+
if (file === void 0) {
|
|
6468
|
+
await archive();
|
|
6469
|
+
return kept;
|
|
6470
|
+
}
|
|
6471
|
+
try {
|
|
6472
|
+
await withFileLock(`${file}.lock`, archive);
|
|
6473
|
+
} catch (error) {
|
|
6474
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not lock the deleted sign-ins to archive a renewed token: ${String(error)}`);
|
|
6475
|
+
return false;
|
|
6476
|
+
}
|
|
6477
|
+
return kept;
|
|
6478
|
+
}
|
|
6479
|
+
/**
|
|
5868
6480
|
* Refresh the account's access token when it is within the margin (or already
|
|
5869
6481
|
* expired), in-flight de-duped per account. A failed refresh keeps the
|
|
5870
6482
|
* existing token when it has not yet expired, so an unreachable refresh
|
|
5871
6483
|
* endpoint never takes down a working session.
|
|
5872
6484
|
*
|
|
5873
6485
|
* Reports what it did, so a caller walking the pool for keep-alive can tell a
|
|
5874
|
-
* pass that refreshed something from one that had nothing to do.
|
|
5875
|
-
*
|
|
5876
|
-
*
|
|
6486
|
+
* pass that refreshed something from one that had nothing to do. An in-flight
|
|
6487
|
+
* refresh another call started is awaited and its result is shared: this call
|
|
6488
|
+
* spent no upstream call of its own, but the account's outcome is the same.
|
|
5877
6489
|
*/
|
|
5878
6490
|
async ensureFresh(account, forced = false) {
|
|
5879
6491
|
if (this.client === void 0) return "fresh";
|
|
@@ -5895,7 +6507,7 @@ var WorkBuddyAccountPool = class {
|
|
|
5895
6507
|
}
|
|
5896
6508
|
try {
|
|
5897
6509
|
const outcome = await this.client.refreshToken(credential);
|
|
5898
|
-
if (account.credential !== credential) return "
|
|
6510
|
+
if (account.credential !== credential || !this.accounts.includes(account)) return "failed";
|
|
5899
6511
|
account.credential = {
|
|
5900
6512
|
...credential,
|
|
5901
6513
|
accessToken: outcome.accessToken,
|
|
@@ -5908,10 +6520,11 @@ var WorkBuddyAccountPool = class {
|
|
|
5908
6520
|
try {
|
|
5909
6521
|
written = await this.renewOwnSignIn(credential, account.credential);
|
|
5910
6522
|
} catch (error) {
|
|
5911
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not persist the renewed token for ${accountLogTag(account.label)}
|
|
5912
|
-
await this.
|
|
5913
|
-
|
|
5914
|
-
|
|
6523
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not persist the renewed token for ${accountLogTag(account.label)}`, error);
|
|
6524
|
+
if (!await this.archiveRefreshedCredential(credential, account.credential)) {
|
|
6525
|
+
account.credential = credential;
|
|
6526
|
+
this.forgetAccount(account.id);
|
|
6527
|
+
}
|
|
5915
6528
|
throw error;
|
|
5916
6529
|
}
|
|
5917
6530
|
if (!written) {
|
|
@@ -5919,7 +6532,11 @@ var WorkBuddyAccountPool = class {
|
|
|
5919
6532
|
await this.scan();
|
|
5920
6533
|
return "fresh";
|
|
5921
6534
|
}
|
|
5922
|
-
await this.
|
|
6535
|
+
if (!await this.archiveRefreshedCredential(credential, account.credential)) {
|
|
6536
|
+
account.credential = credential;
|
|
6537
|
+
this.forgetAccount(account.id);
|
|
6538
|
+
return "failed";
|
|
6539
|
+
}
|
|
5923
6540
|
this.noRefreshWarned.delete(account.id);
|
|
5924
6541
|
const sessionHold = this.heldIds.get(account.id);
|
|
5925
6542
|
if (sessionHold !== void 0 && sessionHold.reason === "session") {
|
|
@@ -5939,7 +6556,7 @@ var WorkBuddyAccountPool = class {
|
|
|
5939
6556
|
try {
|
|
5940
6557
|
return await run;
|
|
5941
6558
|
} finally {
|
|
5942
|
-
this.refreshInflight.delete(account.id);
|
|
6559
|
+
if (this.refreshInflight.get(account.id) === run) this.refreshInflight.delete(account.id);
|
|
5943
6560
|
}
|
|
5944
6561
|
}
|
|
5945
6562
|
/**
|
|
@@ -5956,20 +6573,21 @@ var WorkBuddyAccountPool = class {
|
|
|
5956
6573
|
* exists to stop a mis-parsed reset from parking an account all day, and
|
|
5957
6574
|
* neither of these conditions clears by itself.
|
|
5958
6575
|
*/
|
|
5959
|
-
penalize(accountId, resetAtMs, modelId, hold = false) {
|
|
6576
|
+
penalize(accountId, resetAtMs, modelId, hold = false, failure = "limit") {
|
|
5960
6577
|
const account = this.accounts.find((item) => item.id === accountId);
|
|
5961
6578
|
if (account === void 0) return;
|
|
5962
|
-
|
|
6579
|
+
const countsAsLimit = hold === false && failure === "limit";
|
|
6580
|
+
if (countsAsLimit) account.rateLimitHits += 1;
|
|
5963
6581
|
const now = Date.now();
|
|
5964
6582
|
const stated = resetAtMs !== void 0 && resetAtMs > now;
|
|
5965
|
-
if (
|
|
6583
|
+
if (countsAsLimit && !stated) {
|
|
5966
6584
|
account.rateLimitStreak = now - (account.rateLimitStreakAtMs ?? 0) > RATE_LIMIT_STREAK_WINDOW_MS ? 1 : (account.rateLimitStreak ?? 0) + 1;
|
|
5967
6585
|
account.rateLimitStreakAtMs = now;
|
|
5968
6586
|
}
|
|
5969
6587
|
const holdReason = hold === false ? void 0 : hold;
|
|
5970
6588
|
const cap = holdReason !== void 0 ? POOL_HOLD_MS : PENALIZE_CAP_MS;
|
|
5971
6589
|
const streak = Math.min(Math.max((account.rateLimitStreak ?? 1) - 1, 0), RATE_LIMIT_STREAK_STEPS);
|
|
5972
|
-
const backoff = Math.min(this.cooldownMs * 2 ** streak, Math.max(this.cooldownMs, RATE_LIMIT_STREAK_CAP));
|
|
6590
|
+
const backoff = countsAsLimit ? Math.min(this.cooldownMs * 2 ** streak, Math.max(this.cooldownMs, RATE_LIMIT_STREAK_CAP)) : this.cooldownMs;
|
|
5973
6591
|
const until = stated ? Math.min(resetAtMs, now + cap) : holdReason !== void 0 ? now + cap : now + backoff;
|
|
5974
6592
|
if (modelId !== void 0 && modelId !== "") {
|
|
5975
6593
|
pruneModelCooldowns(account, now);
|
|
@@ -5978,6 +6596,8 @@ var WorkBuddyAccountPool = class {
|
|
|
5978
6596
|
return;
|
|
5979
6597
|
}
|
|
5980
6598
|
account.cooldownUntilMs = Math.max(account.cooldownUntilMs, until);
|
|
6599
|
+
if (failure === "server" && hold === false) this.serverCooldowns.set(account.id, until);
|
|
6600
|
+
else this.serverCooldowns.delete(account.id);
|
|
5981
6601
|
if (holdReason !== void 0) {
|
|
5982
6602
|
const prior = this.heldIds.get(accountId);
|
|
5983
6603
|
const carried = prior !== void 0 && prior.until > now && prior.reason === "session" ? prior : void 0;
|
|
@@ -6019,6 +6639,7 @@ var WorkBuddyAccountPool = class {
|
|
|
6019
6639
|
}
|
|
6020
6640
|
this.heldIds.clear();
|
|
6021
6641
|
this.refusedSignIns.clear();
|
|
6642
|
+
this.serverCooldowns.clear();
|
|
6022
6643
|
}
|
|
6023
6644
|
/** Diagnostics snapshot. Account-wide cooling count (per-model cooling excluded:
|
|
6024
6645
|
* the account as a whole stays usable when only one model is limited). */
|
|
@@ -6716,6 +7337,11 @@ function unavailableAnswer(pool, live, now, modelId) {
|
|
|
6716
7337
|
code: "model_tier",
|
|
6717
7338
|
detail: `no WorkBuddy account has model ${modelId} in its plan; pick another model, or add an account whose plan includes it`
|
|
6718
7339
|
};
|
|
7340
|
+
if (only === "server") return {
|
|
7341
|
+
status: 503,
|
|
7342
|
+
code: "server",
|
|
7343
|
+
detail: `every WorkBuddy account is cooling after upstream server errors for model ${modelId}; retry shortly`
|
|
7344
|
+
};
|
|
6719
7345
|
if (only === "restricted by the upstream") return {
|
|
6720
7346
|
status: 403,
|
|
6721
7347
|
code: "account_restricted",
|
|
@@ -6822,8 +7448,8 @@ function createWorkBuddyShim(options) {
|
|
|
6822
7448
|
if (account === void 0) {
|
|
6823
7449
|
if (accountSkipped && last !== void 0) {
|
|
6824
7450
|
const model = ` for model ${modelId}`;
|
|
6825
|
-
const subject = last.kind === "waf_block" ? "every WorkBuddy account was blocked by the upstream gateway (WAF)" : last.kind === "hard_credit" ? `every WorkBuddy account is out of credits${model}` : last.kind === "session_dead" ? `every WorkBuddy sign-in is no longer accepted${model}` : last.kind === "model_tier" ? `no WorkBuddy account can use model ${modelId}` : last.kind === "account_restricted" ? "every WorkBuddy account was restricted by the upstream" : last.kind === "transport" ? emptyStreams > 0 && transportAttempts === 0 ? `every WorkBuddy account answered${model} with an empty stream` : `the upstream host could not be reached on any account${model}` : `every account is rate-limited${model}`;
|
|
6826
|
-
const advice = last.kind === "soft_rate" ? "resets at the upstream window" : last.kind === "model_tier" ? "pick another model, or add an account whose plan includes it" : last.kind === "account_restricted" ? "appeal the restriction in the WorkBuddy console, or add another account" : last.kind === "waf_block" ? "wait for the upstream gateway block to clear, or change network" : last.kind === "transport" ? emptyStreams > 0 && transportAttempts === 0 ? "the upstream answered and then produced no content; retry the request" : "check the connection to the upstream host" : last.kind === "hard_credit" ? "top up the account, or add another account" : "sign in again in the desktop app";
|
|
7451
|
+
const subject = last.kind === "waf_block" ? "every WorkBuddy account was blocked by the upstream gateway (WAF)" : last.kind === "hard_credit" ? `every WorkBuddy account is out of credits${model}` : last.kind === "session_dead" ? `every WorkBuddy sign-in is no longer accepted${model}` : last.kind === "model_tier" ? `no WorkBuddy account can use model ${modelId}` : last.kind === "account_restricted" ? "every WorkBuddy account was restricted by the upstream" : last.kind === "transport" ? emptyStreams > 0 && transportAttempts === 0 ? `every WorkBuddy account answered${model} with an empty stream` : `the upstream host could not be reached on any account${model}` : last.kind === "server" ? `every WorkBuddy account answered${model} with an upstream server error` : `every account is rate-limited${model}`;
|
|
7452
|
+
const advice = last.kind === "soft_rate" ? "resets at the upstream window" : last.kind === "model_tier" ? "pick another model, or add an account whose plan includes it" : last.kind === "account_restricted" ? "appeal the restriction in the WorkBuddy console, or add another account" : last.kind === "waf_block" ? "wait for the upstream gateway block to clear, or change network" : last.kind === "transport" ? emptyStreams > 0 && transportAttempts === 0 ? "the upstream answered and then produced no content; retry the request" : "check the connection to the upstream host" : last.kind === "server" ? "retry shortly; the upstream service is down" : last.kind === "hard_credit" ? "top up the account, or add another account" : "sign in again in the desktop app";
|
|
6827
7453
|
if (last.kind === "soft_rate") {
|
|
6828
7454
|
const live = pool.list(region).filter((candidate) => !pool.isDisabled(candidate.id));
|
|
6829
7455
|
const wait = unavailableAnswer(pool, live, Date.now(), modelId).retryAfterSeconds;
|
|
@@ -7109,7 +7735,10 @@ function createWorkBuddyShim(options) {
|
|
|
7109
7735
|
* 402 back at the head of the queue every minute. A WAF page is the
|
|
7110
7736
|
* gateway's own and clears on its own within minutes, so it takes the
|
|
7111
7737
|
* configured window rather than a hold that would park a healthy account
|
|
7112
|
-
* for hours over a transient block.
|
|
7738
|
+
* for hours over a transient block. A 5xx is the upstream's own fault, but
|
|
7739
|
+
* it is still served per account: one broken deployment must not lead
|
|
7740
|
+
* every turn, so it takes the configured window and the next account gets
|
|
7741
|
+
* the request.
|
|
7113
7742
|
*
|
|
7114
7743
|
* A `transport` failure is the network path's. A global pool need not
|
|
7115
7744
|
* share a host: `codebuddy.ai` and `workbuddy.ai` logins can be served by
|
|
@@ -7133,7 +7762,7 @@ function createWorkBuddyShim(options) {
|
|
|
7133
7762
|
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} transport failure; rotating`);
|
|
7134
7763
|
continue;
|
|
7135
7764
|
}
|
|
7136
|
-
if (result.kind !== "soft_rate" && result.kind !== "waf_block" && result.kind !== "hard_credit" && result.kind !== "session_dead" && result.kind !== "model_tier" && result.kind !== "account_restricted") break;
|
|
7765
|
+
if (result.kind !== "soft_rate" && result.kind !== "waf_block" && result.kind !== "hard_credit" && result.kind !== "session_dead" && result.kind !== "model_tier" && result.kind !== "account_restricted" && result.kind !== "server") break;
|
|
7137
7766
|
accountSkipped = true;
|
|
7138
7767
|
if (result.kind === "soft_rate") {
|
|
7139
7768
|
const bodyReset = parseRateLimitReset(result.message);
|
|
@@ -7143,7 +7772,7 @@ function createWorkBuddyShim(options) {
|
|
|
7143
7772
|
} else if (result.kind === "model_tier") pool.blockModel(account.id, modelId, Date.now() + MODEL_TIER_HOLD_MS);
|
|
7144
7773
|
else if (result.kind === "account_restricted") pool.penalize(account.id, holdUntil(), void 0, "restricted");
|
|
7145
7774
|
else if (result.kind === "hard_credit" || result.kind === "session_dead") pool.penalize(account.id, holdUntil(), void 0, result.kind === "hard_credit" ? "spent" : "session");
|
|
7146
|
-
else pool.penalize(account.id);
|
|
7775
|
+
else pool.penalize(account.id, void 0, void 0, false, result.kind === "server" || result.kind === "waf_block" ? "server" : "limit");
|
|
7147
7776
|
logger?.warn(`${LOG_PREFIX}: ${accountLogTag(account.label)} ${result.kind} on ${modelId} (attempt ${attempt + 1}/${maxAttempts}); rotating`);
|
|
7148
7777
|
}
|
|
7149
7778
|
if (last === void 0) {
|
|
@@ -10083,6 +10712,10 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
|
|
|
10083
10712
|
inheritTemp: true,
|
|
10084
10713
|
includeSystemDrive: true
|
|
10085
10714
|
}),
|
|
10715
|
+
cwd: (() => {
|
|
10716
|
+
const root = trustedSystemRootOf(env);
|
|
10717
|
+
return root === void 0 ? void 0 : join(root, "System32");
|
|
10718
|
+
})(),
|
|
10086
10719
|
windowsHide: true,
|
|
10087
10720
|
stdio: [
|
|
10088
10721
|
"pipe",
|
|
@@ -10112,6 +10745,7 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
|
|
|
10112
10745
|
if (code === 0) resolve(out);
|
|
10113
10746
|
else reject(new QoderKeyError("unavailable", `PowerShell exited ${code}: ${err.trim().slice(0, 160)}`));
|
|
10114
10747
|
});
|
|
10748
|
+
child.stdin.on("error", () => {});
|
|
10115
10749
|
child.stdin.end(payload.toString("base64"));
|
|
10116
10750
|
});
|
|
10117
10751
|
const key = Buffer.from(stdout.trim(), "base64");
|
|
@@ -12537,6 +13171,12 @@ function originFor(realm) {
|
|
|
12537
13171
|
* upstream answer that named `javascript:` or `file:` would otherwise be handed
|
|
12538
13172
|
* straight to the desktop shell.
|
|
12539
13173
|
*/
|
|
13174
|
+
const LOGIN_AUTH_HOSTS = /* @__PURE__ */ new Set([
|
|
13175
|
+
"copilot.tencent.com",
|
|
13176
|
+
"www.codebuddy.cn",
|
|
13177
|
+
"www.codebuddy.ai",
|
|
13178
|
+
"www.workbuddy.ai"
|
|
13179
|
+
]);
|
|
12540
13180
|
function checkedAuthUrl(value) {
|
|
12541
13181
|
let parsed;
|
|
12542
13182
|
try {
|
|
@@ -12545,6 +13185,7 @@ function checkedAuthUrl(value) {
|
|
|
12545
13185
|
throw new Error("workbuddy login start returned an invalid url");
|
|
12546
13186
|
}
|
|
12547
13187
|
if (parsed.protocol !== "https:") throw new Error("workbuddy login start returned a non-https url");
|
|
13188
|
+
if (parsed.username !== "" || parsed.password !== "" || !LOGIN_AUTH_HOSTS.has(parsed.hostname)) throw new Error("workbuddy login start returned an unexpected host");
|
|
12548
13189
|
return value;
|
|
12549
13190
|
}
|
|
12550
13191
|
/** Browser-shaped headers; `Origin` is the one the endpoints check. */
|
|
@@ -12682,6 +13323,26 @@ async function pollDeviceLogin(realm, state, fetchImpl = fetch) {
|
|
|
12682
13323
|
*
|
|
12683
13324
|
* @module dsh-wtq-pool/source-pool
|
|
12684
13325
|
*/
|
|
13326
|
+
/**
|
|
13327
|
+
* One label per credential, unique inside a source region.
|
|
13328
|
+
*
|
|
13329
|
+
* Trae and Qoder list an account by its display name, and two accounts can
|
|
13330
|
+
* share one. Every per-account decision - the picked account, a failure hold,
|
|
13331
|
+
* a check-in row - is keyed by that label, so a duplicate let one account's
|
|
13332
|
+
* failure hide the other and put a balance under the wrong name. A repeated
|
|
13333
|
+
* name gets the vendor's own user id appended; a name used once is unchanged.
|
|
13334
|
+
*/
|
|
13335
|
+
function uniqueSourceLabels(items, labelOf, idOf) {
|
|
13336
|
+
const labels = items.map((item) => labelOf(item));
|
|
13337
|
+
const counts = /* @__PURE__ */ new Map();
|
|
13338
|
+
for (const label of labels) counts.set(label, (counts.get(label) ?? 0) + 1);
|
|
13339
|
+
return labels.map((label, index) => {
|
|
13340
|
+
if ((counts.get(label) ?? 0) < 2) return label;
|
|
13341
|
+
const item = items[index];
|
|
13342
|
+
const id = item === void 0 ? "" : idOf(item).replace(/[^A-Za-z0-9]/gu, "").slice(-8);
|
|
13343
|
+
return id === "" ? label : `${label}#${id}`;
|
|
13344
|
+
});
|
|
13345
|
+
}
|
|
12685
13346
|
/** Build the pool the Trae and Qoder gateways share, wired to the host's readers. */
|
|
12686
13347
|
function createSourcePool(host) {
|
|
12687
13348
|
/**
|
|
@@ -12985,6 +13646,13 @@ const PLACEHOLDER_BASE_URL = "http://127.0.0.1:1/v1";
|
|
|
12985
13646
|
* paint, so opening it never waits on a billing call per account.
|
|
12986
13647
|
*/
|
|
12987
13648
|
const PROBE_TTL_MS = 6e4;
|
|
13649
|
+
/**
|
|
13650
|
+
* How long a failed billing read is reused.
|
|
13651
|
+
*
|
|
13652
|
+
* A failure at startup is usually transient, and holding it for the full cache
|
|
13653
|
+
* window left the readout on "—" until the next TTL or a manual refresh.
|
|
13654
|
+
*/
|
|
13655
|
+
const PROBE_RETRY_MS = 15e3;
|
|
12988
13656
|
/** How often the desktop sign-ins are re-read while the service runs. */
|
|
12989
13657
|
const ACCOUNT_WATCH_MS = 6e4;
|
|
12990
13658
|
/**
|
|
@@ -13016,6 +13684,8 @@ const SERVICE_ROSTER_BUDGET_MS = 3e3;
|
|
|
13016
13684
|
*/
|
|
13017
13685
|
const LOAD_BOOTSTRAP_BUDGET_MS = 5e3;
|
|
13018
13686
|
const SERVICE_BOOTSTRAP_BUDGET_MS = 1500;
|
|
13687
|
+
/** Bound on closing source gateways when the whole plugin is switched off. */
|
|
13688
|
+
const DISABLED_CLOSE_BUDGET_MS = 2e3;
|
|
13019
13689
|
/**
|
|
13020
13690
|
* One whole refresh pass, and how long a forced one waits for the pass it found
|
|
13021
13691
|
* already running.
|
|
@@ -13134,6 +13804,14 @@ let refreshTimer = null;
|
|
|
13134
13804
|
/** The background refresh in flight, so two passes never overlap. */
|
|
13135
13805
|
let refreshInflight = null;
|
|
13136
13806
|
/**
|
|
13807
|
+
* A refresh asked for while a pass held the slot.
|
|
13808
|
+
*
|
|
13809
|
+
* The pass that is running read settings and rosters when it started, so a
|
|
13810
|
+
* change that arrived after that point was otherwise dropped and took effect on
|
|
13811
|
+
* the next unrelated pass. One follow-up consumes every such request.
|
|
13812
|
+
*/
|
|
13813
|
+
let refreshPending = false;
|
|
13814
|
+
/**
|
|
13137
13815
|
* Counts activations, so a pass from a retired one can tell that it is stale.
|
|
13138
13816
|
*
|
|
13139
13817
|
* A refresh suspends at network awaits, and unload cannot wait for it. Without
|
|
@@ -13200,6 +13878,11 @@ let growthLast = null;
|
|
|
13200
13878
|
* instead of asking the user to read again; the panel refreshes it when it is old.
|
|
13201
13879
|
*/
|
|
13202
13880
|
let growthRead = null;
|
|
13881
|
+
/** Drop the held growth read; the epoch rejects one that lands after this. */
|
|
13882
|
+
function invalidateGrowthRead() {
|
|
13883
|
+
growthRead = null;
|
|
13884
|
+
growthReadEpoch += 1;
|
|
13885
|
+
}
|
|
13203
13886
|
/**
|
|
13204
13887
|
* Which read the answer in flight belongs to.
|
|
13205
13888
|
*
|
|
@@ -13487,6 +14170,8 @@ async function applySettingsEverywhere(toggled) {
|
|
|
13487
14170
|
const generation = loadGeneration;
|
|
13488
14171
|
if (!stillLoaded(generation)) return false;
|
|
13489
14172
|
applySettingsToCore();
|
|
14173
|
+
if (settings.enabled === false) stopAccountWatch();
|
|
14174
|
+
else startAccountWatch();
|
|
13490
14175
|
traeAccountRows = traeAccountRows.filter((row) => regionEnabled("trae", row.region));
|
|
13491
14176
|
qoderAccountRows = qoderAccountRows.filter((row) => regionEnabled("qoder", row.region));
|
|
13492
14177
|
await reconcileTraeGateways();
|
|
@@ -13495,10 +14180,7 @@ async function applySettingsEverywhere(toggled) {
|
|
|
13495
14180
|
if (!stillLoaded(generation)) return false;
|
|
13496
14181
|
syncDeclaration();
|
|
13497
14182
|
if (toggled) probeCache.clear();
|
|
13498
|
-
if (toggled)
|
|
13499
|
-
growthRead = null;
|
|
13500
|
-
growthReadEpoch += 1;
|
|
13501
|
-
}
|
|
14183
|
+
if (toggled) invalidateGrowthRead();
|
|
13502
14184
|
scheduleRefresh("settings");
|
|
13503
14185
|
return true;
|
|
13504
14186
|
}
|
|
@@ -14351,12 +15033,15 @@ async function warmSourceDirectory(entry, signal) {
|
|
|
14351
15033
|
if (signal) bounds.push(signal);
|
|
14352
15034
|
try {
|
|
14353
15035
|
const warm = await fetch(entry.baseUrl + "/v1/models", { signal: bounds.length === 1 ? bounds[0] : AbortSignal.any(bounds) });
|
|
15036
|
+
if (warm.body !== null) await warm.body.cancel().catch(() => {});
|
|
15037
|
+
if (signal && signal.aborted) return false;
|
|
14354
15038
|
entry.lastError = warm.ok ? "" : "directory answered HTTP " + warm.status;
|
|
14355
15039
|
} catch (error) {
|
|
14356
15040
|
if (signal && signal.aborted) return false;
|
|
14357
15041
|
entry.lastError = entry.gateway.models().length > 0 ? "" : "directory unavailable: " + safeMessage(error);
|
|
14358
15042
|
if (entry.lastError !== "") log("warn", "[" + entry.source + ":" + entry.region + "] " + entry.lastError);
|
|
14359
15043
|
}
|
|
15044
|
+
if (signal && signal.aborted) return false;
|
|
14360
15045
|
entry.warmSettled = true;
|
|
14361
15046
|
if (entry.lastError === "" && entry.gateway.models().length > 0) syncDeclaration();
|
|
14362
15047
|
return entry.lastError === "";
|
|
@@ -14602,7 +15287,7 @@ async function createQoderRuntime(region) {
|
|
|
14602
15287
|
},
|
|
14603
15288
|
listedIds: () => qoderDeclarationModels(region).map((model) => model.id),
|
|
14604
15289
|
onAttemptFailure: (credential, outcome) => {
|
|
14605
|
-
const label = typeof credential.name === "string" && credential.name !== "" ? credential.name : credential.userID;
|
|
15290
|
+
const label = qoderLabelOverrides.get(qoderLabelKey(credential, region)) ?? (typeof credential.name === "string" && credential.name !== "" ? credential.name : credential.userID);
|
|
14606
15291
|
noteSourceFailure("qoder", region, label, outcome.retryAfter);
|
|
14607
15292
|
},
|
|
14608
15293
|
port: bound,
|
|
@@ -14754,7 +15439,9 @@ async function createRuntime(region) {
|
|
|
14754
15439
|
connecting: null,
|
|
14755
15440
|
/** A stopped gateway cannot commit a catalog fetch that finishes later. */
|
|
14756
15441
|
retired: false,
|
|
14757
|
-
catalogFetchedAtMs: 0
|
|
15442
|
+
catalogFetchedAtMs: 0,
|
|
15443
|
+
catalogRetryAttempt: 0,
|
|
15444
|
+
catalogRetryTimer: null
|
|
14758
15445
|
};
|
|
14759
15446
|
applyEffectiveSelection(region, runtime);
|
|
14760
15447
|
const preferred = preferredPort(region);
|
|
@@ -14895,20 +15582,25 @@ function trackRuntimeStop(runtime) {
|
|
|
14895
15582
|
* pass nobody asked for.
|
|
14896
15583
|
*/
|
|
14897
15584
|
const modelRetryTimers = /* @__PURE__ */ new Set();
|
|
14898
|
-
function scheduleModelRetries(
|
|
14899
|
-
if (serviceStopped) return;
|
|
15585
|
+
function scheduleModelRetries(runtime) {
|
|
15586
|
+
if (serviceStopped || runtime.retired) return;
|
|
15587
|
+
if (runtime.catalogRetryTimer !== null || runtime.catalogRetryAttempt >= MODEL_RETRY_ATTEMPTS) return;
|
|
14900
15588
|
const timer = setTimeout(() => {
|
|
14901
15589
|
modelRetryTimers.delete(timer);
|
|
15590
|
+
runtime.catalogRetryTimer = null;
|
|
15591
|
+
if (runtime.retired || serviceStopped) return;
|
|
15592
|
+
runtime.catalogRetryAttempt += 1;
|
|
14902
15593
|
scheduleRefresh("model-list-retry");
|
|
14903
|
-
if (attempt < MODEL_RETRY_ATTEMPTS) scheduleModelRetries(attempt + 1);
|
|
14904
15594
|
}, CATALOG_RETRY_MS);
|
|
14905
15595
|
if (typeof timer.unref === "function") timer.unref();
|
|
15596
|
+
runtime.catalogRetryTimer = timer;
|
|
14906
15597
|
modelRetryTimers.add(timer);
|
|
14907
15598
|
}
|
|
14908
15599
|
/** Drop every pending roster retry. */
|
|
14909
15600
|
function clearModelRetries() {
|
|
14910
15601
|
for (const timer of modelRetryTimers) clearTimeout(timer);
|
|
14911
15602
|
modelRetryTimers.clear();
|
|
15603
|
+
for (const runtime of runtimes.values()) runtime.catalogRetryTimer = null;
|
|
14912
15604
|
}
|
|
14913
15605
|
/**
|
|
14914
15606
|
* Bring one gateway online: seed its catalog from that gateway's own account.
|
|
@@ -14930,7 +15622,7 @@ async function connect(runtime, force) {
|
|
|
14930
15622
|
runtime.lastError = "no " + runtime.region + " WorkBuddy sign-in found";
|
|
14931
15623
|
if (core.pool.status().lastScanAtMs === 0) {
|
|
14932
15624
|
runtime.catalogFetchedAtMs = Date.now() - CATALOG_TTL_MS + CATALOG_RETRY_MS;
|
|
14933
|
-
scheduleModelRetries();
|
|
15625
|
+
scheduleModelRetries(runtime);
|
|
14934
15626
|
return false;
|
|
14935
15627
|
}
|
|
14936
15628
|
runtime.catalogFetchedAtMs = Date.now();
|
|
@@ -14942,10 +15634,16 @@ async function connect(runtime, force) {
|
|
|
14942
15634
|
if (runtime.retired) return false;
|
|
14943
15635
|
runtime.catalog.update(catalogFromUpstream(models));
|
|
14944
15636
|
runtime.catalogFetchedAtMs = Date.now();
|
|
15637
|
+
runtime.catalogRetryAttempt = 0;
|
|
15638
|
+
if (runtime.catalogRetryTimer !== null) {
|
|
15639
|
+
clearTimeout(runtime.catalogRetryTimer);
|
|
15640
|
+
modelRetryTimers.delete(runtime.catalogRetryTimer);
|
|
15641
|
+
runtime.catalogRetryTimer = null;
|
|
15642
|
+
}
|
|
14945
15643
|
} catch (error) {
|
|
14946
15644
|
runtime.lastWarning = "model list failed: " + safeMessage(error);
|
|
14947
15645
|
runtime.catalogFetchedAtMs = Date.now() - CATALOG_TTL_MS + CATALOG_RETRY_MS;
|
|
14948
|
-
scheduleModelRetries();
|
|
15646
|
+
scheduleModelRetries(runtime);
|
|
14949
15647
|
}
|
|
14950
15648
|
applyEffectiveSelection(runtime.region, runtime);
|
|
14951
15649
|
if (runtime.retired) return false;
|
|
@@ -14967,7 +15665,7 @@ function catalogFresh(runtime) {
|
|
|
14967
15665
|
* keeps the poll alive until the numbers actually land.
|
|
14968
15666
|
*/
|
|
14969
15667
|
function refreshNeeded() {
|
|
14970
|
-
if (serviceStopped) return false;
|
|
15668
|
+
if (serviceStopped || settings.enabled === false) return false;
|
|
14971
15669
|
if (refreshInflight !== null) return true;
|
|
14972
15670
|
for (const runtime of runtimes.values()) {
|
|
14973
15671
|
if (runtime.connecting) return true;
|
|
@@ -14998,7 +15696,9 @@ function probesStale() {
|
|
|
14998
15696
|
for (const account of core.pool.list()) {
|
|
14999
15697
|
if (account.cooldownUntilMs > now || core.pool.isDisabled(account.id) || !regionEnabled("workbuddy", regionOf(account.credential.domain))) continue;
|
|
15000
15698
|
const cached = probeCache.get(account.id);
|
|
15001
|
-
if (cached === void 0
|
|
15699
|
+
if (cached === void 0) return true;
|
|
15700
|
+
const ttl = cached.value.creditsError !== void 0 ? PROBE_RETRY_MS : PROBE_TTL_MS;
|
|
15701
|
+
if (now - cached.atMs >= ttl) return true;
|
|
15002
15702
|
if (cached.checkinOnly === true) return true;
|
|
15003
15703
|
}
|
|
15004
15704
|
return false;
|
|
@@ -15013,10 +15713,17 @@ function probesStale() {
|
|
|
15013
15713
|
*/
|
|
15014
15714
|
function scheduleRefresh(reason) {
|
|
15015
15715
|
if (serviceStopped) return;
|
|
15016
|
-
if (refreshTimer !== null || refreshInflight !== null)
|
|
15716
|
+
if (refreshTimer !== null || refreshInflight !== null) {
|
|
15717
|
+
if (reason !== "panel") refreshPending = true;
|
|
15718
|
+
return;
|
|
15719
|
+
}
|
|
15017
15720
|
refreshTimer = setTimeout(() => {
|
|
15018
15721
|
refreshTimer = null;
|
|
15019
|
-
refreshAll(reason, false).catch((error) => log("warn", "background refresh failed: " + safeMessage(error)))
|
|
15722
|
+
refreshAll(reason, false).catch((error) => log("warn", "background refresh failed: " + safeMessage(error))).finally(() => {
|
|
15723
|
+
if (!refreshPending || serviceStopped) return;
|
|
15724
|
+
refreshPending = false;
|
|
15725
|
+
scheduleRefresh("pending");
|
|
15726
|
+
});
|
|
15020
15727
|
}, 0);
|
|
15021
15728
|
if (typeof refreshTimer.unref === "function") refreshTimer.unref();
|
|
15022
15729
|
}
|
|
@@ -15066,7 +15773,7 @@ function stalePass() {
|
|
|
15066
15773
|
* would start a pass beside it. The slot therefore outlives both.
|
|
15067
15774
|
*/
|
|
15068
15775
|
async function refreshAll(reason, force) {
|
|
15069
|
-
if (serviceStopped) return await statusDocument({ allowNetwork: false });
|
|
15776
|
+
if (serviceStopped || settings.enabled === false) return await statusDocument({ allowNetwork: false });
|
|
15070
15777
|
const wantForce = force === true;
|
|
15071
15778
|
let previous = null;
|
|
15072
15779
|
if (refreshInflight !== null) {
|
|
@@ -15113,7 +15820,7 @@ async function refreshAll(reason, force) {
|
|
|
15113
15820
|
if (!stillLoaded(generation)) return stalePass();
|
|
15114
15821
|
await settle(reconcileQoderGateways());
|
|
15115
15822
|
if (!stillLoaded(generation)) return stalePass();
|
|
15116
|
-
await settle(refreshSourceAccounts());
|
|
15823
|
+
await settle(refreshSourceAccounts(generation));
|
|
15117
15824
|
if (!stillLoaded(generation)) return stalePass();
|
|
15118
15825
|
await settle(Promise.all([...Array.from(traeGateways.values()), ...Array.from(qoderGateways.values())].filter((entry) => entry.lastError !== "" || entry.gateway.models().length === 0).map((entry) => warmSourceDirectory(entry))));
|
|
15119
15826
|
if (!stillLoaded(generation)) return stalePass();
|
|
@@ -15139,6 +15846,10 @@ async function refreshAll(reason, force) {
|
|
|
15139
15846
|
} finally {
|
|
15140
15847
|
if (previous !== null) await previous;
|
|
15141
15848
|
if (refreshInflight === entry) refreshInflight = null;
|
|
15849
|
+
if (refreshPending && !serviceStopped && stillLoaded(generation)) {
|
|
15850
|
+
refreshPending = false;
|
|
15851
|
+
scheduleRefresh("pending");
|
|
15852
|
+
}
|
|
15142
15853
|
}
|
|
15143
15854
|
})();
|
|
15144
15855
|
refreshInflight = entry;
|
|
@@ -15151,16 +15862,26 @@ async function refreshAll(reason, force) {
|
|
|
15151
15862
|
*/
|
|
15152
15863
|
let traeAccountRows = [];
|
|
15153
15864
|
let qoderAccountRows = [];
|
|
15865
|
+
/** Disambiguated labels by `region + "\n" + user id`, so a gateway that only has
|
|
15866
|
+
* a credential names the same row the panel does. Reset on every activation. */
|
|
15867
|
+
let traeLabelOverrides = /* @__PURE__ */ new Map();
|
|
15868
|
+
let qoderLabelOverrides = /* @__PURE__ */ new Map();
|
|
15154
15869
|
/**
|
|
15155
|
-
* The name one Trae account is listed
|
|
15870
|
+
* The name one Trae account is listed under before duplicates are resolved.
|
|
15156
15871
|
*
|
|
15157
15872
|
* A Trae-generated `username` can read as a stranger (`zhang san xyz`), so the
|
|
15158
|
-
* email is what the panel shows next to it; the label
|
|
15159
|
-
*
|
|
15873
|
+
* email is what the panel shows next to it; the base label stays the app's own
|
|
15874
|
+
* name so it matches what the desktop app displays.
|
|
15160
15875
|
*/
|
|
15161
|
-
function
|
|
15876
|
+
function traeBaseLabel(credential) {
|
|
15162
15877
|
return credential.accountName ?? credential.email ?? credential.userId;
|
|
15163
15878
|
}
|
|
15879
|
+
function traeLabelKey(credential) {
|
|
15880
|
+
return traeRegionOfCredential(credential) + "\n" + (credential.userId || credential.accountName || credential.email || "");
|
|
15881
|
+
}
|
|
15882
|
+
function traeRowLabel(credential) {
|
|
15883
|
+
return traeLabelOverrides.get(traeLabelKey(credential)) ?? traeBaseLabel(credential);
|
|
15884
|
+
}
|
|
15164
15885
|
/**
|
|
15165
15886
|
* The app one Trae sign-in came from.
|
|
15166
15887
|
*
|
|
@@ -15173,10 +15894,16 @@ function traeAppLabelOf(credential) {
|
|
|
15173
15894
|
if (credential.source === "cli") return "Trae CLI";
|
|
15174
15895
|
return traeWindowsAppNames(credential.edition)[0];
|
|
15175
15896
|
}
|
|
15176
|
-
/** The name one Qoder account is listed
|
|
15177
|
-
function
|
|
15897
|
+
/** The name one Qoder account is listed under before duplicates are resolved. */
|
|
15898
|
+
function qoderBaseLabel(credential) {
|
|
15178
15899
|
return credential.name === "" ? credential.userID : credential.name;
|
|
15179
15900
|
}
|
|
15901
|
+
function qoderLabelKey(credential, region) {
|
|
15902
|
+
return (region ?? credential.region) + "\n" + (credential.userID || credential.name || "");
|
|
15903
|
+
}
|
|
15904
|
+
function qoderRowLabel(credential, region) {
|
|
15905
|
+
return qoderLabelOverrides.get(qoderLabelKey(credential, region)) ?? qoderBaseLabel(credential);
|
|
15906
|
+
}
|
|
15180
15907
|
/**
|
|
15181
15908
|
* How long the Trae and Qoder sign-in lists may take in total.
|
|
15182
15909
|
*
|
|
@@ -15306,14 +16033,22 @@ async function qoderRowProbe(credential, previous) {
|
|
|
15306
16033
|
return previous;
|
|
15307
16034
|
}
|
|
15308
16035
|
}
|
|
15309
|
-
async function refreshSourceAccounts() {
|
|
16036
|
+
async function refreshSourceAccounts(generation) {
|
|
15310
16037
|
const now = Date.now();
|
|
15311
16038
|
try {
|
|
15312
16039
|
const regions = activeTraeRegions();
|
|
15313
16040
|
if (regions.length > 0) {
|
|
15314
16041
|
const found = await discoverTraeCredentials();
|
|
15315
|
-
|
|
15316
|
-
|
|
16042
|
+
const allLabels = uniqueSourceLabels(found.credentials, traeBaseLabel, (credential) => credential.userId);
|
|
16043
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
16044
|
+
found.credentials.forEach((credential, index) => {
|
|
16045
|
+
overrides.set(traeLabelKey(credential), allLabels[index]);
|
|
16046
|
+
});
|
|
16047
|
+
const wanted = found.credentials.map((credential, index) => ({
|
|
16048
|
+
credential,
|
|
16049
|
+
label: allLabels[index]
|
|
16050
|
+
})).filter(({ credential }) => regions.includes(traeRegionOfCredential(credential)));
|
|
16051
|
+
const rows = await Promise.all(wanted.map(async ({ credential, label }) => {
|
|
15317
16052
|
const region = traeRegionOfCredential(credential);
|
|
15318
16053
|
const probe = await traeRowProbe(credential, traeAccountRows.find((row) => row.label === label && row.region === region));
|
|
15319
16054
|
noteSourceExpiry("trae", region, label, probe?.usage?.credits?.packages);
|
|
@@ -15327,7 +16062,10 @@ async function refreshSourceAccounts() {
|
|
|
15327
16062
|
...probe?.checkin ? { checkin: probe.checkin } : {},
|
|
15328
16063
|
...probe?.usage ? { usage: probe.usage } : {}
|
|
15329
16064
|
};
|
|
15330
|
-
}))
|
|
16065
|
+
}));
|
|
16066
|
+
if (generation !== loadGeneration) return;
|
|
16067
|
+
traeLabelOverrides = overrides;
|
|
16068
|
+
traeAccountRows = rows.filter((row) => regionEnabled("trae", row.region));
|
|
15331
16069
|
} else traeAccountRows = [];
|
|
15332
16070
|
} catch (error) {
|
|
15333
16071
|
log("warn", "listing Trae sign-ins failed: " + safeMessage(error));
|
|
@@ -15336,14 +16074,21 @@ async function refreshSourceAccounts() {
|
|
|
15336
16074
|
const regions = activeQoderRegions();
|
|
15337
16075
|
if (regions.length > 0) {
|
|
15338
16076
|
const found = await discoverQoderCredentials();
|
|
16077
|
+
const allLabels = uniqueSourceLabels(found.credentials, qoderBaseLabel, (credential) => credential.userID);
|
|
16078
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
16079
|
+
found.credentials.forEach((credential, index) => {
|
|
16080
|
+
overrides.set(qoderLabelKey(credential), allLabels[index]);
|
|
16081
|
+
});
|
|
16082
|
+
const wanted = found.credentials.map((credential, index) => ({
|
|
16083
|
+
credential,
|
|
16084
|
+
label: allLabels[index]
|
|
16085
|
+
})).filter(({ credential }) => regions.includes(credential.region));
|
|
15339
16086
|
const rows = [];
|
|
15340
16087
|
const { left } = budget(SOURCE_ACCOUNTS_BUDGET_MS);
|
|
15341
16088
|
let seen = 0;
|
|
15342
|
-
for (const credential of
|
|
15343
|
-
if (!regions.includes(credential.region)) continue;
|
|
16089
|
+
for (const { credential, label } of wanted) {
|
|
15344
16090
|
if (seen > 0) await delay(QODER_ACCOUNT_DELAY_MS);
|
|
15345
16091
|
seen += 1;
|
|
15346
|
-
const label = qoderRowLabel(credential);
|
|
15347
16092
|
const previous = qoderAccountRows.find((row) => row.label === label && row.region === credential.region);
|
|
15348
16093
|
const probe = left() > 0 ? await qoderRowProbe(credential, previous) : previous;
|
|
15349
16094
|
noteSourceExpiry("qoder", credential.region, label, probe?.usage?.credits?.packages);
|
|
@@ -15356,6 +16101,8 @@ async function refreshSourceAccounts() {
|
|
|
15356
16101
|
...probe?.usage ? { usage: probe.usage } : {}
|
|
15357
16102
|
});
|
|
15358
16103
|
}
|
|
16104
|
+
if (generation !== loadGeneration) return;
|
|
16105
|
+
qoderLabelOverrides = overrides;
|
|
15359
16106
|
qoderAccountRows = rows.filter((row) => regionEnabled("qoder", row.region));
|
|
15360
16107
|
} else qoderAccountRows = [];
|
|
15361
16108
|
} catch (error) {
|
|
@@ -15480,7 +16227,7 @@ function applyProbe(row, probe) {
|
|
|
15480
16227
|
async function accountProbe(account, allowNetwork, checkinOnly = false) {
|
|
15481
16228
|
const cached = probeCache.get(account.id);
|
|
15482
16229
|
if (allowNetwork !== true) return cached === void 0 ? { pending: true } : cached.value;
|
|
15483
|
-
const cachedFresh = cached !== void 0 && Date.now() - cached.atMs < PROBE_TTL_MS;
|
|
16230
|
+
const cachedFresh = cached !== void 0 && Date.now() - cached.atMs < (cached.value.creditsError !== void 0 ? PROBE_RETRY_MS : PROBE_TTL_MS);
|
|
15484
16231
|
const cachedHasCredits = cached !== void 0 && (cached.value.credits !== void 0 || cached.value.creditsError !== void 0);
|
|
15485
16232
|
if (cachedFresh && (checkinOnly || cached.checkinOnly !== true && cachedHasCredits)) return cached.value;
|
|
15486
16233
|
if (signInRefused(account)) return {};
|
|
@@ -15612,7 +16359,6 @@ async function statusDocument(options) {
|
|
|
15612
16359
|
const allowNetwork = options?.allowNetwork === true;
|
|
15613
16360
|
const probeBudget = typeof options?.budgetMs === "number" ? Math.min(PROBE_BATCH_BUDGET_MS, Math.max(0, options.budgetMs)) : PROBE_BATCH_BUDGET_MS;
|
|
15614
16361
|
const now = Date.now();
|
|
15615
|
-
const reserves = creditReserves();
|
|
15616
16362
|
const campaignClock = zonedDayHour(new Date(now));
|
|
15617
16363
|
const accounts = [];
|
|
15618
16364
|
const models = [];
|
|
@@ -15625,7 +16371,7 @@ async function statusDocument(options) {
|
|
|
15625
16371
|
/** Row -> the credits/check-in read that row is still waiting on. */
|
|
15626
16372
|
const pendingProbes = [];
|
|
15627
16373
|
for (const region of activeRegions()) {
|
|
15628
|
-
preferredAccountIds[region] =
|
|
16374
|
+
preferredAccountIds[region] = core.pool.resolvedPreferredId(region) || "";
|
|
15629
16375
|
selectionByRegion[region] = effectiveSelectionFor(region, runtimes.get(region)?.catalog);
|
|
15630
16376
|
if (selectionStale(region, runtimes.get(region)?.catalog)) staleSelectionRegions.push(region);
|
|
15631
16377
|
const available = core.pool.available(now, void 0, region);
|
|
@@ -15633,6 +16379,7 @@ async function statusDocument(options) {
|
|
|
15633
16379
|
runtimeNextUpId.set(region, nextUp === void 0 ? void 0 : nextUp.id);
|
|
15634
16380
|
for (const account of core.pool.list(region)) {
|
|
15635
16381
|
const cooling = account.cooldownUntilMs > now;
|
|
16382
|
+
const creditReserve = core.pool.creditReserve(account.id);
|
|
15636
16383
|
const modelCooldowns = Object.entries(account.modelCooldowns).filter(([, until]) => until > now).sort((a, b) => a[1] - b[1]).map(([modelId, until]) => ({
|
|
15637
16384
|
modelId,
|
|
15638
16385
|
until: new Date(until).toISOString()
|
|
@@ -15648,11 +16395,11 @@ async function statusDocument(options) {
|
|
|
15648
16395
|
rateLimitHits: account.rateLimitHits,
|
|
15649
16396
|
...activeHoldOf(account.id, now),
|
|
15650
16397
|
active: runtimeNextUpId.get(region) === account.id,
|
|
15651
|
-
preferred: preferredAccountIds[region] === account.id,
|
|
16398
|
+
preferred: preferredAccountIds[region] === account.id || core.pool.storedIds(account.id).includes(preferredAccountIds[region]),
|
|
15652
16399
|
disabled: core.pool.isDisabled(account.id),
|
|
15653
16400
|
...account.archived === true ? { archived: true } : {},
|
|
15654
16401
|
...core.pool.ownsSignIn(account.id) ? { own: true } : {},
|
|
15655
|
-
...
|
|
16402
|
+
...creditReserve === void 0 ? {} : { creditReserve }
|
|
15656
16403
|
};
|
|
15657
16404
|
if (!core.pool.isDisabled(account.id)) {
|
|
15658
16405
|
const checkinOnly = cooling;
|
|
@@ -16312,13 +17059,13 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16312
17059
|
* gateway's roster is refetched even inside its refresh window.
|
|
16313
17060
|
*/
|
|
16314
17061
|
case "xd.rescan": {
|
|
17062
|
+
const generation = loadGeneration;
|
|
16315
17063
|
const { left, settle } = budget(RESCAN_BUDGET_MS);
|
|
16316
17064
|
resetDiscoveryCaches();
|
|
16317
|
-
|
|
16318
|
-
growthReadEpoch += 1;
|
|
17065
|
+
invalidateGrowthRead();
|
|
16319
17066
|
if (activeRegions().length > 0) await settle(core.pool.rescan());
|
|
16320
17067
|
await settle(startRuntimes());
|
|
16321
|
-
await settle(refreshSourceAccounts());
|
|
17068
|
+
await settle(refreshSourceAccounts(generation));
|
|
16322
17069
|
await settle(reconcileTraeGateways());
|
|
16323
17070
|
await settle(reconcileQoderGateways());
|
|
16324
17071
|
await settle(Promise.all([...Array.from(traeGateways.values()), ...Array.from(qoderGateways.values())].filter((entry) => entry.lastError !== "" || entry.gateway.models().length === 0).map((entry) => warmSourceDirectory(entry))));
|
|
@@ -16439,25 +17186,27 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16439
17186
|
"deleted"
|
|
16440
17187
|
].includes(state)) throw panelError("region, accountId and a known state are required", "INVALID");
|
|
16441
17188
|
const account = core.pool.list(region).find((item) => item.id === accountId);
|
|
16442
|
-
const
|
|
17189
|
+
const ids = core.pool.storedIds(accountId);
|
|
17190
|
+
const stored = removedAccounts().find((entry) => ids.includes(entry.id));
|
|
16443
17191
|
if (state !== "restored" && account === void 0 && stored === void 0) throw panelError("account does not belong to this gateway", "NOT_FOUND");
|
|
16444
17192
|
if (state === "deleted") {
|
|
16445
17193
|
if (!core.pool.ownsSignIn(accountId)) throw panelError("only an account added from this panel can be deleted", "NOT_OWN");
|
|
16446
17194
|
if (await core.pool.removeOwnSignIn(accountId) !== true) throw panelError("the sign-in file could not be removed", "DELETE_FAILED");
|
|
16447
|
-
|
|
17195
|
+
probeCache.delete(accountId);
|
|
17196
|
+
await settleWithin(core.pool.rescan(), POOL_SCAN_BUDGET_MS);
|
|
16448
17197
|
if (await mutateSettings("disabledAccountIds", (current) => {
|
|
16449
|
-
return (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => id
|
|
17198
|
+
return (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => !ids.includes(id));
|
|
16450
17199
|
}) !== true) log("warn", "could not clear the disabled state for " + accountId);
|
|
16451
17200
|
if (await mutateSettings("creditReserves", (current) => {
|
|
16452
17201
|
const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
|
|
16453
|
-
delete next[
|
|
17202
|
+
for (const id of ids) delete next[id];
|
|
16454
17203
|
return next;
|
|
16455
17204
|
}) !== true) log("warn", "could not clear the credit reserve for " + accountId);
|
|
16456
17205
|
core.pool.applyConfig({
|
|
16457
17206
|
disabledAccountIds: disabledAccountIds(),
|
|
16458
17207
|
creditReserves: creditReserves()
|
|
16459
17208
|
});
|
|
16460
|
-
if (preferredAccountId(region)
|
|
17209
|
+
if (ids.includes(preferredAccountId(region))) {
|
|
16461
17210
|
if (await mutateSettings("preferredAccountIds", (current) => {
|
|
16462
17211
|
const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
|
|
16463
17212
|
delete next[region];
|
|
@@ -16465,17 +17214,16 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16465
17214
|
}) !== true) log("warn", "could not clear the preferred account for " + region);
|
|
16466
17215
|
core.pool.prefer(void 0, region);
|
|
16467
17216
|
}
|
|
16468
|
-
|
|
16469
|
-
growthReadEpoch += 1;
|
|
17217
|
+
invalidateGrowthRead();
|
|
16470
17218
|
return await statusDocument({ allowNetwork: false });
|
|
16471
17219
|
}
|
|
16472
17220
|
if (await mutateSettings("disabledAccountIds", (current) => {
|
|
16473
|
-
const kept = (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => id
|
|
17221
|
+
const kept = (Array.isArray(current) ? current.filter((id) => typeof id === "string") : []).filter((id) => !ids.includes(id));
|
|
16474
17222
|
if (state === "disabled") kept.push(accountId);
|
|
16475
17223
|
return kept;
|
|
16476
17224
|
}) !== true) throw panelError("the account setting could not be saved", "SAVE_FAILED");
|
|
16477
17225
|
if (await mutateSettings("removedAccounts", (current) => {
|
|
16478
|
-
const kept = (Array.isArray(current) ? current.filter((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry)) : []).filter((entry) => entry.id
|
|
17226
|
+
const kept = (Array.isArray(current) ? current.filter((entry) => entry !== null && typeof entry === "object" && !Array.isArray(entry)) : []).filter((entry) => !ids.includes(entry.id));
|
|
16479
17227
|
if (state === "removed") kept.push({
|
|
16480
17228
|
id: accountId,
|
|
16481
17229
|
label: account === void 0 ? stored.label : account.label,
|
|
@@ -16487,7 +17235,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16487
17235
|
const removed = removedAccounts();
|
|
16488
17236
|
core.pool.applyConfig({ disabledAccountIds: disabled });
|
|
16489
17237
|
core.pool.applyRemoved(removed.map((entry) => entry.id));
|
|
16490
|
-
if (accountId !== "" && preferredAccountId(region)
|
|
17238
|
+
if (accountId !== "" && ids.includes(preferredAccountId(region)) && state !== "enabled" && state !== "restored") {
|
|
16491
17239
|
if (await mutateSettings("preferredAccountIds", (current) => {
|
|
16492
17240
|
const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
|
|
16493
17241
|
delete next[region];
|
|
@@ -16495,8 +17243,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16495
17243
|
}) !== true) log("warn", "could not clear the preferred account for " + region);
|
|
16496
17244
|
core.pool.prefer(void 0, region);
|
|
16497
17245
|
}
|
|
16498
|
-
|
|
16499
|
-
growthReadEpoch += 1;
|
|
17246
|
+
invalidateGrowthRead();
|
|
16500
17247
|
return await statusDocument({ allowNetwork: false });
|
|
16501
17248
|
}
|
|
16502
17249
|
/** The credits to keep back on one account: 0 clears the floor. */
|
|
@@ -16509,8 +17256,8 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16509
17256
|
if (!core.pool.list(region).some((account) => account.id === accountId)) throw panelError("account does not belong to this gateway", "NOT_FOUND");
|
|
16510
17257
|
if (await mutateSettings("creditReserves", (current) => {
|
|
16511
17258
|
const next = { ...current && typeof current === "object" && !Array.isArray(current) ? current : {} };
|
|
16512
|
-
|
|
16513
|
-
|
|
17259
|
+
for (const id of core.pool.storedIds(accountId)) delete next[id];
|
|
17260
|
+
if (reserve !== 0) next[accountId] = Math.floor(reserve);
|
|
16514
17261
|
return next;
|
|
16515
17262
|
}) !== true) throw panelError("the reserve could not be saved", "SAVE_FAILED");
|
|
16516
17263
|
core.pool.applyConfig({ creditReserves: creditReserves() });
|
|
@@ -16702,10 +17449,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16702
17449
|
await applySettingsEverywhere(false);
|
|
16703
17450
|
if (payload?.enabled === true) await refreshAll("region-on", true);
|
|
16704
17451
|
else syncDeclaration();
|
|
16705
|
-
if (source === "workbuddy")
|
|
16706
|
-
growthRead = null;
|
|
16707
|
-
growthReadEpoch += 1;
|
|
16708
|
-
}
|
|
17452
|
+
if (source === "workbuddy") invalidateGrowthRead();
|
|
16709
17453
|
return await statusDocument({ allowNetwork: false });
|
|
16710
17454
|
}
|
|
16711
17455
|
/**
|
|
@@ -16724,10 +17468,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16724
17468
|
await applySettingsEverywhere(false);
|
|
16725
17469
|
if (payload?.enabled === true) await refreshAll("source-on", true);
|
|
16726
17470
|
else syncDeclaration();
|
|
16727
|
-
if (payload?.source === "workbuddy")
|
|
16728
|
-
growthRead = null;
|
|
16729
|
-
growthReadEpoch += 1;
|
|
16730
|
-
}
|
|
17471
|
+
if (payload?.source === "workbuddy") invalidateGrowthRead();
|
|
16731
17472
|
return await statusDocument({ allowNetwork: false });
|
|
16732
17473
|
}
|
|
16733
17474
|
/**
|
|
@@ -16774,9 +17515,8 @@ async function onPanelInvoke(channel, payload) {
|
|
|
16774
17515
|
const directory = ownSignInDir(dataPath);
|
|
16775
17516
|
if (directory === "") throw panelError("no plugin data directory to write the sign-in into", "NO_DATA_DIR");
|
|
16776
17517
|
await writeOwnSignIn(directory, answer.signIn);
|
|
16777
|
-
|
|
16778
|
-
|
|
16779
|
-
await settleWithin(core.pool.scan(), POOL_SCAN_BUDGET_MS);
|
|
17518
|
+
invalidateGrowthRead();
|
|
17519
|
+
await settleWithin(core.pool.rescan(), POOL_SCAN_BUDGET_MS);
|
|
16780
17520
|
await refreshAll("panel-login", false);
|
|
16781
17521
|
return {
|
|
16782
17522
|
status: "ok",
|
|
@@ -17945,10 +18685,27 @@ function stopAccountWatch() {
|
|
|
17945
18685
|
* Note this is the only place the roster is fetched during load: opening the
|
|
17946
18686
|
* panel no longer triggers detection of its own.
|
|
17947
18687
|
*/
|
|
18688
|
+
/**
|
|
18689
|
+
* Close every source gateway when the whole plugin is switched off.
|
|
18690
|
+
*
|
|
18691
|
+
* A reload can arrive without the previous activation's stop. Those gateways
|
|
18692
|
+
* hold live credentials and keep answering on loopback, so switching the plugin
|
|
18693
|
+
* off must close them here rather than waiting for a teardown that may not run.
|
|
18694
|
+
*/
|
|
18695
|
+
async function closeSourceGatewaysForDisabled() {
|
|
18696
|
+
if (core.pool !== null) {
|
|
18697
|
+
applySettingsToCore();
|
|
18698
|
+
reconcileRuntimes();
|
|
18699
|
+
}
|
|
18700
|
+
await settleWithin(reconcileTraeGateways(), DISABLED_CLOSE_BUDGET_MS);
|
|
18701
|
+
await settleWithin(reconcileQoderGateways(), DISABLED_CLOSE_BUDGET_MS);
|
|
18702
|
+
}
|
|
17948
18703
|
async function publishDeclarationEarly(generation) {
|
|
17949
18704
|
await adoptHostSettings();
|
|
17950
18705
|
if (!stillLoaded(generation)) return;
|
|
17951
18706
|
if (settings.enabled === false) {
|
|
18707
|
+
await closeSourceGatewaysForDisabled();
|
|
18708
|
+
if (!stillLoaded(generation)) return;
|
|
17952
18709
|
const cleared = syncDeclaration();
|
|
17953
18710
|
if (cleared.ok !== true) log("warn", "declaration not cleared: " + String(cleared.error));
|
|
17954
18711
|
return;
|
|
@@ -17966,7 +18723,7 @@ async function publishDeclarationEarly(generation) {
|
|
|
17966
18723
|
if (!stillLoaded(generation)) return;
|
|
17967
18724
|
await settleWithin(Promise.all(Array.from(runtimes.values()).map(async (runtime) => {
|
|
17968
18725
|
try {
|
|
17969
|
-
await
|
|
18726
|
+
await refreshRuntime(runtime, "load", true);
|
|
17970
18727
|
} catch (error) {
|
|
17971
18728
|
runtime.lastError = safeMessage(error);
|
|
17972
18729
|
log("warn", runtime.region + " failed to start during load: " + runtime.lastError);
|
|
@@ -17986,6 +18743,8 @@ async function onServiceStart() {
|
|
|
17986
18743
|
await adoptHostSettings();
|
|
17987
18744
|
if (!stillLoaded(generation)) return;
|
|
17988
18745
|
if (settings.enabled === false) {
|
|
18746
|
+
await closeSourceGatewaysForDisabled();
|
|
18747
|
+
if (!stillLoaded(generation)) return;
|
|
17989
18748
|
syncDeclaration();
|
|
17990
18749
|
log("info", "plugin disabled in settings; the provider host stays down");
|
|
17991
18750
|
return;
|
|
@@ -18004,7 +18763,7 @@ async function onServiceStart() {
|
|
|
18004
18763
|
if (!stillLoaded(generation)) return;
|
|
18005
18764
|
await settleWithin(Promise.all(Array.from(runtimes.values()).map(async (runtime) => {
|
|
18006
18765
|
try {
|
|
18007
|
-
await
|
|
18766
|
+
await refreshRuntime(runtime, "service", !catalogFresh(runtime));
|
|
18008
18767
|
} catch (error) {
|
|
18009
18768
|
runtime.lastError = safeMessage(error);
|
|
18010
18769
|
log("warn", runtime.region + " failed to start: " + runtime.lastError);
|
|
@@ -18022,6 +18781,7 @@ async function onServiceStop() {
|
|
|
18022
18781
|
clearTimeout(refreshTimer);
|
|
18023
18782
|
refreshTimer = null;
|
|
18024
18783
|
}
|
|
18784
|
+
refreshPending = false;
|
|
18025
18785
|
refreshInflight = null;
|
|
18026
18786
|
stopAutoCheckin();
|
|
18027
18787
|
stopAccountWatch();
|
|
@@ -18041,6 +18801,19 @@ async function onServiceStop() {
|
|
|
18041
18801
|
sourceGatewayStarts.clear();
|
|
18042
18802
|
await Promise.all(closing);
|
|
18043
18803
|
}
|
|
18804
|
+
/**
|
|
18805
|
+
* Drop the Trae/Qoder state keyed to the previous activation's sign-ins.
|
|
18806
|
+
*
|
|
18807
|
+
* Called from both load and unload: a reload can start a new activation while
|
|
18808
|
+
* the old stop is still awaited, and that path skips the old `onUnload`.
|
|
18809
|
+
*/
|
|
18810
|
+
function resetSourceActivationState() {
|
|
18811
|
+
sourceFailureHold.clear();
|
|
18812
|
+
sourceCreditExpiry.clear();
|
|
18813
|
+
sourceRotation.clear();
|
|
18814
|
+
travelAdoptTried.clear();
|
|
18815
|
+
traeIdentityBlockers.clear();
|
|
18816
|
+
}
|
|
18044
18817
|
async function onLoad() {
|
|
18045
18818
|
serviceStopped = false;
|
|
18046
18819
|
loadGeneration += 1;
|
|
@@ -18057,6 +18830,7 @@ async function onLoad() {
|
|
|
18057
18830
|
clearTimeout(refreshTimer);
|
|
18058
18831
|
refreshTimer = null;
|
|
18059
18832
|
}
|
|
18833
|
+
refreshPending = false;
|
|
18060
18834
|
refreshInflight = null;
|
|
18061
18835
|
for (const runtime of runtimes.values()) trackRuntimeStop(runtime);
|
|
18062
18836
|
runtimes.clear();
|
|
@@ -18069,6 +18843,14 @@ async function onLoad() {
|
|
|
18069
18843
|
autoCheckinLast = null;
|
|
18070
18844
|
growthPassRunning = false;
|
|
18071
18845
|
growthLast = null;
|
|
18846
|
+
invalidateGrowthRead();
|
|
18847
|
+
traeAccountRows = [];
|
|
18848
|
+
qoderAccountRows = [];
|
|
18849
|
+
traeLabelOverrides = /* @__PURE__ */ new Map();
|
|
18850
|
+
qoderLabelOverrides = /* @__PURE__ */ new Map();
|
|
18851
|
+
resetSourceActivationState();
|
|
18852
|
+
probeCache.clear();
|
|
18853
|
+
deviceLogins.clear();
|
|
18072
18854
|
keepAliveLast = null;
|
|
18073
18855
|
qoderRetryAt = 0;
|
|
18074
18856
|
core.client = new WorkBuddyUpstreamClient({});
|
|
@@ -18119,11 +18901,7 @@ async function onUnload() {
|
|
|
18119
18901
|
abortWarmups();
|
|
18120
18902
|
const stopping = onServiceStop();
|
|
18121
18903
|
probeCache.clear();
|
|
18122
|
-
|
|
18123
|
-
sourceCreditExpiry.clear();
|
|
18124
|
-
sourceRotation.clear();
|
|
18125
|
-
travelAdoptTried.clear();
|
|
18126
|
-
traeIdentityBlockers.clear();
|
|
18904
|
+
resetSourceActivationState();
|
|
18127
18905
|
gatewayStartFailures.clear();
|
|
18128
18906
|
sourceStartFailures.clear();
|
|
18129
18907
|
sourceGatewayStarts.clear();
|
|
@@ -18211,8 +18989,8 @@ function workbuddyComposerAccounts(region, modelId) {
|
|
|
18211
18989
|
const now = Date.now();
|
|
18212
18990
|
const list = core.pool.list(region);
|
|
18213
18991
|
const available = core.pool.available(now, modelId, region);
|
|
18214
|
-
const preferredId =
|
|
18215
|
-
const next = available.find((account) => account.id === preferredId) ?? core.pool.
|
|
18992
|
+
const preferredId = core.pool.resolvedPreferredId(region);
|
|
18993
|
+
const next = available.find((account) => account.id === preferredId) ?? core.pool.readoutPreview(available);
|
|
18216
18994
|
return list.map((account) => {
|
|
18217
18995
|
const cached = probeCache.get(account.id)?.value?.credits;
|
|
18218
18996
|
return {
|
|
@@ -18753,7 +19531,10 @@ function apply(ctx, config = {}) {
|
|
|
18753
19531
|
getDataPath: async () => {
|
|
18754
19532
|
reportSchemaDegradation(ctx.logger);
|
|
18755
19533
|
const dir = path.join(dshHome(), "dsh-wtq-pool");
|
|
18756
|
-
await fs.mkdir(dir, {
|
|
19534
|
+
await fs.mkdir(dir, {
|
|
19535
|
+
recursive: true,
|
|
19536
|
+
mode: 448
|
|
19537
|
+
});
|
|
18757
19538
|
return dir;
|
|
18758
19539
|
},
|
|
18759
19540
|
onSettingsChanged: (handler) => {
|
|
@@ -18878,7 +19659,7 @@ function apply(ctx, config = {}) {
|
|
|
18878
19659
|
pluginRoot: PLUGIN_ROOT,
|
|
18879
19660
|
invoke: (channel, payload) => onPanelInvoke(channel, payload),
|
|
18880
19661
|
effect: (callback) => webCtx.effect(callback, "dsh-wtq-pool: panel routes"),
|
|
18881
|
-
logger: ctx.logger
|
|
19662
|
+
logger: { warn: (...args) => ctx.logger.warn(...args.map(safeMessage)) }
|
|
18882
19663
|
});
|
|
18883
19664
|
});
|
|
18884
19665
|
ctx.effect(() => async () => {
|
|
@@ -18890,10 +19671,11 @@ function apply(ctx, config = {}) {
|
|
|
18890
19671
|
disposeRegistration = void 0;
|
|
18891
19672
|
if (token !== activationToken) return;
|
|
18892
19673
|
await stopRegisteredService();
|
|
19674
|
+
if (token !== activationToken) return;
|
|
18893
19675
|
await onUnload();
|
|
18894
19676
|
});
|
|
18895
19677
|
onLoad().then(() => {
|
|
18896
|
-
if (!stopped) return startRegisteredService();
|
|
19678
|
+
if (!stopped && token === activationToken) return startRegisteredService();
|
|
18897
19679
|
}).catch((error) => {
|
|
18898
19680
|
if (stopped) return;
|
|
18899
19681
|
ctx.logger.error("dsh-wtq-pool: activation failed", safeMessage(error));
|