@lukstei/dsh-session-handoff 0.2.2-rc.5.10 → 0.2.2-rc.5.12

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
@@ -112,7 +112,7 @@ The client opens the pane. Without the client bundle the session is created but
112
112
  | --- | --- |
113
113
  | Header | session id, `chain` of ancestor ids (when handed off before), cwd, creation time, event and turn counts across the chain |
114
114
  | `## Goal` | first real user prompt of the oldest ancestor, head 500 + tail 300 chars |
115
- | `## Turns` | one `### T<n> [end reason]` block per turn, numbered across the chain, handoff turns skipped. Last 5 turns quote each 1200 head + 400 tail chars; the 30 before them flatten to the ask (500/300) and reply (240 chars); older ones collapse to `… N earlier turns omitted` |
115
+ | `## Turns` | one `### T<n> [end reason]` block per turn, numbered across the chain, handoff turns skipped. each turn labels `**User:**` and `**Assistant:**`; the last turn quotes every user message and the reply in full (capped at 20,000 chars); the 4 before it quote 1200 head + 400 tail chars; the 30 before them flatten to the ask (500/300) and reply (240 chars); every cut is marked `[N chars omitted]`; older ones collapse to `… N earlier turns omitted` |
116
116
  | `## Failures` | newest 20 `tool/result` errors: turn, session id when from an ancestor, tool name, reason (200 chars), plus `… N older failures omitted` |
117
117
  | `## Artifacts` | deduped paths from tool call arguments (`path`, `file_path`, `filePath`, `notebook_path`) across the chain, newest 100, plus `… N older paths omitted`; the brief files themselves are excluded |
118
118
 
@@ -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
  /**
@@ -17,6 +18,9 @@ const TOOL_NAME_LIMIT = 80;
17
18
  const RECENT_TURNS = 5;
18
19
  const RECENT_HEAD = 1200;
19
20
  const RECENT_TAIL = 400;
21
+ /** The last turn is quoted in full up to this cap, split head/tail like the others. */
22
+ const LAST_HEAD = 15e3;
23
+ const LAST_TAIL = 5e3;
20
24
  const FAILURE_MAX = 20;
21
25
  const ARTIFACT_MAX = 100;
22
26
  const SHORT_ID_LENGTH$1 = 8;
@@ -66,7 +70,7 @@ function renderHandoff(snapshots) {
66
70
  turn: event.data.turn,
67
71
  sessionId,
68
72
  index: 0,
69
- ask: "",
73
+ asks: [],
70
74
  outcome: "",
71
75
  reason: void 0,
72
76
  isHandoff: false
@@ -88,7 +92,7 @@ function renderHandoff(snapshots) {
88
92
  break;
89
93
  }
90
94
  if (goal === "") goal = elide(flatten(text), ASK_HEAD, ASK_TAIL);
91
- if (open !== void 0 && open.ask === "") open.ask = text;
95
+ if (open !== void 0) open.asks.push(text);
92
96
  break;
93
97
  }
94
98
  case "assistant/message": {
@@ -173,11 +177,11 @@ function handoffInstruction(sessionId, file) {
173
177
  "Do not start the work until the user confirms the next action."
174
178
  ].join("\n");
175
179
  }
176
- /** Last RECENT_TURNS turns quoted at length, OLDER_TURNS before them flattened, the rest counted. */
180
+ /** The last turn in full, RECENT_TURNS before it at length, OLDER_TURNS before those flattened, the rest counted. */
177
181
  function turnList(work) {
178
182
  const kept = work.slice(-35);
179
183
  const dropped = work.length - kept.length;
180
- const blocks = kept.map((turn, index) => turnBlock(turn, index >= kept.length - RECENT_TURNS));
184
+ const blocks = kept.map((turn, index) => turnBlock(turn, index === kept.length - 1 ? "last" : index >= kept.length - RECENT_TURNS ? "recent" : "older"));
181
185
  if (dropped > 0) blocks.unshift(`… ${dropped} earlier turns omitted`);
182
186
  return blocks.join("\n\n");
183
187
  }
