@octopi-agent/engine 0.65.0 → 0.70.7

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 (99) hide show
  1. package/dist/config-schema/engine.d.ts +84 -0
  2. package/dist/config-schema/engine.js +4 -1
  3. package/dist/config-schema/substrate.d.ts +86 -0
  4. package/dist/config-schema/substrate.js +114 -0
  5. package/dist/config.d.ts +71 -0
  6. package/dist/harness/agent/builder.d.ts +1 -1
  7. package/dist/harness/agent/builder.js +27 -2
  8. package/dist/harness/agent/config-bridge.js +17 -4
  9. package/dist/harness/context/capabilities/summary/gate.js +2 -2
  10. package/dist/harness/context/capabilities/summary/policies.js +5 -5
  11. package/dist/harness/context/capabilities/summary/registry.js +29 -24
  12. package/dist/harness/context/layer-health.js +3 -2
  13. package/dist/harness/context/layers.d.ts +27 -13
  14. package/dist/harness/context/layers.js +76 -66
  15. package/dist/harness/context/system-prompt-assembler.d.ts +3 -0
  16. package/dist/harness/context/system-prompt-assembler.js +11 -1
  17. package/dist/harness/extension/plugin-ecosystem/client-tools/index.d.ts +4 -0
  18. package/dist/harness/extension/plugin-ecosystem/client-tools/index.js +3 -0
  19. package/dist/harness/extension/plugin-ecosystem/client-tools/invoke.d.ts +56 -0
  20. package/dist/harness/extension/plugin-ecosystem/client-tools/invoke.js +281 -0
  21. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.d.ts +98 -0
  22. package/dist/harness/extension/plugin-ecosystem/client-tools/registry.js +250 -0
  23. package/dist/harness/extension/plugin-ecosystem/client-tools/stream.d.ts +124 -0
  24. package/dist/harness/extension/plugin-ecosystem/client-tools/stream.js +372 -0
  25. package/dist/harness/extension/plugin-ecosystem/client-tools/types.d.ts +109 -0
  26. package/dist/harness/extension/plugin-ecosystem/client-tools/types.js +8 -0
  27. package/dist/harness/extension/plugin-ecosystem/index.d.ts +1 -0
  28. package/dist/harness/extension/plugin-ecosystem/index.js +1 -0
  29. package/dist/harness/extension/plugin-ecosystem/tools/builtin.js +1 -1
  30. package/dist/harness/extension/plugin-ecosystem/tools/memory.d.ts +11 -1
  31. package/dist/harness/extension/plugin-ecosystem/tools/memory.js +14 -0
  32. package/dist/harness/index.d.ts +4 -3
  33. package/dist/harness/index.js +2 -1
  34. package/dist/harness/knowledge/query-service.js +5 -5
  35. package/dist/harness/knowledge/retriever.js +1 -1
  36. package/dist/harness/knowledge/source-store.d.ts +17 -2
  37. package/dist/harness/knowledge/source-store.js +6 -5
  38. package/dist/harness/memory/cognition-decay.d.ts +36 -0
  39. package/dist/harness/memory/cognition-decay.js +55 -0
  40. package/dist/harness/memory/cognition-gates.d.ts +60 -0
  41. package/dist/harness/memory/cognition-gates.js +191 -0
  42. package/dist/harness/memory/cognition-trigger.d.ts +30 -0
  43. package/dist/harness/memory/cognition-trigger.js +41 -0
  44. package/dist/harness/memory/cognition-types.d.ts +1 -1
  45. package/dist/harness/memory/cognition.d.ts +40 -8
  46. package/dist/harness/memory/cognition.js +432 -79
  47. package/dist/harness/memory/conceptualizer.d.ts +66 -0
  48. package/dist/harness/memory/conceptualizer.js +246 -0
  49. package/dist/harness/memory/index.d.ts +16 -2
  50. package/dist/harness/memory/index.js +11 -1
  51. package/dist/harness/memory/sqlite/agent-db.d.ts +9 -0
  52. package/dist/harness/memory/sqlite/agent-db.js +118 -15
  53. package/dist/harness/memory/sqlite/cognition-store.d.ts +55 -16
  54. package/dist/harness/memory/sqlite/cognition-store.js +591 -144
  55. package/dist/harness/memory/sqlite/wisdom-store.d.ts +33 -14
  56. package/dist/harness/memory/sqlite/wisdom-store.js +257 -44
  57. package/dist/harness/memory/types.d.ts +331 -16
  58. package/dist/harness/memory/types.js +49 -0
  59. package/dist/harness/memory/wisdom-formation.d.ts +101 -0
  60. package/dist/harness/memory/wisdom-formation.js +304 -0
  61. package/dist/harness/memory/wisdom-gates.d.ts +50 -0
  62. package/dist/harness/memory/wisdom-gates.js +204 -0
  63. package/dist/harness/memory/wisdom-policy.d.ts +107 -0
  64. package/dist/harness/memory/wisdom-policy.js +220 -0
  65. package/dist/harness/memory/wisdom-types.d.ts +3 -2
  66. package/dist/harness/memory/wisdom-types.js +2 -2
  67. package/dist/harness/memory/wisdom.d.ts +27 -0
  68. package/dist/harness/memory/wisdom.js +181 -0
  69. package/dist/harness/run/agent/agent.d.ts +9 -0
  70. package/dist/harness/run/agent/agent.js +19 -0
  71. package/dist/harness/run/reliability/run-agent.js +6 -2
  72. package/dist/harness/run/runner.js +2 -1
  73. package/dist/harness/session/index.d.ts +1 -0
  74. package/dist/harness/session/index.js +1 -0
  75. package/dist/harness/session/title.d.ts +86 -0
  76. package/dist/harness/session/title.js +268 -0
  77. package/dist/harness/shared/events/agent-event-map.d.ts +8 -0
  78. package/dist/harness/shared/events/agent-event-map.js +1 -0
  79. package/dist/index.d.ts +3 -1
  80. package/dist/index.js +1 -0
  81. package/dist/subsystems/cognition-steward/conceptualize/SUBSYSTEM.md +43 -0
  82. package/dist/subsystems/cognition-steward/conceptualize/config.yaml +50 -0
  83. package/dist/subsystems/cognition-steward/conceptualize/handler.d.ts +9 -0
  84. package/dist/subsystems/cognition-steward/conceptualize/handler.js +125 -0
  85. package/dist/subsystems/cognition-steward/consolidate/SUBSYSTEM.md +6 -0
  86. package/dist/subsystems/cognition-steward/consolidate/config.yaml +54 -0
  87. package/dist/subsystems/cognition-steward/consolidate/handler.d.ts +12 -0
  88. package/dist/subsystems/cognition-steward/consolidate/handler.js +93 -0
  89. package/dist/subsystems/wisdom-steward/evaluate/config.yaml +50 -0
  90. package/dist/subsystems/wisdom-steward/evaluate/handler.d.ts +18 -0
  91. package/dist/subsystems/wisdom-steward/evaluate/handler.js +91 -0
  92. package/dist/subsystems/wisdom-steward/formation/SUBSYSTEM.md +42 -0
  93. package/dist/subsystems/wisdom-steward/formation/config.yaml +54 -0
  94. package/dist/subsystems/wisdom-steward/formation/handler.d.ts +18 -0
  95. package/dist/subsystems/wisdom-steward/formation/handler.js +212 -0
  96. package/dist/subsystems/wisdom-steward/govern/config.yaml +55 -0
  97. package/dist/subsystems/wisdom-steward/govern/handler.d.ts +17 -0
  98. package/dist/subsystems/wisdom-steward/govern/handler.js +68 -0
  99. package/package.json +2 -2
