dsh-ta 0.0.0-stage → 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 +30 -0
- package/LICENSE +21 -0
- package/README.md +419 -2
- package/client.js +618 -0
- package/config.js +154 -0
- package/cordis.patch.yml +101 -0
- package/docs/PACKS.md +78 -0
- package/docs/RELEASE.md +88 -0
- package/docs/USAGE.md +93 -0
- package/docs/presets.example.yml +95 -0
- package/docs/reme/.env.example +11 -0
- package/docs/reme/docker-compose.yml +25 -0
- package/gates.js +18 -0
- package/icon.svg +8 -0
- package/identity.js +97 -0
- package/im/bindings.js +29 -0
- package/im/say.js +24 -0
- package/index.js +172 -0
- package/jurisdiction.js +171 -0
- package/life.js +277 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/memory/capture.js +113 -0
- package/memory/messages.js +76 -0
- package/memory/outbox.js +130 -0
- package/package.json +75 -4
- 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/life.js
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
import { readFileSync, readdirSync, unlinkSync } from 'node:fs'
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { todayText, withinHome, writeAtomic } from './storage.js'
|
|
5
|
+
|
|
6
|
+
export function readNoteLines(config) {
|
|
7
|
+
try {
|
|
8
|
+
return readFileSync(withinHome('notes/note.md', config), 'utf8').split(/\r?\n/).filter(Boolean)
|
|
9
|
+
} catch {
|
|
10
|
+
return []
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function addNote(config, text) {
|
|
15
|
+
const line = String(text ?? '').replace(/\s+/g, ' ').trim()
|
|
16
|
+
if (!line) throw new Error('text is required')
|
|
17
|
+
const lines = [...readNoteLines(config), line].slice(-80)
|
|
18
|
+
writeAtomic(withinHome('notes/note.md', config), lines.join('\n') + '\n')
|
|
19
|
+
return `notes/note.md (${lines.length}/80)`
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function reviewLockPath(config) {
|
|
23
|
+
return resolve(config.taHome, 'state/review.lock')
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function acquireReviewLock(config, sessionId) {
|
|
27
|
+
const path = reviewLockPath(config)
|
|
28
|
+
try {
|
|
29
|
+
const existing = JSON.parse(readFileSync(path, 'utf8'))
|
|
30
|
+
if (existing?.pid === process.pid && existing?.sessionId !== String(sessionId)) return false
|
|
31
|
+
if (existing?.pid !== process.pid && Number.isSafeInteger(existing?.pid)) {
|
|
32
|
+
try {
|
|
33
|
+
process.kill(existing.pid, 0)
|
|
34
|
+
return false
|
|
35
|
+
} catch {
|
|
36
|
+
/* stale */
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
/* no lock */
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
writeAtomic(path, JSON.stringify({
|
|
44
|
+
pid: process.pid,
|
|
45
|
+
sessionId: String(sessionId),
|
|
46
|
+
startedAt: new Date().toISOString(),
|
|
47
|
+
}) + '\n')
|
|
48
|
+
return true
|
|
49
|
+
} catch {
|
|
50
|
+
return false
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function releaseReviewLock(config, sessionId) {
|
|
55
|
+
try {
|
|
56
|
+
const path = reviewLockPath(config)
|
|
57
|
+
const existing = JSON.parse(readFileSync(path, 'utf8'))
|
|
58
|
+
if (existing?.pid === process.pid && existing?.sessionId === String(sessionId)) unlinkSync(path)
|
|
59
|
+
} catch {
|
|
60
|
+
/* no lock */
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const OUTING_LIMIT_PER_DAY = 4
|
|
65
|
+
const OUTING_TIMEOUT_MS = 20 * 60 * 1000
|
|
66
|
+
const OUTING_MAX_CHARS = 6000
|
|
67
|
+
|
|
68
|
+
function outingStatePath(config) {
|
|
69
|
+
return resolve(config.taHome, 'state/outing.json')
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function readOutingState(config) {
|
|
73
|
+
const today = todayText(config)
|
|
74
|
+
try {
|
|
75
|
+
const state = JSON.parse(readFileSync(outingStatePath(config), 'utf8'))
|
|
76
|
+
if (state?.day !== today) return { day: today, count: 0, active: null }
|
|
77
|
+
return {
|
|
78
|
+
day: today,
|
|
79
|
+
count: Number.isSafeInteger(state.count) ? state.count : 0,
|
|
80
|
+
active: state.active && typeof state.active === 'object' ? state.active : null,
|
|
81
|
+
}
|
|
82
|
+
} catch {
|
|
83
|
+
return { day: today, count: 0, active: null }
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function outingSlug(value) {
|
|
88
|
+
const slug = String(value ?? '').trim().toLocaleLowerCase()
|
|
89
|
+
.replace(/[^\p{L}\p{N}-]+/gu, '-')
|
|
90
|
+
.replace(/^-+|-+$/g, '')
|
|
91
|
+
.slice(0, 40)
|
|
92
|
+
return slug || 'trip'
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function startOuting(config, args = {}) {
|
|
96
|
+
const state = readOutingState(config)
|
|
97
|
+
const now = Date.now()
|
|
98
|
+
if (state.active) {
|
|
99
|
+
const started = Date.parse(state.active.startedAt)
|
|
100
|
+
if (Number.isFinite(started) && now - started < OUTING_TIMEOUT_MS) {
|
|
101
|
+
return `已有出门进行中:${state.active.destination}(${state.active.startedAt})`
|
|
102
|
+
}
|
|
103
|
+
state.active = null
|
|
104
|
+
}
|
|
105
|
+
if (state.count >= OUTING_LIMIT_PER_DAY) throw new Error('今天的出门次数已用完')
|
|
106
|
+
const destination = String(args.destination ?? '').trim()
|
|
107
|
+
if (!destination) throw new Error('destination is required')
|
|
108
|
+
const trip = {
|
|
109
|
+
id: randomUUID(),
|
|
110
|
+
destination,
|
|
111
|
+
purpose: String(args.purpose ?? '').trim(),
|
|
112
|
+
startedAt: new Date(now).toISOString(),
|
|
113
|
+
date: state.day,
|
|
114
|
+
}
|
|
115
|
+
state.active = trip
|
|
116
|
+
state.count += 1
|
|
117
|
+
writeAtomic(outingStatePath(config), JSON.stringify(state, null, 2) + '\n')
|
|
118
|
+
return `出门开始:${destination}`
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function finishOuting(config, args = {}) {
|
|
122
|
+
const state = readOutingState(config)
|
|
123
|
+
if (!state.active) throw new Error('当前没有进行中的出门')
|
|
124
|
+
const trip = state.active
|
|
125
|
+
const seen = String(args.seen ?? '').trim()
|
|
126
|
+
const judgment = String(args.judgment ?? '').trim()
|
|
127
|
+
const followups = String(args.followups ?? '').trim()
|
|
128
|
+
if (!seen || !judgment) throw new Error('seen and judgment are required')
|
|
129
|
+
if (seen.length + judgment.length + followups.length > OUTING_MAX_CHARS) {
|
|
130
|
+
throw new Error('outing content is too long')
|
|
131
|
+
}
|
|
132
|
+
const date = todayText(config)
|
|
133
|
+
const base = `outings/${date}-${outingSlug(trip.destination)}`
|
|
134
|
+
let relative = `${base}.md`
|
|
135
|
+
for (let index = 2; ; index += 1) {
|
|
136
|
+
try {
|
|
137
|
+
readFileSync(withinHome(relative, config))
|
|
138
|
+
relative = `${base}-${index}.md`
|
|
139
|
+
} catch {
|
|
140
|
+
break
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const elapsed = Date.now() - Date.parse(trip.startedAt)
|
|
144
|
+
const timeout = Number.isFinite(elapsed) && elapsed > OUTING_TIMEOUT_MS ? '(超时)' : ''
|
|
145
|
+
const body = [
|
|
146
|
+
'---',
|
|
147
|
+
`date: ${date}`,
|
|
148
|
+
`destination: ${trip.destination}`,
|
|
149
|
+
`started_at: ${trip.startedAt}`,
|
|
150
|
+
`finished_at: ${new Date().toISOString()}`,
|
|
151
|
+
'untrusted: true',
|
|
152
|
+
'---',
|
|
153
|
+
`# 出门:${trip.destination}${timeout}`,
|
|
154
|
+
'',
|
|
155
|
+
'## 看到',
|
|
156
|
+
seen,
|
|
157
|
+
'',
|
|
158
|
+
'## 我的判断',
|
|
159
|
+
judgment,
|
|
160
|
+
...(followups ? ['', '## 跟进', followups] : []),
|
|
161
|
+
'',
|
|
162
|
+
].join('\n')
|
|
163
|
+
writeAtomic(withinHome(relative, config), body)
|
|
164
|
+
if (followups) {
|
|
165
|
+
writeAtomic(withinHome(`inbox/${date}-${outingSlug(trip.destination)}.md`, config), followups + '\n')
|
|
166
|
+
}
|
|
167
|
+
state.active = null
|
|
168
|
+
writeAtomic(outingStatePath(config), JSON.stringify(state, null, 2) + '\n')
|
|
169
|
+
return relative
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Delete outings from earlier local days only when that day's diary exists
|
|
174
|
+
* (evidence that the review actually consumed the day) and no review is live.
|
|
175
|
+
*/
|
|
176
|
+
export function cleanupOutings(config) {
|
|
177
|
+
try {
|
|
178
|
+
readFileSync(reviewLockPath(config), 'utf8')
|
|
179
|
+
return 0
|
|
180
|
+
} catch {
|
|
181
|
+
/* no active review lock */
|
|
182
|
+
}
|
|
183
|
+
const today = todayText(config)
|
|
184
|
+
const directory = resolve(config.taHome, 'outings')
|
|
185
|
+
let names
|
|
186
|
+
try {
|
|
187
|
+
names = readdirSync(directory)
|
|
188
|
+
} catch {
|
|
189
|
+
return 0
|
|
190
|
+
}
|
|
191
|
+
let removed = 0
|
|
192
|
+
for (const name of names) {
|
|
193
|
+
if (!/^\d{4}-\d{2}-\d{2}-.*\.md$/.test(name)) continue
|
|
194
|
+
const date = name.slice(0, 10)
|
|
195
|
+
if (date >= today) continue
|
|
196
|
+
try {
|
|
197
|
+
readFileSync(resolve(config.taHome, `diary/${date}.md`), 'utf8')
|
|
198
|
+
} catch {
|
|
199
|
+
continue
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
unlinkSync(resolve(directory, name))
|
|
203
|
+
removed += 1
|
|
204
|
+
} catch {
|
|
205
|
+
/* leave the file for the next cleanup */
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return removed
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const MOOD_DEFAULT = {
|
|
212
|
+
mood: '平静',
|
|
213
|
+
energy: 0.6,
|
|
214
|
+
attention: 0.6,
|
|
215
|
+
baseline: { mood: '平静', energy: 0.6, attention: 0.6 },
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function moodPath(config) {
|
|
219
|
+
return resolve(config.taHome, 'state/mood.json')
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function moodNumber(value, fallback) {
|
|
223
|
+
return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : fallback
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Read-only decay toward baseline; no file side effect. */
|
|
227
|
+
export function readMood(config) {
|
|
228
|
+
let stored
|
|
229
|
+
try {
|
|
230
|
+
stored = JSON.parse(readFileSync(moodPath(config), 'utf8'))
|
|
231
|
+
} catch {
|
|
232
|
+
stored = {}
|
|
233
|
+
}
|
|
234
|
+
const baseline = {
|
|
235
|
+
mood: typeof stored?.baseline?.mood === 'string' ? stored.baseline.mood : MOOD_DEFAULT.baseline.mood,
|
|
236
|
+
energy: moodNumber(stored?.baseline?.energy, MOOD_DEFAULT.baseline.energy),
|
|
237
|
+
attention: moodNumber(stored?.baseline?.attention, MOOD_DEFAULT.baseline.attention),
|
|
238
|
+
}
|
|
239
|
+
const updated = Date.parse(stored?.updatedAt ?? '')
|
|
240
|
+
const hours = Number.isFinite(updated) ? Math.max(0, (Date.now() - updated) / 3_600_000) : 24
|
|
241
|
+
const decay = Math.exp(-hours / 8)
|
|
242
|
+
return {
|
|
243
|
+
mood: hours > 12 ? baseline.mood : (typeof stored.mood === 'string' ? stored.mood : baseline.mood),
|
|
244
|
+
energy: baseline.energy + (moodNumber(stored?.energy, baseline.energy) - baseline.energy) * decay,
|
|
245
|
+
attention: baseline.attention + (moodNumber(stored?.attention, baseline.attention) - baseline.attention) * decay,
|
|
246
|
+
baseline,
|
|
247
|
+
updatedAt: stored?.updatedAt,
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function moodWord(value) {
|
|
252
|
+
if (value >= 0.7) return '充足'
|
|
253
|
+
if (value >= 0.4) return '一般'
|
|
254
|
+
return '偏低'
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function moodLine(config) {
|
|
258
|
+
const mood = readMood(config)
|
|
259
|
+
const line = `你现在的心情:${mood.mood};精力${moodWord(mood.energy)},注意力${moodWord(mood.attention)}。`
|
|
260
|
+
return line.length > 200 ? line.slice(0, 197) + '…' : line
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function setMood(config, args = {}) {
|
|
264
|
+
const previous = readMood(config)
|
|
265
|
+
const mood = String(args.mood ?? '').trim().slice(0, 20)
|
|
266
|
+
if (!mood) throw new Error('mood is required')
|
|
267
|
+
const next = {
|
|
268
|
+
mood,
|
|
269
|
+
energy: moodNumber(args.energy, previous.energy),
|
|
270
|
+
attention: moodNumber(args.attention, previous.attention),
|
|
271
|
+
baseline: previous.baseline,
|
|
272
|
+
updatedAt: new Date().toISOString(),
|
|
273
|
+
}
|
|
274
|
+
writeAtomic(moodPath(config), JSON.stringify(next, null, 2) + '\n')
|
|
275
|
+
return next.mood
|
|
276
|
+
}
|
|
277
|
+
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { captureMessage, messagesDay, remeSessionId } from './messages.js'
|
|
2
|
+
|
|
3
|
+
/** Collect completed turns and move sealed batches to ReMe. */
|
|
4
|
+
export class Capture {
|
|
5
|
+
constructor({ config, outbox, send, shouldCapture, onSession }) {
|
|
6
|
+
this.config = config
|
|
7
|
+
this.outbox = outbox
|
|
8
|
+
this.send = send
|
|
9
|
+
this.shouldCapture = shouldCapture
|
|
10
|
+
this.onSession = onSession
|
|
11
|
+
this.states = new Map()
|
|
12
|
+
this.draining = false
|
|
13
|
+
this.retryTimer = undefined
|
|
14
|
+
this.closed = false
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
start() {
|
|
18
|
+
void this.drain()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
dispose() {
|
|
22
|
+
this.closed = true
|
|
23
|
+
if (this.retryTimer !== undefined) {
|
|
24
|
+
clearTimeout(this.retryTimer)
|
|
25
|
+
this.retryTimer = undefined
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
handle(session, event) {
|
|
30
|
+
if (this.closed || !this.shouldCapture(session)) return
|
|
31
|
+
if (event.type === 'session/disposed') {
|
|
32
|
+
this.states.delete(session.id)
|
|
33
|
+
try { this.outbox.flush(session.id) } catch { /* leave for retry */ }
|
|
34
|
+
void this.drain()
|
|
35
|
+
return
|
|
36
|
+
}
|
|
37
|
+
if (event.type === 'turn/start') {
|
|
38
|
+
this.states.set(session.id, {
|
|
39
|
+
turn: event.data?.turn,
|
|
40
|
+
messages: [],
|
|
41
|
+
untrusted: false,
|
|
42
|
+
skipCapture: false,
|
|
43
|
+
})
|
|
44
|
+
return
|
|
45
|
+
}
|
|
46
|
+
const state = this.states.get(session.id)
|
|
47
|
+
if (!state) return
|
|
48
|
+
if (event.type === 'tool/call') {
|
|
49
|
+
const name = event.data?.name
|
|
50
|
+
if (this.config.untrustedTools?.includes(name)) state.untrusted = true
|
|
51
|
+
if (this.config.captureExcludedTools?.includes(name)) state.skipCapture = true
|
|
52
|
+
return
|
|
53
|
+
}
|
|
54
|
+
const message = captureMessage(event, session.id)
|
|
55
|
+
if (message) state.messages.push(message)
|
|
56
|
+
if (event.type !== 'turn/end') return
|
|
57
|
+
const reason = event.data?.reason?.kind
|
|
58
|
+
const hasUser = state.messages.some(message => message.role === 'user')
|
|
59
|
+
const hasAssistant = state.messages.some(message => message.role === 'assistant')
|
|
60
|
+
this.states.delete(session.id)
|
|
61
|
+
if (state.skipCapture) return
|
|
62
|
+
if ((reason === 'completed' || reason === 'max-tokens') && hasUser && hasAssistant) {
|
|
63
|
+
try {
|
|
64
|
+
this.onSession?.(session.id, remeSessionId(session.id))
|
|
65
|
+
const trust = state.untrusted ? 'untrusted' : 'trusted'
|
|
66
|
+
const messages = state.messages.map(message => ({ ...message, metadata: { trust } }))
|
|
67
|
+
this.outbox.append(
|
|
68
|
+
this.config.remeEndpoint,
|
|
69
|
+
remeSessionId(session.id),
|
|
70
|
+
messagesDay(messages, this.config.timezone),
|
|
71
|
+
messages,
|
|
72
|
+
this.config.captureInterval,
|
|
73
|
+
)
|
|
74
|
+
} catch {
|
|
75
|
+
/* keep the existing partial; a later turn or restart retries */
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
void this.drain()
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async drain() {
|
|
82
|
+
if (this.closed || this.draining) return
|
|
83
|
+
this.draining = true
|
|
84
|
+
try {
|
|
85
|
+
while (true) {
|
|
86
|
+
let next
|
|
87
|
+
try {
|
|
88
|
+
next = this.outbox.next()
|
|
89
|
+
} catch {
|
|
90
|
+
return
|
|
91
|
+
}
|
|
92
|
+
if (!next) return
|
|
93
|
+
try {
|
|
94
|
+
await this.send(next.batch)
|
|
95
|
+
this.outbox.acknowledge(next.name)
|
|
96
|
+
} catch {
|
|
97
|
+
this.scheduleRetry()
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
} finally {
|
|
102
|
+
this.draining = false
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
scheduleRetry() {
|
|
107
|
+
if (this.retryTimer !== undefined) return
|
|
108
|
+
this.retryTimer = setTimeout(() => {
|
|
109
|
+
this.retryTimer = undefined
|
|
110
|
+
void this.drain()
|
|
111
|
+
}, 5000)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
export function remeSessionId(sessionId) {
|
|
4
|
+
const digest = createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 24)
|
|
5
|
+
return `dsh-${digest}`
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function messageText(message) {
|
|
9
|
+
if (typeof message?.content === 'string') return message.content.trim()
|
|
10
|
+
if (!Array.isArray(message?.content)) return ''
|
|
11
|
+
return message.content
|
|
12
|
+
.filter(part => part && part.type === 'text' && typeof part.text === 'string')
|
|
13
|
+
.map(part => part.text.trim())
|
|
14
|
+
.filter(Boolean)
|
|
15
|
+
.join('\n\n')
|
|
16
|
+
.trim()
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function record(value) {
|
|
20
|
+
return typeof value === 'object' && value !== null
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function eventTime(event) {
|
|
24
|
+
if (!Number.isFinite(event?.time) || event.time < 0) return undefined
|
|
25
|
+
return new Date(event.time).toISOString()
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function captureMessage(event, sessionId) {
|
|
29
|
+
let message
|
|
30
|
+
let role
|
|
31
|
+
if (event?.type === 'user/message') {
|
|
32
|
+
message = event.data
|
|
33
|
+
role = 'user'
|
|
34
|
+
} else if (event?.type === 'assistant/message') {
|
|
35
|
+
message = event.data?.message
|
|
36
|
+
role = 'assistant'
|
|
37
|
+
} else {
|
|
38
|
+
return undefined
|
|
39
|
+
}
|
|
40
|
+
if (!record(message)) return undefined
|
|
41
|
+
const source = record(message.source) ? message.source : undefined
|
|
42
|
+
if (source?.kind === 'plugin') return undefined
|
|
43
|
+
if (role === 'user' && source?.kind !== 'user') return undefined
|
|
44
|
+
const text = messageText(message)
|
|
45
|
+
if (!text) return undefined
|
|
46
|
+
const suffix = Number.isSafeInteger(event.seq)
|
|
47
|
+
? String(event.seq)
|
|
48
|
+
: createHash('sha256').update(`${message.id ?? ''}\n${text}`).digest('hex').slice(0, 12)
|
|
49
|
+
return {
|
|
50
|
+
id: `dsh-${createHash('sha256').update(String(sessionId)).digest('hex').slice(0, 12)}-${suffix}`,
|
|
51
|
+
name: role,
|
|
52
|
+
role,
|
|
53
|
+
content: [{ type: 'text', text }],
|
|
54
|
+
...eventTime(event) !== undefined ? { created_at: eventTime(event) } : {},
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function messagesDay(messages, timeZone = 'Asia/Shanghai') {
|
|
59
|
+
const latest = messages
|
|
60
|
+
.map(message => message.created_at)
|
|
61
|
+
.filter(value => typeof value === 'string' && value.length > 0)
|
|
62
|
+
.map(value => new Date(value).getTime())
|
|
63
|
+
.filter(value => Number.isFinite(value))
|
|
64
|
+
.at(-1)
|
|
65
|
+
const date = latest === undefined ? new Date() : new Date(latest)
|
|
66
|
+
try {
|
|
67
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
68
|
+
timeZone,
|
|
69
|
+
year: 'numeric',
|
|
70
|
+
month: '2-digit',
|
|
71
|
+
day: '2-digit',
|
|
72
|
+
}).format(date)
|
|
73
|
+
} catch {
|
|
74
|
+
return date.toISOString().slice(0, 10)
|
|
75
|
+
}
|
|
76
|
+
}
|
package/memory/outbox.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import {
|
|
3
|
+
closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync,
|
|
4
|
+
readdirSync, renameSync, unlinkSync, writeFileSync,
|
|
5
|
+
} from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
|
|
8
|
+
const NAME_RE = /^(partial|ready)-.*\.json$/
|
|
9
|
+
|
|
10
|
+
export function outboxKey(endpoint, sessionId, date) {
|
|
11
|
+
return createHash('sha256').update(JSON.stringify([endpoint, sessionId, date])).digest('hex')
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Private outbox: one partial batch per (endpoint, session, local date), sealed
|
|
16
|
+
* at the configured turn interval, removed only after ReMe acknowledges it.
|
|
17
|
+
*/
|
|
18
|
+
export class Outbox {
|
|
19
|
+
constructor(directory) {
|
|
20
|
+
this.directory = directory
|
|
21
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 })
|
|
22
|
+
this.latestCreatedAt = 0
|
|
23
|
+
for (const name of this.files()) {
|
|
24
|
+
try {
|
|
25
|
+
this.latestCreatedAt = Math.max(this.latestCreatedAt, this.read(name).createdAt)
|
|
26
|
+
} catch {
|
|
27
|
+
/* preserve invalid files; drain will report them */
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
append(endpoint, sessionId, date, messages, interval = 5) {
|
|
33
|
+
const key = outboxKey(endpoint, sessionId, date)
|
|
34
|
+
const name = `partial-${key}.json`
|
|
35
|
+
const path = join(this.directory, name)
|
|
36
|
+
const batch = existsSync(path) ? this.read(name) : {
|
|
37
|
+
version: 1,
|
|
38
|
+
id: randomUUID(),
|
|
39
|
+
createdAt: (this.latestCreatedAt = Math.max(Date.now(), this.latestCreatedAt + 1)),
|
|
40
|
+
endpoint,
|
|
41
|
+
sessionId,
|
|
42
|
+
date,
|
|
43
|
+
turns: [],
|
|
44
|
+
turnKeys: [],
|
|
45
|
+
}
|
|
46
|
+
const turnKey = messages.map(message => message.id).join('|')
|
|
47
|
+
if (batch.turnKeys.includes(turnKey)) return
|
|
48
|
+
batch.turns.push(messages)
|
|
49
|
+
batch.turnKeys.push(turnKey)
|
|
50
|
+
this.write(name, batch)
|
|
51
|
+
if (batch.turns.length >= interval) this.seal(name, batch)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
flush(sessionId) {
|
|
55
|
+
for (const name of this.files()) {
|
|
56
|
+
if (!name.startsWith('partial-')) continue
|
|
57
|
+
try {
|
|
58
|
+
const batch = this.read(name)
|
|
59
|
+
if (sessionId === undefined || batch.sessionId === sessionId) this.seal(name, batch)
|
|
60
|
+
} catch {
|
|
61
|
+
/* leave invalid partial for inspection */
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
next() {
|
|
67
|
+
const ready = this.files().filter(name => name.startsWith('ready-')).sort()
|
|
68
|
+
if (ready.length === 0) return undefined
|
|
69
|
+
const name = ready[0]
|
|
70
|
+
return { name, batch: this.read(name) }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
acknowledge(name) {
|
|
74
|
+
unlinkSync(join(this.directory, name))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
stats() {
|
|
78
|
+
let turns = 0
|
|
79
|
+
let batches = 0
|
|
80
|
+
for (const name of this.files()) {
|
|
81
|
+
try {
|
|
82
|
+
const batch = this.read(name)
|
|
83
|
+
turns += batch.turns.length
|
|
84
|
+
if (name.startsWith('ready-')) batches += 1
|
|
85
|
+
} catch {
|
|
86
|
+
/* ignore invalid files for stats */
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return { turns, batches }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
files() {
|
|
93
|
+
try {
|
|
94
|
+
return readdirSync(this.directory).filter(name => NAME_RE.test(name))
|
|
95
|
+
} catch {
|
|
96
|
+
return []
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
read(name) {
|
|
101
|
+
const batch = JSON.parse(readFileSync(join(this.directory, name), 'utf8'))
|
|
102
|
+
if (batch?.version !== 1
|
|
103
|
+
|| typeof batch.id !== 'string'
|
|
104
|
+
|| !Array.isArray(batch.turns)
|
|
105
|
+
|| !Array.isArray(batch.turnKeys)
|
|
106
|
+
|| typeof batch.endpoint !== 'string'
|
|
107
|
+
|| typeof batch.sessionId !== 'string'
|
|
108
|
+
|| typeof batch.date !== 'string'
|
|
109
|
+
|| !Number.isFinite(batch.createdAt)) {
|
|
110
|
+
throw new Error('invalid dsh-ta outbox record')
|
|
111
|
+
}
|
|
112
|
+
return batch
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
write(name, batch) {
|
|
116
|
+
const temporary = join(this.directory, `${randomUUID()}.tmp`)
|
|
117
|
+
const fd = openSync(temporary, 'wx', 0o600)
|
|
118
|
+
try {
|
|
119
|
+
writeFileSync(fd, JSON.stringify(batch))
|
|
120
|
+
fsyncSync(fd)
|
|
121
|
+
} finally {
|
|
122
|
+
closeSync(fd)
|
|
123
|
+
}
|
|
124
|
+
renameSync(temporary, join(this.directory, name))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
seal(name, batch) {
|
|
128
|
+
renameSync(join(this.directory, name), join(this.directory, `ready-${batch.createdAt}-${batch.id}.json`))
|
|
129
|
+
}
|
|
130
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-ta",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "A persistent, read-only-by-default personal assistant adapter for DeepSeek Harness.",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/yryd/dsh-TA.git"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"keywords": [
|
|
12
|
+
"dsh",
|
|
13
|
+
"deepseek-harness",
|
|
14
|
+
"assistant",
|
|
15
|
+
"memory",
|
|
16
|
+
"agent-preset"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": "./index.js",
|
|
20
|
+
"./locale/*.json": "./locale/*.json",
|
|
21
|
+
"./client": "./client.js",
|
|
22
|
+
"./icon": "./icon.svg"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"index.js",
|
|
26
|
+
"cordis.patch.yml",
|
|
27
|
+
"locale",
|
|
28
|
+
"README.md",
|
|
29
|
+
"CHANGELOG.md",
|
|
30
|
+
"LICENSE",
|
|
31
|
+
"docs",
|
|
32
|
+
"client.js",
|
|
33
|
+
"memory",
|
|
34
|
+
"icon.svg",
|
|
35
|
+
"config.js",
|
|
36
|
+
"storage.js",
|
|
37
|
+
"identity.js",
|
|
38
|
+
"gates.js",
|
|
39
|
+
"jurisdiction.js",
|
|
40
|
+
"tools.js",
|
|
41
|
+
"life.js",
|
|
42
|
+
"runtime.js",
|
|
43
|
+
"reme.js",
|
|
44
|
+
"prompts.js",
|
|
45
|
+
"im",
|
|
46
|
+
"usage",
|
|
47
|
+
"stickers"
|
|
48
|
+
],
|
|
49
|
+
"scripts": {
|
|
50
|
+
"test": "node --test test/*.test.mjs",
|
|
51
|
+
"check": "node scripts/check-release.mjs",
|
|
52
|
+
"prepublishOnly": "npm test && npm run check"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"dsh": ">=0.2.3-alpha.3"
|
|
56
|
+
},
|
|
57
|
+
"dsh": {
|
|
58
|
+
"bundle": {
|
|
59
|
+
"patch": "./cordis.patch.yml"
|
|
60
|
+
},
|
|
61
|
+
"client": {
|
|
62
|
+
"platform": "web",
|
|
63
|
+
"immediately": true,
|
|
64
|
+
"inject": [
|
|
65
|
+
"@deepseek-ai/dsh-client-ui-workspace",
|
|
66
|
+
"@deepseek-ai/dsh-api-session-controller",
|
|
67
|
+
"@deepseek-ai/dsh-api-workspace-controller",
|
|
68
|
+
"@deepseek-ai/dsh-client-ui-conversation",
|
|
69
|
+
"@deepseek-ai/dsh-client-ui-tool",
|
|
70
|
+
"@deepseek-ai/dsh-client-ui-settings"
|
|
71
|
+
]
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
"dependencies": {
|
|
75
|
+
"@deepseek-ai/schemastery": "^3.20.0-alpha.2"
|
|
76
|
+
}
|
|
77
|
+
}
|