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

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,209 @@
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. `/handoff` starts a new session beside the current one with the brief loaded, on the same model or on a model picked from a list.
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`, `llm`, `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 google/gemini-4
50
+ ```
51
+
52
+ Typed in the composer, a bare `/handoff` opens the same provider-grouped model list as `/model`, with the current model highlighted; picking a row starts the new session on that model with the brief loaded. The argued form (`<provider>/<model>`, split at the first slash) skips the list. The Host checks the route against the registered LLM providers and the provider's own model resolution, so a typo returns an error before any session is created. Because it creates a new session, it also works across native and ACP models, where an in-place model switch is blocked. Reasoning effort is the model's default. The handoff ring sends the bare line straight to the Host, which keeps the source's model and skips the list. The client half also needs `@deepseek-ai/dsh-client-ui-commands` and `@deepseek-ai/dsh-client-ui-model-selection`.
53
+
54
+ ### Plugin dependencies
55
+
56
+ Server-side and client-side entries.
57
+
58
+ **Server-side** (`inject`: `commands`, `llm`, `sessionQuery`, `workingDirectory`, `sessionController`, `sessionTitle`, `workspaceRegistry`):
59
+
60
+ | Plugin / service | Required? | Provided by | Effect without it |
61
+ |---|---|---|---|
62
+ | `commands` | Required | @deepseek-ai/dsh-commands | Plugin stays pending; never applies. No `/handoff`. |
63
+ | `llm` | Required | @deepseek-ai/dsh-llm | Plugin stays pending; never applies. |
64
+ | `sessionQuery` | Required | @deepseek-ai/dsh-session-query | Plugin stays pending; never applies. |
65
+ | `workingDirectory` | Required | @deepseek-ai/dsh-working-directory | Plugin stays pending; never applies. |
66
+ | `sessionController` | Required | @deepseek-ai/dsh-api-session-controller | Plugin stays pending; never applies. |
67
+ | `sessionTitle` | Required | @deepseek-ai/dsh-session-title | Plugin stays pending; never applies. |
68
+ | `workspaceRegistry` | Required | @deepseek-ai/dsh-workspace | Plugin stays pending; never applies. |
69
+
70
+ **Client-side** (`inject`: `sessions`, `splitView`, `slots`; all required):
71
+
72
+ | Plugin / service | Required? | Provided by | Effect without it |
73
+ |---|---|---|---|
74
+ | `sessions` | Required | @deepseek-ai/dsh-api-session-controller | Plugin stays pending; never applies. |
75
+ | `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. |
76
+
77
+ | `slots` | Required | @deepseek-ai/dsh-client-ui-renderer | Plugin stays pending; never applies. |
78
+
79
+ ### Handoff ring
80
+
81
+ 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`.
82
+
83
+ Code import (no mount): [`@lukstei/dsh-scratch-dir`](../dsh-scratch-dir/README.md) (`scratchDirectory`).
84
+
85
+ Used by: nothing.
86
+
87
+ ### Modes
88
+
89
+ | Input | Model of the new session |
90
+ |---|---|
91
+ | `/handoff` (Host, e.g. from the ring) | the source's own |
92
+ | `/handoff <provider>/<model>` | that model, validated first |
93
+
94
+ Any other argument is an error naming the expected form. A session with no turns returns an error. All I/O failures return `{ kind: "error" }`.
95
+
96
+ ### Launch
97
+
98
+ 1. Renders this session's brief.
99
+ 2. Creates a session via `sessionController.create()` in the current workspace (falls back to `cwd` when the session has no workspace), same `agentPreset`.
100
+ 3. Selects the requested model on the new agent, or replays the source's own selection.
101
+ 4. Titles it with the full source title (or `Handoff <first 8 id chars>` when untitled) and renames the source to `<title> (Resumed)` unless it already ends with that. A user title pins it against auto-generated titles. Adds a Kanban link `Resumed from <source id>` (`dsh://sessions/<id>`, opens the source session) to record the origin.
102
+ 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.
103
+ 6. Copies the source session's kanban links by replaying its `add-link` commands against the new agent.
104
+ 7. Writes `HANDOFF.md` into the new session's scratch directory and queues the read-the-brief follow-up.
105
+ 8. Returns `Handoff launched: <id>`.
106
+
107
+ The client opens the pane. Without the client bundle the session is created but not opened.
108
+
109
+ ### Brief layout
110
+
111
+ | Section | Contents |
112
+ | --- | --- |
113
+ | Header | session id, `chain` of ancestor ids (when handed off before), cwd, creation time, event and turn counts across the chain |
114
+ | `## Goal` | first real user prompt of the oldest ancestor, head 500 + tail 300 chars |
115
+ | `## Turns` | one `### T<n> [end reason]` block per turn, numbered across the chain, handoff turns skipped. Last 5 turns quote each 1200 head + 400 tail chars; the 30 before them flatten to the ask (500/300) and reply (240 chars); older ones collapse to `… N earlier turns omitted` |
116
+ | `## Failures` | newest 20 `tool/result` errors: turn, session id when from an ancestor, tool name, reason (200 chars), plus `… N older failures omitted` |
117
+ | `## Artifacts` | deduped paths from tool call arguments (`path`, `file_path`, `filePath`, `notebook_path`) across the chain, newest 100, plus `… N older paths omitted`; the brief files themselves are excluded |
118
+
119
+ 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.
120
+
121
+ Empty sections render `none`. Output is deterministic for a given log. `request/header`, `agent/inbox/spliced` and reasoning blocks are excluded.
122
+
123
+ -----
124
+
125
+ <a id="understand-the-implementation"></a>
126
+ ## Understand the implementation
127
+
128
+ <details>
129
+ <summary>Implementation internals — click to expand</summary>
130
+
131
+ Files:
132
+
133
+ - [`src/index.ts`](src/index.ts): command registration, model validation, `deliver` (write brief + queue follow-up), `createBeside` (launch).
134
+ - [`src/handoff.ts`](src/handoff.ts): `renderHandoff` and `handoffInstruction`, pure.
135
+ - [`src/launch.ts`](src/launch.ts): `LAUNCH_PREFIX`, `formatLaunchResult`, `launchedSessionId`.
136
+ - [`src/client/index.ts`](src/client/index.ts): client watcher. Tests sit beside each file.
137
+
138
+ Details:
139
+
140
+ - The command declares `input: { hint: "[provider/model]" }`. Without a declared input the client sends the raw line to the model as a prompt and the handler never runs.
141
+ - 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.replaceSession()` when it sees a successful `command/done` starting with `Handoff launched: `, replacing the pane in-place atomically. It then sends `/kanban {"action":"done"}` to the source session, as the Kanban Done button does. A source never initialised in Kanban ignores the done action.
142
+ - 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.
143
+ - 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.
144
+ - 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`.
145
+ - 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.
146
+ - Turn attribution: `user/message` carries no turn number, so it is attributed to the most recently opened turn.
147
+ - Artifact extraction parses tool arguments as JSON; non-JSON payloads are ignored.
148
+ - 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.
149
+ - The scratch path comes from `scratchDirectory()`; an unsafe id throws and the command returns an error.
150
+
151
+ Trust boundary: the session id argument and session log contents are untrusted text; output is markdown written under the scratch directory only.
152
+
153
+ </details>
154
+
155
+ -----
156
+
157
+ <a id="further-exploration"></a>
158
+ ## Further Exploration
159
+
160
+ - [`@lukstei/dsh-scratch-dir`](../dsh-scratch-dir/README.md) — scratch path convention.
161
+ - [`@lukstei/dsh-client-split-view`](../dsh-client-split-view) — pane host.
162
+ - Upstream: [DSH module graph](https://github.com/deepseek-ai/deepseek-harness/blob/master/docs/module-graph.md).
163
+
164
+ <a id="model-experience"></a>
165
+ ## Model Experience
166
+
167
+ ### /handoff
168
+
169
+ #### What the model sees
170
+
171
+ One queued follow-up user message in the receiving session:
172
+
173
+ ```text
174
+ The handoff brief for session <id> is at <path>/HANDOFF.md.
175
+
176
+ Read that file now, then reply with three lines and stop:
177
+ Goal: <one line>
178
+ State: <one line>
179
+ Next: <one line>
180
+
181
+ Do not start the work until the user confirms the next action.
182
+ ```
183
+
184
+ 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.
185
+
186
+ #### Token effect
187
+
188
+ 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).
189
+
190
+ #### KV Cache effect
191
+
192
+ Appended message only; the prompt prefix is untouched. In a launched session this is the first turn.
193
+
194
+ <a id="known-limitations-and-deferred-work"></a>
195
+ ## Known Limitations and Deferred Work
196
+
197
+ - Opening the new pane needs the client bundle and the split-view plugin.
198
+ - The brief is a heuristic summary of the log; tool outputs, reasoning and request headers are not included.
199
+ - `## Turns` size is unbounded in turn count.
200
+
201
+ <a id="dev-note"></a>
202
+ ### Dev Note
203
+
204
+ <details>
205
+ <summary>Working context for maintainers — click to expand</summary>
206
+
207
+ None.
208
+
209
+ </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,248 @@
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 _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
8
+ let react = require("react");
9
+ /**
10
+ * The launched Session id carried by one durable event, or `undefined` when the
11
+ * event is not a successful handoff launch.
12
+ */
13
+ function launchedSessionId(event) {
14
+ if (event.type !== "command/done") return void 0;
15
+ if (event.data.kind !== "success") return void 0;
16
+ const { text } = event.data;
17
+ if (typeof text !== "string" || !text.startsWith("Handoff launched: ")) return;
18
+ return text.slice(18);
19
+ }
20
+ // src/client/acp-usage.ts
21
+ let reader;
22
+ const listeners = /* @__PURE__ */ new Set();
23
+ function setAcpUsageReader(next) {
24
+ reader = next;
25
+ for (const listener of listeners) listener();
26
+ }
27
+ /** `useSyncExternalStore` seat, so a ring mounted before the adapter re-reads once it arrives. */
28
+ function subscribeAcpUsageReader(listener) {
29
+ listeners.add(listener);
30
+ return () => {
31
+ listeners.delete(listener);
32
+ };
33
+ }
34
+ function currentAcpUsageReader() {
35
+ return reader;
36
+ }
37
+ // src/client/level.ts
38
+ /** Anthropic prompt-cache TTL: past this idle gap the next turn re-writes the whole context. */
39
+ const CACHE_TTL_MS = 3e5;
40
+ const WARM = {
41
+ soft: 1e5,
42
+ strong: 15e4
43
+ };
44
+ const COLD = {
45
+ soft: 7e4,
46
+ strong: 1e5
47
+ };
48
+ const SOFT_WINDOW_SHARE = .6;
49
+ const STRONG_WINDOW_SHARE = .8;
50
+ function handoffLevel(pressureTokens, contextWindow, cold) {
51
+ if (pressureTokens === void 0) return "none";
52
+ const bar = cold ? COLD : WARM;
53
+ const soft = contextWindow === void 0 ? bar.soft : Math.min(bar.soft, SOFT_WINDOW_SHARE * contextWindow);
54
+ if (pressureTokens >= (contextWindow === void 0 ? bar.strong : Math.min(bar.strong, STRONG_WINDOW_SHARE * contextWindow))) return "strong";
55
+ return pressureTokens >= soft ? "soft" : "none";
56
+ }
57
+ // src/client/ring.ts
58
+ const COLOR = {
59
+ soft: "#d9a400",
60
+ strong: "#d62839"
61
+ };
62
+ /** Gauge icon beside the send button once the session is big enough that `/handoff` pays off. */
63
+ function HandoffRing({ sessionId, useProjection, useSession, onHandoff }) {
64
+ const pressure = useProjection("contextPressure");
65
+ const running = useSession((session) => session.running);
66
+ const [acp, setAcp] = (0, react.useState)(void 0);
67
+ const [cold, setCold] = (0, react.useState)(false);
68
+ const [pendingSession, setPendingSession] = (0, react.useState)(void 0);
69
+ const readUsage = (0, react.useSyncExternalStore)(subscribeAcpUsageReader, currentAcpUsageReader);
70
+ (0, react.useEffect)(() => {
71
+ if (running || readUsage === void 0) return;
72
+ let live = true;
73
+ readUsage(sessionId).then((usage) => {
74
+ if (live) setAcp(usage);
75
+ });
76
+ return () => {
77
+ live = false;
78
+ };
79
+ }, [
80
+ sessionId,
81
+ running,
82
+ readUsage
83
+ ]);
84
+ const tokens = pressure !== void 0 && pressure.pressureTokens !== void 0 ? pressure.pressureTokens : acp?.used;
85
+ const window = pressure !== void 0 && pressure.contextWindow !== void 0 ? pressure.contextWindow : acp?.size;
86
+ (0, react.useEffect)(() => {
87
+ setCold(false);
88
+ if (running) return;
89
+ const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
90
+ return () => clearTimeout(timer);
91
+ }, [tokens, running]);
92
+ const level = handoffLevel(tokens, window, cold);
93
+ if (level === "none" || tokens === void 0) return null;
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)"}`;
109
+ return (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
110
+ label,
111
+ side: "top",
112
+ portal: true,
113
+ disabled: isDisabled,
114
+ children: (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.Button, {
115
+ variant: "ghost",
116
+ size: "sm",
117
+ disabled: isDisabled,
118
+ title: isDisabled ? label : void 0,
119
+ "aria-label": label,
120
+ style: {
121
+ color: COLOR[level],
122
+ padding: 0,
123
+ width: 28
124
+ },
125
+ icon: (0, react.createElement)(_deepseek_ai_dsh_client_ui_primitives.IconGaugeOutlineMedium, { size: 16 }),
126
+ onClick: () => void startHandoff()
127
+ })
128
+ });
129
+ }
130
+ // src/client/index.ts
131
+ const inject = [
132
+ "sessions",
133
+ "splitView",
134
+ "slots",
135
+ "commandUi",
136
+ "modelDirectories"
137
+ ];
138
+ /**
139
+ * Open every session the Host reports as launched as a pane of its own. A slash
140
+ * command cannot reach the client, so the Host publishes the new id in the
141
+ * command's own `command/done` record and this plugin reads that durable window
142
+ * back.
143
+ *
144
+ * The pane is added through the split store, not `uiWorkspace.openSession`: the
145
+ * split view patches that method into a read-only overlay, whose embedded
146
+ * transcript has no composer of its own, so the prompts would keep landing in
147
+ * the session of the pane underneath.
148
+ */
149
+ function apply(ctx) {
150
+ const sessions = ctx.sessions;
151
+ const off = /* @__PURE__ */ new Map();
152
+ const markDone = async (id) => {
153
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
154
+ await reference.binding.session.command(`/kanban ${JSON.stringify({
155
+ action: "done",
156
+ doneAt: Date.now()
157
+ })}`);
158
+ });
159
+ };
160
+ const run = async (id, line) => {
161
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
162
+ const result = await reference.binding.session.command(line);
163
+ if (!result.ok) console.warn(`session-handoff: ${line} failed`, result);
164
+ });
165
+ };
166
+ const handoff = (id) => run(id, "/handoff");
167
+ ctx.effect(() => ctx.commandUi.decorate({
168
+ name: "handoff",
169
+ available: () => true,
170
+ ui: {
171
+ kind: "popupSelect",
172
+ searchMode: "fuzzy-label",
173
+ options: async (session) => {
174
+ const state = await ctx.modelDirectories.directoryFor(session.sessionId).load();
175
+ return state.groups.flatMap((group) => group.models.map((model) => ({
176
+ id: `${group.id}/${model.id}`,
177
+ label: model.name,
178
+ group: {
179
+ name: group.id,
180
+ label: group.name
181
+ },
182
+ ...state.current !== null && state.current.provider === group.id && state.current.model === model.id ? { active: true } : {}
183
+ })));
184
+ },
185
+ onSelect: (option, session) => run(session.sessionId, `/handoff ${option.id}`)
186
+ }
187
+ }), "session-handoff: /handoff picker");
188
+ const watch = (id) => {
189
+ const binding = sessions.binding(id);
190
+ if (binding === void 0) return;
191
+ const unsubscribe = binding.eventSource.subscribe(() => {
192
+ const { change } = binding.eventSource.getSnapshot();
193
+ if (change.kind !== "append") return;
194
+ for (const entry of change.entries) {
195
+ if (entry.type !== "event") continue;
196
+ const launched = launchedSessionId(entry.event);
197
+ if (launched === void 0) continue;
198
+ ctx.splitView.replaceSession(id, launched);
199
+ markDone(id);
200
+ return;
201
+ }
202
+ });
203
+ off.set(id, unsubscribe);
204
+ };
205
+ const sync = () => {
206
+ for (const id of sessions.list.getSnapshot().ids) {
207
+ if (off.has(id)) continue;
208
+ watch(id);
209
+ }
210
+ for (const [id, unsubscribe] of off) {
211
+ if (sessions.binding(id) !== void 0) continue;
212
+ unsubscribe();
213
+ off.delete(id);
214
+ }
215
+ };
216
+ ctx.effect(() => ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
217
+ name: "conversation.input.right",
218
+ id: "session-handoff.ring",
219
+ order: 1e3,
220
+ inject: () => ({ onHandoff: handoff })
221
+ }, HandoffRing)), "session-handoff: handoff ring");
222
+ ctx.inject(["remote", "remote.dshAcp"], (acpCtx) => {
223
+ const remote = acpCtx.remote.dshAcp;
224
+ const reader = async (id) => {
225
+ const result = await remote.agentSessionSnapshot(id);
226
+ if (!result.ok) {
227
+ console.warn("session-handoff: ACP usage unavailable", result);
228
+ return;
229
+ }
230
+ const usage = result.value.contextUsage;
231
+ return usage === null ? void 0 : usage;
232
+ };
233
+ setAcpUsageReader(reader);
234
+ return () => setAcpUsageReader(void 0);
235
+ });
236
+ const dispose = sessions.list.subscribe(sync);
237
+ sync();
238
+ ctx.effect(() => () => {
239
+ dispose();
240
+ for (const unsubscribe of off.values()) unsubscribe();
241
+ off.clear();
242
+ }, "session-handoff: launch watcher");
243
+ }
244
+ exports.apply = apply;
245
+ exports.inject = inject;
246
+ return module.exports;
247
+ }
248
+ });