@lukstei/dsh-session-handoff 0.2.2-rc.5.6 → 0.2.2-rc.5.8

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
@@ -76,7 +76,7 @@ Server-side and client-side entries.
76
76
 
77
77
  ### Handoff ring
78
78
 
79
- A small ring beside the send button marks a session worth handing off: yellow at 70k prompt tokens, red at 100k. After 5 idle minutes the prompt cache is cold and the bars drop to 40k and 70k. Both bars are also capped at 60% and 80% of the model's context window. For ACP agent sessions, which never report usage to DSH, it reads the agent's context usage from `@zaimokuza/dsh-acp-adapter` once per finished turn. The adapter is an optional peer dependency: without it the ring only covers regular DSH sessions. Display only; run `/handoff` yourself. Thresholds live in `src/client/level.ts`.
79
+ A small gauge button beside the send button marks a session worth handing off: yellow at 100k prompt tokens, red at 150k. After 5 idle minutes the prompt cache is cold and the bars drop to 70k and 100k. Both bars are also capped at 60% and 80% of the model's context window. For ACP agent sessions, which never report usage to DSH, it reads the agent's context usage from `@zaimokuza/dsh-acp-adapter` once per finished turn. The adapter is an optional peer dependency: without it the ring only covers regular DSH sessions. Clicking the button runs `/handoff` directly; it is disabled while a turn is running or a handoff is in flight. Thresholds live in `src/client/level.ts`.
80
80
 
81
81
  Code import (no mount): [`@lukstei/dsh-scratch-dir`](../dsh-scratch-dir/README.md) (`scratchDirectory`).
82
82
 
@@ -108,11 +108,13 @@ The client opens the pane. Without the client bundle the session is created but
108
108
 
109
109
  | Section | Contents |
110
110
  | --- | --- |
