@vibedev-si/dsh-vibedev 0.6.0 → 0.7.0

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
@@ -11417,6 +11590,34 @@ async function generateImages(runtime, call, request, save) {
11417
11590
  };
11418
11591
  }
11419
11592
  /**
11593
+ * Build the result blocks for one generation.
11594
+ *
11595
+ * A result normally names the saved files and nothing else: carrying the pictures is what rewrote a conversation's
11596
+ * middle, made the next turn read the whole prompt again and charged for it. The model reads one back with
11597
+ * `read_image` when it needs to look; `attach` asks for them on this call, the plugin setting on every call.
11598
+ * @param value - the tool's structured result.
11599
+ * @param options - `attach` from the call and the plugin setting.
11600
+ * @returns a text block naming the files, plus an image block per picture when the pictures were asked for.
11601
+ */
11602
+ function imageResultBlocks(value, options) {
11603
+ const pictures = options.attach === true || options.attach !== false && options.imagesInContext === true ? value.images.filter((image) => image.attachment !== void 0 && image.attachment !== null) : [];
11604
+ const count = value.images.length;
11605
+ const lines = ["Generated " + count + " image" + (count === 1 ? "" : "s") + " with " + value.model + ": " + value.images.map((image) => image.path).join(", ") + "."];
11606
+ if (pictures.length > 0) lines.push(count === 1 ? "It is attached below." : "They are attached below.");
11607
+ 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.");
11608
+ if (value.estimatedCny !== void 0) lines.push("Estimated cost " + yuan(Number(value.estimatedCny)) + ".");
11609
+ if (value.revisedPrompt !== void 0) lines.push("The model rewrote the prompt as: " + value.revisedPrompt);
11610
+ const blocks = [{
11611
+ type: "text",
11612
+ text: lines.join(" ")
11613
+ }];
11614
+ for (const picture of pictures) blocks.push({
11615
+ type: "image",
11616
+ attachment: picture.attachment
11617
+ });
11618
+ return blocks;
11619
+ }
11620
+ /**
11420
11621
  * Build the tool.
11421
11622
  * @param runtime - the media runtime.
11422
11623
  * @returns the tool definition.
@@ -11424,7 +11625,7 @@ async function generateImages(runtime, call, request, save) {
11424
11625
  function imageGenerateTool(runtime) {
11425
11626
  return defineTool({
11426
11627
  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.",
11628
+ 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
11629
  parameters: {
11429
11630
  prompt: {
11430
11631
  type: "string",
@@ -11453,6 +11654,10 @@ function imageGenerateTool(runtime) {
11453
11654
  type: "integer",
11454
11655
  description: "Number of images, 1-4. Default 1."
11455
11656
  },
11657
+ attach: {
11658
+ type: "boolean",
11659
+ 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."
11660
+ },
11456
11661
  reference_images: {
11457
11662
  type: "array",
11458
11663
  items: { type: "string" },
@@ -11503,20 +11708,10 @@ function imageGenerateTool(runtime) {
11503
11708
  revisedPrompt: { type: "string" }
11504
11709
  }
11505
11710
  },
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
- }
11711
+ render: (args, value) => imageResultBlocks(value, {
11712
+ attach: args.attach,
11713
+ imagesInContext: runtime.settings.imagesInContext()
11714
+ })
11520
11715
  },
11521
11716
  async execute(args, exec) {
11522
11717
  const result = await generateImages(runtime, exec, {
@@ -14734,6 +14929,7 @@ const Config = Schema.object({
14734
14929
  submitAttempts: Schema.natural().min(1).max(30).default(3),
14735
14930
  reconcileAttempts: Schema.natural().max(30).default(30),
14736
14931
  confirmSpending: Schema.boolean().default(false).volatile(),
14932
+ imagesInContext: Schema.boolean().default(false).volatile(),
14737
14933
  outputDir: Schema.string().default("media").volatile(),
14738
14934
  imageModel: Schema.string().default("").volatile(),
14739
14935
  videoModel: Schema.string().default("").volatile(),
@@ -14759,6 +14955,7 @@ const Config = Schema.object({
14759
14955
  submitAttempts: "原键首次提交总尝试数(含首次,默认3)",
14760
14956
  reconcileAttempts: "原键后台核对次数(0关闭,默认30)",
14761
14957
  confirmSpending: "每次付费生成前先询问(默认关闭)",
14958
+ imagesInContext: "把生成的图片发给模型(默认关闭:只给保存路径)",
14762
14959
  outputDir: "保存目录(相对于工作区)",
14763
14960
  imageModel: "默认生图模型(留空由 Agent 按目录选择)",
14764
14961
  videoModel: "默认视频模型(留空由 Agent 按目录选择)",
@@ -14784,6 +14981,7 @@ const Config = Schema.object({
14784
14981
  submitAttempts: "Initial same-key attempts including first dispatch (default 3)",
14785
14982
  reconcileAttempts: "Additional same-key checks (0 disables; default 30)",
14786
14983
  confirmSpending: "Ask before each paid generation (off by default)",
14984
+ imagesInContext: "Send generated images to the model (off by default: paths only)",
14787
14985
  outputDir: "Output folder (relative to the workspace)",
14788
14986
  imageModel: "Default image model (empty: the agent chooses from the catalog)",
14789
14987
  videoModel: "Default video model (empty: the agent chooses from the catalog)",
@@ -14799,7 +14997,7 @@ const Config = Schema.object({
14799
14997
  stateDir: "Plugin data folder (empty for the default)"
14800
14998
  }
14801
14999
  });
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.";
15000
+ 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
15001
  function apply(ctx, config) {
14804
15002
  const origin = normalizeGatewayOrigin(config.gatewayOrigin);
14805
15003
  const stateDir = stateDirectory(config.stateDir);
@@ -14874,6 +15072,7 @@ function apply(ctx, config) {
14874
15072
  settings: {
14875
15073
  outputDir: () => config.outputDir.get(),
14876
15074
  confirmSpending: () => config.confirmSpending.get(),
15075
+ imagesInContext: () => config.imagesInContext.get(),
14877
15076
  defaultModel: (slot) => slots[slot].get()
14878
15077
  },
14879
15078
  fs: () => ctx.get("fs"),
@@ -15001,6 +15200,10 @@ function apply(ctx, config) {
15001
15200
  for (const accountRoute of [
15002
15201
  ...accountRoutes(accountService),
15003
15202
  ...accountCenterRoutes(http, accountService),
15203
+ ...announcementRoutes({
15204
+ http,
15205
+ account: accountService
15206
+ }),
15004
15207
  ...latencyRoutes(latency)
15005
15208
  ]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
15006
15209
  });
package/lib/runtime.d.ts CHANGED
@@ -39,6 +39,8 @@ export interface MediaSettings {
39
39
  /** Output folder, relative to the workspace (or absolute). */
