dsh-ta 0.3.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.
Files changed (85) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +160 -107
  3. package/cordis.patch.yml +5 -35
  4. package/docs/RELEASE.md +62 -49
  5. package/docs/USAGE.md +6 -7
  6. package/docs/presets.example.yml +7 -43
  7. package/index.js +3 -164
  8. package/package.json +5 -28
  9. package/src/client/client.js +3176 -0
  10. package/{config.js → src/host/config.js} +39 -3
  11. package/src/host/constants.js +7 -0
  12. package/src/host/gates.js +34 -0
  13. package/src/host/identity.js +145 -0
  14. package/{im → src/host/im}/bindings.js +1 -1
  15. package/src/host/index.js +173 -0
  16. package/{jurisdiction.js → src/host/jurisdiction.js} +1 -1
  17. package/src/host/maintenance/collect.js +362 -0
  18. package/src/host/maintenance/completions.js +56 -0
  19. package/src/host/maintenance/consumption.js +67 -0
  20. package/src/host/maintenance/cursors.js +53 -0
  21. package/src/host/maintenance/engine.js +392 -0
  22. package/src/host/maintenance/llm.js +381 -0
  23. package/src/host/maintenance/lock.js +105 -0
  24. package/src/host/maintenance/prompts.js +255 -0
  25. package/src/host/maintenance/runs.js +47 -0
  26. package/src/host/maintenance/schedule.js +173 -0
  27. package/src/host/maintenance/session-cleanup.js +289 -0
  28. package/src/host/maintenance/session-watcher.js +107 -0
  29. package/src/host/maintenance/sleep.js +3 -0
  30. package/src/host/maintenance/stages.js +241 -0
  31. package/src/host/maintenance/state.js +192 -0
  32. package/src/host/prompts.js +96 -0
  33. package/src/host/records.js +175 -0
  34. package/src/host/runtime-manager.js +281 -0
  35. package/{runtime.js → src/host/runtime.js} +6 -8
  36. package/src/host/settings/defaults.js +55 -0
  37. package/{settings → src/host/settings}/home.js +4 -3
  38. package/{settings/routes.js → src/host/settings/http.js} +5 -137
  39. package/{settings → src/host/settings}/im.js +18 -1
  40. package/{settings → src/host/settings}/lifecycle.js +29 -43
  41. package/src/host/settings/persona.js +113 -0
  42. package/src/host/settings/routes.js +229 -0
  43. package/{settings → src/host/settings}/status.js +70 -42
  44. package/src/host/state/appraisals.js +56 -0
  45. package/src/host/state/feel.js +78 -0
  46. package/src/host/state/index.js +9 -0
  47. package/src/host/state/mood.js +103 -0
  48. package/src/host/state/notes.js +18 -0
  49. package/{life.js → src/host/state/outing.js} +13 -136
  50. package/src/host/state/values.js +9 -0
  51. package/{stickers → src/host/stickers}/tool.js +1 -1
  52. package/src/host/storage/fs.js +29 -0
  53. package/src/host/storage/index.js +8 -0
  54. package/src/host/storage/paths.js +20 -0
  55. package/src/host/storage/revision.js +5 -0
  56. package/src/host/storage/session-state.js +38 -0
  57. package/src/host/storage/time.js +127 -0
  58. package/src/host/tools/index.js +152 -0
  59. package/src/host/tools/read.js +252 -0
  60. package/src/host/tools/shared.js +23 -0
  61. package/src/host/tools/wiki.js +35 -0
  62. package/src/host/tools/write.js +164 -0
  63. package/{usage → src/host/usage}/aggregate.js +4 -1
  64. package/{usage → src/host/usage}/ledger.js +47 -21
  65. package/client.js +0 -2554
  66. package/gates.js +0 -18
  67. package/identity.js +0 -97
  68. package/prompts.js +0 -28
  69. package/runtime-manager.js +0 -153
  70. package/settings/defaults.js +0 -41
  71. package/settings/persona.js +0 -203
  72. package/settings/schedule.js +0 -156
  73. package/storage.js +0 -122
  74. package/tools.js +0 -540
  75. /package/{im → src/host/im}/say.js +0 -0
  76. /package/{memory → src/host/memory}/capture.js +0 -0
  77. /package/{memory → src/host/memory}/messages.js +0 -0
  78. /package/{memory → src/host/memory}/outbox.js +0 -0
  79. /package/{reme.js → src/host/reme.js} +0 -0
  80. /package/{settings → src/host/settings}/errors.js +0 -0
  81. /package/{stickers → src/host/stickers}/load.js +0 -0
  82. /package/{stickers → src/host/stickers}/select.js +0 -0
  83. /package/{stickers → src/host/stickers}/serve.js +0 -0
  84. /package/{usage → src/host/usage}/pricing.js +0 -0
  85. /package/{usage → src/host/usage}/serve.js +0 -0
