dsh-wtq-pool 1.2.2 → 1.2.3
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 -5
- package/README.en.md +11 -9
- package/README.md +8 -6
- package/lib/client.js +11 -5
- package/lib/index.js +2000 -820
- package/package.json +15 -18
- package/renderer/panel.js +11 -10
package/lib/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as path from "node:path";
|
|
2
|
-
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
2
|
+
import { basename, dirname, isAbsolute, join, parse, relative, resolve } from "node:path";
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import { cpus, homedir, hostname, release } from "node:os";
|
|
5
5
|
import * as fs from "node:fs/promises";
|
|
@@ -16,7 +16,7 @@ import { constants, createCipheriv, createDecipheriv, createHash, publicEncrypt,
|
|
|
16
16
|
import * as net from "node:net";
|
|
17
17
|
import { BlockList, isIP } from "node:net";
|
|
18
18
|
import * as fs$1 from "node:fs";
|
|
19
|
-
import { statSync } from "node:fs";
|
|
19
|
+
import { existsSync, lstatSync, realpathSync, statSync } from "node:fs";
|
|
20
20
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
21
21
|
import { execFile, execFileSync, spawn } from "node:child_process";
|
|
22
22
|
//#region src/log.ts
|
|
@@ -143,6 +143,18 @@ function writeOpenAIError(res, status, kind, message) {
|
|
|
143
143
|
} });
|
|
144
144
|
}
|
|
145
145
|
/**
|
|
146
|
+
* The names whose value is a credential on its own, with nothing before it.
|
|
147
|
+
*
|
|
148
|
+
* `authorization` and the `x-…` header names are deliberately absent: their
|
|
149
|
+
* value starts with a scheme word (`Bearer`, `Cloud-IDE-JWT`), and a rule that
|
|
150
|
+
* treated the whole value as the credential would consume the scheme and print
|
|
151
|
+
* the token after it. The scheme rule in `REDACTIONS` covers those, and it runs
|
|
152
|
+
* on text the array scan has already cleared.
|
|
153
|
+
*/
|
|
154
|
+
const BARE_CREDENTIAL_KEYS = "access_?token|refresh_?token|id_?token|auth_?token|oauth_?token|api_?key|secret|token";
|
|
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");
|
|
157
|
+
/**
|
|
146
158
|
* Credential shapes in any text that leaves this process.
|
|
147
159
|
*
|
|
148
160
|
* The log path redacts these in the host entry; this is the client path, which runs
|
|
@@ -168,20 +180,146 @@ function writeOpenAIError(res, status, kind, message) {
|
|
|
168
180
|
* carries) plus `x-machine-id`, `x-device-id` and `x-uid`, the Trae machine,
|
|
169
181
|
* device and account ids. Qoder's identity headers were listed and Trae's were
|
|
170
182
|
* not, which is the drift the sentence above is meant to prevent.
|
|
183
|
+
*
|
|
184
|
+
* Arrays are not regex work: `redactCredentialArrays` handles them before this
|
|
185
|
+
* list runs, because a bracket cannot be matched by pattern without either
|
|
186
|
+
* stopping inside an element or backtracking on a body that never closes.
|
|
171
187
|
*/
|
|
172
188
|
const REDACTIONS = [
|
|
173
|
-
[/\b(Bearer|Cosy-Key|Cosy-Machineid|Cosy-Machinetoken|Cosy-User|Cloud-IDE-JWT|X-Cloudide-Token|X-Ide-Token|X-Refresh-Token|X-Api-Key|X-User-Id|x-device-id|x-machine-id|x-uid)\b([\s:="'\\]{1,6})[A-Za-z0-9_+/.=~-]{8,}/gi, "$1$2[redacted]"],
|
|
189
|
+
[/\b(Bearer|Basic|Digest|Negotiate|NTLM|Cosy-Key|Cosy-Machineid|Cosy-Machinetoken|Cosy-User|Cloud-IDE-JWT|X-Cloudide-Token|X-Ide-Token|X-Refresh-Token|X-Api-Key|X-User-Id|x-device-id|x-machine-id|x-uid)\b([\s:="'\\]{1,6})[A-Za-z0-9_+/.=~-]{8,}/gi, "$1$2[redacted]"],
|
|
190
|
+
[/\b(authorization|proxy-authorization)\b([\s:="'\\]{1,6})(?!(?:Bearer|Basic|Digest|Negotiate|NTLM)\b)(?=[A-Za-z0-9_+/.=~-]{8,})(?=[A-Za-z0-9_+/.=~-]*[0-9])[A-Za-z0-9_+/.=~-]+/gi, "$1$2[redacted]"],
|
|
174
191
|
[/\beyJ[A-Za-z0-9_+/.=-]+(?:\.[A-Za-z0-9_+/.=-]+){0,2}/g, "[redacted token]"],
|
|
175
192
|
[/\b(qoder-oauth-token-)[A-Za-z0-9_+/.=-]+/g, "$1[redacted]"],
|
|
176
193
|
[/\b(rt_)[A-Za-z0-9_+/.=-]+/g, "$1[redacted]"],
|
|
177
|
-
[
|
|
194
|
+
[new RegExp(`((?:\\\\{0,2}["']?)(?:${BARE_CREDENTIAL_KEYS})(?:\\\\{0,2}["']?\\s*[:=]\\s*\\\\{0,2}["']?))[A-Za-z0-9_+/.=-]{6,}`, "gi"), "$1[redacted]"],
|
|
178
195
|
[/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g, "[account]"],
|
|
179
196
|
[/\b[A-Za-z]:[\\/][^\r\n"'<>|]*/g, "[redacted path]"],
|
|
180
197
|
[/\\\\[^\r\n"'<>|]+/g, "[redacted path]"],
|
|
181
198
|
[/(['"])(\/(?!\/)[^'"\r\n]+)\1/g, "$1[redacted path]$1"],
|
|
182
|
-
[/(?<![\w./])\/(?:[\w.@-]+(?: [\w.@-]+)*\/)+[\w.@-]+(?: [\w.@-]+)*\.[A-Za-z][\w]*/g, "[redacted path]"]
|
|
199
|
+
[/(?<![\w./])\/(?:[\w.@-]+(?: [\w.@-]+)*\/)+[\w.@-]+(?: [\w.@-]+)*\.[A-Za-z][\w]*/g, "[redacted path]"],
|
|
200
|
+
[/(?<![\w./])(?:\/[\w.@-]+)*\/(?:\.trae|\.trae-cn|\.workbuddy|\.qoder)(?:\/[\w.@-]+)*\/?[^\s"'<>|]*/g, "[redacted path]"]
|
|
183
201
|
];
|
|
184
202
|
/**
|
|
203
|
+
* How far past an opening bracket the scan may look for its closer.
|
|
204
|
+
*
|
|
205
|
+
* A credential array is a handful of elements, but an echo can carry a full JWT
|
|
206
|
+
* (about 1-4 KB) as one element, so the budget has to be generous. It is spent
|
|
207
|
+
* per opening bracket, not per byte of input, so the pass stays linear in the
|
|
208
|
+
* text: what it bounds is how much work one unterminated bracket can cost.
|
|
209
|
+
*/
|
|
210
|
+
const ARRAY_SCAN_LIMIT = 65536;
|
|
211
|
+
/**
|
|
212
|
+
* The index just past the bracket that closes the array starting at `start`.
|
|
213
|
+
*
|
|
214
|
+
* A hand-written scan, not a regular expression, because the bracket cannot be
|
|
215
|
+
* matched by pattern alone: an element may contain `]`, the element may itself
|
|
216
|
+
* be an array, and the quoted form of either may contain a bracket, a quote or
|
|
217
|
+
* an escaped quote. Every expression that tried to state this - `[^\]]*` for
|
|
218
|
+
* the array, a quoted alternative with an optional closing quote - either
|
|
219
|
+
* stopped at a `]` inside an element (`{"x-api-key":["a]b"]}` printed
|
|
220
|
+
* `[redacted]b"]`, the tail of a live credential) or backtracked exponentially
|
|
221
|
+
* on a body that never closes (`{"authorization":` followed by a run of `["`
|
|
222
|
+
* hung the process). The scan walks once, tracks one quote at a time, counts
|
|
223
|
+
* the nested openers, and skips the character after a backslash, so it stays
|
|
224
|
+
* linear and cannot be made to spin.
|
|
225
|
+
*
|
|
226
|
+
* The scan crosses line breaks, because an upstream that prints the request it
|
|
227
|
+
* was sent with `JSON.stringify(body, null, 2)` writes one element per line and
|
|
228
|
+
* cutting at the first break skipped the whole array: a token echoed that way
|
|
229
|
+
* reached the client untouched.
|
|
230
|
+
*
|
|
231
|
+
* What keeps its cost linear is not a line cut but the budget being *consumed*:
|
|
232
|
+
* when the scan gives up, redaction replaces the whole span it examined, so the
|
|
233
|
+
* next bracket starts after that span and no byte is scanned twice.
|
|
234
|
+
*
|
|
235
|
+
* A backslash escapes outside a quoted run too, because the echo this has to
|
|
236
|
+
* survive is a request nested inside another JSON document one escape layer
|
|
237
|
+
* down: there a quote is spelled `\"`, and reading it as an opener ran the scan
|
|
238
|
+
* past the array's real end to the end of the line, deleting the fields after
|
|
239
|
+
* it. One escaping level is what that echo adds; the plugin never produces two.
|
|
240
|
+
*/
|
|
241
|
+
function arrayEnd(text, start) {
|
|
242
|
+
const limit = Math.min(text.length, start + ARRAY_SCAN_LIMIT);
|
|
243
|
+
let quote = "";
|
|
244
|
+
let depth = 1;
|
|
245
|
+
for (let i = start; i < limit; i += 1) {
|
|
246
|
+
const ch = text[i];
|
|
247
|
+
if (ch === "\\") {
|
|
248
|
+
i += 1;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (quote !== "") {
|
|
252
|
+
if (ch === quote) quote = "";
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (ch === "\"" || ch === "'") quote = ch;
|
|
256
|
+
else if (ch === "[") depth += 1;
|
|
257
|
+
else if (ch === "]") {
|
|
258
|
+
depth -= 1;
|
|
259
|
+
if (depth === 0) return i + 1;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return -1;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Where a span the scan gave up on ends.
|
|
266
|
+
*
|
|
267
|
+
* An array whose closer was not found inside the budget is still a credential,
|
|
268
|
+
* so redaction swallows exactly what the scan looked at - no more, which would
|
|
269
|
+
* delete the diagnostic half of the body, and no less, which would print the
|
|
270
|
+
* tail of a truncated token.
|
|
271
|
+
*
|
|
272
|
+
* The span ends at the first line break past the budget, so a body that stops
|
|
273
|
+
* mid-token loses its partial line too rather than printing what is left of it.
|
|
274
|
+
* A single line longer than the whole budget has no break to find inside it and
|
|
275
|
+
* is consumed to its end.
|
|
276
|
+
*/
|
|
277
|
+
function scanGiveUpEnd(text, start) {
|
|
278
|
+
const limit = Math.min(text.length, start + ARRAY_SCAN_LIMIT);
|
|
279
|
+
for (let i = limit; i < text.length; i += 1) if (text[i] === "\n" || text[i] === "\r") return i + 1;
|
|
280
|
+
return text.length;
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Replace every credential array with a placeholder, keeping its key.
|
|
284
|
+
*
|
|
285
|
+
* A whole array, because each element is a credential and a rule that replaced
|
|
286
|
+
* only the ones it recognised as token-shaped would leave the numeric ones and
|
|
287
|
+
* the account ids readable.
|
|
288
|
+
*
|
|
289
|
+
* An array whose closer is never found loses everything the scan looked at,
|
|
290
|
+
* plus the partial line it stopped in: that text is still credential material -
|
|
291
|
+
* a truncated echo is the case where the body was cut off mid-token - so
|
|
292
|
+
* leaving it in place would publish it.
|
|
293
|
+
*
|
|
294
|
+
* A bracket with nothing after it at all is a bracket, not a value, and is left
|
|
295
|
+
* alone.
|
|
296
|
+
*/
|
|
297
|
+
function redactCredentialArrays(text) {
|
|
298
|
+
let out = "";
|
|
299
|
+
let cursor = 0;
|
|
300
|
+
CREDENTIAL_ARRAY_OPEN.lastIndex = 0;
|
|
301
|
+
for (let match = CREDENTIAL_ARRAY_OPEN.exec(text); match !== null; match = CREDENTIAL_ARRAY_OPEN.exec(text)) {
|
|
302
|
+
const key = match[1];
|
|
303
|
+
const bodyStart = match.index + match[0].length;
|
|
304
|
+
const closed = arrayEnd(text, bodyStart);
|
|
305
|
+
if (closed === -1) {
|
|
306
|
+
const stop = scanGiveUpEnd(text, bodyStart);
|
|
307
|
+
if (stop === bodyStart) {
|
|
308
|
+
CREDENTIAL_ARRAY_OPEN.lastIndex = bodyStart;
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
out += text.slice(cursor, match.index) + key + "[redacted]";
|
|
312
|
+
cursor = stop;
|
|
313
|
+
CREDENTIAL_ARRAY_OPEN.lastIndex = stop;
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
out += text.slice(cursor, match.index) + key + "[redacted]";
|
|
317
|
+
cursor = closed;
|
|
318
|
+
CREDENTIAL_ARRAY_OPEN.lastIndex = closed;
|
|
319
|
+
}
|
|
320
|
+
return cursor === 0 ? text : out + text.slice(cursor);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
185
323
|
* Strip credential shapes out of text bound for a client.
|
|
186
324
|
*
|
|
187
325
|
* Applied at the one place every gateway error passes through, so a new caller
|
|
@@ -189,6 +327,7 @@ const REDACTIONS = [
|
|
|
189
327
|
*/
|
|
190
328
|
function redactSecrets(text) {
|
|
191
329
|
let out = typeof text === "string" ? text : String(text);
|
|
330
|
+
out = redactCredentialArrays(out);
|
|
192
331
|
for (const [pattern, replacement] of REDACTIONS) out = out.replace(pattern, replacement);
|
|
193
332
|
return out;
|
|
194
333
|
}
|
|
@@ -937,7 +1076,21 @@ function panelAsset(pluginRoot, name) {
|
|
|
937
1076
|
const dir = path.join(pluginRoot, "renderer");
|
|
938
1077
|
const full = path.join(dir, name);
|
|
939
1078
|
if (!full.startsWith(dir + path.sep)) return void 0;
|
|
940
|
-
|
|
1079
|
+
try {
|
|
1080
|
+
const packageRoot = fs$1.realpathSync(pluginRoot);
|
|
1081
|
+
const rendererRoot = fs$1.realpathSync(dir);
|
|
1082
|
+
const rendererInsidePackage = path.relative(packageRoot, rendererRoot);
|
|
1083
|
+
const rendererEscapesPackage = rendererInsidePackage === ".." || rendererInsidePackage.startsWith(`..${path.sep}`);
|
|
1084
|
+
if (rendererInsidePackage === "" || rendererEscapesPackage || path.isAbsolute(rendererInsidePackage)) return void 0;
|
|
1085
|
+
const resolved = fs$1.realpathSync(full);
|
|
1086
|
+
const insideRenderer = path.relative(rendererRoot, resolved);
|
|
1087
|
+
const assetEscapesRenderer = insideRenderer === ".." || insideRenderer.startsWith(`..${path.sep}`);
|
|
1088
|
+
if (insideRenderer === "" || assetEscapesRenderer || path.isAbsolute(insideRenderer)) return void 0;
|
|
1089
|
+
if (!fs$1.statSync(resolved).isFile()) return void 0;
|
|
1090
|
+
return resolved;
|
|
1091
|
+
} catch {
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
941
1094
|
}
|
|
942
1095
|
/**
|
|
943
1096
|
* The panel page.
|
|
@@ -1084,11 +1237,6 @@ const ROW_ID = "llm-dsh-xdpool";
|
|
|
1084
1237
|
* decision - the configured hours, the slot id, what is due right now - without
|
|
1085
1238
|
* a clock to fake or a settings file to write.
|
|
1086
1239
|
*
|
|
1087
|
-
* The cap on the configured hours is defensive rather than load-bearing - the
|
|
1088
|
-
* filter below already leaves at most 24 distinct values in 0..23 - but a host
|
|
1089
|
-
* entry that skipped it would disagree with this one about which hours are in
|
|
1090
|
-
* force, so the rule lives in one place.
|
|
1091
|
-
*
|
|
1092
1240
|
* @module dsh-wtq-pool/checkin-time
|
|
1093
1241
|
*/
|
|
1094
1242
|
/** The zone the daily check-in hours are read in. */
|
|
@@ -1146,10 +1294,10 @@ function checkinSlotId(day, hour) {
|
|
|
1146
1294
|
/**
|
|
1147
1295
|
* The slot to collect right now, or undefined when nothing is due.
|
|
1148
1296
|
*
|
|
1149
|
-
* An hour
|
|
1150
|
-
*
|
|
1151
|
-
*
|
|
1152
|
-
*
|
|
1297
|
+
* An hour stays due until its slot is consumed, so a machine that slept through
|
|
1298
|
+
* 09:00 still collects when it wakes instead of waiting for tomorrow. The
|
|
1299
|
+
* earliest unconsumed hour wins, so two configured hours still give two passes
|
|
1300
|
+
* a day.
|
|
1153
1301
|
*/
|
|
1154
1302
|
function dueCheckinSlot(now, hours, fired) {
|
|
1155
1303
|
const { day, hour } = zonedDayHour(now);
|
|
@@ -2830,17 +2978,86 @@ function openEncryptedField(field, key) {
|
|
|
2830
2978
|
function cleanIconPath(raw) {
|
|
2831
2979
|
return raw.replace(/^"/u, "").replace(/",-?\d+$/u, "").replace(/,-?\d+$/u, "").trim();
|
|
2832
2980
|
}
|
|
2981
|
+
/** Reject direct UNC and device paths before checking a candidate. */
|
|
2982
|
+
function localWindowsPath(candidate) {
|
|
2983
|
+
return /^[A-Za-z]:[\\/]/u.test(candidate);
|
|
2984
|
+
}
|
|
2833
2985
|
/**
|
|
2834
|
-
*
|
|
2986
|
+
* Keep only candidates on fixed local volumes.
|
|
2835
2987
|
*
|
|
2836
|
-
*
|
|
2837
|
-
*
|
|
2838
|
-
*
|
|
2839
|
-
* user's NTLM response. Only absolute drive paths are considered, and every
|
|
2840
|
-
* stat and spawn goes through the same filter.
|
|
2988
|
+
* A mapped drive still looks like `Z:\...` to Node, and even `lstatSync` can
|
|
2989
|
+
* contact its SMB server. Windows exposes the volume type without opening a
|
|
2990
|
+
* file, so every candidate is filtered before any path component is inspected.
|
|
2841
2991
|
*/
|
|
2842
|
-
function
|
|
2843
|
-
|
|
2992
|
+
function fixedWindowsPaths(candidates) {
|
|
2993
|
+
const local = candidates.filter((candidate) => localWindowsPath(candidate)).map((candidate) => resolve(candidate));
|
|
2994
|
+
if (local.length === 0) return [];
|
|
2995
|
+
const anchor = systemRootOf(process.env) ?? process.env["SystemRoot"] ?? process.env["windir"];
|
|
2996
|
+
if (anchor === void 0) return local;
|
|
2997
|
+
const systemRoot = parse(resolve(anchor)).root.toUpperCase();
|
|
2998
|
+
const elsewhere = [...new Set(local.map((candidate) => parse(candidate).root.toUpperCase()).filter((candidateRoot) => candidateRoot !== "" && candidateRoot !== systemRoot))];
|
|
2999
|
+
const fixed = new Set(elsewhere.length === 0 ? [] : scanFixedRoots(elsewhere));
|
|
3000
|
+
return local.filter((candidate) => {
|
|
3001
|
+
const candidateRoot = parse(candidate).root.toUpperCase();
|
|
3002
|
+
return candidateRoot === systemRoot || candidateRoot !== "" && fixed.has(candidateRoot);
|
|
3003
|
+
});
|
|
3004
|
+
}
|
|
3005
|
+
/** Which of `roots` are fixed drives, asked of PowerShell in one spawn. */
|
|
3006
|
+
function scanFixedRoots(roots) {
|
|
3007
|
+
const interpreter = scanInterpreter(process.env);
|
|
3008
|
+
if (interpreter === void 0) return [];
|
|
3009
|
+
const script = [
|
|
3010
|
+
"$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules')",
|
|
3011
|
+
"$ErrorActionPreference='SilentlyContinue'",
|
|
3012
|
+
"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}",
|
|
3013
|
+
`$roots=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(JSON.stringify(roots), "utf8").toString("base64")}')) | ConvertFrom-Json`,
|
|
3014
|
+
"$out = foreach ($root in @($roots)) {",
|
|
3015
|
+
" try {",
|
|
3016
|
+
" if ([IO.DriveInfo]::new([string]$root).DriveType -eq [IO.DriveType]::Fixed) { [string]$root }",
|
|
3017
|
+
" } catch {}",
|
|
3018
|
+
"}",
|
|
3019
|
+
"ConvertTo-Json -InputObject @($out) -Compress"
|
|
3020
|
+
].join("\n");
|
|
3021
|
+
let parsed;
|
|
3022
|
+
try {
|
|
3023
|
+
const stdout = execFileSync(interpreter, [
|
|
3024
|
+
"-NoProfile",
|
|
3025
|
+
"-NonInteractive",
|
|
3026
|
+
"-ExecutionPolicy",
|
|
3027
|
+
"Bypass",
|
|
3028
|
+
"-Command",
|
|
3029
|
+
script
|
|
3030
|
+
], {
|
|
3031
|
+
encoding: "utf8",
|
|
3032
|
+
timeout: 1e4,
|
|
3033
|
+
windowsHide: true,
|
|
3034
|
+
maxBuffer: 65536,
|
|
3035
|
+
env: signatureScanEnv(),
|
|
3036
|
+
cwd: dirname(dirname(dirname(interpreter)))
|
|
3037
|
+
});
|
|
3038
|
+
parsed = JSON.parse(stdout);
|
|
3039
|
+
} catch {
|
|
3040
|
+
return [];
|
|
3041
|
+
}
|
|
3042
|
+
return (Array.isArray(parsed) ? parsed : [parsed]).filter((entry) => typeof entry === "string").map((entry) => entry.toUpperCase());
|
|
3043
|
+
}
|
|
3044
|
+
/** Walk every Windows path component without following a reparse point. */
|
|
3045
|
+
function windowsPathHasReparsePoint(candidate) {
|
|
3046
|
+
if (process.platform !== "win32") return false;
|
|
3047
|
+
const normalized = resolve(candidate);
|
|
3048
|
+
const root = parse(normalized).root;
|
|
3049
|
+
let current = root;
|
|
3050
|
+
for (const part of normalized.slice(root.length).split(/[\\/]+/u).filter(Boolean)) {
|
|
3051
|
+
current = join(current, part);
|
|
3052
|
+
try {
|
|
3053
|
+
const entry = lstatSync(current, { throwIfNoEntry: false });
|
|
3054
|
+
if (entry === void 0) return true;
|
|
3055
|
+
if (entry.isSymbolicLink()) return true;
|
|
3056
|
+
} catch {
|
|
3057
|
+
return true;
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
return false;
|
|
2844
3061
|
}
|
|
2845
3062
|
function windowsRegistryAppPaths() {
|
|
2846
3063
|
if (process.platform !== "win32") return [];
|
|
@@ -2853,58 +3070,31 @@ function windowsRegistryAppPaths() {
|
|
|
2853
3070
|
registryScannedAtMs = Date.now();
|
|
2854
3071
|
return registryAppPaths;
|
|
2855
3072
|
}
|
|
2856
|
-
/**
|
|
2857
|
-
* The Windows directory, whichever of the two variables holds it.
|
|
2858
|
-
*
|
|
2859
|
-
* Both are read here rather than only in `scanInterpreter`, because the module
|
|
2860
|
-
* path and the interpreter have to come from the same place: pinning the
|
|
2861
|
-
* absolute path from `windir` while the 5.1 module directory was skipped for a
|
|
2862
|
-
* missing `SystemRoot` left `Get-AuthenticodeSignature` unable to load for every
|
|
2863
|
-
* candidate, which is the failure this pair exists to avoid.
|
|
2864
|
-
*/
|
|
3073
|
+
/** Resolve the OS directory without trusting inherited Windows environment variables. */
|
|
2865
3074
|
function systemRootOf(env) {
|
|
3075
|
+
if (process.platform === "win32") try {
|
|
3076
|
+
return realpathSync.native("\\\\?\\GLOBALROOT\\SystemRoot");
|
|
3077
|
+
} catch {
|
|
3078
|
+
return;
|
|
3079
|
+
}
|
|
2866
3080
|
const value = env["SystemRoot"]?.trim() || env["windir"]?.trim();
|
|
2867
3081
|
return value === void 0 || value === "" ? void 0 : value;
|
|
2868
3082
|
}
|
|
2869
|
-
/**
|
|
2870
|
-
* The environment the signature scan runs in.
|
|
2871
|
-
*
|
|
2872
|
-
* `powershell` is Windows PowerShell 5.1, and it resolves
|
|
2873
|
-
* `Microsoft.PowerShell.Security` by walking `PSModulePath` in order. Any machine
|
|
2874
|
-
* with a Store-installed PowerShell 7 carries that build's Modules directory
|
|
2875
|
-
* ahead of the system one, because the Store install prepends it to the variable
|
|
2876
|
-
* the desktop host inherited. 5.1 then binds the 7 build's copy of the module
|
|
2877
|
-
* first and the import dies on a type-data conflict, so
|
|
2878
|
-
* `Get-AuthenticodeSignature` throws for every candidate. The scan's own catch
|
|
2879
|
-
* swallows that, the policy function is handed an empty status, and the at-rest
|
|
2880
|
-
* key reads as "no WorkBuddy executable found" on a machine holding two signed
|
|
2881
|
-
* installs. Putting the 5.1 directory first makes the right copy win.
|
|
2882
|
-
*
|
|
2883
|
-
* The directory is derived from `SystemRoot` rather than written out, and the
|
|
2884
|
-
* rest of the ambient path is left alone so a user's own modules still resolve.
|
|
2885
|
-
* Applying it twice is a no-op, so the answer stays one directory long however
|
|
2886
|
-
* often it is built.
|
|
2887
|
-
*/
|
|
3083
|
+
/** Do not pass user-controlled CLR, module, or executable search paths to PowerShell. */
|
|
2888
3084
|
function signatureScanEnv(env = process.env) {
|
|
2889
3085
|
const systemRoot = systemRootOf(env);
|
|
2890
|
-
|
|
2891
|
-
const modules = systemRoot === void 0 ? void 0 : join(systemRoot, "system32", "WindowsPowerShell", "v1.0", "Modules");
|
|
2892
|
-
if (modules === void 0) return { ...env };
|
|
2893
|
-
if (ambient === modules || ambient?.startsWith(`${modules};`) === true) return { ...env };
|
|
3086
|
+
if (systemRoot === void 0) return {};
|
|
2894
3087
|
return {
|
|
2895
|
-
|
|
2896
|
-
|
|
3088
|
+
SystemRoot: systemRoot,
|
|
3089
|
+
windir: systemRoot,
|
|
3090
|
+
PATH: join(systemRoot, "System32"),
|
|
3091
|
+
PSModulePath: join(systemRoot, "system32", "WindowsPowerShell", "v1.0", "Modules")
|
|
2897
3092
|
};
|
|
2898
3093
|
}
|
|
2899
3094
|
/**
|
|
2900
3095
|
* The interpreter to run the scan with, by absolute path.
|
|
2901
3096
|
*
|
|
2902
|
-
*
|
|
2903
|
-
* scan exists at all: a user-level directory is on the default `PATH`
|
|
2904
|
-
* (`%LOCALAPPDATA%\Microsoft\WindowsApps`), so a bare `powershell` would let
|
|
2905
|
-
* whatever sits there be spawned inside a process holding every WorkBuddy token.
|
|
2906
|
-
* Neither variable set answers `undefined`, and the caller treats that as "no
|
|
2907
|
-
* scan" rather than guessing a path.
|
|
3097
|
+
* The OS directory comes from the Windows object manager, not an inherited path.
|
|
2908
3098
|
*/
|
|
2909
3099
|
function scanInterpreter(env) {
|
|
2910
3100
|
const systemRoot = systemRootOf(env);
|
|
@@ -2916,10 +3106,8 @@ function scanInterpreter(env) {
|
|
|
2916
3106
|
*
|
|
2917
3107
|
* The scan reads `DisplayName`, `DisplayIcon` and `InstallLocation` out of the
|
|
2918
3108
|
* user's own uninstall keys, which means any process running as the user can add
|
|
2919
|
-
* one. It only enumerates here:
|
|
2920
|
-
* and signature-checked in Node
|
|
2921
|
-
* signature read in PowerShell would touch a planted UNC path first and leak an
|
|
2922
|
-
* NTLM response to the host it names.
|
|
3109
|
+
* one. It only enumerates here: directly specified UNC and device paths are
|
|
3110
|
+
* filtered before candidates are stat'ed and signature-checked in Node.
|
|
2923
3111
|
*
|
|
2924
3112
|
* PowerShell does the part only it can do: enumerate the keys and clean the
|
|
2925
3113
|
* resource index and quotes off `DisplayIcon`. The decision is
|
|
@@ -2930,6 +3118,7 @@ function scanInterpreter(env) {
|
|
|
2930
3118
|
function readRegistryAppPaths() {
|
|
2931
3119
|
const script = [
|
|
2932
3120
|
"$ErrorActionPreference='SilentlyContinue'",
|
|
3121
|
+
"$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules')",
|
|
2933
3122
|
"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}",
|
|
2934
3123
|
"function Clean([string]$v) {",
|
|
2935
3124
|
" $v = $v.Trim()",
|
|
@@ -2970,7 +3159,8 @@ function readRegistryAppPaths() {
|
|
|
2970
3159
|
timeout: 2e4,
|
|
2971
3160
|
windowsHide: true,
|
|
2972
3161
|
maxBuffer: 8388608,
|
|
2973
|
-
env: signatureScanEnv()
|
|
3162
|
+
env: signatureScanEnv(),
|
|
3163
|
+
cwd: dirname(dirname(dirname(interpreter)))
|
|
2974
3164
|
});
|
|
2975
3165
|
} catch {
|
|
2976
3166
|
return [];
|
|
@@ -2991,43 +3181,17 @@ function readRegistryAppPaths() {
|
|
|
2991
3181
|
}
|
|
2992
3182
|
return out;
|
|
2993
3183
|
}
|
|
2994
|
-
/**
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
* Exported so the policy can be tested without a registry to plant a key in: the
|
|
2998
|
-
* PowerShell half is not unit-testable, and this half is where the decision
|
|
2999
|
-
* actually lives.
|
|
3000
|
-
*
|
|
3001
|
-
* `Valid` means the chain resolved to a trusted root. A user process cannot
|
|
3002
|
-
* forge the vendor's signature, but it can trust a certificate of its own in the
|
|
3003
|
-
* current user's root store without elevation, so this check raises the bar
|
|
3004
|
-
* rather than proving the file is the vendor's. It still rejects an unsigned
|
|
3005
|
-
* planted executable, and every cached registry path is checked again before it
|
|
3006
|
-
* is run.
|
|
3007
|
-
*
|
|
3008
|
-
* The publisher is deliberately not pinned. The plugin is a third-party build and
|
|
3009
|
-
* the vendor can change its signing certificate; a pinned name would turn that
|
|
3010
|
-
* into a silent loss of the at-rest key on every machine at once, which is a
|
|
3011
|
-
* worse failure than the one being prevented.
|
|
3012
|
-
*
|
|
3013
|
-
* An unknown status is refused, not assumed: `HashMismatch`, `NotSigned` and a
|
|
3014
|
-
* signature PowerShell could not read at all all mean the file is not the
|
|
3015
|
-
* vendor's, and the caller answers "no key" rather than running something.
|
|
3016
|
-
*/
|
|
3017
|
-
function signatureAccepts(status, signer) {
|
|
3018
|
-
return status === "Valid" && signer !== void 0 && signer.trim() !== "";
|
|
3184
|
+
/** Trust the vendor's signing keys, not a subject name or a user-trusted root. */
|
|
3185
|
+
function signatureAccepts(status, publicKeyHash, elevated) {
|
|
3186
|
+
return status === "Valid" && elevated === false && ["2F95C8391B09328BC42D131C50CC7B4E06F9E2A7B1E3624E14C9070A1BE9CC97", "307ECCDC80B73FF1662464E2591BF027124F11175039423BA2FEC1CDE64DB212"].includes(publicKeyHash?.toUpperCase() ?? "");
|
|
3019
3187
|
}
|
|
3020
3188
|
/** Why the last signature scan could not produce an answer, if it could not. */
|
|
3021
3189
|
let signatureScanFailure = "";
|
|
3022
3190
|
/**
|
|
3023
3191
|
* The candidates whose Authenticode signature is valid.
|
|
3024
3192
|
*
|
|
3025
|
-
*
|
|
3026
|
-
*
|
|
3027
|
-
* as the user can write `%LOCALAPPDATA%\\Programs\\WorkBuddy\\WorkBuddy.exe`; when
|
|
3028
|
-
* the host runs elevated, spawning that file would hand it the plugin's whole
|
|
3029
|
-
* environment and every WorkBuddy token. Every path is checked here, and the
|
|
3030
|
-
* registry result is passed through the same check before it is spawned.
|
|
3193
|
+
* A signed file can still be replaced between inspection and execution. Refuse
|
|
3194
|
+
* to run any candidate from an elevated process, including user-writable paths.
|
|
3031
3195
|
*/
|
|
3032
3196
|
async function signedExecutables(candidates) {
|
|
3033
3197
|
if (process.platform !== "win32" || candidates.length === 0) return candidates;
|
|
@@ -3038,20 +3202,32 @@ async function signedExecutables(candidates) {
|
|
|
3038
3202
|
return [];
|
|
3039
3203
|
}
|
|
3040
3204
|
const script = [
|
|
3041
|
-
"$ErrorActionPreference='
|
|
3205
|
+
"$ErrorActionPreference='Stop'",
|
|
3206
|
+
"$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules')",
|
|
3042
3207
|
"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}",
|
|
3208
|
+
"try {",
|
|
3209
|
+
" $principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())",
|
|
3210
|
+
" $elevated = $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)",
|
|
3211
|
+
"} catch { ConvertTo-Json -InputObject @{ elevated = $null; entries = @() } -Compress; exit }",
|
|
3212
|
+
"if ($elevated) { ConvertTo-Json -InputObject @{ elevated = $true; entries = @() } -Compress; exit }",
|
|
3213
|
+
"$ErrorActionPreference='SilentlyContinue'",
|
|
3043
3214
|
`$paths = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(JSON.stringify(candidates), "utf8").toString("base64")}')) | ConvertFrom-Json`,
|
|
3044
3215
|
"$out = foreach ($p in @($paths)) {",
|
|
3045
3216
|
" if ([string]::IsNullOrWhiteSpace([string]$p)) { continue }",
|
|
3046
3217
|
" $s = $null",
|
|
3047
3218
|
" try { $s = Get-AuthenticodeSignature -LiteralPath ([string]$p) } catch { $s = $null }",
|
|
3219
|
+
" $keyHash = \"\"",
|
|
3220
|
+
" if ($s -ne $null -and $s.SignerCertificate -ne $null) {",
|
|
3221
|
+
" $sha = [System.Security.Cryptography.SHA256]::Create()",
|
|
3222
|
+
" try { $keyHash = [BitConverter]::ToString($sha.ComputeHash($s.SignerCertificate.GetPublicKey())).Replace(\"-\", \"\") } finally { $sha.Dispose() }",
|
|
3223
|
+
" }",
|
|
3048
3224
|
" [pscustomobject]@{",
|
|
3049
3225
|
" path = [string]$p",
|
|
3050
3226
|
" status = if ($s -ne $null) { [string]$s.Status } else { \"\" }",
|
|
3051
|
-
"
|
|
3227
|
+
" publicKeyHash = $keyHash",
|
|
3052
3228
|
" }",
|
|
3053
3229
|
"}",
|
|
3054
|
-
"ConvertTo-Json -InputObject @($out) -Compress"
|
|
3230
|
+
"ConvertTo-Json -InputObject @{ elevated = $false; entries = @($out) } -Compress -Depth 3"
|
|
3055
3231
|
].join("\n");
|
|
3056
3232
|
let stdout;
|
|
3057
3233
|
try {
|
|
@@ -3068,7 +3244,8 @@ async function signedExecutables(candidates) {
|
|
|
3068
3244
|
timeout: 2e4,
|
|
3069
3245
|
windowsHide: true,
|
|
3070
3246
|
maxBuffer: 8388608,
|
|
3071
|
-
env: signatureScanEnv()
|
|
3247
|
+
env: signatureScanEnv(),
|
|
3248
|
+
cwd: dirname(dirname(dirname(interpreter)))
|
|
3072
3249
|
}, (error, output) => {
|
|
3073
3250
|
if (error !== null) reject(error);
|
|
3074
3251
|
else resolve(output);
|
|
@@ -3085,25 +3262,35 @@ async function signedExecutables(candidates) {
|
|
|
3085
3262
|
signatureScanFailure = "the signature check returned no readable answer";
|
|
3086
3263
|
return [];
|
|
3087
3264
|
}
|
|
3088
|
-
|
|
3265
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
3266
|
+
signatureScanFailure = "the signature check returned no readable answer";
|
|
3267
|
+
return [];
|
|
3268
|
+
}
|
|
3269
|
+
const result = parsed;
|
|
3270
|
+
if (result["elevated"] !== false) {
|
|
3271
|
+
signatureScanFailure = result["elevated"] === true ? "WorkBuddy key retrieval is unavailable when the host runs elevated; restart it as a regular user" : "the host elevation could not be determined; WorkBuddy key retrieval was skipped";
|
|
3272
|
+
return [];
|
|
3273
|
+
}
|
|
3274
|
+
const entries = Array.isArray(result["entries"]) ? result["entries"] : [];
|
|
3089
3275
|
const accepted = [];
|
|
3090
3276
|
for (const entry of entries) {
|
|
3091
3277
|
if (entry === null || typeof entry !== "object") continue;
|
|
3092
3278
|
const record = entry;
|
|
3093
3279
|
const file = record["path"];
|
|
3094
3280
|
const status = record["status"];
|
|
3095
|
-
const
|
|
3281
|
+
const publicKeyHash = record["publicKeyHash"];
|
|
3096
3282
|
if (typeof file !== "string" || file === "") continue;
|
|
3097
|
-
if (!signatureAccepts(typeof status === "string" ? status : void 0, typeof
|
|
3283
|
+
if (!signatureAccepts(typeof status === "string" ? status : void 0, typeof publicKeyHash === "string" ? publicKeyHash : void 0, false)) continue;
|
|
3098
3284
|
accepted.push(file);
|
|
3099
3285
|
}
|
|
3100
3286
|
return accepted;
|
|
3101
3287
|
}
|
|
3102
3288
|
function statExecutables(candidates) {
|
|
3289
|
+
const localCandidates = process.platform === "win32" ? fixedWindowsPaths(candidates) : candidates;
|
|
3103
3290
|
const files = [];
|
|
3104
|
-
for (const candidate of
|
|
3291
|
+
for (const candidate of localCandidates) {
|
|
3105
3292
|
if (candidate === "") continue;
|
|
3106
|
-
if (process.platform === "win32" &&
|
|
3293
|
+
if (process.platform === "win32" && windowsPathHasReparsePoint(candidate)) continue;
|
|
3107
3294
|
try {
|
|
3108
3295
|
if (statSync(candidate, { throwIfNoEntry: false })?.isFile() === true) files.push(candidate);
|
|
3109
3296
|
} catch {}
|
|
@@ -3111,6 +3298,16 @@ function statExecutables(candidates) {
|
|
|
3111
3298
|
return files;
|
|
3112
3299
|
}
|
|
3113
3300
|
async function executableCandidates(env = process.env) {
|
|
3301
|
+
signatureScanFailure = "";
|
|
3302
|
+
if (process.platform !== "win32") try {
|
|
3303
|
+
if (typeof process.geteuid !== "function" || process.geteuid() === 0) {
|
|
3304
|
+
signatureScanFailure = "WorkBuddy key retrieval requires a non-root host";
|
|
3305
|
+
return [];
|
|
3306
|
+
}
|
|
3307
|
+
} catch {
|
|
3308
|
+
signatureScanFailure = "the host privileges could not be determined; WorkBuddy key retrieval was skipped";
|
|
3309
|
+
return [];
|
|
3310
|
+
}
|
|
3114
3311
|
const override = env[WORKBUDDY_APP_EXECUTABLE_ENV]?.trim();
|
|
3115
3312
|
const known = override === void 0 ? [] : [override];
|
|
3116
3313
|
if (process.platform === "win32") {
|
|
@@ -3136,12 +3333,54 @@ async function executableCandidates(env = process.env) {
|
|
|
3136
3333
|
return signedExecutables(statExecutables(windowsRegistryAppPaths()));
|
|
3137
3334
|
}
|
|
3138
3335
|
function fetchAtRestKeyPayload(executable) {
|
|
3336
|
+
const root = process.platform === "win32" ? systemRootOf(process.env) : "/";
|
|
3337
|
+
if (root === void 0) return Promise.reject(/* @__PURE__ */ new Error("workbuddy: the system directory is unavailable"));
|
|
3338
|
+
const allowed = process.platform === "win32" ? [
|
|
3339
|
+
"SystemRoot",
|
|
3340
|
+
"windir",
|
|
3341
|
+
"SystemDrive",
|
|
3342
|
+
"TEMP",
|
|
3343
|
+
"TMP",
|
|
3344
|
+
"USERPROFILE",
|
|
3345
|
+
"HOMEDRIVE",
|
|
3346
|
+
"HOMEPATH",
|
|
3347
|
+
"APPDATA",
|
|
3348
|
+
"LOCALAPPDATA"
|
|
3349
|
+
] : [
|
|
3350
|
+
"HOME",
|
|
3351
|
+
"USER",
|
|
3352
|
+
"LOGNAME",
|
|
3353
|
+
"TMPDIR",
|
|
3354
|
+
"TMP",
|
|
3355
|
+
"TEMP",
|
|
3356
|
+
"LANG",
|
|
3357
|
+
"LC_ALL",
|
|
3358
|
+
"LC_CTYPE"
|
|
3359
|
+
];
|
|
3360
|
+
const names = new Set(allowed.map((name) => name.toUpperCase()));
|
|
3361
|
+
const trustedWindowsNames = /* @__PURE__ */ new Set([
|
|
3362
|
+
"SYSTEMROOT",
|
|
3363
|
+
"WINDIR",
|
|
3364
|
+
"SYSTEMDRIVE",
|
|
3365
|
+
"PATH",
|
|
3366
|
+
"PSMODULEPATH"
|
|
3367
|
+
]);
|
|
3368
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => {
|
|
3369
|
+
const normalized = name.toUpperCase();
|
|
3370
|
+
return names.has(normalized) && (process.platform !== "win32" || !trustedWindowsNames.has(normalized));
|
|
3371
|
+
}));
|
|
3372
|
+
if (process.platform === "win32") {
|
|
3373
|
+
env["SystemRoot"] = root;
|
|
3374
|
+
env["windir"] = root;
|
|
3375
|
+
if (/^[A-Za-z]:\\/.test(root)) env["SystemDrive"] = root.slice(0, 2);
|
|
3376
|
+
env["PATH"] = join(root, "System32");
|
|
3377
|
+
env["PSModulePath"] = join(root, "System32", "WindowsPowerShell", "v1.0", "Modules");
|
|
3378
|
+
}
|
|
3379
|
+
env["ELECTRON_RUN_AS_NODE"] = "1";
|
|
3139
3380
|
return new Promise((resolve, reject) => {
|
|
3140
3381
|
execFile(executable, ["-e", "try{process.stdout.write(process._linkedBinding('electron_browser_workbuddy_storage').loggerGet())}catch(e){process.exitCode=3;process.stderr.write(String(e&&e.message||e))}"], {
|
|
3141
|
-
env
|
|
3142
|
-
|
|
3143
|
-
ELECTRON_RUN_AS_NODE: "1"
|
|
3144
|
-
},
|
|
3382
|
+
env,
|
|
3383
|
+
cwd: process.platform === "win32" ? join(root, "System32") : root,
|
|
3145
3384
|
timeout: KEY_FETCH_TIMEOUT_MS,
|
|
3146
3385
|
windowsHide: true,
|
|
3147
3386
|
maxBuffer: 1048576
|
|
@@ -3195,7 +3434,7 @@ function ensureAtRestKeys() {
|
|
|
3195
3434
|
const candidates = await executableCandidates();
|
|
3196
3435
|
if (candidates.length === 0) {
|
|
3197
3436
|
lastKeyFailureAtMs = Date.now();
|
|
3198
|
-
lastKeyFailure =
|
|
3437
|
+
lastKeyFailure = signatureScanFailure !== "" ? signatureScanFailure : process.platform === "win32" ? "no WorkBuddy executable with a trusted signing key was found" : "no WorkBuddy executable found in the standard install roots";
|
|
3199
3438
|
return;
|
|
3200
3439
|
}
|
|
3201
3440
|
let anySuccess = false;
|
|
@@ -3232,6 +3471,402 @@ async function encryptedFieldOpener() {
|
|
|
3232
3471
|
};
|
|
3233
3472
|
}
|
|
3234
3473
|
//#endregion
|
|
3474
|
+
//#region src/trusted-process.ts
|
|
3475
|
+
/** Resolve the OS directory without trusting inherited Windows environment variables. */
|
|
3476
|
+
function trustedSystemRootOf(env) {
|
|
3477
|
+
if (process.platform === "win32") try {
|
|
3478
|
+
return realpathSync.native("\\\\?\\GLOBALROOT\\SystemRoot");
|
|
3479
|
+
} catch {
|
|
3480
|
+
return;
|
|
3481
|
+
}
|
|
3482
|
+
const value = env["SystemRoot"]?.trim() || env["windir"]?.trim();
|
|
3483
|
+
return value === void 0 || value === "" ? void 0 : value;
|
|
3484
|
+
}
|
|
3485
|
+
function trustedWindowsPowerShell(env) {
|
|
3486
|
+
const systemRoot = trustedSystemRootOf(env);
|
|
3487
|
+
if (systemRoot === void 0) return void 0;
|
|
3488
|
+
return join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
3489
|
+
}
|
|
3490
|
+
/** Build a PowerShell environment with fixed executable and module search paths. */
|
|
3491
|
+
function trustedWindowsChildEnv(env, options = {}) {
|
|
3492
|
+
const systemRoot = trustedSystemRootOf(env);
|
|
3493
|
+
if (systemRoot === void 0) return {};
|
|
3494
|
+
const result = {};
|
|
3495
|
+
if (options.inheritTemp === true) for (const name of ["TEMP", "TMP"]) {
|
|
3496
|
+
const value = env[name];
|
|
3497
|
+
if (value !== void 0 && value !== "") result[name] = value;
|
|
3498
|
+
}
|
|
3499
|
+
result.SystemRoot = systemRoot;
|
|
3500
|
+
result.windir = systemRoot;
|
|
3501
|
+
if (options.includeSystemDrive === true && /^[A-Za-z]:\\/.test(systemRoot)) result.SystemDrive = systemRoot.slice(0, 2);
|
|
3502
|
+
result.PATH = join(systemRoot, "System32");
|
|
3503
|
+
result.PSModulePath = join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "Modules");
|
|
3504
|
+
return result;
|
|
3505
|
+
}
|
|
3506
|
+
//#endregion
|
|
3507
|
+
//#region src/file-lock.ts
|
|
3508
|
+
const FILE_LOCK_WAIT_MS = 5e3;
|
|
3509
|
+
const UNOWNED_FILE_LOCK_STALE_MS = 6e4;
|
|
3510
|
+
const RETRY_MS = 25;
|
|
3511
|
+
const PROCESS_STARTED_AT_MS = Date.now() - Math.floor(process.uptime() * 1e3);
|
|
3512
|
+
const PROCESS_START_TOLERANCE_MS = 2e3;
|
|
3513
|
+
const RENAME_RETRY_DELAYS_MS = [
|
|
3514
|
+
25,
|
|
3515
|
+
50,
|
|
3516
|
+
100,
|
|
3517
|
+
200,
|
|
3518
|
+
400
|
|
3519
|
+
];
|
|
3520
|
+
const ABANDONED_RECLAIMS = /* @__PURE__ */ new Map();
|
|
3521
|
+
/**
|
|
3522
|
+
* Commit a complete temporary file over its target.
|
|
3523
|
+
*
|
|
3524
|
+
* Windows can report EPERM or EBUSY while another reader is between opening
|
|
3525
|
+
* and closing the target. Retrying preserves the atomic rename and avoids
|
|
3526
|
+
* falling back to a partial in-place write.
|
|
3527
|
+
*/
|
|
3528
|
+
async function replaceFile(temporary, file) {
|
|
3529
|
+
for (let attempt = 0;; attempt += 1) try {
|
|
3530
|
+
await rename(temporary, file);
|
|
3531
|
+
return;
|
|
3532
|
+
} catch (error) {
|
|
3533
|
+
const code = error.code;
|
|
3534
|
+
if (process.platform !== "win32" || code !== "EPERM" && code !== "EBUSY" || attempt >= RENAME_RETRY_DELAYS_MS.length) throw error;
|
|
3535
|
+
await new Promise((resolve) => setTimeout(resolve, RENAME_RETRY_DELAYS_MS[attempt]));
|
|
3536
|
+
}
|
|
3537
|
+
}
|
|
3538
|
+
function processIsAlive(pid) {
|
|
3539
|
+
try {
|
|
3540
|
+
process.kill(pid, 0);
|
|
3541
|
+
return true;
|
|
3542
|
+
} catch (error) {
|
|
3543
|
+
const code = error.code;
|
|
3544
|
+
if (code === "ESRCH") return false;
|
|
3545
|
+
if (code === "EPERM") return true;
|
|
3546
|
+
return;
|
|
3547
|
+
}
|
|
3548
|
+
}
|
|
3549
|
+
function processOutput(command, args, env, cwd) {
|
|
3550
|
+
return new Promise((resolve) => {
|
|
3551
|
+
execFile(command, [...args], {
|
|
3552
|
+
timeout: 2e3,
|
|
3553
|
+
maxBuffer: 1024,
|
|
3554
|
+
windowsHide: true,
|
|
3555
|
+
env,
|
|
3556
|
+
cwd
|
|
3557
|
+
}, (error, stdout) => {
|
|
3558
|
+
if (error !== null) resolve(void 0);
|
|
3559
|
+
else resolve(stdout.trim());
|
|
3560
|
+
});
|
|
3561
|
+
});
|
|
3562
|
+
}
|
|
3563
|
+
async function processStartedAt(pid) {
|
|
3564
|
+
if (pid === process.pid) return PROCESS_STARTED_AT_MS;
|
|
3565
|
+
if (process.platform === "win32") {
|
|
3566
|
+
const systemRoot = trustedSystemRootOf(process.env);
|
|
3567
|
+
const powershell = trustedWindowsPowerShell(process.env);
|
|
3568
|
+
if (systemRoot === void 0 || powershell === void 0) return void 0;
|
|
3569
|
+
const match = (await processOutput(powershell, [
|
|
3570
|
+
"-NoLogo",
|
|
3571
|
+
"-NoProfile",
|
|
3572
|
+
"-NonInteractive",
|
|
3573
|
+
"-Command",
|
|
3574
|
+
`$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules'); $d=(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime(); ([DateTimeOffset]$d).ToUnixTimeMilliseconds()`
|
|
3575
|
+
], trustedWindowsChildEnv(process.env, {
|
|
3576
|
+
inheritTemp: true,
|
|
3577
|
+
includeSystemDrive: true
|
|
3578
|
+
}), join(systemRoot, "System32")))?.match(/\d{10,}/);
|
|
3579
|
+
return match === void 0 || match === null ? void 0 : Number(match[0]);
|
|
3580
|
+
}
|
|
3581
|
+
const ps = ["/usr/bin/ps", "/bin/ps"].find(existsSync);
|
|
3582
|
+
if (ps === void 0) return void 0;
|
|
3583
|
+
const output = await processOutput(ps, [
|
|
3584
|
+
"-p",
|
|
3585
|
+
String(pid),
|
|
3586
|
+
"-o",
|
|
3587
|
+
"lstart="
|
|
3588
|
+
], {
|
|
3589
|
+
PATH: "/usr/bin:/bin",
|
|
3590
|
+
LC_ALL: "C",
|
|
3591
|
+
TZ: "UTC"
|
|
3592
|
+
}, "/");
|
|
3593
|
+
const started = output === void 0 ? NaN : Date.parse(`${output.trim()} UTC`);
|
|
3594
|
+
return Number.isFinite(started) ? started : void 0;
|
|
3595
|
+
}
|
|
3596
|
+
async function lockState(file) {
|
|
3597
|
+
let text;
|
|
3598
|
+
try {
|
|
3599
|
+
text = await readFile(file, "utf8");
|
|
3600
|
+
} catch (error) {
|
|
3601
|
+
const code = error.code;
|
|
3602
|
+
if (code === "ENOENT" || code === "ENOTDIR") return "missing";
|
|
3603
|
+
if (code === "EBUSY" || code === "EPERM" || code === "EACCES") return "current";
|
|
3604
|
+
throw error;
|
|
3605
|
+
}
|
|
3606
|
+
let owner;
|
|
3607
|
+
try {
|
|
3608
|
+
owner = JSON.parse(text);
|
|
3609
|
+
} catch {}
|
|
3610
|
+
if (owner?.state === "abandoned") return "stale";
|
|
3611
|
+
const fileAge = await stat(file).then((entry) => Date.now() - entry.mtimeMs, () => 0);
|
|
3612
|
+
const ownerAlive = typeof owner?.pid === "number" ? processIsAlive(owner.pid) : void 0;
|
|
3613
|
+
if (ownerAlive === false) return "stale";
|
|
3614
|
+
if (ownerAlive === true && typeof owner?.pid === "number") {
|
|
3615
|
+
const recordedStart = typeof owner.processStartedAtMs === "number" ? owner.processStartedAtMs : typeof owner.createdAtMs === "number" ? owner.createdAtMs : void 0;
|
|
3616
|
+
if (recordedStart !== void 0 && Math.abs(fileAge) > PROCESS_START_TOLERANCE_MS) {
|
|
3617
|
+
const actualStart = await processStartedAt(owner.pid);
|
|
3618
|
+
if (actualStart !== void 0 && actualStart - recordedStart > PROCESS_START_TOLERANCE_MS) return "stale";
|
|
3619
|
+
}
|
|
3620
|
+
if (recordedStart === void 0) return fileAge > UNOWNED_FILE_LOCK_STALE_MS ? "stale" : "current";
|
|
3621
|
+
return "current";
|
|
3622
|
+
}
|
|
3623
|
+
return fileAge > UNOWNED_FILE_LOCK_STALE_MS ? "stale" : "current";
|
|
3624
|
+
}
|
|
3625
|
+
async function createOwnedFile(file) {
|
|
3626
|
+
const token = randomUUID();
|
|
3627
|
+
try {
|
|
3628
|
+
await writeFile(file, JSON.stringify({
|
|
3629
|
+
pid: process.pid,
|
|
3630
|
+
token,
|
|
3631
|
+
createdAtMs: Date.now(),
|
|
3632
|
+
processStartedAtMs: PROCESS_STARTED_AT_MS
|
|
3633
|
+
}), {
|
|
3634
|
+
flag: "wx",
|
|
3635
|
+
mode: 384
|
|
3636
|
+
});
|
|
3637
|
+
return token;
|
|
3638
|
+
} catch (error) {
|
|
3639
|
+
if (error.code === "EEXIST") return void 0;
|
|
3640
|
+
throw error;
|
|
3641
|
+
}
|
|
3642
|
+
}
|
|
3643
|
+
async function releaseOwnedFile(file, token) {
|
|
3644
|
+
const deadline = Date.now() + FILE_LOCK_WAIT_MS;
|
|
3645
|
+
while (true) {
|
|
3646
|
+
let owner;
|
|
3647
|
+
try {
|
|
3648
|
+
const parsed = JSON.parse(await readFile(file, "utf8"));
|
|
3649
|
+
owner = typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
3650
|
+
} catch (error) {
|
|
3651
|
+
const code = error.code;
|
|
3652
|
+
if (code === "ENOENT" || code === "ENOTDIR") return "missing";
|
|
3653
|
+
}
|
|
3654
|
+
if (owner !== void 0) {
|
|
3655
|
+
if (owner.token !== token) return "replaced";
|
|
3656
|
+
try {
|
|
3657
|
+
await unlink(file);
|
|
3658
|
+
return "released";
|
|
3659
|
+
} catch (error) {
|
|
3660
|
+
const code = error.code;
|
|
3661
|
+
if (code === "ENOENT" || code === "ENOTDIR") return "missing";
|
|
3662
|
+
try {
|
|
3663
|
+
await writeFile(file, JSON.stringify({
|
|
3664
|
+
...owner,
|
|
3665
|
+
state: "abandoned"
|
|
3666
|
+
}), { mode: 384 });
|
|
3667
|
+
} catch {}
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
if (Date.now() >= deadline) return "failed";
|
|
3671
|
+
await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
|
|
3672
|
+
}
|
|
3673
|
+
}
|
|
3674
|
+
async function newestReclaimGeneration(lock) {
|
|
3675
|
+
const directory = dirname(lock);
|
|
3676
|
+
const prefix = `${basename(lock)}.reclaim.`;
|
|
3677
|
+
const names = await readdir(directory);
|
|
3678
|
+
let generation = 0;
|
|
3679
|
+
for (const name of names) {
|
|
3680
|
+
if (!name.startsWith(prefix)) continue;
|
|
3681
|
+
const suffix = name.slice(prefix.length);
|
|
3682
|
+
if (!/^\d+$/.test(suffix)) continue;
|
|
3683
|
+
generation = Math.max(generation, Number(suffix));
|
|
3684
|
+
}
|
|
3685
|
+
return generation;
|
|
3686
|
+
}
|
|
3687
|
+
async function cleanupTerminalReclaims(lock) {
|
|
3688
|
+
const directory = dirname(lock);
|
|
3689
|
+
const prefix = `${basename(lock)}.reclaim.`;
|
|
3690
|
+
let names;
|
|
3691
|
+
try {
|
|
3692
|
+
names = await readdir(directory);
|
|
3693
|
+
} catch {
|
|
3694
|
+
return;
|
|
3695
|
+
}
|
|
3696
|
+
const claimNames = names.filter((name) => {
|
|
3697
|
+
if (!name.startsWith(prefix)) return false;
|
|
3698
|
+
return /^\d+$/.test(name.slice(prefix.length));
|
|
3699
|
+
});
|
|
3700
|
+
const claimNameSet = new Set(claimNames);
|
|
3701
|
+
for (const claimName of claimNames) {
|
|
3702
|
+
const claim = join(directory, claimName);
|
|
3703
|
+
const sidecars = names.filter((name) => name.startsWith(`${claimName}.abandoned.`));
|
|
3704
|
+
const temporaryFiles = names.filter((name) => name.startsWith(`${claimName}.`) && name.endsWith(".tmp"));
|
|
3705
|
+
let owner;
|
|
3706
|
+
try {
|
|
3707
|
+
const parsed = JSON.parse(await readFile(claim, "utf8"));
|
|
3708
|
+
owner = typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
3709
|
+
} catch {}
|
|
3710
|
+
const terminalState = owner?.state === "complete" || owner?.state === "abandoned";
|
|
3711
|
+
const rememberedAbandonment = ABANDONED_RECLAIMS.get(claim) === owner?.token;
|
|
3712
|
+
if (sidecars.length === 0 && !terminalState && !rememberedAbandonment) continue;
|
|
3713
|
+
let claimRemoved = false;
|
|
3714
|
+
try {
|
|
3715
|
+
await unlink(claim);
|
|
3716
|
+
claimRemoved = true;
|
|
3717
|
+
} catch (error) {
|
|
3718
|
+
const code = error.code;
|
|
3719
|
+
claimRemoved = code === "ENOENT" || code === "ENOTDIR";
|
|
3720
|
+
}
|
|
3721
|
+
if (!claimRemoved) continue;
|
|
3722
|
+
for (const sidecar of sidecars) await unlink(join(directory, sidecar)).catch(() => {});
|
|
3723
|
+
for (const temporary of temporaryFiles) await unlink(join(directory, temporary)).catch(() => {});
|
|
3724
|
+
ABANDONED_RECLAIMS.delete(claim);
|
|
3725
|
+
}
|
|
3726
|
+
for (const name of names) {
|
|
3727
|
+
const marker = name.indexOf(prefix);
|
|
3728
|
+
const abandoned = name.indexOf(".abandoned.", marker + prefix.length);
|
|
3729
|
+
if (marker !== 0 || abandoned === -1) continue;
|
|
3730
|
+
if (claimNameSet.has(name.slice(0, abandoned))) continue;
|
|
3731
|
+
await unlink(join(directory, name)).catch(() => {});
|
|
3732
|
+
}
|
|
3733
|
+
}
|
|
3734
|
+
async function claimStaleReclaim(lock) {
|
|
3735
|
+
const directory = dirname(lock);
|
|
3736
|
+
const prefix = `${basename(lock)}.reclaim.`;
|
|
3737
|
+
const names = await readdir(directory);
|
|
3738
|
+
const generation = names.reduce((highest, name) => {
|
|
3739
|
+
if (!name.startsWith(prefix)) return highest;
|
|
3740
|
+
const match = name.slice(prefix.length).match(/^(\d+)(?:\.abandoned\..+)?$/);
|
|
3741
|
+
return match === null ? highest : Math.max(highest, Number(match[1]));
|
|
3742
|
+
}, 0);
|
|
3743
|
+
const claims = names.filter((name) => {
|
|
3744
|
+
if (!name.startsWith(prefix)) return false;
|
|
3745
|
+
return /^\d+$/.test(name.slice(prefix.length));
|
|
3746
|
+
}).map((name) => join(directory, name));
|
|
3747
|
+
for (const claim of claims) {
|
|
3748
|
+
const claimName = basename(claim);
|
|
3749
|
+
if (names.some((name) => name.startsWith(`${claimName}.abandoned.`))) continue;
|
|
3750
|
+
let owner = {};
|
|
3751
|
+
try {
|
|
3752
|
+
const parsed = JSON.parse(await readFile(claim, "utf8"));
|
|
3753
|
+
owner = typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
3754
|
+
} catch (error) {
|
|
3755
|
+
if (error.code === "ENOENT") {
|
|
3756
|
+
ABANDONED_RECLAIMS.delete(claim);
|
|
3757
|
+
continue;
|
|
3758
|
+
}
|
|
3759
|
+
}
|
|
3760
|
+
if (owner.state === "complete" || owner.state === "abandoned") continue;
|
|
3761
|
+
if (ABANDONED_RECLAIMS.get(claim) === owner.token) continue;
|
|
3762
|
+
if (await lockState(claim) === "current") return void 0;
|
|
3763
|
+
}
|
|
3764
|
+
const file = `${lock}.reclaim.${String(generation + 1).padStart(12, "0")}`;
|
|
3765
|
+
const token = await createOwnedFile(file);
|
|
3766
|
+
return token === void 0 ? void 0 : {
|
|
3767
|
+
file,
|
|
3768
|
+
token,
|
|
3769
|
+
generation: generation + 1
|
|
3770
|
+
};
|
|
3771
|
+
}
|
|
3772
|
+
async function completeReclaim(reclaim) {
|
|
3773
|
+
try {
|
|
3774
|
+
if (JSON.parse(await readFile(reclaim.file, "utf8")).token !== reclaim.token) return;
|
|
3775
|
+
const temporary = `${reclaim.file}.${randomUUID()}.tmp`;
|
|
3776
|
+
try {
|
|
3777
|
+
await writeFile(temporary, JSON.stringify({
|
|
3778
|
+
pid: process.pid,
|
|
3779
|
+
token: reclaim.token,
|
|
3780
|
+
createdAtMs: Date.now(),
|
|
3781
|
+
processStartedAtMs: PROCESS_STARTED_AT_MS,
|
|
3782
|
+
state: "complete"
|
|
3783
|
+
}), { mode: 384 });
|
|
3784
|
+
await replaceFile(temporary, reclaim.file);
|
|
3785
|
+
} catch (error) {
|
|
3786
|
+
await unlink(temporary).catch(() => {});
|
|
3787
|
+
throw error;
|
|
3788
|
+
}
|
|
3789
|
+
} catch (error) {
|
|
3790
|
+
if (error.code !== "ENOENT") throw error;
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
async function abandonReclaim(reclaim, cause) {
|
|
3794
|
+
let marked = false;
|
|
3795
|
+
try {
|
|
3796
|
+
await writeFile(reclaim.file, JSON.stringify({
|
|
3797
|
+
pid: process.pid,
|
|
3798
|
+
token: reclaim.token,
|
|
3799
|
+
createdAtMs: Date.now(),
|
|
3800
|
+
processStartedAtMs: PROCESS_STARTED_AT_MS,
|
|
3801
|
+
state: "abandoned"
|
|
3802
|
+
}), { mode: 384 });
|
|
3803
|
+
marked = true;
|
|
3804
|
+
} catch {}
|
|
3805
|
+
const released = await releaseOwnedFile(reclaim.file, reclaim.token);
|
|
3806
|
+
if (released === "released" || released === "missing") throw cause;
|
|
3807
|
+
if (!marked) {
|
|
3808
|
+
const marker = `${reclaim.file}.abandoned.${reclaim.token}`;
|
|
3809
|
+
try {
|
|
3810
|
+
await writeFile(marker, JSON.stringify({
|
|
3811
|
+
token: reclaim.token,
|
|
3812
|
+
createdAtMs: Date.now(),
|
|
3813
|
+
processStartedAtMs: PROCESS_STARTED_AT_MS
|
|
3814
|
+
}), {
|
|
3815
|
+
flag: "wx",
|
|
3816
|
+
mode: 384
|
|
3817
|
+
});
|
|
3818
|
+
marked = true;
|
|
3819
|
+
} catch (error) {
|
|
3820
|
+
if (error.code === "EEXIST") marked = true;
|
|
3821
|
+
}
|
|
3822
|
+
}
|
|
3823
|
+
if (marked) {
|
|
3824
|
+
ABANDONED_RECLAIMS.delete(reclaim.file);
|
|
3825
|
+
throw cause;
|
|
3826
|
+
}
|
|
3827
|
+
ABANDONED_RECLAIMS.set(reclaim.file, reclaim.token);
|
|
3828
|
+
throw new Error("could not complete or release the lock recovery claim", { cause });
|
|
3829
|
+
}
|
|
3830
|
+
/** Run `work` while holding a lock file shared by every writer to the same document. */
|
|
3831
|
+
async function withFileLock(lock, work) {
|
|
3832
|
+
await mkdir(dirname(lock), { recursive: true });
|
|
3833
|
+
const deadline = Date.now() + FILE_LOCK_WAIT_MS;
|
|
3834
|
+
let token;
|
|
3835
|
+
while (token === void 0) {
|
|
3836
|
+
token = await createOwnedFile(lock);
|
|
3837
|
+
if (token !== void 0) break;
|
|
3838
|
+
const current = await lockState(lock);
|
|
3839
|
+
if (current === "missing") continue;
|
|
3840
|
+
if (current === "stale") {
|
|
3841
|
+
const reclaim = await claimStaleReclaim(lock);
|
|
3842
|
+
if (reclaim !== void 0) {
|
|
3843
|
+
try {
|
|
3844
|
+
if (await newestReclaimGeneration(lock) === reclaim.generation && await lockState(lock) === "stale" && await newestReclaimGeneration(lock) === reclaim.generation) await unlink(lock).catch(() => {});
|
|
3845
|
+
} finally {
|
|
3846
|
+
try {
|
|
3847
|
+
await completeReclaim(reclaim);
|
|
3848
|
+
} catch (error) {
|
|
3849
|
+
await abandonReclaim(reclaim, error);
|
|
3850
|
+
}
|
|
3851
|
+
}
|
|
3852
|
+
continue;
|
|
3853
|
+
}
|
|
3854
|
+
}
|
|
3855
|
+
if (Date.now() >= deadline) throw new Error("timed out waiting for the credential document lock");
|
|
3856
|
+
await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
|
|
3857
|
+
}
|
|
3858
|
+
await cleanupTerminalReclaims(lock);
|
|
3859
|
+
try {
|
|
3860
|
+
await work();
|
|
3861
|
+
} catch (error) {
|
|
3862
|
+
const released = await releaseOwnedFile(lock, token);
|
|
3863
|
+
if (released !== "released" && released !== "missing") throw new Error("work failed and the credential document lock was not released", { cause: error });
|
|
3864
|
+
throw error;
|
|
3865
|
+
}
|
|
3866
|
+
const released = await releaseOwnedFile(lock, token);
|
|
3867
|
+
if (released !== "released" && released !== "missing") throw new Error("work completed but the credential document lock was not released");
|
|
3868
|
+
}
|
|
3869
|
+
//#endregion
|
|
3235
3870
|
//#region src/accounts.ts
|
|
3236
3871
|
/**
|
|
3237
3872
|
* Account pool: discovers every WorkBuddy credential snapshot the desktop app
|
|
@@ -3387,6 +4022,7 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
|
3387
4022
|
const accessToken = decryptableString(auth["accessToken"], decrypt);
|
|
3388
4023
|
if (accessToken === "") return void 0;
|
|
3389
4024
|
const refreshExpiresAtMs = typeof auth["refreshExpiresAt"] === "number" ? expiryToMs(auth["refreshExpiresAt"]) : void 0;
|
|
4025
|
+
const refreshField = encryptedField(auth["refreshToken"]);
|
|
3390
4026
|
const refreshToken = decryptableString(auth["refreshToken"], decrypt);
|
|
3391
4027
|
const refreshExpired = refreshExpiresAtMs !== void 0 && refreshExpiresAtMs > 0 && refreshExpiresAtMs < Date.now();
|
|
3392
4028
|
const lastRefreshAtMs = typeof auth["lastRefreshTime"] === "number" ? expiryToMs(auth["lastRefreshTime"]) : void 0;
|
|
@@ -3394,6 +4030,7 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
|
3394
4030
|
return {
|
|
3395
4031
|
accessToken,
|
|
3396
4032
|
refreshToken: refreshExpired ? "" : refreshToken,
|
|
4033
|
+
...!refreshExpired && refreshField !== void 0 && refreshToken === "" ? { refreshTokenUnavailable: true } : {},
|
|
3397
4034
|
expiresAtMs: typeof auth["expiresAt"] === "number" ? expiryToMs(auth["expiresAt"]) : 0,
|
|
3398
4035
|
...refreshExpiresAtMs === void 0 || refreshExpired ? {} : { refreshExpiresAtMs },
|
|
3399
4036
|
...lastRefreshAtMs === void 0 ? {} : { lastRefreshAtMs },
|
|
@@ -3411,12 +4048,28 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
|
3411
4048
|
* that cannot be opened is an empty string so the caller skips the file
|
|
3412
4049
|
* instead of treating a sealed token as "not signed in".
|
|
3413
4050
|
*/
|
|
4051
|
+
function encryptedField(value) {
|
|
4052
|
+
if (typeof value === "string") {
|
|
4053
|
+
if (!value.trimStart().startsWith("{")) return void 0;
|
|
4054
|
+
const text = value;
|
|
4055
|
+
try {
|
|
4056
|
+
value = JSON.parse(text);
|
|
4057
|
+
} catch {
|
|
4058
|
+
return /"\$wbEncrypted"\s*:/u.test(text) ? null : void 0;
|
|
4059
|
+
}
|
|
4060
|
+
}
|
|
4061
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && Object.hasOwn(value, "$wbEncrypted") ? value : void 0;
|
|
4062
|
+
}
|
|
3414
4063
|
function decryptableString(value, decrypt) {
|
|
3415
|
-
|
|
3416
|
-
if (
|
|
3417
|
-
|
|
3418
|
-
|
|
3419
|
-
|
|
4064
|
+
const field = encryptedField(value);
|
|
4065
|
+
if (field !== void 0) {
|
|
4066
|
+
if (!isEncryptedFieldWrapper(field)) return "";
|
|
4067
|
+
try {
|
|
4068
|
+
return decrypt?.(field) ?? "";
|
|
4069
|
+
} catch {}
|
|
4070
|
+
return "";
|
|
4071
|
+
}
|
|
4072
|
+
return typeof value === "string" ? value : "";
|
|
3420
4073
|
}
|
|
3421
4074
|
/**
|
|
3422
4075
|
* Whether `path` is the desktop app's live sign-in (as opposed to a backup
|
|
@@ -3480,7 +4133,12 @@ function credentialRank(credential, ownDir) {
|
|
|
3480
4133
|
}
|
|
3481
4134
|
/** True when `candidate` should replace `incumbent` for the same account. */
|
|
3482
4135
|
function isFresher(candidate, incumbent, ownDir) {
|
|
3483
|
-
|
|
4136
|
+
const ordering = compareFreshness(candidate, incumbent, ownDir);
|
|
4137
|
+
if (candidate.accessToken !== incumbent.accessToken) return ordering < 0;
|
|
4138
|
+
if (candidate.refreshTokenUnavailable && incumbent.refreshToken !== "") return false;
|
|
4139
|
+
if (ordering !== 0) return ordering < 0;
|
|
4140
|
+
if (candidate.sourcePath === incumbent.sourcePath) return candidate.refreshToken !== incumbent.refreshToken || candidate.refreshTokenUnavailable !== incumbent.refreshTokenUnavailable;
|
|
4141
|
+
return false;
|
|
3484
4142
|
}
|
|
3485
4143
|
/**
|
|
3486
4144
|
* Queue order for the account list: the live sign-in first, then the copy the
|
|
@@ -3511,44 +4169,14 @@ function tokenDigest(accessToken) {
|
|
|
3511
4169
|
* data directory then kept a stale tombstone set; the size is in here so a rewrite
|
|
3512
4170
|
* that lands in the same reported millisecond still reads as a different file.
|
|
3513
4171
|
*/
|
|
4172
|
+
const MISSING_FILE_STAMP = "missing";
|
|
3514
4173
|
async function signInFileStamp(file) {
|
|
3515
4174
|
try {
|
|
3516
4175
|
const entry = await stat(file);
|
|
3517
4176
|
return `${entry.mtimeMs}:${entry.size}`;
|
|
3518
|
-
} catch {
|
|
3519
|
-
return "";
|
|
3520
|
-
}
|
|
3521
|
-
}
|
|
3522
|
-
/**
|
|
3523
|
-
* Run `work` while holding a lock file, or without it when the lock stays taken.
|
|
3524
|
-
*
|
|
3525
|
-
* The tombstone document is the one file two pools over the same data directory
|
|
3526
|
-
* both write, and a read-union-write is only as good as its serialisation. The
|
|
3527
|
-
* budget is short on purpose: a panel call is answered within seconds, and the
|
|
3528
|
-
* work is a few kilobytes of JSON. A lock older than that is a process that died
|
|
3529
|
-
* holding it, so it is dropped and retried.
|
|
3530
|
-
*/
|
|
3531
|
-
async function withFileLock(lock, work) {
|
|
3532
|
-
let held = false;
|
|
3533
|
-
for (let attempt = 0; attempt < 25 && !held; attempt += 1) try {
|
|
3534
|
-
await writeFile(lock, "", {
|
|
3535
|
-
flag: "wx",
|
|
3536
|
-
mode: 384
|
|
3537
|
-
});
|
|
3538
|
-
held = true;
|
|
3539
|
-
break;
|
|
3540
4177
|
} catch (error) {
|
|
3541
|
-
|
|
3542
|
-
|
|
3543
|
-
await unlink(lock).catch(() => {});
|
|
3544
|
-
continue;
|
|
3545
|
-
}
|
|
3546
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
3547
|
-
}
|
|
3548
|
-
try {
|
|
3549
|
-
await work();
|
|
3550
|
-
} finally {
|
|
3551
|
-
if (held) await unlink(lock).catch(() => {});
|
|
4178
|
+
const code = error.code;
|
|
4179
|
+
return code === "ENOENT" || code === "ENOTDIR" ? MISSING_FILE_STAMP : void 0;
|
|
3552
4180
|
}
|
|
3553
4181
|
}
|
|
3554
4182
|
/**
|
|
@@ -3665,12 +4293,16 @@ async function authFilesIn(dir) {
|
|
|
3665
4293
|
let entries;
|
|
3666
4294
|
try {
|
|
3667
4295
|
entries = await readdir(dir);
|
|
3668
|
-
} catch {
|
|
3669
|
-
|
|
4296
|
+
} catch (error) {
|
|
4297
|
+
const code = error.code;
|
|
4298
|
+
return { unavailable: code !== "ENOENT" && code !== "ENOTDIR" };
|
|
3670
4299
|
}
|
|
3671
4300
|
const files = entries.filter((name) => name.endsWith(".info"));
|
|
3672
4301
|
files.sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
|
|
3673
|
-
return
|
|
4302
|
+
return {
|
|
4303
|
+
files: files.map((name) => join(dir, name)),
|
|
4304
|
+
unavailable: false
|
|
4305
|
+
};
|
|
3674
4306
|
}
|
|
3675
4307
|
/** True when the document's access token is a `$wbEncrypted` envelope. */
|
|
3676
4308
|
function sealedAccessToken(text) {
|
|
@@ -3682,23 +4314,53 @@ function sealedAccessToken(text) {
|
|
|
3682
4314
|
}
|
|
3683
4315
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
|
|
3684
4316
|
const document = parsed;
|
|
3685
|
-
return
|
|
4317
|
+
return encryptedField((typeof document["auth"] === "object" && document["auth"] !== null ? document["auth"] : document)["accessToken"]) !== void 0;
|
|
4318
|
+
}
|
|
4319
|
+
/** Identity from a sealed document, using only fields left in plaintext. */
|
|
4320
|
+
function sealedIdentity(text, sourcePath) {
|
|
4321
|
+
let parsed;
|
|
4322
|
+
try {
|
|
4323
|
+
parsed = JSON.parse(text);
|
|
4324
|
+
} catch {
|
|
4325
|
+
return;
|
|
4326
|
+
}
|
|
4327
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
|
|
4328
|
+
const document = parsed;
|
|
4329
|
+
const account = typeof document["account"] === "object" && document["account"] !== null && !Array.isArray(document["account"]) ? document["account"] : document;
|
|
4330
|
+
const uin = typeof account["uin"] === "string" && account["uin"] !== "" ? account["uin"] : void 0;
|
|
4331
|
+
const uid = typeof account["uid"] === "string" && account["uid"] !== "" ? account["uid"] : void 0;
|
|
4332
|
+
if (uin === void 0 && uid === void 0) return void 0;
|
|
4333
|
+
return workbuddyAccountId({
|
|
4334
|
+
uin,
|
|
4335
|
+
uid,
|
|
4336
|
+
nickname: void 0,
|
|
4337
|
+
sourcePath
|
|
4338
|
+
});
|
|
3686
4339
|
}
|
|
3687
4340
|
async function readCredential(path) {
|
|
3688
4341
|
let text;
|
|
3689
4342
|
try {
|
|
3690
4343
|
text = await readFile(path, "utf8");
|
|
3691
|
-
} catch {
|
|
3692
|
-
|
|
4344
|
+
} catch (error) {
|
|
4345
|
+
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
4346
|
+
return code === "ENOENT" || code === "ENOTDIR" ? { kind: "absent" } : { kind: "unreadable" };
|
|
3693
4347
|
}
|
|
3694
|
-
const decrypt = text.includes("\"$wbEncrypted\"") ? await encryptedFieldOpener() : void 0;
|
|
4348
|
+
const decrypt = text.includes("\"$wbEncrypted\"") || text.includes("\\\"$wbEncrypted\\\"") ? await encryptedFieldOpener() : void 0;
|
|
3695
4349
|
const credential = parseWorkBuddyAuth(text, path, decrypt);
|
|
3696
4350
|
if (credential !== void 0) return {
|
|
3697
4351
|
kind: "credential",
|
|
3698
4352
|
credential
|
|
3699
4353
|
};
|
|
3700
|
-
if (sealedAccessToken(text)) return {
|
|
3701
|
-
|
|
4354
|
+
if (sealedAccessToken(text)) return {
|
|
4355
|
+
kind: "sealed",
|
|
4356
|
+
id: sealedIdentity(text, path)
|
|
4357
|
+
};
|
|
4358
|
+
try {
|
|
4359
|
+
JSON.parse(text);
|
|
4360
|
+
return { kind: "absent" };
|
|
4361
|
+
} catch {
|
|
4362
|
+
return { kind: "unreadable" };
|
|
4363
|
+
}
|
|
3702
4364
|
}
|
|
3703
4365
|
/** Refresh a credential this long before its expiry, so a request never rides one that dies mid-flight. */
|
|
3704
4366
|
const REFRESH_MARGIN_MS = 3e5;
|
|
@@ -3843,27 +4505,55 @@ function ownSignInOf(credential) {
|
|
|
3843
4505
|
* two accounts never collide on a name.
|
|
3844
4506
|
*/
|
|
3845
4507
|
async function writeOwnSignIn(directory, signIn, signal) {
|
|
4508
|
+
const file = ownSignInFile(directory, signIn);
|
|
4509
|
+
return await withSignInWriteLock(file, async () => {
|
|
4510
|
+
await writeOwnSignInDocument(file, signIn, signal);
|
|
4511
|
+
return file;
|
|
4512
|
+
});
|
|
4513
|
+
}
|
|
4514
|
+
const signInWriteQueues = /* @__PURE__ */ new Map();
|
|
4515
|
+
async function withSignInWriteLock(file, work) {
|
|
4516
|
+
const run = (signInWriteQueues.get(file) ?? Promise.resolve()).then(work, work);
|
|
4517
|
+
const settled = run.then(() => void 0, () => void 0);
|
|
4518
|
+
signInWriteQueues.set(file, settled);
|
|
4519
|
+
try {
|
|
4520
|
+
return await run;
|
|
4521
|
+
} finally {
|
|
4522
|
+
if (signInWriteQueues.get(file) === settled) signInWriteQueues.delete(file);
|
|
4523
|
+
}
|
|
4524
|
+
}
|
|
4525
|
+
function ownSignInFile(directory, signIn) {
|
|
3846
4526
|
const stable = signIn.uin === "" ? signIn.uid : signIn.uin;
|
|
3847
4527
|
const suffix = stable === "" ? randomUUID() : stable.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 32);
|
|
3848
|
-
|
|
3849
|
-
|
|
4528
|
+
return join(directory, `${OWN_SIGN_IN_PREFIX}${suffix === "" ? randomUUID() : suffix}.info`);
|
|
4529
|
+
}
|
|
4530
|
+
async function writeOwnSignInDocument(file, signIn, signal) {
|
|
3850
4531
|
signal?.throwIfAborted();
|
|
3851
|
-
await
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
|
|
3865
|
-
|
|
3866
|
-
|
|
4532
|
+
await mkdir(dirname(file), { recursive: true });
|
|
4533
|
+
signal?.throwIfAborted();
|
|
4534
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
4535
|
+
try {
|
|
4536
|
+
await writeFile(temporary, JSON.stringify({
|
|
4537
|
+
auth: {
|
|
4538
|
+
accessToken: signIn.accessToken,
|
|
4539
|
+
refreshToken: signIn.refreshToken,
|
|
4540
|
+
expiresAt: signIn.expiresAtMs,
|
|
4541
|
+
domain: signIn.domain,
|
|
4542
|
+
lastRefreshTime: signIn.lastRefreshAtMs ?? Date.now()
|
|
4543
|
+
},
|
|
4544
|
+
account: {
|
|
4545
|
+
...signIn.uid === "" ? {} : { uid: signIn.uid },
|
|
4546
|
+
...signIn.uin === "" ? {} : { uin: signIn.uin },
|
|
4547
|
+
...signIn.enterpriseId === "" ? {} : { enterpriseId: signIn.enterpriseId },
|
|
4548
|
+
...signIn.nickname === "" ? {} : { nickname: signIn.nickname }
|
|
4549
|
+
}
|
|
4550
|
+
}, null, 2), { mode: 384 });
|
|
4551
|
+
signal?.throwIfAborted();
|
|
4552
|
+
await replaceFile(temporary, file);
|
|
4553
|
+
} catch (error) {
|
|
4554
|
+
await unlink(temporary).catch(() => {});
|
|
4555
|
+
throw error;
|
|
4556
|
+
}
|
|
3867
4557
|
}
|
|
3868
4558
|
/**
|
|
3869
4559
|
* Rewrite one of the plugin's own sign-in files with a renewed token.
|
|
@@ -3873,22 +4563,47 @@ async function writeOwnSignIn(directory, signIn, signal) {
|
|
|
3873
4563
|
* auth values a refresh replaces are written. Atomic for the same reason as the
|
|
3874
4564
|
* archive: a truncated `.info` is an account the scan cannot open.
|
|
3875
4565
|
*/
|
|
3876
|
-
async function renewOwnSignInFile(file, credential) {
|
|
3877
|
-
|
|
3878
|
-
|
|
3879
|
-
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
4566
|
+
async function renewOwnSignInFile(file, credential, previous, createIfMissing = false, beforeCommit) {
|
|
4567
|
+
return await withSignInWriteLock(file, async () => {
|
|
4568
|
+
let text;
|
|
4569
|
+
try {
|
|
4570
|
+
text = await readFile(file, "utf8");
|
|
4571
|
+
} catch (error) {
|
|
4572
|
+
if (!createIfMissing || error.code !== "ENOENT") throw error;
|
|
4573
|
+
if (beforeCommit !== void 0 && !await beforeCommit()) return false;
|
|
4574
|
+
await writeOwnSignInDocument(file, ownSignInOf(credential));
|
|
4575
|
+
return true;
|
|
4576
|
+
}
|
|
4577
|
+
const document = JSON.parse(text);
|
|
4578
|
+
const auth = document.auth ?? {};
|
|
4579
|
+
if (auth.accessToken !== previous.accessToken) {
|
|
4580
|
+
const onDisk = parseWorkBuddyAuth(text, file);
|
|
4581
|
+
if (onDisk === void 0) throw new Error("sign-in changed while the token refresh was in flight");
|
|
4582
|
+
if (isFresher(onDisk, previous, dirname(file))) return false;
|
|
4583
|
+
}
|
|
4584
|
+
auth.accessToken = credential.accessToken;
|
|
4585
|
+
auth.refreshToken = credential.refreshToken;
|
|
4586
|
+
auth.expiresAt = credential.expiresAtMs;
|
|
4587
|
+
auth.lastRefreshTime = credential.lastRefreshAtMs ?? Date.now();
|
|
4588
|
+
document.auth = auth;
|
|
4589
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
4590
|
+
try {
|
|
4591
|
+
await writeFile(temporary, JSON.stringify(document, null, 2), { mode: 384 });
|
|
4592
|
+
if (beforeCommit !== void 0 && !await beforeCommit()) {
|
|
4593
|
+
await unlink(temporary).catch(() => {});
|
|
4594
|
+
return false;
|
|
4595
|
+
}
|
|
4596
|
+
await replaceFile(temporary, file);
|
|
4597
|
+
if (beforeCommit !== void 0 && !await beforeCommit()) {
|
|
4598
|
+
await unlink(file).catch(() => {});
|
|
4599
|
+
return false;
|
|
4600
|
+
}
|
|
4601
|
+
return true;
|
|
4602
|
+
} catch (error) {
|
|
4603
|
+
await unlink(temporary).catch(() => {});
|
|
4604
|
+
throw error;
|
|
4605
|
+
}
|
|
4606
|
+
});
|
|
3892
4607
|
}
|
|
3893
4608
|
/**
|
|
3894
4609
|
* Soonest future one-off expiry. Missing or past sorts last. None left -> list head.
|
|
@@ -3918,7 +4633,7 @@ function candidateAuthDirs(env = process.env) {
|
|
|
3918
4633
|
const dirs = [];
|
|
3919
4634
|
const override = nonEmptyEnv(env[WORKBUDDY_AUTH_FILE_ENV]);
|
|
3920
4635
|
if (override !== void 0) dirs.push(override.toLowerCase().endsWith(".info") ? resolve(override, "..") : override);
|
|
3921
|
-
dirs.push(...defaultDesktopAuthDirs());
|
|
4636
|
+
dirs.push(...defaultDesktopAuthDirs(process.platform, homedir(), env));
|
|
3922
4637
|
return dirs;
|
|
3923
4638
|
}
|
|
3924
4639
|
/**
|
|
@@ -3983,6 +4698,21 @@ async function readArchivedCredentials(file) {
|
|
|
3983
4698
|
}
|
|
3984
4699
|
return stored;
|
|
3985
4700
|
}
|
|
4701
|
+
async function removeAbandonedArchiveTemps(file) {
|
|
4702
|
+
const prefix = `${basename(file)}.`;
|
|
4703
|
+
let names;
|
|
4704
|
+
try {
|
|
4705
|
+
names = await readdir(dirname(file));
|
|
4706
|
+
} catch {
|
|
4707
|
+
return;
|
|
4708
|
+
}
|
|
4709
|
+
for (const name of names) {
|
|
4710
|
+
if (!name.startsWith(prefix) || !name.endsWith(".tmp")) continue;
|
|
4711
|
+
const id = name.slice(prefix.length, -4);
|
|
4712
|
+
if (!/^[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}$/iu.test(id)) continue;
|
|
4713
|
+
await unlink(join(dirname(file), name)).catch(() => {});
|
|
4714
|
+
}
|
|
4715
|
+
}
|
|
3986
4716
|
/**
|
|
3987
4717
|
* Write the archive, replacing the previous file only once the new one is whole.
|
|
3988
4718
|
*
|
|
@@ -3991,6 +4721,7 @@ async function readArchivedCredentials(file) {
|
|
|
3991
4721
|
* Only the archived credential is stored, not the raw sign-in document.
|
|
3992
4722
|
*/
|
|
3993
4723
|
async function writeArchivedCredentials(file, entries, signal) {
|
|
4724
|
+
signal?.throwIfAborted();
|
|
3994
4725
|
await mkdir(dirname(file), { recursive: true });
|
|
3995
4726
|
signal?.throwIfAborted();
|
|
3996
4727
|
const body = JSON.stringify({
|
|
@@ -4017,7 +4748,7 @@ async function writeArchivedCredentials(file, entries, signal) {
|
|
|
4017
4748
|
mode: 384
|
|
4018
4749
|
});
|
|
4019
4750
|
signal?.throwIfAborted();
|
|
4020
|
-
await
|
|
4751
|
+
await replaceFile(temporary, file);
|
|
4021
4752
|
} catch (error) {
|
|
4022
4753
|
await unlink(temporary).catch(() => {});
|
|
4023
4754
|
throw error;
|
|
@@ -4097,6 +4828,8 @@ var WorkBuddyAccountPool = class {
|
|
|
4097
4828
|
/** The directories the in-flight scan is reading, so a repoint supersedes it. */
|
|
4098
4829
|
scanDirs = [];
|
|
4099
4830
|
scanAbort = new AbortController();
|
|
4831
|
+
/** A committed delete retires scans that read the roster before it. */
|
|
4832
|
+
rosterRevision = 0;
|
|
4100
4833
|
/**
|
|
4101
4834
|
* Accounts whose "expired with no refresh token" warning has been logged.
|
|
4102
4835
|
*
|
|
@@ -4125,7 +4858,13 @@ var WorkBuddyAccountPool = class {
|
|
|
4125
4858
|
* a delete would hide the account from the pool while the user believed they
|
|
4126
4859
|
* were removing something the plugin had added.
|
|
4127
4860
|
*/
|
|
4128
|
-
|
|
4861
|
+
appHeldFiles = /* @__PURE__ */ new Map();
|
|
4862
|
+
/** An unreadable live sign-in whose account cannot be identified. */
|
|
4863
|
+
unknownLiveSignIn = false;
|
|
4864
|
+
/** Unknown live files stay protected while their directory cannot answer. */
|
|
4865
|
+
unknownLiveFiles = /* @__PURE__ */ new Set();
|
|
4866
|
+
/** Accounts whose desktop live sign-in is present but currently unreadable. */
|
|
4867
|
+
refreshBlockedIds = /* @__PURE__ */ new Set();
|
|
4129
4868
|
/**
|
|
4130
4869
|
* The sign-ins each account's own files hold, as of the last scan.
|
|
4131
4870
|
*
|
|
@@ -4238,7 +4977,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4238
4977
|
*/
|
|
4239
4978
|
ownsSignIn(accountId) {
|
|
4240
4979
|
const account = this.accounts.find((item) => item.id === accountId);
|
|
4241
|
-
if (account === void 0 || this.
|
|
4980
|
+
if (account === void 0 || this.unknownLiveSignIn || [...this.appHeldFiles.values()].includes(accountId)) return false;
|
|
4242
4981
|
return this.isOwnSignInPath(account.credential.sourcePath);
|
|
4243
4982
|
}
|
|
4244
4983
|
/**
|
|
@@ -4259,25 +4998,55 @@ var WorkBuddyAccountPool = class {
|
|
|
4259
4998
|
const account = this.accounts.find((item) => item.id === accountId);
|
|
4260
4999
|
if (account === void 0) return false;
|
|
4261
5000
|
if (!this.ownsSignIn(accountId)) return false;
|
|
5001
|
+
const ownedPath = account.credential.sourcePath;
|
|
5002
|
+
if (!this.isOwnSignInPath(ownedPath)) return false;
|
|
5003
|
+
const deletingCredential = account.credential;
|
|
5004
|
+
const sameCredential = (credential) => credential.accessToken === deletingCredential.accessToken && credential.refreshToken === deletingCredential.refreshToken;
|
|
4262
5005
|
const running = this.scanInflight;
|
|
4263
|
-
const
|
|
5006
|
+
const knownTombstones = await this.loadDeletedSignIns();
|
|
5007
|
+
if (knownTombstones === void 0) throw new Error("could not read the deleted sign-ins");
|
|
5008
|
+
const known = knownTombstones.has(account.id);
|
|
4264
5009
|
if (!await this.rememberDeletedSignIn(account.id, account.credential)) throw new Error("could not record the deleted sign-in");
|
|
4265
|
-
|
|
4266
|
-
|
|
5010
|
+
const settled = running === void 0 ? true : await raceWithTimeout(running.catch(() => {}), DELETE_SCAN_WAIT_MS);
|
|
5011
|
+
const current = this.accounts.find((item) => item.id === account.id);
|
|
5012
|
+
let replaced = current !== void 0 && (!this.ownsSignIn(account.id) || resolve(current.credential.sourcePath) !== resolve(ownedPath) || !sameCredential(current.credential));
|
|
5013
|
+
if (current === void 0) {
|
|
5014
|
+
const tombstone = (await this.loadDeletedSignIns())?.get(account.id);
|
|
5015
|
+
replaced = tombstone === void 0 || tombstone !== void 0 && endsTombstone(tombstone, deletingCredential);
|
|
5016
|
+
}
|
|
5017
|
+
const onDisk = await readCredential(ownedPath);
|
|
5018
|
+
if (!replaced) replaced = onDisk.kind === "sealed" || onDisk.kind === "unreadable" || onDisk.kind === "credential" && (workbuddyAccountId(onDisk.credential) !== account.id || !sameCredential(onDisk.credential));
|
|
5019
|
+
if (replaced) {
|
|
5020
|
+
if (!known) {
|
|
5021
|
+
knownTombstones.delete(account.id);
|
|
5022
|
+
await this.writeDeletedSignIns([account.id]);
|
|
5023
|
+
}
|
|
5024
|
+
return false;
|
|
4267
5025
|
}
|
|
4268
5026
|
try {
|
|
4269
|
-
|
|
5027
|
+
const tombstoneFile = this.deletedSignInsFile();
|
|
5028
|
+
if (tombstoneFile === void 0) await unlink(ownedPath);
|
|
5029
|
+
else await withFileLock(`${tombstoneFile}.lock`, async () => {
|
|
5030
|
+
await unlink(ownedPath);
|
|
5031
|
+
});
|
|
4270
5032
|
} catch (error) {
|
|
4271
5033
|
if (error.code !== "ENOENT") {
|
|
4272
5034
|
if (!known) {
|
|
4273
|
-
|
|
5035
|
+
knownTombstones.delete(account.id);
|
|
4274
5036
|
await this.writeDeletedSignIns([account.id]);
|
|
4275
5037
|
}
|
|
5038
|
+
this.rosterRevision += 1;
|
|
5039
|
+
await this.rescan().catch((rescanError) => {
|
|
5040
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not restore the roster after a failed delete: ${String(rescanError)}`);
|
|
5041
|
+
});
|
|
4276
5042
|
throw error;
|
|
4277
5043
|
}
|
|
4278
5044
|
}
|
|
5045
|
+
this.rosterRevision += 1;
|
|
5046
|
+
if (!settled) running.catch(() => {}).then(() => this.forgetArchived(account.id));
|
|
4279
5047
|
await this.forgetArchived(account.id);
|
|
4280
|
-
this.
|
|
5048
|
+
const remaining = this.accounts.find((item) => item.id === account.id);
|
|
5049
|
+
if (remaining === void 0 || this.isOwnSignInPath(remaining.credential.sourcePath) && resolve(remaining.credential.sourcePath) === resolve(ownedPath)) this.forgetAccount(account.id);
|
|
4281
5050
|
return true;
|
|
4282
5051
|
}
|
|
4283
5052
|
/** Drop one account and everything the pool remembers about it. */
|
|
@@ -4299,6 +5068,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4299
5068
|
*/
|
|
4300
5069
|
async rememberDeletedSignIn(id, credential) {
|
|
4301
5070
|
const tombstones = await this.loadDeletedSignIns();
|
|
5071
|
+
if (tombstones === void 0) return false;
|
|
4302
5072
|
const previous = tombstones.get(id);
|
|
4303
5073
|
tombstones.set(id, {
|
|
4304
5074
|
tokenDigest: tokenDigest(credential.accessToken),
|
|
@@ -4319,11 +5089,12 @@ var WorkBuddyAccountPool = class {
|
|
|
4319
5089
|
*/
|
|
4320
5090
|
async loadDeletedSignIns(signal) {
|
|
4321
5091
|
const file = this.deletedSignInsFile();
|
|
4322
|
-
const stamp = file === void 0 ?
|
|
5092
|
+
const stamp = file === void 0 ? MISSING_FILE_STAMP : await signInFileStamp(file);
|
|
5093
|
+
if (stamp === void 0) return void 0;
|
|
4323
5094
|
if (signal?.aborted) return this.deletedSignIns ?? /* @__PURE__ */ new Map();
|
|
4324
5095
|
if (this.deletedSignIns !== void 0 && this.deletedSignInsStamp === stamp) return this.deletedSignIns;
|
|
4325
5096
|
if (file === void 0) {
|
|
4326
|
-
this.deletedSignInsStamp =
|
|
5097
|
+
this.deletedSignInsStamp = MISSING_FILE_STAMP;
|
|
4327
5098
|
this.deletedSignIns = /* @__PURE__ */ new Map();
|
|
4328
5099
|
return this.deletedSignIns;
|
|
4329
5100
|
}
|
|
@@ -4335,13 +5106,14 @@ var WorkBuddyAccountPool = class {
|
|
|
4335
5106
|
return tombstones;
|
|
4336
5107
|
} catch (error) {
|
|
4337
5108
|
if (signal?.aborted) return this.deletedSignIns ?? /* @__PURE__ */ new Map();
|
|
4338
|
-
|
|
4339
|
-
|
|
5109
|
+
const code = error.code;
|
|
5110
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
5111
|
+
this.deletedSignInsStamp = MISSING_FILE_STAMP;
|
|
4340
5112
|
this.deletedSignIns = /* @__PURE__ */ new Map();
|
|
4341
5113
|
return this.deletedSignIns;
|
|
4342
5114
|
}
|
|
4343
5115
|
this.logger?.warn?.(`${LOG_PREFIX}: could not read the deleted sign-ins: ${String(error)}`);
|
|
4344
|
-
return this.deletedSignIns
|
|
5116
|
+
return this.deletedSignIns;
|
|
4345
5117
|
}
|
|
4346
5118
|
}
|
|
4347
5119
|
/**
|
|
@@ -4359,35 +5131,50 @@ var WorkBuddyAccountPool = class {
|
|
|
4359
5131
|
async writeDeletedSignIns(removed = [], signal) {
|
|
4360
5132
|
const tombstones = this.deletedSignIns;
|
|
4361
5133
|
const file = this.deletedSignInsFile();
|
|
4362
|
-
if (tombstones === void 0
|
|
5134
|
+
if (tombstones === void 0) return false;
|
|
5135
|
+
if (file === void 0) return true;
|
|
4363
5136
|
let written = false;
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
4383
|
-
const
|
|
4384
|
-
|
|
4385
|
-
|
|
4386
|
-
|
|
4387
|
-
|
|
4388
|
-
|
|
4389
|
-
|
|
4390
|
-
|
|
5137
|
+
try {
|
|
5138
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
5139
|
+
if (signal?.aborted) return;
|
|
5140
|
+
let onDisk;
|
|
5141
|
+
try {
|
|
5142
|
+
onDisk = await readDeletedSignInsFile(file);
|
|
5143
|
+
} catch (error) {
|
|
5144
|
+
if (error.code !== "ENOENT") {
|
|
5145
|
+
if (!signal?.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not merge the deleted sign-ins: ${String(error)}`);
|
|
5146
|
+
return;
|
|
5147
|
+
}
|
|
5148
|
+
onDisk = /* @__PURE__ */ new Map();
|
|
5149
|
+
}
|
|
5150
|
+
if (signal?.aborted) return;
|
|
5151
|
+
for (const [id, entry] of onDisk) {
|
|
5152
|
+
if (removed.includes(id)) continue;
|
|
5153
|
+
const ours = tombstones.get(id);
|
|
5154
|
+
if (ours === void 0 || entry.deletedAtMs > ours.deletedAtMs) tombstones.set(id, entry);
|
|
5155
|
+
}
|
|
5156
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
5157
|
+
try {
|
|
5158
|
+
signal?.throwIfAborted();
|
|
5159
|
+
await mkdir(dirname(file), { recursive: true });
|
|
5160
|
+
signal?.throwIfAborted();
|
|
5161
|
+
await writeFile(temporary, JSON.stringify({
|
|
5162
|
+
version: 1,
|
|
5163
|
+
entries: Object.fromEntries(tombstones)
|
|
5164
|
+
}, null, 2), { mode: 384 });
|
|
5165
|
+
signal?.throwIfAborted();
|
|
5166
|
+
await replaceFile(temporary, file);
|
|
5167
|
+
const stamp = await signInFileStamp(file);
|
|
5168
|
+
if (!signal?.aborted && this.deletedSignIns === tombstones) this.deletedSignInsStamp = stamp;
|
|
5169
|
+
written = true;
|
|
5170
|
+
} catch (error) {
|
|
5171
|
+
await unlink(temporary).catch(() => {});
|
|
5172
|
+
if (!signal?.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not record the deleted sign-ins: ${String(error)}`);
|
|
5173
|
+
}
|
|
5174
|
+
});
|
|
5175
|
+
} catch (error) {
|
|
5176
|
+
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
|
+
}
|
|
4391
5178
|
return written;
|
|
4392
5179
|
}
|
|
4393
5180
|
deletedSignInsFile() {
|
|
@@ -4435,10 +5222,10 @@ var WorkBuddyAccountPool = class {
|
|
|
4435
5222
|
* refreshing on its own schedule is how both end up with a spent refresh
|
|
4436
5223
|
* token. An account the client is signed into is skipped for the same reason.
|
|
4437
5224
|
*/
|
|
4438
|
-
async adoptOrphanedSignIns(found, tornDown, signal) {
|
|
5225
|
+
async adoptOrphanedSignIns(found, tornDown, sealedLiveIds, unknownLiveDirs, signal) {
|
|
4439
5226
|
const directory = ownSignInDir(this.dataPath?.() ?? "");
|
|
4440
5227
|
if (directory === "") return [];
|
|
4441
|
-
const liveIds =
|
|
5228
|
+
const liveIds = new Set(sealedLiveIds);
|
|
4442
5229
|
const ownedIds = /* @__PURE__ */ new Set();
|
|
4443
5230
|
for (const credential of found) {
|
|
4444
5231
|
const id = workbuddyAccountId(credential);
|
|
@@ -4451,7 +5238,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4451
5238
|
if (isLiveAuthFile(credential.sourcePath)) continue;
|
|
4452
5239
|
if (ownSignInPath(credential.sourcePath, directory)) continue;
|
|
4453
5240
|
const id = workbuddyAccountId(credential);
|
|
4454
|
-
if (liveIds.has(id) || ownedIds.has(id) || tornDown.has(id)) continue;
|
|
5241
|
+
if (unknownLiveDirs.has(this.homeOf(credential)) || liveIds.has(id) || ownedIds.has(id) || tornDown.has(id)) continue;
|
|
4455
5242
|
if ((credential.uin ?? credential.uid ?? credential.nickname ?? "") === "") continue;
|
|
4456
5243
|
let file;
|
|
4457
5244
|
try {
|
|
@@ -4479,22 +5266,48 @@ var WorkBuddyAccountPool = class {
|
|
|
4479
5266
|
* request already in flight. Anything that did not come from the plugin's own
|
|
4480
5267
|
* directory is left alone - the desktop app owns its files.
|
|
4481
5268
|
*/
|
|
4482
|
-
async renewOwnSignIn(credential) {
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not write the renewed token back for ${accountLogTag(credential.nickname ?? credential.uid)}: ${String(error)}`);
|
|
4488
|
-
}
|
|
4489
|
-
return;
|
|
4490
|
-
}
|
|
5269
|
+
async renewOwnSignIn(previous, credential) {
|
|
5270
|
+
const sinceMs = Date.now();
|
|
5271
|
+
const guard = async () => await this.deleteDidNotTake(credential, sinceMs);
|
|
5272
|
+
if (this.isOwnSignInPath(previous.sourcePath)) return await renewOwnSignInFile(previous.sourcePath, credential, previous, false, guard);
|
|
5273
|
+
if ((credential.uin ?? credential.uid ?? credential.nickname ?? "") === "") return true;
|
|
4491
5274
|
const directory = ownSignInDir(this.dataPath?.() ?? "");
|
|
4492
|
-
if (directory === "") return;
|
|
4493
|
-
|
|
4494
|
-
|
|
4495
|
-
|
|
4496
|
-
|
|
4497
|
-
|
|
5275
|
+
if (directory === "") return true;
|
|
5276
|
+
const file = ownSignInFile(directory, ownSignInOf(credential));
|
|
5277
|
+
if (!await guard()) return false;
|
|
5278
|
+
const written = await renewOwnSignInFile(file, credential, previous, true, guard);
|
|
5279
|
+
if (written) credential.sourcePath = file;
|
|
5280
|
+
return written;
|
|
5281
|
+
}
|
|
5282
|
+
/**
|
|
5283
|
+
* Whether a delete recorded elsewhere still stands against this sign-in.
|
|
5284
|
+
*
|
|
5285
|
+
* A delete records a tombstone, unlinks the file, and reports success. A
|
|
5286
|
+
* renewal in another pool over the same data directory used to race that: its
|
|
5287
|
+
* rename landed after the unlink, the file came back with a token issued
|
|
5288
|
+
* *after* the tombstone, and `endsTombstone` read the recreation as a
|
|
5289
|
+
* re-login and cleared the record - a deleted account came back.
|
|
5290
|
+
*
|
|
5291
|
+
* The test here is not `endsTombstone`, which asks whether the token is newer
|
|
5292
|
+
* than the delete and would call this very rotation a re-login. What matters
|
|
5293
|
+
* is the order of the two acts: a tombstone recorded after this renewal began
|
|
5294
|
+
* is the user deleting an account that was still there, so the write must not
|
|
5295
|
+
* land. `sinceMs` is when this renewal's token was minted - earlier than the
|
|
5296
|
+
* delete, which is exactly the case that used to resurrect the account.
|
|
5297
|
+
*
|
|
5298
|
+
* The set is read under the lock a delete writes it with, so a delete that
|
|
5299
|
+
* committed a moment ago is visible. Nothing blocking runs under that lock.
|
|
5300
|
+
*/
|
|
5301
|
+
async deleteDidNotTake(credential, sinceMs) {
|
|
5302
|
+
const file = this.deletedSignInsFile();
|
|
5303
|
+
if (file === void 0) return true;
|
|
5304
|
+
if (!await stat(file).then(() => true, (error) => error.code !== "ENOENT")) return true;
|
|
5305
|
+
let alive = true;
|
|
5306
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
5307
|
+
const tombstone = (await this.loadDeletedSignIns())?.get(workbuddyAccountId(credential));
|
|
5308
|
+
if (tombstone !== void 0 && tombstone.deletedAtMs >= sinceMs) alive = false;
|
|
5309
|
+
});
|
|
5310
|
+
return alive;
|
|
4498
5311
|
}
|
|
4499
5312
|
/**
|
|
4500
5313
|
* Drop one account from the credential archive.
|
|
@@ -4507,15 +5320,17 @@ var WorkBuddyAccountPool = class {
|
|
|
4507
5320
|
const file = this.archiveFile();
|
|
4508
5321
|
if (file === void 0) return;
|
|
4509
5322
|
const run = this.archiveQueue.then(async () => {
|
|
4510
|
-
|
|
4511
|
-
|
|
4512
|
-
|
|
5323
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
5324
|
+
const stored = await readArchivedCredentials(file);
|
|
5325
|
+
if (!stored.delete(id)) return;
|
|
5326
|
+
await writeArchivedCredentials(file, stored);
|
|
5327
|
+
});
|
|
4513
5328
|
});
|
|
4514
5329
|
this.archiveQueue = run.catch(() => {});
|
|
4515
5330
|
try {
|
|
4516
5331
|
await run;
|
|
4517
5332
|
} catch (error) {
|
|
4518
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not drop
|
|
5333
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not drop a sign-in from the credential archive: ${String(error)}`);
|
|
4519
5334
|
}
|
|
4520
5335
|
}
|
|
4521
5336
|
/** Drop every account, e.g. when the source is switched off. A later `scan()` rebuilds from disk. */
|
|
@@ -4525,7 +5340,10 @@ var WorkBuddyAccountPool = class {
|
|
|
4525
5340
|
this.scanInflight = void 0;
|
|
4526
5341
|
this.scanDirs = [];
|
|
4527
5342
|
this.accounts = [];
|
|
4528
|
-
this.
|
|
5343
|
+
this.appHeldFiles = /* @__PURE__ */ new Map();
|
|
5344
|
+
this.unknownLiveSignIn = false;
|
|
5345
|
+
this.unknownLiveFiles = /* @__PURE__ */ new Set();
|
|
5346
|
+
this.refreshBlockedIds = /* @__PURE__ */ new Set();
|
|
4529
5347
|
}
|
|
4530
5348
|
/** Read after any scan already running, so a manual request gets a fresh snapshot. */
|
|
4531
5349
|
async rescan() {
|
|
@@ -4574,18 +5392,20 @@ var WorkBuddyAccountPool = class {
|
|
|
4574
5392
|
if (file === void 0 || credentials.length === 0) return;
|
|
4575
5393
|
const ownDir = ownSignInDir(this.dataPath?.() ?? "");
|
|
4576
5394
|
const run = this.archiveQueue.then(async () => {
|
|
4577
|
-
|
|
4578
|
-
|
|
4579
|
-
|
|
4580
|
-
|
|
4581
|
-
|
|
4582
|
-
const
|
|
4583
|
-
|
|
4584
|
-
|
|
4585
|
-
|
|
4586
|
-
|
|
4587
|
-
|
|
4588
|
-
|
|
5395
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
5396
|
+
if (signal?.aborted) return;
|
|
5397
|
+
const stored = await readArchivedCredentials(file);
|
|
5398
|
+
if (signal?.aborted) return;
|
|
5399
|
+
let changed = false;
|
|
5400
|
+
for (const credential of credentials) {
|
|
5401
|
+
const id = workbuddyAccountId(credential);
|
|
5402
|
+
const previous = stored.get(id);
|
|
5403
|
+
if (previous !== void 0 && !isFresher(credential, previous, ownDir)) continue;
|
|
5404
|
+
stored.set(id, credential);
|
|
5405
|
+
changed = true;
|
|
5406
|
+
}
|
|
5407
|
+
if (changed) await writeArchivedCredentials(file, stored, signal);
|
|
5408
|
+
});
|
|
4589
5409
|
});
|
|
4590
5410
|
this.archiveQueue = run.catch(() => {});
|
|
4591
5411
|
try {
|
|
@@ -4599,7 +5419,12 @@ var WorkBuddyAccountPool = class {
|
|
|
4599
5419
|
const file = this.archiveFile();
|
|
4600
5420
|
if (file === void 0) return [];
|
|
4601
5421
|
try {
|
|
4602
|
-
|
|
5422
|
+
let stored = /* @__PURE__ */ new Map();
|
|
5423
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
5424
|
+
await removeAbandonedArchiveTemps(file);
|
|
5425
|
+
stored = await readArchivedCredentials(file);
|
|
5426
|
+
});
|
|
5427
|
+
return [...stored.values()].filter((credential) => homes.has(this.homeOf(credential)));
|
|
4603
5428
|
} catch (error) {
|
|
4604
5429
|
this.logger?.warn?.(`${LOG_PREFIX}: could not read the credential archive: ${String(error)}`);
|
|
4605
5430
|
return [];
|
|
@@ -4614,24 +5439,44 @@ var WorkBuddyAccountPool = class {
|
|
|
4614
5439
|
return directory === void 0 || directory === "" ? void 0 : join(directory, ARCHIVE_FILENAME);
|
|
4615
5440
|
}
|
|
4616
5441
|
async scanOnce(dirs, signal = this.scanAbort.signal) {
|
|
5442
|
+
const rosterRevision = this.rosterRevision;
|
|
4617
5443
|
const found = [];
|
|
4618
5444
|
const readableDirs = /* @__PURE__ */ new Set();
|
|
4619
5445
|
const sealedDirs = /* @__PURE__ */ new Set();
|
|
5446
|
+
const sealedFiles = /* @__PURE__ */ new Set();
|
|
5447
|
+
const sealedFileIds = /* @__PURE__ */ new Map();
|
|
5448
|
+
const unreadableFiles = /* @__PURE__ */ new Set();
|
|
5449
|
+
const unavailableDirs = /* @__PURE__ */ new Set();
|
|
4620
5450
|
for (const dir of dirs) {
|
|
4621
5451
|
if (signal.aborted) return this.accounts;
|
|
4622
|
-
const
|
|
5452
|
+
const read = await authFilesIn(dir);
|
|
4623
5453
|
if (signal.aborted) return this.accounts;
|
|
4624
|
-
if (files === void 0)
|
|
5454
|
+
if (read.files === void 0) {
|
|
5455
|
+
if (read.unavailable) unavailableDirs.add(resolve(dir));
|
|
5456
|
+
continue;
|
|
5457
|
+
}
|
|
4625
5458
|
readableDirs.add(resolve(dir));
|
|
4626
|
-
for (const file of files) {
|
|
4627
|
-
const
|
|
5459
|
+
for (const file of read.files) {
|
|
5460
|
+
const credentialRead = await readCredential(file);
|
|
4628
5461
|
if (signal.aborted) return this.accounts;
|
|
4629
|
-
if (
|
|
4630
|
-
else if (
|
|
5462
|
+
if (credentialRead.kind === "credential") found.push(credentialRead.credential);
|
|
5463
|
+
else if (credentialRead.kind === "sealed") {
|
|
5464
|
+
sealedDirs.add(resolve(dir));
|
|
5465
|
+
const resolvedFile = resolve(file);
|
|
5466
|
+
sealedFiles.add(resolvedFile);
|
|
5467
|
+
if (credentialRead.id !== void 0) sealedFileIds.set(resolvedFile, credentialRead.id);
|
|
5468
|
+
} else if (credentialRead.kind === "unreadable") {
|
|
5469
|
+
sealedDirs.add(resolve(dir));
|
|
5470
|
+
unreadableFiles.add(resolve(file));
|
|
5471
|
+
}
|
|
4631
5472
|
}
|
|
4632
5473
|
}
|
|
4633
5474
|
const tombstones = await this.loadDeletedSignIns(signal);
|
|
4634
|
-
if (signal.aborted) return this.accounts;
|
|
5475
|
+
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
5476
|
+
if (tombstones === void 0) {
|
|
5477
|
+
this.lastScanAtMs = Date.now();
|
|
5478
|
+
return this.accounts;
|
|
5479
|
+
}
|
|
4635
5480
|
const tornDown = /* @__PURE__ */ new Set();
|
|
4636
5481
|
const releasedIds = [];
|
|
4637
5482
|
const held = [];
|
|
@@ -4654,11 +5499,19 @@ var WorkBuddyAccountPool = class {
|
|
|
4654
5499
|
found.push(...held);
|
|
4655
5500
|
for (const id of tombstones.keys()) tornDown.add(id);
|
|
4656
5501
|
if (releasedIds.length > 0) await this.writeDeletedSignIns(releasedIds, signal);
|
|
4657
|
-
if (signal.aborted) return this.accounts;
|
|
5502
|
+
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
5503
|
+
const sealedLiveIds = new Set(sealedFileIds.values());
|
|
5504
|
+
for (let index = found.length - 1; index >= 0; index -= 1) {
|
|
5505
|
+
const credential = found[index];
|
|
5506
|
+
if (isLiveAuthFile(credential.sourcePath)) continue;
|
|
5507
|
+
if (ownSignInPath(credential.sourcePath, ownSignInDir(this.dataPath?.() ?? ""))) continue;
|
|
5508
|
+
const id = workbuddyAccountId(credential);
|
|
5509
|
+
if (sealedLiveIds.has(id) || sealedDirs.has(this.homeOf(credential))) found.splice(index, 1);
|
|
5510
|
+
}
|
|
4658
5511
|
await this.archiveCredentials(found, signal);
|
|
4659
|
-
if (signal.aborted) return this.accounts;
|
|
4660
|
-
found.push(...await this.adoptOrphanedSignIns(found, tornDown, signal));
|
|
4661
|
-
if (signal.aborted) return this.accounts;
|
|
5512
|
+
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
5513
|
+
found.push(...await this.adoptOrphanedSignIns(found, tornDown, sealedLiveIds, sealedDirs, signal));
|
|
5514
|
+
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
4662
5515
|
const signInTokens = /* @__PURE__ */ new Map();
|
|
4663
5516
|
for (const credential of found) {
|
|
4664
5517
|
const id = workbuddyAccountId(credential);
|
|
@@ -4667,15 +5520,31 @@ var WorkBuddyAccountPool = class {
|
|
|
4667
5520
|
else held.push(credential);
|
|
4668
5521
|
}
|
|
4669
5522
|
const liveIds = new Set(found.map((credential) => workbuddyAccountId(credential)));
|
|
4670
|
-
const appHeld =
|
|
5523
|
+
const appHeld = /* @__PURE__ */ new Map();
|
|
5524
|
+
for (const [file, id] of this.appHeldFiles) if (sealedFiles.has(file) || unreadableFiles.has(file) || !readableDirs.has(resolve(dirname(file)))) appHeld.set(file, id);
|
|
5525
|
+
for (const credential of found) if (isLiveAuthFile(credential.sourcePath)) appHeld.set(resolve(credential.sourcePath), workbuddyAccountId(credential));
|
|
5526
|
+
for (const [file, id] of sealedFileIds) if (isLiveAuthFile(file)) appHeld.set(file, id);
|
|
5527
|
+
const unknownLiveFiles = /* @__PURE__ */ new Set();
|
|
5528
|
+
for (const file of this.unknownLiveFiles) if (unreadableFiles.has(file) || !readableDirs.has(resolve(dirname(file)))) unknownLiveFiles.add(file);
|
|
5529
|
+
for (const file of sealedFiles) if (isLiveAuthFile(file) && !sealedFileIds.has(file)) unknownLiveFiles.add(file);
|
|
5530
|
+
for (const file of unreadableFiles) if (isLiveAuthFile(file)) unknownLiveFiles.add(file);
|
|
5531
|
+
const unknownLiveSignIn = unknownLiveFiles.size > 0 || unavailableDirs.size > 0;
|
|
5532
|
+
const refreshBlockedIds = /* @__PURE__ */ new Set();
|
|
5533
|
+
for (const [file, id] of appHeld) if (sealedFiles.has(file) || unreadableFiles.has(file) || unavailableDirs.has(resolve(dirname(file)))) refreshBlockedIds.add(id);
|
|
5534
|
+
for (const account of this.accounts) if (sealedFiles.has(resolve(account.credential.sourcePath)) || unreadableFiles.has(resolve(account.credential.sourcePath)) || unavailableDirs.has(this.homeOf(account.credential))) refreshBlockedIds.add(account.id);
|
|
4671
5535
|
const archived = await this.archivedCredentials(readableDirs);
|
|
4672
|
-
if (signal.aborted) return this.accounts;
|
|
5536
|
+
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
4673
5537
|
for (const credential of archived) {
|
|
4674
5538
|
const id = workbuddyAccountId(credential);
|
|
4675
5539
|
if (tornDown.has(id)) continue;
|
|
5540
|
+
if (!this.isOwnSignInPath(credential.sourcePath) && (sealedLiveIds.has(id) || sealedDirs.has(this.homeOf(credential)))) continue;
|
|
4676
5541
|
if (found.some((entry) => workbuddyAccountId(entry) === id && entry.accessToken === credential.accessToken)) continue;
|
|
4677
5542
|
found.push(credential);
|
|
4678
5543
|
}
|
|
5544
|
+
for (const credential of found) {
|
|
5545
|
+
const home = this.homeOf(credential);
|
|
5546
|
+
if (sealedDirs.has(home) || unavailableDirs.has(home)) refreshBlockedIds.add(workbuddyAccountId(credential));
|
|
5547
|
+
}
|
|
4679
5548
|
const byId = /* @__PURE__ */ new Map();
|
|
4680
5549
|
for (const account of this.accounts) byId.set(account.id, account);
|
|
4681
5550
|
for (const credential of found) {
|
|
@@ -4732,7 +5601,10 @@ var WorkBuddyAccountPool = class {
|
|
|
4732
5601
|
this.forgetAccount(id);
|
|
4733
5602
|
}
|
|
4734
5603
|
}
|
|
4735
|
-
this.
|
|
5604
|
+
this.appHeldFiles = appHeld;
|
|
5605
|
+
this.unknownLiveSignIn = unknownLiveSignIn;
|
|
5606
|
+
this.unknownLiveFiles = unknownLiveFiles;
|
|
5607
|
+
this.refreshBlockedIds = refreshBlockedIds;
|
|
4736
5608
|
const ordered = [...byId.values()];
|
|
4737
5609
|
ordered.sort((a, b) => compareQueueOrder(a.credential, b.credential, ownSignInDir(this.dataPath?.() ?? "")));
|
|
4738
5610
|
for (const account of ordered) {
|
|
@@ -4743,7 +5615,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4743
5615
|
else account.archived = true;
|
|
4744
5616
|
}
|
|
4745
5617
|
disambiguateLabels(ordered);
|
|
4746
|
-
if (!sameDirs(this.scanDirsFor(this.authDirs), dirs)) return this.accounts;
|
|
5618
|
+
if (!sameDirs(this.scanDirsFor(this.authDirs), dirs) || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
4747
5619
|
this.accounts = ordered;
|
|
4748
5620
|
this.signInTokens = signInTokens;
|
|
4749
5621
|
this.lastScanAtMs = Date.now();
|
|
@@ -5005,6 +5877,7 @@ var WorkBuddyAccountPool = class {
|
|
|
5005
5877
|
*/
|
|
5006
5878
|
async ensureFresh(account, forced = false) {
|
|
5007
5879
|
if (this.client === void 0) return "fresh";
|
|
5880
|
+
if (this.refreshBlockedIds.has(account.id)) return "fresh";
|
|
5008
5881
|
const credential = account.credential;
|
|
5009
5882
|
const issuedAt = credential.lastRefreshAtMs ?? 0;
|
|
5010
5883
|
const stale = this.isOwnSignInPath(credential.sourcePath) && issuedAt > 0 && Date.now() - issuedAt >= REFRESH_AFTER_MS;
|
|
@@ -5031,8 +5904,22 @@ var WorkBuddyAccountPool = class {
|
|
|
5031
5904
|
...outcome.domain === void 0 || outcome.domain === "" ? {} : { domain: outcome.domain },
|
|
5032
5905
|
lastRefreshAtMs: Date.now()
|
|
5033
5906
|
};
|
|
5907
|
+
let written;
|
|
5908
|
+
try {
|
|
5909
|
+
written = await this.renewOwnSignIn(credential, account.credential);
|
|
5910
|
+
} catch (error) {
|
|
5911
|
+
this.logger?.warn?.(`${LOG_PREFIX}: could not persist the renewed token for ${accountLogTag(account.label)}; keeping it in memory and the archive`, error);
|
|
5912
|
+
await this.archiveCredentials([account.credential]).catch((archiveError) => {
|
|
5913
|
+
this.logger?.error?.(`${LOG_PREFIX}: could not archive the renewed token for ${accountLogTag(account.label)}`, archiveError);
|
|
5914
|
+
});
|
|
5915
|
+
throw error;
|
|
5916
|
+
}
|
|
5917
|
+
if (!written) {
|
|
5918
|
+
account.credential = credential;
|
|
5919
|
+
await this.scan();
|
|
5920
|
+
return "fresh";
|
|
5921
|
+
}
|
|
5034
5922
|
await this.archiveCredentials([account.credential]);
|
|
5035
|
-
await this.renewOwnSignIn(account.credential);
|
|
5036
5923
|
this.noRefreshWarned.delete(account.id);
|
|
5037
5924
|
const sessionHold = this.heldIds.get(account.id);
|
|
5038
5925
|
if (sessionHold !== void 0 && sessionHold.reason === "session") {
|
|
@@ -5140,7 +6027,8 @@ var WorkBuddyAccountPool = class {
|
|
|
5140
6027
|
return {
|
|
5141
6028
|
count: this.accounts.length,
|
|
5142
6029
|
cooling: this.accounts.filter((account) => account.cooldownUntilMs > now).length,
|
|
5143
|
-
lastScanAtMs: this.lastScanAtMs
|
|
6030
|
+
lastScanAtMs: this.lastScanAtMs,
|
|
6031
|
+
scanning: this.scanInflight !== void 0
|
|
5144
6032
|
};
|
|
5145
6033
|
}
|
|
5146
6034
|
};
|
|
@@ -5210,13 +6098,6 @@ const FALLBACK_WORKBUDDY_MODELS = [
|
|
|
5210
6098
|
contextWindow: 2e5,
|
|
5211
6099
|
maxOutputTokens: 128e3,
|
|
5212
6100
|
supportsImages: true
|
|
5213
|
-
},
|
|
5214
|
-
{
|
|
5215
|
-
id: "hy4-preview",
|
|
5216
|
-
name: "Hy4-Preview",
|
|
5217
|
-
contextWindow: 1e6,
|
|
5218
|
-
maxOutputTokens: 128e3,
|
|
5219
|
-
supportsImages: true
|
|
5220
6101
|
}
|
|
5221
6102
|
];
|
|
5222
6103
|
/** Live catalog with a static fallback behind it. */
|
|
@@ -5527,17 +6408,51 @@ function completionState(data) {
|
|
|
5527
6408
|
try {
|
|
5528
6409
|
const parsed = JSON.parse(data);
|
|
5529
6410
|
const choices = Array.isArray(parsed.choices) ? parsed.choices : [];
|
|
6411
|
+
const toolCallIndices = choices.flatMap((choice, index) => Array.isArray(choice?.delta?.tool_calls) && choice.delta.tool_calls.length > 0 ? [typeof choice.index === "number" && Number.isInteger(choice.index) ? choice.index : index] : []);
|
|
5530
6412
|
return {
|
|
5531
6413
|
finished: choices.some((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason !== ""),
|
|
5532
|
-
toolCalls:
|
|
6414
|
+
toolCalls: toolCallIndices.length > 0,
|
|
6415
|
+
toolCallIndices
|
|
5533
6416
|
};
|
|
5534
6417
|
} catch {
|
|
5535
6418
|
return {
|
|
5536
6419
|
finished: false,
|
|
5537
|
-
toolCalls: false
|
|
6420
|
+
toolCalls: false,
|
|
6421
|
+
toolCallIndices: []
|
|
5538
6422
|
};
|
|
5539
6423
|
}
|
|
5540
6424
|
}
|
|
6425
|
+
function completedToolCallData(data, toolCallIndices) {
|
|
6426
|
+
if (toolCallIndices.size === 0) return void 0;
|
|
6427
|
+
try {
|
|
6428
|
+
const parsed = JSON.parse(data);
|
|
6429
|
+
if (!Array.isArray(parsed.choices)) return void 0;
|
|
6430
|
+
let changed = false;
|
|
6431
|
+
for (const [index, choice] of parsed.choices.entries()) {
|
|
6432
|
+
const choiceIndex = typeof choice?.index === "number" && Number.isInteger(choice.index) ? choice.index : index;
|
|
6433
|
+
if (choice?.finish_reason === "stop" && toolCallIndices.has(choiceIndex)) {
|
|
6434
|
+
choice.finish_reason = "tool_calls";
|
|
6435
|
+
changed = true;
|
|
6436
|
+
}
|
|
6437
|
+
}
|
|
6438
|
+
return changed ? JSON.stringify(parsed) : void 0;
|
|
6439
|
+
} catch {
|
|
6440
|
+
return;
|
|
6441
|
+
}
|
|
6442
|
+
}
|
|
6443
|
+
function eventWithData(raw, data, finishTail) {
|
|
6444
|
+
const separator = /\r\n|\r|\n/.exec(raw)?.[0] ?? "\n";
|
|
6445
|
+
const lines = raw.split(/\r\n|\r|\n/);
|
|
6446
|
+
const output = [];
|
|
6447
|
+
let replaced = false;
|
|
6448
|
+
for (const line of lines) if (line === "data" || line.startsWith("data:")) {
|
|
6449
|
+
if (!replaced) output.push("data: " + data);
|
|
6450
|
+
replaced = true;
|
|
6451
|
+
} else output.push(line);
|
|
6452
|
+
let frame = replaced ? output.join(separator) : "data: " + data;
|
|
6453
|
+
if (finishTail && !/(?:\r\n|\r|\n){2}$/u.test(frame)) frame += separator + separator;
|
|
6454
|
+
return Buffer.from(frame);
|
|
6455
|
+
}
|
|
5541
6456
|
/** HTTP status each upstream failure class surfaces as. */
|
|
5542
6457
|
const KIND_STATUS = {
|
|
5543
6458
|
hard_credit: 402,
|
|
@@ -5572,6 +6487,17 @@ const MODEL_TIER_HOLD_MS = 864e5;
|
|
|
5572
6487
|
*/
|
|
5573
6488
|
const MAX_TRANSPORT_ATTEMPTS = 2;
|
|
5574
6489
|
/**
|
|
6490
|
+
* How many accounts one request may lose to a 200 that ended before its first
|
|
6491
|
+
* byte.
|
|
6492
|
+
*
|
|
6493
|
+
* Not a small fixed number: an empty stream is an *answer*, so the host is
|
|
6494
|
+
* reachable and the account behind the next one is worth trying. Two dead
|
|
6495
|
+
* streams in a row used to end the turn through the transport cap and left a
|
|
6496
|
+
* healthy third account untried. The bound is the pool's own size, so every
|
|
6497
|
+
* account gets its turn once and the loop still cannot walk forever.
|
|
6498
|
+
*/
|
|
6499
|
+
const emptyStreamAttemptsFor = (poolSize) => Math.max(3, poolSize);
|
|
6500
|
+
/**
|
|
5575
6501
|
* The business code an account-level 200 envelope carries.
|
|
5576
6502
|
*
|
|
5577
6503
|
* `classifyUpstreamError` only reads codes on the statuses the upstream uses
|
|
@@ -5862,11 +6788,19 @@ function createWorkBuddyShim(options) {
|
|
|
5862
6788
|
const prepared = client.prepareChatBody(raw);
|
|
5863
6789
|
const conversationKey = conversationKeyOf(raw);
|
|
5864
6790
|
let modelId;
|
|
6791
|
+
let bodyIsJson = true;
|
|
5865
6792
|
try {
|
|
5866
6793
|
const parsed = JSON.parse(raw);
|
|
5867
|
-
|
|
6794
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
6795
|
+
const model = parsed.model;
|
|
6796
|
+
modelId = typeof model === "string" && model !== "" ? model : void 0;
|
|
6797
|
+
}
|
|
5868
6798
|
} catch {
|
|
5869
|
-
|
|
6799
|
+
bodyIsJson = false;
|
|
6800
|
+
}
|
|
6801
|
+
if (!bodyIsJson) {
|
|
6802
|
+
writeOpenAIError(res, 400, "invalid_request_error", "body is not valid JSON");
|
|
6803
|
+
return;
|
|
5870
6804
|
}
|
|
5871
6805
|
if (modelId === void 0) {
|
|
5872
6806
|
writeOpenAIError(res, 400, "invalid_request_error", "model is required");
|
|
@@ -5875,19 +6809,21 @@ function createWorkBuddyShim(options) {
|
|
|
5875
6809
|
let tried = 0;
|
|
5876
6810
|
const skipped = /* @__PURE__ */ new Set();
|
|
5877
6811
|
let last;
|
|
5878
|
-
let
|
|
6812
|
+
let accountSkipped = false;
|
|
5879
6813
|
let transportAttempts = 0;
|
|
6814
|
+
let emptyStreams = 0;
|
|
5880
6815
|
let effortFallback;
|
|
5881
6816
|
let effortFallbackBuilt = false;
|
|
5882
6817
|
const maxAttempts = Math.max(8, pool.list(region).length + 2);
|
|
6818
|
+
const maxEmptyStreams = emptyStreamAttemptsFor(pool.list(region).length);
|
|
5883
6819
|
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
5884
6820
|
if (controller.signal.aborted) return;
|
|
5885
6821
|
const account = await pool.acquire(modelId, region, conversationKey, skipped);
|
|
5886
6822
|
if (account === void 0) {
|
|
5887
|
-
if (
|
|
6823
|
+
if (accountSkipped && last !== void 0) {
|
|
5888
6824
|
const model = ` for model ${modelId}`;
|
|
5889
|
-
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" ? `the upstream host could not be reached on any account${model}` : `every account is rate-limited${model}`;
|
|
5890
|
-
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" ? "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";
|
|
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";
|
|
5891
6827
|
if (last.kind === "soft_rate") {
|
|
5892
6828
|
const live = pool.list(region).filter((candidate) => !pool.isDisabled(candidate.id));
|
|
5893
6829
|
const wait = unavailableAnswer(pool, live, Date.now(), modelId).retryAfterSeconds;
|
|
@@ -5927,7 +6863,7 @@ function createWorkBuddyShim(options) {
|
|
|
5927
6863
|
status: 502,
|
|
5928
6864
|
message: `could not refresh the sign-in: ${failure.message}`
|
|
5929
6865
|
};
|
|
5930
|
-
|
|
6866
|
+
accountSkipped = true;
|
|
5931
6867
|
continue;
|
|
5932
6868
|
}
|
|
5933
6869
|
}
|
|
@@ -5951,8 +6887,10 @@ function createWorkBuddyShim(options) {
|
|
|
5951
6887
|
let sawDone = false;
|
|
5952
6888
|
let sawFinish = false;
|
|
5953
6889
|
let sawToolCalls = false;
|
|
6890
|
+
const sawToolCallChoices = /* @__PURE__ */ new Set();
|
|
5954
6891
|
let envelopeFailure;
|
|
5955
6892
|
let headFailure;
|
|
6893
|
+
let headIsEmptyStream = false;
|
|
5956
6894
|
const decoder = new TextDecoder();
|
|
5957
6895
|
const frames = [];
|
|
5958
6896
|
const sse = new SseDecoder((raw, event) => frames.push({
|
|
@@ -6009,7 +6947,7 @@ function createWorkBuddyShim(options) {
|
|
|
6009
6947
|
}
|
|
6010
6948
|
const relayFrames = async (finishTail = false) => {
|
|
6011
6949
|
for (const { raw, event } of frames.splice(0)) {
|
|
6012
|
-
|
|
6950
|
+
let chunk = Buffer.from(finishTail ? raw + "\n\n" : raw);
|
|
6013
6951
|
if (event?.data === "[DONE]") {
|
|
6014
6952
|
if (!sawFinish) {
|
|
6015
6953
|
await writeChunk(res, finishChunk());
|
|
@@ -6025,6 +6963,11 @@ function createWorkBuddyShim(options) {
|
|
|
6025
6963
|
const state = completionState(event.data);
|
|
6026
6964
|
sawFinish ||= state.finished;
|
|
6027
6965
|
sawToolCalls ||= state.toolCalls;
|
|
6966
|
+
for (const index of state.toolCallIndices) sawToolCallChoices.add(index);
|
|
6967
|
+
if (state.finished) {
|
|
6968
|
+
const data = completedToolCallData(event.data, sawToolCallChoices);
|
|
6969
|
+
if (data !== void 0) chunk = eventWithData(raw, data, finishTail);
|
|
6970
|
+
}
|
|
6028
6971
|
}
|
|
6029
6972
|
await writeChunk(res, chunk);
|
|
6030
6973
|
}
|
|
@@ -6041,6 +6984,7 @@ function createWorkBuddyShim(options) {
|
|
|
6041
6984
|
await reader.cancel().catch(() => {});
|
|
6042
6985
|
if (peeked.ended && peeked.refusal === EMPTY_STREAM_REFUSAL) {
|
|
6043
6986
|
headFailure = peeked.refusal;
|
|
6987
|
+
headIsEmptyStream = true;
|
|
6044
6988
|
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with an empty stream; rotating`);
|
|
6045
6989
|
return;
|
|
6046
6990
|
}
|
|
@@ -6056,7 +7000,7 @@ function createWorkBuddyShim(options) {
|
|
|
6056
7000
|
status: 200,
|
|
6057
7001
|
message: peeked.refusal
|
|
6058
7002
|
};
|
|
6059
|
-
|
|
7003
|
+
accountSkipped = true;
|
|
6060
7004
|
envelopeFailure = envelopeKind;
|
|
6061
7005
|
if (envelopeKind === "soft_rate") {
|
|
6062
7006
|
const bodyReset = parseRateLimitReset(peeked.body ?? peeked.refusal);
|
|
@@ -6126,10 +7070,17 @@ function createWorkBuddyShim(options) {
|
|
|
6126
7070
|
status: 502,
|
|
6127
7071
|
message: headFailure
|
|
6128
7072
|
};
|
|
6129
|
-
|
|
7073
|
+
accountSkipped = true;
|
|
6130
7074
|
skipped.add(account.id);
|
|
6131
|
-
|
|
6132
|
-
if (
|
|
7075
|
+
let spent;
|
|
7076
|
+
if (headIsEmptyStream) {
|
|
7077
|
+
emptyStreams += 1;
|
|
7078
|
+
spent = emptyStreams >= maxEmptyStreams;
|
|
7079
|
+
} else {
|
|
7080
|
+
transportAttempts += 1;
|
|
7081
|
+
spent = transportAttempts >= MAX_TRANSPORT_ATTEMPTS;
|
|
7082
|
+
}
|
|
7083
|
+
if (spent) break;
|
|
6133
7084
|
continue;
|
|
6134
7085
|
}
|
|
6135
7086
|
if (envelopeFailure === void 0) return;
|
|
@@ -6175,7 +7126,7 @@ function createWorkBuddyShim(options) {
|
|
|
6175
7126
|
status: result.status,
|
|
6176
7127
|
message: result.message
|
|
6177
7128
|
};
|
|
6178
|
-
|
|
7129
|
+
accountSkipped = true;
|
|
6179
7130
|
skipped.add(account.id);
|
|
6180
7131
|
transportAttempts += 1;
|
|
6181
7132
|
if (transportAttempts >= MAX_TRANSPORT_ATTEMPTS) break;
|
|
@@ -6183,7 +7134,7 @@ function createWorkBuddyShim(options) {
|
|
|
6183
7134
|
continue;
|
|
6184
7135
|
}
|
|
6185
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;
|
|
6186
|
-
|
|
7137
|
+
accountSkipped = true;
|
|
6187
7138
|
if (result.kind === "soft_rate") {
|
|
6188
7139
|
const bodyReset = parseRateLimitReset(result.message);
|
|
6189
7140
|
const headerReset = resetFromRetryAfter(result.retryAfter);
|
|
@@ -7166,7 +8117,7 @@ function buildTraeHeaders(credential, identity, options = {}) {
|
|
|
7166
8117
|
"request-traffic-type": "prod",
|
|
7167
8118
|
"Content-Type": "application/json",
|
|
7168
8119
|
"X-Cloudide-Token": credential.accessToken,
|
|
7169
|
-
"x-uid": credential.userId,
|
|
8120
|
+
...credential.userId === "" ? {} : { "x-uid": credential.userId },
|
|
7170
8121
|
"x-request-id": requestId,
|
|
7171
8122
|
"x-trae-request-id": requestId,
|
|
7172
8123
|
"Accept": "text/event-stream"
|
|
@@ -7862,6 +8813,14 @@ var TraeSoloUpstreamClient = class {
|
|
|
7862
8813
|
* this.
|
|
7863
8814
|
*/
|
|
7864
8815
|
/**
|
|
8816
|
+
* The failure class of a refused peek, carried on the response the peek returns.
|
|
8817
|
+
*
|
|
8818
|
+
* A status code alone cannot separate "this sign-in answered nothing" from "the
|
|
8819
|
+
* service is down for everyone": both are 502, and only the first belongs to
|
|
8820
|
+
* the account. The gateway reads the class from this header.
|
|
8821
|
+
*/
|
|
8822
|
+
const TRAE_FAILURE_KIND_HEADER = "x-wtq-failure-kind";
|
|
8823
|
+
/**
|
|
7865
8824
|
* Words a Trae refusal uses for a sign-in the upstream no longer accepts.
|
|
7866
8825
|
*
|
|
7867
8826
|
* Trae answers a stale login inside the stream, on the same `event: error`
|
|
@@ -7871,6 +8830,12 @@ var TraeSoloUpstreamClient = class {
|
|
|
7871
8830
|
* every request paid one round trip and the healthy sign-ins beside it were
|
|
7872
8831
|
* never tried. The Qoder path in this same plugin classifies the identical
|
|
7873
8832
|
* frame as an authentication failure.
|
|
8833
|
+
*
|
|
8834
|
+
* The list is English because those are the sentences this plugin has seen on
|
|
8835
|
+
* the wire. A code-less refusal in any other language falls to the `server`
|
|
8836
|
+
* class below: the turn is answered 502 and no account is cooled. Widening the
|
|
8837
|
+
* list needs a captured frame, because a phrase that also appears in a real
|
|
8838
|
+
* outage would cool healthy sign-ins.
|
|
7874
8839
|
*/
|
|
7875
8840
|
const TRAE_SIGN_IN_PATTERN = /login expired|not logged in|unauthori[sz]ed|invalid token|token.*(expire|invalid)|\b9095\b/i;
|
|
7876
8841
|
/** Trae's tool calls arrive under either `function_call` or `function`. */
|
|
@@ -8277,9 +9242,9 @@ function bridgeTraeStream(source, model, options = {}) {
|
|
|
8277
9242
|
*/
|
|
8278
9243
|
async function openTraeResponse(response, model, options = {}) {
|
|
8279
9244
|
if (!response.ok) {
|
|
8280
|
-
const detail =
|
|
9245
|
+
const detail = await readErrorBody(response, 1024, void 0, options.refusalReadMs);
|
|
8281
9246
|
return Response.json({ error: {
|
|
8282
|
-
message: detail === "" ? `Trae SOLO returned HTTP ${response.status}` : detail,
|
|
9247
|
+
message: detail === "" ? `Trae SOLO returned HTTP ${response.status}` : redactSecrets(detail),
|
|
8283
9248
|
type: "upstream_error",
|
|
8284
9249
|
code: response.status
|
|
8285
9250
|
} }, { status: response.status });
|
|
@@ -8336,7 +9301,21 @@ async function openTraeResponse(response, model, options = {}) {
|
|
|
8336
9301
|
code: kind === "hard_credit" ? 402 : status
|
|
8337
9302
|
} }, {
|
|
8338
9303
|
status,
|
|
8339
|
-
|
|
9304
|
+
headers: {
|
|
9305
|
+
[TRAE_FAILURE_KIND_HEADER]: kind,
|
|
9306
|
+
...wait === void 0 ? {} : { "Retry-After": wait }
|
|
9307
|
+
}
|
|
9308
|
+
});
|
|
9309
|
+
}
|
|
9310
|
+
if (failure === void 0 && bufferedBytes === 0 && ended) {
|
|
9311
|
+
await reader.cancel().catch(() => {});
|
|
9312
|
+
return Response.json({ error: {
|
|
9313
|
+
message: "Trae SOLO returned an empty answer stream",
|
|
9314
|
+
type: "upstream_error",
|
|
9315
|
+
code: 502
|
|
9316
|
+
} }, {
|
|
9317
|
+
status: 502,
|
|
9318
|
+
headers: { [TRAE_FAILURE_KIND_HEADER]: "empty_stream" }
|
|
8340
9319
|
});
|
|
8341
9320
|
}
|
|
8342
9321
|
const relay = bridgeTraeStream(replaySource(buffered, reader, ended), model, options);
|
|
@@ -8448,10 +9427,15 @@ function createTraeGateway(options) {
|
|
|
8448
9427
|
res.on("close", () => watcher.abort());
|
|
8449
9428
|
const raw = (await readRequestBody(req)).toString("utf8");
|
|
8450
9429
|
let model = "";
|
|
9430
|
+
let bodyIsJson = true;
|
|
8451
9431
|
try {
|
|
8452
9432
|
model = JSON.parse(raw)["model"] ?? "";
|
|
8453
9433
|
} catch {
|
|
8454
|
-
|
|
9434
|
+
bodyIsJson = false;
|
|
9435
|
+
}
|
|
9436
|
+
if (!bodyIsJson) {
|
|
9437
|
+
writeOpenAIError(res, 400, "invalid_request_error", "body is not valid JSON");
|
|
9438
|
+
return;
|
|
8455
9439
|
}
|
|
8456
9440
|
if (typeof model !== "string" || model.trim() === "") {
|
|
8457
9441
|
writeOpenAIError(res, 400, "invalid_request_error", "model is required");
|
|
@@ -8553,11 +9537,13 @@ function createTraeGateway(options) {
|
|
|
8553
9537
|
}
|
|
8554
9538
|
if (relayed.status !== 200) {
|
|
8555
9539
|
const detail = await relayed.text().catch(() => "");
|
|
9540
|
+
const failedKind = relayed.headers.get(TRAE_FAILURE_KIND_HEADER);
|
|
8556
9541
|
return {
|
|
8557
9542
|
ok: false,
|
|
8558
9543
|
status: relayed.status,
|
|
8559
9544
|
message: detail,
|
|
8560
|
-
retryAfter: relayed.headers.get("retry-after")
|
|
9545
|
+
retryAfter: relayed.headers.get("retry-after"),
|
|
9546
|
+
...failedKind === null ? {} : { kind: failedKind }
|
|
8561
9547
|
};
|
|
8562
9548
|
}
|
|
8563
9549
|
return {
|
|
@@ -8574,7 +9560,7 @@ function createTraeGateway(options) {
|
|
|
8574
9560
|
const rotates = (status, kind) => {
|
|
8575
9561
|
if (kind === "aborted") return false;
|
|
8576
9562
|
if (status === 0) return true;
|
|
8577
|
-
return kind === "authentication" || kind === "soft_rate" || kind === "hard_credit" || status === 401 || status === 402 || status === 429;
|
|
9563
|
+
return kind === "authentication" || kind === "soft_rate" || kind === "hard_credit" || kind === "empty_stream" || status === 401 || status === 402 || status === 429;
|
|
8578
9564
|
};
|
|
8579
9565
|
let opened;
|
|
8580
9566
|
for (let index = 0; index < credentials.length; index += 1) {
|
|
@@ -9019,6 +10005,7 @@ const DPAPI_PREFIX = "DPAPI";
|
|
|
9019
10005
|
*/
|
|
9020
10006
|
const DPAPI_SCRIPT = `
|
|
9021
10007
|
$ErrorActionPreference = 'Stop'
|
|
10008
|
+
$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules')
|
|
9022
10009
|
Add-Type -TypeDefinition @'
|
|
9023
10010
|
using System;
|
|
9024
10011
|
using System.Runtime.InteropServices;
|
|
@@ -9053,27 +10040,6 @@ var QoderKeyError = class extends Error {
|
|
|
9053
10040
|
this.name = "QoderKeyError";
|
|
9054
10041
|
}
|
|
9055
10042
|
};
|
|
9056
|
-
function powershellPath(env) {
|
|
9057
|
-
const systemRoot = env.SystemRoot ?? env.windir;
|
|
9058
|
-
if (systemRoot === void 0 || systemRoot === "") return void 0;
|
|
9059
|
-
return join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
9060
|
-
}
|
|
9061
|
-
/** Run the interpreter with a whitelisted environment; nothing user-set rides along. */
|
|
9062
|
-
function childEnv(env) {
|
|
9063
|
-
const allowed = [
|
|
9064
|
-
"SystemRoot",
|
|
9065
|
-
"SystemDrive",
|
|
9066
|
-
"windir",
|
|
9067
|
-
"TEMP",
|
|
9068
|
-
"TMP"
|
|
9069
|
-
];
|
|
9070
|
-
const result = {};
|
|
9071
|
-
for (const name of allowed) {
|
|
9072
|
-
const value = env[name];
|
|
9073
|
-
if (typeof value === "string" && value !== "") result[name] = value;
|
|
9074
|
-
}
|
|
9075
|
-
return result;
|
|
9076
|
-
}
|
|
9077
10043
|
/**
|
|
9078
10044
|
* Unwrap the AES key an app's `Local State` keeps under `os_crypt`.
|
|
9079
10045
|
*
|
|
@@ -9104,7 +10070,7 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
|
|
|
9104
10070
|
} catch {}
|
|
9105
10071
|
const cached = oscryptKeyCache.get(localStatePath);
|
|
9106
10072
|
if (cached !== void 0 && cached.mtimeMs === mtimeMs) return Buffer.from(cached.key);
|
|
9107
|
-
const exe =
|
|
10073
|
+
const exe = trustedWindowsPowerShell(env);
|
|
9108
10074
|
if (exe === void 0) throw new QoderKeyError("unavailable", "SystemRoot is not set, cannot locate PowerShell");
|
|
9109
10075
|
const stdout = await new Promise((resolve, reject) => {
|
|
9110
10076
|
const child = spawn(exe, [
|
|
@@ -9113,7 +10079,10 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
|
|
|
9113
10079
|
"-Command",
|
|
9114
10080
|
DPAPI_SCRIPT
|
|
9115
10081
|
], {
|
|
9116
|
-
env:
|
|
10082
|
+
env: trustedWindowsChildEnv(env, {
|
|
10083
|
+
inheritTemp: true,
|
|
10084
|
+
includeSystemDrive: true
|
|
10085
|
+
}),
|
|
9117
10086
|
windowsHide: true,
|
|
9118
10087
|
stdio: [
|
|
9119
10088
|
"pipe",
|
|
@@ -9471,38 +10440,279 @@ function buildCosyAuthHeaders(body, url, credential) {
|
|
|
9471
10440
|
};
|
|
9472
10441
|
}
|
|
9473
10442
|
//#endregion
|
|
9474
|
-
//#region src/qoder-
|
|
10443
|
+
//#region src/qoder-sse.ts
|
|
10444
|
+
function isPlainObject(value) {
|
|
10445
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10446
|
+
}
|
|
10447
|
+
function tryJsonObject(text) {
|
|
10448
|
+
try {
|
|
10449
|
+
const parsed = JSON.parse(text);
|
|
10450
|
+
return isPlainObject(parsed) ? parsed : void 0;
|
|
10451
|
+
} catch {
|
|
10452
|
+
return;
|
|
10453
|
+
}
|
|
10454
|
+
}
|
|
9475
10455
|
/**
|
|
9476
|
-
* Qoder
|
|
9477
|
-
*
|
|
9478
|
-
* Fetches the callable roster and opens one chat stream. No disk reads here;
|
|
9479
|
-
* tokens stay in the caller's memory.
|
|
9480
|
-
*
|
|
9481
|
-
* Shapes follow `dsh-connect-qoder` (MIT): the `algo/api/v2/model/list`
|
|
9482
|
-
* envelope groups its models by product surface, and only the `chat` group is
|
|
9483
|
-
* callable. Chat requests normalise `developer` to `system`, because a system
|
|
9484
|
-
* message the gateway does not recognise is answered with a permanent
|
|
9485
|
-
* `403 {"code":"10605"}` on every retry.
|
|
9486
|
-
*
|
|
9487
|
-
* Everything the client needs from the outside is injected (credential,
|
|
9488
|
-
* `fetchImpl`), so the whole path can be exercised offline.
|
|
10456
|
+
* Whether a code is the success-range acknowledgement Qoder sends for a
|
|
10457
|
+
* container it accepted. `{"code":0}` and `{"code":200}` are how it acks.
|
|
9489
10458
|
*
|
|
9490
|
-
*
|
|
10459
|
+
* Exported because the check-in parser asks the same question: it treated any
|
|
10460
|
+
* non-zero code as a refusal, so a claim acknowledged with `{"code":200}`
|
|
10461
|
+
* reached the panel as "the upstream refused it". One answer to one question.
|
|
9491
10462
|
*/
|
|
9492
|
-
|
|
9493
|
-
|
|
9494
|
-
"
|
|
9495
|
-
|
|
9496
|
-
|
|
9497
|
-
|
|
9498
|
-
"xhigh",
|
|
9499
|
-
"max"
|
|
9500
|
-
];
|
|
10463
|
+
function isAcknowledgementCode(value) {
|
|
10464
|
+
if (typeof value !== "string" && typeof value !== "number") return false;
|
|
10465
|
+
if (typeof value === "string" && value.length === 0) return false;
|
|
10466
|
+
const code = Number(value);
|
|
10467
|
+
return Number.isFinite(code) && (code === 0 || code >= 200 && code < 300);
|
|
10468
|
+
}
|
|
9501
10469
|
/**
|
|
9502
|
-
* The
|
|
9503
|
-
*
|
|
9504
|
-
*
|
|
9505
|
-
|
|
10470
|
+
* The code and message a failure frame really carries, however deeply they are
|
|
10471
|
+
* wrapped. The walk follows `details`/`error`, or a `message` string that is
|
|
10472
|
+
* itself a JSON document, up to 8 levels — bounded so a self-referential
|
|
10473
|
+
* payload cannot spin. When it bottoms out on an object (the queue descriptor),
|
|
10474
|
+
* that object is far more useful than the string that carried it.
|
|
10475
|
+
*/
|
|
10476
|
+
function unwrapFailure(frame) {
|
|
10477
|
+
let code = "";
|
|
10478
|
+
let detail = "";
|
|
10479
|
+
const signals = [];
|
|
10480
|
+
let node = frame;
|
|
10481
|
+
let descended = false;
|
|
10482
|
+
let codeFromPlainKey = false;
|
|
10483
|
+
let codeFromErrorSpelling = false;
|
|
10484
|
+
let arrivedViaContainer = false;
|
|
10485
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
10486
|
+
if (!isPlainObject(node)) break;
|
|
10487
|
+
const errorSpelling = node["errorCode"] ?? node["errcode"];
|
|
10488
|
+
const levelCode = errorSpelling ?? node["code"];
|
|
10489
|
+
const acknowledgement = arrivedViaContainer && codeFromPlainKey && isAcknowledgementCode(levelCode);
|
|
10490
|
+
if (errorSpelling !== void 0 || !codeFromErrorSpelling && !acknowledgement) {
|
|
10491
|
+
if (typeof levelCode === "string" && levelCode.length > 0) {
|
|
10492
|
+
code = levelCode;
|
|
10493
|
+
codeFromPlainKey = errorSpelling === void 0;
|
|
10494
|
+
codeFromErrorSpelling = errorSpelling !== void 0;
|
|
10495
|
+
} else if (typeof levelCode === "number" && Number.isFinite(levelCode)) {
|
|
10496
|
+
code = String(levelCode);
|
|
10497
|
+
codeFromPlainKey = errorSpelling === void 0;
|
|
10498
|
+
codeFromErrorSpelling = errorSpelling !== void 0;
|
|
10499
|
+
}
|
|
10500
|
+
}
|
|
10501
|
+
const message = node["message"] ?? node["errorMessage"];
|
|
10502
|
+
if (typeof message === "string" && message.trim() !== "" && !signals.includes(message)) signals.push(message);
|
|
10503
|
+
if ((detail === "" || tryJsonObject(detail) !== void 0) && typeof message === "string" && message.length > 0) detail = message;
|
|
10504
|
+
const flat = typeof node["error"] === "string" ? node["error"] : typeof node["details"] === "string" ? node["details"] : void 0;
|
|
10505
|
+
if (flat !== void 0 && flat.trim() !== "" && !signals.includes(flat)) signals.push(flat);
|
|
10506
|
+
if (detail === "" && flat !== void 0 && flat.length > 0) detail = flat;
|
|
10507
|
+
const nested = isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0;
|
|
10508
|
+
const next = nested ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
10509
|
+
if (next === void 0) break;
|
|
10510
|
+
node = next;
|
|
10511
|
+
arrivedViaContainer = nested !== void 0;
|
|
10512
|
+
descended = true;
|
|
10513
|
+
}
|
|
10514
|
+
if (descended && detail === "" && isPlainObject(node)) detail = JSON.stringify(node);
|
|
10515
|
+
if (codeFromPlainKey && isAcknowledgementCode(code)) {
|
|
10516
|
+
code = "";
|
|
10517
|
+
detail = "";
|
|
10518
|
+
}
|
|
10519
|
+
return {
|
|
10520
|
+
code,
|
|
10521
|
+
detail,
|
|
10522
|
+
signals: signals.join("\n")
|
|
10523
|
+
};
|
|
10524
|
+
}
|
|
10525
|
+
/**
|
|
10526
|
+
* The gateway's retry hint, when the frame carries one.
|
|
10527
|
+
*
|
|
10528
|
+
* A carried `0` is the decoder's "no hint" placeholder, not a real wait. The
|
|
10529
|
+
* hint may sit on the envelope, in a nested container, or inside a message that
|
|
10530
|
+
* is itself a JSON document; the walk reads all three so a queue descriptor is
|
|
10531
|
+
* not lost when the outer sentence is the one worth showing.
|
|
10532
|
+
*/
|
|
10533
|
+
function retryAfterSecondsOf(frame) {
|
|
10534
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10535
|
+
let node = frame;
|
|
10536
|
+
for (let depth = 0; depth < 8; depth++) {
|
|
10537
|
+
if (!isPlainObject(node) || seen.has(node)) break;
|
|
10538
|
+
seen.add(node);
|
|
10539
|
+
const direct = node["retryAfterSeconds"];
|
|
10540
|
+
if (typeof direct === "number" && Number.isFinite(direct) && direct > 0) return direct;
|
|
10541
|
+
const message = node["message"] ?? node["errorMessage"];
|
|
10542
|
+
const next = (isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0) ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
10543
|
+
if (next === void 0) break;
|
|
10544
|
+
node = next;
|
|
10545
|
+
}
|
|
10546
|
+
return 0;
|
|
10547
|
+
}
|
|
10548
|
+
/**
|
|
10549
|
+
* The layer holding the frame's content, and the envelope it came in.
|
|
10550
|
+
*
|
|
10551
|
+
* A `body` wrapper is Qoder's own envelope: the frame's content sits one level
|
|
10552
|
+
* down, and so does its refusal. Reading only the inner object dropped an
|
|
10553
|
+
* envelope's `errorCode`/`code` - `{"body":{"choices":[]},"code":401,"message":
|
|
10554
|
+
* "Login expired"}` reached the decoder as a nameless inner object, so the turn
|
|
10555
|
+
* answered 200 with an empty stream and never rotated to the next account,
|
|
10556
|
+
* leaving the user without the re-login prompt that a 401 produces. Both are
|
|
10557
|
+
* returned so a refusal found in either one is honoured.
|
|
10558
|
+
*
|
|
10559
|
+
* `envelope` is undefined when the payload has no wrapper, so the caller can
|
|
10560
|
+
* tell "no outer layer" from "an outer layer with nothing to say".
|
|
10561
|
+
*/
|
|
10562
|
+
function qoderFrameParts(payload) {
|
|
10563
|
+
const outer = tryJsonObject(payload);
|
|
10564
|
+
if (outer === void 0) return void 0;
|
|
10565
|
+
const body = outer["body"];
|
|
10566
|
+
const inner = typeof body === "string" ? tryJsonObject(body) : isPlainObject(body) ? body : void 0;
|
|
10567
|
+
return inner === void 0 ? {
|
|
10568
|
+
envelope: void 0,
|
|
10569
|
+
content: outer
|
|
10570
|
+
} : {
|
|
10571
|
+
envelope: outer,
|
|
10572
|
+
content: inner
|
|
10573
|
+
};
|
|
10574
|
+
}
|
|
10575
|
+
/**
|
|
10576
|
+
* Classify one data payload. A token-accounting frame carries `choices: []`
|
|
10577
|
+
* with a top-level `usage`; it must be forwarded as a chunk, not read as a
|
|
10578
|
+
* failure. Anything with neither output nor a name — a bare `{ success: true }`
|
|
10579
|
+
* keepalive, or a payload whose shape moved — is reported as unknown rather
|
|
10580
|
+
* than guessed at. A frame that carries an empty `choices` and no usage is a
|
|
10581
|
+
* failure frame wearing a chunk's clothes: the upstream reports refusals that
|
|
10582
|
+
* way, and forwarding it as a chunk answered the client with an empty turn.
|
|
10583
|
+
*/
|
|
10584
|
+
function decodeQoderFrame(payload) {
|
|
10585
|
+
const parts = qoderFrameParts(payload);
|
|
10586
|
+
if (parts === void 0) return {
|
|
10587
|
+
type: "unknown",
|
|
10588
|
+
reason: "unparseable",
|
|
10589
|
+
data: payload
|
|
10590
|
+
};
|
|
10591
|
+
const { envelope, content } = parts;
|
|
10592
|
+
const choices = content["choices"];
|
|
10593
|
+
const hasOutput = Array.isArray(choices) && choices.length > 0;
|
|
10594
|
+
const hasUsage = content["usage"] !== void 0 && content["usage"] !== null;
|
|
10595
|
+
if (hasOutput || hasUsage) {
|
|
10596
|
+
if (envelope !== void 0) {
|
|
10597
|
+
const outer = unwrapFailure(envelope);
|
|
10598
|
+
if (outer.code !== "" || outer.detail !== "") return {
|
|
10599
|
+
type: "failure",
|
|
10600
|
+
code: outer.code,
|
|
10601
|
+
detail: outer.detail,
|
|
10602
|
+
signals: outer.signals,
|
|
10603
|
+
retryAfterSeconds: retryAfterSecondsOf(envelope)
|
|
10604
|
+
};
|
|
10605
|
+
}
|
|
10606
|
+
return {
|
|
10607
|
+
type: "chunk",
|
|
10608
|
+
chunk: content
|
|
10609
|
+
};
|
|
10610
|
+
}
|
|
10611
|
+
for (const layer of envelope === void 0 ? [content] : [envelope, content]) {
|
|
10612
|
+
const { code, detail, signals } = unwrapFailure(layer);
|
|
10613
|
+
if (code === "" && detail === "") continue;
|
|
10614
|
+
return {
|
|
10615
|
+
type: "failure",
|
|
10616
|
+
code,
|
|
10617
|
+
detail,
|
|
10618
|
+
signals,
|
|
10619
|
+
retryAfterSeconds: retryAfterSecondsOf(layer)
|
|
10620
|
+
};
|
|
10621
|
+
}
|
|
10622
|
+
return {
|
|
10623
|
+
type: "unknown",
|
|
10624
|
+
reason: "unnamed",
|
|
10625
|
+
data: content
|
|
10626
|
+
};
|
|
10627
|
+
}
|
|
10628
|
+
/**
|
|
10629
|
+
* One unterminated line may not grow without bound; chat deltas are small.
|
|
10630
|
+
* The ceiling is a memory guard on the upstream's answer, which no request-body
|
|
10631
|
+
* limit bounds: a frame this size is a stream gone wrong, not a chat delta.
|
|
10632
|
+
*/
|
|
10633
|
+
const MAX_LINE_CHARS = 67108864;
|
|
10634
|
+
/**
|
|
10635
|
+
* Incremental reader for the Qoder wire form: one JSON payload per `data:`
|
|
10636
|
+
* line. Qoder sends no `event:`/`id:`/`retry` fields, so this stays a plain
|
|
10637
|
+
* line reader instead of duplicating a full SSE event parser.
|
|
10638
|
+
*/
|
|
10639
|
+
var QoderFrameDecoder = class {
|
|
10640
|
+
buffer = "";
|
|
10641
|
+
done = false;
|
|
10642
|
+
/** Whether the wire has supplied its terminal marker, independent of TCP EOF. */
|
|
10643
|
+
get ended() {
|
|
10644
|
+
return this.done;
|
|
10645
|
+
}
|
|
10646
|
+
/** Payloads seen so far; `[DONE]` ends the stream and yields nothing. */
|
|
10647
|
+
push(chunk) {
|
|
10648
|
+
if (this.done) return [];
|
|
10649
|
+
this.buffer += chunk;
|
|
10650
|
+
const payloads = [];
|
|
10651
|
+
for (;;) {
|
|
10652
|
+
const match = /\r\n|\n|\r/.exec(this.buffer);
|
|
10653
|
+
if (match === null || match.index === void 0) break;
|
|
10654
|
+
if (match[0] === "\r" && match.index + 1 === this.buffer.length) break;
|
|
10655
|
+
const line = this.buffer.slice(0, match.index).trim();
|
|
10656
|
+
this.buffer = this.buffer.slice(match.index + match[0].length);
|
|
10657
|
+
if (!line.startsWith("data:")) continue;
|
|
10658
|
+
const payload = line.slice(5).trim();
|
|
10659
|
+
if (payload.length === 0) continue;
|
|
10660
|
+
if (payload === "[DONE]") {
|
|
10661
|
+
this.done = true;
|
|
10662
|
+
return payloads;
|
|
10663
|
+
}
|
|
10664
|
+
payloads.push(payload);
|
|
10665
|
+
}
|
|
10666
|
+
if (this.buffer.length > MAX_LINE_CHARS) {
|
|
10667
|
+
this.buffer = "";
|
|
10668
|
+
throw new Error("sse line exceeded 67108864 characters without a newline");
|
|
10669
|
+
}
|
|
10670
|
+
return payloads;
|
|
10671
|
+
}
|
|
10672
|
+
/** Flush a final payload the upstream left without a trailing newline. */
|
|
10673
|
+
finish() {
|
|
10674
|
+
if (this.done) return [];
|
|
10675
|
+
this.done = true;
|
|
10676
|
+
const line = this.buffer.trim();
|
|
10677
|
+
this.buffer = "";
|
|
10678
|
+
if (!line.startsWith("data:")) return [];
|
|
10679
|
+
const payload = line.slice(5).trim();
|
|
10680
|
+
return payload.length === 0 || payload === "[DONE]" ? [] : [payload];
|
|
10681
|
+
}
|
|
10682
|
+
};
|
|
10683
|
+
//#endregion
|
|
10684
|
+
//#region src/qoder-client.ts
|
|
10685
|
+
/**
|
|
10686
|
+
* Qoder minimal upstream client.
|
|
10687
|
+
*
|
|
10688
|
+
* Fetches the callable roster and opens one chat stream. No disk reads here;
|
|
10689
|
+
* tokens stay in the caller's memory.
|
|
10690
|
+
*
|
|
10691
|
+
* Shapes follow `dsh-connect-qoder` (MIT): the `algo/api/v2/model/list`
|
|
10692
|
+
* envelope groups its models by product surface, and only the `chat` group is
|
|
10693
|
+
* callable. Chat requests normalise `developer` to `system`, because a system
|
|
10694
|
+
* message the gateway does not recognise is answered with a permanent
|
|
10695
|
+
* `403 {"code":"10605"}` on every retry.
|
|
10696
|
+
*
|
|
10697
|
+
* Everything the client needs from the outside is injected (credential,
|
|
10698
|
+
* `fetchImpl`), so the whole path can be exercised offline.
|
|
10699
|
+
*
|
|
10700
|
+
* @module dsh-wtq-pool/qoder-client
|
|
10701
|
+
*/
|
|
10702
|
+
/** Qoder's thinking ladder, low to high: the upstream's own order. */
|
|
10703
|
+
const QODER_EFFORT_ORDER = [
|
|
10704
|
+
"none",
|
|
10705
|
+
"low",
|
|
10706
|
+
"medium",
|
|
10707
|
+
"high",
|
|
10708
|
+
"xhigh",
|
|
10709
|
+
"max"
|
|
10710
|
+
];
|
|
10711
|
+
/**
|
|
10712
|
+
* The levels a catalog row can list: the ladder without "none", which is not a
|
|
10713
|
+
* level but the off value. Keeping it out of the table is what stops it from
|
|
10714
|
+
* ever being published as a level or picked as a model's default.
|
|
10715
|
+
*/
|
|
9506
10716
|
const QODER_TABLE_LEVELS = QODER_EFFORT_ORDER.filter((level) => level !== "none");
|
|
9507
10717
|
/** Model directory path; `Encode=1` names the permuted-base64 wire form. */
|
|
9508
10718
|
const QODER_MODELS_PATH = "/algo/api/v2/model/list?Encode=1";
|
|
@@ -9586,6 +10796,8 @@ function qoderRawEpochMs(value) {
|
|
|
9586
10796
|
return value < QODER_EPOCH_SECONDS_BOUNDARY_MS ? Math.floor(value * 1e3) : Math.floor(value);
|
|
9587
10797
|
}
|
|
9588
10798
|
if (typeof value === "string") {
|
|
10799
|
+
const numeric = Number(value);
|
|
10800
|
+
if (Number.isFinite(numeric) && numeric > 0) return numeric < QODER_EPOCH_SECONDS_BOUNDARY_MS ? Math.floor(numeric * 1e3) : Math.floor(numeric);
|
|
9589
10801
|
const parsed = Date.parse(value);
|
|
9590
10802
|
return Number.isFinite(parsed) ? parsed : void 0;
|
|
9591
10803
|
}
|
|
@@ -9751,9 +10963,9 @@ function qoderCheckinStateFrom(payload, nowMs = Date.now()) {
|
|
|
9751
10963
|
* When the next round opens, for an account whose current round is not
|
|
9752
10964
|
* claimable right now (already collected, or its window has not started).
|
|
9753
10965
|
*
|
|
9754
|
-
*
|
|
9755
|
-
*
|
|
9756
|
-
*
|
|
10966
|
+
* Read off the campaigns the upstream listed, not from a fixed hour: this is
|
|
10967
|
+
* the answer to "when can I claim" - and the moment the automatic pass comes
|
|
10968
|
+
* back for.
|
|
9757
10969
|
*/
|
|
9758
10970
|
function qoderNextOpenAt(payload, nowMs) {
|
|
9759
10971
|
const list = payload?.campaigns;
|
|
@@ -9793,7 +11005,7 @@ function qoderNormalizeClaimResult(payload, campaign) {
|
|
|
9793
11005
|
const amountValue = Number(body?.reward?.amount ?? body?.benefit?.amount ?? (typeof campaign !== "undefined" ? qoderBenefitOf(campaign)?.amount : void 0));
|
|
9794
11006
|
const expiresAt = qoderEpochMs(body?.expiresAt);
|
|
9795
11007
|
const code = Number(body?.code ?? body?.errcode);
|
|
9796
|
-
const refusal = Number.isFinite(code) && code
|
|
11008
|
+
const refusal = Number.isFinite(code) && !isAcknowledgementCode(code) ? String(body?.message ?? body?.msg ?? "upstream code " + code).slice(0, 200) : "";
|
|
9797
11009
|
return {
|
|
9798
11010
|
claimed: granted,
|
|
9799
11011
|
replayed,
|
|
@@ -10197,346 +11409,142 @@ var QoderUpstreamClient = class {
|
|
|
10197
11409
|
return {
|
|
10198
11410
|
...userQuota === void 0 ? {} : { userQuota },
|
|
10199
11411
|
...addOnQuota === void 0 ? {} : { addOnQuota },
|
|
10200
|
-
dedicatedPackages,
|
|
10201
|
-
...expiresAtMs === void 0 ? {} : { expiresAtMs },
|
|
10202
|
-
...neverExpires ? { neverExpires: true } : {},
|
|
10203
|
-
source
|
|
10204
|
-
};
|
|
10205
|
-
};
|
|
10206
|
-
try {
|
|
10207
|
-
return parse(await read(QODER_USAGE_PRESENTATION_PATH), "presentation");
|
|
10208
|
-
} catch (error) {
|
|
10209
|
-
if (signal?.aborted) throw error;
|
|
10210
|
-
return parse(await read(QODER_USAGE_PATH), "quota");
|
|
10211
|
-
}
|
|
10212
|
-
}
|
|
10213
|
-
/**
|
|
10214
|
-
* Read the raw campaigns payload once. One round trip answers both the
|
|
10215
|
-
* promotional rows and the daily check-in round; the pure selectors above
|
|
10216
|
-
* split it without a second request.
|
|
10217
|
-
*/
|
|
10218
|
-
async fetchCampaigns(signal) {
|
|
10219
|
-
const credential = await this.options.credential();
|
|
10220
|
-
const response = await this.fetchImpl(qoderEndpoint(this.openApiBase(), QODER_CAMPAIGNS_PATH), {
|
|
10221
|
-
method: "GET",
|
|
10222
|
-
headers: qoderOpenApiHeaders(credential),
|
|
10223
|
-
redirect: "error",
|
|
10224
|
-
signal: signal ?? AbortSignal.timeout(DIRECTORY_TIMEOUT_MS)
|
|
10225
|
-
});
|
|
10226
|
-
if (!response.ok) throw new Error(`Qoder campaigns failed: HTTP ${response.status} ${await readErrorBody(response, 300, signal)}`);
|
|
10227
|
-
return await response.json();
|
|
10228
|
-
}
|
|
10229
|
-
/**
|
|
10230
|
-
* Claim one campaign's benefit, returning the raw answer. A repeat answers
|
|
10231
|
-
* `replayed: true` rather than failing; `qoderNormalizeClaimResult` narrows it.
|
|
10232
|
-
*/
|
|
10233
|
-
async claimCampaign(campaignId, signal) {
|
|
10234
|
-
if (typeof campaignId !== "string" || campaignId.length === 0) throw new Error("Qoder check-in failed: no campaign id to claim");
|
|
10235
|
-
const credential = await this.options.credential();
|
|
10236
|
-
const response = await this.fetchImpl(qoderEndpoint(this.openApiBase(), qoderClaimCampaignPath(campaignId)), {
|
|
10237
|
-
method: "POST",
|
|
10238
|
-
headers: {
|
|
10239
|
-
...qoderOpenApiHeaders(credential),
|
|
10240
|
-
"Content-Type": "application/json"
|
|
10241
|
-
},
|
|
10242
|
-
body: "{}",
|
|
10243
|
-
redirect: "error",
|
|
10244
|
-
signal: signal ?? AbortSignal.timeout(DIRECTORY_TIMEOUT_MS)
|
|
10245
|
-
});
|
|
10246
|
-
if (!response.ok) {
|
|
10247
|
-
const detail = await readErrorBody(response, 300, signal);
|
|
10248
|
-
throw new Error(`Qoder check-in failed: HTTP ${response.status} ${detail.slice(0, 200)}`);
|
|
10249
|
-
}
|
|
10250
|
-
const text = await response.text();
|
|
10251
|
-
try {
|
|
10252
|
-
return JSON.parse(text);
|
|
10253
|
-
} catch {
|
|
10254
|
-
const contentType = response.headers.get("content-type") ?? "no content-type";
|
|
10255
|
-
throw new Error(`Qoder check-in: response is not valid JSON (${contentType}) — ${text.slice(0, 300)}`);
|
|
10256
|
-
}
|
|
10257
|
-
}
|
|
10258
|
-
/**
|
|
10259
|
-
* Open one chat stream for a model. The caller owns the SSE translation;
|
|
10260
|
-
* a refusal answers as a classified error with the body truncated.
|
|
10261
|
-
*/
|
|
10262
|
-
async chatStream(openAiBody, model, options = {}) {
|
|
10263
|
-
let plain;
|
|
10264
|
-
try {
|
|
10265
|
-
plain = buildQoderChatBody(openAiBody, model, options);
|
|
10266
|
-
} catch (error) {
|
|
10267
|
-
const detail = error instanceof Error ? error.message : "";
|
|
10268
|
-
return {
|
|
10269
|
-
ok: false,
|
|
10270
|
-
status: 400,
|
|
10271
|
-
kind: "client",
|
|
10272
|
-
message: detail === "" ? "invalid JSON request" : detail
|
|
10273
|
-
};
|
|
10274
|
-
}
|
|
10275
|
-
let credential;
|
|
10276
|
-
try {
|
|
10277
|
-
credential = await this.options.credential();
|
|
10278
|
-
} catch (error) {
|
|
10279
|
-
return {
|
|
10280
|
-
ok: false,
|
|
10281
|
-
status: 503,
|
|
10282
|
-
kind: "server",
|
|
10283
|
-
message: `credential read failed: ${String(error instanceof Error ? error.message : error)}`
|
|
10284
|
-
};
|
|
10285
|
-
}
|
|
10286
|
-
const url = qoderEndpoint(this.baseUrl(), QODER_CHAT_PATH);
|
|
10287
|
-
const bodyBytes = encodeBody(plain);
|
|
10288
|
-
const headers = buildCosyAuthHeaders(bodyBytes, url, credential);
|
|
10289
|
-
let response;
|
|
10290
|
-
const deadline = headersDeadline(options.signal, options.timeouts?.headersMs ?? CHAT_HEADERS_TIMEOUT_MS);
|
|
10291
|
-
try {
|
|
10292
|
-
response = await this.fetchImpl(url, {
|
|
10293
|
-
method: "POST",
|
|
10294
|
-
headers: {
|
|
10295
|
-
"Content-Type": "application/json",
|
|
10296
|
-
...headers,
|
|
10297
|
-
...options.extraHeaders
|
|
10298
|
-
},
|
|
10299
|
-
body: bodyBytes,
|
|
10300
|
-
redirect: "error",
|
|
10301
|
-
signal: deadline.signal
|
|
10302
|
-
});
|
|
10303
|
-
} catch (error) {
|
|
10304
|
-
if (options.signal?.aborted === true) return {
|
|
10305
|
-
ok: false,
|
|
10306
|
-
status: 0,
|
|
10307
|
-
kind: "aborted",
|
|
10308
|
-
message: "cancelled by the caller"
|
|
10309
|
-
};
|
|
10310
|
-
return {
|
|
10311
|
-
ok: false,
|
|
10312
|
-
status: 0,
|
|
10313
|
-
kind: "server",
|
|
10314
|
-
message: `transport error: ${String(error)}`
|
|
10315
|
-
};
|
|
10316
|
-
} finally {
|
|
10317
|
-
deadline.arrived();
|
|
10318
|
-
}
|
|
10319
|
-
if (!response.ok) {
|
|
10320
|
-
const text = await readErrorBody(response, 300, options.signal);
|
|
10321
|
-
return {
|
|
10322
|
-
ok: false,
|
|
10323
|
-
status: response.status,
|
|
10324
|
-
kind: classifyQoderUpstreamError(response.status),
|
|
10325
|
-
message: text.slice(0, 300) || `Qoder returned HTTP ${response.status}`,
|
|
10326
|
-
retryAfter: response.headers.get("retry-after")
|
|
10327
|
-
};
|
|
10328
|
-
}
|
|
10329
|
-
return {
|
|
10330
|
-
ok: true,
|
|
10331
|
-
response: response.body === null ? response : new Response(withIdleWatchdog(response.body, options.timeouts?.idleMs, options.signal), {
|
|
10332
|
-
status: response.status,
|
|
10333
|
-
headers: response.headers
|
|
10334
|
-
})
|
|
10335
|
-
};
|
|
10336
|
-
}
|
|
10337
|
-
};
|
|
10338
|
-
//#endregion
|
|
10339
|
-
//#region src/qoder-sse.ts
|
|
10340
|
-
function isPlainObject(value) {
|
|
10341
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10342
|
-
}
|
|
10343
|
-
function tryJsonObject(text) {
|
|
10344
|
-
try {
|
|
10345
|
-
const parsed = JSON.parse(text);
|
|
10346
|
-
return isPlainObject(parsed) ? parsed : void 0;
|
|
10347
|
-
} catch {
|
|
10348
|
-
return;
|
|
10349
|
-
}
|
|
10350
|
-
}
|
|
10351
|
-
/**
|
|
10352
|
-
* Whether a code is the success-range acknowledgement Qoder sends for a
|
|
10353
|
-
* container it accepted. `{"code":0}` and `{"code":200}` are how it acks.
|
|
10354
|
-
*/
|
|
10355
|
-
function isAcknowledgementCode(value) {
|
|
10356
|
-
if (typeof value !== "string" && typeof value !== "number") return false;
|
|
10357
|
-
if (typeof value === "string" && value.length === 0) return false;
|
|
10358
|
-
const code = Number(value);
|
|
10359
|
-
return Number.isFinite(code) && (code === 0 || code >= 200 && code < 300);
|
|
10360
|
-
}
|
|
10361
|
-
/**
|
|
10362
|
-
* The code and message a failure frame really carries, however deeply they are
|
|
10363
|
-
* wrapped. The walk follows `details`/`error`, or a `message` string that is
|
|
10364
|
-
* itself a JSON document, up to 8 levels — bounded so a self-referential
|
|
10365
|
-
* payload cannot spin. When it bottoms out on an object (the queue descriptor),
|
|
10366
|
-
* that object is far more useful than the string that carried it.
|
|
10367
|
-
*/
|
|
10368
|
-
function unwrapFailure(frame) {
|
|
10369
|
-
let code = "";
|
|
10370
|
-
let detail = "";
|
|
10371
|
-
const signals = [];
|
|
10372
|
-
let node = frame;
|
|
10373
|
-
let descended = false;
|
|
10374
|
-
let codeFromPlainKey = false;
|
|
10375
|
-
let codeFromErrorSpelling = false;
|
|
10376
|
-
let arrivedViaContainer = false;
|
|
10377
|
-
for (let depth = 0; depth < 8; depth++) {
|
|
10378
|
-
if (!isPlainObject(node)) break;
|
|
10379
|
-
const errorSpelling = node["errorCode"] ?? node["errcode"];
|
|
10380
|
-
const levelCode = errorSpelling ?? node["code"];
|
|
10381
|
-
const acknowledgement = arrivedViaContainer && codeFromPlainKey && isAcknowledgementCode(levelCode);
|
|
10382
|
-
if (errorSpelling !== void 0 || !codeFromErrorSpelling && !acknowledgement) {
|
|
10383
|
-
if (typeof levelCode === "string" && levelCode.length > 0) {
|
|
10384
|
-
code = levelCode;
|
|
10385
|
-
codeFromPlainKey = errorSpelling === void 0;
|
|
10386
|
-
codeFromErrorSpelling = errorSpelling !== void 0;
|
|
10387
|
-
} else if (typeof levelCode === "number" && Number.isFinite(levelCode)) {
|
|
10388
|
-
code = String(levelCode);
|
|
10389
|
-
codeFromPlainKey = errorSpelling === void 0;
|
|
10390
|
-
codeFromErrorSpelling = errorSpelling !== void 0;
|
|
10391
|
-
}
|
|
10392
|
-
}
|
|
10393
|
-
const message = node["message"] ?? node["errorMessage"];
|
|
10394
|
-
if (typeof message === "string" && message.trim() !== "" && !signals.includes(message)) signals.push(message);
|
|
10395
|
-
if ((detail === "" || tryJsonObject(detail) !== void 0) && typeof message === "string" && message.length > 0) detail = message;
|
|
10396
|
-
const flat = typeof node["error"] === "string" ? node["error"] : typeof node["details"] === "string" ? node["details"] : void 0;
|
|
10397
|
-
if (flat !== void 0 && flat.trim() !== "" && !signals.includes(flat)) signals.push(flat);
|
|
10398
|
-
if (detail === "" && flat !== void 0 && flat.length > 0) detail = flat;
|
|
10399
|
-
const nested = isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0;
|
|
10400
|
-
const next = nested ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
10401
|
-
if (next === void 0) break;
|
|
10402
|
-
node = next;
|
|
10403
|
-
arrivedViaContainer = nested !== void 0;
|
|
10404
|
-
descended = true;
|
|
10405
|
-
}
|
|
10406
|
-
if (descended && detail === "" && isPlainObject(node)) detail = JSON.stringify(node);
|
|
10407
|
-
if (codeFromPlainKey && isAcknowledgementCode(code)) code = "";
|
|
10408
|
-
return {
|
|
10409
|
-
code,
|
|
10410
|
-
detail,
|
|
10411
|
-
signals: signals.join("\n")
|
|
10412
|
-
};
|
|
10413
|
-
}
|
|
10414
|
-
/**
|
|
10415
|
-
* The gateway's retry hint, when the frame carries one.
|
|
10416
|
-
*
|
|
10417
|
-
* A carried `0` is the decoder's "no hint" placeholder, not a real wait. The
|
|
10418
|
-
* hint may sit on the envelope, in a nested container, or inside a message that
|
|
10419
|
-
* is itself a JSON document; the walk reads all three so a queue descriptor is
|
|
10420
|
-
* not lost when the outer sentence is the one worth showing.
|
|
10421
|
-
*/
|
|
10422
|
-
function retryAfterSecondsOf(frame) {
|
|
10423
|
-
const seen = /* @__PURE__ */ new Set();
|
|
10424
|
-
let node = frame;
|
|
10425
|
-
for (let depth = 0; depth < 8; depth++) {
|
|
10426
|
-
if (!isPlainObject(node) || seen.has(node)) break;
|
|
10427
|
-
seen.add(node);
|
|
10428
|
-
const direct = node["retryAfterSeconds"];
|
|
10429
|
-
if (typeof direct === "number" && Number.isFinite(direct) && direct > 0) return direct;
|
|
10430
|
-
const message = node["message"] ?? node["errorMessage"];
|
|
10431
|
-
const next = (isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0) ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
10432
|
-
if (next === void 0) break;
|
|
10433
|
-
node = next;
|
|
10434
|
-
}
|
|
10435
|
-
return 0;
|
|
10436
|
-
}
|
|
10437
|
-
/**
|
|
10438
|
-
* The inner chunk of one data payload: the envelope's `body` when it is a JSON
|
|
10439
|
-
* string, the object when it is inline, and the envelope itself when it carries
|
|
10440
|
-
* neither. Returns undefined when no layer parses.
|
|
10441
|
-
*/
|
|
10442
|
-
function unwrapQoderFrame(payload) {
|
|
10443
|
-
const envelope = tryJsonObject(payload);
|
|
10444
|
-
if (envelope === void 0) return void 0;
|
|
10445
|
-
const body = envelope["body"];
|
|
10446
|
-
if (typeof body === "string") return tryJsonObject(body);
|
|
10447
|
-
if (isPlainObject(body)) return body;
|
|
10448
|
-
return envelope;
|
|
10449
|
-
}
|
|
10450
|
-
/**
|
|
10451
|
-
* Classify one data payload. A token-accounting frame carries `choices: []`
|
|
10452
|
-
* with a top-level `usage`; it must be forwarded as a chunk, not read as a
|
|
10453
|
-
* failure. Anything with neither output nor a name — a bare `{ success: true }`
|
|
10454
|
-
* keepalive, or a payload whose shape moved — is reported as unknown rather
|
|
10455
|
-
* than guessed at. A frame that carries an empty `choices` and no usage is a
|
|
10456
|
-
* failure frame wearing a chunk's clothes: the upstream reports refusals that
|
|
10457
|
-
* way, and forwarding it as a chunk answered the client with an empty turn.
|
|
10458
|
-
*/
|
|
10459
|
-
function decodeQoderFrame(payload) {
|
|
10460
|
-
const chunk = unwrapQoderFrame(payload);
|
|
10461
|
-
if (chunk === void 0) return {
|
|
10462
|
-
type: "unknown",
|
|
10463
|
-
reason: "unparseable",
|
|
10464
|
-
data: payload
|
|
10465
|
-
};
|
|
10466
|
-
const choices = chunk["choices"];
|
|
10467
|
-
const hasOutput = Array.isArray(choices) && choices.length > 0;
|
|
10468
|
-
const hasUsage = chunk["usage"] !== void 0 && chunk["usage"] !== null;
|
|
10469
|
-
if (hasOutput || hasUsage) return {
|
|
10470
|
-
type: "chunk",
|
|
10471
|
-
chunk
|
|
10472
|
-
};
|
|
10473
|
-
const { code, detail, signals } = unwrapFailure(chunk);
|
|
10474
|
-
if (code === "" && detail === "") return {
|
|
10475
|
-
type: "unknown",
|
|
10476
|
-
reason: "unnamed",
|
|
10477
|
-
data: chunk
|
|
10478
|
-
};
|
|
10479
|
-
return {
|
|
10480
|
-
type: "failure",
|
|
10481
|
-
code,
|
|
10482
|
-
detail,
|
|
10483
|
-
signals,
|
|
10484
|
-
retryAfterSeconds: retryAfterSecondsOf(chunk)
|
|
10485
|
-
};
|
|
10486
|
-
}
|
|
10487
|
-
/**
|
|
10488
|
-
* One unterminated line may not grow without bound; chat deltas are small.
|
|
10489
|
-
* The ceiling is a memory guard on the upstream's answer, which no request-body
|
|
10490
|
-
* limit bounds: a frame this size is a stream gone wrong, not a chat delta.
|
|
10491
|
-
*/
|
|
10492
|
-
const MAX_LINE_CHARS = 67108864;
|
|
10493
|
-
/**
|
|
10494
|
-
* Incremental reader for the Qoder wire form: one JSON payload per `data:`
|
|
10495
|
-
* line. Qoder sends no `event:`/`id:`/`retry` fields, so this stays a plain
|
|
10496
|
-
* line reader instead of duplicating a full SSE event parser.
|
|
10497
|
-
*/
|
|
10498
|
-
var QoderFrameDecoder = class {
|
|
10499
|
-
buffer = "";
|
|
10500
|
-
done = false;
|
|
10501
|
-
/** Whether the wire has supplied its terminal marker, independent of TCP EOF. */
|
|
10502
|
-
get ended() {
|
|
10503
|
-
return this.done;
|
|
11412
|
+
dedicatedPackages,
|
|
11413
|
+
...expiresAtMs === void 0 ? {} : { expiresAtMs },
|
|
11414
|
+
...neverExpires ? { neverExpires: true } : {},
|
|
11415
|
+
source
|
|
11416
|
+
};
|
|
11417
|
+
};
|
|
11418
|
+
try {
|
|
11419
|
+
return parse(await read(QODER_USAGE_PRESENTATION_PATH), "presentation");
|
|
11420
|
+
} catch (error) {
|
|
11421
|
+
if (signal?.aborted) throw error;
|
|
11422
|
+
return parse(await read(QODER_USAGE_PATH), "quota");
|
|
11423
|
+
}
|
|
10504
11424
|
}
|
|
10505
|
-
/**
|
|
10506
|
-
|
|
10507
|
-
|
|
10508
|
-
|
|
10509
|
-
|
|
10510
|
-
|
|
10511
|
-
|
|
10512
|
-
|
|
10513
|
-
|
|
10514
|
-
|
|
10515
|
-
|
|
10516
|
-
|
|
10517
|
-
|
|
10518
|
-
|
|
10519
|
-
|
|
10520
|
-
|
|
10521
|
-
|
|
10522
|
-
|
|
10523
|
-
|
|
11425
|
+
/**
|
|
11426
|
+
* Read the raw campaigns payload once. One round trip answers both the
|
|
11427
|
+
* promotional rows and the daily check-in round; the pure selectors above
|
|
11428
|
+
* split it without a second request.
|
|
11429
|
+
*/
|
|
11430
|
+
async fetchCampaigns(signal) {
|
|
11431
|
+
const credential = await this.options.credential();
|
|
11432
|
+
const response = await this.fetchImpl(qoderEndpoint(this.openApiBase(), QODER_CAMPAIGNS_PATH), {
|
|
11433
|
+
method: "GET",
|
|
11434
|
+
headers: qoderOpenApiHeaders(credential),
|
|
11435
|
+
redirect: "error",
|
|
11436
|
+
signal: signal ?? AbortSignal.timeout(DIRECTORY_TIMEOUT_MS)
|
|
11437
|
+
});
|
|
11438
|
+
if (!response.ok) throw new Error(`Qoder campaigns failed: HTTP ${response.status} ${await readErrorBody(response, 300, signal)}`);
|
|
11439
|
+
return await response.json();
|
|
11440
|
+
}
|
|
11441
|
+
/**
|
|
11442
|
+
* Claim one campaign's benefit, returning the raw answer. A repeat answers
|
|
11443
|
+
* `replayed: true` rather than failing; `qoderNormalizeClaimResult` narrows it.
|
|
11444
|
+
*/
|
|
11445
|
+
async claimCampaign(campaignId, signal) {
|
|
11446
|
+
if (typeof campaignId !== "string" || campaignId.length === 0) throw new Error("Qoder check-in failed: no campaign id to claim");
|
|
11447
|
+
const credential = await this.options.credential();
|
|
11448
|
+
const response = await this.fetchImpl(qoderEndpoint(this.openApiBase(), qoderClaimCampaignPath(campaignId)), {
|
|
11449
|
+
method: "POST",
|
|
11450
|
+
headers: {
|
|
11451
|
+
...qoderOpenApiHeaders(credential),
|
|
11452
|
+
"Content-Type": "application/json"
|
|
11453
|
+
},
|
|
11454
|
+
body: "{}",
|
|
11455
|
+
redirect: "error",
|
|
11456
|
+
signal: signal ?? AbortSignal.timeout(DIRECTORY_TIMEOUT_MS)
|
|
11457
|
+
});
|
|
11458
|
+
if (!response.ok) {
|
|
11459
|
+
const detail = await readErrorBody(response, 300, signal);
|
|
11460
|
+
throw new Error(`Qoder check-in failed: HTTP ${response.status} ${detail.slice(0, 200)}`);
|
|
10524
11461
|
}
|
|
10525
|
-
|
|
10526
|
-
|
|
10527
|
-
|
|
11462
|
+
const text = await response.text();
|
|
11463
|
+
try {
|
|
11464
|
+
return JSON.parse(text);
|
|
11465
|
+
} catch {
|
|
11466
|
+
const contentType = response.headers.get("content-type") ?? "no content-type";
|
|
11467
|
+
throw new Error(`Qoder check-in: response is not valid JSON (${contentType}) — ${text.slice(0, 300)}`);
|
|
10528
11468
|
}
|
|
10529
|
-
return payloads;
|
|
10530
11469
|
}
|
|
10531
|
-
/**
|
|
10532
|
-
|
|
10533
|
-
|
|
10534
|
-
|
|
10535
|
-
|
|
10536
|
-
|
|
10537
|
-
|
|
10538
|
-
|
|
10539
|
-
|
|
11470
|
+
/**
|
|
11471
|
+
* Open one chat stream for a model. The caller owns the SSE translation;
|
|
11472
|
+
* a refusal answers as a classified error with the body truncated.
|
|
11473
|
+
*/
|
|
11474
|
+
async chatStream(openAiBody, model, options = {}) {
|
|
11475
|
+
let plain;
|
|
11476
|
+
try {
|
|
11477
|
+
plain = buildQoderChatBody(openAiBody, model, options);
|
|
11478
|
+
} catch (error) {
|
|
11479
|
+
const detail = error instanceof Error ? error.message : "";
|
|
11480
|
+
return {
|
|
11481
|
+
ok: false,
|
|
11482
|
+
status: 400,
|
|
11483
|
+
kind: "client",
|
|
11484
|
+
message: detail === "" ? "invalid JSON request" : detail
|
|
11485
|
+
};
|
|
11486
|
+
}
|
|
11487
|
+
let credential;
|
|
11488
|
+
try {
|
|
11489
|
+
credential = await this.options.credential();
|
|
11490
|
+
} catch (error) {
|
|
11491
|
+
return {
|
|
11492
|
+
ok: false,
|
|
11493
|
+
status: 503,
|
|
11494
|
+
kind: "server",
|
|
11495
|
+
message: `credential read failed: ${String(error instanceof Error ? error.message : error)}`
|
|
11496
|
+
};
|
|
11497
|
+
}
|
|
11498
|
+
const url = qoderEndpoint(this.baseUrl(), QODER_CHAT_PATH);
|
|
11499
|
+
const bodyBytes = encodeBody(plain);
|
|
11500
|
+
const headers = buildCosyAuthHeaders(bodyBytes, url, credential);
|
|
11501
|
+
let response;
|
|
11502
|
+
const deadline = headersDeadline(options.signal, options.timeouts?.headersMs ?? CHAT_HEADERS_TIMEOUT_MS);
|
|
11503
|
+
try {
|
|
11504
|
+
response = await this.fetchImpl(url, {
|
|
11505
|
+
method: "POST",
|
|
11506
|
+
headers: {
|
|
11507
|
+
"Content-Type": "application/json",
|
|
11508
|
+
...headers,
|
|
11509
|
+
...options.extraHeaders
|
|
11510
|
+
},
|
|
11511
|
+
body: bodyBytes,
|
|
11512
|
+
redirect: "error",
|
|
11513
|
+
signal: deadline.signal
|
|
11514
|
+
});
|
|
11515
|
+
} catch (error) {
|
|
11516
|
+
if (options.signal?.aborted === true) return {
|
|
11517
|
+
ok: false,
|
|
11518
|
+
status: 0,
|
|
11519
|
+
kind: "aborted",
|
|
11520
|
+
message: "cancelled by the caller"
|
|
11521
|
+
};
|
|
11522
|
+
return {
|
|
11523
|
+
ok: false,
|
|
11524
|
+
status: 0,
|
|
11525
|
+
kind: "server",
|
|
11526
|
+
message: `transport error: ${String(error)}`
|
|
11527
|
+
};
|
|
11528
|
+
} finally {
|
|
11529
|
+
deadline.arrived();
|
|
11530
|
+
}
|
|
11531
|
+
if (!response.ok) {
|
|
11532
|
+
const text = await readErrorBody(response, 300, options.signal);
|
|
11533
|
+
return {
|
|
11534
|
+
ok: false,
|
|
11535
|
+
status: response.status,
|
|
11536
|
+
kind: classifyQoderUpstreamError(response.status),
|
|
11537
|
+
message: text.slice(0, 300) || `Qoder returned HTTP ${response.status}`,
|
|
11538
|
+
retryAfter: response.headers.get("retry-after")
|
|
11539
|
+
};
|
|
11540
|
+
}
|
|
11541
|
+
return {
|
|
11542
|
+
ok: true,
|
|
11543
|
+
response: response.body === null ? response : new Response(withIdleWatchdog(response.body, options.timeouts?.idleMs, options.signal), {
|
|
11544
|
+
status: response.status,
|
|
11545
|
+
headers: response.headers
|
|
11546
|
+
})
|
|
11547
|
+
};
|
|
10540
11548
|
}
|
|
10541
11549
|
};
|
|
10542
11550
|
//#endregion
|
|
@@ -10647,6 +11655,14 @@ function queueSeconds(frame) {
|
|
|
10647
11655
|
* and a multi-hour Retry-After, and classifying it as a queue would turn it
|
|
10648
11656
|
* into a long sleep instead of a failover.
|
|
10649
11657
|
*/
|
|
11658
|
+
/**
|
|
11659
|
+
* The failure class of a refused peek, carried on the response the peek returns.
|
|
11660
|
+
*
|
|
11661
|
+
* A status code alone cannot separate "this sign-in answered nothing" from "the
|
|
11662
|
+
* service is down for everyone": both are 502, and only the first belongs to
|
|
11663
|
+
* the account. The gateway reads the class from this header.
|
|
11664
|
+
*/
|
|
11665
|
+
const QODER_FAILURE_KIND_HEADER = "x-wtq-failure-kind";
|
|
10650
11666
|
function classifyQoderFailure(failure) {
|
|
10651
11667
|
const code = failure.code.trim();
|
|
10652
11668
|
const text = `${code} ${failure.message} ${failure.signals ?? ""}`;
|
|
@@ -11052,7 +12068,7 @@ async function openQoderResponse(response, model, options = {}) {
|
|
|
11052
12068
|
if (!response.ok) {
|
|
11053
12069
|
const detail = await readErrorBody(response, 1024);
|
|
11054
12070
|
return Response.json({ error: {
|
|
11055
|
-
message: detail === "" ? `Qoder returned HTTP ${response.status}` : detail,
|
|
12071
|
+
message: detail === "" ? `Qoder returned HTTP ${response.status}` : redactSecrets(detail),
|
|
11056
12072
|
type: "upstream_error",
|
|
11057
12073
|
code: response.status
|
|
11058
12074
|
} }, { status: response.status });
|
|
@@ -11133,17 +12149,31 @@ async function openQoderResponse(response, model, options = {}) {
|
|
|
11133
12149
|
}
|
|
11134
12150
|
if (failure !== void 0 && !sawOutput) {
|
|
11135
12151
|
await reader.cancel().catch(() => {});
|
|
11136
|
-
const { status, error } = classifyQoderFailure(failure);
|
|
12152
|
+
const { status, kind, error } = classifyQoderFailure(failure);
|
|
11137
12153
|
const retryAfter = error instanceof QoderQueueRejection || error instanceof QoderDailyLimitRejection ? error.retryAfterSeconds : void 0;
|
|
11138
12154
|
const wait = retryAfter === void 0 ? void 0 : retryAfterHeader(retryAfter);
|
|
11139
12155
|
return Response.json({ error: {
|
|
11140
|
-
message: error.message === "" ? `Qoder refused the request (${failure.code})` : error.message.slice(0, 1024),
|
|
12156
|
+
message: error.message === "" ? `Qoder refused the request (${failure.code})` : redactSecrets(error.message).slice(0, 1024),
|
|
11141
12157
|
type: "upstream_error",
|
|
11142
12158
|
code: status,
|
|
11143
12159
|
...retryAfter === void 0 || !(retryAfter > 0) ? {} : { retryAfterSeconds: retryAfter }
|
|
11144
12160
|
} }, {
|
|
11145
12161
|
status,
|
|
11146
|
-
|
|
12162
|
+
headers: {
|
|
12163
|
+
[QODER_FAILURE_KIND_HEADER]: kind,
|
|
12164
|
+
...wait === void 0 ? {} : { "Retry-After": wait }
|
|
12165
|
+
}
|
|
12166
|
+
});
|
|
12167
|
+
}
|
|
12168
|
+
if (failure === void 0 && bufferedBytes === 0 && ended) {
|
|
12169
|
+
await reader.cancel().catch(() => {});
|
|
12170
|
+
return Response.json({ error: {
|
|
12171
|
+
message: "Qoder returned an empty answer stream",
|
|
12172
|
+
type: "upstream_error",
|
|
12173
|
+
code: 502
|
|
12174
|
+
} }, {
|
|
12175
|
+
status: 502,
|
|
12176
|
+
headers: { [QODER_FAILURE_KIND_HEADER]: "empty_stream" }
|
|
11147
12177
|
});
|
|
11148
12178
|
}
|
|
11149
12179
|
const relay = bridgeQoderStream(replaySource(buffered, {
|
|
@@ -11243,10 +12273,15 @@ function createQoderGateway(options) {
|
|
|
11243
12273
|
res.on("close", () => watcher.abort());
|
|
11244
12274
|
const raw = (await readRequestBody(req)).toString("utf8");
|
|
11245
12275
|
let model = "";
|
|
12276
|
+
let bodyIsJson = true;
|
|
11246
12277
|
try {
|
|
11247
12278
|
model = JSON.parse(raw)["model"] ?? "";
|
|
11248
12279
|
} catch {
|
|
11249
|
-
|
|
12280
|
+
bodyIsJson = false;
|
|
12281
|
+
}
|
|
12282
|
+
if (!bodyIsJson) {
|
|
12283
|
+
writeOpenAIError(res, 400, "invalid_request_error", "body is not valid JSON");
|
|
12284
|
+
return;
|
|
11250
12285
|
}
|
|
11251
12286
|
if (typeof model !== "string" || model.trim() === "") {
|
|
11252
12287
|
writeOpenAIError(res, 400, "invalid_request_error", "model is required");
|
|
@@ -11331,11 +12366,13 @@ function createQoderGateway(options) {
|
|
|
11331
12366
|
}
|
|
11332
12367
|
if (relayed.status !== 200) {
|
|
11333
12368
|
const detail = await relayed.text().catch(() => "");
|
|
12369
|
+
const failedKind = relayed.headers.get(QODER_FAILURE_KIND_HEADER);
|
|
11334
12370
|
return {
|
|
11335
12371
|
ok: false,
|
|
11336
12372
|
status: relayed.status,
|
|
11337
12373
|
message: detail,
|
|
11338
|
-
retryAfter: relayed.headers.get("retry-after")
|
|
12374
|
+
retryAfter: relayed.headers.get("retry-after"),
|
|
12375
|
+
...failedKind === null ? {} : { kind: failedKind }
|
|
11339
12376
|
};
|
|
11340
12377
|
}
|
|
11341
12378
|
return {
|
|
@@ -11352,7 +12389,7 @@ function createQoderGateway(options) {
|
|
|
11352
12389
|
const rotates = (status, kind) => {
|
|
11353
12390
|
if (kind === "aborted") return false;
|
|
11354
12391
|
if (status === 0) return true;
|
|
11355
|
-
return kind === "authentication" || kind === "soft_rate" || kind === "hard_credit" || status === 401 || status === 402 || status === 429;
|
|
12392
|
+
return kind === "authentication" || kind === "soft_rate" || kind === "hard_credit" || kind === "empty_stream" || status === 401 || status === 402 || status === 429;
|
|
11356
12393
|
};
|
|
11357
12394
|
let opened;
|
|
11358
12395
|
for (let index = 0; index < credentials.length; index += 1) {
|
|
@@ -11990,13 +13027,6 @@ const SERVICE_BOOTSTRAP_BUDGET_MS = 1500;
|
|
|
11990
13027
|
*/
|
|
11991
13028
|
const REFRESH_PASS_BUDGET_MS = 18e3;
|
|
11992
13029
|
/**
|
|
11993
|
-
* How often the token keep-alive walks the pool.
|
|
11994
|
-
*
|
|
11995
|
-
* Half of the lifetime the pool assumes for a token that reports none, so a
|
|
11996
|
-
* sign-in nobody has used is renewed while it still works rather than at the
|
|
11997
|
-
* moment a request needs it.
|
|
11998
|
-
*/
|
|
11999
|
-
/**
|
|
12000
13030
|
* How long a started panel login stays pollable.
|
|
12001
13031
|
*
|
|
12002
13032
|
* The browser half is the user's to finish, so it is measured in minutes
|
|
@@ -12025,6 +13055,8 @@ let settings = {};
|
|
|
12025
13055
|
* a switch the user just flipped.
|
|
12026
13056
|
*/
|
|
12027
13057
|
let settingsRevision = 0;
|
|
13058
|
+
/** Orders overlapping reads, so a slower older response cannot replace a newer one. */
|
|
13059
|
+
let settingsReadSequence = 0;
|
|
12028
13060
|
/**
|
|
12029
13061
|
* Bumped only by writes this process made, never by a document the host pushed.
|
|
12030
13062
|
*
|
|
@@ -12047,7 +13079,7 @@ const runtimes = /* @__PURE__ */ new Map();
|
|
|
12047
13079
|
*/
|
|
12048
13080
|
const runtimeStarts = /* @__PURE__ */ new Map();
|
|
12049
13081
|
/**
|
|
12050
|
-
*
|
|
13082
|
+
* Retired gateway starts and closes that may still hold a port.
|
|
12051
13083
|
*
|
|
12052
13084
|
* That function runs synchronously inside settings application, yet a source
|
|
12053
13085
|
* toggled off and straight back on starts a new gateway while the old one's
|
|
@@ -12080,6 +13112,8 @@ const gatewayStartFailures = /* @__PURE__ */ new Map();
|
|
|
12080
13112
|
const sourceStartFailures = /* @__PURE__ */ new Map();
|
|
12081
13113
|
/** One in-flight source-gateway start per region, shared by overlapping passes. */
|
|
12082
13114
|
const sourceGatewayStarts = /* @__PURE__ */ new Map();
|
|
13115
|
+
/** Retired source starts and closes that may hold a port, keyed `source:region`. */
|
|
13116
|
+
const pendingSourceStops = /* @__PURE__ */ new Map();
|
|
12083
13117
|
/** Provider ids the host has confirmed it is serving, this process's lifetime. */
|
|
12084
13118
|
let publishedIds = /* @__PURE__ */ new Set();
|
|
12085
13119
|
/**
|
|
@@ -12295,13 +13329,16 @@ async function loadSettings() {
|
|
|
12295
13329
|
* the switch the user had just flipped.
|
|
12296
13330
|
*/
|
|
12297
13331
|
async function adoptHostSettings() {
|
|
13332
|
+
const readSequence = ++settingsReadSequence;
|
|
12298
13333
|
const revision = settingsRevision;
|
|
13334
|
+
const generation = loadGeneration;
|
|
12299
13335
|
const next = await loadSettings();
|
|
13336
|
+
if (readSequence !== settingsReadSequence) return false;
|
|
12300
13337
|
if (next === void 0) {
|
|
12301
13338
|
log("warn", "could not read settings; keeping the last known document");
|
|
12302
13339
|
return false;
|
|
12303
13340
|
}
|
|
12304
|
-
if (settingsRevision !== revision) return false;
|
|
13341
|
+
if (settingsRevision !== revision || loadGeneration !== generation) return false;
|
|
12305
13342
|
settings = next;
|
|
12306
13343
|
return true;
|
|
12307
13344
|
}
|
|
@@ -12317,9 +13354,12 @@ async function adoptHostSettings() {
|
|
|
12317
13354
|
* it read, and the panel answered success for a change that was gone.
|
|
12318
13355
|
*/
|
|
12319
13356
|
async function saveSettings(patch) {
|
|
13357
|
+
const generation = loadGeneration;
|
|
12320
13358
|
return enqueueWrite(async () => {
|
|
13359
|
+
if (generation !== loadGeneration) return false;
|
|
12321
13360
|
try {
|
|
12322
13361
|
await pi.plugin.setSettings(patch);
|
|
13362
|
+
if (generation !== loadGeneration) return false;
|
|
12323
13363
|
settings = {
|
|
12324
13364
|
...settings,
|
|
12325
13365
|
...patch
|
|
@@ -12362,13 +13402,22 @@ function enqueueWrite(work) {
|
|
|
12362
13402
|
* `undefined` means "no change", which skips the write entirely.
|
|
12363
13403
|
*/
|
|
12364
13404
|
async function mutateSettings(key, mutate) {
|
|
13405
|
+
const generation = loadGeneration;
|
|
12365
13406
|
return enqueueWrite(async () => {
|
|
12366
|
-
|
|
13407
|
+
if (generation !== loadGeneration) return false;
|
|
13408
|
+
let adopted = false;
|
|
13409
|
+
for (let attempt = 0; attempt < 2 && !adopted; attempt += 1) {
|
|
13410
|
+
adopted = await adoptHostSettings();
|
|
13411
|
+
if (generation !== loadGeneration) return false;
|
|
13412
|
+
}
|
|
13413
|
+
if (!adopted) return false;
|
|
12367
13414
|
const current = settings[key];
|
|
12368
13415
|
const next = await mutate(current);
|
|
13416
|
+
if (generation !== loadGeneration) return false;
|
|
12369
13417
|
if (next === void 0) return true;
|
|
12370
13418
|
try {
|
|
12371
13419
|
await pi.plugin.setSettings({ [key]: next });
|
|
13420
|
+
if (generation !== loadGeneration) return false;
|
|
12372
13421
|
settings = {
|
|
12373
13422
|
...settings,
|
|
12374
13423
|
[key]: next
|
|
@@ -12407,23 +13456,24 @@ function resetDiscoveryCaches() {
|
|
|
12407
13456
|
*/
|
|
12408
13457
|
async function onHostSettingsChanged(next) {
|
|
12409
13458
|
if (next === null || typeof next !== "object" || Array.isArray(next)) return false;
|
|
13459
|
+
const generation = loadGeneration;
|
|
12410
13460
|
const localRevision = localSettingsRevision;
|
|
12411
13461
|
return enqueueWrite(async () => {
|
|
12412
|
-
if (
|
|
13462
|
+
if (!stillLoaded(generation)) return false;
|
|
12413
13463
|
const before = settings;
|
|
12414
13464
|
if (localSettingsRevision !== localRevision) {
|
|
12415
13465
|
if (!await adoptHostSettings()) {
|
|
12416
|
-
scheduleRefresh("settings");
|
|
13466
|
+
if (stillLoaded(generation)) scheduleRefresh("settings");
|
|
12417
13467
|
return false;
|
|
12418
13468
|
}
|
|
12419
13469
|
} else {
|
|
12420
13470
|
settings = next;
|
|
12421
13471
|
settingsRevision += 1;
|
|
12422
13472
|
}
|
|
13473
|
+
if (!stillLoaded(generation)) return false;
|
|
12423
13474
|
const toggled = Object.values(SOURCE_SETTING_KEYS).some((key) => Object.hasOwn(settings, key) && before[key] !== settings[key]);
|
|
12424
13475
|
if (toggled) resetDiscoveryCaches();
|
|
12425
|
-
await applySettingsEverywhere(toggled);
|
|
12426
|
-
return true;
|
|
13476
|
+
return await applySettingsEverywhere(toggled);
|
|
12427
13477
|
});
|
|
12428
13478
|
}
|
|
12429
13479
|
/**
|
|
@@ -12434,11 +13484,15 @@ async function onHostSettingsChanged(next) {
|
|
|
12434
13484
|
* document to merge.
|
|
12435
13485
|
*/
|
|
12436
13486
|
async function applySettingsEverywhere(toggled) {
|
|
13487
|
+
const generation = loadGeneration;
|
|
13488
|
+
if (!stillLoaded(generation)) return false;
|
|
12437
13489
|
applySettingsToCore();
|
|
12438
13490
|
traeAccountRows = traeAccountRows.filter((row) => regionEnabled("trae", row.region));
|
|
12439
13491
|
qoderAccountRows = qoderAccountRows.filter((row) => regionEnabled("qoder", row.region));
|
|
12440
13492
|
await reconcileTraeGateways();
|
|
13493
|
+
if (!stillLoaded(generation)) return false;
|
|
12441
13494
|
await reconcileQoderGateways();
|
|
13495
|
+
if (!stillLoaded(generation)) return false;
|
|
12442
13496
|
syncDeclaration();
|
|
12443
13497
|
if (toggled) probeCache.clear();
|
|
12444
13498
|
if (toggled) {
|
|
@@ -12944,6 +13998,44 @@ async function settleWithin(work, budgetMs) {
|
|
|
12944
13998
|
clearTimeout(timer);
|
|
12945
13999
|
}
|
|
12946
14000
|
}
|
|
14001
|
+
async function waitForRuntimeStops() {
|
|
14002
|
+
const deadline = Date.now() + 1500;
|
|
14003
|
+
while (pendingRuntimeStops.length > 0) {
|
|
14004
|
+
const left = deadline - Date.now();
|
|
14005
|
+
if (left <= 0 || await settleWithin(Promise.allSettled(pendingRuntimeStops), left) === void 0) return;
|
|
14006
|
+
}
|
|
14007
|
+
}
|
|
14008
|
+
async function waitForSourceStops(key) {
|
|
14009
|
+
const deadline = Date.now() + 1500;
|
|
14010
|
+
while (pendingSourceStops.has(key)) {
|
|
14011
|
+
const left = deadline - Date.now();
|
|
14012
|
+
if (left <= 0 || await settleWithin(Promise.allSettled(pendingSourceStops.get(key)), left) === void 0) return;
|
|
14013
|
+
}
|
|
14014
|
+
}
|
|
14015
|
+
function trackPendingSource(key, stopping) {
|
|
14016
|
+
let pending = pendingSourceStops.get(key);
|
|
14017
|
+
if (pending === void 0) {
|
|
14018
|
+
pending = /* @__PURE__ */ new Set();
|
|
14019
|
+
pendingSourceStops.set(key, pending);
|
|
14020
|
+
}
|
|
14021
|
+
pending.add(stopping);
|
|
14022
|
+
const forget = () => {
|
|
14023
|
+
pending.delete(stopping);
|
|
14024
|
+
if (pending.size === 0 && pendingSourceStops.get(key) === pending) pendingSourceStops.delete(key);
|
|
14025
|
+
};
|
|
14026
|
+
stopping.then(forget, forget);
|
|
14027
|
+
return stopping;
|
|
14028
|
+
}
|
|
14029
|
+
function trackSourceStop(entry) {
|
|
14030
|
+
const key = entry.source + ":" + entry.region;
|
|
14031
|
+
return trackPendingSource(key, (async () => {
|
|
14032
|
+
try {
|
|
14033
|
+
await entry.gateway.close();
|
|
14034
|
+
} catch (error) {
|
|
14035
|
+
log("warn", "[" + key + "] gateway did not close cleanly: " + safeMessage(error));
|
|
14036
|
+
}
|
|
14037
|
+
})());
|
|
14038
|
+
}
|
|
12947
14039
|
/**
|
|
12948
14040
|
* One deadline, and the two things a bounded pass does with it.
|
|
12949
14041
|
*
|
|
@@ -13154,12 +14246,62 @@ function syncDeclaration() {
|
|
|
13154
14246
|
];
|
|
13155
14247
|
const currentIds = new Set(current.map((provider) => provider.id));
|
|
13156
14248
|
const warming = warmingGatewayIds();
|
|
13157
|
-
const retained = declaredProviders().
|
|
14249
|
+
const retained = declaredProviders().flatMap((provider) => {
|
|
14250
|
+
if (!activeIds.has(provider.id) || currentIds.has(provider.id) || !warming.has(provider.id)) return [];
|
|
14251
|
+
const rebound = warmingDescriptor(provider);
|
|
14252
|
+
return rebound === void 0 ? [] : [rebound];
|
|
14253
|
+
});
|
|
13158
14254
|
const result = writeDeclaration([...current, ...retained]);
|
|
13159
14255
|
runtimeState.write = result;
|
|
13160
14256
|
return result;
|
|
13161
14257
|
}
|
|
13162
14258
|
/**
|
|
14259
|
+
* Rebind a retained roster to the address the current run serves on.
|
|
14260
|
+
*
|
|
14261
|
+
* A gateway that is still trying has no address to retain: the fallback each
|
|
14262
|
+
* descriptor uses is its preferred port, and nothing is listening there before
|
|
14263
|
+
* the listener is created. Republishing that address would leave the host with a
|
|
14264
|
+
* row whose every request is refused while the panel reports no drift, which is
|
|
14265
|
+
* the failure this retention exists to avoid.
|
|
14266
|
+
*
|
|
14267
|
+
* Only the placeholder is refused, not every missing address: a runtime that has
|
|
14268
|
+
* been created but has not recorded an address yet is still on its way, and the
|
|
14269
|
+
* preferred port is where it will land. WorkBuddy always checked the placeholder
|
|
14270
|
+
* for its own gateways; the Trae and Qoder branches did not, so a gateway that
|
|
14271
|
+
* had failed to bind left its saved row published over a dead port.
|
|
14272
|
+
*/
|
|
14273
|
+
function warmingDescriptor(provider) {
|
|
14274
|
+
const NOT_LISTENING = "http://127.0.0.1:1/v1";
|
|
14275
|
+
const listeningAt = (address) => address !== NOT_LISTENING;
|
|
14276
|
+
for (const [region, id] of Object.entries(PROVIDER_ID_BY_REGION)) {
|
|
14277
|
+
if (id !== provider.id) continue;
|
|
14278
|
+
const runtime = runtimes.get(region);
|
|
14279
|
+
if (runtime !== void 0 && !listeningAt(runtime.baseUrl)) return void 0;
|
|
14280
|
+
return {
|
|
14281
|
+
...provider,
|
|
14282
|
+
baseUrl: descriptorFor(region).baseUrl
|
|
14283
|
+
};
|
|
14284
|
+
}
|
|
14285
|
+
for (const [region, id] of Object.entries(TRAE_PROVIDER_ID_BY_REGION)) {
|
|
14286
|
+
if (id !== provider.id) continue;
|
|
14287
|
+
const entry = traeGateways.get(region);
|
|
14288
|
+
if (entry !== void 0 && !listeningAt(entry.baseUrl)) return void 0;
|
|
14289
|
+
return {
|
|
14290
|
+
...provider,
|
|
14291
|
+
baseUrl: descriptorForTrae(region).baseUrl
|
|
14292
|
+
};
|
|
14293
|
+
}
|
|
14294
|
+
for (const [region, id] of Object.entries(QODER_PROVIDER_ID_BY_REGION)) {
|
|
14295
|
+
if (id !== provider.id) continue;
|
|
14296
|
+
const entry = qoderGateways.get(region);
|
|
14297
|
+
if (entry !== void 0 && !listeningAt(entry.baseUrl)) return void 0;
|
|
14298
|
+
return {
|
|
14299
|
+
...provider,
|
|
14300
|
+
baseUrl: descriptorForQoder(region).baseUrl
|
|
14301
|
+
};
|
|
14302
|
+
}
|
|
14303
|
+
}
|
|
14304
|
+
/**
|
|
13163
14305
|
* The provider ids of the active gateways that are still warming up.
|
|
13164
14306
|
*
|
|
13165
14307
|
* "Warming" is the only reason a row is republished for a gateway that cannot
|
|
@@ -13173,6 +14315,10 @@ function warmingGatewayIds() {
|
|
|
13173
14315
|
const runtime = runtimes.get(region);
|
|
13174
14316
|
if (gatewayStartFailures.has(region)) continue;
|
|
13175
14317
|
if (runtime === void 0 || runtime.connecting !== null) ids.add(PROVIDER_ID_BY_REGION[region]);
|
|
14318
|
+
else {
|
|
14319
|
+
const pool = core.pool?.status();
|
|
14320
|
+
if (pool?.lastScanAtMs === 0 && pool.scanning === true) ids.add(PROVIDER_ID_BY_REGION[region]);
|
|
14321
|
+
}
|
|
13176
14322
|
}
|
|
13177
14323
|
for (const [source, gateways, regions, idByRegion] of [[
|
|
13178
14324
|
"trae",
|
|
@@ -13330,26 +14476,31 @@ async function reconcileTraeGateways() {
|
|
|
13330
14476
|
if (active.includes(region)) continue;
|
|
13331
14477
|
traeGateways.delete(region);
|
|
13332
14478
|
sourceStartFailures.delete("trae:" + region);
|
|
13333
|
-
|
|
13334
|
-
await entry.gateway.close();
|
|
13335
|
-
} catch (error) {
|
|
13336
|
-
log("warn", "[trae:" + region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
13337
|
-
}
|
|
14479
|
+
await trackSourceStop(entry);
|
|
13338
14480
|
}
|
|
13339
14481
|
for (const region of active) {
|
|
13340
14482
|
if (!stillLoaded(generation) || serviceStopped) return;
|
|
13341
14483
|
if (traeGateways.has(region)) continue;
|
|
13342
14484
|
const key = "trae:" + region;
|
|
13343
|
-
|
|
13344
|
-
if (
|
|
14485
|
+
await waitForSourceStops(key);
|
|
14486
|
+
if (!stillLoaded(generation)) return;
|
|
14487
|
+
if (!activeTraeRegions().includes(region)) continue;
|
|
14488
|
+
if (traeGateways.has(region)) continue;
|
|
14489
|
+
let pending = sourceGatewayStarts.get(key);
|
|
14490
|
+
while (pending !== void 0) {
|
|
13345
14491
|
await pending.catch(() => {});
|
|
13346
|
-
|
|
14492
|
+
await waitForSourceStops(key);
|
|
14493
|
+
if (!stillLoaded(generation)) return;
|
|
14494
|
+
if (!activeTraeRegions().includes(region) || traeGateways.has(region)) break;
|
|
14495
|
+
if (sourceGatewayStarts.get(key) === pending) sourceGatewayStarts.delete(key);
|
|
14496
|
+
pending = sourceGatewayStarts.get(key);
|
|
13347
14497
|
}
|
|
14498
|
+
if (!activeTraeRegions().includes(region) || traeGateways.has(region)) continue;
|
|
13348
14499
|
const starting = createTraeRuntime(region);
|
|
13349
14500
|
sourceGatewayStarts.set(key, starting);
|
|
13350
14501
|
try {
|
|
13351
14502
|
const entry = await starting;
|
|
13352
|
-
if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await entry
|
|
14503
|
+
if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await trackSourceStop(entry);
|
|
13353
14504
|
else {
|
|
13354
14505
|
traeGateways.set(region, entry);
|
|
13355
14506
|
sourceStartFailures.delete(key);
|
|
@@ -13486,26 +14637,31 @@ async function reconcileQoderGateways() {
|
|
|
13486
14637
|
if (active.includes(region)) continue;
|
|
13487
14638
|
qoderGateways.delete(region);
|
|
13488
14639
|
sourceStartFailures.delete("qoder:" + region);
|
|
13489
|
-
|
|
13490
|
-
await entry.gateway.close();
|
|
13491
|
-
} catch (error) {
|
|
13492
|
-
log("warn", "[qoder:" + region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
13493
|
-
}
|
|
14640
|
+
await trackSourceStop(entry);
|
|
13494
14641
|
}
|
|
13495
14642
|
for (const region of active) {
|
|
13496
14643
|
if (!stillLoaded(generation) || serviceStopped) return;
|
|
13497
14644
|
if (qoderGateways.has(region)) continue;
|
|
13498
14645
|
const key = "qoder:" + region;
|
|
13499
|
-
|
|
13500
|
-
if (
|
|
14646
|
+
await waitForSourceStops(key);
|
|
14647
|
+
if (!stillLoaded(generation)) return;
|
|
14648
|
+
if (!activeQoderRegions().includes(region)) continue;
|
|
14649
|
+
if (qoderGateways.has(region)) continue;
|
|
14650
|
+
let pending = sourceGatewayStarts.get(key);
|
|
14651
|
+
while (pending !== void 0) {
|
|
13501
14652
|
await pending.catch(() => {});
|
|
13502
|
-
|
|
14653
|
+
await waitForSourceStops(key);
|
|
14654
|
+
if (!stillLoaded(generation)) return;
|
|
14655
|
+
if (!activeQoderRegions().includes(region) || qoderGateways.has(region)) break;
|
|
14656
|
+
if (sourceGatewayStarts.get(key) === pending) sourceGatewayStarts.delete(key);
|
|
14657
|
+
pending = sourceGatewayStarts.get(key);
|
|
13503
14658
|
}
|
|
14659
|
+
if (!activeQoderRegions().includes(region) || qoderGateways.has(region)) continue;
|
|
13504
14660
|
const starting = createQoderRuntime(region);
|
|
13505
14661
|
sourceGatewayStarts.set(key, starting);
|
|
13506
14662
|
try {
|
|
13507
14663
|
const entry = await starting;
|
|
13508
|
-
if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await entry
|
|
14664
|
+
if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await trackSourceStop(entry);
|
|
13509
14665
|
else {
|
|
13510
14666
|
qoderGateways.set(region, entry);
|
|
13511
14667
|
sourceStartFailures.delete(key);
|
|
@@ -13669,7 +14825,7 @@ async function settleStartedRuntime(region, runtime, unwanted) {
|
|
|
13669
14825
|
if (held === runtime) return true;
|
|
13670
14826
|
if (runtime.retired === true) return false;
|
|
13671
14827
|
if (unwanted || held !== void 0) {
|
|
13672
|
-
await
|
|
14828
|
+
await trackRuntimeStop(runtime);
|
|
13673
14829
|
return false;
|
|
13674
14830
|
}
|
|
13675
14831
|
runtimes.set(region, runtime);
|
|
@@ -13689,7 +14845,10 @@ async function settleStartedRuntime(region, runtime, unwanted) {
|
|
|
13689
14845
|
async function startRuntimes() {
|
|
13690
14846
|
const generation = loadGeneration;
|
|
13691
14847
|
if (!stillLoaded(generation)) return;
|
|
13692
|
-
if (pendingRuntimeStops.length > 0)
|
|
14848
|
+
if (pendingRuntimeStops.length > 0) {
|
|
14849
|
+
await waitForRuntimeStops();
|
|
14850
|
+
if (!stillLoaded(generation)) return;
|
|
14851
|
+
}
|
|
13693
14852
|
await Promise.all(activeRegions().map(async (region) => {
|
|
13694
14853
|
if (runtimes.has(region)) return;
|
|
13695
14854
|
try {
|
|
@@ -13706,10 +14865,24 @@ async function stopRuntime(runtime) {
|
|
|
13706
14865
|
if (runtime.retired === true) return;
|
|
13707
14866
|
runtime.retired = true;
|
|
13708
14867
|
runtime.signedIn = false;
|
|
13709
|
-
gatewayStartFailures.delete(runtime.region);
|
|
13710
|
-
|
|
14868
|
+
if (runtimes.get(runtime.region) === runtime) gatewayStartFailures.delete(runtime.region);
|
|
14869
|
+
try {
|
|
14870
|
+
if (runtime.shim) await runtime.shim.close();
|
|
14871
|
+
} catch (error) {
|
|
13711
14872
|
log("warn", "[workbuddy:" + runtime.region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
13712
|
-
}
|
|
14873
|
+
}
|
|
14874
|
+
}
|
|
14875
|
+
function trackPendingRuntime(stopping) {
|
|
14876
|
+
pendingRuntimeStops.push(stopping);
|
|
14877
|
+
const forget = () => {
|
|
14878
|
+
const index = pendingRuntimeStops.indexOf(stopping);
|
|
14879
|
+
if (index !== -1) pendingRuntimeStops.splice(index, 1);
|
|
14880
|
+
};
|
|
14881
|
+
stopping.then(forget, forget);
|
|
14882
|
+
return stopping;
|
|
14883
|
+
}
|
|
14884
|
+
function trackRuntimeStop(runtime) {
|
|
14885
|
+
return trackPendingRuntime(stopRuntime(runtime));
|
|
13713
14886
|
}
|
|
13714
14887
|
/**
|
|
13715
14888
|
* Come back for a roster that could not be read.
|
|
@@ -13914,7 +15087,7 @@ async function refreshAll(reason, force) {
|
|
|
13914
15087
|
}
|
|
13915
15088
|
for (const region of activeRegions()) {
|
|
13916
15089
|
if (pendingRuntimeStops.length > 0) {
|
|
13917
|
-
await
|
|
15090
|
+
await waitForRuntimeStops();
|
|
13918
15091
|
if (!stillLoaded(generation)) return stalePass();
|
|
13919
15092
|
}
|
|
13920
15093
|
if (runtimes.has(region)) continue;
|
|
@@ -13923,13 +15096,14 @@ async function refreshAll(reason, force) {
|
|
|
13923
15096
|
try {
|
|
13924
15097
|
runtime = await settle(starting);
|
|
13925
15098
|
} catch (error) {
|
|
15099
|
+
if (!stillLoaded(generation)) return stalePass();
|
|
13926
15100
|
gatewayStartFailures.set(region, safeMessage(error));
|
|
13927
15101
|
log("warn", "[" + region + "] gateway could not start: " + safeMessage(error));
|
|
13928
15102
|
continue;
|
|
13929
15103
|
}
|
|
13930
15104
|
if (runtime === void 0) {
|
|
13931
15105
|
starting.then((late) => {
|
|
13932
|
-
if (runtimes.get(region) !== late) return
|
|
15106
|
+
if (runtimes.get(region) !== late) return trackRuntimeStop(late);
|
|
13933
15107
|
}).catch(() => {});
|
|
13934
15108
|
continue;
|
|
13935
15109
|
}
|
|
@@ -14251,7 +15425,7 @@ function applySettingsToCore() {
|
|
|
14251
15425
|
function reconcileRuntimes() {
|
|
14252
15426
|
const active = new Set(activeRegions());
|
|
14253
15427
|
for (const [region, runtime] of runtimes) if (!active.has(region)) {
|
|
14254
|
-
|
|
15428
|
+
trackRuntimeStop(runtime);
|
|
14255
15429
|
runtimes.delete(region);
|
|
14256
15430
|
}
|
|
14257
15431
|
if (active.size === 0 && core.pool) {
|
|
@@ -15986,9 +17160,9 @@ async function redeemAccountStreak(account) {
|
|
|
15986
17160
|
const chances = await core.client.lotteryChances(account.credential);
|
|
15987
17161
|
for (let draw = 0; draw < chances; draw += 1) {
|
|
15988
17162
|
if (signal.aborted) return result;
|
|
15989
|
-
|
|
17163
|
+
await core.client.drawLottery(account.credential);
|
|
15990
17164
|
detail.lottery += 1;
|
|
15991
|
-
log("info", "streak " + accountLogTag(account.label) + ": draw " + (draw + 1) + "/" + chances
|
|
17165
|
+
log("info", "streak " + accountLogTag(account.label) + ": draw " + (draw + 1) + "/" + chances);
|
|
15992
17166
|
}
|
|
15993
17167
|
} catch (error) {
|
|
15994
17168
|
detail.failed += 1;
|
|
@@ -16771,8 +17945,9 @@ function stopAccountWatch() {
|
|
|
16771
17945
|
* Note this is the only place the roster is fetched during load: opening the
|
|
16772
17946
|
* panel no longer triggers detection of its own.
|
|
16773
17947
|
*/
|
|
16774
|
-
async function publishDeclarationEarly() {
|
|
17948
|
+
async function publishDeclarationEarly(generation) {
|
|
16775
17949
|
await adoptHostSettings();
|
|
17950
|
+
if (!stillLoaded(generation)) return;
|
|
16776
17951
|
if (settings.enabled === false) {
|
|
16777
17952
|
const cleared = syncDeclaration();
|
|
16778
17953
|
if (cleared.ok !== true) log("warn", "declaration not cleared: " + String(cleared.error));
|
|
@@ -16782,9 +17957,13 @@ async function publishDeclarationEarly() {
|
|
|
16782
17957
|
reconcileRuntimes();
|
|
16783
17958
|
const { left: bootstrapLeft } = budget(LOAD_BOOTSTRAP_BUDGET_MS);
|
|
16784
17959
|
await settleWithin(reconcileTraeGateways(), bootstrapLeft());
|
|
17960
|
+
if (!stillLoaded(generation)) return;
|
|
16785
17961
|
await settleWithin(reconcileQoderGateways(), bootstrapLeft());
|
|
17962
|
+
if (!stillLoaded(generation)) return;
|
|
16786
17963
|
if (activeRegions().length > 0) await settleWithin(core.pool.scan(), bootstrapLeft());
|
|
17964
|
+
if (!stillLoaded(generation)) return;
|
|
16787
17965
|
await settleWithin(startRuntimes(), bootstrapLeft());
|
|
17966
|
+
if (!stillLoaded(generation)) return;
|
|
16788
17967
|
await settleWithin(Promise.all(Array.from(runtimes.values()).map(async (runtime) => {
|
|
16789
17968
|
try {
|
|
16790
17969
|
await connect(runtime, true);
|
|
@@ -16793,6 +17972,7 @@ async function publishDeclarationEarly() {
|
|
|
16793
17972
|
log("warn", runtime.region + " failed to start during load: " + runtime.lastError);
|
|
16794
17973
|
}
|
|
16795
17974
|
})), LOAD_ROSTER_BUDGET_MS);
|
|
17975
|
+
if (!stillLoaded(generation)) return;
|
|
16796
17976
|
const written = syncDeclaration();
|
|
16797
17977
|
if (written.ok !== true) log("warn", "declaration not written: " + String(written.error));
|
|
16798
17978
|
else if (written.changed === true) log("info", "declaration updated at load time; " + written.providerCount + " provider(s)");
|
|
@@ -16801,6 +17981,8 @@ async function onServiceStart() {
|
|
|
16801
17981
|
const generation = loadGeneration;
|
|
16802
17982
|
serviceStopped = false;
|
|
16803
17983
|
if (warmAbort.signal.aborted) warmAbort = new AbortController();
|
|
17984
|
+
await writeChain;
|
|
17985
|
+
if (!stillLoaded(generation)) return;
|
|
16804
17986
|
await adoptHostSettings();
|
|
16805
17987
|
if (!stillLoaded(generation)) return;
|
|
16806
17988
|
if (settings.enabled === false) {
|
|
@@ -16835,6 +18017,7 @@ async function onServiceStart() {
|
|
|
16835
18017
|
async function onServiceStop() {
|
|
16836
18018
|
serviceStopped = true;
|
|
16837
18019
|
loadGeneration += 1;
|
|
18020
|
+
core.pool?.clear();
|
|
16838
18021
|
if (refreshTimer !== null) {
|
|
16839
18022
|
clearTimeout(refreshTimer);
|
|
16840
18023
|
refreshTimer = null;
|
|
@@ -16845,22 +18028,24 @@ async function onServiceStop() {
|
|
|
16845
18028
|
abortWarmups();
|
|
16846
18029
|
clearModelRetries();
|
|
16847
18030
|
checkinAbort.abort();
|
|
16848
|
-
const closing = Array.from(runtimes.values()).map(
|
|
18031
|
+
const closing = Array.from(runtimes.values()).map(trackRuntimeStop);
|
|
16849
18032
|
runtimes.clear();
|
|
18033
|
+
for (const starting of runtimeStarts.values()) trackPendingRuntime(starting);
|
|
16850
18034
|
runtimeStarts.clear();
|
|
16851
|
-
for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) closing.push(entry
|
|
16852
|
-
log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
16853
|
-
}));
|
|
18035
|
+
for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) closing.push(trackSourceStop(entry));
|
|
16854
18036
|
traeGateways.clear();
|
|
16855
18037
|
qoderGateways.clear();
|
|
16856
18038
|
gatewayStartFailures.clear();
|
|
16857
18039
|
sourceStartFailures.clear();
|
|
18040
|
+
for (const [key, starting] of sourceGatewayStarts) trackPendingSource(key, starting);
|
|
16858
18041
|
sourceGatewayStarts.clear();
|
|
16859
18042
|
await Promise.all(closing);
|
|
16860
18043
|
}
|
|
16861
18044
|
async function onLoad() {
|
|
16862
18045
|
serviceStopped = false;
|
|
16863
18046
|
loadGeneration += 1;
|
|
18047
|
+
const generation = loadGeneration;
|
|
18048
|
+
core.pool?.clear();
|
|
16864
18049
|
abortWarmups();
|
|
16865
18050
|
warmAbort = new AbortController();
|
|
16866
18051
|
checkinAbort.abort();
|
|
@@ -16873,9 +18058,11 @@ async function onLoad() {
|
|
|
16873
18058
|
refreshTimer = null;
|
|
16874
18059
|
}
|
|
16875
18060
|
refreshInflight = null;
|
|
16876
|
-
for (const runtime of runtimes.values())
|
|
18061
|
+
for (const runtime of runtimes.values()) trackRuntimeStop(runtime);
|
|
16877
18062
|
runtimes.clear();
|
|
18063
|
+
for (const starting of runtimeStarts.values()) trackPendingRuntime(starting);
|
|
16878
18064
|
runtimeStarts.clear();
|
|
18065
|
+
for (const [key, starting] of sourceGatewayStarts) trackPendingSource(key, starting);
|
|
16879
18066
|
sourceGatewayStarts.clear();
|
|
16880
18067
|
checkinPassRunning = false;
|
|
16881
18068
|
autoCheckinSlots.clear();
|
|
@@ -16896,24 +18083,29 @@ async function onLoad() {
|
|
|
16896
18083
|
error: (...args) => log("error", gatewayLogLine("", args))
|
|
16897
18084
|
}
|
|
16898
18085
|
});
|
|
18086
|
+
await writeChain;
|
|
18087
|
+
if (!stillLoaded(generation)) return;
|
|
16899
18088
|
await adoptHostSettings();
|
|
16900
|
-
if (
|
|
18089
|
+
if (!stillLoaded(generation)) return;
|
|
16901
18090
|
publishedIds = /* @__PURE__ */ new Set();
|
|
18091
|
+
let nextDataPath;
|
|
16902
18092
|
try {
|
|
16903
|
-
|
|
18093
|
+
nextDataPath = await pi.plugin.getDataPath();
|
|
16904
18094
|
} catch (error) {
|
|
16905
|
-
|
|
18095
|
+
nextDataPath = "";
|
|
16906
18096
|
log("warn", "no plugin data path: " + safeMessage(error));
|
|
16907
18097
|
}
|
|
18098
|
+
if (!stillLoaded(generation)) return;
|
|
18099
|
+
dataPath = nextDataPath;
|
|
16908
18100
|
loadCheckinSlots();
|
|
16909
|
-
if (
|
|
18101
|
+
if (!stillLoaded(generation)) return;
|
|
16910
18102
|
pi.services.register({
|
|
16911
18103
|
id: SERVICE_ID,
|
|
16912
18104
|
start: onServiceStart,
|
|
16913
18105
|
stop: onServiceStop
|
|
16914
18106
|
});
|
|
16915
18107
|
subscribeToHostSettings();
|
|
16916
|
-
await publishDeclarationEarly();
|
|
18108
|
+
await publishDeclarationEarly(generation);
|
|
16917
18109
|
}
|
|
16918
18110
|
async function onUnload() {
|
|
16919
18111
|
loadGeneration += 1;
|
|
@@ -16925,7 +18117,7 @@ async function onUnload() {
|
|
|
16925
18117
|
stopAccountWatch();
|
|
16926
18118
|
clearModelRetries();
|
|
16927
18119
|
abortWarmups();
|
|
16928
|
-
|
|
18120
|
+
const stopping = onServiceStop();
|
|
16929
18121
|
probeCache.clear();
|
|
16930
18122
|
sourceFailureHold.clear();
|
|
16931
18123
|
sourceCreditExpiry.clear();
|
|
@@ -16937,6 +18129,7 @@ async function onUnload() {
|
|
|
16937
18129
|
sourceGatewayStarts.clear();
|
|
16938
18130
|
deviceLogins.clear();
|
|
16939
18131
|
unsubscribeFromHostSettings();
|
|
18132
|
+
await stopping;
|
|
16940
18133
|
}
|
|
16941
18134
|
function composerPointsEnabled() {
|
|
16942
18135
|
return settings.showComposerPoints === true;
|
|
@@ -17157,6 +18350,8 @@ const STREAM_IDLE_TIMEOUT_MS = 3e5;
|
|
|
17157
18350
|
/** Image-request budgets at the dsh-llm-pi-ai defaults. */
|
|
17158
18351
|
const REQUEST_IMAGE_BUDGETS = {
|
|
17159
18352
|
maxRequestImageBytes: 20971520,
|
|
18353
|
+
maxRequestImages: 50,
|
|
18354
|
+
imageOffloadCountQuantum: 10,
|
|
17160
18355
|
requestImagePixelBudget: 4194304,
|
|
17161
18356
|
requestImageMaxBytes: 1048576
|
|
17162
18357
|
};
|
|
@@ -17336,56 +18531,43 @@ function toPiModel(row, baseUrl, providerId) {
|
|
|
17336
18531
|
compat: { supportsReasoningEffort: map !== void 0 }
|
|
17337
18532
|
};
|
|
17338
18533
|
}
|
|
17339
|
-
/**
|
|
17340
|
-
* Whether the resolved pi-ai carries the prompt inside the transcript.
|
|
17341
|
-
*
|
|
17342
|
-
* The host folds `Context.systemPrompt` and `Context.tools` into a leading
|
|
17343
|
-
* `role:"system"` message before a provider sees a request, and only a
|
|
17344
|
-
* generation that exports `normalizeContext` reads that message back. Which
|
|
17345
|
-
* generation this plugin gets is not its own call: the harness resolves
|
|
17346
|
-
* `@earendil-works/pi-ai` through the profile's hoisted linker, so a profile
|
|
17347
|
-
* that hoists an older generation hands this provider a transcript its own copy
|
|
17348
|
-
* of pi-ai never learned to read.
|
|
17349
|
-
*/
|
|
18534
|
+
/** Whether this delegate reads the prompt and tools from a transcript. */
|
|
17350
18535
|
const PI_AI_FOLDS_TRANSCRIPT = typeof piAi.normalizeContext === "function";
|
|
17351
|
-
/**
|
|
17352
|
-
function
|
|
17353
|
-
|
|
17354
|
-
|
|
17355
|
-
|
|
17356
|
-
}
|
|
17357
|
-
|
|
17358
|
-
|
|
17359
|
-
|
|
17360
|
-
|
|
17361
|
-
|
|
17362
|
-
|
|
17363
|
-
|
|
17364
|
-
|
|
17365
|
-
|
|
17366
|
-
|
|
17367
|
-
|
|
17368
|
-
|
|
17369
|
-
|
|
17370
|
-
|
|
17371
|
-
|
|
17372
|
-
const
|
|
17373
|
-
if (leading?.role !== "system") return context;
|
|
17374
|
-
const prompt = promptText(leading);
|
|
17375
|
-
const tools = Array.isArray(leading.toolsAdded) ? leading.toolsAdded : [];
|
|
17376
|
-
if (prompt.length === 0) log?.warn("dsh-wtq-pool: the folded system message carried no prompt text, so this request is sent without one");
|
|
18536
|
+
/** Match the adapter's request shape to the pi-ai generation used by the delegate. */
|
|
18537
|
+
function contextForDelegate(context) {
|
|
18538
|
+
if (PI_AI_FOLDS_TRANSCRIPT) {
|
|
18539
|
+
const legacy = context;
|
|
18540
|
+
return legacy.systemPrompt === void 0 && legacy.tools === void 0 ? context : piAi.normalizeContext(legacy);
|
|
18541
|
+
}
|
|
18542
|
+
const legacy = context;
|
|
18543
|
+
const messages = legacy.messages;
|
|
18544
|
+
if (!Array.isArray(messages) || !messages.some((message) => message.role === "system")) return context;
|
|
18545
|
+
const text = legacy.systemPrompt ? [legacy.systemPrompt] : [];
|
|
18546
|
+
const sections = /* @__PURE__ */ new Map();
|
|
18547
|
+
const tools = new Map((legacy.tools ?? []).map((tool) => [tool.name, tool]));
|
|
18548
|
+
for (const message of messages) {
|
|
18549
|
+
if (message.role !== "system") continue;
|
|
18550
|
+
const part = piAi.contentText(message.content);
|
|
18551
|
+
if (part.length > 0) text.push(part);
|
|
18552
|
+
for (const [name, value] of Object.entries(message.sections ?? {})) if (value === null) sections.delete(name);
|
|
18553
|
+
else sections.set(name, value);
|
|
18554
|
+
for (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);
|
|
18555
|
+
for (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);
|
|
18556
|
+
}
|
|
18557
|
+
const prompt = [...text, ...Object.values(Object.fromEntries(sections))].filter(Boolean).join("\n\n");
|
|
17377
18558
|
return {
|
|
17378
|
-
...
|
|
17379
|
-
|
|
17380
|
-
|
|
18559
|
+
...legacy,
|
|
18560
|
+
systemPrompt: prompt || void 0,
|
|
18561
|
+
tools: [...tools.values()],
|
|
18562
|
+
messages: messages.filter((message) => message.role !== "system")
|
|
17381
18563
|
};
|
|
17382
18564
|
}
|
|
17383
18565
|
/** Wrap one API implementation so every request arrives in the shape it reads. */
|
|
17384
|
-
function withDelegateShape(api
|
|
18566
|
+
function withDelegateShape(api) {
|
|
17385
18567
|
return {
|
|
17386
18568
|
...api,
|
|
17387
|
-
stream: (model, context, options) => api.stream(model, contextForDelegate(context
|
|
17388
|
-
streamSimple: (model, context, options) => api.streamSimple(model, contextForDelegate(context
|
|
18569
|
+
stream: (model, context, options) => api.stream(model, contextForDelegate(context), options),
|
|
18570
|
+
streamSimple: (model, context, options) => api.streamSimple(model, contextForDelegate(context), options)
|
|
17389
18571
|
};
|
|
17390
18572
|
}
|
|
17391
18573
|
/**
|
|
@@ -17396,8 +18578,6 @@ function withDelegateShape(api, log) {
|
|
|
17396
18578
|
* holding one profile per row is what keeps all six alive at once.
|
|
17397
18579
|
*/
|
|
17398
18580
|
function buildAdapter(descriptors, ctx) {
|
|
17399
|
-
const adapterPrototype = PiAiAdapter.prototype;
|
|
17400
|
-
if (typeof PiAiAdapter !== "function" || typeof adapterPrototype.resolveModel !== "function" || typeof adapterPrototype.prepareCall !== "function" || typeof adapterPrototype.stream !== "function") ctx.logger.error("dsh-wtq-pool: the resolved @deepseek-ai/dsh-llm-pi-ai is not the generation this plugin is written against (its adapter is missing members this plugin binds), so every request would be reshaped for a transcript that copy never learned to read");
|
|
17401
18581
|
const profiles = /* @__PURE__ */ new Map();
|
|
17402
18582
|
const providerIds = [];
|
|
17403
18583
|
for (const row of descriptors) {
|
|
@@ -17418,7 +18598,7 @@ function buildAdapter(descriptors, ctx) {
|
|
|
17418
18598
|
}
|
|
17419
18599
|
} },
|
|
17420
18600
|
models,
|
|
17421
|
-
api: withDelegateShape(openAICompletionsApi()
|
|
18601
|
+
api: withDelegateShape(openAICompletionsApi())
|
|
17422
18602
|
}),
|
|
17423
18603
|
getModels: () => models
|
|
17424
18604
|
};
|