forked from deepseek-ai/deepseek-harness
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
294 lines (276 loc) · 11.6 KB
/
Copy pathindex.ts
File metadata and controls
294 lines (276 loc) · 11.6 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
/**
* Shared route, framing, timeout, assembly, and validation policy for
* model-backed session-title providers.
* @module @deepseek-ai/dsh-session-title-llm
*/
import type { Context } from '@deepseek-ai/cordis'
import z from '@deepseek-ai/schemastery'
import { createUserMessage, BlockAssembler, deepFreeze } from '@deepseek-ai/dsh-llm'
import type { FinishReason, GenerateOptions, Message } from '@deepseek-ai/dsh-llm'
import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout'
import {
normalizeSessionTitle,
SessionTitleProviderId,
} from '@deepseek-ai/dsh-session-title'
import type {
SessionTitleAutomaticMode,
SessionTitleModelProvenance,
SessionTitleProviderRequest,
SessionTitleProviderResult,
SessionTitleUserMessage,
} from '@deepseek-ai/dsh-session-title'
/** Exact model-visible request recorded before one auxiliary title dispatch. */
export interface SessionTitleLlmRequestEventData {
/** Registered title-provider identity responsible for the request. */
readonly titleProvider: SessionTitleProviderId
/** Exact human `user/message` seqs represented in `messages`. */
readonly messageSeqs: number[]
/** Exact auxiliary LLM route. */
readonly route: SessionTitleModelProvenance
/** Exact auxiliary system prompt. */
readonly system: string
/** Exact auxiliary message list. */
readonly messages: Message[]
/** Exact auxiliary output-token cap. */
readonly maxTokens: number
}
declare module '@deepseek-ai/dsh-session/types' {
interface SessionEventMap {
/** Log-only pre-dispatch record of one session-title model request. */
'session/title-llm-request': SessionTitleLlmRequestEventData
}
}
/** Capability-owned timeout reason code for auxiliary title requests. */
export const SESSION_TITLE_TIMEOUT_CODE = 'SESSION_TITLE_TIMEOUT'
/** Required deployment policy for one model-backed title plugin. */
export interface SessionTitleLlmConfig {
/** Target word count for non-CJK titles. */
readonly targetWords: number
/** Target character count for Chinese, Japanese, or Korean titles. */
readonly targetCjkCharacters: number
/** Maximum UTF-8 bytes in the final JSON-framed user prompt. */
readonly maxInputBytes: number
/** Auxiliary generation output-token cap. */
readonly maxOutputTokens: number
/** End-to-end auxiliary request deadline in milliseconds. */
readonly timeoutMs: number
/** Optional explicit provider route; must be paired with `model`. */
readonly provider?: string
/** Optional explicit model id; must be paired with `provider`. */
readonly model?: string
}
/** Validated immutable model-provider policy. */
export interface ResolvedSessionTitleLlmConfig extends SessionTitleLlmConfig {}
/** Shared Loader field schemas with no library defaults. */
export const SessionTitleLlmConfigFields = {
targetWords: z.number().step(1).min(1).required(),
targetCjkCharacters: z.number().step(1).min(1).required(),
maxInputBytes: z.number().step(1).min(1).required(),
maxOutputTokens: z.number().step(1).min(1).required(),
timeoutMs: z.number().step(1).min(1).max(MAX_TIMER_DELAY_MS).required(),
provider: z.string(),
model: z.string(),
}
/** Shared Loader schema with no library defaults. */
export const SessionTitleLlmConfigSchema: z<SessionTitleLlmConfig> = z.object(SessionTitleLlmConfigFields)
/** Complete configuration key set for direct construction validation. */
const CONFIG_KEYS: ReadonlySet<string> = new Set([
'targetWords',
'targetCjkCharacters',
'maxInputBytes',
'maxOutputTokens',
'timeoutMs',
'provider',
'model',
])
/** Validate one positive integer limit. */
function assertPositiveInteger(name: string, value: number): void {
if (!Number.isInteger(value) || value <= 0) {
throw new Error(`session-title-llm: ${name} must be a positive integer`)
}
}
/**
* Validate and detach required model-provider configuration.
* @param config - untrusted plugin configuration.
* @returns immutable policy with optional route absence preserved.
*/
export function resolveSessionTitleLlmConfig(
config: SessionTitleLlmConfig,
): ResolvedSessionTitleLlmConfig {
const candidate: unknown = config
if (candidate === null || typeof candidate !== 'object') {
throw new Error('session-title-llm: configuration is required')
}
const value = candidate as SessionTitleLlmConfig
for (const key of Object.keys(value)) {
if (!CONFIG_KEYS.has(key)) throw new Error(`session-title-llm: unknown config key "${key}"`)
}
assertPositiveInteger('targetWords', value.targetWords)
assertPositiveInteger('targetCjkCharacters', value.targetCjkCharacters)
assertPositiveInteger('maxInputBytes', value.maxInputBytes)
assertPositiveInteger('maxOutputTokens', value.maxOutputTokens)
assertPositiveInteger('timeoutMs', value.timeoutMs)
if (value.timeoutMs > MAX_TIMER_DELAY_MS) {
throw new Error(`session-title-llm: timeoutMs must not exceed ${MAX_TIMER_DELAY_MS}`)
}
const hasProvider = value.provider !== undefined
const hasModel = value.model !== undefined
if (hasProvider !== hasModel) {
throw new Error('session-title-llm: provider and model must be supplied together')
}
if (hasProvider
&& (typeof value.provider !== 'string' || value.provider.length === 0
|| typeof value.model !== 'string' || value.model.length === 0)) {
throw new Error('session-title-llm: provider and model overrides must be non-empty strings')
}
return deepFreeze({ ...value })
}
/** Select the provider-owned message subset from one fixed service revision. */
export type SessionTitleLlmMessageSelector = (
messages: readonly SessionTitleUserMessage[],
) => readonly SessionTitleUserMessage[]
/**
* Register one model-backed provider through the shared configuration and call policy.
* @param ctx - context exposing the title and LLM services.
* @param config - untrusted required deployment policy.
* @param id - stable plugin id recorded with generated titles.
* @param automatic - provider-owned automatic generation cadence.
* @param selectMessages - exact source-message selection for one revision.
*/
export function registerSessionTitleLlmProvider(
ctx: Context,
config: SessionTitleLlmConfig,
id: string,
automatic: SessionTitleAutomaticMode,
selectMessages: SessionTitleLlmMessageSelector,
): void {
const resolved = resolveSessionTitleLlmConfig(config)
const titleProvider = SessionTitleProviderId(id)
ctx.sessionTitle.register({
id: titleProvider,
automatic,
async generate(request) {
return generateSessionTitleWithLlm(ctx, resolved, request, selectMessages(request.messages), titleProvider)
},
})
}
/** Resolve the explicit pair or the exact route captured from `request/header`. */
function resolveRoute(
config: ResolvedSessionTitleLlmConfig,
request: SessionTitleProviderRequest,
): SessionTitleModelProvenance {
if (config.provider !== undefined && config.model !== undefined) {
return { provider: config.provider, model: config.model }
}
if (request.route === undefined) {
throw new Error('session-title-llm: no logged request route is available; configure provider and model together')
}
return request.route
}
/** Stable language-aware system instruction shared by both provider plugins. */
function systemPrompt(config: ResolvedSessionTitleLlmConfig): string {
return [
'Create a concise title for an AI coding-assistant session from the supplied human messages.',
'Return only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.',
'Use the language of the messages.',
`Aim for about ${config.targetWords} words in non-CJK languages or ${config.targetCjkCharacters} CJK characters.`,
].join('\n')
}
/** Frame exact messages as JSON so user text cannot break structural delimiters. */
function frameMessages(messages: readonly SessionTitleUserMessage[]): string {
return `Generate the session title from this JSON array of human messages:\n${JSON.stringify(messages)}`
}
/** Translate terminal finish reasons into an auxiliary-call failure. */
function finishError(finish: FinishReason): Error | undefined {
switch (finish.kind) {
case 'stop':
return undefined
case 'error':
case 'aborted': {
const error = new Error(finish.failure.message) as Error & { code?: string }
error.code = finish.failure.code
return error
}
case 'max-tokens':
return new Error('session-title-llm: title output reached maxOutputTokens')
case 'tool-calls':
return new Error('session-title-llm: title model unexpectedly requested a tool')
default:
return new Error(`session-title-llm: unsupported finish reason "${String((finish as { kind?: unknown }).kind)}"`)
}
}
/**
* Generate one title through the shared auxiliary LLM call.
* @param ctx - context exposing the registered LLM service.
* @param config - validated model-provider policy.
* @param request - service-owned session, route, message snapshot, and cancellation.
* @param selectedMessages - exact provider-selected subset to frame and attribute.
* @param titleProvider - registered title-provider identity recorded with the request.
* @returns normalized non-empty title, exact source seqs, and used model route.
*/
export async function generateSessionTitleWithLlm(
ctx: Context,
config: ResolvedSessionTitleLlmConfig,
request: SessionTitleProviderRequest,
selectedMessages: readonly SessionTitleUserMessage[],
titleProvider: SessionTitleProviderId,
): Promise<SessionTitleProviderResult> {
request.signal.throwIfAborted()
if (selectedMessages.length === 0) {
throw new Error('session-title-llm: at least one source message is required')
}
const framedInput = frameMessages(selectedMessages)
const inputBytes = Buffer.byteLength(framedInput, 'utf8')
if (inputBytes > config.maxInputBytes) {
throw new Error(`session-title-llm: input is ${inputBytes} bytes, exceeding maxInputBytes ${config.maxInputBytes}`)
}
const route = resolveRoute(config, request)
const messages: Message[] = [createUserMessage({
content: [{ type: 'text', text: framedInput }],
source: { kind: 'plugin', plugin: 'dsh-session-title-llm' },
})]
const system = systemPrompt(config)
using callDeadline = deadline(request.signal, config.timeoutMs, SESSION_TITLE_TIMEOUT_CODE)
const options: GenerateOptions = deepFreeze({
provider: route.provider,
model: route.model,
messages,
system,
maxTokens: config.maxOutputTokens,
sessionId: request.session.id,
purpose: 'session-title',
signal: callDeadline.signal,
})
request.session.append('session/title-llm-request', {
titleProvider,
messageSeqs: selectedMessages.map(message => message.seq),
route,
system,
messages,
maxTokens: config.maxOutputTokens,
})
callDeadline.signal.throwIfAborted()
const assembler = new BlockAssembler()
for await (const chunk of ctx.llm.stream(options)) {
callDeadline.signal.throwIfAborted()
assembler.push(chunk)
}
callDeadline.signal.throwIfAborted()
const terminalError = finishError(assembler.finish)
if (terminalError !== undefined) throw terminalError
const blocks = assembler.blocks()
if (blocks.some(block => block.type === 'tool-call')) {
throw new Error('session-title-llm: title output must contain text only')
}
const text = blocks
.filter((block): block is Extract<(typeof blocks)[number], { type: 'text' }> => block.type === 'text')
.map(block => block.text)
.join(' ')
const title = normalizeSessionTitle(text, Number.MAX_SAFE_INTEGER)
if (title.length === 0) throw new Error('session-title-llm: title model produced no text')
return {
title,
messageSeqs: selectedMessages.map(message => message.seq),
model: route,
}
}