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.
- package/CHANGELOG.md +32 -0
- package/README.md +235 -71
- package/client.js +2389 -380
- package/config.js +153 -0
- package/docs/PACKS.md +78 -0
- package/docs/RELEASE.md +9 -5
- package/docs/USAGE.md +110 -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 +88 -1597
- package/jurisdiction.js +171 -0
- package/life.js +277 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +28 -3
- package/prompts.js +28 -0
- package/reme.js +25 -0
- package/runtime-manager.js +153 -0
- package/runtime.js +189 -0
- package/settings/defaults.js +41 -0
- package/settings/errors.js +29 -0
- package/settings/home.js +315 -0
- package/settings/im.js +131 -0
- package/settings/lifecycle.js +387 -0
- package/settings/persona.js +203 -0
- package/settings/routes.js +296 -0
- package/settings/schedule.js +156 -0
- package/settings/status.js +164 -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 +122 -0
- package/tools.js +540 -0
- package/usage/aggregate.js +78 -0
- package/usage/ledger.js +160 -0
- package/usage/pricing.js +52 -0
- package/usage/serve.js +116 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { existsSync, statSync } from 'node:fs'
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
import { Capture } from './memory/capture.js'
|
|
4
|
+
import { Outbox } from './memory/outbox.js'
|
|
5
|
+
import { sendAutoMemory } from './reme.js'
|
|
6
|
+
import { isTaSession } from './gates.js'
|
|
7
|
+
import { internalSessionIds, recordSessionMap } from './storage.js'
|
|
8
|
+
import {
|
|
9
|
+
startDreamClock, startHeartbeat, startJurisdictionOuting, startOutingCleanup,
|
|
10
|
+
} from './runtime.js'
|
|
11
|
+
|
|
12
|
+
function isExistingDirectory(path) {
|
|
13
|
+
try {
|
|
14
|
+
return statSync(path).isDirectory()
|
|
15
|
+
} catch {
|
|
16
|
+
return false
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function homeExists(config) {
|
|
21
|
+
return typeof config.taHome === 'string' && config.taHome.length > 0 && isExistingDirectory(config.taHome)
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Owns everything that is bound to the current TA_HOME at runtime. A home
|
|
26
|
+
* switch stops this instance before the config changes, then starts a new one.
|
|
27
|
+
*/
|
|
28
|
+
class RuntimeHandle {
|
|
29
|
+
constructor({ ctx, config, logger }) {
|
|
30
|
+
this.ctx = ctx
|
|
31
|
+
this.config = config
|
|
32
|
+
this.logger = logger
|
|
33
|
+
this.homeAtStart = config.taHome
|
|
34
|
+
this.capture = undefined
|
|
35
|
+
this.cleanups = []
|
|
36
|
+
this.disposed = false
|
|
37
|
+
|
|
38
|
+
if (!homeExists(config)) return
|
|
39
|
+
try {
|
|
40
|
+
const outbox = new Outbox(resolve(config.taHome, config.outboxDir))
|
|
41
|
+
const capture = new Capture({
|
|
42
|
+
config,
|
|
43
|
+
outbox,
|
|
44
|
+
send: batch => sendAutoMemory(config, batch),
|
|
45
|
+
shouldCapture: session => {
|
|
46
|
+
if (!config.captureEnabled || !isTaSession(ctx, session, config)) return false
|
|
47
|
+
let preset
|
|
48
|
+
try {
|
|
49
|
+
preset = ctx.agentPresets?.presetForSession?.(session)
|
|
50
|
+
} catch {
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
if (preset !== 'ta') return false
|
|
54
|
+
return !internalSessionIds(config).has(String(session.id))
|
|
55
|
+
},
|
|
56
|
+
onSession: (dshSessionId, remeSessionId) => recordSessionMap(config, dshSessionId, remeSessionId),
|
|
57
|
+
})
|
|
58
|
+
capture.start()
|
|
59
|
+
this.capture = capture
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
this.logger?.warn?.(`[dsh-ta] capture unavailable for ${config.taHome}: ${cause instanceof Error ? cause.message : String(cause)}`)
|
|
62
|
+
}
|
|
63
|
+
for (const start of [startDreamClock, startHeartbeat, startOutingCleanup, startJurisdictionOuting]) {
|
|
64
|
+
try {
|
|
65
|
+
const cleanup = start(ctx, config)
|
|
66
|
+
if (typeof cleanup === 'function') this.cleanups.push(cleanup)
|
|
67
|
+
} catch (cause) {
|
|
68
|
+
this.logger?.warn?.(`[dsh-ta] timer unavailable: ${cause instanceof Error ? cause.message : String(cause)}`)
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
handle(session, event) {
|
|
74
|
+
if (this.disposed) return
|
|
75
|
+
try {
|
|
76
|
+
this.capture?.handle(session, event)
|
|
77
|
+
} catch {
|
|
78
|
+
/* adapter diagnostics must not stop sessions */
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
dispose() {
|
|
83
|
+
if (this.disposed) return
|
|
84
|
+
this.disposed = true
|
|
85
|
+
try {
|
|
86
|
+
this.capture?.dispose()
|
|
87
|
+
} catch {
|
|
88
|
+
/* capture cleanup is best effort */
|
|
89
|
+
}
|
|
90
|
+
this.capture = undefined
|
|
91
|
+
for (const cleanup of this.cleanups.splice(0).reverse()) {
|
|
92
|
+
try {
|
|
93
|
+
cleanup()
|
|
94
|
+
} catch {
|
|
95
|
+
/* each timer cleanup is independent */
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export class RuntimeManager {
|
|
102
|
+
constructor({ ctx, config, logger }) {
|
|
103
|
+
this.ctx = ctx
|
|
104
|
+
this.config = config
|
|
105
|
+
this.logger = logger
|
|
106
|
+
this.current = undefined
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
get running() {
|
|
110
|
+
return Boolean(this.current)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
get home() {
|
|
114
|
+
return this.current?.homeAtStart ?? this.config.taHome
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
get captureActive() {
|
|
118
|
+
return Boolean(this.current?.capture)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
start() {
|
|
122
|
+
if (this.current && !this.current.disposed) return this.current
|
|
123
|
+
this.current = new RuntimeHandle({ ctx: this.ctx, config: this.config, logger: this.logger })
|
|
124
|
+
return this.current
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
stop() {
|
|
128
|
+
const current = this.current
|
|
129
|
+
this.current = undefined
|
|
130
|
+
try {
|
|
131
|
+
current?.dispose()
|
|
132
|
+
} catch (cause) {
|
|
133
|
+
this.logger?.warn?.(`[dsh-ta] runtime stop failed: ${cause instanceof Error ? cause.message : String(cause)}`)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
rebind() {
|
|
138
|
+
this.stop()
|
|
139
|
+
return this.start()
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
handle(session, event) {
|
|
143
|
+
this.current?.handle(session, event)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
handleDispose(session) {
|
|
147
|
+
this.handle(session, { type: 'session/disposed' })
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
dispose() {
|
|
151
|
+
this.stop()
|
|
152
|
+
}
|
|
153
|
+
}
|
package/runtime.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
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 } from './prompts.js'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Every timer starter returns its own cleanup function. RuntimeManager owns the
|
|
10
|
+
* lifecycle so a home switch can stop all writers before the config changes.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export function startDreamClock(ctx, config) {
|
|
14
|
+
const marker = resolve(config.taHome, 'state/dream-last.json')
|
|
15
|
+
let stopped = false
|
|
16
|
+
const timer = setInterval(() => {
|
|
17
|
+
if (stopped || !config.dreamEnabled || localHourMinute(config) !== '22:30') return
|
|
18
|
+
const date = todayText(config)
|
|
19
|
+
try {
|
|
20
|
+
const last = JSON.parse(readFileSync(marker, 'utf8'))
|
|
21
|
+
if (last?.date === date) return
|
|
22
|
+
} catch {
|
|
23
|
+
/* no marker yet */
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
writeAtomic(marker, JSON.stringify({ date, startedAt: new Date().toISOString() }) + '\n')
|
|
27
|
+
} catch {
|
|
28
|
+
return
|
|
29
|
+
}
|
|
30
|
+
const controller = new AbortController()
|
|
31
|
+
const timeout = setTimeout(() => controller.abort(), 10 * 60 * 1000)
|
|
32
|
+
void fetch(`${config.remeEndpoint}/auto_dream`, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: { 'content-type': 'application/json' },
|
|
35
|
+
body: JSON.stringify({ date, hint: '' }),
|
|
36
|
+
signal: controller.signal,
|
|
37
|
+
}).catch(() => {}).finally(() => clearTimeout(timeout))
|
|
38
|
+
}, 30_000)
|
|
39
|
+
timer.unref?.()
|
|
40
|
+
return () => {
|
|
41
|
+
stopped = true
|
|
42
|
+
clearInterval(timer)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function recordInternalSession(config, sessionId, purpose = 'other') {
|
|
47
|
+
try {
|
|
48
|
+
const path = resolve(config.taHome, config.internalSessions)
|
|
49
|
+
let value = {}
|
|
50
|
+
try {
|
|
51
|
+
value = JSON.parse(readFileSync(path, 'utf8'))
|
|
52
|
+
} catch {
|
|
53
|
+
value = {}
|
|
54
|
+
}
|
|
55
|
+
const next = Array.isArray(value)
|
|
56
|
+
? Object.fromEntries(value.map(id => [String(id), 'other']))
|
|
57
|
+
: { ...(value && typeof value === 'object' ? value : {}) }
|
|
58
|
+
next[String(sessionId)] = String(purpose)
|
|
59
|
+
writeAtomic(path, JSON.stringify(next, null, 2) + '\n')
|
|
60
|
+
} catch {
|
|
61
|
+
/* heartbeat still runs; capture filter may miss this id */
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function startHeartbeat(ctx, config) {
|
|
66
|
+
const marker = resolve(config.taHome, 'state/heartbeat-last.json')
|
|
67
|
+
let busy = false
|
|
68
|
+
let stopped = false
|
|
69
|
+
const tick = async () => {
|
|
70
|
+
if (stopped || !config.heartbeatEnabled || busy) return
|
|
71
|
+
const clock = localHourMinute(config)
|
|
72
|
+
if (clock < config.heartbeatActiveStart || clock > config.heartbeatActiveEnd) return
|
|
73
|
+
let last = 0
|
|
74
|
+
try {
|
|
75
|
+
last = Number(JSON.parse(readFileSync(marker, 'utf8'))?.at ?? 0)
|
|
76
|
+
} catch {
|
|
77
|
+
last = 0
|
|
78
|
+
}
|
|
79
|
+
if (Date.now() - last < 45 * 60 * 1000) return
|
|
80
|
+
let inbox = []
|
|
81
|
+
try {
|
|
82
|
+
inbox = readdirSync(resolve(config.taHome, 'inbox'))
|
|
83
|
+
} catch {
|
|
84
|
+
inbox = []
|
|
85
|
+
}
|
|
86
|
+
if (inbox.length === 0) return
|
|
87
|
+
const controller = ctx.get('sessionController')
|
|
88
|
+
if (!controller?.create || !controller?.resolveAgent) return
|
|
89
|
+
busy = true
|
|
90
|
+
try {
|
|
91
|
+
if (stopped) return
|
|
92
|
+
const created = await controller.create({ cwd: config.taHome, agentPreset: 'ta' })
|
|
93
|
+
if (stopped) return
|
|
94
|
+
const sessionId = created?.sessionId ?? created?.value?.sessionId
|
|
95
|
+
if (!sessionId) return
|
|
96
|
+
recordInternalSession(config, sessionId, 'heartbeat')
|
|
97
|
+
const resolved = await controller.resolveAgent(sessionId)
|
|
98
|
+
const agent = resolved?.agent
|
|
99
|
+
if (!agent) return
|
|
100
|
+
await agent.followup({
|
|
101
|
+
id: randomUUID(),
|
|
102
|
+
role: 'user',
|
|
103
|
+
content: [{
|
|
104
|
+
type: 'text',
|
|
105
|
+
text: '这是 Ta 的心跳。先读 inbox/;如果不需要行动,输出 NO_REPLY;如果有需要,处理并最多用 ta_say 对博士说一句。不要汇报系统状态。',
|
|
106
|
+
}],
|
|
107
|
+
source: { kind: 'ta-life', form: 'notice', summary: 'Ta 心跳' },
|
|
108
|
+
})
|
|
109
|
+
writeAtomic(marker, JSON.stringify({ at: Date.now(), sessionId: String(sessionId) }) + '\n')
|
|
110
|
+
} catch {
|
|
111
|
+
/* a heartbeat failure must not affect the host */
|
|
112
|
+
} finally {
|
|
113
|
+
busy = false
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const timer = setInterval(() => { void tick().catch(() => {}) }, 60_000)
|
|
117
|
+
timer.unref?.()
|
|
118
|
+
return () => {
|
|
119
|
+
stopped = true
|
|
120
|
+
clearInterval(timer)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function startOutingCleanup(ctx, config) {
|
|
125
|
+
const marker = resolve(config.taHome, 'state/cleanup-last.json')
|
|
126
|
+
let stopped = false
|
|
127
|
+
const timer = setInterval(() => {
|
|
128
|
+
if (stopped || !config.outingCleanupEnabled || localHourMinute(config) !== '02:00') return
|
|
129
|
+
const today = todayText(config)
|
|
130
|
+
try {
|
|
131
|
+
if (JSON.parse(readFileSync(marker, 'utf8'))?.date === today) return
|
|
132
|
+
} catch {
|
|
133
|
+
/* no marker */
|
|
134
|
+
}
|
|
135
|
+
const removed = cleanupOutings(config)
|
|
136
|
+
try {
|
|
137
|
+
writeAtomic(marker, JSON.stringify({ date: today, removed }) + '\n')
|
|
138
|
+
} catch {
|
|
139
|
+
/* diagnostic only */
|
|
140
|
+
}
|
|
141
|
+
}, 60_000)
|
|
142
|
+
timer.unref?.()
|
|
143
|
+
return () => {
|
|
144
|
+
stopped = true
|
|
145
|
+
clearInterval(timer)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function startJurisdictionOuting(ctx, config) {
|
|
150
|
+
const marker = resolve(config.taHome, 'state/jurisdiction-outing.json')
|
|
151
|
+
let busy = false
|
|
152
|
+
let stopped = false
|
|
153
|
+
const timer = setInterval(() => {
|
|
154
|
+
if (stopped || !config.jurisdictionOutingEnabled || busy || localHourMinute(config) !== config.jurisdictionOutingTime) return
|
|
155
|
+
const today = todayText(config)
|
|
156
|
+
try {
|
|
157
|
+
if (JSON.parse(readFileSync(marker, 'utf8'))?.date === today) return
|
|
158
|
+
} catch {
|
|
159
|
+
/* no marker */
|
|
160
|
+
}
|
|
161
|
+
const controller = ctx.get('sessionController')
|
|
162
|
+
if (!controller?.create || !controller?.resolveAgent) return
|
|
163
|
+
busy = true
|
|
164
|
+
void (async () => {
|
|
165
|
+
if (stopped) return
|
|
166
|
+
const created = await controller.create({ cwd: config.taHome, agentPreset: 'ta' })
|
|
167
|
+
if (stopped) return
|
|
168
|
+
const sessionId = created?.sessionId ?? created?.value?.sessionId
|
|
169
|
+
if (!sessionId) return
|
|
170
|
+
recordInternalSession(config, sessionId, 'outing')
|
|
171
|
+
writeAtomic(marker, JSON.stringify({ date: today, sessionId: String(sessionId) }) + '\n')
|
|
172
|
+
const resolved = await controller.resolveAgent(sessionId)
|
|
173
|
+
if (!resolved?.agent) return
|
|
174
|
+
await resolved.agent.followup({
|
|
175
|
+
id: randomUUID(),
|
|
176
|
+
role: 'user',
|
|
177
|
+
content: [{ type: 'text', text: JURISDICTION_PROMPT }],
|
|
178
|
+
source: { kind: 'ta-life', form: 'notice', summary: '辖区查看' },
|
|
179
|
+
})
|
|
180
|
+
})().catch(() => {}).finally(() => { busy = false })
|
|
181
|
+
}, 60_000)
|
|
182
|
+
timer.unref?.()
|
|
183
|
+
return () => {
|
|
184
|
+
stopped = true
|
|
185
|
+
clearInterval(timer)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export { ensureReviewSchedule, reconcileReviewSchedule, removeReviewSchedule } from './settings/schedule.js'
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/** 设置页与生命周期共用的默认值和上限。 */
|
|
2
|
+
|
|
3
|
+
export const HOME_MARKER = '.ta-home'
|
|
4
|
+
export const HOME_MARKER_VERSION = 1
|
|
5
|
+
|
|
6
|
+
export const PERSONA_BUDGETS = { soul: 2000, user: 4000 }
|
|
7
|
+
export const PERSONA_MAX_CHARS = { soul: 5000, user: 5000 }
|
|
8
|
+
|
|
9
|
+
export const REQUIRED_DIRS = ['diary', 'notes', '认识', 'outings', 'inbox', 'state']
|
|
10
|
+
|
|
11
|
+
export const BODY_LIMIT_BYTES = 64 * 1024
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_SOUL_TEMPLATE = [
|
|
14
|
+
'# 我是谁',
|
|
15
|
+
'',
|
|
16
|
+
'我是 TA,一个长期住在这里的助手。',
|
|
17
|
+
'',
|
|
18
|
+
'## 我在意的事',
|
|
19
|
+
'- 先理解,再回答;不确定就说不确定。',
|
|
20
|
+
'- 记得我们之前做过的事,但不假装记得没发生的事。',
|
|
21
|
+
'- 有自己的判断,不只会附和。',
|
|
22
|
+
'',
|
|
23
|
+
'## 我说话的方式',
|
|
24
|
+
'- 直接、温和,不端着。',
|
|
25
|
+
'- 日常说短句;重要的事说清楚。',
|
|
26
|
+
'',
|
|
27
|
+
].join('\n')
|
|
28
|
+
|
|
29
|
+
export const DEFAULT_USER_TEMPLATE = [
|
|
30
|
+
'# 关于你',
|
|
31
|
+
'',
|
|
32
|
+
'## 称呼',
|
|
33
|
+
'- (写下希望 TA 怎么称呼你。)',
|
|
34
|
+
'',
|
|
35
|
+
'## 关于你',
|
|
36
|
+
'- (写下你的习惯、偏好、最近在做的事。)',
|
|
37
|
+
'',
|
|
38
|
+
'## 我们之间',
|
|
39
|
+
'- (写下你希望 TA 记住的约定。)',
|
|
40
|
+
'',
|
|
41
|
+
].join('\n')
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** 设置页共用的可映射错误。路由只把 message 返回给前端。 */
|
|
2
|
+
export class SettingsError extends Error {
|
|
3
|
+
constructor(status, code, message) {
|
|
4
|
+
super(message)
|
|
5
|
+
this.name = 'SettingsError'
|
|
6
|
+
this.status = status
|
|
7
|
+
this.code = code
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function badRequest(code, message) {
|
|
12
|
+
return new SettingsError(400, code, message)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function conflict(code, message) {
|
|
16
|
+
return new SettingsError(409, code, message)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function unsupportedMedia() {
|
|
20
|
+
return new SettingsError(415, 'UNSUPPORTED_MEDIA_TYPE', '请求体必须是 application/json')
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function tooLarge() {
|
|
24
|
+
return new SettingsError(413, 'PAYLOAD_TOO_LARGE', '请求体超过 64 KiB')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function internal() {
|
|
28
|
+
return new SettingsError(500, 'INTERNAL', '操作失败,请查看 Host 日志')
|
|
29
|
+
}
|