dsh-feiyu-life 2.3.2 → 2.5.2
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 +53 -0
- package/README.md +15 -4
- package/agency-runner.js +28 -0
- package/agency.js +841 -0
- package/assets/references/feiyu-front.jpg +0 -0
- package/assets/references/feiyu-turnaround.jpg +0 -0
- package/client.js +9 -12
- package/docs/CONFIGURATION.md +13 -8
- package/docs/DESIGN.md +14 -2
- package/gen.js +25 -4
- package/image-prompt.js +97 -56
- package/image.js +45 -56
- package/index.js +60 -2
- package/package.json +4 -2
- package/sharing.js +25 -9
package/agency.js
ADDED
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
// dsh-feiyu-life · internal agenda / drive loop
|
|
2
|
+
//
|
|
3
|
+
// This is not a second proactive sender and it never performs a real-world
|
|
4
|
+
// action. It keeps one short-lived focus derived from real unfinished things
|
|
5
|
+
// (continuity tasks/commitments/threads, explicit self goals, needs and
|
|
6
|
+
// affects), executes only a bounded internal review step when the focus is a
|
|
7
|
+
// goal/thread, and lets that focus influence context and follow-up candidates.
|
|
8
|
+
// A source is only marked done when its actual continuity/mind state says so.
|
|
9
|
+
|
|
10
|
+
import { randomUUID } from 'node:crypto'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { homedir } from 'node:os'
|
|
13
|
+
import { atomicWriteJson, readJsonBounded, withLock } from './storage.js'
|
|
14
|
+
|
|
15
|
+
export const AGENCY_VERSION = 2
|
|
16
|
+
export const AGENCY_LIMITS = {
|
|
17
|
+
recent: 24, deferred: 24, abandoned: 24, executions: 40, candidates: 40, fileBytes: 256 * 1024,
|
|
18
|
+
holdMs: 15 * 60 * 1000, deferMs: 30 * 60 * 1000, reviewIntervalMs: 30 * 60 * 1000,
|
|
19
|
+
followupWaitMs: 48 * 3600000, ignoredRetryMs: 72 * 3600000, newFactWaitMs: 30 * 60 * 1000,
|
|
20
|
+
}
|
|
21
|
+
const root = () => process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
22
|
+
export const agencyPath = () => join(root(), 'feiyu-life-agency.json')
|
|
23
|
+
const clamp = (n, a, b, fallback = 0) => {
|
|
24
|
+
const value = Number(n)
|
|
25
|
+
return Number.isFinite(value) ? Math.max(a, Math.min(b, value)) : fallback
|
|
26
|
+
}
|
|
27
|
+
const text = (value, max = 160) => String(value || '').trim().replace(/\s+/g, ' ').slice(0, max)
|
|
28
|
+
const negativeReply = /(别催|不用催|别再提|不想提|别问|别管|没兴趣)/
|
|
29
|
+
const sensitiveText = /密码|口令|验证码|私钥|助记词|api[ _-]?key|access[ _-]?token|secret|身份证|银行卡|信用卡/i
|
|
30
|
+
const stopTopic = new Set(['事情', '这个', '那个', '一下', '最近', '自己', '问题', '东西', '时候', '还是', '可以'])
|
|
31
|
+
|
|
32
|
+
/** Pull a reply reference only if the host payload actually exposes one. */
|
|
33
|
+
export function inboxReplyReference(payload) {
|
|
34
|
+
const message = payload?.message || payload?.data?.message || payload?.data?.item || payload || {}
|
|
35
|
+
return text(message.replyTo || message.reply_to || message.parentId || message.parent_id || message.source?.replyTo || message.source?.parentId || payload?.replyTo || '', 180)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function topicMatches(body, row) {
|
|
39
|
+
const haystack = String(body || '').replace(/\s+/g, '')
|
|
40
|
+
if (!haystack) return false
|
|
41
|
+
const topic = text(row?.topic, 160)
|
|
42
|
+
if (topic && topic.length >= 2) {
|
|
43
|
+
if (haystack.includes(topic)) return true
|
|
44
|
+
const parts = topic.split(/[,。!?、;:,.!?;:\s/|]+/).filter((x) => x.length >= 2 && !stopTopic.has(x))
|
|
45
|
+
if (parts.some((x) => haystack.includes(x))) return true
|
|
46
|
+
}
|
|
47
|
+
// A source key is not user-facing, but its last meaningful segment can be
|
|
48
|
+
// an explicit referent in Chinese (e.g. task title already in topic).
|
|
49
|
+
const source = text(row?.lastStage, 180)
|
|
50
|
+
if (source && haystack.includes(source)) return true
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function defaultAgency(now = Date.now()) {
|
|
55
|
+
return {
|
|
56
|
+
v: AGENCY_VERSION, updatedAt: now, focus: null, deferred: [], abandoned: [],
|
|
57
|
+
outreach: {}, executions: [], recent: [], explored: {},
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function normalizeStep(x, index = 0) {
|
|
62
|
+
const label = text(x?.label, 120)
|
|
63
|
+
if (!label) return null
|
|
64
|
+
const inferred = /复盘/.test(label) ? 'review' : /下一步|继续推进/.test(label) ? 'wait' : 'wait'
|
|
65
|
+
return {
|
|
66
|
+
label,
|
|
67
|
+
status: ['pending', 'active', 'done', 'skipped'].includes(x?.status) ? x.status : 'pending',
|
|
68
|
+
kind: ['review', 'wait', 'confirm', 'rest'].includes(x?.kind) ? x.kind : inferred,
|
|
69
|
+
evidence: text(x?.evidence, 180),
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function normalizePlan(x, now = Date.now()) {
|
|
74
|
+
if (!x || typeof x !== 'object') return null
|
|
75
|
+
const sourceKey = text(x.sourceKey, 160)
|
|
76
|
+
const title = text(x.title, 120)
|
|
77
|
+
if (!sourceKey || !title) return null
|
|
78
|
+
return {
|
|
79
|
+
id: text(x.id, 80) || `agc-${randomUUID()}`,
|
|
80
|
+
sourceKey,
|
|
81
|
+
sourceId: text(x.sourceId, 120),
|
|
82
|
+
sourceType: ['task', 'commitment', 'thread', 'goal', 'rest', 'interest', 'relationship'].includes(x.sourceType) ? x.sourceType : 'task',
|
|
83
|
+
scope: ['virtual', 'local'].includes(x.scope) ? x.scope : '',
|
|
84
|
+
title,
|
|
85
|
+
detail: text(x.detail, 180),
|
|
86
|
+
nextStep: text(x.nextStep, 160),
|
|
87
|
+
dueAt: Math.max(0, Number(x.dueAt) || 0),
|
|
88
|
+
dueLabel: text(x.dueLabel, 60),
|
|
89
|
+
sourceUpdatedAt: Math.max(0, Number(x.sourceUpdatedAt) || 0),
|
|
90
|
+
expiresAt: Math.max(0, Number(x.expiresAt) || 0),
|
|
91
|
+
priority: clamp(x.priority, 0, 100, 50),
|
|
92
|
+
score: clamp(x.score, 0, 100, 50),
|
|
93
|
+
cost: clamp(x.cost, 1, 5, 2),
|
|
94
|
+
risk: clamp(x.risk, 0, 3, 0),
|
|
95
|
+
status: ['active', 'deferred', 'done', 'abandoned'].includes(x.status) ? x.status : 'active',
|
|
96
|
+
steps: (Array.isArray(x.steps) ? x.steps : []).map(normalizeStep).filter(Boolean).slice(0, 4),
|
|
97
|
+
stepIndex: Math.max(0, Math.round(Number(x.stepIndex) || 0)),
|
|
98
|
+
progress: clamp(x.progress, 0, 100, 0),
|
|
99
|
+
createdAt: Math.max(0, Number(x.createdAt) || now),
|
|
100
|
+
updatedAt: Math.max(0, Number(x.updatedAt) || now),
|
|
101
|
+
lastReviewAt: Math.max(0, Number(x.lastReviewAt) || 0),
|
|
102
|
+
lastActionAt: Math.max(0, Number(x.lastActionAt) || 0),
|
|
103
|
+
internalPlan: x?.internalPlan && typeof x.internalPlan === 'object' ? {
|
|
104
|
+
at: Math.max(0, Number(x.internalPlan.at) || 0),
|
|
105
|
+
nextAction: text(x.internalPlan.nextAction, 160),
|
|
106
|
+
evidence: text(x.internalPlan.evidence, 220),
|
|
107
|
+
} : null,
|
|
108
|
+
reason: text(x.reason, 160),
|
|
109
|
+
pendingProgress: text(x.pendingProgress, 80),
|
|
110
|
+
attempts: Math.max(0, Math.round(Number(x.attempts) || 0)),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function normalizeDeferred(x) {
|
|
115
|
+
const sourceKey = text(x?.sourceKey, 160)
|
|
116
|
+
if (!sourceKey) return null
|
|
117
|
+
return {
|
|
118
|
+
sourceKey,
|
|
119
|
+
until: Math.max(0, Number(x.until) || 0),
|
|
120
|
+
attempts: Math.max(0, Math.round(Number(x.attempts) || 0)),
|
|
121
|
+
reason: text(x?.reason, 160),
|
|
122
|
+
lastSourceUpdatedAt: Math.max(0, Number(x?.lastSourceUpdatedAt) || 0),
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function normalizeAbandoned(x) {
|
|
127
|
+
const sourceKey = text(x?.sourceKey, 160)
|
|
128
|
+
if (!sourceKey) return null
|
|
129
|
+
return {
|
|
130
|
+
sourceKey, at: Math.max(0, Number(x.at) || 0), reason: text(x.reason, 160),
|
|
131
|
+
lastSourceUpdatedAt: Math.max(0, Number(x.lastSourceUpdatedAt) || 0),
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function normalizeOutreach(x) {
|
|
136
|
+
const lastAt = Math.max(0, Number(x?.lastAt) || 0)
|
|
137
|
+
if (!lastAt) return null
|
|
138
|
+
return {
|
|
139
|
+
lastAt,
|
|
140
|
+
count: Math.max(0, Math.round(Number(x?.count) || 0)),
|
|
141
|
+
status: ['awaiting', 'responded', 'ignored', 'declined'].includes(x?.status) ? x.status : 'awaiting',
|
|
142
|
+
lastStage: text(x?.lastStage, 180),
|
|
143
|
+
lastSourceUpdatedAt: Math.max(0, Number(x?.lastSourceUpdatedAt) || 0),
|
|
144
|
+
nextAt: Math.max(0, Number(x?.nextAt) || 0),
|
|
145
|
+
sessionId: text(x?.sessionId, 120),
|
|
146
|
+
topic: text(x?.topic, 160),
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function normalizeAgency(raw, now = Date.now()) {
|
|
151
|
+
if (!raw || ![1, AGENCY_VERSION].includes(Number(raw.v))) return defaultAgency(now)
|
|
152
|
+
const outreach = {}
|
|
153
|
+
if (raw.outreach && typeof raw.outreach === 'object') {
|
|
154
|
+
for (const [key, value] of Object.entries(raw.outreach)) {
|
|
155
|
+
const clean = normalizeOutreach(value)
|
|
156
|
+
if (clean && key) outreach[text(key, 160)] = clean
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const focus = normalizePlan(raw.focus, now)
|
|
160
|
+
return {
|
|
161
|
+
v: AGENCY_VERSION,
|
|
162
|
+
updatedAt: Math.max(0, Number(raw.updatedAt) || now),
|
|
163
|
+
focus: focus && ['active', 'deferred'].includes(focus.status) ? focus : null,
|
|
164
|
+
deferred: (Array.isArray(raw.deferred) ? raw.deferred : []).map(normalizeDeferred).filter(Boolean).slice(-AGENCY_LIMITS.deferred),
|
|
165
|
+
abandoned: (Array.isArray(raw.abandoned) ? raw.abandoned : []).map(normalizeAbandoned).filter(Boolean).slice(-AGENCY_LIMITS.abandoned),
|
|
166
|
+
outreach: Object.fromEntries(Object.entries(outreach).slice(-AGENCY_LIMITS.recent)),
|
|
167
|
+
explored: Object.fromEntries(Object.entries(raw.explored && typeof raw.explored === 'object' ? raw.explored : {}).flatMap(([key, value]) => {
|
|
168
|
+
const at = Math.max(0, Number(value) || 0)
|
|
169
|
+
return key && at ? [[text(key, 160), at]] : []
|
|
170
|
+
}).slice(-AGENCY_LIMITS.recent)),
|
|
171
|
+
executions: (Array.isArray(raw.executions) ? raw.executions : []).flatMap((x) => {
|
|
172
|
+
const sourceKey = text(x?.sourceKey, 160); const action = text(x?.action, 40); const evidence = text(x?.evidence, 220)
|
|
173
|
+
return sourceKey && action && evidence ? [{ at: Math.max(0, Number(x?.at) || 0), sourceKey, action, evidence }] : []
|
|
174
|
+
}).slice(-AGENCY_LIMITS.executions),
|
|
175
|
+
recent: (Array.isArray(raw.recent) ? raw.recent : []).flatMap((x) => {
|
|
176
|
+
const title = text(x?.title, 120)
|
|
177
|
+
return title ? [{ at: Math.max(0, Number(x.at) || 0), sourceKey: text(x.sourceKey, 160), title, status: text(x.status, 24) || 'done' }] : []
|
|
178
|
+
}).slice(-AGENCY_LIMITS.recent),
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export function readAgency(now = Date.now()) {
|
|
183
|
+
const read = readJsonBounded(agencyPath(), { maxBytes: AGENCY_LIMITS.fileBytes })
|
|
184
|
+
if (!read.ok) return defaultAgency(now)
|
|
185
|
+
const clean = normalizeAgency(read.value, now)
|
|
186
|
+
if (Number(read.value?.v) !== AGENCY_VERSION) {
|
|
187
|
+
// v1 had no outreach/abandoned/executions; migrate once instead of
|
|
188
|
+
// treating the old file as permanently empty.
|
|
189
|
+
try { writeAgency(clean, now) } catch {}
|
|
190
|
+
}
|
|
191
|
+
return clean
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function writeAgency(value, now = Date.now()) {
|
|
195
|
+
return atomicWriteJson(agencyPath(), normalizeAgency(value, now))
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function sourceMap(continuity, mind, candidates = []) {
|
|
199
|
+
const map = new Map()
|
|
200
|
+
for (const entity of Array.isArray(candidates) ? candidates : []) {
|
|
201
|
+
if (!map.has(entity?.sourceKey)) map.set(entity.sourceKey, { ...entity, status: 'active' })
|
|
202
|
+
}
|
|
203
|
+
for (const [kind, list] of [['task', continuity?.tasks], ['commitment', continuity?.commitments], ['thread', continuity?.threads]]) {
|
|
204
|
+
for (const entity of Array.isArray(list) ? list.slice(-20) : []) {
|
|
205
|
+
map.set(`continuity:${kind}:${entity.id}`, {
|
|
206
|
+
...entity, sourceType: kind,
|
|
207
|
+
sourceUpdatedAt: Math.max(0, Number(entity.updatedAt) || 0),
|
|
208
|
+
})
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
for (const goal of Array.isArray(mind?.goals) ? mind.goals.slice(-20) : []) {
|
|
212
|
+
map.set(`mind:goal:${goal.id}`, {
|
|
213
|
+
...goal, sourceType: 'goal', sourceUpdatedAt: Math.max(0, Number(goal.updatedAt) || 0),
|
|
214
|
+
})
|
|
215
|
+
}
|
|
216
|
+
return map
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function dueRank(entity, now) {
|
|
220
|
+
const due = Number(entity?.dueAt) || 0
|
|
221
|
+
if (!due) return 5
|
|
222
|
+
const delta = due - now
|
|
223
|
+
if (delta < 0) return 0
|
|
224
|
+
if (delta <= 6 * 3600000) return 1
|
|
225
|
+
if (delta <= 36 * 3600000) return 2
|
|
226
|
+
return 3
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function stepsFor(entity, type) {
|
|
230
|
+
if (type === 'rest') return [{ label: text(entity.nextStep, 120) || '先休息一下', kind: 'rest', status: 'active', evidence: '' }]
|
|
231
|
+
if (type === 'goal' || type === 'thread') {
|
|
232
|
+
return [
|
|
233
|
+
{ label: `复盘:${text(entity.title, 100)}`, kind: 'review', status: 'active', evidence: '' },
|
|
234
|
+
{ label: entity.nextStep ? `下一步:${text(entity.nextStep, 120)}` : '等待真实进展', kind: 'wait', status: 'pending', evidence: '' },
|
|
235
|
+
]
|
|
236
|
+
}
|
|
237
|
+
if (type === 'interest' || type === 'relationship') {
|
|
238
|
+
return [
|
|
239
|
+
{ label: `想一想:${text(entity.title, 100)}`, kind: 'review', status: 'active', evidence: '' },
|
|
240
|
+
{ label: '放回心里,不急着说', kind: 'wait', status: 'pending', evidence: '' },
|
|
241
|
+
]
|
|
242
|
+
}
|
|
243
|
+
return [
|
|
244
|
+
{ label: '等待合适时机', kind: 'wait', status: 'active', evidence: '' },
|
|
245
|
+
{ label: '完成后再确认', kind: 'confirm', status: 'pending', evidence: '' },
|
|
246
|
+
]
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function candidateForEntity(entity, sourceKey, now) {
|
|
250
|
+
const type = entity.sourceType
|
|
251
|
+
if (type === 'goal' && entity.status !== 'active') return null
|
|
252
|
+
if (type === 'goal' && entity.scope && !['virtual', 'local'].includes(entity.scope)) return null
|
|
253
|
+
if (['task', 'commitment'].includes(type) && !['open', 'paused'].includes(entity.status)) return null
|
|
254
|
+
if (type === 'thread' && entity.status !== 'active') return null
|
|
255
|
+
const due = dueRank(entity, now)
|
|
256
|
+
const dueAt = Math.max(0, Number(entity.dueAt) || 0)
|
|
257
|
+
let score = type === 'commitment' ? 64 : type === 'task' ? 58 : type === 'thread' ? 62 : 54
|
|
258
|
+
if (due === 0) score += 26
|
|
259
|
+
else if (due === 1) score += 18
|
|
260
|
+
else if (due === 2) score += 8
|
|
261
|
+
if (type === 'thread') score += Math.max(0, 100 - (Number(entity.progress) || 0)) * 0.08
|
|
262
|
+
if (entity.nextStep) score += 4
|
|
263
|
+
if (entity.personId) score += 3
|
|
264
|
+
if (type === 'goal' && Number(entity.progress) > 70) score += 3
|
|
265
|
+
const cost = type === 'task' ? 1 : type === 'commitment' ? 2 : type === 'thread' ? 3 : 2
|
|
266
|
+
score -= cost * 4
|
|
267
|
+
return {
|
|
268
|
+
id: `agc-${sourceKey.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 48)}`,
|
|
269
|
+
sourceKey,
|
|
270
|
+
sourceId: text(entity.id, 120),
|
|
271
|
+
sourceType: type,
|
|
272
|
+
scope: ['virtual', 'local'].includes(entity.scope) ? entity.scope : '',
|
|
273
|
+
title: text(entity.title, 120),
|
|
274
|
+
detail: text(entity.detail, 180),
|
|
275
|
+
nextStep: text(entity.nextStep, 160),
|
|
276
|
+
dueAt,
|
|
277
|
+
dueLabel: dueAt ? (due === 0 ? '已经逾期' : due === 1 ? '今天到期' : due === 2 ? '这两天到期' : '有期限') : '',
|
|
278
|
+
sourceUpdatedAt: Math.max(0, Number(entity.sourceUpdatedAt || entity.updatedAt) || 0),
|
|
279
|
+
expiresAt: 0,
|
|
280
|
+
priority: type === 'commitment' ? 80 : type === 'task' ? 70 : type === 'thread' ? 72 : 60,
|
|
281
|
+
score: clamp(score, 0, 100, 50),
|
|
282
|
+
cost,
|
|
283
|
+
risk: 0,
|
|
284
|
+
steps: stepsFor(entity, type),
|
|
285
|
+
stepIndex: 0,
|
|
286
|
+
progress: clamp(entity.progress, 0, 100, 0),
|
|
287
|
+
reason: dueAt ? '有实际截止时间' : (entity.nextStep ? '有明确下一步' : '还没完成'),
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Pure candidates from persisted sources; no invented people/places/weather. */
|
|
292
|
+
export function buildAgencyCandidates({ now = Date.now(), continuity, mind, vitality = {}, affect = {}, events = [] } = {}) {
|
|
293
|
+
const map = sourceMap(continuity, mind)
|
|
294
|
+
const out = []
|
|
295
|
+
const needAt = Math.max(0, Number(continuity?.needs?.updatedAt) || 0)
|
|
296
|
+
const affectAt = Math.max(0, Number(affect?.lastEventAt) || 0)
|
|
297
|
+
for (const [sourceKey, entity] of map) {
|
|
298
|
+
const candidate = candidateForEntity(entity, sourceKey, now)
|
|
299
|
+
if (candidate && candidate.title) out.push(candidate)
|
|
300
|
+
}
|
|
301
|
+
if (Number(vitality.energy) < 45) {
|
|
302
|
+
out.push({
|
|
303
|
+
id: 'agc-need-energy', sourceKey: 'needs:energy', sourceId: 'energy', sourceType: 'rest',
|
|
304
|
+
title: '给自己留点空隙', detail: '精力偏低', nextStep: '先休息一下,别硬撑',
|
|
305
|
+
dueAt: 0, dueLabel: '', sourceUpdatedAt: needAt, expiresAt: 0,
|
|
306
|
+
priority: 55, score: 56, cost: 1, risk: 0,
|
|
307
|
+
steps: [{ label: '先休息一下,别硬撑', kind: 'rest', status: 'active', evidence: '' }],
|
|
308
|
+
stepIndex: 0, progress: 0, reason: '精力偏低',
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
if (Number(affect.valence) < 35) {
|
|
312
|
+
out.push({
|
|
313
|
+
id: 'agc-need-mood', sourceKey: 'needs:mood', sourceId: 'mood', sourceType: 'rest',
|
|
314
|
+
title: '缓一缓', detail: '情绪偏低', nextStep: '不急着处理所有事',
|
|
315
|
+
dueAt: 0, dueLabel: '', sourceUpdatedAt: affectAt, expiresAt: 0,
|
|
316
|
+
priority: 50, score: 50, cost: 1, risk: 0,
|
|
317
|
+
steps: [{ label: '不急着处理所有事', kind: 'rest', status: 'active', evidence: '' }],
|
|
318
|
+
stepIndex: 0, progress: 0, reason: '情绪偏低',
|
|
319
|
+
})
|
|
320
|
+
}
|
|
321
|
+
if (Number(continuity?.needs?.stress) > 75) {
|
|
322
|
+
out.push({
|
|
323
|
+
id: 'agc-need-stress', sourceKey: 'needs:stress', sourceId: 'stress', sourceType: 'rest',
|
|
324
|
+
title: '松一口气', detail: '压力偏高', nextStep: '先把手头的事放一放',
|
|
325
|
+
dueAt: 0, dueLabel: '', sourceUpdatedAt: needAt,
|
|
326
|
+
expiresAt: 0, priority: 45, score: 48, cost: 1, risk: 0,
|
|
327
|
+
steps: [{ label: '先把手头的事放一放', kind: 'rest', status: 'active', evidence: '' }],
|
|
328
|
+
stepIndex: 0, progress: 0, reason: '压力偏高',
|
|
329
|
+
})
|
|
330
|
+
}
|
|
331
|
+
if (Number(continuity?.needs?.socialNeed) > 70) {
|
|
332
|
+
out.push({
|
|
333
|
+
id: 'agc-need-social', sourceKey: 'needs:social', sourceId: 'social', sourceType: 'relationship',
|
|
334
|
+
title: '想找人说说话', detail: '社交需求偏高', nextStep: '找合适的时机和人聊两句',
|
|
335
|
+
dueAt: 0, dueLabel: '', sourceUpdatedAt: needAt,
|
|
336
|
+
expiresAt: 0, priority: 45, score: 45, cost: 2, risk: 0,
|
|
337
|
+
steps: [{ label: '等一个不打扰人的时机', kind: 'wait', status: 'active', evidence: '' }],
|
|
338
|
+
stepIndex: 0, progress: 0, reason: '社交需求偏高',
|
|
339
|
+
})
|
|
340
|
+
}
|
|
341
|
+
for (const memory of Array.isArray(mind?.memories) ? mind.memories.slice(-8) : []) {
|
|
342
|
+
if (memory.kind !== 'promise' || memory.status !== 'active' || !memory.summary || sensitiveText.test(memory.summary)) continue
|
|
343
|
+
const sourceKey = `mind:promise:${memory.id}`
|
|
344
|
+
out.push({
|
|
345
|
+
id: `agc-${sourceKey.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 48)}`,
|
|
346
|
+
sourceKey, sourceId: text(memory.id, 120), sourceType: 'task',
|
|
347
|
+
title: `答应过:${text(memory.summary, 100)}`, detail: '一个明确的承诺',
|
|
348
|
+
nextStep: '', dueAt: 0, dueLabel: '', sourceUpdatedAt: Number(memory.updatedAt) || 0,
|
|
349
|
+
expiresAt: Number(memory.expiresAt) || (Number(memory.updatedAt) ? Number(memory.updatedAt) + 7 * 86400000 : 0), priority: 45, score: 45, cost: 1, risk: 0,
|
|
350
|
+
steps: [{ label: '等合适的时机兑现', kind: 'wait', status: 'active', evidence: '' }, { label: '兑现后再确认', kind: 'confirm', status: 'pending', evidence: '' }],
|
|
351
|
+
stepIndex: 0, progress: 0, reason: '明确承诺',
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
for (const person of Array.isArray(continuity?.people) ? continuity.people.slice(-12) : []) {
|
|
355
|
+
if (person.status !== 'active' || !person.notes || sensitiveText.test(person.notes) || Number(person.updatedAt) < now - 7 * 86400000) continue
|
|
356
|
+
const sourceKey = `relationship:${person.id}`
|
|
357
|
+
out.push({
|
|
358
|
+
id: `agc-${sourceKey.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 48)}`,
|
|
359
|
+
sourceKey, sourceId: text(person.id, 120), sourceType: 'relationship',
|
|
360
|
+
title: `想起${text(person.name, 40)}: ${text(person.notes, 100)}`, detail: '最近记录的关系',
|
|
361
|
+
nextStep: '', dueAt: 0, dueLabel: '', sourceUpdatedAt: Number(person.updatedAt) || 0,
|
|
362
|
+
expiresAt: Number(person.updatedAt) ? Number(person.updatedAt) + 3 * 86400000 : 0, priority: 35, score: 42, cost: 1, risk: 0,
|
|
363
|
+
steps: [{ label: `想一想:${text(person.name, 40)}`, kind: 'review', status: 'active', evidence: '' }, { label: '等自然的话题出现', kind: 'wait', status: 'pending', evidence: '' }],
|
|
364
|
+
stepIndex: 0, progress: 0, reason: '最近记录的关系',
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
// Persisted self preferences are low-priority interests, not requests for
|
|
368
|
+
// the user to do anything. TTL keeps them from becoming permanent clutter.
|
|
369
|
+
for (const pref of Array.isArray(mind?.preferences) ? mind.preferences.slice(-12) : []) {
|
|
370
|
+
if (pref.owner !== 'self' || pref.status !== 'active' || !pref.key || sensitiveText.test(`${pref.key} ${pref.value}`)) continue
|
|
371
|
+
const sourceKey = `mind:preference:${pref.id || pref.key}`
|
|
372
|
+
out.push({
|
|
373
|
+
id: `agc-${sourceKey.replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 48)}`,
|
|
374
|
+
sourceKey, sourceId: text(pref.id || pref.key, 120), sourceType: 'interest',
|
|
375
|
+
title: `想${text(pref.key, 60)}:${text(pref.value, 100)}`, detail: '自己的偏好',
|
|
376
|
+
nextStep: '', dueAt: 0, dueLabel: '', sourceUpdatedAt: Number(pref.updatedAt) || 0,
|
|
377
|
+
expiresAt: Number(pref.updatedAt) ? Number(pref.updatedAt) + 7 * 86400000 : 0, priority: 40, score: 40, cost: 1, risk: 0,
|
|
378
|
+
steps: [{ label: `想一想:${text(pref.key, 60)}`, kind: 'review', status: 'active', evidence: '' }, { label: '放回心里,不急着说', kind: 'wait', status: 'pending', evidence: '' }],
|
|
379
|
+
stepIndex: 0, progress: 0, reason: '自己的偏好',
|
|
380
|
+
})
|
|
381
|
+
}
|
|
382
|
+
// A persisted recent event can become a quiet reflection candidate. It is
|
|
383
|
+
// intentionally low priority and expires quickly; it never invents details.
|
|
384
|
+
for (const event of Array.isArray(events) ? events.slice(-4) : []) {
|
|
385
|
+
const summary = text(event?.summary || event?.reason || event?.text, 120)
|
|
386
|
+
if (!summary || !event?.id || sensitiveText.test(summary)) continue
|
|
387
|
+
const at = Math.max(0, Number(event.at) || now)
|
|
388
|
+
out.push({
|
|
389
|
+
id: `agc-event-${String(event.id).replace(/[^a-zA-Z0-9_-]/g, '-').slice(0, 40)}`,
|
|
390
|
+
sourceKey: `event:${event.id}`, sourceId: text(event.id, 120), sourceType: 'interest',
|
|
391
|
+
title: `想起:${summary}`, detail: '最近落盘的经历', nextStep: '', dueAt: 0, dueLabel: '',
|
|
392
|
+
sourceUpdatedAt: at, expiresAt: at + 24 * 3600000, priority: 35, score: 38, cost: 1, risk: 0,
|
|
393
|
+
steps: [{ label: '想一想这段经历', kind: 'review', status: 'active', evidence: '' }, { label: '只是想一想,不急着说', kind: 'wait', status: 'pending', evidence: '' }],
|
|
394
|
+
stepIndex: 0, progress: 0, reason: '近期经历',
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
return out.filter((x) => !x.expiresAt || x.expiresAt > now).sort((a, b) => b.score - a.score || a.sourceKey.localeCompare(b.sourceKey)).slice(0, AGENCY_LIMITS.candidates)
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function stable(value) {
|
|
401
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`
|
|
402
|
+
if (value && typeof value === 'object') return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stable(value[key])}`).join(',')}}`
|
|
403
|
+
return JSON.stringify(value)
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function mergeSteps(existing = [], incoming = []) {
|
|
407
|
+
return incoming.map((step, i) => {
|
|
408
|
+
const old = existing[i]
|
|
409
|
+
if (old && (old.status === 'done' || old.status === 'skipped')) {
|
|
410
|
+
return { ...step, label: old.label, status: old.status, evidence: old.evidence }
|
|
411
|
+
}
|
|
412
|
+
if (old && old.status === 'active' && step.status === 'pending') return { ...step, status: 'active' }
|
|
413
|
+
return { ...step }
|
|
414
|
+
})
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function advanceProgress(steps, evidence, now) {
|
|
418
|
+
// A review step is the safe internal action. Do not advance a waiting step
|
|
419
|
+
// before that review has actually been recorded.
|
|
420
|
+
if (steps.some((x) => x.kind === 'review' && x.status !== 'done')) return { steps, stepIndex: 0 }
|
|
421
|
+
const index = steps.findIndex((x) => x.status === 'active' && x.kind !== 'review')
|
|
422
|
+
if (index < 0) return { steps, stepIndex: 0 }
|
|
423
|
+
const updated = steps.map((x, i) => i === index ? { ...x, status: 'done', evidence } : x)
|
|
424
|
+
const next = updated[index + 1]
|
|
425
|
+
if (next && next.status === 'pending') next.status = 'active'
|
|
426
|
+
return { steps: updated, stepIndex: Math.min(updated.length - 1, index + 1) }
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function executeReview(state, focus, now) {
|
|
430
|
+
if (!focus || !['goal', 'thread', 'interest', 'relationship'].includes(focus.sourceType)) return false
|
|
431
|
+
if (focus.lastReviewAt && now - focus.lastReviewAt < AGENCY_LIMITS.reviewIntervalMs) return false
|
|
432
|
+
const index = focus.steps.findIndex((x) => x.kind === 'review' && x.status !== 'done')
|
|
433
|
+
if (index < 0) return false
|
|
434
|
+
const evidence = `内部复盘:${focus.title}${focus.nextStep ? `,下一步仍是 ${focus.nextStep}` : ''};没有外部事实,不记为完成。`
|
|
435
|
+
focus.steps = focus.steps.map((x, i) => i === index ? { ...x, status: 'done', evidence } : x)
|
|
436
|
+
const next = focus.steps[index + 1]
|
|
437
|
+
if (next && next.status === 'pending') next.status = 'active'
|
|
438
|
+
focus.stepIndex = Math.min(focus.steps.length - 1, index + 1)
|
|
439
|
+
focus.lastReviewAt = now
|
|
440
|
+
focus.lastActionAt = now
|
|
441
|
+
if (focus.pendingProgress) {
|
|
442
|
+
const advanced = advanceProgress(focus.steps, focus.pendingProgress, now)
|
|
443
|
+
focus.steps = advanced.steps
|
|
444
|
+
focus.stepIndex = Math.max(focus.stepIndex, advanced.stepIndex)
|
|
445
|
+
focus.pendingProgress = ''
|
|
446
|
+
}
|
|
447
|
+
focus.reason = '内部复盘完成,等待真实进展'
|
|
448
|
+
focus.internalPlan = {
|
|
449
|
+
at: now,
|
|
450
|
+
nextAction: focus.nextStep || '等待真实进展',
|
|
451
|
+
evidence,
|
|
452
|
+
}
|
|
453
|
+
state.executions.push({ at: now, sourceKey: focus.sourceKey, action: 'review', evidence })
|
|
454
|
+
state.executions = state.executions.slice(-AGENCY_LIMITS.executions)
|
|
455
|
+
return true
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
function deferFocus(state, focus, now, reason) {
|
|
459
|
+
const attempts = focus.attempts + 1
|
|
460
|
+
if (attempts >= 3) {
|
|
461
|
+
state.abandoned.push({
|
|
462
|
+
sourceKey: focus.sourceKey, at: now, reason: reason || '反复被推迟',
|
|
463
|
+
lastSourceUpdatedAt: focus.sourceUpdatedAt || 0,
|
|
464
|
+
})
|
|
465
|
+
state.abandoned = state.abandoned.slice(-AGENCY_LIMITS.abandoned)
|
|
466
|
+
state.recent.push({ at: now, sourceKey: focus.sourceKey, title: focus.title, status: 'abandoned' })
|
|
467
|
+
state.recent = state.recent.slice(-AGENCY_LIMITS.recent)
|
|
468
|
+
return { abandoned: true }
|
|
469
|
+
}
|
|
470
|
+
state.deferred.push({
|
|
471
|
+
sourceKey: focus.sourceKey, until: now + AGENCY_LIMITS.deferMs, attempts,
|
|
472
|
+
reason: reason || '暂时推迟', lastSourceUpdatedAt: focus.sourceUpdatedAt || 0,
|
|
473
|
+
})
|
|
474
|
+
state.deferred = state.deferred.slice(-AGENCY_LIMITS.deferred)
|
|
475
|
+
return { deferred: true }
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function pruneDeferred(state, candidates, now) {
|
|
479
|
+
const byKey = new Map(candidates.map((x) => [x.sourceKey, x]))
|
|
480
|
+
let changed = false
|
|
481
|
+
const remaining = []
|
|
482
|
+
for (const item of state.deferred) {
|
|
483
|
+
const source = byKey.get(item.sourceKey)
|
|
484
|
+
if (item.until > now && !(source && source.sourceUpdatedAt > item.lastSourceUpdatedAt)) { remaining.push(item); continue }
|
|
485
|
+
changed = true
|
|
486
|
+
if (item.attempts >= 3) {
|
|
487
|
+
state.abandoned.push({
|
|
488
|
+
sourceKey: item.sourceKey, at: now, reason: '推迟次数用尽', lastSourceUpdatedAt: item.lastSourceUpdatedAt,
|
|
489
|
+
})
|
|
490
|
+
state.recent.push({ at: now, sourceKey: item.sourceKey, title: source?.title || item.sourceKey, status: 'abandoned' })
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
state.deferred = remaining.slice(-AGENCY_LIMITS.deferred)
|
|
494
|
+
state.abandoned = state.abandoned.slice(-AGENCY_LIMITS.abandoned)
|
|
495
|
+
state.recent = state.recent.slice(-AGENCY_LIMITS.recent)
|
|
496
|
+
return changed
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function isAbandoned(state, candidate) {
|
|
500
|
+
const row = state.abandoned.find((x) => x.sourceKey === candidate.sourceKey)
|
|
501
|
+
if (!row) return false
|
|
502
|
+
return !(candidate.sourceUpdatedAt > row.lastSourceUpdatedAt)
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function outreachFor(state, sourceKey) {
|
|
506
|
+
return state.outreach[sourceKey] || null
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function updateOutreachTimeouts(state, now) {
|
|
510
|
+
let changed = false
|
|
511
|
+
for (const [key, row] of Object.entries(state.outreach)) {
|
|
512
|
+
if (row.status === 'awaiting' && now - row.lastAt >= AGENCY_LIMITS.followupWaitMs) {
|
|
513
|
+
row.status = 'ignored'
|
|
514
|
+
row.nextAt = now + AGENCY_LIMITS.ignoredRetryMs
|
|
515
|
+
changed = true
|
|
516
|
+
} else if (row.status === 'ignored' && row.count >= 2 && now >= row.nextAt) {
|
|
517
|
+
row.status = 'declined'
|
|
518
|
+
row.nextAt = now
|
|
519
|
+
changed = true
|
|
520
|
+
}
|
|
521
|
+
if (!row.lastAt && !row.status) delete state.outreach[key]
|
|
522
|
+
}
|
|
523
|
+
return changed
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
function candidateAvailable(candidate, state, deferred, now) {
|
|
527
|
+
if (!candidate) return false
|
|
528
|
+
if (candidate.expiresAt && candidate.expiresAt <= now) return false
|
|
529
|
+
if (isAbandoned(state, candidate)) return false
|
|
530
|
+
const blocked = deferred.get(candidate.sourceKey)
|
|
531
|
+
if (!blocked) return true
|
|
532
|
+
if (blocked.attempts >= 3) return false
|
|
533
|
+
if (blocked.until > now && !(candidate.sourceUpdatedAt > blocked.lastSourceUpdatedAt)) return false
|
|
534
|
+
return true
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function reconcileSharingOutreach(state, rows, now) {
|
|
538
|
+
let changed = false
|
|
539
|
+
for (const row of Array.isArray(rows) ? rows : []) {
|
|
540
|
+
const sourceKey = text(row?.sourceKey, 160)
|
|
541
|
+
const stageKey = text(row?.stageKey, 180)
|
|
542
|
+
const at = Math.max(0, Number(row?.at) || 0)
|
|
543
|
+
if (!sourceKey || !stageKey || !at || String(row?.kind || '') !== 'followup') continue
|
|
544
|
+
const previous = state.outreach[sourceKey]
|
|
545
|
+
if (previous && previous.lastStage === stageKey) {
|
|
546
|
+
if (!previous.sessionId && row.sessionId) {
|
|
547
|
+
previous.sessionId = text(row.sessionId, 120)
|
|
548
|
+
previous.topic = text(row.title, 160)
|
|
549
|
+
changed = true
|
|
550
|
+
}
|
|
551
|
+
continue
|
|
552
|
+
}
|
|
553
|
+
if (previous && previous.lastAt >= at) continue
|
|
554
|
+
state.outreach[sourceKey] = {
|
|
555
|
+
lastAt: at,
|
|
556
|
+
count: Math.max(1, Number(previous?.count) || 0) + (previous ? 1 : 0),
|
|
557
|
+
status: 'awaiting',
|
|
558
|
+
lastStage: stageKey,
|
|
559
|
+
lastSourceUpdatedAt: Math.max(0, Number(previous?.lastSourceUpdatedAt) || 0, Number(row?.sourceUpdatedAt) || 0),
|
|
560
|
+
nextAt: 0,
|
|
561
|
+
sessionId: text(row?.sessionId, 120),
|
|
562
|
+
topic: text(row?.title, 160),
|
|
563
|
+
}
|
|
564
|
+
changed = true
|
|
565
|
+
}
|
|
566
|
+
return changed
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
export function tickAgency(input = {}) {
|
|
570
|
+
const now = Number(input.now) || Date.now()
|
|
571
|
+
const result = withLock(agencyPath() + '.lock', () => {
|
|
572
|
+
const state = readAgency(now)
|
|
573
|
+
const candidates = buildAgencyCandidates({ ...input, now })
|
|
574
|
+
const map = sourceMap(input.continuity, input.mind, candidates)
|
|
575
|
+
const deferred = new Map(state.deferred.map((x) => [x.sourceKey, x]))
|
|
576
|
+
let changed = reconcileSharingOutreach(state, input.sharingRecent, now)
|
|
577
|
+
changed = updateOutreachTimeouts(state, now) || changed
|
|
578
|
+
|
|
579
|
+
// A new persisted fact reopens a previously abandoned source. It is not
|
|
580
|
+
// automatic forgiveness: a genuinely newer source revision is required.
|
|
581
|
+
state.abandoned = state.abandoned.filter((row) => {
|
|
582
|
+
const source = map.get(row.sourceKey)
|
|
583
|
+
if (source && Number(source.sourceUpdatedAt) > row.lastSourceUpdatedAt) {
|
|
584
|
+
state.recent.push({ at: now, sourceKey: row.sourceKey, title: source.title || row.sourceKey, status: 'reopened' })
|
|
585
|
+
changed = true
|
|
586
|
+
return false
|
|
587
|
+
}
|
|
588
|
+
return true
|
|
589
|
+
})
|
|
590
|
+
state.recent = state.recent.slice(-AGENCY_LIMITS.recent)
|
|
591
|
+
|
|
592
|
+
let focus = state.focus
|
|
593
|
+
if (focus) {
|
|
594
|
+
const source = map.get(focus.sourceKey)
|
|
595
|
+
const done = source && ['completed', 'cancelled', 'archived'].includes(source.status)
|
|
596
|
+
const paused = source && source.status === 'paused'
|
|
597
|
+
if (!source) {
|
|
598
|
+
state.recent.push({ at: now, sourceKey: focus.sourceKey, title: focus.title, status: 'closed' })
|
|
599
|
+
focus = null
|
|
600
|
+
changed = true
|
|
601
|
+
} else if (done) {
|
|
602
|
+
state.recent.push({ at: now, sourceKey: focus.sourceKey, title: focus.title, status: 'done' })
|
|
603
|
+
focus = null
|
|
604
|
+
changed = true
|
|
605
|
+
} else if (paused) {
|
|
606
|
+
deferFocus(state, focus, now, '来源暂停')
|
|
607
|
+
focus = null
|
|
608
|
+
changed = true
|
|
609
|
+
} else if (['rest', 'interest', 'relationship'].includes(focus.sourceType)) {
|
|
610
|
+
// Needs/interests/relationships are stable focus cards. They only
|
|
611
|
+
// close when their candidate/TTL disappears; they never auto-execute.
|
|
612
|
+
} else {
|
|
613
|
+
const next = candidateForEntity(source, focus.sourceKey, now)
|
|
614
|
+
if (next) {
|
|
615
|
+
const progressChanged = next.progress !== focus.progress
|
|
616
|
+
const steps = mergeSteps(focus.steps, next.steps)
|
|
617
|
+
const updated = {
|
|
618
|
+
...focus, ...next, steps, createdAt: focus.createdAt, attempts: focus.attempts,
|
|
619
|
+
lastReviewAt: focus.lastReviewAt, lastActionAt: focus.lastActionAt,
|
|
620
|
+
reason: focus.lastReviewAt ? focus.reason : next.reason,
|
|
621
|
+
updatedAt: progressChanged ? now : focus.updatedAt,
|
|
622
|
+
stepIndex: Math.max(focus.stepIndex, next.stepIndex),
|
|
623
|
+
}
|
|
624
|
+
if (progressChanged) {
|
|
625
|
+
const evidence = `来源进度 ${focus.progress}→${next.progress}`
|
|
626
|
+
const advanced = advanceProgress(updated.steps, evidence, now)
|
|
627
|
+
updated.steps = advanced.steps
|
|
628
|
+
updated.stepIndex = Math.max(updated.stepIndex, advanced.stepIndex)
|
|
629
|
+
updated.lastActionAt = now
|
|
630
|
+
if (updated.steps.some((x) => x.kind === 'review' && x.status !== 'done')) updated.pendingProgress = evidence
|
|
631
|
+
state.executions.push({ at: now, sourceKey: focus.sourceKey, action: 'observe-progress', evidence: `${evidence},只更新内部观察` })
|
|
632
|
+
state.executions = state.executions.slice(-AGENCY_LIMITS.executions)
|
|
633
|
+
}
|
|
634
|
+
if (stable(updated) !== stable(focus)) { focus = updated; changed = true }
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
let lowReviewed = false
|
|
640
|
+
if (focus && executeReview(state, focus, now)) {
|
|
641
|
+
changed = true
|
|
642
|
+
if (['interest', 'relationship'].includes(focus.sourceType)) {
|
|
643
|
+
state.recent.push({ at: now, sourceKey: focus.sourceKey, title: focus.title, status: 'reviewed' })
|
|
644
|
+
state.recent = state.recent.slice(-AGENCY_LIMITS.recent)
|
|
645
|
+
state.explored[focus.sourceKey] = now
|
|
646
|
+
focus = null
|
|
647
|
+
lowReviewed = true
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
if (!focus && !lowReviewed) {
|
|
652
|
+
const available = candidates.filter((c) => candidateAvailable(c, state, deferred, now))
|
|
653
|
+
let best = available.find((c) => c.score >= 50)
|
|
654
|
+
if (!best) {
|
|
655
|
+
// Low-priority interests/relationships/events become reachable only
|
|
656
|
+
// after a deterministic exploration cooldown, never by randomness.
|
|
657
|
+
best = available.filter((c) => c.score >= 35).find((c) => {
|
|
658
|
+
const seen = Number(state.explored[c.sourceKey]) || 0
|
|
659
|
+
return !seen || now - seen >= 6 * 3600000
|
|
660
|
+
})
|
|
661
|
+
}
|
|
662
|
+
if (best) {
|
|
663
|
+
const blocked = deferred.get(best.sourceKey)
|
|
664
|
+
focus = {
|
|
665
|
+
...best, status: 'active', createdAt: now, updatedAt: now,
|
|
666
|
+
lastReviewAt: 0, lastActionAt: 0,
|
|
667
|
+
attempts: Math.max(0, Number(blocked?.attempts) || 0),
|
|
668
|
+
}
|
|
669
|
+
if (Number(best.score) < 50) state.explored[best.sourceKey] = now
|
|
670
|
+
state.deferred = state.deferred.filter((x) => x.sourceKey !== best.sourceKey)
|
|
671
|
+
state.focus = focus
|
|
672
|
+
changed = true
|
|
673
|
+
}
|
|
674
|
+
} else {
|
|
675
|
+
const available = candidates.filter((c) => candidateAvailable(c, state, deferred, now))
|
|
676
|
+
const best = available.find((c) => c.score >= 50 && c.score >= focus.score + 8 && c.sourceKey !== focus.sourceKey)
|
|
677
|
+
if (best && now - focus.updatedAt >= AGENCY_LIMITS.holdMs) {
|
|
678
|
+
deferFocus(state, focus, now, '更高优先级的当前事项')
|
|
679
|
+
const blocked = deferred.get(best.sourceKey)
|
|
680
|
+
focus = {
|
|
681
|
+
...best, status: 'active', createdAt: now, updatedAt: now,
|
|
682
|
+
lastReviewAt: 0, lastActionAt: 0,
|
|
683
|
+
attempts: Math.max(0, Number(blocked?.attempts) || 0),
|
|
684
|
+
}
|
|
685
|
+
state.deferred = state.deferred.filter((x) => x.sourceKey !== best.sourceKey)
|
|
686
|
+
state.focus = focus
|
|
687
|
+
changed = true
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
if (pruneDeferred(state, candidates, now)) changed = true
|
|
692
|
+
// Remove outreach rows whose source vanished or completed.
|
|
693
|
+
for (const key of Object.keys(state.outreach)) {
|
|
694
|
+
const source = map.get(key)
|
|
695
|
+
if (source && ['completed', 'cancelled', 'archived'].includes(source.status)) { delete state.outreach[key]; changed = true }
|
|
696
|
+
}
|
|
697
|
+
state.abandoned = state.abandoned.slice(-AGENCY_LIMITS.abandoned)
|
|
698
|
+
state.recent = state.recent.slice(-AGENCY_LIMITS.recent)
|
|
699
|
+
state.explored = Object.fromEntries(Object.entries(state.explored || {}).slice(-AGENCY_LIMITS.recent))
|
|
700
|
+
state.updatedAt = now
|
|
701
|
+
state.focus = focus
|
|
702
|
+
if (changed) writeAgency(state, now)
|
|
703
|
+
return { state, focus, candidates, changed }
|
|
704
|
+
}, { staleMs: 5000 })
|
|
705
|
+
if (result) return result
|
|
706
|
+
// Another process may hold the lock for a few milliseconds. Wait briefly so
|
|
707
|
+
// a concurrent tick reports the same focus instead of a transient null.
|
|
708
|
+
for (let i = 0; i < 20; i++) {
|
|
709
|
+
const current = readAgency(now)
|
|
710
|
+
if (current.focus) return { state: current, focus: current.focus, candidates: [], changed: false }
|
|
711
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10)
|
|
712
|
+
}
|
|
713
|
+
const current = readAgency(now)
|
|
714
|
+
return { state: current, focus: current.focus, candidates: [], changed: false }
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
export function agencyContext(focus) {
|
|
718
|
+
if (!focus || !focus.title) return ''
|
|
719
|
+
const due = focus.dueLabel ? `,${focus.dueLabel}` : ''
|
|
720
|
+
const nextAction = focus.nextStep || focus.internalPlan?.nextAction || ''
|
|
721
|
+
const next = nextAction ? `,下一步:${nextAction}` : ''
|
|
722
|
+
return `(心里在推进)${focus.title}${due}${next}。这是内部计划,只有实际发生才算完成,不要凭空说已经做了。`
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** A proactive pending follow-up; never a completed life fact. */
|
|
726
|
+
export function agencyShareCandidates(focus, options = {}) {
|
|
727
|
+
if (!focus || !focus.title || focus.sourceType === 'rest' || focus.sourceType === 'interest') return []
|
|
728
|
+
const now = Number(options.now) || Date.now()
|
|
729
|
+
const date = String(options.date || '')
|
|
730
|
+
if (!date) return []
|
|
731
|
+
const state = options.state || defaultAgency(now)
|
|
732
|
+
const out = outreachFor(state, focus.sourceKey)
|
|
733
|
+
const sourceUpdatedAt = Math.max(0, Number(focus.sourceUpdatedAt || 0))
|
|
734
|
+
if (out) {
|
|
735
|
+
if (out.status === 'declined' && sourceUpdatedAt <= out.lastSourceUpdatedAt) return []
|
|
736
|
+
if (out.status === 'responded' && sourceUpdatedAt <= out.lastSourceUpdatedAt) return []
|
|
737
|
+
if (out.status === 'awaiting' && now - out.lastAt < AGENCY_LIMITS.followupWaitMs) return []
|
|
738
|
+
if (out.status === 'ignored' && now < out.nextAt) return []
|
|
739
|
+
if (out.count >= 2 && sourceUpdatedAt <= out.lastSourceUpdatedAt) return []
|
|
740
|
+
if (sourceUpdatedAt > out.lastSourceUpdatedAt && now - out.lastAt < AGENCY_LIMITS.newFactWaitMs) return []
|
|
741
|
+
}
|
|
742
|
+
const urgent = Number(focus.dueAt) > 0 && focus.dueAt - now <= 36 * 3600000
|
|
743
|
+
const score = clamp(urgent ? 86 : focus.nextStep ? 84 : 76, 0, 100, 0)
|
|
744
|
+
if (score < 84) return []
|
|
745
|
+
const fact = focus.dueLabel
|
|
746
|
+
? `你之前记着「${focus.title}」,${focus.dueLabel}`
|
|
747
|
+
: `你心里还挂着「${focus.title}」,下一步是${focus.nextStep || '继续推进'}`
|
|
748
|
+
return [{
|
|
749
|
+
eventId: `agency:${focus.sourceKey}`,
|
|
750
|
+
stageKey: `agency:${focus.sourceKey}:${out?.count || 0}`,
|
|
751
|
+
kind: 'followup', category: `agency:${focus.sourceType}`,
|
|
752
|
+
title: focus.title, facts: [fact], tone: '关心', score,
|
|
753
|
+
followup: false, atMinute: options.nowMinute || 0, sourceKey: focus.sourceKey,
|
|
754
|
+
sessionId: text(options.sessionId, 120),
|
|
755
|
+
sourceUpdatedAt,
|
|
756
|
+
}]
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** Record a successful enqueue so the same pending source waits for a reply. */
|
|
760
|
+
export function markAgencyOutreach(candidate, options = {}) {
|
|
761
|
+
const now = Number(options.now) || Date.now()
|
|
762
|
+
const sourceKey = text(candidate?.sourceKey, 160)
|
|
763
|
+
if (!sourceKey) return { ok: false, reason: 'no-source' }
|
|
764
|
+
const result = withLock(agencyPath() + '.lock', () => {
|
|
765
|
+
const state = readAgency(now)
|
|
766
|
+
const focus = state.focus && state.focus.sourceKey === sourceKey ? state.focus : null
|
|
767
|
+
const previous = state.outreach[sourceKey]
|
|
768
|
+
state.outreach[sourceKey] = {
|
|
769
|
+
lastAt: now,
|
|
770
|
+
count: Math.max(0, Number(previous?.count) || 0) + 1,
|
|
771
|
+
status: 'awaiting',
|
|
772
|
+
lastStage: text(candidate.stageKey, 180),
|
|
773
|
+
lastSourceUpdatedAt: Math.max(0, Number(focus?.sourceUpdatedAt || candidate.sourceUpdatedAt) || 0),
|
|
774
|
+
nextAt: 0,
|
|
775
|
+
sessionId: text(options.sessionId, 120),
|
|
776
|
+
topic: text(options.topic || candidate.title, 160),
|
|
777
|
+
}
|
|
778
|
+
state.updatedAt = now
|
|
779
|
+
writeAgency(state, now)
|
|
780
|
+
return { ok: true, outreach: state.outreach[sourceKey] }
|
|
781
|
+
}, { staleMs: 5000 })
|
|
782
|
+
return result || { ok: false, reason: 'locked' }
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** Consume a human message: a reply clears the wait; a refusal suppresses. */
|
|
786
|
+
export function observeAgencyReply(value, options = {}) {
|
|
787
|
+
const now = Number(options.now) || Date.now()
|
|
788
|
+
const sessionId = text(options.sessionId, 120)
|
|
789
|
+
const replyTo = text(options.replyTo, 180)
|
|
790
|
+
const body = text(value, 400)
|
|
791
|
+
if (!sessionId) return { ok: false, changed: false, reason: 'no-session' }
|
|
792
|
+
const result = withLock(agencyPath() + '.lock', () => {
|
|
793
|
+
const state = readAgency(now)
|
|
794
|
+
const rows = Object.values(state.outreach)
|
|
795
|
+
.filter((row) => row.sessionId === sessionId)
|
|
796
|
+
.filter((row) => row.status === 'awaiting' || row.status === 'ignored')
|
|
797
|
+
.filter((row) => now - row.lastAt <= AGENCY_LIMITS.followupWaitMs)
|
|
798
|
+
.sort((a, b) => b.lastAt - a.lastAt)
|
|
799
|
+
let row = null
|
|
800
|
+
if (replyTo) {
|
|
801
|
+
// Explicit reference is the only reliable association.
|
|
802
|
+
row = rows.find((x) => x.lastStage === replyTo || x.topic === replyTo) || null
|
|
803
|
+
if (!row) return { ok: true, changed: false, reason: 'unassociated' }
|
|
804
|
+
} else {
|
|
805
|
+
// Otherwise require the text itself to point at the topic. An arbitrary
|
|
806
|
+
// same-session message is not evidence that the pending item was answered.
|
|
807
|
+
row = rows.find((x) => topicMatches(body, x)) || null
|
|
808
|
+
if (!row) {
|
|
809
|
+
// A short, strong refusal immediately after a single pending item can
|
|
810
|
+
// be treated as a refusal of that only item. It never touches siblings.
|
|
811
|
+
if (negativeReply.test(body)) {
|
|
812
|
+
const recent = rows.filter((x) => now - x.lastAt <= 10 * 60000)
|
|
813
|
+
if (recent.length === 1) row = recent[0]
|
|
814
|
+
}
|
|
815
|
+
if (!row) return { ok: true, changed: false, reason: 'unassociated' }
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
if (negativeReply.test(body)) {
|
|
819
|
+
row.status = 'declined'
|
|
820
|
+
row.nextAt = now
|
|
821
|
+
} else {
|
|
822
|
+
row.status = 'responded'
|
|
823
|
+
row.nextAt = 0
|
|
824
|
+
}
|
|
825
|
+
state.updatedAt = now
|
|
826
|
+
writeAgency(state, now)
|
|
827
|
+
return { ok: true, changed: true, sourceKey: row.lastStage || row.topic || '' }
|
|
828
|
+
}, { staleMs: 5000 })
|
|
829
|
+
return result || { ok: false, reason: 'locked' }
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** Production inbox adapter: only exposes a reply reference when payload has one. */
|
|
833
|
+
export function handleAgencyInboxReply(value, payload, sessionId, options = {}) {
|
|
834
|
+
return observeAgencyReply(value, {
|
|
835
|
+
...options,
|
|
836
|
+
sessionId,
|
|
837
|
+
replyTo: inboxReplyReference(payload),
|
|
838
|
+
})
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
export function agencyStatus(now = Date.now()) { return readAgency(now) }
|