@v587d/capital-generation 2.19.3 → 2.21.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.
@@ -0,0 +1,585 @@
1
+ /**
2
+ * TODO tracking. Briefs stay the source of truth; this service derives one watch per
3
+ * confirm/verify item, feeds the dedicated verifier task its candidate list, and applies the
4
+ * verdicts that task returns. No other task's final answer is treated as evidence.
5
+ */
6
+ import { createHash } from 'node:crypto'
7
+ import { isDeepStrictEqual } from 'node:util'
8
+
9
+ import { includesQuote, sourceBlocksOf } from './brief.js'
10
+ import { sanitizeMessage } from './redact.js'
11
+ import { localPartsAt } from './time.js'
12
+
13
+ export const TODO_WATCH_MAX_AGE_MS = 72 * 60 * 60_000
14
+ export const TODO_WATCH_TICK_MS = 5 * 60_000
15
+ /** Operational verifier tasks; only these receive the candidate list and return verdicts. */
16
+ export const TODO_VERIFIER_TASK_IDS = new Set(['todo-verifier-close'])
17
+ export const TODO_VERIFIER_MAX_TODOS = 30
18
+ const TODO_WATCH_EVIDENCE_CHARS = 160
19
+ const CONFIRM_HANDOFF = '请到看板 TODO 处理。'
20
+ const CONFIRM_AUTO_HANDOFF = '自动核验未能确认这条人工判断,需要你处理。'
21
+ const VERIFY_HANDOFF = '核验任务没有找到足够的同口径数据,需要你处理。'
22
+ const MISSING_HANDOFF = '本次核验没有返回这条的结论,需要你处理。'
23
+ const VERDICTS = new Set(['triggered', 'not_triggered', 'insufficient'])
24
+ const CONFIDENCE = new Set(['high', 'medium', 'low'])
25
+
26
+ function iso(now) {
27
+ return new Date(now).toISOString()
28
+ }
29
+
30
+ function timeZoneOf(value) {
31
+ if (typeof value === 'string' && value.length > 0) {
32
+ try {
33
+ new Intl.DateTimeFormat('en-US', { timeZone: value }).format(0)
34
+ return value
35
+ } catch {
36
+ // Fall through to the server zone.
37
+ }
38
+ }
39
+ try {
40
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai'
41
+ } catch {
42
+ return 'Asia/Shanghai'
43
+ }
44
+ }
45
+
46
+ function todoWatchId(profileKey, todoId) {
47
+ return `tw_${createHash('sha256').update(`${profileKey}\u0000${todoId}`).digest('hex').slice(0, 32)}`
48
+ }
49
+
50
+ function watchable(item, now, today, existing) {
51
+ if (item?.kind !== 'confirm' && item?.kind !== 'verify') return false
52
+ const seen = Date.parse(item.lastSeenAt)
53
+ if (!Number.isFinite(seen) || now - seen > TODO_WATCH_MAX_AGE_MS) return false
54
+ // Past-due items are not picked up retroactively; an existing watch still needs its handoff.
55
+ if (existing === undefined && item.kind === 'verify' && typeof item.dueAt === 'string' && item.dueAt < today) return false
56
+ return true
57
+ }
58
+
59
+ function cleanEvidence(value) {
60
+ if (typeof value !== 'string') return undefined
61
+ const text = value.replace(/\s+/g, ' ').trim()
62
+ if (text.length === 0) return undefined
63
+ return Array.from(text).slice(0, TODO_WATCH_EVIDENCE_CHARS).join('')
64
+ }
65
+
66
+ function cleanSource(value) {
67
+ if (typeof value !== 'string') return undefined
68
+ const text = value.replace(/\s+/g, ' ').trim()
69
+ if (text.length === 0) return undefined
70
+ return Array.from(text).slice(0, 300).join('')
71
+ }
72
+
73
+ function errorText(error) {
74
+ return sanitizeMessage(String(error?.message ?? error)).slice(0, 300)
75
+ }
76
+
77
+ export function isUsSymbol(symbol) {
78
+ if (typeof symbol !== 'string' || symbol.length === 0) return false
79
+ if (/\.(?:HK|SH|SZ|BJ)$/i.test(symbol)) return false
80
+ if (/\.(?:OQ|N|US|NYSE|NASDAQ)$/i.test(symbol)) return true
81
+ // Bare tickers (CRWV, NVDA, BABA) are US; A/H codes are digits or carry an exchange suffix.
82
+ return /^[A-Za-z][A-Za-z.\-]*$/.test(symbol)
83
+ }
84
+
85
+ /** A user decision covers only the version the user saw, exactly like `todo_acks`. */
86
+ function decisionCovers(decision, lastSeenAt) {
87
+ if (decision === undefined) return false
88
+ const decidedAt = Date.parse(decision.confirmedAt)
89
+ const seenAt = Date.parse(lastSeenAt)
90
+ if (!Number.isFinite(decidedAt) || !Number.isFinite(seenAt)) return true
91
+ return seenAt <= decidedAt
92
+ }
93
+
94
+ /**
95
+ * Validate the verifier's result block against the evidence text it claims to quote. A quote
96
+ * that exists in neither the tool output nor the final answer is a fabrication and is dropped.
97
+ */
98
+ export function parseWatchOutput(raw, { todos, blocks, sourceText }) {
99
+ let text = String(raw ?? '').trim()
100
+ const fences = [...text.matchAll(/```(?:json)?\s*([\s\S]*?)\s*```/gi)]
101
+ if (fences.length > 0) {
102
+ text = fences.at(-1)[1].trim()
103
+ } else {
104
+ // A verifier may wrap the JSON in a short prose preamble; keep the outermost object.
105
+ const start = text.indexOf('{')
106
+ const end = text.lastIndexOf('}')
107
+ if (start >= 0 && end > start) text = text.slice(start, end + 1)
108
+ }
109
+ let value
110
+ try {
111
+ value = JSON.parse(text)
112
+ } catch {
113
+ return []
114
+ }
115
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return []
116
+ const byId = new Map((Array.isArray(todos) ? todos : []).map((todo) => [todo.id, todo]))
117
+ const blockList = Array.isArray(blocks) ? blocks : []
118
+ const results = []
119
+ const seen = new Set()
120
+ for (const entry of Array.isArray(value.results) ? value.results : []) {
121
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue
122
+ if (typeof entry.id !== 'string' || !byId.has(entry.id) || seen.has(entry.id)) continue
123
+ if (!VERDICTS.has(entry.verdict)) continue
124
+ const sourceId = Number(entry.sourceId)
125
+ const block = Number.isInteger(sourceId) && sourceId >= 1 && sourceId <= blockList.length
126
+ ? blockList[sourceId - 1]
127
+ : undefined
128
+ const evidence = cleanEvidence(entry.evidence)
129
+ if (evidence === undefined) continue
130
+ if (!(block !== undefined && includesQuote(block.text, evidence)) && !includesQuote(sourceText, evidence)) continue
131
+ const confidence = CONFIDENCE.has(entry.confidence) ? entry.confidence : 'low'
132
+ const verdict = (entry.verdict === 'triggered' || entry.verdict === 'not_triggered') && confidence === 'low'
133
+ ? 'insufficient'
134
+ : entry.verdict
135
+ seen.add(entry.id)
136
+ results.push({
137
+ id: entry.id,
138
+ verdict,
139
+ confidence,
140
+ evidence,
141
+ source: cleanSource(entry.source),
142
+ })
143
+ }
144
+ return results
145
+ }
146
+
147
+ export function createTodoWatchService(options) {
148
+ const { store, board, now = () => Date.now(), logger, getSettings, readAnswer } = options
149
+ const profileKey = store.profileKey
150
+ const timeZone = timeZoneOf(options.timeZone)
151
+ let chain = Promise.resolve()
152
+ let timer
153
+ let stopped = false
154
+
155
+ function settings() {
156
+ return typeof getSettings === 'function' ? getSettings() ?? {} : getSettings ?? {}
157
+ }
158
+
159
+ function owner() {
160
+ return typeof options.isOwner === 'function' ? options.isOwner() === true : true
161
+ }
162
+
163
+ function serialize(operation) {
164
+ const next = chain.then(operation, operation)
165
+ chain = next.then(() => {}, () => {})
166
+ return next
167
+ }
168
+
169
+ async function openTodos() {
170
+ if (board === undefined || typeof board.openTodos !== 'function') return []
171
+ return board.openTodos({ days: '14', tz: timeZone })
172
+ }
173
+
174
+ /** Explicit dates win; a "today" label expires at the end of the day it was written. */
175
+ function dueDateOf(item) {
176
+ if (typeof item.dueAt === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(item.dueAt)) return item.dueAt
177
+ const label = typeof item.dueLabel === 'string' ? item.dueLabel.trim() : ''
178
+ if (label !== '今天' && label !== '今日') return undefined
179
+ const seen = Date.parse(item.lastSeenAt)
180
+ return Number.isFinite(seen) ? localPartsAt(seen, timeZone).date : undefined
181
+ }
182
+
183
+ /** Distinguishes "checked and missed" from "never got a deadline-grade answer". */
184
+ function expiredReasonFor(existing, item, dueDate) {
185
+ if (item.kind === 'confirm') return 'not_confirmed'
186
+ const checkedAt = existing?.checkedAt === undefined ? NaN : Date.parse(existing.checkedAt)
187
+ const checkedDate = Number.isFinite(checkedAt) ? localPartsAt(checkedAt, timeZone).date : undefined
188
+ if (existing?.verdict === 'not_triggered' && checkedDate !== undefined && dueDate !== undefined && checkedDate >= dueDate) {
189
+ return 'not_triggered'
190
+ }
191
+ if (existing?.verdict === 'insufficient' || existing?.status === 'needs_human') return 'no_data'
192
+ return 'not_verified'
193
+ }
194
+
195
+ function buildWatch(existing, item, at, today, decision) {
196
+ const firstSeenAt = existing === undefined || Date.parse(item.lastSeenAt) < Date.parse(existing.firstSeenAt)
197
+ ? item.lastSeenAt
198
+ : existing.firstSeenAt
199
+ const reopened = existing !== undefined
200
+ && (existing.status === 'resolved' || existing.status === 'expired')
201
+ && Date.parse(item.lastSeenAt) > Date.parse(existing.lastSeenAt)
202
+ const covered = decisionCovers(decision, item.lastSeenAt)
203
+ let status = existing?.status ?? (item.kind === 'confirm' ? 'needs_human' : 'watching')
204
+ let handoffReason = existing?.handoffReason
205
+ let resolvedFrom = existing?.resolvedFrom
206
+ let autoRequestedAt = existing?.autoRequestedAt
207
+ let expiredReason = existing?.expiredReason
208
+ const dueDate = dueDateOf(item)
209
+ if (reopened) {
210
+ status = item.kind === 'confirm' ? 'needs_human' : 'watching'
211
+ handoffReason = undefined
212
+ resolvedFrom = undefined
213
+ expiredReason = undefined
214
+ }
215
+ if (autoRequestedAt !== undefined && status !== 'triggered' && status !== 'resolved') {
216
+ status = 'watching'
217
+ handoffReason = undefined
218
+ }
219
+ if (covered) {
220
+ status = 'resolved'
221
+ handoffReason = undefined
222
+ autoRequestedAt = undefined
223
+ expiredReason = undefined
224
+ if (existing !== undefined && existing.status !== 'resolved') resolvedFrom = existing.status
225
+ }
226
+ if (item.kind === 'confirm' && (status === 'watching' || status === 'needs_human') && autoRequestedAt === undefined) {
227
+ status = 'needs_human'
228
+ if (handoffReason === undefined) handoffReason = CONFIRM_HANDOFF
229
+ }
230
+ if (dueDate !== undefined && dueDate < today && status !== 'triggered' && status !== 'resolved') {
231
+ status = 'expired'
232
+ handoffReason = undefined
233
+ autoRequestedAt = undefined
234
+ if (expiredReason === undefined) expiredReason = expiredReasonFor(existing, item, dueDate)
235
+ }
236
+ if (status !== 'expired') expiredReason = undefined
237
+ if (status !== 'needs_human') handoffReason = undefined
238
+ const next = {
239
+ schemaVersion: 1,
240
+ id: existing?.id ?? todoWatchId(profileKey, item.id),
241
+ profileKey,
242
+ todoId: item.id,
243
+ kind: item.kind,
244
+ status,
245
+ title: item.title,
246
+ ...(item.detail === undefined ? {} : { detail: item.detail }),
247
+ ...(item.symbol === undefined ? {} : { symbol: item.symbol }),
248
+ ...(item.trigger === undefined ? {} : { trigger: item.trigger }),
249
+ ...(item.dueAt === undefined ? {} : { dueAt: item.dueAt }),
250
+ firstSeenAt,
251
+ lastSeenAt: item.lastSeenAt,
252
+ ...(existing?.checkedAt === undefined || reopened ? {} : { checkedAt: existing.checkedAt }),
253
+ ...(autoRequestedAt === undefined ? {} : { autoRequestedAt }),
254
+ ...(expiredReason === undefined ? {} : { expiredReason }),
255
+ ...(existing?.verdict === undefined || reopened ? {} : { verdict: existing.verdict }),
256
+ ...(existing?.evidence === undefined || reopened ? {} : { evidence: existing.evidence }),
257
+ ...(existing?.source === undefined || reopened ? {} : { source: existing.source }),
258
+ ...(handoffReason === undefined ? {} : { handoffReason }),
259
+ ...(existing?.evidenceRunId === undefined || reopened ? {} : { evidenceRunId: existing.evidenceRunId }),
260
+ ...(existing?.evidenceSessionId === undefined || reopened ? {} : { evidenceSessionId: existing.evidenceSessionId }),
261
+ ...(resolvedFrom === undefined ? {} : { resolvedFrom }),
262
+ ...(reopened || existing?.notifiedAt === undefined ? {} : { notifiedAt: existing.notifiedAt }),
263
+ ...(reopened || existing?.notifiedStatus === undefined ? {} : { notifiedStatus: existing.notifiedStatus }),
264
+ createdAt: existing?.createdAt ?? at,
265
+ updatedAt: existing?.updatedAt ?? at,
266
+ }
267
+ if (isDeepStrictEqual(next, existing)) return undefined
268
+ return { ...next, updatedAt: at }
269
+ }
270
+
271
+ function expireMissing(existing, at, ackById) {
272
+ if (existing.status === 'resolved' || existing.status === 'expired') return undefined
273
+ const ack = ackById.get(existing.todoId)
274
+ if (ack !== undefined && Date.parse(ack.confirmedAt) >= Date.parse(existing.lastSeenAt)) {
275
+ const next = {
276
+ ...existing,
277
+ status: 'resolved',
278
+ ...(existing.status === 'resolved' ? {} : { resolvedFrom: existing.status }),
279
+ updatedAt: at,
280
+ }
281
+ delete next.autoRequestedAt
282
+ delete next.handoffReason
283
+ delete next.expiredReason
284
+ return isDeepStrictEqual(next, existing) ? undefined : next
285
+ }
286
+ // A triggered condition stays visible until the user acknowledges it.
287
+ if (existing.status === 'triggered') return undefined
288
+ const next = { ...existing, status: 'expired', expiredReason: 'stale', updatedAt: at }
289
+ delete next.autoRequestedAt
290
+ delete next.handoffReason
291
+ return isDeepStrictEqual(next, existing) ? undefined : next
292
+ }
293
+
294
+ async function syncInternal() {
295
+ if (!owner()) return
296
+ const at = iso(now())
297
+ const today = localPartsAt(now(), timeZone).date
298
+ const todos = await openTodos()
299
+ const acks = await store.listTodoAcks()
300
+ const ackById = new Map(acks.map((ack) => [ack.todoId, ack]))
301
+ const existing = await store.listTodoWatches()
302
+ const existingById = new Map(existing.map((record) => [record.todoId, record]))
303
+ const openIds = new Set()
304
+ for (const item of todos) {
305
+ const existingWatch = existingById.get(item.id)
306
+ if (!watchable(item, now(), today, existingWatch)) continue
307
+ openIds.add(item.id)
308
+ const next = buildWatch(existingWatch, item, at, today, ackById.get(item.id))
309
+ if (next !== undefined) await store.putTodoWatch(next)
310
+ }
311
+ for (const record of existing) {
312
+ if (openIds.has(record.todoId)) continue
313
+ const next = expireMissing(record, at, ackById)
314
+ if (next !== undefined) await store.putTodoWatch(next)
315
+ }
316
+ }
317
+
318
+ async function notifyPendingInternal() {
319
+ if (!owner()) return
320
+ const at = iso(now())
321
+ const enabled = settings().inAppNotifications !== false
322
+ const acks = await store.listTodoAcks()
323
+ const decisionById = new Map(acks.map((ack) => [ack.todoId, ack]))
324
+ for (const watch of await store.listTodoWatches()) {
325
+ if (watch.status !== 'triggered' && watch.status !== 'needs_human') continue
326
+ if (decisionCovers(decisionById.get(watch.todoId), watch.lastSeenAt)) continue
327
+ if (watch.notifiedStatus === watch.status) continue
328
+ // A disabled inbox or an item that has already aged out must not turn into a backlog
329
+ // notification the moment settings change. Mark it seen without sending.
330
+ const age = now() - Date.parse(watch.lastSeenAt)
331
+ const suppress = !enabled || (watch.kind === 'confirm' && age > TODO_WATCH_MAX_AGE_MS)
332
+ if (!suppress) {
333
+ const triggered = watch.status === 'triggered'
334
+ const prefix = triggered ? '已触发' : '待人工处理'
335
+ const message = triggered
336
+ ? [watch.evidence, watch.source].filter((value) => typeof value === 'string' && value.length > 0).join(' · ')
337
+ : watch.handoffReason ?? VERIFY_HANDOFF
338
+ await store.addNotification({
339
+ kind: triggered ? 'todo_triggered' : 'todo_needs_human',
340
+ title: `${prefix}:${watch.title}`.slice(0, 120),
341
+ message: sanitizeMessage(message).slice(0, 500),
342
+ todoId: watch.todoId,
343
+ ...(watch.evidenceRunId === undefined ? {} : { runId: watch.evidenceRunId }),
344
+ })
345
+ }
346
+ await store.putTodoWatch({
347
+ ...watch,
348
+ notifiedAt: at,
349
+ notifiedStatus: watch.status,
350
+ updatedAt: at,
351
+ })
352
+ }
353
+ }
354
+
355
+ async function sync() {
356
+ return serialize(async () => {
357
+ await syncInternal()
358
+ await notifyPendingInternal()
359
+ })
360
+ }
361
+
362
+ function isVerifierTask(task) {
363
+ return TODO_VERIFIER_TASK_IDS.has(task?.sourceBuiltinId)
364
+ }
365
+
366
+ async function candidateWatches(task) {
367
+ if (!isVerifierTask(task)) return []
368
+ const [watches, acks] = await Promise.all([store.listTodoWatches(), store.listTodoAcks()])
369
+ const decisionById = new Map(acks.map((ack) => [ack.todoId, ack]))
370
+ const today = localPartsAt(now(), timeZone).date
371
+ return watches
372
+ .filter((watch) => {
373
+ if (decisionCovers(decisionById.get(watch.todoId), watch.lastSeenAt)) return false
374
+ if (watch.kind !== 'verify' && watch.autoRequestedAt === undefined) return false
375
+ if (watch.status !== 'watching' && watch.status !== 'needs_human') return false
376
+ // Expired conditions are settled, not re-checked with post-deadline data.
377
+ if (typeof watch.dueAt === 'string' && watch.dueAt < today) return false
378
+ return !isUsSymbol(watch.symbol)
379
+ })
380
+ .sort((left, right) =>
381
+ (left.autoRequestedAt === undefined ? 1 : 0) - (right.autoRequestedAt === undefined ? 1 : 0)
382
+ || String(left.autoRequestedAt ?? '').localeCompare(String(right.autoRequestedAt ?? ''))
383
+ || String(left.dueAt ?? '9999-12-31').localeCompare(String(right.dueAt ?? '9999-12-31'))
384
+ || String(left.checkedAt ?? '').localeCompare(String(right.checkedAt ?? ''))
385
+ || String(right.lastSeenAt).localeCompare(String(left.lastSeenAt))
386
+ || left.todoId.localeCompare(right.todoId))
387
+ .slice(0, TODO_VERIFIER_MAX_TODOS)
388
+ }
389
+
390
+ async function hasCandidates(task) {
391
+ if (!isVerifierTask(task)) return true
392
+ return (await candidateWatches(task)).length > 0
393
+ }
394
+
395
+ function candidatePayload(watch) {
396
+ return {
397
+ id: watch.todoId,
398
+ title: watch.title,
399
+ ...(watch.detail === undefined ? {} : { detail: watch.detail }),
400
+ ...(watch.symbol === undefined ? {} : { symbol: watch.symbol }),
401
+ ...(watch.trigger === undefined ? {} : { trigger: watch.trigger }),
402
+ ...(watch.dueAt === undefined ? {} : { dueAt: watch.dueAt }),
403
+ kind: watch.kind,
404
+ status: watch.status,
405
+ lastSeenAt: watch.lastSeenAt,
406
+ }
407
+ }
408
+
409
+ async function promptContextFor(task) {
410
+ if (!isVerifierTask(task)) return undefined
411
+ const candidates = await candidateWatches(task)
412
+ const trigger = task?.trigger ?? {}
413
+ const header = [
414
+ `核验窗口:A 股/港股收盘后(交易日 ${trigger.time ?? '16:30'},${trigger.timezone ?? timeZone})`,
415
+ `当前时间:${iso(now())}`,
416
+ ]
417
+ if (candidates.length === 0) {
418
+ return {
419
+ text: `${header.join('\n')}\n\n本次没有待核验的 TODO。直接返回 {"results":[]},不要调用工具。`,
420
+ candidates: [],
421
+ empty: true,
422
+ }
423
+ }
424
+ return {
425
+ text: [
426
+ ...header,
427
+ `候选 TODO(共 ${candidates.length} 条,必须逐条返回):`,
428
+ JSON.stringify(candidates.map(candidatePayload), null, 2),
429
+ '输出要求:先写一句本次核验摘要,再输出一个 ```json 代码块:',
430
+ '{"results":[{"id":"候选 id","verdict":"triggered|not_triggered|insufficient","confidence":"high|medium|low","evidence":"工具结果中的原文片段","source":"来源 + as-of"}]}',
431
+ 'triggered / not_triggered 必须有可核验的工具原文;缺数据、只见到媒体转述、口径不一致或条件有歧义一律 insufficient。',
432
+ ].join('\n'),
433
+ candidates: candidates.map(candidatePayload),
434
+ empty: false,
435
+ }
436
+ }
437
+
438
+ async function applyVerifierAnswer(payload) {
439
+ if (!owner()) return
440
+ const { run, task, text, toolText } = payload
441
+ if (typeof text !== 'string' || text.trim().length === 0) return
442
+ await syncInternal()
443
+ const all = await store.listTodoWatches()
444
+ const acks = await store.listTodoAcks()
445
+ const decisionById = new Map(acks.map((ack) => [ack.todoId, ack]))
446
+ const snapshot = Array.isArray(run.verificationTodoIds) ? new Set(run.verificationTodoIds) : undefined
447
+ const candidates = all
448
+ .filter((watch) => (watch.kind === 'verify' || watch.autoRequestedAt !== undefined)
449
+ && (watch.status === 'watching' || watch.status === 'needs_human')
450
+ && !decisionCovers(decisionById.get(watch.todoId), watch.lastSeenAt)
451
+ && (snapshot === undefined || snapshot.has(watch.todoId)))
452
+ .sort((left, right) => String(left.todoId).localeCompare(String(right.todoId)))
453
+ if (candidates.length === 0) {
454
+ await notifyPendingInternal()
455
+ return
456
+ }
457
+ // Subagents keep their raw tool output in child sessions; the main answer is the compiled
458
+ // evidence record. Accept either source rather than rejecting every delegated lookup.
459
+ const evidenceText = [toolText, text]
460
+ .filter((value) => typeof value === 'string' && value.trim().length > 0)
461
+ .join('\n')
462
+ const blocks = sourceBlocksOf(evidenceText, Number.POSITIVE_INFINITY)
463
+ const todos = candidates.map(candidatePayload)
464
+ const results = parseWatchOutput(text, { todos, blocks, sourceText: evidenceText })
465
+ const resultById = new Map(results.map((result) => [result.id, result]))
466
+ const today = localPartsAt(now(), timeZone).date
467
+ const currentById = new Map((await store.listTodoWatches()).map((watch) => [watch.todoId, watch]))
468
+ const decisionByIdAtApply = new Map((await store.listTodoAcks()).map((ack) => [ack.todoId, ack]))
469
+ const at = iso(now())
470
+ for (const candidate of candidates) {
471
+ const current = currentById.get(candidate.todoId)
472
+ if (current === undefined) continue
473
+ if (current.kind !== 'verify' && current.autoRequestedAt === undefined) continue
474
+ if (current.status !== 'watching' && current.status !== 'needs_human') continue
475
+ if (decisionCovers(decisionByIdAtApply.get(current.todoId), current.lastSeenAt)) continue
476
+ const result = resultById.get(candidate.todoId)
477
+ const overdue = typeof current.dueAt === 'string' && current.dueAt < today
478
+ let status = current.status
479
+ let handoffReason
480
+ let expiredReason
481
+ if (result === undefined) {
482
+ if (overdue) {
483
+ status = 'expired'
484
+ expiredReason = 'no_data'
485
+ } else {
486
+ status = 'needs_human'
487
+ handoffReason = MISSING_HANDOFF
488
+ }
489
+ } else if (result.verdict === 'triggered') {
490
+ status = 'triggered'
491
+ } else if (result.verdict === 'not_triggered') {
492
+ if (overdue) {
493
+ status = 'expired'
494
+ expiredReason = current.kind === 'confirm' ? 'not_confirmed' : 'not_triggered'
495
+ } else if (current.kind === 'confirm') {
496
+ status = 'needs_human'
497
+ handoffReason = CONFIRM_AUTO_HANDOFF
498
+ } else {
499
+ status = 'watching'
500
+ }
501
+ } else if (overdue) {
502
+ status = 'expired'
503
+ expiredReason = 'no_data'
504
+ } else {
505
+ status = 'needs_human'
506
+ handoffReason = VERIFY_HANDOFF
507
+ }
508
+ const next = {
509
+ ...current,
510
+ status,
511
+ checkedAt: at,
512
+ verdict: result?.verdict ?? 'insufficient',
513
+ evidenceRunId: run.id,
514
+ ...(run.sessionId === undefined ? {} : { evidenceSessionId: run.sessionId }),
515
+ ...(handoffReason === undefined ? {} : { handoffReason }),
516
+ ...(expiredReason === undefined ? {} : { expiredReason }),
517
+ updatedAt: at,
518
+ }
519
+ // A promoted item gets one user-requested attempt; a failed one returns to manual before
520
+ // the deadline, and is archived once the deadline has passed.
521
+ delete next.autoRequestedAt
522
+ if (status !== 'expired') delete next.expiredReason
523
+ if (result?.evidence === undefined) delete next.evidence
524
+ else next.evidence = result.evidence
525
+ if (result?.source === undefined) delete next.source
526
+ else next.source = result.source
527
+ if (handoffReason === undefined) delete next.handoffReason
528
+ await store.putTodoWatch(next)
529
+ }
530
+ await notifyPendingInternal()
531
+ }
532
+
533
+ async function onFinalAnswer(payload) {
534
+ if (stopped || payload?.run?.status !== 'succeeded') return
535
+ if (!isVerifierTask(payload?.task)) return
536
+ return serialize(() => applyVerifierAnswer(payload)).catch((error) => {
537
+ logger?.warn?.(`capital-automation: TODO 核验结果处理失败:${errorText(error)}`)
538
+ })
539
+ }
540
+
541
+ async function onVerifierRun(payload) {
542
+ if (stopped || !isVerifierTask(payload?.task) || payload?.run?.status !== 'succeeded') return
543
+ if (typeof readAnswer !== 'function' || typeof payload.run.sessionId !== 'string') return
544
+ try {
545
+ const answer = await readAnswer(payload.run.sessionId)
546
+ await onFinalAnswer({ ...payload, text: answer.text, toolText: answer.toolText })
547
+ } catch (error) {
548
+ logger?.warn?.(`capital-automation: TODO 核验读取 session 失败:${errorText(error)}`)
549
+ }
550
+ }
551
+
552
+ function start() {
553
+ if (timer !== undefined || stopped) return
554
+ void sync().catch((error) => logger?.warn?.(`capital-automation: TODO 同步失败:${errorText(error)}`))
555
+ timer = setInterval(() => {
556
+ void sync().catch((error) => logger?.warn?.(`capital-automation: TODO 同步失败:${errorText(error)}`))
557
+ }, TODO_WATCH_TICK_MS)
558
+ timer.unref?.()
559
+ }
560
+
561
+ function stop() {
562
+ stopped = true
563
+ if (timer !== undefined) {
564
+ clearInterval(timer)
565
+ timer = undefined
566
+ }
567
+ }
568
+
569
+ async function flush() {
570
+ await chain
571
+ }
572
+
573
+ return {
574
+ onFinalAnswer,
575
+ onVerifierRun,
576
+ isVerifierTask,
577
+ promptContextFor,
578
+ hasCandidates,
579
+ sync,
580
+ flush,
581
+ start,
582
+ stop,
583
+ dispose: stop,
584
+ }
585
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-charts",
3
- "version": "2.19.3",
3
+ "version": "2.21.0",
4
4
  "description": "自动模式的图表前端组件(浏览器半边 + 序列旁路路由):由 @v587d/capital-generation 随包携带并作为 host 平面行挂载。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/config",
3
- "version": "2.19.3",
3
+ "version": "2.21.0",
4
4
  "description": "自动模式的取数凭据与偏好配置行:卡片坐在 @v587d/capital-generation 插件主页的「配置」段,点这一行本身没有表单。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -56,21 +56,23 @@ export function createChartDelivery(options) {
56
56
  return inboxMessages(inbox).every(isSettledNotice);
57
57
  };
