dsh-ta 0.2.0 → 0.4.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 +111 -1
- package/README.md +325 -140
- package/cordis.patch.yml +5 -35
- package/docs/RELEASE.md +63 -46
- package/docs/USAGE.md +25 -9
- package/docs/presets.example.yml +7 -43
- package/index.js +3 -170
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -19
- package/src/client/client.js +3176 -0
- package/{config.js → src/host/config.js} +39 -4
- package/src/host/constants.js +7 -0
- package/src/host/gates.js +34 -0
- package/src/host/identity.js +145 -0
- package/{im → src/host/im}/bindings.js +1 -1
- package/src/host/index.js +173 -0
- package/{jurisdiction.js → src/host/jurisdiction.js} +1 -1
- package/src/host/maintenance/collect.js +362 -0
- package/src/host/maintenance/completions.js +56 -0
- package/src/host/maintenance/consumption.js +67 -0
- package/src/host/maintenance/cursors.js +53 -0
- package/src/host/maintenance/engine.js +392 -0
- package/src/host/maintenance/llm.js +381 -0
- package/src/host/maintenance/lock.js +105 -0
- package/src/host/maintenance/prompts.js +255 -0
- package/src/host/maintenance/runs.js +47 -0
- package/src/host/maintenance/schedule.js +173 -0
- package/src/host/maintenance/session-cleanup.js +289 -0
- package/src/host/maintenance/session-watcher.js +107 -0
- package/src/host/maintenance/sleep.js +3 -0
- package/src/host/maintenance/stages.js +241 -0
- package/src/host/maintenance/state.js +192 -0
- package/src/host/prompts.js +96 -0
- package/src/host/records.js +175 -0
- package/{reme.js → src/host/reme.js} +3 -1
- package/src/host/runtime-manager.js +281 -0
- package/{runtime.js → src/host/runtime.js} +28 -50
- package/src/host/settings/defaults.js +55 -0
- package/src/host/settings/errors.js +29 -0
- package/src/host/settings/home.js +316 -0
- package/src/host/settings/http.js +164 -0
- package/src/host/settings/im.js +148 -0
- package/src/host/settings/lifecycle.js +373 -0
- package/src/host/settings/persona.js +113 -0
- package/src/host/settings/routes.js +229 -0
- package/src/host/settings/status.js +192 -0
- package/src/host/state/appraisals.js +56 -0
- package/src/host/state/feel.js +78 -0
- package/src/host/state/index.js +9 -0
- package/src/host/state/mood.js +103 -0
- package/src/host/state/notes.js +18 -0
- package/{life.js → src/host/state/outing.js} +13 -136
- package/src/host/state/values.js +9 -0
- package/{stickers → src/host/stickers}/tool.js +1 -1
- package/src/host/storage/fs.js +29 -0
- package/src/host/storage/index.js +8 -0
- package/src/host/storage/paths.js +20 -0
- package/src/host/storage/revision.js +5 -0
- package/src/host/storage/session-state.js +38 -0
- package/src/host/storage/time.js +127 -0
- package/src/host/tools/index.js +152 -0
- package/src/host/tools/read.js +252 -0
- package/src/host/tools/shared.js +23 -0
- package/src/host/tools/wiki.js +35 -0
- package/src/host/tools/write.js +164 -0
- package/{usage → src/host/usage}/aggregate.js +4 -1
- package/src/host/usage/ledger.js +186 -0
- package/src/host/usage/serve.js +116 -0
- package/client.js +0 -618
- package/gates.js +0 -18
- package/identity.js +0 -97
- package/prompts.js +0 -28
- package/storage.js +0 -95
- package/tools.js +0 -540
- package/usage/ledger.js +0 -126
- package/usage/serve.js +0 -38
- /package/{im → src/host/im}/say.js +0 -0
- /package/{memory → src/host/memory}/capture.js +0 -0
- /package/{memory → src/host/memory}/messages.js +0 -0
- /package/{memory → src/host/memory}/outbox.js +0 -0
- /package/{stickers → src/host/stickers}/load.js +0 -0
- /package/{stickers → src/host/stickers}/select.js +0 -0
- /package/{stickers → src/host/stickers}/serve.js +0 -0
- /package/{usage → src/host/usage}/pricing.js +0 -0
|
@@ -1,65 +1,8 @@
|
|
|
1
1
|
import { readFileSync, readdirSync, unlinkSync } from 'node:fs'
|
|
2
|
-
import { resolve } from 'node:path'
|
|
3
2
|
import { randomUUID } from 'node:crypto'
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
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
|
-
}
|
|
3
|
+
import { resolve } from 'node:path'
|
|
4
|
+
import { todayText, withinHome, writeAtomic } from '../storage/index.js'
|
|
5
|
+
import { readMaintenanceLock } from '../maintenance/lock.js'
|
|
63
6
|
|
|
64
7
|
const OUTING_LIMIT_PER_DAY = 4
|
|
65
8
|
const OUTING_TIMEOUT_MS = 20 * 60 * 1000
|
|
@@ -92,6 +35,11 @@ function outingSlug(value) {
|
|
|
92
35
|
return slug || 'trip'
|
|
93
36
|
}
|
|
94
37
|
|
|
38
|
+
/** 当前是否有进行中的出门;供维护 D9 等待/跳过判断。 */
|
|
39
|
+
export function readOutingActive(config) {
|
|
40
|
+
return readOutingState(config).active
|
|
41
|
+
}
|
|
42
|
+
|
|
95
43
|
export function startOuting(config, args = {}) {
|
|
96
44
|
const state = readOutingState(config)
|
|
97
45
|
const now = Date.now()
|
|
@@ -118,7 +66,7 @@ export function startOuting(config, args = {}) {
|
|
|
118
66
|
return `出门开始:${destination}`
|
|
119
67
|
}
|
|
120
68
|
|
|
121
|
-
export function finishOuting(config, args = {}) {
|
|
69
|
+
export function finishOuting(config, args = {}, { sessionId } = {}) {
|
|
122
70
|
const state = readOutingState(config)
|
|
123
71
|
if (!state.active) throw new Error('当前没有进行中的出门')
|
|
124
72
|
const trip = state.active
|
|
@@ -144,10 +92,12 @@ export function finishOuting(config, args = {}) {
|
|
|
144
92
|
const timeout = Number.isFinite(elapsed) && elapsed > OUTING_TIMEOUT_MS ? '(超时)' : ''
|
|
145
93
|
const body = [
|
|
146
94
|
'---',
|
|
95
|
+
`id: ${trip.id}`,
|
|
147
96
|
`date: ${date}`,
|
|
148
97
|
`destination: ${trip.destination}`,
|
|
149
98
|
`started_at: ${trip.startedAt}`,
|
|
150
99
|
`finished_at: ${new Date().toISOString()}`,
|
|
100
|
+
...(sessionId ? [`session_id: ${String(sessionId)}`] : []),
|
|
151
101
|
'untrusted: true',
|
|
152
102
|
'---',
|
|
153
103
|
`# 出门:${trip.destination}${timeout}`,
|
|
@@ -171,15 +121,10 @@ export function finishOuting(config, args = {}) {
|
|
|
171
121
|
|
|
172
122
|
/**
|
|
173
123
|
* Delete outings from earlier local days only when that day's diary exists
|
|
174
|
-
* (evidence that
|
|
124
|
+
* (evidence that maintenance consumed the day) and no maintenance run is live.
|
|
175
125
|
*/
|
|
176
126
|
export function cleanupOutings(config) {
|
|
177
|
-
|
|
178
|
-
readFileSync(reviewLockPath(config), 'utf8')
|
|
179
|
-
return 0
|
|
180
|
-
} catch {
|
|
181
|
-
/* no active review lock */
|
|
182
|
-
}
|
|
127
|
+
if (readMaintenanceLock(config)) return 0
|
|
183
128
|
const today = todayText(config)
|
|
184
129
|
const directory = resolve(config.taHome, 'outings')
|
|
185
130
|
let names
|
|
@@ -207,71 +152,3 @@ export function cleanupOutings(config) {
|
|
|
207
152
|
}
|
|
208
153
|
return removed
|
|
209
154
|
}
|
|
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
|
-
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export function clamp01(value, fallback = 0) {
|
|
2
|
+
const number = Number(value)
|
|
3
|
+
return Number.isFinite(number) ? Math.max(0, Math.min(1, number)) : fallback
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export function clampSigned(value, fallback = 0) {
|
|
7
|
+
const number = Number(value)
|
|
8
|
+
return Number.isFinite(number) ? Math.max(-1, Math.min(1, number)) : fallback
|
|
9
|
+
}
|
|
@@ -3,7 +3,7 @@ import { extname, resolve } from 'node:path'
|
|
|
3
3
|
import { randomUUID } from 'node:crypto'
|
|
4
4
|
import { activePack, readStickerState, resolveStickerFile, stickerStatePath } from './load.js'
|
|
5
5
|
import { selectSticker, stickerEmotions } from './select.js'
|
|
6
|
-
import { todayText, writeAtomic } from '../storage.js'
|
|
6
|
+
import { todayText, writeAtomic } from '../storage/index.js'
|
|
7
7
|
|
|
8
8
|
const DEFAULT_MAX_PER_DAY = 12
|
|
9
9
|
const DEFAULT_MIN_GAP_MINUTES = 30
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { accessSync, constants, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/** 原子写:临时文件 + rename,失败不破坏原文件。 */
|
|
5
|
+
export function writeAtomic(path, text) {
|
|
6
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
7
|
+
const temporary = `${path}.tmp-${process.pid}-${Date.now()}`
|
|
8
|
+
writeFileSync(temporary, text)
|
|
9
|
+
renameSync(temporary, path)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function readTextIfExists(path) {
|
|
13
|
+
try {
|
|
14
|
+
if (!statSync(path).isFile()) return undefined
|
|
15
|
+
return readFileSync(path, 'utf8')
|
|
16
|
+
} catch {
|
|
17
|
+
return undefined
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function isWritableDirectory(path) {
|
|
22
|
+
try {
|
|
23
|
+
if (!statSync(path).isDirectory()) return false
|
|
24
|
+
accessSync(path, constants.W_OK)
|
|
25
|
+
return true
|
|
26
|
+
} catch {
|
|
27
|
+
return false
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { realPath, withinHome } from './paths.js'
|
|
2
|
+
export { writeAtomic, readTextIfExists, isWritableDirectory } from './fs.js'
|
|
3
|
+
export { sha256Revision } from './revision.js'
|
|
4
|
+
export { recordSessionMap, readInternalSessions, internalSessionIds } from './session-state.js'
|
|
5
|
+
export {
|
|
6
|
+
todayText, zonedMidnightUtc, localDateText, localClockText, zonedIso, startOfLocalDay,
|
|
7
|
+
addLocalDays, localWeekday,
|
|
8
|
+
} from './time.js'
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs'
|
|
2
|
+
import { resolve, sep } from 'node:path'
|
|
3
|
+
|
|
4
|
+
export function realPath(value) {
|
|
5
|
+
if (typeof value !== 'string' || value.length === 0) return ''
|
|
6
|
+
try {
|
|
7
|
+
return realpathSync.native(value)
|
|
8
|
+
} catch {
|
|
9
|
+
return resolve(value)
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Resolve a path inside TA_HOME; throw when it escapes (symlinks included). */
|
|
14
|
+
export function withinHome(relative, config) {
|
|
15
|
+
if (typeof relative !== 'string' || relative.length === 0) throw new Error('path is required')
|
|
16
|
+
const base = realPath(config.taHome)
|
|
17
|
+
const target = realPath(resolve(base, relative))
|
|
18
|
+
if (target !== base && !target.startsWith(base + sep)) throw new Error('path is outside TA_HOME')
|
|
19
|
+
return target
|
|
20
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { resolve } from 'node:path'
|
|
3
|
+
|
|
4
|
+
/** ReMe 会话 id → DSH 会话 id;只作诊断映射,不阻塞 capture。 */
|
|
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
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
const VALID_TIME_ZONES = new Map()
|
|
2
|
+
const DEFAULT_TIME_ZONE = 'Asia/Shanghai'
|
|
3
|
+
|
|
4
|
+
function timeZoneOf(config) {
|
|
5
|
+
const value = typeof config?.timezone === 'string' && config.timezone ? config.timezone : DEFAULT_TIME_ZONE
|
|
6
|
+
const cached = VALID_TIME_ZONES.get(value)
|
|
7
|
+
if (cached) return cached
|
|
8
|
+
try {
|
|
9
|
+
new Intl.DateTimeFormat('en-CA', { timeZone: value }).format(new Date(0))
|
|
10
|
+
VALID_TIME_ZONES.set(value, value)
|
|
11
|
+
return value
|
|
12
|
+
} catch {
|
|
13
|
+
VALID_TIME_ZONES.set(value, DEFAULT_TIME_ZONE)
|
|
14
|
+
return DEFAULT_TIME_ZONE
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function dateParts(dateText) {
|
|
19
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dateText ?? ''))
|
|
20
|
+
if (!match) throw new Error(`date must be YYYY-MM-DD: ${dateText}`)
|
|
21
|
+
return { year: Number(match[1]), month: Number(match[2]), day: Number(match[3]) }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function zonedParts(ms, timeZone) {
|
|
25
|
+
const parts = new Intl.DateTimeFormat('en-CA', {
|
|
26
|
+
timeZone,
|
|
27
|
+
year: 'numeric',
|
|
28
|
+
month: '2-digit',
|
|
29
|
+
day: '2-digit',
|
|
30
|
+
hour: '2-digit',
|
|
31
|
+
minute: '2-digit',
|
|
32
|
+
second: '2-digit',
|
|
33
|
+
hourCycle: 'h23',
|
|
34
|
+
}).formatToParts(new Date(ms))
|
|
35
|
+
const pick = type => Number(parts.find(part => part.type === type)?.value ?? 0)
|
|
36
|
+
return {
|
|
37
|
+
year: pick('year'),
|
|
38
|
+
month: pick('month'),
|
|
39
|
+
day: pick('day'),
|
|
40
|
+
hour: pick('hour'),
|
|
41
|
+
minute: pick('minute'),
|
|
42
|
+
second: pick('second'),
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* UTC epoch milliseconds of local midnight for `dateText` in `timeZone`.
|
|
48
|
+
* Guessing UTC midnight and correcting by the zone wall clock converges for
|
|
49
|
+
* every IANA zone, including DST transitions.
|
|
50
|
+
*/
|
|
51
|
+
export function zonedMidnightUtc(dateText, timeZone) {
|
|
52
|
+
const { year, month, day } = dateParts(dateText)
|
|
53
|
+
const target = Date.UTC(year, month - 1, day)
|
|
54
|
+
let guess = target
|
|
55
|
+
for (let round = 0; round < 4; round += 1) {
|
|
56
|
+
const parts = zonedParts(guess, timeZone)
|
|
57
|
+
const seen = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second)
|
|
58
|
+
const delta = seen - target
|
|
59
|
+
if (delta === 0) break
|
|
60
|
+
guess -= delta
|
|
61
|
+
}
|
|
62
|
+
return guess
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** `YYYY-MM-DD` of one instant in the configured time zone. */
|
|
66
|
+
export function localDateText(config, ms = Date.now()) {
|
|
67
|
+
return new Intl.DateTimeFormat('en-CA', {
|
|
68
|
+
timeZone: timeZoneOf(config),
|
|
69
|
+
year: 'numeric',
|
|
70
|
+
month: '2-digit',
|
|
71
|
+
day: '2-digit',
|
|
72
|
+
}).format(new Date(ms))
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function todayText(config) {
|
|
76
|
+
return localDateText(config)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** `HH:mm` of one instant in the configured time zone. */
|
|
80
|
+
export function localClockText(config, ms = Date.now()) {
|
|
81
|
+
const parts = new Intl.DateTimeFormat('en-GB', {
|
|
82
|
+
timeZone: timeZoneOf(config),
|
|
83
|
+
hour: '2-digit',
|
|
84
|
+
minute: '2-digit',
|
|
85
|
+
hourCycle: 'h23',
|
|
86
|
+
}).formatToParts(new Date(ms))
|
|
87
|
+
const hour = parts.find(part => part.type === 'hour')?.value
|
|
88
|
+
const minute = parts.find(part => part.type === 'minute')?.value
|
|
89
|
+
return `${hour ?? '00'}:${minute ?? '00'}`
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** ISO-8601 text with the zone's real offset, e.g. 2026-12-04T23:00:03+08:00. */
|
|
93
|
+
export function zonedIso(config, ms = Date.now()) {
|
|
94
|
+
const timeZone = timeZoneOf(config)
|
|
95
|
+
const parts = zonedParts(ms, timeZone)
|
|
96
|
+
const offsetMs = Date.UTC(
|
|
97
|
+
parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second,
|
|
98
|
+
) - Math.floor(ms / 1000) * 1000
|
|
99
|
+
const offsetMinutes = Math.round(offsetMs / 60_000)
|
|
100
|
+
const sign = offsetMinutes >= 0 ? '+' : '-'
|
|
101
|
+
const abs = Math.abs(offsetMinutes)
|
|
102
|
+
const offset = `${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}:${String(abs % 60).padStart(2, '0')}`
|
|
103
|
+
const pad = value => String(value).padStart(2, '0')
|
|
104
|
+
return `${parts.year}-${pad(parts.month)}-${pad(parts.day)}T${pad(parts.hour)}:${pad(parts.minute)}:${pad(parts.second)}${offset}`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function startOfLocalDay(config, dateText) {
|
|
108
|
+
const date = typeof dateText === 'string' && dateText ? dateText : todayText(config)
|
|
109
|
+
return zonedMidnightUtc(date, timeZoneOf(config))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Add whole local calendar days to a `YYYY-MM-DD` text. */
|
|
113
|
+
export function addLocalDays(dateText, days) {
|
|
114
|
+
const { year, month, day } = dateParts(dateText)
|
|
115
|
+
const next = new Date(Date.UTC(year, month - 1, day + Number(days)))
|
|
116
|
+
return `${next.getUTCFullYear()}-${String(next.getUTCMonth() + 1).padStart(2, '0')}-${String(next.getUTCDate()).padStart(2, '0')}`
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
|
|
120
|
+
|
|
121
|
+
/** 0 = Sunday ... 6 = Saturday for one local date. */
|
|
122
|
+
export function localWeekday(dateText, timeZone) {
|
|
123
|
+
const noon = zonedMidnightUtc(dateText, timeZone) + 12 * 3_600_000
|
|
124
|
+
const name = new Intl.DateTimeFormat('en-US', { timeZone, weekday: 'short' }).format(new Date(noon))
|
|
125
|
+
const index = WEEKDAYS.indexOf(name)
|
|
126
|
+
return index === -1 ? 0 : index
|
|
127
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { isMaintenanceSession, isTaSession } from '../gates.js'
|
|
2
|
+
import { stickerTool } from '../stickers/tool.js'
|
|
3
|
+
import { createReadTools } from './read.js'
|
|
4
|
+
import { createWriteTools } from './write.js'
|
|
5
|
+
import { stringTool } from './shared.js'
|
|
6
|
+
|
|
7
|
+
const SAFE_INHERITED_TOOLS = [
|
|
8
|
+
'read',
|
|
9
|
+
'read_image',
|
|
10
|
+
'glob',
|
|
11
|
+
'grep',
|
|
12
|
+
'web_search',
|
|
13
|
+
'web_fetch',
|
|
14
|
+
'ask_user_question',
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
const toolSets = new Map()
|
|
18
|
+
|
|
19
|
+
function buildTools(ctx, config) {
|
|
20
|
+
const tools = [
|
|
21
|
+
...createReadTools(ctx, config),
|
|
22
|
+
...createWriteTools(ctx, config),
|
|
23
|
+
]
|
|
24
|
+
const sticker = stickerTool(ctx, config)
|
|
25
|
+
if (sticker) tools.push(sticker)
|
|
26
|
+
return tools
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
function maintenanceTool(runtime) {
|
|
31
|
+
return stringTool(
|
|
32
|
+
'ta_maintenance_run',
|
|
33
|
+
'Run the deterministic TA maintenance pipeline once (collect, emotion, diary, RECENT, weekly self/认识 when due). This is the only allowed action in a maintenance trigger session.',
|
|
34
|
+
{ type: 'object', additionalProperties: false, properties: {} },
|
|
35
|
+
async (_args, exec) => {
|
|
36
|
+
if (!runtime) return '维护运行时不可用。'
|
|
37
|
+
const sessionId = exec?.agent?.session?.id
|
|
38
|
+
const started = runtime.runMaintenanceNow({ reason: 'schedule', triggerSessionId: sessionId })
|
|
39
|
+
if (!started?.started) return `维护未启动:${started?.reason ?? 'unknown'}`
|
|
40
|
+
const result = await runtime.whenIdle()
|
|
41
|
+
return JSON.stringify({
|
|
42
|
+
runId: result?.runId ?? started.runId,
|
|
43
|
+
status: result?.status ?? 'unknown',
|
|
44
|
+
success: result?.success === true,
|
|
45
|
+
stages: Array.isArray(result?.stages)
|
|
46
|
+
? result.stages.map(stage => ({ stage: stage.stage, status: stage.status }))
|
|
47
|
+
: [],
|
|
48
|
+
})
|
|
49
|
+
},
|
|
50
|
+
)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function buildMaintenanceTools(runtime) {
|
|
54
|
+
return [maintenanceTool(runtime)]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function disposeToolSet(agentId) {
|
|
58
|
+
const disposers = toolSets.get(agentId)
|
|
59
|
+
if (!disposers) return
|
|
60
|
+
toolSets.delete(agentId)
|
|
61
|
+
for (const dispose of disposers) {
|
|
62
|
+
try {
|
|
63
|
+
dispose()
|
|
64
|
+
} catch {
|
|
65
|
+
/* already unwound */
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function hasTool(agent, name) {
|
|
71
|
+
try {
|
|
72
|
+
return agent.ctx.tools.get(name, agent) !== undefined
|
|
73
|
+
} catch {
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function presetOf(ctx, session) {
|
|
79
|
+
try {
|
|
80
|
+
return ctx?.agentPresets?.presetForSession?.(session)
|
|
81
|
+
} catch {
|
|
82
|
+
return undefined
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function syncAgent(ctx, agent, config, runtime) {
|
|
87
|
+
if (!agent?.session) return
|
|
88
|
+
const maintenance = isMaintenanceSession(ctx, agent.session, config)
|
|
89
|
+
const want = maintenance || isTaSession(ctx, agent.session, config)
|
|
90
|
+
const existing = toolSets.get(agent.id)
|
|
91
|
+
if (want && !existing) {
|
|
92
|
+
if (maintenance) {
|
|
93
|
+
const disposers = []
|
|
94
|
+
for (const tool of buildMaintenanceTools(runtime)) {
|
|
95
|
+
if (hasTool(agent, tool.name)) continue
|
|
96
|
+
try {
|
|
97
|
+
disposers.push(agent.ctx.tools.register(tool))
|
|
98
|
+
} catch {
|
|
99
|
+
/* 维护工具注册失败时不注册其他工具 */
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
disposers.push(agent.ctx.tools.restrict({ allow: ['ta_maintenance_run'] }))
|
|
104
|
+
} catch {
|
|
105
|
+
/* restriction is best effort */
|
|
106
|
+
}
|
|
107
|
+
toolSets.set(agent.id, disposers)
|
|
108
|
+
return
|
|
109
|
+
}
|
|
110
|
+
// 0.4 只保留 ta 预设;旧 ta-review 会话不再注册任何写工具。
|
|
111
|
+
if (presetOf(ctx, agent.session) !== 'ta') return
|
|
112
|
+
const disposers = []
|
|
113
|
+
for (const tool of buildTools(ctx, config)) {
|
|
114
|
+
if (hasTool(agent, tool.name)) continue
|
|
115
|
+
try {
|
|
116
|
+
disposers.push(agent.ctx.tools.register(tool))
|
|
117
|
+
} catch {
|
|
118
|
+
/* 单个工具注册失败不阻塞其他工具 */
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const sticker = stickerTool(ctx, config)
|
|
122
|
+
if (sticker && !hasTool(agent, sticker.name)) {
|
|
123
|
+
try {
|
|
124
|
+
disposers.push(agent.ctx.tools.register(sticker))
|
|
125
|
+
} catch {
|
|
126
|
+
/* sticker is optional */
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
// A preset only adds tools; root/MCP/office/terminal tools remain inherited.
|
|
130
|
+
// Restrict the inherited surface to the read-only allowlist.
|
|
131
|
+
try {
|
|
132
|
+
disposers.push(agent.ctx.tools.restrict({ allow: SAFE_INHERITED_TOOLS }))
|
|
133
|
+
} catch {
|
|
134
|
+
/* restriction is best effort */
|
|
135
|
+
}
|
|
136
|
+
toolSets.set(agent.id, disposers)
|
|
137
|
+
try {
|
|
138
|
+
const permission = ctx.get('permissionPresets')
|
|
139
|
+
if (permission?.current && permission?.set && permission.current(agent.session) !== config.permissionPreset) {
|
|
140
|
+
permission.set(agent.session, config.permissionPreset)
|
|
141
|
+
}
|
|
142
|
+
} catch {
|
|
143
|
+
/* permission service unavailable; account preset still applies */
|
|
144
|
+
}
|
|
145
|
+
} else if (!want && existing) {
|
|
146
|
+
disposeToolSet(agent.id)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function disposeAgent(config, agent) {
|
|
151
|
+
disposeToolSet(agent.id)
|
|
152
|
+
}
|