@vibedev-si/dsh-vibedev 0.3.9 → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -48,7 +48,7 @@ const MIN_READ_SPACING_MS = 5e3;
48
48
  * current when nobody opens anything.
49
49
  */
50
50
  const CATALOG_REFRESH_GAP_MS = 6e4;
51
- const record$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
51
+ const record$10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
52
52
  const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
53
53
  /**
54
54
  * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
@@ -283,8 +283,8 @@ var AccountService = class {
283
283
  redirect: "error"
284
284
  });
285
285
  if (!response.ok) return {};
286
- const body = record$9(await response.json().catch(() => void 0));
287
- const data = record$9(body?.data) ?? body;
286
+ const body = record$10(await response.json().catch(() => void 0));
287
+ const data = record$10(body?.data) ?? body;
288
288
  const balance = amountOf(data?.balance);
289
289
  const currency = text$8(data?.currency) ?? "CNY";
290
290
  const frozen = amountOf(data?.frozen_balance);
@@ -401,7 +401,7 @@ function json$2(status, body) {
401
401
  });
402
402
  }
403
403
  function failure(error) {
404
- const candidate = record$9(error)?.code;
404
+ const candidate = record$10(error)?.code;
405
405
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
406
406
  return json$2(500, { error: {
407
407
  code,
@@ -436,7 +436,7 @@ function accountRoutes(account) {
436
436
  requestBody: "buffered",
437
437
  fetch: async (request) => {
438
438
  try {
439
- const body = record$9(await request.json().catch(() => void 0));
439
+ const body = record$10(await request.json().catch(() => void 0));
440
440
  return json$2(200, await account.signIn(body?.open !== false));
441
441
  } catch (error) {
442
442
  return failure(error);
@@ -969,7 +969,7 @@ var MediaError = class extends HarnessError {
969
969
  this.details = details;
970
970
  }
971
971
  };
972
- function record$8(value) {
972
+ function record$9(value) {
973
973
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
974
974
  }
975
975
  function text$7(value) {
@@ -995,10 +995,10 @@ function amount$1(value) {
995
995
  * @returns the fields found.
996
996
  */
997
997
  function parseGatewayFailure(body) {
998
- const root = record$8(body);
998
+ const root = record$9(body);
999
999
  if (root === void 0) return {};
1000
- const source = record$8(root.error) ?? root;
1001
- const metadata = record$8(source.metadata) ?? record$8(root.metadata);
1000
+ const source = record$9(root.error) ?? root;
1001
+ const metadata = record$9(source.metadata) ?? record$9(root.metadata);
1002
1002
  const code = text$7(source.code) ?? text$7(source.type) ?? text$7(root.reason);
1003
1003
  const message = text$7(source.message) ?? (typeof root.error === "string" ? text$7(root.error) : void 0);
1004
1004
  const field = text$7(source.field) ?? text$7(metadata?.field);
@@ -1229,7 +1229,7 @@ async function downloadTo(response, temporary, maxBytes, signal) {
1229
1229
  throw error;
1230
1230
  }
1231
1231
  }