111
- | Header | session id, cwd, creation time, event and turn counts |
112
- | `## Goal` | first user prompt, head 500 + tail 300 chars |
113
- | `## Turns` | one `### T<n> [end reason]` block per turn: ask and final reply. Last 5 turns quote each 1200 head + 400 tail chars; older turns flatten to the ask (500/300) and reply (240 chars) |
114
- | `## Failures` | every `tool/result` with `isError`: turn, tool name, reason (200 chars) |
115
- | `## Artifacts` | deduped paths from tool call arguments (`path`, `file_path`, `filePath`, `notebook_path`), max 12 |
111
+ | Header | session id, `chain` of ancestor ids (when handed off before), cwd, creation time, event and turn counts across the chain |
112
+ | `## Goal` | first real user prompt of the oldest ancestor, head 500 + tail 300 chars |
113
+ | `## 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` |
114
+ | `## Failures` | newest 20 `tool/result` errors: turn, session id when from an ancestor, tool name, reason (200 chars), plus `… N older failures omitted` |
115
+ | `## 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 |
116
+
117
+ Every section is bounded by entry count and per-line length (paths 300 chars, tool names 80), so a brief stays near 50k characters however many times a session is handed off.
116
118
 
117
119
  Empty sections render `none`. Output is deterministic for a given log. `request/header`, `agent/inbox/spliced` and reasoning blocks are excluded.
118
120
 
@@ -141,6 +143,7 @@ Details:
141
143
  - A session created by `cwd` alone is attached to no workspace and stays out of the sidebar tree until the next Host start, so the workspace id is used when available.
142
144
  - Turn attribution: `user/message` carries no turn number, so it is attributed to the most recently opened turn.
143
145
  - Artifact extraction parses tool arguments as JSON; non-JSON payloads are ignored.
146
+ - Handoff chain: a handed-off session starts with the follow-up "The handoff brief for session <id> is at <file>." `readChain` follows that id back through `sessionQuery.readSession` (cycle-guarded; a deleted parent ends the walk) and `renderHandoff` merges the logs oldest first. The follow-up turn and the read of its brief file add no Goal, Turn or Artifact.
144
147
  - The scratch path comes from `scratchDirectory()`; an unsafe id throws and the command returns an error.
145
148
 
146
149
  Trust boundary: the session id argument and session log contents are untrusted text; output is markdown written under the scratch directory only.
package/dist/client.js CHANGED
@@ -65,6 +65,7 @@ window.__ModuleLoader__.load({
65
65
  const running = useSession((session) => session.running);
66
66
  const [acp, setAcp] = (0, react.useState)(void 0);
67
67
  const [cold, setCold] = (0, react.useState)(false);
68
+ const [pendingSession, setPendingSession] = (0, react.useState)(void 0);
68
69
  const readUsage = (0, react.useSyncExternalStore)(subscribeAcpUsageReader, currentAcpUsageReader);
69
70
  (0, react.useEffect)(() => {
70
71
  if (running || readUsage === void 0) return;
@@ -90,14 +91,31 @@ window.__ModuleLoader__.load({
90
91
  }, [tokens, running]);
91
92
  const level = handoffLevel(tokens, window, cold);
92
93
  if (level === "none" || tokens === void 0) return null;
93
- const label = `Context ${Math.round(tokens / 1e3)}k tokens: ${cold ? "cache is cold, a fresh session is cheaper now" : "consider a fresh session"}. Click to hand off (/handoff)`;
94
+ const k = Math.round(tokens / 1e3);
95
+ const pending = pendingSession === sessionId;
96
+ const isDisabled = running || pending;
97
+ const startHandoff = async () => {
98
+ if (isDisabled) return;
99
+ setPendingSession(sessionId);
100
+ try {
101
+ await onHandoff(sessionId);
102
+ } catch (error) {
103
+ console.error("session-handoff: handoff failed", error);
104
+ } finally {
105
+ setPendingSession((current) => current === sessionId ? void 0 : current);
106
+ }
107
+ };
108
+ const label = `Context ${k}k tokens: ${cold ? "cache is cold, a fresh session is cheaper now" : "consider a fresh session"}. ${pending ? "Handing off…" : running ? "Wait for the current turn to finish to hand off (/handoff)" : "Click to hand off (/handoff)"}`;
94
109
  return (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
95
110
  label,
96
111
  side: "top",
97
112
  portal: true,
113
+ disabled: isDisabled,
98
114
  children: (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Button, {
99
115
  variant: "ghost",
100
116
  size: "sm",
117
+ disabled: isDisabled,
118
+ title: isDisabled ? label : void 0,
101
119
  "aria-label": label,
102
120
  style: {
103
121
  color: COLOR[level],
@@ -105,7 +123,7 @@ window.__ModuleLoader__.load({
105
123
  width: 28
106
124
  },
107
125
  icon: (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.IconGaugeOutlineMedium, { size: 16 }),
108
- onClick: () => void onHandoff(sessionId)
126
+ onClick: () => void startHandoff()
109
127
  })
110
128
  });
111
129
  }
@@ -139,7 +157,8 @@ window.__ModuleLoader__.load({
139
157
  };
140
158
  const handoff = async (id) => {
141
159
  await sessions.using(id, { source: "splitView" }, async (reference) => {
142
- await reference.binding.session.command("/handoff");
160
+ const result = await reference.binding.session.command("/handoff");
161
+ if (!result.ok) console.warn("session-handoff: /handoff failed", result);
143
162
  });
144
163
  };
145
164
  const watch = (id) => {
package/dist/index.js ADDED
@@ -0,0 +1,434 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
4
+ import { scratchDirectory } from "@lukstei/dsh-scratch-dir";
5
+ // src/handoff.ts
6
+ /**
7
+ * Bounds on quoted text. The Goal and older turns quote a head and a tail of the user's
8
+ * ask; the last RECENT_TURNS use a larger budget so the receiving agent still reads the
9
+ * actual words.
10
+ */
11
+ const ASK_HEAD = 500;
12
+ const ASK_TAIL = 300;
13
+ const OUTCOME_LIMIT = 240;
14
+ const FAILURE_LIMIT = 200;
15
+ const PATH_LIMIT = 300;
16
+ const TOOL_NAME_LIMIT = 80;
17
+ const RECENT_TURNS = 5;
18
+ const RECENT_HEAD = 1200;
19
+ const RECENT_TAIL = 400;
20
+ const FAILURE_MAX = 20;
21
+ const ARTIFACT_MAX = 100;
22
+ const SHORT_ID_LENGTH$1 = 8;
23
+ /** Tool argument keys that carry a durable file path. */
24
+ const PATH_KEYS = [
25
+ "path",
26
+ "file_path",
27
+ "filePath",
28
+ "notebook_path"
29
+ ];
30
+ /** The first line of every handoff follow-up; names the parent session and its brief. */
31
+ const INSTRUCTION_LINE = /^The handoff brief for session (\S+) is at (.+)\.$/;
32
+ /**
33
+ * Id of the session whose brief this session was started from, read from the
34
+ * handoff follow-up it received.
35
+ */
36
+ function parentSessionId(snapshot) {
37
+ for (const event of snapshot.events) {
38
+ if (event.type !== "user/message" || event.data.source.kind !== "user") continue;
39
+ const text = blockText(event.data.content);
40
+ if (text === "") continue;
41
+ const match = INSTRUCTION_LINE.exec(text.split("\n", 1)[0]);
42
+ return match === null ? void 0 : match[1];
43
+ }
44
+ }
45
+ /**
46
+ * Renders one brief for a handoff chain.
47
+ * @param snapshots - Session logs, oldest ancestor first, the handed-off session last.
48
+ */
49
+ function renderHandoff(snapshots) {
50
+ const turns = [];
51
+ const failures = [];
52
+ const artifacts = /* @__PURE__ */ new Map();
53
+ const briefFiles = /* @__PURE__ */ new Set();
54
+ let goal = "";
55
+ let eventCount = 0;
56
+ for (const snapshot of snapshots) {
57
+ const sessionId = String(snapshot.session.id);
58
+ const byId = /* @__PURE__ */ new Map();
59
+ const callNames = /* @__PURE__ */ new Map();
60
+ let open;
61
+ let sawUserMessage = false;
62
+ eventCount += snapshot.events.length;
63
+ for (const event of snapshot.events) switch (event.type) {
64
+ case "turn/start": {
65
+ const opened = {
66
+ turn: event.data.turn,
67
+ sessionId,
68
+ index: 0,
69
+ ask: "",
70
+ outcome: "",
71
+ reason: void 0,
72
+ isHandoff: false
73
+ };
74
+ turns.push(opened);
75
+ byId.set(event.data.turn, opened);
76
+ open = opened;
77
+ break;
78
+ }
79
+ case "user/message": {
80
+ if (event.data.source.kind !== "user") break;
81
+ const text = blockText(event.data.content);
82
+ if (text === "") break;
83
+ const instruction = sawUserMessage ? null : INSTRUCTION_LINE.exec(text.split("\n", 1)[0]);
84
+ sawUserMessage = true;
85
+ if (instruction !== null) {
86
+ briefFiles.add(instruction[2]);
87
+ if (open !== void 0) open.isHandoff = true;
88
+ break;
89
+ }
90
+ if (goal === "") goal = elide(flatten(text), ASK_HEAD, ASK_TAIL);
91
+ if (open !== void 0 && open.ask === "") open.ask = text;
92
+ break;
93
+ }
94
+ case "assistant/message": {
95
+ const arc = byId.get(event.data.turn);
96
+ if (arc === void 0) break;
97
+ arc.outcome = blockText(event.data.message.content);
98
+ break;
99
+ }
100
+ case "turn/end": {
101
+ const arc = byId.get(event.data.turn);
102
+ if (arc === void 0) break;
103
+ arc.reason = event.data.reason;
104
+ break;
105
+ }
106
+ case "tool/call": {
107
+ const arc = byId.get(event.data.turn);
108
+ callNames.set(event.data.callId, event.data.name);
109
+ if (arc === void 0 || arc.isHandoff) break;
110
+ collectArtifacts(event.data.arguments, artifacts, briefFiles);
111
+ break;
112
+ }
113
+ case "tool/result": {
114
+ const arc = byId.get(event.data.turn);
115
+ if (event.data.message.isError !== true || arc === void 0) break;
116
+ if (arc.isHandoff) break;
117
+ const callId = event.data.message.toolCallId;
118
+ const name = callNames.get(callId);
119
+ failures.push({
120
+ arc,
121
+ text: `tool \`${clip(name === void 0 ? callId : name, TOOL_NAME_LIMIT)}\`: ${clip(errorReason(event.data.error), FAILURE_LIMIT)}`
122
+ });
123
+ break;
124
+ }
125
+ }
126
+ }
127
+ const work = turns.filter((turn) => !turn.isHandoff);
128
+ work.forEach((turn, index) => {
129
+ turn.index = index + 1;
130
+ });
131
+ const current = snapshots[snapshots.length - 1];
132
+ const id = String(current.session.id);
133
+ const cwd = current.session.cwd;
134
+ return {
135
+ markdown: `${[
136
+ `# Handoff — ${id}`,
137
+ "",
138
+ `- session: \`${id}\``,
139
+ ...snapshots.length > 1 ? [`- chain: ${snapshots.map((snapshot) => `\`${shortId$1(String(snapshot.session.id))}\``).join(" → ")}`] : [],
140
+ `- cwd: \`${cwd === void 0 ? "unknown" : cwd}\``,
141
+ `- created: ${new Date(current.session.createdAt).toISOString()}`,
142
+ `- events: ${eventCount}`,
143
+ `- turns: ${work.length}`,
144
+ "",
145
+ "## Goal",
146
+ "",
147
+ goal === "" ? "none" : goal,
148
+ "",
149
+ "## Turns",
150
+ "",
151
+ work.length === 0 ? "none" : turnList(work),
152
+ "",
153
+ "## Failures",
154
+ "",
155
+ failures.length === 0 ? "none" : bounded(failures.map(({ arc, text }) => `- **T${arc.index}**${arc.sessionId === id ? "" : ` (${shortId$1(arc.sessionId)})`} ${text}`), FAILURE_MAX, "older failures"),
156
+ "",
157
+ "## Artifacts",
158
+ "",
159
+ artifacts.size === 0 ? "none" : bounded([...artifacts.keys()].map((file) => `- \`${file}\``), ARTIFACT_MAX, "older paths")
160
+ ].join("\n")}\n`,
161
+ turns: work.length
162
+ };
163
+ }
164
+ function handoffInstruction(sessionId, file) {
165
+ return [
166
+ `The handoff brief for session ${sessionId} is at ${file}.`,
167
+ "",
168
+ "Read that file now, then reply with three lines and stop:",
169
+ "Goal: <one line>",
170
+ "State: <one line>",
171
+ "Next: <one line>",
172
+ "",
173
+ "Do not start the work until the user confirms the next action."
174
+ ].join("\n");
175
+ }
176
+ /** Last RECENT_TURNS turns quoted at length, OLDER_TURNS before them flattened, the rest counted. */
177
+ function turnList(work) {
178
+ const kept = work.slice(-35);
179
+ const dropped = work.length - kept.length;
180
+ const blocks = kept.map((turn, index) => turnBlock(turn, index >= kept.length - RECENT_TURNS));
181
+ if (dropped > 0) blocks.unshift(`… ${dropped} earlier turns omitted`);
182
+ return blocks.join("\n\n");
183
+ }
184
+ /** Keeps the newest `max` lines, naming how many older ones were dropped. */
185
+ function bounded(lines, max, noun) {
186
+ const dropped = lines.length - max;
187
+ if (dropped <= 0) return lines.join("\n");
188
+ return [`- … ${dropped} ${noun} omitted`, ...lines.slice(-max)].join("\n");
189
+ }
190
+ function shortId$1(id) {
191
+ return id.slice(0, SHORT_ID_LENGTH$1);
192
+ }
193
+ /** Recent turns quote the ask and reply at length; older turns are flattened and short. */
194
+ function turnBlock(turn, recent) {
195
+ 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}`;
198
+ }
199
+ function blockText(blocks) {
200
+ const parts = [];
201
+ for (const block of blocks) if (block.type === "text") parts.push(block.text);
202
+ return parts.join("\n");
203
+ }
204
+ /** Collapses whitespace so a quote fits on one line, then cuts it. */
205
+ function clip(value, limit) {
206
+ const flat = flatten(value);
207
+ if (flat.length <= limit) return flat;
208
+ return `${flat.slice(0, limit - 1)}…`;
209
+ }
210
+ function flatten(value) {
211
+ return value.replace(/\s+/g, " ").trim();
212
+ }
213
+ /**
214
+ * Keeps `head` chars from the start and `tail` chars from the end, naming how much was
215
+ * dropped. Raw text is preserved so the Tail keeps the shape of code blocks and tables.
216
+ */
217
+ function elide(value, head, tail) {
218
+ const trimmed = value.trim();
219
+ if (trimmed.length <= head + tail) return trimmed;
220
+ const omitted = trimmed.length - head - tail;
221
+ return `${trimmed.slice(0, head)} … [${omitted} chars omitted] … ${trimmed.slice(-tail)}`;
222
+ }
223
+ function errorReason(error) {
224
+ if (error === void 0) return "failed";
225
+ if (error.reason === void 0) return error.code;
226
+ return error.reason;
227
+ }
228
+ function collectArtifacts(args, into, briefFiles) {
229
+ let parsed;
230
+ try {
231
+ parsed = JSON.parse(args);
232
+ } catch {
233
+ return;
234
+ }
235
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return;
236
+ const record = parsed;
237
+ for (const key of PATH_KEYS) {
238
+ const value = record[key];
239
+ if (typeof value !== "string" || value === "" || briefFiles.has(value)) continue;
240
+ const path = clip(value, PATH_LIMIT);
241
+ into.delete(path);
242
+ into.set(path, true);
243
+ }
244
+ }
245
+ // src/launch.ts
246
+ /**
247
+ * First line of the launch result. A slash command has no structured return
248
+ * channel, so the Host encodes the new Session id here and the client reads it
249
+ * back out of the durable `command/done` record.
250
+ */
251
+ const LAUNCH_PREFIX = "Handoff launched: ";
252
+ function formatLaunchResult(sessionId) {
253
+ return `${LAUNCH_PREFIX}${String(sessionId)}`;
254
+ }
255
+ // src/index.ts
256
+ const name = "session-handoff";
257
+ const inject = [
258
+ "commands",
259
+ "sessionQuery",
260
+ "workingDirectory",
261
+ "sessionController",
262
+ "sessionTitle",
263
+ "workspaceRegistry"
264
+ ];
265
+ const HANDOFF_FILE = "HANDOFF.md";
266
+ const RECENT_LIMIT = 5;
267
+ const SHORT_ID_LENGTH = 8;
268
+ const RESUMED_SUFFIX = " (Resumed)";
269
+ function apply(ctx) {
270
+ ctx.commands.register({
271
+ name: "handoff",
272
+ description: "Hand this session off to a new one, or write the resume brief for <session-id> into this one",
273
+ input: { hint: "[session-id]" },
274
+ handler: (invocation) => handoff(ctx, invocation)
275
+ });
276
+ }
277
+ function resolveHandoffTarget(sessions, query) {
278
+ const exact = sessions.filter((session) => String(session.header.id) === query);
279
+ if (exact.length > 0) return exact;
280
+ return sessions.filter((session) => String(session.header.id).startsWith(query));
281
+ }
282
+ async function handoff(ctx, invocation) {
283
+ const raw = invocation.rawInput.trim();
284
+ const launch = raw === "";
285
+ const agent = invocation.agent;
286
+ let targetId;
287
+ if (launch) targetId = agent.session.id;
288
+ else {
289
+ const sessions = await ctx.sessionQuery.listSessions(invocation.signal);
290
+ const matches = resolveHandoffTarget(sessions, raw);
291
+ if (matches.length === 0) return {
292
+ kind: "error",
293
+ text: `No session matches "${raw}". Most recent sessions:\n${sessions.slice(0, RECENT_LIMIT).map((session) => `- ${String(session.header.id)}`).join("\n")}`
294
+ };
295
+ if (matches.length > 1) return {
296
+ kind: "error",
297
+ text: `"${raw}" is ambiguous:\n${matches.map((session) => `- ${String(session.header.id)}`).join("\n")}`
298
+ };
299
+ targetId = matches[0].header.id;
300
+ if (targetId === agent.session.id) return {
301
+ kind: "error",
302
+ text: "That is this session; there is nothing to hand off."
303
+ };
304
+ }
305
+ try {
306
+ const snapshot = await ctx.sessionQuery.readSession(targetId);
307
+ const rendered = renderHandoff(await readChain(ctx, snapshot, invocation.signal));
308
+ if (rendered.turns === 0) return {
309
+ kind: "error",
310
+ text: launch ? "This session has no turns to hand off." : `Session ${shortId(targetId)} has no turns to hand off.`
311
+ };
312
+ if (launch) return {
313
+ kind: "success",
314
+ text: formatLaunchResult((await createBeside(ctx, agent, targetId, rendered.markdown, snapshot, invocation.signal)).sessionId)
315
+ };
316
+ const file = await deliver(ctx, agent, targetId, rendered.markdown);
317
+ return {
318
+ kind: "success",
319
+ text: `Handoff for ${shortId(targetId)} (${rendered.turns} turns) → ${file}`
320
+ };
321
+ } catch (error) {
322
+ return {
323
+ kind: "error",
324
+ text: `Handoff failed: ${error instanceof Error ? error.message : String(error)}`
325
+ };
326
+ }
327
+ }
328
+ /**
329
+ * The handed-off session preceded by every ancestor it was itself handed off from,
330
+ * oldest first, so the brief keeps what earlier briefs summarized.
331
+ */
332
+ async function readChain(ctx, snapshot, signal) {
333
+ const chain = [snapshot];
334
+ const seen = /* @__PURE__ */ new Set([String(snapshot.session.id)]);
335
+ let parent = parentSessionId(snapshot);
336
+ if (parent === void 0) return chain;
337
+ const known = new Set((await ctx.sessionQuery.listSessions(signal)).map((session) => String(session.header.id)));
338
+ while (parent !== void 0 && !seen.has(parent) && known.has(parent)) {
339
+ seen.add(parent);
340
+ const ancestor = await ctx.sessionQuery.readSession(parent);
341
+ chain.unshift(ancestor);
342
+ parent = parentSessionId(ancestor);
343
+ }
344
+ return chain;
345
+ }
346
+ /**
347
+ * Write the brief into the agent's own scratch directory and queue the follow-up
348
+ * turn that tells it to read that file.
349
+ * @param ctx - Host context.
350
+ * @param agent - Agent that receives the brief and the follow-up.
351
+ * @param targetId - Durable id of the handed-off session.
352
+ * @param markdown - Rendered brief.
353
+ * @returns absolute path of the written brief.
354
+ */
355
+ async function deliver(ctx, agent, targetId, markdown) {
356
+ const dir = scratchDirectory(ctx.workingDirectory.get(agent.session), String(agent.session.id));
357
+ if (dir === void 0) throw new Error(`Unsafe session id "${String(agent.session.id)}"; no handoff written.`);
358
+ await mkdir(dir, { recursive: true });
359
+ const file = path.join(dir, HANDOFF_FILE);
360
+ await writeFile(file, markdown, "utf8");
361
+ agent.followup(createUserMessage({
362
+ content: [{
363
+ type: "text",
364
+ text: handoffInstruction(targetId, file)
365
+ }],
366
+ source: { kind: "user" }
367
+ }));
368
+ return file;
369
+ }
370
+ function workspaceOf(ctx, sessionId) {
371
+ for (const workspace of ctx.workspaceRegistry.list()) if (workspace.sessionIds.includes(sessionId)) return workspace;
372
+ }
373
+ function kanbanLinkArgs(snapshot) {
374
+ const all = [];
375
+ for (const event of snapshot.events) {
376
+ if (event.type !== "command/run" || event.data.name !== "kanban") continue;
377
+ const args = event.data.args;
378
+ if (args === void 0) continue;
379
+ try {
380
+ const parsed = JSON.parse(args);
381
+ if (typeof parsed === "object" && parsed !== null && "action" in parsed && parsed.action === "add-link") all.push(args);
382
+ } catch {}
383
+ }
384
+ return all;
385
+ }
386
+ function shortId(id) {
387
+ return id.slice(0, SHORT_ID_LENGTH);
388
+ }
389
+ /**
390
+ * Create the resumed session beside this one: same workspace, same preset, same
391
+ * model, the brief in its own scratch directory, and one follow-up turn that
392
+ * tells it to read that brief.
393
+ * @param ctx - Host context.
394
+ * @param source - Session the command runs in.
395
+ * @param targetId - Durable id of the handed-off session.
396
+ * @param markdown - Rendered brief.
397
+ * @param snapshot - Source session log, the origin of the kanban links to copy.
398
+ * @param signal - Cancellation signal of the invoking command.
399
+ * @returns the created session identity.
400
+ */
401
+ async function createBeside(ctx, source, targetId, markdown, snapshot, signal) {
402
+ const selection = source.model.current();
403
+ const agentPreset = source.session.header.agentPreset;
404
+ const workspace = workspaceOf(ctx, source.session.id);
405
+ const created = await ctx.sessionController.create(workspace === void 0 ? {
406
+ cwd: ctx.workingDirectory.get(source.session),
407
+ agentPreset
408
+ } : {
409
+ workspaceId: workspace.id,
410
+ agentPreset
411
+ });
412
+ const resolved = await ctx.sessionController.resolveAgent(created.sessionId);
413
+ if ("error" in resolved) throw new Error(resolved.error.message);
414
+ const agent = resolved.agent;
415
+ if (selection !== void 0) agent.model.select(selection);
416
+ const sourceTitle = ctx.sessionTitle.get(source.session);
417
+ ctx.sessionTitle.rename(agent.session, sourceTitle === void 0 ? `Handoff ${shortId(targetId)}` : sourceTitle.title);
418
+ if (sourceTitle !== void 0 && !sourceTitle.title.endsWith(RESUMED_SUFFIX)) ctx.sessionTitle.rename(source.session, `${sourceTitle.title}${RESUMED_SUFFIX}`);
419
+ await ctx.commands.execute(agent, `/kanban ${JSON.stringify({
420
+ action: "init",
421
+ createdAt: Date.now()
422
+ })}`, [], signal);
423
+ for (const args of kanbanLinkArgs(snapshot)) await ctx.commands.execute(agent, `/kanban ${args}`, [], signal);
424
+ const sourceLink = {
425
+ action: "add-link",
426
+ label: `Resumed from ${targetId}`,
427
+ url: `dsh://sessions/${targetId}`,
428
+ priority: 0
429
+ };
430
+ await ctx.commands.execute(agent, `/kanban ${JSON.stringify(sourceLink)}`, [], signal);
431
+ await deliver(ctx, agent, targetId, markdown);
432
+ return created;
433
+ }
434
+ export { apply, inject, name, resolveHandoffTarget };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lukstei/dsh-session-handoff",
3
- "version": "0.2.2-rc.5.6",
3
+ "version": "0.2.2-rc.5.8",
4
4
  "description": "Session handoff brief command for DSH",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -42,7 +42,7 @@
