dsh-magpie-connect 0.7.0 → 0.7.2

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/dsh.plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-magpie-connect",
3
3
  "description": "Magpie gateway models for the DeepSeek Harness web GUI",
4
- "version": "0.7.0",
4
+ "version": "0.7.2",
5
5
  "entry": {
6
6
  "name": "dsh-magpie-connect",
7
7
  "inject": [
package/lib/client.js CHANGED
@@ -158,8 +158,11 @@ var EN = {
158
158
  "trace.candidate.used": "{n}% used",
159
159
  "trace.candidate.amount": "{amount} / {limit} {unit}",
160
160
  "trace.unit.credits": "credits",
161
+ "trace.unit.credits.total": "total credits",
161
162
  "trace.unit.tokens": "tokens",
163
+ "trace.unit.tokens.total": "total tokens",
162
164
  "trace.unit.requests": "requests",
165
+ "trace.unit.requests.total": "total requests",
163
166
  "trace.webTraceMissing": "Save the Magpie Web Key for full routing-group detail.",
164
167
  "trace.webTraceUnauthorized": "Magpie Web Key was refused; the simplified routing view remains.",
165
168
  "trace.webTraceUnavailable": "Full routing-group detail is unavailable; showing the simplified view.",
@@ -303,8 +306,11 @@ var ZH = {
303
306
  "trace.candidate.used": "\u5DF2\u7528 {n}%",
304
307
  "trace.candidate.amount": "{amount} / {limit} {unit}",
305
308
  "trace.unit.credits": "\u79EF\u5206",
309
+ "trace.unit.credits.total": "\u603B\u79EF\u5206",
306
310
  "trace.unit.tokens": "tokens",
311
+ "trace.unit.tokens.total": "\u603B tokens",
307
312
  "trace.unit.requests": "\u6B21",
313
+ "trace.unit.requests.total": "\u603B\u6B21\u6570",
308
314
  "trace.webTraceMissing": "\u4FDD\u5B58 Magpie Web Key \u540E\u53EF\u663E\u793A\u5B8C\u6574\u8DEF\u7531\u7EC4\u8BE6\u60C5\u3002",
309
315
  "trace.webTraceUnauthorized": "Magpie Web Key \u88AB\u62D2\u7EDD\uFF1B\u5F53\u524D\u663E\u793A\u7B80\u5316\u8DEF\u7531\u89C6\u56FE\u3002",
310
316
  "trace.webTraceUnavailable": "\u5B8C\u6574\u8DEF\u7531\u7EC4\u8BE6\u60C5\u6682\u4E0D\u53EF\u7528\uFF1B\u5F53\u524D\u663E\u793A\u7B80\u5316\u89C6\u56FE\u3002",
@@ -775,7 +781,7 @@ function shouldRetryPending(snapshot2, attempts, limit = PENDING_RETRY_LIMIT) {
775
781
 
776
782
  // src/client/page.tsx
777
783
  var import_jsx_runtime3 = require("react/jsx-runtime");
778
- var PLUGIN_VERSION = "0.6.0";
784
+ var PLUGIN_VERSION = "0.7.2";
779
785
  var REPO_URL = "https://github.com/bitxeno/dsh-magpie-connect";
780
786
  var css2 = {
781
787
  section: { display: "flex", flexDirection: "column", gap: 16, maxWidth: 780, paddingBottom: 32 },
@@ -1282,6 +1288,10 @@ function resetParts(resetsAt, now = Date.now()) {
1282
1288
  if (hours < 48) return { n: hours, unit: "h" };
1283
1289
  return { n: Math.ceil(hours / 24), unit: "d" };
1284
1290
  }
1291
+ function isTotalWindowName(windowName) {
1292
+ if (windowName === void 0) return false;
1293
+ return /^(grand\s+)?total\b/i.test(windowName.trim());
1294
+ }
1285
1295
  function maskUser(user) {
1286
1296
  if (user === void 0) return void 0;
1287
1297
  const at = user.indexOf("@");
@@ -1391,6 +1401,34 @@ function prefersCoarsePointer(target) {
1391
1401
  return matchMedia("(pointer: coarse)").matches;
1392
1402
  }
1393
1403
 
1404
+ // src/client/trace-wires.ts
1405
+ var WIRE_GUTTER = 34;
1406
+ var WIRE_X0 = 10;
1407
+ var WIRE_X1 = 26;
1408
+ var WIRE_Y0 = 16;
1409
+ var NO_WIRES = { width: 0, height: 0, paths: [] };
1410
+ function buildWireState(group, cards, activeIndex, outcomes) {
1411
+ const midX = (WIRE_X0 + WIRE_X1) / 2;
1412
+ const paths = cards.map((card, index) => {
1413
+ const y3 = card.top - group.top + card.height / 2;
1414
+ return {
1415
+ // The S curve: leave the header horizontally, bend through the gutter,
1416
+ // and meet the card horizontally at its mid-height.
1417
+ d: `M${WIRE_X0} ${WIRE_Y0} C${midX} ${WIRE_Y0} ${midX} ${y3} ${WIRE_X1} ${y3}`,
1418
+ active: index === activeIndex,
1419
+ live: outcomes[index] === "processing"
1420
+ };
1421
+ });
1422
+ return { width: WIRE_GUTTER, height: group.height, paths };
1423
+ }
1424
+ function sameWires(a, b) {
1425
+ if (a.width !== b.width || a.height !== b.height || a.paths.length !== b.paths.length) return false;
1426
+ return a.paths.every((path, index) => {
1427
+ const other = b.paths[index];
1428
+ return other !== void 0 && other.d === path.d && other.active === path.active && other.live === path.live;
1429
+ });
1430
+ }
1431
+
1394
1432
  // src/client/trace-button.tsx
1395
1433
  var import_jsx_runtime5 = require("react/jsx-runtime");
1396
1434
  var DESKTOP_REFRESH_MS = 5e3;
@@ -1782,42 +1820,49 @@ function RoutingGroupCard(props) {
1782
1820
  const showHeader = section.hideHeader !== true;
1783
1821
  const activeIndex = section.candidates.findIndex((candidate) => candidate.outcome === "answered" || candidate.outcome === "processing");
1784
1822
  const groupRef = (0, import_react4.useRef)(null);
1785
- const [wires, setWires] = (0, import_react4.useState)({ width: 0, height: 0, paths: [] });
1823
+ const [wires, setWires] = (0, import_react4.useState)(NO_WIRES);
1786
1824
  (0, import_react4.useLayoutEffect)(() => {
1787
1825
  const container = groupRef.current;
1788
1826
  if (container === null || !showHeader) {
1789
- setWires({ width: 0, height: 0, paths: [] });
1827
+ setWires(NO_WIRES);
1790
1828
  return;
1791
1829
  }
1792
1830
  const measure = () => {
1793
- const rect = container.getBoundingClientRect();
1794
1831
  const rows = Array.from(container.querySelectorAll("[data-magpie-candidate]"));
1795
- const x0 = 10;
1796
- const x3 = 26;
1797
- const mx = (x0 + x3) / 2;
1798
- const y0 = 16;
1799
- const paths = rows.map((row, index) => {
1800
- const card = row.getBoundingClientRect();
1801
- const y3 = card.top - rect.top + card.height / 2;
1802
- return {
1803
- d: `M${x0} ${y0} C${mx} ${y0} ${mx} ${y3} ${x3} ${y3}`,
1804
- active: index === activeIndex,
1805
- live: section.candidates[index]?.outcome === "processing"
1806
- };
1807
- });
1808
- setWires({ width: rect.width, height: rect.height, paths });
1832
+ const next = buildWireState(
1833
+ container.getBoundingClientRect(),
1834
+ rows.map((row) => row.getBoundingClientRect()),
1835
+ activeIndex,
1836
+ section.candidates.map((candidate) => candidate.outcome)
1837
+ );
1838
+ setWires((current) => sameWires(current, next) ? current : next);
1809
1839
  };
1810
1840
  measure();
1811
1841
  window.addEventListener("resize", measure);
1812
- return () => window.removeEventListener("resize", measure);
1842
+ const observer = new ResizeObserver(measure);
1843
+ observer.observe(container);
1844
+ return () => {
1845
+ observer.disconnect();
1846
+ window.removeEventListener("resize", measure);
1847
+ };
1813
1848
  }, [showHeader, activeIndex, section.candidates]);
1814
1849
  return /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)("div", { ref: groupRef, style: traceGroupStyle, children: [
1815
- showHeader && wires.width > 0 ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1850
+ showHeader && wires.height > 0 ? /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1816
1851
  "svg",
1817
1852
  {
1818
1853
  "aria-hidden": "true",
1819
- viewBox: `0 0 ${wires.width} ${wires.height}`,
1820
- style: { position: "absolute", inset: 0, width: "100%", height: "100%", overflow: "visible", pointerEvents: "none" },
1854
+ viewBox: `0 0 ${WIRE_GUTTER} ${wires.height}`,
1855
+ style: {
1856
+ position: "absolute",
1857
+ top: 0,
1858
+ left: 0,
1859
+ // An explicit box equal to the viewBox: no aspect-ratio fitting,
1860
+ // so no scale — a stroke stays 1.5px and a wire stays put.
1861
+ width: `${WIRE_GUTTER}px`,
1862
+ height: `${wires.height}px`,
1863
+ overflow: "visible",
1864
+ pointerEvents: "none"
1865
+ },
1821
1866
  children: wires.paths.map((wire, index) => /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(
1822
1867
  "path",
1823
1868
  {
@@ -1899,7 +1944,9 @@ function candidateDetail(candidate) {
1899
1944
  }
1900
1945
  const amount = candidate.amount !== void 0 && Number.isFinite(candidate.amount) ? Math.round(candidate.amount * 100) / 100 : void 0;
1901
1946
  const limit = candidate.limit !== void 0 && Number.isFinite(candidate.limit) ? Math.round(candidate.limit * 100) / 100 : void 0;
1902
- const unit = candidate.unit !== void 0 && candidate.unit !== "" ? text(`trace.unit.${candidate.unit}`) !== `trace.unit.${candidate.unit}` ? text(`trace.unit.${candidate.unit}`) : candidate.unit : "";
1947
+ const windowName = candidate.windowName;
1948
+ const unitKey = candidate.unit !== void 0 && candidate.unit !== "" ? `trace.unit.${candidate.unit}` : "";
1949
+ const unit = isTotalWindowName(windowName) && unitKey !== "" && text(`${unitKey}.total`) !== `${unitKey}.total` ? text(`${unitKey}.total`) : unitKey !== "" && text(unitKey) !== unitKey ? text(unitKey) : candidate.unit ?? "";
1903
1950
  const amountText = amount !== void 0 && limit !== void 0 ? text("trace.candidate.amount", { amount, limit, unit }).trim() : candidate.usedPct !== void 0 ? text("trace.candidate.used", { n: candidate.usedPct }) : "";
1904
1951
  const renew = candidate.renews?.[0] !== void 0 ? resetParts(candidate.renews[0]) : void 0;
1905
1952
  const resetText = renew !== void 0 ? text("trace.quotaReset", { d: formatDuration(renew, "reset") }) : "";
package/lib/index.js CHANGED
@@ -1717,14 +1717,65 @@ function statusForStatusCode(code) {
1717
1717
  if (code >= 500) return "network";
1718
1718
  return "unknown";
1719
1719
  }
1720
+ var WEB_PROBE_TIMEOUT_MS = 1500;
1721
+ var WEB_COOKIE_FALLBACK_PORTS = ["3430", "443", "80"];
1722
+ function guessedWebCookie(base) {
1723
+ try {
1724
+ const url = new URL(base);
1725
+ return `magpie_web_${url.port || (url.protocol === "https:" ? "443" : "80")}`;
1726
+ } catch {
1727
+ return "magpie_web_3430";
1728
+ }
1729
+ }
1730
+ var webCookieNames = /* @__PURE__ */ new Map();
1731
+ var webBasesResolved = /* @__PURE__ */ new Map();
1732
+ async function discoverWebCookieName(base, webKey, signal) {
1733
+ try {
1734
+ const response = await fetch(`${base.replace(/\/+$/, "")}/?k=${encodeURIComponent(webKey)}`, {
1735
+ redirect: "manual",
1736
+ cache: "no-store",
1737
+ signal
1738
+ });
1739
+ const match = /magpie_web_[A-Za-z0-9._-]+/.exec(response.headers.get("set-cookie") ?? "");
1740
+ return match?.[0];
1741
+ } catch {
1742
+ return void 0;
1743
+ }
1744
+ }
1745
+ async function fetchWebResponse(base, webKey, path, accept, signal) {
1746
+ const tried = [];
1747
+ const attempt = (name2) => {
1748
+ tried.push(name2);
1749
+ return fetch(`${base}${path}`, {
1750
+ headers: { cookie: `${name2}=${webKey}`, accept },
1751
+ cache: "no-store",
1752
+ signal
1753
+ });
1754
+ };
1755
+ const cached = webCookieNames.get(base);
1756
+ let response = await attempt(cached ?? guessedWebCookie(base));
1757
+ if (response.status === 401) {
1758
+ const discovered = await discoverWebCookieName(base, webKey, signal);
1759
+ if (discovered !== void 0 && !tried.includes(discovered)) {
1760
+ response = await attempt(discovered);
1761
+ }
1762
+ if (response.status === 401) {
1763
+ for (const port of WEB_COOKIE_FALLBACK_PORTS) {
1764
+ const name2 = `magpie_web_${port}`;
1765
+ if (tried.includes(name2)) continue;
1766
+ response = await attempt(name2);
1767
+ if (response.status !== 401) break;
1768
+ }
1769
+ }
1770
+ }
1771
+ if (response.ok) {
1772
+ const winner = tried[tried.length - 1];
1773
+ if (winner !== void 0) webCookieNames.set(base, winner);
1774
+ }
1775
+ return response;
1776
+ }
1720
1777
  async function fetchWebJson(base, webKey, path, signal) {
1721
- const url = new URL(base);
1722
- const port = url.port || (url.protocol === "https:" ? "443" : "80");
1723
- const response = await fetch(`${base}${path}`, {
1724
- headers: { cookie: `magpie_web_${port}=${webKey}`, accept: "application/json" },
1725
- cache: "no-store",
1726
- signal
1727
- });
1778
+ const response = await fetchWebResponse(base, webKey, path, "application/json", signal);
1728
1779
  if (!response.ok) {
1729
1780
  const error = new Error(`Magpie Web HTTP ${response.status} ${path}`);
1730
1781
  error.statusCode = response.status;
@@ -1733,29 +1784,40 @@ async function fetchWebJson(base, webKey, path, signal) {
1733
1784
  return await response.json();
1734
1785
  }
1735
1786
  function webBases(base) {
1736
- const candidates = [];
1787
+ const candidates = [base];
1737
1788
  try {
1738
1789
  const url = new URL(base);
1739
- if (url.port === "3430") return [base];
1740
- url.port = "3430";
1741
- candidates.push(`${url.origin}${url.pathname.replace(/\/+$/, "")}`);
1742
- candidates.push(base);
1790
+ if (url.port !== "3430") {
1791
+ url.port = "3430";
1792
+ candidates.push(`${url.origin}${url.pathname.replace(/\/+$/, "")}`);
1793
+ }
1743
1794
  } catch {
1744
1795
  return [base];
1745
1796
  }
1746
1797
  return [...new Set(candidates)];
1747
1798
  }
1799
+ function orderedWebBases(base) {
1800
+ const bases = webBases(base);
1801
+ const known = webBasesResolved.get(base);
1802
+ return known !== void 0 && bases.includes(known) ? [known, ...bases.filter((b) => b !== known)] : bases;
1803
+ }
1804
+ function webTrySignal(signal, index) {
1805
+ if (index === 0) return signal;
1806
+ const budget = AbortSignal.timeout(WEB_PROBE_TIMEOUT_MS);
1807
+ return typeof AbortSignal.any === "function" ? AbortSignal.any([signal, budget]) : budget;
1808
+ }
1748
1809
  async function fetchFullWebTrace(base, webKey, signal) {
1749
1810
  let lastError;
1750
- for (const candidate of webBases(base)) {
1811
+ for (const [index, candidate] of orderedWebBases(base).entries()) {
1751
1812
  try {
1752
- const trace = await fetchWebJson(candidate, webKey, `${WEB_TRACE_PATH}?after=0`, signal);
1813
+ const trace = await fetchWebJson(candidate, webKey, `${WEB_TRACE_PATH}?after=0`, webTrySignal(signal, index));
1753
1814
  if (!Array.isArray(trace.routes)) {
1754
1815
  throw new Error("Magpie Web returned an unexpected trace shape");
1755
1816
  }
1817
+ webBasesResolved.set(base, candidate);
1756
1818
  return { trace, base: candidate };
1757
1819
  } catch (error) {
1758
- if (isAbort(error)) throw error;
1820
+ if (signal.aborted) throw error;
1759
1821
  lastError = error;
1760
1822
  }
1761
1823
  }
@@ -1765,13 +1827,7 @@ function routingUrlFor(base) {
1765
1827
  return `${base.replace(/\/+$/, "")}/?view=routing`;
1766
1828
  }
1767
1829
  async function fetchWebBinary(base, webKey, path, signal) {
1768
- const url = new URL(base);
1769
- const port = url.port || (url.protocol === "https:" ? "443" : "80");
1770
- const response = await fetch(`${base}${path}`, {
1771
- headers: { cookie: `magpie_web_${port}=${webKey}`, accept: "image/svg+xml,image/png,*/*" },
1772
- cache: "no-store",
1773
- signal
1774
- });
1830
+ const response = await fetchWebResponse(base, webKey, path, "image/svg+xml,image/png,*/*", signal);
1775
1831
  if (!response.ok) {
1776
1832
  const error = new Error(`Magpie Web HTTP ${response.status} ${path}`);
1777
1833
  error.statusCode = response.status;
@@ -1803,11 +1859,13 @@ async function fetchWebIcon(base, webKey, name2, signal) {
1803
1859
  const ext = PNG_ICONS.has(safe) ? "png" : "svg";
1804
1860
  const path = `/icons/${safe}.${ext}`;
1805
1861
  let lastError;
1806
- for (const candidate of webBases(base)) {
1862
+ for (const [index, candidate] of orderedWebBases(base).entries()) {
1807
1863
  try {
1808
- return await fetchWebBinary(candidate, webKey, path, signal);
1864
+ const icon = await fetchWebBinary(candidate, webKey, path, webTrySignal(signal, index));
1865
+ webBasesResolved.set(base, candidate);
1866
+ return icon;
1809
1867
  } catch (error) {
1810
- if (isAbort(error)) throw error;
1868
+ if (signal.aborted) throw error;
1811
1869
  lastError = error;
1812
1870
  }
1813
1871
  }
@@ -1860,8 +1918,16 @@ function maskHolder(user) {
1860
1918
  const head = user.slice(0, Math.max(1, Math.min(at, 4)));
1861
1919
  return `${head}\u2026`;
1862
1920
  }
1921
+ function isTotalWindow(entry) {
1922
+ return /^(grand\s+)?total\b/i.test((str(entry, "name") ?? "").trim());
1923
+ }
1924
+ function hasShare(entry) {
1925
+ return num(entry, "used") !== void 0 || pctOfParts(entry) !== void 0;
1926
+ }
1863
1927
  function pickWindow(windows) {
1864
- return windows.find((entry) => num(entry, "used") !== void 0 || pctOfParts(entry) !== void 0) ?? windows.find((entry) => str(entry, "resetsAt") !== void 0) ?? windows[0];
1928
+ const usable = windows.filter((entry) => entry.unlimited !== true && hasShare(entry));
1929
+ const counted = windows.filter((entry) => entry.unlimited !== true);
1930
+ return usable.find(isTotalWindow) ?? usable[0] ?? counted.find((entry) => str(entry, "resetsAt") !== void 0) ?? counted[0] ?? windows[0];
1865
1931
  }
1866
1932
  function toAccountRow(account) {
1867
1933
  const provider = str(account, "name") ?? str(account, "provider");
@@ -1929,6 +1995,8 @@ function toTraceCandidate(entry, outcome, restOverride) {
1929
1995
  const via = Array.isArray(entry.via) ? entry.via.filter((value) => typeof value === "string" && value !== "") : [];
1930
1996
  const amount = num(entry, "amount");
1931
1997
  const limit = num(entry, "limit");
1998
+ const partsPct = pctOfParts(entry);
1999
+ const usedPct = amount !== void 0 && limit !== void 0 && limit > 0 ? partsPct ?? pctOf(used) : pctOf(used);
1932
2000
  const restRaw = restOverride ?? (entry.rest && typeof entry.rest === "object" ? entry.rest : void 0);
1933
2001
  const status = num(entry, "status");
1934
2002
  const ms = num(entry, "ms");
@@ -1944,10 +2012,11 @@ function toTraceCandidate(entry, outcome, restOverride) {
1944
2012
  ...str(entry, "model") !== void 0 ? { model: str(entry, "model") } : {},
1945
2013
  ...str(entry, "fixed") !== void 0 ? { fixed: str(entry, "fixed") } : {},
1946
2014
  ...via.length > 0 ? { via } : {},
1947
- ...used !== void 0 ? { usedPct: pctOf(used) } : {},
2015
+ ...usedPct !== void 0 ? { usedPct } : {},
1948
2016
  ...amount !== void 0 ? { amount } : {},
1949
2017
  ...limit !== void 0 ? { limit } : {},
1950
2018
  ...str(entry, "unit") !== void 0 ? { unit: str(entry, "unit") } : {},
2019
+ ...str(entry, "windowName") !== void 0 ? { windowName: str(entry, "windowName") } : {},
1951
2020
  ...renews.length > 0 ? { renews } : {},
1952
2021
  ...restRaw !== void 0 ? { rest: restRaw } : {},
1953
2022
  outcome,
@@ -2016,12 +2085,20 @@ function toSessionTrace(route, accounts) {
2016
2085
  const quota = accounts.find(
2017
2086
  (account) => account.providerId === str(entry, "provider") && ((account.user ?? "").toLowerCase() === maskHolder(str(entry, "who"))?.toLowerCase() || account.user === void 0)
2018
2087
  );
2088
+ const entryAmount = num(entry, "amount");
2089
+ const entryLimit = num(entry, "limit");
2090
+ const namesPickedWindow = quota?.windowName !== void 0 && (entryAmount === void 0 && entryLimit === void 0 || entryLimit !== void 0 && quota.limit !== void 0 && Math.abs(entryLimit - quota.limit) < 0.01);
2019
2091
  const quotaEnrichment = {
2020
- ...quota?.usedPct !== void 0 && num(entry, "used") === void 0 ? { used: quota.usedPct } : {},
2021
- ...quota?.resetsAt !== void 0 && !Array.isArray(entry.renews) ? { renews: [quota.resetsAt] } : {},
2022
- ...quota?.amount !== void 0 ? { amount: quota.amount } : {},
2023
- ...quota?.limit !== void 0 ? { limit: quota.limit } : {},
2024
- ...quota?.unit !== void 0 ? { unit: quota.unit } : {}
2092
+ // The trace row's own counters are what routing weighed, so they win;
2093
+ // the quota windows only fill what the row left out. Filling `used` from
2094
+ // one window while `amount`/`limit` came from another is exactly the
2095
+ // mismatch this guard prevents.
2096
+ ...num(entry, "used") === void 0 && quota?.usedPct !== void 0 ? { used: quota.usedPct } : {},
2097
+ ...entryAmount === void 0 && quota?.amount !== void 0 ? { amount: quota.amount } : {},
2098
+ ...entryLimit === void 0 && quota?.limit !== void 0 ? { limit: quota.limit } : {},
2099
+ ...str(entry, "unit") === void 0 && quota?.unit !== void 0 ? { unit: quota.unit } : {},
2100
+ ...str(entry, "windowName") === void 0 && namesPickedWindow ? { windowName: quota.windowName } : {},
2101
+ ...!Array.isArray(entry.renews) && quota?.resetsAt !== void 0 ? { renews: [quota.resetsAt] } : {}
2025
2102
  };
2026
2103
  const row = toTraceCandidate({ ...entry, ...quotaEnrichment }, kind, tried?.rest);
2027
2104
  if (row === void 0) return void 0;