dsh-workbuddy-bridge 0.5.9 → 0.5.11

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
@@ -1,4 +1,4 @@
1
- import { $ as validAppVersion, A as modelWithCurrentPromotion, B as upstreamDisplayMessage, C as variantFor, D as WorkBuddyUpstreamClient, F as regionOf, G as readCliVersion, H as FALLBACK_CN_APP_VERSION, I as PROBE_EFFORT_CANDIDATES, J as WORKBUDDY_APP_VERSION_FILENAME, K as resolveChatIdentity, L as probeModel, M as parseModelCatalog, N as prepareChatBody, O as isChannelGateBody, P as prepareInternationalChatBody, Q as resolveAppVersion, R as randomSentinel, S as WORKBUDDY_VARIANTS, U as chatUserAgent, V as CN_APP_VERSION_FILENAME, W as fallbackChatIdentity, X as installedAppVersion, Y as appUserAgent, Z as readBundleVersion, _ as desktopAuthCandidatesFor, a as readHostHeartbeat, b as AI_VARIANT, c as WORKBUDDY_BRIDGE_VERSION, d as WorkBuddyCatalog, f as WORKBUDDY_AUTH_FILENAME, g as defaultDesktopAuthPath, h as defaultDesktopAuthCandidates, i as processStartTimeMs, j as normalizeCredits, k as isPlanLimitBody, l as FALLBACK_WORKBUDDY_AI_MODELS, m as WorkBuddyCredentialStore, n as clearHostHeartbeat, o as workbuddyHostHeartbeatPath, p as WORKBUDDY_AUTH_FILE_ENV, q as validCliVersion, r as isHeartbeatProcessAlive, s as writeHostHeartbeat, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, u as FALLBACK_WORKBUDDY_MODELS, v as parseWorkBuddyAuth, w as WORKBUDDY_CREDIT_PATH, x as CN_VARIANT, y as workbuddyOwnAuthPath, z as classifyUpstreamError } from "./heartbeat-36zt0_g0.js";
1
+ import { $ as readBundleVersion, A as isPlanLimitBody, B as randomSentinel, C as variantFor, D as WorkBuddyUpstreamClient, F as prepareChatRequest, G as chatUserAgent, H as upstreamDisplayMessage, I as prepareInternationalChatBody, J as resolveChatIdentity, K as fallbackChatIdentity, L as regionOf, M as normalizeCredits, N as parseModelCatalog, O as cacheConversationId, P as prepareChatBody, Q as installedAppVersion, R as PROBE_EFFORT_CANDIDATES, S as WORKBUDDY_VARIANTS, U as CN_APP_VERSION_FILENAME, V as classifyUpstreamError, W as FALLBACK_CN_APP_VERSION, X as WORKBUDDY_APP_VERSION_FILENAME, Y as validCliVersion, Z as appUserAgent, _ as desktopAuthCandidatesFor, a as readHostHeartbeat, b as AI_VARIANT, c as WORKBUDDY_BRIDGE_VERSION, d as WorkBuddyCatalog, et as resolveAppVersion, f as WORKBUDDY_AUTH_FILENAME, g as defaultDesktopAuthPath, h as defaultDesktopAuthCandidates, i as processStartTimeMs, j as modelWithCurrentPromotion, k as isChannelGateBody, l as FALLBACK_WORKBUDDY_AI_MODELS, m as WorkBuddyCredentialStore, n as clearHostHeartbeat, o as workbuddyHostHeartbeatPath, p as WORKBUDDY_AUTH_FILE_ENV, q as readCliVersion, r as isHeartbeatProcessAlive, s as writeHostHeartbeat, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as validAppVersion, u as FALLBACK_WORKBUDDY_MODELS, v as parseWorkBuddyAuth, w as WORKBUDDY_CREDIT_PATH, x as CN_VARIANT, y as workbuddyOwnAuthPath, z as probeModel } from "./heartbeat-BE0IAXli.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { dirname, join, resolve } from "node:path";
4
4
  import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
@@ -337,842 +337,849 @@ function resolveDefaultEffort(info, offered) {
337
337
  return offered.includes("high") ? "high" : offered[0];
338
338
  }
339
339
  //#endregion
340
- //#region src/llm/adapter.ts
340
+ //#region src/llm/loopback.ts
341
341
  /**
342
- * The `workbuddy` pi-ai provider: one loopback-backed adapter registered
343
- * into the Harness LLM seam, assembled from public `dsh-llm-pi-ai`
344
- * extension points the way `dsh-codex-connect` assembles its Codex route.
342
+ * Shared loopback gates for the plugin's local HTTP surfaces: the loopback
343
+ * shim and the same-origin web-status route. Both are only ever meant to be
344
+ * addressed through the machine's loopback interface.
345
345
  *
346
- * @module dsh-workbuddy-bridge/adapter
346
+ * @module dsh-workbuddy-bridge/loopback
347
347
  */
348
- /** Provider route this bundle owns. */
349
- const WORKBUDDY_PROVIDER = "workbuddy";
350
- /** Provider idle ceiling while one stream read is outstanding. */
351
- const WORKBUDDY_STREAM_IDLE_TIMEOUT_MS = 3e5;
348
+ /** Loopback hostnames a local plugin surface may be addressed by. */
349
+ const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
350
+ "127.0.0.1",
351
+ "localhost",
352
+ "[::1]"
353
+ ]);
354
+ /** Strip the optional :port from a Host header value, IPv6-bracket aware. */
355
+ function hostnameOfHost(host) {
356
+ let hostname = host.trim().toLowerCase();
357
+ if (hostname.startsWith("[")) {
358
+ const end = hostname.indexOf("]");
359
+ return end === -1 ? hostname : hostname.slice(0, end + 1);
360
+ }
361
+ const colon = hostname.lastIndexOf(":");
362
+ if (colon !== -1 && !hostname.slice(0, colon).includes(":") && /^\d+$/.test(hostname.slice(colon + 1))) hostname = hostname.slice(0, colon);
363
+ return hostname;
364
+ }
352
365
  /**
353
- * Image-request budgets at the dsh-llm-pi-ai defaults; the profile type made
354
- * them required in 0.1.1-rc.2. They bound requests to models whose catalog
355
- * entry declares `supportsImages`; text-only models never receive images.
356
- *
357
- * The **retained-count** pair joined them in the 0.2.2 rc line, with the same
358
- * defaults the host's own config schema applies: at most 50 image occurrences
359
- * per request, overflowing 10 at a time. Both are whole-request bounds on a
360
- * deterministic inline request version, so the route simply adopts the host's
361
- * defaults rather than inventing tighter ones — crossing them would rewrite
362
- * the request prefix, which this route never has a reason to do.
366
+ * The request's Host header must name the loopback interface. A DNS-rebinding
367
+ * page (attacker domain re-resolved to 127.0.0.1) sends its own domain in
368
+ * Host, so this check drops those before any routing happens.
363
369
  */
364
- const REQUEST_IMAGE_BUDGETS = {
365
- maxRequestImageBytes: 20971520,
366
- maxRequestImages: 50,
367
- imageOffloadCountQuantum: 10,
368
- requestImagePixelBudget: 4194304,
369
- requestImageMaxBytes: 1048576
370
- };
370
+ function hostIsLoopback(host) {
371
+ if (host === void 0 || host.trim() === "") return false;
372
+ return LOOPBACK_HOSTS.has(hostnameOfHost(host));
373
+ }
371
374
  /**
372
- * Inert pi-ai auth plane. The workbuddy route authenticates only through the
373
- * shim shared secret resolved per request by `resolveApiKey`, so pi-ai's own
374
- * credential lifecycle and ambient discovery must never manufacture a
375
- * credential for it. `PiAiAdapterOptions.auth` is required since 0.1.1-rc.2;
376
- * every ambient question here answers "nothing stored, nothing set".
375
+ * A browser-sent Origin (present header) must be loopback. Non-browser
376
+ * clients (the plugin's own fetch calls) send no Origin at all and pass.
377
377
  */