40
40
  readonly outputDir: () => string;
41
41
  readonly confirmSpending: () => boolean;
42
+ /** Send the generated images to the model; off by default, so a result is the saved paths. */
43
+ readonly imagesInContext: () => boolean;
42
44
  /** A pinned model id, or `''` to let the agent choose. */
43
45
  readonly defaultModel: (slot: ModelSlot) => string;
44
46
  }
@@ -3,6 +3,7 @@
3
3
  * save them in the workspace and show them to the model.
4
4
  * @module dsh-vibedev/tools/image
5
5
  */
6
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm';
6
7
  import type { ToolDefinition } from '@deepseek-ai/dsh-tools';
7
8
  import type { MediaCall, MediaRuntime } from '../runtime.js';
8
9
  /** One image request, as the tool and host callers make it. */
@@ -43,6 +44,30 @@ export declare function generateImages(runtime: MediaRuntime, call: MediaCall, r
43
44
  estimatedCny?: string;
44
45
  revisedPrompt?: string;
45
46
  }>;
47
+ /** What a generation returns to the conversation: the saved paths, and the pictures only when they were asked for. */
48
+ export interface ImageResultView {
49
+ readonly model: string;
50
+ readonly images: readonly {
51
+ readonly path: string;
52
+ readonly attachment?: unknown;
53
+ }[];
54
+ readonly estimatedCny?: string;
55
+ readonly revisedPrompt?: string;
56
+ }
57
+ /**
58
+ * Build the result blocks for one generation.
59
+ *
60
+ * A result normally names the saved files and nothing else: carrying the pictures is what rewrote a conversation's
61
+ * middle, made the next turn read the whole prompt again and charged for it. The model reads one back with
62
+ * `read_image` when it needs to look; `attach` asks for them on this call, the plugin setting on every call.
63
+ * @param value - the tool's structured result.
64
+ * @param options - `attach` from the call and the plugin setting.
65
+ * @returns a text block naming the files, plus an image block per picture when the pictures were asked for.
66
+ */
67
+ export declare function imageResultBlocks(value: ImageResultView, options: {
68
+ attach?: boolean;
69
+ imagesInContext?: boolean;
70
+ }): ContentBlock[];
46
71
  /**
47
72
  * Build the tool.
48
73
  * @param runtime - the media runtime.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vibedev-si/dsh-vibedev",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "VibeDev 账号与模型:在 DeepSeek Harness 里登录 VibeDev,与 DeepSeek 账号并存,使用 VibeDev 网关的模型(Claude、GPT 等),并生成图片、视频、音乐和播客 · VibeDev account and models for DeepSeek Harness: sign in to VibeDev next to the DeepSeek account and use the VibeDev gateway's models (Claude, GPT and more), plus image, video, music and podcast generation",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",