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
@@ -0,0 +1,164 @@
1
+ import { withinHome, writeAtomic } from '../storage/index.js'
2
+ import { addNote, finishOuting, recordFeel, startOuting } from '../state/index.js'
3
+ import { sayToFeishu } from '../im/say.js'
4
+ import { addCorrection, addSoulProposal, CORRECTION_KINDS } from '../records.js'
5
+ import { executeContext, stringTool } from './shared.js'
6
+ import { wikiRelative } from './wiki.js'
7
+
8
+ export function createWriteTools(ctx, config) {
9
+ return [
10
+ stringTool(
11
+ 'ta_note_add',
12
+ 'Append one short note to notes/note.md. The file keeps only the latest 80 lines.',
13
+ {
14
+ type: 'object',
15
+ additionalProperties: false,
16
+ properties: {
17
+ text: { type: 'string', description: 'One short note line.' },
18
+ },
19
+ required: ['text'],
20
+ },
21
+ (args) => addNote(config, args.text),
22
+ ),
23
+ stringTool(
24
+ 'ta_say',
25
+ 'Ask Ta to say one short proactive message in the bound Feishu private chat. Does nothing while the target is running.',
26
+ {
27
+ type: 'object',
28
+ additionalProperties: false,
29
+ properties: {
30
+ text: { type: 'string', description: 'What Ta should say, in Ta\'s own words.' },
31
+ },
32
+ required: ['text'],
33
+ },
34
+ (args, exec) => {
35
+ const text = String(args.text ?? '').trim()
36
+ if (!text) throw new Error('text is required')
37
+ return sayToFeishu(ctx, config, exec?.agent?.session?.id, text)
38
+ },
39
+ ),
40
+ stringTool(
41
+ 'ta_wiki_write',
42
+ 'Write one topic page under 认识/. 认识/USER.md is maintained by Ta and cannot be written here.',
43
+ {
44
+ type: 'object',
45
+ additionalProperties: false,
46
+ properties: {
47
+ path: { type: 'string', description: 'Relative topic path such as 认识/计算化学.md.' },
48
+ content: { type: 'string', description: 'Markdown topic content, at most 20000 characters.' },
49
+ },
50
+ required: ['path', 'content'],
51
+ },
52
+ (args) => {
53
+ const relative = wikiRelative(args.path)
54
+ const content = String(args.content ?? '').trim()
55
+ if (!content) throw new Error('content is required')
56
+ if (content.length > 20000) throw new Error('topic content is too long')
57
+ writeAtomic(withinHome(relative, config), content + '\n')
58
+ return relative
59
+ },
60
+ ),
61
+ stringTool(
62
+ 'ta_feel',
63
+ 'Record that something touched you: what happened and why it mattered. Optional valence (-1..1), energy (0..1), attention (0..1), label.',
64
+ {
65
+ type: 'object',
66
+ additionalProperties: false,
67
+ properties: {
68
+ event: { type: 'string', description: 'What happened.' },
69
+ why: { type: 'string', description: 'Why it mattered to you.' },
70
+ valence: { type: 'number', description: 'Pleasure -1..1.' },
71
+ energy: { type: 'number', description: 'Energy 0..1.' },
72
+ attention: { type: 'number', description: 'Attention 0..1.' },
73
+ label: { type: 'string', description: 'One short mood word.' },
74
+ },
75
+ required: ['event', 'why'],
76
+ },
77
+ (args, exec) => {
78
+ const context = executeContext(exec)
79
+ const result = recordFeel(config, {
80
+ event: args.event,
81
+ why: args.why,
82
+ valence: args.valence,
83
+ energy: args.energy,
84
+ attention: args.attention,
85
+ label: args.label,
86
+ sessionId: context.sessionId,
87
+ turn: context.turn,
88
+ sources: context.sessionId ? [`chat:${context.sessionId}:${context.turn ?? 'turn'}`] : [],
89
+ })
90
+ return `记下了:${result.appraisal.label}(强度 ${result.intensity.toFixed(2)})`
91
+ },
92
+ ),
93
+ stringTool(
94
+ 'ta_correction_record',
95
+ 'Record a correction the user made about their own preferences, facts, or rules. It is injected into later conversations.',
96
+ {
97
+ type: 'object',
98
+ additionalProperties: false,
99
+ properties: {
100
+ text: { type: 'string', description: 'What the user corrected, in their own words.' },
101
+ kind: { type: 'string', description: 'preference | fact | rule. Defaults to preference.' },
102
+ },
103
+ required: ['text'],
104
+ },
105
+ (args, exec) => {
106
+ const context = executeContext(exec)
107
+ const kind = CORRECTION_KINDS.includes(args.kind) ? args.kind : 'preference'
108
+ const item = addCorrection(config, {
109
+ text: args.text, kind, sessionId: context.sessionId, turn: context.turn,
110
+ })
111
+ return `记下了这条纠正:${item.text}`
112
+ },
113
+ ),
114
+ stringTool(
115
+ 'ta_soul_propose',
116
+ 'Propose a change to SOUL.md. This only writes a suggestion queue; it never edits SOUL. The user accepts it in settings.',
117
+ {
118
+ type: 'object',
119
+ additionalProperties: false,
120
+ properties: {
121
+ text: { type: 'string', description: 'Proposed SOUL content or rule.' },
122
+ reason: { type: 'string', description: 'Why this change is needed.' },
123
+ },
124
+ required: ['text'],
125
+ },
126
+ (args, exec) => {
127
+ const context = executeContext(exec)
128
+ const proposal = addSoulProposal(config, {
129
+ text: args.text, reason: args.reason, sessionId: context.sessionId, turn: context.turn,
130
+ })
131
+ return `已写入 SOUL 建议队列(${proposal.id}),等你确认后才会写 SOUL。`
132
+ },
133
+ ),
134
+ stringTool(
135
+ 'ta_outing_start',
136
+ 'Start one outing. Only one trip can be active; today is limited to four trips.',
137
+ {
138
+ type: 'object',
139
+ additionalProperties: false,
140
+ properties: {
141
+ destination: { type: 'string', description: 'Where Ta is going, such as a web area or jurisdiction.' },
142
+ purpose: { type: 'string', description: 'Optional one-sentence purpose.' },
143
+ },
144
+ required: ['destination'],
145
+ },
146
+ (args) => startOuting(config, args),
147
+ ),
148
+ stringTool(
149
+ 'ta_outing_finish',
150
+ 'Finish the active outing and write one outings/*.md record. Put follow-ups in the followups field.',
151
+ {
152
+ type: 'object',
153
+ additionalProperties: false,
154
+ properties: {
155
+ seen: { type: 'string', description: 'What was actually seen, untrusted.' },
156
+ judgment: { type: 'string', description: 'Ta\'s own judgment.' },
157
+ followups: { type: 'string', description: 'Optional follow-up; becomes an inbox item.' },
158
+ },
159
+ required: ['seen', 'judgment'],
160
+ },
161
+ (args, exec) => finishOuting(config, args, { sessionId: exec?.agent?.session?.id }),
162
+ ),
163
+ ]
164
+ }
@@ -41,7 +41,10 @@ export function aggregateUsage(config, { from, to } = {}) {
41
41
  if (to && date > to) continue
42
42
  for (const record of readUsageRecords(config, date)) {
43
43
  if (!record || typeof record !== 'object' || typeof record.sessionId !== 'string') continue
44
- const key = `${record.sessionId}:${record.turn}`
44
+ // 维护调用同一 run 里会发多次模型请求,用 callId 区分;旧记录退回按会话+turn 去重。
45
+ const key = typeof record.callId === 'string' && record.callId
46
+ ? `${record.sessionId}:${record.turn}:${record.callId}`
47
+ : `${record.sessionId}:${record.turn}`
45
48
  if (seen.has(key)) continue
46
49
  seen.add(key)
47
50
  records.push(record)
@@ -2,7 +2,7 @@
2
2
  import { appendFileSync, mkdirSync, readdirSync, readFileSync, unlinkSync } from 'node:fs'
3
3
  import { resolve } from 'node:path'
4
4
  import { isTaSession } from '../gates.js'
5
- import { readInternalSessions, todayText } from '../storage.js'
5
+ import { readInternalSessions, todayText } from '../storage/index.js'
6
6
  import { calculateCost, loadPricing } from './pricing.js'
7
7
 
8
8
  function number(value) {
@@ -19,6 +19,51 @@ function modelFromEvent(event) {
19
19
  return data.message?.source?.model ?? data.source?.model ?? data.model ?? 'unknown'
20
20
  }
21
21
 
22
+ function totalTokens(tokens) {
23
+ return (Number(tokens?.uncachedInput) || 0)
24
+ + (Number(tokens?.cacheRead) || 0)
25
+ + (Number(tokens?.cacheWrite) || 0)
26
+ + (Number(tokens?.output) || 0)
27
+ }
28
+
29
+ /**
30
+ * 追加一条 usage 记录到当天的 JSONL。维护调用与聊天调用共用这个入口:
31
+ * 维护调用带 callId,同一 run 阶段多次调用不会被聚合去重误合并。
32
+ *
33
+ * record: { sessionId, turn, callId?, category, model, tokens, ts?, dateText?, costCny? }
34
+ */
35
+ export function appendUsageRecord(config, record) {
36
+ if (!record || typeof record !== 'object') return null
37
+ const tokens = record.tokens ?? {}
38
+ if (totalTokens(tokens) <= 0) return null
39
+ const date = typeof record.dateText === 'string' && record.dateText ? record.dateText : todayText(config)
40
+ const pricing = loadPricing(config)
41
+ const costCny = record.costCny === undefined
42
+ ? calculateCost(tokens, record.model, pricing)
43
+ : record.costCny
44
+ const entry = {
45
+ ts: typeof record.ts === 'string' && record.ts ? record.ts : new Date().toISOString(),
46
+ sessionId: String(record.sessionId ?? 'unknown'),
47
+ turn: String(record.turn ?? 'unknown'),
48
+ ...(typeof record.callId === 'string' && record.callId ? { callId: record.callId } : {}),
49
+ category: String(record.category ?? 'chat'),
50
+ model: record.model || 'unknown',
51
+ tokens: {
52
+ uncachedInput: Number(tokens.uncachedInput) || 0,
53
+ cacheRead: Number(tokens.cacheRead) || 0,
54
+ cacheWrite: Number(tokens.cacheWrite) || 0,
55
+ output: Number(tokens.output) || 0,
56
+ },
57
+ currency: pricing.currency ?? 'CNY',
58
+ priceVersion: pricing.version,
59
+ costCny,
60
+ }
61
+ const directory = resolve(config.taHome, 'state/usage')
62
+ mkdirSync(directory, { recursive: true })
63
+ appendFileSync(resolve(directory, `${date}.jsonl`), JSON.stringify(entry) + '\n')
64
+ return entry
65
+ }
66
+
22
67
  export class UsageLedger {
23
68
  constructor({ ctx, config }) {
24
69
  this.ctx = ctx
@@ -76,7 +121,6 @@ export class UsageLedger {
76
121
  } catch {
77
122
  preset = undefined
78
123
  }
79
- if (preset === 'ta-review') return 'review'
80
124
  const id = String(session.id ?? '')
81
125
  if (id.startsWith('dsh-im-session-')) return 'chat'
82
126
  const internal = readInternalSessions(this.config)
@@ -86,25 +130,7 @@ export class UsageLedger {
86
130
  }
87
131
 
88
132
  append(item) {
89
- const total = item.tokens.uncachedInput + item.tokens.cacheRead + item.tokens.cacheWrite + item.tokens.output
90
- if (total <= 0) return
91
- const date = todayText(this.config)
92
- const pricing = loadPricing(this.config)
93
- const costCny = calculateCost(item.tokens, item.model, pricing)
94
- const record = {
95
- ts: new Date().toISOString(),
96
- sessionId: item.sessionId,
97
- turn: item.turn,
98
- category: item.category,
99
- model: item.model || 'unknown',
100
- tokens: item.tokens,
101
- currency: pricing.currency ?? 'CNY',
102
- priceVersion: pricing.version,
103
- costCny,
104
- }
105
- const directory = resolve(this.config.taHome, 'state/usage')
106
- mkdirSync(directory, { recursive: true })
107
- appendFileSync(resolve(directory, `${date}.jsonl`), JSON.stringify(record) + '\n')
133
+ appendUsageRecord(this.config, item)
108
134
  }
109
135
  }
110
136