Swadhin Biswas feat: implement mervelas cli engine, built-in tools, and reactive UI · 4/3/2026
0358986
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
/**
* Session title generation via Haiku.
*
* Standalone module with minimal dependencies so it can be imported from
* print.ts (SDK control request handler) without pulling in the React/chalk/
* git dependency chain that teleport.tsx carries.
*
* This is the single source of truth for AI-generated session titles across
* all surfaces. Previously there were separate Haiku title generators:
* - teleport.tsx generateTitleAndBranch (6-word title + branch for CCR)
* - rename/generateSessionName.ts (kebab-case name for /rename)
* Each remains for backwards compat; new callers should use this module.
*/
import { z } from 'zod/v4'
import { getIsNonInteractiveSession } from '../bootstrap/state.js'
import { logEvent } from '../services/analytics/index.js'
import { queryHaiku } from '../services/api/mervelas.js'
import type { Message } from '../types/message.js'
import { logForDebugging } from './debug.js'
import { safeParseJSON } from './json.js'
import { lazySchema } from './lazySchema.js'
import { extractTextContent } from './messages.js'
import { asSystemPrompt } from './systemPromptType.js'
const MAX_CONVERSATION_TEXT = 1000
/**
* Flatten a message array into a single text string for Haiku title input.
* Skips meta/non-human messages. Tail-slices to the last 1000 chars so
* recent context wins when the conversation is long.
*/
export function extractConversationText(messages: Message[]): string {
const parts: string[] = []
for (const msg of messages) {
if (msg.type !== 'user' && msg.type !== 'assistant') continue
if ('isMeta' in msg && msg.isMeta) continue
if ('origin' in msg && msg.origin && msg.origin.kind !== 'human') continue
const content = msg.message.content
if (typeof content === 'string') {
parts.push(content)
} else if (Array.isArray(content)) {
for (const block of content) {
if ('type' in block && block.type === 'text' && 'text' in block) {
parts.push(block.text as string)
}
}
}
}
const text = parts.join('\n')
return text.length > MAX_CONVERSATION_TEXT
? text.slice(-MAX_CONVERSATION_TEXT)
: text
}
const SESSION_TITLE_PROMPT = `Generate a concise, sentence-case title (3-7 words) that captures the main topic or goal of this coding session. The title should be clear enough that the user recognizes the session in a list. Use sentence case: capitalize only the first word and proper nouns.
Return JSON with a single "title" field.
Good examples:
{"title": "Fix login button on mobile"}
{"title": "Add OAuth authentication"}
{"title": "Debug failing CI tests"}
{"title": "Refactor API client error handling"}
Bad (too vague): {"title": "Code changes"}
Bad (too long): {"title": "Investigate and fix the issue where the login button does not respond on mobile devices"}
Bad (wrong case): {"title": "Fix Login Button On Mobile"}`
const titleSchema = lazySchema(() => z.object({ title: z.string() }))
/**
* Generate a sentence-case session title from a description or first message.
* Returns null on error or if Haiku returns an unparseable response.
*
* @param description - The user's first message or a description of the session
* @param signal - Abort signal for cancellation
*/
export async function generateSessionTitle(
description: string,
signal: AbortSignal,
): Promise<string | null> {
const trimmed = description.trim()
if (!trimmed) return null
try {
const result = await queryHaiku({
systemPrompt: asSystemPrompt([SESSION_TITLE_PROMPT]),
userPrompt: trimmed,
outputFormat: {
type: 'json_schema',
schema: {
type: 'object',
properties: {
title: { type: 'string' },
},
required: ['title'],
additionalProperties: false,
},
},
signal,
options: {
querySource: 'generate_session_title',
agents: [],
// Reflect the actual session mode — this module is called from
// both the SDK print path (non-interactive) and the CCR remote
// session path via useRemoteSession (interactive).
isNonInteractiveSession: getIsNonInteractiveSession(),
hasAppendSystemPrompt: false,
mcpTools: [],
},
})
const text = extractTextContent(result.message.content)
const parsed = titleSchema().safeParse(safeParseJSON(text))
const title = parsed.success ? parsed.data.title.trim() || null : null
logEvent('tengu_session_title_generated', { success: title !== null })
return title
} catch (error) {
logForDebugging(`generateSessionTitle failed: ${error}`, {
level: 'error',
})
logEvent('tengu_session_title_generated', { success: false })
return null
}
}