dsh-ta 0.1.0 → 0.2.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.
- package/CHANGELOG.md +12 -0
- package/README.md +32 -0
- package/client.js +74 -1
- package/config.js +154 -0
- package/docs/PACKS.md +78 -0
- package/docs/USAGE.md +93 -0
- package/gates.js +18 -0
- package/identity.js +97 -0
- package/im/bindings.js +29 -0
- package/im/say.js +24 -0
- package/index.js +53 -1556
- package/jurisdiction.js +171 -0
- package/life.js +277 -0
- package/package.json +17 -2
- package/prompts.js +28 -0
- package/reme.js +23 -0
- package/runtime.js +209 -0
- package/stickers/load.js +107 -0
- package/stickers/select.js +39 -0
- package/stickers/serve.js +48 -0
- package/stickers/tool.js +150 -0
- package/storage.js +95 -0
- package/tools.js +540 -0
- package/usage/aggregate.js +78 -0
- package/usage/ledger.js +126 -0
- package/usage/pricing.js +52 -0
- package/usage/serve.js +38 -0
package/runtime.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { readFileSync, readdirSync } from 'node:fs'
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { cleanupOutings } from './life.js'
|
|
5
|
+
import { localHourMinute, todayText, writeAtomic } from './storage.js'
|
|
6
|
+
import { JURISDICTION_PROMPT, REVIEW_PROMPT, REVIEW_TITLE } from './prompts.js'
|
|
7
|
+
|
|
8
|
+
export async function ensureReviewSchedule(ctx, config) {
|
|
9
|
+
const schedule = ctx.get?.('schedule')
|
|
10
|
+
if (!schedule?.list || !schedule?.create) return
|
|
11
|
+
try {
|
|
12
|
+
const page = await schedule.list({ active: true })
|
|
13
|
+
if ((page.items ?? []).some(item => item.title === REVIEW_TITLE)) return
|
|
14
|
+
const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)
|
|
15
|
+
const date = new Intl.DateTimeFormat('en-CA', {
|
|
16
|
+
timeZone: config.timezone,
|
|
17
|
+
year: 'numeric',
|
|
18
|
+
month: '2-digit',
|
|
19
|
+
day: '2-digit',
|
|
20
|
+
}).format(tomorrow).replaceAll('-', '')
|
|
21
|
+
await schedule.create({
|
|
22
|
+
title: REVIEW_TITLE,
|
|
23
|
+
prompt: REVIEW_PROMPT,
|
|
24
|
+
timing: {
|
|
25
|
+
kind: 'rrule',
|
|
26
|
+
rrule: `DTSTART;TZID=${config.timezone}:${date}T230000\nRRULE:FREQ=DAILY`,
|
|
27
|
+
},
|
|
28
|
+
target: {
|
|
29
|
+
kind: 'new_once',
|
|
30
|
+
create: { cwd: config.taHome, agentPreset: 'ta-review' },
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
} catch {
|
|
34
|
+
/* schedule service may be unavailable in a reduced profile */
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function startDreamClock(ctx, config) {
|
|
39
|
+
const marker = resolve(config.taHome, 'state/dream-last.json')
|
|
40
|
+
const timer = setInterval(() => {
|
|
41
|
+
if (!config.dreamEnabled || localHourMinute(config) !== '22:30') return
|
|
42
|
+
const date = todayText(config)
|
|
43
|
+
try {
|
|
44
|
+
const last = JSON.parse(readFileSync(marker, 'utf8'))
|
|
45
|
+
if (last?.date === date) return
|
|
46
|
+
} catch {
|
|
47
|
+
/* no marker yet */
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
writeAtomic(marker, JSON.stringify({ date, startedAt: new Date().toISOString() }) + '\n')
|
|
51
|
+
} catch {
|
|
52
|
+
return
|
|
53
|
+
}
|
|
54
|
+
const controller = new AbortController()
|
|
55
|
+
const timeout = setTimeout(() => controller.abort(), 10 * 60 * 1000)
|
|
56
|
+
void fetch(`${config.remeEndpoint}/auto_dream`, {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
headers: { 'content-type': 'application/json' },
|
|
59
|
+
body: JSON.stringify({ date, hint: '' }),
|
|
60
|
+
signal: controller.signal,
|
|
61
|
+
}).catch(() => {}).finally(() => clearTimeout(timeout))
|
|
62
|
+
}, 30_000)
|
|
63
|
+
timer.unref?.()
|
|
64
|
+
if (typeof ctx.effect !== 'function') {
|
|
65
|
+
clearInterval(timer)
|
|
66
|
+
return
|
|
67
|
+
}
|
|
68
|
+
ctx.effect(() => () => clearInterval(timer), 'dsh-ta.dreamClock')
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function recordInternalSession(config, sessionId, purpose = 'other') {
|
|
72
|
+
try {
|
|
73
|
+
const path = resolve(config.taHome, config.internalSessions)
|
|
74
|
+
let value = {}
|
|
75
|
+
try {
|
|
76
|
+
value = JSON.parse(readFileSync(path, 'utf8'))
|
|
77
|
+
} catch {
|
|
78
|
+
value = {}
|
|
79
|
+
}
|
|
80
|
+
const next = Array.isArray(value)
|
|
81
|
+
? Object.fromEntries(value.map(id => [String(id), 'other']))
|
|
82
|
+
: { ...(value && typeof value === 'object' ? value : {}) }
|
|
83
|
+
next[String(sessionId)] = String(purpose)
|
|
84
|
+
writeAtomic(path, JSON.stringify(next, null, 2) + '\n')
|
|
85
|
+
} catch {
|
|
86
|
+
/* heartbeat still runs; capture filter may miss this id */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function startHeartbeat(ctx, config) {
|
|
91
|
+
const marker = resolve(config.taHome, 'state/heartbeat-last.json')
|
|
92
|
+
let busy = false
|
|
93
|
+
const tick = async () => {
|
|
94
|
+
if (!config.heartbeatEnabled || busy) return
|
|
95
|
+
const clock = localHourMinute(config)
|
|
96
|
+
if (clock < config.heartbeatActiveStart || clock > config.heartbeatActiveEnd) return
|
|
97
|
+
let last = 0
|
|
98
|
+
try {
|
|
99
|
+
last = Number(JSON.parse(readFileSync(marker, 'utf8'))?.at ?? 0)
|
|
100
|
+
} catch {
|
|
101
|
+
last = 0
|
|
102
|
+
}
|
|
103
|
+
if (Date.now() - last < 45 * 60 * 1000) return
|
|
104
|
+
let inbox = []
|
|
105
|
+
try {
|
|
106
|
+
inbox = readdirSync(resolve(config.taHome, 'inbox'))
|
|
107
|
+
} catch {
|
|
108
|
+
inbox = []
|
|
109
|
+
}
|
|
110
|
+
if (inbox.length === 0) return
|
|
111
|
+
const controller = ctx.get('sessionController')
|
|
112
|
+
if (!controller?.create || !controller?.resolveAgent) return
|
|
113
|
+
busy = true
|
|
114
|
+
try {
|
|
115
|
+
const created = await controller.create({ cwd: config.taHome, agentPreset: 'ta' })
|
|
116
|
+
const sessionId = created?.sessionId ?? created?.value?.sessionId
|
|
117
|
+
if (!sessionId) return
|
|
118
|
+
recordInternalSession(config, sessionId, 'heartbeat')
|
|
119
|
+
const resolved = await controller.resolveAgent(sessionId)
|
|
120
|
+
const agent = resolved?.agent
|
|
121
|
+
if (!agent) return
|
|
122
|
+
await agent.followup({
|
|
123
|
+
id: randomUUID(),
|
|
124
|
+
role: 'user',
|
|
125
|
+
content: [{
|
|
126
|
+
type: 'text',
|
|
127
|
+
text: '这是 Ta 的心跳。先读 inbox/;如果不需要行动,输出 NO_REPLY;如果有需要,处理并最多用 ta_say 对博士说一句。不要汇报系统状态。',
|
|
128
|
+
}],
|
|
129
|
+
source: { kind: 'ta-life', form: 'notice', summary: 'Ta 心跳' },
|
|
130
|
+
})
|
|
131
|
+
writeAtomic(marker, JSON.stringify({ at: Date.now(), sessionId: String(sessionId) }) + '\n')
|
|
132
|
+
} catch {
|
|
133
|
+
/* a heartbeat failure must not affect the host */
|
|
134
|
+
} finally {
|
|
135
|
+
busy = false
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const timer = setInterval(() => { void tick().catch(() => {}) }, 60_000)
|
|
139
|
+
timer.unref?.()
|
|
140
|
+
if (typeof ctx.effect === 'function') {
|
|
141
|
+
ctx.effect(() => () => clearInterval(timer), 'dsh-ta.heartbeat')
|
|
142
|
+
} else {
|
|
143
|
+
clearInterval(timer)
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function startOutingCleanup(ctx, config) {
|
|
148
|
+
const marker = resolve(config.taHome, 'state/cleanup-last.json')
|
|
149
|
+
const timer = setInterval(() => {
|
|
150
|
+
if (!config.outingCleanupEnabled || localHourMinute(config) !== '02:00') return
|
|
151
|
+
const today = todayText(config)
|
|
152
|
+
try {
|
|
153
|
+
if (JSON.parse(readFileSync(marker, 'utf8'))?.date === today) return
|
|
154
|
+
} catch {
|
|
155
|
+
/* no marker */
|
|
156
|
+
}
|
|
157
|
+
const removed = cleanupOutings(config)
|
|
158
|
+
try {
|
|
159
|
+
writeAtomic(marker, JSON.stringify({ date: today, removed }) + '\n')
|
|
160
|
+
} catch {
|
|
161
|
+
/* diagnostic only */
|
|
162
|
+
}
|
|
163
|
+
}, 60_000)
|
|
164
|
+
timer.unref?.()
|
|
165
|
+
if (typeof ctx.effect === 'function') {
|
|
166
|
+
ctx.effect(() => () => clearInterval(timer), 'dsh-ta.outingCleanup')
|
|
167
|
+
} else {
|
|
168
|
+
clearInterval(timer)
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function startJurisdictionOuting(ctx, config) {
|
|
173
|
+
const marker = resolve(config.taHome, 'state/jurisdiction-outing.json')
|
|
174
|
+
let busy = false
|
|
175
|
+
const timer = setInterval(() => {
|
|
176
|
+
if (!config.jurisdictionOutingEnabled || busy || localHourMinute(config) !== config.jurisdictionOutingTime) return
|
|
177
|
+
const today = todayText(config)
|
|
178
|
+
try {
|
|
179
|
+
if (JSON.parse(readFileSync(marker, 'utf8'))?.date === today) return
|
|
180
|
+
} catch {
|
|
181
|
+
/* no marker */
|
|
182
|
+
}
|
|
183
|
+
const controller = ctx.get('sessionController')
|
|
184
|
+
if (!controller?.create || !controller?.resolveAgent) return
|
|
185
|
+
busy = true
|
|
186
|
+
void (async () => {
|
|
187
|
+
const created = await controller.create({ cwd: config.taHome, agentPreset: 'ta' })
|
|
188
|
+
const sessionId = created?.sessionId ?? created?.value?.sessionId
|
|
189
|
+
if (!sessionId) return
|
|
190
|
+
recordInternalSession(config, sessionId, 'outing')
|
|
191
|
+
writeAtomic(marker, JSON.stringify({ date: today, sessionId: String(sessionId) }) + '\n')
|
|
192
|
+
const resolved = await controller.resolveAgent(sessionId)
|
|
193
|
+
if (!resolved?.agent) return
|
|
194
|
+
await resolved.agent.followup({
|
|
195
|
+
id: randomUUID(),
|
|
196
|
+
role: 'user',
|
|
197
|
+
content: [{ type: 'text', text: JURISDICTION_PROMPT }],
|
|
198
|
+
source: { kind: 'ta-life', form: 'notice', summary: '辖区查看' },
|
|
199
|
+
})
|
|
200
|
+
})().catch(() => {}).finally(() => { busy = false })
|
|
201
|
+
}, 60_000)
|
|
202
|
+
timer.unref?.()
|
|
203
|
+
if (typeof ctx.effect === 'function') {
|
|
204
|
+
ctx.effect(() => () => clearInterval(timer), 'dsh-ta.jurisdictionOuting')
|
|
205
|
+
} else {
|
|
206
|
+
clearInterval(timer)
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
package/stickers/load.js
ADDED
|
@@ -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
|
+
}
|
package/stickers/tool.js
ADDED
|
@@ -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: `` }),
|
|
145
|
+
pack: selected.pack,
|
|
146
|
+
version: selected.version,
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
}
|
|
150
|
+
}
|
package/storage.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, resolve, sep } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export function recordSessionMap(config, dshSessionId, remeSessionId) {
|
|
5
|
+
try {
|
|
6
|
+
const path = resolve(config.taHome, config.sessionMap)
|
|
7
|
+
let value = {}
|
|
8
|
+
try {
|
|
9
|
+
value = JSON.parse(readFileSync(path, 'utf8'))
|
|
10
|
+
} catch {
|
|
11
|
+
value = {}
|
|
12
|
+
}
|
|
13
|
+
if (value[remeSessionId] === dshSessionId) return
|
|
14
|
+
value[remeSessionId] = dshSessionId
|
|
15
|
+
mkdirSync(resolve(config.taHome, 'state'), { recursive: true })
|
|
16
|
+
const temporary = `${path}.tmp`
|
|
17
|
+
writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n')
|
|
18
|
+
renameSync(temporary, path)
|
|
19
|
+
} catch {
|
|
20
|
+
/* mapping is diagnostic; capture must not fail for it */
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function readInternalSessions(config) {
|
|
25
|
+
try {
|
|
26
|
+
const value = JSON.parse(readFileSync(resolve(config.taHome, config.internalSessions), 'utf8'))
|
|
27
|
+
return Array.isArray(value) ? value : (value && typeof value === 'object' ? value : {})
|
|
28
|
+
} catch {
|
|
29
|
+
return {}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function internalSessionIds(config) {
|
|
34
|
+
const value = readInternalSessions(config)
|
|
35
|
+
const ids = Array.isArray(value) ? value : Object.keys(value)
|
|
36
|
+
return new Set(ids.filter(id => typeof id === 'string'))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
export function realPath(value) {
|
|
41
|
+
if (typeof value !== 'string' || value.length === 0) return ''
|
|
42
|
+
try {
|
|
43
|
+
return realpathSync.native(value)
|
|
44
|
+
} catch {
|
|
45
|
+
return resolve(value)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* True only for an ordinary Session whose cwd is Ta's home and whose current
|
|
51
|
+
* preset is one of the configured Ta presets.
|
|
52
|
+
*/
|
|
53
|
+
export function withinHome(relative, config) {
|
|
54
|
+
if (typeof relative !== 'string' || relative.length === 0) throw new Error('path is required')
|
|
55
|
+
const base = realPath(config.taHome)
|
|
56
|
+
const target = realPath(resolve(base, relative))
|
|
57
|
+
if (target !== base && !target.startsWith(base + sep)) throw new Error('path is outside TA_HOME')
|
|
58
|
+
return target
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function writeAtomic(path, text) {
|
|
62
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
63
|
+
const temporary = `${path}.tmp-${process.pid}-${Date.now()}`
|
|
64
|
+
writeFileSync(temporary, text)
|
|
65
|
+
renameSync(temporary, path)
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function todayText(config) {
|
|
69
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
70
|
+
timeZone: config.timezone,
|
|
71
|
+
year: 'numeric',
|
|
72
|
+
month: '2-digit',
|
|
73
|
+
day: '2-digit',
|
|
74
|
+
}).format(new Date())
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function startOfLocalDay(config) {
|
|
78
|
+
const date = todayText(config)
|
|
79
|
+
if (config.timezone === 'Asia/Shanghai') return Date.parse(`${date}T00:00:00+08:00`)
|
|
80
|
+
return new Date(`${date}T00:00:00`).getTime()
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
export function localHourMinute(config) {
|
|
85
|
+
const parts = new Intl.DateTimeFormat('en-GB', {
|
|
86
|
+
timeZone: config.timezone,
|
|
87
|
+
hour: '2-digit',
|
|
88
|
+
minute: '2-digit',
|
|
89
|
+
hourCycle: 'h23',
|
|
90
|
+
}).formatToParts(new Date())
|
|
91
|
+
const hour = parts.find(part => part.type === 'hour')?.value
|
|
92
|
+
const minute = parts.find(part => part.type === 'minute')?.value
|
|
93
|
+
return `${hour ?? '00'}:${minute ?? '00'}`
|
|
94
|
+
}
|
|
95
|
+
|