@@ -190,11 +194,17 @@ function bounded(lines, max, noun) {
190
194
  function shortId$1(id) {
191
195
  return id.slice(0, SHORT_ID_LENGTH$1);
192
196
  }
193
- /** Recent turns quote the ask and reply at length; older turns are flattened and short. */
194
- function turnBlock(turn, recent) {
197
+ /**
198
+ * The last turn quotes every user message and the reply in full, recent turns quote the first
199
+ * ask and the reply at length, older turns are flattened and short. Roles are labelled so an
200
+ * unanswered ask is never mistaken for a reply.
201
+ */
202
+ function turnBlock(turn, tier) {
195
203
  const kind = turn.reason === void 0 ? "unfinished" : turn.reason.kind;
196
- const body = (recent ? [elide(turn.ask, RECENT_HEAD, RECENT_TAIL), elide(turn.outcome, RECENT_HEAD, RECENT_TAIL)] : [elide(flatten(turn.ask), ASK_HEAD, ASK_TAIL), clip(turn.outcome, OUTCOME_LIMIT)]).filter((part) => part !== "").join("\n\n");
197
- return `### T${turn.index} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
204
+ const quote = (text) => tier === "last" ? elide(text, LAST_HEAD, LAST_TAIL) : elide(text, RECENT_HEAD, RECENT_TAIL);
205
+ const user = (tier === "last" ? turn.asks : turn.asks.slice(0, 1)).map((ask) => tier === "older" ? `**User:** ${elide(flatten(ask), ASK_HEAD, ASK_TAIL)}` : `**User:**\n\n${quote(ask)}`);
206
+ const reply = turn.outcome.trim() === "" ? "**Assistant:** (no reply)" : tier === "older" ? `**Assistant:** ${clip(turn.outcome, OUTCOME_LIMIT)}` : `**Assistant:**\n\n${quote(turn.outcome)}`;
207
+ return `### T${turn.index} [${kind}]\n\n${[...user, reply].join("\n\n")}`;
198
208
  }
199
209
  function blockText(blocks) {
200
210
  const parts = [];
@@ -205,7 +215,7 @@ function blockText(blocks) {
205
215
  function clip(value, limit) {
206
216
  const flat = flatten(value);
207
217
  if (flat.length <= limit) return flat;
208
- return `${flat.slice(0, limit - 1)}…`;
218
+ return `${flat.slice(0, limit)} … [${flat.length - limit} chars omitted]`;
209
219
  }
210
220
  function flatten(value) {
211
221
  return value.replace(/\s+/g, " ").trim();
@@ -252,6 +262,9 @@ const LAUNCH_PREFIX = "Handoff launched: ";
252
262
  function formatLaunchResult(sessionId) {
253
263
  return `${LAUNCH_PREFIX}${String(sessionId)}`;
254
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__";
255
268
  // src/index.ts
256
269
  const name = "session-handoff";
257
270
  const inject = [
@@ -261,12 +274,33 @@ const inject = [
261
274
  "sessionController",
262
275
  "sessionTitle",
263
276
  "workspaceRegistry",
264
- "llm"
277
+ "llm",
278
+ "webServer"
265
279
  ];
266
280
  const HANDOFF_FILE = "HANDOFF.md";
267
281
  const SHORT_ID_LENGTH = 8;
268
282
  const RESUMED_SUFFIX = " (Resumed)";
269
- 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
+ });
270
304
  ctx.commands.register({
271
305
  name: "handoff",
272
306
  description: "Hand this session off to a new one (bare: pick the model from a list)",
@@ -451,4 +485,4 @@ async function createBeside(ctx, source, targetId, markdown, snapshot, signal, m
451
485
  await deliver(ctx, agent, targetId, markdown);
452
486
  return created;
453
487
  }
454
- 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.10",
3
+ "version": "0.2.2-rc.5.12",
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.10"
47
+ "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.12"
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.10",
94
+ "@lukstei/dsh-client-split-view": "0.2.2-rc.5.12",
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/handoff.ts CHANGED
@@ -16,6 +16,9 @@ const TOOL_NAME_LIMIT = 80;
16
16
  const RECENT_TURNS = 5;
17
17
  const RECENT_HEAD = 1200;
18
18
  const RECENT_TAIL = 400;
19
+ /** The last turn is quoted in full up to this cap, split head/tail like the others. */
20
+ const LAST_HEAD = 15000;
21
+ const LAST_TAIL = 5000;
19
22
  /**
20
23
  * Bounds that keep a brief small however long the handoff chain is: each section
21
24
  * keeps only its newest entries and names how many it dropped.
@@ -41,7 +44,8 @@ interface TurnArc {
41
44
  readonly sessionId: string;
42
45
  /** Running number across the whole chain; assigned after collection. */
43
46
  index: number;
44
- ask: string;
47
+ /** Every user message of the turn, in order. */
48
+ asks: string[];
45
49
  outcome: string;
46
50
  reason: TurnEndReason | undefined;
47
51
  /** The turn only read a parent brief; it carries no work of its own. */
@@ -102,7 +106,7 @@ export function renderHandoff(
102
106
  turn: event.data.turn,
103
107
  sessionId,
104
108
  index: 0,
105
- ask: "",
109
+ asks: [],
106
110
  outcome: "",
107
111
  reason: undefined,
108
112
  isHandoff: false,
@@ -128,7 +132,7 @@ export function renderHandoff(
128
132
  break;
129
133
  }
130
134
  if (goal === "") goal = elide(flatten(text), ASK_HEAD, ASK_TAIL);
131
- if (open !== undefined && open.ask === "") open.ask = text;
135
+ if (open !== undefined) open.asks.push(text);
132
136
  break;
133
137
  }
134
138
  case "assistant/message": {
@@ -239,12 +243,19 @@ export function handoffInstruction(sessionId: string, file: string): string {
239
243
  ].join("\n");
240
244
  }
241
245
 
242
- /** Last RECENT_TURNS turns quoted at length, OLDER_TURNS before them flattened, the rest counted. */
246
+ /** The last turn in full, RECENT_TURNS before it at length, OLDER_TURNS before those flattened, the rest counted. */
243
247
  function turnList(work: readonly TurnArc[]): string {
244
248
  const kept = work.slice(-(RECENT_TURNS + OLDER_TURNS));
245
249
  const dropped = work.length - kept.length;
246
250
  const blocks = kept.map((turn, index) =>
247
- turnBlock(turn, index >= kept.length - RECENT_TURNS),
251
+ turnBlock(
252
+ turn,
253
+ index === kept.length - 1
254
+ ? "last"
255
+ : index >= kept.length - RECENT_TURNS
256
+ ? "recent"
257
+ : "older",
258
+ ),
248
259
  );
249
260
  if (dropped > 0) blocks.unshift(`… ${dropped} earlier turns omitted`);
250
261
  return blocks.join("\n\n");
@@ -261,23 +272,30 @@ function shortId(id: string): string {
261
272
  return id.slice(0, SHORT_ID_LENGTH);
262
273
  }
263
274
 
264
- /** Recent turns quote the ask and reply at length; older turns are flattened and short. */
265
- function turnBlock(turn: TurnArc, recent: boolean): string {
275
+ /**
276
+ * The last turn quotes every user message and the reply in full, recent turns quote the first
277
+ * ask and the reply at length, older turns are flattened and short. Roles are labelled so an
278
+ * unanswered ask is never mistaken for a reply.
279
+ */
280
+ function turnBlock(turn: TurnArc, tier: "last" | "recent" | "older"): string {
266
281
  const kind = turn.reason === undefined ? "unfinished" : turn.reason.kind;
267
- const body = (
268
- recent
269
- ? [
270
- elide(turn.ask, RECENT_HEAD, RECENT_TAIL),
271
- elide(turn.outcome, RECENT_HEAD, RECENT_TAIL),
272
- ]
273
- : [
274
- elide(flatten(turn.ask), ASK_HEAD, ASK_TAIL),
275
- clip(turn.outcome, OUTCOME_LIMIT),
276
- ]
277
- )
278
- .filter((part) => part !== "")
279
- .join("\n\n");
280
- return `### T${turn.index} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
282
+ const quote = (text: string): string =>
283
+ tier === "last"
284
+ ? elide(text, LAST_HEAD, LAST_TAIL)
285
+ : elide(text, RECENT_HEAD, RECENT_TAIL);
286
+ const asks = tier === "last" ? turn.asks : turn.asks.slice(0, 1);
287
+ const user = asks.map((ask) =>
288
+ tier === "older"
289
+ ? `**User:** ${elide(flatten(ask), ASK_HEAD, ASK_TAIL)}`
290
+ : `**User:**\n\n${quote(ask)}`,
291
+ );
292
+ const reply =
293
+ turn.outcome.trim() === ""
294
+ ? "**Assistant:** (no reply)"
295
+ : tier === "older"
296
+ ? `**Assistant:** ${clip(turn.outcome, OUTCOME_LIMIT)}`
297
+ : `**Assistant:**\n\n${quote(turn.outcome)}`;
298
+ return `### T${turn.index} [${kind}]\n\n${[...user, reply].join("\n\n")}`;
281
299
  }
282
300
 
283
301
  function blockText(blocks: readonly ContentBlock[]): string {
@@ -292,7 +310,7 @@ function blockText(blocks: readonly ContentBlock[]): string {
292
310
  function clip(value: string, limit: number): string {
293
311
  const flat = flatten(value);
294
312
  if (flat.length <= limit) return flat;
295
- return `${flat.slice(0, limit - 1)}…`;
313
+ return `${flat.slice(0, limit)} … [${flat.length - limit} chars omitted]`;
296
314
  }
297
315
 
298
316
  function flatten(value: string): string {
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__";