-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.ts
More file actions
500 lines (430 loc) · 15.2 KB
/
index.ts
File metadata and controls
500 lines (430 loc) · 15.2 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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/**
* Smart Title Plugin for OpenCode
*
* Automatically generates meaningful session titles based on conversation content.
* Uses OpenCode auth provider for unified authentication across all AI providers.
*
* Configuration: ~/.config/opencode/smart-title.jsonc
* Logs: ~/.config/opencode/logs/smart-title/YYYY-MM-DD.log
*
* NOTE: ai package is lazily imported to avoid loading the 2.8MB package during
* plugin initialization. The package is only loaded when title generation is needed.
*/
import type { Plugin } from "@opencode-ai/plugin"
import { getConfig } from "./lib/config.js"
import { Logger } from "./lib/logger.js"
import { selectModel } from "./lib/model-selector.js"
import { TITLE_PROMPT } from "./prompt.js"
import { join } from "path"
import { homedir } from "os"
// Type for OpenCode client object
interface OpenCodeClient {
session: {
messages: (params: { path: { id: string } }) => Promise<any>
update: (params: { path: { id: string }, body: { title: string } }) => Promise<any>
get: (params: { path: { id: string } }) => Promise<any>
}
tui: {
showToast: (params: { body: { title: string, message: string, variant: "info" | "success" | "warning" | "error", duration: number } }) => Promise<any>
}
}
// Conversation turn structure for context extraction
interface ConversationTurn {
user: {
text: string
time: number
}
assistant?: {
first: string
last: string
time: number
}
}
interface MessagePart {
type: string
text?: string
synthetic?: boolean
}
interface Message {
info: {
id: string
role: "user" | "assistant" | "system"
sessionID: string
time: {
created: number
completed?: number
}
parentID?: string
}
parts: MessagePart[]
}
/**
* Checks if a session is a subagent (child session)
* Subagent sessions should skip title generation
*/
async function isSubagentSession(
client: OpenCodeClient,
sessionID: string,
logger: Logger
): Promise<boolean> {
try {
const result = await client.session.get({ path: { id: sessionID } })
if (result.data?.parentID) {
logger.debug("subagent-check", "Detected subagent session, skipping title generation", {
sessionID,
parentID: result.data.parentID
})
return true
}
return false
} catch (error: any) {
logger.error("subagent-check", "Failed to check if session is subagent", {
sessionID,
error: error.message
})
return false
}
}
// Track idle event count per session for threshold-based updates
const sessionIdleCount = new Map<string, number>()
/**
* Extract only text content from message parts, excluding synthetic content
*/
function extractTextOnly(parts: MessagePart[]): string {
// Only extract text parts, exclude synthetic content
const textParts = parts.filter(
part => part.type === "text" && !part.synthetic
)
return textParts
.map(part => part.text || '')
.join("\n")
.trim()
}
/**
* Extract smart context from conversation
* Returns first and last assistant messages per turn to minimize token usage
*/
async function extractSmartContext(
client: OpenCodeClient,
sessionId: string,
logger: Logger
): Promise<ConversationTurn[]> {
logger.debug('context-extraction', 'Fetching session messages', { sessionId })
// Get all messages
const { data: messages } = await client.session.messages({
path: { id: sessionId }
})
logger.debug('context-extraction', 'Messages fetched', {
sessionId,
totalMessages: messages.length
})
// Filter out system messages
const conversationMessages = messages.filter(
(msg: Message) => msg.info.role === "user" || msg.info.role === "assistant"
)
logger.debug('context-extraction', 'Filtered conversation messages', {
sessionId,
conversationMessages: conversationMessages.length
})
// Group into turns
const turns: ConversationTurn[] = []
let currentTurn: ConversationTurn | null = null
let assistantMessagesInTurn: Array<{ text: string, time: number }> = []
for (const msg of conversationMessages) {
if (msg.info.role === "user") {
// Save previous turn if exists
if (currentTurn && assistantMessagesInTurn.length > 0) {
currentTurn.assistant = {
first: assistantMessagesInTurn[0].text,
last: assistantMessagesInTurn[assistantMessagesInTurn.length - 1].text,
time: assistantMessagesInTurn[0].time
}
turns.push(currentTurn)
}
// Start new turn
const userText = extractTextOnly(msg.parts)
currentTurn = {
user: {
text: userText,
time: msg.info.time.created
}
}
assistantMessagesInTurn = []
} else if (msg.info.role === "assistant") {
// Collect assistant messages for this turn
const assistantText = extractTextOnly(msg.parts)
if (assistantText.length > 0) {
assistantMessagesInTurn.push({
text: assistantText,
time: msg.info.time.created
})
}
}
}
// Don't forget the last turn (might not have assistant response yet)
if (currentTurn) {
if (assistantMessagesInTurn.length > 0) {
currentTurn.assistant = {
first: assistantMessagesInTurn[0].text,
last: assistantMessagesInTurn[assistantMessagesInTurn.length - 1].text,
time: assistantMessagesInTurn[0].time
}
}
// Include the turn even if it doesn't have an assistant response yet
// This ensures the triggering user message is included in the context
turns.push(currentTurn)
}
logger.debug('context-extraction', 'Extracted conversation turns', {
sessionId,
turnCount: turns.length
})
return turns
}
/**
* Truncate text to specified length with ellipsis
*/
function truncate(text: string, maxLength: number): string {
if (text.length <= maxLength) return text
return text.substring(0, maxLength) + "..."
}
/**
* Format conversation context for title generation
*/
function formatContextForTitle(turns: ConversationTurn[]): string {
const formatted: string[] = []
for (const turn of turns) {
// Add user message
formatted.push(`User: ${turn.user.text}`)
formatted.push("") // Empty line for readability
// Add assistant messages if they exist
if (turn.assistant) {
if (turn.assistant.first === turn.assistant.last) {
// Only one message - don't duplicate
formatted.push(`Assistant: ${turn.assistant.first}`)
} else {
// Multiple messages - show first and last
formatted.push(`Assistant (initial): ${turn.assistant.first}`)
formatted.push(`Assistant (final): ${turn.assistant.last}`)
}
formatted.push("") // Empty line between turns
}
}
return formatted.join("\n")
}
/**
* Clean AI-generated title
*/
function cleanTitle(raw: string): string {
// Remove thinking tags
let cleaned = raw.replace(/<think>[\s\S]*?<\/think>\s*/g, "")
// Get first non-empty line
const lines = cleaned.split("\n").map(line => line.trim())
cleaned = lines.find(line => line.length > 0) || "Untitled"
// Truncate if too long
if (cleaned.length > 100) {
cleaned = cleaned.substring(0, 97) + "..."
}
return cleaned
}
/**
* Generate title from conversation context using AI
*/
async function generateTitleFromContext(
context: string,
configModel: string | undefined,
logger: Logger,
client: OpenCodeClient
): Promise<string | null> {
try {
logger.debug('title-generation', 'Selecting model', { configModel })
const { model, modelInfo, source, reason, failedModel } = await selectModel(
logger,
configModel
)
logger.info('title-generation', 'Model selected', {
providerID: modelInfo.providerID,
modelID: modelInfo.modelID,
source,
reason
})
// Show toast if we had to fallback from a configured model
if (failedModel) {
try {
await client.tui.showToast({
body: {
title: "Smart Title: Model fallback",
message: `${failedModel.providerID}/${failedModel.modelID} failed\nUsing ${modelInfo.providerID}/${modelInfo.modelID}`,
variant: "info",
duration: 5000
}
})
logger.info('title-generation', 'Toast notification shown for model fallback', {
failedModel,
selectedModel: modelInfo
})
} catch (toastError: any) {
logger.error('title-generation', 'Failed to show toast notification', {
error: toastError.message
})
// Don't fail the whole operation if toast fails
}
}
logger.debug('title-generation', 'Generating title', {
contextLength: context.length
})
// Lazy import - only load the 2.8MB ai package when actually needed
const { generateText } = await import('ai')
const result = await generateText({
model,
messages: [
{
role: 'user',
content: `${TITLE_PROMPT}\n\n<conversation>\n${context}\n</conversation>\n\nOutput the title now:`
}
]
})
const title = cleanTitle(result.text)
logger.info('title-generation', 'Title generated successfully', {
title,
titleLength: title.length,
rawLength: result.text.length
})
return title
} catch (error: any) {
logger.error('title-generation', 'Failed to generate title', {
error: error.message,
stack: error.stack
})
return null
}
}
/**
* Update session title with smart context
*/
async function updateSessionTitle(
client: OpenCodeClient,
sessionId: string,
logger: Logger,
config: ReturnType<typeof getConfig>
): Promise<void> {
try {
logger.info('update-title', 'Title update triggered', { sessionId })
// Extract smart context
const turns = await extractSmartContext(client, sessionId, logger)
// Need at least one turn to generate title
if (turns.length === 0) {
logger.warn('update-title', 'No conversation turns found', { sessionId })
return
}
logger.info('update-title', 'Context extracted', {
sessionId,
turnCount: turns.length
})
// Log truncated context for debugging
for (const turn of turns) {
logger.debug('update-title', 'Turn context', {
user: truncate(turn.user.text, 100),
hasAssistant: !!turn.assistant
})
}
// Format context
const context = formatContextForTitle(turns)
// Generate title
const newTitle = await generateTitleFromContext(
context,
config.model,
logger,
client
)
if (!newTitle) {
logger.warn('update-title', 'Title generation returned null', { sessionId })
return
}
logger.info('update-title', 'Updating session with new title', {
sessionId,
title: newTitle
})
// Update session
await client.session.update({
path: { id: sessionId },
body: { title: newTitle }
})
logger.info('update-title', 'Session title updated successfully', {
sessionId,
title: newTitle
})
} catch (error: any) {
logger.error('update-title', 'Failed to update session title', {
sessionId,
error: error.message,
stack: error.stack
})
}
}
/**
* Smart Title Plugin
* Automatically updates session titles using AI and smart context selection
*/
const SmartTitlePlugin: Plugin = async (ctx) => {
const config = getConfig(ctx)
// Exit early if plugin is disabled
if (!config.enabled) {
return {}
}
const logger = new Logger(config.debug)
const { client } = ctx
logger.info('plugin', 'Smart Title plugin initialized', {
enabled: config.enabled,
debug: config.debug,
model: config.model,
updateThreshold: config.updateThreshold,
globalConfigFile: join(homedir(), ".config", "opencode", "smart-title.jsonc"),
projectConfigFile: ctx.directory ? join(ctx.directory, ".opencode", "smart-title.jsonc") : "N/A",
logDirectory: join(homedir(), ".config", "opencode", "logs", "smart-title")
})
return {
event: async ({ event }) => {
// @ts-ignore - session.status is not yet in the SDK types
if (event.type === "session.status" && event.properties.status.type === "idle") {
// @ts-ignore
const sessionId = event.properties.sessionID
logger.debug('event', 'Session became idle', { sessionId })
// Skip if this is a subagent session
if (await isSubagentSession(client, sessionId, logger)) {
return
}
// Increment idle count for this session
const currentCount = (sessionIdleCount.get(sessionId) || 0) + 1
sessionIdleCount.set(sessionId, currentCount)
logger.debug('event', 'Idle count updated', {
sessionId,
currentCount,
threshold: config.updateThreshold
})
// Only update title if we've reached the threshold
if (currentCount % config.updateThreshold !== 0) {
logger.debug('event', 'Threshold not reached, skipping title update', {
sessionId,
currentCount,
threshold: config.updateThreshold
})
return
}
logger.info('event', 'Threshold reached, triggering title update for idle session', {
sessionId,
currentCount,
threshold: config.updateThreshold
})
// Fire and forget - don't block the event handler
updateSessionTitle(client, sessionId, logger, config).catch((error) => {
logger.error('event', 'Title update failed', {
sessionId,
error: error.message,
stack: error.stack
})
})
}
}
}
}
export default SmartTitlePlugin