dsh-lowtide 0.2.0 → 0.2.2

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
@@ -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, {
@@ -6138,16 +6188,18 @@ function priceTableOf(store) {
6138
6188
  return store.config.prices && Object.keys(store.config.prices).length > 0 ? store.config.prices : void 0;
6139
6189
  }
6140
6190
  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);
6191
+ const now = /* @__PURE__ */ new Date();
6192
+ if (!hasPriceEntry(modelId, prices, now)) return 0;
6193
+ return prices === void 0 ? cost(usage, modelId, now, windows) : cost(usage, modelId, now, windows, prices);
6143
6194
  }
6144
6195
  /** 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. */
6196
+ * Only models with a real price entry (the official table — including legacy
6197
+ * aliases such as deepseek-v4-flash-vision-exp — or a user price override)
6198
+ * get a baseline; anything else yields 0 so no fake savings are reported. */
6148
6199
  function peakCostOf(usage, modelId, prices) {
6149
- if (!hasPriceEntry(modelId, prices)) return 0;
6150
- return costAtRow(usage, tierFor(modelId, prices).peak);
6200
+ const now = /* @__PURE__ */ new Date();
6201
+ if (!hasPriceEntry(modelId, prices, now)) return 0;
6202
+ return costAtRow(usage, tierFor(modelId, prices, now).peak);
6151
6203
  }
6152
6204
  /** Retrying a quota/balance rejection is pointless (and costly): the account
6153
6205
  * state cannot change inside one batch. Matches deepseek's 402 payload. */
