forked from bristena-op/opencode-session-handoff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
381 lines (335 loc) · 11.5 KB
/
index.ts
File metadata and controls
381 lines (335 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import type { Plugin, PluginInput } from "@opencode-ai/plugin";
import type { Message, Part } from "@opencode-ai/sdk";
import { z } from "zod";
import { buildHandoffPrompt } from "./prompt.ts";
import { createAutoUpdateHook } from "./auto-update.ts";
type PluginClient = PluginInput["client"];
interface PluginContext {
directory: string;
client: PluginClient;
serverUrl: URL;
}
interface Todo {
content: string;
status: string;
}
interface ModelConfig {
providerID: string;
modelID: string;
}
interface SessionContext {
title: string;
todos: Todo[];
modelConfig?: ModelConfig;
agent?: string;
}
interface MessageWithParts {
info: Message;
parts: Part[];
}
async function fetchSessionTitle(
client: PluginClient,
sessionId: string,
directory: string,
): Promise<string> {
try {
const result = await client.session.get({
path: { id: sessionId },
query: { directory },
});
return result?.data?.title || "Unknown";
} catch {
return "Unknown";
}
}
function extractModelFromMessage(msg: Message | undefined): {
modelConfig?: ModelConfig;
agent?: string;
} {
if (!msg) return {};
if (msg.role !== "assistant") return {};
const out: { modelConfig?: ModelConfig; agent?: string } = {};
if (msg.providerID && msg.modelID) {
out.modelConfig = { providerID: msg.providerID, modelID: msg.modelID };
}
if (msg.mode) out.agent = msg.mode;
return out;
}
async function fetchModelConfig(
client: PluginClient,
sessionId: string,
directory: string,
): Promise<{ modelConfig?: ModelConfig; agent?: string }> {
try {
const result = await client.session.messages({
path: { id: sessionId },
query: { directory },
});
if (!result?.data || !Array.isArray(result.data)) return {};
const messages = result.data as MessageWithParts[];
const assistantMessages = messages.filter((m) => m.info.role === "assistant");
const lastAssistant = assistantMessages[assistantMessages.length - 1];
return extractModelFromMessage(lastAssistant?.info);
} catch {
return {};
}
}
async function fetchTodos(
client: PluginClient,
sessionId: string,
directory: string,
): Promise<Todo[]> {
try {
const result = await client.session.todo({
path: { id: sessionId },
query: { directory },
});
return Array.isArray(result?.data) ? (result.data as Todo[]) : [];
} catch {
return [];
}
}
async function gatherSessionContext(
pluginCtx: PluginContext,
sessionId: string,
): Promise<SessionContext> {
const [title, modelResult, todos] = await Promise.all([
fetchSessionTitle(pluginCtx.client, sessionId, pluginCtx.directory),
fetchModelConfig(pluginCtx.client, sessionId, pluginCtx.directory),
fetchTodos(pluginCtx.client, sessionId, pluginCtx.directory),
]);
const ctx: SessionContext = { title, todos };
if (modelResult.modelConfig) ctx.modelConfig = modelResult.modelConfig;
if (modelResult.agent) ctx.agent = modelResult.agent;
return ctx;
}
interface HandoffToolArgs {
summary: string;
next_steps?: string[];
blocked?: string;
key_decisions?: string[];
files_modified?: string[];
goal?: string;
}
interface CreateSessionParams {
client: PluginClient;
directory: string;
title: string;
context: SessionContext;
handoffPrompt: string;
}
async function createAndPromptSession(params: CreateSessionParams): Promise<string | null> {
const { client, directory, title, context, handoffPrompt } = params;
const newSession = await client.session.create({
query: { directory },
body: { title },
});
const sessionId = newSession?.data?.id;
if (!sessionId) return null;
const body: {
model?: ModelConfig;
agent?: string;
parts: Array<{ type: "text"; text: string }>;
} = { parts: [{ type: "text" as const, text: handoffPrompt }] };
if (context.modelConfig) body.model = context.modelConfig;
if (context.agent) body.agent = context.agent;
await client.session.promptAsync({
path: { id: sessionId },
query: { directory },
body,
});
return sessionId;
}
function buildHandoffArgs(args: HandoffToolArgs, sessionID: string, todos: Todo[]) {
return {
previousSessionId: sessionID,
summary: args.summary,
blocked: args.blocked || "",
modified_files: args.files_modified || [],
reference_files: [] as string[],
decisions: (args.key_decisions || []).map((d) => ({
decision: d,
reason: "",
})),
tried_failed: [] as Array<{ approach: string; why_failed: string }>,
next_steps: args.next_steps || [],
user_prefs: [] as string[],
...(todos.length > 0 && { todos }),
...(args.goal && { goal: args.goal }),
};
}
async function executeHandoff(
pluginCtx: PluginContext,
args: HandoffToolArgs,
sessionID: string,
): Promise<string> {
if (!args.summary?.trim()) {
return "Error: summary is required. Provide a 1-3 sentence summary of the current state.";
}
const context = sessionID
? await gatherSessionContext(pluginCtx, sessionID)
: { title: "Unknown", todos: [] };
const handoffPrompt = buildHandoffPrompt(buildHandoffArgs(args, sessionID, context.todos));
const newTitle = `Handoff: ${context.title}`;
const sessionId = await createAndPromptSession({
client: pluginCtx.client,
directory: pluginCtx.directory,
title: newTitle,
context,
handoffPrompt,
});
if (!sessionId) return "Failed to create session";
await pluginCtx.client.tui.openSessions({
query: { directory: pluginCtx.directory },
});
const model = context.modelConfig;
const modelDisplay = model ? `${model.providerID}/${model.modelID}` : "default model";
return `✓ Session "${newTitle}" created (${context.agent || "default"} · ${modelDisplay}). Select it from the picker.`;
}
const handoffArgsSchema = {
summary: z.string().describe("1-3 sentence summary of current state (required)"),
goal: z.string().optional().describe("Goal for the next session if user specified one"),
next_steps: z.array(z.string()).optional().describe("Array of remaining tasks"),
blocked: z.string().optional().describe("Current blocker if any"),
key_decisions: z.array(z.string()).optional().describe("Important decisions made"),
files_modified: z.array(z.string()).optional().describe("Key files that were changed"),
};
function createHandoffTool(pluginCtx: PluginContext) {
return {
description: `Generate a compact continuation prompt and start a new session with it.
When called, this tool:
1. Uses YOUR summary of what was accomplished (required)
2. Auto-fetches todo state from current session
3. Creates a new session with a minimal handoff prompt (~100-200 tokens)
4. Returns the new session ID
IMPORTANT: You MUST provide a concise summary. Do not dump the entire conversation - distill it to essential context only.
The new session will have access to \`read_session\` tool if more context is needed later.`,
args: handoffArgsSchema,
async execute(args: Record<string, unknown>, ctx: { sessionID: string }) {
return executeHandoff(pluginCtx, args as unknown as HandoffToolArgs, ctx.sessionID);
},
};
}
async function executeReadSession(
pluginCtx: { directory: string; client: PluginClient },
sessionID: string,
): Promise<string> {
if (!sessionID) {
return "No session ID available";
}
try {
const messagesResult = await pluginCtx.client.session.messages({
path: { id: sessionID },
query: { directory: pluginCtx.directory },
});
if (!messagesResult?.data || !Array.isArray(messagesResult.data)) {
return "No messages found";
}
const messages = (messagesResult.data as MessageWithParts[]).slice(-20);
const formatted = messages.map((msg) => {
const role = msg.info.role || "unknown";
const textParts = msg.parts.filter(
(p): p is Part & { type: "text"; text: string } => p.type === "text",
);
const content = textParts.map((p) => p.text || "").join("\n") || "[no text content]";
return `[${role}]: ${content.slice(0, 2000)}${content.length > 2000 ? "..." : ""}`;
});
return `Messages (last ${messages.length}):\n\n${formatted.join("\n\n---\n\n")}`;
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
return `Failed to read session: ${errorMsg}`;
}
}
function createReadSessionTool(pluginCtx: { directory: string; client: PluginClient }) {
return {
description: `Read messages from the previous session to get additional context.
USE SPARINGLY - only when:
- User explicitly asks to "load more context" or "read previous session"
- You encounter something from the handoff that needs clarification
- You need specific details not captured in the handoff summary
This tool fetches the last 20 messages which uses significant tokens. The handoff summary should be sufficient for most continuations.`,
args: {},
async execute(_args: Record<string, unknown>, ctx: { sessionID: string }) {
return executeReadSession(pluginCtx, ctx.sessionID);
},
};
}
export function isHandoffTrigger(text: string): boolean {
const trimmed = text.trim().toLowerCase();
return (
trimmed === "handoff" ||
trimmed === "/handoff" ||
trimmed === "session handoff" ||
trimmed.startsWith("handoff ") ||
trimmed.startsWith("/handoff ")
);
}
export function extractGoalFromHandoff(text: string): string | null {
const trimmed = text.trim();
const lower = trimmed.toLowerCase();
if (lower.startsWith("/handoff ")) {
return trimmed.slice(9).trim() || null;
}
if (lower.startsWith("handoff ")) {
return trimmed.slice(8).trim() || null;
}
return null;
}
const HandoffPlugin: Plugin = async (ctx) => {
const autoUpdateHook = createAutoUpdateHook({
directory: ctx.directory,
client: ctx.client,
});
return {
event: autoUpdateHook.event,
tool: {
session_handoff: createHandoffTool({
directory: ctx.directory,
client: ctx.client,
serverUrl: ctx.serverUrl,
}),
read_session: createReadSessionTool({
directory: ctx.directory,
client: ctx.client,
}),
},
"chat.message": async (
_input: {
sessionID: string;
agent?: string;
model?: { providerID: string; modelID: string };
messageID?: string;
variant?: string;
},
output: { message: unknown; parts: Part[] },
) => {
const textParts = output.parts.filter(
(p): p is Part & { type: "text"; text: string } =>
p.type === "text" && typeof (p as { text?: string }).text === "string",
);
for (const part of textParts) {
if (isHandoffTrigger(part.text)) {
const goal = extractGoalFromHandoff(part.text);
part.text = [
'<system-instruction priority="critical">',
"The user has triggered a session handoff. You MUST invoke the `session_handoff` tool immediately.",
"",
"DO NOT interpret this as a regular task request.",
"DO NOT continue working on any previous tasks.",
"DO NOT ask clarifying questions.",
"",
"IMMEDIATELY call the session_handoff tool with:",
"- summary: A brief summary of what was accomplished in this session",
goal ? `- goal: "${goal}"` : "- goal: (not specified)",
"- next_steps: Any remaining tasks from the todo list",
"- key_decisions: Important decisions made during the session",
"- files_modified: Key files that were changed",
"</system-instruction>",
].join("\n");
break;
}
}
},
};
};
export default HandoffPlugin;