@vibedev-si/dsh-vibedev 0.10.0 → 0.11.1

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/lib/index.js CHANGED
@@ -2136,6 +2136,639 @@ function accountCenterRoutes(http, account) {
2136
2136
  })), ...accountBusinessActionsRoutes(http, account)];
2137
2137
  }
2138
2138
  //#endregion
2139
+ //#region src/chat-consent/contract.ts
2140
+ /**
2141
+ * The desktop chat consent contract (VibeDev messages contract v1, section 3): the request the VibeDev desktop's Host
2142
+ * passes to `vibedevDesktopChatConsent`, the results it can get back, and the plugin's checks of them. Three layers
2143
+ * check a decision — this plugin, the desktop Host and the desktop main process — and the plugin is the strictest of
2144
+ * them; the desktop's layers keep checks of their own, which may reuse these functions but are not bound to match them.
2145
+ * Pure functions only (no I/O, no Node APIs), so a checker here can be imported or ported as it is.
2146
+ * @module dsh-vibedev/chat-consent/contract
2147
+ */
2148
+ /**
2149
+ * The service name the desktop Host looks up: `ctx.get('vibedevDesktopChatConsent')`. It was `vibedevChatConsent`
2150
+ * before the first release, and that name is never registered: the desktop-host of the rc.2 beta build looks the
2151
+ * service up under it and forwards the answer as a bare callback string, and its main process ends the Host on the
2152
+ * object this service answers. Under this name a beta build finds no service and falls back to its failure prompt.
2153
+ */
2154
+ const DESKTOP_CHAT_CONSENT_SERVICE = "vibedevDesktopChatConsent";
2155
+ /** The protocol version the service object carries as `version`. */
2156
+ const CHAT_CONSENT_VERSION = 1;
2157
+ /** The first-party origins the checks here use: a private copy, so nothing outside this module can change it. */
2158
+ const FIRST_PARTY_ORIGINS = /* @__PURE__ */ new Set(["https://vibedev.studio", "https://api.vibedev.studio"]);
2159
+ /**
2160
+ * The first-party VibeDev origins. The service exists only while the plugin's own gateway is one of them: the App Token
2161
+ * that gateway issued may then go to the chat OIDC issuer ({@link CHAT_CONSENT_ENDPOINT_ORIGIN}), which belongs to the
2162
+ * same deployment. A token any other gateway issued never does. Frozen, and only a copy: the checks never read it.
2163
+ */
2164
+ const CHAT_CONSENT_FIRST_PARTY_ORIGINS = Object.freeze([...FIRST_PARTY_ORIGINS]);
2165
+ /**
2166
+ * The only origin a consent endpoint may be on: the chat OIDC issuer host. The gateway consumes chat sign-in requests
2167
+ * on this host alone; the same route answers 404 on `https://api.vibedev.studio`.
2168
+ */
2169
+ const CHAT_CONSENT_ENDPOINT_ORIGIN = "https://vibedev.studio";
2170
+ /** Where one consent decision is posted by default: the issuer host, where the gateway consumes chat OIDC requests. */
2171
+ const DEFAULT_CHAT_CONSENT_ENDPOINT = "https://vibedev.studio/api/v1/vibedev/chat-oidc/desktop-consent";
2172
+ /**
2173
+ * The Matrix callback an answer must lead to by default: the Synapse OIDC callback of the production homeserver
2174
+ * (`matrix.vibedev.studio`). A build whose Messages use another homeserver, such as a beta build on the test site, sets
2175
+ * `chatConsent.callbackUrl` to that homeserver's callback: the gateway answers each request with the callback of the
2176
+ * chat client that issued it, and any other callback is refused.
2177
+ */
2178
+ const DEFAULT_CHAT_CONSENT_CALLBACK_URL = "https://matrix.vibedev.studio/_synapse/client/oidc/callback";
2179
+ /** The longest callback URL any party accepts. */
2180
+ const CHAT_CONSENT_MAX_CALLBACK_LENGTH = 1024;
2181
+ /** A VibeDev user id, as the Matrix user mapping writes it (`@vibedev_{sub}:…`). */
2182
+ const SUBJECT = /^[1-9]\d{0,18}$/;
2183
+ /** A pending chat OIDC request (`request` on the consent page). */
2184
+ const HANDLE = /^[A-Za-z0-9_-]{43}$/;
2185
+ /** The `state` Synapse sent with the authorization request, returned unchanged. */
2186
+ const STATE = /^[A-Za-z0-9_-]{16,256}$/;
2187
+ /** A one-time authorization code. */
2188
+ const CODE = /^[A-Za-z0-9_-]{43}$/;
2189
+ const STATUSES = /* @__PURE__ */ new Set([
2190
+ "redirect",
2191
+ "signed-out",
2192
+ "mismatch",
2193
+ "rejected",
2194
+ "failed"
2195
+ ]);
2196
+ /**
2197
+ * Read a consent request.
2198
+ * @param value - what a caller passed.
2199
+ * @returns a copy of the request when every field is valid, else undefined.
2200
+ */
2201
+ function readChatConsentRequest(value) {
2202
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
2203
+ try {
2204
+ const { subject, handle, approve } = value;
2205
+ return typeof subject === "string" && SUBJECT.test(subject) && typeof handle === "string" && HANDLE.test(handle) && typeof approve === "boolean" ? {
2206
+ subject,
2207
+ handle,
2208
+ approve
2209
+ } : void 0;
2210
+ } catch {
2211
+ return;
2212
+ }
2213
+ }
2214
+ /**
2215
+ * Check a Matrix callback against the configured callback and the decision it answers. It must be at most 1024
2216
+ * characters, https, in canonical form (`new URL(value).href === value`), without credentials or any `#`, on the
2217
+ * configured origin and path, with exactly two raw query parameters: `state` and `code` when the decision approves,
2218
+ * `state` and `error=access_denied` when it declines. Values are compared as sent, never decoded, so a percent-encoded
2219
+ * or `+`-spelled value, a repeated name or a third parameter is refused.
2220
+ * @param value - the callback the gateway answered.
2221
+ * @param approve - the decision it answers.
2222
+ * @param callbackUrl - the configured callback (origin and path).
2223
+ * @returns the callback unchanged when it passes, else undefined.
2224
+ */
2225
+ function readChatConsentCallback(value, approve, callbackUrl) {
2226
+ if (typeof value !== "string" || value.length === 0 || value.length > 1024 || value.includes("#")) return void 0;
2227
+ let expected;
2228
+ let url;
2229
+ try {
2230
+ expected = normalizeChatConsentCallbackUrl(callbackUrl);
2231
+ url = new URL(value);
2232
+ } catch {
2233
+ return;
2234
+ }
2235
+ if (url.href !== value || url.protocol !== "https:" || url.username !== "" || url.password !== "" || `${url.origin}${url.pathname}` !== expected) return void 0;
2236
+ const pairs = url.search.slice(1).split("&");
2237
+ if (pairs.length !== 2) return void 0;
2238
+ const query = /* @__PURE__ */ new Map();
2239
+ for (const pair of pairs) {
2240
+ const separator = pair.indexOf("=");
2241
+ if (separator <= 0) return void 0;
2242
+ const name = pair.slice(0, separator);
2243
+ if (query.has(name)) return void 0;
2244
+ query.set(name, pair.slice(separator + 1));
2245
+ }
2246
+ if (!STATE.test(query.get("state") ?? "")) return void 0;
2247
+ return (approve ? CODE.test(query.get("code") ?? "") : query.get("error") === "access_denied") ? value : void 0;
2248
+ }
2249
+ /**
2250
+ * Check what a `vibedevDesktopChatConsent` service answered, as its caller must before acting on it.
2251
+ * @param value - the answer.
2252
+ * @param approve - the decision that was asked for.
2253
+ * @param callbackUrl - the configured callback (origin and path).
2254
+ * @returns a copy of the result when it is one the contract allows, else undefined (the caller then reports `failed`).
2255
+ */
2256
+ function readChatConsentResult(value, approve, callbackUrl) {
2257
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
2258
+ try {
2259
+ const { status, url } = value;
2260
+ if (typeof status !== "string" || !STATUSES.has(status)) return void 0;
2261
+ if (status !== "redirect") return { status };
2262
+ const callback = readChatConsentCallback(url, approve, callbackUrl);
2263
+ return callback === void 0 ? void 0 : {
2264
+ status,
2265
+ url: callback
2266
+ };
2267
+ } catch {
2268
+ return;
2269
+ }
2270
+ }
2271
+ /**
2272
+ * Whether a gateway is first-party, so that its App Token may go to the chat OIDC issuer.
2273
+ * @param origin - a canonical origin, such as the normalized `gatewayOrigin`.
2274
+ * @returns whether it is one of the origins {@link CHAT_CONSENT_FIRST_PARTY_ORIGINS} lists (read from a private copy).
2275
+ */
2276
+ function isFirstPartyChatConsentOrigin(origin) {
2277
+ return FIRST_PARTY_ORIGINS.has(origin);
2278
+ }
2279
+ function configuredUrl(value, field) {
2280
+ const text = typeof value === "string" ? value.trim() : "";
2281
+ let url;
2282
+ try {
2283
+ url = new URL(text);
2284
+ } catch {}
2285
+ if (url === void 0 || url.protocol !== "https:") throw new Error(`${field} must be an absolute https URL.`);
2286
+ if (url.username !== "" || url.password !== "") throw new Error(`${field} must not carry credentials.`);
2287
+ if (text.includes("?") || text.includes("#")) throw new Error(`${field} must not carry a query or a fragment.`);
2288
+ return url;
2289
+ }
2290
+ /**
2291
+ * Validate `chatConsent.endpoint`: an https URL on the chat OIDC issuer host ({@link CHAT_CONSENT_ENDPOINT_ORIGIN}),
2292
+ * without credentials, query or fragment.
2293
+ * @param value - the configured endpoint.
2294
+ * @returns the endpoint in canonical form.
2295
+ * @throws an Error naming the rule it breaks (never echoing credentials).
2296
+ */
2297
+ function normalizeChatConsentEndpoint(value) {
2298
+ const url = configuredUrl(value, "chatConsent.endpoint");
2299
+ if (url.origin !== "https://vibedev.studio") throw new Error(`chatConsent.endpoint must be on ${CHAT_CONSENT_ENDPOINT_ORIGIN}, the chat OIDC issuer host where the gateway consumes chat sign-in requests, not ${url.origin}.`);
2300
+ return url.href;
2301
+ }
2302
+ /**
2303
+ * Validate `chatConsent.callbackUrl`: an https URL without credentials, query or fragment.
2304
+ * @param value - the configured callback.
2305
+ * @returns the callback in canonical form (its origin and path).
2306
+ * @throws an Error naming the rule it breaks (never echoing credentials).
2307
+ */
2308
+ function normalizeChatConsentCallbackUrl(value) {
2309
+ return configuredUrl(value, "chatConsent.callbackUrl").href;
2310
+ }
2311
+ /**
2312
+ * Read the plugin's `chatConsent` config. An absent or blank field means its default; any other value must pass its
2313
+ * rule. Nothing is thrown: a setting that breaks a rule is reported, so the plugin can leave the service out and keep
2314
+ * everything else running.
2315
+ * @param value - the `chatConsent` object of the plugin Config.
2316
+ * @returns the canonical endpoint and callback, or the problems, each naming its field and the rule it breaks.
2317
+ */
2318
+ function readChatConsentSettings(value) {
2319
+ const problems = [];
2320
+ const read = (field, raw, fallback, normalize) => {
2321
+ if (raw !== void 0 && raw !== null && typeof raw !== "string") {
2322
+ problems.push(`chatConsent.${field} must be text.`);
2323
+ return;
2324
+ }
2325
+ const text = typeof raw === "string" ? raw.trim() : "";
2326
+ try {
2327
+ return normalize(text === "" ? fallback : text);
2328
+ } catch (error) {
2329
+ problems.push(error instanceof Error ? error.message : `chatConsent.${field} is not valid.`);
2330
+ return;
2331
+ }
2332
+ };
2333
+ const endpoint = read("endpoint", value?.endpoint, DEFAULT_CHAT_CONSENT_ENDPOINT, normalizeChatConsentEndpoint);
2334
+ const callbackUrl = read("callbackUrl", value?.callbackUrl, DEFAULT_CHAT_CONSENT_CALLBACK_URL, normalizeChatConsentCallbackUrl);
2335
+ return endpoint === void 0 || callbackUrl === void 0 ? {
2336
+ ok: false,
2337
+ problems
2338
+ } : {
2339
+ ok: true,
2340
+ endpoint,
2341
+ callbackUrl
2342
+ };
2343
+ }
2344
+ //#endregion
2345
+ //#region src/auth/sign-in-state.ts
2346
+ const REDEEM_PATH = "/api/v1/vibedev/link/redeem";
2347
+ const NETWORK_CODES = /* @__PURE__ */ new Set([
2348
+ "ECONNREFUSED",
2349
+ "ECONNRESET",
2350
+ "ECONNABORTED",
2351
+ "ENOTFOUND",
2352
+ "EAI_AGAIN",
2353
+ "ENETUNREACH",
2354
+ "EHOSTUNREACH",
2355
+ "EPIPE",
2356
+ "ETIMEDOUT",
2357
+ "UND_ERR_CONNECT_TIMEOUT",
2358
+ "UND_ERR_HEADERS_TIMEOUT",
2359
+ "UND_ERR_BODY_TIMEOUT",
2360
+ "UND_ERR_SOCKET",
2361
+ "CERT_HAS_EXPIRED",
2362
+ "DEPTH_ZERO_SELF_SIGNED_CERT",
2363
+ "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
2364
+ "ERR_TLS_CERT_ALTNAME_INVALID"
2365
+ ]);
2366
+ const TIMEOUT_CODES = /* @__PURE__ */ new Set([
2367
+ "ETIMEDOUT",
2368
+ "UND_ERR_CONNECT_TIMEOUT",
2369
+ "UND_ERR_HEADERS_TIMEOUT",
2370
+ "UND_ERR_BODY_TIMEOUT"
2371
+ ]);
2372
+ /** Read only fixed transport codes, never error text, stack, body or arbitrary fields. */
2373
+ function transportFailure(error) {
2374
+ let cause = error;
2375
+ let timeout = false;
2376
+ let networkCode;
2377
+ for (let depth = 0; depth < 5 && typeof cause === "object" && cause !== null; depth++) {
2378
+ const value = cause;
2379
+ if (value.name === "TimeoutError") timeout = true;
2380
+ if (typeof value.code === "string" && NETWORK_CODES.has(value.code)) {
2381
+ networkCode ??= value.code;
2382
+ if (TIMEOUT_CODES.has(value.code)) timeout = true;
2383
+ }
2384
+ cause = value.cause;
2385
+ }
2386
+ return {
2387
+ errorCode: timeout ? "timeout" : "network",
2388
+ ...networkCode === void 0 ? {} : { networkCode }
2389
+ };
2390
+ }
2391
+ const EXPLANATIONS = {
2392
+ network: ["无法连接登录网关,请检查网络后重新登录。", "The sign-in gateway could not be reached. Check the connection and start sign-in again."],
2393
+ timeout: ["登录等待或网关请求已超时,请重新登录。", "Sign-in or the gateway request timed out. Start sign-in again."],
2394
+ "gateway-refused": ["登录网关拒绝了请求,请重新登录。", "The gateway refused the sign-in request. Start sign-in again."],
2395
+ "gateway-unavailable": ["登录网关暂时不可用,请稍后重新登录。", "The sign-in gateway is temporarily unavailable. Start sign-in again later."],
2396
+ protocol: ["登录网关返回了无效的凭据格式,请稍后重新登录。", "The gateway returned an invalid credential response. Start sign-in again later."],
2397
+ storage: ["无法准备或保存本地登录凭据,请检查存储权限后重新登录。", "Local sign-in credentials could not be prepared or saved. Check storage permissions and start sign-in again."],
2398
+ callback: ["无法启动或使用本地登录回调,请重新登录。", "The local sign-in callback could not be started or used. Start sign-in again."]
2399
+ };
2400
+ const STAGES = {
2401
+ listen: ["本地回调监听", "Local callback listener"],
2402
+ device: ["准备本地设备标识", "Preparing the local device identity"],
2403
+ redeem: ["交换登录凭据", "Exchanging sign-in credentials"],
2404
+ persist: ["保存本地凭据", "Saving local credentials"]
2405
+ };
2406
+ /** A fixed bilingual explanation suitable for exposed rejection messages. */
2407
+ function failureMessage(attempt) {
2408
+ const [chinese, english] = EXPLANATIONS[attempt.errorCode ?? "callback"];
2409
+ const stage = attempt.stage === void 0 ? "" : ` ${STAGES[attempt.stage].join(" / ")}; stage=${attempt.stage}.`;
2410
+ const status = attempt.httpStatus === void 0 ? "" : ` HTTP ${attempt.httpStatus}.`;
2411
+ return `${english} ${chinese} errorCode=${attempt.errorCode ?? "callback"}.${stage}${status}`;
2412
+ }
2413
+ const escapeHtml = (text) => text.replace(/[&<>"']/g, (character) => ({
2414
+ "&": "&amp;",
2415
+ "<": "&lt;",
2416
+ ">": "&gt;",
2417
+ "\"": "&quot;",
2418
+ "'": "&#39;"
2419
+ })[character]);
2420
+ /** Only our fixed explanation and escaped safe enum/status fields reach the browser. */
2421
+ function failurePage(attempt) {
2422
+ return `<h1>Sign-in failed.</h1><p>${escapeHtml(failureMessage(attempt))}</p><p>请回到对话重新登录。</p>`;
2423
+ }
2424
+ /** Explicit log allowlist; adding fields to the public attempt never expands log output. */
2425
+ function attemptLog(event, attempt) {
2426
+ return `dsh-vibedev sign-in ${JSON.stringify({
2427
+ event,
2428
+ id: attempt.id,
2429
+ phase: attempt.phase,
2430
+ gatewayOrigin: attempt.gatewayOrigin,
2431
+ path: REDEEM_PATH,
2432
+ ...attempt.stage === void 0 ? {} : { stage: attempt.stage },
2433
+ ...attempt.errorCode === void 0 ? {} : { errorCode: attempt.errorCode },
2434
+ ...attempt.httpStatus === void 0 ? {} : { httpStatus: attempt.httpStatus },
2435
+ ...attempt.networkCode === void 0 ? {} : { networkCode: attempt.networkCode }
2436
+ })}`;
2437
+ }
2438
+ //#endregion
2439
+ //#region src/chat-consent/service.ts
2440
+ /** Default for {@link ChatConsentHostServiceOptions.timeoutMs}. */
2441
+ const DEFAULT_TIMEOUT_MS$2 = 1e4;
2442
+ /**
2443
+ * The largest answer read. The callback itself is at most 1024 characters; a JSON encoder that escapes `&` as `\u0026`
2444
+ * (Go's does) adds a few bytes per parameter, and the margin leaves room for a field or two more.
2445
+ */
2446
+ const MAX_RESPONSE_BYTES$1 = 8192;
2447
+ /**
2448
+ * A VibeDev App access token: `vdat_` and base64url, as the gateway issues it to an App session. The consent route
2449
+ * authenticates nothing else (any other token is refused with APP_TOKEN_INVALID before the request is read).
2450
+ */
2451
+ const APP_TOKEN = /^vdat_[A-Za-z0-9_-]+$/;
2452
+ /**
2453
+ * Whether a credential is a signed-in App account's App Token: the plugin's own sign-in (the VibeDev desktop's account)
2454
+ * or a host account service's token, either way `vdat_…`. A development key never is, whatever it looks like.
2455
+ */
2456
+ function isAppCredential(credential) {
2457
+ return credential.kind !== "key" && APP_TOKEN.test(credential.token);
2458
+ }
2459
+ /** Whether a failed fetch refused a redirect (`redirect: 'error'`; undici rejects with "fetch failed" caused by "unexpected redirect"). */
2460
+ function refusedRedirect(error) {
2461
+ try {
2462
+ let cause = error;
2463
+ for (let depth = 0; depth < 5 && typeof cause === "object" && cause !== null; depth++) {
2464
+ const { message } = cause;
2465
+ if (typeof message === "string" && /\bredirect\b/i.test(message)) return true;
2466
+ cause = cause.cause;
2467
+ }
2468
+ } catch {}
2469
+ return false;
2470
+ }
2471
+ /** Wait for work, ending early with the signal's reason when it aborts; the work itself keeps running. */
2472
+ function untilAborted(work, signal) {
2473
+ return new Promise((resolve, reject) => {
2474
+ const onAbort = () => {
2475
+ reject(signal.reason);
2476
+ };
2477
+ if (signal.aborted) {
2478
+ onAbort();
2479
+ return;
2480
+ }
2481
+ signal.addEventListener("abort", onAbort, { once: true });
2482
+ work.then((value) => {
2483
+ signal.removeEventListener("abort", onAbort);
2484
+ resolve(value);
2485
+ }, (error) => {
2486
+ signal.removeEventListener("abort", onAbort);
2487
+ reject(error);
2488
+ });
2489
+ });
2490
+ }
2491
+ /** Stop reading a body nobody will read. */
2492
+ function discard(response) {
2493
+ response.body?.cancel().catch(() => void 0);
2494
+ }
2495
+ /**
2496
+ * Read a body up to a limit, ending when the signal aborts even if the stream itself would not.
2497
+ * @returns the text, or undefined when the body is (or declares itself) larger than the limit.
2498
+ * @throws the signal's reason when it aborted, or what the stream failed with.
2499
+ */
2500
+ async function readCapped$2(response, limit, signal) {
2501
+ const declared = response.headers.get("content-length");
2502
+ if (declared !== null && !(/^\d+$/.test(declared) && Number(declared) <= limit)) {
2503
+ discard(response);
2504
+ return;
2505
+ }
2506
+ if (response.body === null) return "";
2507
+ const reader = response.body.getReader();
2508
+ let detach = () => void 0;
2509
+ const aborted = new Promise((_resolve, reject) => {
2510
+ const onAbort = () => {
2511
+ reject(signal.reason);
2512
+ };
2513
+ if (signal.aborted) {
2514
+ onAbort();
2515
+ return;
2516
+ }
2517
+ signal.addEventListener("abort", onAbort, { once: true });
2518
+ detach = () => {
2519
+ signal.removeEventListener("abort", onAbort);
2520
+ };
2521
+ });
2522
+ aborted.catch(() => void 0);
2523
+ const chunks = [];
2524
+ let total = 0;
2525
+ try {
2526
+ for (;;) {
2527
+ const next = await Promise.race([reader.read(), aborted]);
2528
+ if (next.done) break;
2529
+ total += next.value.byteLength;
2530
+ if (total > limit) return void 0;
2531
+ chunks.push(next.value);
2532
+ }
2533
+ } finally {
2534
+ detach();
2535
+ reader.cancel().catch(() => void 0);
2536
+ }
2537
+ const bytes = new Uint8Array(total);
2538
+ let offset = 0;
2539
+ for (const chunk of chunks) {
2540
+ bytes.set(chunk, offset);
2541
+ offset += chunk.byteLength;
2542
+ }
2543
+ return new TextDecoder().decode(bytes);
2544
+ }
2545
+ /**
2546
+ * What a refusal says about itself: its JSON body when one can be read within the limit and the time left, and the
2547
+ * gateway's error headers. Never throws: an unreadable body leaves the headers alone.
2548
+ */
2549
+ async function failureOf(response, signal) {
2550
+ let body;
2551
+ try {
2552
+ const text = await readCapped$2(response, MAX_RESPONSE_BYTES$1, signal);
2553
+ body = text === void 0 ? void 0 : JSON.parse(text);
2554
+ } catch {
2555
+ body = void 0;
2556
+ }
2557
+ return gatewayFailureWithHeaders(body, response.headers);
2558
+ }
2559
+ /** The chat consent capability for the VibeDev desktop's Host, registered as `vibedevDesktopChatConsent`. */
2560
+ var ChatConsentHostService = class {
2561
+ options;
2562
+ version = 1;
2563
+ endpoint;
2564
+ callbackUrl;
2565
+ /**
2566
+ * @param options - the endpoint and callback, the account, and where diagnostics go.
2567
+ * @throws an Error when the endpoint is not https on the issuer host, or the callback is not an https URL without
2568
+ * query or fragment: whoever constructs the service, the token cannot be pointed anywhere else.
2569
+ */
2570
+ constructor(options) {
2571
+ this.options = options;
2572
+ this.endpoint = normalizeChatConsentEndpoint(options.endpoint);
2573
+ this.callbackUrl = normalizeChatConsentCallbackUrl(options.callbackUrl);
2574
+ }
2575
+ /**
2576
+ * Post one decision with the signed-in App account's token. Bound to this service, so a caller may also hold and call
2577
+ * the function alone (`const { resolve } = service`).
2578
+ * @param request - the decision; anything that is not a valid request is answered `failed` without a request.
2579
+ * @returns the outcome; the promise never rejects.
2580
+ */
2581
+ resolve = async (request) => {
2582
+ try {
2583
+ return await this.decide(request);
2584
+ } catch {
2585
+ return this.refuse("failed", { reason: "internal" });
2586
+ }
2587
+ };
2588
+ async decide(input) {
2589
+ const request = readChatConsentRequest(input);
2590
+ if (request === void 0) return this.refuse("failed", { reason: "invalid-request" });
2591
+ const owner = this.options.signal;
2592
+ const deadline = AbortSignal.timeout(this.options.timeoutMs ?? DEFAULT_TIMEOUT_MS$2);
2593
+ const signal = owner === void 0 ? deadline : AbortSignal.any([owner, deadline]);
2594
+ let credentialKind;
2595
+ const refuse = (status, diagnostic) => this.refuse(status, credentialKind === void 0 ? diagnostic : {
2596
+ ...diagnostic,
2597
+ credential: credentialKind
2598
+ });
2599
+ const stopped = () => refuse("failed", { reason: owner?.aborted === true ? "unloaded" : "timeout" });
2600
+ if (signal.aborted) return stopped();
2601
+ let identity;
2602
+ try {
2603
+ identity = await untilAborted(this.options.identity(), signal);
2604
+ } catch {
2605
+ return signal.aborted ? stopped() : refuse("failed", { reason: "account-unavailable" });
2606
+ }
2607
+ if (!identity.signedIn) return refuse("signed-out", { reason: "signed-out" });
2608
+ const { credential, userId } = identity;
2609
+ credentialKind = credential.kind;
2610
+ if (!isAppCredential(credential)) return refuse("signed-out", { reason: "not-app-credential" });
2611
+ if (userId === void 0) return refuse("failed", { reason: "account-unknown" });
2612
+ if (userId !== request.subject) return refuse("mismatch", { reason: "subject-mismatch" });
2613
+ if (signal.aborted) return stopped();
2614
+ let response;
2615
+ try {
2616
+ response = await (this.options.fetch ?? globalThis.fetch)(this.endpoint, {
2617
+ method: "POST",
2618
+ headers: {
2619
+ accept: "application/json",
2620
+ authorization: `Bearer ${credential.token}`,
2621
+ "content-type": "application/json",
2622
+ "user-agent": this.options.userAgent
2623
+ },
2624
+ body: JSON.stringify({
2625
+ request: request.handle,
2626
+ approve: request.approve
2627
+ }),
2628
+ redirect: "error",
2629
+ signal
2630
+ });
2631
+ } catch (error) {
2632
+ if (signal.aborted) return stopped();
2633
+ if (refusedRedirect(error)) return refuse("failed", { reason: "redirect" });
2634
+ const failure = transportFailure(error);
2635
+ return refuse("failed", {
2636
+ reason: failure.errorCode === "timeout" ? "timeout" : "network",
2637
+ ...failure.networkCode === void 0 ? {} : { networkCode: failure.networkCode }
2638
+ });
2639
+ }
2640
+ const httpStatus = response.status;
2641
+ if (httpStatus === 401) return refuse("rejected", {
2642
+ reason: "gateway-refused",
2643
+ httpStatus,
2644
+ ...isUserAuthenticationFailure(await failureOf(response, signal)) && this.reportRejected(credential) ? { credentialRejected: true } : {}
2645
+ });
2646
+ if (httpStatus >= 400 && httpStatus < 500) {
2647
+ discard(response);
2648
+ return refuse("rejected", {
2649
+ reason: "gateway-refused",
2650
+ httpStatus
2651
+ });
2652
+ }
2653
+ if (!response.ok) {
2654
+ discard(response);
2655
+ return refuse("failed", {
2656
+ reason: httpStatus >= 500 ? "gateway-unavailable" : "gateway-status",
2657
+ httpStatus
2658
+ });
2659
+ }
2660
+ let body;
2661
+ try {
2662
+ body = await readCapped$2(response, MAX_RESPONSE_BYTES$1, signal);
2663
+ } catch (error) {
2664
+ if (signal.aborted) return stopped();
2665
+ const failure = transportFailure(error);
2666
+ return refuse("failed", {
2667
+ reason: "network",
2668
+ httpStatus,
2669
+ ...failure.networkCode === void 0 ? {} : { networkCode: failure.networkCode }
2670
+ });
2671
+ }
2672
+ if (body === void 0) return refuse("failed", {
2673
+ reason: "response-too-large",
2674
+ httpStatus
2675
+ });
2676
+ let answer;
2677
+ try {
2678
+ answer = JSON.parse(body);
2679
+ } catch {
2680
+ return refuse("failed", {
2681
+ reason: "invalid-response",
2682
+ httpStatus
2683
+ });
2684
+ }
2685
+ const redirect = typeof answer === "object" && answer !== null && !Array.isArray(answer) ? answer.redirect_to : void 0;
2686
+ if (typeof redirect !== "string") return refuse("failed", {
2687
+ reason: "invalid-response",
2688
+ httpStatus
2689
+ });
2690
+ const url = readChatConsentCallback(redirect, request.approve, this.callbackUrl);
2691
+ if (url === void 0) return refuse("failed", {
2692
+ reason: "invalid-callback",
2693
+ httpStatus
2694
+ });
2695
+ return {
2696
+ status: "redirect",
2697
+ url
2698
+ };
2699
+ }
2700
+ /**
2701
+ * Report a rejected credential to its owner without waiting for it, so neither a slow owner nor a failing one changes
2702
+ * the answer.
2703
+ * @returns whether it was reported (there is an owner to tell, and the credential is not a development key).
2704
+ */
2705
+ reportRejected(credential) {
2706
+ const reject = this.options.rejectCredential;
2707
+ if (reject === void 0 || credential.kind === "key") return false;
2708
+ Promise.resolve().then(() => reject(credential)).catch(() => void 0);
2709
+ return true;
2710
+ }
2711
+ /** Answer an outcome other than a redirect, with one diagnostic line of fixed facts. */
2712
+ refuse(status, diagnostic) {
2713
+ try {
2714
+ this.options.log(`dsh-vibedev chat consent ${JSON.stringify({
2715
+ outcome: status,
2716
+ reason: diagnostic.reason,
2717
+ ...diagnostic.httpStatus === void 0 ? {} : { httpStatus: diagnostic.httpStatus },
2718
+ ...diagnostic.networkCode === void 0 ? {} : { networkCode: diagnostic.networkCode },
2719
+ ...diagnostic.credential === void 0 ? {} : { credential: diagnostic.credential },
2720
+ ...diagnostic.credentialRejected === true ? { credentialRejected: true } : {}
2721
+ })}`);
2722
+ } catch {}
2723
+ return { status };
2724
+ }
2725
+ };
2726
+ //#endregion
2727
+ //#region src/chat-consent/install.ts
2728
+ /**
2729
+ * Provide `vibedevDesktopChatConsent` when the settings and the gateway allow it. Otherwise one line says why — an
2730
+ * error for a setting that breaks a rule (each problem names its field and the rule), a notice for a gateway that is
2731
+ * not first-party — and the plugin carries on without the service.
2732
+ * @param ctx - the plugin's context; the service is withdrawn, and a decision still running aborted, when it unloads.
2733
+ * @param options - the gateway origin, the settings, the account and where diagnostics go.
2734
+ * @returns whether the service is provided.
2735
+ */
2736
+ function installChatConsent(ctx, options) {
2737
+ const settings = readChatConsentSettings(options.settings);
2738
+ if (!settings.ok) {
2739
+ ctx.logger.error(`dsh-vibedev: ${DESKTOP_CHAT_CONSENT_SERVICE} is not provided, so the desktop uses web consent instead; the rest of the plugin is unaffected. ${settings.problems.join(" ")}`);
2740
+ return false;
2741
+ }
2742
+ if (!isFirstPartyChatConsentOrigin(options.origin)) {
2743
+ ctx.logger.info(`dsh-vibedev: ${DESKTOP_CHAT_CONSENT_SERVICE} is not provided: ${options.origin} is not a first-party VibeDev gateway, so its credential never goes to the chat consent endpoint`);
2744
+ return false;
2745
+ }
2746
+ const owner = new AbortController();
2747
+ let service;
2748
+ try {
2749
+ service = new ChatConsentHostService({
2750
+ endpoint: settings.endpoint,
2751
+ callbackUrl: settings.callbackUrl,
2752
+ identity: options.identity,
2753
+ rejectCredential: options.rejectCredential,
2754
+ userAgent: options.userAgent,
2755
+ log: options.log,
2756
+ signal: owner.signal
2757
+ });
2758
+ } catch (error) {
2759
+ ctx.logger.error(`dsh-vibedev: ${DESKTOP_CHAT_CONSENT_SERVICE} is not provided: ${error instanceof Error ? error.message : "its settings are not valid."}`);
2760
+ return false;
2761
+ }
2762
+ ctx.effect(() => {
2763
+ const withdraw = ctx.provide(DESKTOP_CHAT_CONSENT_SERVICE, service);
2764
+ return () => {
2765
+ owner.abort();
2766
+ withdraw();
2767
+ };
2768
+ }, "dsh-vibedev: desktop chat consent");
2769
+ return true;
2770
+ }
2771
+ //#endregion
2139
2772
  //#region src/announcements/routes.ts