@@ -1,156 +0,0 @@
1
- import { REVIEW_PROMPT, REVIEW_TITLE } from '../prompts.js'
2
- import { realPath } from '../storage.js'
3
-
4
- function targetHome(entry) {
5
- const target = entry?.target
6
- if (target?.kind === 'new_once' || target?.kind === 'new') {
7
- return typeof target.create?.cwd === 'string' ? target.create.cwd : undefined
8
- }
9
- return undefined
10
- }
11
-
12
- /**
13
- * 只把 new_once / new 目标的任务当作回顾任务候选;没有 target 的老任务
14
- * 仍然允许按标题保守匹配(下面还会要求“全库唯一同名”)。
15
- * 明确指向已有 Session 的同名任务不是 Ta 的回顾任务,永远不碰。
16
- */
17
- function isReviewTarget(entry) {
18
- const target = entry?.target
19
- if (target === undefined || target === null) return true
20
- return target.kind === 'new_once' || target.kind === 'new'
21
- }
22
-
23
- async function readCatalog(schedule) {
24
- if (typeof schedule?.catalog === 'function') {
25
- const entries = await schedule.catalog()
26
- return Array.isArray(entries) ? entries : []
27
- }
28
- if (typeof schedule?.list === 'function') {
29
- const page = await schedule.list({ active: true })
30
- return Array.isArray(page?.items) ? page.items : []
31
- }
32
- return undefined
33
- }
34
-
35
- function sameHome(left, right) {
36
- if (typeof left !== 'string' || typeof right !== 'string') return false
37
- return realPath(left) === realPath(right)
38
- }
39
-
40
- /**
41
- * Remove only the review tasks that provably belong to one home. A title-only
42
- * match is accepted only when exactly one review task lacks target metadata,
43
- * so a user-created task can never be swept away by accident.
44
- */
45
- export async function removeReviewSchedule(ctx, home, logger) {
46
- const schedule = ctx?.get?.('schedule')
47
- const empty = { removed: 0, skipped: 0, warnings: [] }
48
- if (!schedule?.edit || !schedule?.catalog && !schedule?.list) {
49
- return { ...empty, warnings: ['日程服务不可用,旧回顾任务没有自动清理'] }
50
- }
51
- let entries
52
- try {
53
- entries = await readCatalog(schedule)
54
- } catch (cause) {
55
- return { ...empty, warnings: [`读取日程失败:${cause instanceof Error ? cause.message : String(cause)}`] }
56
- }
57
- if (!entries) return { ...empty, warnings: ['日程服务没有可读列表,旧回顾任务没有自动清理'] }
58
-
59
- const titled = entries.filter(entry => entry?.title === REVIEW_TITLE)
60
- const review = titled.filter(isReviewTarget)
61
- if (review.length === 0) return empty
62
- const withCwd = review.filter(entry => typeof targetHome(entry) === 'string')
63
- const withoutCwd = review.filter(entry => typeof targetHome(entry) !== 'string')
64
- const matched = withCwd.filter(entry => sameHome(targetHome(entry), home))
65
- const warnings = []
66
- if (withoutCwd.length === 1 && withCwd.length === 0 && titled.length === 1) {
67
- matched.push(withoutCwd[0])
68
- warnings.push('回顾任务缺少目标目录,只能按标题保守匹配')
69
- } else if (withoutCwd.length > 0) {
70
- warnings.push(`有 ${withoutCwd.length} 个回顾任务缺少目标目录,已跳过以免误删`)
71
- }
72
-
73
- let removed = 0
74
- let skipped = 0
75
- for (const entry of new Set(matched)) {
76
- if (!entry.id) {
77
- skipped += 1
78
- continue
79
- }
80
- try {
81
- const result = await schedule.edit({ id: entry.id, action: 'delete' })
82
- // edit 删除成功固定返回 { id, deleted: true };未找到等拒绝也会带 id,
83
- // 所以必须只看 deleted 字段,不能按 id 相等来判断。
84
- const deleted = result?.deleted === true
85
- if (deleted) {
86
- removed += 1
87
- logger?.info?.(`[dsh-ta] removed review schedule ${entry.id} for ${home}`)
88
- } else {
89
- skipped += 1
90
- warnings.push(`回顾任务 ${entry.id} 未删除(${result?.code ?? 'unknown'})`)
91
- }
92
- } catch (cause) {
93
- skipped += 1
94
- warnings.push(`回顾任务 ${entry.id} 删除失败:${cause instanceof Error ? cause.message : String(cause)}`)
95
- }
96
- }
97
- return { removed, skipped, warnings }
98
- }
99
-
100
- function rruleForTomorrow(config) {
101
- const tomorrow = new Date(Date.now() + 24 * 60 * 60 * 1000)
102
- const date = new Intl.DateTimeFormat('en-CA', {
103
- timeZone: config.timezone,
104
- year: 'numeric',
105
- month: '2-digit',
106
- day: '2-digit',
107
- }).format(tomorrow).replaceAll('-', '')
108
- return `DTSTART;TZID=${config.timezone}:${date}T230000\nRRULE:FREQ=DAILY`
109
- }
110
-
111
- /** Ensure exactly one nightly review task for the configured home. */
112
- export async function ensureReviewSchedule(ctx, config) {
113
- const schedule = ctx?.get?.('schedule')
114
- if (!schedule?.create) return { created: false, existing: false, warnings: [] }
115
- let entries
116
- try {
117
- entries = await readCatalog(schedule)
118
- } catch {
119
- entries = undefined
120
- }
121
- if (Array.isArray(entries)) {
122
- const existing = entries.some(entry => entry?.title === REVIEW_TITLE
123
- && entry?.status !== 'ended'
124
- && sameHome(targetHome(entry), config.taHome))
125
- if (existing) return { created: false, existing: true, warnings: [] }
126
- }
127
- try {
128
- await schedule.create({
129
- title: REVIEW_TITLE,
130
- prompt: REVIEW_PROMPT,
131
- timing: { kind: 'rrule', rrule: rruleForTomorrow(config) },
132
- target: {
133
- kind: 'new_once',
134
- create: { cwd: config.taHome, agentPreset: 'ta-review' },
135
- },
136
- })
137
- return { created: true, existing: false, warnings: [] }
138
- } catch (cause) {
139
- return {
140
- created: false,
141
- existing: false,
142
- warnings: [`创建回顾任务失败:${cause instanceof Error ? cause.message : String(cause)}`],
143
- }
144
- }
145
- }
146
-
147
- export async function reconcileReviewSchedule(ctx, config, previousHome, logger) {
148
- const warnings = []
149
- if (previousHome && !sameHome(previousHome, config.taHome)) {
150
- const removed = await removeReviewSchedule(ctx, previousHome, logger)
151
- warnings.push(...removed.warnings)
152
- }
153
- const ensured = await ensureReviewSchedule(ctx, config)
154
- warnings.push(...(ensured.warnings ?? []))
155
- return { ...ensured, warnings }
156
- }
package/storage.js DELETED
@@ -1,122 +0,0 @@
1
- import { createHash } from 'node:crypto'
2
- import { accessSync, constants, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from 'node:fs'
3
- import { dirname, resolve, sep } from 'node:path'
4
-
5
- export function recordSessionMap(config, dshSessionId, remeSessionId) {
6
- try {
7
- const path = resolve(config.taHome, config.sessionMap)
8
- let value = {}
9
- try {
10
- value = JSON.parse(readFileSync(path, 'utf8'))
11
- } catch {
12
- value = {}
13
- }
14
- if (value[remeSessionId] === dshSessionId) return
15
- value[remeSessionId] = dshSessionId
16
- mkdirSync(resolve(config.taHome, 'state'), { recursive: true })
17
- const temporary = `${path}.tmp`
18
- writeFileSync(temporary, JSON.stringify(value, null, 2) + '\n')
19
- renameSync(temporary, path)
20
- } catch {
21
- /* mapping is diagnostic; capture must not fail for it */
22
- }
23
- }
24
-
25
- export function readInternalSessions(config) {
26
- try {
27
- const value = JSON.parse(readFileSync(resolve(config.taHome, config.internalSessions), 'utf8'))
28
- return Array.isArray(value) ? value : (value && typeof value === 'object' ? value : {})
29
- } catch {
30
- return {}
31
- }
32
- }
33
-
34
- export function internalSessionIds(config) {
35
- const value = readInternalSessions(config)
36
- const ids = Array.isArray(value) ? value : Object.keys(value)
37
- return new Set(ids.filter(id => typeof id === 'string'))
38
- }
39
-
40
-
41
- export function realPath(value) {
42
- if (typeof value !== 'string' || value.length === 0) return ''
43
- try {
44
- return realpathSync.native(value)
45
- } catch {
46
- return resolve(value)
47
- }
48
- }
49
-
50
- /**
51
- * True only for an ordinary Session whose cwd is Ta's home and whose current
52
- * preset is one of the configured Ta presets.
53
- */
54
- export function withinHome(relative, config) {
55
- if (typeof relative !== 'string' || relative.length === 0) throw new Error('path is required')
56
- const base = realPath(config.taHome)
57
- const target = realPath(resolve(base, relative))
58
- if (target !== base && !target.startsWith(base + sep)) throw new Error('path is outside TA_HOME')
59
- return target
60
- }
61
-
62
- export function writeAtomic(path, text) {
63
- mkdirSync(dirname(path), { recursive: true })
64
- const temporary = `${path}.tmp-${process.pid}-${Date.now()}`
65
- writeFileSync(temporary, text)
66
- renameSync(temporary, path)
67
- }
68
-
69
- export function readTextIfExists(path) {
70
- try {
71
- if (!statSync(path).isFile()) return undefined
72
- return readFileSync(path, 'utf8')
73
- } catch {
74
- return undefined
75
- }
76
- }
77
-
78
- export function sha256Revision(text) {
79
- return `sha256:${createHash('sha256').update(String(text ?? ''), 'utf8').digest('hex')}`
80
- }
81
-
82
- export function ensureDir(path) {
83
- mkdirSync(path, { recursive: true })
84
- }
85
-
86
- export function isWritableDirectory(path) {
87
- try {
88
- if (!statSync(path).isDirectory()) return false
89
- accessSync(path, constants.W_OK)
90
- return true
91
- } catch {
92
- return false
93
- }
94
- }
95
-
96
- export function todayText(config) {
97
- return new Intl.DateTimeFormat('en-CA', {
98
- timeZone: config.timezone,
99
- year: 'numeric',
100
- month: '2-digit',
101
- day: '2-digit',
102
- }).format(new Date())
103
- }
104
-
105
- export function startOfLocalDay(config) {
106
- const date = todayText(config)
107
- if (config.timezone === 'Asia/Shanghai') return Date.parse(`${date}T00:00:00+08:00`)
108
- return new Date(`${date}T00:00:00`).getTime()
109
- }
110
-
111
-
112
- export function localHourMinute(config) {
113
- const parts = new Intl.DateTimeFormat('en-GB', {
114
- timeZone: config.timezone,
115
- hour: '2-digit',
116
- minute: '2-digit',
117
- hourCycle: 'h23',
118
- }).formatToParts(new Date())
119
- const hour = parts.find(part => part.type === 'hour')?.value
120
- const minute = parts.find(part => part.type === 'minute')?.value
121
- return `${hour ?? '00'}:${minute ?? '00'}`
122
- }