@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.
@@ -0,0 +1,170 @@
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-commands/client";
4
+ import type {} from "@deepseek-ai/dsh-client-ui-conversation/client";
5
+ import type {} from "@deepseek-ai/dsh-client-ui-model-selection/client";
6
+ import type {} from "@deepseek-ai/dsh-client-ui-renderer/client";
7
+ import type { SessionId } from "@deepseek-ai/dsh-session/types";
8
+ import type {} from "@lukstei/dsh-client-split-view/client-contract";
9
+ import type {} from "@zaimokuza/dsh-acp-adapter/remote";
10
+ import { launchedSessionId } from "../launch.ts";
11
+ import { type AcpUsageReader, setAcpUsageReader } from "./acp-usage.ts";
12
+ import { HandoffRing } from "./ring.ts";
13
+
14
+ export const inject = [
15
+ "sessions",
16
+ "splitView",
17
+ "slots",
18
+ "commandUi",
19
+ "modelDirectories",
20
+ ];
21
+
22
+ /**
23
+ * Open every session the Host reports as launched as a pane of its own. A slash
24
+ * command cannot reach the client, so the Host publishes the new id in the
25
+ * command's own `command/done` record and this plugin reads that durable window
26
+ * back.
27
+ *
28
+ * The pane is added through the split store, not `uiWorkspace.openSession`: the
29
+ * split view patches that method into a read-only overlay, whose embedded
30
+ * transcript has no composer of its own, so the prompts would keep landing in
31
+ * the session of the pane underneath.
32
+ */
33
+ export function apply(ctx: Context): void {
34
+ // Shared Context merges the Host SessionStore with the Client ISessions, so the
35
+ // client object layer is named explicitly.
36
+ const sessions = ctx.sessions as unknown as ISessions;
37
+ const off = new Map<SessionId, () => void>();
38
+
39
+ // Same effect as the Kanban Done button: record done.
40
+ const markDone = async (id: SessionId): Promise<void> => {
41
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
42
+ await reference.binding.session.command(
43
+ `/kanban ${JSON.stringify({ action: "done", doneAt: Date.now() })}`,
44
+ );
45
+ });
46
+ };
47
+
48
+ // Same command the user would type; sent directly so the composer draft stays untouched.
49
+ const run = async (id: SessionId, line: string): Promise<void> => {
50
+ await sessions.using(id, { source: "splitView" }, async (reference) => {
51
+ const result = await reference.binding.session.command(line);
52
+ if (!result.ok) {
53
+ console.warn(`session-handoff: ${line} failed`, result);
54
+ }
55
+ });
56
+ };
57
+ const handoff = (id: SessionId): Promise<void> => run(id, "/handoff");
58
+
59
+ // A bare composer `/handoff` opens the same model list as `/model`; the pick is
60
+ // submitted back as the argued line the Host command parses (the ring sends the bare line straight to the Host, which keeps the source model).
61
+ ctx.effect(
62
+ () =>
63
+ ctx.commandUi.decorate({
64
+ name: "handoff",
65
+ available: () => true,
66
+ ui: {
67
+ kind: "popupSelect",
68
+ searchMode: "fuzzy-label",
69
+ options: async (session) => {
70
+ const state = await ctx.modelDirectories
71
+ .directoryFor(session.sessionId)
72
+ .load();
73
+ return state.groups.flatMap((group) =>
74
+ group.models.map((model) => ({
75
+ id: `${group.id}/${model.id}`,
76
+ label: model.name,
77
+ group: { name: group.id, label: group.name },
78
+ ...(state.current !== null &&
79
+ state.current.provider === group.id &&
80
+ state.current.model === model.id
81
+ ? { active: true }
82
+ : {}),
83
+ })),
84
+ );
85
+ },
86
+ onSelect: (option, session) =>
87
+ run(session.sessionId, `/handoff ${option.id}`),
88
+ },
89
+ }),
90
+ "session-handoff: /handoff picker",
91
+ );
92
+
93
+ const watch = (id: SessionId): void => {
94
+ const binding = sessions.binding(id);
95
+ if (binding === undefined) return;
96
+ const unsubscribe = binding.eventSource.subscribe(() => {
97
+ const { change } = binding.eventSource.getSnapshot();
98
+ // edge case: `replace` replays the whole window on first open and again
99
+ // after every reconnect gap, so it would re-open panes the user closed;
100
+ // the split view already restores its own panes from local storage.
101
+ if (change.kind !== "append") return;
102
+ for (const entry of change.entries) {
103
+ if (entry.type !== "event") continue;
104
+ const launched = launchedSessionId(entry.event);
105
+ if (launched === undefined) continue;
106
+ ctx.splitView.replaceSession(id, launched);
107
+ void markDone(id);
108
+ return;
109
+ }
110
+ });
111
+ off.set(id, unsubscribe);
112
+ };
113
+
114
+ const sync = (): void => {
115
+ for (const id of sessions.list.getSnapshot().ids) {
116
+ if (off.has(id)) continue;
117
+ watch(id);
118
+ }
119
+ for (const [id, unsubscribe] of off) {
120
+ if (sessions.binding(id) !== undefined) continue;
121
+ unsubscribe();
122
+ off.delete(id);
123
+ }
124
+ };
125
+
126
+ ctx.effect(
127
+ () =>
128
+ ctx.slots.inject("conversation.input.right", () =>
129
+ ctx.slots.register(
130
+ {
131
+ name: "conversation.input.right",
132
+ id: "session-handoff.ring",
133
+ order: 1000,
134
+ inject: () => ({ onHandoff: handoff }),
135
+ },
136
+ HandoffRing,
137
+ ),
138
+ ),
139
+ "session-handoff: handoff ring",
140
+ );
141
+
142
+ // Optional: the ACP adapter's remote exists only while that plugin is mounted. Outside this
143
+ // scope the reader stays unset and the ring falls back to the DSH `contextPressure`.
144
+ // `remote` is requested alongside, as the adapter's own client does for its namespace.
145
+ ctx.inject(["remote", "remote.dshAcp"], (acpCtx) => {
146
+ const remote = acpCtx.remote.dshAcp;
147
+ const reader: AcpUsageReader = async (id) => {
148
+ const result = await remote.agentSessionSnapshot(id);
149
+ if (!result.ok) {
150
+ console.warn("session-handoff: ACP usage unavailable", result);
151
+ return undefined;
152
+ }
153
+ const usage = result.value.contextUsage;
154
+ return usage === null ? undefined : usage;
155
+ };
156
+ setAcpUsageReader(reader);
157
+ return () => setAcpUsageReader(undefined);
158
+ });
159
+
160
+ const dispose = sessions.list.subscribe(sync);
161
+ sync();
162
+ ctx.effect(
163
+ () => () => {
164
+ dispose();
165
+ for (const unsubscribe of off.values()) unsubscribe();
166
+ off.clear();
167
+ },
168
+ "session-handoff: launch watcher",
169
+ );
170
+ }
@@ -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: 100_000, strong: 150_000 };
9
+ const COLD = { soft: 70_000, strong: 100_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,123 @@
1
+ import {
2
+ Button,
3
+ IconGaugeOutlineMedium,
4
+ Tooltip,
5
+ } from "@deepseek-ai/dsh-client-ui-primitives";
6
+ import type {} from "@deepseek-ai/dsh-client-ui-session/client";
7
+ import type { SessionStandardProps } from "@deepseek-ai/dsh-client-ui-slots";
8
+ import type {} from "@deepseek-ai/dsh-token-meter/client";
9
+ import {
10
+ createElement,
11
+ useEffect,
12
+ useState,
13
+ useSyncExternalStore,
14
+ } from "react";
15
+ import {
16
+ type AcpUsage,
17
+ currentAcpUsageReader,
18
+ subscribeAcpUsageReader,
19
+ } from "./acp-usage.ts";
20
+ import { CACHE_TTL_MS, handoffLevel } from "./level.ts";
21
+
22
+ const COLOR = { soft: "#d9a400", strong: "#d62839" } as const;
23
+
24
+ /** Gauge icon beside the send button once the session is big enough that `/handoff` pays off. */
25
+ export function HandoffRing({
26
+ sessionId,
27
+ useProjection,
28
+ useSession,
29
+ onHandoff,
30
+ }: Pick<SessionStandardProps, "sessionId" | "useProjection" | "useSession"> & {
31
+ onHandoff: (sessionId: SessionStandardProps["sessionId"]) => Promise<void>;
32
+ }) {
33
+ const pressure = useProjection("contextPressure");
34
+ const running = useSession((session) => session.running);
35
+ const [acp, setAcp] = useState<AcpUsage | undefined>(undefined);
36
+ const [cold, setCold] = useState(false);
37
+ const [pendingSession, setPendingSession] = useState<
38
+ SessionStandardProps["sessionId"] | undefined
39
+ >(undefined);
40
+
41
+ // ACP agents report occupancy to the adapter, never to DSH's `contextPressure`; read it
42
+ // when a turn settles. The reader is unset (so this is a no-op) without the adapter.
43
+ const readUsage = useSyncExternalStore(
44
+ subscribeAcpUsageReader,
45
+ currentAcpUsageReader,
46
+ );
47
+ useEffect(() => {
48
+ if (running || readUsage === undefined) return;
49
+ let live = true;
50
+ void readUsage(sessionId).then((usage) => {
51
+ if (live) setAcp(usage);
52
+ });
53
+ return () => {
54
+ live = false;
55
+ };
56
+ }, [sessionId, running, readUsage]);
57
+
58
+ const tokens =
59
+ pressure !== undefined && pressure.pressureTokens !== undefined
60
+ ? pressure.pressureTokens
61
+ : acp?.used;
62
+ const window =
63
+ pressure !== undefined && pressure.contextWindow !== undefined
64
+ ? pressure.contextWindow
65
+ : acp?.size;
66
+
67
+ // A new usage sample or a running turn means the cache was just touched; once idle for
68
+ // the TTL it is cold. Mount counts as warm because the last request time is unknown.
69
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `tokens` is the restart trigger
70
+ useEffect(() => {
71
+ setCold(false);
72
+ if (running) return;
73
+ const timer = setTimeout(() => setCold(true), CACHE_TTL_MS);
74
+ return () => clearTimeout(timer);
75
+ }, [tokens, running]);
76
+
77
+ const level = handoffLevel(tokens, window, cold);
78
+ if (level === "none" || tokens === undefined) return null;
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
+ };
95
+ const hint = cold
96
+ ? "cache is cold, a fresh session is cheaper now"
97
+ : "consider a fresh session";
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}`;
104
+ return createElement(Tooltip, {
105
+ label,
106
+ side: "top",
107
+ portal: true,
108
+ // Disabled native buttons omit mouseleave, so close Tooltip from state.
109
+ disabled: isDisabled,
110
+ // biome-ignore lint/correctness/noChildrenProp: Tooltip types `children` as a required prop, which createElement's 3rd argument does not satisfy
111
+ children: createElement(Button, {
112
+ variant: "ghost",
113
+ size: "sm",
114
+ disabled: isDisabled,
115
+ title: isDisabled ? label : undefined,
116
+ "aria-label": label,
117
+ // the icon strokes with currentColor; 28px square instead of the text-button padding
118
+ style: { color: COLOR[level], padding: 0, width: 28 },
119
+ icon: createElement(IconGaugeOutlineMedium, { size: 16 }),
120
+ onClick: () => void startHandoff(),
121
+ }),
122
+ });
123
+ }
package/src/handoff.ts ADDED
@@ -0,0 +1,345 @@
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 PATH_LIMIT = 300;
15
+ const TOOL_NAME_LIMIT = 80;
16
+ const RECENT_TURNS = 5;
17
+ const RECENT_HEAD = 1200;
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;
27
+
28
+ /** Tool argument keys that carry a durable file path. */
29
+ const PATH_KEYS = ["path", "file_path", "filePath", "notebook_path"];
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
+
34
+ export interface RenderedHandoff {
35
+ readonly markdown: string;
36
+ readonly turns: number;
37
+ }
38
+
39
+ interface TurnArc {
40
+ readonly turn: number;
41
+ readonly sessionId: string;
42
+ /** Running number across the whole chain; assigned after collection. */
43
+ index: number;
44
+ ask: string;
45
+ outcome: string;
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;
73
+ }
74
+
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 {
82
+ const turns: TurnArc[] = [];
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>();
87
+ let goal = "";
88
+ let eventCount = 0;
89
+
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;
168
+ }
169
+ }
170
+ }
171
+
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;
180
+ const lines = [
181
+ `# Handoff — ${id}`,
182
+ "",
183
+ `- session: \`${id}\``,
184
+ ...(snapshots.length > 1
185
+ ? [
186
+ `- chain: ${snapshots.map((snapshot) => `\`${shortId(String(snapshot.session.id))}\``).join(" → ")}`,
187
+ ]
188
+ : []),
189
+ `- cwd: \`${cwd === undefined ? "unknown" : cwd}\``,
190
+ `- created: ${new Date(current.session.createdAt).toISOString()}`,
191
+ `- events: ${eventCount}`,
192
+ `- turns: ${work.length}`,
193
+ "",
194
+ "## Goal",
195
+ "",
196
+ goal === "" ? "none" : goal,
197
+ "",
198
+ "## Turns",
199
+ "",
200
+ work.length === 0 ? "none" : turnList(work),
201
+ "",
202
+ "## Failures",
203
+ "",
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
+ ),
214
+ "",
215
+ "## Artifacts",
216
+ "",
217
+ artifacts.size === 0
218
+ ? "none"
219
+ : bounded(
220
+ [...artifacts.keys()].map((file) => `- \`${file}\``),
221
+ ARTIFACT_MAX,
222
+ "older paths",
223
+ ),
224
+ ];
225
+
226
+ return { markdown: `${lines.join("\n")}\n`, turns: work.length };
227
+ }
228
+
229
+ export function handoffInstruction(sessionId: string, file: string): string {
230
+ return [
231
+ `The handoff brief for session ${sessionId} is at ${file}.`,
232
+ "",
233
+ "Read that file now, then reply with three lines and stop:",
234
+ "Goal: <one line>",
235
+ "State: <one line>",
236
+ "Next: <one line>",
237
+ "",
238
+ "Do not start the work until the user confirms the next action.",
239
+ ].join("\n");
240
+ }
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
+
264
+ /** Recent turns quote the ask and reply at length; older turns are flattened and short. */
265
+ function turnBlock(turn: TurnArc, recent: boolean): string {
266
+ const kind = turn.reason === undefined ? "unfinished" : turn.reason.kind;
267
+ const body = (
268
+ recent
269
+ ? [
270
+ elide(turn.ask, RECENT_HEAD, RECENT_TAIL),
271
+ elide(turn.outcome, RECENT_HEAD, RECENT_TAIL),
272
+ ]
273
+ : [
274
+ elide(flatten(turn.ask), ASK_HEAD, ASK_TAIL),
275
+ clip(turn.outcome, OUTCOME_LIMIT),
276
+ ]
277
+ )
278
+ .filter((part) => part !== "")
279
+ .join("\n\n");
280
+ return `### T${turn.index} [${kind}]\n\n${body === "" ? "(no content)" : body}`;
281
+ }
282
+
283
+ function blockText(blocks: readonly ContentBlock[]): string {
284
+ const parts: string[] = [];
285
+ for (const block of blocks) {
286
+ if (block.type === "text") parts.push(block.text);
287
+ }
288
+ return parts.join("\n");
289
+ }
290
+
291
+ /** Collapses whitespace so a quote fits on one line, then cuts it. */
292
+ function clip(value: string, limit: number): string {
293
+ const flat = flatten(value);
294
+ if (flat.length <= limit) return flat;
295
+ return `${flat.slice(0, limit - 1)}…`;
296
+ }
297
+
298
+ function flatten(value: string): string {
299
+ return value.replace(/\s+/g, " ").trim();
300
+ }
301
+
302
+ /**
303
+ * Keeps `head` chars from the start and `tail` chars from the end, naming how much was
304
+ * dropped. Raw text is preserved so the Tail keeps the shape of code blocks and tables.
305
+ */
306
+ function elide(value: string, head: number, tail: number): string {
307
+ const trimmed = value.trim();
308
+ if (trimmed.length <= head + tail) return trimmed;
309
+ const omitted = trimmed.length - head - tail;
310
+ return `${trimmed.slice(0, head)} … [${omitted} chars omitted] … ${trimmed.slice(-tail)}`;
311
+ }
312
+
313
+ function errorReason(
314
+ error: { name: string; code: string; reason?: string } | undefined,
315
+ ): string {
316
+ if (error === undefined) return "failed";
317
+ if (error.reason === undefined) return error.code;
318
+ return error.reason;
319
+ }
320
+
321
+ function collectArtifacts(
322
+ args: string,
323
+ into: Map<string, true>,
324
+ briefFiles: ReadonlySet<string>,
325
+ ): void {
326
+ let parsed: unknown;
327
+ try {
328
+ parsed = JSON.parse(args);
329
+ } catch {
330
+ // edge case: tool arguments are model-produced JSON; a non-JSON payload names no path
331
+ return;
332
+ }
333
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
334
+ return;
335
+ // Safe: the guard above admits only non-null, non-array objects.
336
+ const record = parsed as Record<string, unknown>;
337
+ for (const key of PATH_KEYS) {
338
+ const value = record[key];
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);
344
+ }
345
+ }