2140
2773
  /** The Host route the renderer polls. */
2141
2774
  const ANNOUNCEMENTS_ROUTE = "/api/dsh-vibedev/announcements";
@@ -3376,7 +4009,10 @@ const ACCOUNT_PAGES = [
3376
4009
  * idempotency are handled once.
3377
4010
  *
3378
4011
  * The credential is attached only to requests on the gateway origin: upload
3379
- * URLs and third-party links never see it.
4012
+ * URLs and third-party links never see it. The one controlled exception lives
4013
+ * outside this client: `chat-consent/service.ts` posts the App Token to the
4014
+ * configured consent endpoint (`chatConsent.endpoint`), which must be on the
4015
+ * chat OIDC issuer host `https://vibedev.studio`.
3380
4016
  * @module dsh-vibedev/gateway/http
3381
4017
  */
3382
4018
  /** Legacy capacity/backoff codes; none independently proves a billing outcome. */
@@ -4246,9 +4882,13 @@ function developmentKey(origin, name, env = process.env) {
4246
4882
  * key named by an environment variable.
4247
4883
  * @module dsh-vibedev/auth/credentials
4248
4884
  */
4885
+ /** The header `resolveRequestCredential` carries the account token in (`ACCOUNT_TOKEN_HEADER` of the 0.2.3 account service). */
4886
+ const HOST_ACCOUNT_TOKEN_HEADER = "x-dsh-auth-token";
4249
4887
  /** Resolves the credential for each request and routes rejections back to its owner. */
4250
4888
  var CredentialChain = class {
4251
4889
  options;
4890
+ /** The host credential released last through `resolveRequestCredential`, so a rejection can use its own invalidation. */
4891
+ released;
4252
4892
  /**
4253
4893
  * @param options - origin and the three sources.
4254
4894
  */
@@ -4257,7 +4897,7 @@ var CredentialChain = class {
4257
4897
  }
4258
4898
  /** The credential for the next request, or undefined while nobody is signed in. */
4259
4899
  async resolve() {
4260
- const hosted = await this.options.account()?.resolveToken(`${this.options.origin.replace(/\/+$/, "")}/v1/models`).catch(() => void 0);
4900
+ const hosted = await this.hostedToken(`${this.options.origin.replace(/\/+$/, "")}/v1/models`);
4261
4901
  if (hosted !== void 0 && hosted !== "") return {
4262
4902
  token: hosted,
4263
4903
  kind: "account"
@@ -4278,9 +4918,42 @@ var CredentialChain = class {
4278
4918
  * @param credential - the rejected credential.
4279
4919
  */
4280
4920
  async reject(credential) {
4281
- if (credential.kind === "account") await this.options.account()?.rejectToken(credential.token);
4921
+ if (credential.kind === "account") await this.rejectHosted(credential.token);
4282
4922
  else if (credential.kind === "plugin") await this.options.plugin?.reject(credential.token);
4283
4923
  }
4924
+ /**
4925
+ * The host account's token for the gateway, whichever way this DSH release offers it. A host that offers neither
4926
+ * method, or whose lookup fails (synchronously or not), yields nothing and the chain moves on to the plugin's own sign-in.
4927
+ */
4928
+ async hostedToken(url) {
4929
+ const account = this.options.account();
4930
+ if (account === void 0) return void 0;
4931
+ try {
4932
+ if (typeof account.resolveRequestCredential === "function") {
4933
+ const credential = await account.resolveRequestCredential(url);
4934
+ if (credential === void 0) return void 0;
4935
+ const token = credential.headers[HOST_ACCOUNT_TOKEN_HEADER];
4936
+ if (typeof token === "string" && token !== "") {
4937
+ this.released = {
4938
+ token,
4939
+ reject: () => credential.reject()
4940
+ };
4941
+ return token;
4942
+ }
4943
+ }
4944
+ if (typeof account.resolveToken === "function") return await account.resolveToken(url);
4945
+ } catch {}
4946
+ }
4947
+ async rejectHosted(token) {
4948
+ const released = this.released;
4949
+ if (released?.token === token) {
4950
+ this.released = void 0;
4951
+ await released.reject();
4952
+ return;
4953
+ }
4954
+ const account = this.options.account();
4955
+ if (typeof account?.rejectToken === "function") await account.rejectToken(token);
4956
+ }
4284
4957
  };
4285
4958
  /** Credential identity for one gateway; never consult another gateway's record. */
4286
4959
  function gatewayGrantKey(origin) {
@@ -4428,100 +5101,6 @@ function grantStorage(root, credentials, selectedOrigin = DEFAULT_GATEWAY_ORIGIN
4428
5101
  };
4429
5102
  }
4430
5103
  //#endregion
4431
- //#region src/auth/sign-in-state.ts
4432
- const REDEEM_PATH = "/api/v1/vibedev/link/redeem";
4433
- const NETWORK_CODES = /* @__PURE__ */ new Set([
4434
- "ECONNREFUSED",
4435
- "ECONNRESET",
4436
- "ECONNABORTED",
4437
- "ENOTFOUND",
4438
- "EAI_AGAIN",
4439
- "ENETUNREACH",
4440
- "EHOSTUNREACH",
4441
- "EPIPE",
4442
- "ETIMEDOUT",
4443
- "UND_ERR_CONNECT_TIMEOUT",
4444
- "UND_ERR_HEADERS_TIMEOUT",
4445
- "UND_ERR_BODY_TIMEOUT",
4446
- "UND_ERR_SOCKET",
4447
- "CERT_HAS_EXPIRED",
4448
- "DEPTH_ZERO_SELF_SIGNED_CERT",
4449
- "UNABLE_TO_VERIFY_LEAF_SIGNATURE",
4450
- "ERR_TLS_CERT_ALTNAME_INVALID"
4451
- ]);
4452
- const TIMEOUT_CODES = /* @__PURE__ */ new Set([
4453
- "ETIMEDOUT",
4454
- "UND_ERR_CONNECT_TIMEOUT",
4455
- "UND_ERR_HEADERS_TIMEOUT",
4456
- "UND_ERR_BODY_TIMEOUT"
4457
- ]);
4458
- /** Read only fixed transport codes, never error text, stack, body or arbitrary fields. */
4459
- function transportFailure(error) {
4460
- let cause = error;
4461
- let timeout = false;
4462
- let networkCode;
4463
- for (let depth = 0; depth < 5 && typeof cause === "object" && cause !== null; depth++) {
4464
- const value = cause;
4465
- if (value.name === "TimeoutError") timeout = true;
4466
- if (typeof value.code === "string" && NETWORK_CODES.has(value.code)) {
4467
- networkCode ??= value.code;
4468
- if (TIMEOUT_CODES.has(value.code)) timeout = true;
4469
- }
4470
- cause = value.cause;
4471
- }
4472
- return {
4473
- errorCode: timeout ? "timeout" : "network",
4474
- ...networkCode === void 0 ? {} : { networkCode }
4475
- };
4476
- }
4477
- const EXPLANATIONS = {
4478
- network: ["无法连接登录网关,请检查网络后重新登录。", "The sign-in gateway could not be reached. Check the connection and start sign-in again."],
4479
- timeout: ["登录等待或网关请求已超时,请重新登录。", "Sign-in or the gateway request timed out. Start sign-in again."],
4480
- "gateway-refused": ["登录网关拒绝了请求,请重新登录。", "The gateway refused the sign-in request. Start sign-in again."],
4481
- "gateway-unavailable": ["登录网关暂时不可用,请稍后重新登录。", "The sign-in gateway is temporarily unavailable. Start sign-in again later."],
4482
- protocol: ["登录网关返回了无效的凭据格式,请稍后重新登录。", "The gateway returned an invalid credential response. Start sign-in again later."],
4483
- storage: ["无法准备或保存本地登录凭据,请检查存储权限后重新登录。", "Local sign-in credentials could not be prepared or saved. Check storage permissions and start sign-in again."],
4484
- callback: ["无法启动或使用本地登录回调,请重新登录。", "The local sign-in callback could not be started or used. Start sign-in again."]
4485
- };
4486
- const STAGES = {
4487
- listen: ["本地回调监听", "Local callback listener"],
4488
- device: ["准备本地设备标识", "Preparing the local device identity"],
4489
- redeem: ["交换登录凭据", "Exchanging sign-in credentials"],
4490
- persist: ["保存本地凭据", "Saving local credentials"]
4491
- };
4492
- /** A fixed bilingual explanation suitable for exposed rejection messages. */
4493
- function failureMessage(attempt) {
4494
- const [chinese, english] = EXPLANATIONS[attempt.errorCode ?? "callback"];
4495
- const stage = attempt.stage === void 0 ? "" : ` ${STAGES[attempt.stage].join(" / ")}; stage=${attempt.stage}.`;
4496
- const status = attempt.httpStatus === void 0 ? "" : ` HTTP ${attempt.httpStatus}.`;
4497
- return `${english} ${chinese} errorCode=${attempt.errorCode ?? "callback"}.${stage}${status}`;
4498
- }
4499
- const escapeHtml = (text) => text.replace(/[&<>"']/g, (character) => ({
4500
- "&": "&amp;",
4501
- "<": "&lt;",
4502
- ">": "&gt;",
4503
- "\"": "&quot;",
4504
- "'": "&#39;"
4505
- })[character]);
4506
- /** Only our fixed explanation and escaped safe enum/status fields reach the browser. */
4507
- function failurePage(attempt) {
4508
- return `<h1>Sign-in failed.</h1><p>${escapeHtml(failureMessage(attempt))}</p><p>请回到对话重新登录。</p>`;
4509
- }
4510
- /** Explicit log allowlist; adding fields to the public attempt never expands log output. */
4511
- function attemptLog(event, attempt) {
4512
- return `dsh-vibedev sign-in ${JSON.stringify({
4513
- event,
4514
- id: attempt.id,
4515
- phase: attempt.phase,
4516
- gatewayOrigin: attempt.gatewayOrigin,
4517
- path: REDEEM_PATH,
4518
- ...attempt.stage === void 0 ? {} : { stage: attempt.stage },
4519
- ...attempt.errorCode === void 0 ? {} : { errorCode: attempt.errorCode },
4520
- ...attempt.httpStatus === void 0 ? {} : { httpStatus: attempt.httpStatus },
4521
- ...attempt.networkCode === void 0 ? {} : { networkCode: attempt.networkCode }
4522
- })}`;
4523
- }
4524
- //#endregion
4525
5104
  //#region src/auth/login.ts
4526
5105
  /**
4527
5106
  * The plugin's own VibeDev sign-in, for hosts whose account service does not
@@ -5089,7 +5668,12 @@ var PluginLogin = class {
5089
5668
  const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20971520;
5090
5669
  /** Total-pixel budget that preserves the complete 2048px normalized attachment. */
5091
5670
  const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 4194304;
5092
- /** Raw encoded-byte target before inline base64 expansion. */
5671
+ /**
5672
+ * Raw encoded bytes allowed for one request image, before inline base64 expansion. A hard limit under DSH 0.2.3 (a larger
5673
+ * encoding is shrunk further; that is also the preferred size) and a target under rc.5. DSH's pi-ai default is 0.75 MiB
5674
+ * (a 20 MiB request over 20 images); 1 MiB keeps what 0.11.0 sent, and the oldest images are offloaded when the request
5675
+ * exceeds `DEFAULT_MAX_REQUEST_IMAGE_BYTES`.
5676
+ */
5093
5677
  const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1048576;
5094
5678
  //#endregion
5095
5679
  //#region src/llm/relay.ts
@@ -5534,6 +6118,9 @@ function toPiAssistant(message, onDegrade) {
5534
6118
  * image-limit import moved to ./limits.ts,
5535
6119
  * so the gateway adapter can choose a wire protocol per model. Keep it in step with upstream.
5536
6120
  *
6121
+ * Kept in step with 0.2.3 for what changes at run time: the request-image target (see `requestImageTarget`) and the text of a
6122
+ * system message (see `systemText`).
6123
+ *
5537
6124
  * Harness request-history conversion into pi-ai's Context vocabulary.
5538
6125
  *
5539
6126
  * @module dsh-llm-pi-ai/context
@@ -5542,6 +6129,16 @@ function toPiAssistant(message, onDegrade) {
5542
6129
  function flattenText(message) {
5543
6130
  return message.content.filter((block) => block.type === "text").map((block) => block.text).join("");
5544
6131
  }
6132
+ /**
6133
+ * The text of a system message: each text block trimmed, empty ones dropped, the rest joined with blank lines.
6134
+ * DSH 0.2.3 stores one system message as one trimmed text block per prompt section and leaves the separators to the
6135
+ * adapter (rc.5 stored the whole prompt as a single block, which this leaves as it was but for its outer whitespace).
6136
+ * Joining the blocks with nothing, as `flattenText` does, would run the sections together.
6137
+ * Same as `systemText` of DSH's own pi-ai adapter.
6138
+ */
6139
+ function systemText(message) {
6140
+ return message.content.filter((block) => block.type === "text").map((block) => block.text.trim()).filter((text) => text.length > 0).join("\n\n");
6141
+ }
5545
6142
  /** Recover the pi-ai toolResult message for one harness tool-role message. */
5546
6143
  function toolResultOf(message, toolNames, content) {
5547
6144
  return {
@@ -5614,25 +6211,21 @@ function toolsOf(options) {
5614
6211
  }
5615
6212
  /**
5616
6213
  * Select the pi-ai `systemPrompt` source shared by both conversion paths.
5617
- * `options.system` wins when defined and every history message converts,
5618
- * including a leading `system` message, which then folds into a `user`
5619
- * message. Otherwise a leading `system` history message supplies the prompt
5620
- * and leaves the converted history; empty leading text sends no prompt.
6214
+ * `options.system`, when defined, comes first; every leading `system` history message follows it, all joined with
6215
+ * blank lines, and those messages leave the converted history. Empty text sends no prompt.
5621
6216
  */
5622
6217
  function splitSystemPrompt(options) {
5623
- if (options.system !== void 0) return {
5624
- systemPrompt: options.system,
5625
- messages: options.messages
5626
- };
5627
- const [first, ...rest] = options.messages;
5628
- if (first?.role !== "system") return {
5629
- systemPrompt: void 0,
5630
- messages: options.messages
5631
- };
5632
- const text = flattenText(first);
6218
+ const text = [options.system];
6219
+ let end = 0;
6220
+ for (const message of options.messages) {
6221
+ if (message.role !== "system") break;
6222
+ text.push(systemText(message));
6223
+ end++;
6224
+ }
6225
+ const systemPrompt = text.filter(Boolean).join("\n\n");
5633
6226
  return {
5634
- systemPrompt: text.length > 0 ? text : void 0,
5635
- messages: rest
6227
+ systemPrompt: systemPrompt.length > 0 ? systemPrompt : void 0,
6228
+ messages: options.messages.slice(end)
5636
6229
  };
5637
6230
  }
5638
6231
  /** Assemble the request-level pi-ai context envelope shared by both conversion paths. */
@@ -5652,11 +6245,15 @@ function appendAssistant(message, messages, toolNames, onReplayDegrade) {
5652
6245
  /** Append the system and assistant roles both context builders treat identically; true when consumed. */
5653
6246
  function appendSystemOrAssistant(message, messages, toolNames, onReplayDegrade) {
5654
6247
  if (message.role === "system") {
5655
- messages.push({
5656
- role: "user",
5657
- content: flattenText(message),
5658
- timestamp: 0
5659
- });
6248
+ const content = systemText(message);
6249
+ if (content.length > 0) {
6250
+ const reminder = content.replaceAll("</system-reminder>", "<\\/system-reminder>");
6251
+ messages.push({
6252
+ role: "user",
6253
+ content: `<system-reminder>\n${reminder}\n</system-reminder>`,
6254
+ timestamp: 0
6255
+ });
6256
+ }
5660
6257
  return true;
5661
6258
  }
5662
6259
  if (message.role === "assistant") {
@@ -5685,11 +6282,17 @@ function textOnlyContext(options, onReplayDegrade) {
5685
6282
  }
5686
6283
  return piContext(split.systemPrompt, options, messages);
5687
6284
  }
5688
- /** Deterministic request target for one source under the route budgets. */
6285
+ /**
6286
+ * Deterministic request target for one source under the route budgets.
6287
+ * Assigned to `ImageRequestTarget` of whichever `@deepseek-ai/dsh-attachment` the host runs: the declared type
6288
+ * changed in 0.2.3, and the object satisfies both.
6289
+ */
5689
6290
  function requestImageTarget(ref, budget) {
5690
6291
  return {
5691
6292
  ...requestImageDimensions(ref.width, ref.height, budget.maxPixels),
5692
- maxBytes: budget.maxBytes
6293
+ maxBytes: budget.maxBytes,
6294
+ maxImageBytes: budget.maxBytes,
6295
+ imageTargetBytes: budget.maxBytes
5693
6296
  };
5694
6297
  }
5695
6298
  function toPiContext(options, images, onReplayDegrade) {
@@ -6704,6 +7307,12 @@ function _usingCtx() {
6704
7307
  * raise its sign-in prompt; the chat shows this failure's own message.
6705
7308
  */
6706
7309
  const SIGN_IN_REQUIRED_CODE = "VIBEDEV_SIGN_IN_REQUIRED";
7310
+ /**
7311
+ * LlmError's constructor takes only built-in codes in DSH 0.2.3's types, though it accepts any non-empty string at run time
7312
+ * (0.2.2-rc.5 and 0.2.3 alike; LlmError.fromFailure is the upstream route for a foreign code but rc.5 lacks it). The
7313
+ * plugin's own code is therefore passed through the constructor's parameter type, which is a cast that holds in both.
7314
+ */
7315
+ const SIGN_IN_REQUIRED_LLM_CODE = SIGN_IN_REQUIRED_CODE;
6707
7316
  /** Failure code for a used-up balance; not the Harness's `ACCOUNT_QUOTA`, which opens the DeepSeek top-up. */
6708
7317
  const INSUFFICIENT_BALANCE_CODE = "VIBEDEV_INSUFFICIENT_BALANCE";
6709
7318
  /** No promotions apply, shared so an unlabelled listing allocates nothing. */
@@ -6799,7 +7408,7 @@ var GatewayAdapter = class extends LlmAdapter {
6799
7408
  }
6800
7409
  modelOf(snapshot, provider, id) {
6801
7410
  this.assertOwned(provider);
6802
- if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
7411
+ if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_LLM_CODE);
6803
7412
  const catalog = snapshot.byId.get(id);
6804
7413
  const model = snapshot.models.getModel(provider, id);
6805
7414
  if (catalog === void 0 || model === void 0) throw new LlmError(`VibeDev has no model "${id}"`, "UNKNOWN_MODEL");
@@ -6808,6 +7417,18 @@ var GatewayAdapter = class extends LlmAdapter {
6808
7417
  catalog
6809
7418
  };
6810
7419
  }
7420
+ /**
7421
+ * The request-image target for a stored image: the one `toPiContext` reads the request version with, from the same
7422
+ * function and the same budgets. Computer Use asks for it to size and encode a screenshot and to map coordinates onto
7423
+ * the image the model sees; the base class returns the source size, which would let `toPiContext` shrink the
7424
+ * screenshot again afterwards and put the model's coordinates out of step with the tool's.
7425
+ */
7426
+ imageRequestTarget(_provider, _model, image) {
7427
+ return requestImageTarget(image, {
7428
+ maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET,
7429
+ maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7430
+ });
7431
+ }
6811
7432
  providerInfo(provider) {
6812
7433
  this.assertOwned(provider);
6813
7434
  const relay = this.config.relayProvider;
@@ -6897,7 +7518,7 @@ var GatewayAdapter = class extends LlmAdapter {
6897
7518
  const starting = startingReasoning(catalog);
6898
7519
  const reasoning = resolveReasoningLevel(model, options.reasoningEffort ?? (starting === void 0 ? void 0 : effortOf(starting)));
6899
7520
  let credential = await this.config.resolveCredential();
6900
- if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
7521
+ if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_LLM_CODE);
6901
7522
  const sessionId = options.sessionId === void 0 ? void 0 : String(options.sessionId);
6902
7523
  const deviceId = model.api === "anthropic-messages" && sessionId !== void 0 ? await this.config.deviceId?.() : void 0;
6903
7524
  const consumer = new AbortController();
@@ -15312,6 +15933,10 @@ const Config = Schema.object({
15312
15933
  client: Schema.string().default("vibedev-plugin"),
15313
15934
  primary: Schema.boolean().default(false),
15314
15935
  gatewayFetch: Schema.boolean().default(false),
15936
+ chatConsent: Schema.object({
15937
+ endpoint: Schema.string().default(DEFAULT_CHAT_CONSENT_ENDPOINT),
15938
+ callbackUrl: Schema.string().default(DEFAULT_CHAT_CONSENT_CALLBACK_URL)
15939
+ }),
15315
15940
  apiKeyEnv: Schema.string().default(""),
15316
15941
  stateDir: Schema.string().default("")
15317
15942
  }).i18n({
@@ -15338,6 +15963,11 @@ const Config = Schema.object({
15338
15963
  client: "登录时报给网关的客户端名称(决定用量记在哪个密钥下)",
15339
15964
  primary: "作为应用的主账号:侧边栏底部的账号行和设置里的第一个分区(VibeDev 应用)",
15340
15965
  gatewayFetch: "把网关的抽取式抓取注册为 vibedev-gateway 提供方(注册不等于启用:仍需在 web 行选择 fetchProvider;默认关闭)",
15966
+ chatConsent: {
15967
+ $description: "VibeDev 桌面「消息」的一次授权(vibedevDesktopChatConsent)。留空用默认值;不合规则时只是不提供这个服务(Host 日志写明字段和规则),插件其余功能照常",
15968
+ endpoint: "授权接口:接收已登录 App 账号的令牌,必须是 https 且在聊天 OIDC 签发方主机 https://vibedev.studio 上(网关只在那里处理授权请求)",
15969
+ callbackUrl: "Matrix 回调地址(https,只含源和路径):网关返回的回调必须与它一致"
15970
+ },
15341
15971
  apiKeyEnv: "开发用密钥所在的环境变量(仅在未登录时使用)",
15342
15972
  stateDir: "插件数据目录(留空为默认)"
15343
15973
  },
@@ -15364,6 +15994,11 @@ const Config = Schema.object({
15364
15994
  client: "Client name reported to the gateway at sign-in (decides which key the usage is recorded under)",
15365
15995
  primary: "Act as the main account of the app: the account row at the foot of the sidebar and the first Settings section (the VibeDev app)",
15366
15996
  gatewayFetch: "Register the gateway's extracted-content Fetch as the provider `vibedev-gateway` (registration does not select it: the web row still sets `fetchProvider`; off by default)",
15997
+ chatConsent: {
15998
+ $description: "One-step chat sign-in for VibeDev desktop Messages (vibedevDesktopChatConsent). Blank means the default; a value that breaks its rule only leaves this service out (the Host log names the field and the rule), and the rest of the plugin runs as usual",
15999
+ endpoint: "Consent endpoint: receives the signed-in App account's token; https on the chat OIDC issuer host https://vibedev.studio (the gateway handles consent there alone)",
16000
+ callbackUrl: "Matrix callback (https, origin and path only): every callback the gateway answers must match it"
16001
+ },
15367
16002
  apiKeyEnv: "Environment variable with a development key (used only while signed out)",
15368
16003
  stateDir: "Plugin data folder (empty for the default)"
15369
16004
  }
@@ -15566,6 +16201,14 @@ function apply(ctx, config) {
15566
16201
  refreshCatalog: () => route?.refresh() ?? Promise.resolve()
15567
16202
  });
15568
16203
  account = accountService;
16204
+ installChatConsent(ctx, {
16205
+ origin,
16206
+ settings: config.chatConsent,
16207
+ identity: () => accountService.identity(),
16208
+ rejectCredential: (credential) => chain.reject(credential),
16209
+ userAgent,
16210
+ log: warn
16211
+ });
15569
16212
  const latency = new LatencyProbe({
15570
16213
  origin,
15571
16214
  userAgent
@@ -15630,6 +16273,6 @@ function apply(ctx, config) {
15630
16273
  });
15631
16274
  }
15632
16275
  //#endregion
15633
- export { ACCOUNT_ROUTE_PREFIX, AccountService, Config, ContentError, ContentHostService, FEEDBACK_ATTACHMENT_ROUTE, FEEDBACK_ROUTE, GATEWAY_FETCH_PROVIDER_ID as FETCH_PROVIDER_ID, GatewayFetchProvider, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, NegotiatedGatewayFetchProvider, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_RELAY_ROUTE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, readGatewayFetchCapability, version };
16276
+ export { ACCOUNT_ROUTE_PREFIX, AccountService, CHAT_CONSENT_ENDPOINT_ORIGIN, CHAT_CONSENT_FIRST_PARTY_ORIGINS, CHAT_CONSENT_MAX_CALLBACK_LENGTH, CHAT_CONSENT_VERSION, ChatConsentHostService, Config, ContentError, ContentHostService, DEFAULT_CHAT_CONSENT_CALLBACK_URL, DEFAULT_CHAT_CONSENT_ENDPOINT, DESKTOP_CHAT_CONSENT_SERVICE, FEEDBACK_ATTACHMENT_ROUTE, FEEDBACK_ROUTE, GATEWAY_FETCH_PROVIDER_ID as FETCH_PROVIDER_ID, GatewayFetchProvider, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, NegotiatedGatewayFetchProvider, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_RELAY_ROUTE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, readChatConsentCallback, readChatConsentRequest, readChatConsentResult, readGatewayFetchCapability, version };
15634
16277
 
15635
16278
  //# sourceMappingURL=index.js.map