42
42
  }
43
43
  },
44
44
  "dependencies": {
45
- "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.6"
45
+ "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.8"
46
46
  },
47
47
  "peerDependencies": {
48
48
  "@deepseek-ai/cordis": "*",
@@ -81,7 +81,7 @@
81
81
  "@deepseek-ai/dsh-token-meter": "0.2.2-rc.5",
82
82
  "@deepseek-ai/dsh-working-directory": "0.2.2-rc.5",
83
83
  "@deepseek-ai/dsh-workspace": "0.2.2-rc.5",
84
- "@lukstei/dsh-client-split-view": "0.2.2-rc.5.6",
84
+ "@lukstei/dsh-client-split-view": "0.2.2-rc.5.8",
85
85
  "@types/node": "^26.0.0",
86
86
  "@types/react": "^19.3.0",
87
87
  "@zaimokuza/dsh-acp-adapter": "0.2.2-rc.5.2",
@@ -40,7 +40,10 @@ export function apply(ctx: Context): void {
40
40
  // Same command the user would type; sent directly so the composer draft stays untouched.
41
41
  const handoff = async (id: SessionId): Promise<void> => {
42
42
  await sessions.using(id, { source: "splitView" }, async (reference) => {
43
- await reference.binding.session.command("/handoff");
43
+ const result = await reference.binding.session.command("/handoff");
44
+ if (!result.ok) {
45
+ console.warn("session-handoff: /handoff failed", result);
46
+ }
44
47
  });
45
48
  };
46
49
 
@@ -34,6 +34,9 @@ export function HandoffRing({
34
34
  const running = useSession((session) => session.running);
35
35
  const [acp, setAcp] = useState<AcpUsage | undefined>(undefined);
36
36
  const [cold, setCold] = useState(false);
37
+ const [pendingSession, setPendingSession] = useState<
38
+ SessionStandardProps["sessionId"] | undefined
39
+ >(undefined);
37
40
 
38
41
  // ACP agents report occupancy to the adapter, never to DSH's `contextPressure`; read it
39
42
  // when a turn settles. The reader is unset (so this is a no-op) without the adapter.
@@ -74,23 +77,47 @@ export function HandoffRing({
74
77
  const level = handoffLevel(tokens, window, cold);
75
78
  if (level === "none" || tokens === undefined) return null;
76
79
  const k = Math.round(tokens / 1000);
80
+ const pending = pendingSession === sessionId;
81
+ const isDisabled = running || pending;
82
+ const startHandoff = async (): Promise<void> => {
83
+ if (isDisabled) return;
84
+ setPendingSession(sessionId);
85
+ try {
86
+ await onHandoff(sessionId);
87
+ } catch (error: unknown) {
88
+ console.error("session-handoff: handoff failed", error);
89
+ } finally {
90
+ setPendingSession((current) =>
91
+ current === sessionId ? undefined : current,
92
+ );
93
+ }
94
+ };
77
95
  const hint = cold
78
96
  ? "cache is cold, a fresh session is cheaper now"
79
97
  : "consider a fresh session";
80
- const label = `Context ${k}k tokens: ${hint}. Click to hand off (/handoff)`;
98
+ const action = pending
99
+ ? "Handing off…"
100
+ : running
101
+ ? "Wait for the current turn to finish to hand off (/handoff)"
102
+ : "Click to hand off (/handoff)";
103
+ const label = `Context ${k}k tokens: ${hint}. ${action}`;
81
104
  return createElement(Tooltip, {
82
105
  label,
83
106
  side: "top",
84
107
  portal: true,
108
+ // Disabled native buttons omit mouseleave, so close Tooltip from state.
109
+ disabled: isDisabled,
85
110
  // biome-ignore lint/correctness/noChildrenProp: Tooltip types `children` as a required prop, which createElement's 3rd argument does not satisfy
86
111
  children: createElement(Button, {
87
112
  variant: "ghost",
88
113
  size: "sm",
114
+ disabled: isDisabled,
115
+ title: isDisabled ? label : undefined,
89
116
  "aria-label": label,
90
117
  // the icon strokes with currentColor; 28px square instead of the text-button padding
91
118
  style: { color: COLOR[level], padding: 0, width: 28 },
92
119
  icon: createElement(IconGaugeOutlineMedium, { size: 16 }),
93
- onClick: () => void onHandoff(sessionId),
120
+ onClick: () => void startHandoff(),
94
121
  }),
95
122
  });
96
123
  }
package/src/handoff.ts CHANGED
@@ -11,14 +11,26 @@ const ASK_HEAD = 500;
11
11
  const ASK_TAIL = 300;
12
12
  const OUTCOME_LIMIT = 240;
13
13
  const FAILURE_LIMIT = 200;
14
- const ARTIFACT_LIMIT = 12;
14
+ const PATH_LIMIT = 300;
15
+ const TOOL_NAME_LIMIT = 80;
15
16
  const RECENT_TURNS = 5;
16
17
  const RECENT_HEAD = 1200;
17
18
  const RECENT_TAIL = 400;
19
+ /**
20
+ * Bounds that keep a brief small however long the handoff chain is: each section
21
+ * keeps only its newest entries and names how many it dropped.
22
+ */
23
+ const OLDER_TURNS = 30;
24
+ const FAILURE_MAX = 20;
25
+ const ARTIFACT_MAX = 100;
26
+ const SHORT_ID_LENGTH = 8;
18
27
 
19
28
  /** Tool argument keys that carry a durable file path. */
20
29
  const PATH_KEYS = ["path", "file_path", "filePath", "notebook_path"];
21
30
 
31
+ /** The first line of every handoff follow-up; names the parent session and its brief. */
32
+ const INSTRUCTION_LINE = /^The handoff brief for session (\S+) is at (.+)\.$/;
33
+
22
34
  export interface RenderedHandoff {
23
35
  readonly markdown: string;
24
36
  readonly turns: number;
@@ -26,90 +38,158 @@ export interface RenderedHandoff {
26
38
 
27
39
  interface TurnArc {
28
40
  readonly turn: number;
41
+ readonly sessionId: string;
42
+ /** Running number across the whole chain; assigned after collection. */
43
+ index: number;
29
44
  ask: string;
30
45
  outcome: string;
31
46
  reason: TurnEndReason | undefined;
47
+ /** The turn only read a parent brief; it carries no work of its own. */
48
+ isHandoff: boolean;
49
+ }
50
+
51
+ interface Failure {
52
+ readonly arc: TurnArc;
53
+ readonly text: string;
54
+ }
55
+
56
+ /**
57
+ * Id of the session whose brief this session was started from, read from the
58
+ * handoff follow-up it received.
59
+ */
60
+ export function parentSessionId(
61
+ snapshot: SessionLogSnapshot,
62
+ ): string | undefined {
63
+ for (const event of snapshot.events) {
64
+ if (event.type !== "user/message" || event.data.source.kind !== "user")
65
+ continue;
66
+ const text = blockText(event.data.content);
67
+ if (text === "") continue;
68
+ // Only the session's first user message can be the handoff follow-up.
69
+ const match = INSTRUCTION_LINE.exec(text.split("\n", 1)[0]);
70
+ return match === null ? undefined : match[1];
71
+ }
72
+ return undefined;
32
73
  }
33
74
 
34
- export function renderHandoff(snapshot: SessionLogSnapshot): RenderedHandoff {
75
+ /**
76
+ * Renders one brief for a handoff chain.
77
+ * @param snapshots - Session logs, oldest ancestor first, the handed-off session last.
78
+ */
79
+ export function renderHandoff(
80
+ snapshots: readonly SessionLogSnapshot[],
81
+ ): RenderedHandoff {
35
82
  const turns: TurnArc[] = [];
36
- const byId = new Map<number, TurnArc>();
37
- const failures: string[] = [];
38
- const artifacts: string[] = [];
39
- const callNames = new Map<string, string>();
40
- const seenArtifacts = new Set<string>();
41
- let open: TurnArc | undefined;
83
+ const failures: Failure[] = [];
84
+ // A Map keeps insertion order; re-inserting moves a repeated path to its newest use.
85
+ const artifacts = new Map<string, true>();
86
+ const briefFiles = new Set<string>();
42
87
  let goal = "";
88
+ let eventCount = 0;
43
89
 
44
- for (const event of snapshot.events) {
45
- switch (event.type) {
46
- case "turn/start": {
47
- const opened: TurnArc = {
48
- turn: event.data.turn,
49
- ask: "",
50
- outcome: "",
51
- reason: undefined,
52
- };
53
- turns.push(opened);
54
- byId.set(event.data.turn, opened);
55
- // edge case: `user/message` carries no turn number, so it is attributed
56
- // to the most recently opened turn.
57
- open = opened;
58
- break;
59
- }
60
- case "user/message": {
61
- if (event.data.source.kind !== "user") break;
62
- const text = blockText(event.data.content);
63
- if (text === "") break;
64
- if (goal === "") goal = elide(flatten(text), ASK_HEAD, ASK_TAIL);
65
- if (open !== undefined && open.ask === "") open.ask = text;
66
- break;
67
- }
68
- case "assistant/message": {
69
- const arc = byId.get(event.data.turn);
70
- if (arc === undefined) break;
71
- // The last text-bearing step of a turn is the answer the user saw.
72
- arc.outcome = blockText(event.data.message.content);
73
- break;
74
- }
75
- case "turn/end": {
76
- const arc = byId.get(event.data.turn);
77
- if (arc === undefined) break;
78
- arc.reason = event.data.reason;
79
- break;
80
- }
81
- case "tool/call": {
82
- const arc = byId.get(event.data.turn);
83
- callNames.set(event.data.callId, event.data.name);
84
- if (arc === undefined) break;
85
- collectArtifacts(event.data.arguments, artifacts, seenArtifacts);
86
- break;
87
- }
88
- case "tool/result": {
89
- const arc = byId.get(event.data.turn);
90
- if (event.data.message.isError !== true || arc === undefined) break;
91
- const callId = event.data.message.toolCallId;
92
- const name = callNames.get(callId);
93
- failures.push(
94
- `- **T${arc.turn}** tool \`${name === undefined ? callId : name}\`: ${clip(errorReason(event.data.error), FAILURE_LIMIT)}`,
95
- );
96
- break;
90
+ for (const snapshot of snapshots) {
91
+ const sessionId = String(snapshot.session.id);
92
+ const byId = new Map<number, TurnArc>();
93
+ const callNames = new Map<string, string>();
94
+ let open: TurnArc | undefined;
95
+ let sawUserMessage = false;
96
+ eventCount += snapshot.events.length;
97
+
98
+ for (const event of snapshot.events) {
99
+ switch (event.type) {
100
+ case "turn/start": {
101
+ const opened: TurnArc = {
102
+ turn: event.data.turn,
103
+ sessionId,
104
+ index: 0,
105
+ ask: "",
106
+ outcome: "",
107
+ reason: undefined,
108
+ isHandoff: false,
109
+ };
110
+ turns.push(opened);
111
+ byId.set(event.data.turn, opened);
112
+ // edge case: `user/message` carries no turn number, so it is attributed
113
+ // to the most recently opened turn.
114
+ open = opened;
115
+ break;
116
+ }
117
+ case "user/message": {
118
+ if (event.data.source.kind !== "user") break;
119
+ const text = blockText(event.data.content);
120
+ if (text === "") break;
121
+ const instruction = sawUserMessage
122
+ ? null
123
+ : INSTRUCTION_LINE.exec(text.split("\n", 1)[0]);
124
+ sawUserMessage = true;
125
+ if (instruction !== null) {
126
+ briefFiles.add(instruction[2]);
127
+ if (open !== undefined) open.isHandoff = true;
128
+ break;
129
+ }
130
+ if (goal === "") goal = elide(flatten(text), ASK_HEAD, ASK_TAIL);
131
+ if (open !== undefined && open.ask === "") open.ask = text;
132
+ break;
133
+ }
134
+ case "assistant/message": {
135
+ const arc = byId.get(event.data.turn);
136
+ if (arc === undefined) break;
137
+ // The last text-bearing step of a turn is the answer the user saw.
138
+ arc.outcome = blockText(event.data.message.content);
139
+ break;
140
+ }
141
+ case "turn/end": {
142
+ const arc = byId.get(event.data.turn);
143
+ if (arc === undefined) break;
144
+ arc.reason = event.data.reason;
145
+ break;
146
+ }
147
+ case "tool/call": {
148
+ const arc = byId.get(event.data.turn);
149
+ callNames.set(event.data.callId, event.data.name);
150
+ if (arc === undefined || arc.isHandoff) break;
151
+ collectArtifacts(event.data.arguments, artifacts, briefFiles);
152
+ break;
153
+ }
154
+ case "tool/result": {
155
+ const arc = byId.get(event.data.turn);
156
+ if (event.data.message.isError !== true || arc === undefined) break;
157
+ if (arc.isHandoff) break;
158
+ const callId = event.data.message.toolCallId;
159
+ const name = callNames.get(callId);
160
+ failures.push({
161
+ arc,
162
+ text: `tool \`${clip(name === undefined ? callId : name, TOOL_NAME_LIMIT)}\`: ${clip(errorReason(event.data.error), FAILURE_LIMIT)}`,
163
+ });
164
+ break;
165
+ }
166
+ default:
167
+ break;
97
168
  }
98
- default:
99
- break;
100
169
  }
101
170
  }
102
171
 
103
- const id = String(snapshot.session.id);
104
- const cwd = snapshot.session.cwd;
172
+ const work = turns.filter((turn) => !turn.isHandoff);
173
+ work.forEach((turn, index) => {
174
+ turn.index = index + 1;
175
+ });
176
+
177
+ const current = snapshots[snapshots.length - 1];
178
+ const id = String(current.session.id);
179
+ const cwd = current.session.cwd;
105
180
  const lines = [
106
181
  `# Handoff — ${id}`,
107
182
  "",
108
183
  `- session: \`${id}\``,
184
+ ...(snapshots.length > 1
185
+ ? [
186
+ `- chain: ${snapshots.map((snapshot) => `\`${shortId(String(snapshot.session.id))}\``).join(" → ")}`,
187
+ ]
188
+ : []),
109
189
  `- cwd: \`${cwd === undefined ? "unknown" : cwd}\``,
110
- `- created: ${new Date(snapshot.session.createdAt).toISOString()}`,
111
- `- events: ${snapshot.events.length}`,
112
- `- turns: ${turns.length}`,
190
+ `- created: ${new Date(current.session.createdAt).toISOString()}`,
191
+ `- events: ${eventCount}`,
192
+ `- turns: ${work.length}`,
113
193
  "",
114
194
  "## Goal",
115
195
  "",
@@ -117,26 +197,33 @@ export function renderHandoff(snapshot: SessionLogSnapshot): RenderedHandoff {
117
197
  "",
118
198
  "## Turns",
119
199
  "",
120
- turns.length === 0
121
- ? "none"
122
- : turns
123
- .map((turn, index) =>
124
- turnBlock(turn, index >= turns.length - RECENT_TURNS),
125
- )
126
- .join("\n\n"),
200
+ work.length === 0 ? "none" : turnList(work),
127
201
  "",
128
202
  "## Failures",
129
203
  "",
130
- failures.length === 0 ? "none" : failures.join("\n"),
204
+ failures.length === 0
205
+ ? "none"
206
+ : bounded(
207
+ failures.map(
208
+ ({ arc, text }) =>
209
+ `- **T${arc.index}**${arc.sessionId === id ? "" : ` (${shortId(arc.sessionId)})`} ${text}`,
210
+ ),
211
+ FAILURE_MAX,
212
+ "older failures",
213
+ ),
131
214
  "",
132
215
  "## Artifacts",
133
216
  "",
134
- artifacts.length === 0
217
+ artifacts.size === 0
135
218
  ? "none"
136
- : artifacts.map((file) => `- \`${file}\``).join("\n"),
219
+ : bounded(
220
+ [...artifacts.keys()].map((file) => `- \`${file}\``),
221
+ ARTIFACT_MAX,
222
+ "older paths",
223
+ ),
137
224
  ];
138
225
 
139
- return { markdown: `${lines.join("\n")}\n`, turns: turns.length };
226
+ return { markdown: `${lines.join("\n")}\n`, turns: work.length };
140
227
  }
141
228
 
142
229
  export function handoffInstruction(sessionId: string, file: string): string {
@@ -152,6 +239,28 @@ export function handoffInstruction(sessionId: string, file: string): string {
152
239
  ].join("\n");
153
240
  }
154
241
 
242
+ /** Last RECENT_TURNS turns quoted at length, OLDER_TURNS before them flattened, the rest counted. */
243
+ function turnList(work: readonly TurnArc[]): string {
244
+ const kept = work.slice(-(RECENT_TURNS + OLDER_TURNS));
245
+ const dropped = work.length - kept.length;
246
+ const blocks = kept.map((turn, index) =>
247
+ turnBlock(turn, index >= kept.length - RECENT_TURNS),
248
+ );
249
+ if (dropped > 0) blocks.unshift(`… ${dropped} earlier turns omitted`);
250
+ return blocks.join("\n\n");
251
+ }
252
+
253
+ /** Keeps the newest `max` lines, naming how many older ones were dropped. */
254
+ function bounded(lines: string[], max: number, noun: string): string {
255
+ const dropped = lines.length - max;
256
+ if (dropped <= 0) return lines.join("\n");
257
+ return [`- … ${dropped} ${noun} omitted`, ...lines.slice(-max)].join("\n");
258
+ }
259
+
260
+ function shortId(id: string): string {
261
+ return id.slice(0, SHORT_ID_LENGTH);
262
+ }
263
+
155
264
  /** Recent turns quote the ask and reply at length; older turns are flattened and short. */
156
265
  function turnBlock(turn: TurnArc, recent: boolean): string {
157
266
  const kind = turn.reason === undefined ? "unfinished" : turn.reason.kind;
@@ -168,7 +277,7 @@ function turnBlock(turn: TurnArc, recent: boolean): string {
168
277
  )
169
278
  .filter((part) => part !== "")
170
279
  .join("\n\n");
171
- return `### T${turn.turn} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
280
+ return `### T${turn.index} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
172
281
  }
173
282
 
174
283
  function blockText(blocks: readonly ContentBlock[]): string {
@@ -211,8 +320,8 @@ function errorReason(
211
320
 
212
321
  function collectArtifacts(
213
322
  args: string,
214
- into: string[],
215
- seen: Set<string>,
323
+ into: Map<string, true>,
324
+ briefFiles: ReadonlySet<string>,
216
325
  ): void {
217
326
  let parsed: unknown;
218
327
  try {
@@ -227,9 +336,10 @@ function collectArtifacts(
227
336
  const record = parsed as Record<string, unknown>;
228
337
  for (const key of PATH_KEYS) {
229
338
  const value = record[key];
230
- if (typeof value !== "string" || value === "" || seen.has(value)) continue;
231
- seen.add(value);
232
- into.push(value);
233
- if (into.length >= ARTIFACT_LIMIT) return;
339
+ if (typeof value !== "string" || value === "" || briefFiles.has(value))
340
+ continue;
341
+ const path = clip(value, PATH_LIMIT);
342
+ into.delete(path);
343
+ into.set(path, true);
234
344
  }
235
345
  }
package/src/index.ts CHANGED
@@ -18,7 +18,11 @@ import type {} from "@deepseek-ai/dsh-session-title";
18
18
  import type {} from "@deepseek-ai/dsh-working-directory";
19
19
  import type { Workspace } from "@deepseek-ai/dsh-workspace";
20
20
  import { scratchDirectory } from "@lukstei/dsh-scratch-dir";
21
- import { handoffInstruction, renderHandoff } from "./handoff.ts";
21
+ import {
22
+ handoffInstruction,
23
+ parentSessionId,
24
+ renderHandoff,
25
+ } from "./handoff.ts";
22
26
  import { formatLaunchResult } from "./launch.ts";
23
27
 
24
28
  export const name = "session-handoff";
@@ -105,7 +109,9 @@ async function handoff(
105
109
 
106
110
  try {
107
111
  const snapshot = await ctx.sessionQuery.readSession(targetId);
108
- const rendered = renderHandoff(snapshot);
112
+ const rendered = renderHandoff(
113
+ await readChain(ctx, snapshot, invocation.signal),
114
+ );
109
115
  if (rendered.turns === 0) {
110
116
  return {
111
117
  kind: "error",
@@ -142,6 +148,35 @@ async function handoff(
142
148
  }
143
149
  }
144
150
 
151
+ /**
152
+ * The handed-off session preceded by every ancestor it was itself handed off from,
153
+ * oldest first, so the brief keeps what earlier briefs summarized.
154
+ */
155
+ async function readChain(
156
+ ctx: Context,
157
+ snapshot: SessionLogSnapshot,
158
+ signal: AbortSignal,
159
+ ): Promise<SessionLogSnapshot[]> {
160
+ const chain = [snapshot];
161
+ const seen = new Set([String(snapshot.session.id)]);
162
+ let parent = parentSessionId(snapshot);
163
+ if (parent === undefined) return chain;
164
+ // `readSession` has no typed not-found error, so deleted parents are found by id.
165
+ const known = new Set(
166
+ (await ctx.sessionQuery.listSessions(signal)).map((session) =>
167
+ String(session.header.id),
168
+ ),
169
+ );
170
+ while (parent !== undefined && !seen.has(parent) && known.has(parent)) {
171
+ seen.add(parent);
172
+ // Safe: the id was just matched against the listed session ids.
173
+ const ancestor = await ctx.sessionQuery.readSession(parent as SessionId);
174
+ chain.unshift(ancestor);
175
+ parent = parentSessionId(ancestor);
176
+ }
177
+ return chain;
178
+ }
179
+
145
180
  /**
146
181
  * Write the brief into the agent's own scratch directory and queue the follow-up
147
182
  * turn that tells it to read that file.