@vibedev-si/dsh-vibedev 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -49,8 +49,8 @@ const MIN_READ_SPACING_MS = 5e3;
49
49
  * current when nobody opens anything.
50
50
  */
51
51
  const CATALOG_REFRESH_GAP_MS = 6e4;
52
- const record$13 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
53
- const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
52
+ const record$14 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
53
+ const text$9 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
54
54
  /**
55
55
  * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
56
56
  * writes with an exponent are spelled out), a string as sent; anything else, or text that is not a plain decimal, is
@@ -62,7 +62,7 @@ function amountOf(value) {
62
62
  if (!Number.isFinite(value)) return void 0;
63
63
  raw = String(value);
64
64
  if (raw.includes("e")) raw = Math.abs(value) >= 1 ? BigInt(value).toString() : value.toFixed(20).replace(/0+$/, "").replace(/\.$/, "");
65
- } else raw = text$8(value);
65
+ } else raw = text$9(value);
66
66
  return raw !== void 0 && /^-?\d+(\.\d+)?$/.test(raw) ? raw : void 0;
67
67
  }
68
68
  /** What a read showed, for telling whether the next one changed anything (when it was read is not a change). */
@@ -304,14 +304,14 @@ var AccountService = class {
304
304
  redirect: "error"
305
305
  });
306
306
  if (!response.ok) return {};
307
- const body = record$13(await response.json().catch(() => void 0));
308
- const data = record$13(body?.data) ?? body;
307
+ const body = record$14(await response.json().catch(() => void 0));
308
+ const data = record$14(body?.data) ?? body;
309
309
  const balance = amountOf(data?.balance);
310
- const currency = text$8(data?.currency) ?? "CNY";
310
+ const currency = text$9(data?.currency) ?? "CNY";
311
311
  const frozen = amountOf(data?.frozen_balance);
312
- const id = typeof data?.id === "number" ? String(data.id) : text$8(data?.id);
313
- const nickname = text$8(data?.nickname) ?? text$8(data?.username);
314
- const email = text$8(data?.email);
312
+ const id = typeof data?.id === "number" ? String(data.id) : text$9(data?.id);
313
+ const nickname = text$9(data?.nickname) ?? text$9(data?.username);
314
+ const email = text$9(data?.email);
315
315
  const user = id === void 0 && nickname === void 0 && email === void 0 ? void 0 : {
316
316
  ...id === void 0 ? {} : { id },
317
317
  ...email === void 0 ? {} : { email },
@@ -416,7 +416,7 @@ function userOf(user) {
416
416
  ...nickname === void 0 ? {} : { nickname }
417
417
  };
418
418
  }
