@v587d/capital-generation 2.16.1 → 2.17.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.
@@ -8,6 +8,8 @@ import { homedir } from 'node:os'
8
8
  import { join } from 'node:path'
9
9
 
10
10
  import { createRunRunner, buildRunPrompt, sessionTitleOf } from './runner.js'
11
+ import { createBriefService } from './brief.js'
12
+ import { createBoardService } from './board.js'
11
13
  import { createScheduler } from './scheduler.js'
12
14
  import { createAutomationService, AutomationError } from './service.js'
13
15
  import { createAutomationStore, domainSpec, ROUTE_PATH } from './store.js'
@@ -62,12 +64,14 @@ export function createAutomationRuntime(options) {
62
64
  calendar,
63
65
  settings: getSettings,
64
66
  })
67
+ let briefs
65
68
  const runner = createRunRunner({
66
69
  ctx,
67
70
  store,
68
71
  settings: getSettings,
69
72
  profile: { displayName, runDir },
70
73
  workspaces,
74
+ onRunSucceeded: (payload) => briefs?.onRunSucceeded(payload),
71
75
  now,
72
76
  logger,
73
77
  })
@@ -80,6 +84,18 @@ export function createAutomationRuntime(options) {
80
84
  now,
81
85
  logger,
82
86
  })
87
+ briefs = createBriefService({
88
+ ctx,
89
+ store,
90
+ scheduler,
91
+ now,
92
+ logger,
93
+ })
94
+ const boardService = createBoardService({
95
+ store,
96
+ scheduler,
97
+ now,
98
+ })
83
99
  const service = createAutomationService({
84
100
  store,
85
101
  scheduler,
@@ -89,6 +105,8 @@ export function createAutomationRuntime(options) {
89
105
  workspaces,
90
106
  version,
91
107
  settings: getSettings,
108
+ briefs,
109
+ boardService,
92
110
  now,
93
111
  })
94
112
  runner.installListeners()
@@ -97,7 +115,7 @@ export function createAutomationRuntime(options) {
97
115
  installAutomationPolicy({ ctx: toolsCtx, runner, logger })
98
116
  })
99
117
  }
100
- return { store, runner, scheduler, service, calendar, workspaces, profile: { displayName, runDir, ownerDir } }
118
+ return { store, runner, scheduler, briefs, service, calendar, workspaces, profile: { displayName, runDir, ownerDir } }
101
119
  }
102
120
 
103
121
  function authorizeFactory(ctx) {
@@ -158,12 +176,16 @@ export function apply(ctx) {
158
176
  })
159
177
  activeService = created.service
160
178
  created.scheduler.start()
161
- .then(() => logger?.info?.(`capital-automation: scheduler ${created.scheduler.status().state}`))
179
+ .then(() => {
180
+ created.briefs?.start()
181
+ logger?.info?.(`capital-automation: scheduler ${created.scheduler.status().state}`)
182
+ })
162
183
  .catch((error) => logger?.error?.(`capital-automation: scheduler 启动失败:${String(error)}`))
