@lukstei/dsh-session-handoff 0.0.0-stage → 0.2.2-rc.5.4

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lukas Steinbrecher
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,204 @@
1
- # Temporary Holding Version
1
+ # @lukstei/dsh-session-handoff
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ## Summary
4
+
5
+ Adds a `/handoff` command that turns a session log into a short resume brief. Bare `/handoff` starts a new session beside the current one with the brief loaded; `/handoff <session-id>` writes another session's brief into the current session.
6
+
7
+ ## Table of Contents
8
+
9
+ - [Use this package](#use-this-package)
10
+ - [Understand the implementation](#understand-the-implementation)
11
+ - [Further Exploration](#further-exploration)
12
+ - [Model Experience](#model-experience)
13
+ - [Known Limitations and Deferred Work](#known-limitations-and-deferred-work)
14
+ - [Dev Note](#dev-note)
15
+
16
+ -----
17
+
18
+ <a id="use-this-package"></a>
19
+ ## Use this package
20
+
21
+ Mount through the bundle patch ([`cordis.patch.yml`](cordis.patch.yml)) and add the package to the profile:
22
+
23
+ ```yaml
24
+ # ~/.dsh/profiles/desktop/cordis.patch.yml
25
+ - insert:
26
+ - id: session-handoff
27
+ name: '@lukstei/dsh-session-handoff'
28
+ config: {}
29
+ ```
30
+
31
+ ```json
32
+ // ~/.dsh/profiles/desktop/package.json
33
+ {
34
+ "dsh": { "profile": { "bundles": ["@lukstei/dsh-session-handoff"] } },
35
+ "dependencies": {
36
+ "@lukstei/dsh-session-handoff": "^0.1.0"
37
+ }
38
+ }
39
+ ```
40
+
41
+ Then `pnpm install` in the profile directory and restart the harness. No config fields.
42
+
43
+ Required Host services (`inject`): `commands`, `sessionQuery`, `workingDirectory`, `sessionController`, `sessionTitle`, `workspaceRegistry`. Workspace dependency: [`@lukstei/dsh-scratch-dir`](../dsh-scratch-dir/README.md) (`scratchDirectory()`).
44
+
45
+ The client half needs `@deepseek-ai/dsh-api-session-controller` and [`@lukstei/dsh-client-split-view`](../dsh-client-split-view/README.md). Build it with `pnpm build` (emits `dist/client.js`); rebuild and restart after changing `src/client/`. The client bundle is marked `immediately` because no route lazily pulls it in; without stage-one prefetch its watcher would never register.
46
+
47
+ ```text
48
+ /handoff
49
+ /handoff 06542298
50
+ /handoff 06542298-c989-417d-9ed4-fa5877768140
51
+ ```
52
+
53
+ ### Plugin dependencies
54
+
55
+ Server-side and client-side entries.
56
+
57
+ **Server-side** (`inject`: `commands`, `sessionQuery`, `workingDirectory`, `sessionController`, `sessionTitle`, `workspaceRegistry`):
58
+
59
+ | Plugin / service | Required? | Provided by | Effect without it |
60
+ |---|---|---|---|
61
+ | `commands` | Required | @deepseek-ai/dsh-commands | Plugin stays pending; never applies. No `/handoff`. |
62
+ | `sessionQuery` | Required | @deepseek-ai/dsh-session-query | Plugin stays pending; never applies. |
63
+ | `workingDirectory` | Required | @deepseek-ai/dsh-working-directory | Plugin stays pending; never applies. |
64
+ | `sessionController` | Required | @deepseek-ai/dsh-api-session-controller | Plugin stays pending; never applies. |
65
+ | `sessionTitle` | Required | @deepseek-ai/dsh-session-title | Plugin stays pending; never applies. |
66
+ | `workspaceRegistry` | Required | @deepseek-ai/dsh-workspace | Plugin stays pending; never applies. |
67
+
68
+ **Client-side** (`inject`: `sessions`, `splitView`, `slots`; all required):
69
+
70
+ | Plugin / service | Required? | Provided by | Effect without it |
71
+ |---|---|---|---|
72
+ | `sessions` | Required | @deepseek-ai/dsh-api-session-controller | Plugin stays pending; never applies. |
73
+ | `splitView` | Required | [`@lukstei/dsh-client-split-view`](../dsh-client-split-view/README.md) (also in `dsh.client.inject`) | Plugin stays pending; never applies. The client entry (launch into a pane) does not activate; the host `/handoff` command still works. |
74
+
75
+ | `slots` | Required | @deepseek-ai/dsh-client-ui-renderer | Plugin stays pending; never applies. |
76
+
77
+ ### Handoff ring
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`.
80
+
81
+ Code import (no mount): [`@lukstei/dsh-scratch-dir`](../dsh-scratch-dir/README.md) (`scratchDirectory`).
82
+
83
+ Used by: nothing.
84
+
85
+ ### Modes
86
+
87
+ | Input | Brief describes | Brief lands in | Then |
88
+ |---|---|---|---|
89
+ | `/handoff` | this session | scratch directory of a newly created session | New session opens as a split pane; the source is marked done in Kanban and its pane is closed. |
90
+ | `/handoff <id-or-prefix>` | that session | `<cwd>/.agents/scratch/<current-session-id>/HANDOFF.md` | Current agent is told to read it. |
91
+
92
+ Id resolution: exact id first, then unique prefix over `sessionQuery.listSessions()`. Unknown ids return an error listing the 5 most recent sessions; ambiguous prefixes list candidates. Passing the current session's id is an error. Any non-id text, including `launch`, is treated as an id. A session with no turns returns an error. All I/O failures return `{ kind: "error" }`.
93
+
94
+ ### Bare `/handoff` launch
95
+
96
+ 1. Renders this session's brief.
97
+ 2. Creates a session via `sessionController.create()` in the current workspace (falls back to `cwd` when the session has no workspace), same `agentPreset`.
98
+ 3. Replays the current model selection onto the new agent.
99
+ 4. Titles it `<source title> - Handoff` (or `Handoff <first 8 id chars>` when untitled). A user title pins it against auto-generated titles.
100
+ 5. Runs `/kanban {"action":"init","createdAt":…}` against the new agent so it appears on the Kanban board. No `prompt` is sent, since that would seed the composer draft with the follow-up text.
101
+ 6. Copies the source session's kanban links by replaying its `add-link` commands against the new agent.
102
+ 7. Writes `HANDOFF.md` into the new session's scratch directory and queues the read-the-brief follow-up.
103
+ 8. Returns `Handoff launched: <id>`.
104
+
105
+ The client opens the pane. Without the client bundle the session is created but not opened.
106
+
107
+ ### Brief layout
108
+
109
+ | Section | Contents |
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 |
116
+
117
+ Empty sections render `none`. Output is deterministic for a given log. `request/header`, `agent/inbox/spliced` and reasoning blocks are excluded.
118
+
119
+ -----
120
+
121
+ <a id="understand-the-implementation"></a>
122
+ ## Understand the implementation
123
+
124
+ <details>
125
+ <summary>Implementation internals — click to expand</summary>
126
+
127
+ Files:
128
+
129
+ - [`src/index.ts`](src/index.ts): command registration, target resolution, `deliver` (write brief + queue follow-up), `createBeside` (launch).
130
+ - [`src/handoff.ts`](src/handoff.ts): `renderHandoff` and `handoffInstruction`, pure.
131
+ - [`src/launch.ts`](src/launch.ts): `LAUNCH_PREFIX`, `formatLaunchResult`, `launchedSessionId`.
132
+ - [`src/client/index.ts`](src/client/index.ts): client watcher. Tests sit beside each file.
133
+
134
+ Details:
135
+
136
+ - The command declares `input: { hint: "[session-id]" }`. Without a declared input the client sends the raw line to the model as a prompt and the handler never runs.
137
+ - A slash command has no structured return channel to the client, so the Host encodes the new id in the command result text, which is persisted in the `command/done` event. The client subscribes to every open session's event source and calls `ctx.splitView.toggleSession()` when it sees a successful `command/done` starting with `Handoff launched: `. It then sends `/kanban {"action":"done"}` to the source session and calls `ctx.splitView.removeSession()` on it, as the Kanban Done button does. A source never initialised in Kanban ignores the done action but still loses its pane.
138
+ - The pane is added through the split store, not `uiWorkspace.openSession()`. The split view patches that method into a read-only overlay without its own composer, so prompts would keep landing in the pane underneath.
139
+ - The client reacts only to `append` changes. A `replace` replays the whole window on first open and after reconnect gaps and would reopen panes the user closed; the split view restores its panes from local storage.
140
+ - Kanban membership is a session-log fact: the board lists only sessions whose `kanban` projection is initialized, which happens when `/kanban` runs in that session. Hence the explicit `init`.
141
+ - 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
+ - Turn attribution: `user/message` carries no turn number, so it is attributed to the most recently opened turn.
143
+ - Artifact extraction parses tool arguments as JSON; non-JSON payloads are ignored.
144
+ - The scratch path comes from `scratchDirectory()`; an unsafe id throws and the command returns an error.
145
+
146
+ Trust boundary: the session id argument and session log contents are untrusted text; output is markdown written under the scratch directory only.
147
+
148
+ </details>
149
+
150
+ -----
151
+
152
+ <a id="further-exploration"></a>
153
+ ## Further Exploration
154
+
155
+ - [`@lukstei/dsh-scratch-dir`](../dsh-scratch-dir/README.md) — scratch path convention.
156
+ - [`@lukstei/dsh-client-split-view`](../dsh-client-split-view) — pane host.
157
+ - Upstream: [DSH module graph](https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/module-graph.md).
158
+
159
+ <a id="model-experience"></a>
160
+ ## Model Experience
161
+
162
+ ### /handoff
163
+
164
+ #### What the model sees
165
+
166
+ One queued follow-up user message in the receiving session:
167
+
168
+ ```text
169
+ The handoff brief for session <id> is at <path>/HANDOFF.md.
170
+
171
+ Read that file now, then reply with three lines and stop:
172
+ Goal: <one line>
173
+ State: <one line>
174
+ Next: <one line>
175
+
176
+ Do not start the work until the user confirms the next action.
177
+ ```
178
+
179
+ The model then reads `HANDOFF.md` with its own file tools. It gets no tool, system prompt section or other injected context from this package. A follow-up is used because the system prompt is fixed at the first request; `agent.followup()` writes a logged `user/message`, so the instruction is replayable and visible in the transcript.
180
+
181
+ #### Token effect
182
+
183
+ About 60 tokens for the message, plus the brief when read. Brief size grows with turn count (one `## Turns` block per turn, up to about 1,000 chars each for older turns; the last 5 turns are quoted longer).
184
+
185
+ #### KV Cache effect
186
+
187
+ Appended message only; the prompt prefix is untouched. In a launched session this is the first turn.
188
+
189
+ <a id="known-limitations-and-deferred-work"></a>
190
+ ## Known Limitations and Deferred Work
191
+
192
+ - Opening the new pane needs the client bundle and the split-view plugin.
193
+ - The brief is a heuristic summary of the log; tool outputs, reasoning and request headers are not included.
194
+ - `## Turns` size is unbounded in turn count.
195
+
196
+ <a id="dev-note"></a>
197
+ ### Dev Note
198
+
199
+ <details>
200
+ <summary>Working context for maintainers — click to expand</summary>
201
+
202
+ None.
203
+
204
+ </details>
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: session-handoff
3
+ name: '@lukstei/dsh-session-handoff'
4
+ config: {}
package/dist/client.js ADDED
@@ -0,0 +1,196 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@lukstei/dsh-session-handoff",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react = require("react");
8
+ /**
9
+ * The launched Session id carried by one durable event, or `undefined` when the
10
+ * event is not a successful handoff launch.
11
+ */
12
+ function launchedSessionId(event) {
13
+ if (event.type !== "command/done") return void 0;
14
+ if (event.data.kind !== "success") return void 0;
15
+ const { text } = event.data;
16
+ if (typeof text !== "string" || !text.startsWith("Handoff launched: ")) return;
17
+ return text.slice(18);
18
+ }
19
+ // src/client/acp-usage.ts
20
+ let reader;
21
+ const listeners = /* @__PURE__ */ new Set();
22
+ function setAcpUsageReader(next) {
23
+ reader = next;
24
+ for (const listener of listeners) listener();
25
+ }
26
+ /** `useSyncExternalStore` seat, so a ring mounted before the adapter re-reads once it arrives. */
27
+ function subscribeAcpUsageReader(listener) {
28
+ listeners.add(listener);
29
+ return () => {
30
+ listeners.delete(listener);
31
+ };
32
+ }
33
+ function currentAcpUsageReader() {
34
+ return reader;
35
+ }
36
+ // src/client/level.ts
37
+ /** Anthropic prompt-cache TTL: past this idle gap the next turn re-writes the whole context. */
38
+ const CACHE_TTL_MS = 3e5;
39
+ const WARM = {
40
+ soft: 7e4,
41
+ strong: 1e5
42
+ };
43
+ const COLD = {
44
+ soft: 4e4,
45
+ strong: 7e4
46
+ };
47
+ const SOFT_WINDOW_SHARE = .6;
48
+ const STRONG_WINDOW_SHARE = .8;
49
+ function handoffLevel(pressureTokens, contextWindow, cold) {
50
+ if (pressureTokens === void 0) return "none";
51
+ const bar = cold ? COLD : WARM;
52
+ const soft = contextWindow === void 0 ? bar.soft : Math.min(bar.soft, SOFT_WINDOW_SHARE * contextWindow);
53
+ if (pressureTokens >= (contextWindow === void 0 ? bar.strong : Math.min(bar.strong, STRONG_WINDOW_SHARE * contextWindow))) return "strong";
54
+ return pressureTokens >= soft ? "soft" : "none";
55
+ }
56
+ // src/client/ring.ts
57
+ const COLOR = {
58
+ soft: "#d9a400",
59
+ strong: "#d62839"
60
+ };
61
+ /** Small ring beside the send button once the session is big enough that `/handoff` pays off. */
62
+ function HandoffRing({ sessionId, useProjection, useSession }) {
63
+ const pressure = useProjection("contextPressure");
64
+ const running = useSession((session) => session.running);
65
+ const [acp, setAcp] = (0, react.useState)(void 0);
66
+ const [cold, setCold] = (0, react.useState)(false);
67
+ const readUsage = (0, react.useSyncExternalStore)(subscribeAcpUsageReader, currentAcpUsageReader);
68
+ (0, react.useEffect)(() => {
69
+ if (running || readUsage === void 0) return;
70
+ let live = true;
71
+ readUsage(sessionId).then((usage) => {
72
+ if (live) setAcp(usage);
73
+ });
74
+ return () => {
75
+ live = false;
76
+ };
77
+ }, [
78
+ sessionId,
79
+ running,
80
+ readUsage
81
+ ]);
82
+ const tokens = pressure !== void 0 && pressure.pressureTokens !== void 0 ? pressure.pressureTokens : acp?.used;
83
+ const window = pressure !== void 0 && pressure.contextWindow !== void 0 ? pressure.contextWindow : acp?.size;
84
+ (0, react.useEffect)(() => {
85
+ setCold(false);
86
+ if (running) return;
87
+ const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
88
+ return () => clearTimeout(timer);
89
+ }, [tokens, running]);
90
+ const level = handoffLevel(tokens, window, cold);
91
+ if (level === "none" || tokens === void 0) return null;
92
+ const k = Math.round(tokens / 1e3);
93
+ return (0, react.createElement)("span", {
94
+ role: "img",
95
+ title: `Context ${k}k tokens: ${cold ? "cache is cold, a fresh session is cheaper now" : "consider a fresh session"} (/handoff)`,
96
+ "aria-label": `Handoff ${level === "strong" ? "recommended" : "suggested"}`,
97
+ style: {
98
+ width: 14,
99
+ height: 14,
100
+ boxSizing: "border-box",
101
+ borderRadius: "50%",
102
+ border: `2px solid ${COLOR[level]}`,
103
+ flex: "none"
104
+ }
105
+ });
106
+ }
107
+ // src/client/index.ts
108
+ const inject = [
109
+ "sessions",
110
+ "splitView",
111
+ "slots"
112
+ ];
113
+ /**
114
+ * Open every session the Host reports as launched as a pane of its own. A slash
115
+ * command cannot reach the client, so the Host publishes the new id in the
116
+ * command's own `command/done` record and this plugin reads that durable window
117
+ * back.
118
+ *
119
+ * The pane is added through the split store, not `uiWorkspace.openSession`: the
120
+ * split view patches that method into a read-only overlay, whose embedded
121
+ * transcript has no composer of its own, so the prompts would keep landing in
122
+ * the session of the pane underneath.
123
+ */
124
+ function apply(ctx) {
125
+ const sessions = ctx.sessions;
126
+ const off = /* @__PURE__ */ new Map();
127
+ const finish = async (id) => {
128
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
129
+ await reference.binding.session.command(`/kanban ${JSON.stringify({
130
+ action: "done",
131
+ doneAt: Date.now()
132
+ })}`);
133
+ });
134
+ ctx.splitView.removeSession(id);
135
+ };
136
+ const watch = (id) => {
137
+ const binding = sessions.binding(id);
138
+ if (binding === void 0) return;
139
+ const unsubscribe = binding.eventSource.subscribe(() => {
140
+ const { change } = binding.eventSource.getSnapshot();
141
+ if (change.kind !== "append") return;
142
+ for (const entry of change.entries) {
143
+ if (entry.type !== "event") continue;
144
+ const launched = launchedSessionId(entry.event);
145
+ if (launched === void 0) continue;
146
+ ctx.splitView.toggleSession(launched);
147
+ finish(id);
148
+ return;
149
+ }
150
+ });
151
+ off.set(id, unsubscribe);
152
+ };
153
+ const sync = () => {
154
+ for (const id of sessions.list.getSnapshot().ids) {
155
+ if (off.has(id)) continue;
156
+ watch(id);
157
+ }
158
+ for (const [id, unsubscribe] of off) {
159
+ if (sessions.binding(id) !== void 0) continue;
160
+ unsubscribe();
161
+ off.delete(id);
162
+ }
163
+ };
164
+ ctx.effect(() => ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
165
+ name: "conversation.input.right",
166
+ id: "session-handoff.ring",
167
+ order: 90,
168
+ inject: () => ({})
169
+ }, HandoffRing)), "session-handoff: handoff ring");
170
+ ctx.inject(["remote", "remote.dshAcp"], (acpCtx) => {
171
+ const remote = acpCtx.remote.dshAcp;
172
+ const reader = async (id) => {
173
+ const result = await remote.agentSessionSnapshot(id);
174
+ if (!result.ok) {
175
+ console.warn("session-handoff: ACP usage unavailable", result);
176
+ return;
177
+ }
178
+ const usage = result.value.contextUsage;
179
+ return usage === null ? void 0 : usage;
180
+ };
181
+ setAcpUsageReader(reader);
182
+ return () => setAcpUsageReader(void 0);
183
+ });
184
+ const dispose = sessions.list.subscribe(sync);
185
+ sync();
186
+ ctx.effect(() => () => {
187
+ dispose();
188
+ for (const unsubscribe of off.values()) unsubscribe();
189
+ off.clear();
190
+ }, "session-handoff: launch watcher");
191
+ }
192
+ exports.apply = apply;
193
+ exports.inject = inject;
194
+ return module.exports;
195
+ }
196
+ });
package/package.json CHANGED
@@ -1,6 +1,109 @@
1
1
  {
2
2
  "name": "@lukstei/dsh-session-handoff",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.2.2-rc.5.4",
4
+ "description": "Session handoff brief command for DSH",
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./client": "./dist/client.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "src",
15
+ "dist",
16
+ "README.md",
17
+ "cordis.patch.yml",
18
+ "!src/**/*.spec.*",
19
+ "!src/**/*.test.*",
20
+ "!src/**/*.stories.*",
21
+ "!src/**/stories",
22
+ "!src/**/*.e2e.*",
23
+ "!src/**/__snapshots__",
24
+ "!src/**/fixtures"
25
+ ],
26
+ "dsh": {
27
+ "bundle": {
28
+ "patch": "./cordis.patch.yml"
29
+ },
30
+ "client": {
31
+ "platform": "web",
32
+ "immediately": true,
33
+ "inject": [
34
+ "@deepseek-ai/dsh-api-session-controller",
35
+ "@lukstei/dsh-client-split-view",
36
+ "@deepseek-ai/dsh-client-ui-conversation",
37
+ "@deepseek-ai/dsh-client-ui-renderer"
38
+ ]
39
+ }
40
+ },
41
+ "dependencies": {
42
+ "@lukstei/dsh-scratch-dir": "0.2.2-rc.5.4"
43
+ },
44
+ "peerDependencies": {
45
+ "@deepseek-ai/cordis": "*",
46
+ "@deepseek-ai/dsh-agent": "*",
47
+ "@deepseek-ai/dsh-api-session-controller": "*",
48
+ "@deepseek-ai/dsh-client-ui-conversation": "*",
49
+ "@deepseek-ai/dsh-client-ui-renderer": "*",
50
+ "@deepseek-ai/dsh-client-ui-session": "*",
51
+ "@deepseek-ai/dsh-client-ui-slots": "*",
52
+ "@deepseek-ai/dsh-commands": "*",
53
+ "@deepseek-ai/dsh-llm": "*",
54
+ "@deepseek-ai/dsh-session": "*",
55
+ "@deepseek-ai/dsh-session-query": "*",
56
+ "@deepseek-ai/dsh-session-title": "*",
57
+ "@deepseek-ai/dsh-token-meter": "*",
58
+ "@deepseek-ai/dsh-working-directory": "*",
59
+ "@deepseek-ai/dsh-workspace": "*",
60
+ "@zaimokuza/dsh-acp-adapter": "*",
61
+ "react": "*"
62
+ },
63
+ "devDependencies": {
64
+ "@deepseek-ai/cordis": "4.1.0",
65
+ "@deepseek-ai/dsh-agent": "0.2.2-rc.5",
66
+ "@deepseek-ai/dsh-api-session-controller": "0.2.2-rc.5",
67
+ "@deepseek-ai/dsh-client-ui-conversation": "0.2.2-rc.5",
68
+ "@deepseek-ai/dsh-client-ui-renderer": "0.2.2-rc.5",
69
+ "@deepseek-ai/dsh-client-ui-session": "0.2.2-rc.5",
70
+ "@deepseek-ai/dsh-client-ui-slots": "0.2.2-rc.5",
71
+ "@deepseek-ai/dsh-commands": "0.2.2-rc.5",
72
+ "@deepseek-ai/dsh-llm": "0.2.2-rc.5",
73
+ "@deepseek-ai/dsh-session": "0.2.2-rc.5",
74
+ "@deepseek-ai/dsh-session-query": "0.2.2-rc.5",
75
+ "@deepseek-ai/dsh-session-title": "0.2.2-rc.5",
76
+ "@deepseek-ai/dsh-token-meter": "0.2.2-rc.5",
77
+ "@deepseek-ai/dsh-working-directory": "0.2.2-rc.5",
78
+ "@deepseek-ai/dsh-workspace": "0.2.2-rc.5",
79
+ "@lukstei/dsh-client-split-view": "0.2.2-rc.5.4",
80
+ "@types/node": "^26.0.0",
81
+ "@types/react": "^19.3.0",
82
+ "@zaimokuza/dsh-acp-adapter": "0.2.2-rc.5.2",
83
+ "react": "^19.3.1",
84
+ "tsdown": "^0.23.0",
85
+ "typescript": "^7.0.2"
86
+ },
87
+ "peerDependenciesMeta": {
88
+ "@zaimokuza/dsh-acp-adapter": {
89
+ "optional": true
90
+ }
91
+ },
92
+ "license": "MIT",
93
+ "repository": {
94
+ "type": "git",
95
+ "url": "git+https://github.com/lukstei/dsh-plugins.git",
96
+ "directory": "packages/dsh-session-handoff"
97
+ },
98
+ "publishConfig": {
99
+ "access": "public"
100
+ },
101
+ "scripts": {
102
+ "build": "tsdown --config tsdown.config.ts --logLevel error",
103
+ "dev": "tsdown --config tsdown.config.ts --watch",
104
+ "check": "biome check --reporter=concise .",
105
+ "typecheck": "tsc --noEmit",
106
+ "test": "node --experimental-test-module-mocks --test --test-reporter=dot",
107
+ "verify": "pnpm --silent run check && pnpm --silent run build && pnpm --silent run typecheck && pnpm --silent run test"
108
+ }
6
109
  }
