@v587d/capital-generation 2.21.4 → 2.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +5 -5
  3. package/automation/board.js +89 -22
  4. package/automation/client.js +3 -3
  5. package/automation/client.src.cjs +5 -1
  6. package/automation/index.js +35 -0
  7. package/automation/package.json +1 -1
  8. package/automation/runner.js +3 -2
  9. package/chart-ui/package.json +1 -1
  10. package/config/package.json +1 -1
  11. package/lib/agents/messaging-policy.d.ts +21 -0
  12. package/lib/agents/messaging-policy.js +100 -0
  13. package/lib/agents/role-tool-policy.d.ts +23 -7
  14. package/lib/agents/role-tool-policy.js +118 -33
  15. package/lib/agents/root-tool-policy.d.ts +13 -2
  16. package/lib/agents/root-tool-policy.js +87 -28
  17. package/lib/agents/wait-for-agents.d.ts +7 -3
  18. package/lib/agents/wait-for-agents.js +4 -3
  19. package/lib/collector-runtime.js +2 -2
  20. package/lib/data-collector/tools.d.ts +1 -1
  21. package/lib/data-collector/tools.js +31 -3
  22. package/lib/data-collector/upstream-retry.d.ts +48 -0
  23. package/lib/data-collector/upstream-retry.js +192 -0
  24. package/lib/policy-entry.d.ts +3 -3
  25. package/lib/policy-entry.js +3 -1
  26. package/lib/web-retriever/local-fetch.d.ts +1 -1
  27. package/lib/web-retriever/local-fetch.js +1 -1
  28. package/lib/web-retriever/wind-client.d.ts +1 -1
  29. package/lib/web-retriever/wind-client.js +1 -1
  30. package/package.json +6 -6
  31. package/preset/capital-generation/README.md +2 -1
  32. package/preset/capital-generation/agent.patch.yml +58 -44
  33. package/preset/capital-generation/skills/capital-data-profile/SKILL.md +2 -2
  34. package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +20 -8
  35. package/preset/capital-generation/skills/capital-data-query/SKILL.md +2 -2
  36. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  37. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  38. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +70 -72
  39. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  40. package/preset/capital-generation/skills/capital-visualization-protocol/SKILL.md +1 -0
  41. package/watchlist/package.json +1 -1
@@ -13,6 +13,8 @@ export const RETRIEVAL_DENIED_TOOLS = [
13
13
  'eastmoney_announcements', 'eastmoney_announcement_body',
14
14
  'sina_reports', 'ths_eps_forecast',
15
15
  ];
16
+ /** Generic host web entry points; the only outbound surface is web_retriever's named tools. */
17
+ export const HOST_WEB_DENIED_TOOLS = ['web_fetch', 'anysearch_batch_search', 'anysearch_capabilities'];
16
18
  export const OCR_TOOL_NAME = 'ocr';
17
19
  /** Name-level deny cannot express the form distinction; this is a call-level guard. */
18
20
  export const OCR_ROOT_URL_DENIED = 'ocr 的 url 形态只对被委派的 web_retriever 开放:外部 PDF 链接请委派 subagent_web_retriever 解析。'
@@ -40,11 +42,23 @@ export function ocrFormGuardReasonFor(ctx) {
40
42
  }
41
43
  /** Mounted as a platform pair; recognize both everywhere or the other platform's gate is dead. */
42
44
  export const SHELL_TOOL_NAMES = ['bash', 'pwsh'];
