@lukstei/dsh-session-handoff 0.2.2-rc.5.11 → 0.2.2-rc.5.13

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/README.md CHANGED
@@ -191,6 +191,22 @@ About 60 tokens for the message, plus the brief when read. Brief size grows with
191
191
 
192
192
  Appended message only; the prompt prefix is untouched. In a launched session this is the first turn.
193
193
 
194
+ <a id="configuration"></a>
195
+ ## Configuration
196
+
197
+ The gauge ring appears when the context reaches a size bar. Bars are in tokens and differ for a warm and a cold prompt cache. Set them for every model (`defaults`), per provider id (`providers`) or per `provider/model` (`models`); the most specific entry wins, field by field.
198
+
199
+ ```yaml
200
+ config:
201
+ defaults: { warmSoft: 100000, warmStrong: 150000, coldSoft: 70000, coldStrong: 100000, cacheTtlMs: 300000 }
202
+ providers:
203
+ anthropic: { cacheTtlMs: 300000 }
204
+ models:
205
+ deepseek/deepseek-chat: { warmSoft: 60000, warmStrong: 90000 }
206
+ ```
207
+
208
+ Unset fields use the values above. A model's context window still caps the bars at 60% and 80%.
209
+
194
210
  <a id="known-limitations-and-deferred-work"></a>
195
211
  ## Known Limitations and Deferred Work
196
212
 
