@v587d/capital-generation 2.19.1 → 2.19.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.
@@ -36,6 +36,11 @@ export const MAX_RUNS_PER_TASK = 200
36
36
  export const MAX_RUNS_PER_PROFILE = 2_000
37
37
  export const MAX_NOTIFICATIONS_PER_PROFILE = 200
38
38
  export const MAX_TODO_ACKS_PER_PROFILE = 500
39
+ export const MAX_ASKS_PER_PROFILE = 400
40
+ export const MAX_ASK_QUESTION_CHARS = 500
41
+ export const MAX_ASK_PREVIEW_CHARS = 160
42
+ export const MAX_ASK_ANSWER_CHARS = 20_000
43
+ export const ASK_TIMEOUT_MS = 30 * 60_000
39
44
  export const MAX_ERRORS_PER_RUN = 20
40
45
 
41
46
  export const MAX_TITLE_CHARS = 120
@@ -10,6 +10,7 @@ import { join } from 'node:path'
10
10
  import { createRunRunner, buildRunPrompt, sessionTitleOf } from './runner.js'
11
11
  import { createBriefService } from './brief.js'
12
12
  import { createBoardService } from './board.js'
13
+ import { createAskService } from './ask.js'
13
14
  import { createScheduler } from './scheduler.js'
14
15
  import { createAutomationService, AutomationError } from './service.js'
15
16
  import { createAutomationStore, domainSpec, ROUTE_PATH } from './store.js'
@@ -64,6 +65,12 @@ export function createAutomationRuntime(options) {
64
65
  calendar,
65
66
  settings: getSettings,
66
67
  })
68
+ const asks = createAskService({
69
+ ctx,
70
+ store,
71
+ now,
72
+ logger,
73
+ })
67
74
  let briefs