@@ -106,19 +106,35 @@ export declare class CognitionLayer extends BaseLayer {
106
106
  assemble(ctx: LayerAssembleContext): Promise<LayerContent | null>;
107
107
  }
108
108
  /**
109
- * Wisdom 层 — 从 WisdomStore 读取高优先思维范式
109
+ * Wisdom 层 — 小核心 + 场景匹配注入判断范式
110
110
  *
111
- * 当前薄实现:取全部并按 priority 排序后截断。
112
- * 后续可改为场景匹配 / applicableScenarios 过滤。
111
+ * 不做全量 dump。匹配失败只注入 core(宁缺毋滥)。
113
112
  */
114
113
  export declare class WisdomLayer extends BaseLayer {
115
- private readonly getEntries;
114
+ private readonly select;
115
+ private readonly onInjected?;
116
+ private readonly coreMaxItems?;
117
+ private readonly scenarioMaxItems?;
116
118
  constructor(options: {
117
- getEntries: () => Promise<Array<{
118
- id: string;
119
- content: string;
120
- priority: number;
119
+ select: (query: string) => Promise<Array<{
120
+ entry: {
121
+ id: string;
122
+ statement: string;
123
+ scenario: {
124
+ problemTypes: string[];
125
+ antiScenarios?: string[];
126
+ };
127
+ effect: {
128
+ posture?: string;
129
+ questions?: string[];
130
+ };
131
+ };
132
+ bucket: 'core' | 'scenario';
121
133
  }>>;
134
+ /** S1 applied 入账(注入命中) */
135
+ onInjected?: (ids: string[]) => void | Promise<void>;
136
+ coreMaxItems?: number;
137
+ scenarioMaxItems?: number;
122
138
  order?: number;
123
139
  });
124
140
  assemble(ctx: LayerAssembleContext): Promise<LayerContent | null>;
@@ -133,11 +149,9 @@ export interface CreateDefaultLayersOptions {
133
149
  knowledgeShowProgress?: 'off' | 'bucket' | 'exact';
134
150
  memoryStore?: MemoryStore;
135
151
  cognitionStore?: ConceptGraphStore;
136
- wisdomEntries?: () => Promise<Array<{
137
- id: string;
138
- content: string;
139
- priority: number;
140
- }>>;
152
+ wisdomStore?: import('../memory/types.js').WisdomStore;
153
+ wisdomCoreMaxItems?: number;
154
+ wisdomScenarioMaxItems?: number;
141
155
  }
142
156
  /**
143
157
  * 按可用依赖创建启用层列表
@@ -6,6 +6,7 @@
6
6
  * 各层质量打磨后续替换 assemble 实现即可,契约不变。
7
7
  */
8
8
  import { LAYER_DEFAULT_SHARE, LAYER_ORDER, LAYER_PRIORITY, } from './layer-types.js';
9
+ import { formatWisdomBody } from '../memory/wisdom-formation.js';
9
10
  // ── 基类 ──
10
11
  class BaseLayer {
11
12
  id;
@@ -251,37 +252,57 @@ export class MemoryLayer extends BaseLayer {
251
252
  });
252
253
  }
253
254
  }
