dsh-wtq-pool 1.2.1 → 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 +34 -4
- package/README.en.md +16 -14
- package/README.md +14 -12
- package/lib/client.js +11 -5
- package/lib/index.js +2147 -875
- package/package.json +15 -18
- package/renderer/panel.css +1 -0
- package/renderer/panel.js +13 -12
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);
|
|
@@ -1920,17 +2068,8 @@ function parseUpstreamModel(value) {
|
|
|
1920
2068
|
...supportsImages === void 0 ? {} : { supportsImages }
|
|
1921
2069
|
};
|
|
1922
2070
|
}
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
* with a user turn.
|
|
1926
|
-
*
|
|
1927
|
-
* The international gateway refuses a request whose first message is not a
|
|
1928
|
-
* system prompt (code 11128, "first message is not system prompt"), and a host
|
|
1929
|
-
* that starts with the user's turn sends none. The content is empty on purpose:
|
|
1930
|
-
* it satisfies the check without adding an instruction the model would follow,
|
|
1931
|
-
* so the model still sees exactly what the host sent. The CN gateway asks for
|
|
1932
|
-
* neither, so this is the one part of the shape that is region-specific.
|
|
1933
|
-
*/
|
|
2071
|
+
const NEUTRAL_SYSTEM_PROMPT = "You are a helpful assistant.";
|
|
2072
|
+
/** Global requires a leading system turn; Kimi rejects an empty placeholder. */
|
|
1934
2073
|
function withLeadingSystemPrompt(prepared) {
|
|
1935
2074
|
let body;
|
|
1936
2075
|
try {
|
|
@@ -1946,7 +2085,7 @@ function withLeadingSystemPrompt(prepared) {
|
|
|
1946
2085
|
if (typeof first === "object" && first !== null && first["role"] === "system") return prepared;
|
|
1947
2086
|
obj["messages"] = [{
|
|
1948
2087
|
role: "system",
|
|
1949
|
-
content:
|
|
2088
|
+
content: NEUTRAL_SYSTEM_PROMPT
|
|
1950
2089
|
}, ...messages];
|
|
1951
2090
|
return JSON.stringify(obj);
|
|
1952
2091
|
}
|
|
@@ -2001,7 +2140,7 @@ function contentText(content) {
|
|
|
2001
2140
|
* quoted the client name would fail the next request; that copy is renamed. A
|
|
2002
2141
|
* neutral system message stays first so a gateway that insists on one still sees
|
|
2003
2142
|
* it. Returns undefined when there is nothing to move or rename, which is also
|
|
2004
|
-
* what keeps
|
|
2143
|
+
* what keeps the neutral placeholder from folding into the user turn again.
|
|
2005
2144
|
*/
|
|
2006
2145
|
function foldSystemIntoUser(prepared) {
|
|
2007
2146
|
let body;
|
|
@@ -2017,12 +2156,14 @@ function foldSystemIntoUser(prepared) {
|
|
|
2017
2156
|
const prompts = [];
|
|
2018
2157
|
const rest = [];
|
|
2019
2158
|
let renamed = false;
|
|
2159
|
+
let hadSystem = false;
|
|
2020
2160
|
for (const value of messages) {
|
|
2021
2161
|
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
2022
2162
|
const message = value;
|
|
2023
2163
|
if (message["role"] === "system" || message["role"] === "developer") {
|
|
2164
|
+
hadSystem = true;
|
|
2024
2165
|
const text = contentText(message["content"]);
|
|
2025
|
-
if (text.trim() !== "") prompts.push(text);
|
|
2166
|
+
if (text.trim() !== "" && text !== NEUTRAL_SYSTEM_PROMPT) prompts.push(text);
|
|
2026
2167
|
continue;
|
|
2027
2168
|
}
|
|
2028
2169
|
if (message["role"] === "assistant" && "content" in message) {
|
|
@@ -2041,7 +2182,10 @@ function foldSystemIntoUser(prepared) {
|
|
|
2041
2182
|
}
|
|
2042
2183
|
if (prompts.length === 0 && !renamed) return void 0;
|
|
2043
2184
|
if (prompts.length === 0) {
|
|
2044
|
-
obj["messages"] =
|
|
2185
|
+
obj["messages"] = hadSystem ? [{
|
|
2186
|
+
role: "system",
|
|
2187
|
+
content: NEUTRAL_SYSTEM_PROMPT
|
|
2188
|
+
}, ...rest] : rest;
|
|
2045
2189
|
return JSON.stringify(obj);
|
|
2046
2190
|
}
|
|
2047
2191
|
const instructions = prompts.join("\n\n");
|
|
@@ -2063,7 +2207,7 @@ function foldSystemIntoUser(prepared) {
|
|
|
2063
2207
|
}
|
|
2064
2208
|
obj["messages"] = [{
|
|
2065
2209
|
role: "system",
|
|
2066
|
-
content:
|
|
2210
|
+
content: NEUTRAL_SYSTEM_PROMPT
|
|
2067
2211
|
}, ...rest];
|
|
2068
2212
|
return JSON.stringify(obj);
|
|
2069
2213
|
}
|
|
@@ -2834,17 +2978,86 @@ function openEncryptedField(field, key) {
|
|
|
2834
2978
|
function cleanIconPath(raw) {
|
|
2835
2979
|
return raw.replace(/^"/u, "").replace(/",-?\d+$/u, "").replace(/,-?\d+$/u, "").trim();
|
|
2836
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
|
+
}
|
|
2837
2985
|
/**
|
|
2838
|
-
*
|
|
2986
|
+
* Keep only candidates on fixed local volumes.
|
|
2839
2987
|
*
|
|
2840
|
-
*
|
|
2841
|
-
*
|
|
2842
|
-
*
|
|
2843
|
-
* user's NTLM response. Only absolute drive paths are considered, and every
|
|
2844
|
-
* 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.
|
|
2845
2991
|
*/
|
|
2846
|
-
function
|
|
2847
|
-
|
|
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;
|
|
2848
3061
|
}
|
|
2849
3062
|
function windowsRegistryAppPaths() {
|
|
2850
3063
|
if (process.platform !== "win32") return [];
|
|
@@ -2857,58 +3070,31 @@ function windowsRegistryAppPaths() {
|
|
|
2857
3070
|
registryScannedAtMs = Date.now();
|
|
2858
3071
|
return registryAppPaths;
|
|
2859
3072
|
}
|
|
2860
|
-
/**
|
|
2861
|
-
* The Windows directory, whichever of the two variables holds it.
|
|
2862
|
-
*
|
|
2863
|
-
* Both are read here rather than only in `scanInterpreter`, because the module
|
|
2864
|
-
* path and the interpreter have to come from the same place: pinning the
|
|
2865
|
-
* absolute path from `windir` while the 5.1 module directory was skipped for a
|
|
2866
|
-
* missing `SystemRoot` left `Get-AuthenticodeSignature` unable to load for every
|
|
2867
|
-
* candidate, which is the failure this pair exists to avoid.
|
|
2868
|
-
*/
|
|
3073
|
+
/** Resolve the OS directory without trusting inherited Windows environment variables. */
|
|
2869
3074
|
function systemRootOf(env) {
|
|
3075
|
+
if (process.platform === "win32") try {
|
|
3076
|
+
return realpathSync.native("\\\\?\\GLOBALROOT\\SystemRoot");
|
|
3077
|
+
} catch {
|
|
3078
|
+
return;
|
|
3079
|
+
}
|
|
2870
3080
|
const value = env["SystemRoot"]?.trim() || env["windir"]?.trim();
|
|
2871
3081
|
return value === void 0 || value === "" ? void 0 : value;
|
|
2872
3082
|
}
|
|
2873
|
-
/**
|
|
2874
|
-
* The environment the signature scan runs in.
|
|
2875
|
-
*
|
|
2876
|
-
* `powershell` is Windows PowerShell 5.1, and it resolves
|
|
2877
|
-
* `Microsoft.PowerShell.Security` by walking `PSModulePath` in order. Any machine
|
|
2878
|
-
* with a Store-installed PowerShell 7 carries that build's Modules directory
|
|
2879
|
-
* ahead of the system one, because the Store install prepends it to the variable
|
|
2880
|
-
* the desktop host inherited. 5.1 then binds the 7 build's copy of the module
|
|
2881
|
-
* first and the import dies on a type-data conflict, so
|
|
2882
|
-
* `Get-AuthenticodeSignature` throws for every candidate. The scan's own catch
|
|
2883
|
-
* swallows that, the policy function is handed an empty status, and the at-rest
|
|
2884
|
-
* key reads as "no WorkBuddy executable found" on a machine holding two signed
|
|
2885
|
-
* installs. Putting the 5.1 directory first makes the right copy win.
|
|
2886
|
-
*
|
|
2887
|
-
* The directory is derived from `SystemRoot` rather than written out, and the
|
|
2888
|
-
* rest of the ambient path is left alone so a user's own modules still resolve.
|
|
2889
|
-
* Applying it twice is a no-op, so the answer stays one directory long however
|
|
2890
|
-
* often it is built.
|
|
2891
|
-
*/
|
|
3083
|
+
/** Do not pass user-controlled CLR, module, or executable search paths to PowerShell. */
|
|
2892
3084
|
function signatureScanEnv(env = process.env) {
|
|
2893
3085
|
const systemRoot = systemRootOf(env);
|
|
2894
|
-
|
|
2895
|
-
const modules = systemRoot === void 0 ? void 0 : join(systemRoot, "system32", "WindowsPowerShell", "v1.0", "Modules");
|
|
2896
|
-
if (modules === void 0) return { ...env };
|
|
2897
|
-
if (ambient === modules || ambient?.startsWith(`${modules};`) === true) return { ...env };
|
|
3086
|
+
if (systemRoot === void 0) return {};
|
|
2898
3087
|
return {
|
|
2899
|
-
|
|
2900
|
-
|
|
3088
|
+
SystemRoot: systemRoot,
|
|
3089
|
+
windir: systemRoot,
|
|
3090
|
+
PATH: join(systemRoot, "System32"),
|
|
3091
|
+
PSModulePath: join(systemRoot, "system32", "WindowsPowerShell", "v1.0", "Modules")
|
|
2901
3092
|
};
|
|
2902
3093
|
}
|
|
2903
3094
|
/**
|
|
2904
3095
|
* The interpreter to run the scan with, by absolute path.
|
|
2905
3096
|
*
|
|
2906
|
-
*
|
|
2907
|
-
* scan exists at all: a user-level directory is on the default `PATH`
|
|
2908
|
-
* (`%LOCALAPPDATA%\Microsoft\WindowsApps`), so a bare `powershell` would let
|
|
2909
|
-
* whatever sits there be spawned inside a process holding every WorkBuddy token.
|
|
2910
|
-
* Neither variable set answers `undefined`, and the caller treats that as "no
|
|
2911
|
-
* scan" rather than guessing a path.
|
|
3097
|
+
* The OS directory comes from the Windows object manager, not an inherited path.
|
|
2912
3098
|
*/
|
|
2913
3099
|
function scanInterpreter(env) {
|
|
2914
3100
|
const systemRoot = systemRootOf(env);
|
|
@@ -2920,10 +3106,8 @@ function scanInterpreter(env) {
|
|
|
2920
3106
|
*
|
|
2921
3107
|
* The scan reads `DisplayName`, `DisplayIcon` and `InstallLocation` out of the
|
|
2922
3108
|
* user's own uninstall keys, which means any process running as the user can add
|
|
2923
|
-
* one. It only enumerates here:
|
|
2924
|
-
* and signature-checked in Node
|
|
2925
|
-
* signature read in PowerShell would touch a planted UNC path first and leak an
|
|
2926
|
-
* 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.
|
|
2927
3111
|
*
|
|
2928
3112
|
* PowerShell does the part only it can do: enumerate the keys and clean the
|
|
2929
3113
|
* resource index and quotes off `DisplayIcon`. The decision is
|
|
@@ -2934,6 +3118,7 @@ function scanInterpreter(env) {
|
|
|
2934
3118
|
function readRegistryAppPaths() {
|
|
2935
3119
|
const script = [
|
|
2936
3120
|
"$ErrorActionPreference='SilentlyContinue'",
|
|
3121
|
+
"$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules')",
|
|
2937
3122
|
"try { [Console]::OutputEncoding=[System.Text.Encoding]::UTF8 } catch {}",
|
|
2938
3123
|
"function Clean([string]$v) {",
|
|
2939
3124
|
" $v = $v.Trim()",
|
|
@@ -2974,7 +3159,8 @@ function readRegistryAppPaths() {
|
|
|
2974
3159
|
timeout: 2e4,
|
|
2975
3160
|
windowsHide: true,
|
|
2976
3161
|
maxBuffer: 8388608,
|
|
2977
|
-
env: signatureScanEnv()
|
|
3162
|
+
env: signatureScanEnv(),
|
|
3163
|
+
cwd: dirname(dirname(dirname(interpreter)))
|
|
2978
3164
|
});
|
|
2979
3165
|
} catch {
|
|
2980
3166
|
return [];
|
|
@@ -2995,43 +3181,17 @@ function readRegistryAppPaths() {
|
|
|
2995
3181
|
}
|
|
2996
3182
|
return out;
|
|
2997
3183
|
}
|
|
2998
|
-
/**
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
* Exported so the policy can be tested without a registry to plant a key in: the
|
|
3002
|
-
* PowerShell half is not unit-testable, and this half is where the decision
|
|
3003
|
-
* actually lives.
|
|
3004
|
-
*
|
|
3005
|
-
* `Valid` means the chain resolved to a trusted root. A user process cannot
|
|
3006
|
-
* forge the vendor's signature, but it can trust a certificate of its own in the
|
|
3007
|
-
* current user's root store without elevation, so this check raises the bar
|
|
3008
|
-
* rather than proving the file is the vendor's. It still rejects an unsigned
|
|
3009
|
-
* planted executable, and every cached registry path is checked again before it
|
|
3010
|
-
* is run.
|
|
3011
|
-
*
|
|
3012
|
-
* The publisher is deliberately not pinned. The plugin is a third-party build and
|
|
3013
|
-
* the vendor can change its signing certificate; a pinned name would turn that
|
|
3014
|
-
* into a silent loss of the at-rest key on every machine at once, which is a
|
|
3015
|
-
* worse failure than the one being prevented.
|
|
3016
|
-
*
|
|
3017
|
-
* An unknown status is refused, not assumed: `HashMismatch`, `NotSigned` and a
|
|
3018
|
-
* signature PowerShell could not read at all all mean the file is not the
|
|
3019
|
-
* vendor's, and the caller answers "no key" rather than running something.
|
|
3020
|
-
*/
|
|
3021
|
-
function signatureAccepts(status, signer) {
|
|
3022
|
-
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() ?? "");
|
|
3023
3187
|
}
|
|
3024
3188
|
/** Why the last signature scan could not produce an answer, if it could not. */
|
|
3025
3189
|
let signatureScanFailure = "";
|
|
3026
3190
|
/**
|
|
3027
3191
|
* The candidates whose Authenticode signature is valid.
|
|
3028
3192
|
*
|
|
3029
|
-
*
|
|
3030
|
-
*
|
|
3031
|
-
* as the user can write `%LOCALAPPDATA%\\Programs\\WorkBuddy\\WorkBuddy.exe`; when
|
|
3032
|
-
* the host runs elevated, spawning that file would hand it the plugin's whole
|
|
3033
|
-
* environment and every WorkBuddy token. Every path is checked here, and the
|
|
3034
|
-
* 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.
|
|
3035
3195
|
*/
|
|
3036
3196
|
async function signedExecutables(candidates) {
|
|
3037
3197
|
if (process.platform !== "win32" || candidates.length === 0) return candidates;
|
|
@@ -3042,20 +3202,32 @@ async function signedExecutables(candidates) {
|
|
|
3042
3202
|
return [];
|
|
3043
3203
|
}
|
|
3044
3204
|
const script = [
|
|
3045
|
-
"$ErrorActionPreference='
|
|
3205
|
+
"$ErrorActionPreference='Stop'",
|
|
3206
|
+
"$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules')",
|
|
3046
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'",
|
|
3047
3214
|
`$paths = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${Buffer.from(JSON.stringify(candidates), "utf8").toString("base64")}')) | ConvertFrom-Json`,
|
|
3048
3215
|
"$out = foreach ($p in @($paths)) {",
|
|
3049
3216
|
" if ([string]::IsNullOrWhiteSpace([string]$p)) { continue }",
|
|
3050
3217
|
" $s = $null",
|
|
3051
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
|
+
" }",
|
|
3052
3224
|
" [pscustomobject]@{",
|
|
3053
3225
|
" path = [string]$p",
|
|
3054
3226
|
" status = if ($s -ne $null) { [string]$s.Status } else { \"\" }",
|
|
3055
|
-
"
|
|
3227
|
+
" publicKeyHash = $keyHash",
|
|
3056
3228
|
" }",
|
|
3057
3229
|
"}",
|
|
3058
|
-
"ConvertTo-Json -InputObject @($out) -Compress"
|
|
3230
|
+
"ConvertTo-Json -InputObject @{ elevated = $false; entries = @($out) } -Compress -Depth 3"
|
|
3059
3231
|
].join("\n");
|
|
3060
3232
|
let stdout;
|
|
3061
3233
|
try {
|
|
@@ -3072,7 +3244,8 @@ async function signedExecutables(candidates) {
|
|
|
3072
3244
|
timeout: 2e4,
|
|
3073
3245
|
windowsHide: true,
|
|
3074
3246
|
maxBuffer: 8388608,
|
|
3075
|
-
env: signatureScanEnv()
|
|
3247
|
+
env: signatureScanEnv(),
|
|
3248
|
+
cwd: dirname(dirname(dirname(interpreter)))
|
|
3076
3249
|
}, (error, output) => {
|
|
3077
3250
|
if (error !== null) reject(error);
|
|
3078
3251
|
else resolve(output);
|
|
@@ -3089,25 +3262,35 @@ async function signedExecutables(candidates) {
|
|
|
3089
3262
|
signatureScanFailure = "the signature check returned no readable answer";
|
|
3090
3263
|
return [];
|
|
3091
3264
|
}
|
|
3092
|
-
|
|
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"] : [];
|
|
3093
3275
|
const accepted = [];
|
|
3094
3276
|
for (const entry of entries) {
|
|
3095
3277
|
if (entry === null || typeof entry !== "object") continue;
|
|
3096
3278
|
const record = entry;
|
|
3097
3279
|
const file = record["path"];
|
|
3098
3280
|
const status = record["status"];
|
|
3099
|
-
const
|
|
3281
|
+
const publicKeyHash = record["publicKeyHash"];
|
|
3100
3282
|
if (typeof file !== "string" || file === "") continue;
|
|
3101
|
-
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;
|
|
3102
3284
|
accepted.push(file);
|
|
3103
3285
|
}
|
|
3104
3286
|
return accepted;
|
|
3105
3287
|
}
|
|
3106
3288
|
function statExecutables(candidates) {
|
|
3289
|
+
const localCandidates = process.platform === "win32" ? fixedWindowsPaths(candidates) : candidates;
|
|
3107
3290
|
const files = [];
|
|
3108
|
-
for (const candidate of
|
|
3291
|
+
for (const candidate of localCandidates) {
|
|
3109
3292
|
if (candidate === "") continue;
|
|
3110
|
-
if (process.platform === "win32" &&
|
|
3293
|
+
if (process.platform === "win32" && windowsPathHasReparsePoint(candidate)) continue;
|
|
3111
3294
|
try {
|
|
3112
3295
|
if (statSync(candidate, { throwIfNoEntry: false })?.isFile() === true) files.push(candidate);
|
|
3113
3296
|
} catch {}
|
|
@@ -3115,6 +3298,16 @@ function statExecutables(candidates) {
|
|
|
3115
3298
|
return files;
|
|
3116
3299
|
}
|
|
3117
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
|
+
}
|
|
3118
3311
|
const override = env[WORKBUDDY_APP_EXECUTABLE_ENV]?.trim();
|
|
3119
3312
|
const known = override === void 0 ? [] : [override];
|
|
3120
3313
|
if (process.platform === "win32") {
|
|
@@ -3140,12 +3333,54 @@ async function executableCandidates(env = process.env) {
|
|
|
3140
3333
|
return signedExecutables(statExecutables(windowsRegistryAppPaths()));
|
|
3141
3334
|
}
|
|
3142
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";
|
|
3143
3380
|
return new Promise((resolve, reject) => {
|
|
3144
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))}"], {
|
|
3145
|
-
env
|
|
3146
|
-
|
|
3147
|
-
ELECTRON_RUN_AS_NODE: "1"
|
|
3148
|
-
},
|
|
3382
|
+
env,
|
|
3383
|
+
cwd: process.platform === "win32" ? join(root, "System32") : root,
|
|
3149
3384
|
timeout: KEY_FETCH_TIMEOUT_MS,
|
|
3150
3385
|
windowsHide: true,
|
|
3151
3386
|
maxBuffer: 1048576
|
|
@@ -3199,7 +3434,7 @@ function ensureAtRestKeys() {
|
|
|
3199
3434
|
const candidates = await executableCandidates();
|
|
3200
3435
|
if (candidates.length === 0) {
|
|
3201
3436
|
lastKeyFailureAtMs = Date.now();
|
|
3202
|
-
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";
|
|
3203
3438
|
return;
|
|
3204
3439
|
}
|
|
3205
3440
|
let anySuccess = false;
|
|
@@ -3236,6 +3471,402 @@ async function encryptedFieldOpener() {
|
|
|
3236
3471
|
};
|
|
3237
3472
|
}
|
|
3238
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
|
|
3239
3870
|
//#region src/accounts.ts
|
|
3240
3871
|
/**
|
|
3241
3872
|
* Account pool: discovers every WorkBuddy credential snapshot the desktop app
|
|
@@ -3391,6 +4022,7 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
|
3391
4022
|
const accessToken = decryptableString(auth["accessToken"], decrypt);
|
|
3392
4023
|
if (accessToken === "") return void 0;
|
|
3393
4024
|
const refreshExpiresAtMs = typeof auth["refreshExpiresAt"] === "number" ? expiryToMs(auth["refreshExpiresAt"]) : void 0;
|
|
4025
|
+
const refreshField = encryptedField(auth["refreshToken"]);
|
|
3394
4026
|
const refreshToken = decryptableString(auth["refreshToken"], decrypt);
|
|
3395
4027
|
const refreshExpired = refreshExpiresAtMs !== void 0 && refreshExpiresAtMs > 0 && refreshExpiresAtMs < Date.now();
|
|
3396
4028
|
const lastRefreshAtMs = typeof auth["lastRefreshTime"] === "number" ? expiryToMs(auth["lastRefreshTime"]) : void 0;
|
|
@@ -3398,6 +4030,7 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
|
3398
4030
|
return {
|
|
3399
4031
|
accessToken,
|
|
3400
4032
|
refreshToken: refreshExpired ? "" : refreshToken,
|
|
4033
|
+
...!refreshExpired && refreshField !== void 0 && refreshToken === "" ? { refreshTokenUnavailable: true } : {},
|
|
3401
4034
|
expiresAtMs: typeof auth["expiresAt"] === "number" ? expiryToMs(auth["expiresAt"]) : 0,
|
|
3402
4035
|
...refreshExpiresAtMs === void 0 || refreshExpired ? {} : { refreshExpiresAtMs },
|
|
3403
4036
|
...lastRefreshAtMs === void 0 ? {} : { lastRefreshAtMs },
|
|
@@ -3415,12 +4048,28 @@ function parseWorkBuddyAuth(text, sourcePath, decrypt) {
|
|
|
3415
4048
|
* that cannot be opened is an empty string so the caller skips the file
|
|
3416
4049
|
* instead of treating a sealed token as "not signed in".
|
|
3417
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
|
+
}
|
|
3418
4063
|
function decryptableString(value, decrypt) {
|
|
3419
|
-
|
|
3420
|
-
if (
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
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 : "";
|
|
3424
4073
|
}
|
|
3425
4074
|
/**
|
|
3426
4075
|
* Whether `path` is the desktop app's live sign-in (as opposed to a backup
|
|
@@ -3484,7 +4133,12 @@ function credentialRank(credential, ownDir) {
|
|
|
3484
4133
|
}
|
|
3485
4134
|
/** True when `candidate` should replace `incumbent` for the same account. */
|
|
3486
4135
|
function isFresher(candidate, incumbent, ownDir) {
|
|
3487
|
-
|
|
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;
|
|
3488
4142
|
}
|
|
3489
4143
|
/**
|
|
3490
4144
|
* Queue order for the account list: the live sign-in first, then the copy the
|
|
@@ -3515,44 +4169,14 @@ function tokenDigest(accessToken) {
|
|
|
3515
4169
|
* data directory then kept a stale tombstone set; the size is in here so a rewrite
|
|
3516
4170
|
* that lands in the same reported millisecond still reads as a different file.
|
|
3517
4171
|
*/
|
|
4172
|
+
const MISSING_FILE_STAMP = "missing";
|
|
3518
4173
|
async function signInFileStamp(file) {
|
|
3519
4174
|
try {
|
|
3520
4175
|
const entry = await stat(file);
|
|
3521
4176
|
return `${entry.mtimeMs}:${entry.size}`;
|
|
3522
|
-
} catch {
|
|
3523
|
-
return "";
|
|
3524
|
-
}
|
|
3525
|
-
}
|
|
3526
|
-
/**
|
|
3527
|
-
* Run `work` while holding a lock file, or without it when the lock stays taken.
|
|
3528
|
-
*
|
|
3529
|
-
* The tombstone document is the one file two pools over the same data directory
|
|
3530
|
-
* both write, and a read-union-write is only as good as its serialisation. The
|
|
3531
|
-
* budget is short on purpose: a panel call is answered within seconds, and the
|
|
3532
|
-
* work is a few kilobytes of JSON. A lock older than that is a process that died
|
|
3533
|
-
* holding it, so it is dropped and retried.
|
|
3534
|
-
*/
|
|
3535
|
-
async function withFileLock(lock, work) {
|
|
3536
|
-
let held = false;
|
|
3537
|
-
for (let attempt = 0; attempt < 25 && !held; attempt += 1) try {
|
|
3538
|
-
await writeFile(lock, "", {
|
|
3539
|
-
flag: "wx",
|
|
3540
|
-
mode: 384
|
|
3541
|
-
});
|
|
3542
|
-
held = true;
|
|
3543
|
-
break;
|
|
3544
4177
|
} catch (error) {
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
await unlink(lock).catch(() => {});
|
|
3548
|
-
continue;
|
|
3549
|
-
}
|
|
3550
|
-
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
3551
|
-
}
|
|
3552
|
-
try {
|
|
3553
|
-
await work();
|
|
3554
|
-
} finally {
|
|
3555
|
-
if (held) await unlink(lock).catch(() => {});
|
|
4178
|
+
const code = error.code;
|
|
4179
|
+
return code === "ENOENT" || code === "ENOTDIR" ? MISSING_FILE_STAMP : void 0;
|
|
3556
4180
|
}
|
|
3557
4181
|
}
|
|
3558
4182
|
/**
|
|
@@ -3669,12 +4293,16 @@ async function authFilesIn(dir) {
|
|
|
3669
4293
|
let entries;
|
|
3670
4294
|
try {
|
|
3671
4295
|
entries = await readdir(dir);
|
|
3672
|
-
} catch {
|
|
3673
|
-
|
|
4296
|
+
} catch (error) {
|
|
4297
|
+
const code = error.code;
|
|
4298
|
+
return { unavailable: code !== "ENOENT" && code !== "ENOTDIR" };
|
|
3674
4299
|
}
|
|
3675
4300
|
const files = entries.filter((name) => name.endsWith(".info"));
|
|
3676
4301
|
files.sort((a, b) => a < b ? 1 : a > b ? -1 : 0);
|
|
3677
|
-
return
|
|
4302
|
+
return {
|
|
4303
|
+
files: files.map((name) => join(dir, name)),
|
|
4304
|
+
unavailable: false
|
|
4305
|
+
};
|
|
3678
4306
|
}
|
|
3679
4307
|
/** True when the document's access token is a `$wbEncrypted` envelope. */
|
|
3680
4308
|
function sealedAccessToken(text) {
|
|
@@ -3686,23 +4314,53 @@ function sealedAccessToken(text) {
|
|
|
3686
4314
|
}
|
|
3687
4315
|
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
|
|
3688
4316
|
const document = parsed;
|
|
3689
|
-
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
|
+
});
|
|
3690
4339
|
}
|
|
3691
4340
|
async function readCredential(path) {
|
|
3692
4341
|
let text;
|
|
3693
4342
|
try {
|
|
3694
4343
|
text = await readFile(path, "utf8");
|
|
3695
|
-
} catch {
|
|
3696
|
-
|
|
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" };
|
|
3697
4347
|
}
|
|
3698
|
-
const decrypt = text.includes("\"$wbEncrypted\"") ? await encryptedFieldOpener() : void 0;
|
|
4348
|
+
const decrypt = text.includes("\"$wbEncrypted\"") || text.includes("\\\"$wbEncrypted\\\"") ? await encryptedFieldOpener() : void 0;
|
|
3699
4349
|
const credential = parseWorkBuddyAuth(text, path, decrypt);
|
|
3700
4350
|
if (credential !== void 0) return {
|
|
3701
4351
|
kind: "credential",
|
|
3702
4352
|
credential
|
|
3703
4353
|
};
|
|
3704
|
-
if (sealedAccessToken(text)) return {
|
|
3705
|
-
|
|
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
|
+
}
|
|
3706
4364
|
}
|
|
3707
4365
|
/** Refresh a credential this long before its expiry, so a request never rides one that dies mid-flight. */
|
|
3708
4366
|
const REFRESH_MARGIN_MS = 3e5;
|
|
@@ -3846,27 +4504,56 @@ function ownSignInOf(credential) {
|
|
|
3846
4504
|
* account rewrites its own file instead of leaving a second copy behind, and
|
|
3847
4505
|
* two accounts never collide on a name.
|
|
3848
4506
|
*/
|
|
3849
|
-
async function writeOwnSignIn(directory, signIn) {
|
|
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) {
|
|
3850
4526
|
const stable = signIn.uin === "" ? signIn.uid : signIn.uin;
|
|
3851
4527
|
const suffix = stable === "" ? randomUUID() : stable.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 32);
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
3859
|
-
|
|
3860
|
-
|
|
3861
|
-
|
|
3862
|
-
|
|
3863
|
-
|
|
3864
|
-
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
4528
|
+
return join(directory, `${OWN_SIGN_IN_PREFIX}${suffix === "" ? randomUUID() : suffix}.info`);
|
|
4529
|
+
}
|
|
4530
|
+
async function writeOwnSignInDocument(file, signIn, signal) {
|
|
4531
|
+
signal?.throwIfAborted();
|
|
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
|
+
}
|
|
3870
4557
|
}
|
|
3871
4558
|
/**
|
|
3872
4559
|
* Rewrite one of the plugin's own sign-in files with a renewed token.
|
|
@@ -3876,22 +4563,47 @@ async function writeOwnSignIn(directory, signIn) {
|
|
|
3876
4563
|
* auth values a refresh replaces are written. Atomic for the same reason as the
|
|
3877
4564
|
* archive: a truncated `.info` is an account the scan cannot open.
|
|
3878
4565
|
*/
|
|
3879
|
-
async function renewOwnSignInFile(file, credential) {
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
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
|
+
});
|
|
3895
4607
|
}
|
|
3896
4608
|
/**
|
|
3897
4609
|
* Soonest future one-off expiry. Missing or past sorts last. None left -> list head.
|
|
@@ -3921,7 +4633,7 @@ function candidateAuthDirs(env = process.env) {
|
|
|
3921
4633
|
const dirs = [];
|
|
3922
4634
|
const override = nonEmptyEnv(env[WORKBUDDY_AUTH_FILE_ENV]);
|
|
3923
4635
|
if (override !== void 0) dirs.push(override.toLowerCase().endsWith(".info") ? resolve(override, "..") : override);
|
|
3924
|
-
dirs.push(...defaultDesktopAuthDirs());
|
|
4636
|
+
dirs.push(...defaultDesktopAuthDirs(process.platform, homedir(), env));
|
|
3925
4637
|
return dirs;
|
|
3926
4638
|
}
|
|
3927
4639
|
/**
|
|
@@ -3986,6 +4698,21 @@ async function readArchivedCredentials(file) {
|
|
|
3986
4698
|
}
|
|
3987
4699
|
return stored;
|
|
3988
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
|
+
}
|
|
3989
4716
|
/**
|
|
3990
4717
|
* Write the archive, replacing the previous file only once the new one is whole.
|
|
3991
4718
|
*
|
|
@@ -3993,8 +4720,10 @@ async function readArchivedCredentials(file) {
|
|
|
3993
4720
|
* leave a truncated file behind if it is interrupted: temp file, then rename.
|
|
3994
4721
|
* Only the archived credential is stored, not the raw sign-in document.
|
|
3995
4722
|
*/
|
|
3996
|
-
async function writeArchivedCredentials(file, entries) {
|
|
4723
|
+
async function writeArchivedCredentials(file, entries, signal) {
|
|
4724
|
+
signal?.throwIfAborted();
|
|
3997
4725
|
await mkdir(dirname(file), { recursive: true });
|
|
4726
|
+
signal?.throwIfAborted();
|
|
3998
4727
|
const body = JSON.stringify({
|
|
3999
4728
|
version: 1,
|
|
4000
4729
|
entries: [...entries].map(([id, credential]) => ({
|
|
@@ -4018,7 +4747,8 @@ async function writeArchivedCredentials(file, entries) {
|
|
|
4018
4747
|
encoding: "utf8",
|
|
4019
4748
|
mode: 384
|
|
4020
4749
|
});
|
|
4021
|
-
|
|
4750
|
+
signal?.throwIfAborted();
|
|
4751
|
+
await replaceFile(temporary, file);
|
|
4022
4752
|
} catch (error) {
|
|
4023
4753
|
await unlink(temporary).catch(() => {});
|
|
4024
4754
|
throw error;
|
|
@@ -4097,6 +4827,9 @@ var WorkBuddyAccountPool = class {
|
|
|
4097
4827
|
deletedSignInsStamp;
|
|
4098
4828
|
/** The directories the in-flight scan is reading, so a repoint supersedes it. */
|
|
4099
4829
|
scanDirs = [];
|
|
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
|
*
|
|
@@ -4168,7 +4907,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4168
4907
|
let emptied = false;
|
|
4169
4908
|
if (options.authDirs !== void 0 && options.authDirs.length > 0) {
|
|
4170
4909
|
if (!sameDirs(this.authDirs, options.authDirs)) {
|
|
4171
|
-
this.
|
|
4910
|
+
this.clear();
|
|
4172
4911
|
emptied = true;
|
|
4173
4912
|
}
|
|
4174
4913
|
this.authDirs = options.authDirs;
|
|
@@ -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),
|
|
@@ -4317,28 +5087,33 @@ var WorkBuddyAccountPool = class {
|
|
|
4317
5087
|
* client's directory until the client overwrites it, so a tombstone that
|
|
4318
5088
|
* expired would bring that copy straight back, refresh token included.
|
|
4319
5089
|
*/
|
|
4320
|
-
async loadDeletedSignIns() {
|
|
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;
|
|
5094
|
+
if (signal?.aborted) return this.deletedSignIns ?? /* @__PURE__ */ new Map();
|
|
4323
5095
|
if (this.deletedSignIns !== void 0 && this.deletedSignInsStamp === stamp) return this.deletedSignIns;
|
|
4324
5096
|
if (file === void 0) {
|
|
4325
|
-
this.deletedSignInsStamp =
|
|
5097
|
+
this.deletedSignInsStamp = MISSING_FILE_STAMP;
|
|
4326
5098
|
this.deletedSignIns = /* @__PURE__ */ new Map();
|
|
4327
5099
|
return this.deletedSignIns;
|
|
4328
5100
|
}
|
|
4329
5101
|
try {
|
|
4330
5102
|
const tombstones = await readDeletedSignInsFile(file);
|
|
5103
|
+
if (signal?.aborted) return this.deletedSignIns ?? /* @__PURE__ */ new Map();
|
|
4331
5104
|
this.deletedSignInsStamp = stamp;
|
|
4332
5105
|
this.deletedSignIns = tombstones;
|
|
4333
5106
|
return tombstones;
|
|
4334
5107
|
} catch (error) {
|
|
4335
|
-
if (
|
|
4336
|
-
|
|
5108
|
+
if (signal?.aborted) return this.deletedSignIns ?? /* @__PURE__ */ new Map();
|
|
5109
|
+
const code = error.code;
|
|
5110
|
+
if (code === "ENOENT" || code === "ENOTDIR") {
|
|
5111
|
+
this.deletedSignInsStamp = MISSING_FILE_STAMP;
|
|
4337
5112
|
this.deletedSignIns = /* @__PURE__ */ new Map();
|
|
4338
5113
|
return this.deletedSignIns;
|
|
4339
5114
|
}
|
|
4340
5115
|
this.logger?.warn?.(`${LOG_PREFIX}: could not read the deleted sign-ins: ${String(error)}`);
|
|
4341
|
-
return this.deletedSignIns
|
|
5116
|
+
return this.deletedSignIns;
|
|
4342
5117
|
}
|
|
4343
5118
|
}
|
|
4344
5119
|
/**
|
|
@@ -4353,33 +5128,53 @@ var WorkBuddyAccountPool = class {
|
|
|
4353
5128
|
* Answers false when the file could not be written, so a delete can refuse to
|
|
4354
5129
|
* report success on a state it could not record.
|
|
4355
5130
|
*/
|
|
4356
|
-
async writeDeletedSignIns(removed = []) {
|
|
5131
|
+
async writeDeletedSignIns(removed = [], signal) {
|
|
4357
5132
|
const tombstones = this.deletedSignIns;
|
|
4358
5133
|
const file = this.deletedSignInsFile();
|
|
4359
|
-
if (tombstones === void 0
|
|
5134
|
+
if (tombstones === void 0) return false;
|
|
5135
|
+
if (file === void 0) return true;
|
|
4360
5136
|
let written = false;
|
|
4361
|
-
|
|
4362
|
-
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
|
|
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
|
+
}
|
|
4383
5178
|
return written;
|
|
4384
5179
|
}
|
|
4385
5180
|
deletedSignInsFile() {
|
|
@@ -4427,10 +5222,10 @@ var WorkBuddyAccountPool = class {
|
|
|
4427
5222
|
* refreshing on its own schedule is how both end up with a spent refresh
|
|
4428
5223
|
* token. An account the client is signed into is skipped for the same reason.
|
|
4429
5224
|
*/
|
|
4430
|
-
async adoptOrphanedSignIns(found, tornDown) {
|
|
5225
|
+
async adoptOrphanedSignIns(found, tornDown, sealedLiveIds, unknownLiveDirs, signal) {
|
|
4431
5226
|
const directory = ownSignInDir(this.dataPath?.() ?? "");
|
|
4432
5227
|
if (directory === "") return [];
|
|
4433
|
-
const liveIds =
|
|
5228
|
+
const liveIds = new Set(sealedLiveIds);
|
|
4434
5229
|
const ownedIds = /* @__PURE__ */ new Set();
|
|
4435
5230
|
for (const credential of found) {
|
|
4436
5231
|
const id = workbuddyAccountId(credential);
|
|
@@ -4439,18 +5234,20 @@ var WorkBuddyAccountPool = class {
|
|
|
4439
5234
|
}
|
|
4440
5235
|
const adopted = [];
|
|
4441
5236
|
for (const credential of found) {
|
|
5237
|
+
if (signal.aborted) break;
|
|
4442
5238
|
if (isLiveAuthFile(credential.sourcePath)) continue;
|
|
4443
5239
|
if (ownSignInPath(credential.sourcePath, directory)) continue;
|
|
4444
5240
|
const id = workbuddyAccountId(credential);
|
|
4445
|
-
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;
|
|
4446
5242
|
if ((credential.uin ?? credential.uid ?? credential.nickname ?? "") === "") continue;
|
|
4447
5243
|
let file;
|
|
4448
5244
|
try {
|
|
4449
5245
|
file = await writeOwnSignIn(directory, {
|
|
4450
5246
|
...ownSignInOf(credential),
|
|
4451
5247
|
lastRefreshAtMs: credential.lastRefreshAtMs ?? 0
|
|
4452
|
-
});
|
|
5248
|
+
}, signal);
|
|
4453
5249
|
} catch (error) {
|
|
5250
|
+
if (signal.aborted) break;
|
|
4454
5251
|
this.logger?.warn?.(`${LOG_PREFIX}: could not take over ${accountLogTag(accountLabel(credential))}: ${String(error)}`);
|
|
4455
5252
|
continue;
|
|
4456
5253
|
}
|
|
@@ -4469,22 +5266,48 @@ var WorkBuddyAccountPool = class {
|
|
|
4469
5266
|
* request already in flight. Anything that did not come from the plugin's own
|
|
4470
5267
|
* directory is left alone - the desktop app owns its files.
|
|
4471
5268
|
*/
|
|
4472
|
-
async renewOwnSignIn(credential) {
|
|
4473
|
-
|
|
4474
|
-
|
|
4475
|
-
|
|
4476
|
-
|
|
4477
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not write the renewed token back for ${accountLogTag(credential.nickname ?? credential.uid)}: ${String(error)}`);
|
|
4478
|
-
}
|
|
4479
|
-
return;
|
|
4480
|
-
}
|
|
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;
|
|
4481
5274
|
const directory = ownSignInDir(this.dataPath?.() ?? "");
|
|
4482
|
-
if (directory === "") return;
|
|
4483
|
-
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
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;
|
|
4488
5311
|
}
|
|
4489
5312
|
/**
|
|
4490
5313
|
* Drop one account from the credential archive.
|
|
@@ -4497,27 +5320,43 @@ var WorkBuddyAccountPool = class {
|
|
|
4497
5320
|
const file = this.archiveFile();
|
|
4498
5321
|
if (file === void 0) return;
|
|
4499
5322
|
const run = this.archiveQueue.then(async () => {
|
|
4500
|
-
|
|
4501
|
-
|
|
4502
|
-
|
|
5323
|
+
await withFileLock(`${file}.lock`, async () => {
|
|
5324
|
+
const stored = await readArchivedCredentials(file);
|
|
5325
|
+
if (!stored.delete(id)) return;
|
|
5326
|
+
await writeArchivedCredentials(file, stored);
|
|
5327
|
+
});
|
|
4503
5328
|
});
|
|
4504
5329
|
this.archiveQueue = run.catch(() => {});
|
|
4505
5330
|
try {
|
|
4506
5331
|
await run;
|
|
4507
5332
|
} catch (error) {
|
|
4508
|
-
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)}`);
|
|
4509
5334
|
}
|
|
4510
5335
|
}
|
|
4511
5336
|
/** Drop every account, e.g. when the source is switched off. A later `scan()` rebuilds from disk. */
|
|
4512
5337
|
clear() {
|
|
5338
|
+
this.scanAbort.abort();
|
|
5339
|
+
this.scanAbort = new AbortController();
|
|
5340
|
+
this.scanInflight = void 0;
|
|
5341
|
+
this.scanDirs = [];
|
|
4513
5342
|
this.accounts = [];
|
|
4514
|
-
this.
|
|
4515
|
-
|
|
4516
|
-
|
|
5343
|
+
this.appHeldFiles = /* @__PURE__ */ new Map();
|
|
5344
|
+
this.unknownLiveSignIn = false;
|
|
5345
|
+
this.unknownLiveFiles = /* @__PURE__ */ new Set();
|
|
5346
|
+
this.refreshBlockedIds = /* @__PURE__ */ new Set();
|
|
5347
|
+
}
|
|
5348
|
+
/** Read after any scan already running, so a manual request gets a fresh snapshot. */
|
|
5349
|
+
async rescan() {
|
|
5350
|
+
const signal = this.scanAbort.signal;
|
|
5351
|
+
await this.scanInflight?.catch(() => {});
|
|
5352
|
+
if (signal.aborted) return this.accounts;
|
|
5353
|
+
return this.scan();
|
|
5354
|
+
}
|
|
5355
|
+
/** Scan the auth directories and merge newly discovered accounts. */
|
|
4517
5356
|
async scan() {
|
|
4518
5357
|
const dirs = this.scanDirsFor(this.authDirs);
|
|
4519
5358
|
if (this.scanInflight !== void 0 && sameDirs(this.scanDirs, dirs)) return this.scanInflight;
|
|
4520
|
-
const inflight = this.scanOnce(dirs).finally(() => {
|
|
5359
|
+
const inflight = this.scanOnce(dirs, this.scanAbort.signal).finally(() => {
|
|
4521
5360
|
if (this.scanInflight === inflight) {
|
|
4522
5361
|
this.scanInflight = void 0;
|
|
4523
5362
|
this.scanDirs = [];
|
|
@@ -4548,27 +5387,31 @@ var WorkBuddyAccountPool = class {
|
|
|
4548
5387
|
*
|
|
4549
5388
|
* Best effort by design: a failed write costs the archive, never the scan.
|
|
4550
5389
|
*/
|
|
4551
|
-
async archiveCredentials(credentials) {
|
|
5390
|
+
async archiveCredentials(credentials, signal) {
|
|
4552
5391
|
const file = this.archiveFile();
|
|
4553
5392
|
if (file === void 0 || credentials.length === 0) return;
|
|
4554
5393
|
const ownDir = ownSignInDir(this.dataPath?.() ?? "");
|
|
4555
5394
|
const run = this.archiveQueue.then(async () => {
|
|
4556
|
-
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
|
|
4565
|
-
|
|
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
|
+
});
|
|
4566
5409
|
});
|
|
4567
5410
|
this.archiveQueue = run.catch(() => {});
|
|
4568
5411
|
try {
|
|
4569
5412
|
await run;
|
|
4570
5413
|
} catch (error) {
|
|
4571
|
-
this.logger?.warn?.(`${LOG_PREFIX}: could not update the credential archive: ${String(error)}`);
|
|
5414
|
+
if (!signal?.aborted) this.logger?.warn?.(`${LOG_PREFIX}: could not update the credential archive: ${String(error)}`);
|
|
4572
5415
|
}
|
|
4573
5416
|
}
|
|
4574
5417
|
/** Credentials the archive kept for a directory this walk can read. */
|
|
@@ -4576,7 +5419,12 @@ var WorkBuddyAccountPool = class {
|
|
|
4576
5419
|
const file = this.archiveFile();
|
|
4577
5420
|
if (file === void 0) return [];
|
|
4578
5421
|
try {
|
|
4579
|
-
|
|
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)));
|
|
4580
5428
|
} catch (error) {
|
|
4581
5429
|
this.logger?.warn?.(`${LOG_PREFIX}: could not read the credential archive: ${String(error)}`);
|
|
4582
5430
|
return [];
|
|
@@ -4590,21 +5438,45 @@ var WorkBuddyAccountPool = class {
|
|
|
4590
5438
|
const directory = this.dataPath?.();
|
|
4591
5439
|
return directory === void 0 || directory === "" ? void 0 : join(directory, ARCHIVE_FILENAME);
|
|
4592
5440
|
}
|
|
4593
|
-
async scanOnce(dirs) {
|
|
5441
|
+
async scanOnce(dirs, signal = this.scanAbort.signal) {
|
|
5442
|
+
const rosterRevision = this.rosterRevision;
|
|
4594
5443
|
const found = [];
|
|
4595
5444
|
const readableDirs = /* @__PURE__ */ new Set();
|
|
4596
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();
|
|
4597
5450
|
for (const dir of dirs) {
|
|
4598
|
-
|
|
4599
|
-
|
|
5451
|
+
if (signal.aborted) return this.accounts;
|
|
5452
|
+
const read = await authFilesIn(dir);
|
|
5453
|
+
if (signal.aborted) return this.accounts;
|
|
5454
|
+
if (read.files === void 0) {
|
|
5455
|
+
if (read.unavailable) unavailableDirs.add(resolve(dir));
|
|
5456
|
+
continue;
|
|
5457
|
+
}
|
|
4600
5458
|
readableDirs.add(resolve(dir));
|
|
4601
|
-
for (const file of files) {
|
|
4602
|
-
const
|
|
4603
|
-
if (
|
|
4604
|
-
|
|
5459
|
+
for (const file of read.files) {
|
|
5460
|
+
const credentialRead = await readCredential(file);
|
|
5461
|
+
if (signal.aborted) return this.accounts;
|
|
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
|
+
}
|
|
4605
5472
|
}
|
|
4606
5473
|
}
|
|
4607
|
-
const tombstones = await this.loadDeletedSignIns();
|
|
5474
|
+
const tombstones = await this.loadDeletedSignIns(signal);
|
|
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
|
+
}
|
|
4608
5480
|
const tornDown = /* @__PURE__ */ new Set();
|
|
4609
5481
|
const releasedIds = [];
|
|
4610
5482
|
const held = [];
|
|
@@ -4626,9 +5498,20 @@ var WorkBuddyAccountPool = class {
|
|
|
4626
5498
|
found.length = 0;
|
|
4627
5499
|
found.push(...held);
|
|
4628
5500
|
for (const id of tombstones.keys()) tornDown.add(id);
|
|
4629
|
-
if (releasedIds.length > 0) await this.writeDeletedSignIns(releasedIds);
|
|
4630
|
-
|
|
4631
|
-
|
|
5501
|
+
if (releasedIds.length > 0) await this.writeDeletedSignIns(releasedIds, signal);
|
|
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
|
+
}
|
|
5511
|
+
await this.archiveCredentials(found, signal);
|
|
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;
|
|
4632
5515
|
const signInTokens = /* @__PURE__ */ new Map();
|
|
4633
5516
|
for (const credential of found) {
|
|
4634
5517
|
const id = workbuddyAccountId(credential);
|
|
@@ -4637,13 +5520,31 @@ var WorkBuddyAccountPool = class {
|
|
|
4637
5520
|
else held.push(credential);
|
|
4638
5521
|
}
|
|
4639
5522
|
const liveIds = new Set(found.map((credential) => workbuddyAccountId(credential)));
|
|
4640
|
-
const appHeld =
|
|
4641
|
-
for (const
|
|
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);
|
|
5535
|
+
const archived = await this.archivedCredentials(readableDirs);
|
|
5536
|
+
if (signal.aborted || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
5537
|
+
for (const credential of archived) {
|
|
4642
5538
|
const id = workbuddyAccountId(credential);
|
|
4643
5539
|
if (tornDown.has(id)) continue;
|
|
5540
|
+
if (!this.isOwnSignInPath(credential.sourcePath) && (sealedLiveIds.has(id) || sealedDirs.has(this.homeOf(credential)))) continue;
|
|
4644
5541
|
if (found.some((entry) => workbuddyAccountId(entry) === id && entry.accessToken === credential.accessToken)) continue;
|
|
4645
5542
|
found.push(credential);
|
|
4646
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
|
+
}
|
|
4647
5548
|
const byId = /* @__PURE__ */ new Map();
|
|
4648
5549
|
for (const account of this.accounts) byId.set(account.id, account);
|
|
4649
5550
|
for (const credential of found) {
|
|
@@ -4700,7 +5601,10 @@ var WorkBuddyAccountPool = class {
|
|
|
4700
5601
|
this.forgetAccount(id);
|
|
4701
5602
|
}
|
|
4702
5603
|
}
|
|
4703
|
-
this.
|
|
5604
|
+
this.appHeldFiles = appHeld;
|
|
5605
|
+
this.unknownLiveSignIn = unknownLiveSignIn;
|
|
5606
|
+
this.unknownLiveFiles = unknownLiveFiles;
|
|
5607
|
+
this.refreshBlockedIds = refreshBlockedIds;
|
|
4704
5608
|
const ordered = [...byId.values()];
|
|
4705
5609
|
ordered.sort((a, b) => compareQueueOrder(a.credential, b.credential, ownSignInDir(this.dataPath?.() ?? "")));
|
|
4706
5610
|
for (const account of ordered) {
|
|
@@ -4711,7 +5615,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4711
5615
|
else account.archived = true;
|
|
4712
5616
|
}
|
|
4713
5617
|
disambiguateLabels(ordered);
|
|
4714
|
-
if (!sameDirs(this.scanDirsFor(this.authDirs), dirs)) return this.accounts;
|
|
5618
|
+
if (!sameDirs(this.scanDirsFor(this.authDirs), dirs) || rosterRevision !== this.rosterRevision) return this.accounts;
|
|
4715
5619
|
this.accounts = ordered;
|
|
4716
5620
|
this.signInTokens = signInTokens;
|
|
4717
5621
|
this.lastScanAtMs = Date.now();
|
|
@@ -4811,27 +5715,32 @@ var WorkBuddyAccountPool = class {
|
|
|
4811
5715
|
* fresh desktop login is the usual way out of an exhausted pool.
|
|
4812
5716
|
*/
|
|
4813
5717
|
async acquire(modelId, region, conversationKey, excludeIds) {
|
|
5718
|
+
const signal = this.scanAbort.signal;
|
|
4814
5719
|
const eligibleNow = () => {
|
|
4815
5720
|
const list = this.available(Date.now(), modelId, region);
|
|
4816
5721
|
return excludeIds === void 0 ? list : list.filter((item) => !excludeIds.has(item.id));
|
|
4817
5722
|
};
|
|
4818
5723
|
if (this.accounts.length === 0) await this.scan();
|
|
5724
|
+
if (signal.aborted) return void 0;
|
|
4819
5725
|
let pool = eligibleNow();
|
|
4820
5726
|
if (pool.length === 0) {
|
|
4821
5727
|
await this.scan();
|
|
5728
|
+
if (signal.aborted) return void 0;
|
|
4822
5729
|
pool = eligibleNow();
|
|
4823
5730
|
}
|
|
4824
5731
|
if (pool.length === 0) return void 0;
|
|
4825
5732
|
const preferredId = this.preferredIds.get(region);
|
|
4826
|
-
const
|
|
4827
|
-
|
|
4828
|
-
|
|
4829
|
-
|
|
4830
|
-
|
|
4831
|
-
|
|
4832
|
-
|
|
4833
|
-
|
|
4834
|
-
|
|
5733
|
+
const remaining = new Set(pool.map((account) => account.id));
|
|
5734
|
+
while (remaining.size > 0) {
|
|
5735
|
+
const account = pool.find((item) => item.id === preferredId) ?? this.pick(pool, conversationKey);
|
|
5736
|
+
if (account === void 0) return void 0;
|
|
5737
|
+
remaining.delete(account.id);
|
|
5738
|
+
await this.ensureFresh(account);
|
|
5739
|
+
if (signal.aborted) return void 0;
|
|
5740
|
+
const eligible = eligibleNow();
|
|
5741
|
+
if (eligible.includes(account)) return account;
|
|
5742
|
+
pool = eligible.filter((item) => remaining.has(item.id));
|
|
5743
|
+
}
|
|
4835
5744
|
}
|
|
4836
5745
|
pick(pool, conversationKey) {
|
|
4837
5746
|
if (this.distribution === "expiry") return this.pickByExpiry(pool);
|
|
@@ -4968,6 +5877,7 @@ var WorkBuddyAccountPool = class {
|
|
|
4968
5877
|
*/
|
|
4969
5878
|
async ensureFresh(account, forced = false) {
|
|
4970
5879
|
if (this.client === void 0) return "fresh";
|
|
5880
|
+
if (this.refreshBlockedIds.has(account.id)) return "fresh";
|
|
4971
5881
|
const credential = account.credential;
|
|
4972
5882
|
const issuedAt = credential.lastRefreshAtMs ?? 0;
|
|
4973
5883
|
const stale = this.isOwnSignInPath(credential.sourcePath) && issuedAt > 0 && Date.now() - issuedAt >= REFRESH_AFTER_MS;
|
|
@@ -4994,8 +5904,22 @@ var WorkBuddyAccountPool = class {
|
|
|
4994
5904
|
...outcome.domain === void 0 || outcome.domain === "" ? {} : { domain: outcome.domain },
|
|
4995
5905
|
lastRefreshAtMs: Date.now()
|
|
4996
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
|
+
}
|
|
4997
5922
|
await this.archiveCredentials([account.credential]);
|
|
4998
|
-
await this.renewOwnSignIn(account.credential);
|
|
4999
5923
|
this.noRefreshWarned.delete(account.id);
|
|
5000
5924
|
const sessionHold = this.heldIds.get(account.id);
|
|
5001
5925
|
if (sessionHold !== void 0 && sessionHold.reason === "session") {
|
|
@@ -5103,7 +6027,8 @@ var WorkBuddyAccountPool = class {
|
|
|
5103
6027
|
return {
|
|
5104
6028
|
count: this.accounts.length,
|
|
5105
6029
|
cooling: this.accounts.filter((account) => account.cooldownUntilMs > now).length,
|
|
5106
|
-
lastScanAtMs: this.lastScanAtMs
|
|
6030
|
+
lastScanAtMs: this.lastScanAtMs,
|
|
6031
|
+
scanning: this.scanInflight !== void 0
|
|
5107
6032
|
};
|
|
5108
6033
|
}
|
|
5109
6034
|
};
|
|
@@ -5173,13 +6098,6 @@ const FALLBACK_WORKBUDDY_MODELS = [
|
|
|
5173
6098
|
contextWindow: 2e5,
|
|
5174
6099
|
maxOutputTokens: 128e3,
|
|
5175
6100
|
supportsImages: true
|
|
5176
|
-
},
|
|
5177
|
-
{
|
|
5178
|
-
id: "hy4-preview",
|
|
5179
|
-
name: "Hy4-Preview",
|
|
5180
|
-
contextWindow: 1e6,
|
|
5181
|
-
maxOutputTokens: 128e3,
|
|
5182
|
-
supportsImages: true
|
|
5183
6101
|
}
|
|
5184
6102
|
];
|
|
5185
6103
|
/** Live catalog with a static fallback behind it. */
|
|
@@ -5310,12 +6228,17 @@ const MAX_LINE_CHARS$1 = 67108864;
|
|
|
5310
6228
|
*/
|
|
5311
6229
|
const MAX_DATA_CHARS = 4194304;
|
|
5312
6230
|
var SseDecoder = class {
|
|
6231
|
+
onFrame;
|
|
5313
6232
|
buffer = "";
|
|
5314
6233
|
event;
|
|
5315
6234
|
id;
|
|
5316
6235
|
retry;
|
|
5317
6236
|
data = [];
|
|
5318
6237
|
dataChars = 0;
|
|
6238
|
+
rawFrame = "";
|
|
6239
|
+
constructor(onFrame) {
|
|
6240
|
+
this.onFrame = onFrame;
|
|
6241
|
+
}
|
|
5319
6242
|
push(chunk) {
|
|
5320
6243
|
this.buffer += chunk;
|
|
5321
6244
|
const events = [];
|
|
@@ -5324,9 +6247,14 @@ var SseDecoder = class {
|
|
|
5324
6247
|
if (match === null || match.index === void 0) break;
|
|
5325
6248
|
if (match[0] === "\r" && match.index + 1 === this.buffer.length) break;
|
|
5326
6249
|
const line = this.buffer.slice(0, match.index);
|
|
6250
|
+
if (this.onFrame !== void 0) this.appendRaw(this.buffer.slice(0, match.index + match[0].length));
|
|
5327
6251
|
this.buffer = this.buffer.slice(match.index + match[0].length);
|
|
5328
6252
|
const emitted = this.consumeLine(line);
|
|
5329
6253
|
if (emitted !== void 0) events.push(emitted);
|
|
6254
|
+
if (line === "" && this.onFrame !== void 0) {
|
|
6255
|
+
this.onFrame(this.rawFrame, emitted);
|
|
6256
|
+
this.rawFrame = "";
|
|
6257
|
+
}
|
|
5330
6258
|
}
|
|
5331
6259
|
if (this.buffer.length > MAX_LINE_CHARS$1) {
|
|
5332
6260
|
this.buffer = "";
|
|
@@ -5343,6 +6271,7 @@ var SseDecoder = class {
|
|
|
5343
6271
|
finish() {
|
|
5344
6272
|
const events = [];
|
|
5345
6273
|
if (this.buffer !== "") {
|
|
6274
|
+
if (this.onFrame !== void 0) this.appendRaw(this.buffer);
|
|
5346
6275
|
const tail = this.buffer.endsWith("\r") ? this.buffer.slice(0, -1) : this.buffer;
|
|
5347
6276
|
const emitted = this.consumeLine(tail);
|
|
5348
6277
|
this.buffer = "";
|
|
@@ -5350,8 +6279,19 @@ var SseDecoder = class {
|
|
|
5350
6279
|
}
|
|
5351
6280
|
const final = this.dispatch();
|
|
5352
6281
|
if (final !== void 0) events.push(final);
|
|
6282
|
+
if (this.rawFrame !== "" && this.onFrame !== void 0) {
|
|
6283
|
+
this.onFrame(this.rawFrame, events[0]);
|
|
6284
|
+
this.rawFrame = "";
|
|
6285
|
+
}
|
|
5353
6286
|
return events;
|
|
5354
6287
|
}
|
|
6288
|
+
appendRaw(value) {
|
|
6289
|
+
if (this.rawFrame.length + value.length > MAX_DATA_CHARS) {
|
|
6290
|
+
this.rawFrame = "";
|
|
6291
|
+
throw new Error("sse event exceeded 4194304 characters of framing without a separator");
|
|
6292
|
+
}
|
|
6293
|
+
this.rawFrame += value;
|
|
6294
|
+
}
|
|
5355
6295
|
consumeLine(line) {
|
|
5356
6296
|
if (line === "") return this.dispatch();
|
|
5357
6297
|
if (line.startsWith(":")) return void 0;
|
|
@@ -5464,15 +6404,55 @@ function decodeTraeEvent(event) {
|
|
|
5464
6404
|
* Loopback guards, the request body bound and the server shell live in
|
|
5465
6405
|
* `./loopback` — one copy, shared with the Trae and Qoder gateways.
|
|
5466
6406
|
*/
|
|
5467
|
-
|
|
5468
|
-
function carriesFinishReason(data) {
|
|
6407
|
+
function completionState(data) {
|
|
5469
6408
|
try {
|
|
5470
6409
|
const parsed = JSON.parse(data);
|
|
5471
|
-
|
|
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] : []);
|
|
6412
|
+
return {
|
|
6413
|
+
finished: choices.some((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason !== ""),
|
|
6414
|
+
toolCalls: toolCallIndices.length > 0,
|
|
6415
|
+
toolCallIndices
|
|
6416
|
+
};
|
|
5472
6417
|
} catch {
|
|
5473
|
-
return
|
|
6418
|
+
return {
|
|
6419
|
+
finished: false,
|
|
6420
|
+
toolCalls: false,
|
|
6421
|
+
toolCallIndices: []
|
|
6422
|
+
};
|
|
6423
|
+
}
|
|
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;
|
|
5474
6441
|
}
|
|
5475
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
|
+
}
|
|
5476
6456
|
/** HTTP status each upstream failure class surfaces as. */
|
|
5477
6457
|
const KIND_STATUS = {
|
|
5478
6458
|
hard_credit: 402,
|
|
@@ -5507,6 +6487,17 @@ const MODEL_TIER_HOLD_MS = 864e5;
|
|
|
5507
6487
|
*/
|
|
5508
6488
|
const MAX_TRANSPORT_ATTEMPTS = 2;
|
|
5509
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
|
+
/**
|
|
5510
6501
|
* The business code an account-level 200 envelope carries.
|
|
5511
6502
|
*
|
|
5512
6503
|
* `classifyUpstreamError` only reads codes on the statuses the upstream uses
|
|
@@ -5797,11 +6788,19 @@ function createWorkBuddyShim(options) {
|
|
|
5797
6788
|
const prepared = client.prepareChatBody(raw);
|
|
5798
6789
|
const conversationKey = conversationKeyOf(raw);
|
|
5799
6790
|
let modelId;
|
|
6791
|
+
let bodyIsJson = true;
|
|
5800
6792
|
try {
|
|
5801
6793
|
const parsed = JSON.parse(raw);
|
|
5802
|
-
|
|
6794
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
6795
|
+
const model = parsed.model;
|
|
6796
|
+
modelId = typeof model === "string" && model !== "" ? model : void 0;
|
|
6797
|
+
}
|
|
5803
6798
|
} catch {
|
|
5804
|
-
|
|
6799
|
+
bodyIsJson = false;
|
|
6800
|
+
}
|
|
6801
|
+
if (!bodyIsJson) {
|
|
6802
|
+
writeOpenAIError(res, 400, "invalid_request_error", "body is not valid JSON");
|
|
6803
|
+
return;
|
|
5805
6804
|
}
|
|
5806
6805
|
if (modelId === void 0) {
|
|
5807
6806
|
writeOpenAIError(res, 400, "invalid_request_error", "model is required");
|
|
@@ -5810,19 +6809,21 @@ function createWorkBuddyShim(options) {
|
|
|
5810
6809
|
let tried = 0;
|
|
5811
6810
|
const skipped = /* @__PURE__ */ new Set();
|
|
5812
6811
|
let last;
|
|
5813
|
-
let
|
|
6812
|
+
let accountSkipped = false;
|
|
5814
6813
|
let transportAttempts = 0;
|
|
6814
|
+
let emptyStreams = 0;
|
|
5815
6815
|
let effortFallback;
|
|
5816
6816
|
let effortFallbackBuilt = false;
|
|
5817
6817
|
const maxAttempts = Math.max(8, pool.list(region).length + 2);
|
|
6818
|
+
const maxEmptyStreams = emptyStreamAttemptsFor(pool.list(region).length);
|
|
5818
6819
|
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
|
5819
6820
|
if (controller.signal.aborted) return;
|
|
5820
6821
|
const account = await pool.acquire(modelId, region, conversationKey, skipped);
|
|
5821
6822
|
if (account === void 0) {
|
|
5822
|
-
if (
|
|
6823
|
+
if (accountSkipped && last !== void 0) {
|
|
5823
6824
|
const model = ` for model ${modelId}`;
|
|
5824
|
-
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}`;
|
|
5825
|
-
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";
|
|
5826
6827
|
if (last.kind === "soft_rate") {
|
|
5827
6828
|
const live = pool.list(region).filter((candidate) => !pool.isDisabled(candidate.id));
|
|
5828
6829
|
const wait = unavailableAnswer(pool, live, Date.now(), modelId).retryAfterSeconds;
|
|
@@ -5862,7 +6863,7 @@ function createWorkBuddyShim(options) {
|
|
|
5862
6863
|
status: 502,
|
|
5863
6864
|
message: `could not refresh the sign-in: ${failure.message}`
|
|
5864
6865
|
};
|
|
5865
|
-
|
|
6866
|
+
accountSkipped = true;
|
|
5866
6867
|
continue;
|
|
5867
6868
|
}
|
|
5868
6869
|
}
|
|
@@ -5885,10 +6886,22 @@ function createWorkBuddyShim(options) {
|
|
|
5885
6886
|
const reader = relayStreamOf(result.response).getReader();
|
|
5886
6887
|
let sawDone = false;
|
|
5887
6888
|
let sawFinish = false;
|
|
6889
|
+
let sawToolCalls = false;
|
|
6890
|
+
const sawToolCallChoices = /* @__PURE__ */ new Set();
|
|
5888
6891
|
let envelopeFailure;
|
|
5889
6892
|
let headFailure;
|
|
6893
|
+
let headIsEmptyStream = false;
|
|
5890
6894
|
const decoder = new TextDecoder();
|
|
5891
|
-
const
|
|
6895
|
+
const frames = [];
|
|
6896
|
+
const sse = new SseDecoder((raw, event) => frames.push({
|
|
6897
|
+
raw,
|
|
6898
|
+
event
|
|
6899
|
+
}));
|
|
6900
|
+
const finishChunk = () => Buffer.from(`data: ${JSON.stringify({ choices: [{
|
|
6901
|
+
index: 0,
|
|
6902
|
+
delta: {},
|
|
6903
|
+
finish_reason: openAIFinishReason(void 0, sawToolCalls)
|
|
6904
|
+
}] })}\n\n`);
|
|
5892
6905
|
const startStream = () => {
|
|
5893
6906
|
res.writeHead(200, {
|
|
5894
6907
|
"Content-Type": "text/event-stream",
|
|
@@ -5929,13 +6942,37 @@ function createWorkBuddyShim(options) {
|
|
|
5929
6942
|
function closeWithoutDone() {
|
|
5930
6943
|
if (sawDone || !res.writable) return;
|
|
5931
6944
|
logger?.warn?.("wtq-pool: upstream stream ended without [DONE]");
|
|
5932
|
-
if (!sawFinish) res.write(
|
|
5933
|
-
index: 0,
|
|
5934
|
-
delta: {},
|
|
5935
|
-
finish_reason: "stop"
|
|
5936
|
-
}] })}\n\n`);
|
|
6945
|
+
if (!sawFinish) res.write(finishChunk());
|
|
5937
6946
|
res.end("data: [DONE]\n\n");
|
|
5938
6947
|
}
|
|
6948
|
+
const relayFrames = async (finishTail = false) => {
|
|
6949
|
+
for (const { raw, event } of frames.splice(0)) {
|
|
6950
|
+
let chunk = Buffer.from(finishTail ? raw + "\n\n" : raw);
|
|
6951
|
+
if (event?.data === "[DONE]") {
|
|
6952
|
+
if (!sawFinish) {
|
|
6953
|
+
await writeChunk(res, finishChunk());
|
|
6954
|
+
sawFinish = true;
|
|
6955
|
+
}
|
|
6956
|
+
await writeChunk(res, chunk);
|
|
6957
|
+
sawDone = true;
|
|
6958
|
+
res.end();
|
|
6959
|
+
await reader.cancel().catch(() => {});
|
|
6960
|
+
return true;
|
|
6961
|
+
}
|
|
6962
|
+
if (event !== void 0) {
|
|
6963
|
+
const state = completionState(event.data);
|
|
6964
|
+
sawFinish ||= state.finished;
|
|
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
|
+
}
|
|
6971
|
+
}
|
|
6972
|
+
await writeChunk(res, chunk);
|
|
6973
|
+
}
|
|
6974
|
+
return false;
|
|
6975
|
+
};
|
|
5939
6976
|
await (async () => {
|
|
5940
6977
|
let head = [];
|
|
5941
6978
|
let ended = false;
|
|
@@ -5947,6 +6984,7 @@ function createWorkBuddyShim(options) {
|
|
|
5947
6984
|
await reader.cancel().catch(() => {});
|
|
5948
6985
|
if (peeked.ended && peeked.refusal === EMPTY_STREAM_REFUSAL) {
|
|
5949
6986
|
headFailure = peeked.refusal;
|
|
6987
|
+
headIsEmptyStream = true;
|
|
5950
6988
|
logger?.warn?.(`${LOG_PREFIX}: ${accountLogTag(account.label)} answered 200 with an empty stream; rotating`);
|
|
5951
6989
|
return;
|
|
5952
6990
|
}
|
|
@@ -5962,7 +7000,7 @@ function createWorkBuddyShim(options) {
|
|
|
5962
7000
|
status: 200,
|
|
5963
7001
|
message: peeked.refusal
|
|
5964
7002
|
};
|
|
5965
|
-
|
|
7003
|
+
accountSkipped = true;
|
|
5966
7004
|
envelopeFailure = envelopeKind;
|
|
5967
7005
|
if (envelopeKind === "soft_rate") {
|
|
5968
7006
|
const bodyReset = parseRateLimitReset(peeked.body ?? peeked.refusal);
|
|
@@ -6008,33 +7046,15 @@ function createWorkBuddyShim(options) {
|
|
|
6008
7046
|
} : await reader.read();
|
|
6009
7047
|
if (done || value === void 0) break;
|
|
6010
7048
|
if (!res.writable) return;
|
|
6011
|
-
|
|
6012
|
-
|
|
6013
|
-
const decoded = decoder.decode(value, { stream: true });
|
|
6014
|
-
const events = sse.push(decoded);
|
|
6015
|
-
if (!sawFinish && events.some((event) => carriesFinishReason(event.data))) sawFinish = true;
|
|
6016
|
-
if (events.some((event) => event.data === "[DONE]")) {
|
|
6017
|
-
if (!sawFinish && res.writable) {
|
|
6018
|
-
res.write(`data: ${JSON.stringify({ choices: [{
|
|
6019
|
-
index: 0,
|
|
6020
|
-
delta: {},
|
|
6021
|
-
finish_reason: "stop"
|
|
6022
|
-
}] })}\n\n`);
|
|
6023
|
-
sawFinish = true;
|
|
6024
|
-
}
|
|
6025
|
-
sawDone = true;
|
|
6026
|
-
if (res.writable) res.end();
|
|
6027
|
-
await reader.cancel().catch(() => {});
|
|
6028
|
-
return;
|
|
6029
|
-
}
|
|
6030
|
-
} catch {}
|
|
7049
|
+
sse.push(decoder.decode(value, { stream: true }));
|
|
7050
|
+
if (await relayFrames()) return;
|
|
6031
7051
|
}
|
|
6032
|
-
if (!sawDone)
|
|
7052
|
+
if (!sawDone) {
|
|
6033
7053
|
const rest = decoder.decode();
|
|
6034
|
-
|
|
6035
|
-
|
|
6036
|
-
if (
|
|
6037
|
-
}
|
|
7054
|
+
if (rest !== "") sse.push(rest);
|
|
7055
|
+
sse.finish();
|
|
7056
|
+
if (await relayFrames(true)) return;
|
|
7057
|
+
}
|
|
6038
7058
|
closeWithoutDone();
|
|
6039
7059
|
} catch (error) {
|
|
6040
7060
|
failInBand(error);
|
|
@@ -6050,10 +7070,17 @@ function createWorkBuddyShim(options) {
|
|
|
6050
7070
|
status: 502,
|
|
6051
7071
|
message: headFailure
|
|
6052
7072
|
};
|
|
6053
|
-
|
|
7073
|
+
accountSkipped = true;
|
|
6054
7074
|
skipped.add(account.id);
|
|
6055
|
-
|
|
6056
|
-
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;
|
|
6057
7084
|
continue;
|
|
6058
7085
|
}
|
|
6059
7086
|
if (envelopeFailure === void 0) return;
|
|
@@ -6099,7 +7126,7 @@ function createWorkBuddyShim(options) {
|
|
|
6099
7126
|
status: result.status,
|
|
6100
7127
|
message: result.message
|
|
6101
7128
|
};
|
|
6102
|
-
|
|
7129
|
+
accountSkipped = true;
|
|
6103
7130
|
skipped.add(account.id);
|
|
6104
7131
|
transportAttempts += 1;
|
|
6105
7132
|
if (transportAttempts >= MAX_TRANSPORT_ATTEMPTS) break;
|
|
@@ -6107,7 +7134,7 @@ function createWorkBuddyShim(options) {
|
|
|
6107
7134
|
continue;
|
|
6108
7135
|
}
|
|
6109
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;
|
|
6110
|
-
|
|
7137
|
+
accountSkipped = true;
|
|
6111
7138
|
if (result.kind === "soft_rate") {
|
|
6112
7139
|
const bodyReset = parseRateLimitReset(result.message);
|
|
6113
7140
|
const headerReset = resetFromRetryAfter(result.retryAfter);
|
|
@@ -7090,7 +8117,7 @@ function buildTraeHeaders(credential, identity, options = {}) {
|
|
|
7090
8117
|
"request-traffic-type": "prod",
|
|
7091
8118
|
"Content-Type": "application/json",
|
|
7092
8119
|
"X-Cloudide-Token": credential.accessToken,
|
|
7093
|
-
"x-uid": credential.userId,
|
|
8120
|
+
...credential.userId === "" ? {} : { "x-uid": credential.userId },
|
|
7094
8121
|
"x-request-id": requestId,
|
|
7095
8122
|
"x-trae-request-id": requestId,
|
|
7096
8123
|
"Accept": "text/event-stream"
|
|
@@ -7786,6 +8813,14 @@ var TraeSoloUpstreamClient = class {
|
|
|
7786
8813
|
* this.
|
|
7787
8814
|
*/
|
|
7788
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
|
+
/**
|
|
7789
8824
|
* Words a Trae refusal uses for a sign-in the upstream no longer accepts.
|
|
7790
8825
|
*
|
|
7791
8826
|
* Trae answers a stale login inside the stream, on the same `event: error`
|
|
@@ -7795,6 +8830,12 @@ var TraeSoloUpstreamClient = class {
|
|
|
7795
8830
|
* every request paid one round trip and the healthy sign-ins beside it were
|
|
7796
8831
|
* never tried. The Qoder path in this same plugin classifies the identical
|
|
7797
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.
|
|
7798
8839
|
*/
|
|
7799
8840
|
const TRAE_SIGN_IN_PATTERN = /login expired|not logged in|unauthori[sz]ed|invalid token|token.*(expire|invalid)|\b9095\b/i;
|
|
7800
8841
|
/** Trae's tool calls arrive under either `function_call` or `function`. */
|
|
@@ -8201,9 +9242,9 @@ function bridgeTraeStream(source, model, options = {}) {
|
|
|
8201
9242
|
*/
|
|
8202
9243
|
async function openTraeResponse(response, model, options = {}) {
|
|
8203
9244
|
if (!response.ok) {
|
|
8204
|
-
const detail =
|
|
9245
|
+
const detail = await readErrorBody(response, 1024, void 0, options.refusalReadMs);
|
|
8205
9246
|
return Response.json({ error: {
|
|
8206
|
-
message: detail === "" ? `Trae SOLO returned HTTP ${response.status}` : detail,
|
|
9247
|
+
message: detail === "" ? `Trae SOLO returned HTTP ${response.status}` : redactSecrets(detail),
|
|
8207
9248
|
type: "upstream_error",
|
|
8208
9249
|
code: response.status
|
|
8209
9250
|
} }, { status: response.status });
|
|
@@ -8260,7 +9301,21 @@ async function openTraeResponse(response, model, options = {}) {
|
|
|
8260
9301
|
code: kind === "hard_credit" ? 402 : status
|
|
8261
9302
|
} }, {
|
|
8262
9303
|
status,
|
|
8263
|
-
|
|
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" }
|
|
8264
9319
|
});
|
|
8265
9320
|
}
|
|
8266
9321
|
const relay = bridgeTraeStream(replaySource(buffered, reader, ended), model, options);
|
|
@@ -8372,10 +9427,15 @@ function createTraeGateway(options) {
|
|
|
8372
9427
|
res.on("close", () => watcher.abort());
|
|
8373
9428
|
const raw = (await readRequestBody(req)).toString("utf8");
|
|
8374
9429
|
let model = "";
|
|
9430
|
+
let bodyIsJson = true;
|
|
8375
9431
|
try {
|
|
8376
9432
|
model = JSON.parse(raw)["model"] ?? "";
|
|
8377
9433
|
} catch {
|
|
8378
|
-
|
|
9434
|
+
bodyIsJson = false;
|
|
9435
|
+
}
|
|
9436
|
+
if (!bodyIsJson) {
|
|
9437
|
+
writeOpenAIError(res, 400, "invalid_request_error", "body is not valid JSON");
|
|
9438
|
+
return;
|
|
8379
9439
|
}
|
|
8380
9440
|
if (typeof model !== "string" || model.trim() === "") {
|
|
8381
9441
|
writeOpenAIError(res, 400, "invalid_request_error", "model is required");
|
|
@@ -8477,11 +9537,13 @@ function createTraeGateway(options) {
|
|
|
8477
9537
|
}
|
|
8478
9538
|
if (relayed.status !== 200) {
|
|
8479
9539
|
const detail = await relayed.text().catch(() => "");
|
|
9540
|
+
const failedKind = relayed.headers.get(TRAE_FAILURE_KIND_HEADER);
|
|
8480
9541
|
return {
|
|
8481
9542
|
ok: false,
|
|
8482
9543
|
status: relayed.status,
|
|
8483
9544
|
message: detail,
|
|
8484
|
-
retryAfter: relayed.headers.get("retry-after")
|
|
9545
|
+
retryAfter: relayed.headers.get("retry-after"),
|
|
9546
|
+
...failedKind === null ? {} : { kind: failedKind }
|
|
8485
9547
|
};
|
|
8486
9548
|
}
|
|
8487
9549
|
return {
|
|
@@ -8498,7 +9560,7 @@ function createTraeGateway(options) {
|
|
|
8498
9560
|
const rotates = (status, kind) => {
|
|
8499
9561
|
if (kind === "aborted") return false;
|
|
8500
9562
|
if (status === 0) return true;
|
|
8501
|
-
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;
|
|
8502
9564
|
};
|
|
8503
9565
|
let opened;
|
|
8504
9566
|
for (let index = 0; index < credentials.length; index += 1) {
|
|
@@ -8943,6 +10005,7 @@ const DPAPI_PREFIX = "DPAPI";
|
|
|
8943
10005
|
*/
|
|
8944
10006
|
const DPAPI_SCRIPT = `
|
|
8945
10007
|
$ErrorActionPreference = 'Stop'
|
|
10008
|
+
$env:PSModulePath=[IO.Path]::Combine($env:SystemRoot,'System32\\WindowsPowerShell\\v1.0\\Modules')
|
|
8946
10009
|
Add-Type -TypeDefinition @'
|
|
8947
10010
|
using System;
|
|
8948
10011
|
using System.Runtime.InteropServices;
|
|
@@ -8977,27 +10040,6 @@ var QoderKeyError = class extends Error {
|
|
|
8977
10040
|
this.name = "QoderKeyError";
|
|
8978
10041
|
}
|
|
8979
10042
|
};
|
|
8980
|
-
function powershellPath(env) {
|
|
8981
|
-
const systemRoot = env.SystemRoot ?? env.windir;
|
|
8982
|
-
if (systemRoot === void 0 || systemRoot === "") return void 0;
|
|
8983
|
-
return join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
8984
|
-
}
|
|
8985
|
-
/** Run the interpreter with a whitelisted environment; nothing user-set rides along. */
|
|
8986
|
-
function childEnv(env) {
|
|
8987
|
-
const allowed = [
|
|
8988
|
-
"SystemRoot",
|
|
8989
|
-
"SystemDrive",
|
|
8990
|
-
"windir",
|
|
8991
|
-
"TEMP",
|
|
8992
|
-
"TMP"
|
|
8993
|
-
];
|
|
8994
|
-
const result = {};
|
|
8995
|
-
for (const name of allowed) {
|
|
8996
|
-
const value = env[name];
|
|
8997
|
-
if (typeof value === "string" && value !== "") result[name] = value;
|
|
8998
|
-
}
|
|
8999
|
-
return result;
|
|
9000
|
-
}
|
|
9001
10043
|
/**
|
|
9002
10044
|
* Unwrap the AES key an app's `Local State` keeps under `os_crypt`.
|
|
9003
10045
|
*
|
|
@@ -9028,7 +10070,7 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
|
|
|
9028
10070
|
} catch {}
|
|
9029
10071
|
const cached = oscryptKeyCache.get(localStatePath);
|
|
9030
10072
|
if (cached !== void 0 && cached.mtimeMs === mtimeMs) return Buffer.from(cached.key);
|
|
9031
|
-
const exe =
|
|
10073
|
+
const exe = trustedWindowsPowerShell(env);
|
|
9032
10074
|
if (exe === void 0) throw new QoderKeyError("unavailable", "SystemRoot is not set, cannot locate PowerShell");
|
|
9033
10075
|
const stdout = await new Promise((resolve, reject) => {
|
|
9034
10076
|
const child = spawn(exe, [
|
|
@@ -9037,7 +10079,10 @@ async function unwrapQoderOscryptKey(localStatePath, options = {}) {
|
|
|
9037
10079
|
"-Command",
|
|
9038
10080
|
DPAPI_SCRIPT
|
|
9039
10081
|
], {
|
|
9040
|
-
env:
|
|
10082
|
+
env: trustedWindowsChildEnv(env, {
|
|
10083
|
+
inheritTemp: true,
|
|
10084
|
+
includeSystemDrive: true
|
|
10085
|
+
}),
|
|
9041
10086
|
windowsHide: true,
|
|
9042
10087
|
stdio: [
|
|
9043
10088
|
"pipe",
|
|
@@ -9395,21 +10440,262 @@ function buildCosyAuthHeaders(body, url, credential) {
|
|
|
9395
10440
|
};
|
|
9396
10441
|
}
|
|
9397
10442
|
//#endregion
|
|
9398
|
-
//#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
|
+
}
|
|
9399
10455
|
/**
|
|
9400
|
-
* Qoder
|
|
9401
|
-
*
|
|
9402
|
-
* Fetches the callable roster and opens one chat stream. No disk reads here;
|
|
9403
|
-
* tokens stay in the caller's memory.
|
|
9404
|
-
*
|
|
9405
|
-
* Shapes follow `dsh-connect-qoder` (MIT): the `algo/api/v2/model/list`
|
|
9406
|
-
* envelope groups its models by product surface, and only the `chat` group is
|
|
9407
|
-
* callable. Chat requests normalise `developer` to `system`, because a system
|
|
9408
|
-
* message the gateway does not recognise is answered with a permanent
|
|
9409
|
-
* `403 {"code":"10605"}` on every retry.
|
|
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.
|
|
9410
10458
|
*
|
|
9411
|
-
*
|
|
9412
|
-
*
|
|
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.
|
|
10462
|
+
*/
|
|
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
|
+
}
|
|
10469
|
+
/**
|
|
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.
|
|
9413
10699
|
*
|
|
9414
10700
|
* @module dsh-wtq-pool/qoder-client
|
|
9415
10701
|
*/
|
|
@@ -9510,6 +10796,8 @@ function qoderRawEpochMs(value) {
|
|
|
9510
10796
|
return value < QODER_EPOCH_SECONDS_BOUNDARY_MS ? Math.floor(value * 1e3) : Math.floor(value);
|
|
9511
10797
|
}
|
|
9512
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);
|
|
9513
10801
|
const parsed = Date.parse(value);
|
|
9514
10802
|
return Number.isFinite(parsed) ? parsed : void 0;
|
|
9515
10803
|
}
|
|
@@ -9675,9 +10963,9 @@ function qoderCheckinStateFrom(payload, nowMs = Date.now()) {
|
|
|
9675
10963
|
* When the next round opens, for an account whose current round is not
|
|
9676
10964
|
* claimable right now (already collected, or its window has not started).
|
|
9677
10965
|
*
|
|
9678
|
-
*
|
|
9679
|
-
*
|
|
9680
|
-
*
|
|
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.
|
|
9681
10969
|
*/
|
|
9682
10970
|
function qoderNextOpenAt(payload, nowMs) {
|
|
9683
10971
|
const list = payload?.campaigns;
|
|
@@ -9717,7 +11005,7 @@ function qoderNormalizeClaimResult(payload, campaign) {
|
|
|
9717
11005
|
const amountValue = Number(body?.reward?.amount ?? body?.benefit?.amount ?? (typeof campaign !== "undefined" ? qoderBenefitOf(campaign)?.amount : void 0));
|
|
9718
11006
|
const expiresAt = qoderEpochMs(body?.expiresAt);
|
|
9719
11007
|
const code = Number(body?.code ?? body?.errcode);
|
|
9720
|
-
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) : "";
|
|
9721
11009
|
return {
|
|
9722
11010
|
claimed: granted,
|
|
9723
11011
|
replayed,
|
|
@@ -10139,328 +11427,124 @@ var QoderUpstreamClient = class {
|
|
|
10139
11427
|
* promotional rows and the daily check-in round; the pure selectors above
|
|
10140
11428
|
* split it without a second request.
|
|
10141
11429
|
*/
|
|
10142
|
-
async fetchCampaigns(signal) {
|
|
10143
|
-
const credential = await this.options.credential();
|
|
10144
|
-
const response = await this.fetchImpl(qoderEndpoint(this.openApiBase(), QODER_CAMPAIGNS_PATH), {
|
|
10145
|
-
method: "GET",
|
|
10146
|
-
headers: qoderOpenApiHeaders(credential),
|
|
10147
|
-
redirect: "error",
|
|
10148
|
-
signal: signal ?? AbortSignal.timeout(DIRECTORY_TIMEOUT_MS)
|
|
10149
|
-
});
|
|
10150
|
-
if (!response.ok) throw new Error(`Qoder campaigns failed: HTTP ${response.status} ${await readErrorBody(response, 300, signal)}`);
|
|
10151
|
-
return await response.json();
|
|
10152
|
-
}
|
|
10153
|
-
/**
|
|
10154
|
-
* Claim one campaign's benefit, returning the raw answer. A repeat answers
|
|
10155
|
-
* `replayed: true` rather than failing; `qoderNormalizeClaimResult` narrows it.
|
|
10156
|
-
*/
|
|
10157
|
-
async claimCampaign(campaignId, signal) {
|
|
10158
|
-
if (typeof campaignId !== "string" || campaignId.length === 0) throw new Error("Qoder check-in failed: no campaign id to claim");
|
|
10159
|
-
const credential = await this.options.credential();
|
|
10160
|
-
const response = await this.fetchImpl(qoderEndpoint(this.openApiBase(), qoderClaimCampaignPath(campaignId)), {
|
|
10161
|
-
method: "POST",
|
|
10162
|
-
headers: {
|
|
10163
|
-
...qoderOpenApiHeaders(credential),
|
|
10164
|
-
"Content-Type": "application/json"
|
|
10165
|
-
},
|
|
10166
|
-
body: "{}",
|
|
10167
|
-
redirect: "error",
|
|
10168
|
-
signal: signal ?? AbortSignal.timeout(DIRECTORY_TIMEOUT_MS)
|
|
10169
|
-
});
|
|
10170
|
-
if (!response.ok) {
|
|
10171
|
-
const detail = await readErrorBody(response, 300, signal);
|
|
10172
|
-
throw new Error(`Qoder check-in failed: HTTP ${response.status} ${detail.slice(0, 200)}`);
|
|
10173
|
-
}
|
|
10174
|
-
const text = await response.text();
|
|
10175
|
-
try {
|
|
10176
|
-
return JSON.parse(text);
|
|
10177
|
-
} catch {
|
|
10178
|
-
const contentType = response.headers.get("content-type") ?? "no content-type";
|
|
10179
|
-
throw new Error(`Qoder check-in: response is not valid JSON (${contentType}) — ${text.slice(0, 300)}`);
|
|
10180
|
-
}
|
|
10181
|
-
}
|
|
10182
|
-
/**
|
|
10183
|
-
* Open one chat stream for a model. The caller owns the SSE translation;
|
|
10184
|
-
* a refusal answers as a classified error with the body truncated.
|
|
10185
|
-
*/
|
|
10186
|
-
async chatStream(openAiBody, model, options = {}) {
|
|
10187
|
-
let plain;
|
|
10188
|
-
try {
|
|
10189
|
-
plain = buildQoderChatBody(openAiBody, model, options);
|
|
10190
|
-
} catch (error) {
|
|
10191
|
-
const detail = error instanceof Error ? error.message : "";
|
|
10192
|
-
return {
|
|
10193
|
-
ok: false,
|
|
10194
|
-
status: 400,
|
|
10195
|
-
kind: "client",
|
|
10196
|
-
message: detail === "" ? "invalid JSON request" : detail
|
|
10197
|
-
};
|
|
10198
|
-
}
|
|
10199
|
-
let credential;
|
|
10200
|
-
try {
|
|
10201
|
-
credential = await this.options.credential();
|
|
10202
|
-
} catch (error) {
|
|
10203
|
-
return {
|
|
10204
|
-
ok: false,
|
|
10205
|
-
status: 503,
|
|
10206
|
-
kind: "server",
|
|
10207
|
-
message: `credential read failed: ${String(error instanceof Error ? error.message : error)}`
|
|
10208
|
-
};
|
|
10209
|
-
}
|
|
10210
|
-
const url = qoderEndpoint(this.baseUrl(), QODER_CHAT_PATH);
|
|
10211
|
-
const bodyBytes = encodeBody(plain);
|
|
10212
|
-
const headers = buildCosyAuthHeaders(bodyBytes, url, credential);
|
|
10213
|
-
let response;
|
|
10214
|
-
const deadline = headersDeadline(options.signal, options.timeouts?.headersMs ?? CHAT_HEADERS_TIMEOUT_MS);
|
|
10215
|
-
try {
|
|
10216
|
-
response = await this.fetchImpl(url, {
|
|
10217
|
-
method: "POST",
|
|
10218
|
-
headers: {
|
|
10219
|
-
"Content-Type": "application/json",
|
|
10220
|
-
...headers,
|
|
10221
|
-
...options.extraHeaders
|
|
10222
|
-
},
|
|
10223
|
-
body: bodyBytes,
|
|
10224
|
-
redirect: "error",
|
|
10225
|
-
signal: deadline.signal
|
|
10226
|
-
});
|
|
10227
|
-
} catch (error) {
|
|
10228
|
-
if (options.signal?.aborted === true) return {
|
|
10229
|
-
ok: false,
|
|
10230
|
-
status: 0,
|
|
10231
|
-
kind: "aborted",
|
|
10232
|
-
message: "cancelled by the caller"
|
|
10233
|
-
};
|
|
10234
|
-
return {
|
|
10235
|
-
ok: false,
|
|
10236
|
-
status: 0,
|
|
10237
|
-
kind: "server",
|
|
10238
|
-
message: `transport error: ${String(error)}`
|
|
10239
|
-
};
|
|
10240
|
-
} finally {
|
|
10241
|
-
deadline.arrived();
|
|
10242
|
-
}
|
|
10243
|
-
if (!response.ok) {
|
|
10244
|
-
const text = await readErrorBody(response, 300, options.signal);
|
|
10245
|
-
return {
|
|
10246
|
-
ok: false,
|
|
10247
|
-
status: response.status,
|
|
10248
|
-
kind: classifyQoderUpstreamError(response.status),
|
|
10249
|
-
message: text.slice(0, 300) || `Qoder returned HTTP ${response.status}`,
|
|
10250
|
-
retryAfter: response.headers.get("retry-after")
|
|
10251
|
-
};
|
|
10252
|
-
}
|
|
10253
|
-
return {
|
|
10254
|
-
ok: true,
|
|
10255
|
-
response: response.body === null ? response : new Response(withIdleWatchdog(response.body, options.timeouts?.idleMs, options.signal), {
|
|
10256
|
-
status: response.status,
|
|
10257
|
-
headers: response.headers
|
|
10258
|
-
})
|
|
10259
|
-
};
|
|
10260
|
-
}
|
|
10261
|
-
};
|
|
10262
|
-
//#endregion
|
|
10263
|
-
//#region src/qoder-sse.ts
|
|
10264
|
-
function isPlainObject(value) {
|
|
10265
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10266
|
-
}
|
|
10267
|
-
function tryJsonObject(text) {
|
|
10268
|
-
try {
|
|
10269
|
-
const parsed = JSON.parse(text);
|
|
10270
|
-
return isPlainObject(parsed) ? parsed : void 0;
|
|
10271
|
-
} catch {
|
|
10272
|
-
return;
|
|
10273
|
-
}
|
|
10274
|
-
}
|
|
10275
|
-
/**
|
|
10276
|
-
* Whether a code is the success-range acknowledgement Qoder sends for a
|
|
10277
|
-
* container it accepted. `{"code":0}` and `{"code":200}` are how it acks.
|
|
10278
|
-
*/
|
|
10279
|
-
function isAcknowledgementCode(value) {
|
|
10280
|
-
if (typeof value !== "string" && typeof value !== "number") return false;
|
|
10281
|
-
if (typeof value === "string" && value.length === 0) return false;
|
|
10282
|
-
const code = Number(value);
|
|
10283
|
-
return Number.isFinite(code) && (code === 0 || code >= 200 && code < 300);
|
|
10284
|
-
}
|
|
10285
|
-
/**
|
|
10286
|
-
* The code and message a failure frame really carries, however deeply they are
|
|
10287
|
-
* wrapped. The walk follows `details`/`error`, or a `message` string that is
|
|
10288
|
-
* itself a JSON document, up to 8 levels — bounded so a self-referential
|
|
10289
|
-
* payload cannot spin. When it bottoms out on an object (the queue descriptor),
|
|
10290
|
-
* that object is far more useful than the string that carried it.
|
|
10291
|
-
*/
|
|
10292
|
-
function unwrapFailure(frame) {
|
|
10293
|
-
let code = "";
|
|
10294
|
-
let detail = "";
|
|
10295
|
-
const signals = [];
|
|
10296
|
-
let node = frame;
|
|
10297
|
-
let descended = false;
|
|
10298
|
-
let codeFromPlainKey = false;
|
|
10299
|
-
let codeFromErrorSpelling = false;
|
|
10300
|
-
let arrivedViaContainer = false;
|
|
10301
|
-
for (let depth = 0; depth < 8; depth++) {
|
|
10302
|
-
if (!isPlainObject(node)) break;
|
|
10303
|
-
const errorSpelling = node["errorCode"] ?? node["errcode"];
|
|
10304
|
-
const levelCode = errorSpelling ?? node["code"];
|
|
10305
|
-
const acknowledgement = arrivedViaContainer && codeFromPlainKey && isAcknowledgementCode(levelCode);
|
|
10306
|
-
if (errorSpelling !== void 0 || !codeFromErrorSpelling && !acknowledgement) {
|
|
10307
|
-
if (typeof levelCode === "string" && levelCode.length > 0) {
|
|
10308
|
-
code = levelCode;
|
|
10309
|
-
codeFromPlainKey = errorSpelling === void 0;
|
|
10310
|
-
codeFromErrorSpelling = errorSpelling !== void 0;
|
|
10311
|
-
} else if (typeof levelCode === "number" && Number.isFinite(levelCode)) {
|
|
10312
|
-
code = String(levelCode);
|
|
10313
|
-
codeFromPlainKey = errorSpelling === void 0;
|
|
10314
|
-
codeFromErrorSpelling = errorSpelling !== void 0;
|
|
10315
|
-
}
|
|
10316
|
-
}
|
|
10317
|
-
const message = node["message"] ?? node["errorMessage"];
|
|
10318
|
-
if (typeof message === "string" && message.trim() !== "" && !signals.includes(message)) signals.push(message);
|
|
10319
|
-
if ((detail === "" || tryJsonObject(detail) !== void 0) && typeof message === "string" && message.length > 0) detail = message;
|
|
10320
|
-
const flat = typeof node["error"] === "string" ? node["error"] : typeof node["details"] === "string" ? node["details"] : void 0;
|
|
10321
|
-
if (flat !== void 0 && flat.trim() !== "" && !signals.includes(flat)) signals.push(flat);
|
|
10322
|
-
if (detail === "" && flat !== void 0 && flat.length > 0) detail = flat;
|
|
10323
|
-
const nested = isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0;
|
|
10324
|
-
const next = nested ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
10325
|
-
if (next === void 0) break;
|
|
10326
|
-
node = next;
|
|
10327
|
-
arrivedViaContainer = nested !== void 0;
|
|
10328
|
-
descended = true;
|
|
10329
|
-
}
|
|
10330
|
-
if (descended && detail === "" && isPlainObject(node)) detail = JSON.stringify(node);
|
|
10331
|
-
if (codeFromPlainKey && isAcknowledgementCode(code)) code = "";
|
|
10332
|
-
return {
|
|
10333
|
-
code,
|
|
10334
|
-
detail,
|
|
10335
|
-
signals: signals.join("\n")
|
|
10336
|
-
};
|
|
10337
|
-
}
|
|
10338
|
-
/**
|
|
10339
|
-
* The gateway's retry hint, when the frame carries one.
|
|
10340
|
-
*
|
|
10341
|
-
* A carried `0` is the decoder's "no hint" placeholder, not a real wait. The
|
|
10342
|
-
* hint may sit on the envelope, in a nested container, or inside a message that
|
|
10343
|
-
* is itself a JSON document; the walk reads all three so a queue descriptor is
|
|
10344
|
-
* not lost when the outer sentence is the one worth showing.
|
|
10345
|
-
*/
|
|
10346
|
-
function retryAfterSecondsOf(frame) {
|
|
10347
|
-
const seen = /* @__PURE__ */ new Set();
|
|
10348
|
-
let node = frame;
|
|
10349
|
-
for (let depth = 0; depth < 8; depth++) {
|
|
10350
|
-
if (!isPlainObject(node) || seen.has(node)) break;
|
|
10351
|
-
seen.add(node);
|
|
10352
|
-
const direct = node["retryAfterSeconds"];
|
|
10353
|
-
if (typeof direct === "number" && Number.isFinite(direct) && direct > 0) return direct;
|
|
10354
|
-
const message = node["message"] ?? node["errorMessage"];
|
|
10355
|
-
const next = (isPlainObject(node["details"]) ? node["details"] : isPlainObject(node["error"]) ? node["error"] : void 0) ?? (typeof message === "string" ? tryJsonObject(message) : void 0);
|
|
10356
|
-
if (next === void 0) break;
|
|
10357
|
-
node = next;
|
|
10358
|
-
}
|
|
10359
|
-
return 0;
|
|
10360
|
-
}
|
|
10361
|
-
/**
|
|
10362
|
-
* The inner chunk of one data payload: the envelope's `body` when it is a JSON
|
|
10363
|
-
* string, the object when it is inline, and the envelope itself when it carries
|
|
10364
|
-
* neither. Returns undefined when no layer parses.
|
|
10365
|
-
*/
|
|
10366
|
-
function unwrapQoderFrame(payload) {
|
|
10367
|
-
const envelope = tryJsonObject(payload);
|
|
10368
|
-
if (envelope === void 0) return void 0;
|
|
10369
|
-
const body = envelope["body"];
|
|
10370
|
-
if (typeof body === "string") return tryJsonObject(body);
|
|
10371
|
-
if (isPlainObject(body)) return body;
|
|
10372
|
-
return envelope;
|
|
10373
|
-
}
|
|
10374
|
-
/**
|
|
10375
|
-
* Classify one data payload. A token-accounting frame carries `choices: []`
|
|
10376
|
-
* with a top-level `usage`; it must be forwarded as a chunk, not read as a
|
|
10377
|
-
* failure. Anything with neither output nor a name — a bare `{ success: true }`
|
|
10378
|
-
* keepalive, or a payload whose shape moved — is reported as unknown rather
|
|
10379
|
-
* than guessed at. A frame that carries an empty `choices` and no usage is a
|
|
10380
|
-
* failure frame wearing a chunk's clothes: the upstream reports refusals that
|
|
10381
|
-
* way, and forwarding it as a chunk answered the client with an empty turn.
|
|
10382
|
-
*/
|
|
10383
|
-
function decodeQoderFrame(payload) {
|
|
10384
|
-
const chunk = unwrapQoderFrame(payload);
|
|
10385
|
-
if (chunk === void 0) return {
|
|
10386
|
-
type: "unknown",
|
|
10387
|
-
reason: "unparseable",
|
|
10388
|
-
data: payload
|
|
10389
|
-
};
|
|
10390
|
-
const choices = chunk["choices"];
|
|
10391
|
-
const hasOutput = Array.isArray(choices) && choices.length > 0;
|
|
10392
|
-
const hasUsage = chunk["usage"] !== void 0 && chunk["usage"] !== null;
|
|
10393
|
-
if (hasOutput || hasUsage) return {
|
|
10394
|
-
type: "chunk",
|
|
10395
|
-
chunk
|
|
10396
|
-
};
|
|
10397
|
-
const { code, detail, signals } = unwrapFailure(chunk);
|
|
10398
|
-
if (code === "" && detail === "") return {
|
|
10399
|
-
type: "unknown",
|
|
10400
|
-
reason: "unnamed",
|
|
10401
|
-
data: chunk
|
|
10402
|
-
};
|
|
10403
|
-
return {
|
|
10404
|
-
type: "failure",
|
|
10405
|
-
code,
|
|
10406
|
-
detail,
|
|
10407
|
-
signals,
|
|
10408
|
-
retryAfterSeconds: retryAfterSecondsOf(chunk)
|
|
10409
|
-
};
|
|
10410
|
-
}
|
|
10411
|
-
/**
|
|
10412
|
-
* One unterminated line may not grow without bound; chat deltas are small.
|
|
10413
|
-
* The ceiling is a memory guard on the upstream's answer, which no request-body
|
|
10414
|
-
* limit bounds: a frame this size is a stream gone wrong, not a chat delta.
|
|
10415
|
-
*/
|
|
10416
|
-
const MAX_LINE_CHARS = 67108864;
|
|
10417
|
-
/**
|
|
10418
|
-
* Incremental reader for the Qoder wire form: one JSON payload per `data:`
|
|
10419
|
-
* line. Qoder sends no `event:`/`id:`/`retry` fields, so this stays a plain
|
|
10420
|
-
* line reader instead of duplicating a full SSE event parser.
|
|
10421
|
-
*/
|
|
10422
|
-
var QoderFrameDecoder = class {
|
|
10423
|
-
buffer = "";
|
|
10424
|
-
done = false;
|
|
10425
|
-
/** Whether the wire has supplied its terminal marker, independent of TCP EOF. */
|
|
10426
|
-
get ended() {
|
|
10427
|
-
return this.done;
|
|
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();
|
|
10428
11440
|
}
|
|
10429
|
-
/**
|
|
10430
|
-
|
|
10431
|
-
|
|
10432
|
-
|
|
10433
|
-
|
|
10434
|
-
|
|
10435
|
-
|
|
10436
|
-
|
|
10437
|
-
|
|
10438
|
-
|
|
10439
|
-
|
|
10440
|
-
|
|
10441
|
-
|
|
10442
|
-
|
|
10443
|
-
|
|
10444
|
-
|
|
10445
|
-
|
|
10446
|
-
|
|
10447
|
-
|
|
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)}`);
|
|
10448
11461
|
}
|
|
10449
|
-
|
|
10450
|
-
|
|
10451
|
-
|
|
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)}`);
|
|
10452
11468
|
}
|
|
10453
|
-
return payloads;
|
|
10454
11469
|
}
|
|
10455
|
-
/**
|
|
10456
|
-
|
|
10457
|
-
|
|
10458
|
-
|
|
10459
|
-
|
|
10460
|
-
|
|
10461
|
-
|
|
10462
|
-
|
|
10463
|
-
|
|
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
|
+
};
|
|
10464
11548
|
}
|
|
10465
11549
|
};
|
|
10466
11550
|
//#endregion
|
|
@@ -10571,6 +11655,14 @@ function queueSeconds(frame) {
|
|
|
10571
11655
|
* and a multi-hour Retry-After, and classifying it as a queue would turn it
|
|
10572
11656
|
* into a long sleep instead of a failover.
|
|
10573
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";
|
|
10574
11666
|
function classifyQoderFailure(failure) {
|
|
10575
11667
|
const code = failure.code.trim();
|
|
10576
11668
|
const text = `${code} ${failure.message} ${failure.signals ?? ""}`;
|
|
@@ -10976,7 +12068,7 @@ async function openQoderResponse(response, model, options = {}) {
|
|
|
10976
12068
|
if (!response.ok) {
|
|
10977
12069
|
const detail = await readErrorBody(response, 1024);
|
|
10978
12070
|
return Response.json({ error: {
|
|
10979
|
-
message: detail === "" ? `Qoder returned HTTP ${response.status}` : detail,
|
|
12071
|
+
message: detail === "" ? `Qoder returned HTTP ${response.status}` : redactSecrets(detail),
|
|
10980
12072
|
type: "upstream_error",
|
|
10981
12073
|
code: response.status
|
|
10982
12074
|
} }, { status: response.status });
|
|
@@ -11057,17 +12149,31 @@ async function openQoderResponse(response, model, options = {}) {
|
|
|
11057
12149
|
}
|
|
11058
12150
|
if (failure !== void 0 && !sawOutput) {
|
|
11059
12151
|
await reader.cancel().catch(() => {});
|
|
11060
|
-
const { status, error } = classifyQoderFailure(failure);
|
|
12152
|
+
const { status, kind, error } = classifyQoderFailure(failure);
|
|
11061
12153
|
const retryAfter = error instanceof QoderQueueRejection || error instanceof QoderDailyLimitRejection ? error.retryAfterSeconds : void 0;
|
|
11062
12154
|
const wait = retryAfter === void 0 ? void 0 : retryAfterHeader(retryAfter);
|
|
11063
12155
|
return Response.json({ error: {
|
|
11064
|
-
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),
|
|
11065
12157
|
type: "upstream_error",
|
|
11066
12158
|
code: status,
|
|
11067
12159
|
...retryAfter === void 0 || !(retryAfter > 0) ? {} : { retryAfterSeconds: retryAfter }
|
|
11068
12160
|
} }, {
|
|
11069
12161
|
status,
|
|
11070
|
-
|
|
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" }
|
|
11071
12177
|
});
|
|
11072
12178
|
}
|
|
11073
12179
|
const relay = bridgeQoderStream(replaySource(buffered, {
|
|
@@ -11167,10 +12273,15 @@ function createQoderGateway(options) {
|
|
|
11167
12273
|
res.on("close", () => watcher.abort());
|
|
11168
12274
|
const raw = (await readRequestBody(req)).toString("utf8");
|
|
11169
12275
|
let model = "";
|
|
12276
|
+
let bodyIsJson = true;
|
|
11170
12277
|
try {
|
|
11171
12278
|
model = JSON.parse(raw)["model"] ?? "";
|
|
11172
12279
|
} catch {
|
|
11173
|
-
|
|
12280
|
+
bodyIsJson = false;
|
|
12281
|
+
}
|
|
12282
|
+
if (!bodyIsJson) {
|
|
12283
|
+
writeOpenAIError(res, 400, "invalid_request_error", "body is not valid JSON");
|
|
12284
|
+
return;
|
|
11174
12285
|
}
|
|
11175
12286
|
if (typeof model !== "string" || model.trim() === "") {
|
|
11176
12287
|
writeOpenAIError(res, 400, "invalid_request_error", "model is required");
|
|
@@ -11255,11 +12366,13 @@ function createQoderGateway(options) {
|
|
|
11255
12366
|
}
|
|
11256
12367
|
if (relayed.status !== 200) {
|
|
11257
12368
|
const detail = await relayed.text().catch(() => "");
|
|
12369
|
+
const failedKind = relayed.headers.get(QODER_FAILURE_KIND_HEADER);
|
|
11258
12370
|
return {
|
|
11259
12371
|
ok: false,
|
|
11260
12372
|
status: relayed.status,
|
|
11261
12373
|
message: detail,
|
|
11262
|
-
retryAfter: relayed.headers.get("retry-after")
|
|
12374
|
+
retryAfter: relayed.headers.get("retry-after"),
|
|
12375
|
+
...failedKind === null ? {} : { kind: failedKind }
|
|
11263
12376
|
};
|
|
11264
12377
|
}
|
|
11265
12378
|
return {
|
|
@@ -11276,7 +12389,7 @@ function createQoderGateway(options) {
|
|
|
11276
12389
|
const rotates = (status, kind) => {
|
|
11277
12390
|
if (kind === "aborted") return false;
|
|
11278
12391
|
if (status === 0) return true;
|
|
11279
|
-
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;
|
|
11280
12393
|
};
|
|
11281
12394
|
let opened;
|
|
11282
12395
|
for (let index = 0; index < credentials.length; index += 1) {
|
|
@@ -11914,13 +13027,6 @@ const SERVICE_BOOTSTRAP_BUDGET_MS = 1500;
|
|
|
11914
13027
|
*/
|
|
11915
13028
|
const REFRESH_PASS_BUDGET_MS = 18e3;
|
|
11916
13029
|
/**
|
|
11917
|
-
* How often the token keep-alive walks the pool.
|
|
11918
|
-
*
|
|
11919
|
-
* Half of the lifetime the pool assumes for a token that reports none, so a
|
|
11920
|
-
* sign-in nobody has used is renewed while it still works rather than at the
|
|
11921
|
-
* moment a request needs it.
|
|
11922
|
-
*/
|
|
11923
|
-
/**
|
|
11924
13030
|
* How long a started panel login stays pollable.
|
|
11925
13031
|
*
|
|
11926
13032
|
* The browser half is the user's to finish, so it is measured in minutes
|
|
@@ -11949,6 +13055,8 @@ let settings = {};
|
|
|
11949
13055
|
* a switch the user just flipped.
|
|
11950
13056
|
*/
|
|
11951
13057
|
let settingsRevision = 0;
|
|
13058
|
+
/** Orders overlapping reads, so a slower older response cannot replace a newer one. */
|
|
13059
|
+
let settingsReadSequence = 0;
|
|
11952
13060
|
/**
|
|
11953
13061
|
* Bumped only by writes this process made, never by a document the host pushed.
|
|
11954
13062
|
*
|
|
@@ -11971,7 +13079,7 @@ const runtimes = /* @__PURE__ */ new Map();
|
|
|
11971
13079
|
*/
|
|
11972
13080
|
const runtimeStarts = /* @__PURE__ */ new Map();
|
|
11973
13081
|
/**
|
|
11974
|
-
*
|
|
13082
|
+
* Retired gateway starts and closes that may still hold a port.
|
|
11975
13083
|
*
|
|
11976
13084
|
* That function runs synchronously inside settings application, yet a source
|
|
11977
13085
|
* toggled off and straight back on starts a new gateway while the old one's
|
|
@@ -12004,6 +13112,8 @@ const gatewayStartFailures = /* @__PURE__ */ new Map();
|
|
|
12004
13112
|
const sourceStartFailures = /* @__PURE__ */ new Map();
|
|
12005
13113
|
/** One in-flight source-gateway start per region, shared by overlapping passes. */
|
|
12006
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();
|
|
12007
13117
|
/** Provider ids the host has confirmed it is serving, this process's lifetime. */
|
|
12008
13118
|
let publishedIds = /* @__PURE__ */ new Set();
|
|
12009
13119
|
/**
|
|
@@ -12219,13 +13329,16 @@ async function loadSettings() {
|
|
|
12219
13329
|
* the switch the user had just flipped.
|
|
12220
13330
|
*/
|
|
12221
13331
|
async function adoptHostSettings() {
|
|
13332
|
+
const readSequence = ++settingsReadSequence;
|
|
12222
13333
|
const revision = settingsRevision;
|
|
13334
|
+
const generation = loadGeneration;
|
|
12223
13335
|
const next = await loadSettings();
|
|
13336
|
+
if (readSequence !== settingsReadSequence) return false;
|
|
12224
13337
|
if (next === void 0) {
|
|
12225
13338
|
log("warn", "could not read settings; keeping the last known document");
|
|
12226
13339
|
return false;
|
|
12227
13340
|
}
|
|
12228
|
-
if (settingsRevision !== revision) return false;
|
|
13341
|
+
if (settingsRevision !== revision || loadGeneration !== generation) return false;
|
|
12229
13342
|
settings = next;
|
|
12230
13343
|
return true;
|
|
12231
13344
|
}
|
|
@@ -12241,9 +13354,12 @@ async function adoptHostSettings() {
|
|
|
12241
13354
|
* it read, and the panel answered success for a change that was gone.
|
|
12242
13355
|
*/
|
|
12243
13356
|
async function saveSettings(patch) {
|
|
13357
|
+
const generation = loadGeneration;
|
|
12244
13358
|
return enqueueWrite(async () => {
|
|
13359
|
+
if (generation !== loadGeneration) return false;
|
|
12245
13360
|
try {
|
|
12246
13361
|
await pi.plugin.setSettings(patch);
|
|
13362
|
+
if (generation !== loadGeneration) return false;
|
|
12247
13363
|
settings = {
|
|
12248
13364
|
...settings,
|
|
12249
13365
|
...patch
|
|
@@ -12286,13 +13402,22 @@ function enqueueWrite(work) {
|
|
|
12286
13402
|
* `undefined` means "no change", which skips the write entirely.
|
|
12287
13403
|
*/
|
|
12288
13404
|
async function mutateSettings(key, mutate) {
|
|
13405
|
+
const generation = loadGeneration;
|
|
12289
13406
|
return enqueueWrite(async () => {
|
|
12290
|
-
|
|
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;
|
|
12291
13414
|
const current = settings[key];
|
|
12292
13415
|
const next = await mutate(current);
|
|
13416
|
+
if (generation !== loadGeneration) return false;
|
|
12293
13417
|
if (next === void 0) return true;
|
|
12294
13418
|
try {
|
|
12295
13419
|
await pi.plugin.setSettings({ [key]: next });
|
|
13420
|
+
if (generation !== loadGeneration) return false;
|
|
12296
13421
|
settings = {
|
|
12297
13422
|
...settings,
|
|
12298
13423
|
[key]: next
|
|
@@ -12331,23 +13456,24 @@ function resetDiscoveryCaches() {
|
|
|
12331
13456
|
*/
|
|
12332
13457
|
async function onHostSettingsChanged(next) {
|
|
12333
13458
|
if (next === null || typeof next !== "object" || Array.isArray(next)) return false;
|
|
13459
|
+
const generation = loadGeneration;
|
|
12334
13460
|
const localRevision = localSettingsRevision;
|
|
12335
13461
|
return enqueueWrite(async () => {
|
|
12336
|
-
if (
|
|
13462
|
+
if (!stillLoaded(generation)) return false;
|
|
12337
13463
|
const before = settings;
|
|
12338
13464
|
if (localSettingsRevision !== localRevision) {
|
|
12339
13465
|
if (!await adoptHostSettings()) {
|
|
12340
|
-
scheduleRefresh("settings");
|
|
13466
|
+
if (stillLoaded(generation)) scheduleRefresh("settings");
|
|
12341
13467
|
return false;
|
|
12342
13468
|
}
|
|
12343
13469
|
} else {
|
|
12344
13470
|
settings = next;
|
|
12345
13471
|
settingsRevision += 1;
|
|
12346
13472
|
}
|
|
13473
|
+
if (!stillLoaded(generation)) return false;
|
|
12347
13474
|
const toggled = Object.values(SOURCE_SETTING_KEYS).some((key) => Object.hasOwn(settings, key) && before[key] !== settings[key]);
|
|
12348
13475
|
if (toggled) resetDiscoveryCaches();
|
|
12349
|
-
await applySettingsEverywhere(toggled);
|
|
12350
|
-
return true;
|
|
13476
|
+
return await applySettingsEverywhere(toggled);
|
|
12351
13477
|
});
|
|
12352
13478
|
}
|
|
12353
13479
|
/**
|
|
@@ -12358,11 +13484,15 @@ async function onHostSettingsChanged(next) {
|
|
|
12358
13484
|
* document to merge.
|
|
12359
13485
|
*/
|
|
12360
13486
|
async function applySettingsEverywhere(toggled) {
|
|
13487
|
+
const generation = loadGeneration;
|
|
13488
|
+
if (!stillLoaded(generation)) return false;
|
|
12361
13489
|
applySettingsToCore();
|
|
12362
13490
|
traeAccountRows = traeAccountRows.filter((row) => regionEnabled("trae", row.region));
|
|
12363
13491
|
qoderAccountRows = qoderAccountRows.filter((row) => regionEnabled("qoder", row.region));
|
|
12364
13492
|
await reconcileTraeGateways();
|
|
13493
|
+
if (!stillLoaded(generation)) return false;
|
|
12365
13494
|
await reconcileQoderGateways();
|
|
13495
|
+
if (!stillLoaded(generation)) return false;
|
|
12366
13496
|
syncDeclaration();
|
|
12367
13497
|
if (toggled) probeCache.clear();
|
|
12368
13498
|
if (toggled) {
|
|
@@ -12868,6 +13998,44 @@ async function settleWithin(work, budgetMs) {
|
|
|
12868
13998
|
clearTimeout(timer);
|
|
12869
13999
|
}
|
|
12870
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
|
+
}
|
|
12871
14039
|
/**
|
|
12872
14040
|
* One deadline, and the two things a bounded pass does with it.
|
|
12873
14041
|
*
|
|
@@ -13078,12 +14246,62 @@ function syncDeclaration() {
|
|
|
13078
14246
|
];
|
|
13079
14247
|
const currentIds = new Set(current.map((provider) => provider.id));
|
|
13080
14248
|
const warming = warmingGatewayIds();
|
|
13081
|
-
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
|
+
});
|
|
13082
14254
|
const result = writeDeclaration([...current, ...retained]);
|
|
13083
14255
|
runtimeState.write = result;
|
|
13084
14256
|
return result;
|
|
13085
14257
|
}
|
|
13086
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
|
+
/**
|
|
13087
14305
|
* The provider ids of the active gateways that are still warming up.
|
|
13088
14306
|
*
|
|
13089
14307
|
* "Warming" is the only reason a row is republished for a gateway that cannot
|
|
@@ -13097,6 +14315,10 @@ function warmingGatewayIds() {
|
|
|
13097
14315
|
const runtime = runtimes.get(region);
|
|
13098
14316
|
if (gatewayStartFailures.has(region)) continue;
|
|
13099
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
|
+
}
|
|
13100
14322
|
}
|
|
13101
14323
|
for (const [source, gateways, regions, idByRegion] of [[
|
|
13102
14324
|
"trae",
|
|
@@ -13254,26 +14476,31 @@ async function reconcileTraeGateways() {
|
|
|
13254
14476
|
if (active.includes(region)) continue;
|
|
13255
14477
|
traeGateways.delete(region);
|
|
13256
14478
|
sourceStartFailures.delete("trae:" + region);
|
|
13257
|
-
|
|
13258
|
-
await entry.gateway.close();
|
|
13259
|
-
} catch (error) {
|
|
13260
|
-
log("warn", "[trae:" + region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
13261
|
-
}
|
|
14479
|
+
await trackSourceStop(entry);
|
|
13262
14480
|
}
|
|
13263
14481
|
for (const region of active) {
|
|
13264
14482
|
if (!stillLoaded(generation) || serviceStopped) return;
|
|
13265
14483
|
if (traeGateways.has(region)) continue;
|
|
13266
14484
|
const key = "trae:" + region;
|
|
13267
|
-
|
|
13268
|
-
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) {
|
|
13269
14491
|
await pending.catch(() => {});
|
|
13270
|
-
|
|
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);
|
|
13271
14497
|
}
|
|
14498
|
+
if (!activeTraeRegions().includes(region) || traeGateways.has(region)) continue;
|
|
13272
14499
|
const starting = createTraeRuntime(region);
|
|
13273
14500
|
sourceGatewayStarts.set(key, starting);
|
|
13274
14501
|
try {
|
|
13275
14502
|
const entry = await starting;
|
|
13276
|
-
if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await entry
|
|
14503
|
+
if (!stillLoaded(generation) || !activeTraeRegions().includes(region) || traeGateways.has(region)) await trackSourceStop(entry);
|
|
13277
14504
|
else {
|
|
13278
14505
|
traeGateways.set(region, entry);
|
|
13279
14506
|
sourceStartFailures.delete(key);
|
|
@@ -13410,26 +14637,31 @@ async function reconcileQoderGateways() {
|
|
|
13410
14637
|
if (active.includes(region)) continue;
|
|
13411
14638
|
qoderGateways.delete(region);
|
|
13412
14639
|
sourceStartFailures.delete("qoder:" + region);
|
|
13413
|
-
|
|
13414
|
-
await entry.gateway.close();
|
|
13415
|
-
} catch (error) {
|
|
13416
|
-
log("warn", "[qoder:" + region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
13417
|
-
}
|
|
14640
|
+
await trackSourceStop(entry);
|
|
13418
14641
|
}
|
|
13419
14642
|
for (const region of active) {
|
|
13420
14643
|
if (!stillLoaded(generation) || serviceStopped) return;
|
|
13421
14644
|
if (qoderGateways.has(region)) continue;
|
|
13422
14645
|
const key = "qoder:" + region;
|
|
13423
|
-
|
|
13424
|
-
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) {
|
|
13425
14652
|
await pending.catch(() => {});
|
|
13426
|
-
|
|
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);
|
|
13427
14658
|
}
|
|
14659
|
+
if (!activeQoderRegions().includes(region) || qoderGateways.has(region)) continue;
|
|
13428
14660
|
const starting = createQoderRuntime(region);
|
|
13429
14661
|
sourceGatewayStarts.set(key, starting);
|
|
13430
14662
|
try {
|
|
13431
14663
|
const entry = await starting;
|
|
13432
|
-
if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await entry
|
|
14664
|
+
if (!stillLoaded(generation) || !activeQoderRegions().includes(region) || qoderGateways.has(region)) await trackSourceStop(entry);
|
|
13433
14665
|
else {
|
|
13434
14666
|
qoderGateways.set(region, entry);
|
|
13435
14667
|
sourceStartFailures.delete(key);
|
|
@@ -13593,7 +14825,7 @@ async function settleStartedRuntime(region, runtime, unwanted) {
|
|
|
13593
14825
|
if (held === runtime) return true;
|
|
13594
14826
|
if (runtime.retired === true) return false;
|
|
13595
14827
|
if (unwanted || held !== void 0) {
|
|
13596
|
-
await
|
|
14828
|
+
await trackRuntimeStop(runtime);
|
|
13597
14829
|
return false;
|
|
13598
14830
|
}
|
|
13599
14831
|
runtimes.set(region, runtime);
|
|
@@ -13613,7 +14845,10 @@ async function settleStartedRuntime(region, runtime, unwanted) {
|
|
|
13613
14845
|
async function startRuntimes() {
|
|
13614
14846
|
const generation = loadGeneration;
|
|
13615
14847
|
if (!stillLoaded(generation)) return;
|
|
13616
|
-
if (pendingRuntimeStops.length > 0)
|
|
14848
|
+
if (pendingRuntimeStops.length > 0) {
|
|
14849
|
+
await waitForRuntimeStops();
|
|
14850
|
+
if (!stillLoaded(generation)) return;
|
|
14851
|
+
}
|
|
13617
14852
|
await Promise.all(activeRegions().map(async (region) => {
|
|
13618
14853
|
if (runtimes.has(region)) return;
|
|
13619
14854
|
try {
|
|
@@ -13630,10 +14865,24 @@ async function stopRuntime(runtime) {
|
|
|
13630
14865
|
if (runtime.retired === true) return;
|
|
13631
14866
|
runtime.retired = true;
|
|
13632
14867
|
runtime.signedIn = false;
|
|
13633
|
-
gatewayStartFailures.delete(runtime.region);
|
|
13634
|
-
|
|
14868
|
+
if (runtimes.get(runtime.region) === runtime) gatewayStartFailures.delete(runtime.region);
|
|
14869
|
+
try {
|
|
14870
|
+
if (runtime.shim) await runtime.shim.close();
|
|
14871
|
+
} catch (error) {
|
|
13635
14872
|
log("warn", "[workbuddy:" + runtime.region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
13636
|
-
}
|
|
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));
|
|
13637
14886
|
}
|
|
13638
14887
|
/**
|
|
13639
14888
|
* Come back for a roster that could not be read.
|
|
@@ -13831,14 +15080,14 @@ async function refreshAll(reason, force) {
|
|
|
13831
15080
|
await adoptHostSettings();
|
|
13832
15081
|
if (!stillLoaded(generation)) return stalePass();
|
|
13833
15082
|
applySettingsToCore();
|
|
13834
|
-
if (poolNeedsScan) {
|
|
15083
|
+
if (poolNeedsScan && activeRegions().length > 0) {
|
|
13835
15084
|
poolNeedsScan = false;
|
|
13836
15085
|
await settle(core.pool.scan());
|
|
13837
15086
|
if (!stillLoaded(generation)) return stalePass();
|
|
13838
15087
|
}
|
|
13839
15088
|
for (const region of activeRegions()) {
|
|
13840
15089
|
if (pendingRuntimeStops.length > 0) {
|
|
13841
|
-
await
|
|
15090
|
+
await waitForRuntimeStops();
|
|
13842
15091
|
if (!stillLoaded(generation)) return stalePass();
|
|
13843
15092
|
}
|
|
13844
15093
|
if (runtimes.has(region)) continue;
|
|
@@ -13847,13 +15096,14 @@ async function refreshAll(reason, force) {
|
|
|
13847
15096
|
try {
|
|
13848
15097
|
runtime = await settle(starting);
|
|
13849
15098
|
} catch (error) {
|
|
15099
|
+
if (!stillLoaded(generation)) return stalePass();
|
|
13850
15100
|
gatewayStartFailures.set(region, safeMessage(error));
|
|
13851
15101
|
log("warn", "[" + region + "] gateway could not start: " + safeMessage(error));
|
|
13852
15102
|
continue;
|
|
13853
15103
|
}
|
|
13854
15104
|
if (runtime === void 0) {
|
|
13855
15105
|
starting.then((late) => {
|
|
13856
|
-
if (runtimes.get(region) !== late) return
|
|
15106
|
+
if (runtimes.get(region) !== late) return trackRuntimeStop(late);
|
|
13857
15107
|
}).catch(() => {});
|
|
13858
15108
|
continue;
|
|
13859
15109
|
}
|
|
@@ -14175,7 +15425,7 @@ function applySettingsToCore() {
|
|
|
14175
15425
|
function reconcileRuntimes() {
|
|
14176
15426
|
const active = new Set(activeRegions());
|
|
14177
15427
|
for (const [region, runtime] of runtimes) if (!active.has(region)) {
|
|
14178
|
-
|
|
15428
|
+
trackRuntimeStop(runtime);
|
|
14179
15429
|
runtimes.delete(region);
|
|
14180
15430
|
}
|
|
14181
15431
|
if (active.size === 0 && core.pool) {
|
|
@@ -15066,7 +16316,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
15066
16316
|
resetDiscoveryCaches();
|
|
15067
16317
|
growthRead = null;
|
|
15068
16318
|
growthReadEpoch += 1;
|
|
15069
|
-
if (activeRegions().length > 0) await settle(core.pool.
|
|
16319
|
+
if (activeRegions().length > 0) await settle(core.pool.rescan());
|
|
15070
16320
|
await settle(startRuntimes());
|
|
15071
16321
|
await settle(refreshSourceAccounts());
|
|
15072
16322
|
await settle(reconcileTraeGateways());
|
|
@@ -15518,6 +16768,7 @@ async function onPanelInvoke(channel, payload) {
|
|
|
15518
16768
|
throw panelError("the login link has expired; start again", "LOGIN_EXPIRED");
|
|
15519
16769
|
}
|
|
15520
16770
|
const answer = await pollDeviceLogin(realm, pending.state);
|
|
16771
|
+
if (deviceLogins.get(realm) !== pending) throw panelError("this login is no longer waiting; start again", "NO_LOGIN");
|
|
15521
16772
|
if (answer.status !== "ok") return { status: "pending" };
|
|
15522
16773
|
deviceLogins.delete(realm);
|
|
15523
16774
|
const directory = ownSignInDir(dataPath);
|
|
@@ -15750,7 +17001,7 @@ async function runCheckinPass(options) {
|
|
|
15750
17001
|
if (want("qoder")) {
|
|
15751
17002
|
const now = Date.now();
|
|
15752
17003
|
const opening = typeof qoder?.opensAt === "number" && qoder.opensAt > now ? qoder.opensAt : 0;
|
|
15753
|
-
const backoff = Number(qoder?.failed) > 0 && (typeof qoder?.reason === "string" || qoder?.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
|
|
17004
|
+
const backoff = Number(qoder?.failed) > 0 && qoder?.retry !== false && (typeof qoder?.reason === "string" || qoder?.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
|
|
15754
17005
|
qoderRetryAt = opening === 0 ? backoff : backoff === 0 ? opening : Math.min(opening, backoff);
|
|
15755
17006
|
}
|
|
15756
17007
|
Object.assign(started, {
|
|
@@ -15845,9 +17096,20 @@ async function redeemAccountStreak(account) {
|
|
|
15845
17096
|
lottery: 0,
|
|
15846
17097
|
failed: 0
|
|
15847
17098
|
};
|
|
17099
|
+
const result = {
|
|
17100
|
+
claimed: 0,
|
|
17101
|
+
credit: 0,
|
|
17102
|
+
energy: 0,
|
|
17103
|
+
detail
|
|
17104
|
+
};
|
|
17105
|
+
const signal = currentCheckinSignal();
|
|
17106
|
+
if (signal.aborted) return result;
|
|
15848
17107
|
const conversationId = "wb2api-streak-" + Date.now();
|
|
15849
17108
|
try {
|
|
15850
|
-
|
|
17109
|
+
const cards = await core.client.makeupCards(account.credential);
|
|
17110
|
+
if (signal.aborted) return result;
|
|
17111
|
+
if (cards > 0 && await core.client.missedYesterday(account.credential)) {
|
|
17112
|
+
if (signal.aborted) return result;
|
|
15851
17113
|
const yesterday = zonedDay(-1);
|
|
15852
17114
|
await core.client.useMakeupCard(account.credential, yesterday);
|
|
15853
17115
|
detail.makeup += 1;
|
|
@@ -15857,13 +17119,17 @@ async function redeemAccountStreak(account) {
|
|
|
15857
17119
|
detail.failed += 1;
|
|
15858
17120
|
log("warn", "streak " + accountLogTag(account.label) + ": make-up: " + safeMessage(error));
|
|
15859
17121
|
}
|
|
15860
|
-
for (const [label, collect] of [["gift", () => core.client.claimGift(account.credential)], ["compensation", () => core.client.claimCompensation(account.credential)]])
|
|
15861
|
-
|
|
15862
|
-
|
|
15863
|
-
|
|
15864
|
-
|
|
15865
|
-
|
|
15866
|
-
|
|
17122
|
+
for (const [label, collect] of [["gift", () => core.client.claimGift(account.credential)], ["compensation", () => core.client.claimCompensation(account.credential)]]) {
|
|
17123
|
+
if (signal.aborted) return result;
|
|
17124
|
+
try {
|
|
17125
|
+
const paid = await collect();
|
|
17126
|
+
if (paid > 0) {
|
|
17127
|
+
detail[label] += paid;
|
|
17128
|
+
log("info", "streak " + accountLogTag(account.label) + ": " + label + " +" + paid + "c");
|
|
17129
|
+
}
|
|
17130
|
+
} catch {}
|
|
17131
|
+
}
|
|
17132
|
+
if (signal.aborted) return result;
|
|
15867
17133
|
try {
|
|
15868
17134
|
await core.client.reportChatActivity(account.credential, conversationId);
|
|
15869
17135
|
detail.activity += 1;
|
|
@@ -15872,17 +17138,16 @@ async function redeemAccountStreak(account) {
|
|
|
15872
17138
|
log("warn", "streak " + accountLogTag(account.label) + ": activity report failed: " + safeMessage(error));
|
|
15873
17139
|
}
|
|
15874
17140
|
await checkinDelay(STREAK_REPORT_READ_GAP_MS);
|
|
17141
|
+
if (signal.aborted) return result;
|
|
15875
17142
|
const status = await core.client.growthStreakFull(account.credential);
|
|
15876
|
-
let claimed = 0;
|
|
15877
|
-
let credit = 0;
|
|
15878
|
-
let energy = 0;
|
|
15879
17143
|
for (const tier of status.tiers) {
|
|
15880
17144
|
if (tier.status !== "unlocked") continue;
|
|
17145
|
+
if (signal.aborted) return result;
|
|
15881
17146
|
try {
|
|
15882
17147
|
await core.client.redeemStreakTier(account.credential, tier.tier);
|
|
15883
|
-
claimed += 1;
|
|
15884
|
-
credit += tier.credit;
|
|
15885
|
-
energy += tier.energy;
|
|
17148
|
+
result.claimed += 1;
|
|
17149
|
+
result.credit += tier.credit;
|
|
17150
|
+
result.energy += tier.energy;
|
|
15886
17151
|
detail.streak += 1;
|
|
15887
17152
|
log("info", "streak " + accountLogTag(account.label) + ": redeemed " + tier.tier + " (+" + tier.credit + "c +" + tier.energy + "e)");
|
|
15888
17153
|
} catch (error) {
|
|
@@ -15890,23 +17155,20 @@ async function redeemAccountStreak(account) {
|
|
|
15890
17155
|
log("warn", "streak " + accountLogTag(account.label) + ": redeem " + tier.tier + " failed: " + safeMessage(error));
|
|
15891
17156
|
}
|
|
15892
17157
|
}
|
|
17158
|
+
if (signal.aborted) return result;
|
|
15893
17159
|
try {
|
|
15894
17160
|
const chances = await core.client.lotteryChances(account.credential);
|
|
15895
17161
|
for (let draw = 0; draw < chances; draw += 1) {
|
|
15896
|
-
|
|
17162
|
+
if (signal.aborted) return result;
|
|
17163
|
+
await core.client.drawLottery(account.credential);
|
|
15897
17164
|
detail.lottery += 1;
|
|
15898
|
-
log("info", "streak " + accountLogTag(account.label) + ": draw " + (draw + 1) + "/" + chances
|
|
17165
|
+
log("info", "streak " + accountLogTag(account.label) + ": draw " + (draw + 1) + "/" + chances);
|
|
15899
17166
|
}
|
|
15900
17167
|
} catch (error) {
|
|
15901
17168
|
detail.failed += 1;
|
|
15902
17169
|
log("warn", "streak " + accountLogTag(account.label) + ": lottery: " + safeMessage(error));
|
|
15903
17170
|
}
|
|
15904
|
-
return
|
|
15905
|
-
claimed,
|
|
15906
|
-
credit,
|
|
15907
|
-
energy,
|
|
15908
|
-
detail
|
|
15909
|
-
};
|
|
17171
|
+
return result;
|
|
15910
17172
|
}
|
|
15911
17173
|
/**
|
|
15912
17174
|
* Collect the streak bonus of every account.
|
|
@@ -16241,7 +17503,8 @@ async function qoderCheckinAll() {
|
|
|
16241
17503
|
return {
|
|
16242
17504
|
...counts,
|
|
16243
17505
|
failed: 1,
|
|
16244
|
-
reason
|
|
17506
|
+
reason,
|
|
17507
|
+
retry: true
|
|
16245
17508
|
};
|
|
16246
17509
|
}
|
|
16247
17510
|
if (found.failures.length > 0) {
|
|
@@ -16256,6 +17519,7 @@ async function qoderCheckinAll() {
|
|
|
16256
17519
|
seen += 1;
|
|
16257
17520
|
const result = await qoderClaimFor(credential);
|
|
16258
17521
|
counts[result.outcome] += 1;
|
|
17522
|
+
if (result.outcome === "failed" && counts.reason === void 0 && result.reason) counts.reason = safeMessage(result.reason);
|
|
16259
17523
|
markSourceCheckinRow("qoder", qoderRowLabel(credential), credential.region, result);
|
|
16260
17524
|
if (result.retry === true) counts.retry = true;
|
|
16261
17525
|
if (result.opensAt !== void 0 && (counts.opensAt === void 0 || result.opensAt < counts.opensAt)) counts.opensAt = result.opensAt;
|
|
@@ -16294,10 +17558,11 @@ async function qoderClaimFor(credential) {
|
|
|
16294
17558
|
}
|
|
16295
17559
|
const result = qoderNormalizeClaimResult(await client.claimCampaign(id));
|
|
16296
17560
|
if (result.reason !== void 0) {
|
|
16297
|
-
|
|
17561
|
+
const reason = safeMessage(result.reason);
|
|
17562
|
+
log("warn", "[qoder:" + credential.region + "] check-in refused for " + accountLogTag(qoderRowLabel(credential)) + ": " + reason);
|
|
16298
17563
|
return {
|
|
16299
17564
|
outcome: "failed",
|
|
16300
|
-
reason
|
|
17565
|
+
reason,
|
|
16301
17566
|
retry: false
|
|
16302
17567
|
};
|
|
16303
17568
|
}
|
|
@@ -16362,6 +17627,7 @@ async function traeCheckinAll() {
|
|
|
16362
17627
|
if (index > 0) await checkinDelay(Math.max(1e3, TRAE_ACCOUNT_DELAY_MS + Math.round((Math.random() * 2 - 1) * TRAE_ACCOUNT_JITTER_MS)));
|
|
16363
17628
|
const result = await traeClaimFor(credential, desktopCandidates);
|
|
16364
17629
|
counts[result.outcome] += 1;
|
|
17630
|
+
if (result.outcome === "failed" && counts.reason === void 0 && result.reason) counts.reason = safeMessage(result.reason);
|
|
16365
17631
|
markSourceCheckinRow("trae", traeRowLabel(credential), "cn", result);
|
|
16366
17632
|
if (result.deviceCheckedIn === true) spentEditions.add(credential.edition);
|
|
16367
17633
|
}
|
|
@@ -16528,7 +17794,7 @@ async function autoCheckinTick(now) {
|
|
|
16528
17794
|
if (!stillLoaded(retryGeneration)) return autoCheckinLast;
|
|
16529
17795
|
const now = Date.now();
|
|
16530
17796
|
const opening = typeof retry.opensAt === "number" && retry.opensAt > now ? retry.opensAt : 0;
|
|
16531
|
-
const backoff = Number(retry.failed) > 0 && (typeof retry.reason === "string" || retry.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
|
|
17797
|
+
const backoff = Number(retry.failed) > 0 && retry.retry !== false && (typeof retry.reason === "string" || retry.retry === true) ? now + QODER_RETRY_BACKOFF_MS : 0;
|
|
16532
17798
|
qoderRetryAt = opening === 0 ? backoff : backoff === 0 ? opening : Math.min(opening, backoff);
|
|
16533
17799
|
const claimedBefore = Number(autoCheckinLast?.qoder?.claimed) || 0;
|
|
16534
17800
|
autoCheckinLast = {
|
|
@@ -16679,8 +17945,9 @@ function stopAccountWatch() {
|
|
|
16679
17945
|
* Note this is the only place the roster is fetched during load: opening the
|
|
16680
17946
|
* panel no longer triggers detection of its own.
|
|
16681
17947
|
*/
|
|
16682
|
-
async function publishDeclarationEarly() {
|
|
17948
|
+
async function publishDeclarationEarly(generation) {
|
|
16683
17949
|
await adoptHostSettings();
|
|
17950
|
+
if (!stillLoaded(generation)) return;
|
|
16684
17951
|
if (settings.enabled === false) {
|
|
16685
17952
|
const cleared = syncDeclaration();
|
|
16686
17953
|
if (cleared.ok !== true) log("warn", "declaration not cleared: " + String(cleared.error));
|
|
@@ -16690,9 +17957,13 @@ async function publishDeclarationEarly() {
|
|
|
16690
17957
|
reconcileRuntimes();
|
|
16691
17958
|
const { left: bootstrapLeft } = budget(LOAD_BOOTSTRAP_BUDGET_MS);
|
|
16692
17959
|
await settleWithin(reconcileTraeGateways(), bootstrapLeft());
|
|
17960
|
+
if (!stillLoaded(generation)) return;
|
|
16693
17961
|
await settleWithin(reconcileQoderGateways(), bootstrapLeft());
|
|
17962
|
+
if (!stillLoaded(generation)) return;
|
|
16694
17963
|
if (activeRegions().length > 0) await settleWithin(core.pool.scan(), bootstrapLeft());
|
|
17964
|
+
if (!stillLoaded(generation)) return;
|
|
16695
17965
|
await settleWithin(startRuntimes(), bootstrapLeft());
|
|
17966
|
+
if (!stillLoaded(generation)) return;
|
|
16696
17967
|
await settleWithin(Promise.all(Array.from(runtimes.values()).map(async (runtime) => {
|
|
16697
17968
|
try {
|
|
16698
17969
|
await connect(runtime, true);
|
|
@@ -16701,6 +17972,7 @@ async function publishDeclarationEarly() {
|
|
|
16701
17972
|
log("warn", runtime.region + " failed to start during load: " + runtime.lastError);
|
|
16702
17973
|
}
|
|
16703
17974
|
})), LOAD_ROSTER_BUDGET_MS);
|
|
17975
|
+
if (!stillLoaded(generation)) return;
|
|
16704
17976
|
const written = syncDeclaration();
|
|
16705
17977
|
if (written.ok !== true) log("warn", "declaration not written: " + String(written.error));
|
|
16706
17978
|
else if (written.changed === true) log("info", "declaration updated at load time; " + written.providerCount + " provider(s)");
|
|
@@ -16709,6 +17981,8 @@ async function onServiceStart() {
|
|
|
16709
17981
|
const generation = loadGeneration;
|
|
16710
17982
|
serviceStopped = false;
|
|
16711
17983
|
if (warmAbort.signal.aborted) warmAbort = new AbortController();
|
|
17984
|
+
await writeChain;
|
|
17985
|
+
if (!stillLoaded(generation)) return;
|
|
16712
17986
|
await adoptHostSettings();
|
|
16713
17987
|
if (!stillLoaded(generation)) return;
|
|
16714
17988
|
if (settings.enabled === false) {
|
|
@@ -16743,6 +18017,7 @@ async function onServiceStart() {
|
|
|
16743
18017
|
async function onServiceStop() {
|
|
16744
18018
|
serviceStopped = true;
|
|
16745
18019
|
loadGeneration += 1;
|
|
18020
|
+
core.pool?.clear();
|
|
16746
18021
|
if (refreshTimer !== null) {
|
|
16747
18022
|
clearTimeout(refreshTimer);
|
|
16748
18023
|
refreshTimer = null;
|
|
@@ -16753,22 +18028,24 @@ async function onServiceStop() {
|
|
|
16753
18028
|
abortWarmups();
|
|
16754
18029
|
clearModelRetries();
|
|
16755
18030
|
checkinAbort.abort();
|
|
16756
|
-
const closing = Array.from(runtimes.values()).map(
|
|
18031
|
+
const closing = Array.from(runtimes.values()).map(trackRuntimeStop);
|
|
16757
18032
|
runtimes.clear();
|
|
18033
|
+
for (const starting of runtimeStarts.values()) trackPendingRuntime(starting);
|
|
16758
18034
|
runtimeStarts.clear();
|
|
16759
|
-
for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) closing.push(entry
|
|
16760
|
-
log("warn", "[" + entry.source + ":" + entry.region + "] gateway did not close cleanly: " + safeMessage(error));
|
|
16761
|
-
}));
|
|
18035
|
+
for (const entry of [...traeGateways.values(), ...qoderGateways.values()]) closing.push(trackSourceStop(entry));
|
|
16762
18036
|
traeGateways.clear();
|
|
16763
18037
|
qoderGateways.clear();
|
|
16764
18038
|
gatewayStartFailures.clear();
|
|
16765
18039
|
sourceStartFailures.clear();
|
|
18040
|
+
for (const [key, starting] of sourceGatewayStarts) trackPendingSource(key, starting);
|
|
16766
18041
|
sourceGatewayStarts.clear();
|
|
16767
18042
|
await Promise.all(closing);
|
|
16768
18043
|
}
|
|
16769
18044
|
async function onLoad() {
|
|
16770
18045
|
serviceStopped = false;
|
|
16771
18046
|
loadGeneration += 1;
|
|
18047
|
+
const generation = loadGeneration;
|
|
18048
|
+
core.pool?.clear();
|
|
16772
18049
|
abortWarmups();
|
|
16773
18050
|
warmAbort = new AbortController();
|
|
16774
18051
|
checkinAbort.abort();
|
|
@@ -16781,9 +18058,11 @@ async function onLoad() {
|
|
|
16781
18058
|
refreshTimer = null;
|
|
16782
18059
|
}
|
|
16783
18060
|
refreshInflight = null;
|
|
16784
|
-
for (const runtime of runtimes.values())
|
|
18061
|
+
for (const runtime of runtimes.values()) trackRuntimeStop(runtime);
|
|
16785
18062
|
runtimes.clear();
|
|
18063
|
+
for (const starting of runtimeStarts.values()) trackPendingRuntime(starting);
|
|
16786
18064
|
runtimeStarts.clear();
|
|
18065
|
+
for (const [key, starting] of sourceGatewayStarts) trackPendingSource(key, starting);
|
|
16787
18066
|
sourceGatewayStarts.clear();
|
|
16788
18067
|
checkinPassRunning = false;
|
|
16789
18068
|
autoCheckinSlots.clear();
|
|
@@ -16804,24 +18083,29 @@ async function onLoad() {
|
|
|
16804
18083
|
error: (...args) => log("error", gatewayLogLine("", args))
|
|
16805
18084
|
}
|
|
16806
18085
|
});
|
|
18086
|
+
await writeChain;
|
|
18087
|
+
if (!stillLoaded(generation)) return;
|
|
16807
18088
|
await adoptHostSettings();
|
|
16808
|
-
if (
|
|
18089
|
+
if (!stillLoaded(generation)) return;
|
|
16809
18090
|
publishedIds = /* @__PURE__ */ new Set();
|
|
18091
|
+
let nextDataPath;
|
|
16810
18092
|
try {
|
|
16811
|
-
|
|
18093
|
+
nextDataPath = await pi.plugin.getDataPath();
|
|
16812
18094
|
} catch (error) {
|
|
16813
|
-
|
|
18095
|
+
nextDataPath = "";
|
|
16814
18096
|
log("warn", "no plugin data path: " + safeMessage(error));
|
|
16815
18097
|
}
|
|
18098
|
+
if (!stillLoaded(generation)) return;
|
|
18099
|
+
dataPath = nextDataPath;
|
|
16816
18100
|
loadCheckinSlots();
|
|
16817
|
-
if (
|
|
18101
|
+
if (!stillLoaded(generation)) return;
|
|
16818
18102
|
pi.services.register({
|
|
16819
18103
|
id: SERVICE_ID,
|
|
16820
18104
|
start: onServiceStart,
|
|
16821
18105
|
stop: onServiceStop
|
|
16822
18106
|
});
|
|
16823
18107
|
subscribeToHostSettings();
|
|
16824
|
-
await publishDeclarationEarly();
|
|
18108
|
+
await publishDeclarationEarly(generation);
|
|
16825
18109
|
}
|
|
16826
18110
|
async function onUnload() {
|
|
16827
18111
|
loadGeneration += 1;
|
|
@@ -16833,7 +18117,7 @@ async function onUnload() {
|
|
|
16833
18117
|
stopAccountWatch();
|
|
16834
18118
|
clearModelRetries();
|
|
16835
18119
|
abortWarmups();
|
|
16836
|
-
|
|
18120
|
+
const stopping = onServiceStop();
|
|
16837
18121
|
probeCache.clear();
|
|
16838
18122
|
sourceFailureHold.clear();
|
|
16839
18123
|
sourceCreditExpiry.clear();
|
|
@@ -16845,6 +18129,7 @@ async function onUnload() {
|
|
|
16845
18129
|
sourceGatewayStarts.clear();
|
|
16846
18130
|
deviceLogins.clear();
|
|
16847
18131
|
unsubscribeFromHostSettings();
|
|
18132
|
+
await stopping;
|
|
16848
18133
|
}
|
|
16849
18134
|
function composerPointsEnabled() {
|
|
16850
18135
|
return settings.showComposerPoints === true;
|
|
@@ -17065,6 +18350,8 @@ const STREAM_IDLE_TIMEOUT_MS = 3e5;
|
|
|
17065
18350
|
/** Image-request budgets at the dsh-llm-pi-ai defaults. */
|
|
17066
18351
|
const REQUEST_IMAGE_BUDGETS = {
|
|
17067
18352
|
maxRequestImageBytes: 20971520,
|
|
18353
|
+
maxRequestImages: 50,
|
|
18354
|
+
imageOffloadCountQuantum: 10,
|
|
17068
18355
|
requestImagePixelBudget: 4194304,
|
|
17069
18356
|
requestImageMaxBytes: 1048576
|
|
17070
18357
|
};
|
|
@@ -17244,56 +18531,43 @@ function toPiModel(row, baseUrl, providerId) {
|
|
|
17244
18531
|
compat: { supportsReasoningEffort: map !== void 0 }
|
|
17245
18532
|
};
|
|
17246
18533
|
}
|
|
17247
|
-
/**
|
|
17248
|
-
* Whether the resolved pi-ai carries the prompt inside the transcript.
|
|
17249
|
-
*
|
|
17250
|
-
* The host folds `Context.systemPrompt` and `Context.tools` into a leading
|
|
17251
|
-
* `role:"system"` message before a provider sees a request, and only a
|
|
17252
|
-
* generation that exports `normalizeContext` reads that message back. Which
|
|
17253
|
-
* generation this plugin gets is not its own call: the harness resolves
|
|
17254
|
-
* `@earendil-works/pi-ai` through the profile's hoisted linker, so a profile
|
|
17255
|
-
* that hoists an older generation hands this provider a transcript its own copy
|
|
17256
|
-
* of pi-ai never learned to read.
|
|
17257
|
-
*/
|
|
18534
|
+
/** Whether this delegate reads the prompt and tools from a transcript. */
|
|
17258
18535
|
const PI_AI_FOLDS_TRANSCRIPT = typeof piAi.normalizeContext === "function";
|
|
17259
|
-
/**
|
|
17260
|
-
function
|
|
17261
|
-
|
|
17262
|
-
|
|
17263
|
-
|
|
17264
|
-
}
|
|
17265
|
-
|
|
17266
|
-
|
|
17267
|
-
|
|
17268
|
-
|
|
17269
|
-
|
|
17270
|
-
|
|
17271
|
-
|
|
17272
|
-
|
|
17273
|
-
|
|
17274
|
-
|
|
17275
|
-
|
|
17276
|
-
|
|
17277
|
-
|
|
17278
|
-
|
|
17279
|
-
|
|
17280
|
-
const
|
|
17281
|
-
if (leading?.role !== "system") return context;
|
|
17282
|
-
const prompt = promptText(leading);
|
|
17283
|
-
const tools = Array.isArray(leading.toolsAdded) ? leading.toolsAdded : [];
|
|
17284
|
-
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");
|
|
17285
18558
|
return {
|
|
17286
|
-
...
|
|
17287
|
-
|
|
17288
|
-
|
|
18559
|
+
...legacy,
|
|
18560
|
+
systemPrompt: prompt || void 0,
|
|
18561
|
+
tools: [...tools.values()],
|
|
18562
|
+
messages: messages.filter((message) => message.role !== "system")
|
|
17289
18563
|
};
|
|
17290
18564
|
}
|
|
17291
18565
|
/** Wrap one API implementation so every request arrives in the shape it reads. */
|
|
17292
|
-
function withDelegateShape(api
|
|
18566
|
+
function withDelegateShape(api) {
|
|
17293
18567
|
return {
|
|
17294
18568
|
...api,
|
|
17295
|
-
stream: (model, context, options) => api.stream(model, contextForDelegate(context
|
|
17296
|
-
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)
|
|
17297
18571
|
};
|
|
17298
18572
|
}
|
|
17299
18573
|
/**
|
|
@@ -17304,8 +18578,6 @@ function withDelegateShape(api, log) {
|
|
|
17304
18578
|
* holding one profile per row is what keeps all six alive at once.
|
|
17305
18579
|
*/
|
|
17306
18580
|
function buildAdapter(descriptors, ctx) {
|
|
17307
|
-
const adapterPrototype = PiAiAdapter.prototype;
|
|
17308
|
-
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");
|
|
17309
18581
|
const profiles = /* @__PURE__ */ new Map();
|
|
17310
18582
|
const providerIds = [];
|
|
17311
18583
|
for (const row of descriptors) {
|
|
@@ -17326,7 +18598,7 @@ function buildAdapter(descriptors, ctx) {
|
|
|
17326
18598
|
}
|
|
17327
18599
|
} },
|
|
17328
18600
|
models,
|
|
17329
|
-
api: withDelegateShape(openAICompletionsApi()
|
|
18601
|
+
api: withDelegateShape(openAICompletionsApi())
|
|
17330
18602
|
}),
|
|
17331
18603
|
getModels: () => models
|
|
17332
18604
|
};
|