378
- const INERT_AUTH = {
379
- credentials: {
380
- async read() {},
381
- async list() {
382
- return [];
383
- },
384
- async modify() {
385
- throw new Error("dsh-workbuddy-bridge: the workbuddy route has no pi-ai credential lifecycle");
386
- },
387
- async delete() {}
388
- },
389
- authContext: {
390
- async env() {},
391
- async fileExists() {
392
- return false;
393
- }
378
+ function originIsLoopback(origin) {
379
+ if (origin === void 0 || origin.trim() === "") return true;
380
+ try {
381
+ const { hostname } = new URL(origin);
382
+ return LOOPBACK_HOSTS.has(hostname) || hostname === "::1";
383
+ } catch {
384
+ return false;
394
385
  }
395
- };
396
- /** No per-token pricing is knowable for a subscription quota; report zero. */
397
- const NO_COST = {
398
- input: 0,
399
- output: 0,
400
- cacheRead: 0,
401
- cacheWrite: 0
402
- };
386
+ }
387
+ //#endregion
388
+ //#region src/llm/shim.ts
403
389
  /**
404
- * The suffix appended to a model's display name so its billing rate is visible
405
- * wherever the name is shown.
390
+ * Loopback OpenAI-compatible endpoint. The pi-ai provider points here; the
391
+ * shim applies the WorkBuddy wire quirks (forced streaming, string
392
+ * `tool_choice`, CLI-shaped headers) and forwards to the real upstream.
393
+ * It binds 127.0.0.1 only and never serves another interface.
406
394
  *
407
- * The separator is a middle dot rather than a hyphen or colon: model names
408
- * already contain hyphens (`GLM-5.3-Flash`, `Deepseek-V4-Flash`), so a hyphen
409
- * separator would be ambiguous about where the name ends and the rate begins.
395
+ * Inbound hardening: the loopback bind alone is not a trust boundary (any
396
+ * local process or a DNS-rebinding page can reach 127.0.0.1), so every
397
+ * request must carry a loopback Host header, browser-sent Origins must be
398
+ * loopback, chat POSTs must be application/json, and the Authorization
399
+ * header must carry the shim's per-process shared secret. The plugin's
400
+ * own client satisfies all four by construction; local attackers cannot
401
+ * read the secret out of the plugin process's memory.
402
+ *
403
+ * @module dsh-workbuddy-bridge/shim
410
404
  */
411
- const RATE_SEPARATOR = " · ";
405
+ const REQUEST_BODY_LIMIT = 67108864;
406
+ /** Opaque DSH session key on the authenticated adapter-to-shim hop only. */
407
+ const CACHE_SESSION_HEADER = "x-workbuddy-cache-session";
412
408
  /**
413
- * Append the billing rate to one model's display name.
409
+ * Pull the response id and `credit` out of one SSE `data:` payload.
414
410
  *
415
- * The rate AND the declared promo badges ride the *name* alone: since DSH
416
- * 0.1.2 the composer's model seat (`ModelSelect`) renders `model.name` only —
417
- * `description` is no longer read there at all (the 0.1.1-era client rendered
418
- * it, which is why the badges used to be visible in the seat). The `/model`
419
- * popup renders the name too, so a separate `description` copy would either
420
- * duplicate (rate) or vanish (badges) depending on client generation.
411
+ * WorkBuddy's OpenAI-compatible stream reports what a message cost as an extra
412
+ * `credit` member beside the standard token buckets on the final usage frame
413
+ * (measured: `glm-5.3` answering 900 tokens reported `credit: 0.51`). The
414
+ * member is not part of the OpenAI schema, so it is read defensively off the
415
+ * parsed object rather than through any typed shape, and every frame without a
416
+ * usable number is skipped.
421
417
  *
422
- * This is display-only and cannot affect routing: the wire request is built
423
- * from `model.id` (pi-ai's completions API sets `model: model.id`), the
424
- * selection a picker submits is `{provider, model: id, reasoningEffort}`, and
425
- * `dsh-llm` validates `name` as a non-empty string without comparing its
426
- * contents. Nothing in the host resolves a model *by* name.
427
- */
428
- /**
429
- * The catalog display suffix: the billing rate followed by the declared promo
430
- * badges (`限时免费`, `夜间折扣`), or undefined when the row carries neither.
431
- * The badge labels are the upstream's own spellings and the host seam has no
432
- * locale service, so non-Chinese UIs see them verbatim — accepted until the
433
- * picker grows a localized badge slot.
418
+ * @param payload - the text after `data: ` on one frame.
419
+ * @returns the response id and credit, or undefined when this frame carries none.
434
420
  */
435
- function displaySuffix(info) {
436
- const parts = [normalizeCredits(info.billing?.credits), ...info.billing?.badges ?? []].filter((part) => part !== void 0 && part !== "");
437
- return parts.length === 0 ? void 0 : parts.join(" · ");
438
- }
439
- /** Append the catalog display suffix to one model's display name. */
440
- function withCatalogDisplay(name, info) {
441
- const suffix = displaySuffix(info);
442
- return suffix === void 0 ? name : `${name}${RATE_SEPARATOR}${suffix}`;
421
+ function readCreditFrame(payload) {
422
+ if (payload === "" || payload.startsWith("[DONE]")) return void 0;
423
+ let parsed;
424
+ try {
425
+ parsed = JSON.parse(payload);
426
+ } catch {
427
+ return;
428
+ }
429
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
430
+ const frame = parsed;
431
+ const id = typeof frame["id"] === "string" ? frame["id"] : "";
432
+ if (id === "") return void 0;
433
+ const usage = frame["usage"];
434
+ if (typeof usage !== "object" || usage === null || Array.isArray(usage)) return void 0;
435
+ const credit = usage["credit"];
436
+ if (typeof credit !== "number" || !Number.isFinite(credit) || credit < 0) return void 0;
437
+ return {
438
+ id,
439
+ credit
440
+ };
443
441
  }
444
442
  /**
445
- * Translate a model's resolved thinking-level switch into pi-ai's
446
- * `thinkingLevelMap` (every level pinned to its wire spelling or `null` for
447
- * unsupported), mirroring `dsh-llm-pi-ai`'s own `resolveModelReasoning`.
448
- *
449
- * The *decision* of which levels a model offers is not made here — it lives in
450
- * {@link resolveEfforts}, which the status document reads too. That sharing is
451
- * the point: the composer's bulb is lit from the same answer the picker is
452
- * built from, so a model cannot show a control in one place and none in the
453
- * other. This function only reshapes that answer for pi-ai.
443
+ * Split a raw chunk into complete SSE `data:` payloads, carrying the trailing
444
+ * partial line into the next chunk.
454
445
  *
455
- * The offered set is described internally as "verified accepted", never as
456
- * "verified effective": acceptance proves the upstream did not reject the
457
- * spelling, not that it changes what the model does.
446
+ * A TCP read boundary lands wherever it likes — mid-JSON, mid-line — so
447
+ * scanning each chunk on its own would parse a truncated object and drop the
448
+ * very frame that carries the cost. The remainder is returned for the caller to
449
+ * prepend.
458
450
  *
459
- * `off` is a picker name, not a wire spelling. It stays pinned to the literal
460
- * `'off'` (a `null` here would remove the level from the picker entirely), and
461
- * the shared preparation in `src/protocol/client.ts` strips that exact value
462
- * before the request leaves the plugin — in both regions, because both
463
- * endpoints reject it (issues #49 and #13). Selecting Off therefore means "send
464
- * no `reasoning_effort`", and what the model then does is upstream's call.
451
+ * @param carry - bytes left over from the previous chunk.
452
+ * @param chunk - the bytes just read.
453
+ * @returns the complete payloads, and the new carry.
465
454
  */
466
- function reasoningFields(info, observed) {
467
- const resolved = resolveEfforts(info, observed);
468
- if (resolved.efforts.length === 0) return { reasoning: false };
469
- const efforts = resolved.efforts;
455
+ function readCreditChunk(carry, chunk) {
456
+ const lines = (carry + chunk).split("\n");
457
+ const carryOver = lines.pop() ?? "";
458
+ const payloads = [];
459
+ for (const line of lines) {
460
+ const trimmed = line.trimEnd();
461
+ if (!trimmed.startsWith("data:")) continue;
462
+ payloads.push(trimmed.slice(5).trim());
463
+ }
470
464
  return {
471
- reasoning: true,
472
- thinkingLevelMap: {
473
- off: resolved.canDisable ? "off" : null,
474
- minimal: null,
475
- low: efforts.includes("low") ? "low" : null,
476
- medium: efforts.includes("medium") ? "medium" : null,
477
- high: efforts.includes("high") ? "high" : null,
478
- xhigh: efforts.includes("xhigh") ? "xhigh" : null,
479
- max: efforts.includes("max") ? "max" : null
480
- }
465
+ payloads,
466
+ carry: carryOver
481
467
  };
482
468
  }
483
- /** Build one pi-ai model descriptor pointing at the loopback shim. */
484
- function toPiModel(info, baseUrl, observed, providerId = WORKBUDDY_PROVIDER) {
485
- return {
486
- id: info.id,
487
- name: info.name,
488
- api: "openai-completions",
489
- provider: providerId,
490
- baseUrl,
491
- input: info.supportsImages === true ? ["text", "image"] : ["text"],
492
- ...reasoningFields(info, observed),
493
- cost: NO_COST,
494
- contextWindow: info.contextWindow,
495
- maxTokens: info.maxTokens,
496
- compat: { maxTokensField: "max_tokens" }
497
- };
469
+ /** Chat-completion POSTs must carry a JSON body type (simple-request CSRF drops here). */
470
+ function isJsonContentType(req) {
471
+ const type = req.headers["content-type"];
472
+ return typeof type === "string" && type.trim().toLowerCase().startsWith("application/json");
498
473
  }
474
+ /** HTTP status each upstream failure class surfaces as. */
475
+ const KIND_STATUS = {
476
+ hard_credit: 402,
477
+ soft_rate: 429,
478
+ session_dead: 401,
479
+ not_found: 502,
480
+ server: 502,
481
+ client: 400
482
+ };
499
483
  /**
500
- * Assemble the adapter. The provider's `getModels` reads the live catalog,
501
- * and every model's `baseUrl` is re-resolved per read so the shim's
502
- * ephemeral port applies from the first snapshot after startup.
484
+ * What to do when the gateway refuses a request on content (code `11-128`).
503
485
  *
504
- * The profile is constructed by hand rather than through dsh-llm-pi-ai's
505
- * internal `resolveProfiles()`: that helper is not part of the package's
506
- * public export surface (root entry, `lib/` deep imports blocked by the
507
- * exports map, `src/` not shipped), so hand-assembly is the only supported
508
- * path and every newly required field must be adopted here explicitly —
509
- * `modelErrors` is one such field.
486
+ * Two actions only, and the copy keeps the code spelled `11-128` so that the
487
+ * guidance itself, echoed back into a later request, cannot re-arm the gate.
488
+ * No status digits (see {@link failureMessage}) and no retry advice: retrying
489
+ * the same poisoned conversation reproduces the refusal.
490
+ *
491
+ * The running version rides along (issue #30): the same symptom reaches users
492
+ * on two very different layers — an install older than the fix, and a residual
493
+ * trigger after it — and without the version the user cannot tell which layer
494
+ * they are on, so the first thing they check is their account.
510
495
  */
511
- function createWorkBuddyAdapter(options) {
512
- const { shim, catalog, resolveAttachments, observe, hidden } = options;
513
- const providerId = options.providerId ?? "workbuddy";
514
- const displayName = options.displayName ?? "WorkBuddy";
515
- const buildModels = () => {
516
- const baseUrl = `${shim.baseUrl()}/v1`;
517
- return catalog.current().map((info) => toPiModel(info, baseUrl, observe?.(info.id), providerId));
518
- };
519
- const provider = {
520
- ...createProvider({
521
- id: providerId,
522
- name: displayName,
523
- auth: { apiKey: {
524
- name: "WorkBuddy OAuth bearer token",
525
- async resolve({ credential }) {
526
- const apiKey = credential?.key;
527
- return apiKey === void 0 || apiKey.length === 0 ? void 0 : {
528
- auth: { apiKey },
529
- source: "WorkBuddy"
530
- };
531
- }
532
- } },
533
- models: buildModels(),
534
- api: openAICompletionsApi()
535
- }),
536
- getModels: () => buildModels()
537
- };
538
- const profile = {
539
- provider: providerId,
540
- displayName,
541
- streamIdleTimeoutMs: WORKBUDDY_STREAM_IDLE_TIMEOUT_MS,
542
- retryPolicy: resolveRetryPolicy(void 0, "dsh-workbuddy-bridge retryPolicy"),
543
- configuredMaxTokens: /* @__PURE__ */ new Map(),
544
- modelErrors: /* @__PURE__ */ new Map(),
545
- ...REQUEST_IMAGE_BUDGETS,
546
- piProvider: provider
547
- };
548
- let profiles = /* @__PURE__ */ new Map([[providerId, profile]]);
549
- return {
550
- adapter: new WorkBuddyPiAiAdapter(catalog, hidden ?? (() => []), observe ?? (() => void 0), {
551
- profiles: () => profiles,
552
- auth: INERT_AUTH,
553
- resolveApiKey: async () => shim.token(),
554
- ...resolveAttachments === void 0 ? {} : { resolveAttachments }
555
- }),
556
- invalidate: () => {
557
- profiles = /* @__PURE__ */ new Map([[providerId, profile]]);
558
- }
559
- };
496
+ function channelGateHint() {
497
+ return ` — 渠道校验拦截(11-128)。请新开会话重试;若持续出现,先更新插件(当前 ${WORKBUDDY_BRIDGE_VERSION}) / blocked by channel verification (11-128): start a new conversation, and update the plugin if it persists (running ${WORKBUDDY_BRIDGE_VERSION})`;
560
498
  }
561
499
  /**
562
- * The WorkBuddy route's adapter: `PiAiAdapter` with the billing rate folded
563
- * into the catalog answers it returns to the DSH model pickers.
500
+ * What to do when the account's plan excludes the requested model (issue #24).
564
501
  *
565
- * `PiAiAdapter.listModels()` and `.resolveModel()` build their answers straight
566
- * from the pi-ai descriptors, which carry no billing fact, so the rate is
567
- * layered on here by looking the model up in the live catalog. Both overrides
568
- * delegate to `super` and then rewrite only the display fields, so streaming,
569
- * capability resolution, and effort mapping stay exactly as `dsh-llm-pi-ai`
570
- * implements them.
502
+ * No retry advice, because no retry can help: the model is not on this tier,
503
+ * and only picking a different model succeeds. The upstream's own
504
+ * `displayMsg` ("Your account type does not support this model.") says what is
505
+ * wrong but not what to do, which is the gap this fills.
506
+ */
507
+ const PLAN_LIMIT_HINT = " — 当前账号套餐不包含这个模型(11158),请换用其他模型 / your plan does not include this model (11158): pick another one";
508
+ function writeJson(res, status, body) {
509
+ const payload = JSON.stringify(body);
510
+ res.writeHead(status, {
511
+ "Content-Type": "application/json",
512
+ "Content-Length": Buffer.byteLength(payload)
513
+ });
514
+ res.end(payload);
515
+ }
516
+ function writeOpenAIError(res, status, kind, message) {
517
+ writeJson(res, status, { error: {
518
+ message,
519
+ type: kind,
520
+ code: kind
521
+ } });
522
+ }
523
+ /**
524
+ * The one-line reason a failed upstream request is reported with.
571
525
  *
572
- * `resolveModel()` and `prepareCall()` additionally answer the *default*
573
- * thinking level. `dsh-llm-pi-ai` can only report a default from a whole-route
574
- * profile field (`profile.reasoning`), which cannot express one level per
575
- * model, so the per-model answer has to be attached here. Two call sites are
576
- * required rather than one: the picker reads `resolveModel()`, while the
577
- * request path reads `prepareCall()`, and a default present on only one of them
578
- * would show the user a level the wire does not actually send.
526
+ * The host does not read our HTTP status to classify a failure: `dsh-llm-pi-ai`
527
+ * matches the **message text** (`if (/\b(?:401|403)\b/.test(message)) return
528
+ * "AUTH"`), and the chat UI then replaces whatever we wrote with
529
+ * "API key is invalid". So a status may only appear here when the failure
530
+ * really is an authentication one; every other class keeps its digits out, or
531
+ * a restricted account or a rejected prompt reaches the user as a bad key.
579
532
  *
580
- * A model missing from the catalog (an id the shim would serve but the last
581
- * upstream refresh did not list) falls through with its name untouched rather
582
- * than being dropped: catalog membership is advisory, and the seam tolerates
583
- * serving an unlisted id.
533
+ * The upstream's own `displayMsg` wins over the raw body: it is the sentence
534
+ * written for a human ("账号存在异常行为,已被限制使用"), while the body is a JSON
535
+ * document whose `msg` is often a machine phrase such as `request illegal`.
536
+ *
537
+ * The channel-gate code (`11-128`) appends {@link channelGateHint}: its raw
538
+ * body is `{"message":"请求被拦截,请重新发送","type":"client","code":"client"}`,
539
+ * which on its own reads as a transient hiccup the user should simply retry —
540
+ * the two actions that actually help (a new conversation; update the plugin)
541
+ * are not guessable from it. A plan-limit refusal (`11158`) appends
542
+ * {@link PLAN_LIMIT_HINT} for the same reason: the fix is "pick another model",
543
+ * which the upstream copy does not say.
584
544
  */
585
- var WorkBuddyPiAiAdapter = class extends PiAiAdapter {
586
- catalog;
587
- hidden;
588
- observe;
589
- constructor(catalog, hidden, observe, options) {
590
- super(options);
591
- this.catalog = catalog;
592
- this.hidden = hidden;
593
- this.observe = observe;
594
- }
595
- /** Catalog entry for one model id, or undefined when the catalog omits it. */
596
- infoFor(model) {
597
- return this.catalog.current().find((entry) => entry.id === model);
598
- }
599
- /**
600
- * The default level for one model, or undefined when it has no switch.
601
- *
602
- * Derived from the *same* switch the picker is built from — `resolveEfforts`
603
- * with the same observation the adapter passes to `reasoningFields` — so the
604
- * default can never name a level this model does not offer.
605
- */
606
- defaultEffortFor(model) {
607
- const info = this.infoFor(model);
608
- if (info === void 0) return void 0;
609
- const effort = resolveDefaultEffort(info, resolveEfforts(info, this.observe(model)).efforts);
610
- return effort === void 0 ? void 0 : ReasoningEffortId(effort);
611
- }
612
- /**
613
- * Attach the per-model default to an already-resolved model answer.
614
- *
615
- * Written as a rewrite of `reasoning` rather than a spread of the whole
616
- * answer: `reasoning.defaultEffort` must stay absent — not `undefined` — on a
617
- * model with no switch, because the host reads absence as "offer Default".
618
- */
619
- withDefaultEffort(resolved) {
620
- const effort = this.defaultEffortFor(resolved.id);
621
- if (effort === void 0 || resolved.reasoning === void 0) return resolved;
622
- return {
623
- ...resolved,
624
- reasoning: {
625
- ...resolved.reasoning,
626
- defaultEffort: effort
545
+ function failureMessage(result) {
546
+ const reason = upstreamDisplayMessage(result.message) ?? result.message.slice(0, 400);
547
+ const head = `workbuddy upstream ${result.kind}`;
548
+ const line = result.kind === "session_dead" ? `${head} (http ${result.status}): ${reason}` : `${head}: ${reason}`;
549
+ const gated = isChannelGateBody(result.message) ? `${line}${channelGateHint()}` : line;
550
+ return isPlanLimitBody(result.message) ? `${gated}${PLAN_LIMIT_HINT}` : gated;
551
+ }
552
+ /** Read a request body with a size cap; over-limit bodies fail the request. */ function readBody$1(req) {
553
+ return new Promise((resolve, reject) => {
554
+ const chunks = [];
555
+ let size = 0;
556
+ req.on("data", (chunk) => {
557
+ size += chunk.length;
558
+ if (size > REQUEST_BODY_LIMIT) {
559
+ reject(/* @__PURE__ */ new Error("request body too large"));
560
+ req.destroy();
561
+ return;
627
562
  }
628
- };
629
- }
630
- async listModels(provider) {
631
- const models = await super.listModels(provider);
632
- const hidden = new Set(this.hidden());
633
- return models.flatMap((model) => {
634
- if (hidden.has(model.id)) return [];
635
- const info = this.infoFor(model.id);
636
- if (info === void 0) return [model];
637
- return [{
638
- ...model,
639
- name: withCatalogDisplay(model.name, info)
640
- }];
563
+ chunks.push(chunk);
641
564
  });
642
- }
643
- async resolveModel(provider, model, signal) {
644
- const resolved = await super.resolveModel(provider, model, signal);
645
- const info = this.infoFor(model);
646
- const named = info === void 0 ? resolved : {
647
- ...resolved,
648
- name: withCatalogDisplay(resolved.name, info)
649
- };
650
- return this.withDefaultEffort(named);
651
- }
652
- async prepareCall(provider, model, signal) {
653
- const prepared = await super.prepareCall(provider, model, signal);
654
- return {
655
- ...prepared,
656
- model: this.withDefaultEffort(prepared.model)
657
- };
658
- }
659
- };
660
- /** The capture log under `$DSH_HOME`; one JSON object per line. */
661
- const CAPTURE_LOG_FILENAME = ".workbuddy-captures.jsonl";
662
- /**
663
- * Held across the request/response pair.
664
- *
665
- * A single slot is deliberate rather than a map: this is a human-driven
666
- * diagnostic, the host serialises one turn at a time, and the cost of a
667
- * collision (one record with another's verdict) is a re-run, not a wrong fix.
668
- * A map would need per-request ids threaded through the client for no gain here.
669
- */
670
- let pending;
671
- /** Where the log goes right now, or `undefined` when disarmed. */
672
- function captureTarget() {
673
- const fromEnv = process.env["WORKBUDDY_CAPTURE_BODY"];
674
- if (fromEnv !== void 0 && fromEnv.trim() !== "") return fromEnv;
675
- try {
676
- const home = resolveDshHome();
677
- return existsSync(join(home, ".workbuddy-capture.on")) ? join(home, CAPTURE_LOG_FILENAME) : void 0;
678
- } catch {
679
- return;
680
- }
565
+ req.on("end", () => resolve(Buffer.concat(chunks)));
566
+ req.on("error", reject);
567
+ });
681
568
  }
682
569
  /**
683
- * Strip credential material before anything is written.
684
- *
685
- * The log is meant to be pasted into an issue. A bearer token in it would hand
686
- * the reporter's account to whoever reads the issue, so redaction happens on the
687
- * way in rather than being left to whoever copies the file.
570
+ * Start the loopback endpoint. Requests carry any bearer; the loopback bind
571
+ * is the boundary, and the upstream credential comes from the store alone.
688
572
  */
689
- function redacted(headers) {
690
- const out = {};
691
- for (const [name, value] of Object.entries(headers)) {
692
- const lowered = name.toLowerCase();
693
- out[name] = lowered === "authorization" || lowered === "cookie" || lowered.includes("token") ? "[redacted]" : value;
694
- }
695
- return out;
696
- }
573
+ function createWorkBuddyShim(options) {
574
+ const { store, client, catalog, observeCredit } = options;
575
+ const logger = options.logger;
576
+ const SHARED_SECRET = randomBytes(32).toString("base64url");
577
+ /** Constant-time bearer check; absent or mismatched bearers are rejected. */
578
+ function bearerOk(req) {
579
+ const header = req.headers.authorization;
580
+ if (typeof header !== "string") return false;
581
+ const match = /^Bearer\s+(.+)$/i.exec(header.trim());
582
+ if (match === null) return false;
583
+ const presented = match[1];
584
+ const expected = SHARED_SECRET;
585
+ const a = Buffer.from(presented);
586
+ const b = Buffer.from(expected);
587
+ if (a.length !== b.length) return false;
588
+ return timingSafeEqual(a, b);
589
+ }
590
+ const server = createServer((req, res) => {
591
+ handle(req, res);
592
+ });
593
+ const ready = new Promise((resolve, reject) => {
594
+ server.once("listening", () => resolve());
595
+ server.once("error", reject);
596
+ });
597
+ server.listen(0, "127.0.0.1");
598
+ const baseUrl = () => {
599
+ const address = server.address();
600
+ if (address === null || typeof address === "string") throw new Error("workbuddy shim has no listening address");
601
+ return `http://127.0.0.1:${address.port}`;
602
+ };
603
+ async function handle(req, res) {
604
+ try {
605
+ if (!hostIsLoopback(req.headers.host)) {
606
+ writeOpenAIError(res, 403, "host_not_allowed", "Host header must name the loopback interface");
607
+ return;
608
+ }
609
+ if (!originIsLoopback(req.headers.origin)) {
610
+ writeOpenAIError(res, 403, "origin_not_allowed", "Origin must be a loopback origin");
611
+ return;
612
+ }
613
+ if (!bearerOk(req)) {
614
+ writeOpenAIError(res, 401, "unauthorized", "missing or invalid Authorization bearer");
615
+ return;
616
+ }
617
+ const url = req.url ?? "/";
618
+ if (req.method === "GET" && (url === "/healthz" || url === "/healthz/")) {
619
+ writeJson(res, 200, { ok: true });
620
+ return;
621
+ }
622
+ if (req.method === "GET" && (url === "/v1/models" || url === "/v1/models/")) {
623
+ writeJson(res, 200, {
624
+ object: "list",
625
+ data: catalog.current().map((model) => ({
626
+ id: model.id,
627
+ object: "model",
628
+ created: 0,
629
+ owned_by: "workbuddy"
630
+ }))
631
+ });
632
+ return;
633
+ }
634
+ if (req.method === "POST" && (url === "/v1/chat/completions" || url === "/v1/chat/completions/")) {
635
+ await chatCompletions(req, res);
636
+ return;
637
+ }
638
+ writeOpenAIError(res, 404, "not_found", `no such route: ${req.method} ${url}`);
639
+ } catch (error) {
640
+ if (!res.headersSent) writeOpenAIError(res, 500, "internal", String(error));
641
+ else res.end();
642
+ }
643
+ }
644
+ async function chatCompletions(req, res) {
645
+ if (!isJsonContentType(req)) {
646
+ writeOpenAIError(res, 415, "unsupported_media_type", "Content-Type must be application/json");
647
+ return;
648
+ }
649
+ let credential;
650
+ try {
651
+ credential = await store.resolve();
652
+ } catch (error) {
653
+ writeOpenAIError(res, 401, "not_signed_in", String(error));
654
+ return;
655
+ }
656
+ const raw = (await readBody$1(req)).toString("utf8");
657
+ const prepared = prepareChatRequest(raw);
658
+ const conversationId = cacheConversationId(credential, prepared.model, req.headers[CACHE_SESSION_HEADER]);
659
+ const controller = new AbortController();
660
+ req.on("close", () => controller.abort());
661
+ const result = await client.chatStream(credential, prepared.body, controller.signal, conversationId);
662
+ if (!result.ok) {
663
+ writeOpenAIError(res, KIND_STATUS[result.kind], result.kind, failureMessage(result));
664
+ return;
665
+ }
666
+ res.writeHead(200, {
667
+ "Content-Type": "text/event-stream",
668
+ "Cache-Control": "no-cache",
669
+ Connection: "keep-alive",
670
+ "X-Accel-Buffering": "no"
671
+ });
672
+ let sawDone = false;
673
+ /**
674
+ * Bytes of the frame currently being read.
675
+ *
676
+ * The cost arrives on the last usage frame, and that frame is exactly the
677
+ * one a TCP read boundary is most likely to split: parsing each chunk in
678
+ * isolation would drop it. Complete lines are accumulated into `carry` and
679
+ * only whole `data:` payloads are inspected.
680
+ */
681
+ let carry = "";
682
+ /** The last cost observed for this response; reported once, at the end. */
683
+ let observed;
684
+ /**
685
+ * Decodes the byte stream without splitting a multi-byte character across
686
+ * chunks.
687
+ *
688
+ * `chunk.toString('utf8')` would turn a character straddling a read
689
+ * boundary into U+FFFD, and since answers routinely contain Chinese that is
690
+ * not hypothetical. A mangled frame fails `JSON.parse` and is dropped —
691
+ * which for the frame carrying the cost would mean a message silently
692
+ * losing its label.
693
+ */
694
+ const decoder = new StringDecoder("utf8");
695
+ const body = Readable.fromWeb(result.response.body);
696
+ body.on("data", (chunk) => {
697
+ if (chunk.includes("[DONE]")) sawDone = true;
698
+ if (observeCredit === void 0) return;
699
+ const read = readCreditChunk(carry, decoder.write(chunk));
700
+ carry = read.carry;
701
+ for (const payload of read.payloads) {
702
+ const frame = readCreditFrame(payload);
703
+ if (frame !== void 0) observed = frame;
704
+ }
705
+ });
706
+ body.on("error", (error) => {
707
+ logger?.warn("dsh-workbuddy-bridge: upstream stream failed mid-flight", error);
708
+ if (!sawDone && res.writable) res.end("data: [DONE]\n\n");
709
+ });
710
+ body.on("end", () => {
711
+ if (observeCredit !== void 0 && observed !== void 0) observeCredit(observed.id, observed.credit);
712
+ });
713
+ body.pipe(res);
714
+ }
715
+ return {
716
+ ready,
717
+ baseUrl,
718
+ token: () => SHARED_SECRET,
719
+ close: () => new Promise((resolve, reject) => {
720
+ server.close(() => resolve());
721
+ server.closeAllConnections();
722
+ server.once("error", reject);
723
+ })
724
+ };
725
+ }
726
+ //#endregion
727
+ //#region src/llm/adapter.ts
697
728
  /**
698
- * A non-reversible fingerprint of the bearer token, for comparing two runs.
729
+ * The `workbuddy` pi-ai provider: one loopback-backed adapter registered
730
+ * into the Harness LLM seam, assembled from public `dsh-llm-pi-ai`
731
+ * extension points the way `dsh-codex-connect` assembles its Codex route.
699
732
  *
700
- * The token itself stays out of the log, but "was this the same token?" is a real
701
- * question when the same body and headers answer 200 on a replay and 400 from the
702
- * host: a token refresh between the two makes them different requests. A digest
703
- * answers it without storing the secret.
733
+ * @module dsh-workbuddy-bridge/adapter
704
734
  */
705
- function tokenFingerprint(headers) {
706
- const entry = Object.entries(headers).find(([name]) => name.toLowerCase() === "authorization");
707
- if (entry === void 0) return void 0;
708
- const token = entry[1].replace(/^Bearer\s+/i, "");
709
- if (token === "") return void 0;
710
- return createHash("sha256").update(token).digest("hex").slice(0, 12);
711
- }
735
+ /** Provider route this bundle owns. */
736
+ const WORKBUDDY_PROVIDER = "workbuddy";
737
+ /** Provider idle ceiling while one stream read is outstanding. */
738
+ const WORKBUDDY_STREAM_IDLE_TIMEOUT_MS = 3e5;
712
739
  /**
713
- * Remember the request that is about to leave.
740
+ * Image-request budgets at the dsh-llm-pi-ai defaults; the profile type made
741
+ * them required in 0.1.1-rc.2. They bound requests to models whose catalog
742
+ * entry declares `supportsImages`; text-only models never receive images.
714
743
  *
715
- * Called from the client's `onChatRequest` hook, i.e. after every header and the
716
- * body are final and before the fetch — so what is recorded is what the upstream
717
- * receives, not what the caller intended.
744
+ * The **retained-count** pair joined them in the 0.2.2 rc line, with the same
745
+ * defaults the host's own config schema applies: at most 50 image occurrences
746
+ * per request, overflowing 10 at a time. Both are whole-request bounds on a
747
+ * deterministic inline request version, so the route simply adopts the host's
748
+ * defaults rather than inventing tighter ones — crossing them would rewrite
749
+ * the request prefix, which this route never has a reason to do.
718
750
  */
719
- function rememberChatRequest(url, headers, body) {
720
- if (captureTarget() === void 0) return;
721
- pending = {
722
- url,
723
- headers: redacted(headers),
724
- body,
725
- at: (/* @__PURE__ */ new Date()).toISOString(),
726
- token: tokenFingerprint(headers)
727
- };
728
- }
751
+ const REQUEST_IMAGE_BUDGETS = {
752
+ maxRequestImageBytes: 20971520,
753
+ maxRequestImages: 50,
754
+ imageOffloadCountQuantum: 10,
755
+ requestImagePixelBudget: 4194304,
756
+ requestImageMaxBytes: 1048576
757
+ };
729
758
  /**
730
- * The most recent request this process captured, with its verdict.
731
- *
732
- * Exists so a maintainer can re-send the exact refused request from **inside**
733
- * the host process: the same body, headers and token answered 200 from a separate
734
- * process and 400 from the host, which leaves the sending process as the only
735
- * remaining variable.
736
- *
737
- * Falls back to the capture log's last line, because the in-memory slot does not
738
- * survive a plugin reload — and a reload is exactly when the experiment is
739
- * needed.
759
+ * Inert pi-ai auth plane. The workbuddy route authenticates only through the
760
+ * shim shared secret resolved per request by `resolveApiKey`, so pi-ai's own
761
+ * credential lifecycle and ambient discovery must never manufacture a
762
+ * credential for it. `PiAiAdapterOptions.auth` is required since 0.1.1-rc.2;
763
+ * every ambient question here answers "nothing stored, nothing set".
740
764
  */
741
- function lastCapturedRequest() {
742
- if (lastRequest !== void 0) return lastRequest;
743
- const target = captureTarget();
744
- if (target === void 0 || !existsSync(target)) return void 0;
745
- try {
746
- const last = readFileSync(target, "utf8").split("\n").filter((line) => line.trim() !== "").at(-1);
747
- if (last === void 0) return void 0;
748
- const record = JSON.parse(last);
749
- if (typeof record.body !== "string") return void 0;
750
- return {
751
- body: record.body,
752
- at: record.at ?? "",
753
- status: record.status ?? 0,
754
- headers: record.headers ?? {}
755
- };
756
- } catch {
757
- return;
765
+ const INERT_AUTH = {
766
+ credentials: {
767
+ async read() {},
768
+ async list() {
769
+ return [];
770
+ },
771
+ async modify() {
772
+ throw new Error("dsh-workbuddy-bridge: the workbuddy route has no pi-ai credential lifecycle");
773
+ },
774
+ async delete() {}
775
+ },
776
+ authContext: {
777
+ async env() {},
778
+ async fileExists() {
779
+ return false;
780
+ }
758
781
  }
759
- }
760
- /** Set by {@link rememberChatRequest} and refreshed by {@link recordChatOutcome}. */
761
- let lastRequest;
782
+ };
783
+ /** No per-token pricing is knowable for a subscription quota; report zero. */
784
+ const NO_COST = {
785
+ input: 0,
786
+ output: 0,
787
+ cacheRead: 0,
788
+ cacheWrite: 0
789
+ };
762
790
  /**
763
- * Append the pending request with its verdict.
791
+ * The suffix appended to a model's display name so its billing rate is visible
792
+ * wherever the name is shown.
764
793
  *
765
- * `status` 0 means a transport failure. A missing pending request (a caller that
766
- * skips the hook) writes nothing rather than inventing a record.
794
+ * The separator is a middle dot rather than a hyphen or colon: model names
795
+ * already contain hyphens (`GLM-5.3-Flash`, `Deepseek-V4-Flash`), so a hyphen
796
+ * separator would be ambiguous about where the name ends and the rate begins.
767
797
  */
768
- function recordChatOutcome(status, message) {
769
- const target = captureTarget();
770
- const entry = pending;
771
- pending = void 0;
772
- if (entry !== void 0) lastRequest = {
773
- body: entry.body,
774
- at: entry.at,
775
- status,
776
- headers: entry.headers
777
- };
778
- if (target === void 0 || entry === void 0) return;
779
- const line = JSON.stringify({
780
- at: entry.at,
781
- url: entry.url,
782
- status,
783
- ...message === void 0 ? {} : { message: message.slice(0, 400) },
784
- tokenFingerprint: entry.token,
785
- headers: entry.headers,
786
- bodyLength: entry.body.length,
787
- body: entry.body
788
- });
789
- try {
790
- appendFileSync(target, `${line}\n`, { mode: 384 });
791
- } catch {}
792
- }
793
- //#endregion
794
- //#region src/llm/loopback.ts
798
+ const RATE_SEPARATOR = " · ";
795
799
  /**
796
- * Shared loopback gates for the plugin's local HTTP surfaces: the loopback
797
- * shim and the same-origin web-status route. Both are only ever meant to be
798
- * addressed through the machine's loopback interface.
800
+ * Append the billing rate to one model's display name.
799
801
  *
800
- * @module dsh-workbuddy-bridge/loopback
802
+ * The rate AND the declared promo badges ride the *name* alone: since DSH
803
+ * 0.1.2 the composer's model seat (`ModelSelect`) renders `model.name` only —
804
+ * `description` is no longer read there at all (the 0.1.1-era client rendered
805
+ * it, which is why the badges used to be visible in the seat). The `/model`
806
+ * popup renders the name too, so a separate `description` copy would either
807
+ * duplicate (rate) or vanish (badges) depending on client generation.
808
+ *
809
+ * This is display-only and cannot affect routing: the wire request is built
810
+ * from `model.id` (pi-ai's completions API sets `model: model.id`), the
811
+ * selection a picker submits is `{provider, model: id, reasoningEffort}`, and
812
+ * `dsh-llm` validates `name` as a non-empty string without comparing its
813
+ * contents. Nothing in the host resolves a model *by* name.
801
814
  */
802
- /** Loopback hostnames a local plugin surface may be addressed by. */
803
- const LOOPBACK_HOSTS = /* @__PURE__ */ new Set([
804
- "127.0.0.1",
805
- "localhost",
806
- "[::1]"
807
- ]);
808
- /** Strip the optional :port from a Host header value, IPv6-bracket aware. */
809
- function hostnameOfHost(host) {
810
- let hostname = host.trim().toLowerCase();
811
- if (hostname.startsWith("[")) {
812
- const end = hostname.indexOf("]");
813
- return end === -1 ? hostname : hostname.slice(0, end + 1);
814
- }
815
- const colon = hostname.lastIndexOf(":");
816
- if (colon !== -1 && !hostname.slice(0, colon).includes(":") && /^\d+$/.test(hostname.slice(colon + 1))) hostname = hostname.slice(0, colon);
817
- return hostname;
815
+ /**
816
+ * The catalog display suffix: the billing rate followed by the declared promo
817
+ * badges (`限时免费`, `夜间折扣`), or undefined when the row carries neither.
818
+ * The badge labels are the upstream's own spellings and the host seam has no
819
+ * locale service, so non-Chinese UIs see them verbatim — accepted until the
820
+ * picker grows a localized badge slot.
821
+ */
822
+ function displaySuffix(info) {
823
+ const parts = [normalizeCredits(info.billing?.credits), ...info.billing?.badges ?? []].filter((part) => part !== void 0 && part !== "");
824
+ return parts.length === 0 ? void 0 : parts.join(" · ");
825
+ }
826
+ /** Append the catalog display suffix to one model's display name. */
827
+ function withCatalogDisplay(name, info) {
828
+ const suffix = displaySuffix(info);
829
+ return suffix === void 0 ? name : `${name}${RATE_SEPARATOR}${suffix}`;
818
830
  }
819
831
  /**
820
- * The request's Host header must name the loopback interface. A DNS-rebinding
821
- * page (attacker domain re-resolved to 127.0.0.1) sends its own domain in
822
- * Host, so this check drops those before any routing happens.
832
+ * Translate a model's resolved thinking-level switch into pi-ai's
833
+ * `thinkingLevelMap` (every level pinned to its wire spelling or `null` for
834
+ * unsupported), mirroring `dsh-llm-pi-ai`'s own `resolveModelReasoning`.
835
+ *
836
+ * The *decision* of which levels a model offers is not made here — it lives in
837
+ * {@link resolveEfforts}, which the status document reads too. That sharing is
838
+ * the point: the composer's bulb is lit from the same answer the picker is
839
+ * built from, so a model cannot show a control in one place and none in the
840
+ * other. This function only reshapes that answer for pi-ai.
841
+ *
842
+ * The offered set is described internally as "verified accepted", never as
843
+ * "verified effective": acceptance proves the upstream did not reject the
844
+ * spelling, not that it changes what the model does.
845
+ *
846
+ * `off` is a picker name, not a wire spelling. It stays pinned to the literal
847
+ * `'off'` (a `null` here would remove the level from the picker entirely), and
848
+ * the shared preparation in `src/protocol/client.ts` strips that exact value
849
+ * before the request leaves the plugin — in both regions, because both
850
+ * endpoints reject it (issues #49 and #13). Selecting Off therefore means "send
851
+ * no `reasoning_effort`", and what the model then does is upstream's call.
823
852
  */
824
- function hostIsLoopback(host) {
825
- if (host === void 0 || host.trim() === "") return false;
826
- return LOOPBACK_HOSTS.has(hostnameOfHost(host));
853
+ function reasoningFields(info, observed) {
854
+ const resolved = resolveEfforts(info, observed);
855
+ if (resolved.efforts.length === 0) return { reasoning: false };
856
+ const efforts = resolved.efforts;
857
+ return {
858
+ reasoning: true,
859
+ thinkingLevelMap: {
860
+ off: resolved.canDisable ? "off" : null,
861
+ minimal: null,
862
+ low: efforts.includes("low") ? "low" : null,
863
+ medium: efforts.includes("medium") ? "medium" : null,
864
+ high: efforts.includes("high") ? "high" : null,
865
+ xhigh: efforts.includes("xhigh") ? "xhigh" : null,
866
+ max: efforts.includes("max") ? "max" : null
867
+ }
868
+ };
869
+ }
870
+ /** Build one pi-ai model descriptor pointing at the loopback shim. */
871
+ function toPiModel(info, baseUrl, observed, providerId = WORKBUDDY_PROVIDER) {
872
+ return {
873
+ id: info.id,
874
+ name: info.name,
875
+ api: "openai-completions",
876
+ provider: providerId,
877
+ baseUrl,
878
+ input: info.supportsImages === true ? ["text", "image"] : ["text"],
879
+ ...reasoningFields(info, observed),
880
+ cost: NO_COST,
881
+ contextWindow: info.contextWindow,
882
+ maxTokens: info.maxTokens,
883
+ compat: { maxTokensField: "max_tokens" }
884
+ };
827
885
  }
828
886
  /**
829
- * A browser-sent Origin (present header) must be loopback. Non-browser
830
- * clients (the plugin's own fetch calls) send no Origin at all and pass.
887
+ * Assemble the adapter. The provider's `getModels` reads the live catalog,
888
+ * and every model's `baseUrl` is re-resolved per read so the shim's
889
+ * ephemeral port applies from the first snapshot after startup.
890
+ *
891
+ * The profile is constructed by hand rather than through dsh-llm-pi-ai's
892
+ * internal `resolveProfiles()`: that helper is not part of the package's
893
+ * public export surface (root entry, `lib/` deep imports blocked by the
894
+ * exports map, `src/` not shipped), so hand-assembly is the only supported
895
+ * path and every newly required field must be adopted here explicitly —
896
+ * `modelErrors` is one such field.
831
897
  */
832
- function originIsLoopback(origin) {
833
- if (origin === void 0 || origin.trim() === "") return true;
834
- try {
835
- const { hostname } = new URL(origin);
836
- return LOOPBACK_HOSTS.has(hostname) || hostname === "::1";
837
- } catch {
838
- return false;
839
- }
898
+ function createWorkBuddyAdapter(options) {
899
+ const { shim, catalog, resolveAttachments, observe, hidden } = options;
900
+ const providerId = options.providerId ?? "workbuddy";
901
+ const displayName = options.displayName ?? "WorkBuddy";
902
+ const buildModels = () => {
903
+ const baseUrl = `${shim.baseUrl()}/v1`;
904
+ return catalog.current().map((info) => toPiModel(info, baseUrl, observe?.(info.id), providerId));
905
+ };
906
+ const provider = {
907
+ ...createProvider({
908
+ id: providerId,
909
+ name: displayName,
910
+ auth: { apiKey: {
911
+ name: "WorkBuddy OAuth bearer token",
912
+ async resolve({ credential }) {
913
+ const apiKey = credential?.key;
914
+ return apiKey === void 0 || apiKey.length === 0 ? void 0 : {
915
+ auth: { apiKey },
916
+ source: "WorkBuddy"
917
+ };
918
+ }
919
+ } },
920
+ models: buildModels(),
921
+ api: openAICompletionsApi()
922
+ }),
923
+ getModels: () => buildModels()
924
+ };
925
+ const profile = {
926
+ provider: providerId,
927
+ displayName,
928
+ streamIdleTimeoutMs: WORKBUDDY_STREAM_IDLE_TIMEOUT_MS,
929
+ retryPolicy: resolveRetryPolicy(void 0, "dsh-workbuddy-bridge retryPolicy"),
930
+ configuredMaxTokens: /* @__PURE__ */ new Map(),
931
+ modelErrors: /* @__PURE__ */ new Map(),
932
+ ...REQUEST_IMAGE_BUDGETS,
933
+ piProvider: provider
934
+ };
935
+ let profiles = /* @__PURE__ */ new Map([[providerId, profile]]);
936
+ return {
937
+ adapter: new WorkBuddyPiAiAdapter(catalog, hidden ?? (() => []), observe ?? (() => void 0), {
938
+ profiles: () => profiles,
939
+ auth: INERT_AUTH,
940
+ prepareHeaders({ sessionId }, headers) {
941
+ if (sessionId && process.env["WORKBUDDY_HY4_CACHE_AFFINITY"] !== "0") headers.set(CACHE_SESSION_HEADER, createHash("sha256").update(sessionId).digest("hex"));
942
+ return headers;
943
+ },
944
+ resolveApiKey: async () => shim.token(),
945
+ ...resolveAttachments === void 0 ? {} : { resolveAttachments }
946
+ }),
947
+ invalidate: () => {
948
+ profiles = /* @__PURE__ */ new Map([[providerId, profile]]);
949
+ }
950
+ };
840
951
  }
841
- //#endregion
842
- //#region src/llm/shim.ts
843
952
  /**
844
- * Loopback OpenAI-compatible endpoint. The pi-ai provider points here; the
845
- * shim applies the WorkBuddy wire quirks (forced streaming, string
846
- * `tool_choice`, CLI-shaped headers) and forwards to the real upstream.
847
- * It binds 127.0.0.1 only and never serves another interface.
953
+ * The WorkBuddy route's adapter: `PiAiAdapter` with the billing rate folded
954
+ * into the catalog answers it returns to the DSH model pickers.
848
955
  *
849
- * Inbound hardening: the loopback bind alone is not a trust boundary (any
850
- * local process or a DNS-rebinding page can reach 127.0.0.1), so every
851
- * request must carry a loopback Host header, browser-sent Origins must be
852
- * loopback, chat POSTs must be application/json, and the Authorization
853
- * header must carry the shim's per-process shared secret. The plugin's
854
- * own client satisfies all four by construction; local attackers cannot
855
- * read the secret out of the plugin process's memory.
956
+ * `PiAiAdapter.listModels()` and `.resolveModel()` build their answers straight
957
+ * from the pi-ai descriptors, which carry no billing fact, so the rate is
958
+ * layered on here by looking the model up in the live catalog. Both overrides
959
+ * delegate to `super` and then rewrite only the display fields, so streaming,
960
+ * capability resolution, and effort mapping stay exactly as `dsh-llm-pi-ai`
961
+ * implements them.
856
962
  *
857
- * @module dsh-workbuddy-bridge/shim
963
+ * `resolveModel()` and `prepareCall()` additionally answer the *default*
964
+ * thinking level. `dsh-llm-pi-ai` can only report a default from a whole-route
965
+ * profile field (`profile.reasoning`), which cannot express one level per
966
+ * model, so the per-model answer has to be attached here. Two call sites are
967
+ * required rather than one: the picker reads `resolveModel()`, while the
968
+ * request path reads `prepareCall()`, and a default present on only one of them
969
+ * would show the user a level the wire does not actually send.
970
+ *
971
+ * A model missing from the catalog (an id the shim would serve but the last
972
+ * upstream refresh did not list) falls through with its name untouched rather
973
+ * than being dropped: catalog membership is advisory, and the seam tolerates
974
+ * serving an unlisted id.
858
975
  */
859
- const REQUEST_BODY_LIMIT = 67108864;
976
+ var WorkBuddyPiAiAdapter = class extends PiAiAdapter {
977
+ catalog;
978
+ hidden;
979
+ observe;
980
+ constructor(catalog, hidden, observe, options) {
981
+ super(options);
982
+ this.catalog = catalog;
983
+ this.hidden = hidden;
984
+ this.observe = observe;
985
+ }
986
+ /** Catalog entry for one model id, or undefined when the catalog omits it. */
987
+ infoFor(model) {
988
+ return this.catalog.current().find((entry) => entry.id === model);
989
+ }
990
+ /**
991
+ * The default level for one model, or undefined when it has no switch.
992
+ *
993
+ * Derived from the *same* switch the picker is built from — `resolveEfforts`
994
+ * with the same observation the adapter passes to `reasoningFields` — so the
995
+ * default can never name a level this model does not offer.
996
+ */
997
+ defaultEffortFor(model) {
998
+ const info = this.infoFor(model);
999
+ if (info === void 0) return void 0;
1000
+ const effort = resolveDefaultEffort(info, resolveEfforts(info, this.observe(model)).efforts);
1001
+ return effort === void 0 ? void 0 : ReasoningEffortId(effort);
1002
+ }
1003
+ /**
1004
+ * Attach the per-model default to an already-resolved model answer.
1005
+ *
1006
+ * Written as a rewrite of `reasoning` rather than a spread of the whole
1007
+ * answer: `reasoning.defaultEffort` must stay absent — not `undefined` — on a
1008
+ * model with no switch, because the host reads absence as "offer Default".
1009
+ */
1010
+ withDefaultEffort(resolved) {
1011
+ const effort = this.defaultEffortFor(resolved.id);
1012
+ if (effort === void 0 || resolved.reasoning === void 0) return resolved;
1013
+ return {
1014
+ ...resolved,
1015
+ reasoning: {
1016
+ ...resolved.reasoning,
1017
+ defaultEffort: effort
1018
+ }
1019
+ };
1020
+ }
1021
+ async listModels(provider) {
1022
+ const models = await super.listModels(provider);
1023
+ const hidden = new Set(this.hidden());
1024
+ return models.flatMap((model) => {
1025
+ if (hidden.has(model.id)) return [];
1026
+ const info = this.infoFor(model.id);
1027
+ if (info === void 0) return [model];
1028
+ return [{
1029
+ ...model,
1030
+ name: withCatalogDisplay(model.name, info)
1031
+ }];
1032
+ });
1033
+ }
1034
+ async resolveModel(provider, model, signal) {
1035
+ const resolved = await super.resolveModel(provider, model, signal);
1036
+ const info = this.infoFor(model);
1037
+ const named = info === void 0 ? resolved : {
1038
+ ...resolved,
1039
+ name: withCatalogDisplay(resolved.name, info)
1040
+ };
1041
+ return this.withDefaultEffort(named);
1042
+ }
1043
+ async prepareCall(provider, model, signal) {
1044
+ const prepared = await super.prepareCall(provider, model, signal);
1045
+ return {
1046
+ ...prepared,
1047
+ model: this.withDefaultEffort(prepared.model)
1048
+ };
1049
+ }
1050
+ };
1051
+ /** The capture log under `$DSH_HOME`; one JSON object per line. */
1052
+ const CAPTURE_LOG_FILENAME = ".workbuddy-captures.jsonl";
860
1053
  /**
861
- * Pull the response id and `credit` out of one SSE `data:` payload.
862
- *
863
- * WorkBuddy's OpenAI-compatible stream reports what a message cost as an extra
864
- * `credit` member beside the standard token buckets on the final usage frame
865
- * (measured: `glm-5.3` answering 900 tokens reported `credit: 0.51`). The
866
- * member is not part of the OpenAI schema, so it is read defensively off the
867
- * parsed object rather than through any typed shape, and every frame without a
868
- * usable number is skipped.
1054
+ * Held across the request/response pair.
869
1055
  *
870
- * @param payload - the text after `data: ` on one frame.
871
- * @returns the response id and credit, or undefined when this frame carries none.
1056
+ * A single slot is deliberate rather than a map: this is a human-driven
1057
+ * diagnostic, the host serialises one turn at a time, and the cost of a
1058
+ * collision (one record with another's verdict) is a re-run, not a wrong fix.
1059
+ * A map would need per-request ids threaded through the client for no gain here.
872
1060
  */
873
- function readCreditFrame(payload) {
874
- if (payload === "" || payload.startsWith("[DONE]")) return void 0;
875
- let parsed;
1061
+ let pending;
1062
+ /** Where the log goes right now, or `undefined` when disarmed. */
1063
+ function captureTarget() {
1064
+ const fromEnv = process.env["WORKBUDDY_CAPTURE_BODY"];
1065
+ if (fromEnv !== void 0 && fromEnv.trim() !== "") return fromEnv;
876
1066
  try {
877
- parsed = JSON.parse(payload);
1067
+ const home = resolveDshHome();
1068
+ return existsSync(join(home, ".workbuddy-capture.on")) ? join(home, CAPTURE_LOG_FILENAME) : void 0;
878
1069
  } catch {
879
1070
  return;
880
1071
  }
881
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
882
- const frame = parsed;
883
- const id = typeof frame["id"] === "string" ? frame["id"] : "";
884
- if (id === "") return void 0;
885
- const usage = frame["usage"];
886
- if (typeof usage !== "object" || usage === null || Array.isArray(usage)) return void 0;
887
- const credit = usage["credit"];
888
- if (typeof credit !== "number" || !Number.isFinite(credit) || credit < 0) return void 0;
889
- return {
890
- id,
891
- credit
892
- };
893
1072
  }
894
1073
  /**
895
- * Split a raw chunk into complete SSE `data:` payloads, carrying the trailing
896
- * partial line into the next chunk.
897
- *
898
- * A TCP read boundary lands wherever it likes — mid-JSON, mid-line — so
899
- * scanning each chunk on its own would parse a truncated object and drop the
900
- * very frame that carries the cost. The remainder is returned for the caller to
901
- * prepend.
1074
+ * Strip credential material before anything is written.
902
1075
  *
903
- * @param carry - bytes left over from the previous chunk.
904
- * @param chunk - the bytes just read.
905
- * @returns the complete payloads, and the new carry.
1076
+ * The log is meant to be pasted into an issue. A bearer token in it would hand
1077
+ * the reporter's account to whoever reads the issue, so redaction happens on the
1078
+ * way in rather than being left to whoever copies the file.
906
1079
  */
907
- function readCreditChunk(carry, chunk) {
908
- const lines = (carry + chunk).split("\n");
909
- const carryOver = lines.pop() ?? "";
910
- const payloads = [];
911
- for (const line of lines) {
912
- const trimmed = line.trimEnd();
913
- if (!trimmed.startsWith("data:")) continue;
914
- payloads.push(trimmed.slice(5).trim());
1080
+ function redacted(headers) {
1081
+ const out = {};
1082
+ for (const [name, value] of Object.entries(headers)) {
1083
+ const lowered = name.toLowerCase();
1084
+ out[name] = lowered === "authorization" || lowered === "cookie" || lowered.includes("token") ? "[redacted]" : value;
915
1085
  }
916
- return {
917
- payloads,
918
- carry: carryOver
919
- };
920
- }
921
- /** Chat-completion POSTs must carry a JSON body type (simple-request CSRF drops here). */
922
- function isJsonContentType(req) {
923
- const type = req.headers["content-type"];
924
- return typeof type === "string" && type.trim().toLowerCase().startsWith("application/json");
1086
+ return out;
925
1087
  }
926
- /** HTTP status each upstream failure class surfaces as. */
927
- const KIND_STATUS = {
928
- hard_credit: 402,
929
- soft_rate: 429,
930
- session_dead: 401,
931
- not_found: 502,
932
- server: 502,
933
- client: 400
934
- };
935
1088
  /**
936
- * What to do when the gateway refuses a request on content (code `11-128`).
937
- *
938
- * Two actions only, and the copy keeps the code spelled `11-128` so that the
939
- * guidance itself, echoed back into a later request, cannot re-arm the gate.
940
- * No status digits (see {@link failureMessage}) and no retry advice: retrying
941
- * the same poisoned conversation reproduces the refusal.
1089
+ * A non-reversible fingerprint of the bearer token, for comparing two runs.
942
1090
  *
943
- * The running version rides along (issue #30): the same symptom reaches users
944
- * on two very different layers — an install older than the fix, and a residual
945
- * trigger after it — and without the version the user cannot tell which layer
946
- * they are on, so the first thing they check is their account.
1091
+ * The token itself stays out of the log, but "was this the same token?" is a real
1092
+ * question when the same body and headers answer 200 on a replay and 400 from the
1093
+ * host: a token refresh between the two makes them different requests. A digest
1094
+ * answers it without storing the secret.
947
1095
  */
948
- function channelGateHint() {
949
- return ` — 渠道校验拦截(11-128)。请新开会话重试;若持续出现,先更新插件(当前 ${WORKBUDDY_BRIDGE_VERSION}) / blocked by channel verification (11-128): start a new conversation, and update the plugin if it persists (running ${WORKBUDDY_BRIDGE_VERSION})`;
1096
+ function tokenFingerprint(headers) {
1097
+ const entry = Object.entries(headers).find(([name]) => name.toLowerCase() === "authorization");
1098
+ if (entry === void 0) return void 0;
1099
+ const token = entry[1].replace(/^Bearer\s+/i, "");
1100
+ if (token === "") return void 0;
1101
+ return createHash("sha256").update(token).digest("hex").slice(0, 12);
950
1102
  }
951
1103
  /**
952
- * What to do when the account's plan excludes the requested model (issue #24).
1104
+ * Remember the request that is about to leave.
953
1105
  *
954
- * No retry advice, because no retry can help: the model is not on this tier,
955
- * and only picking a different model succeeds. The upstream's own
956
- * `displayMsg` ("Your account type does not support this model.") says what is
957
- * wrong but not what to do, which is the gap this fills.
958
- */
959
- const PLAN_LIMIT_HINT = " — 当前账号套餐不包含这个模型(11158),请换用其他模型 / your plan does not include this model (11158): pick another one";
960
- function writeJson(res, status, body) {
961
- const payload = JSON.stringify(body);
962
- res.writeHead(status, {
963
- "Content-Type": "application/json",
964
- "Content-Length": Buffer.byteLength(payload)
965
- });
966
- res.end(payload);
967
- }
968
- function writeOpenAIError(res, status, kind, message) {
969
- writeJson(res, status, { error: {
970
- message,
971
- type: kind,
972
- code: kind
973
- } });
1106
+ * Called from the client's `onChatRequest` hook, i.e. after every header and the
1107
+ * body are final and before the fetch — so what is recorded is what the upstream
1108
+ * receives, not what the caller intended.
1109
+ */
1110
+ function rememberChatRequest(url, headers, body) {
1111
+ if (captureTarget() === void 0) return;
1112
+ pending = {
1113
+ url,
1114
+ headers: redacted(headers),
1115
+ body,
1116
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1117
+ token: tokenFingerprint(headers)
1118
+ };
974
1119
  }
975
1120
  /**
976
- * The one-line reason a failed upstream request is reported with.
977
- *
978
- * The host does not read our HTTP status to classify a failure: `dsh-llm-pi-ai`
979
- * matches the **message text** (`if (/\b(?:401|403)\b/.test(message)) return
980
- * "AUTH"`), and the chat UI then replaces whatever we wrote with
981
- * "API key is invalid". So a status may only appear here when the failure
982
- * really is an authentication one; every other class keeps its digits out, or
983
- * a restricted account or a rejected prompt reaches the user as a bad key.
1121
+ * The most recent request this process captured, with its verdict.
984
1122
  *
985
- * The upstream's own `displayMsg` wins over the raw body: it is the sentence
986
- * written for a human ("账号存在异常行为,已被限制使用"), while the body is a JSON
987
- * document whose `msg` is often a machine phrase such as `request illegal`.
1123
+ * Exists so a maintainer can re-send the exact refused request from **inside**
1124
+ * the host process: the same body, headers and token answered 200 from a separate
1125
+ * process and 400 from the host, which leaves the sending process as the only
1126
+ * remaining variable.
988
1127
  *
989
- * The channel-gate code (`11-128`) appends {@link channelGateHint}: its raw
990
- * body is `{"message":"请求被拦截,请重新发送","type":"client","code":"client"}`,
991
- * which on its own reads as a transient hiccup the user should simply retry —
992
- * the two actions that actually help (a new conversation; update the plugin)
993
- * are not guessable from it. A plan-limit refusal (`11158`) appends
994
- * {@link PLAN_LIMIT_HINT} for the same reason: the fix is "pick another model",
995
- * which the upstream copy does not say.
1128
+ * Falls back to the capture log's last line, because the in-memory slot does not
1129
+ * survive a plugin reload — and a reload is exactly when the experiment is
1130
+ * needed.
996
1131
  */
997
- function failureMessage(result) {
998
- const reason = upstreamDisplayMessage(result.message) ?? result.message.slice(0, 400);
999
- const head = `workbuddy upstream ${result.kind}`;
1000
- const line = result.kind === "session_dead" ? `${head} (http ${result.status}): ${reason}` : `${head}: ${reason}`;
1001
- const gated = isChannelGateBody(result.message) ? `${line}${channelGateHint()}` : line;
1002
- return isPlanLimitBody(result.message) ? `${gated}${PLAN_LIMIT_HINT}` : gated;
1003
- }
1004
- /** Read a request body with a size cap; over-limit bodies fail the request. */ function readBody$1(req) {
1005
- return new Promise((resolve, reject) => {
1006
- const chunks = [];
1007
- let size = 0;
1008
- req.on("data", (chunk) => {
1009
- size += chunk.length;
1010
- if (size > REQUEST_BODY_LIMIT) {
1011
- reject(/* @__PURE__ */ new Error("request body too large"));
1012
- req.destroy();
1013
- return;
1014
- }
1015
- chunks.push(chunk);
1016
- });
1017
- req.on("end", () => resolve(Buffer.concat(chunks)));
1018
- req.on("error", reject);
1019
- });
1132
+ function lastCapturedRequest() {
1133
+ if (lastRequest !== void 0) return lastRequest;
1134
+ const target = captureTarget();
1135
+ if (target === void 0 || !existsSync(target)) return void 0;
1136
+ try {
1137
+ const last = readFileSync(target, "utf8").split("\n").filter((line) => line.trim() !== "").at(-1);
1138
+ if (last === void 0) return void 0;
1139
+ const record = JSON.parse(last);
1140
+ if (typeof record.body !== "string") return void 0;
1141
+ return {
1142
+ body: record.body,
1143
+ at: record.at ?? "",
1144
+ status: record.status ?? 0,
1145
+ headers: record.headers ?? {}
1146
+ };
1147
+ } catch {
1148
+ return;
1149
+ }
1020
1150
  }
1151
+ /** Set by {@link rememberChatRequest} and refreshed by {@link recordChatOutcome}. */
1152
+ let lastRequest;
1021
1153
  /**
1022
- * Start the loopback endpoint. Requests carry any bearer; the loopback bind
1023
- * is the boundary, and the upstream credential comes from the store alone.
1154
+ * Append the pending request with its verdict.
1155
+ *
1156
+ * `status` 0 means a transport failure. A missing pending request (a caller that
1157
+ * skips the hook) writes nothing rather than inventing a record.
1024
1158
  */
1025
- function createWorkBuddyShim(options) {
1026
- const { store, client, catalog, observeCredit } = options;
1027
- const logger = options.logger;
1028
- const SHARED_SECRET = randomBytes(32).toString("base64url");
1029
- /** Constant-time bearer check; absent or mismatched bearers are rejected. */
1030
- function bearerOk(req) {
1031
- const header = req.headers.authorization;
1032
- if (typeof header !== "string") return false;
1033
- const match = /^Bearer\s+(.+)$/i.exec(header.trim());
1034
- if (match === null) return false;
1035
- const presented = match[1];
1036
- const expected = SHARED_SECRET;
1037
- const a = Buffer.from(presented);
1038
- const b = Buffer.from(expected);
1039
- if (a.length !== b.length) return false;
1040
- return timingSafeEqual(a, b);
1041
- }
1042
- const server = createServer((req, res) => {
1043
- handle(req, res);
1044
- });
1045
- const ready = new Promise((resolve, reject) => {
1046
- server.once("listening", () => resolve());
1047
- server.once("error", reject);
1048
- });
1049
- server.listen(0, "127.0.0.1");
1050
- const baseUrl = () => {
1051
- const address = server.address();
1052
- if (address === null || typeof address === "string") throw new Error("workbuddy shim has no listening address");
1053
- return `http://127.0.0.1:${address.port}`;
1054
- };
1055
- async function handle(req, res) {
1056
- try {
1057
- if (!hostIsLoopback(req.headers.host)) {
1058
- writeOpenAIError(res, 403, "host_not_allowed", "Host header must name the loopback interface");
1059
- return;
1060
- }
1061
- if (!originIsLoopback(req.headers.origin)) {
1062
- writeOpenAIError(res, 403, "origin_not_allowed", "Origin must be a loopback origin");
1063
- return;
1064
- }
1065
- if (!bearerOk(req)) {
1066
- writeOpenAIError(res, 401, "unauthorized", "missing or invalid Authorization bearer");
1067
- return;
1068
- }
1069
- const url = req.url ?? "/";
1070
- if (req.method === "GET" && (url === "/healthz" || url === "/healthz/")) {
1071
- writeJson(res, 200, { ok: true });
1072
- return;
1073
- }
1074
- if (req.method === "GET" && (url === "/v1/models" || url === "/v1/models/")) {
1075
- writeJson(res, 200, {
1076
- object: "list",
1077
- data: catalog.current().map((model) => ({
1078
- id: model.id,
1079
- object: "model",
1080
- created: 0,
1081
- owned_by: "workbuddy"
1082
- }))
1083
- });
1084
- return;
1085
- }
1086
- if (req.method === "POST" && (url === "/v1/chat/completions" || url === "/v1/chat/completions/")) {
1087
- await chatCompletions(req, res);
1088
- return;
1089
- }
1090
- writeOpenAIError(res, 404, "not_found", `no such route: ${req.method} ${url}`);
1091
- } catch (error) {
1092
- if (!res.headersSent) writeOpenAIError(res, 500, "internal", String(error));
1093
- else res.end();
1094
- }
1095
- }
1096
- async function chatCompletions(req, res) {
1097
- if (!isJsonContentType(req)) {
1098
- writeOpenAIError(res, 415, "unsupported_media_type", "Content-Type must be application/json");
1099
- return;
1100
- }
1101
- let credential;
1102
- try {
1103
- credential = await store.resolve();
1104
- } catch (error) {
1105
- writeOpenAIError(res, 401, "not_signed_in", String(error));
1106
- return;
1107
- }
1108
- const raw = (await readBody$1(req)).toString("utf8");
1109
- const prepared = prepareChatBody(raw);
1110
- const controller = new AbortController();
1111
- req.on("close", () => controller.abort());
1112
- const result = await client.chatStream(credential, prepared, controller.signal);
1113
- if (!result.ok) {
1114
- writeOpenAIError(res, KIND_STATUS[result.kind], result.kind, failureMessage(result));
1115
- return;
1116
- }
1117
- res.writeHead(200, {
1118
- "Content-Type": "text/event-stream",
1119
- "Cache-Control": "no-cache",
1120
- Connection: "keep-alive",
1121
- "X-Accel-Buffering": "no"
1122
- });
1123
- let sawDone = false;
1124
- /**
1125
- * Bytes of the frame currently being read.
1126
- *
1127
- * The cost arrives on the last usage frame, and that frame is exactly the
1128
- * one a TCP read boundary is most likely to split: parsing each chunk in
1129
- * isolation would drop it. Complete lines are accumulated into `carry` and
1130
- * only whole `data:` payloads are inspected.
1131
- */
1132
- let carry = "";
1133
- /** The last cost observed for this response; reported once, at the end. */
1134
- let observed;
1135
- /**
1136
- * Decodes the byte stream without splitting a multi-byte character across
1137
- * chunks.
1138
- *
1139
- * `chunk.toString('utf8')` would turn a character straddling a read
1140
- * boundary into U+FFFD, and since answers routinely contain Chinese that is
1141
- * not hypothetical. A mangled frame fails `JSON.parse` and is dropped —
1142
- * which for the frame carrying the cost would mean a message silently
1143
- * losing its label.
1144
- */
1145
- const decoder = new StringDecoder("utf8");
1146
- const body = Readable.fromWeb(result.response.body);
1147
- body.on("data", (chunk) => {
1148
- if (chunk.includes("[DONE]")) sawDone = true;
1149
- if (observeCredit === void 0) return;
1150
- const read = readCreditChunk(carry, decoder.write(chunk));
1151
- carry = read.carry;
1152
- for (const payload of read.payloads) {
1153
- const frame = readCreditFrame(payload);
1154
- if (frame !== void 0) observed = frame;
1155
- }
1156
- });
1157
- body.on("error", (error) => {
1158
- logger?.warn("dsh-workbuddy-bridge: upstream stream failed mid-flight", error);
1159
- if (!sawDone && res.writable) res.end("data: [DONE]\n\n");
1160
- });
1161
- body.on("end", () => {
1162
- if (observeCredit !== void 0 && observed !== void 0) observeCredit(observed.id, observed.credit);
1163
- });
1164
- body.pipe(res);
1165
- }
1166
- return {
1167
- ready,
1168
- baseUrl,
1169
- token: () => SHARED_SECRET,
1170
- close: () => new Promise((resolve, reject) => {
1171
- server.close(() => resolve());
1172
- server.closeAllConnections();
1173
- server.once("error", reject);
1174
- })
1159
+ function recordChatOutcome(status, message) {
1160
+ const target = captureTarget();
1161
+ const entry = pending;
1162
+ pending = void 0;
1163
+ if (entry !== void 0) lastRequest = {
1164
+ body: entry.body,
1165
+ at: entry.at,
1166
+ status,
1167
+ headers: entry.headers
1175
1168
  };
1169
+ if (target === void 0 || entry === void 0) return;
1170
+ const line = JSON.stringify({
1171
+ at: entry.at,
1172
+ url: entry.url,
1173
+ status,
1174
+ ...message === void 0 ? {} : { message: message.slice(0, 400) },
1175
+ tokenFingerprint: entry.token,
1176
+ headers: entry.headers,
1177
+ bodyLength: entry.body.length,
1178
+ body: entry.body
1179
+ });
1180
+ try {
1181
+ appendFileSync(target, `${line}\n`, { mode: 384 });
1182
+ } catch {}
1176
1183
  }
1177
1184
  //#endregion
1178
1185
  //#region src/llm/credit-log.ts