68
75
  const runner = createRunRunner({
69
76
  ctx,
@@ -94,6 +101,7 @@ export function createAutomationRuntime(options) {
94
101
  const boardService = createBoardService({
95
102
  store,
96
103
  scheduler,
104
+ asks,
97
105
  now,
98
106
  })
99
107
  const service = createAutomationService({
@@ -106,6 +114,7 @@ export function createAutomationRuntime(options) {
106
114
  version,
107
115
  settings: getSettings,
108
116
  briefs,
117
+ asks,
109
118
  boardService,
110
119
  now,
111
120
  })
@@ -115,7 +124,7 @@ export function createAutomationRuntime(options) {
115
124
  installAutomationPolicy({ ctx: toolsCtx, runner, logger })
116
125
  })
117
126
  }
118
- return { store, runner, scheduler, briefs, service, calendar, workspaces, profile: { displayName, runDir, ownerDir } }
127
+ return { store, runner, scheduler, briefs, asks, service, calendar, workspaces, profile: { displayName, runDir, ownerDir } }
119
128
  }
120
129
 
121
130
  function authorizeFactory(ctx) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-automation",
3
- "version": "2.19.1",
3
+ "version": "2.19.2",
4
4
  "description": "CapGen 投研自动化:独立 host bundle(固定 capital_automation 域、单 scheduler owner、/capital-automation 路由与浏览器页面)。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -41,6 +41,7 @@
41
41
  "runner.js",
42
42
  "brief.js",
43
43
  "board.js",
44
+ "ask.js",
44
45
  "scheduler.js",
45
46
  "workspaces.js",
46
47
  "contract.js",
@@ -236,6 +236,20 @@ async function dispatch({ req, method, suffix, url, service, requestId }) {
236
236
  if (suffix === '/board/todos/confirm' && method === 'POST') {
237
237
  return { body: await service.confirmTodo(await readBody(req)) }
238
238
  }
239
+ const askCreate = /^\/board\/briefs\/([^/]+)\/ask$/.exec(suffix)
240
+ if (askCreate !== null && method === 'POST') {
241
+ return { body: await service.askBrief(decodeId(askCreate[1]), await readBody(req)), status: 202 }
242
+ }
243
+ const askAnswer = /^\/board\/asks\/([^/]+)\/answer$/.exec(suffix)
244
+ if (askAnswer !== null) {
245
+ if (method !== 'GET') throw new AutomationError('method_not_allowed', '只支持 GET。', 405)
246
+ return { body: await service.askAnswer(decodeId(askAnswer[1])) }
247
+ }
248
+ const askDetail = /^\/board\/asks\/([^/]+)$/.exec(suffix)
249
+ if (askDetail !== null) {
250
+ if (method !== 'GET') throw new AutomationError('method_not_allowed', '只支持 GET。', 405)
251
+ return { body: await service.askStatus(decodeId(askDetail[1])) }
252
+ }
239
253
  const briefRetry = /^\/board\/briefs\/([^/]+)\/retry$/.exec(suffix)
240
254
  if (briefRetry !== null && method === 'POST') {
241
255
  return { body: await service.retryBrief(decodeId(briefRetry[1])), status: 202 }
@@ -8,6 +8,8 @@ import {
8
8
  ACTIVE_RUN_STATUSES,
9
9
  DEFAULT_AUTOMATION_SETTINGS,
10
10
  MAX_DESCRIPTION_CHARS,
11
+ MAX_ASK_PREVIEW_CHARS,
12
+ MAX_ASK_QUESTION_CHARS,
11
13
  MAX_ERROR_MESSAGE_CHARS,
12
14
  MAX_ERRORS_PER_RUN,
13
15
  MAX_INSTRUCTION_CHARS,
@@ -350,6 +352,37 @@ export const TodoAckSchema = z.strictObject({
350
352
  confirmedAt: isoInstant,
351
353
  })
352
354
 
355
+ /**
356
+ * One board follow-up. The question and its first finished turn live here; the Session remains
357
+ * the full transcript. `baselineSeq` is the log cursor before the prompt, so a later lazy read
358
+ * can tell this answer apart from the run's original assistant message.
359
+ */
360
+ export const AskRecordSchema = z.strictObject({
361
+ schemaVersion: z.literal(1),
362
+ id: z.string().min(1).max(80),
363
+ profileKey: z.string().min(1).max(80),
364
+ runId: z.string().min(1).max(120),
365
+ sessionId: z.string().min(1).max(120),
366
+ question: z.string().trim().min(1).max(MAX_ASK_QUESTION_CHARS),
367
+ baselineSeq: z.number().int().min(-1),
368
+ status: z.enum(['running', 'ready', 'failed']),
369
+ preview: z.string().min(1).max(MAX_ASK_PREVIEW_CHARS).optional(),
370
+ error: z.string().max(300).optional(),
371
+ createdAt: isoInstant,
372
+ updatedAt: isoInstant,
373
+ finishedAt: isoInstant.optional(),
374
+ }).superRefine((ask, ctx) => {
375
+ if (ask.status === 'ready') {
376
+ if (ask.preview === undefined) ctx.addIssue({ code: 'custom', path: ['preview'], message: 'ready ask requires preview' })
377
+ if (ask.finishedAt === undefined) ctx.addIssue({ code: 'custom', path: ['finishedAt'], message: 'ready ask requires finishedAt' })
378
+ } else if (ask.status === 'failed') {
379
+ if (ask.error === undefined) ctx.addIssue({ code: 'custom', path: ['error'], message: 'failed ask requires error' })
380
+ if (ask.finishedAt === undefined) ctx.addIssue({ code: 'custom', path: ['finishedAt'], message: 'failed ask requires finishedAt' })
381
+ } else if (ask.preview !== undefined || ask.error !== undefined || ask.finishedAt !== undefined) {
382
+ ctx.addIssue({ code: 'custom', message: 'running ask must not carry preview/error/finishedAt' })
383
+ }
384
+ })
385
+
353
386
  export const OwnerRecordSchema = z.strictObject({
354
387
  schemaVersion: z.literal(1),
355
388
  profileKey: z.string().min(1).max(80),
@@ -390,6 +423,11 @@ export const TodoConfirmSchema = z.strictObject({
390
423
  id: z.string().min(1).max(200),
391
424
  })
392
425
 
426
+ export const AskCreateSchema = z.strictObject({
427
+ question: z.string().trim().min(1).max(MAX_ASK_QUESTION_CHARS),
428
+ timeZone: timeZone.optional(),
429
+ })
430
+
393
431
  export const NotificationsReadSchema = z.strictObject({
394
432
  ids: z.array(z.string().min(1).max(80)).max(200).optional(),
395
433
  all: z.boolean().optional(),
@@ -17,6 +17,7 @@ import {
17
17
  MIN_RUN_TIMEOUT_MINUTES,
18
18
  } from './defaults.js'
19
19
  import {
20
+ AskCreateSchema,
20
21
  NotificationsReadSchema,
21
22
  TaskCategorySchema,
22
23
  TaskCreateSchema,
@@ -105,7 +106,7 @@ export class AutomationError extends Error {
105
106
  }
106
107
 
107
108
  export function createAutomationService(options) {
108
- const { store, scheduler, runner, calendar, profile, workspaces, version, settings, briefs, boardService, now = () => Date.now() } = options
109
+ const { store, scheduler, runner, calendar, profile, workspaces, version, settings, briefs, asks, boardService, now = () => Date.now() } = options
109
110
  let chain = Promise.resolve()
110
111
 
111
112
  function serialize(operation) {
@@ -170,6 +171,15 @@ export function createAutomationService(options) {
170
171
  } catch (error) {
171
172
  storage = { state: 'unavailable', error: sanitizeMessage(String(error)) }
172
173
  }
174
+ let unread = 0
175
+ if (storage.state === 'ready') {
176
+ // The badge ships with the page shell so entry never has to list notifications.
177
+ try {
178
+ unread = await store.unreadNotificationCount('task')
179
+ } catch {
180
+ unread = 0
181
+ }
182
+ }
173
183
  let workspaceList = []
174
184
  let workspaceError
175
185
  try {
@@ -181,6 +191,7 @@ export function createAutomationService(options) {
181
191
  profile: { key: store.profileKey, name: profile.displayName, state: 'current' },
182
192
  version,
183
193
  storage,
194
+ notifications: { unread },
184
195
  workspaces: workspaceList,
185
196
  defaultWorkspaceId: workspaceList.find((item) => item.default === true)?.id ?? null,
186
197
  ...(workspaceError === undefined ? {} : { workspaceError }),
@@ -398,6 +409,47 @@ export function createAutomationService(options) {
398
409
  }
399
410
  }
400
411
 
412
+ function mapAskError(error) {
413
+ if (error?.askError === true) {
414
+ throw new AutomationError(error.code, error.message, error.status ?? 400, error.extra)
415
+ }
416
+ throw error
417
+ }
418
+
419
+ async function askBrief(runId, input) {
420
+ if (asks === undefined || typeof asks.ask !== 'function') {
421
+ throw new AutomationError('ask_unavailable', '追问服务暂时不可用。', 503)
422
+ }
423
+ const parsed = parseStrict(AskCreateSchema, input, 'board/ask')
424
+ try {
425
+ return { ask: await asks.ask(runId, parsed) }
426
+ } catch (error) {
427
+ mapAskError(error)
428
+ }
429
+ }
430
+
431
+ async function askStatus(askId) {
432
+ if (asks === undefined || typeof asks.status !== 'function') {
433
+ throw new AutomationError('ask_unavailable', '追问服务暂时不可用。', 503)
434
+ }
435
+ try {
436
+ return { ask: await asks.status(askId) }
437
+ } catch (error) {
438
+ mapAskError(error)
439
+ }
440
+ }
441
+
442
+ async function askAnswer(askId) {
443
+ if (asks === undefined || typeof asks.answer !== 'function') {
444
+ throw new AutomationError('ask_unavailable', '追问服务暂时不可用。', 503)
445
+ }
446
+ try {
447
+ return await asks.answer(askId)
448
+ } catch (error) {
449
+ mapAskError(error)
450
+ }
451
+ }
452
+
401
453
  async function retryBrief(runId) {
402
454
  if (briefs === undefined || typeof briefs.retry !== 'function') {
403
455
  throw new AutomationError('brief_not_found', '任务简报服务暂时不可用。', 503)
@@ -460,6 +512,9 @@ export function createAutomationService(options) {
460
512
  board,
461
513
  confirmTodo,
462
514
  retryBrief,
515
+ askBrief,
516
+ askStatus,
517
+ askAnswer,
463
518
  listNotifications,
464
519
  markNotificationsRead,
465
520
  storageState: async () => {
@@ -6,6 +6,7 @@
6
6
  import { createHash, randomUUID } from 'node:crypto'
7
7
  import { isDeepStrictEqual } from 'node:util'
8
8
  import {
9
+ AskRecordSchema,
9
10
  AttemptRecordSchema,
10
11
  AutomationTaskSchema,
11
12
  NotificationSchema,
@@ -24,6 +25,7 @@ import { BUILTIN_BY_ID, BUILTIN_DEFINITIONS } from './builtins.js'
24
25
  import { DEFAULT_CUSTOM_ICON, builtinTaskIcon } from './task-icons.js'
25
26
  import {
26
27
  DEFAULT_AUTOMATION_SETTINGS,
28
+ MAX_ASKS_PER_PROFILE,
27
29
  MAX_ERRORS_PER_RUN,
28
30
  MAX_NOTIFICATIONS_PER_PROFILE,
29
31
  MAX_RUNS_PER_PROFILE,
@@ -51,6 +53,7 @@ export const domainSpec = {
51
53
  meta: { valueSchema: OwnerRecordSchema },
52
54
  briefs: { valueSchema: TaskBriefSchema },
53
55
  todo_acks: { valueSchema: TodoAckSchema },
56
+ asks: { valueSchema: AskRecordSchema },
54
57
  },
55
58
  }
56
59
 
@@ -140,6 +143,7 @@ export function createAutomationStore(options) {
140
143
  const profileById = new Map(builtins.map((definition) => [definition.id, definition]))
141
144
  let opening
142
145
  let claimChain = Promise.resolve()
146
+ let askChain = Promise.resolve()
143
147
 
144
148
  /** Profile-level defaults; a task without its own limits inherits these. */
145
149
  function defaultLimits() {
@@ -180,6 +184,12 @@ export function createAutomationStore(options) {
180
184
  return next
181
185
  }
182
186
 
187
+ function serializeAsk(operation) {
188
+ const next = askChain.then(operation, operation)
189
+ askChain = next.then(() => {}, () => {})
190
+ return next
191
+ }
192
+
183
193
  async function open() {
184
194
  if (opening === undefined) {
185
195
  opening = (async () => {
@@ -193,6 +203,7 @@ export function createAutomationStore(options) {
193
203
  meta: domain.table('meta'),
194
204
  briefs: domain.table('briefs'),
195
205
  todoAcks: domain.table('todo_acks'),
206
+ asks: domain.table('asks'),
196
207
  }
197
208
  })()
198
209
  }
@@ -217,6 +228,10 @@ export function createAutomationStore(options) {
217
228
  return record !== undefined && record.profileKey === profileKey
218
229
  }
219
230
 
231
+ function ownAsk(record) {
232
+ return record !== undefined && record.profileKey === profileKey
233
+ }
234
+
220
235
  async function seedBuiltins(tables) {
221
236
  const at = iso(now())
222
237
  for (const definition of builtins) {
@@ -418,6 +433,9 @@ export function createAutomationStore(options) {
418
433
  await tables.briefs.delete(briefId)
419
434
  }
420
435
  }
436
+ for (const [askId, ask] of [...tables.asks.entries()]) {
437
+ if (ownAsk(ask) && runIds.has(ask.runId)) await tables.asks.delete(askId)
438
+ }
421
439
  return tables.tasks.delete(id)
422
440
  }
423
441
 
@@ -569,6 +587,9 @@ export function createAutomationStore(options) {
569
587
  await tables.runs.delete(id)
570
588
  const brief = tables.briefs.get(id)
571
589
  if (ownBrief(brief)) await tables.briefs.delete(id)
590
+ for (const [askId, ask] of [...tables.asks.entries()]) {
591
+ if (ownAsk(ask) && ask.runId === id) await tables.asks.delete(askId)
592
+ }
572
593
  }
573
594
  }
574
595
 
@@ -757,6 +778,98 @@ export function createAutomationStore(options) {
757
778
  return count
758
779
  }
759
780
 
781
+ async function retainAsks(tables) {
782
+ const records = []
783
+ for (const [, record] of tables.asks.entries()) if (ownAsk(record)) records.push(record)
784
+ if (records.length <= MAX_ASKS_PER_PROFILE) return
785
+ records.sort((left, right) => right.createdAt.localeCompare(left.createdAt) || right.id.localeCompare(left.id))
786
+ for (const record of records.slice(MAX_ASKS_PER_PROFILE)) {
787
+ // A running ask is still the user's only handle on that turn; drop it only after it settles.
788
+ if (record.status !== 'running') await tables.asks.delete(record.id)
789
+ }
790
+ }
791
+
792
+ async function pendingAskForRunIn(tables, runId) {
793
+ let found
794
+ for (const [, record] of tables.asks.entries()) {
795
+ if (!ownAsk(record) || record.runId !== runId || record.status !== 'running') continue
796
+ if (found === undefined || record.createdAt > found.createdAt) found = record
797
+ }
798
+ return found
799
+ }
800
+
801
+ async function createAsk(input) {
802
+ return serializeAsk(async () => {
803
+ const tables = await ensure()
804
+ const pending = await pendingAskForRunIn(tables, input.runId)
805
+ if (pending !== undefined) {
806
+ const error = new Error('上一条追问还在回答,等它结束再问。')
807
+ error.code = 'ask_pending'
808
+ error.askId = pending.id
809
+ throw error
810
+ }
811
+ const at = iso(now())
812
+ const record = parseStrict(AskRecordSchema, {
813
+ schemaVersion: 1,
814
+ id: `ask_${random().replace(/-/g, '')}`,
815
+ profileKey,
816
+ runId: input.runId,
817
+ sessionId: input.sessionId,
818
+ question: input.question,
819
+ baselineSeq: Number.isSafeInteger(input.baselineSeq) ? input.baselineSeq : -1,
820
+ status: 'running',
821
+ createdAt: at,
822
+ updatedAt: at,
823
+ }, 'ask')
824
+ await tables.asks.put(record.id, record)
825
+ await retainAsks(tables)
826
+ return record
827
+ })
828
+ }
829
+
830
+ async function getAsk(id) {
831
+ const tables = await ensure()
832
+ const record = tables.asks.get(id)
833
+ return ownAsk(record) ? record : undefined
834
+ }
835
+
836
+ async function pendingAskForRun(runId) {
837
+ const tables = await ensure()
838
+ return pendingAskForRunIn(tables, runId)
839
+ }
840
+
841
+ async function latestAsksForRuns(runIds) {
842
+ const tables = await ensure()
843
+ const wanted = new Set(runIds)
844
+ const result = new Map()
845
+ for (const [, record] of tables.asks.entries()) {
846
+ if (!ownAsk(record) || !wanted.has(record.runId)) continue
847
+ const current = result.get(record.runId)
848
+ if (current === undefined || record.createdAt > current.createdAt) result.set(record.runId, record)
849
+ }
850
+ return result
851
+ }
852
+
853
+ async function updateAsk(id, patch) {
854
+ const tables = await ensure()
855
+ const current = tables.asks.get(id)
856
+ if (!ownAsk(current)) return undefined
857
+ const next = parseStrict(AskRecordSchema, {
858
+ ...current,
859
+ ...patch,
860
+ updatedAt: iso(now()),
861
+ }, 'ask')
862
+ await tables.asks.put(id, next)
863
+ return next
864
+ }
865
+
866
+ async function deleteAsk(id) {
867
+ const tables = await ensure()
868
+ const current = tables.asks.get(id)
869
+ if (!ownAsk(current)) return false
870
+ return tables.asks.delete(id)
871
+ }
872
+
760
873
  async function listTodoAcks() {
761
874
  const tables = await ensure()
762
875
  const records = []
@@ -992,6 +1105,12 @@ export function createAutomationStore(options) {
992
1105
  listBriefsForRuns,
993
1106
  listBriefsForProfile,
994
1107
  countBriefs,
1108
+ createAsk,
1109
+ getAsk,
1110
+ pendingAskForRun,
1111
+ latestAsksForRuns,
1112
+ updateAsk,
1113
+ deleteAsk,
995
1114
  listTodoAcks,
996
1115
  confirmTodo,
997
1116
  updateBrief,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/capital-charts",
3
- "version": "2.19.1",
3
+ "version": "2.19.2",
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.1",
3
+ "version": "2.19.2",
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.19.1";
6
+ export declare const LOCAL_FETCH_CLIENT_VERSION = "2.19.2";
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.1';
7
+ export const LOCAL_FETCH_CLIENT_VERSION = '2.19.2';
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.1";
38
+ export declare const WIND_CLIENT_VERSION = "2.19.2";
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.1';
22
+ export const WIND_CLIENT_VERSION = '2.19.2';
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.1",
3
+ "version": "2.19.2",
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.19.1",
3
+ "version": "2.19.2",
4
4
  "description": "自动模式的用户自选股(宿主级清单 + Fuyao 报价快照 + /capital-watchlist 路由 + 输入框菜单弹窗):由 @v587d/capital-generation 随包携带并作为 host 平面行挂载。",
5
5
  "license": "MIT",
6
6
  "type": "module",