1232
- const SOURCES = /* @__PURE__ */ new Set([
1232
+ const SOURCES$1 = /* @__PURE__ */ new Set([
1233
1233
  "message",
1234
1234
  "command",
1235
1235
  "menu"
@@ -1244,7 +1244,7 @@ function isOwner(value) {
1244
1244
  function isItem(value) {
1245
1245
  const item = value;
1246
1246
  const body = item?.body;
1247
- return typeof item === "object" && item !== null && typeof body === "object" && body !== null && typeof body.id === "string" && body.id !== "" && SOURCES.has(String(body.source)) && typeof body.client === "object" && body.client !== null && typeof body.client.app === "string" && (body.category === void 0 || body.category === null || isCategory(body.category)) && isOwner(item.owner) && typeof item.enqueuedAt === "number" && typeof item.attempts === "number" && typeof item.nextAt === "number";
1247
+ return typeof item === "object" && item !== null && typeof body === "object" && body !== null && typeof body.id === "string" && body.id !== "" && SOURCES$1.has(String(body.source)) && typeof body.client === "object" && body.client !== null && typeof body.client.app === "string" && (body.category === void 0 || body.category === null || isCategory(body.category)) && isOwner(item.owner) && typeof item.enqueuedAt === "number" && typeof item.attempts === "number" && typeof item.nextAt === "number";
1248
1248
  }
1249
1249
  /** The persistent queue. All changes are serialized; reads see the latest state. */
1250
1250
  var FeedbackQueue = class {
@@ -1519,7 +1519,7 @@ const invalid = (field) => json(400, { error: {
1519
1519
  code: "FEEDBACK_INVALID",
1520
1520
  field
1521
1521
  } });
1522
- const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1522
+ const record$8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1523
1523
  /**
1524
1524
  * The feedback routes.
1525
1525
  * @param options - the uploader's submit, the recent errors and the credential check.
@@ -1537,7 +1537,7 @@ function feedbackRoutes(options) {
1537
1537
  requestBody: "buffered",
1538
1538
  fetch: async (request) => {
1539
1539
  try {
1540
- const body = record$7(await request.json().catch(() => void 0));
1540
+ const body = record$8(await request.json().catch(() => void 0));
1541
1541
  if (body === void 0) return invalid("body");
1542
1542
  if (body.category !== void 0 && body.category !== null && !isCategory(body.category)) return invalid("category");
1543
1543
  if (body.text !== void 0 && typeof body.text !== "string") return invalid("text");
@@ -1547,7 +1547,7 @@ function feedbackRoutes(options) {
1547
1547
  if (text === void 0 && category === void 0) return invalid("text");
1548
1548
  let content;
1549
1549
  if (body.attachment !== void 0 && body.attachment !== null) {
1550
- const given = record$7(body.attachment)?.content;
1550
+ const given = record$8(body.attachment)?.content;
1551
1551
  if (typeof given !== "string" || given === "" || Buffer$1.byteLength(given, "utf8") > 262144) return invalid("attachment");
1552
1552
  content = given;
1553
1553
  }
@@ -2646,7 +2646,7 @@ const CALLBACK_PATH = "/dsh-media/callback";
2646
2646
  function base64url(data) {
2647
2647
  return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
2648
2648
  }
2649
- const record$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2649
+ const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2650
2650
  const text$6 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
2651
2651
  /**
2652
2652
  * Read a token answer (`redeem` or `refresh`).
@@ -2656,13 +2656,13 @@ const text$6 = (value) => typeof value === "string" && value.trim() !== "" ? val
2656
2656
  * @returns the grant, or undefined when the answer lacks tokens.
2657
2657
  */
2658
2658
  function parseGrant(body, now, previous) {
2659
- const envelope = record$6(body);
2660
- const data = record$6(envelope?.data) ?? envelope;
2659
+ const envelope = record$7(body);
2660
+ const data = record$7(envelope?.data) ?? envelope;
2661
2661
  const accessToken = text$6(data?.access_token);
2662
2662
  const refreshToken = text$6(data?.refresh_token);
2663
2663
  if (data === void 0 || accessToken === void 0 || refreshToken === void 0) return void 0;
2664
2664
  const seconds = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2665
- const user = record$6(data.user);
2665
+ const user = record$7(data.user);
2666
2666
  const sessionId = text$6(data.session_id) ?? previous?.sessionId;
2667
2667
  const parsedUser = user === void 0 ? previous?.user : {
2668
2668
  ...text$6(user.id) === void 0 && typeof user.id !== "number" ? {} : { id: String(user.id) },
@@ -3087,8 +3087,8 @@ var PluginLogin = class {
3087
3087
  return;
3088
3088
  }
3089
3089
  if (!live()) return;
3090
- const envelope = record$6(body);
3091
- const parsed = envelope !== void 0 && (envelope.code === void 0 || envelope.code === 0) && (envelope.data === void 0 || record$6(envelope.data) !== void 0) ? parseGrant(body, this.now()) : void 0;
3090
+ const envelope = record$7(body);
3091
+ const parsed = envelope !== void 0 && (envelope.code === void 0 || envelope.code === 0) && (envelope.data === void 0 || record$7(envelope.data) !== void 0) ? parseGrant(body, this.now()) : void 0;
3092
3092
  if (parsed === void 0) {
3093
3093
  answer(502, "VibeDev", failurePage({
3094
3094
  ...this.attempt,
@@ -3273,7 +3273,7 @@ const ENDPOINT = {
3273
3273
  "openai-responses": "/v1/responses",
3274
3274
  "openai-completions": "/v1/chat/completions"
3275
3275
  };
3276
- const record$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3276
+ const record$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3277
3277
  const strings$1 = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
3278
3278
  const positive$1 = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
3279
3279
  const price$1 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
@@ -3327,15 +3327,15 @@ function reasoningLevelsOf(value) {
3327
3327
  * @returns the chat models, in catalog order; entries that are not chat models or cannot be called are left out.
3328
3328
  */
3329
3329
  function parseCatalog(body) {
3330
- const list = Array.isArray(body) ? body : record$5(body)?.data;
3330
+ const list = Array.isArray(body) ? body : record$6(body)?.data;
3331
3331
  if (!Array.isArray(list)) return [];
3332
3332
  const models = [];
3333
3333
  const seen = /* @__PURE__ */ new Set();
3334
3334
  for (const raw of list) {
3335
- const entry = record$5(raw);
3335
+ const entry = record$6(raw);
3336
3336
  const id = typeof entry?.id === "string" ? entry.id.trim() : "";
3337
3337
  if (entry === void 0 || id === "" || seen.has(id)) continue;
3338
- const capabilities = record$5(entry.capabilities);
3338
+ const capabilities = record$6(entry.capabilities);
3339
3339
  if (capabilities === void 0) continue;
3340
3340
  if (typeof entry.media_type === "string" && entry.media_type !== "") continue;
3341
3341
  if (typeof entry.internal_role === "string" && entry.internal_role !== "") continue;
@@ -4397,6 +4397,54 @@ async function* toStreamChunks(events, contextWindow, callerSignal, requestedMod
4397
4397
  throw new LlmError("pi-ai event stream ended without done/error", "STREAM_CLOSED");
4398
4398
  }
4399
4399
  //#endregion
4400
+ //#region src/llm/cache-ttl.ts
4401
+ /** Anthropic cache retention changes only existing cache-control markers in serialized content. */
4402
+ const CLAUDE_CACHE_TTLS = [
4403
+ "default",
4404
+ "5m",
4405
+ "1h"
4406
+ ];
4407
+ const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4408
+ function cacheBlock(value, ttl, nested) {
4409
+ const block = object(value);
4410
+ if (block === void 0) return value;
4411
+ const marker = object(block.cache_control);
4412
+ const next = marker?.type === "ephemeral" ? {
4413
+ ...block,
4414
+ cache_control: {
4415
+ ...marker,
4416
+ ttl
4417
+ }
4418
+ } : { ...block };
4419
+ if (nested && Array.isArray(block.content)) next.content = block.content.map((child) => cacheBlock(child, ttl, true));
4420
+ const source = object(block.source);
4421
+ if (nested && block.type === "document" && source?.type === "content" && Array.isArray(source.content)) next.source = {
4422
+ ...source,
4423
+ content: source.content.map((child) => cacheBlock(child, ttl, true))
4424
+ };
4425
+ return next;
4426
+ }
4427
+ /**
4428
+ * Set an explicit TTL on the Anthropic payload's existing ephemeral cache breakpoints.
4429
+ * @param payload - serialized Anthropic request; borrowed, never mutated.
4430
+ * @param ttl - user preference captured for this request; default preserves the original payload.
4431
+ * @returns the original payload for default, or a copy with known cache-control slots updated.
4432
+ */
4433
+ function withClaudeCacheTtl(payload, ttl) {
4434
+ if (ttl === "default") return payload;
4435
+ const next = { ...payload };
4436
+ if (Array.isArray(payload.system)) next.system = payload.system.map((block) => cacheBlock(block, ttl, true));
4437
+ if (Array.isArray(payload.tools)) next.tools = payload.tools.map((tool) => cacheBlock(tool, ttl, false));
4438
+ if (Array.isArray(payload.messages)) next.messages = payload.messages.map((value) => {
4439
+ const message = object(value);
4440
+ return message !== void 0 && Array.isArray(message.content) ? {
4441
+ ...message,
4442
+ content: message.content.map((block) => cacheBlock(block, ttl, true))
4443
+ } : value;
4444
+ });
4445
+ return next;
4446
+ }
4447
+ //#endregion
4400
4448
  //#region \0@oxc-project+runtime@0.152.0/helpers/esm/usingCtx.js
4401
4449
  function _usingCtx() {
4402
4450
  var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
@@ -4601,19 +4649,24 @@ var GatewayAdapter = class extends LlmAdapter {
4601
4649
  }
4602
4650
  prepareCall(provider, model, _signal) {
4603
4651
  const snapshot = this.current();
4652
+ const claudeCacheTtl = this.cacheTtlFor(this.modelOf(snapshot, provider, model).model);
4604
4653
  return Promise.resolve({
4605
4654
  model: this.modelInfo(snapshot, provider, model),
4606
- stream: (options) => this.streamWithSnapshot(options, snapshot)
4655
+ stream: (options) => this.streamWithSnapshot(options, snapshot, claudeCacheTtl)
4607
4656
  });
4608
4657
  }
4609
4658
  stream(options) {
4610
4659
  return this.streamWithSnapshot(options, this.current());
4611
4660
  }
4612
- async *streamWithSnapshot(options, snapshot) {
4661
+ cacheTtlFor(model) {
4662
+ return model.api === "anthropic-messages" && relayIdentity(model.id).baseId.toLowerCase().startsWith("claude") ? this.config.claudeCacheTtl?.() ?? "default" : "default";
4663
+ }
4664
+ async *streamWithSnapshot(options, snapshot, preparedTtl) {
4613
4665
  try {
4614
4666
  var _usingCtx$1 = _usingCtx();
4615
4667
  if (options.stop !== void 0) throw new LlmError("the VibeDev gateway adapter does not support GenerateOptions.stop", "UNSUPPORTED_OPTION");
4616
4668
  const { model, catalog } = this.modelOf(snapshot, options.provider, options.model);
4669
+ const claudeCacheTtl = preparedTtl ?? this.cacheTtlFor(model);
4617
4670
  const starting = startingReasoning(catalog);
4618
4671
  const reasoning = resolveReasoningLevel(model, options.reasoningEffort ?? (starting === void 0 ? void 0 : effortOf(starting)));
4619
4672
  let credential = await this.config.resolveCredential();
@@ -4691,7 +4744,8 @@ var GatewayAdapter = class extends LlmAdapter {
4691
4744
  onPayload: (payload) => this.shapePayload(payload, model, {
4692
4745
  ...sessionId === void 0 ? {} : { sessionId },
4693
4746
  off: reasoning === "off" && offersNone,
4694
- reasoning: enabledReasoning !== void 0
4747
+ reasoning: enabledReasoning !== void 0,
4748
+ claudeCacheTtl
4695
4749
  }),
4696
4750
  fetch: observingFetch,
4697
4751
  onResponse: (received) => {
@@ -4780,6 +4834,8 @@ var GatewayAdapter = class extends LlmAdapter {
4780
4834
  effort: "none"
4781
4835
  };
4782
4836
  if (request.reasoning || request.off) delete shaped.temperature;
4837
+ break;
4838
+ case "anthropic-messages": return withClaudeCacheTtl(shaped, request.claudeCacheTtl);
4783
4839
  }
4784
4840
  return shaped;
4785
4841
  }
@@ -4904,6 +4960,7 @@ function installGatewayModels(ctx, options) {
4904
4960
  rejectCredential: options.rejectCredential,
4905
4961
  deviceId: options.deviceId,
4906
4962
  cacheRetention: options.cacheRetention ?? "short",
4963
+ claudeCacheTtl: options.claudeCacheTtl,
4907
4964
  resolveAttachments: () => ctx.get("attachments"),
4908
4965
  resolveImageAccess: (attachments, ref) => resolveImageAttachmentAccess(attachments, (hostPath) => ctx.get("fs")?.processPathFromHostPath(hostPath), ref),
4909
4966
  onReplayDegrade: ({ provider, model, reason }) => {
@@ -5065,7 +5122,7 @@ const FIRST_LOOK_MS = 1e3;
5065
5122
  const LOOK_STEP_MAX_MS = 1e4;
5066
5123
  /** Uploads this library starts for one file: its own, and one more after another upload of the file ended without it. */
5067
5124
  const OWN_UPLOADS = 2;
5068
- const record$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5125
+ const record$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5069
5126
  const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5070
5127
  const httpUrl$1 = (value) => {
5071
5128
  const url = text$5(value);
@@ -5078,7 +5135,7 @@ const httpUrl$1 = (value) => {
5078
5135
  * @returns the asset facts, or undefined when the answer names no usable URL.
5079
5136
  */
5080
5137
  function parseAsset(body, fallbackType) {
5081
- const raw = record$4(body);
5138
+ const raw = record$5(body);
5082
5139
  const assetId = text$5(raw?.asset_id);
5083
5140
  const referenceUrl = httpUrl$1(raw?.reference_url);
5084
5141
  if (raw === void 0 || assetId === void 0 || referenceUrl === void 0) return void 0;
@@ -5228,7 +5285,7 @@ var MediaLibrary = class {
5228
5285
  }
5229
5286
  /** `POST /uploads`: the asset when the library already holds the file, else the upload it hands out. */
5230
5287
  async declare(media, purpose, sha256, signal) {
5231
- const created = record$4(await this.http.json("/v1/media-assets/uploads", {
5288
+ const created = record$5(await this.http.json("/v1/media-assets/uploads", {
5232
5289
  method: "POST",
5233
5290
  json: {
5234
5291
  filename: media.name,
@@ -5265,7 +5322,7 @@ var MediaLibrary = class {
5265
5322
  const uploadUrl = httpUrl$1(created.upload_url) ?? (text$5(created.upload_url)?.startsWith("/") === true ? this.http.url(text$5(created.upload_url)) : void 0);
5266
5323
  if (uploadUrl === void 0) throw new MediaError(`The VibeDev gateway returned no upload address for "${media.source}".`, "ASSET_UPLOAD_URL_MISSING");
5267
5324
  const headers = { "content-type": media.mime };
5268
- for (const [name, value] of Object.entries(record$4(created.upload_headers) ?? {})) if (typeof value === "string") headers[name.toLowerCase()] = value;
5325
+ for (const [name, value] of Object.entries(record$5(created.upload_headers) ?? {})) if (typeof value === "string") headers[name.toLowerCase()] = value;
5269
5326
  await this.http.send(uploadUrl, {
5270
5327
  method: "PUT",
5271
5328
  body: media.data,
@@ -5327,7 +5384,7 @@ const AUDIO_GENERATION_KINDS = [
5327
5384
  "speech",
5328
5385
  "transcription"
5329
5386
  ];
5330
- const record$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5387
+ const record$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5331
5388
  const text$4 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5332
5389
  const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
5333
5390
  const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
@@ -5375,15 +5432,15 @@ function parseModes(raw) {
5375
5432
  const version = field(raw, "modes_schema_version");
5376
5433
  const modesRaw = raw.modes;
5377
5434
  if (version === void 0 && modesRaw === void 0) return {};
5378
- if (version !== 1 || record$3(modesRaw) === void 0) return { unreadableModesVersion: typeof version === "number" ? version : 0 };
5435
+ if (version !== 1 || record$4(modesRaw) === void 0) return { unreadableModesVersion: typeof version === "number" ? version : 0 };
5379
5436
  const modes = {};
5380
5437
  for (const mode of VIDEO_MODES) {
5381
- const entry = record$3(modesRaw[mode]);
5438
+ const entry = record$4(modesRaw[mode]);
5382
5439
  if (entry === void 0) continue;
5383
- const inputsRaw = record$3(entry.inputs) ?? {};
5440
+ const inputsRaw = record$4(entry.inputs) ?? {};
5384
5441
  const inputs = {};
5385
5442
  for (const [key, limitRaw] of Object.entries(inputsRaw)) {
5386
- const limit = record$3(limitRaw);
5443
+ const limit = record$4(limitRaw);
5387
5444
  const min = count(limit?.min);
5388
5445
  const max = count(limit?.max);
5389
5446
  if (!VIDEO_INPUTS.includes(key) || limit === void 0 || min === void 0 || max === void 0 || min > max) return { unreadableModesVersion: 1 };
@@ -5492,7 +5549,7 @@ function parseVideoCapabilities(raw) {
5492
5549
  if (Array.isArray(combinationsRaw)) {
5493
5550
  const combinations = [];
5494
5551
  for (const item of combinationsRaw) {
5495
- const entry = record$3(item);
5552
+ const entry = record$4(item);
5496
5553
  if (entry === void 0) continue;
5497
5554
  const duration = positive(field(entry, "duration_seconds"));
5498
5555
  const ratio = text$4(entry.ratio);
@@ -5586,12 +5643,12 @@ const PRICE_UNITS = [
5586
5643
  ];
5587
5644
  /** The audio block: `entry.audio`, else `capabilities.audio`, else the fields flattened into `capabilities`. */
5588
5645
  function audioBlock(entry, capabilities) {
5589
- const own = record$3(entry.audio) ?? record$3(capabilities.audio);
5646
+ const own = record$4(entry.audio) ?? record$4(capabilities.audio);
5590
5647
  if (own !== void 0) return own;
5591
5648
  return field(capabilities, "generation_kind") !== void 0 ? capabilities : void 0;
5592
5649
  }
5593
5650
  function stringChoices(raw) {
5594
- const choices = record$3(raw);
5651
+ const choices = record$4(raw);
5595
5652
  if (choices === void 0) return void 0;
5596
5653
  const out = {};
5597
5654
  for (const [name, values] of Object.entries(choices)) {
@@ -5664,10 +5721,10 @@ function seedReferenceLimits(raw) {
5664
5721
  function parseOutputFormats(raw) {
5665
5722
  const declared = field(raw, "output_formats");
5666
5723
  if (!Array.isArray(declared)) return void 0;
5667
- const rates = record$3(field(raw, "sample_rates")) ?? record$3(field(raw, "output_sample_rates"));
5724
+ const rates = record$4(field(raw, "sample_rates")) ?? record$4(field(raw, "output_sample_rates"));
5668
5725
  const formats = [];
5669
5726
  for (const item of declared) {
5670
- const entry = record$3(item);
5727
+ const entry = record$4(item);
5671
5728
  const format = (entry === void 0 ? text$4(item) : text$4(entry.format))?.toLowerCase();
5672
5729
  if (format === void 0 || formats.some((known) => known.format === format)) continue;
5673
5730
  const sampleRates = (entry === void 0 ? void 0 : field(entry, "sample_rates")) ?? rates?.[format];
@@ -5698,7 +5755,7 @@ function parseAudioCapabilities(raw) {
5698
5755
  "reference_image_input",
5699
5756
  "speaker_input"
5700
5757
  ].some((name) => bool(raw, name) !== void 0);
5701
- const references = parseReferenceLimits(record$3(field(raw, "references")) ?? record$3(field(raw, "reference_audio")), union ? "object" : "url") ?? seedReferenceLimits(raw);
5758
+ const references = parseReferenceLimits(record$4(field(raw, "references")) ?? record$4(field(raw, "reference_audio")), union ? "object" : "url") ?? seedReferenceLimits(raw);
5702
5759
  const outputFormats = parseOutputFormats(raw);
5703
5760
  const defaultFormat = text$4(field(raw, "default_format"))?.toLowerCase();
5704
5761
  const choices = stringChoices(field(raw, "choices") ?? field(raw, "field_options"));
@@ -5740,12 +5797,12 @@ function parseAudioCapabilities(raw) {
5740
5797
  return result;
5741
5798
  }
5742
5799
  function parsePricing(value, audioUnit) {
5743
- const raw = record$3(value);
5800
+ const raw = record$4(value);
5744
5801
  if (raw === void 0) return void 0;
5745
5802
  const unit = (item) => PRICE_UNITS.includes(item) ? item : item === void 0 && audioUnit !== void 0 ? audioUnit : void 0;
5746
5803
  const tiers = [];
5747
5804
  if (Array.isArray(raw.tiers)) for (const entry of raw.tiers) {
5748
- const tier = record$3(entry);
5805
+ const tier = record$4(entry);
5749
5806
  const name = text$4(tier?.tier);
5750
5807
  const tierUnit = unit(tier?.unit);
5751
5808
  const amount = typeof tier?.amount === "number" && Number.isFinite(tier.amount) && tier.amount >= 0 ? tier.amount : void 0;
@@ -5755,7 +5812,7 @@ function parsePricing(value, audioUnit) {
5755
5812
  amount
5756
5813
  });
5757
5814
  }
5758
- const fallback = record$3(raw.default);
5815
+ const fallback = record$4(raw.default);
5759
5816
  const fallbackUnit = unit(fallback?.unit);
5760
5817
  const fallbackAmount = typeof fallback?.amount === "number" && Number.isFinite(fallback.amount) && fallback.amount >= 0 ? fallback.amount : void 0;
5761
5818
  if (tiers.length === 0 && (fallbackUnit === void 0 || fallbackAmount === void 0)) return void 0;
@@ -5783,7 +5840,7 @@ function condition(raw, snake) {
5783
5840
  */
5784
5841
  function parseVideoPricing(value) {
5785
5842
  if (value === void 0 || value === null) return {};
5786
- const raw = record$3(value);
5843
+ const raw = record$4(value);
5787
5844
  if (raw === void 0) return { videoPricingIssue: "invalid" };
5788
5845
  if (field(raw, "schema_version") !== 1) return { videoPricingIssue: "unknown-schema" };
5789
5846
  const invalid = { videoPricingIssue: "invalid" };
@@ -5793,7 +5850,7 @@ function parseVideoPricing(value) {
5793
5850
  if (!Array.isArray(rulesRaw) || rulesRaw.length === 0) return invalid;
5794
5851
  const rules = [];
5795
5852
  for (const item of rulesRaw) {
5796
- const entry = record$3(item);
5853
+ const entry = record$4(item);
5797
5854
  if (entry === void 0) return invalid;
5798
5855
  const resolution = text$4(field(entry, "resolution"));
5799
5856
  const perMillion = price(field(entry, "price_per_million_tokens"));
@@ -5845,15 +5902,15 @@ function kindOf(entry, capabilities, audio) {
5845
5902
  * @returns the media models, in catalog order.
5846
5903
  */
5847
5904
  function parseMediaCatalog(body) {
5848
- const entries = Array.isArray(body) ? body : record$3(body)?.data;
5905
+ const entries = Array.isArray(body) ? body : record$4(body)?.data;
5849
5906
  if (!Array.isArray(entries)) return [];
5850
5907
  const models = [];
5851
5908
  const seen = /* @__PURE__ */ new Set();
5852
5909
  for (const item of entries) {
5853
- const entry = record$3(item);
5910
+ const entry = record$4(item);
5854
5911
  const id = text$4(entry?.id);
5855
5912
  if (entry === void 0 || id === void 0 || seen.has(id)) continue;
5856
- const capabilities = record$3(entry.capabilities) ?? {};
5913
+ const capabilities = record$4(entry.capabilities) ?? {};
5857
5914
  const audioRaw = audioBlock(entry, capabilities);
5858
5915
  const audio = audioRaw === void 0 ? void 0 : parseAudioCapabilities(audioRaw);
5859
5916
  const kind = kindOf(entry, capabilities, audio);
@@ -5869,7 +5926,7 @@ function parseMediaCatalog(body) {
5869
5926
  let video;
5870
5927
  if (kind === "video") video = {
5871
5928
  ...parseVideoCapabilities(capabilities),
5872
- ...parseVideoCapabilities(record$3(entry.video) ?? {})
5929
+ ...parseVideoCapabilities(record$4(entry.video) ?? {})
5873
5930
  };
5874
5931
  const imageSizes = kind === "image" ? optionList(field(capabilities, "image_sizes")) : void 0;
5875
5932
  const imageRatios = kind === "image" ? optionList(field(capabilities, "image_ratios")) : void 0;
@@ -7718,6 +7775,381 @@ function audioFormOf(model) {
7718
7775
  };
7719
7776
  }
7720
7777
  //#endregion
7778
+ //#region src/tasks/progress.ts
7779
+ const record$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7780
+ const nonNegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
7781
+ const position = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
7782
+ const instant = (value) => {
7783
+ if (typeof value !== "string" || value.trim() === "") return void 0;
7784
+ const ms = Date.parse(value);
7785
+ return Number.isFinite(ms) ? ms : void 0;
7786
+ };
7787
+ const PHASES = {
7788
+ submitting: "pending_submit",
7789
+ pending_submit: "pending_submit",
7790
+ queued: "queued",
7791
+ waiting: "queued",
7792
+ running: "generating",
7793
+ processing: "generating",
7794
+ in_progress: "generating",
7795
+ generating: "generating",
7796
+ archiving: "archiving",
7797
+ uploading: "archiving",
7798
+ finalizing: "archiving",
7799
+ completed: "done",
7800
+ succeeded: "done",
7801
+ done: "done"
7802
+ };
7803
+ const SOURCES = /* @__PURE__ */ new Set(["upstream", "history"]);
7804
+ const CONFIDENCES = /* @__PURE__ */ new Set([
7805
+ "high",
7806
+ "medium",
7807
+ "low"
7808
+ ]);
7809
+ /** Fewest and most seconds between two queries the gateway may ask for. */
7810
+ const POLL_MIN_SECONDS = 2;
7811
+ const POLL_MAX_SECONDS = 30;
7812
+ function phaseOf(value) {
7813
+ return typeof value === "string" ? PHASES[value.trim().toLowerCase()] : void 0;
7814
+ }
7815
+ /** 0–1 as given; above 1 and up to 100 a percentage. */
7816
+ function progressOf$1(value) {
7817
+ const number = nonNegative(value);
7818
+ if (number === void 0 || number > 100) return void 0;
7819
+ return number > 1 ? number / 100 : number;
7820
+ }
7821
+ function timingOf(value, receivedAt) {
7822
+ const raw = record$3(value);
7823
+ if (raw === void 0) return void 0;
7824
+ const serverTime = instant(raw.server_time);
7825
+ const skew = serverTime === void 0 ? 0 : receivedAt - serverTime;
7826
+ const local = (field) => {
7827
+ const at = instant(field);
7828
+ return at === void 0 ? void 0 : at + skew;
7829
+ };
7830
+ const after = (field) => {
7831
+ const seconds = nonNegative(field);
7832
+ return seconds === void 0 ? void 0 : receivedAt + seconds * 1e3;
7833
+ };
7834
+ const facts = {
7835
+ phase: phaseOf(raw.phase),
7836
+ startedAt: local(raw.started_at),
7837
+ phaseStartedAt: local(raw.phase_started_at),
7838
+ estimatedCompletionAt: after(raw.estimated_remaining_seconds),
7839
+ p90CompletionAt: after(raw.remaining_p90_seconds),
7840
+ estimateSource: typeof raw.estimate_source === "string" && SOURCES.has(raw.estimate_source) ? raw.estimate_source : void 0,
7841
+ confidence: typeof raw.confidence === "string" && CONFIDENCES.has(raw.confidence) ? raw.confidence : void 0,
7842
+ progress: progressOf$1(raw.progress)
7843
+ };
7844
+ const known = Object.fromEntries(Object.entries(facts).filter(([, fact]) => fact !== void 0));
7845
+ return Object.keys(known).length === 0 ? void 0 : {
7846
+ ...known,
7847
+ observedAt: receivedAt
7848
+ };
7849
+ }
7850
+ function queueOf(value) {
7851
+ const raw = record$3(value);
7852
+ if (raw === void 0) return void 0;
7853
+ const facts = {
7854
+ position: position(raw.position),
7855
+ positionMin: position(raw.position_min),
7856
+ positionMax: position(raw.position_max)
7857
+ };
7858
+ const known = Object.fromEntries(Object.entries(facts).filter(([, fact]) => fact !== void 0));
7859
+ return Object.keys(known).length === 0 ? void 0 : known;
7860
+ }
7861
+ /**
7862
+ * Read the progress facts of a task answer.
7863
+ * @param raw - the parsed task answer.
7864
+ * @param receivedAt - when this machine received it (epoch ms); the anchor of every time.
7865
+ * @returns only the facts the answer gives in a readable form.
7866
+ */
7867
+ function parseProgress(raw, receivedAt) {
7868
+ const timing = timingOf(raw.timing, receivedAt);
7869
+ const queue = queueOf(raw.queue);
7870
+ const poll = nonNegative(raw.next_poll_after_seconds);
7871
+ return {
7872
+ ...timing === void 0 ? {} : { timing },
7873
+ ...queue === void 0 ? {} : { queue },
7874
+ ...poll === void 0 ? {} : { nextPollAfterSeconds: Math.min(POLL_MAX_SECONDS, Math.max(POLL_MIN_SECONDS, poll)) }
7875
+ };
7876
+ }
7877
+ /** The local download of a finished task's results is recorded under this progress line. */
7878
+ const SAVING_PROGRESS = "saving the result";
7879
+ /**
7880
+ * The stage of a task: `submitting` while the gateway has not confirmed it or
7881
+ * has not submitted it upstream, `saving` while the result is archived by the
7882
+ * gateway or downloaded here, `queued`, and otherwise `generating`.
7883
+ * @param task - the task's status, progress line and timing.
7884
+ * @returns the stage, or undefined for a finished task.
7885
+ */
7886
+ function stageOf(task) {
7887
+ if (task.status === "submitting") return "submitting";
7888
+ if (task.status !== "pending") return void 0;
7889
+ if (task.progress === "saving the result" || task.timing?.phase === "archiving") return "saving";
7890
+ if (task.timing?.phase === "queued") return "queued";
7891
+ if (task.timing?.phase === "pending_submit") return "submitting";
7892
+ return "generating";
7893
+ }
7894
+ const STAGE_WORDS = {
7895
+ submitting: {
7896
+ en: "being submitted",
7897
+ zh: "提交中"
7898
+ },
7899
+ queued: {
7900
+ en: "queued",
7901
+ zh: "排队中"
7902
+ },
7903
+ generating: {
7904
+ en: "generating",
7905
+ zh: "生成中"
7906
+ },
7907
+ saving: {
7908
+ en: "saving the result",
7909
+ zh: "保存中"
7910
+ }
7911
+ };
7912
+ function queueWords(queue) {
7913
+ if (queue?.position !== void 0) return {
7914
+ en: `position ${queue.position} in the queue`,
7915
+ zh: `第 ${queue.position} 位`
7916
+ };
7917
+ if (queue?.positionMin !== void 0 && queue.positionMax !== void 0) return {
7918
+ en: `position ${queue.positionMin}–${queue.positionMax} in the queue`,
7919
+ zh: `第 ${queue.positionMin}–${queue.positionMax} 位`
7920
+ };
7921
+ }
7922
+ /**
7923
+ * The time left, in coarse words: under a minute, about N minutes, or slower
7924
+ * than estimated once the estimate has passed. An estimate the gateway marks
7925
+ * as low confidence is not stated.
7926
+ * @param timing - the task's timing.
7927
+ * @param now - this machine's clock (epoch ms).
7928
+ * @returns the wording, or undefined without a usable estimate.
7929
+ */
7930
+ function remainingWords(timing, now) {
7931
+ if (timing?.estimatedCompletionAt === void 0 || timing.confidence === "low") return void 0;
7932
+ const left = timing.estimatedCompletionAt - now;
7933
+ if (left < 0) return {
7934
+ en: "slower than estimated (still running)",
7935
+ zh: "比预计慢"
7936
+ };
7937
+ if (left < 6e4) return {
7938
+ en: "under 1 min left",
7939
+ zh: "不到 1 分钟"
7940
+ };
7941
+ const minutes = Math.max(1, Math.round(left / 6e4));
7942
+ return {
7943
+ en: `about ${minutes} min left`,
7944
+ zh: `约 ${minutes} 分钟`
7945
+ };
7946
+ }
7947
+ /**
7948
+ * How a running task with progress facts reads: stage, queue position, the
7949
+ * provider's progress and the time left, in English with the Chinese wording
7950
+ * after it (`queued, position 3 in the queue, about 2 min left (排队中 · 第 3 位 · 约 2 分钟)`).
7951
+ * @param task - the task's status, progress line, timing and queue.
7952
+ * @param now - this machine's clock (epoch ms).
7953
+ * @returns the wording, or undefined when the task is finished or carries no progress facts.
7954
+ */
7955
+ function progressWords(task, now) {
7956
+ if (task.timing === void 0 && task.queue === void 0) return void 0;
7957
+ const stage = stageOf(task);
7958
+ if (stage === void 0) return void 0;
7959
+ const percent = task.timing?.progress === void 0 ? void 0 : `${Math.round(task.timing.progress * 100)}%`;
7960
+ const parts = [queueWords(task.queue), remainingWords(task.timing, now)].filter((part) => part !== void 0);
7961
+ const en = [`${STAGE_WORDS[stage].en}${percent === void 0 ? "" : ` ${percent}`}`, ...parts.map((part) => part.en)].join(", ");
7962
+ const queue = queueWords(task.queue);
7963
+ return `${en} (${[
7964
+ STAGE_WORDS[stage].zh,
7965
+ queue?.zh,
7966
+ percent,
7967
+ remainingWords(task.timing, now)?.zh
7968
+ ].filter((part) => part !== void 0).join(" · ")})`;
7969
+ }
7970
+ //#endregion
7971
+ //#region src/tasks/store.ts
7972
+ /**
7973
+ * The durable list of video and audio tasks, one file per task under
7974
+ * `<state dir>/tasks/`, so harness processes sharing a home never overwrite
7975
+ * each other's tasks. A task is recorded before it is submitted, under the id
7976
+ * that doubles as its `Idempotency-Key`: a submission cut short is resent under
7977
+ * the same key (the gateway returns the original task instead of creating a
7978
+ * second one), and a task still running when the host restarts is followed to
7979
+ * the end. A claim file names the process following a task, so two processes
7980
+ * never poll and download the same one.
7981
+ * @module dsh-vibedev/tasks/store
7982
+ */
7983
+ /** Terminal tasks kept for listings; live ones are always kept. */
7984
+ const KEEP_FINISHED = 100;
7985
+ const TERMINAL = /* @__PURE__ */ new Set([
7986
+ "completed",
7987
+ "failed",
7988
+ "lost"
7989
+ ]);
7990
+ const SAFE_ID = /^[\w-]{1,80}$/;
7991
+ /**
7992
+ * Whether a task has ended.
7993
+ * @param record - the task.
7994
+ * @returns true for completed, failed and lost tasks.
7995
+ */
7996
+ function isFinished(record) {
7997
+ return TERMINAL.has(record.status);
7998
+ }
7999
+ function parse(text) {
8000
+ try {
8001
+ const value = JSON.parse(text);
8002
+ return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.status === "string" ? value : void 0;
8003
+ } catch {
8004
+ return;
8005
+ }
8006
+ }
8007
+ /** Task records under `<state dir>/tasks/`. */
8008
+ var TaskStore = class {
8009
+ directory;
8010
+ now;
8011
+ chains = /* @__PURE__ */ new Map();
8012
+ /**
8013
+ * @param directory - the plugin state directory.
8014
+ * @param now - clock.
8015
+ */
8016
+ constructor(directory, now = Date.now) {
8017
+ this.directory = directory;
8018
+ this.now = now;
8019
+ }
8020
+ get dir() {
8021
+ return join(this.directory, "tasks");
8022
+ }
8023
+ file(id, suffix = "json") {
8024
+ if (!SAFE_ID.test(id)) throw new Error(`invalid task id ${JSON.stringify(id)}`);
8025
+ return join(this.dir, `${id}.${suffix}`);
8026
+ }
8027
+ /** Run one change to a task after the previous change to it in this process. */
8028
+ serial(id, run) {
8029
+ const next = (this.chains.get(id) ?? Promise.resolve()).then(run, run);
8030
+ const settled = next.catch(() => void 0);
8031
+ this.chains.set(id, settled);
8032
+ settled.then(() => {
8033
+ if (this.chains.get(id) === settled) this.chains.delete(id);
8034
+ });
8035
+ return next;
8036
+ }
8037
+ /** All tasks, newest first, as they are on disk now (other processes' tasks included). */
8038
+ async list() {
8039
+ const names = await readdir(this.dir).catch(() => []);
8040
+ return (await Promise.all(names.filter((name) => name.endsWith(".json")).map((name) => readFile(join(this.dir, name), "utf8").then(parse, () => void 0)))).filter((record) => record !== void 0).sort((a, b) => b.createdAt - a.createdAt);
8041
+ }
8042
+ /**
8043
+ * One task.
8044
+ * @param id - its local id.
8045
+ * @returns the task, or undefined.
8046
+ */
8047
+ async get(id) {
8048
+ return readFile(this.file(id), "utf8").then(parse, () => void 0);
8049
+ }
8050
+ /**
8051
+ * Record a new task.
8052
+ * @param record - the task.
8053
+ * @returns the stored task.
8054
+ */
8055
+ add(record) {
8056
+ return this.serial(record.id, async () => {
8057
+ await writeFileAtomic(this.file(record.id), new TextEncoder().encode(JSON.stringify(record, null, 2)));
8058
+ await this.prune().catch(() => void 0);
8059
+ return record;
8060
+ });
8061
+ }
8062
+ /**
8063
+ * Change a task.
8064
+ * @param id - its local id.
8065
+ * @param patch - the fields to replace.
8066
+ * @returns the updated task, or undefined when it is unknown.
8067
+ */
8068
+ update(id, patch) {
8069
+ return this.serial(id, async () => {
8070
+ const current = await this.get(id);
8071
+ if (current === void 0) return void 0;
8072
+ const next = {
8073
+ ...current,
8074
+ ...patch,
8075
+ updatedAt: this.now()
8076
+ };
8077
+ await writeFileAtomic(this.file(id), new TextEncoder().encode(JSON.stringify(next, null, 2)));
8078
+ return next;
8079
+ });
8080
+ }
8081
+ /**
8082
+ * Forget a task, such as a submission the gateway refused outright.
8083
+ * @param id - its local id.
8084
+ */
8085
+ remove(id) {
8086
+ return this.serial(id, async () => {
8087
+ await rm(this.file(id), { force: true });
8088
+ await rm(this.file(id, "claim"), { force: true });
8089
+ });
8090
+ }
8091
+ /**
8092
+ * Claim the right to follow a task: free, already ours, or held by a process
8093
+ * that stopped renewing it for `staleMs`.
8094
+ * @param id - the task.
8095
+ * @param holder - this process's claim id.
8096
+ * @param staleMs - how old an unrenewed claim may be before it is taken over.
8097
+ * @returns whether this process now holds the claim.
8098
+ */
8099
+ async claim(id, holder, staleMs) {
8100
+ const path = this.file(id, "claim");
8101
+ for (let attempt = 0; attempt < 2; attempt++) {
8102
+ try {
8103
+ const handle = await open(path, "wx");
8104
+ await handle.writeFile(JSON.stringify({
8105
+ holder,
8106
+ at: this.now()
8107
+ }));
8108
+ await handle.close();
8109
+ return true;
8110
+ } catch (error) {
8111
+ if (error.code !== "EEXIST") return false;
8112
+ }
8113
+ const current = await readFile(path, "utf8").then((text) => JSON.parse(text), () => void 0);
8114
+ if (current?.holder === holder) {
8115
+ await this.renewClaim(id, holder);
8116
+ return true;
8117
+ }
8118
+ const at = typeof current?.at === "number" ? current.at : 0;
8119
+ if (this.now() - at < staleMs) return false;
8120
+ await rm(path, { force: true });
8121
+ }
8122
+ return false;
8123
+ }
8124
+ /**
8125
+ * Keep a claim alive.
8126
+ * @param id - the task.
8127
+ * @param holder - this process's claim id.
8128
+ */
8129
+ async renewClaim(id, holder) {
8130
+ await writeFileAtomic(this.file(id, "claim"), new TextEncoder().encode(JSON.stringify({
8131
+ holder,
8132
+ at: this.now()
8133
+ })));
8134
+ }
8135
+ /**
8136
+ * Give up a claim this process holds.
8137
+ * @param id - the task.
8138
+ * @param holder - this process's claim id.
8139
+ */
8140
+ async release(id, holder) {
8141
+ const path = this.file(id, "claim");
8142
+ if ((await readFile(path, "utf8").then((text) => JSON.parse(text), () => void 0))?.holder === holder) await rm(path, { force: true });
8143
+ }
8144
+ async prune() {
8145
+ const finished = (await this.list()).filter(isFinished);
8146
+ for (const record of finished.slice(KEEP_FINISHED)) {
8147
+ await rm(this.file(record.id), { force: true });
8148
+ await rm(this.file(record.id, "claim"), { force: true });
8149
+ }
8150
+ }
8151
+ };
8152
+ //#endregion
7721
8153
  //#region src/tools/common.ts
7722
8154
  /** How a media input may be given, for parameter descriptions. */
7723
8155
  const SOURCE_HELP = "a workspace file path, an http(s) link, or chat:1 for the most recent matching file the user attached in this conversation (chat:2 the one before)";
@@ -7766,7 +8198,10 @@ function describeTask(runtime, exec, record) {
7766
8198
  }
7767
8199
  case "failed": return `${what} task ${record.id} failed${record.error === void 0 ? "" : ` (${record.error.code}: ${record.error.message})`}.${moneyLine(record)}`;
7768
8200
  case "lost": return `${what} task ${record.id} is no longer followed: ${record.error?.message ?? "unknown reason"}`;
7769
- default: return `${what} task ${record.id} with ${record.model} is ${record.status === "submitting" ? "being submitted" : record.progress ?? "in progress"}; results are saved under ${show(record.outputDir)} when it finishes.`;
8201
+ default: {
8202
+ const state = (record.timing === void 0 && record.queue === void 0 ? void 0 : progressWords(record, runtime.now())) ?? (record.status === "submitting" ? "being submitted" : record.progress ?? "in progress");
8203
+ return `${what} task ${record.id} with ${record.model} is ${state}; results are saved under ${show(record.outputDir)} when it finishes.`;
8204
+ }
7770
8205
  }
7771
8206
  }
7772
8207
  /**
@@ -8887,6 +9322,16 @@ function videoGenerateTool(runtime) {
8887
9322
  * {@link MediaHostService.result} (the files to play or download).
8888
9323
  * @module dsh-vibedev/service
8889
9324
  */
9325
+ /** The stage, timing and queue of a running task; nothing for a finished one. */
9326
+ function progressView(record) {
9327
+ if (isFinished(record)) return {};
9328
+ const stage = stageOf(record);
9329
+ return {
9330
+ ...stage === void 0 ? {} : { stage },
9331
+ ...record.timing === void 0 ? {} : { timing: { ...record.timing } },
9332
+ ...record.queue === void 0 ? {} : { queue: { ...record.queue } }
9333
+ };
9334
+ }
8890
9335
  const view = (record) => ({
8891
9336
  id: record.id,
8892
9337
  kind: record.kind,
@@ -8894,6 +9339,7 @@ const view = (record) => ({
8894
9339
  model: record.model,
8895
9340
  status: record.status,
8896
9341
  ...record.progress === void 0 ? {} : { progress: record.progress },
9342
+ ...progressView(record),
8897
9343
  ...record.outputs === void 0 ? {} : { outputs: record.outputs.map(({ index: _index, bytes: _bytes, ...output }) => ({ ...output })) },
8898
9344
  ...record.error === void 0 ? {} : { error: { ...record.error } },
8899
9345
  ...record.estimatedCny === void 0 ? {} : { estimatedCny: record.estimatedCny },
@@ -9116,189 +9562,24 @@ var MediaHostService = class {
9116
9562
  }
9117
9563
  };
9118
9564
  //#endregion
9119
- //#region src/tasks/store.ts
9120
- /**
9121
- * The durable list of video and audio tasks, one file per task under
9122
- * `<state dir>/tasks/`, so harness processes sharing a home never overwrite
9123
- * each other's tasks. A task is recorded before it is submitted, under the id
9124
- * that doubles as its `Idempotency-Key`: a submission cut short is resent under
9125
- * the same key (the gateway returns the original task instead of creating a
9126
- * second one), and a task still running when the host restarts is followed to
9127
- * the end. A claim file names the process following a task, so two processes
9128
- * never poll and download the same one.
9129
- * @module dsh-vibedev/tasks/store
9130
- */
9131
- /** Terminal tasks kept for listings; live ones are always kept. */
9132
- const KEEP_FINISHED = 100;
9133
- const TERMINAL = /* @__PURE__ */ new Set([
9134
- "completed",
9135
- "failed",
9136
- "lost"
9137
- ]);
9138
- const SAFE_ID = /^[\w-]{1,80}$/;
9565
+ //#region src/tasks/remote.ts
9139
9566
  /**
9140
- * Whether a task has ended.
9141
- * @param record - the task.
9142
- * @returns true for completed, failed and lost tasks.
9567
+ * Reading the gateway's asynchronous task objects: `POST /v1/videos` and
9568
+ * `GET /v1/videos/{id}` (OpenAI video shape plus the gateway's `effective`
9569
+ * receipt and `asset`), and `POST /v1/audio/generations` and
9570
+ * `GET /v1/audio/generations/{id}` (`outputs[]`). Unknown statuses count as
9571
+ * still running; only an explicit terminal status ends a task.
9572
+ *
9573
+ * Both kinds carry the same settlement facts in `effective`: `billing_status`
9574
+ * (`pending`/`settled`), `billing_pending_reason`, `charged_cny` (kept as the
9575
+ * exact string given), `billed_tokens` and `estimated_cny`. A completed task
9576
+ * whose billing is pending has its result; only the charge is still to come.
9577
+ *
9578
+ * Newer gateways add progress facts (`timing`, `queue`,
9579
+ * `next_poll_after_seconds`), read by {@link parseProgress} against the time
9580
+ * the answer arrived.
9581
+ * @module dsh-vibedev/tasks/remote
9143
9582
  */
9144
- function isFinished(record) {
9145
- return TERMINAL.has(record.status);
9146
- }
9147
- function parse(text) {
9148
- try {
9149
- const value = JSON.parse(text);
9150
- return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.status === "string" ? value : void 0;
9151
- } catch {
9152
- return;
9153
- }
9154
- }
9155
- /** Task records under `<state dir>/tasks/`. */
9156
- var TaskStore = class {
9157
- directory;
9158
- now;
9159
- chains = /* @__PURE__ */ new Map();
9160
- /**
9161
- * @param directory - the plugin state directory.
9162
- * @param now - clock.
9163
- */
9164
- constructor(directory, now = Date.now) {
9165
- this.directory = directory;
9166
- this.now = now;
9167
- }
9168
- get dir() {
9169
- return join(this.directory, "tasks");
9170
- }
9171
- file(id, suffix = "json") {
9172
- if (!SAFE_ID.test(id)) throw new Error(`invalid task id ${JSON.stringify(id)}`);
9173
- return join(this.dir, `${id}.${suffix}`);
9174
- }
9175
- /** Run one change to a task after the previous change to it in this process. */
9176
- serial(id, run) {
9177
- const next = (this.chains.get(id) ?? Promise.resolve()).then(run, run);
9178
- const settled = next.catch(() => void 0);
9179
- this.chains.set(id, settled);
9180
- settled.then(() => {
9181
- if (this.chains.get(id) === settled) this.chains.delete(id);
9182
- });
9183
- return next;
9184
- }
9185
- /** All tasks, newest first, as they are on disk now (other processes' tasks included). */
9186
- async list() {
9187
- const names = await readdir(this.dir).catch(() => []);
9188
- return (await Promise.all(names.filter((name) => name.endsWith(".json")).map((name) => readFile(join(this.dir, name), "utf8").then(parse, () => void 0)))).filter((record) => record !== void 0).sort((a, b) => b.createdAt - a.createdAt);
9189
- }
9190
- /**
9191
- * One task.
9192
- * @param id - its local id.
9193
- * @returns the task, or undefined.
9194
- */
9195
- async get(id) {
9196
- return readFile(this.file(id), "utf8").then(parse, () => void 0);
9197
- }
9198
- /**
9199
- * Record a new task.
9200
- * @param record - the task.
9201
- * @returns the stored task.
9202
- */
9203
- add(record) {
9204
- return this.serial(record.id, async () => {
9205
- await writeFileAtomic(this.file(record.id), new TextEncoder().encode(JSON.stringify(record, null, 2)));
9206
- await this.prune().catch(() => void 0);
9207
- return record;
9208
- });
9209
- }
9210
- /**
9211
- * Change a task.
9212
- * @param id - its local id.
9213
- * @param patch - the fields to replace.
9214
- * @returns the updated task, or undefined when it is unknown.
9215
- */
9216
- update(id, patch) {
9217
- return this.serial(id, async () => {
9218
- const current = await this.get(id);
9219
- if (current === void 0) return void 0;
9220
- const next = {
9221
- ...current,
9222
- ...patch,
9223
- updatedAt: this.now()
9224
- };
9225
- await writeFileAtomic(this.file(id), new TextEncoder().encode(JSON.stringify(next, null, 2)));
9226
- return next;
9227
- });
9228
- }
9229
- /**
9230
- * Forget a task, such as a submission the gateway refused outright.
9231
- * @param id - its local id.
9232
- */
9233
- remove(id) {
9234
- return this.serial(id, async () => {
9235
- await rm(this.file(id), { force: true });
9236
- await rm(this.file(id, "claim"), { force: true });
9237
- });
9238
- }
9239
- /**
9240
- * Claim the right to follow a task: free, already ours, or held by a process
9241
- * that stopped renewing it for `staleMs`.
9242
- * @param id - the task.
9243
- * @param holder - this process's claim id.
9244
- * @param staleMs - how old an unrenewed claim may be before it is taken over.
9245
- * @returns whether this process now holds the claim.
9246
- */
9247
- async claim(id, holder, staleMs) {
9248
- const path = this.file(id, "claim");
9249
- for (let attempt = 0; attempt < 2; attempt++) {
9250
- try {
9251
- const handle = await open(path, "wx");
9252
- await handle.writeFile(JSON.stringify({
9253
- holder,
9254
- at: this.now()
9255
- }));
9256
- await handle.close();
9257
- return true;
9258
- } catch (error) {
9259
- if (error.code !== "EEXIST") return false;
9260
- }
9261
- const current = await readFile(path, "utf8").then((text) => JSON.parse(text), () => void 0);
9262
- if (current?.holder === holder) {
9263
- await this.renewClaim(id, holder);
9264
- return true;
9265
- }
9266
- const at = typeof current?.at === "number" ? current.at : 0;
9267
- if (this.now() - at < staleMs) return false;
9268
- await rm(path, { force: true });
9269
- }
9270
- return false;
9271
- }
9272
- /**
9273
- * Keep a claim alive.
9274
- * @param id - the task.
9275
- * @param holder - this process's claim id.
9276
- */
9277
- async renewClaim(id, holder) {
9278
- await writeFileAtomic(this.file(id, "claim"), new TextEncoder().encode(JSON.stringify({
9279
- holder,
9280
- at: this.now()
9281
- })));
9282
- }
9283
- /**
9284
- * Give up a claim this process holds.
9285
- * @param id - the task.
9286
- * @param holder - this process's claim id.
9287
- */
9288
- async release(id, holder) {
9289
- const path = this.file(id, "claim");
9290
- if ((await readFile(path, "utf8").then((text) => JSON.parse(text), () => void 0))?.holder === holder) await rm(path, { force: true });
9291
- }
9292
- async prune() {
9293
- const finished = (await this.list()).filter(isFinished);
9294
- for (const record of finished.slice(KEEP_FINISHED)) {
9295
- await rm(this.file(record.id), { force: true });
9296
- await rm(this.file(record.id, "claim"), { force: true });
9297
- }
9298
- }
9299
- };
9300
- //#endregion
9301
- //#region src/tasks/remote.ts
9302
9583
  const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
9303
9584
  const text$1 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
9304
9585
  const httpUrl = (value) => {
@@ -9423,9 +9704,10 @@ function receipt(raw) {
9423
9704
  /**
9424
9705
  * Read a video task.
9425
9706
  * @param body - the parsed answer.
9707
+ * @param receivedAt - when this machine received it (epoch ms), the anchor of its progress times.
9426
9708
  * @returns the task, or undefined when the answer names no task id.
9427
9709
  */
9428
- function parseVideoTask(body) {
9710
+ function parseVideoTask(body, receivedAt = Date.now()) {
9429
9711
  const raw = record$1(body);
9430
9712
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
9431
9713
  if (raw === void 0 || id === void 0) return void 0;
@@ -9451,6 +9733,7 @@ function parseVideoTask(body) {
9451
9733
  ...error === void 0 ? {} : { error },
9452
9734
  ...receipt(raw),
9453
9735
  ...settlementOf(raw, status),
9736
+ ...parseProgress(raw, receivedAt),
9454
9737
  outputs: state === "completed" ? [{
9455
9738
  index: 0,
9456
9739
  ...url === void 0 ? {} : { url },
@@ -9462,9 +9745,10 @@ function parseVideoTask(body) {
9462
9745
  /**
9463
9746
  * Read a music or podcast task.
9464
9747
  * @param body - the parsed answer.
9748
+ * @param receivedAt - when this machine received it (epoch ms), the anchor of its progress times.
9465
9749
  * @returns the task, or undefined when the answer names no task id.
9466
9750
  */
9467
- function parseAudioTask(body) {
9751
+ function parseAudioTask(body, receivedAt = Date.now()) {
9468
9752
  const raw = record$1(body);
9469
9753
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
9470
9754
  if (raw === void 0 || id === void 0) return void 0;
@@ -9506,6 +9790,7 @@ function parseAudioTask(body) {
9506
9790
  ...receipt(raw),
9507
9791
  ...settlementOf(raw, status),
9508
9792
  ...billedLengths(raw),
9793
+ ...parseProgress(raw, receivedAt),
9509
9794
  outputs: state === "completed" ? outputs : []
9510
9795
  };
9511
9796
  }
@@ -9739,7 +10024,7 @@ var TaskTracker = class {
9739
10024
  idempotencyKey: draft.id,
9740
10025
  timeoutMs: SUBMIT_TIMEOUT_MS,
9741
10026
  ...signal === void 0 ? {} : { signal }
9742
- }));
10027
+ }), this.now());
9743
10028
  if (task === void 0) throw new MediaError("The VibeDev gateway accepted the request but returned no task id.", "GATEWAY_BAD_RESPONSE");
9744
10029
  } catch (error) {
9745
10030
  if (signal?.aborted === true) {
@@ -9862,8 +10147,14 @@ var TaskTracker = class {
9862
10147
  }
9863
10148
  async finish(id, patch) {
9864
10149
  this.downloadFailures.delete(id);
10150
+ const current = await this.options.store.get(id).catch(() => void 0);
10151
+ const progressFacts = {
10152
+ ...current?.timing === void 0 && patch.timing === void 0 ? {} : { timing: void 0 },
10153
+ ...current?.queue === void 0 && patch.queue === void 0 ? {} : { queue: void 0 }
10154
+ };
9865
10155
  const record = await this.update(id, {
9866
10156
  ...patch,
10157
+ ...progressFacts,
9867
10158
  progress: void 0,
9868
10159
  finishedAt: this.now()
9869
10160
  });
@@ -9931,16 +10222,16 @@ var TaskTracker = class {
9931
10222
  idempotencyKey: record.id,
9932
10223
  timeoutMs: SUBMIT_TIMEOUT_MS,
9933
10224
  signal: this.signal
9934
- }));
10225
+ }), this.now());
9935
10226
  } else task = spec.parse(await this.options.http.json(spec.poll(record.gatewayId), {
9936
10227
  timeoutMs: 3e4,
9937
10228
  signal: this.signal
9938
- }));
10229
+ }), this.now());
9939
10230
  if (task === void 0) throw new MediaError("The VibeDev gateway returned an unreadable task.", "GATEWAY_BAD_RESPONSE");
9940
10231
  record = await this.apply(record, task);
9941
10232
  failures = 0;
9942
10233
  if (isFinished(record)) return record;
9943
- await this.sleep(spec.interval(age), this.signal);
10234
+ await this.sleep(task.nextPollAfterSeconds === void 0 ? spec.interval(age) : task.nextPollAfterSeconds * 1e3, this.signal);
9944
10235
  } catch (error) {
9945
10236
  if (this.signal.aborted) break;
9946
10237
  failures++;
@@ -10048,6 +10339,17 @@ var TaskTracker = class {
10048
10339
  ...billing
10049
10340
  };
10050
10341
  }
10342
+ /**
10343
+ * The progress facts to record from an answer. Each answer replaces the
10344
+ * last one's, so a fact it no longer gives is removed; a record that never
10345
+ * had any (an older gateway) is left untouched.
10346
+ */
10347
+ progressFactsOf(record, task) {
10348
+ return {
10349
+ ...task.timing === void 0 && record.timing === void 0 ? {} : { timing: task.timing },
10350
+ ...task.queue === void 0 && record.queue === void 0 ? {} : { queue: task.queue }
10351
+ };
10352
+ }
10051
10353
  /** Record what the gateway says about a task; save the outputs of a finished one. */
10052
10354
  async apply(record, task) {
10053
10355
  const money = this.moneyOf(record, task);
@@ -10055,7 +10357,8 @@ var TaskTracker = class {
10055
10357
  gatewayId: task.id,
10056
10358
  status: "pending",
10057
10359
  progress: progressLine(task),
10058
- ...money
10360
+ ...money,
10361
+ ...this.progressFactsOf(record, task)
10059
10362
  });
10060
10363
  if (task.state === "failed") return this.finish(record.id, {
10061
10364
  gatewayId: task.id,
@@ -10066,8 +10369,9 @@ var TaskTracker = class {
10066
10369
  const current = await this.update(record.id, {
10067
10370
  gatewayId: task.id,
10068
10371
  status: "pending",
10069
- progress: "saving the result",
10070
- ...money
10372
+ progress: SAVING_PROGRESS,
10373
+ ...money,
10374
+ ...this.progressFactsOf(record, task)
10071
10375
  });
10072
10376
  const { outputs, missing } = await this.saveOutputs(current, task);
10073
10377
  if (missing > 0) {
@@ -10080,7 +10384,7 @@ var TaskTracker = class {
10080
10384
  const settled = await this.options.http.json(SPECS[record.kind].poll(task.id), {
10081
10385
  timeoutMs: 15e3,
10082
10386
  signal: this.signal
10083
- }).then((body) => SPECS[record.kind].parse(body), () => void 0);
10387
+ }).then((body) => SPECS[record.kind].parse(body, this.now()), () => void 0);
10084
10388
  if (settled !== void 0) charged = {
10085
10389
  ...money,
10086
10390
  ...this.moneyOf(current, settled)
@@ -10119,7 +10423,7 @@ var TaskTracker = class {
10119
10423
  const task = spec.parse(await this.options.http.json(spec.poll(record.gatewayId), {
10120
10424
  timeoutMs: 3e4,
10121
10425
  ...signal === void 0 ? {} : { signal }
10122
- }));
10426
+ }), this.now());
10123
10427
  if (task === void 0) throw new MediaError("The VibeDev gateway returned an unreadable task.", "GATEWAY_BAD_RESPONSE");
10124
10428
  const money = this.moneyOf(record, task);
10125
10429
  if (task.state !== "completed") return this.update(id, money);
@@ -10662,7 +10966,7 @@ function mediaModelsTool(runtime) {
10662
10966
  function mediaTasksTool(runtime) {
10663
10967
  return defineTool({
10664
10968
  name: "media_tasks",
10665
- description: "Show the video and audio generation tasks dsh-vibedev is following or has finished (newest first): status, progress, saved files and charges. Background jobs already report completion, so use this only when asked, after a restart, or to look up an earlier result.",
10969
+ description: "Show the video and audio generation tasks dsh-vibedev is following or has finished (newest first): status, progress (stage, queue position and time left when the gateway reports them), saved files and charges. Background jobs already report completion, so use this only when asked, after a restart, or to look up an earlier result.",
10666
10970
  parameters: {
10667
10971
  task_id: {
10668
10972
  type: "string",
@@ -10954,6 +11258,7 @@ const inject = ["tools"];
10954
11258
  const Config = Schema.object({
10955
11259
  displayName: Schema.string().default("VibeDev"),
10956
11260
  relayDisplayName: Schema.string().default("中转"),
11261
+ claudeCacheTtl: Schema.union(CLAUDE_CACHE_TTLS.map((value) => Schema.const(value))).default("default").volatile(),
10957
11262
  preferredModels: Schema.array(Schema.string()).default([]),
10958
11263
  openBrowserOnSignIn: Schema.boolean().default(true),
10959
11264
  catalogRefreshMinutes: Schema.number().min(1).max(1440).default(30),
@@ -10974,6 +11279,7 @@ const Config = Schema.object({
10974
11279
  "zh-CN": {
10975
11280
  displayName: "模型选择器里显示的名称",
10976
11281
  relayDisplayName: "中转模型分组名称",
11282
+ claudeCacheTtl: "Claude 提示词缓存保留时间(默认 / 5分钟 / 1小时)",
10977
11283
  preferredModels: "排在最前的 VibeDev 模型(按顺序,留空按网关顺序)",
10978
11284
  openBrowserOnSignIn: "登录时自动打开系统浏览器",
10979
11285
  catalogRefreshMinutes: "模型目录定时刷新间隔(分钟;没人打开余额卡片、账号菜单或设置时的兜底)",
@@ -10994,6 +11300,7 @@ const Config = Schema.object({
10994
11300
  "en-US": {
10995
11301
  displayName: "Name the model pickers show",
10996
11302
  relayDisplayName: "Relay model group name",
11303
+ claudeCacheTtl: "Claude prompt cache lifetime (default / 5 minutes / 1 hour)",
10997
11304
  preferredModels: "VibeDev models listed first, in this order (empty: the gateway's order)",
10998
11305
  openBrowserOnSignIn: "Open the system browser when signing in",
10999
11306
  catalogRefreshMinutes: "Model catalog refresh interval in minutes (the fallback when nobody opens the balance card, the account menu or Settings)",
@@ -11112,6 +11419,7 @@ function apply(ctx, config) {
11112
11419
  origin,
11113
11420
  displayName: config.displayName,
11114
11421
  relayDisplayName: config.relayDisplayName,
11422
+ claudeCacheTtl: () => config.claudeCacheTtl.get(),
11115
11423
  resolveCredential: () => chain.resolve(),
11116
11424
  rejectCredential: (credential) => chain.reject(credential),
11117
11425
  deviceId: () => storage.deviceId(),