@@ -6821,9 +6873,31 @@ function listWorkspaceSessions(limitPerWorkspace = 30) {
6821
6873
  const sseClients = /* @__PURE__ */ new Set();
6822
6874
  /** Hard cap on concurrent SSE connections (pentest P7). */
6823
6875
  const MAX_SSE_CLIENTS = 16;
6876
+ /** One warning per failure burst — a throwing payload must not spam the log. */
6877
+ let broadcastWarnedAt = 0;
6878
+ /**
6879
+ * Push the aggregate state to every SSE client.
6880
+ *
6881
+ * `statePayload` reads live services (`ctx.agentDefaultModel`, the scheduler,
6882
+ * the ledger); a throw there used to reject the fire-and-forget promise and
6883
+ * kill the whole heartbeat silently — the browser then kept a half-open stream
6884
+ * and froze the pill. Failures are now contained: the frame is skipped, the
6885
+ * next heartbeat (15s) retries, and the reason is logged once per minute.
6886
+ */
6824
6887
  async function broadcastState(ctx, routes) {
6825
6888
  if (sseClients.size === 0) return;
6826
- const frame = `event: state\ndata: ${JSON.stringify(await statePayload(ctx, routes))}\n\n`;
6889
+ let payload;
6890
+ try {
6891
+ payload = JSON.stringify(await statePayload(ctx, routes));
6892
+ } catch (error) {
6893
+ const now = Date.now();
6894
+ if (now - broadcastWarnedAt > 6e4) {
6895
+ broadcastWarnedAt = now;
6896
+ ctx.logger("lowtide").warn("state broadcast failed: %s", error instanceof Error ? error.message : String(error));
6897
+ }
6898
+ return;
6899
+ }
6900
+ const frame = `event: state\ndata: ${payload}\n\n`;
6827
6901
  for (const client of Array.from(sseClients)) try {
6828
6902
  client.write(frame);
6829
6903
  } catch {
@@ -6936,6 +7010,7 @@ function registerRoutes(ctx, routes) {
6936
7010
  "cache-control": "no-cache",
6937
7011
  connection: "keep-alive"
6938
7012
  });
7013
+ res.write("retry: 5000\n\n");
6939
7014
  res.write(": connected\n\n");
6940
7015
  sseClients.add(res);
6941
7016
  req.on("close", () => {
@@ -6944,6 +7019,12 @@ function registerRoutes(ctx, routes) {
6944
7019
  res.on("close", () => {
6945
7020
  sseClients.delete(res);
6946
7021
  });
7022
+ req.on("error", () => {
7023
+ sseClients.delete(res);
7024
+ });
7025
+ res.on("error", () => {
7026
+ sseClients.delete(res);
7027
+ });
6947
7028
  broadcastState(ctx, routes);
6948
7029
  return;
6949
7030
  }
@@ -7359,6 +7440,22 @@ function validateConfigUpdate(patch) {
7359
7440
  }
7360
7441
  return null;
7361
7442
  }
7443
+ /** Normalized weekday list for schedule comparison (undefined/empty = every day). */
7444
+ function dayKey(days) {
7445
+ return days === void 0 || days.length === 0 ? "all" : [...days].sort((a, b) => a - b).join(",");
7446
+ }
7447
+ /**
7448
+ * Whether the configured peak windows still match the official schedule
7449
+ * (official hours converted into this machine's clock). A mismatch means
7450
+ * DeepSeek changed its peak hours since the user last adopted them, and the
7451
+ * UI offers a one-click re-adopt instead of silently billing on stale hours.
7452
+ */
7453
+ function officialScheduleDrift(configured, officialLocal) {
7454
+ if (configured.length === 0) return false;
7455
+ const peaks = configured.filter((w) => w.level === "peak" && (w.multiplier === void 0 || w.multiplier === 1));
7456
+ if (peaks.length !== officialLocal.length) return true;
7457
+ return officialLocal.some((o) => !peaks.some((p) => p.start === o.start && p.end === o.end && dayKey(p.days) === dayKey(o.days)));
7458
+ }
7362
7459
  async function statePayload(ctx, routes) {
7363
7460
  const { store, scheduler } = routes;
7364
7461
  const now = /* @__PURE__ */ new Date();
@@ -7366,7 +7463,8 @@ async function statePayload(ctx, routes) {
7366
7463
  const windows = config.windows.length > 0 ? config.windows : OFFICIAL_PEAK_WINDOWS;
7367
7464
  const match = levelAt(now, windows);
7368
7465
  const modelId = ctx.agentDefaultModel.currentSelection().model;
7369
- const tier = tierFor(modelId, store.config.prices);
7466
+ const priceModel = resolvePriceModel(modelId, now);
7467
+ const tier = tierFor(modelId, store.config.prices, now);
7370
7468
  const activeLevel = match?.level ?? "off";
7371
7469
  const multiplier = match?.multiplier ?? 1;
7372
7470
  const row = rowForLevel(tier, activeLevel, multiplier);
@@ -7376,6 +7474,8 @@ async function statePayload(ctx, routes) {
7376
7474
  gateLeadMin: config.batch.gateLeadMin
7377
7475
  });
7378
7476
  const nextOff = nextOffPeakStart(now, windows);
7477
+ const systemTz = systemTimeZone();
7478
+ const officialInLocal = windowsInTz(OFFICIAL_PEAK_WINDOWS, systemTz, now);
7379
7479
  const activeTasks = store.tasks.filter((t) => t.status !== "dropped" && t.status !== "cancelled");
7380
7480
  const ledger = store.ledgerToday(now);
7381
7481
  const latestReport = store.reports[0] ?? null;
@@ -7385,6 +7485,8 @@ async function statePayload(ctx, routes) {
7385
7485
  return {
7386
7486
  ok: true,
7387
7487
  time: now.toISOString(),
7488
+ /** Snapshot instant — the client tier clock compares it with its own clock. */
7489
+ serverNow: now.getTime(),
7388
7490
  autonomy: config.autonomy,
7389
7491
  level: match === null ? null : {
7390
7492
  level: match.level,
@@ -7396,14 +7498,22 @@ async function statePayload(ctx, routes) {
7396
7498
  end: match.window.end
7397
7499
  }
7398
7500
  },
7501
+ /**
7502
+ * Raw effective windows (own `tz`/`days` preserved). The client derives the
7503
+ * displayed 闲时/忙时 locally from these with the same `levelAt` function, so
7504
+ * a stalled push stream can never freeze the pill.
7505
+ */
7506
+ windows,
7399
7507
  price: {
7400
7508
  model: modelId,
7509
+ /** Billing id after alias/route resolution (e.g. V4 Pro → deepseek-flash). */
7510
+ priceModel,
7401
7511
  input: row.input,
7402
7512
  inputCached: row.inputCached,
7403
7513
  output: row.output,
7404
7514
  tier: activeLevel,
7405
7515
  multiplier,
7406
- priceKnown: hasPriceEntry(modelId, store.config.prices),
7516
+ priceKnown: hasPriceEntry(modelId, store.config.prices, now),
7407
7517
  peakInput: tier.peak.input,
7408
7518
  peakOutput: tier.peak.output,
7409
7519
  offInput: tier.off.input,
@@ -7412,8 +7522,12 @@ async function statePayload(ctx, routes) {
7412
7522
  nextBatchAt: nextBatch.getTime(),
7413
7523
  countdownMs: minutesUntil(now, nextBatch) * 6e4,
7414
7524
  nextOffPeakAt: nextOff === null ? null : nextOff.getTime(),
7415
- systemTz: systemTimeZone(),
7416
- officialInLocal: windowsInTz(OFFICIAL_PEAK_WINDOWS, systemTimeZone(), now),
7525
+ systemTz,
7526
+ officialInLocal,
7527
+ /** True when the saved windows no longer match the official schedule. */
7528
+ officialDrift: officialScheduleDrift(config.windows, officialInLocal),
7529
+ /** Model-routing notice (e.g. V4 Pro retired → billed as Flash). */
7530
+ priceNotice: priceRouteNotice(modelId, now),
7417
7531
  batch: {
7418
7532
  window: config.batch.window,
7419
7533
  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;
@@ -270,6 +271,8 @@ declare const zh: {
270
271
  'settings.priceTierOff': string;
271
272
  'settings.officialTitle': string;
272
273
  'settings.officialBody': string;
274
+ 'settings.officialDrift': string;
275
+ 'settings.modelRetiring': string;
273
276
  'settings.localTz': string;
274
277
  'settings.officialPeakLocal': string;
275
278
  'settings.officialWeekend': string;
@@ -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;
@@ -1,6 +1,12 @@
1
+ import type { WindowCfg } from 'lowtide-core';
2
+ import { type TierSnapshot } from './lib/tierClock.ts';
3
+ /** Re-exported so components (the pill) share one staleness definition. */
4
+ export { SSE_STALE_MS } from './lib/tierClock.ts';
1
5
  export interface HostState {
2
6
  ok: boolean;
3
7
  time: string;
8
+ /** Snapshot instant (epoch ms) — lets the client spot clock skew. */
9
+ serverNow?: number;
4
10
  autonomy: string;
5
11
  level: {
6
12
  level: string;
@@ -12,8 +18,12 @@ export interface HostState {
12
18
  end: string;
13
19
  };
14
20
  } | null;
21
+ /** Raw effective windows (own tz/days) — the client tier clock's input. */
22
+ windows?: WindowCfg[];
15
23
  price: {
16
24
  model: string;
25
+ /** Billing id after alias/route resolution (optional on older hosts). */
26
+ priceModel?: string;
17
27
  input: number;
18
28
  inputCached: number;
19
29
  output: number;
@@ -28,6 +38,8 @@ export interface HostState {
28
38
  offInput: number;
29
39
  offOutput: number;
30
40
  };
41
+ /** Billing notice for the selected model (e.g. V4 Pro retired → Flash). */
42
+ priceNotice?: string | null;
31
43
  nextBatchAt: number;
32
44
  countdownMs: number;
33
45
  nextOffPeakAt: number | null;
@@ -40,6 +52,8 @@ export interface HostState {
40
52
  end: string;
41
53
  crossesDay: boolean;
42
54
  }>;
55
+ /** True when the saved windows drifted from the official schedule. */
56
+ officialDrift?: boolean;
43
57
  batch: {
44
58
  window: string;
45
59
  paused: boolean;
@@ -177,12 +191,31 @@ export interface ClientUiState {
177
191
  lastReportId: string | null;
178
192
  /** Active locale id ('zh' | 'en'), synced from the host locale service. */
179
193
  activeLocale: string;
194
+ /**
195
+ * Tier derived from the local clock + the host's windows. This is what the
196
+ * pill and the intercept card DISPLAY, so a stalled stream can never freeze
197
+ * 闲时/忙时; the host's `price.tier` stays the pricing/ledger authority.
198
+ */
199
+ tier: TierSnapshot;
200
+ /** When `tier` was last derived (epoch ms). */
201
+ tierAt: number;
202
+ /** Newest state frame seen from either transport (epoch ms, 0 = never). */
203
+ lastFrameAt: number;
204
+ /** False while the live push is silent/absent and polling carries the UI. */
205
+ sseHealthy: boolean;
180
206
  }
181
207
  export declare const lowtideStore: import("@deepseek-ai/dsh-client-runtime/client").SnapshotStore<ClientUiState>;
182
208
  export declare function showToast(text: string): void;
183
209
  export declare function clearToast(): void;
210
+ /** Reset the UI slice (plugin unload) — the full field list lives here so a
211
+ * new field can never be forgotten by a caller's hand-written literal. */
212
+ export declare function resetUiState(): void;
184
213
  /** Trigger one immediate poll (used after write actions for fast refresh). */
185
214
  export declare function refreshNow(): void;
215
+ /** Re-derive the displayed tier right now (after a window edit, say). */
216
+ export declare function refreshTier(): void;
217
+ /** Feed the clock from a config payload when no host frame is available yet. */
218
+ export declare function setTierWindows(windows: WindowCfg[] | null, tz?: string | null): void;
186
219
  export declare function startPolling(): () => void;
187
220
  export declare function useHost<T>(selector: (host: HostState) => T): T | undefined;
188
221
  export declare function useLowtide<T>(selector: (state: ClientUiState) => T): T;
@@ -12,8 +12,10 @@ import type { Context } from '@deepseek-ai/cordis';
12
12
  export interface AvailableModel {
13
13
  id: string;
14
14
  name: string;
15
- /** Whether this model has an official/override price entry (deepseek pair). */
15
+ /** Whether this model has an official/override price entry (aliases count). */
16
16
  priceKnown: boolean;
17
+ /** The id that actually gets billed (legacy alias / dated route resolved). */
18
+ priceModel: string;
17
19
  /** Adapter-declared input modalities (e.g. ["text", "image"]) — optional. */
18
20
  inputModalities?: string[];
19
21
  /** Supported reasoning efforts with the adapter's native labels. */
@@ -24,6 +26,8 @@ export interface AvailableModel {
24
26
  }>;
25
27
  /** The model's default reasoning effort id, when the adapter declares one. */
26
28
  defaultReasoningEffort?: string;
29
+ /** Billing notice (e.g. a retired model routed to a cheaper one). */
30
+ notice?: string;
27
31
  }
28
32
  export interface AvailableProvider {
29
33
  provider: string;
@@ -5,6 +5,7 @@
5
5
  * loopback only and the README deployment guidance (SSH tunnel) is Phase 4.
6
6
  */
7
7
  import type { Context } from '@deepseek-ai/cordis';
8
+ import { type WindowCfg, type WindowLocal } from 'lowtide-core';
8
9
  import type { Scheduler } from './scheduler.ts';
9
10
  import { LowtideStore } from './store.ts';
10
11
  export type { TriageAction } from './state-machine.ts';
@@ -14,3 +15,10 @@ export interface Routes {
14
15
  scheduler: Scheduler;
15
16
  }
16
17
  export declare function registerRoutes(ctx: Context, routes: Routes): void;
18
+ /**
19
+ * Whether the configured peak windows still match the official schedule
20
+ * (official hours converted into this machine's clock). A mismatch means
21
+ * DeepSeek changed its peak hours since the user last adopted them, and the
22
+ * UI offers a one-click re-adopt instead of silently billing on stale hours.
23
+ */
24
+ export declare function officialScheduleDrift(configured: WindowCfg[], officialLocal: WindowLocal[]): boolean;