@v587d/capital-generation 2.21.3 → 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 (44) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +5 -5
  3. package/automation/board.js +89 -22
  4. package/automation/brief.js +60 -28
  5. package/automation/client.js +3 -3
  6. package/automation/client.src.cjs +5 -1
  7. package/automation/index.js +35 -0
  8. package/automation/json-text.js +69 -0
  9. package/automation/package.json +1 -1
  10. package/automation/runner.js +3 -2
  11. package/automation/watch.js +1 -59
  12. package/chart-ui/package.json +1 -1
  13. package/config/package.json +1 -1
  14. package/lib/agents/messaging-policy.d.ts +21 -0
  15. package/lib/agents/messaging-policy.js +100 -0
  16. package/lib/agents/role-tool-policy.d.ts +23 -7
  17. package/lib/agents/role-tool-policy.js +118 -33
  18. package/lib/agents/root-tool-policy.d.ts +13 -2
  19. package/lib/agents/root-tool-policy.js +87 -28
  20. package/lib/agents/wait-for-agents.d.ts +7 -3
  21. package/lib/agents/wait-for-agents.js +4 -3
  22. package/lib/collector-runtime.js +2 -2
  23. package/lib/data-collector/tools.d.ts +1 -1
  24. package/lib/data-collector/tools.js +31 -3
  25. package/lib/data-collector/upstream-retry.d.ts +48 -0
  26. package/lib/data-collector/upstream-retry.js +192 -0
  27. package/lib/policy-entry.d.ts +3 -3
  28. package/lib/policy-entry.js +3 -1
  29. package/lib/web-retriever/local-fetch.d.ts +1 -1
  30. package/lib/web-retriever/local-fetch.js +1 -1
  31. package/lib/web-retriever/wind-client.d.ts +1 -1
  32. package/lib/web-retriever/wind-client.js +1 -1
  33. package/package.json +6 -6
  34. package/preset/capital-generation/README.md +2 -1
  35. package/preset/capital-generation/agent.patch.yml +58 -44
  36. package/preset/capital-generation/skills/capital-data-profile/SKILL.md +2 -2
  37. package/preset/capital-generation/skills/capital-data-protocol/SKILL.md +20 -8
  38. package/preset/capital-generation/skills/capital-data-query/SKILL.md +2 -2
  39. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  40. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  41. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +70 -72
  42. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  43. package/preset/capital-generation/skills/capital-visualization-protocol/SKILL.md +1 -0
  44. package/watchlist/package.json +1 -1
@@ -1,23 +1,42 @@
1
1
  /**
2
- * Role tool surfaces by mounted role preset. `toolFilter` was removed upstream, so tools come
3
- * from family rows (composition) and there is no allow-list here. Restricting the agent scope
4
- * filters preset contributions; identity is the preset id, not root/child. Listeners on `ctx.root`.
2
+ * Role tool surfaces by mounted role preset. Family rows define scoped tools; host-global tools
3
+ * are intersected with an explicit allow-list so a new dsh-base tool cannot leak into a leaf.
4
+ * Identity is the preset id, not root/child. Listeners live on `ctx.root`.
5
5
  */
6
- import { isRootAgent, recordGuardDecision } from './root-tool-policy.js';
6
+ import { isRootAgent, OCR_TOOL_NAME, recordGuardDecision, RETRIEVAL_DENIED_TOOLS, TEAM_DENIED_TOOLS } from './root-tool-policy.js';
7
7
  import { readPresetClaim } from '../preset-claim.js';
8
8
  import { ROLE_PRESET_ID_LIST, ROLE_PRESET_IDS } from '../preset-ids.js';
9
9
  export { ROLE_PRESET_IDS, ROLE_PRESET_ID_LIST } from '../preset-ids.js';
10
10
  /** Registered together with `send_message` by `tool-subagent-control`; no host switch, so leaf roles deny these by name.
11
11
  * 0.2.2 moved `list_agents` into the same main entry, so the welded set grew from one to two names. */
12
12
  export const SIBLING_DENIED_TOOLS = ['interrupt_agent', 'list_agents'];