58
58
  const flush = (session, turn, agent) => {
59
- // A later step in the same exchange may omit `turn`; it still must not write a second card.
60
- if (flushed)
61
- return;
62
59
  const inbox = options.inboxOf?.(session);
63
60
  reconcileSettled(inbox);
64
- if (!idle(inbox))
65
- return;
66
61
  // The wake guard drops notices that would otherwise make the loop open another step after
67
- // this answer. Run it even when no chart is selected, and never let it block delivery.
62
+ // this answer. It must run on every pure-text finish, including when a child is still marked
63
+ // running: a late settlement notice is exactly the race that adds a "nothing new" turn.
64
+ // Chart delivery stays gated on `idle` below; a guard failure must not strand a card.
68
65
  try {
69
66
  options.onClosing?.(session, agent, turn);
70
67
  }
71
68
  catch {
72
69
  // A guard failure must not strand an already-selected card.
73
70
  }
71
+ // A later step in the same exchange may omit `turn`; it still must not write a second card.
72
+ if (flushed)
73
+ return;
74
+ if (!idle(inbox))
75
+ return;
74
76
  const inputs = (explicit.length > 0 ? explicit : autoInputs(session)).slice(0, maxCharts);
75
77
  if (inputs.length === 0)
76
78
  return;
@@ -3,7 +3,7 @@
3
3
  * Known limit: DNS resolves per request but the IP is not pinned to the connection,
4
4
  * so a rebinding window remains (same trade-off as dsh-search-first).
5
5
  */
6
- export declare const LOCAL_FETCH_CLIENT_VERSION = "2.19.3";
6
+ export declare const LOCAL_FETCH_CLIENT_VERSION = "2.21.0";
7
7
  export declare const LOCAL_FETCH_MAX_URL_LENGTH = 2048;
8
8
  export type LocalFetchErrorCode = 'ABORTED' | 'TIMEOUT' | 'INVALID_URL' | 'BLOCKED_URL' | 'DNS' | 'REDIRECT' | 'HTTP' | 'TOO_LARGE' | 'UNSUPPORTED_CONTENT_TYPE';
9
9
  export declare class LocalFetchError extends Error {
@@ -4,7 +4,7 @@
4
4
  * so a rebinding window remains (same trade-off as dsh-search-first).
5
5
  */
6
6
  import { htmlToMarkdown, stripInvisibleText } from './html-markdown.js';
7
- export const LOCAL_FETCH_CLIENT_VERSION = '2.19.3';
7
+ export const LOCAL_FETCH_CLIENT_VERSION = '2.21.0';
8
8
  export const LOCAL_FETCH_MAX_URL_LENGTH = 2048;
9
9
  export class LocalFetchError extends Error {
10
10
  code;
@@ -35,7 +35,7 @@ export interface WindCallResult {
35
35
  code?: WindErrorCode;
36
36
  }
37
37
  /** Must match `package.json` version; a test pins the two together. */
38
- export declare const WIND_CLIENT_VERSION = "2.19.3";
38
+ export declare const WIND_CLIENT_VERSION = "2.21.0";
39
39
  export interface WindClient {
40
40
  callTool(toolName: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<WindCallResult>;
41
41
  }
@@ -19,7 +19,7 @@ export const WIND_SERVER_ENDPOINTS = {
19
19
  analytics_data: 'https://mcp.wind.com.cn/vserver_analytics_data/mcp/',
20
20
  };
21
21
  /** Must match `package.json` version; a test pins the two together. */
22
- export const WIND_CLIENT_VERSION = '2.19.3';
22
+ export const WIND_CLIENT_VERSION = '2.21.0';
23
23
  function errorText(error) {
24
24
  return error instanceof Error ? error.message : String(error);
25
25
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-generation",
3
- "version": "2.19.3",
3
+ "version": "2.21.0",
4
4
  "description": "Capital Generation:面向中国散户的 AI 投资助手插件(自动模式 Agent Preset)",
5
5
  "icon": "assets/cg-icon.png",
6
6
  "author": "v587d",