@vibedev-si/dsh-vibedev 0.3.10 → 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;
@@ -5122,7 +5122,7 @@ const FIRST_LOOK_MS = 1e3;
5122
5122
  const LOOK_STEP_MAX_MS = 1e4;
5123
5123
  /** Uploads this library starts for one file: its own, and one more after another upload of the file ended without it. */
5124
5124
  const OWN_UPLOADS = 2;
5125
- 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;
5126
5126
  const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5127
5127
  const httpUrl$1 = (value) => {
5128
5128
  const url = text$5(value);
@@ -5135,7 +5135,7 @@ const httpUrl$1 = (value) => {
5135
5135
  * @returns the asset facts, or undefined when the answer names no usable URL.
5136
5136
  */
5137
5137
  function parseAsset(body, fallbackType) {
5138
- const raw = record$4(body);
5138
+ const raw = record$5(body);
5139
5139
  const assetId = text$5(raw?.asset_id);
5140
5140
  const referenceUrl = httpUrl$1(raw?.reference_url);
5141
5141
  if (raw === void 0 || assetId === void 0 || referenceUrl === void 0) return void 0;
@@ -5285,7 +5285,7 @@ var MediaLibrary = class {
5285
5285
  }
5286
5286
  /** `POST /uploads`: the asset when the library already holds the file, else the upload it hands out. */
5287
5287
  async declare(media, purpose, sha256, signal) {
5288
- 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", {
5289
5289
  method: "POST",
5290
5290
  json: {
5291
5291
  filename: media.name,
@@ -5322,7 +5322,7 @@ var MediaLibrary = class {
5322
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);
5323
5323
  if (uploadUrl === void 0) throw new MediaError(`The VibeDev gateway returned no upload address for "${media.source}".`, "ASSET_UPLOAD_URL_MISSING");
5324
5324
  const headers = { "content-type": media.mime };
5325
- 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;
5326
5326
  await this.http.send(uploadUrl, {
5327
5327
  method: "PUT",
5328
5328
  body: media.data,
@@ -5384,7 +5384,7 @@ const AUDIO_GENERATION_KINDS = [
5384
5384
  "speech",
5385
5385
  "transcription"
5386
5386
  ];
5387
- 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;
5388
5388
  const text$4 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5389
5389
  const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
5390
5390
  const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
@@ -5432,15 +5432,15 @@ function parseModes(raw) {
5432
5432
  const version = field(raw, "modes_schema_version");
5433
5433
  const modesRaw = raw.modes;
5434
5434
  if (version === void 0 && modesRaw === void 0) return {};
5435
- 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 };
5436
5436
  const modes = {};
5437
5437
  for (const mode of VIDEO_MODES) {
5438
- const entry = record$3(modesRaw[mode]);
5438
+ const entry = record$4(modesRaw[mode]);
5439
5439
  if (entry === void 0) continue;
5440
- const inputsRaw = record$3(entry.inputs) ?? {};
5440
+ const inputsRaw = record$4(entry.inputs) ?? {};
5441
5441
  const inputs = {};
5442
5442
  for (const [key, limitRaw] of Object.entries(inputsRaw)) {
5443
- const limit = record$3(limitRaw);
5443
+ const limit = record$4(limitRaw);
5444
5444
  const min = count(limit?.min);
5445
5445
  const max = count(limit?.max);
5446
5446
  if (!VIDEO_INPUTS.includes(key) || limit === void 0 || min === void 0 || max === void 0 || min > max) return { unreadableModesVersion: 1 };
@@ -5549,7 +5549,7 @@ function parseVideoCapabilities(raw) {
5549
5549
  if (Array.isArray(combinationsRaw)) {
5550
5550
  const combinations = [];
5551
5551
  for (const item of combinationsRaw) {
5552
- const entry = record$3(item);
5552
+ const entry = record$4(item);
5553
5553
  if (entry === void 0) continue;
5554
5554
  const duration = positive(field(entry, "duration_seconds"));
5555
5555
  const ratio = text$4(entry.ratio);
@@ -5643,12 +5643,12 @@ const PRICE_UNITS = [
5643
5643
  ];
5644
5644
  /** The audio block: `entry.audio`, else `capabilities.audio`, else the fields flattened into `capabilities`. */
5645
5645
  function audioBlock(entry, capabilities) {
5646
- const own = record$3(entry.audio) ?? record$3(capabilities.audio);
5646
+ const own = record$4(entry.audio) ?? record$4(capabilities.audio);
5647
5647
  if (own !== void 0) return own;
5648
5648
  return field(capabilities, "generation_kind") !== void 0 ? capabilities : void 0;
5649
5649
  }
5650
5650
  function stringChoices(raw) {
5651
- const choices = record$3(raw);
5651
+ const choices = record$4(raw);
5652
5652
  if (choices === void 0) return void 0;
5653
5653
  const out = {};
5654
5654
  for (const [name, values] of Object.entries(choices)) {
@@ -5721,10 +5721,10 @@ function seedReferenceLimits(raw) {
5721
5721
  function parseOutputFormats(raw) {
5722
5722
  const declared = field(raw, "output_formats");
5723
5723
  if (!Array.isArray(declared)) return void 0;
5724
- 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"));
5725
5725
  const formats = [];
5726
5726
  for (const item of declared) {
5727
- const entry = record$3(item);
5727
+ const entry = record$4(item);
5728
5728
  const format = (entry === void 0 ? text$4(item) : text$4(entry.format))?.toLowerCase();
5729
5729
  if (format === void 0 || formats.some((known) => known.format === format)) continue;
5730
5730
  const sampleRates = (entry === void 0 ? void 0 : field(entry, "sample_rates")) ?? rates?.[format];
@@ -5755,7 +5755,7 @@ function parseAudioCapabilities(raw) {
5755
5755
  "reference_image_input",
5756
5756
  "speaker_input"
5757
5757
  ].some((name) => bool(raw, name) !== void 0);
5758
- 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);
5759
5759
  const outputFormats = parseOutputFormats(raw);
5760
5760
  const defaultFormat = text$4(field(raw, "default_format"))?.toLowerCase();
5761
5761
  const choices = stringChoices(field(raw, "choices") ?? field(raw, "field_options"));
@@ -5797,12 +5797,12 @@ function parseAudioCapabilities(raw) {
5797
5797
  return result;
5798
5798
  }
5799
5799
  function parsePricing(value, audioUnit) {
5800
- const raw = record$3(value);
5800
+ const raw = record$4(value);
5801
5801
  if (raw === void 0) return void 0;
5802
5802
  const unit = (item) => PRICE_UNITS.includes(item) ? item : item === void 0 && audioUnit !== void 0 ? audioUnit : void 0;
5803
5803
  const tiers = [];
5804
5804
  if (Array.isArray(raw.tiers)) for (const entry of raw.tiers) {
5805
- const tier = record$3(entry);
5805
+ const tier = record$4(entry);
5806
5806
  const name = text$4(tier?.tier);
5807
5807
  const tierUnit = unit(tier?.unit);
5808
5808
  const amount = typeof tier?.amount === "number" && Number.isFinite(tier.amount) && tier.amount >= 0 ? tier.amount : void 0;
@@ -5812,7 +5812,7 @@ function parsePricing(value, audioUnit) {
5812
5812
  amount
5813
5813
  });
5814
5814
  }
5815
- const fallback = record$3(raw.default);
5815
+ const fallback = record$4(raw.default);
5816
5816
  const fallbackUnit = unit(fallback?.unit);
5817
5817
  const fallbackAmount = typeof fallback?.amount === "number" && Number.isFinite(fallback.amount) && fallback.amount >= 0 ? fallback.amount : void 0;
5818
5818
  if (tiers.length === 0 && (fallbackUnit === void 0 || fallbackAmount === void 0)) return void 0;
@@ -5840,7 +5840,7 @@ function condition(raw, snake) {
5840
5840
  */
5841
5841
  function parseVideoPricing(value) {
5842
5842
  if (value === void 0 || value === null) return {};
5843
- const raw = record$3(value);
5843
+ const raw = record$4(value);
5844
5844
  if (raw === void 0) return { videoPricingIssue: "invalid" };
5845
5845
  if (field(raw, "schema_version") !== 1) return { videoPricingIssue: "unknown-schema" };
5846
5846
  const invalid = { videoPricingIssue: "invalid" };
@@ -5850,7 +5850,7 @@ function parseVideoPricing(value) {
5850
5850
  if (!Array.isArray(rulesRaw) || rulesRaw.length === 0) return invalid;
5851
5851
  const rules = [];
5852
5852
  for (const item of rulesRaw) {
5853
- const entry = record$3(item);
5853
+ const entry = record$4(item);
5854
5854
  if (entry === void 0) return invalid;
5855
5855
  const resolution = text$4(field(entry, "resolution"));
5856
5856
  const perMillion = price(field(entry, "price_per_million_tokens"));
@@ -5902,15 +5902,15 @@ function kindOf(entry, capabilities, audio) {
5902
5902
  * @returns the media models, in catalog order.
5903
5903
  */
5904
5904
  function parseMediaCatalog(body) {
5905
- const entries = Array.isArray(body) ? body : record$3(body)?.data;
5905
+ const entries = Array.isArray(body) ? body : record$4(body)?.data;
5906
5906
  if (!Array.isArray(entries)) return [];
5907
5907
  const models = [];
5908
5908
  const seen = /* @__PURE__ */ new Set();
5909
5909
  for (const item of entries) {
5910
- const entry = record$3(item);
5910
+ const entry = record$4(item);
5911
5911
  const id = text$4(entry?.id);
5912
5912
  if (entry === void 0 || id === void 0 || seen.has(id)) continue;
5913
- const capabilities = record$3(entry.capabilities) ?? {};
5913
+ const capabilities = record$4(entry.capabilities) ?? {};
5914
5914
  const audioRaw = audioBlock(entry, capabilities);
5915
5915
  const audio = audioRaw === void 0 ? void 0 : parseAudioCapabilities(audioRaw);
5916
5916
  const kind = kindOf(entry, capabilities, audio);
@@ -5926,7 +5926,7 @@ function parseMediaCatalog(body) {
5926
5926
  let video;
5927
5927
  if (kind === "video") video = {
5928
5928
  ...parseVideoCapabilities(capabilities),
5929
- ...parseVideoCapabilities(record$3(entry.video) ?? {})
5929
+ ...parseVideoCapabilities(record$4(entry.video) ?? {})
5930
5930
  };
5931
5931
  const imageSizes = kind === "image" ? optionList(field(capabilities, "image_sizes")) : void 0;
5932
5932
  const imageRatios = kind === "image" ? optionList(field(capabilities, "image_ratios")) : void 0;
@@ -7775,6 +7775,381 @@ function audioFormOf(model) {
7775
7775
  };
7776
7776
  }
7777
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
7778
8153
  //#region src/tools/common.ts
7779
8154
  /** How a media input may be given, for parameter descriptions. */
7780
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)";
@@ -7823,7 +8198,10 @@ function describeTask(runtime, exec, record) {
7823
8198
  }
7824
8199
  case "failed": return `${what} task ${record.id} failed${record.error === void 0 ? "" : ` (${record.error.code}: ${record.error.message})`}.${moneyLine(record)}`;
7825
8200
  case "lost": return `${what} task ${record.id} is no longer followed: ${record.error?.message ?? "unknown reason"}`;
7826
- 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
+ }
7827
8205
  }
7828
8206
  }
7829
8207
  /**
@@ -8944,6 +9322,16 @@ function videoGenerateTool(runtime) {
8944
9322
  * {@link MediaHostService.result} (the files to play or download).
8945
9323
  * @module dsh-vibedev/service
8946
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
+ }
8947
9335
  const view = (record) => ({
8948
9336
  id: record.id,
8949
9337
  kind: record.kind,
@@ -8951,6 +9339,7 @@ const view = (record) => ({
8951
9339
  model: record.model,
8952
9340
  status: record.status,
8953
9341
  ...record.progress === void 0 ? {} : { progress: record.progress },
9342
+ ...progressView(record),
8954
9343
  ...record.outputs === void 0 ? {} : { outputs: record.outputs.map(({ index: _index, bytes: _bytes, ...output }) => ({ ...output })) },
8955
9344
  ...record.error === void 0 ? {} : { error: { ...record.error } },
8956
9345
  ...record.estimatedCny === void 0 ? {} : { estimatedCny: record.estimatedCny },
@@ -9173,189 +9562,24 @@ var MediaHostService = class {
9173
9562
  }
9174
9563
  };
9175
9564
  //#endregion
9176
- //#region src/tasks/store.ts
9177
- /**
9178
- * The durable list of video and audio tasks, one file per task under
9179
- * `<state dir>/tasks/`, so harness processes sharing a home never overwrite
9180
- * each other's tasks. A task is recorded before it is submitted, under the id
9181
- * that doubles as its `Idempotency-Key`: a submission cut short is resent under
9182
- * the same key (the gateway returns the original task instead of creating a
9183
- * second one), and a task still running when the host restarts is followed to
9184
- * the end. A claim file names the process following a task, so two processes
9185
- * never poll and download the same one.
9186
- * @module dsh-vibedev/tasks/store
9187
- */
9188
- /** Terminal tasks kept for listings; live ones are always kept. */
9189
- const KEEP_FINISHED = 100;
9190
- const TERMINAL = /* @__PURE__ */ new Set([
9191
- "completed",
9192
- "failed",
9193
- "lost"
9194
- ]);
9195
- const SAFE_ID = /^[\w-]{1,80}$/;
9565
+ //#region src/tasks/remote.ts
9196
9566
  /**
9197
- * Whether a task has ended.
9198
- * @param record - the task.
9199
- * @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
9200
9582
  */
9201
- function isFinished(record) {
9202
- return TERMINAL.has(record.status);
9203
- }
9204
- function parse(text) {
9205
- try {
9206
- const value = JSON.parse(text);
9207
- return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.status === "string" ? value : void 0;
9208
- } catch {
9209
- return;
9210
- }
9211
- }
9212
- /** Task records under `<state dir>/tasks/`. */
9213
- var TaskStore = class {
9214
- directory;
9215
- now;
9216
- chains = /* @__PURE__ */ new Map();
9217
- /**
9218
- * @param directory - the plugin state directory.
9219
- * @param now - clock.
9220
- */
9221
- constructor(directory, now = Date.now) {
9222
- this.directory = directory;
9223
- this.now = now;
9224
- }
9225
- get dir() {
9226
- return join(this.directory, "tasks");
9227
- }
9228
- file(id, suffix = "json") {
9229
- if (!SAFE_ID.test(id)) throw new Error(`invalid task id ${JSON.stringify(id)}`);
9230
- return join(this.dir, `${id}.${suffix}`);
9231
- }
9232
- /** Run one change to a task after the previous change to it in this process. */
9233
- serial(id, run) {
9234
- const next = (this.chains.get(id) ?? Promise.resolve()).then(run, run);
9235
- const settled = next.catch(() => void 0);
9236
- this.chains.set(id, settled);
9237
- settled.then(() => {
9238
- if (this.chains.get(id) === settled) this.chains.delete(id);
9239
- });
9240
- return next;
9241
- }
9242
- /** All tasks, newest first, as they are on disk now (other processes' tasks included). */
9243
- async list() {
9244
- const names = await readdir(this.dir).catch(() => []);
9245
- 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);
9246
- }
9247
- /**
9248
- * One task.
9249
- * @param id - its local id.
9250
- * @returns the task, or undefined.
9251
- */
9252
- async get(id) {
9253
- return readFile(this.file(id), "utf8").then(parse, () => void 0);
9254
- }
9255
- /**
9256
- * Record a new task.
9257
- * @param record - the task.
9258
- * @returns the stored task.
9259
- */
9260
- add(record) {
9261
- return this.serial(record.id, async () => {
9262
- await writeFileAtomic(this.file(record.id), new TextEncoder().encode(JSON.stringify(record, null, 2)));
9263
- await this.prune().catch(() => void 0);
9264
- return record;
9265
- });
9266
- }
9267
- /**
9268
- * Change a task.
9269
- * @param id - its local id.
9270
- * @param patch - the fields to replace.
9271
- * @returns the updated task, or undefined when it is unknown.
9272
- */
9273
- update(id, patch) {
9274
- return this.serial(id, async () => {
9275
- const current = await this.get(id);
9276
- if (current === void 0) return void 0;
9277
- const next = {
9278
- ...current,
9279
- ...patch,
9280
- updatedAt: this.now()
9281
- };
9282
- await writeFileAtomic(this.file(id), new TextEncoder().encode(JSON.stringify(next, null, 2)));
9283
- return next;
9284
- });
9285
- }
9286
- /**
9287
- * Forget a task, such as a submission the gateway refused outright.
9288
- * @param id - its local id.
9289
- */
9290
- remove(id) {
9291
- return this.serial(id, async () => {
9292
- await rm(this.file(id), { force: true });
9293
- await rm(this.file(id, "claim"), { force: true });
9294
- });
9295
- }
9296
- /**
9297
- * Claim the right to follow a task: free, already ours, or held by a process
9298
- * that stopped renewing it for `staleMs`.
9299
- * @param id - the task.
9300
- * @param holder - this process's claim id.
9301
- * @param staleMs - how old an unrenewed claim may be before it is taken over.
9302
- * @returns whether this process now holds the claim.
9303
- */
9304
- async claim(id, holder, staleMs) {
9305
- const path = this.file(id, "claim");
9306
- for (let attempt = 0; attempt < 2; attempt++) {
9307
- try {
9308
- const handle = await open(path, "wx");
9309
- await handle.writeFile(JSON.stringify({
9310
- holder,
9311
- at: this.now()
9312
- }));
9313
- await handle.close();
9314
- return true;
9315
- } catch (error) {
9316
- if (error.code !== "EEXIST") return false;
9317
- }
9318
- const current = await readFile(path, "utf8").then((text) => JSON.parse(text), () => void 0);
9319
- if (current?.holder === holder) {
9320
- await this.renewClaim(id, holder);
9321
- return true;
9322
- }
9323
- const at = typeof current?.at === "number" ? current.at : 0;
9324
- if (this.now() - at < staleMs) return false;
9325
- await rm(path, { force: true });
9326
- }
9327
- return false;
9328
- }
9329
- /**
9330
- * Keep a claim alive.
9331
- * @param id - the task.
9332
- * @param holder - this process's claim id.
9333
- */
9334
- async renewClaim(id, holder) {
9335
- await writeFileAtomic(this.file(id, "claim"), new TextEncoder().encode(JSON.stringify({
9336
- holder,
9337
- at: this.now()
9338
- })));
9339
- }
9340
- /**
9341
- * Give up a claim this process holds.
9342
- * @param id - the task.
9343
- * @param holder - this process's claim id.
9344
- */
9345
- async release(id, holder) {
9346
- const path = this.file(id, "claim");
9347
- if ((await readFile(path, "utf8").then((text) => JSON.parse(text), () => void 0))?.holder === holder) await rm(path, { force: true });
9348
- }
9349
- async prune() {
9350
- const finished = (await this.list()).filter(isFinished);
9351
- for (const record of finished.slice(KEEP_FINISHED)) {
9352
- await rm(this.file(record.id), { force: true });
9353
- await rm(this.file(record.id, "claim"), { force: true });
9354
- }
9355
- }
9356
- };
9357
- //#endregion
9358
- //#region src/tasks/remote.ts
9359
9583
  const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
9360
9584
  const text$1 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
9361
9585
  const httpUrl = (value) => {
@@ -9480,9 +9704,10 @@ function receipt(raw) {
9480
9704
  /**
9481
9705
  * Read a video task.
9482
9706
  * @param body - the parsed answer.
9707
+ * @param receivedAt - when this machine received it (epoch ms), the anchor of its progress times.
9483
9708
  * @returns the task, or undefined when the answer names no task id.
9484
9709
  */
9485
- function parseVideoTask(body) {
9710
+ function parseVideoTask(body, receivedAt = Date.now()) {
9486
9711
  const raw = record$1(body);
9487
9712
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
9488
9713
  if (raw === void 0 || id === void 0) return void 0;
@@ -9508,6 +9733,7 @@ function parseVideoTask(body) {
9508
9733
  ...error === void 0 ? {} : { error },
9509
9734
  ...receipt(raw),
9510
9735
  ...settlementOf(raw, status),
9736
+ ...parseProgress(raw, receivedAt),
9511
9737
  outputs: state === "completed" ? [{
9512
9738
  index: 0,
9513
9739
  ...url === void 0 ? {} : { url },
@@ -9519,9 +9745,10 @@ function parseVideoTask(body) {
9519
9745
  /**
9520
9746
  * Read a music or podcast task.
9521
9747
  * @param body - the parsed answer.
9748
+ * @param receivedAt - when this machine received it (epoch ms), the anchor of its progress times.
9522
9749
  * @returns the task, or undefined when the answer names no task id.
9523
9750
  */
9524
- function parseAudioTask(body) {
9751
+ function parseAudioTask(body, receivedAt = Date.now()) {
9525
9752
  const raw = record$1(body);
9526
9753
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
9527
9754
  if (raw === void 0 || id === void 0) return void 0;
@@ -9563,6 +9790,7 @@ function parseAudioTask(body) {
9563
9790
  ...receipt(raw),
9564
9791
  ...settlementOf(raw, status),
9565
9792
  ...billedLengths(raw),
9793
+ ...parseProgress(raw, receivedAt),
9566
9794
  outputs: state === "completed" ? outputs : []
9567
9795
  };
9568
9796
  }
@@ -9796,7 +10024,7 @@ var TaskTracker = class {
9796
10024
  idempotencyKey: draft.id,
9797
10025
  timeoutMs: SUBMIT_TIMEOUT_MS,
9798
10026
  ...signal === void 0 ? {} : { signal }
9799
- }));
10027
+ }), this.now());
9800
10028
  if (task === void 0) throw new MediaError("The VibeDev gateway accepted the request but returned no task id.", "GATEWAY_BAD_RESPONSE");
9801
10029
  } catch (error) {
9802
10030
  if (signal?.aborted === true) {
@@ -9919,8 +10147,14 @@ var TaskTracker = class {
9919
10147
  }
9920
10148
  async finish(id, patch) {
9921
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
+ };
9922
10155
  const record = await this.update(id, {
9923
10156
  ...patch,
10157
+ ...progressFacts,
9924
10158
  progress: void 0,
9925
10159
  finishedAt: this.now()
9926
10160
  });
@@ -9988,16 +10222,16 @@ var TaskTracker = class {
9988
10222
  idempotencyKey: record.id,
9989
10223
  timeoutMs: SUBMIT_TIMEOUT_MS,
9990
10224
  signal: this.signal
9991
- }));
10225
+ }), this.now());
9992
10226
  } else task = spec.parse(await this.options.http.json(spec.poll(record.gatewayId), {
9993
10227
  timeoutMs: 3e4,
9994
10228
  signal: this.signal
9995
- }));
10229
+ }), this.now());
9996
10230
  if (task === void 0) throw new MediaError("The VibeDev gateway returned an unreadable task.", "GATEWAY_BAD_RESPONSE");
9997
10231
  record = await this.apply(record, task);
9998
10232
  failures = 0;
9999
10233
  if (isFinished(record)) return record;
10000
- await this.sleep(spec.interval(age), this.signal);
10234
+ await this.sleep(task.nextPollAfterSeconds === void 0 ? spec.interval(age) : task.nextPollAfterSeconds * 1e3, this.signal);
10001
10235
  } catch (error) {
10002
10236
  if (this.signal.aborted) break;
10003
10237
  failures++;
@@ -10105,6 +10339,17 @@ var TaskTracker = class {
10105
10339
  ...billing
10106
10340
  };
10107
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
+ }
10108
10353
  /** Record what the gateway says about a task; save the outputs of a finished one. */
10109
10354
  async apply(record, task) {
10110
10355
  const money = this.moneyOf(record, task);
@@ -10112,7 +10357,8 @@ var TaskTracker = class {
10112
10357
  gatewayId: task.id,
10113
10358
  status: "pending",
10114
10359
  progress: progressLine(task),
10115
- ...money
10360
+ ...money,
10361
+ ...this.progressFactsOf(record, task)
10116
10362
  });
10117
10363
  if (task.state === "failed") return this.finish(record.id, {
10118
10364
  gatewayId: task.id,
@@ -10123,8 +10369,9 @@ var TaskTracker = class {
10123
10369
  const current = await this.update(record.id, {
10124
10370
  gatewayId: task.id,
10125
10371
  status: "pending",
10126
- progress: "saving the result",
10127
- ...money
10372
+ progress: SAVING_PROGRESS,
10373
+ ...money,
10374
+ ...this.progressFactsOf(record, task)
10128
10375
  });
10129
10376
  const { outputs, missing } = await this.saveOutputs(current, task);
10130
10377
  if (missing > 0) {
@@ -10137,7 +10384,7 @@ var TaskTracker = class {
10137
10384
  const settled = await this.options.http.json(SPECS[record.kind].poll(task.id), {
10138
10385
  timeoutMs: 15e3,
10139
10386
  signal: this.signal
10140
- }).then((body) => SPECS[record.kind].parse(body), () => void 0);
10387
+ }).then((body) => SPECS[record.kind].parse(body, this.now()), () => void 0);
10141
10388
  if (settled !== void 0) charged = {
10142
10389
  ...money,
10143
10390
  ...this.moneyOf(current, settled)
@@ -10176,7 +10423,7 @@ var TaskTracker = class {
10176
10423
  const task = spec.parse(await this.options.http.json(spec.poll(record.gatewayId), {
10177
10424
  timeoutMs: 3e4,
10178
10425
  ...signal === void 0 ? {} : { signal }
10179
- }));
10426
+ }), this.now());
10180
10427
  if (task === void 0) throw new MediaError("The VibeDev gateway returned an unreadable task.", "GATEWAY_BAD_RESPONSE");
10181
10428
  const money = this.moneyOf(record, task);
10182
10429
  if (task.state !== "completed") return this.update(id, money);
@@ -10719,7 +10966,7 @@ function mediaModelsTool(runtime) {
10719
10966
  function mediaTasksTool(runtime) {
10720
10967
  return defineTool({
10721
10968
  name: "media_tasks",
10722
- 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.",
10723
10970
  parameters: {
10724
10971
  task_id: {
10725
10972
  type: "string",