254
- // ── Cognition(薄图谱片段) ──
255
+ // ── Cognition(扩散激活子图;强弱边分列) ──
255
256
  export class CognitionLayer extends BaseLayer {
256
257
  store;
257
258
  depth;
258
259
  constructor(options) {
259
260
  super('cognition', { order: options.order });
260
261
  this.store = options.store;
261
- this.depth = options.depth ?? 1;
262
+ this.depth = options.depth ?? 2;
262
263
  }
263
264
  async assemble(ctx) {
264
265
  if (!ctx.query?.trim())
265
266
  return null;
266
- const graph = await resolveCognitionGraph(this.store, ctx.query, this.depth);
267
+ const queryTokens = ctx.query
268
+ .split(/\s+/)
269
+ .map((t) => t.trim())
270
+ .filter((t) => t.length >= 2)
271
+ .slice(0, 8);
272
+ const seeds = queryTokens.length ? queryTokens : [ctx.query.trim()];
273
+ const graph = await this.store.spreadingActivate(seeds, {
274
+ depth: this.depth,
275
+ limit: 40,
276
+ });
267
277
  if (!graph.nodes.length)
268
278
  return null;
269
- const lines = [];
279
+ const nameOf = new Map(graph.nodes.map((n) => [n.id, n.name]));
280
+ const strong = [];
281
+ const weakNames = new Set();
270
282
  for (const edge of graph.edges) {
271
- const source = graph.nodes.find((n) => n.id === edge.sourceId);
272
- const target = graph.nodes.find((n) => n.id === edge.targetId);
273
- if (source && target) {
274
- const desc = edge.description ? ` (${edge.description})` : '';
275
- lines.push(`- ${source.name} —[${edge.relationType}]→ ${target.name}${desc}`);
283
+ const source = nameOf.get(edge.sourceId);
284
+ const target = nameOf.get(edge.targetId);
285
+ if (!source || !target)
286
+ continue;
287
+ if (edge.relationType === 'related' || edge.status === 'shadow') {
288
+ weakNames.add(source);
289
+ weakNames.add(target);
290
+ continue;
276
291
  }
292
+ const desc = edge.description ? ` (${edge.description})` : '';
293
+ strong.push(`- ${source} —[${edge.relationType}]→ ${target}${desc}`);
277
294
  }
278
- // 无边时仍列出命中概念,避免「有节点却整层 empty」
279
- if (lines.length === 0) {
280
- for (const node of graph.nodes) {
281
- const desc = node.description ? `: ${node.description}` : '';
282
- lines.push(`- ${node.name}${desc}`);
295
+ // 弱边只作折叠相关,不伪造成因果格式
296
+ for (const n of graph.nodes) {
297
+ if (!weakNames.has(n.name) && !strong.some((l) => l.includes(n.name))) {
298
+ weakNames.add(n.name);
283
299
  }
284
300
  }
301
+ const lines = [...strong];
302
+ const weak = [...weakNames].filter((name) => !strong.some((l) => l.includes(name)));
303
+ if (weak.length) {
304
+ lines.push(`相关:${weak.join('、')}`);
305
+ }
285
306
  if (lines.length === 0)
286
307
  return null;
287
308
  const text = `# 相关概念\n\n${lines.join('\n')}`;
@@ -292,70 +313,46 @@ export class CognitionLayer extends BaseLayer {
292
313
  });
293
314
  }
294
315
  }
295
- /**
296
- * 解析认知图:先 store.queryRelated,失败则从全图按「概念名 ⊆ query」筛种子再扩边
297
- *
298
- * @param store - ConceptGraphStore
299
- * @param query - 检索文本(通常为最近用户消息)
300
- * @param depth - 扩展深度
301
- * @returns 命中的子图(可能为空)
302
- */
303
- async function resolveCognitionGraph(store, query, depth) {
304
- const direct = await store.queryRelated(query, depth);
305
- if (direct.nodes.length)
306
- return direct;
307
- const full = await store.getFullGraph();
308
- const q = query.toLowerCase();
309
- const seeds = full.nodes.filter((n) => n.name && q.includes(n.name.toLowerCase()));
310
- if (!seeds.length)
311
- return { nodes: [], edges: [] };
312
- const collected = new Map(seeds.map((n) => [n.id, n]));
313
- const nodeById = new Map(full.nodes.map((n) => [n.id, n]));
314
- const visited = new Set(seeds.map((n) => n.id));
315
- const queue = seeds.map((n) => ({ id: n.id, d: 0 }));
316
- while (queue.length > 0) {
317
- const { id, d } = queue.shift();
318
- if (d >= depth)
319
- continue;
320
- for (const e of full.edges) {
321
- const neighborId = e.sourceId === id ? e.targetId : e.targetId === id ? e.sourceId : null;
322
- if (!neighborId || visited.has(neighborId))
323
- continue;
324
- const node = nodeById.get(neighborId);
325
- if (!node)
326
- continue;
327
- visited.add(neighborId);
328
- collected.set(neighborId, node);
329
- queue.push({ id: neighborId, d: d + 1 });
330
- }
331
- }
332
- const edges = full.edges.filter((e) => collected.has(e.sourceId) && collected.has(e.targetId));
333
- return { nodes: [...collected.values()], edges };
334
- }
335
316
  // ── Wisdom(静态/半静态) ──
336
317
  /**
337
- * Wisdom 层 — 从 WisdomStore 读取高优先思维范式
318
+ * Wisdom 层 — 小核心 + 场景匹配注入判断范式
338
319
  *
339
- * 当前薄实现:取全部并按 priority 排序后截断。
340
- * 后续可改为场景匹配 / applicableScenarios 过滤。
320
+ * 不做全量 dump。匹配失败只注入 core(宁缺毋滥)。
341
321
  */
342
322
  export class WisdomLayer extends BaseLayer {
343
- getEntries;
323
+ select;
324
+ onInjected;
325
+ coreMaxItems;
326
+ scenarioMaxItems;
344
327
  constructor(options) {
345
328
  super('wisdom', { order: options.order });
346
- this.getEntries = options.getEntries;
329
+ this.select = options.select;
330
+ this.onInjected = options.onInjected;
331
+ this.coreMaxItems = options.coreMaxItems;
332
+ this.scenarioMaxItems = options.scenarioMaxItems;
347
333
  }
348
334
  async assemble(ctx) {
349
- const entries = await this.getEntries();
350
- if (entries.length === 0)
335
+ const picks = await this.select(ctx.query ?? '');
336
+ if (picks.length === 0)
337
+ return null;
338
+ const body = formatWisdomBody(picks);
339
+ if (!body)
351
340
  return null;
352
- const sorted = [...entries].sort((a, b) => b.priority - a.priority);
353
- const body = sorted.map((w) => w.content).join('\n\n');
354
341
  const text = `# 思维框架\n\n${body}`;
355
342
  const { text: truncated, dropped } = this.truncateToBudget(text, ctx.tokenBudget);
343
+ const sources = picks.map((p) => p.entry.id);
344
+ // S1:实际进入 system 的条目记 applied(轻量,不跑 confidence)
345
+ if (this.onInjected && sources.length) {
346
+ try {
347
+ await this.onInjected(sources);
348
+ }
349
+ catch {
350
+ // 入账失败不拖垮装配;结局环可由 evaluate 兜
351
+ }
352
+ }
356
353
  return this.content(truncated, {
357
354
  dropped,
358
- sources: sorted.map((e) => e.id),
355
+ sources,
359
356
  });
360
357
  }
361
358
  }
@@ -367,8 +364,21 @@ export class WisdomLayer extends BaseLayer {
367
364
  */
368
365
  export function createDefaultLayers(options) {
369
366
  const layers = [];
370
- if (options.wisdomEntries) {
371
- layers.push(new WisdomLayer({ getEntries: options.wisdomEntries }));
367
+ if (options.wisdomStore) {
368
+ const store = options.wisdomStore;
369
+ layers.push(new WisdomLayer({
370
+ select: async (query) => {
371
+ const picks = await store.selectForInjection({
372
+ text: query,
373
+ coreMaxItems: options.wisdomCoreMaxItems,
374
+ scenarioMaxItems: options.wisdomScenarioMaxItems,
375
+ });
376
+ return picks.map((p) => ({ entry: p.entry, bucket: p.bucket }));
377
+ },
378
+ onInjected: (ids) => store.touchApplied(ids),
379
+ coreMaxItems: options.wisdomCoreMaxItems,
380
+ scenarioMaxItems: options.wisdomScenarioMaxItems,
381
+ }));
372
382
  }
373
383
  if (options.personaText) {
374
384
  layers.push(new PersonaLayer({ getText: options.personaText }));
@@ -45,6 +45,9 @@ export declare function createDefaultSystemPromptAssembler(options?: {
45
45
  /** Knowledge Tier 0 catalog(有哪些源);内容命中不进 system */
46
46
  knowledgeCatalog?: KnowledgeCatalogProvider;
47
47
  wisdomStore?: WisdomStore;
48
+ /** Wisdom 注入条数硬顶 */
49
+ wisdomCoreMaxItems?: number;
50
+ wisdomScenarioMaxItems?: number;
48
51
  cognitionStore?: ConceptGraphStore;
49
52
  memoryLimit?: number;
50
53
  knowledgeMaxEntries?: number;
@@ -83,7 +83,17 @@ export function createDefaultSystemPromptAssembler(options) {
83
83
  layers.push(new SkillLayer({ getPromptText: getSkillPromptText }));
84
84
  }
85
85
  if (wisdomStore) {
86
- layers.push(new WisdomLayer({ getEntries: () => wisdomStore.getAll() }));
86
+ layers.push(new WisdomLayer({
87
+ select: async (query) => {
88
+ const picks = await wisdomStore.selectForInjection({
89
+ text: query,
90
+ coreMaxItems: options?.wisdomCoreMaxItems,
91
+ scenarioMaxItems: options?.wisdomScenarioMaxItems,
92
+ });
93
+ return picks.map((p) => ({ entry: p.entry, bucket: p.bucket }));
94
+ },
95
+ onInjected: (ids) => wisdomStore.touchApplied(ids),
96
+ }));
87
97
  }
88
98
  if (options?.knowledgeCatalog) {
89
99
  layers.push(new KnowledgeLayer({
@@ -0,0 +1,4 @@
1
+ export type { ClientToolCall, ClientToolCallId, ClientToolCallOutcome, ClientToolClientFilter, ClientToolDescriptor, ClientToolDeviceMeta, ClientToolErrorReason, ClientToolInteraction, ClientToolName, ClientToolProvider, ClientToolResult, ClientToolSensitivity, } from './types.js';
2
+ export { createClientTool, makeClientToolCallId, DEFAULT_CLIENT_TOOL_TIMEOUT_MS, validateClientToolArgs, validateClientToolDescriptor, validateClientToolOutcome, requireDevicePurpose, type ClientToolInvoker, type ClientToolInvokeRequest, } from './invoke.js';
3
+ export { ClientToolRegistry, type ClientToolRouteDecision, } from './registry.js';
4
+ export { ClientStreamTransport, createSinkStreamTool, createSourceStreamTool, createStreamStopTool, type ClientStreamChannel, type ClientStreamDirection, type ClientStreamEvent, type ClientStreamEventType, type ClientStreamSampleInput, type ClientStreamTransportDeps, type OpenStreamInput, type StreamDomainToolDeps, type StreamStopToolDeps, } from './stream.js';
@@ -0,0 +1,3 @@
1
+ export { createClientTool, makeClientToolCallId, DEFAULT_CLIENT_TOOL_TIMEOUT_MS, validateClientToolArgs, validateClientToolDescriptor, validateClientToolOutcome, requireDevicePurpose, } from './invoke.js';
2
+ export { ClientToolRegistry, } from './registry.js';
3
+ export { ClientStreamTransport, createSinkStreamTool, createSourceStreamTool, createStreamStopTool, } from './stream.js';
@@ -0,0 +1,56 @@
1
+ /**
2
+ * createClientTool — 把 ClientToolDescriptor 装成 RegisteredTool
3
+ *
4
+ * 与 createAskUserTool 同模式:handler 经 invoker 闭包注入,
5
+ * Host(Gateway)负责路由到客户端并等待 ClientToolCallOutcome。
6
+ *
7
+ * 返回值约定(LLM 可见):
8
+ * - ok+value → { kind:'value', data }
9
+ * - ok+asset → { kind:'asset', assetId, mime, sizeBytes, ... }
10
+ * - error → { error: reason, hint? } (显式失败,禁止空成功)
11
+ */
12
+ import type { RegisteredTool, ToolExecutionContext, ToolParameter } from '@octopi-agent/core/types/tools.js';
13
+ import type { ClientToolCallOutcome, ClientToolDescriptor } from './types.js';
14
+ export interface ClientToolInvokeRequest {
15
+ name: string;
16
+ args: Record<string, unknown>;
17
+ sessionId: string;
18
+ agentId: string;
19
+ /** 生成的 callId,Host 可用于挂 pending */
20
+ callId: string;
21
+ ttlAt: number;
22
+ /** 与 Loop toolCallId 对齐(可选;Host 可回填) */
23
+ toolCallId?: string;
24
+ runId?: string;
25
+ /** Run 中止信号;Host 应据此取消 pending */
26
+ abortSignal?: AbortSignal;
27
+ }
28
+ /** Client tool 在 LLM tool 面上的可见性(会话级) */
29
+ export type ClientToolVisibility = (sessionId: string, toolName: string) => boolean;
30
+ /**
31
+ * Host 侧执行:路由到 client、等待 UI/设备、返回结局。
32
+ */
33
+ export type ClientToolInvoker = (request: ClientToolInvokeRequest, context: ToolExecutionContext) => Promise<ClientToolCallOutcome>;
34
+ /** 默认工具等待上限(与 definition.timeoutMs 对齐) */
35
+ export declare const DEFAULT_CLIENT_TOOL_TIMEOUT_MS = 300000;
36
+ /** 生成 callId(Host 也可覆盖) */
37
+ export declare function makeClientToolCallId(): string;
38
+ /** 按 ToolParameter 校验调用参数(LLM 直呼 handler 时 ToolBus 不代验) */
39
+ export declare function validateClientToolArgs(parameters: Record<string, ToolParameter>, args: Record<string, unknown>): string | null;
40
+ /** 敏感 device 必须带 purpose(§6 红线:禁止无理由采集) */
41
+ export declare function requireDevicePurpose(descriptor: ClientToolDescriptor, args: Record<string, unknown>): string | null;
42
+ /** 注册前描述符校验(REST/插件入口防污染 tool 面) */
43
+ export declare function validateClientToolDescriptor(raw: unknown): string | null;
44
+ /** resolve 入参校验:禁止 ok 空 result / 未知 reason(§14.2 无空成功) */
45
+ export declare function validateClientToolOutcome(raw: unknown): string | null;
46
+ /**
47
+ * 创建可注册进 ToolBus 的 Client Tool
48
+ *
49
+ * @param descriptor - 客户端注册的能力契约
50
+ * @param invoker - Host 执行体(路由 + 等待 + TTL)
51
+ * @param options.timeoutMs - **仅** standalone 时作本地兜底超时;Host 路径不要传,避免双定时器
52
+ */
53
+ export declare function createClientTool(descriptor: ClientToolDescriptor, invoker: ClientToolInvoker, options?: {
54
+ timeoutMs?: number;
55
+ makeCallId?: () => string;
56
+ }): RegisteredTool;
@@ -0,0 +1,281 @@
1
+ /**
2
+ * createClientTool — 把 ClientToolDescriptor 装成 RegisteredTool
3
+ *
4
+ * 与 createAskUserTool 同模式:handler 经 invoker 闭包注入,
5
+ * Host(Gateway)负责路由到客户端并等待 ClientToolCallOutcome。
6
+ *
7
+ * 返回值约定(LLM 可见):
8
+ * - ok+value → { kind:'value', data }
9
+ * - ok+asset → { kind:'asset', assetId, mime, sizeBytes, ... }
10
+ * - error → { error: reason, hint? } (显式失败,禁止空成功)
11
+ */
12
+ /** 默认工具等待上限(与 definition.timeoutMs 对齐) */
13
+ export const DEFAULT_CLIENT_TOOL_TIMEOUT_MS = 300_000;
14
+ /** 生成 callId(Host 也可覆盖) */
15
+ export function makeClientToolCallId() {
16
+ return `ctc_${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
17
+ }
18
+ /** 按 ToolParameter 校验调用参数(LLM 直呼 handler 时 ToolBus 不代验) */
19
+ export function validateClientToolArgs(parameters, args) {
20
+ for (const [key, param] of Object.entries(parameters)) {
21
+ const value = args[key];
22
+ if (value === undefined || value === null) {
23
+ if (param.required)
24
+ return `missing required argument "${key}"`;
25
+ continue;
26
+ }
27
+ const actual = Array.isArray(value) ? 'array' : typeof value;
28
+ const expected = param.type === 'object' && actual === 'object' ? 'object' : param.type;
29
+ if (param.type === 'object' ? actual !== 'object' || Array.isArray(value) : actual !== expected) {
30
+ return `argument "${key}" must be ${param.type}, got ${actual}`;
31
+ }
32
+ if (param.enum && !param.enum.includes(value)) {
33
+ return `argument "${key}" must be one of: ${param.enum.join(', ')}`;
34
+ }
35
+ if (param.type === 'string' && typeof value === 'string') {
36
+ if (param.minLength != null && value.length < param.minLength) {
37
+ return `argument "${key}" minLength=${param.minLength}`;
38
+ }
39
+ if (param.maxLength != null && value.length > param.maxLength) {
40
+ return `argument "${key}" maxLength=${param.maxLength}`;
41
+ }
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+ /** 敏感 device 必须带 purpose(§6 红线:禁止无理由采集) */
47
+ export function requireDevicePurpose(descriptor, args) {
48
+ if (descriptor.interaction !== 'device')
49
+ return null;
50
+ const sensitivity = descriptor.device?.sensitivity ?? 'personal';
51
+ if (sensitivity === 'public')
52
+ return null;
53
+ const purpose = args.purpose;
54
+ if (typeof purpose !== 'string' || purpose.trim().length === 0) {
55
+ return 'purpose is required for device tools with personal/sensitive data';
56
+ }
57
+ return null;
58
+ }
59
+ /** 注册前描述符校验(REST/插件入口防污染 tool 面) */
60
+ export function validateClientToolDescriptor(raw) {
61
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
62
+ return 'descriptor must be an object';
63
+ const d = raw;
64
+ if (typeof d.name !== 'string' || d.name.trim().length === 0)
65
+ return 'name must be a non-empty string';
66
+ if (typeof d.description !== 'string' || d.description.trim().length === 0) {
67
+ return `descriptor "${String(d.name)}": description must be a non-empty string`;
68
+ }
69
+ if (!d.parameters || typeof d.parameters !== 'object' || Array.isArray(d.parameters)) {
70
+ return `descriptor "${d.name}": parameters must be an object`;
71
+ }
72
+ if (d.interaction != null && !['silent', 'ui', 'device'].includes(String(d.interaction))) {
73
+ return `descriptor "${d.name}": interaction must be silent|ui|device`;
74
+ }
75
+ if (d.processing != null && !['server', 'local'].includes(String(d.processing))) {
76
+ return `descriptor "${d.name}": processing must be server|local`;
77
+ }
78
+ if (d.clientFilter != null) {
79
+ if (typeof d.clientFilter !== 'object' || Array.isArray(d.clientFilter)) {
80
+ return `descriptor "${d.name}": clientFilter must be an object`;
81
+ }
82
+ const f = d.clientFilter;
83
+ if (f.platforms != null && !Array.isArray(f.platforms)) {
84
+ return `descriptor "${d.name}": clientFilter.platforms must be an array`;
85
+ }
86
+ if (f.instanceId != null && typeof f.instanceId !== 'string') {
87
+ return `descriptor "${d.name}": clientFilter.instanceId must be a string`;
88
+ }
89
+ }
90
+ if (d.stream != null) {
91
+ if (typeof d.stream !== 'object' || Array.isArray(d.stream)) {
92
+ return `descriptor "${d.name}": stream must be an object`;
93
+ }
94
+ const s = d.stream;
95
+ if (!['source', 'sink', 'stop'].includes(String(s.direction))) {
96
+ return `descriptor "${d.name}": stream.direction must be source|sink|stop`;
97
+ }
98
+ if (s.handleKey != null && typeof s.handleKey !== 'string') {
99
+ return `descriptor "${d.name}": stream.handleKey must be a string`;
100
+ }
101
+ }
102
+ if (d.device &&
103
+ typeof d.device === 'object' &&
104
+ !Array.isArray(d.device) &&
105
+ d.device.sensitivity === 'sensitive' &&
106
+ d.device.consent === 'none') {
107
+ return `descriptor "${d.name}": sensitive device must not use consent=none`;
108
+ }
109
+ return null;
110
+ }
111
+ /** resolve 入参校验:禁止 ok 空 result / 未知 reason(§14.2 无空成功) */
112
+ export function validateClientToolOutcome(raw) {
113
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
114
+ return 'outcome must be an object';
115
+ const o = raw;
116
+ if (o.processing != null && !['server', 'local'].includes(String(o.processing))) {
117
+ return 'outcome.processing must be server|local';
118
+ }
119
+ if (o.status === 'ok') {
120
+ const result = o.result;
121
+ if (!result || typeof result !== 'object')
122
+ return 'outcome.ok requires result';
123
+ if (result.kind === 'value') {
124
+ if (!('data' in result))
125
+ return 'outcome.ok.value requires data';
126
+ return null;
127
+ }
128
+ if (result.kind === 'asset') {
129
+ if (typeof result.assetId !== 'string' || !result.assetId)
130
+ return 'asset requires assetId';
131
+ if (typeof result.mime !== 'string' || !result.mime)
132
+ return 'asset requires mime';
133
+ if (typeof result.sizeBytes !== 'number')
134
+ return 'asset requires sizeBytes';
135
+ return null;
136
+ }
137
+ return 'result.kind must be value|asset';
138
+ }
139
+ if (o.status === 'error') {
140
+ const allowed = [
141
+ 'invalid_arguments',
142
+ 'client_unavailable',
143
+ 'consent_denied',
144
+ 'permission_denied',
145
+ 'expired',
146
+ 'cancelled',
147
+ 'unsupported',
148
+ 'internal',
149
+ ];
150
+ if (typeof o.reason !== 'string' || !allowed.includes(o.reason)) {
151
+ return `outcome.error.reason must be one of: ${allowed.join(', ')}`;
152
+ }
153
+ return null;
154
+ }
155
+ return 'outcome.status must be ok|error';
156
+ }
157
+ function outcomeToLlmResult(outcome) {
158
+ if (outcome.status === 'ok') {
159
+ return toLlmSuccess(outcome.result);
160
+ }
161
+ return { error: outcome.reason, hint: outcome.hint };
162
+ }
163
+ function toLlmSuccess(result) {
164
+ if (result.kind === 'value') {
165
+ return { kind: 'value', data: result.data };
166
+ }
167
+ return {
168
+ kind: 'asset',
169
+ assetId: result.assetId,
170
+ mime: result.mime,
171
+ sizeBytes: result.sizeBytes,
172
+ name: result.name,
173
+ preview: result.preview,
174
+ };
175
+ }
176
+ /**
177
+ * 创建可注册进 ToolBus 的 Client Tool
178
+ *
179
+ * @param descriptor - 客户端注册的能力契约
180
+ * @param invoker - Host 执行体(路由 + 等待 + TTL)
181
+ * @param options.timeoutMs - **仅** standalone 时作本地兜底超时;Host 路径不要传,避免双定时器
182
+ */
183
+ export function createClientTool(descriptor, invoker, options) {
184
+ const makeCallId = options?.makeCallId ?? makeClientToolCallId;
185
+ const fallbackTimeoutMs = options?.timeoutMs;
186
+ return {
187
+ definition: {
188
+ name: descriptor.name,
189
+ description: descriptor.description,
190
+ parameters: descriptor.parameters,
191
+ // Host 负责 TTL;此处不写 timeoutMs,避免与 Host 双定时器分叉
192
+ version: descriptor.version,
193
+ requiresConfirmation: descriptor.interaction === 'device' &&
194
+ (descriptor.device?.consent ?? 'prompt') !== 'none',
195
+ },
196
+ handler: async (args, context) => {
197
+ if (context?.abortSignal?.aborted) {
198
+ return { error: 'cancelled', hint: 'aborted before client tool invoke' };
199
+ }
200
+ const sessionId = context?.sessionId;
201
+ const agentId = context?.agentId;
202
+ if (!sessionId || !agentId) {
203
+ return {
204
+ error: 'invalid_arguments',
205
+ hint: 'sessionId and agentId are required in tool context',
206
+ };
207
+ }
208
+ const argError = validateClientToolArgs(descriptor.parameters ?? {}, args);
209
+ if (argError) {
210
+ return { error: 'invalid_arguments', hint: argError };
211
+ }
212
+ const purposeError = requireDevicePurpose(descriptor, args);
213
+ if (purposeError) {
214
+ return { error: 'invalid_arguments', hint: purposeError };
215
+ }
216
+ const callId = makeCallId();
217
+ const ttlMs = fallbackTimeoutMs ?? DEFAULT_CLIENT_TOOL_TIMEOUT_MS;
218
+ const ttlAt = Date.now() + ttlMs;
219
+ const abortSignal = context?.abortSignal;
220
+ let timer;
221
+ const outcome = await new Promise((resolve, reject) => {
222
+ const cleanup = () => {
223
+ if (timer !== undefined)
224
+ clearTimeout(timer);
225
+ abortSignal?.removeEventListener('abort', onAbort);
226
+ };
227
+ const onAbort = () => {
228
+ cleanup();
229
+ resolve({
230
+ status: 'error',
231
+ reason: 'cancelled',
232
+ hint: 'run aborted while waiting for client tool',
233
+ processing: descriptor.processing ?? 'server',
234
+ });
235
+ };
236
+ if (abortSignal) {
237
+ abortSignal.addEventListener('abort', onAbort, { once: true });
238
+ if (abortSignal.aborted) {
239
+ onAbort();
240
+ return;
241
+ }
242
+ }
243
+ if (fallbackTimeoutMs !== undefined) {
244
+ timer = setTimeout(() => {
245
+ cleanup();
246
+ resolve({
247
+ status: 'error',
248
+ reason: 'expired',
249
+ hint: `client tool timed out after ${fallbackTimeoutMs}ms`,
250
+ processing: descriptor.processing ?? 'server',
251
+ });
252
+ }, fallbackTimeoutMs);
253
+ }
254
+ invoker({
255
+ name: descriptor.name,
256
+ args,
257
+ sessionId,
258
+ agentId,
259
+ callId,
260
+ ttlAt,
261
+ abortSignal,
262
+ }, context).then((value) => {
263
+ cleanup();
264
+ resolve({
265
+ ...value,
266
+ processing: value.processing ?? descriptor.processing ?? 'server',
267
+ });
268
+ }, (err) => {
269
+ cleanup();
270
+ resolve({
271
+ status: 'error',
272
+ reason: 'internal',
273
+ hint: err instanceof Error ? err.message : String(err),
274
+ processing: descriptor.processing ?? 'server',
275
+ });
276
+ });
277
+ });
278
+ return outcomeToLlmResult(outcome);
279
+ },
280
+ };
281
+ }