419
- function json$2(status, body) {
419
+ function json$3(status, body) {
420
420
  return new Response(JSON.stringify(body), {
421
421
  status,
422
422
  headers: {
@@ -426,9 +426,9 @@ function json$2(status, body) {
426
426
  });
427
427
  }
428
428
  function failure$1(error) {
429
- const candidate = record$13(error)?.code;
429
+ const candidate = record$14(error)?.code;
430
430
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
431
- return json$2(500, { error: {
431
+ return json$3(500, { error: {
432
432
  code,
433
433
  message: code === "SIGN_IN_CANCELLED" ? "Sign-in was cancelled. 登录已取消。" : code === "SIGN_IN_TIMEOUT" ? "Sign-in expired. 登录已超时,请重新登录。" : "The account request could not be completed. 账号请求未完成,请查看登录诊断后重试。"
434
434
  } });
@@ -445,8 +445,8 @@ function accountRoutes(account) {
445
445
  methods: ["POST"],
446
446
  requestBody: "buffered",
447
447
  fetch: async (request) => {
448
- const body = record$13(await request.json().catch(() => void 0));
449
- return json$2(200, { consumed: typeof body?.id === "string" && account.consumeNavigation(body.id) });
448
+ const body = record$14(await request.json().catch(() => void 0));
449
+ return json$3(200, { consumed: typeof body?.id === "string" && account.consumeNavigation(body.id) });
450
450
  }
451
451
  },
452
452
  {
@@ -458,7 +458,7 @@ function accountRoutes(account) {
458
458
  const query = new URL(request.url, "http://host").searchParams;
459
459
  const since = query.get("since");
460
460
  if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
461
- return json$2(200, await account.view(query.get("fresh") === "1"));
461
+ return json$3(200, await account.view(query.get("fresh") === "1"));
462
462
  } catch (error) {
463
463
  return failure$1(error);
464
464
  }
@@ -470,8 +470,8 @@ function accountRoutes(account) {
470
470
  requestBody: "buffered",
471
471
  fetch: async (request) => {
472
472
  try {
473
- const body = record$13(await request.json().catch(() => void 0));
474
- return json$2(200, await account.signIn(body?.open !== false));
473
+ const body = record$14(await request.json().catch(() => void 0));
474
+ return json$3(200, await account.signIn(body?.open !== false));
475
475
  } catch (error) {
476
476
  return failure$1(error);
477
477
  }
@@ -483,7 +483,7 @@ function accountRoutes(account) {
483
483
  requestBody: "buffered",
484
484
  fetch: () => {
485
485
  account.cancel();
486
- return Promise.resolve(json$2(200, { ok: true }));
486
+ return Promise.resolve(json$3(200, { ok: true }));
487
487
  }
488
488
  },
489
489
  {
@@ -492,7 +492,7 @@ function accountRoutes(account) {
492
492
  requestBody: "buffered",
493
493
  fetch: async () => {
494
494
  try {
495
- return await account.signOut() ? json$2(200, { ok: true }) : json$2(409, { error: {
495
+ return await account.signOut() ? json$3(200, { ok: true }) : json$3(409, { error: {
496
496
  code: "SIGNED_IN_BY_APP",
497
497
  message: "The VibeDev account is the app's sign-in; sign out in the app."
498
498
  } });
@@ -605,10 +605,10 @@ function normalizeErrorStage(value) {
605
605
  request: "submit"
606
606
  }[word];
607
607
  }
608
- function record$12(value) {
608
+ function record$13(value) {
609
609
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
610
610
  }
611
- function text$7(value) {
611
+ function text$8(value) {
612
612
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
613
613
  }
614
614
  function count$1(value) {
@@ -617,7 +617,7 @@ function count$1(value) {
617
617
  /** A CNY amount the gateway sends as a two-decimal string (a number is accepted too). */
618
618
  function amount$1(value) {
619
619
  if (typeof value === "number" && Number.isFinite(value)) return value.toFixed(2);
620
- const raw = text$7(value);
620
+ const raw = text$8(value);
621
621
  return raw !== void 0 && /^-?\d+(?:\.\d+)?$/.test(raw) ? raw : void 0;
622
622
  }
623
623
  /**
@@ -631,16 +631,16 @@ function amount$1(value) {
631
631
  * @returns the fields found.
632
632
  */
633
633
  function parseGatewayFailure(body) {
634
- const root = record$12(body);
634
+ const root = record$13(body);
635
635
  if (root === void 0) return {};
636
- const source = record$12(root.error) ?? root;
637
- const metadata = record$12(source.metadata) ?? record$12(root.metadata);
638
- const gatewayCode = text$7(source.gateway_code) ?? text$7(root.gateway_code);
639
- const code = gatewayCode ?? text$7(source.code) ?? text$7(source.type) ?? text$7(root.reason);
640
- const message = text$7(source.message) ?? (typeof root.error === "string" ? text$7(root.error) : void 0);
641
- const field = text$7(source.field) ?? text$7(metadata?.field);
642
- const rule = text$7(source.rule) ?? text$7(metadata?.rule);
643
- const rechargeUrl = text$7(source.recharge_url) ?? text$7(root.recharge_url);
636
+ const source = record$13(root.error) ?? root;
637
+ const metadata = record$13(source.metadata) ?? record$13(root.metadata);
638
+ const gatewayCode = text$8(source.gateway_code) ?? text$8(root.gateway_code);
639
+ const code = gatewayCode ?? text$8(source.code) ?? text$8(source.type) ?? text$8(root.reason);
640
+ const message = text$8(source.message) ?? (typeof root.error === "string" ? text$8(root.error) : void 0);
641
+ const field = text$8(source.field) ?? text$8(metadata?.field);
642
+ const rule = text$8(source.rule) ?? text$8(metadata?.rule);
643
+ const rechargeUrl = text$8(source.recharge_url) ?? text$8(root.recharge_url);
644
644
  const numbers = {
645
645
  active: count$1(source.active),
646
646
  limit: count$1(source.limit)
@@ -650,19 +650,19 @@ function parseGatewayFailure(body) {
650
650
  availableCny: amount$1(source.available_cny),
651
651
  pendingCny: amount$1(source.pending_cny)
652
652
  };
653
- const submissionState = text$7(source.submission_state) ?? text$7(root.submission_state);
654
- const retryAction = text$7(source.retry_action) ?? text$7(root.retry_action);
655
- const assetId = text$7(source.asset_id) ?? text$7(root.asset_id);
653
+ const submissionState = text$8(source.submission_state) ?? text$8(root.submission_state);
654
+ const retryAction = text$8(source.retry_action) ?? text$8(root.retry_action);
655
+ const assetId = text$8(source.asset_id) ?? text$8(root.asset_id);
656
656
  return {
657
657
  ...gatewayCode === void 0 ? {} : { gatewayCode },
658
658
  ...Object.fromEntries(Object.entries({
659
- category: normalizeErrorCategory(text$7(source.category) ?? text$7(root.category), code),
660
- stage: normalizeErrorStage(text$7(source.stage) ?? text$7(root.stage)),
661
- requestId: text$7(source.request_id) ?? text$7(root.request_id),
662
- taskId: text$7(source.task_id) ?? text$7(root.task_id),
663
- operationId: text$7(source.operation_id) ?? text$7(root.operation_id),
664
- billingState: text$7(source.billing_state) ?? text$7(root.billing_state),
665
- retryAt: text$7(source.retry_at) ?? text$7(root.retry_at),
659
+ category: normalizeErrorCategory(text$8(source.category) ?? text$8(root.category), code),
660
+ stage: normalizeErrorStage(text$8(source.stage) ?? text$8(root.stage)),
661
+ requestId: text$8(source.request_id) ?? text$8(root.request_id),
662
+ taskId: text$8(source.task_id) ?? text$8(root.task_id),
663
+ operationId: text$8(source.operation_id) ?? text$8(root.operation_id),
664
+ billingState: text$8(source.billing_state) ?? text$8(root.billing_state),
665
+ retryAt: text$8(source.retry_at) ?? text$8(root.retry_at),
666
666
  retryAfterSeconds: count$1(source.retry_after_seconds) ?? count$1(root.retry_after_seconds)
667
667
  }).filter(([, value]) => value !== void 0)),
668
668
  ...code === void 0 ? {} : { code },
@@ -729,11 +729,11 @@ function gatewayFailureWithHeaders(body, headers) {
729
729
  const failure = parseGatewayFailure(body);
730
730
  return {
731
731
  ...failure,
732
- code: failure.gatewayCode ?? text$7(headers.get("x-vibedev-error-code")) ?? failure.code,
733
- category: normalizeErrorCategory(failure.category ?? text$7(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$7(headers.get("x-vibedev-error-code")) ?? failure.code),
734
- requestId: failure.requestId ?? text$7(headers.get("x-request-id")),
735
- retryAction: failure.retryAction ?? text$7(headers.get("x-vibedev-retry-action")),
736
- retryAt: failure.retryAt ?? text$7(headers.get("x-vibedev-retry-at"))
732
+ code: failure.gatewayCode ?? text$8(headers.get("x-vibedev-error-code")) ?? failure.code,
733
+ category: normalizeErrorCategory(failure.category ?? text$8(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$8(headers.get("x-vibedev-error-code")) ?? failure.code),
734
+ requestId: failure.requestId ?? text$8(headers.get("x-request-id")),
735
+ retryAction: failure.retryAction ?? text$8(headers.get("x-vibedev-retry-action")),
736
+ retryAt: failure.retryAt ?? text$8(headers.get("x-vibedev-retry-at"))
737
737
  };
738
738
  }
739
739
  function isUserAuthenticationFailure(failure) {
@@ -742,19 +742,19 @@ function isUserAuthenticationFailure(failure) {
742
742
  function sdkGatewayFailure(message, headers = {}) {
743
743
  const prefix = /\bvibedev:([A-Z][A-Z0-9_]{1,100}):/.exec(message)?.[1];
744
744
  const legacy = /["'](?:gateway_code|code)["']\s*:\s*["'](APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)["']/.exec(message)?.[1];
745
- const code = text$7(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
746
- const category = text$7(headers["x-vibedev-error-category"]) ?? (code === void 0 ? void 0 : /^(?:APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)$/.test(code) ? "authentication" : /^(?:BALANCE_INSUFFICIENT|SUBSCRIPTION_QUOTA_EXHAUSTED|MODEL_NOT_INCLUDED|BILLING_SOURCE_UNAVAILABLE)$/.test(code) ? "billing" : code === "CONTENT_REJECTED" ? "content_rejected" : code === "SUBMISSION_UNCERTAIN" ? "submission_uncertain" : /^(?:UPSTREAM_UNAVAILABLE|TASK_QUERY_UNAVAILABLE|RESULT_DOWNLOAD_UNAVAILABLE)$/.test(code) ? "service_unavailable" : "internal_error");
745
+ const code = text$8(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
746
+ const category = text$8(headers["x-vibedev-error-category"]) ?? (code === void 0 ? void 0 : /^(?:APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)$/.test(code) ? "authentication" : /^(?:BALANCE_INSUFFICIENT|SUBSCRIPTION_QUOTA_EXHAUSTED|MODEL_NOT_INCLUDED|BILLING_SOURCE_UNAVAILABLE)$/.test(code) ? "billing" : code === "CONTENT_REJECTED" ? "content_rejected" : code === "SUBMISSION_UNCERTAIN" ? "submission_uncertain" : /^(?:UPSTREAM_UNAVAILABLE|TASK_QUERY_UNAVAILABLE|RESULT_DOWNLOAD_UNAVAILABLE)$/.test(code) ? "service_unavailable" : "internal_error");
747
747
  if (code === void 0 && category === void 0) return void 0;
748
748
  return {
749
749
  code,
750
750
  category: normalizeErrorCategory(category, code),
751
- requestId: text$7(headers["x-request-id"]),
752
- retryAction: text$7(headers["x-vibedev-retry-action"])
751
+ requestId: text$8(headers["x-request-id"]),
752
+ retryAction: text$8(headers["x-vibedev-retry-action"])
753
753
  };
754
754
  }
755
755
  //#endregion
756
756
  //#region src/account/center-price-contract.ts
757
- const record$11 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
757
+ const record$12 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
758
758
  const keys = (value = "") => value.split(" ").filter(Boolean);
759
759
  const scalar$1 = (value) => value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && value.length <= 1e3 && !/\b(?:Bearer\s|vdat_|sk-)|https?:\/\/|eyJ[A-Za-z0-9_-]+\./i.test(value) ? value : void 0;
760
760
  /** Only public DNS HTTPS references become navigable links. No credentials, IPs or local hosts. */
@@ -772,7 +772,7 @@ function publicReferenceUrl(value) {
772
772
  }
773
773
  function project$1(value, shape) {
774
774
  if (value === null) return null;
775
- const source = record$11(value);
775
+ const source = record$12(value);
776
776
  if (!source) return void 0;
777
777
  const out = {};
778
778
  for (const key of keys(shape.fields)) {
@@ -800,7 +800,7 @@ function project$1(value, shape) {
800
800
  out[key] = source[key].slice(0, key === "models" ? 48 : 1e3).map((item) => child === "scalar" ? scalar$1(item) : child === "matrix" ? Array.isArray(item) ? item.slice(0, 64).map(scalar$1).filter((v) => v !== void 0) : void 0 : project$1(item, child)).filter((item) => item !== void 0);
801
801
  }
802
802
  for (const [key, child] of Object.entries(shape.maps ?? {})) {
803
- const map = record$11(source[key]);
803
+ const map = record$12(source[key]);
804
804
  if (!map) continue;
805
805
  out[key] = Object.fromEntries(Object.entries(map).slice(0, 64).filter(([name, value]) => /^[a-z][a-z0-9_]{0,63}$/i.test(name) && !/secret|password|credential|api_key/i.test(name) && (key !== "reasoning_effort_multipliers" || [
806
806
  "none",
@@ -1628,11 +1628,11 @@ function projectBusinessReceipt(value) {
1628
1628
  //#endregion
1629
1629
  //#region src/account/center-contract.ts
1630
1630
  /** Exact, read-only account-page schemas. No caller-selected URL or object shape. */
1631
- const record$10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1631
+ const record$11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1632
1632
  const fields = (text) => text.split(" ");
1633
1633
  const scalar = (value) => value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && value.length <= 1e3 && !/\b(?:Bearer\s|vdat_|sk-)|https?:\/\/|eyJ[A-Za-z0-9_-]+\./i.test(value) ? value : void 0;
1634
1634
  function project(value, shape) {
1635
- const source = record$10(value);
1635
+ const source = record$11(value);
1636
1636
  if (source === void 0) return void 0;
1637
1637
  if (shape === imageSizes) return Object.fromEntries(Object.entries(source).filter(([key, item]) => {
1638
1638
  const kilo = /^(\d{1,2}(?:\.\d{1,3})?)K$/.exec(key), dimensions = /^(\d{1,5})x(\d{1,5})$/.exec(key);
@@ -1887,7 +1887,7 @@ function centerQuery(path, params) {
1887
1887
  /** Legacy summary only: monetary weekly fields become a percentage, never a five-hour window. */
1888
1888
  function projectAccountData(value) {
1889
1889
  const convert = (item) => {
1890
- const output = project(item, subscription), source = record$10(item);
1890
+ const output = project(item, subscription), source = record$11(item);
1891
1891
  if (output === void 0 || source === void 0) return void 0;
1892
1892
  const number = (n) => typeof n === "number" && Number.isFinite(n) ? n : typeof n === "string" && /^\d+(?:\.\d+)?$/.test(n) ? Number(n) : void 0;
1893
1893
  const used = number(source.weekly_used_usd), limit = number(source.weekly_limit_usd);
@@ -1899,7 +1899,7 @@ function projectAccountData(value) {
1899
1899
  return output;
1900
1900
  };
1901
1901
  if (Array.isArray(value)) return value.slice(0, 1e3).map(convert).filter((item) => item !== void 0);
1902
- const source = record$10(value);
1902
+ const source = record$11(value);
1903
1903
  return source === void 0 ? {} : {
1904
1904
  ...project(source, { fields: ["active_count"] }),
1905
1905
  ...Array.isArray(source.subscriptions) ? { subscriptions: source.subscriptions.slice(0, 1e3).map(convert).filter((item) => item !== void 0) } : {}
@@ -2136,6 +2136,178 @@ function accountCenterRoutes(http, account) {
2136
2136
  })), ...accountBusinessActionsRoutes(http, account)];
2137
2137
  }
2138
2138
  //#endregion
2139
+ //#region src/announcements/routes.ts
2140
+ /** The Host route the renderer polls. */
2141
+ const ANNOUNCEMENTS_ROUTE = "/api/dsh-vibedev/announcements";
2142
+ /**
2143
+ * The receipt's own Host route. A Host Fetch route owns one exact pathname, so this is a
2144
+ * sibling of the list rather than a `:id` child of it; the id is in the request body.
2145
+ */
2146
+ const ANNOUNCEMENTS_READ_ROUTE = `${ANNOUNCEMENTS_ROUTE}/read`;
2147
+ /**
2148
+ * Where the gateway serves the same list. Every account read goes to `/v1/account/*`
2149
+ * (`auth/me`, `entitlements`, `model-plaza`, `payment/*`, and our own `feedback`), so
2150
+ * announcements belong beside them; `/api/v1/vibedev/*` is only the sign-in and
2151
+ * device-authorization surface (`app-token/*`, `link/redeem`).
2152
+ */
2153
+ const GATEWAY_ANNOUNCEMENTS_PATH = "/v1/account/announcements";
2154
+ const json$2 = (status, body) => new Response(JSON.stringify(body), {
2155
+ status,
2156
+ headers: {
2157
+ "content-type": "application/json; charset=utf-8",
2158
+ "cache-control": "no-store"
2159
+ }
2160
+ });
2161
+ const unavailable = () => json$2(200, {
2162
+ available: false,
2163
+ items: [],
2164
+ unread: 0
2165
+ });
2166
+ const record$10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2167
+ const text$7 = (value) => typeof value === "string" ? value : void 0;
2168
+ const identifier = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
2169
+ /**
2170
+ * One announcement from the wire, with every field it needs and nothing else.
2171
+ * @param value - one entry of the gateway's list.
2172
+ * @returns the announcement, or undefined when the entry cannot be rendered.
2173
+ */
2174
+ function parseAnnouncement(value) {
2175
+ const item = record$10(value);
2176
+ if (item === void 0) return void 0;
2177
+ const id = identifier(item.id);
2178
+ const title = text$7(item.title);
2179
+ const content = text$7(item.content);
2180
+ const createdAt = text$7(item.created_at);
2181
+ if (id === void 0 || title === void 0 || content === void 0 || createdAt === void 0) return void 0;
2182
+ return {
2183
+ id,
2184
+ title,
2185
+ content,
2186
+ createdAt,
2187
+ notifyMode: item.notify_mode === "popup" ? "popup" : "silent",
2188
+ ...typeof item.starts_at === "string" ? { startsAt: item.starts_at } : {},
2189
+ ...typeof item.ends_at === "string" ? { endsAt: item.ends_at } : {},
2190
+ readAt: text$7(item.read_at) ?? null
2191
+ };
2192
+ }
2193
+ /**
2194
+ * The entries of a list answer, whether the gateway wraps them or not.
2195
+ * @param payload - the parsed body.
2196
+ * @returns the entries, or undefined when the body is not a list.
2197
+ */
2198
+ function entriesOf(payload) {
2199
+ if (Array.isArray(payload)) return payload;
2200
+ const data = record$10(payload)?.data;
2201
+ return Array.isArray(data) ? data : void 0;
2202
+ }
2203
+ /**
2204
+ * Both routes.
2205
+ * @param options - the gateway client and the account whose credential the reads go with.
2206
+ * @returns routes for the client connection.
2207
+ */
2208
+ function announcementRoutes({ http, account }) {
2209
+ const changed = () => {
2210
+ http.invalidateAccountSnapshots();
2211
+ return json$2(409, { error: {
2212
+ code: "ACCOUNT_CHANGED",
2213
+ category: "authentication",
2214
+ message: "账号已切换,请刷新页面。"
2215
+ } });
2216
+ };
2217
+ /** Resolve the account and refuse a read that belongs to the account the page no longer shows. */
2218
+ const enter = async (request) => {
2219
+ const identity = await account.identity();
2220
+ if (!identity.signedIn) return json$2(401, { error: {
2221
+ code: "AUTHENTICATION_REQUIRED",
2222
+ category: "authentication",
2223
+ message: "请先登录 VibeDev。"
2224
+ } });
2225
+ const expected = request.headers.get("X-VibeDev-Expected-User");
2226
+ if (expected !== null && expected !== identity.userId) return changed();
2227
+ return { identity };
2228
+ };
2229
+ /**
2230
+ * Whether a refusal means "this gateway has no announcements yet" rather than a real failure.
2231
+ * A route that does not exist answers 404; a method it does not serve answers 405.
2232
+ */
2233
+ const missing = (error) => error instanceof MediaError && (error.details.status === 404 || error.details.status === 405);
2234
+ const request = (identity, signal) => ({
2235
+ timeoutMs: 15e3,
2236
+ signal,
2237
+ busyRetries: 0,
2238
+ isCurrentAccount: async () => {
2239
+ const now = await account.identity();
2240
+ return now.signedIn && now.userId === identity.userId;
2241
+ }
2242
+ });
2243
+ return [{
2244
+ path: ANNOUNCEMENTS_ROUTE,
2245
+ methods: ["GET"],
2246
+ requestBody: "buffered",
2247
+ fetch: async (incoming) => {
2248
+ const entered = await enter(incoming);
2249
+ if (entered instanceof Response) return entered;
2250
+ const unreadOnly = new URL(incoming.url, "http://host").searchParams.get("unread_only") === "true";
2251
+ try {
2252
+ const entries = entriesOf(await http.json(`${GATEWAY_ANNOUNCEMENTS_PATH}${unreadOnly ? "?unread_only=true" : ""}`, request(entered.identity, incoming.signal)));
2253
+ if (entries === void 0) return json$2(502, { error: {
2254
+ code: "ANNOUNCEMENTS_UNREADABLE",
2255
+ category: "service_unavailable"
2256
+ } });
2257
+ const items = entries.map(parseAnnouncement).filter((item) => item !== void 0);
2258
+ const unread = items.filter((item) => item.readAt === null).length;
2259
+ return json$2(200, {
2260
+ available: true,
2261
+ items,
2262
+ unread
2263
+ });
2264
+ } catch (error) {
2265
+ if (missing(error)) return unavailable();
2266
+ if (error instanceof MediaError && error.details.status === 401) return json$2(401, { error: {
2267
+ code: "AUTHENTICATION_REQUIRED",
2268
+ category: "authentication",
2269
+ message: "请先登录 VibeDev。"
2270
+ } });
2271
+ return json$2(502, { error: {
2272
+ code: "ANNOUNCEMENTS_UNAVAILABLE",
2273
+ category: "service_unavailable"
2274
+ } });
2275
+ }
2276
+ }
2277
+ }, {
2278
+ path: ANNOUNCEMENTS_READ_ROUTE,
2279
+ methods: ["POST"],
2280
+ requestBody: "buffered",
2281
+ fetch: async (incoming) => {
2282
+ const entered = await enter(incoming);
2283
+ if (entered instanceof Response) return entered;
2284
+ const body = record$10(await incoming.json().catch(() => void 0));
2285
+ const id = identifier(body?.id);
2286
+ if (id === void 0) return json$2(400, { error: {
2287
+ code: "ANNOUNCEMENT_INVALID_ID",
2288
+ category: "invalid_input"
2289
+ } });
2290
+ try {
2291
+ await http.json(`${GATEWAY_ANNOUNCEMENTS_PATH}/${id}/read`, {
2292
+ ...request(entered.identity, incoming.signal),
2293
+ method: "POST",
2294
+ json: {}
2295
+ });
2296
+ return json$2(200, { ok: true });
2297
+ } catch (error) {
2298
+ if (missing(error)) return json$2(200, {
2299
+ ok: false,
2300
+ available: false
2301
+ });
2302
+ return json$2(502, { error: {
2303
+ code: "ANNOUNCEMENT_RECEIPT_FAILED",
2304
+ category: "service_unavailable"
2305
+ } });
2306
+ }
2307
+ }
2308
+ }];
2309
+ }
2310
+ //#endregion
2139
2311
  //#region src/account/latency.ts
2140
2312
  /** Path of the latency route. */
2141
2313
  const LATENCY_ROUTE = "/api/dsh-vibedev/latency";
@@ -3193,7 +3365,8 @@ const ACCOUNT_PAGES = [
3193
3365
  "orders",
3194
3366
  "redeem",
3195
3367
  "affiliate",
3196
- "profile"
3368
+ "profile",
3369
+ "messages"
3197
3370
  ];
3198
3371
  //#endregion
3199
3372
  //#region src/gateway/http.ts
@@ -5071,12 +5244,14 @@ function parseCatalog(body) {
5071
5244
  const levels = reasoningLevelsOf(capabilities.reasoning_levels);
5072
5245
  const defaultReasoning = typeof capabilities.default_reasoning === "string" && levels?.includes(capabilities.default_reasoning) ? capabilities.default_reasoning : void 0;
5073
5246
  const inputs = strings$1(capabilities.input_modalities) ?? [];
5247
+ const maxInputTokens = positive$2(capabilities.max_input_tokens);
5074
5248
  seen.add(id);
5075
5249
  models.push({
5076
5250
  id,
5077
5251
  name: modelDisplayName(id, typeof entry.display_name === "string" && entry.display_name.trim() !== "" ? entry.display_name.trim() : void 0),
5078
5252
  api,
5079
5253
  contextWindow: positive$2(capabilities.context_window) ?? 2e5,
5254
+ ...maxInputTokens === void 0 ? {} : { maxInputTokens },
5080
5255
  maxTokens: positive$2(capabilities.max_output_tokens) ?? 32768,
5081
5256
  input: inputs.includes("image") ? ["text", "image"] : ["text"],
5082
5257
  ...levels === void 0 ? {} : { reasoningLevels: levels },
@@ -5704,6 +5879,54 @@ const openAICompletionsApi = () => lazyApi(() => import("./openai-completions-Dq
5704
5879
  //#region node_modules/@earendil-works/pi-ai/dist/api/openai-responses.lazy.js
5705
5880
  const openAIResponsesApi = () => lazyApi(() => import("./openai-responses-DygWnsye.js"));
5706
5881
  //#endregion
5882
+ //#region src/llm/context-budget.ts
5883
+ /**
5884
+ * What a catalog model's returned `contextWindow` should be.
5885
+ *
5886
+ * The host compacts from the window it is told: `basic-compaction` starts at
5887
+ * `min(thresholdRatio × window, window − maxTokens − headroomTokens)` (defaults 0.8, 65,536) and
5888
+ * measures against provider usage plus a heuristic delta. Declaring the provider's *input cap* as the
5889
+ * window therefore compacts at 80% of that cap at best, and earlier whenever the output reserve is
5890
+ * large — but declaring more than the cap lets a request outgrow it before compaction fires.
5891
+ *
5892
+ * The gateway states both numbers: `context_window` (capacity) and `max_input_tokens` (the cap its
5893
+ * provider enforces; the value a `context_length_exceeded` error quotes). Where the two agree, the
5894
+ * input cap is the real limit and the provider bills output outside it, so the host's total capacity
5895
+ * is `input + maxTokens`: the reserve the host subtracts then cancels out and the trigger lands in
5896
+ * the 80–90% band of the real input budget. Where `context_window` is larger than the input cap it
5897
+ * is a real total, and the window never claims past it.
5898
+ *
5899
+ * @module dsh-vibedev/llm/context-budget
5900
+ */
5901
+ /** Share of the provider's input budget compaction should start around. */
5902
+ const CONTEXT_COMPACT_TARGET = .88;
5903
+ /** The host compaction default this arithmetic is written against (`thresholdRatio`). */
5904
+ const HOST_THRESHOLD_RATIO = .8;
5905
+ /** The host compaction default reserve below the message budget (`headroomTokens`). */
5906
+ const HOST_HEADROOM_TOKENS = 65536;
5907
+ /**
5908
+ * The window to report to the host.
5909
+ *
5910
+ * Without a stated input cap this is the catalog capacity unchanged: nothing here may claim more
5911
+ * capacity than the catalog gave. With one, the declared window is sized so the host's own threshold
5912
+ * lands near {@link CONTEXT_COMPACT_TARGET} of that cap, bounded by the real total whenever the
5913
+ * catalog states one.
5914
+ * @param budget - the catalog's capacity, input cap and output reserve.
5915
+ * @param fallback - window for a catalog that states no capacity at all.
5916
+ * @returns a positive token count to declare as the model's context window.
5917
+ */
5918
+ function declaredContextWindow(budget, fallback) {
5919
+ const window = budget.contextWindow;
5920
+ const input = budget.maxInputTokens;
5921
+ if (input === void 0) return window ?? fallback;
5922
+ const inputBudget = window === void 0 ? input : Math.min(input, window);
5923
+ if (inputBudget <= 0) return window ?? fallback;
5924
+ const target = Math.round(inputBudget * CONTEXT_COMPACT_TARGET);
5925
+ const reachable = Math.max(Math.ceil(target / HOST_THRESHOLD_RATIO), target + budget.maxTokens + HOST_HEADROOM_TOKENS);
5926
+ const ceiling = window === void 0 || window === input ? inputBudget + budget.maxTokens : window;
5927
+ return Math.max(inputBudget, Math.min(reachable, ceiling));
5928
+ }
5929
+ //#endregion
5707
5930
  //#region src/llm/models.ts
5708
5931
  /**
5709
5932
  * pi-ai model descriptors and the multi-protocol provider for the gateway.
@@ -5808,7 +6031,11 @@ function toPiModel(model, provider, origin) {
5808
6031
  ...reasoning ? { thinkingLevelMap: thinkingLevelMap(levels) } : {},
5809
6032
  input: [...model.input],
5810
6033
  cost: { ...model.cost },
5811
- contextWindow: model.contextWindow,
6034
+ contextWindow: declaredContextWindow({
6035
+ contextWindow: model.contextWindow,
6036
+ ...model.maxInputTokens === void 0 ? {} : { maxInputTokens: model.maxInputTokens },
6037
+ maxTokens: model.maxTokens
6038
+ }, model.contextWindow),
5812
6039
  maxTokens: model.maxTokens,
5813
6040
  ...compat === void 0 ? {} : { compat }
5814
6041
  };
@@ -5912,9 +6139,23 @@ function mapUsage(usage) {
5912
6139
  ...usage.cacheWrite > 0 ? { cacheWriteTokens: usage.cacheWrite } : {}
5913
6140
  };
5914
6141
  }
6142
+ /**
6143
+ * Provider wordings for a request that outgrew the model's context window and that
6144
+ * {@link isContextWindowExceededError} does not know. Anthropic's Messages API answers
6145
+ * `prompt is too long: 1025721 tokens > 1000000 maximum`, which matches none of its patterns;
6146
+ * classified as a generic 400 this failure is non-retryable, so the host never gets the chance to
6147
+ * compact and retry the request it could still serve.
6148
+ */
6149
+ const PROMPT_OVER_LIMIT = /\b(?:prompt|input|messages?|request)\b[^.]{0,40}\btoo\s+(?:long|large)\b|\b\d+\s*tokens?\s*>\s*\d+\s*(?:maximum|max)\b/i;
6150
+ /**
6151
+ * Classify one pi-ai error message into the harness failure code it should carry.
6152
+ * @param message - the flattened provider error text pi-ai hands over.
6153
+ * @returns the harness code for this failure.
6154
+ */
5915
6155
  function classifyPiAiError(message) {
5916
6156
  if (/\b(?:401|403)\b/.test(message)) return "AUTH";
5917
6157
  if (isQuotaExceededError(message)) return QUOTA_EXCEEDED_CODE;
6158
+ if (isContextWindowExceededError(message) || PROMPT_OVER_LIMIT.test(message)) return CONTEXT_WINDOW_EXCEEDED_CODE;
5918
6159
  if (/\b429\b|rate.?limit/i.test(message)) return "RATE_LIMIT";
5919
6160
  if (/\b413\b|failed to buffer the request body:\s*length limit exceeded|payload too large|request body too large/i.test(message)) return "INVALID_REQUEST";
5920
6161
  if (/\b400\b|invalid.?request/i.test(message)) return "INVALID_REQUEST";
@@ -11417,6 +11658,34 @@ async function generateImages(runtime, call, request, save) {
11417
11658
  };
11418
11659
  }
11419
11660
  /**
11661
+ * Build the result blocks for one generation.
11662
+ *
11663
+ * A result normally names the saved files and nothing else: carrying the pictures is what rewrote a conversation's
11664
+ * middle, made the next turn read the whole prompt again and charged for it. The model reads one back with
11665
+ * `read_image` when it needs to look; `attach` asks for them on this call, the plugin setting on every call.
11666
+ * @param value - the tool's structured result.
11667
+ * @param options - `attach` from the call and the plugin setting.
11668
+ * @returns a text block naming the files, plus an image block per picture when the pictures were asked for.
11669
+ */
11670
+ function imageResultBlocks(value, options) {
11671
+ const pictures = options.attach === true || options.attach !== false && options.imagesInContext === true ? value.images.filter((image) => image.attachment !== void 0 && image.attachment !== null) : [];
11672
+ const count = value.images.length;
11673
+ const lines = ["Generated " + count + " image" + (count === 1 ? "" : "s") + " with " + value.model + ": " + value.images.map((image) => image.path).join(", ") + "."];
11674
+ if (pictures.length > 0) lines.push(count === 1 ? "It is attached below." : "They are attached below.");
11675
+ else lines.push(count === 1 ? "Only the saved file is here, so you cannot see the picture: read it with read_image when you need to look, or pass its path as reference_images to edit it." : "Only the saved files are here, so you cannot see the pictures: read one with read_image when you need to look, or pass a path as reference_images to edit it.");
11676
+ if (value.estimatedCny !== void 0) lines.push("Estimated cost " + yuan(Number(value.estimatedCny)) + ".");
11677
+ if (value.revisedPrompt !== void 0) lines.push("The model rewrote the prompt as: " + value.revisedPrompt);
11678
+ const blocks = [{
11679
+ type: "text",
11680
+ text: lines.join(" ")
11681
+ }];
11682
+ for (const picture of pictures) blocks.push({
11683
+ type: "image",
11684
+ attachment: picture.attachment
11685
+ });
11686
+ return blocks;
11687
+ }
11688
+ /**
11420
11689
  * Build the tool.
11421
11690
  * @param runtime - the media runtime.
11422
11691
  * @returns the tool definition.
@@ -11424,7 +11693,7 @@ async function generateImages(runtime, call, request, save) {
11424
11693
  function imageGenerateTool(runtime) {
11425
11694
  return defineTool({
11426
11695
  name: "image_generate",
11427
- description: "Generate images with a VibeDev image model and save them in the workspace (media/images/); you see the results. With reference_images it edits or derives from those images (style transfer, variations, putting a product into a scene). Costs VibeDev balance per image (about ¥0.1 for gpt-image models); use media_models for the models and prices. Takes about 20 seconds per image.",
11696
+ description: "Generate images with a VibeDev image model and save them in the workspace (media/images/). The result is the saved files, not the pictures: read one with read_image when you need to look at it. With reference_images it edits or derives from those images (style transfer, variations, putting a product into a scene). Costs VibeDev balance per image (about ¥0.1 for gpt-image models); use media_models for the models and prices. Takes about 20 seconds per image.",
11428
11697
  parameters: {
11429
11698
  prompt: {
11430
11699
  type: "string",
@@ -11453,6 +11722,10 @@ function imageGenerateTool(runtime) {
11453
11722
  type: "integer",
11454
11723
  description: "Number of images, 1-4. Default 1."
11455
11724
  },
11725
+ attach: {
11726
+ type: "boolean",
11727
+ description: "Put the pictures in this result so you can see them without a second call; false keeps the saved paths only. Omit for the default."
11728
+ },
11456
11729
  reference_images: {
11457
11730
  type: "array",
11458
11731
  items: { type: "string" },
@@ -11503,20 +11776,10 @@ function imageGenerateTool(runtime) {
11503
11776
  revisedPrompt: { type: "string" }
11504
11777
  }
11505
11778
  },
11506
- render: (_args, value) => {
11507
- const lines = [`Generated ${value.images.length} image${value.images.length === 1 ? "" : "s"} with ${value.model}: ${value.images.map((image) => image.path).join(", ")}.`];
11508
- if (value.estimatedCny !== void 0) lines.push(`Estimated cost ${yuan(Number(value.estimatedCny))}.`);
11509
- if (value.revisedPrompt !== void 0) lines.push(`The model rewrote the prompt as: ${value.revisedPrompt}`);
11510
- const blocks = [{
11511
- type: "text",
11512
- text: lines.join(" ")
11513
- }];
11514
- for (const image of value.images) if (image.attachment !== void 0 && image.attachment !== null) blocks.push({
11515
- type: "image",
11516
- attachment: image.attachment
11517
- });
11518
- return blocks;
11519
- }
11779
+ render: (args, value) => imageResultBlocks(value, {
11780
+ attach: args.attach,
11781
+ imagesInContext: runtime.settings.imagesInContext()
11782
+ })
11520
11783
  },
11521
11784
  async execute(args, exec) {
11522
11785
  const result = await generateImages(runtime, exec, {
@@ -14734,6 +14997,7 @@ const Config = Schema.object({
14734
14997
  submitAttempts: Schema.natural().min(1).max(30).default(3),
14735
14998
  reconcileAttempts: Schema.natural().max(30).default(30),
14736
14999
  confirmSpending: Schema.boolean().default(false).volatile(),
15000
+ imagesInContext: Schema.boolean().default(false).volatile(),
14737
15001
  outputDir: Schema.string().default("media").volatile(),
14738
15002
  imageModel: Schema.string().default("").volatile(),
14739
15003
  videoModel: Schema.string().default("").volatile(),
@@ -14759,6 +15023,7 @@ const Config = Schema.object({
14759
15023
  submitAttempts: "原键首次提交总尝试数(含首次,默认3)",
14760
15024
  reconcileAttempts: "原键后台核对次数(0关闭,默认30)",
14761
15025
  confirmSpending: "每次付费生成前先询问(默认关闭)",
15026
+ imagesInContext: "把生成的图片发给模型(默认关闭:只给保存路径)",
14762
15027
  outputDir: "保存目录(相对于工作区)",
14763
15028
  imageModel: "默认生图模型(留空由 Agent 按目录选择)",
14764
15029
  videoModel: "默认视频模型(留空由 Agent 按目录选择)",
@@ -14784,6 +15049,7 @@ const Config = Schema.object({
14784
15049
  submitAttempts: "Initial same-key attempts including first dispatch (default 3)",
14785
15050
  reconcileAttempts: "Additional same-key checks (0 disables; default 30)",
14786
15051
  confirmSpending: "Ask before each paid generation (off by default)",
15052
+ imagesInContext: "Send generated images to the model (off by default: paths only)",
14787
15053
  outputDir: "Output folder (relative to the workspace)",
14788
15054
  imageModel: "Default image model (empty: the agent chooses from the catalog)",
14789
15055
  videoModel: "Default video model (empty: the agent chooses from the catalog)",
@@ -14799,7 +15065,7 @@ const Config = Schema.object({
14799
15065
  stateDir: "Plugin data folder (empty for the default)"
14800
15066
  }
14801
15067
  });
14802
- const GUIDANCE = "VibeDev media tools: image_generate, video_generate, audio_generate (music, a podcast or speech) and audio_transcribe create and transcribe media with the user's VibeDev account; media_models lists models and prices. Use them on your own judgment whenever generated media serves the request (illustrations, product shots, storyboard frames, short clips, background music, a podcast episode, a voice-over), not only when a tool is named. They spend the user's balance, so make what the request needs rather than speculative variations. Results are saved in the workspace under media/. Pass files the user attached in this chat as chat:1 (the most recent), chat:2, and so on. Video and audio run as background jobs: carry on and let the job notification report the result.";
15068
+ const GUIDANCE = "VibeDev media tools: image_generate, video_generate, audio_generate (music, a podcast or speech) and audio_transcribe create and transcribe media with the user's VibeDev account; media_models lists models and prices. Use them on your own judgment whenever generated media serves the request (illustrations, product shots, storyboard frames, short clips, background music, a podcast episode, a voice-over), not only when a tool is named. They spend the user's balance, so make what the request needs rather than speculative variations. Results are saved in the workspace under media/. An image result is the saved file, not the picture: read it with read_image when you need to look, and read each file once — every read is another image in the context. Pass files the user attached in this chat as chat:1 (the most recent), chat:2, and so on. Video and audio run as background jobs: carry on and let the job notification report the result.";
14803
15069
  function apply(ctx, config) {
14804
15070
  const origin = normalizeGatewayOrigin(config.gatewayOrigin);
14805
15071
  const stateDir = stateDirectory(config.stateDir);
@@ -14874,6 +15140,7 @@ function apply(ctx, config) {
14874
15140
  settings: {
14875
15141
  outputDir: () => config.outputDir.get(),
14876
15142
  confirmSpending: () => config.confirmSpending.get(),
15143
+ imagesInContext: () => config.imagesInContext.get(),
14877
15144
  defaultModel: (slot) => slots[slot].get()
14878
15145
  },
14879
15146
  fs: () => ctx.get("fs"),
@@ -15001,6 +15268,10 @@ function apply(ctx, config) {
15001
15268
  for (const accountRoute of [
15002
15269
  ...accountRoutes(accountService),
15003
15270
  ...accountCenterRoutes(http, accountService),
15271
+ ...announcementRoutes({
15272
+ http,
15273
+ account: accountService
15274
+ }),
15004
15275
  ...latencyRoutes(latency)
15005
15276
  ]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
15006
15277
  });