13
- /** Leaf roles need `send_message`, so they inherit the welded `interrupt_agent` / `list_agents`;
14
- * specialist mounts no control row. Tolerant per-name deny records misses without failing open. */
13
+ /** Shared leaf capabilities that are host-global in rc.2, not preset-scoped. */
14
+ const ROLE_MESSAGING_TOOLS = ['send_message', 'skill'];
15
+ const ROLE_TIME_TOOLS = ['get_local_datetime', 'resolve_data_time_range'];
16
+ /** Full intended surface; only names that resolve as host-global are enforced by the allow-list.
17
+ * Scoped family-row tools stay visible regardless; they must remain in this list for review. */
18
+ export const COLLECTOR_ROLE_TOOLS = [
19
+ ...ROLE_MESSAGING_TOOLS, ...ROLE_TIME_TOOLS,
20
+ 'request_data', 'list_capabilities', 'describe_capability', 'dc_status',
21
+ ];
22
+ export const RETRIEVER_ROLE_TOOLS = [
23
+ ...ROLE_MESSAGING_TOOLS, ...ROLE_TIME_TOOLS, ...RETRIEVAL_DENIED_TOOLS,
24
+ OCR_TOOL_NAME, 'anysearch_batch_search', 'anysearch_capabilities',
25
+ ];
26
+ export const SPECIALIST_ROLE_TOOLS = [
27
+ ...ROLE_TIME_TOOLS, 'skill', 'render_chart',
28
+ ];
29
+ /** Every role denies Team tools. Only control-row roles also deny the welded sibling names. */
30
+ const DENY_TEAM = { denyTeam: TEAM_DENIED_TOOLS };
31
+ /** Leaf roles need `send_message`, so they inherit the welded `interrupt_agent` / `list_agents`.
32
+ * Junior runs only through PTC (run_code is reserved and cannot be named by restrict), so its
33
+ * surface is already narrowed by the executor and no allow-list is applied. */
15
34
  export const ROLE_TOOL_SURFACES = {
16
- [ROLE_PRESET_IDS.collector]: { denySiblings: SIBLING_DENIED_TOOLS },
17
- [ROLE_PRESET_IDS.junior]: { denySiblings: SIBLING_DENIED_TOOLS },
18
- [ROLE_PRESET_IDS.retriever]: { denySiblings: SIBLING_DENIED_TOOLS },
19
- [ROLE_PRESET_IDS.specialist]: {},
20
- [ROLE_PRESET_IDS.analyst]: { denySiblings: SIBLING_DENIED_TOOLS },
35
+ [ROLE_PRESET_IDS.collector]: { allowTools: COLLECTOR_ROLE_TOOLS, denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
36
+ [ROLE_PRESET_IDS.junior]: { denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
37
+ [ROLE_PRESET_IDS.retriever]: { allowTools: RETRIEVER_ROLE_TOOLS, denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
38
+ [ROLE_PRESET_IDS.specialist]: { allowTools: SPECIALIST_ROLE_TOOLS, ...DENY_TEAM },
39
+ [ROLE_PRESET_IDS.analyst]: { denySiblings: SIBLING_DENIED_TOOLS, ...DENY_TEAM },
21
40
  };
22
41
  /** Role preset id only, undefined for root and other presets; failure means "do not converge". */
23
42
  export function rolePresetIdOf(ctx, agent) {
@@ -33,14 +52,20 @@ const installedRoots = new WeakSet();
33
52
  /** Call-level guard installs independently of the listener. */
34
53
  const installedGuardRoots = new WeakSet();
35
54
  export function rolePolicyProbes() {
36
- return probes.map((probe) => ({ ...probe, denied: [...probe.denied], failed: [...probe.failed] }));
55
+ return probes.map((probe) => ({
56
+ ...probe,
57
+ denied: [...probe.denied],
58
+ failed: [...probe.failed],
59
+ ...(probe.allowedGlobals === undefined ? {} : { allowedGlobals: [...probe.allowedGlobals] }),
60
+ ...(probe.removedGlobals === undefined ? {} : { removedGlobals: [...probe.removedGlobals] }),
61
+ }));
37
62
  }
38
63
  /** Test-only: clears records and the dedupe table. */
39
64
  export function resetRolePolicyProbes() {
40
65
  probes.length = 0;
41
66
  handled.clear();
42
67
  }
43
- /** Tolerant per-name deny: invisible names are recorded, never thrown; called on agent creation. */
68
+ /** Tolerant deny plus host-global allow-list: invisible names are recorded, never thrown. */
44
69
  export function restrictRoleAgentTools(agent, surface) {
45
70
  const denied = [];
46
71
  const failed = [];
@@ -54,7 +79,30 @@ export function restrictRoleAgentTools(agent, surface) {
54
79
  if (tools === undefined || typeof tools.restrict !== 'function') {
55
80
  return { outcome: 'unavailable', denied, failed };
56
81
  }
57
- for (const name of surface.denySiblings ?? []) {
82
+ let allowedGlobals;
83
+ let removedGlobals;
84
+ let allowFailed = false;
85
+ if (surface.allowTools !== undefined) {
86
+ try {
87
+ const restrictable = tools.view?.(agent)?.restrictableNames;
88
+ if (restrictable === undefined) {
89
+ // Without the pre-restriction view we cannot tell inherited tools from the role's own
90
+ // scoped rows; an allow-list built from the global view would hide send_message.
91
+ allowFailed = true;
92
+ }
93
+ else {
94
+ const names = new Set(restrictable);
95
+ allowedGlobals = [...new Set(surface.allowTools)].filter((name) => names.has(name)).sort();
96
+ removedGlobals = [...names].filter((name) => !allowedGlobals.includes(name)).sort();
97
+ if (names.size > 0)
98
+ tools.restrict({ allow: allowedGlobals });
99
+ }
100
+ }
101
+ catch {
102
+ allowFailed = true;
103
+ }
104
+ }
105
+ for (const name of [...(surface.denySiblings ?? []), ...(surface.denyTeam ?? [])]) {
58
106
  try {
59
107
  tools.restrict({ deny: [name] });
60
108
  denied.push(name);
@@ -63,7 +111,14 @@ export function restrictRoleAgentTools(agent, surface) {
63
111
  failed.push(name);
64
112
  }
65
113
  }
66
- return { outcome: 'restricted', denied, failed };
114
+ return {
115
+ outcome: 'restricted',
116
+ denied,
117
+ failed,
118
+ ...(allowedGlobals === undefined ? {} : { allowedGlobals }),
119
+ ...(removedGlobals === undefined ? {} : { removedGlobals }),
120
+ ...(allowFailed ? { allowFailed } : {}),
121
+ };
67
122
  }
68
123
  /** Call-level residual guard: created-time restrict misses manually opened role modes, so
69
124
  * read identity per call. Fail open unless a role preset is confirmed. */
@@ -144,39 +199,64 @@ export function registerRoleToolPolicy(ctx) {
144
199
  return;
145
200
  installedRoots.add(listenCtx);
146
201
  const install = () => {
202
+ const seenAgents = new Map();
203
+ const converge = (agent, presetId) => {
204
+ const id = typeof agent?.session?.id === 'string' ? agent.session.id : undefined;
205
+ if (id !== undefined && handled.has(id))
206
+ return;
207
+ const surface = ROLE_TOOL_SURFACES[presetId];
208
+ const result = restrictRoleAgentTools(agent, surface);
209
+ if (id !== undefined)
210
+ handled.add(id);
211
+ probes.push({ agentId: id, root: isRootAgent(agent), presetId, ...result });
212
+ if (probes.length > MAX_PROBES)
213
+ probes.shift();
214
+ if (result.outcome === 'unavailable') {
215
+ ctx.logger?.warn(`capital-generation: 角色 ${presetId} 的工具收敛没装上(restrict 面不可用):该 child 仍看得见 ${[...SIBLING_DENIED_TOOLS, ...TEAM_DENIED_TOOLS].join(' / ')}`);
216
+ }
217
+ else if (result.allowFailed) {
218
+ ctx.logger?.warn(`capital-generation: 角色 ${presetId} 的宿主全局工具白名单没装上(definitions/allow 面不可用):该 child 仍可能看到未授权的宿主工具`);
219
+ }
220
+ };
147
221
  const stopCreated = listenCtx.on?.('agent/created', (payload) => {
148
222
  try {
149
223
  const agent = payload?.agent;
150
224
  const id = typeof agent?.session?.id === 'string' ? agent.session.id : undefined;
151
- if (id !== undefined && handled.has(id))
152
- return;
225
+ if (id !== undefined)
226
+ seenAgents.set(id, agent);
153
227
  const presetId = rolePresetIdOf(ctx, agent);
154
228
  if (presetId === undefined)
155
229
  return;
156
- const surface = ROLE_TOOL_SURFACES[presetId];
157
- if (surface.denySiblings === undefined || surface.denySiblings.length === 0) {
158
- if (id !== undefined)
159
- handled.add(id);
160
- return;
161
- }
162
- const result = restrictRoleAgentTools(agent, surface);
163
- if (id !== undefined)
164
- handled.add(id);
165
- probes.push({ agentId: id, root: isRootAgent(agent), presetId, ...result });
166
- if (probes.length > MAX_PROBES)
167
- probes.shift();
168
- if (result.outcome === 'unavailable') {
169
- ctx.logger?.warn(`capital-generation: 角色 ${presetId} 的兄弟名字收敛没装上(restrict 面不可用):该 child 仍看得见 ${SIBLING_DENIED_TOOLS.join(' / ')}`);
170
- }
230
+ converge(agent, presetId);
171
231
  }
172
232
  catch (error) {
173
233
  ctx.logger?.warn(`capital-generation: 角色工具面收敛异常:${error instanceof Error ? error.message : String(error)}`);
174
234
  }
175
235
  });
236
+ // Manually opened role presets are selected after agent/created; the preset event is the
237
+ // only point where the agent exists and the role identity is known.
238
+ const onAny = listenCtx.on;
239
+ const stopPreset = onAny?.('agent-preset/selected', (sessionId, presetId) => {
240
+ if (typeof sessionId !== 'string' || typeof presetId !== 'string')
241
+ return;
242
+ if (!ROLE_PRESET_ID_LIST.includes(presetId))
243
+ return;
244
+ try {
245
+ const agents = ctx.get?.('agents');
246
+ const agent = seenAgents.get(sessionId) ?? agents?.get?.(sessionId);
247
+ if (agent !== undefined)
248
+ converge(agent, presetId);
249
+ }
250
+ catch (error) {
251
+ ctx.logger?.warn(`capital-generation: 角色 preset 选择后收敛异常:${error instanceof Error ? error.message : String(error)}`);
252
+ }
253
+ });
176
254
  const stopDisposed = listenCtx.on?.('agent/disposed', (payload) => {
177
255
  const id = typeof payload?.agent?.session?.id === 'string' ? payload.agent.session.id : undefined;
178
- if (id !== undefined)
256
+ if (id !== undefined) {
179
257
  handled.delete(id);
258
+ seenAgents.delete(id);
259
+ }
180
260
  });
181
261
  return () => {
182
262
  try {
@@ -184,6 +264,11 @@ export function registerRoleToolPolicy(ctx) {
184
264
  stopCreated();
185
265
  }
186
266
  catch { /* ignore */ }
267
+ try {
268
+ if (typeof stopPreset === 'function')
269
+ stopPreset();
270
+ }
271
+ catch { /* ignore */ }
187
272
  try {
188
273
  if (typeof stopDisposed === 'function')
189
274
  stopDisposed();
@@ -4,6 +4,8 @@
4
4
  */
5
5
  /** Outbound tools (search 2 + wind 2 + named sources 11); `ocr` is excluded because only its url form is restricted. */
6
6
  export declare const RETRIEVAL_DENIED_TOOLS: readonly ["anysearch_search", "web_retriever_fetch", "wind_docs_announcements", "wind_docs_news", "cls_telegraph", "wscn_lives", "cninfo_irm", "sseinfo_qa", "eastmoney_724", "eastmoney_stock_news", "eastmoney_reports", "eastmoney_announcements", "eastmoney_announcement_body", "sina_reports", "ths_eps_forecast"];
7
+ /** Generic host web entry points; the only outbound surface is web_retriever's named tools. */
8
+ export declare const HOST_WEB_DENIED_TOOLS: readonly ["web_fetch", "anysearch_batch_search", "anysearch_capabilities"];
7
9
  export declare const OCR_TOOL_NAME = "ocr";
8
10
  /** Name-level deny cannot express the form distinction; this is a call-level guard. */
9
11
  export declare const OCR_ROOT_URL_DENIED: string;
@@ -12,16 +14,25 @@ export declare function ocrUrlFormRequested(exec: GuardedExecution | undefined):
12
14
  export declare function ocrFormGuardReasonFor(ctx: PolicyContext): (exec: GuardedExecution | undefined) => string | undefined;
13
15
  /** Mounted as a platform pair; recognize both everywhere or the other platform's gate is dead. */
14
16
  export declare const SHELL_TOOL_NAMES: readonly ["bash", "pwsh"];
15
- export declare const ROOT_AGENT_DENIED_TOOLS: readonly ["render_chart", "prepare_chart_source", "anysearch_search", "web_retriever_fetch", "wind_docs_announcements", "wind_docs_news", "cls_telegraph", "wscn_lives", "cninfo_irm", "sseinfo_qa", "eastmoney_724", "eastmoney_stock_news", "eastmoney_reports", "eastmoney_announcements", "eastmoney_announcement_body", "sina_reports", "ths_eps_forecast", "write", "edit"];
17
+ /** dsh-base mounts Agent Team globally. We keep the rows (other modes may use them) and deny the
18
+ * four tools on every Capital agent; the `team:policy` prompt section is host-owned and cannot be
19
+ * removed by a name deny, so Capital intentionally ignores that text. */
20
+ export declare const TEAM_DENIED_TOOLS: readonly ["team_task_create", "team_task_list", "team_task_get", "team_task_update"];
21
+ export declare const ROOT_AGENT_DENIED_TOOLS: readonly ["render_chart", "prepare_chart_source", "team_task_create", "team_task_list", "team_task_get", "team_task_update", "anysearch_search", "web_retriever_fetch", "wind_docs_announcements", "wind_docs_news", "cls_telegraph", "wscn_lives", "cninfo_irm", "sseinfo_qa", "eastmoney_724", "eastmoney_stock_news", "eastmoney_reports", "eastmoney_announcements", "eastmoney_announcement_body", "sina_reports", "ths_eps_forecast", "web_fetch", "anysearch_batch_search", "anysearch_capabilities", "write", "edit"];
16
22
  export declare const CAPITAL_PRESET_ID = "capital-generation";
17
23
  interface ToolRestriction {
18
24
  allow?: readonly string[];
19
25
  deny?: readonly string[];
20
26
  }
27
+ interface ToolViewLike {
28
+ readonly restrictableNames?: ReadonlySet<string>;
29
+ }
21
30
  /** `guard` only returns a deny string, so listener order can never turn a deny into an allow. */
22
31
  interface RestrictedToolRuntime {
23
32
  restrict?(filter: ToolRestriction): unknown;
24
33
  guard?(guard: (execution: GuardedExecution) => string | undefined): unknown;
34
+ /** Runtime view of inherited global/ancestor tools; used to skip names absent from this scope. */
35
+ view?(scope?: unknown): ToolViewLike | undefined;
25
36
  }
26
37
  export interface GuardedExecution {
27
38
  readonly name?: string;
@@ -87,7 +98,7 @@ export declare const FS_WRITE_READ_ONLY: string;
87
98
  export declare function fsWriteGuardReasonFor(ctx: PolicyContext): (execution: GuardedExecution) => string | undefined;
88
99
  export declare function registerFsWriteGuard(ctx: PolicyContext): void;
89
100
  export interface RootToolPolicyOptions {
90
- /** Host policy passes false: family rows already close the surface, so record only. */
101
+ /** false = record only. Host policy now keeps deny on: host-global tools are not closed by rows. */
91
102
  deny?: boolean;
92
103
  }
93
104
  export declare function registerRootToolPolicy(ctx: PolicyContext, options?: RootToolPolicyOptions): void;
@@ -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;