ds-bot 0.0.0-stage → 0.1.0

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,174 @@
1
+ // Images for text-only models. Every model may take images; before a Session request
2
+ // reaches a model that cannot read them, each image becomes text from a vision model.
3
+ // Texts are kept per attachment, so later requests repeat the same words and the
4
+ // prompt cache still hits.
5
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
6
+ import { join } from 'node:path'
7
+ import { BlockAssembler } from '@deepseek-ai/dsh-llm'
8
+ import { OCR_CACHE_MAX, OCR_PROMPT, OCR_RETRY_MS, OCR_TIMEOUT_MS } from './constants.js'
9
+ import { splitRef } from './text.js'
10
+
11
+ export function install(rt) {
12
+ const { ctx, config, home } = rt
13
+
14
+ // `textOnlyModels` names models whose provider claims image input but rejects it.
15
+ const textOnlyModels = new Set(config.textOnlyModels ?? [])
16
+ const ocrPath = join(home, 'ocr.json')
17
+ let ocrCache = null
18
+ let ocrWriting = Promise.resolve()
19
+ const ocrPending = new Map()
20
+ const ocrFailed = new Map()
21
+
22
+ const liveImages = message => Array.isArray(message?.content)
23
+ && message.content.some(block => block?.type === 'image' && !block.offloaded)
24
+
25
+ async function readsImages(provider, model) {
26
+ if (textOnlyModels.has(`${provider}/${model}`)) return false
27
+ try {
28
+ const info = await ctx.llm.resolveModelInfo(provider, model)
29
+ return info.inputModalities === undefined || info.inputModalities.includes('image')
30
+ } catch {
31
+ return true
32
+ }
33
+ }
34
+
35
+ // The configured `ocrModel` first, then served models that declare image input, the
36
+ // DSH default among them first.
37
+ async function ocrRoute() {
38
+ const models = await rt.catalog()
39
+ const served = new Set(models.map(entry => entry.ref))
40
+ const declared = models.filter(entry => entry.input?.includes('image')).map(entry => entry.ref)
41
+ const fallback = rt.defaultRef()
42
+ for (const ref of new Set([config.ocrModel, ...declared.filter(ref => ref === fallback), ...declared])) {
43
+ const route = splitRef(ref)
44
+ if (route && served.has(ref) && await readsImages(route.provider, route.model)) return { ref, ...route }
45
+ }
46
+ return undefined
47
+ }
48
+
49
+ async function loadOcr() {
50
+ if (ocrCache !== null) return
51
+ try {
52
+ ocrCache = new Map(Object.entries(JSON.parse(await readFile(ocrPath, 'utf8'))))
53
+ } catch (error) {
54
+ if (error?.code !== 'ENOENT') rt.warn('ds-bot: unreadable OCR cache %s: %s', ocrPath, error)
55
+ ocrCache = new Map()
56
+ }
57
+ }
58
+
59
+ function saveOcr() {
60
+ while (ocrCache.size > OCR_CACHE_MAX) ocrCache.delete(ocrCache.keys().next().value)
61
+ const snapshot = JSON.stringify(Object.fromEntries(ocrCache))
62
+ ocrWriting = ocrWriting.then(async () => {
63
+ await mkdir(home, { recursive: true })
64
+ const temp = `${ocrPath}.${process.pid}.tmp`
65
+ await writeFile(temp, snapshot, 'utf8')
66
+ await rename(temp, ocrPath)
67
+ }).catch(error => rt.warn('ds-bot: OCR cache write failed: %s', error))
68
+ }
69
+
70
+ // `sessionId` is the Session the reading is for; its usage counts there.
71
+ async function readImage(attachment, sessionId) {
72
+ const route = await ocrRoute()
73
+ if (route === undefined) throw new Error('no vision model is available')
74
+ const assembler = new BlockAssembler()
75
+ // No sessionId: this call is not a Session request, so the hook below lets it through.
76
+ for await (const chunk of ctx.llm.stream({
77
+ provider: route.provider,
78
+ model: route.model,
79
+ messages: rt.tagUsage([{ role: 'user', content: [{ type: 'image', attachment }, { type: 'text', text: OCR_PROMPT }] }], { sessionId, kind: 'image' }),
80
+ maxTokens: 8192,
81
+ signal: AbortSignal.timeout(OCR_TIMEOUT_MS),
82
+ })) assembler.push(chunk)
83
+ const finish = assembler.finish
84
+ if (finish.kind === 'error' || finish.kind === 'aborted') throw new Error(finish.failure?.message ?? finish.kind)
85
+ const text = assembler.blocks().filter(block => block.type === 'text').map(block => block.text).join('\n').trim()
86
+ if (text === '') throw new Error('the vision model returned no text')
87
+ const model = (await rt.catalog()).find(entry => entry.ref === route.ref)?.name ?? route.model
88
+ return { text, model }
89
+ }
90
+
91
+ // Resolves to the cached reading, or to null when the image cannot be read now.
92
+ async function imageReading(attachment, sessionId) {
93
+ const id = String(attachment.attachmentId)
94
+ if (ocrCache.has(id)) return ocrCache.get(id)
95
+ const failed = ocrFailed.get(id)
96
+ if (failed && Date.now() - failed.at < OCR_RETRY_MS) return null
97
+ if (!ocrPending.has(id)) {
98
+ ocrPending.set(id, readImage(attachment, sessionId).then((reading) => {
99
+ ocrCache.set(id, reading)
100
+ ocrFailed.delete(id)
101
+ saveOcr()
102
+ return reading
103
+ }, (error) => {
104
+ rt.warn('ds-bot: could not read image %s: %s', id, error)
105
+ ocrFailed.set(id, { at: Date.now() })
106
+ return null
107
+ }).finally(() => ocrPending.delete(id)))
108
+ }
109
+ return ocrPending.get(id)
110
+ }
111
+
112
+ const imageLabel = attachment => (attachment.name
113
+ ? `"${attachment.name}"`
114
+ : `sha256:${String(attachment.attachmentId).slice('sha256:'.length, 'sha256:'.length + 8)}`)
115
+
116
+ function imageAsText(attachment, reading) {
117
+ const label = imageLabel(attachment)
118
+ return {
119
+ type: 'text',
120
+ text: reading === null
121
+ ? `[Image ${label}: you cannot see images and it could not be read right now. Ask the user what it shows if it matters.]`
122
+ : `[Image ${label}. You cannot see images, so ${reading.model} read it for you:]\n${reading.text}\n[End of image ${label}]`,
123
+ }
124
+ }
125
+
126
+ // Members read the group as text, so a picture posted there reaches every member,
127
+ // vision model or not, as its reading.
128
+ async function imagesForGroup(attachments, sessionId) {
129
+ await loadOcr()
130
+ return Promise.all(attachments.map(async (attachment) => {
131
+ const reading = await imageReading(attachment, sessionId)
132
+ const label = imageLabel(attachment)
133
+ return reading === null
134
+ ? `[Image ${label}: it could not be read right now. Ask the user what it shows if it matters.]`
135
+ : `[Image ${label}, read by ${reading.model}:]\n${reading.text}\n[End of image ${label}]`
136
+ }))
137
+ }
138
+
139
+ async function withImagesAsText(messages, sessionId) {
140
+ await loadOcr()
141
+ const images = new Map()
142
+ for (const message of messages) {
143
+ if (!liveImages(message)) continue
144
+ for (const block of message.content) {
145
+ if (block?.type === 'image' && !block.offloaded) images.set(String(block.attachment.attachmentId), block.attachment)
146
+ }
147
+ }
148
+ const readings = new Map(await Promise.all([...images].map(async ([id, attachment]) => [id, await imageReading(attachment, sessionId)])))
149
+ return messages.map(message => (liveImages(message)
150
+ ? {
151
+ ...message,
152
+ content: message.content.map(block => (block?.type === 'image' && !block.offloaded
153
+ ? imageAsText(block.attachment, readings.get(String(block.attachment.attachmentId)))
154
+ : block)),
155
+ }
156
+ : message))
157
+ }
158
+
159
+ ctx.on('llm/stream', (options, next) => {
160
+ if (options.sessionId === undefined || !(options.messages ?? []).some(liveImages)) return next()
161
+ return (async function* imagesAsTextOrPass() {
162
+ await rt.load()
163
+ if (rt.roomOf(options.sessionId) !== undefined || await readsImages(options.provider, options.model)) {
164
+ yield* next()
165
+ return
166
+ }
167
+ // `next` cannot take new messages, so the rewritten request starts over; it
168
+ // carries no image, so this listener lets it through.
169
+ yield* ctx.llm.stream({ ...options, messages: await withImagesAsText(options.messages, options.sessionId) })
170
+ })()
171
+ })
172
+
173
+ Object.assign(rt, { imagesForGroup })
174
+ }