@@ -0,0 +1,31 @@
1
+ /** Context occupancy an ACP agent reported, as the adapter exposes it. */
2
+ export interface AcpUsage {
3
+ readonly used: number;
4
+ readonly size: number;
5
+ }
6
+
7
+ export type AcpUsageReader = (
8
+ sessionId: string,
9
+ ) => Promise<AcpUsage | undefined>;
10
+
11
+ // smell: module-level seat; the optional ACP scope in `index.ts` fills it, so the ring needs no
12
+ // hard dependency on the adapter.
13
+ let reader: AcpUsageReader | undefined;
14
+ const listeners = new Set<() => void>();
15
+
16
+ export function setAcpUsageReader(next: AcpUsageReader | undefined): void {
17
+ reader = next;
18
+ for (const listener of listeners) listener();
19
+ }
20
+
21
+ /** `useSyncExternalStore` seat, so a ring mounted before the adapter re-reads once it arrives. */
22
+ export function subscribeAcpUsageReader(listener: () => void): () => void {
23
+ listeners.add(listener);
24
+ return () => {
25
+ listeners.delete(listener);
26
+ };
27
+ }
28
+
29
+ export function currentAcpUsageReader(): AcpUsageReader | undefined {
30
+ return reader;
31
+ }
@@ -0,0 +1,118 @@
1
+ import type { Context } from "@deepseek-ai/cordis";
2
+ import type { ISessions } from "@deepseek-ai/dsh-api-session-controller/client";
3
+ import type {} from "@deepseek-ai/dsh-client-ui-conversation/client";
4
+ import type {} from "@deepseek-ai/dsh-client-ui-renderer/client";
5
+ import type { SessionId } from "@deepseek-ai/dsh-session/types";
6
+ import type {} from "@lukstei/dsh-client-split-view/client-contract";
7
+ import type {} from "@zaimokuza/dsh-acp-adapter/remote";
8
+ import { launchedSessionId } from "../launch.ts";
9
+ import { type AcpUsageReader, setAcpUsageReader } from "./acp-usage.ts";
10
+ import { HandoffRing } from "./ring.ts";
11
+
12
+ export const inject = ["sessions", "splitView", "slots"];
13
+
14
+ /**
15
+ * Open every session the Host reports as launched as a pane of its own. A slash
16
+ * command cannot reach the client, so the Host publishes the new id in the
17
+ * command's own `command/done` record and this plugin reads that durable window
18
+ * back.
19
+ *
20
+ * The pane is added through the split store, not `uiWorkspace.openSession`: the
21
+ * split view patches that method into a read-only overlay, whose embedded
22
+ * transcript has no composer of its own, so the prompts would keep landing in
23
+ * the session of the pane underneath.
24
+ */
25
+ export function apply(ctx: Context): void {
26
+ // Shared Context merges the Host SessionStore with the Client ISessions, so the
27
+ // client object layer is named explicitly.
28
+ const sessions = ctx.sessions as unknown as ISessions;
29
+ const off = new Map<SessionId, () => void>();
30
+
31
+ // Same effect as the Kanban Done button: record done, then close the pane.
32
+ const finish = async (id: SessionId): Promise<void> => {
33
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
34
+ await reference.binding.session.command(
35
+ `/kanban ${JSON.stringify({ action: "done", doneAt: Date.now() })}`,
36
+ );
37
+ });
38
+ ctx.splitView.removeSession(id);
39
+ };
40
+
41
+ const watch = (id: SessionId): void => {
42
+ const binding = sessions.binding(id);
43
+ if (binding === undefined) return;
44
+ const unsubscribe = binding.eventSource.subscribe(() => {
45
+ const { change } = binding.eventSource.getSnapshot();
46
+ // edge case: `replace` replays the whole window on first open and again
47
+ // after every reconnect gap, so it would re-open panes the user closed;
48
+ // the split view already restores its own panes from local storage.
49
+ if (change.kind !== "append") return;
50
+ for (const entry of change.entries) {
51
+ if (entry.type !== "event") continue;
52
+ const launched = launchedSessionId(entry.event);
53
+ if (launched === undefined) continue;
54
+ ctx.splitView.toggleSession(launched);
55
+ void finish(id);
56
+ return;
57
+ }
58
+ });
59
+ off.set(id, unsubscribe);
60
+ };
61
+
62
+ const sync = (): void => {
63
+ for (const id of sessions.list.getSnapshot().ids) {
64
+ if (off.has(id)) continue;
65
+ watch(id);
66
+ }
67
+ for (const [id, unsubscribe] of off) {
68
+ if (sessions.binding(id) !== undefined) continue;
69
+ unsubscribe();
70
+ off.delete(id);
71
+ }
72
+ };
73
+
74
+ ctx.effect(
75
+ () =>
76
+ ctx.slots.inject("conversation.input.right", () =>
77
+ ctx.slots.register(
78
+ {
79
+ name: "conversation.input.right",
80
+ id: "session-handoff.ring",
81
+ order: 90,
82
+ inject: () => ({}),
83
+ },
84
+ HandoffRing,
85
+ ),
86
+ ),
87
+ "session-handoff: handoff ring",
88
+ );
89
+
90
+ // Optional: the ACP adapter's remote exists only while that plugin is mounted. Outside this
91
+ // scope the reader stays unset and the ring falls back to the DSH `contextPressure`.
92
+ // `remote` is requested alongside, as the adapter's own client does for its namespace.
93
+ ctx.inject(["remote", "remote.dshAcp"], (acpCtx) => {
94
+ const remote = acpCtx.remote.dshAcp;
95
+ const reader: AcpUsageReader = async (id) => {
96
+ const result = await remote.agentSessionSnapshot(id);
97
+ if (!result.ok) {
98
+ console.warn("session-handoff: ACP usage unavailable", result);
99
+ return undefined;
100
+ }
101
+ const usage = result.value.contextUsage;
102
+ return usage === null ? undefined : usage;
103
+ };
104
+ setAcpUsageReader(reader);
105
+ return () => setAcpUsageReader(undefined);
106
+ });
107
+
108
+ const dispose = sessions.list.subscribe(sync);
109
+ sync();
110
+ ctx.effect(
111
+ () => () => {
112
+ dispose();
113
+ for (const unsubscribe of off.values()) unsubscribe();
114
+ off.clear();
115
+ },
116
+ "session-handoff: launch watcher",
117
+ );
118
+ }
@@ -0,0 +1,31 @@
1
+ export type HandoffLevel = "none" | "soft" | "strong";
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;
5
+
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: 70_000, strong: 100_000 };
9
+ const COLD = { soft: 40_000, strong: 70_000 };
10
+ // The window still caps the bars, so small-window models warn before compaction does.
11
+ const SOFT_WINDOW_SHARE = 0.6;
12
+ const STRONG_WINDOW_SHARE = 0.8;
13
+
14
+ export function handoffLevel(
15
+ pressureTokens: number | undefined,
16
+ contextWindow: number | undefined,
17
+ cold: boolean,
18
+ ): HandoffLevel {
19
+ if (pressureTokens === undefined) return "none";
20
+ const bar = cold ? COLD : WARM;
21
+ const soft =
22
+ contextWindow === undefined
23
+ ? bar.soft
24
+ : Math.min(bar.soft, SOFT_WINDOW_SHARE * contextWindow);
25
+ const strong =
26
+ contextWindow === undefined
27
+ ? bar.strong
28
+ : Math.min(bar.strong, STRONG_WINDOW_SHARE * contextWindow);
29
+ if (pressureTokens >= strong) return "strong";
30
+ return pressureTokens >= soft ? "soft" : "none";
31
+ }
@@ -0,0 +1,85 @@
1
+ import type {} from "@deepseek-ai/dsh-client-ui-session/client";
2
+ import type { SessionStandardProps } from "@deepseek-ai/dsh-client-ui-slots";
3
+ import type {} from "@deepseek-ai/dsh-token-meter/client";
4
+ import {
5
+ createElement,
6
+ useEffect,
7
+ useState,
8
+ useSyncExternalStore,
9
+ } from "react";
10
+ import {
11
+ type AcpUsage,
12
+ currentAcpUsageReader,
13
+ subscribeAcpUsageReader,
14
+ } from "./acp-usage.ts";
15
+ import { CACHE_TTL_MS, handoffLevel } from "./level.ts";
16
+
17
+ const COLOR = { soft: "#d9a400", strong: "#d62839" } as const;
18
+
19
+ /** Small ring beside the send button once the session is big enough that `/handoff` pays off. */
20
+ export function HandoffRing({
21
+ sessionId,
22
+ useProjection,
23
+ useSession,
24
+ }: Pick<SessionStandardProps, "sessionId" | "useProjection" | "useSession">) {
25
+ const pressure = useProjection("contextPressure");
26
+ const running = useSession((session) => session.running);
27
+ const [acp, setAcp] = useState<AcpUsage | undefined>(undefined);
28
+ const [cold, setCold] = useState(false);
29
+
30
+ // ACP agents report occupancy to the adapter, never to DSH's `contextPressure`; read it
31
+ // when a turn settles. The reader is unset (so this is a no-op) without the adapter.
32
+ const readUsage = useSyncExternalStore(
33
+ subscribeAcpUsageReader,
34
+ currentAcpUsageReader,
35
+ );
36
+ useEffect(() => {
37
+ if (running || readUsage === undefined) return;
38
+ let live = true;
39
+ void readUsage(sessionId).then((usage) => {
40
+ if (live) setAcp(usage);
41
+ });
42
+ return () => {
43
+ live = false;
44
+ };
45
+ }, [sessionId, running, readUsage]);
46
+
47
+ const tokens =
48
+ pressure !== undefined && pressure.pressureTokens !== undefined
49
+ ? pressure.pressureTokens
50
+ : acp?.used;
51
+ const window =
52
+ pressure !== undefined && pressure.contextWindow !== undefined
53
+ ? pressure.contextWindow
54
+ : acp?.size;
55
+
56
+ // A new usage sample or a running turn means the cache was just touched; once idle for
57
+ // the TTL it is cold. Mount counts as warm because the last request time is unknown.
58
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `tokens` is the restart trigger
59
+ useEffect(() => {
60
+ setCold(false);
61
+ if (running) return;
62
+ const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
63
+ return () => clearTimeout(timer);
64
+ }, [tokens, running]);
65
+
66
+ const level = handoffLevel(tokens, window, cold);
67
+ if (level === "none" || tokens === undefined) return null;
68
+ const k = Math.round(tokens / 1000);
69
+ const hint = cold
70
+ ? "cache is cold, a fresh session is cheaper now"
71
+ : "consider a fresh session";
72
+ return createElement("span", {
73
+ role: "img",
74
+ title: `Context ${k}k tokens: ${hint} (/handoff)`,
75
+ "aria-label": `Handoff ${level === "strong" ? "recommended" : "suggested"}`,
76
+ style: {
77
+ width: 14,
78
+ height: 14,
79
+ boxSizing: "border-box",
80
+ borderRadius: "50%",
81
+ border: `2px solid ${COLOR[level]}`,
82
+ flex: "none",
83
+ },
84
+ });
85
+ }
package/src/handoff.ts ADDED
@@ -0,0 +1,235 @@
1
+ import type { ContentBlock } from "@deepseek-ai/dsh-llm";
2
+ import type { TurnEndReason } from "@deepseek-ai/dsh-session";
3
+ import type { SessionLogSnapshot } from "@deepseek-ai/dsh-session-query";
4
+
5
+ /**
6
+ * Bounds on quoted text. The Goal and older turns quote a head and a tail of the user's
7
+ * ask; the last RECENT_TURNS use a larger budget so the receiving agent still reads the
8
+ * actual words.
9
+ */
10
+ const ASK_HEAD = 500;
11
+ const ASK_TAIL = 300;
12
+ const OUTCOME_LIMIT = 240;
13
+ const FAILURE_LIMIT = 200;
14
+ const ARTIFACT_LIMIT = 12;
15
+ const RECENT_TURNS = 5;
16
+ const RECENT_HEAD = 1200;
17
+ const RECENT_TAIL = 400;
18
+
19
+ /** Tool argument keys that carry a durable file path. */
20
+ const PATH_KEYS = ["path", "file_path", "filePath", "notebook_path"];
21
+
22
+ export interface RenderedHandoff {
23
+ readonly markdown: string;
24
+ readonly turns: number;
25
+ }
26
+
27
+ interface TurnArc {
28
+ readonly turn: number;
29
+ ask: string;
30
+ outcome: string;
31
+ reason: TurnEndReason | undefined;
32
+ }
33
+
34
+ export function renderHandoff(snapshot: SessionLogSnapshot): RenderedHandoff {
35
+ 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;
42
+ let goal = "";
43
+
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;
97
+ }
98
+ default:
99
+ break;
100
+ }
101
+ }
102
+
103
+ const id = String(snapshot.session.id);
104
+ const cwd = snapshot.session.cwd;
105
+ const lines = [
106
+ `# Handoff — ${id}`,
107
+ "",
108
+ `- session: \`${id}\``,
109
+ `- cwd: \`${cwd === undefined ? "unknown" : cwd}\``,
110
+ `- created: ${new Date(snapshot.session.createdAt).toISOString()}`,
111
+ `- events: ${snapshot.events.length}`,
112
+ `- turns: ${turns.length}`,
113
+ "",
114
+ "## Goal",
115
+ "",
116
+ goal === "" ? "none" : goal,
117
+ "",
118
+ "## Turns",
119
+ "",
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"),
127
+ "",
128
+ "## Failures",
129
+ "",
130
+ failures.length === 0 ? "none" : failures.join("\n"),
131
+ "",
132
+ "## Artifacts",
133
+ "",
134
+ artifacts.length === 0
135
+ ? "none"
136
+ : artifacts.map((file) => `- \`${file}\``).join("\n"),
137
+ ];
138
+
139
+ return { markdown: `${lines.join("\n")}\n`, turns: turns.length };
140
+ }
141
+
142
+ export function handoffInstruction(sessionId: string, file: string): string {
143
+ return [
144
+ `The handoff brief for session ${sessionId} is at ${file}.`,
145
+ "",
146
+ "Read that file now, then reply with three lines and stop:",
147
+ "Goal: <one line>",
148
+ "State: <one line>",
149
+ "Next: <one line>",
150
+ "",
151
+ "Do not start the work until the user confirms the next action.",
152
+ ].join("\n");
153
+ }
154
+
155
+ /** Recent turns quote the ask and reply at length; older turns are flattened and short. */
156
+ function turnBlock(turn: TurnArc, recent: boolean): string {
157
+ const kind = turn.reason === undefined ? "unfinished" : turn.reason.kind;
158
+ const body = (
159
+ recent
160
+ ? [
161
+ elide(turn.ask, RECENT_HEAD, RECENT_TAIL),
162
+ elide(turn.outcome, RECENT_HEAD, RECENT_TAIL),
163
+ ]
164
+ : [
165
+ elide(flatten(turn.ask), ASK_HEAD, ASK_TAIL),
166
+ clip(turn.outcome, OUTCOME_LIMIT),
167
+ ]
168
+ )
169
+ .filter((part) => part !== "")
170
+ .join("\n\n");
171
+ return `### T${turn.turn} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
172
+ }
173
+
174
+ function blockText(blocks: readonly ContentBlock[]): string {
175
+ const parts: string[] = [];
176
+ for (const block of blocks) {
177
+ if (block.type === "text") parts.push(block.text);
178
+ }
179
+ return parts.join("\n");
180
+ }
181
+
182
+ /** Collapses whitespace so a quote fits on one line, then cuts it. */
183
+ function clip(value: string, limit: number): string {
184
+ const flat = flatten(value);
185
+ if (flat.length <= limit) return flat;
186
+ return `${flat.slice(0, limit - 1)}…`;
187
+ }
188
+
189
+ function flatten(value: string): string {
190
+ return value.replace(/\s+/g, " ").trim();
191
+ }
192
+
193
+ /**
194
+ * Keeps `head` chars from the start and `tail` chars from the end, naming how much was
195
+ * dropped. Raw text is preserved so the Tail keeps the shape of code blocks and tables.
196
+ */
197
+ function elide(value: string, head: number, tail: number): string {
198
+ const trimmed = value.trim();
199
+ if (trimmed.length <= head + tail) return trimmed;
200
+ const omitted = trimmed.length - head - tail;
201
+ return `${trimmed.slice(0, head)} … [${omitted} chars omitted] … ${trimmed.slice(-tail)}`;
202
+ }
203
+
204
+ function errorReason(
205
+ error: { name: string; code: string; reason?: string } | undefined,
206
+ ): string {
207
+ if (error === undefined) return "failed";
208
+ if (error.reason === undefined) return error.code;
209
+ return error.reason;
210
+ }
211
+
212
+ function collectArtifacts(
213
+ args: string,
214
+ into: string[],
215
+ seen: Set<string>,
216
+ ): void {
217
+ let parsed: unknown;
218
+ try {
219
+ parsed = JSON.parse(args);
220
+ } catch {
221
+ // edge case: tool arguments are model-produced JSON; a non-JSON payload names no path
222
+ return;
223
+ }
224
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
225
+ return;
226
+ // Safe: the guard above admits only non-null, non-array objects.
227
+ const record = parsed as Record<string, unknown>;
228
+ for (const key of PATH_KEYS) {
229
+ 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;
234
+ }
235
+ }
package/src/index.ts ADDED
@@ -0,0 +1,287 @@
1
+ import { mkdir, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import type { Context } from "@deepseek-ai/cordis";
4
+ import type { Agent } from "@deepseek-ai/dsh-agent";
5
+ import type { SessionCreateValue } from "@deepseek-ai/dsh-api-session-controller";
6
+ import type {
7
+ CommandInvocation,
8
+ CommandResult,
9
+ } from "@deepseek-ai/dsh-commands";
10
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
11
+ import type {} from "@deepseek-ai/dsh-session";
12
+ import type { SessionId } from "@deepseek-ai/dsh-session/types";
13
+ import type {
14
+ SessionLogSnapshot,
15
+ SessionRecord,
16
+ } from "@deepseek-ai/dsh-session-query";
17
+ import type {} from "@deepseek-ai/dsh-session-title";
18
+ import type {} from "@deepseek-ai/dsh-working-directory";
19
+ import type { Workspace } from "@deepseek-ai/dsh-workspace";
20
+ import { scratchDirectory } from "@lukstei/dsh-scratch-dir";
21
+ import { handoffInstruction, renderHandoff } from "./handoff.ts";
22
+ import { formatLaunchResult } from "./launch.ts";
23
+
24
+ export const name = "session-handoff";
25
+ export const inject = [
26
+ "commands",
27
+ "sessionQuery",
28
+ "workingDirectory",
29
+ "sessionController",
30
+ "sessionTitle",
31
+ "workspaceRegistry",
32
+ ];
33
+
34
+ const HANDOFF_FILE = "HANDOFF.md";
35
+ const RECENT_LIMIT = 5;
36
+ const SHORT_ID_LENGTH = 8;
37
+
38
+ export function apply(ctx: Context): void {
39
+ ctx.commands.register({
40
+ name: "handoff",
41
+ description:
42
+ "Hand this session off to a new one, or write the resume brief for <session-id> into this one",
43
+ // edge case: without a declared input the client sends the raw line to the
44
+ // model as a prompt and this handler never runs.
45
+ input: { hint: "[session-id]" },
46
+ handler: (invocation: CommandInvocation): Promise<CommandResult> =>
47
+ handoff(ctx, invocation),
48
+ });
49
+ }
50
+
51
+ export function resolveHandoffTarget(
52
+ sessions: readonly SessionRecord[],
53
+ query: string,
54
+ ): readonly SessionRecord[] {
55
+ const exact = sessions.filter(
56
+ (session) => String(session.header.id) === query,
57
+ );
58
+ if (exact.length > 0) return exact;
59
+ return sessions.filter((session) =>
60
+ String(session.header.id).startsWith(query),
61
+ );
62
+ }
63
+
64
+ async function handoff(
65
+ ctx: Context,
66
+ invocation: CommandInvocation,
67
+ ): Promise<CommandResult> {
68
+ const raw = invocation.rawInput.trim();
69
+ // edge case: no id means "this session", the common case, so it skips the
70
+ // session index entirely and reads the agent's own session.
71
+ const launch = raw === "";
72
+ const agent = invocation.agent;
73
+
74
+ let targetId: SessionId;
75
+ if (launch) {
76
+ targetId = agent.session.id;
77
+ } else {
78
+ const sessions = await ctx.sessionQuery.listSessions(invocation.signal);
79
+ const matches = resolveHandoffTarget(sessions, raw);
80
+ if (matches.length === 0) {
81
+ const recent = sessions
82
+ .slice(0, RECENT_LIMIT)
83
+ .map((session) => `- ${String(session.header.id)}`)
84
+ .join("\n");
85
+ return {
86
+ kind: "error",
87
+ text: `No session matches "${raw}". Most recent sessions:\n${recent}`,
88
+ };
89
+ }
90
+ if (matches.length > 1) {
91
+ const candidates = matches
92
+ .map((session) => `- ${String(session.header.id)}`)
93
+ .join("\n");
94
+ return { kind: "error", text: `"${raw}" is ambiguous:\n${candidates}` };
95
+ }
96
+ targetId = matches[0].header.id;
97
+ if (targetId === agent.session.id) {
98
+ return {
99
+ kind: "error",
100
+ text: "That is this session; there is nothing to hand off.",
101
+ };
102
+ }
103
+ }
104
+
105
+ try {
106
+ const snapshot = await ctx.sessionQuery.readSession(targetId);
107
+ const rendered = renderHandoff(snapshot);
108
+ if (rendered.turns === 0) {
109
+ return {
110
+ kind: "error",
111
+ text: launch
112
+ ? "This session has no turns to hand off."
113
+ : `Session ${shortId(targetId)} has no turns to hand off.`,
114
+ };
115
+ }
116
+ if (launch) {
117
+ const created = await createBeside(
118
+ ctx,
119
+ agent,
120
+ targetId,
121
+ rendered.markdown,
122
+ snapshot,
123
+ invocation.signal,
124
+ );
125
+ return {
126
+ kind: "success",
127
+ text: formatLaunchResult(created.sessionId),
128
+ };
129
+ }
130
+
131
+ const file = await deliver(ctx, agent, targetId, rendered.markdown);
132
+ return {
133
+ kind: "success",
134
+ text: `Handoff for ${shortId(targetId)} (${rendered.turns} turns) → ${file}`,
135
+ };
136
+ } catch (error: unknown) {
137
+ return {
138
+ kind: "error",
139
+ text: `Handoff failed: ${error instanceof Error ? error.message : String(error)}`,
140
+ };
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Write the brief into the agent's own scratch directory and queue the follow-up
146
+ * turn that tells it to read that file.
147
+ * @param ctx - Host context.
148
+ * @param agent - Agent that receives the brief and the follow-up.
149
+ * @param targetId - Durable id of the handed-off session.
150
+ * @param markdown - Rendered brief.
151
+ * @returns absolute path of the written brief.
152
+ */
153
+ async function deliver(
154
+ ctx: Context,
155
+ agent: Agent,
156
+ targetId: string,
157
+ markdown: string,
158
+ ): Promise<string> {
159
+ const dir = scratchDirectory(
160
+ ctx.workingDirectory.get(agent.session),
161
+ String(agent.session.id),
162
+ );
163
+ if (dir === undefined) {
164
+ throw new Error(
165
+ `Unsafe session id "${String(agent.session.id)}"; no handoff written.`,
166
+ );
167
+ }
168
+ await mkdir(dir, { recursive: true });
169
+ const file = path.join(dir, HANDOFF_FILE);
170
+ await writeFile(file, markdown, "utf8");
171
+ agent.followup(
172
+ createUserMessage({
173
+ content: [
174
+ {
175
+ type: "text",
176
+ text: handoffInstruction(targetId, file),
177
+ },
178
+ ],
179
+ source: { kind: "user" },
180
+ }),
181
+ );
182
+ return file;
183
+ }
184
+
185
+ function workspaceOf(
186
+ ctx: Context,
187
+ sessionId: SessionId,
188
+ ): Workspace | undefined {
189
+ for (const workspace of ctx.workspaceRegistry.list()) {
190
+ if (workspace.sessionIds.includes(sessionId)) return workspace;
191
+ }
192
+ return undefined;
193
+ }
194
+
195
+ function kanbanLinkArgs(snapshot: SessionLogSnapshot): string[] {
196
+ const all: string[] = [];
197
+ for (const event of snapshot.events) {
198
+ if (event.type !== "command/run" || event.data.name !== "kanban") continue;
199
+ const args = event.data.args;
200
+ if (args === undefined) continue;
201
+ try {
202
+ const parsed: unknown = JSON.parse(args);
203
+ if (
204
+ typeof parsed === "object" &&
205
+ parsed !== null &&
206
+ "action" in parsed &&
207
+ parsed.action === "add-link"
208
+ )
209
+ all.push(args);
210
+ } catch {
211
+ // edge case: non-JSON kanban args carry no link
212
+ }
213
+ }
214
+ return all;
215
+ }
216
+
217
+ function shortId(id: string): string {
218
+ return id.slice(0, SHORT_ID_LENGTH);
219
+ }
220
+
221
+ /**
222
+ * Create the resumed session beside this one: same workspace, same preset, same
223
+ * model, the brief in its own scratch directory, and one follow-up turn that
224
+ * tells it to read that brief.
225
+ * @param ctx - Host context.
226
+ * @param source - Session the command runs in.
227
+ * @param targetId - Durable id of the handed-off session.
228
+ * @param markdown - Rendered brief.
229
+ * @param snapshot - Source session log, the origin of the kanban links to copy.
230
+ * @param signal - Cancellation signal of the invoking command.
231
+ * @returns the created session identity.
232
+ */
233
+ async function createBeside(
234
+ ctx: Context,
235
+ source: Agent,
236
+ targetId: string,
237
+ markdown: string,
238
+ snapshot: SessionLogSnapshot,
239
+ signal: AbortSignal,
240
+ ): Promise<SessionCreateValue> {
241
+ const selection = source.model.current();
242
+ const agentPreset = source.session.header.agentPreset;
243
+ // edge case: a session created by cwd alone is attached to no workspace, so it
244
+ // would stay out of the sidebar tree until the next Host start.
245
+ const workspace = workspaceOf(ctx, source.session.id);
246
+ const created = await ctx.sessionController.create(
247
+ workspace === undefined
248
+ ? { cwd: ctx.workingDirectory.get(source.session), agentPreset }
249
+ : { workspaceId: workspace.id, agentPreset },
250
+ );
251
+ const resolved = await ctx.sessionController.resolveAgent(created.sessionId);
252
+ if ("error" in resolved) throw new Error(resolved.error.message);
253
+
254
+ const agent = resolved.agent;
255
+ // edge case: the fresh agent would otherwise start on the deployment default,
256
+ // so the caller's selection is recorded before its first turn.
257
+ if (selection !== undefined) agent.model.select(selection);
258
+
259
+ // edge case: left to itself the session is titled from the first message it
260
+ // receives, which is the handoff instruction, so every handoff reads "Handoff
261
+ // brief"; a user title pins the derived one against automatic generation.
262
+ const sourceTitle = ctx.sessionTitle.get(source.session);
263
+ ctx.sessionTitle.rename(
264
+ agent.session,
265
+ sourceTitle === undefined
266
+ ? `Handoff ${shortId(targetId)}`
267
+ : `${sourceTitle.title} - Handoff`,
268
+ );
269
+
270
+ // edge case: a session the controller creates carries no kanban marker, so the
271
+ // board would never list it; this is the init kanban's own client sends.
272
+ await ctx.commands.execute(
273
+ agent,
274
+ `/kanban ${JSON.stringify({ action: "init", createdAt: Date.now() })}`,
275
+ [],
276
+ signal,
277
+ );
278
+
279
+ // Replaying the source's add-link commands in order reproduces its link set,
280
+ // since the kanban fold dedupes by url.
281
+ for (const args of kanbanLinkArgs(snapshot)) {
282
+ await ctx.commands.execute(agent, `/kanban ${args}`, [], signal);
283
+ }
284
+
285
+ await deliver(ctx, agent, targetId, markdown);
286
+ return created;
287
+ }
package/src/launch.ts ADDED
@@ -0,0 +1,28 @@
1
+ import type { SessionEvent, SessionId } from "@deepseek-ai/dsh-session/types";
2
+
3
+ /**
4
+ * First line of the launch result. A slash command has no structured return
5
+ * channel, so the Host encodes the new Session id here and the client reads it
6
+ * back out of the durable `command/done` record.
7
+ */
8
+ export const LAUNCH_PREFIX = "Handoff launched: ";
9
+
10
+ export function formatLaunchResult(sessionId: SessionId): string {
11
+ return `${LAUNCH_PREFIX}${String(sessionId)}`;
12
+ }
13
+
14
+ /**
15
+ * The launched Session id carried by one durable event, or `undefined` when the
16
+ * event is not a successful handoff launch.
17
+ */
18
+ export function launchedSessionId(event: SessionEvent): SessionId | undefined {
19
+ if (event.type !== "command/done") return undefined;
20
+ if (event.data.kind !== "success") return undefined;
21
+ const { text } = event.data;
22
+ if (typeof text !== "string" || !text.startsWith(LAUNCH_PREFIX)) {
23
+ return undefined;
24
+ }
25
+ // edge case: the id is a host-generated uuid that round-tripped through the
26
+ // result text, so the brand is restored rather than validated.
27
+ return text.slice(LAUNCH_PREFIX.length) as SessionId;
28
+ }