dsh-lowtide 0.2.1 → 0.2.3

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
@@ -5,7 +5,7 @@ import { execFile } from "node:child_process";
5
5
  import { homedir } from "node:os";
6
6
  import { installModelSelection } from "@deepseek-ai/dsh-agent";
7
7
  import { ReasoningEffortId, createUserMessage } from "@deepseek-ai/dsh-llm";
8
- import { SessionId } from "@deepseek-ai/dsh-session";
8
+ import { SessionId, SessionLogOffset } from "@deepseek-ai/dsh-session";
9
9
  //#region ../core/src/windows.ts
10
10
  const DEFAULT_MULTIPLIER = {
11
11
  peak: 2,
@@ -241,9 +241,11 @@ function windowsInTz(windows, tz, probe = /* @__PURE__ */ new Date()) {
241
241
  //#endregion
242
242
  //#region ../core/src/pricing.ts
243
243
  /**
244
- * Pricing: official DeepSeek peak/valley table (effective 2026-08-17, sourced
245
- * from the official announcement of 2026-08-13; see PLAN §0.2), overrides,
246
- * and usage→¥ conversion. Pure functions.
244
+ * Pricing: official DeepSeek peak/valley table (effective 2026-09-10 — the
245
+ * DeepSeek-V4.1-Flash release, which renamed the flash model to
246
+ * `deepseek-flash` and cut its prices; sourced from api-docs.deepseek.com),
247
+ * overrides, legacy-id aliases, dated billing routes, and usage→¥ conversion.
248
+ * Pure functions.
247
249
  *
248
250
  * Usage semantics (verified against rc.7 @deepseek-ai/dsh-llm-deepseek
249
251
  * mapUsage, lib/index.js:190-199):
@@ -253,20 +255,23 @@ function windowsInTz(windows, tz, probe = /* @__PURE__ */ new Date()) {
253
255
  * - The rc.7 harness TokenUsage reports no cacheWriteTokens field.
254
256
  *
255
257
  * Peak = Beijing 09:00–12:00, 14:00–18:00 weekdays only; weekends (Sat/Sun)
256
- * are always off-peak (announced 2026-08-22, effective 2026-08-23).
258
+ * are always off-peak (announced 2026-08-22, effective 2026-08-23; unchanged
259
+ * by the 2026-09-10 price cut). Off-peak is exactly half of peak.
257
260
  * All amounts are CNY per 1M tokens.
258
261
  */
262
+ /** Canonical id of the current official flash model (V4.1-Flash, multimodal). */
263
+ const FLASH_MODEL_ID = "deepseek-flash";
259
264
  const OFFICIAL_PRICES = {
260
- "deepseek-v4-flash": {
265
+ [FLASH_MODEL_ID]: {
261
266
  peak: {
262
- input: 3,
263
- inputCached: .1,
264
- output: 9
267
+ input: 2,
268
+ inputCached: .04,
269
+ output: 8
265
270
  },
266
271
  off: {
267
- input: 1.5,
268
- inputCached: .05,
269
- output: 4.5
272
+ input: 1,
273
+ inputCached: .02,
274
+ output: 4
270
275
  }
271
276
  },
272
277
  "deepseek-v4-pro": {
@@ -280,20 +285,40 @@ const OFFICIAL_PRICES = {
280
285
  inputCached: .15,
281
286
  output: 13.5
282
287
  }
283
- },
284
- "deepseek-v4-flash-vision-exp": {
285
- peak: {
286
- input: 3,
287
- inputCached: .1,
288
- output: 9
289
- },
290
- off: {
291
- input: 1.5,
292
- inputCached: .05,
293
- output: 4.5
294
- }
295
288
  }
296
289
  };
290
+ /**
291
+ * Legacy model ids that DeepSeek still accepts but has retired: requests are
292
+ * served by DeepSeek-V4.1-Flash and billed at the Flash price (official docs,
293
+ * 2026-09-10). Mapping them keeps old persisted tasks and existing Harness
294
+ * catalogs priced instead of silently falling back to "价格未知".
295
+ */
296
+ const PRICE_ALIASES = {
297
+ "deepseek-v4-flash": FLASH_MODEL_ID,
298
+ "deepseek-v4-flash-vision-exp": FLASH_MODEL_ID
299
+ };
300
+ const PRICE_ROUTING = [{
301
+ model: "deepseek-v4-pro",
302
+ from: "2026-09-14T04:00:00.000Z",
303
+ to: FLASH_MODEL_ID,
304
+ note: "DeepSeek V4 Pro 于北京时间 2026-09-14 12:00 起下线,请求按 V4.1-Flash 计费"
305
+ }];
306
+ /**
307
+ * Resolve the model id that actually gets billed at `when`: legacy aliases are
308
+ * mapped to their canonical entry first, then dated routes apply (V4 Pro →
309
+ * Flash after its retirement instant).
310
+ */
311
+ function resolvePriceModel(model, when = /* @__PURE__ */ new Date()) {
312
+ const aliased = PRICE_ALIASES[model] ?? model;
313
+ let resolved = aliased;
314
+ for (const route of PRICE_ROUTING) if ((route.model === model || route.model === aliased) && when.getTime() >= Date.parse(route.from)) resolved = route.to;
315
+ return resolved;
316
+ }
317
+ /** The active routing notice for a model at `when` (null when none applies). */
318
+ function priceRouteNotice(model, when = /* @__PURE__ */ new Date()) {
319
+ for (const route of PRICE_ROUTING) if (route.model === model && when.getTime() >= Date.parse(route.from)) return route.note;
320
+ return null;
321
+ }
297
322
  /** Official peak windows (Beijing-defined calendar; tz fixed Asia/Shanghai).
298
323
  * days: [1,2,3,4,5] = weekdays only; weekends are always off-peak. */
299
324
  const OFFICIAL_PEAK_WINDOWS = [{
@@ -326,18 +351,25 @@ const OFFICIAL_PEAK_WINDOWS = [{
326
351
  ]
327
352
  }];
328
353
  /** Fallback tier for models without an explicit entry (keeps the UI alive). */
329
- const FALLBACK_TIER = OFFICIAL_PRICES["deepseek-v4-flash"];
354
+ const FALLBACK_TIER = OFFICIAL_PRICES[FLASH_MODEL_ID];
330
355
  /**
331
- * Resolve a model's price tier. Unknown models fall back to the flash tier
332
- * instead of throwing — the UI can flag `hasPriceEntry === false` and show a
333
- * "按默认价估算" hint rather than going dark.
356
+ * Resolve a model's price tier at `when`. Resolution order:
357
+ * 1. billing id from `resolvePriceModel` (alias + dated route),
358
+ * 2. a user override on that id, then on the raw id (legacy overrides keep
359
+ * working after a rename),
360
+ * 3. the official table, then the flash fallback.
361
+ * Unknown models fall back to the flash tier instead of throwing — the UI can
362
+ * flag `hasPriceEntry === false` and show a "按默认价估算" hint rather than
363
+ * going dark.
334
364
  */
335
- function tierFor(model, prices = OFFICIAL_PRICES) {
336
- return prices[model] ?? OFFICIAL_PRICES[model] ?? FALLBACK_TIER;
365
+ function tierFor(model, prices = OFFICIAL_PRICES, when = /* @__PURE__ */ new Date()) {
366
+ const billed = resolvePriceModel(model, when);
367
+ return prices[billed] ?? prices[model] ?? OFFICIAL_PRICES[billed] ?? FALLBACK_TIER;
337
368
  }
338
- /** Whether the model has an explicit price entry (override or official). */
339
- function hasPriceEntry(model, prices = OFFICIAL_PRICES) {
340
- return model in prices || model in OFFICIAL_PRICES;
369
+ /** Whether the model has an explicit price entry (override, alias or official). */
370
+ function hasPriceEntry(model, prices = OFFICIAL_PRICES, when = /* @__PURE__ */ new Date()) {
371
+ const billed = resolvePriceModel(model, when);
372
+ return billed in prices || model in prices || billed in OFFICIAL_PRICES;
341
373
  }
342
374
  /** Cost in ¥ for a usage at a known tier row. */
343
375
  function costAtRow(usage, row) {
@@ -367,7 +399,7 @@ function rowForLevel(tier, level, multiplier = 1) {
367
399
  * window multipliers over the off row.
368
400
  */
369
401
  function cost(usage, model, when, windows = OFFICIAL_PEAK_WINDOWS, prices = OFFICIAL_PRICES) {
370
- const tier = tierFor(model, prices);
402
+ const tier = tierFor(model, prices, when);
371
403
  const match = levelAt(when, windows);
372
404
  if (match === null || match.level === "off") return costAtRow(usage, tier.off);
373
405
  if (match.level === "peak") return costAtRow(usage, tier.peak);
@@ -378,9 +410,9 @@ function estimateTokens(prompt, files) {
378
410
  return Math.ceil(prompt.length / 3.5) + files.reduce((sum, file) => sum + Math.ceil(file.size / 4), 0);
379
411
  }
380
412
  /** Peak/off cost estimate for a draft prompt + files, assuming ~5:1 out ratio is not applied (input-only bound). */
381
- function estimate(prompt, files, model, prices = OFFICIAL_PRICES) {
413
+ function estimate(prompt, files, model, prices = OFFICIAL_PRICES, when = /* @__PURE__ */ new Date()) {
382
414
  const tokens = estimateTokens(prompt, files);
383
- const tier = tierFor(model, prices);
415
+ const tier = tierFor(model, prices, when);
384
416
  return {
385
417
  peak: costAtRow({
386
418
  input: tokens,
@@ -396,6 +428,13 @@ function estimate(prompt, files, model, prices = OFFICIAL_PRICES) {
396
428
  }
397
429
  //#endregion
398
430
  //#region ../core/src/model.ts
431
+ /** The reasoning levels every DeepSeek adapter accepts (its wire set). */
432
+ const DEEPSEEK_REASONING_EFFORTS = [
433
+ "off",
434
+ "low",
435
+ "high",
436
+ "max"
437
+ ];
399
438
  const DEFAULT_BATCH_WINDOW = "19:00-23:30";
400
439
  function defaultConfig() {
401
440
  return {
@@ -5359,7 +5398,7 @@ async function intake(input, defaultWorkspace, options) {
5359
5398
  }
5360
5399
  const ref = await gitRef(workspace);
5361
5400
  const sizes = files.map((f) => ({ size: f.size ?? 0 }));
5362
- const modelId = data.model ?? options?.modelId ?? "deepseek-v4-flash";
5401
+ const modelId = data.model ?? options?.modelId ?? "deepseek-flash";
5363
5402
  const prices = mergePrices(options?.prices);
5364
5403
  const priced = estimate(data.prompt, sizes, modelId, prices);
5365
5404
  const priceKnown = hasPriceEntry(modelId, prices);
@@ -5404,7 +5443,7 @@ function mergePrices(overrides) {
5404
5443
  const merged = { ...OFFICIAL_PRICES };
5405
5444
  for (const [model, tier] of Object.entries(overrides)) {
5406
5445
  const t = tier;
5407
- const base = merged[model] ?? OFFICIAL_PRICES["deepseek-v4-flash"];
5446
+ const base = merged[model] ?? FALLBACK_TIER;
5408
5447
  merged[model] = {
5409
5448
  peak: {
5410
5449
  ...base.peak,
@@ -5457,13 +5496,16 @@ async function listAvailableModels(ctx, prices = OFFICIAL_PRICES) {
5457
5496
  });
5458
5497
  if (typeof info?.reasoning?.defaultEffort === "string") defaultReasoningEffort = info.reasoning.defaultEffort;
5459
5498
  } catch {}
5499
+ const notice = priceRouteNotice(m.id);
5460
5500
  return {
5461
5501
  id: m.id,
5462
5502
  name: m.name,
5463
5503
  priceKnown: hasPriceEntry(m.id, prices),
5504
+ priceModel: resolvePriceModel(m.id),
5464
5505
  ...m.inputModalities !== void 0 ? { inputModalities: [...m.inputModalities] } : {},
5465
5506
  ...reasoningEfforts !== void 0 ? { reasoningEfforts } : {},
5466
- ...defaultReasoningEffort !== void 0 ? { defaultReasoningEffort } : {}
5507
+ ...defaultReasoningEffort !== void 0 ? { defaultReasoningEffort } : {},
5508
+ ...notice !== null ? { notice } : {}
5467
5509
  };
5468
5510
  }));
5469
5511
  } catch {
@@ -5637,14 +5679,22 @@ async function executeTurns(ctx, task, nextMessage, timeoutMs, reasoning, resume
5637
5679
  }
5638
5680
  const baseSelection = resolveBatchModel(liveSelection, void 0, task.model, providerOverride);
5639
5681
  let effectiveReasoning = reasoning;
5640
- if (reasoning !== void 0) try {
5641
- const efforts = (await ctx.llm.resolveModelInfo(baseSelection.provider, baseSelection.model))?.reasoning?.efforts;
5642
- const supported = Array.isArray(efforts) ? efforts.map((e) => e.id) : [];
5643
- if (supported.length > 0 && !supported.includes(reasoning)) {
5644
- console.warn(`[lowtide] ${baseSelection.provider}/${baseSelection.model} does not support reasoning "${reasoning}" — falling back to the model default`);
5682
+ if (reasoning !== void 0) {
5683
+ let supported = [];
5684
+ try {
5685
+ const efforts = (await ctx.llm.resolveModelInfo(baseSelection.provider, baseSelection.model))?.reasoning?.efforts;
5686
+ supported = Array.isArray(efforts) ? efforts.map((e) => e.id) : [];
5687
+ } catch {}
5688
+ if (supported.length > 0) {
5689
+ if (!supported.includes(reasoning)) {
5690
+ console.warn(`[lowtide] ${baseSelection.provider}/${baseSelection.model} does not support reasoning "${reasoning}" — falling back to the model default`);
5691
+ effectiveReasoning = void 0;
5692
+ }
5693
+ } else if (baseSelection.provider === "deepseek-official" && !DEEPSEEK_REASONING_EFFORTS.includes(reasoning)) {
5694
+ console.warn(`[lowtide] deepseek-official rejects reasoning "${reasoning}" on the wire — falling back to the model default`);
5645
5695
  effectiveReasoning = void 0;
5646
5696
  }
5647
- } catch {}
5697
+ }
5648
5698
  const selection = resolveBatchModel(liveSelection, effectiveReasoning, task.model, providerOverride);
5649
5699
  const setup = async (agentCtx) => {
5650
5700
  installModelSelection(agentCtx, {
@@ -5686,22 +5736,40 @@ async function executeTurns(ctx, task, nextMessage, timeoutMs, reasoning, resume
5686
5736
  const reason = error instanceof Error ? error.message : String(error);
5687
5737
  console.error(`[lowtide] resume ${resumeSessionId} failed (${reason}) — trying fork-style continuation`);
5688
5738
  const live = ctx.sessions.get(SessionId(resumeSessionId));
5689
- const cut = live === void 0 ? null : forkSeedBoundary(live.events);
5690
- if (live !== void 0 && cut !== null) {
5691
- const seed = live.events.slice(0, cut);
5692
- handle = await ctx.agents.create({
5693
- sessionId: SessionId(`lt-${task.id}-${Date.now()}`),
5739
+ const liveCompat = live;
5740
+ const newSessionApi = typeof liveCompat?.snapshotEvents === "function";
5741
+ const liveEvents = liveCompat === void 0 ? void 0 : newSessionApi ? liveCompat.snapshotEvents() : liveCompat.events;
5742
+ const cut = liveEvents === void 0 ? null : forkSeedBoundary(liveEvents);
5743
+ if (live !== void 0 && liveEvents !== void 0 && cut !== null) {
5744
+ const seed = liveEvents.slice(0, cut);
5745
+ const sessionId = SessionId(`lt-${task.id}-${Date.now()}`);
5746
+ const agentOptions = {
5747
+ provider: selection.provider,
5748
+ model: selection.model
5749
+ };
5750
+ const preset = live.header.agentPreset !== void 0 ? { agentPreset: live.header.agentPreset } : {};
5751
+ handle = await ctx.agents.create(newSessionApi ? {
5752
+ sessionId,
5694
5753
  seed,
5754
+ inheritedEventCount: SessionLogOffset(cut),
5695
5755
  meta: {
5696
5756
  cwd: workspacePath,
5697
5757
  parentSession: SessionId(resumeSessionId),
5698
- seedLength: cut,
5699
- ...live.header.agentPreset !== void 0 ? { agentPreset: live.header.agentPreset } : {}
5758
+ isSeeded: true,
5759
+ ...preset
5700
5760
  },
5701
- agentOptions: {
5702
- provider: selection.provider,
5703
- model: selection.model
5761
+ agentOptions,
5762
+ setup
5763
+ } : {
5764
+ sessionId,
5765
+ seed,
5766
+ meta: {
5767
+ cwd: workspacePath,
5768
+ parentSession: SessionId(resumeSessionId),
5769
+ seedLength: cut,
5770
+ ...preset
5704
5771
  },
5772
+ agentOptions,
5705
5773
  setup
5706
5774
  });
5707
5775
  forked = true;
@@ -6138,16 +6206,18 @@ function priceTableOf(store) {
6138
6206
  return store.config.prices && Object.keys(store.config.prices).length > 0 ? store.config.prices : void 0;
6139
6207
  }
6140
6208
  function costOf(usage, modelId, windows, prices) {
6141
- if (!hasPriceEntry(modelId, prices)) return 0;
6142
- return prices === void 0 ? cost(usage, modelId, /* @__PURE__ */ new Date(), windows) : cost(usage, modelId, /* @__PURE__ */ new Date(), windows, prices);
6209
+ const now = /* @__PURE__ */ new Date();
6210
+ if (!hasPriceEntry(modelId, prices, now)) return 0;
6211
+ return prices === void 0 ? cost(usage, modelId, now, windows) : cost(usage, modelId, now, windows, prices);
6143
6212
  }
6144
6213
  /** Hypothetical peak-hour cost of a usage — the "what you saved" baseline.
6145
- * Only models with a real price entry (official table incl.
6146
- * deepseek-v4-flash-vision-exp, or a user price override) get a baseline;
6147
- * anything else yields 0 so no fake savings are ever reported. */
6214
+ * Only models with a real price entry (the official table — including legacy
6215
+ * aliases such as deepseek-v4-flash-vision-exp — or a user price override)
6216
+ * get a baseline; anything else yields 0 so no fake savings are reported. */
6148
6217
  function peakCostOf(usage, modelId, prices) {
6149
- if (!hasPriceEntry(modelId, prices)) return 0;
6150
- return costAtRow(usage, tierFor(modelId, prices).peak);
6218
+ const now = /* @__PURE__ */ new Date();
6219
+ if (!hasPriceEntry(modelId, prices, now)) return 0;
6220
+ return costAtRow(usage, tierFor(modelId, prices, now).peak);
6151
6221
  }
6152
6222
  /** Retrying a quota/balance rejection is pointless (and costly): the account
6153
6223
  * state cannot change inside one batch. Matches deepseek's 402 payload. */
@@ -6821,9 +6891,31 @@ function listWorkspaceSessions(limitPerWorkspace = 30) {
6821
6891
  const sseClients = /* @__PURE__ */ new Set();
6822
6892
  /** Hard cap on concurrent SSE connections (pentest P7). */
6823
6893
  const MAX_SSE_CLIENTS = 16;
6894
+ /** One warning per failure burst — a throwing payload must not spam the log. */
6895
+ let broadcastWarnedAt = 0;
6896
+ /**
6897
+ * Push the aggregate state to every SSE client.
6898
+ *
6899
+ * `statePayload` reads live services (`ctx.agentDefaultModel`, the scheduler,
6900
+ * the ledger); a throw there used to reject the fire-and-forget promise and
6901
+ * kill the whole heartbeat silently — the browser then kept a half-open stream
6902
+ * and froze the pill. Failures are now contained: the frame is skipped, the
6903
+ * next heartbeat (15s) retries, and the reason is logged once per minute.
6904
+ */
6824
6905
  async function broadcastState(ctx, routes) {
6825
6906
  if (sseClients.size === 0) return;
6826
- const frame = `event: state\ndata: ${JSON.stringify(await statePayload(ctx, routes))}\n\n`;
6907
+ let payload;
6908
+ try {
6909
+ payload = JSON.stringify(await statePayload(ctx, routes));
6910
+ } catch (error) {
6911
+ const now = Date.now();
6912
+ if (now - broadcastWarnedAt > 6e4) {
6913
+ broadcastWarnedAt = now;
6914
+ ctx.logger("lowtide").warn("state broadcast failed: %s", error instanceof Error ? error.message : String(error));
6915
+ }
6916
+ return;
6917
+ }
6918
+ const frame = `event: state\ndata: ${payload}\n\n`;
6827
6919
  for (const client of Array.from(sseClients)) try {
6828
6920
  client.write(frame);
6829
6921
  } catch {
@@ -6936,6 +7028,7 @@ function registerRoutes(ctx, routes) {
6936
7028
  "cache-control": "no-cache",
6937
7029
  connection: "keep-alive"
6938
7030
  });
7031
+ res.write("retry: 5000\n\n");
6939
7032
  res.write(": connected\n\n");
6940
7033
  sseClients.add(res);
6941
7034
  req.on("close", () => {
@@ -6944,6 +7037,12 @@ function registerRoutes(ctx, routes) {
6944
7037
  res.on("close", () => {
6945
7038
  sseClients.delete(res);
6946
7039
  });
7040
+ req.on("error", () => {
7041
+ sseClients.delete(res);
7042
+ });
7043
+ res.on("error", () => {
7044
+ sseClients.delete(res);
7045
+ });
6947
7046
  broadcastState(ctx, routes);
6948
7047
  return;
6949
7048
  }
@@ -7359,6 +7458,22 @@ function validateConfigUpdate(patch) {
7359
7458
  }
7360
7459
  return null;
7361
7460
  }
7461
+ /** Normalized weekday list for schedule comparison (undefined/empty = every day). */
7462
+ function dayKey(days) {
7463
+ return days === void 0 || days.length === 0 ? "all" : [...days].sort((a, b) => a - b).join(",");
7464
+ }
7465
+ /**
7466
+ * Whether the configured peak windows still match the official schedule
7467
+ * (official hours converted into this machine's clock). A mismatch means
7468
+ * DeepSeek changed its peak hours since the user last adopted them, and the
7469
+ * UI offers a one-click re-adopt instead of silently billing on stale hours.
7470
+ */
7471
+ function officialScheduleDrift(configured, officialLocal) {
7472
+ if (configured.length === 0) return false;
7473
+ const peaks = configured.filter((w) => w.level === "peak" && (w.multiplier === void 0 || w.multiplier === 1));
7474
+ if (peaks.length !== officialLocal.length) return true;
7475
+ return officialLocal.some((o) => !peaks.some((p) => p.start === o.start && p.end === o.end && dayKey(p.days) === dayKey(o.days)));
7476
+ }
7362
7477
  async function statePayload(ctx, routes) {
7363
7478
  const { store, scheduler } = routes;
7364
7479
  const now = /* @__PURE__ */ new Date();
@@ -7366,7 +7481,8 @@ async function statePayload(ctx, routes) {
7366
7481
  const windows = config.windows.length > 0 ? config.windows : OFFICIAL_PEAK_WINDOWS;
7367
7482
  const match = levelAt(now, windows);
7368
7483
  const modelId = ctx.agentDefaultModel.currentSelection().model;
7369
- const tier = tierFor(modelId, store.config.prices);
7484
+ const priceModel = resolvePriceModel(modelId, now);
7485
+ const tier = tierFor(modelId, store.config.prices, now);
7370
7486
  const activeLevel = match?.level ?? "off";
7371
7487
  const multiplier = match?.multiplier ?? 1;
7372
7488
  const row = rowForLevel(tier, activeLevel, multiplier);
@@ -7376,6 +7492,8 @@ async function statePayload(ctx, routes) {
7376
7492
  gateLeadMin: config.batch.gateLeadMin
7377
7493
  });
7378
7494
  const nextOff = nextOffPeakStart(now, windows);
7495
+ const systemTz = systemTimeZone();
7496
+ const officialInLocal = windowsInTz(OFFICIAL_PEAK_WINDOWS, systemTz, now);
7379
7497
  const activeTasks = store.tasks.filter((t) => t.status !== "dropped" && t.status !== "cancelled");
7380
7498
  const ledger = store.ledgerToday(now);
7381
7499
  const latestReport = store.reports[0] ?? null;
@@ -7385,6 +7503,8 @@ async function statePayload(ctx, routes) {
7385
7503
  return {
7386
7504
  ok: true,
7387
7505
  time: now.toISOString(),
7506
+ /** Snapshot instant — the client tier clock compares it with its own clock. */
7507
+ serverNow: now.getTime(),
7388
7508
  autonomy: config.autonomy,
7389
7509
  level: match === null ? null : {
7390
7510
  level: match.level,
@@ -7396,14 +7516,22 @@ async function statePayload(ctx, routes) {
7396
7516
  end: match.window.end
7397
7517
  }
7398
7518
  },
7519
+ /**
7520
+ * Raw effective windows (own `tz`/`days` preserved). The client derives the
7521
+ * displayed 闲时/忙时 locally from these with the same `levelAt` function, so
7522
+ * a stalled push stream can never freeze the pill.
7523
+ */
7524
+ windows,
7399
7525
  price: {
7400
7526
  model: modelId,
7527
+ /** Billing id after alias/route resolution (e.g. V4 Pro → deepseek-flash). */
7528
+ priceModel,
7401
7529
  input: row.input,
7402
7530
  inputCached: row.inputCached,
7403
7531
  output: row.output,
7404
7532
  tier: activeLevel,
7405
7533
  multiplier,
7406
- priceKnown: hasPriceEntry(modelId, store.config.prices),
7534
+ priceKnown: hasPriceEntry(modelId, store.config.prices, now),
7407
7535
  peakInput: tier.peak.input,
7408
7536
  peakOutput: tier.peak.output,
7409
7537
  offInput: tier.off.input,
@@ -7412,8 +7540,12 @@ async function statePayload(ctx, routes) {
7412
7540
  nextBatchAt: nextBatch.getTime(),
7413
7541
  countdownMs: minutesUntil(now, nextBatch) * 6e4,
7414
7542
  nextOffPeakAt: nextOff === null ? null : nextOff.getTime(),
7415
- systemTz: systemTimeZone(),
7416
- officialInLocal: windowsInTz(OFFICIAL_PEAK_WINDOWS, systemTimeZone(), now),
7543
+ systemTz,
7544
+ officialInLocal,
7545
+ /** True when the saved windows no longer match the official schedule. */
7546
+ officialDrift: officialScheduleDrift(config.windows, officialInLocal),
7547
+ /** Model-routing notice (e.g. V4 Pro retired → billed as Flash). */
7548
+ priceNotice: priceRouteNotice(modelId, now),
7417
7549
  batch: {
7418
7550
  window: config.batch.window,
7419
7551
  paused: config.batch.paused,
@@ -161,7 +161,8 @@ export declare function getModels(): Promise<ModelsResponse>;
161
161
  /** Read the full lowtide config (settings page seed). */
162
162
  export declare function getConfig(): Promise<ConfigResponse>;
163
163
  /** Settings-page meta from the live state: system timezone + official peak
164
- * windows converted to the local clock (explainer + one-click adopt). */
164
+ * windows converted to the local clock (explainer + one-click adopt), plus
165
+ * whether the saved windows drifted from the official schedule. */
165
166
  export declare function getStateMeta(): Promise<{
166
167
  ok: boolean;
167
168
  systemTz?: string;
@@ -172,6 +173,7 @@ export declare function getStateMeta(): Promise<{
172
173
  crossesDay: boolean;
173
174
  days?: number[];
174
175
  }>;
176
+ officialDrift?: boolean;
175
177
  error?: string;
176
178
  }>;
177
179
  /** Persist a partial config update; takes effect immediately (next scheduler tick). */
@@ -8,6 +8,9 @@ export interface InterceptMatched {
8
8
  * Pure chain routing: priced window ∧ not dismissed ∧ session present ∧
9
9
  * draft non-empty. The draft condition keeps the native bar (and the queue
10
10
  * dock) visible until the user actually starts typing (PLAN §6.2).
11
+ *
12
+ * v0.2.2: the tier comes from the local clock (`store.tier`), so a stalled
13
+ * push stream can neither hide nor freeze the intercept card at a boundary.
11
14
  */
12
15
  export declare function selectIntercept(owner: ComposerChainProps): InterceptMatched | null;
13
16
  export type InterceptCardProps = PropsRuntime<'conversation.composer'> & {
@@ -1,3 +1,10 @@
1
+ /**
2
+ * Wall-clock tick for "now" markers (v0.2.2): re-renders every `periodMs`
3
+ * (default 30s) and on mount. The 24h band's marker used to be computed once
4
+ * per render with no timer, so it never moved on its own — the same class of
5
+ * staleness the tier clock fixes for the pill.
6
+ */
7
+ export declare function useWallClock(periodMs?: number): number;
1
8
  /** ¥3.82 two-decimals; ¥123 without decimals at ≥¥100; <¥0.01 for dust (PLAN §3.6). */
2
9
  export declare function Money({ yuan, className }: {
3
10
  yuan: number;
@@ -18,6 +18,7 @@ declare const zh: {
18
18
  'pill.off': string;
19
19
  'pill.custom': string;
20
20
  'pill.running': string;
21
+ 'pill.stale': string;
21
22
  'tooltip.time': string;
22
23
  'tooltip.timeNoWindow': string;
23
24
  'tooltip.queue': string;
@@ -108,6 +109,7 @@ declare const zh: {
108
109
  'modal.editDesc': string;
109
110
  'modal.saveEdit': string;
110
111
  'modal.cancel': string;
112
+ 'modal.close': string;
111
113
  'modal.submit': string;
112
114
  'modal.promptPlaceholderSingle': string;
113
115
  'modal.promptPlaceholderIterative': string;
@@ -270,6 +272,8 @@ declare const zh: {
270
272
  'settings.priceTierOff': string;
271
273
  'settings.officialTitle': string;
272
274
  'settings.officialBody': string;
275
+ 'settings.officialDrift': string;
276
+ 'settings.modelRetiring': string;
273
277
  'settings.localTz': string;
274
278
  'settings.officialPeakLocal': string;
275
279
  'settings.officialWeekend': string;
@@ -9,7 +9,7 @@
9
9
  * the host locale service; every slot entry declares `locale: NS` so the
10
10
  * framework injects the typed `t` seat into component props.
11
11
  */
12
- import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client';
12
+ import type { Context as ClientContext } from '@deepseek-ai/cordis';
13
13
  /** Required services before this client module materializes. */
14
14
  export declare const inject: string[];
15
15
  export declare function apply(ctx: ClientContext): void;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Client-side tier clock (v0.2.2): derives the displayed 闲时/忙时 from the
3
+ * CONFIGURED windows and the LOCAL clock, using the very same pure `levelAt`
4
+ * the host uses (imported from lowtide-core, which is inlined into the client
5
+ * bundle — it is not a `@deepseek-ai/*` platform module).
6
+ *
7
+ * Why this exists — the reported bug:
8
+ * The price pill used to be a pure mirror of the host's pushed state. The
9
+ * client disables its 4s polling as soon as the EventSource reports `open`
10
+ * and had no freshness check, so ONE silently stalled stream (host restart
11
+ * leaving a half-open socket, a hidden/frozen Electron window, system sleep,
12
+ * a swapped SSE client) froze 闲时/忙时 forever — and `connected === false`
13
+ * was invisible while a host snapshot existed. The pill simply stopped
14
+ * following the clock.
15
+ *
16
+ * This module makes the tier a function of time, never of stream liveness:
17
+ * - recomputed on every state frame (host config may change),
18
+ * - recomputed on a 30s heartbeat (covers suspend/resume and clock jumps),
19
+ * - recomputed exactly at the next window boundary (+1s), so a 12:00 or
20
+ * 18:00 flip is visible even with zero server traffic.
21
+ */
22
+ import { type WindowCfg, type WindowLevel } from 'lowtide-core';
23
+ /**
24
+ * How long the UI tolerates silence from the push stream before it stops
25
+ * trusting it. The host heartbeats every 15s, so 45s = three missed frames.
26
+ */
27
+ export declare const SSE_STALE_MS = 45000;
28
+ /**
29
+ * Freshness predicate for the live state stream: an OPEN EventSource is not a
30
+ * HEALTHY one. `lastFrameAt === 0` means no frame has ever arrived.
31
+ */
32
+ export declare function isStreamFresh(lastFrameAt: number, nowMs: number, staleMs?: number): boolean;
33
+ export interface TierSnapshot {
34
+ /** Effective level right now; 'off' when no window matches (off-peak base). */
35
+ level: WindowLevel;
36
+ /** Window multiplier over the off-peak row (1 for official peak/off). */
37
+ multiplier: number;
38
+ /** The matching window's boundaries, for the tooltip (null = off-peak). */
39
+ window: {
40
+ id: string;
41
+ label?: string;
42
+ start: string;
43
+ end: string;
44
+ } | null;
45
+ }
46
+ /** The off-peak fallback snapshot (also used before the first host frame). */
47
+ export declare const OFF_TIER: TierSnapshot;
48
+ /**
49
+ * Derive the tier at `now` from raw windows (own `tz`/`days` preserved — the
50
+ * host sends them verbatim precisely so this stays timezone-correct for
51
+ * west-hemisphere users with day-shifted windows).
52
+ */
53
+ export declare function deriveTier(windows: WindowCfg[], tz: string, now: Date): TierSnapshot;
54
+ /** Epoch ms of the next boundary that can change the level (null = none). */
55
+ export declare function nextBoundaryAt(windows: WindowCfg[], tz: string, now: Date): number | null;
56
+ /** Resolve the timezone to evaluate windows in (host-provided wins). */
57
+ export declare function tierTimeZone(hostTz?: string | null): string;
58
+ export interface TierClockOptions {
59
+ /** Current windows (null/empty before the first host frame → keep the last tier). */
60
+ getWindows: () => WindowCfg[] | null;
61
+ /** Current tz (host-provided, falling back to the browser's own). */
62
+ getTimeZone: () => string;
63
+ /** Called only when the derived tier actually changes. */
64
+ onChange: (tier: TierSnapshot) => void;
65
+ /** Heartbeat period in ms (default 30s). */
66
+ tickMs?: number;
67
+ /** Injectable clock (tests). */
68
+ now?: () => number;
69
+ }
70
+ export interface TierClock {
71
+ /** Recompute immediately (called on every host frame and on demand). */
72
+ refresh(): TierSnapshot;
73
+ /** Last derived snapshot. */
74
+ current(): TierSnapshot;
75
+ stop(): void;
76
+ }
77
+ /**
78
+ * Start the tier clock. Returns a handle whose `refresh()` is called whenever a
79
+ * host frame arrives; `stop()` clears both timers (wired into `ctx.effect`).
80
+ */
81
+ export declare function startTierClock(options: TierClockOptions): TierClock;