package/dist/client.js CHANGED
@@ -17,6 +17,44 @@ window.__ModuleLoader__.load({
17
17
  if (typeof text !== "string" || !text.startsWith("Handoff launched: ")) return;
18
18
  return text.slice(18);
19
19
  }
20
+ // src/limits.ts
21
+ const BUILTIN_LIMITS = {
22
+ warm: {
23
+ soft: 1e5,
24
+ strong: 15e4
25
+ },
26
+ cold: {
27
+ soft: 7e4,
28
+ strong: 1e5
29
+ },
30
+ cacheTtlMs: 3e5
31
+ };
32
+ /** Precedence: `models["provider/model"]`, then `providers[provider]`, then `defaults`, then the built-ins. */
33
+ function resolveLimits(config, route) {
34
+ const layers = [
35
+ config.defaults,
36
+ route === void 0 || config.providers === void 0 ? void 0 : config.providers[route.provider],
37
+ route === void 0 || config.models === void 0 ? void 0 : config.models[`${route.provider}/${route.model}`]
38
+ ];
39
+ const pick = (key, fallback) => {
40
+ let value = fallback;
41
+ for (const layer of layers) if (layer !== void 0 && layer[key] !== void 0) value = layer[key];
42
+ return value;
43
+ };
44
+ return {
45
+ warm: {
46
+ soft: pick("warmSoft", BUILTIN_LIMITS.warm.soft),
47
+ strong: pick("warmStrong", BUILTIN_LIMITS.warm.strong)
48
+ },
49
+ cold: {
50
+ soft: pick("coldSoft", BUILTIN_LIMITS.cold.soft),
51
+ strong: pick("coldStrong", BUILTIN_LIMITS.cold.strong)
52
+ },
53
+ cacheTtlMs: pick("cacheTtlMs", BUILTIN_LIMITS.cacheTtlMs)
54
+ };
55
+ }
56
+ /** Name of the page global the Host fills with the validated config. */
57
+ const CONFIG_GLOBAL = "__DSH_SESSION_HANDOFF_CONFIG__";
20
58
  // src/client/acp-usage.ts
21
59
  let reader;
22
60
  const listeners = /* @__PURE__ */ new Set();
@@ -35,21 +73,11 @@ window.__ModuleLoader__.load({
35
73
  return reader;
36
74
  }
37
75
  // src/client/level.ts
38
- /** Anthropic prompt-cache TTL: past this idle gap the next turn re-writes the whole context. */
39
- const CACHE_TTL_MS = 3e5;
40
- const WARM = {
41
- soft: 1e5,
42
- strong: 15e4
43
- };
44
- const COLD = {
45
- soft: 7e4,
46
- strong: 1e5
47
- };
48
76
  const SOFT_WINDOW_SHARE = .6;
49
77
  const STRONG_WINDOW_SHARE = .8;
50
- function handoffLevel(pressureTokens, contextWindow, cold) {
78
+ function handoffLevel(pressureTokens, contextWindow, cold, limits) {
51
79
  if (pressureTokens === void 0) return "none";
52
- const bar = cold ? COLD : WARM;
80
+ const bar = cold ? limits.cold : limits.warm;
53
81
  const soft = contextWindow === void 0 ? bar.soft : Math.min(bar.soft, SOFT_WINDOW_SHARE * contextWindow);
54
82
  if (pressureTokens >= (contextWindow === void 0 ? bar.strong : Math.min(bar.strong, STRONG_WINDOW_SHARE * contextWindow))) return "strong";
55
83
  return pressureTokens >= soft ? "soft" : "none";
@@ -60,10 +88,11 @@ window.__ModuleLoader__.load({
60
88
  strong: "#d62839"
61
89
  };
62
90
  /** Gauge icon beside the send button once the session is big enough that `/handoff` pays off. */
63
- function HandoffRing({ sessionId, useProjection, useSession, onHandoff }) {
91
+ function HandoffRing({ sessionId, useProjection, useSession, onHandoff, loadRoute, config }) {
64
92
  const pressure = useProjection("contextPressure");
65
93
  const running = useSession((session) => session.running);
66
94
  const [acp, setAcp] = (0, react.useState)(void 0);
95
+ const [route, setRoute] = (0, react.useState)(void 0);
67
96
  const [cold, setCold] = (0, react.useState)(false);
68
97
  const [pendingSession, setPendingSession] = (0, react.useState)(void 0);
69
98
  const readUsage = (0, react.useSyncExternalStore)(subscribeAcpUsageReader, currentAcpUsageReader);
@@ -81,15 +110,34 @@ window.__ModuleLoader__.load({
81
110
  running,
82
111
  readUsage
83
112
  ]);
113
+ (0, react.useEffect)(() => {
114
+ if (running) return;
115
+ let live = true;
116
+ loadRoute(sessionId).then((current) => {
117
+ if (live) setRoute(current);
118
+ });
119
+ return () => {
120
+ live = false;
121
+ };
122
+ }, [
123
+ sessionId,
124
+ running,
125
+ loadRoute
126
+ ]);
127
+ const limits = resolveLimits(config, route);
84
128
  const tokens = pressure !== void 0 && pressure.pressureTokens !== void 0 ? pressure.pressureTokens : acp?.used;
85
129
  const window = pressure !== void 0 && pressure.contextWindow !== void 0 ? pressure.contextWindow : acp?.size;
86
130
  (0, react.useEffect)(() => {
87
131
  setCold(false);
88
132
  if (running) return;
89
- const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
133
+ const timer = setTimeout(() => setCold(true), limits.cacheTtlMs);
90
134
  return () => clearTimeout(timer);
91
- }, [tokens, running]);
92
- const level = handoffLevel(tokens, window, cold);
135
+ }, [
136
+ tokens,
137
+ running,
138
+ limits.cacheTtlMs
139
+ ]);
140
+ const level = handoffLevel(tokens, window, cold, limits);
93
141
  if (level === "none" || tokens === void 0) return null;
94
142
  const k = Math.round(tokens / 1e3);
95
143
  const pending = pendingSession === sessionId;
@@ -163,6 +211,11 @@ window.__ModuleLoader__.load({
163
211
  if (!result.ok) console.warn(`session-handoff: ${line} failed`, result);
164
212
  });
165
213
  };
214
+ const config = globalThis[CONFIG_GLOBAL];
215
+ const loadRoute = async (id) => {
216
+ const { current } = await ctx.modelDirectories.directoryFor(id).load();
217
+ return current === null ? void 0 : current;
218
+ };
166
219
  const handoff = (id) => run(id, "/handoff");
167
220
  ctx.effect(() => ctx.commandUi.decorate({
168
221
  name: "handoff",
@@ -217,7 +270,11 @@ window.__ModuleLoader__.load({
217
270
  name: "conversation.input.right",
218
271
  id: "session-handoff.ring",
219
272
  order: 1e3,
220
- inject: () => ({ onHandoff: handoff })
273
+ inject: () => ({
274
+ onHandoff: handoff,
275
+ loadRoute,
276
+ config
277
+ })
221
278
  }, HandoffRing)), "session-handoff: handoff ring");
222
279
  ctx.inject(["remote", "remote.dshAcp"], (acpCtx) => {
223
280
  const remote = acpCtx.remote.dshAcp;
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { mkdir, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
4
+ import Schema from "@deepseek-ai/schemastery";
4
5
  import { scratchDirectory } from "@lukstei/dsh-scratch-dir";
5
6
  // src/handoff.ts
6
7
  /**
@@ -261,6 +262,9 @@ const LAUNCH_PREFIX = "Handoff launched: ";
261
262
  function formatLaunchResult(sessionId) {
262
263
  return `${LAUNCH_PREFIX}${String(sessionId)}`;
263
264
  }
265
+ // src/limits.ts
266
+ /** Name of the page global the Host fills with the validated config. */
267
+ const CONFIG_GLOBAL = "__DSH_SESSION_HANDOFF_CONFIG__";
264
268
  // src/index.ts
265
269
  const name = "session-handoff";
266
270
  const inject = [
@@ -270,12 +274,33 @@ const inject = [
270
274
  "sessionController",
271
275
  "sessionTitle",
272
276
  "workspaceRegistry",
273
- "llm"
277
+ "llm",
278
+ "webServer"
274
279
  ];
275
280
  const HANDOFF_FILE = "HANDOFF.md";
276
281
  const SHORT_ID_LENGTH = 8;
277
282
  const RESUMED_SUFFIX = " (Resumed)";
278
- function apply(ctx) {
283
+ const tokens = (what) => Schema.natural().description(`${what} (tokens).`);
284
+ const limitOverride = Schema.object({
285
+ warmSoft: tokens("Warm cache: context size that shows the amber ring"),
286
+ warmStrong: tokens("Warm cache: context size that shows the red ring"),
287
+ coldSoft: tokens("Cold cache: context size that shows the amber ring"),
288
+ coldStrong: tokens("Cold cache: context size that shows the red ring"),
289
+ cacheTtlMs: Schema.natural().description("Idle milliseconds after which the provider's prompt cache counts as cold.")
290
+ });
291
+ const Config = Schema.object({
292
+ defaults: limitOverride.description("Applies to every model."),
293
+ providers: Schema.dict(limitOverride).description("Per provider id; overrides `defaults`."),
294
+ models: Schema.dict(limitOverride).description("Per \"provider/model\"; overrides `providers`.")
295
+ });
296
+ function apply(ctx, config) {
297
+ ctx.on("webserver/index-inject", (table) => {
298
+ table.push({
299
+ kind: "global",
300
+ name: CONFIG_GLOBAL,
301
+ value: config
302
+ });
303
+ });
279
304
  ctx.commands.register({
280
305
  name: "handoff",
281
306
  description: "Hand this session off to a new one (bare: pick the model from a list)",
@@ -460,4 +485,4 @@ async function createBeside(ctx, source, targetId, markdown, snapshot, signal, m
460
485
  await deliver(ctx, agent, targetId, markdown);
461
486
  return created;
462
487
  }
463
- export { apply, inject, name, parseModelArg };
488
+ export { Config, apply, inject, name, parseModelArg };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lukstei/dsh-session-handoff",
3
- "version": "0.2.2-rc.5.11",
3
+ "version": "0.2.2-rc.5.13",
4
4
  "description": "Session handoff brief command for DSH",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -44,7 +44,7 @@
44
44
  }
45
45
  },
46
46
  "dependencies": {
47
- "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.11"
47
+ "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.13"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@deepseek-ai/cordis": "*",
@@ -58,7 +58,9 @@
58
58
  "@deepseek-ai/dsh-client-ui-session": "*",
59
59
  "@deepseek-ai/dsh-client-ui-slots": "*",
60
60
  "@deepseek-ai/dsh-commands": "*",
61
+ "@deepseek-ai/dsh-host-webserver": "*",
61
62
  "@deepseek-ai/dsh-llm": "*",
63
+ "@deepseek-ai/schemastery": "*",
62
64
  "@deepseek-ai/dsh-session": "*",
63
65
  "@deepseek-ai/dsh-session-query": "*",
64
66
  "@deepseek-ai/dsh-session-title": "*",
@@ -80,14 +82,16 @@
80
82
  "@deepseek-ai/dsh-client-ui-session": "0.2.2-rc.5",
81
83
  "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.5",
82
84
  "@deepseek-ai/dsh-commands": "0.2.2-rc.5",
85
+ "@deepseek-ai/dsh-host-webserver": "0.2.2-rc.5",
83
86
  "@deepseek-ai/dsh-llm": "0.2.2-rc.5",
87
+ "@deepseek-ai/schemastery": "3.19.0",
84
88
  "@deepseek-ai/dsh-session": "0.2.2-rc.5",
85
89
  "@deepseek-ai/dsh-session-query": "0.2.2-rc.5",
86
90
  "@deepseek-ai/dsh-session-title": "0.2.2-rc.5",
87
91
  "@deepseek-ai/dsh-token-meter": "0.2.2-rc.5",
88
92
  "@deepseek-ai/dsh-working-directory": "0.2.2-rc.5",
89
93
  "@deepseek-ai/dsh-workspace": "0.2.2-rc.5",
90
- "@lukstei/dsh-client-split-view": "0.2.2-rc.5.11",
94
+ "@lukstei/dsh-client-split-view": "0.2.2-rc.5.13",
91
95
  "@types/node": "^26.0.0",
92
96
  "@types/react": "^19.3.0",
93
97
  "@zaimokuza/dsh-acp-adapter": "0.2.2-rc.5.2",
@@ -8,6 +8,7 @@ import type { SessionId } from "@deepseek-ai/dsh-session/types";
8
8
  import type {} from "@lukstei/dsh-client-split-view/client-contract";
9
9
  import type {} from "@zaimokuza/dsh-acp-adapter/remote";
10
10
  import { launchedSessionId } from "../launch.ts";
11
+ import { CONFIG_GLOBAL, type LimitsConfig } from "../limits.ts";
11
12
  import { type AcpUsageReader, setAcpUsageReader } from "./acp-usage.ts";
12
13
  import { HandoffRing } from "./ring.ts";
13
14
 
@@ -54,6 +55,16 @@ export function apply(ctx: Context): void {
54
55
  }
55
56
  });
56
57
  };
58
+ // Safe: the Host validated this value against its Config schema before injecting it.
59
+ const config = (globalThis as unknown as Record<string, LimitsConfig>)[
60
+ CONFIG_GLOBAL
61
+ ];
62
+ const loadRoute = async (
63
+ id: SessionId,
64
+ ): Promise<{ provider: string; model: string } | undefined> => {
65
+ const { current } = await ctx.modelDirectories.directoryFor(id).load();
66
+ return current === null ? undefined : current;
67
+ };
57
68
  const handoff = (id: SessionId): Promise<void> => run(id, "/handoff");
58
69
 
59
70
  // A bare composer `/handoff` opens the same model list as `/model`; the pick is
@@ -131,7 +142,7 @@ export function apply(ctx: Context): void {
131
142
  name: "conversation.input.right",
132
143
  id: "session-handoff.ring",
133
144
  order: 1000,
134
- inject: () => ({ onHandoff: handoff }),
145
+ inject: () => ({ onHandoff: handoff, loadRoute, config }),
135
146
  },
136
147
  HandoffRing,
137
148
  ),
@@ -1,12 +1,7 @@
1
- export type HandoffLevel = "none" | "soft" | "strong";
1
+ import type { Limits } from "../limits.ts";
2
2
 
3
- /** Anthropic prompt-cache TTL: past this idle gap the next turn re-writes the whole context. */
4
- export const CACHE_TTL_MS = 5 * 60_000;
3
+ export type HandoffLevel = "none" | "soft" | "strong";
5
4
 
6
- // Absolute prompt sizes, tuned by cost: a fresh session starts near 18k tokens, so a handoff
7
- // pays back sooner the more context a turn re-sends. A cold cache lowers both bars.
8
- const WARM = { soft: 100_000, strong: 150_000 };
9
- const COLD = { soft: 70_000, strong: 100_000 };
10
5
  // The window still caps the bars, so small-window models warn before compaction does.
11
6
  const SOFT_WINDOW_SHARE = 0.6;
12
7
  const STRONG_WINDOW_SHARE = 0.8;
@@ -15,9 +10,10 @@ export function handoffLevel(
15
10
  pressureTokens: number | undefined,
16
11
  contextWindow: number | undefined,
17
12
  cold: boolean,
13
+ limits: Limits,
18
14
  ): HandoffLevel {
19
15
  if (pressureTokens === undefined) return "none";
20
- const bar = cold ? COLD : WARM;
16
+ const bar = cold ? limits.cold : limits.warm;
21
17
  const soft =
22
18
  contextWindow === undefined
23
19
  ? bar.soft
@@ -12,12 +12,13 @@ import {
12
12
  useState,
13
13
  useSyncExternalStore,
14
14
  } from "react";
15
+ import { type LimitsConfig, resolveLimits } from "../limits.ts";
15
16
  import {
16
17
  type AcpUsage,
17
18
  currentAcpUsageReader,
18
19
  subscribeAcpUsageReader,
19
20
  } from "./acp-usage.ts";
20
- import { CACHE_TTL_MS, handoffLevel } from "./level.ts";
21
+ import { handoffLevel } from "./level.ts";
21
22
 
22
23
  const COLOR = { soft: "#d9a400", strong: "#d62839" } as const;
23
24
 
@@ -27,12 +28,22 @@ export function HandoffRing({
27
28
  useProjection,
28
29
  useSession,
29
30
  onHandoff,
31
+ loadRoute,
32
+ config,
30
33
  }: Pick<SessionStandardProps, "sessionId" | "useProjection" | "useSession"> & {
31
34
  onHandoff: (sessionId: SessionStandardProps["sessionId"]) => Promise<void>;
35
+ /** The session's current provider and model, which select its limits. */
36
+ loadRoute: (
37
+ sessionId: SessionStandardProps["sessionId"],
38
+ ) => Promise<{ provider: string; model: string } | undefined>;
39
+ config: LimitsConfig;
32
40
  }) {
33
41
  const pressure = useProjection("contextPressure");
34
42
  const running = useSession((session) => session.running);
35
43
  const [acp, setAcp] = useState<AcpUsage | undefined>(undefined);
44
+ const [route, setRoute] = useState<
45
+ { provider: string; model: string } | undefined
46
+ >(undefined);
36
47
  const [cold, setCold] = useState(false);
37
48
  const [pendingSession, setPendingSession] = useState<
38
49
  SessionStandardProps["sessionId"] | undefined
@@ -55,6 +66,19 @@ export function HandoffRing({
55
66
  };
56
67
  }, [sessionId, running, readUsage]);
57
68
 
69
+ // The model can change between turns, so re-read it whenever a turn settles.
70
+ useEffect(() => {
71
+ if (running) return;
72
+ let live = true;
73
+ void loadRoute(sessionId).then((current) => {
74
+ if (live) setRoute(current);
75
+ });
76
+ return () => {
77
+ live = false;
78
+ };
79
+ }, [sessionId, running, loadRoute]);
80
+ const limits = resolveLimits(config, route);
81
+
58
82
  const tokens =
59
83
  pressure !== undefined && pressure.pressureTokens !== undefined
60
84
  ? pressure.pressureTokens
@@ -70,11 +94,11 @@ export function HandoffRing({
70
94
  useEffect(() => {
71
95
  setCold(false);
72
96
  if (running) return;
73
- const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
97
+ const timer = setTimeout(() => setCold(true), limits.cacheTtlMs);
74
98
  return () => clearTimeout(timer);
75
- }, [tokens, running]);
99
+ }, [tokens, running, limits.cacheTtlMs]);
76
100
 
77
- const level = handoffLevel(tokens, window, cold);
101
+ const level = handoffLevel(tokens, window, cold, limits);
78
102
  if (level === "none" || tokens === undefined) return null;
79
103
  const k = Math.round(tokens / 1000);
80
104
  const pending = pendingSession === sessionId;
package/src/index.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  CommandInvocation,
8
8
  CommandResult,
9
9
  } from "@deepseek-ai/dsh-commands";
10
+ import type {} from "@deepseek-ai/dsh-host-webserver";
10
11
  import { createUserMessage } from "@deepseek-ai/dsh-llm";
11
12
  import type {} from "@deepseek-ai/dsh-session";
12
13
  import type { SessionId } from "@deepseek-ai/dsh-session/types";
@@ -14,6 +15,7 @@ import type { SessionLogSnapshot } from "@deepseek-ai/dsh-session-query";
14
15
  import type {} from "@deepseek-ai/dsh-session-title";
15
16
  import type {} from "@deepseek-ai/dsh-working-directory";
16
17
  import type { Workspace } from "@deepseek-ai/dsh-workspace";
18
+ import Schema from "@deepseek-ai/schemastery";
17
19
  import { scratchDirectory } from "@lukstei/dsh-scratch-dir";
18
20
  import {
19
21
  handoffInstruction,
@@ -21,6 +23,11 @@ import {
21
23
  renderHandoff,
22
24
  } from "./handoff.ts";
23
25
  import { formatLaunchResult } from "./launch.ts";
26
+ import {
27
+ CONFIG_GLOBAL,
28
+ type LimitOverride,
29
+ type LimitsConfig,
30
+ } from "./limits.ts";
24
31
 
25
32
  export const name = "session-handoff";
26
33
  export const inject = [
@@ -31,13 +38,40 @@ export const inject = [
31
38
  "sessionTitle",
32
39
  "workspaceRegistry",
33
40
  "llm",
41
+ "webServer",
34
42
  ];
35
43
 
36
44
  const HANDOFF_FILE = "HANDOFF.md";
37
45
  const SHORT_ID_LENGTH = 8;
38
46
  const RESUMED_SUFFIX = " (Resumed)";
39
47
 
40
- export function apply(ctx: Context): void {
48
+ const tokens = (what: string) =>
49
+ Schema.natural().description(`${what} (tokens).`);
50
+
51
+ const limitOverride: Schema<LimitOverride> = Schema.object({
52
+ warmSoft: tokens("Warm cache: context size that shows the amber ring"),
53
+ warmStrong: tokens("Warm cache: context size that shows the red ring"),
54
+ coldSoft: tokens("Cold cache: context size that shows the amber ring"),
55
+ coldStrong: tokens("Cold cache: context size that shows the red ring"),
56
+ cacheTtlMs: Schema.natural().description(
57
+ "Idle milliseconds after which the provider's prompt cache counts as cold.",
58
+ ),
59
+ });
60
+
61
+ export const Config: Schema<LimitsConfig> = Schema.object({
62
+ defaults: limitOverride.description("Applies to every model."),
63
+ providers: Schema.dict(limitOverride).description(
64
+ "Per provider id; overrides `defaults`.",
65
+ ),
66
+ models: Schema.dict(limitOverride).description(
67
+ 'Per "provider/model"; overrides `providers`.',
68
+ ),
69
+ });
70
+
71
+ export function apply(ctx: Context, config: LimitsConfig): void {
72
+ ctx.on("webserver/index-inject", (table) => {
73
+ table.push({ kind: "global", name: CONFIG_GLOBAL, value: config });
74
+ });
41
75
  ctx.commands.register({
42
76
  name: "handoff",
43
77
  description:
package/src/limits.ts ADDED
@@ -0,0 +1,79 @@
1
+ /** Token bars at which the ring suggests a handoff. */
2
+ export interface Bars {
3
+ readonly soft: number;
4
+ readonly strong: number;
5
+ }
6
+
7
+ export interface Limits {
8
+ readonly warm: Bars;
9
+ /** Bars once the prompt cache has expired; lower, since the next turn re-writes the context. */
10
+ readonly cold: Bars;
11
+ /** Idle time after which the provider's prompt cache is considered cold. */
12
+ readonly cacheTtlMs: number;
13
+ }
14
+
15
+ /** Flat, all-optional overrides; unset fields fall through to the next level. */
16
+ export interface LimitOverride {
17
+ warmSoft?: number;
18
+ warmStrong?: number;
19
+ coldSoft?: number;
20
+ coldStrong?: number;
21
+ cacheTtlMs?: number;
22
+ }
23
+
24
+ export interface LimitsConfig {
25
+ /** Applies to every model. */
26
+ defaults?: LimitOverride;
27
+ /** Keyed by provider id. */
28
+ providers?: Record<string, LimitOverride>;
29
+ /** Keyed by `provider/model`; wins over the provider entry. */
30
+ models?: Record<string, LimitOverride>;
31
+ }
32
+
33
+ // Absolute prompt sizes, tuned by cost: a fresh session starts near 18k tokens, so a handoff
34
+ // pays back sooner the more context a turn re-sends. Anthropic's cache TTL is 5 minutes.
35
+ export const BUILTIN_LIMITS: Limits = {
36
+ warm: { soft: 100_000, strong: 150_000 },
37
+ cold: { soft: 70_000, strong: 100_000 },
38
+ cacheTtlMs: 5 * 60_000,
39
+ };
40
+
41
+ /** Precedence: `models["provider/model"]`, then `providers[provider]`, then `defaults`, then the built-ins. */
42
+ export function resolveLimits(
43
+ config: LimitsConfig,
44
+ route: { provider: string; model: string } | undefined,
45
+ ): Limits {
46
+ const layers: (LimitOverride | undefined)[] = [
47
+ config.defaults,
48
+ route === undefined || config.providers === undefined
49
+ ? undefined
50
+ : config.providers[route.provider],
51
+ route === undefined || config.models === undefined
52
+ ? undefined
53
+ : config.models[`${route.provider}/${route.model}`],
54
+ ];
55
+ const pick = <K extends keyof LimitOverride>(
56
+ key: K,
57
+ fallback: number,
58
+ ): number => {
59
+ let value = fallback;
60
+ for (const layer of layers) {
61
+ if (layer !== undefined && layer[key] !== undefined) value = layer[key];
62
+ }
63
+ return value;
64
+ };
65
+ return {
66
+ warm: {
67
+ soft: pick("warmSoft", BUILTIN_LIMITS.warm.soft),
68
+ strong: pick("warmStrong", BUILTIN_LIMITS.warm.strong),
69
+ },
70
+ cold: {
71
+ soft: pick("coldSoft", BUILTIN_LIMITS.cold.soft),
72
+ strong: pick("coldStrong", BUILTIN_LIMITS.cold.strong),
73
+ },
74
+ cacheTtlMs: pick("cacheTtlMs", BUILTIN_LIMITS.cacheTtlMs),
75
+ };
76
+ }
77
+
78
+ /** Name of the page global the Host fills with the validated config. */
79
+ export const CONFIG_GLOBAL = "__DSH_SESSION_HANDOFF_CONFIG__";