163
184
  appCtx.effect(() => async () => {
164
185
  if (activeService === created.service) {
165
186
  activeService = undefined
166
187
  }
188
+ await created.briefs?.stop?.()
167
189
  await created.scheduler.stop().catch(() => {})
168
190
  created.calendar.dispose?.()
169
191
  await created.runner.dispose?.()
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-automation",
3
- "version": "2.16.1",
3
+ "version": "2.17.0",
4
4
  "description": "CapGen 投研自动化:独立 host bundle(固定 capital_automation 域、单 scheduler owner、/capital-automation 路由与浏览器页面)。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -39,6 +39,8 @@
39
39
  "store.js",
40
40
  "service.js",
41
41
  "runner.js",
42
+ "brief.js",
43
+ "board.js",
42
44
  "scheduler.js",
43
45
  "workspaces.js",
44
46
  "contract.js",
@@ -121,12 +121,12 @@ function decodeId(raw) {
121
121
  return id
122
122
  }
123
123
 
124
- function queryOf(url, allowedKeys) {
124
+ function queryOf(url, allowedKeys, maxKeys = MAX_QUERY_KEYS) {
125
125
  const result = {}
126
126
  let count = 0
127
127
  for (const [key, value] of url.searchParams.entries()) {
128
128
  count += 1
129
- if (count > MAX_QUERY_KEYS || !allowedKeys.has(key) || Object.prototype.hasOwnProperty.call(result, key)) {
129
+ if (count > maxKeys || !allowedKeys.has(key) || Object.prototype.hasOwnProperty.call(result, key)) {
130
130
  throw new AutomationError('invalid_query', '查询参数无效。', 400)
131
131
  }
132
132
  if (value.length > MAX_QUERY_VALUE_CHARS) {
@@ -230,6 +230,13 @@ async function dispatch({ req, method, suffix, url, service, requestId }) {
230
230
  if (suffix === WORKSPACES_SUFFIX && method === 'GET') {
231
231
  return { body: await service.workspaceCatalog() }
232
232
  }
233
+ if (suffix === '/board' && method === 'GET') {
234
+ return { body: await service.board(queryOf(url, new Set(['days', 'tz', 'limit', 'before', 'category']), 5)) }
235
+ }
236
+ const briefRetry = /^\/board\/briefs\/([^/]+)\/retry$/.exec(suffix)
237
+ if (briefRetry !== null && method === 'POST') {
238
+ return { body: await service.retryBrief(decodeId(briefRetry[1])), status: 202 }
239
+ }
233
240
  if (suffix === '/runs' && method === 'GET') {
234
241
  return { body: await service.listRuns(queryOf(url, new Set(['limit', 'before']))) }
235
242
  }
@@ -116,7 +116,7 @@ ${task.instruction}
116
116
  }
117
117
 
118
118
  export function createRunRunner(options) {
119
- const { ctx, store, settings, profile, workspaces, now = () => Date.now(), logger, random } = options
119
+ const { ctx, store, settings, profile, workspaces, onRunSucceeded, now = () => Date.now(), logger, random } = options
120
120
  const entries = new Map()
121
121
  const pendingDispatches = new Set()
122
122
  const bySession = new Map()
@@ -317,7 +317,19 @@ export function createRunRunner(options) {
317
317
  })
318
318
  entries.delete(entry.id)
319
319
  if (entry.sessionId !== undefined) bySession.delete(entry.sessionId)
320
- await notify(entry, updated ?? { ...entry.run, status })
320
+ const finalRun = updated ?? { ...entry.run, status }
321
+ try {
322
+ await notify(entry, finalRun)
323
+ } catch (error) {
324
+ logger?.warn?.(`capital-automation: run notification failed: ${String(error)}`)
325
+ }
326
+ if (finalRun.status === 'succeeded' && typeof onRunSucceeded === 'function') {
327
+ try {
328
+ await onRunSucceeded({ run: finalRun, task: entry.task })
329
+ } catch (error) {
330
+ logger?.warn?.(`capital-automation: brief enqueue failed: ${String(error)}`)
331
+ }
332
+ }
321
333
  }
322
334
 
323
335
  async function notify(entry, run) {
@@ -278,6 +278,66 @@ export const NotificationSchema = z.strictObject({
278
278
  readAt: isoInstant.optional(),
279
279
  })
280
280
 
281
+ /** Derived task brief. One per successful run; storage validates it on every open. */
282
+ export const BriefItemSchema = z.strictObject({
283
+ kind: z.enum(['confirm', 'verify', 'track']),
284
+ title: z.string().min(1).max(40),
285
+ detail: z.string().max(120).optional(),
286
+ symbol: z.string().max(20).optional(),
287
+ trigger: z.string().max(80).optional(),
288
+ dueAt: z.string().refine(isCalendarDate, { message: 'must be a valid YYYY-MM-DD date' }).optional(),
289
+ dueLabel: z.string().max(20).optional(),
290
+ sourceQuote: z.string().min(1).max(160),
291
+ })
292
+
293
+ export const BriefStockSchema = z.strictObject({
294
+ symbol: z.string().min(1).max(20),
295
+ name: z.string().min(1).max(40),
296
+ roles: z.array(z.enum(['holding', 'watch', 'event', 'risk'])).min(1).max(3),
297
+ note: z.string().max(80).optional(),
298
+ nextAt: z.string().refine(isCalendarDate, { message: 'must be a valid YYYY-MM-DD date' }).optional(),
299
+ })
300
+
301
+ export const BriefGapSchema = z.strictObject({
302
+ kind: z.enum(['capability', 'transient', 'conflict', 'quality']),
303
+ topic: z.string().min(2).max(24),
304
+ detail: z.string().min(1).max(100),
305
+ sourceQuote: z.string().min(1).max(160),
306
+ })
307
+
308
+ export const TaskBriefSchema = z.strictObject({
309
+ schemaVersion: z.literal(1),
310
+ profileKey: z.string().min(1).max(80),
311
+ runId: z.string().min(1).max(80),
312
+ taskId: z.string().min(1).max(80),
313
+ sessionId: z.string().min(1).max(120).optional(),
314
+ status: z.enum(['pending', 'ready', 'failed', 'skipped']),
315
+ headline: z.string().min(4).max(24).optional(),
316
+ plain: z.string().min(40).max(200).optional(),
317
+ items: z.array(BriefItemSchema).max(6),
318
+ stocks: z.array(BriefStockSchema).max(8),
319
+ gaps: z.array(BriefGapSchema).max(6),
320
+ coverage: z.enum(['full', 'partial']).optional(),
321
+ model: z.string().max(120).optional(),
322
+ promptVersion: z.number().int().min(1).max(99),
323
+ sourceHash: z.string().regex(/^[a-f0-9]{16}$/).optional(),
324
+ error: z.string().max(300).optional(),
325
+ lastError: z.string().max(300).optional(),
326
+ lastErrorAt: isoInstant.optional(),
327
+ attempts: z.number().int().min(0).max(5),
328
+ generatedAt: isoInstant.optional(),
329
+ updatedAt: isoInstant,
330
+ }).superRefine((brief, ctx) => {
331
+ if (brief.status === 'ready') {
332
+ if (brief.headline === undefined) ctx.addIssue({ code: 'custom', path: ['headline'], message: 'ready brief requires headline' })
333
+ if (brief.plain === undefined) ctx.addIssue({ code: 'custom', path: ['plain'], message: 'ready brief requires plain' })
334
+ } else if (brief.status === 'failed') {
335
+ if (brief.error === undefined) ctx.addIssue({ code: 'custom', path: ['error'], message: 'failed brief requires error' })
336
+ } else if (brief.headline !== undefined || brief.plain !== undefined) {
337
+ ctx.addIssue({ code: 'custom', message: `${brief.status} brief must not carry headline/plain` })
338
+ }
339
+ })
340
+
281
341
  export const OwnerRecordSchema = z.strictObject({
282
342
  schemaVersion: z.literal(1),
283
343
  profileKey: z.string().min(1).max(80),
@@ -104,7 +104,7 @@ export class AutomationError extends Error {
104
104
  }
105
105
 
106
106
  export function createAutomationService(options) {
107
- const { store, scheduler, runner, calendar, profile, workspaces, version, settings, now = () => Date.now() } = options
107
+ const { store, scheduler, runner, calendar, profile, workspaces, version, settings, briefs, boardService, now = () => Date.now() } = options
108
108
  let chain = Promise.resolve()
109
109
 
110
110
  function serialize(operation) {
@@ -372,6 +372,33 @@ export function createAutomationService(options) {
372
372
  return { days: buckets, total, success, failure }
373
373
  }
374
374
 
375
+ async function board(query = {}) {
376
+ if (boardService === undefined || typeof boardService.board !== 'function') {
377
+ throw new AutomationError('board_unavailable', '看板服务暂时不可用。', 503)
378
+ }
379
+ try {
380
+ return await boardService.board(query)
381
+ } catch (error) {
382
+ if (error?.boardError === true) throw new AutomationError(error.code, error.message, error.status ?? 400)
383
+ throw error
384
+ }
385
+ }
386
+
387
+ async function retryBrief(runId) {
388
+ if (briefs === undefined || typeof briefs.retry !== 'function') {
389
+ throw new AutomationError('brief_not_found', '任务简报服务暂时不可用。', 503)
390
+ }
391
+ const result = await briefs.retry(runId)
392
+ if (result?.ok !== true) {
393
+ throw new AutomationError(
394
+ result?.code ?? 'brief_not_retryable',
395
+ result?.message ?? '这条任务简报暂时不能重试。',
396
+ result?.status ?? 409,
397
+ )
398
+ }
399
+ return { queued: true }
400
+ }
401
+
375
402
  async function listNotifications(query = {}) {
376
403
  let unreadOnly = false
377
404
  if (query.unread !== undefined) {
@@ -416,6 +443,8 @@ export function createAutomationService(options) {
416
443
  getRun,
417
444
  listRuns,
418
445
  runHistory,
446
+ board,
447
+ retryBrief,
419
448
  listNotifications,
420
449
  markNotificationsRead,
421
450
  storageState: async () => {
@@ -12,6 +12,7 @@ import {
12
12
  OwnerRecordSchema,
13
13
  RunRecordSchema,
14
14
  TaskConfigSchema,
15
+ TaskBriefSchema,
15
16
  TaskOverridesSchema,
16
17
  TaskRecordSchema,
17
18
  isActiveRun,
@@ -46,6 +47,7 @@ export const domainSpec = {
46
47
  attempts: { valueSchema: AttemptRecordSchema },
47
48
  notifications: { valueSchema: NotificationSchema },
48
49
  meta: { valueSchema: OwnerRecordSchema },
50
+ briefs: { valueSchema: TaskBriefSchema },
49
51
  },
50
52
  }
51
53
 
@@ -181,6 +183,7 @@ export function createAutomationStore(options) {
181
183
  attempts: domain.table('attempts'),
182
184
  notifications: domain.table('notifications'),
183
185
  meta: domain.table('meta'),
186
+ briefs: domain.table('briefs'),
184
187
  }
185
188
  })()
186
189
  }
@@ -201,6 +204,10 @@ export function createAutomationStore(options) {
201
204
  return record !== undefined && record.profileKey === profileKey
202
205
  }
203
206
 
207
+ function ownBrief(record) {
208
+ return record !== undefined && record.profileKey === profileKey
209
+ }
210
+
204
211
  async function seedBuiltins(tables) {
205
212
  const at = iso(now())
206
213
  for (const definition of builtins) {
@@ -397,6 +404,11 @@ export function createAutomationStore(options) {
397
404
  await tables.notifications.delete(notificationId)
398
405
  }
399
406
  }
407
+ for (const [briefId, brief] of [...tables.briefs.entries()]) {
408
+ if (ownBrief(brief) && (brief.taskId === id || runIds.has(brief.runId))) {
409
+ await tables.briefs.delete(briefId)
410
+ }
411
+ }
400
412
  return tables.tasks.delete(id)
401
413
  }
402
414
 
@@ -544,7 +556,11 @@ export function createAutomationStore(options) {
544
556
  perTask.set(run.taskId, count)
545
557
  if (index >= MAX_RUNS_PER_PROFILE || count > MAX_RUNS_PER_TASK) doomed.add(run.id)
546
558
  })
547
- for (const id of doomed) await tables.runs.delete(id)
559
+ for (const id of doomed) {
560
+ await tables.runs.delete(id)
561
+ const brief = tables.briefs.get(id)
562
+ if (ownBrief(brief)) await tables.briefs.delete(id)
563
+ }
548
564
  }
549
565
 
550
566
  async function claimOccurrence(input) {
@@ -671,6 +687,122 @@ export function createAutomationStore(options) {
671
687
  return changed
672
688
  }
673
689
 
690
+ async function createBrief(input) {
691
+ const tables = await ensure()
692
+ const existing = tables.briefs.get(input.runId)
693
+ if (existing !== undefined) return ownBrief(existing) ? existing : undefined
694
+ const at = iso(now())
695
+ const record = parseStrict(TaskBriefSchema, {
696
+ schemaVersion: 1,
697
+ profileKey,
698
+ runId: input.runId,
699
+ taskId: input.taskId,
700
+ ...(input.sessionId === undefined ? {} : { sessionId: input.sessionId }),
701
+ status: 'pending',
702
+ items: [],
703
+ stocks: [],
704
+ gaps: [],
705
+ promptVersion: input.promptVersion ?? 1,
706
+ attempts: 0,
707
+ updatedAt: at,
708
+ }, 'brief')
709
+ await tables.briefs.put(record.runId, record)
710
+ return record
711
+ }
712
+
713
+ async function putBrief(record) {
714
+ const tables = await ensure()
715
+ const clean = parseStrict(TaskBriefSchema, { ...record, profileKey }, 'brief')
716
+ await tables.briefs.put(clean.runId, clean)
717
+ return clean
718
+ }
719
+
720
+ async function getBrief(runId) {
721
+ const tables = await ensure()
722
+ const record = tables.briefs.get(runId)
723
+ return ownBrief(record) ? record : undefined
724
+ }
725
+
726
+ async function listBriefsForRuns(runIds) {
727
+ const tables = await ensure()
728
+ const result = new Map()
729
+ for (const runId of runIds) {
730
+ const record = tables.briefs.get(runId)
731
+ if (ownBrief(record)) result.set(runId, record)
732
+ }
733
+ return result
734
+ }
735
+
736
+ async function listBriefsForProfile() {
737
+ const tables = await ensure()
738
+ const records = []
739
+ for (const [, record] of tables.briefs.entries()) if (ownBrief(record)) records.push(record)
740
+ records.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt) || left.runId.localeCompare(right.runId))
741
+ return records
742
+ }
743
+
744
+ async function countBriefs() {
745
+ const tables = await ensure()
746
+ let count = 0
747
+ for (const [, record] of tables.briefs.entries()) if (ownBrief(record)) count += 1
748
+ return count
749
+ }
750
+
751
+ async function updateBrief(runId, patch) {
752
+ const tables = await ensure()
753
+ const current = tables.briefs.get(runId)
754
+ if (!ownBrief(current)) return undefined
755
+ const next = {
756
+ ...current,
757
+ ...patch,
758
+ profileKey,
759
+ updatedAt: iso(now()),
760
+ }
761
+ if (next.status === 'pending') {
762
+ if (typeof current.error === 'string' && current.error.length > 0) {
763
+ next.lastError = current.error
764
+ next.lastErrorAt = iso(now())
765
+ }
766
+ delete next.headline
767
+ delete next.plain
768
+ delete next.error
769
+ delete next.generatedAt
770
+ next.items = []
771
+ next.stocks = []
772
+ next.gaps = []
773
+ }
774
+ const clean = parseStrict(TaskBriefSchema, next, 'brief')
775
+ await tables.briefs.put(runId, clean)
776
+ return clean
777
+ }
778
+
779
+ async function deleteBrief(runId) {
780
+ const tables = await ensure()
781
+ const current = tables.briefs.get(runId)
782
+ if (!ownBrief(current)) return false
783
+ return tables.briefs.delete(runId)
784
+ }
785
+
786
+ function publicBrief(brief) {
787
+ return {
788
+ runId: brief.runId,
789
+ taskId: brief.taskId,
790
+ sessionId: brief.sessionId ?? null,
791
+ status: brief.status,
792
+ headline: brief.headline ?? null,
793
+ plain: brief.plain ?? null,
794
+ coverage: brief.coverage ?? null,
795
+ error: brief.error ?? null,
796
+ attempts: brief.attempts,
797
+ generatedAt: brief.generatedAt ?? null,
798
+ counts: {
799
+ items: brief.items.length,
800
+ stocks: brief.stocks.length,
801
+ gaps: brief.gaps.length,
802
+ },
803
+ }
804
+ }
805
+
674
806
  async function setOwnerMeta(record) {
675
807
  const tables = await ensure()
676
808
  const clean = parseStrict(OwnerRecordSchema, record, 'owner meta')
@@ -811,6 +943,15 @@ export function createAutomationStore(options) {
811
943
  hasAttempt,
812
944
  setAttemptState,
813
945
  listAttemptsForRun,
946
+ createBrief,
947
+ putBrief,
948
+ getBrief,
949
+ listBriefsForRuns,
950
+ listBriefsForProfile,
951
+ countBriefs,
952
+ updateBrief,
953
+ deleteBrief,
954
+ publicBrief,
814
955
  addNotification,
815
956
  listNotifications,
816
957
  unreadNotificationCount,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-charts",
3
- "version": "2.16.1",
3
+ "version": "2.17.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.16.1",
3
+ "version": "2.17.0",
4
4
  "description": "自动模式的取数凭据与偏好配置行:卡片坐在 @v587d/capital-generation 插件主页的「配置」段,点这一行本身没有表单。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -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.16.1";
6
+ export declare const LOCAL_FETCH_CLIENT_VERSION = "2.17.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.16.1';
7
+ export const LOCAL_FETCH_CLIENT_VERSION = '2.17.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.16.1";
38
+ export declare const WIND_CLIENT_VERSION = "2.17.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.16.1';
22
+ export const WIND_CLIENT_VERSION = '2.17.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.16.1",
3
+ "version": "2.17.0",
4
4
  "description": "Capital Generation:面向中国散户的 AI 投资助手插件(自动模式 Agent Preset)",
5
5
  "icon": "assets/cg-icon.png",
6
6
  "author": "v587d",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/watchlist",
3
- "version": "2.16.1",
3
+ "version": "2.17.0",
4
4
  "description": "自动模式的用户自选股(宿主级清单 + Fuyao 报价快照 + /capital-watchlist 路由 + 输入框菜单弹窗):由 @v587d/capital-generation 随包携带并作为 host 平面行挂载。",
5
5
  "license": "MIT",
6
6
  "type": "module",