dsh-ta 0.1.0 → 0.3.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,107 @@
1
+ /** Local sticker packs. Assets are user-installed; nothing is bundled in npm. */
2
+ import { readFileSync, readdirSync, realpathSync, statSync } from 'node:fs'
3
+ import { isAbsolute, relative, resolve, sep } from 'node:path'
4
+
5
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$/
6
+ const SAFE_FILE = /\.(png|gif|webp|jpg|jpeg)$/i
7
+
8
+ export function stickerStatePath(config) {
9
+ return resolve(config.taHome, 'state/stickers.json')
10
+ }
11
+
12
+ export function readStickerState(config) {
13
+ try {
14
+ const value = JSON.parse(readFileSync(stickerStatePath(config), 'utf8'))
15
+ return value && typeof value === 'object' ? value : {}
16
+ } catch {
17
+ return {}
18
+ }
19
+ }
20
+
21
+ export function packsRoot(config) {
22
+ return resolve(config.taHome, 'stickers/packs')
23
+ }
24
+
25
+ function within(root, candidate) {
26
+ const path = resolve(candidate)
27
+ const rel = relative(root, path)
28
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
29
+ }
30
+
31
+ export function resolveStickerFile(pack, relative) {
32
+ if (typeof relative !== 'string' || relative.length === 0 || isAbsolute(relative)) return null
33
+ if (!SAFE_FILE.test(relative) || relative.split(/[\\/]/).includes('..')) return null
34
+ try {
35
+ const target = realpathSync(resolve(pack.dir, relative))
36
+ if (!within(pack.dir, target) || !statSync(target).isFile()) return null
37
+ return target
38
+ } catch {
39
+ return null
40
+ }
41
+ }
42
+
43
+ function validPackDir(root, entry) {
44
+ try {
45
+ const target = realpathSync(resolve(root, entry.name))
46
+ if (!within(root, target) || !statSync(target).isDirectory()) return null
47
+ const manifest = JSON.parse(readFileSync(resolve(target, 'pack.json'), 'utf8'))
48
+ if (manifest?.schemaVersion !== 1) return null
49
+ if (typeof manifest.id !== 'string' || !SAFE_ID.test(manifest.id)) return null
50
+ if (typeof manifest.version !== 'string' || !SAFE_ID.test(manifest.version)) return null
51
+ if (!Array.isArray(manifest.stickers)) return null
52
+ const declared = manifest.variants
53
+ let variants = {}
54
+ if (Array.isArray(declared)) {
55
+ // Legacy local packs declare variant names only; per-sticker variants carry the files.
56
+ if (!declared.every(variant => typeof variant === 'string' && SAFE_ID.test(variant))) return null
57
+ } else if (declared !== undefined) {
58
+ if (typeof declared !== 'object' || declared === null) return null
59
+ variants = { ...declared }
60
+ }
61
+ const pack = { ...manifest, dir: target, name: entry.name, variants }
62
+ for (const [variant, file] of Object.entries(variants)) {
63
+ if (!SAFE_ID.test(variant) || resolveStickerFile(pack, file) === null) return null
64
+ }
65
+ const stickers = manifest.stickers.map(sticker => {
66
+ if (typeof sticker?.id !== 'string' || !SAFE_ID.test(sticker.id)) return null
67
+ if (!Array.isArray(sticker.emotion) || sticker.emotion.length === 0) return null
68
+ if (typeof sticker.file !== 'string' || resolveStickerFile(pack, sticker.file) === null) return null
69
+ const localVariants = {}
70
+ if (sticker.variants !== undefined) {
71
+ if (typeof sticker.variants !== 'object' || sticker.variants === null || Array.isArray(sticker.variants)) return null
72
+ for (const [variant, file] of Object.entries(sticker.variants)) {
73
+ if (!SAFE_ID.test(variant) || resolveStickerFile(pack, file) === null) return null
74
+ localVariants[variant] = file
75
+ }
76
+ }
77
+ return { ...sticker, variants: localVariants }
78
+ }).filter(Boolean)
79
+ if (stickers.length === 0) return null
80
+ return { ...pack, stickers }
81
+ } catch {
82
+ return null
83
+ }
84
+ }
85
+
86
+ export function listPacks(config) {
87
+ const root = packsRoot(config)
88
+ let entries
89
+ try {
90
+ entries = readdirSync(root, { withFileTypes: true })
91
+ } catch {
92
+ return []
93
+ }
94
+ return entries
95
+ .filter(entry => entry.isDirectory())
96
+ .map(entry => validPackDir(root, entry))
97
+ .filter(Boolean)
98
+ }
99
+
100
+ export function activePack(config) {
101
+ const state = readStickerState(config)
102
+ const packs = listPacks(config)
103
+ const requested = typeof state.activePack === 'string' ? state.activePack : ''
104
+ return packs.find(pack => `${pack.id}@${pack.version}` === requested)
105
+ ?? packs.find(pack => pack.id === requested)
106
+ ?? (packs.length === 1 ? packs[0] : null)
107
+ }
@@ -0,0 +1,39 @@
1
+ import { activePack } from './load.js'
2
+
3
+ function token(value) {
4
+ return String(value ?? '').trim().toLowerCase()
5
+ }
6
+
7
+ export function selectSticker(config, emotion, variant) {
8
+ const pack = activePack(config)
9
+ if (!pack) return null
10
+ const wanted = token(emotion)
11
+ const candidates = pack.stickers.filter(sticker => sticker.emotion.some(item => token(item) === wanted))
12
+ if (candidates.length === 0) return null
13
+ const selected = candidates[Math.floor(Math.random() * candidates.length)]
14
+ const selectedVariant = typeof variant === 'string' && variant
15
+ ? variant
16
+ : (pack.defaultVariant ?? 'default')
17
+ const file = selected.variants?.[selectedVariant] ?? pack.variants?.[selectedVariant] ?? selected.file
18
+ return {
19
+ pack: pack.id,
20
+ version: pack.version,
21
+ variant: selectedVariant,
22
+ id: selected.id,
23
+ text: selected.text ?? selected.emotion.join(' / '),
24
+ file,
25
+ dir: pack.dir,
26
+ }
27
+ }
28
+
29
+ export function stickerEmotions(config) {
30
+ const pack = activePack(config)
31
+ if (!pack) return []
32
+ return [...new Set(pack.stickers.flatMap(sticker => sticker.emotion))].sort()
33
+ }
34
+
35
+ export function stickerGuidance(config) {
36
+ const pack = activePack(config)
37
+ if (!pack) return ''
38
+ return `You can occasionally send one local sticker with ta_sticker when it naturally adds tone. Use at most one per turn, never instead of a substantive answer. Prefer it for strong emotion or when there is little to say. After the tool call, if the tool result contains a markdown field, include that exact line in your final reply. Keep a short text reply too; do not end the turn with the sticker alone. The image must be in the assistant text, not only in the tool result. Available emotions: ${stickerEmotions(config).join(', ')}.`
39
+ }
@@ -0,0 +1,48 @@
1
+ import { createReadStream } from 'node:fs'
2
+ import { listPacks, resolveStickerFile } from './load.js'
3
+
4
+ const ROOT = '/api/dsh-ta/stickers'
5
+ const MIME = { '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg' }
6
+
7
+ export function mountStickerRoute(ctx, config) {
8
+ if (typeof ctx.inject !== 'function') return
9
+ ctx.inject(['webServer'], scope => {
10
+ const server = scope.webServer ?? scope.get?.('webServer')
11
+ if (typeof server?.register !== 'function') return
12
+ try {
13
+ scope.effect(() => server.register({
14
+ kind: 'prefix',
15
+ path: ROOT,
16
+ auth: 'anonymous',
17
+ handler: (request, response) => {
18
+ let parts
19
+ try {
20
+ const pathname = new URL(request.url ?? '/', 'http://localhost').pathname
21
+ parts = pathname.slice(ROOT.length + 1).split('/').map(decodeURIComponent)
22
+ } catch {
23
+ response.writeHead(400); response.end(); return
24
+ }
25
+ if (parts.length < 4) { response.writeHead(404); response.end(); return }
26
+ const [id, version, variant, ...fileParts] = parts
27
+ const pack = listPacks(config).find(item => item.id === id && item.version === version)
28
+ if (!pack) { response.writeHead(404); response.end(); return }
29
+ const relative = fileParts.join('/')
30
+ const file = pack.stickers.find(item => (item.variants?.[variant] ?? pack.variants?.[variant] ?? item.file) === relative)
31
+ const target = file ? resolveStickerFile(pack, relative) : null
32
+ if (!target) { response.writeHead(404); response.end(); return }
33
+ try {
34
+ response.writeHead(200, { 'content-type': MIME[relative.slice(relative.lastIndexOf('.')).toLowerCase()] ?? 'application/octet-stream', 'cache-control': 'public, max-age=86400' })
35
+ const stream = createReadStream(target)
36
+ stream.on('error', () => { if (!response.headersSent) response.writeHead(500); response.destroy() })
37
+ response.on('close', () => stream.destroy())
38
+ stream.pipe(response)
39
+ } catch {
40
+ response.writeHead(404); response.end()
41
+ }
42
+ },
43
+ }), 'dsh-ta sticker route')
44
+ } catch (error) {
45
+ try { ctx.logger?.warn?.(error) } catch { /* logger optional */ }
46
+ }
47
+ })
48
+ }
@@ -0,0 +1,150 @@
1
+ import { copyFileSync, mkdirSync } from 'node:fs'
2
+ import { extname, resolve } from 'node:path'
3
+ import { randomUUID } from 'node:crypto'
4
+ import { activePack, readStickerState, resolveStickerFile, stickerStatePath } from './load.js'
5
+ import { selectSticker, stickerEmotions } from './select.js'
6
+ import { todayText, writeAtomic } from '../storage.js'
7
+
8
+ const DEFAULT_MAX_PER_DAY = 12
9
+ const DEFAULT_MIN_GAP_MINUTES = 30
10
+ const pendingDeliveries = new WeakMap()
11
+ const deliveryListeners = new WeakSet()
12
+
13
+ function ensureDeliveryListener(ctx) {
14
+ if (deliveryListeners.has(ctx) || typeof ctx.on !== 'function') return
15
+ deliveryListeners.add(ctx)
16
+ ctx.on('tools/result', (exec, result) => {
17
+ const delivery = pendingDeliveries.get(exec)
18
+ pendingDeliveries.delete(exec)
19
+ if (delivery === undefined || result?.isError) return
20
+ try {
21
+ delivery.session.append('deliverables/presented', {
22
+ turn: delivery.turn,
23
+ callId: exec.callId,
24
+ files: delivery.files,
25
+ })
26
+ } catch (error) {
27
+ try { ctx.logger?.warn?.(error) } catch { /* logger optional */ }
28
+ }
29
+ })
30
+ }
31
+
32
+ function sessionCooldown(config, state, sessionId) {
33
+ const today = todayText(config)
34
+ const sessions = state && typeof state.sessions === 'object' && state.sessions !== null ? state.sessions : {}
35
+ const previous = sessions[String(sessionId)] ?? {}
36
+ return {
37
+ sessions,
38
+ previous,
39
+ count: previous.day === today ? Number(previous.count) || 0 : 0,
40
+ }
41
+ }
42
+
43
+ export function stickerTool(ctx, config) {
44
+ ensureDeliveryListener(ctx)
45
+ const pack = activePack(config)
46
+ if (!pack) return null
47
+ const emotions = stickerEmotions(config)
48
+ return {
49
+ name: 'ta_sticker',
50
+ description: `Send one local reaction sticker only when it naturally adds tone. Use at most one per turn, and do not replace a substantive answer. Available emotions: ${emotions.join(', ')}.`,
51
+ parameters: {
52
+ type: 'object',
53
+ additionalProperties: false,
54
+ properties: {
55
+ emotion: { type: 'string', description: `One of: ${emotions.join(', ')}` },
56
+ variant: { type: 'string', description: 'Optional pack variant; defaults to the pack default.' },
57
+ },
58
+ required: ['emotion'],
59
+ },
60
+ output: {
61
+ schema: {
62
+ type: 'object',
63
+ additionalProperties: false,
64
+ properties: {
65
+ ok: { type: 'boolean' },
66
+ emotion: { type: 'string' },
67
+ text: { type: 'string' },
68
+ image: { type: 'string' },
69
+ imagePath: { type: 'string' },
70
+ markdown: { type: 'string' },
71
+ pack: { type: 'string' },
72
+ version: { type: 'string' },
73
+ },
74
+ required: ['ok', 'emotion', 'text', 'image', 'imagePath', 'pack', 'version'],
75
+ },
76
+ render: (_args, value) => {
77
+ const visible = {
78
+ ok: value.ok,
79
+ emotion: value.emotion,
80
+ text: value.text,
81
+ pack: value.pack,
82
+ version: value.version,
83
+ }
84
+ return [{ type: 'text', text: value.markdown
85
+ ? `表情已准备。最终回复必须原样包含这行 Markdown:\n${value.markdown}\nSTICKER:${JSON.stringify(value)}`
86
+ : `表情已发送。\nSTICKER:${JSON.stringify(visible)}` }]
87
+ },
88
+ },
89
+ async execute(args, exec) {
90
+ const emotion = String(args?.emotion ?? '').trim()
91
+ if (!emotion) throw new Error('emotion is required')
92
+ const state = readStickerState(config)
93
+ const today = todayText(config)
94
+ const session = exec?.agent?.session
95
+ const sessionId = String(session?.id ?? 'unknown')
96
+ const cooldown = sessionCooldown(config, state, sessionId)
97
+ const maxPerDay = Number.isSafeInteger(config.stickerMaxPerDay) ? config.stickerMaxPerDay : DEFAULT_MAX_PER_DAY
98
+ const minGapMinutes = Number.isFinite(config.stickerMinGapMinutes) ? config.stickerMinGapMinutes : DEFAULT_MIN_GAP_MINUTES
99
+ const minGapMs = minGapMinutes * 60 * 1000
100
+ if (cooldown.count >= maxPerDay) throw new Error('今天表情已经够多了')
101
+ if (minGapMs > 0 && Number.isFinite(cooldown.previous.lastAt) && Date.now() - cooldown.previous.lastAt < minGapMs) {
102
+ throw new Error('刚刚已经发过表情,先缓一缓')
103
+ }
104
+ const selected = selectSticker(config, emotion, args?.variant)
105
+ if (!selected) throw new Error(`没有这个情绪的表情:${emotion}`)
106
+ const extension = extname(selected.file).toLowerCase() || '.png'
107
+ const relative = `outbox/stickers/${randomUUID()}${extension}`
108
+ const destination = resolve(config.taHome, relative)
109
+ mkdirSync(resolve(config.taHome, 'outbox/stickers'), { recursive: true })
110
+ const source = resolveStickerFile({ dir: selected.dir }, selected.file)
111
+ if (!source) throw new Error('表情文件不可用')
112
+ copyFileSync(source, destination)
113
+ const image = `/api/dsh-ta/stickers/${encodeURIComponent(selected.pack)}/${encodeURIComponent(selected.version)}/${encodeURIComponent(selected.variant)}/${selected.file.split('/').map(encodeURIComponent).join('/')}`
114
+ const isIm = sessionId.startsWith('dsh-im-session-')
115
+ if (isIm) {
116
+ try {
117
+ const boundary = ctx.agents?.turnBoundaryOf?.(session)
118
+ if (boundary?.openTurnStartSeq !== null && boundary?.lastTurn !== undefined) {
119
+ pendingDeliveries.set(exec, {
120
+ session,
121
+ turn: boundary.lastTurn,
122
+ files: [{ path: destination, description: selected.text }],
123
+ })
124
+ }
125
+ } catch {
126
+ /* delivery is optional; the tool result still stands */
127
+ }
128
+ }
129
+ writeAtomic(stickerStatePath(config), JSON.stringify({
130
+ ...state,
131
+ activePack: `${selected.pack}@${selected.version}`,
132
+ activeVariant: selected.variant,
133
+ sessions: {
134
+ ...cooldown.sessions,
135
+ [sessionId]: { day: today, count: cooldown.count + 1, lastAt: Date.now() },
136
+ },
137
+ }, null, 2) + '\n')
138
+ return {
139
+ ok: true,
140
+ emotion,
141
+ text: selected.text,
142
+ image,
143
+ imagePath: destination,
144
+ ...(isIm ? {} : { markdown: `![表情](<${destination}>)` }),
145
+ pack: selected.pack,
146
+ version: selected.version,
147
+ }
148
+ },
149
+ }
150
+ }
package/storage.js ADDED
@@ -0,0 +1,122 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { accessSync, constants, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs'
3
+ import { dirname, resolve, sep } from 'node:path'
4
+
5
+ export function recordSessionMap(config, dshSessionId, remeSessionId) {
6
+ try {
7
+ const path = resolve(config.taHome, config.sessionMap)
8
+ let value = {}
9
+ try {
10
+ value = JSON.parse(readFileSync(path, 'utf8'))
11
+ } catch {
12
+ value = {}
13
+ }
14
+ if (value[remeSessionId] === dshSessionId) return
15
+ value[remeSessionId] = dshSessionId
16
+ mkdirSync(resolve(config.taHome, 'state'), { recursive: true })
17
+ const temporary = `${path}.tmp`
18
+ writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n')
19
+ renameSync(temporary, path)
20
+ } catch {
21
+ /* mapping is diagnostic; capture must not fail for it */
22
+ }
23
+ }
24
+
25
+ export function readInternalSessions(config) {
26
+ try {
27
+ const value = JSON.parse(readFileSync(resolve(config.taHome, config.internalSessions), 'utf8'))
28
+ return Array.isArray(value) ? value : (value && typeof value === 'object' ? value : {})
29
+ } catch {
30
+ return {}
31
+ }
32
+ }
33
+
34
+ export function internalSessionIds(config) {
35
+ const value = readInternalSessions(config)
36
+ const ids = Array.isArray(value) ? value : Object.keys(value)
37
+ return new Set(ids.filter(id => typeof id === 'string'))
38
+ }
39
+
40
+
41
+ export function realPath(value) {
42
+ if (typeof value !== 'string' || value.length === 0) return ''
43
+ try {
44
+ return realpathSync.native(value)
45
+ } catch {
46
+ return resolve(value)
47
+ }
48
+ }
49
+
50
+ /**
51
+ * True only for an ordinary Session whose cwd is Ta's home and whose current
52
+ * preset is one of the configured Ta presets.
53
+ */
54
+ export function withinHome(relative, config) {
55
+ if (typeof relative !== 'string' || relative.length === 0) throw new Error('path is required')
56
+ const base = realPath(config.taHome)
57
+ const target = realPath(resolve(base, relative))
58
+ if (target !== base && !target.startsWith(base + sep)) throw new Error('path is outside TA_HOME')
59
+ return target
60
+ }
61
+
62
+ export function writeAtomic(path, text) {
63
+ mkdirSync(dirname(path), { recursive: true })
64
+ const temporary = `${path}.tmp-${process.pid}-${Date.now()}`
65
+ writeFileSync(temporary, text)
66
+ renameSync(temporary, path)
67
+ }
68
+
69
+ export function readTextIfExists(path) {
70
+ try {
71
+ if (!statSync(path).isFile()) return undefined
72
+ return readFileSync(path, 'utf8')
73
+ } catch {
74
+ return undefined
75
+ }
76
+ }
77
+
78
+ export function sha256Revision(text) {
79
+ return `sha256:${createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex')}`
80
+ }
81
+
82
+ export function ensureDir(path) {
83
+ mkdirSync(path, { recursive: true })
84
+ }
85
+
86
+ export function isWritableDirectory(path) {
87
+ try {
88
+ if (!statSync(path).isDirectory()) return false
89
+ accessSync(path, constants.W_OK)
90
+ return true
91
+ } catch {
92
+ return false
93
+ }
94
+ }
95
+
96
+ export function todayText(config) {
97
+ return new Intl.DateTimeFormat('en-CA', {
98
+ timeZone: config.timezone,
99
+ year: 'numeric',
100
+ month: '2-digit',
101
+ day: '2-digit',
102
+ }).format(new Date())
103
+ }
104
+
105
+ export function startOfLocalDay(config) {
106
+ const date = todayText(config)
107
+ if (config.timezone === 'Asia/Shanghai') return Date.parse(`${date}T00:00:00+08:00`)
108
+ return new Date(`${date}T00:00:00`).getTime()
109
+ }
110
+
111
+
112
+ export function localHourMinute(config) {
113
+ const parts = new Intl.DateTimeFormat('en-GB', {
114
+ timeZone: config.timezone,
115
+ hour: '2-digit',
116
+ minute: '2-digit',
117
+ hourCycle: 'h23',
118
+ }).formatToParts(new Date())
119
+ const hour = parts.find(part => part.type === 'hour')?.value
120
+ const minute = parts.find(part => part.type === 'minute')?.value
121
+ return `${hour ?? '00'}:${minute ?? '00'}`
122
+ }