45
+ /** dsh-base mounts Agent Team globally. We keep the rows (other modes may use them) and deny the
46
+ * four tools on every Capital agent; the `team:policy` prompt section is host-owned and cannot be
47
+ * removed by a name deny, so Capital intentionally ignores that text. */
48
+ export const TEAM_DENIED_TOOLS = [
49
+ 'team_task_create',
50
+ 'team_task_list',
51
+ 'team_task_get',
52
+ 'team_task_update',
53
+ ];
43
54
  export const ROOT_AGENT_DENIED_TOOLS = [
44
55
  /** Charts only flow through junior -> visualization_specialist. */
45
56
  'render_chart',
46
57
  'prepare_chart_source',
58
+ /** Team stays mounted but is not Capital's delegation board. */
59
+ ...TEAM_DENIED_TOOLS,
47
60
  ...RETRIEVAL_DENIED_TOOLS,
61
+ ...HOST_WEB_DENIED_TOOLS,
48
62
  /** Not a boundary (the host global layer registers them); the call-level fs guard is the real block. */
49
63
  'write',
50
64
  'edit',
@@ -122,7 +136,19 @@ export function restrictRootAgentTools(agent, record) {
122
136
  }
123
137
  if (tools === undefined || typeof tools.restrict !== 'function')
124
138
  return 'unavailable';
139
+ let restrictable;
140
+ try {
141
+ const names = tools.view?.(agent)?.restrictableNames;
142
+ if (names !== undefined)
143
+ restrictable = new Set(names);
144
+ }
145
+ catch {
146
+ restrictable = undefined;
147
+ }
125
148
  for (const name of ROOT_AGENT_DENIED_TOOLS) {
149
+ // Family-row tools live in another scope; only inherited names are restrictable here.
150
+ if (restrictable !== undefined && !restrictable.has(name))
151
+ continue;
126
152
  try {
127
153
  tools.restrict({ deny: [name] });
128
154
  record?.denied.push(name);
@@ -263,48 +289,81 @@ export function registerRootToolPolicy(ctx, options = {}) {
263
289
  return;
264
290
  installedPolicyRoots.add(listenCtx);
265
291
  const install = () => {
292
+ const converged = new Set();
293
+ const seenAgents = new Map();
294
+ const converge = (agent) => {
295
+ const id = agentSessionId(agent);
296
+ if (id !== undefined && converged.has(id))
297
+ return;
298
+ const isRoot = isRootAgent(agent);
299
+ // Root only: children always have a parentSession and would crowd the 8-entry window.
300
+ const probe = isRoot
301
+ ? { agentId: id, root: true, presetId: presetIdOf(ctx, agent), outcome: 'pending', denied: [], failed: [] }
302
+ : undefined;
303
+ if (probe !== undefined) {
304
+ probes.push(probe);
305
+ if (probes.length > MAX_PROBES)
306
+ probes.shift();
307
+ }
308
+ if (!isCapitalAgent(ctx, agent)) {
309
+ if (probe !== undefined)
310
+ probe.outcome = 'not-capital';
311
+ return;
312
+ }
313
+ if (id !== undefined)
314
+ converged.add(id);
315
+ if (options.deny === false) {
316
+ // Composition already removed data/web/chart; per-name deny would only add `failed` noise.
317
+ if (probe !== undefined)
318
+ probe.outcome = 'skipped';
319
+ }
320
+ else {
321
+ const outcome = restrictRootAgentTools(agent, probe);
322
+ if (probe !== undefined)
323
+ probe.outcome = outcome;
324
+ if (outcome === 'unavailable') {
325
+ ctx.logger?.warn(`capital-generation: 根 Agent 工具收敛未生效(${outcome}):主 Agent 仍会看到 ${ROOT_AGENT_DENIED_TOOLS.join(' / ')}`);
326
+ }
327
+ }
328
+ };
266
329
  const stopCreated = listenCtx.on?.('agent/created', (payload) => {
267
330
  try {
268
331
  const agent = payload?.agent;
269
- const isRoot = isRootAgent(agent);
270
- // Root only: children always have a parentSession and would crowd the 8-entry window.
271
- const probe = isRoot
272
- ? { agentId: agentSessionId(agent), root: true, presetId: presetIdOf(ctx, agent), outcome: 'pending', denied: [], failed: [] }
273
- : undefined;
274
- if (probe !== undefined) {
275
- probes.push(probe);
276
- if (probes.length > MAX_PROBES)
277
- probes.shift();
278
- }
279
- if (!isCapitalAgent(ctx, agent)) {
280
- if (probe !== undefined)
281
- probe.outcome = 'not-capital';
282
- return;
283
- }
284
- if (options.deny === false) {
285
- // Composition already removed data/web/chart; per-name deny would only add `failed` noise.
286
- if (probe !== undefined)
287
- probe.outcome = 'skipped';
288
- }
289
- else {
290
- const outcome = restrictRootAgentTools(agent, probe);
291
- if (probe !== undefined)
292
- probe.outcome = outcome;
293
- if (outcome === 'unavailable') {
294
- ctx.logger?.warn(`capital-generation: 根 Agent 工具收敛未生效(${outcome}):主 Agent 仍会看到 ${ROOT_AGENT_DENIED_TOOLS.join(' / ')}`);
295
- }
296
- }
332
+ const id = agentSessionId(agent);
333
+ if (id !== undefined)
334
+ seenAgents.set(id, agent);
335
+ converge(agent);
297
336
  }
298
337
  catch (error) {
299
338
  ctx.logger?.warn(`capital-generation: 根 Agent 工具收敛异常:${error instanceof Error ? error.message : String(error)}`);
300
339
  }
301
340
  });
341
+ // Manually opened root mode: preset is selected after agent/created, same as role presets.
342
+ const onAny = listenCtx.on;
343
+ const stopPreset = onAny?.('agent-preset/selected', (sessionId, presetId) => {
344
+ if (typeof sessionId !== 'string' || presetId !== CAPITAL_PRESET_ID)
345
+ return;
346
+ try {
347
+ const agents = ctx.get?.('agents');
348
+ const agent = seenAgents.get(sessionId) ?? agents?.get?.(sessionId);
349
+ if (agent !== undefined)
350
+ converge(agent);
351
+ }
352
+ catch (error) {
353
+ ctx.logger?.warn(`capital-generation: 根 preset 选择后收敛异常:${error instanceof Error ? error.message : String(error)}`);
354
+ }
355
+ });
302
356
  return () => {
303
357
  try {
304
358
  if (typeof stopCreated === 'function')
305
359
  stopCreated();
306
360
  }
307
361
  catch { /* ignore */ }
362
+ try {
363
+ if (typeof stopPreset === 'function')
364
+ stopPreset();
365
+ }
366
+ catch { /* ignore */ }
308
367
  };
309
368
  };
310
369
  if (typeof ctx.effect === 'function') {
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Root-only `wait_for_agents`: hold one turn across child relays; returns on the first relay, on
3
- * the tree settling, or after 30s. `waitForChildren` has no abort parameter; the slice races it.
4
- * Host contract: docs/reference/dsh-surface-ledger.md L36.
3
+ * the tree settling, or after 30s. Neither wait method has an abort parameter; the slice races it.
4
+ * rc.2 renamed `waitForChildren` to `waitForTreeWork`; accept both so a rollback does not brick the
5
+ * turn while rc.2 is the supported baseline. Host contract: docs/reference/dsh-surface-ledger.md L36.
5
6
  */
6
7
  import type { Context } from '@deepseek-ai/cordis';
7
8
  export interface WaitInboxLike {
@@ -26,7 +27,10 @@ export interface WaitDescendantLike {
26
27
  readonly activity?: string;
27
28
  }
28
29
  export interface WaitSubagentsLike {
29
- waitForChildren(parent: WaitAgentLike): Promise<boolean>;
30
+ /** rc.2 name. */
31
+ waitForTreeWork?(root: WaitAgentLike): Promise<boolean>;
32
+ /** rc.1 name; kept as a rollback escape hatch, not a supported baseline. */
33
+ waitForChildren?(parent: WaitAgentLike): Promise<boolean>;
30
34
  listDescendants?(rootSessionId: string, signal?: AbortSignal): Promise<readonly WaitDescendantLike[]>;
31
35
  }
32
36
  interface AgentsLike {
@@ -154,8 +154,9 @@ export function waitForAgentsToolDefinition(deps) {
154
154
  if (exec.signal.aborted)
155
155
  throw abortReason(exec.signal);
156
156
  const service = deps.subagents();
157
- if (service?.waitForChildren === undefined) {
158
- throw new Error('wait_for_agents 不可用:宿主 subagents 服务未挂载;不要用 list_agents 轮询代替。');
157
+ const waitTree = service?.waitForTreeWork ?? service?.waitForChildren;
158
+ if (service === undefined || typeof waitTree !== 'function') {
159
+ throw new Error('wait_for_agents 不可用:宿主未提供 waitForTreeWork/waitForChildren;不要用 list_agents 轮询代替。');
159
160
  }
160
161
  const started = now();
161
162
  const initial = pendingCounts(agent);
@@ -194,7 +195,7 @@ export function waitForAgentsToolDefinition(deps) {
194
195
  let outcome;
195
196
  const slice = waitTimer(waitSliceMs, exec.signal);
196
197
  try {
197
- const wait = Promise.resolve(service.waitForChildren(agent));
198
+ const wait = Promise.resolve(waitTree.call(service, agent));
198
199
  // The loser of the race must not become an unhandled rejection when the slice or a relay wins.
199
200
  wait.catch(() => undefined);
200
201
  outcome = await Promise.race([
@@ -37,8 +37,8 @@ function diagnosticsFor(ctx, config) {
37
37
  root: probe.root,
38
38
  presetId: probe.presetId,
39
39
  outcome: probe.outcome,
40
- // Roles have no allow-list (family rows define the surface); report sibling
41
- // denials and call-level guard rejections.
40
+ // Scoped tools come from family rows; host-global tools are gated by the
41
+ // role allow-list (not model-visible). `allowed` stays empty in this readout.
42
42
  allowed: [],
43
43
  denied: probe.denied,
44
44
  failed: probe.failed,
@@ -9,7 +9,7 @@ export interface DataCollectorDiagnostics {
9
9
  }>;
10
10
  /**
11
11
  * Tool-surface restriction snapshot (root/role policies), restated locally so this layer does
12
- * not depend on the agents layer. `allowed` stays empty now that allow-lists are gone.
12
+ * not depend on the agents layer. `allowed` stays empty: host-global allow-lists are not model-visible.
13
13
  */
14
14
  rootPolicy?: () => Array<{
15
15
  agentId: string | undefined;
@@ -1,3 +1,4 @@
1
+ import { UpstreamRetryBudget, classifyUpstreamFailure, retryBudgetKey, upstreamFailureError, } from './upstream-retry.js';
1
2
  // Session reading and authorization have one implementation (src/tool-exec.ts); do not re-implement here.
2
3
  import { authorizedSession, sessionIdentityDecisions } from '../tool-exec.js';
3
4
  import { DATA_COLLECTION_PRESET_IDS } from '../preset-ids.js';
@@ -123,8 +124,9 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
123
124
  const tools = ctx.get('tools');
124
125
  if (!tools)
125
126
  return;
127
+ const retryBudget = new UpstreamRetryBudget();
126
128
  const registrations = [
127
- tool('request_data', '向数据管道请求数据:宿主先按 capability+params 校验当前 session 的已验证 manifest;force_refresh=false 或省略且命中未过期、满足该来源缓存新鲜度的 Dataset 时直接返回已有 DatasetRef,不访问上游;force_refresh=true 才重新取数并生成新的不可变 Dataset(默认保留 7 天),绝不覆盖旧 Dataset。明确要现在/最新的行情快照时请用 force_refresh=true,7 天是保留期而非实时新鲜度。本工具只返回 DatasetRef(dataset_id / artifact_ref / schema / row_count / captured_at / retention_until 等元数据),绝不返回原始数据行。capability 必须是 list_capabilities 返回的短能力名(如 ticker_search / quote / history / trading_calendar),params 必须按 describe_capability({ capability }) 返回的 input_schema 填写。若返回 request_params_invalid,先重新调用 describe_capability({ capability: "<当前能力名>" }),再按 schema 修正并重试一次;不要凭记忆猜参数。task_id 必须由主 Agent 在本轮委派前确定,并在所有子 Agent 与最终报告中原样复用;不要由 data_collector 自行生成。相同 capability+params 的并发请求合并为同一次执行。当前 workspace 只读或落盘失败时抛错 workspace_not_writable(绝不退化为内存假成功)。请求归属自动记为当前 delegated child session,不接收 requester_agent_id 参数。', jsonObject({
129
+ tool('request_data', '向数据管道请求数据:宿主先按 capability+params 校验当前 session 的已验证 manifest;force_refresh=false 或省略且命中未过期、满足该来源缓存新鲜度的 Dataset 时直接返回已有 DatasetRef,不访问上游;force_refresh=true 才重新取数并生成新的不可变 Dataset(默认保留 7 天),绝不覆盖旧 Dataset。明确要现在/最新的行情快照时请用 force_refresh=true,7 天是保留期而非实时新鲜度。本工具只返回 DatasetRef(dataset_id / artifact_ref / schema / row_count / captured_at / retention_until 等元数据),绝不返回原始数据行。capability 必须是 list_capabilities 返回的短能力名(如 ticker_search / quote / history / trading_calendar),params 必须按 describe_capability({ capability }) 返回的 input_schema 填写。若返回 request_params_invalid,先重新调用 describe_capability({ capability: "<当前能力名>" }),再按 schema 修正并重试一次;不要凭记忆猜参数。可重试上游失败(限流、网络、超时、5xx)对同一 capability 最多 3 次尝试;返回 upstream_retry_exhausted 后停止重试,改用等价能力或回告主 Agent,不要用 wait_agent 等上游恢复。task_id 必须由主 Agent 在本轮委派前确定,并在所有子 Agent 与最终报告中原样复用;不要由 data_collector 自行生成。相同 capability+params 的并发请求合并为同一次执行。当前 workspace 只读或落盘失败时抛错 workspace_not_writable(绝不退化为内存假成功)。请求归属自动记为当前 delegated child session,不接收 requester_agent_id 参数。', jsonObject({
128
130
  capability: { type: 'string' },
129
131
  params: freeObject,
130
132
  force_refresh: { type: 'boolean' },
@@ -132,20 +134,46 @@ export function registerDataCollectorTools(ctx, hub, diagnostics) {
132
134
  }, ['capability', 'params', 'task_id']), datasetRefSchema(), async (args, exec) => {
133
135
  const requestedCapability = boundedString(args.capability, 'capability', MAX_ID_LENGTH);
134
136
  const session = authorizedSession(ctx, exec, 'request_data', DATA_COLLECTION_PRESET_IDS);
137
+ let budgetKey;
138
+ let capability;
135
139
  try {
136
140
  const params = boundedParams(args.params);
137
141
  // Fail early with the same catalog guidance as describe_capability instead of
138
142
  // making the model infer a capability typo from a low-level Hub error.
139
- const capability = resolveCapability(hub, requestedCapability);
140
- return await hub.request({
143
+ capability = resolveCapability(hub, requestedCapability);
144
+ budgetKey = retryBudgetKey(session.id, capability);
145
+ const prior = retryBudget.inspect(budgetKey);
146
+ if (prior?.exhausted) {
147
+ throw upstreamFailureError({
148
+ capability,
149
+ failure: prior.failure,
150
+ attempts: prior.attempts,
151
+ maxAttempts: retryBudget.maxAttempts,
152
+ terminal: true,
153
+ });
154
+ }
155
+ const ref = await hub.request({
141
156
  capability,
142
157
  params,
143
158
  force_refresh: args.force_refresh === true,
144
159
  task_id: boundedString(args.task_id, 'task_id', MAX_ID_LENGTH),
145
160
  session,
146
161
  }, { signal: exec.signal });
162
+ retryBudget.reset(budgetKey);
163
+ return ref;
147
164
  }
148
165
  catch (error) {
166
+ const failure = capability && budgetKey ? classifyUpstreamFailure(error) : null;
167
+ if (failure && budgetKey && capability) {
168
+ const snapshot = retryBudget.record(budgetKey, failure);
169
+ throw upstreamFailureError({
170
+ capability,
171
+ failure,
172
+ attempts: snapshot.attempts,
173
+ maxAttempts: retryBudget.maxAttempts,
174
+ terminal: snapshot.exhausted,
175
+ });
176
+ }
149
177
  throw requestParamsError(error, requestedCapability) ?? error;
150
178
  }
151
179
  }),
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Retry budget for `request_data` upstream failures: three attempts per session+capability.
3
+ * Only rate limits, transport failures, timeouts and 5xx count; parameter/credential errors never do.
4
+ */
5
+ export declare const MAX_UPSTREAM_ATTEMPTS = 3;
6
+ export declare const UPSTREAM_RETRY_WINDOW_MS: number;
7
+ export type UpstreamFailureKind = 'rate_limited' | 'transport' | 'timeout' | 'server';
8
+ export interface UpstreamFailure {
9
+ kind: UpstreamFailureKind;
10
+ message: string;
11
+ }
12
+ export interface RetryBudgetSnapshot {
13
+ attempts: number;
14
+ exhausted: boolean;
15
+ failure: UpstreamFailure;
16
+ }
17
+ /**
18
+ * Classify only failures worth another upstream call. A `fetch failed` is a transport failure, not a
19
+ * rate limit; the two stay separate so the model can report what actually happened.
20
+ */
21
+ export declare function classifyUpstreamFailure(error: unknown): UpstreamFailure | null;
22
+ /** Per-session+capability consecutive-failure counter; success or a five-minute gap resets it. */
23
+ export declare class UpstreamRetryBudget {
24
+ readonly maxAttempts: number;
25
+ private readonly windowMs;
26
+ private readonly now;
27
+ private readonly entries;
28
+ constructor(options?: {
29
+ maxAttempts?: number;
30
+ windowMs?: number;
31
+ now?: () => number;
32
+ });
33
+ inspect(key: string): RetryBudgetSnapshot | undefined;
34
+ record(key: string, failure: UpstreamFailure): RetryBudgetSnapshot;
35
+ reset(key: string): void;
36
+ private liveEntry;
37
+ private prune;
38
+ }
39
+ export declare function retryBudgetKey(sessionId: string, capability: string): string;
40
+ export declare function alternativesFor(capability: string): readonly string[];
41
+ /** Model-visible error; `terminal` is the third failure and carries the stop/report instruction. */
42
+ export declare function upstreamFailureError(input: {
43
+ capability: string;
44
+ failure: UpstreamFailure;
45
+ attempts: number;
46
+ maxAttempts?: number;
47
+ terminal: boolean;
48
+ }): Error;
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Retry budget for `request_data` upstream failures: three attempts per session+capability.
3
+ * Only rate limits, transport failures, timeouts and 5xx count; parameter/credential errors never do.
4
+ */
5
+ export const MAX_UPSTREAM_ATTEMPTS = 3;
6
+ export const UPSTREAM_RETRY_WINDOW_MS = 5 * 60_000;
7
+ const RATE_LIMIT_CODES = new Set(['rate_limited', 'eastmoney_rate_limit', 'tencent_rate_limit']);
8
+ const PERMANENT_CODES = new Set([
9
+ 'credential_missing', 'capability_closed', 'plan_closed', 'invalid_parameter',
10
+ 'request_params_invalid', 'workspace_not_writable', 'upstream_retry_exhausted',
11
+ 'tencent_invalid_param', 'tencent_empty_response', 'tencent_invalid_response',
12
+ 'eastmoney_invalid_response', 'eastmoney_upstream_error',
13
+ ]);
14
+ const TRANSIENT_CODES = new Set(['tencent_kline_unavailable']);
15
+ const PERMANENT_CODE_PREFIXES = [
16
+ 'credential_', 'capability_', 'plan_', 'invalid_', 'request_params_',
17
+ 'workspace_', 'dataset_', 'upstream_retry_',
18
+ ];
19
+ const PERMANENT_PATTERN = /workspace_not_writable|credential_missing|capability_closed|plan_closed|request_params_invalid|invalid_parameter|unsupported parameter|\bparameter\b[^.]*\bmust\b|API error (?:1002|1003|2004)|HTTP (?:400|401|402|403|404|405|409|410|422)\b/i;
20
+ const RATE_LIMIT_PATTERN = /\b429\b|\b4001\b|rate.?limit|too many requests/i;
21
+ const TIMEOUT_PATTERN = /request timed out|timed out|timeout|ETIMEDOUT|ESOCKETTIMEDOUT/i;
22
+ const TRANSPORT_PATTERN = /fetch failed|ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|EPIPE|socket hang up|network error|connection reset|connection refused|TLS|certificate/i;
23
+ const SERVER_PATTERN = /HTTP (?:error )?5\d\d|bad gateway|service unavailable|gateway timeout|server error/i;
24
+ /** Capability-level substitutes that are actually equivalent enough to hint at; schema still needs a check. */
25
+ const UPSTREAM_ALTERNATIVES = Object.freeze({
26
+ index_quote: ['tencent_quote'],
27
+ quote: ['ftshare_ashare_quote', 'tencent_quote'],
28
+ ftshare_ashare_quote: ['quote', 'tencent_quote'],
29
+ history: ['tencent_kline'],
30
+ index_history: ['tencent_kline'],
31
+ tencent_quote: ['quote', 'ftshare_ashare_quote'],
32
+ tencent_kline: ['history', 'index_history'],
33
+ });
34
+ function codeOf(error) {
35
+ if (!error || typeof error !== 'object')
36
+ return undefined;
37
+ const code = error.code;
38
+ return typeof code === 'string' ? code : undefined;
39
+ }
40
+ function statusOf(error) {
41
+ if (!error || typeof error !== 'object')
42
+ return undefined;
43
+ const status = error.status;
44
+ return typeof status === 'number' ? status : undefined;
45
+ }
46
+ function kindOf(error) {
47
+ if (!error || typeof error !== 'object')
48
+ return undefined;
49
+ const kind = error.kind;
50
+ return typeof kind === 'string' ? kind : undefined;
51
+ }
52
+ function nameOf(error) {
53
+ if (!error || typeof error !== 'object')
54
+ return undefined;
55
+ const name = error.name;
56
+ return typeof name === 'string' ? name : undefined;
57
+ }
58
+ function permanentCode(code) {
59
+ if (!code)
60
+ return false;
61
+ if (PERMANENT_CODES.has(code))
62
+ return true;
63
+ return PERMANENT_CODE_PREFIXES.some((prefix) => code.startsWith(prefix));
64
+ }
65
+ /**
66
+ * Classify only failures worth another upstream call. A `fetch failed` is a transport failure, not a
67
+ * rate limit; the two stay separate so the model can report what actually happened.
68
+ */
69
+ export function classifyUpstreamFailure(error) {
70
+ if (error === undefined || error === null)
71
+ return null;
72
+ const message = error instanceof Error ? error.message : String(error);
73
+ const code = codeOf(error);
74
+ const status = statusOf(error);
75
+ const kind = kindOf(error);
76
+ if (nameOf(error) === 'AbortError' || code === 'ABORTED' || /\brequest aborted\b/i.test(message))
77
+ return null;
78
+ if (permanentCode(code))
79
+ return null;
80
+ if (kind === 'credential_missing' || kind === 'capability_closed' || kind === 'plan_closed' || kind === 'invalid_parameter')
81
+ return null;
82
+ if (kind === 'rate_limited')
83
+ return { kind: 'rate_limited', message };
84
+ if (code && RATE_LIMIT_CODES.has(code))
85
+ return { kind: 'rate_limited', message };
86
+ if (status === 429)
87
+ return { kind: 'rate_limited', message };
88
+ // Eastmoney IP bans surface as 403; other 403s are plan/permission errors and must not be retried.
89
+ if (status === 403)
90
+ return /eastmoney/i.test(message) ? { kind: 'rate_limited', message } : null;
91
+ if (status === 408)
92
+ return { kind: 'timeout', message };
93
+ if (status !== undefined && status >= 500 && status <= 599)
94
+ return { kind: 'server', message };
95
+ if (code && TRANSIENT_CODES.has(code))
96
+ return { kind: 'transport', message };
97
+ if (/eastmoney HTTP 403/i.test(message))
98
+ return { kind: 'rate_limited', message };
99
+ if (PERMANENT_PATTERN.test(message))
100
+ return null;
101
+ if (RATE_LIMIT_PATTERN.test(message))
102
+ return { kind: 'rate_limited', message };
103
+ if (TIMEOUT_PATTERN.test(message))
104
+ return { kind: 'timeout', message };
105
+ if (TRANSPORT_PATTERN.test(message))
106
+ return { kind: 'transport', message };
107
+ if (SERVER_PATTERN.test(message))
108
+ return { kind: 'server', message };
109
+ return null;
110
+ }
111
+ /** Per-session+capability consecutive-failure counter; success or a five-minute gap resets it. */
112
+ export class UpstreamRetryBudget {
113
+ maxAttempts;
114
+ windowMs;
115
+ now;
116
+ entries = new Map();
117
+ constructor(options = {}) {
118
+ this.maxAttempts = options.maxAttempts ?? MAX_UPSTREAM_ATTEMPTS;
119
+ this.windowMs = options.windowMs ?? UPSTREAM_RETRY_WINDOW_MS;
120
+ this.now = options.now ?? (() => Date.now());
121
+ if (!Number.isSafeInteger(this.maxAttempts) || this.maxAttempts < 1)
122
+ throw new Error('maxAttempts must be a positive safe integer');
123
+ if (!Number.isFinite(this.windowMs) || this.windowMs <= 0)
124
+ throw new Error('windowMs must be positive');
125
+ }
126
+ inspect(key) {
127
+ const entry = this.liveEntry(key);
128
+ if (!entry)
129
+ return undefined;
130
+ return { attempts: entry.attempts, exhausted: entry.attempts >= this.maxAttempts, failure: entry.failure };
131
+ }
132
+ record(key, failure) {
133
+ const existing = this.liveEntry(key);
134
+ const attempts = existing ? existing.attempts + 1 : 1;
135
+ this.entries.set(key, { attempts, at: this.now(), failure });
136
+ this.prune();
137
+ return { attempts, exhausted: attempts >= this.maxAttempts, failure };
138
+ }
139
+ reset(key) {
140
+ this.entries.delete(key);
141
+ }
142
+ liveEntry(key) {
143
+ const entry = this.entries.get(key);
144
+ if (!entry)
145
+ return undefined;
146
+ if (this.now() - entry.at > this.windowMs) {
147
+ this.entries.delete(key);
148
+ return undefined;
149
+ }
150
+ return entry;
151
+ }
152
+ prune() {
153
+ const now = this.now();
154
+ for (const [key, entry] of this.entries) {
155
+ if (now - entry.at > this.windowMs)
156
+ this.entries.delete(key);
157
+ }
158
+ if (this.entries.size <= 1000)
159
+ return;
160
+ const oldest = [...this.entries.entries()].sort((a, b) => a[1].at - b[1].at).slice(0, this.entries.size - 1000);
161
+ for (const [key] of oldest)
162
+ this.entries.delete(key);
163
+ }
164
+ }
165
+ export function retryBudgetKey(sessionId, capability) {
166
+ return `${sessionId}\u0000${capability}`;
167
+ }
168
+ export function alternativesFor(capability) {
169
+ return UPSTREAM_ALTERNATIVES[capability] ?? [];
170
+ }
171
+ /** Model-visible error; `terminal` is the third failure and carries the stop/report instruction. */
172
+ export function upstreamFailureError(input) {
173
+ const maxAttempts = input.maxAttempts ?? MAX_UPSTREAM_ATTEMPTS;
174
+ const alternatives = alternativesFor(input.capability);
175
+ const alternativeText = alternatives.length > 0
176
+ ? `可改用 ${alternatives.join(' / ')}(先用 describe_capability 核对字段、单位与代码范围;切换后在 source_label 注明)。`
177
+ : '没有已核对的等价上游。';
178
+ const state = input.terminal
179
+ ? `已连续 ${input.attempts} 次可重试失败`
180
+ : `第 ${input.attempts}/${maxAttempts} 次可重试失败`;
181
+ const next = input.terminal
182
+ ? `已停止重试:不要再次调用 ${input.capability},也不要用 wait_agent 等上游恢复。${alternativeText}立即发 data_failed + data_collection_completed,如实回告 lead。`
183
+ : `不要用 wait_agent 等;${alternativeText}若无法切换再重试,最多 ${maxAttempts} 次。`;
184
+ const prefix = input.terminal ? 'upstream_retry_exhausted' : 'upstream_retryable_failure';
185
+ const error = new Error(`${prefix}: ${input.capability} ${state}(${input.failure.kind}: ${input.failure.message})。${next}`);
186
+ const tagged = error;
187
+ tagged.code = input.terminal ? 'upstream_retry_exhausted' : 'upstream_retryable_failure';
188
+ tagged.attempts = input.attempts;
189
+ tagged.capability = input.capability;
190
+ tagged.alternatives = alternatives;
191
+ return error;
192
+ }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Host-plane Capital policy row: call-level gates that preset composition cannot express.
3
- * Root convergence (visibility already closed by family rows), per-name sibling deny,
4
- * call-level guards for the `ocr` url form and role `interrupt_agent`, plus shell and fs
5
- * guards. Identity must be read per call: the host creates the Agent before selecting a
3
+ * Root host-global deny, role host-global allow-list (family rows own scoped tools), per-name
4
+ * sibling deny, call-level guards for the `ocr` url form and role `interrupt_agent`, plus shell
5
+ * and fs guards. Identity must be read per call: the host creates the Agent before selecting a
6
6
  * preset. Also hides delegation-only roles from the remote roster. Listens on `ctx.root`;
7
7
  * one registration per process.
8
8
  */
@@ -1,4 +1,5 @@
1
1
  import { registerBashGuard } from './agents/bash-guard.js';
2
+ import { registerSendMessageGuard } from './agents/messaging-policy.js';
2
3
  import { registerPresetRosterFilter } from './agents/preset-roster.js';
3
4
  import { registerFsWriteGuard, registerRootOcrGuard, registerRootToolPolicy } from './agents/root-tool-policy.js';
4
5
  import { registerRoleSiblingGuard, registerRoleToolPolicy } from './agents/role-tool-policy.js';
@@ -12,10 +13,11 @@ export const inject = ['tools'];
12
13
  export function apply(ctx) {
13
14
  const policy = ctx;
14
15
  // Preset rows now own visibility; the host keeps only call-level gates.
15
- registerRootToolPolicy(policy, { deny: false });
16
+ registerRootToolPolicy(policy);
16
17
  registerRootOcrGuard(policy);
17
18
  registerRoleToolPolicy(policy);
18
19
  registerRoleSiblingGuard(policy);
20
+ registerSendMessageGuard(policy);
19
21
  registerBashGuard(policy);
20
22
  registerFsWriteGuard(policy);
21
23
  registerPresetRosterFilter(ctx);
@@ -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.21.4";
6
+ export declare const LOCAL_FETCH_CLIENT_VERSION = "2.22.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.21.4';
7
+ export const LOCAL_FETCH_CLIENT_VERSION = '2.22.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.21.4";
38
+ export declare const WIND_CLIENT_VERSION = "2.22.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.21.4';
22
+ export const WIND_CLIENT_VERSION = '2.22.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.21.4",
3
+ "version": "2.22.0",
4
4
  "description": "Capital Generation:面向中国散户的 AI 投资助手插件(自动模式 Agent Preset)",
5
5
  "icon": "assets/cg-icon.png",
6
6
  "author": "v587d",
@@ -163,14 +163,14 @@
163
163
  },
164
164
  "peerDependencies": {
165
165
  "@deepseek-ai/cordis": "~4.1.0",
166
- "@deepseek-ai/dsh-skill": "0.2.2-rc.1",
167
- "@deepseek-ai/dsh-skill-filesystem": "0.2.2-rc.1"
166
+ "@deepseek-ai/dsh-skill": "0.2.2-rc.2",
167
+ "@deepseek-ai/dsh-skill-filesystem": "0.2.2-rc.2"
168
168
  },
169
169
  "devDependencies": {
170
170
  "@deepseek-ai/cordis": "~4.1.0",
171
- "@deepseek-ai/dsh-skill": "^0.2.2-rc.1",
172
- "@deepseek-ai/dsh-skill-filesystem": "^0.2.2-rc.1",
173
- "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.1",
171
+ "@deepseek-ai/dsh-skill": "^0.2.2-rc.2",
172
+ "@deepseek-ai/dsh-skill-filesystem": "^0.2.2-rc.2",
173
+ "@deepseek-ai/dsh-system-prompt": "^0.2.2-rc.2",
174
174
  "@deepseek-ai/schemastery": "^3.19.0",
175
175
  "esbuild": "^0.28.2",
176
176
  "js-yaml": "^5.4.1",
@@ -103,7 +103,8 @@
103
103
  替代是「persona 与工具插件改住 Agent Preset,委派行只用 `agentPreset` 选它」——这一条我们做到底:
104
104
  本仓当前由 preset 族行暴露的 29 颗模型工具,按族拆成
105
105
  `@v587d/capital-generation/tools/<family>` 的 subpath 入口行
106
- (`package.json` 的 `exports`),每颗 preset 只挂自己那几族,**不再有运行期名字级 allow 名单**。
106
+ (`package.json` 的 `exports`),每颗 preset 只挂自己那几族;宿主全局工具另由
107
+ `role-tool-policy` 的显式白名单收口(**scoped 工具面仍只由族行决定**)。
107
108
  行契约(那一行注册哪些名字)只有一份,住 `test/family-rows.mjs`:`test/family-entries.test.mjs`
108
109
  拿它实测每个入口注册了什么,`test/persona.test.mjs` 拿它核对 YAML 的组合结果。
109
110
  - collector:`tools/collect` + `tools/time`;junior:`tools/dataset-read` + `tools/chart-source` +