ds-bot 0.0.0-stage → 0.1.1

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,91 @@
1
+ // One writer per plugin home. dsh Web and dsh Desktop share ~/.dsh, and each host keeps
2
+ // the team in memory and writes state.json whole, so two hosts at once would undo each
3
+ // other's changes. The first host to load takes `state.lock`; a second one only reads.
4
+ //
5
+ // The lock is a small JSON file (pid, host, a random token) whose mtime the holder bumps
6
+ // on a timer. It counts as gone when its process has exited (same host) or when it has
7
+ // not been bumped for `staleMs`, which also covers a reused pid after a crash. On another
8
+ // host only the age can tell, so a lock on shared storage waits out `staleMs`. The token,
9
+ // not the pid, decides ownership: a holder that finds another token has lost the lock.
10
+ import { randomUUID } from 'node:crypto'
11
+ import { readFileSync, statSync, unlinkSync, utimesSync, writeFileSync } from 'node:fs'
12
+ import { hostname } from 'node:os'
13
+
14
+ export function pidAlive(pid) {
15
+ try {
16
+ process.kill(pid, 0)
17
+ return true
18
+ } catch (error) {
19
+ // EPERM: the process exists but belongs to someone else.
20
+ return error?.code === 'EPERM'
21
+ }
22
+ }
23
+
24
+ export function homeLock(path, { staleMs = 60_000, beatMs = 15_000, host = hostname(), pid = process.pid, isAlive = pidAlive, now = Date.now } = {}) {
25
+ const token = randomUUID()
26
+ let timer
27
+
28
+ // undefined: no lock file; null: a file that does not parse (being written right now).
29
+ const read = () => {
30
+ try {
31
+ return JSON.parse(readFileSync(path, 'utf8'))
32
+ } catch (error) {
33
+ return error?.code === 'ENOENT' ? undefined : null
34
+ }
35
+ }
36
+ const age = () => {
37
+ try { return now() - statSync(path).mtimeMs } catch { return Infinity }
38
+ }
39
+ const live = (holder) => {
40
+ if (holder === undefined) return false
41
+ if (age() >= staleMs) return false
42
+ if (holder === null) return true
43
+ if (holder.host !== host) return true
44
+ // A lock this same process left (a plugin reload whose dispose never ran) is no rival.
45
+ return holder.pid !== pid && isAlive(holder.pid)
46
+ }
47
+ const owns = () => read()?.token === token
48
+
49
+ const beat = () => {
50
+ if (!owns()) {
51
+ stop()
52
+ return
53
+ }
54
+ const time = new Date(now())
55
+ try { utimesSync(path, time, time) } catch {}
56
+ }
57
+ const stop = () => {
58
+ if (timer !== undefined) clearInterval(timer)
59
+ timer = undefined
60
+ }
61
+
62
+ // Take the lock if it is free or its holder is gone. Returns undefined when this
63
+ // process holds it, else what the lock file says about the holder.
64
+ function claim() {
65
+ if (owns()) return undefined
66
+ for (let attempt = 0; attempt < 3; attempt++) {
67
+ try {
68
+ writeFileSync(path, JSON.stringify({ pid, host, token, since: now() }), { flag: 'wx' })
69
+ stop()
70
+ timer = setInterval(beat, beatMs)
71
+ timer.unref?.()
72
+ return undefined
73
+ } catch (error) {
74
+ if (error?.code !== 'EEXIST') throw error
75
+ }
76
+ const holder = read()
77
+ if (live(holder)) return holder ?? {}
78
+ try { unlinkSync(path) } catch {}
79
+ }
80
+ return read() ?? {}
81
+ }
82
+
83
+ function release() {
84
+ stop()
85
+ if (owns()) {
86
+ try { unlinkSync(path) } catch {}
87
+ }
88
+ }
89
+
90
+ return { claim, owns, release, read }
91
+ }
@@ -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
+ }