@tbox.cn/app-agent-sdk-server 0.1.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.
@@ -0,0 +1,2282 @@
1
+ import { HandlerRegistry, ServerContext, HandlerResult, LocalSkill, PreToolDef, RegistryTool, PreToolHistoryTurn, PreToolRouting, WsAuthenticator, ScopeSessionRegistry, AuthRuntime, TboxTtsClient } from '@tbox.cn/app-sdk-server';
2
+ export * from '@tbox.cn/app-sdk-server';
3
+ export { TtsVoiceConfig } from '@tbox.cn/app-sdk-server';
4
+ export { InferModuleCards } from '@tbox.cn/app-sdk-core';
5
+ import * as _tbox_cn_app_contracts from '@tbox.cn/app-contracts';
6
+ import { SendMessageMediaItem, SkillRecord, ServerEvent, PreToolRecord, MemoryKind, MemoryRecord, MemoryStore, MemoryStoreCapabilities, MemoryErrorCode, RequestContext as RequestContext$1, CardMeta, CardSnapshot, Identity, ExternalCredentials, HelloAckChatConfig, TboxCardPayload } from '@tbox.cn/app-contracts';
7
+ import * as _mastra_core_tools from '@mastra/core/tools';
8
+ import { Tool } from '@mastra/core/tools';
9
+ export { Tool, createTool } from '@mastra/core/tools';
10
+ import { ObservabilityExporter, TracingEvent, SpanType } from '@mastra/core/observability';
11
+ import { ModelMessage, LanguageModel } from 'ai';
12
+ import { AsyncLocalStorage } from 'node:async_hooks';
13
+ import { ZodTypeAny, z } from 'zod';
14
+ import { SkillInput } from '@mastra/core/skills';
15
+ import { RequestContext } from '@mastra/core/request-context';
16
+ import * as ws from 'ws';
17
+ import { WebSocket } from 'ws';
18
+ import * as http from 'http';
19
+ import * as _mastra_core_schema from '@mastra/core/schema';
20
+ import * as node_modules__tbox_cn_app_sdk_server_src_upstream from 'node_modules/@tbox.cn/app-sdk-server/src/upstream';
21
+ import { Router, Express } from 'express';
22
+ import * as _tbox_cn_agent_plugin from '@tbox.cn/agent-plugin';
23
+ import { ConfiguredPluginToolReference, PluginRunResult } from '@tbox.cn/agent-plugin';
24
+
25
+ declare class TboxTraceExporter implements ObservabilityExporter {
26
+ name: string;
27
+ private seq;
28
+ private correlationByTraceId;
29
+ exportTracingEvent(event: TracingEvent): Promise<void>;
30
+ emitCustomSpan(opts: {
31
+ spanId: string;
32
+ traceId: string;
33
+ parentSpanId?: string;
34
+ type: SpanType;
35
+ name: string;
36
+ startTime: Date;
37
+ endTime: Date;
38
+ input?: unknown;
39
+ output?: unknown;
40
+ metadata?: Record<string, unknown>;
41
+ errorInfo?: {
42
+ message: string;
43
+ type?: string;
44
+ stack?: string;
45
+ };
46
+ requestId: string;
47
+ conversationId?: string;
48
+ sessionId?: string;
49
+ }): void;
50
+ emitErrorSpan(opts: {
51
+ requestId: string;
52
+ conversationId?: string;
53
+ sessionId?: string;
54
+ name?: string;
55
+ error: unknown;
56
+ metadata?: Record<string, unknown>;
57
+ }): void;
58
+ flush(): Promise<void>;
59
+ shutdown(): Promise<void>;
60
+ private resolveCorrelation;
61
+ }
62
+ /** 模块级单例:让 presenter 等业务代码能 emit 自定义 span。 */
63
+ declare const tboxTraceExporter: TboxTraceExporter;
64
+
65
+ /**
66
+ * intent-framework:意图识别框架(003 §3.3,hybrid 模式)。
67
+ * SDK 提供框架(路由/匹配),意图表由应用源码提供(业务域轴)。
68
+ */
69
+
70
+ interface IntentRoute {
71
+ /** 意图唯一标识 */
72
+ id: string;
73
+ /** 关键词(BM25 分词打分);空数组表示仅 LLM 分类 */
74
+ keywords: string[];
75
+ /** 命中的 handlerId */
76
+ handlerId: string;
77
+ /** 默认 action */
78
+ action: string;
79
+ /**
80
+ * 匹配语义(洋葱路由 L1/L3 分层):
81
+ * - 'exact':整句全等命中(trim 后 ===)且优先于 BM25——适用于按钮/选择器发出的
82
+ * 固定整句值(如会员偏好按钮);此类值绝不进入 BM25 词袋(相似查询误命中,F3)。
83
+ * - 'prefix':模板句头前缀命中(trim 后 startsWith)且优先于 BM25——适用于模块生成的
84
+ * 动态模板句(如卡片导航「查看「X」…」),头全等 + handler 内模板全等校验双层把关;
85
+ * 与 exact 同不入 BM25 词袋,prefix 误延展由 handler 洋葱守卫放行(不吞轮)。
86
+ * - 'bm25'(缺省):关键词词袋模糊命中。**顶层语义分类职责归 skill 路由与 LLM 工具编排**
87
+ * (BM25 单标签 + handler 硬短路会截断复合句)——顶层声明_bm25 为 legacy,装配期 warn;
88
+ * 合法存续域 = handler 内部二层 action 分辨(域内、带兜底、无跨域截断面)。
89
+ */
90
+ match?: 'exact' | 'prefix' | 'bm25';
91
+ }
92
+ /**
93
+ * 意图匹配(统一检索层,无 LLM 依赖的确定性路径):确定性档优先——L1 exact 整句全等、
94
+ * prefix 模板句头前缀(均 trim 容差、不入 BM25 索引);L3 BM25 打分 + 命中规则从严
95
+ * (长词 OR ≥2 token),取规则通过的首个 score top(并列 id 字典序,确定性)。
96
+ * 未命中 → undefined(调用方走 LLM)。空 keywords route 不参与(仅 LLM 分类)。
97
+ */
98
+ declare function matchIntent(routes: IntentRoute[], text: string): IntentRoute | undefined;
99
+ /**
100
+ * 意图分发器:命中关键词 → HandlerRegistry.dispatch。
101
+ * 未命中返回空结果(由调用方走 LLM 自由回复)。
102
+ */
103
+ declare function createIntentDispatcher(routes: IntentRoute[], handlers: HandlerRegistry): (text: string, ctx: ServerContext, payload?: unknown) => Promise<HandlerResult | undefined>;
104
+
105
+ /**
106
+ * 加载本地 skill 目录(009 D7):
107
+ * `dir/<skill-name>/SKILL.md`(frontmatter:name/description/metadata.routingTerms)+ `references/**​/*.md`(递归)。
108
+ * - dir 不存在(ENOENT——应用级/模块级 skills 目录均为可选形态)→ [] + info 静默跳过;
109
+ * 无权限等意外 IO → [] + warn。
110
+ * - 逐 skill try/catch:单个目录异常(缺 SKILL.md / IO 失败)跳过 + warn,不阻断其余。
111
+ * - 穿越防护:references 解析后相对路径以 `..` 开头或为绝对路径 → 跳过 + warn。
112
+ * - name 校验失败 → 跳过 + warn(防 reminder 解析注入)。
113
+ */
114
+ declare function loadLocalSkills(dir: string): Promise<LocalSkill[]>;
115
+ /**
116
+ * 唯一转换点(009 D5):LocalSkill → mastra InlineSkill。
117
+ * 仅 progressive 注册路径使用;accelerated 模式不触达 mastra skill 层。
118
+ * references 内存化(__referenceContents),运行期零文件系统暴露。
119
+ */
120
+ declare function toMastraSkill(skill: LocalSkill): SkillInput;
121
+ /**
122
+ * 模块包级文件 skill 加载(009 模块文件化能力,底层下沉):
123
+ * 包名解析定位模块包根 → 包根/skills 目录(SKILL.md 格式,复用 loadLocalSkills)。
124
+ * dev / dist / 发布态 / 应用 bundle 形态路径恒等(单一策略,零包名形态约定):
125
+ * - createRequire 以调用方文件为基准向上解析消费方 node_modules——
126
+ * dev(workspace link)、模块 dist、应用 build dist(bundle 内联后仍从 bundle
127
+ * 位置向上解析)、发布态(node_modules 内模块位置)均命中;
128
+ * - 前置:目标模块 package.json exports 须含 `"./package.json"`(标准惯例,
129
+ * doctor pack-exports 兼容;codegen 展开与本地骨架已默认保留)。
130
+ * - 恒 resolve(失败降级 [] + 可行动诊断 warn,不 throw):模块顶层 await 调用时
131
+ * 不会因加载失败中断应用启动链。
132
+ */
133
+ declare function loadModuleSkills(packageName: string, importMetaUrl: string): Promise<LocalSkill[]>;
134
+
135
+ /** 默认文件 URL 前缀(可被 createChatEngine 的 fileUrlPrefix 覆盖) */
136
+ declare const DEFAULT_FILE_URL_PREFIX = "https://mdn.alipayobjects.com/tcmarket/afts/file/";
137
+ type ImagePart = {
138
+ type: 'image';
139
+ image: URL;
140
+ mimeType?: string;
141
+ };
142
+ type TextPart = {
143
+ type: 'text';
144
+ text: string;
145
+ };
146
+ type ContentPart = ImagePart | TextPart;
147
+ /**
148
+ * 将用户输入文本 + 媒体附件组装为 LLM 可用的 content。
149
+ * - 图片 → image URL part(多模态)
150
+ * - 其他文件 → 文字占位符
151
+ * - 无媒体 → 纯文本
152
+ */
153
+ declare function buildUserContent(text: string, mediaItems?: SendMessageMediaItem[], fileUrlPrefix?: string): string | ContentPart[];
154
+ /**
155
+ * 轮级注入块组(composeTurnUserContent 输入)。
156
+ * 块语义见 platform-instructions 注入块协议节(四类块清单)。
157
+ */
158
+ interface TurnReminderBlocks {
159
+ /** card-decision 决策提醒块(modelEnabled 轮恒注入) */
160
+ cardDecision?: string;
161
+ /** pre-tool 预执行数据块(每 done 工具一个,按完成序) */
162
+ preToolBlocks?: string[];
163
+ /** memory 背景数据块(recall 命中轮) */
164
+ memoryBlock?: string;
165
+ /** skill 块(完整 SOP 注入或去重轮 recap) */
166
+ skillBlock?: string;
167
+ }
168
+ /**
169
+ * 轮级 user 内容统一组装(W3,2026-09-01;顺序契约唯一真源):
170
+ * `[card-decision → preTool₁..n → memory → skill → userText]`。
171
+ * 分组逻辑:协议指令 → 本轮数据族(前景 preTool + 背景 memory 相邻)→ 域规程(紧邻正文,
172
+ * 注意力就近)→ 正文。chat() 与 submitForm 单点共用;与 buildInjectedUserContent 字节级同构
173
+ * (仅传 skillBlock 时产物恒等——测试钉死)。
174
+ * 无块时 string 原样返回(handler 直出轮 history 形态不变);空 string → 无正文 part
175
+ * (submitForm reminder 消息形态)。
176
+ */
177
+ declare function composeTurnUserContent(blocks: TurnReminderBlocks, userContent: string | ContentPart[]): string | ContentPart[];
178
+ /**
179
+ * 从媒体附件中提取图片的完整 URL 列表。
180
+ * 用于保存消息时记录 multiModalInputs。
181
+ */
182
+ declare function extractImageUrls(mediaItems?: SendMessageMediaItem[], fileUrlPrefix?: string): string[];
183
+
184
+ /**
185
+ * 宽泛路由词(公开导出,skill-router re-export 保持公开面):
186
+ * 词素展开(词 + 拆字)后整体不入索引——高频泛词不参与路由(原降权语义升级为排除)。
187
+ */
188
+ declare const BROAD_ROUTING_TERMS: ReadonlySet<string>;
189
+
190
+ /**
191
+ * 本地 skill 双模式(009 D2):accelerated(默认,本地路由注入)/ progressive(原生渐进)。
192
+ * 全局配置、运行期恒定——非每轮动态,保证 Agent 构造(system prompt + 工具列表)恒态 → 前缀缓存稳定。
193
+ */
194
+ declare const DEFAULT_SKILL_MODE: "accelerated";
195
+ type SkillMode = 'accelerated' | 'progressive';
196
+ /** 解析环境变量(TBOX_SKILL_MODE);非法值 → 默认 + warn(确定性:静默降级为默认) */
197
+ declare function resolveSkillMode(value?: string): SkillMode;
198
+ /**
199
+ * 公开路由入口(纯函数):BM25 全量打分 + 命中规则(长词 OR ≥2 token)取最高分。
200
+ * bigram 全切分下词目 ⊆ 查询 ⇒ 词目内相邻二字恒为查询 token(长词规则直过),
201
+ * 原词目原文直命中兜底通道已无必要(2026-08-26 统一检索层移除)。空文本/空 skills → undefined。
202
+ */
203
+ declare function selectSkill(text: string, skills: LocalSkill[]): LocalSkill | undefined;
204
+ declare function scanInjectedSkills(history: ModelMessage[]): Set<string>;
205
+ /** 构建 reminder 块(SOP 全文 + references,一次到位 → 零 skill_read 轮次) */
206
+ declare function buildSkillReminder(skill: LocalSkill): string;
207
+ /**
208
+ * 注入决策单点(纯函数,供日志/诊断与 applySkillReminder 共用):
209
+ * - injected:BM25 最高分 skill 未注入过且命中规则 → 注入;
210
+ * - duplicate:BM25 最高分 skill 已注入过(同域多轮)→ 去重拦截,不寻次高分——
211
+ * 防止主 skill 已注入后次高分 skill 趁虚误注入(跨域劫持 bug 修复);
212
+ * - none:全量路由未命中(正常闲聊,日志层静默)。
213
+ *
214
+ * 注意:复合场景(本轮文本同时命中两个不同域的词,如「帮我找个停车场然后领张优惠券」)
215
+ * 仅注入最高分 skill;第二域在下一轮再次命中时才注入——这与旧行为一致(旧逻辑在首轮也只能注入一个)。
216
+ */
217
+ type SkillInjectionDecision = {
218
+ action: 'injected';
219
+ skill: LocalSkill;
220
+ } | {
221
+ action: 'duplicate';
222
+ skill: LocalSkill;
223
+ } | {
224
+ action: 'none';
225
+ };
226
+ declare function decideSkillInjection(input: {
227
+ /** 原始用户文本(selectSkill 打分输入) */
228
+ text: string;
229
+ /** 会话历史(不含本轮) */
230
+ history: ModelMessage[];
231
+ /** 可用 skills */
232
+ skills: LocalSkill[];
233
+ }): SkillInjectionDecision;
234
+ /**
235
+ * 注入组装(纯函数,009 D3 提取):reminder 块恒前置 + userContent 双形态归一化
236
+ * (string → [{type:'text',text}])。chat() 与 applySkillReminder 同源共用(字节级同构红线)。
237
+ */
238
+ declare function buildInjectedUserContent(skill: LocalSkill, userContent: string | ContentPart[]): ContentPart[];
239
+ /** 构建 recap 块(去重轮注入;短于完整 SOP,会话级恒定文案 + skill 名) */
240
+ declare function buildSkillRecapReminder(skill: LocalSkill): string;
241
+ /**
242
+ * 去重重申组装(纯函数):recap 块恒前置 + 双形态归一化。
243
+ * chat() 与 applySkillReminder 同源共用(与 buildInjectedUserContent 字节级同构红线对齐)。
244
+ */
245
+ declare function buildRecapUserContent(skill: LocalSkill, userContent: string | ContentPart[]): ContentPart[];
246
+ /**
247
+ * 加速模式注入组合(纯函数,不 push):
248
+ * - 调用契约:history 不含本轮(调用方保证在 history.push 前调用);
249
+ * - 决策经 decideSkillInjection 单点(候选集排除已注入 skill 后再路由:主 skill 已注入时,
250
+ * 复合文本中次高分未注入 skill 仍可命中注入);
251
+ * - injected → buildInjectedUserContent(完整 SOP reminder 恒前置);
252
+ * - duplicate → buildRecapUserContent(会话级恒真约束重申块前置——完整 SOP 去重,
253
+ * 恒真约束不塌陷;recap 块同标签形状 → 后续轮仍稳定判重);
254
+ * - none → 原样返回。
255
+ */
256
+ declare function applySkillReminder(input: {
257
+ /** 原始用户文本(selectSkill 打分输入,与 buildUserContent 同源) */
258
+ text: string;
259
+ /** buildUserContent 产物 */
260
+ userContent: string | ContentPart[];
261
+ /** 会话历史(不含本轮) */
262
+ history: ModelMessage[];
263
+ /** 可用 skills */
264
+ skills: LocalSkill[];
265
+ }): string | ContentPart[];
266
+ /**
267
+ * 前端 skill 加载表达事件序列(009 D9,纯函数,不发射):
268
+ * - 合成 tool-call 序列 [START, ARGS, END, RESULT],toolCallName = SKILL_TOOL_CALL_NAME;
269
+ * - args/result 经 contracts buildSkillToolCallPayload 单点序列化(与历史表达字节级同构);
270
+ * - 调用契约:RUN_STARTED 之后、模型流之前发射(前端 isGenerating 门控满足;
271
+ * thinking 气泡承载,TEXT_MESSAGE_START 的 id 替换保留 toolCalls);
272
+ * - toolCallId 由调用方生成传入(可测性);RESULT.messageId 为 AG-UI 必填字段。
273
+ */
274
+ declare function buildSkillToolCallEvents(skill: SkillRecord, toolCallId: string, messageId: string): ServerEvent[];
275
+
276
+ /**
277
+ * 尽早工具执行管线(PR-2):模型流中工具参数完整即预执行(fire-and-forget),
278
+ * mastra foreach 执行工具时经 take-once 缓存命中返回。
279
+ *
280
+ * 机制链:模型装饰器(Object.create 原型委托 + doStream 流 TransformStream 只观测透传)
281
+ * → 边界封板(tool-input-start(前序槽)/ tool-input-end(同 id 槽)/ flush + JSON.parse
282
+ * 验证——禁「闭合即 fire」:嵌套前缀歧义,裁定 1)→ fire 预执行(hardened Tool 层 execute,
283
+ * 校验/sanitize/context 重组/output 校验与 foreach 同构,裁定 3)→
284
+ * Map<toolCallId, Promise> take-once 缓存 → mastra foreach 命中(tool-cards hit 点)。
285
+ *
286
+ * 正确性安全网:args 漂移(交错流尾巴 / 终态 input ≠ 快照)→ invalidate 作废 →
287
+ * 纯丢弃(hit 点在 capture 层,drift 错误参数永不进卡池,INV4)→ mastra 原样执行(现状路径)。
288
+ *
289
+ * 不变量:INV1 单向降级(任何异常/无 scope/白名单外 → 字节级现状)· INV2 执行上界
290
+ * (同 toolCallId 预执行 ≤1 + 生效执行 =1)· INV3 正确性>缓存(漂移恒作废)·
291
+ * INV5 作废先于查找(装饰器 flush 在上游关流时触发,先于 foreach)。
292
+ * ⚠ mastra 内部契约依赖(升级哨兵测试锁定):AISDKV6LanguageModel 纯委托 doStream /
293
+ * toolOptions 携带 toolCallId / foreach 并发语义 / Tool 校验层。全部依赖的判定过程见 Agent Note
294
+ * (2026-09-04-parallel-tool-execution)。
295
+ *
296
+ * 观测(2026-09-05 强化):tool_preexec 事件 outcome × trigger × reason 归因——
297
+ * fired/hit/invalidated/skip × next-start/input-end/flush;hit 为区间行
298
+ * (startedAt=fire 时刻,durMs=advance)。双窗正交:preexec 窗 [fire, hit] 与
299
+ * agent 窗(tool_call/tool_result,_toolStarts 计时)互不覆写;联窗指标
300
+ * (execDur/saved/coverage)离线经 audit-toolcall-stream.mjs 计算。
301
+ */
302
+
303
+ /**
304
+ * 尽早执行白名单标记(symbol 经 getOwnPropertyDescriptors 穿透 harden/capture 两层浅克隆;
305
+ * 不进 JSON 序列化面)。定义单源在本文件(tool-cards hit 点与本管线同源,避免
306
+ * tool-cards ← → create-module-tool 模块环);模块侧 API(withEarlyExecution)经
307
+ * create-module-tool 转出。
308
+ */
309
+ declare const EARLY_EXECUTION_MARKER: unique symbol;
310
+
311
+ /**
312
+ * 模块侧工具创建封装(P3 评审 P0-1 修复)。
313
+ * 模块(module-* 与 scenario-* 模块)创建 LLM 工具时经此入口引用 @mastra/core,
314
+ * 避免模块直接 import 框架内部包导致 pnpm 解析出第二个 @mastra/core 实例
315
+ * (单例铁律,002 §10.1)。@mastra/core 由 app-sdk 唯一持有(dependencies),
316
+ * 经本文件 re-export,模块只需依赖 @tbox.cn/app-sdk。
317
+ */
318
+
319
+ /**
320
+ * 任意具体化实例的 Mastra Tool(泛型擦除别名,agent 侧专用)。
321
+ * Tool 泛型参数(input/output/context/id...)在各业务工具间反变,用 unknown 默认值
322
+ * 无法接受具体工具实例;统一用 any 擦除泛型差异,具体 schema 由工具自身约束。
323
+ * 结构兼容通用侧 RegistryTool(@tbox.cn/app-sdk-server)——注册表存储面按结构接收。
324
+ */
325
+ type AnyTool = Tool<any, any, any, any, any, string, any>;
326
+ /** internalTool 标记(symbol 经 getOwnPropertyDescriptors 穿透 harden/capture 两层浅克隆;不进 JSON 序列化面) */
327
+ declare const INTERNAL_TOOL: unique symbol;
328
+ /**
329
+ * 内部工具标记(B3):标记后的工具经 omitInternal 从 Agent 模型工具集中剔除——
330
+ * 模型看不到(工具列表更短 → 静态前缀更小),但 preTool 预执行路径照常工作
331
+ * (wrappedPreTools 从**源 map** 取 capture 包装实例,与 Agent 面解耦)。
332
+ *
333
+ * ⚠ 原实例标记(不返回新对象):build-engine D9 实例一致性校验(tools[def.tool.id] === def.tool)
334
+ * 要求声明、注册、标记三处同一实例——返回新对象会致 preTool 声明静默失配被丢。
335
+ * description 约定:内部工具 description 须含「模型勿调用」标注(doctor 第 24 条双向校验)。
336
+ */
337
+ declare function internalTool<T extends object>(tool: T): T;
338
+
339
+ /**
340
+ * 尽早执行白名单标记(原实例标记,禁拷贝——normalizePreTools D9 实例一致性
341
+ * (tools[tool.id] === def.tool)要求引用恒等,返回新对象会致 preTool 声明静默失配被丢)。
342
+ *
343
+ * 标记后的工具:模型流中该调用参数文本完整(边界封板 + JSON.parse 验证)即由引擎
344
+ * **异步预执行**(execCtx 仅含 requestContext + toolCallId + abortSignal),mastra foreach
345
+ * 消费缓存返回;参数漂移时预执行作废、foreach 原样重执行(正确性由引擎保证)。
346
+ *
347
+ * 使用规约(modules.md 同步):
348
+ * - 仅标记**只读查询类**工具(幂等、无副作用、同一参数可重复执行);
349
+ * 支付/表单提交/internalTool/带 backgroundConfig 或 suspend 的工具禁标记;
350
+ * - execute 禁依赖 requestContext 之外的 execCtx 字段(messages/llmContext 等预执行态缺席);
351
+ * - 预执行的失败/生效语义与 foreach 完全同构(硬化的 Tool 校验层全体生效)。
352
+ */
353
+ declare function withEarlyExecution<T extends object>(tool: T): T;
354
+ /**
355
+ * 剔除内部工具(B3):返回**新 Record**(不变量:源 map 只读——chat-engine wrappedPreTools
356
+ * 的 capture 包装实例取自源 map,过滤后的副本不影响 preTool 路径工具解析)。
357
+ * omitInternal(空集) = 恒等(回滚休眠态:不标记任何工具时行为与旧版逐字节一致)。
358
+ */
359
+ declare function omitInternal<T extends object>(tools: Record<string, T>): Record<string, T>;
360
+ /**
361
+ * 出卡工具 description 预告知(W2,2026-09-01):追加单源标准句
362
+ * 「命中数据时结果附可展示卡片(cards)。」(actions: true 追加「操作入口在卡片上。」)。
363
+ * 动机:出卡工具 description 零「卡」字样时,模型在调用前无从知晓结果含卡片候选
364
+ * → 直答不调用 → 候选池空 → 无卡(R3);一句话预告知在调用决策点建立预期。
365
+ *
366
+ * 使用规约(modules.md 同步):模块创建点**单点 wrap**;工具注册与 definePreTool 声明
367
+ * 均使用 wrapped 实例(normalizePreTools 实例一致性校验兼容);禁在 wrap 句之外
368
+ * 自行描述出卡机制(标签语法/cardType 目录——机制归平台段单源)。
369
+ * 浅拷贝(getOwnPropertyDescriptors)不改原实例;id/execute/inputSchema 引用保持。
370
+ */
371
+ declare function withCardEmissionHint<T extends {
372
+ description?: string;
373
+ }>(tool: T, opts?: {
374
+ actions?: boolean;
375
+ }): T;
376
+
377
+ /**
378
+ * LLM 入参卫生:递归清除对象键值位的 null 与字符串 "null"/"undefined"(trim + 大小写不敏感)。
379
+ * 刻意不做 JSON.parse——D11 字符串化规范下数字串(page:"1")必须保持字符串;
380
+ * 数组元素与其他字符串一律不动("null" 仅在对象键值位是污染形态)。
381
+ * 装配期经 build-engine hardenToolsForLlm 以 z.preprocess 注入,模块无感知。
382
+ */
383
+ declare function sanitizeLlmToolInput(input: unknown): unknown;
384
+ /** sanitize 包装(导出供 harden 与单测共用;非 zod schema 由调用方探测) */
385
+ declare function withLlmInputSanitize<T extends ZodTypeAny>(schema: T): T;
386
+
387
+ /** 投影截断上限(最近 N 条;10 轮对话决策余量) */
388
+ declare const PRE_TOOL_HISTORY_LIMIT = 20;
389
+ /** 单工具总预算缺省(decide + execute 共享;0 = 整体禁用) */
390
+ declare const DEFAULT_PRE_TOOL_TIMEOUT_MS = 2000;
391
+ /** 单轮预执行工具数上限(常量,非配置项——防上下文/延迟爆炸) */
392
+ /** 单轮预执行截断上限(2026-09-01 4→5:核心路径 preTool 扩容——parking-fee + listCoupons 加入后六族,
393
+ * 2026-09-03 always 三席(mall-context/floor-shops/customer-service-faq v3)+ keywords 竞争;
394
+ * 全命中轮仍按序裁至 5) */
395
+ declare const DEFAULT_MAX_PRE_TOOLS_PER_RUN = 5;
396
+ /** 超时错误(与执行失败同语义:不入 LLM 上下文,前端 error 态) */
397
+ declare class PreToolTimeoutError extends Error {
398
+ constructor();
399
+ }
400
+ /**
401
+ * 解析 TBOX_PRE_TOOL_TIMEOUT_MS(同 resolveSkillMode 形态):
402
+ * '0' → 0(禁用);非负整数 → 生效;非法/缺省 → 默认 + warn。
403
+ */
404
+ declare function resolvePreToolTimeout(value?: string): number;
405
+ /**
406
+ * 键序稳定序列化(B3 session-args dedup 键构造):
407
+ * 递归对象键按字典序排序 + 丢弃 undefined 值字段——同参不同键序/undefined 噪声 → 同键。
408
+ * 数组保序(顺序语义);循环引用防御性断裂([Circular])。
409
+ * 前提:入参为 JSON round-trip 产物(decide args 已过 JSON 序列化门)——纯树无共享引用,
410
+ * DAG 共享引用会被误判 [Circular](对本用例无影响;作通用工具时需知晓)。
411
+ */
412
+ declare function stableStringify(value: unknown): string;
413
+ /**
414
+ * mastra 泛型提取版 args 推断(D4,agent 侧专用):
415
+ * mastra Tool 首个泛型参数 = inputSchema 的 InferSchema(1.57.0 实证 inputSchema 为
416
+ * StandardSchemaWithJSON 非 ZodType——不能用 inputSchema 属性推导,必须泛型参数提取)。
417
+ * 通用侧 InferToolArgs(pre-tool-def.ts)为 standard-schema 兜底版。
418
+ */
419
+ type InferToolArgsMastra<T extends AnyTool> = T extends Tool<infer In, any, any, any, any, any, any> ? In extends Record<string, unknown> ? In : Record<string, unknown> : Record<string, unknown>;
420
+ /** 强类型构造 helper(D4):泛型由 tool 实例推断,decide 的 args 类型 = InferToolArgsMastra<typeof tool>。 */
421
+ declare function definePreTool<T extends AnyTool>(tool: T, spec: Omit<PreToolDef<T, InferToolArgsMastra<T>>, 'tool'>): PreToolDef<T, InferToolArgsMastra<T>>;
422
+ /**
423
+ * 候选选择(零 IO 纯函数):
424
+ * - always → 恒候选(score 0);keywords → BM25 命中(score > 0)且满足命中规则(长词 OR ≥2 token);
425
+ * - 同 tool.id 去重:always 优先,同模式保留高分(并列保留先出现者,R12);
426
+ * - 排序 key:(isAlways ? 0 : 1, -score, toolId)——always 保底,超限按字典序裁;
427
+ * - 截断至 DEFAULT_MAX_PRE_TOOLS_PER_RUN。
428
+ * - 防御(P3a,直调 createChatEngine 路径不经 normalize):旧形态声明(无 tool 引用 /
429
+ * 无 routing 字段 / 非法 routing / keywords 空 terms)→ warn 跳过不崩——
430
+ * 与装配路径「降级不崩」承诺对齐(装配路径声明恒合法,此防御为冗余保险)。
431
+ */
432
+ declare function selectPreTools(text: string, preTools: PreToolDef[]): PreToolDef[];
433
+ /**
434
+ * 历史投影(零 IO 纯函数):ModelMessage[] → PreToolHistoryTurn[]。
435
+ * - 截断最近 PRE_TOOL_HISTORY_LIMIT 条;仅 user/assistant;
436
+ * - content 提取:字符串直取 / parts 过滤 text part 拼接(不含 tool-call/tool-result/reasoning)。
437
+ * - 投影含 user 消息内的 system-reminder 注入块文本(card-decision/pre-tool/memory/skill 恒序
438
+ * 注入随 history 累积)——当前 decide 零消费 history 内容;未来若加扫描,必须先经
439
+ * `stripSystemReminderBlocks` 剥离(注入块文本不得参与路由打分)。
440
+ */
441
+ declare function projectHistory(history: readonly ModelMessage[]): PreToolHistoryTurn[];
442
+ /**
443
+ * 数据注入块构建(D5,每 done 工具一个块;server-only、仅内存 LLM 上下文):
444
+ * 不随 query 持久化(saveMessage.query = 原始 content);不进事件载荷 / 路由恢复(三隔离,D7)。
445
+ * 无 desc 属性(模型已在 availableTools 见 description)。
446
+ * 纯数据块:块内零指令文本——等价/快照时效语义归平台段「注入块协议」(单源),
447
+ * 块尾使用规则会随内存 history 跨轮累积泛化(R11 同族缺陷),已删除。
448
+ */
449
+ declare function buildPreToolDirectives(records: PreToolRecord[]): string[];
450
+ /**
451
+ * 预执行开始事件(执行前发射——前端立即显示「自动查询中」spinner,感知优化):
452
+ * [TOOL_CALL_START, TOOL_CALL_ARGS],ARGS 载荷经 contracts 单点序列化。
453
+ */
454
+ declare function buildPreToolCallStartEvents(input: {
455
+ toolName: string;
456
+ description?: string;
457
+ toolArgs?: unknown;
458
+ toolCallId: string;
459
+ }): ServerEvent[];
460
+ /** 预执行结束事件(执行后发射):[TOOL_CALL_END, TOOL_CALL_RESULT],RESULT.messageId 为 AG-UI 必填。 */
461
+ declare function buildPreToolCallEndEvents(input: {
462
+ toolName: string;
463
+ status: 'done' | 'error';
464
+ result?: unknown;
465
+ error?: string;
466
+ toolCallId: string;
467
+ messageId: string;
468
+ }): ServerEvent[];
469
+ /**
470
+ * 单工具 deadline(decide + execute 共享同一预算,per-tool 流水线):
471
+ * 候选并行下墙钟上界 = ms。超时 → PreToolTimeoutError(调用方按 error 降级,不注入)。
472
+ * 实现:settled 守卫 + then 双分支——超时后底层 fn 的迟到 resolve/reject 均被本 then
473
+ * 消费(丢弃),避免 Promise.race 形态下迟到 rejection 无处理器导致的 unhandledRejection。
474
+ */
475
+ declare function withDeadline<T>(ms: number, fn: () => Promise<T>): Promise<T>;
476
+ /** 预执行上下文(mastra 耦合单点收敛面) */
477
+ interface PreToolExecContext {
478
+ requestContext: RequestContext;
479
+ observe?: unknown;
480
+ abortSignal?: AbortSignal;
481
+ }
482
+ /**
483
+ * 直调工具执行(唯一接触 mastra execute 语义的 helper):
484
+ * - 守卫:execute 函数存在(ToolAction.execute 为可选字段);
485
+ * - 上下文:per-run requestContext(identity/credentials 并发安全)+ noopObserve + abortSignal;
486
+ * - JSON 归一:对齐 mastra 模型路径 ensureSerializable,防非 JSON 输出在
487
+ * WS 事件与 history ModelMessage 两处断裂;归一失败抛出 → 调用方按 error 降级。
488
+ */
489
+ declare function executePreTool(tool: RegistryTool, args: Record<string, unknown>, execCtx: PreToolExecContext): Promise<unknown>;
490
+
491
+ /** importance 基线(W 系列评审冻结):preference/fact 0.7、episode 0.6 */
492
+ declare const MEMORY_IMPORTANCE_BASE: Record<MemoryKind, number>;
493
+ /** 单用户(userId×scopeKey)记忆容量上限;超限淘汰最低 importance(同分删最旧) */
494
+ declare const MEMORY_MAX_PER_USER = 200;
495
+ /** list 缺省条数 */
496
+ declare const MEMORY_LIST_DEFAULT_LIMIT = 50;
497
+ /** list 上限(与容量上限对齐) */
498
+ declare const MEMORY_LIST_MAX_LIMIT = 200;
499
+ /**
500
+ * scope → 确定性排序键(INV-6 纯函数):键字母序 `k1:v1|k2:v2`;无 scope/空对象 → ''。
501
+ * 值内 `|` `:` `\` 反斜杠转义(双向唯一:不同 scope 恒映射不同 key)。
502
+ */
503
+ declare function scopeToKey(scope?: Record<string, string>): string;
504
+ /** content → 去重哈希(trim + lowercase 归一后 SHA-256 hex 前 16 位) */
505
+ declare function hashContent(content: string): string;
506
+ /** 生成记录 id:`mem_<8hex>` */
507
+ declare function generateMemoryId(): string;
508
+ /** 治理字段扩展(实现内部,不进契约面) */
509
+ interface StoredMemoryRecord extends MemoryRecord {
510
+ contentHash: string;
511
+ scopeKey: string;
512
+ }
513
+ declare function createInMemoryMemoryStore(now?: () => number): MemoryStore;
514
+
515
+ /**
516
+ * recall 缓存装饰器(B4,O1+O2 合一):MemoryStore 的 list 半 TTL 缓存 + 空结果负缓存短路。
517
+ *
518
+ * 动机(观测证据,会话 20260904bKa651026049):knowledge 模式 recall = search + list 双 HTTP
519
+ * 并发(gap 83-298ms ≈ 单 RTT);零命中轮照付双请求。零记忆用户(绝大多数)list 半恒空——
520
+ * 负缓存短路后 recallMs <10ms(第 2 轮起);有记忆用户 list 半 60s TTL 缓存免重复 RTT。
521
+ *
522
+ * 语义(不变量账本):
523
+ * - list() → TTL 缓存(键 = userId+scope);空结果 → empty 标记(负缓存);
524
+ * - search() → empty 标记新鲜 → 返回 [](零 HTTP);否则透传(结果不缓存——query 逐轮不同);
525
+ * - save()/delete() → 失效 list 缓存与 empty 标记(同实例写失效)→ 透传;
526
+ * - 错误不缓存(透传抛出,下轮重试);
527
+ * - bounded 状态显式容量(不变量 5):TTL + LRU 条目双限,防无界增长;
528
+ * - 组合序(不变量 6):withRecallCache(gatedStore)——gate 失败穿透装饰器,不污染缓存。
529
+ *
530
+ * 观测(N1 显式标记):getLastRecallCacheState(store) → recall.ts 读入 memory_recall.cache
531
+ * ('hit' | 'miss' | 'negative';装饰器缺席 → 'miss' 恒定,零影响)。
532
+ * 作用域审计:memory 三工具(memory_save/search/list)与 recall 共用同一 store 实例——
533
+ * save 经装饰器失效钩子保证工具写入后缓存一致;HTTP 管理面接受 ≤60s list staleness。
534
+ * 多机部署:会话粘同实例(sessions 进程内 Map)→ 写失效覆盖主导路径;跨实例窗口由 TTL 界定。
535
+ */
536
+
537
+ interface RecallCacheOptions {
538
+ /** list 结果 TTL(缺省 60_000ms) */
539
+ listTtlMs?: number;
540
+ /** LRU 条目上限(list 缓存与 empty 标记各自独立限;缺省 10_000) */
541
+ maxEntries?: number;
542
+ }
543
+ declare const DEFAULT_LIST_TTL_MS = 60000;
544
+ declare const DEFAULT_MAX_ENTRIES = 10000;
545
+ /** 命中态观测(N1):per-store 实例最近一次 recall 相关读的缓存判定 */
546
+ type RecallCacheState = 'hit' | 'miss' | 'negative';
547
+ declare function getLastRecallCacheState(store: MemoryStore): RecallCacheState;
548
+ declare function withRecallCache(store: MemoryStore, opts?: RecallCacheOptions): MemoryStore;
549
+
550
+ /**
551
+ * system-reminder 注入块工具(leaf:无依赖,trace-transform 与 memory/recall 共用单源)。
552
+ *
553
+ * 独立成模块的动机:trace 层净化不得 import memory/recall(logger 依赖链成环
554
+ * trace-transform → recall → logger → trace-exporter → trace-transform)。
555
+ *
556
+ * 块协议:`<system-reminder …>…</system-reminder>`(skill / preTool / memory /
557
+ * card-decision 四类注入块统一围栏,属性不限——见 platform-instructions)。
558
+ */
559
+ /**
560
+ * 剥离完整 `<system-reminder …>` 块(任意属性——skill/preTool/memory 等注入块):
561
+ * submitForm recall 查询清洗 + TBOX_TRACE 展示面净化共用。
562
+ * 未闭合残片保留(宁留不误删)。
563
+ */
564
+ declare function stripSystemReminderBlocks(text: string): string;
565
+
566
+ /**
567
+ * 记忆召回与注入块构造(017:引擎单点——混合配额检索策略归此,store 不掺配额,F1 正交化)。
568
+ *
569
+ * 检索策略(K1 修复形态):
570
+ * - search 半(相关性)与 list 半(importance)经 Promise.allSettled 并发,per-half 独立降级
571
+ * (半失败 → warn + 贡献空,不摧毁另一半);
572
+ * - 孤半存活(另一半 skipped/failed)→ 独占全额 topK 配额;
573
+ * - 双半皆死(capabilities 门控)→ 返回 [](等价 memory-off,零调用零 warn——L1);
574
+ * - 合并:search 结果在前(相关性优先)→ id 去重 → 截断 topK。
575
+ *
576
+ * 注入块(单一构造器——双 transport 字节级同构的构造性保证):
577
+ * - `<system-reminder memory>` 围栏 + 背景声明(提示注入防御:明示非本轮用户输入);
578
+ * - 行格式 `- (id) [kind] content(MM-DD)`——id 供 memory_forget 引用、日期供模型自裁矛盾(W2);
579
+ * - 内容区 `<` 转义(INV-5,preTool D5 同款边界:转义记录内容,不动围栏标签自身);
580
+ * - 零记录 → 空串(零命中零注入,W4)。
581
+ */
582
+
583
+ /** recall topK 缺省(与 memory_search 工具 topK 同值单源) */
584
+ declare const DEFAULT_MEMORY_TOP_K = 5;
585
+ /** 单条记录注入截断缺省(字符) */
586
+ declare const DEFAULT_MEMORY_MAX_CHARS_PER_RECORD = 200;
587
+ /** 归一 topK(undefined → 缺省;非法 → clamp ≥1) */
588
+ declare function clampMemoryTopK(v?: number): number;
589
+ /** 归一 maxCharsPerRecord(undefined → 缺省;非法 → clamp ≥20) */
590
+ declare function clampMemoryMaxChars(v?: number): number;
591
+ /** capabilities 缺省(未声明 = 全真,契约语义单点) */
592
+ declare function memoryStoreCapabilities(store: MemoryStore): MemoryStoreCapabilities;
593
+ /** 引擎 memory 选项(ChatEngineOptions.memory 展开形态;build-engine 透传) */
594
+ interface MemoryEngineOptions {
595
+ store: MemoryStore;
596
+ /** run 期 scope 解析(attributes → scope;装配端注入,对齐 deployment.assembly.extractScopeKey 先例) */
597
+ resolveScope?: (attributes: Record<string, unknown>) => Record<string, string> | undefined;
598
+ /** 召回条数缺省 5 */
599
+ topK?: number;
600
+ /** 单条注入截断缺省 200 字符 */
601
+ maxCharsPerRecord?: number;
602
+ /** recall 整体 deadline ms(缺省 = env TBOX_MEMORY_RECALL_TIMEOUT_MS → 200(B4 起,原 600);0 = 禁用注入) */
603
+ recallTimeoutMs?: number;
604
+ /** memory 后端模式(观测字段——memory_recall.mode/run_end 面板归因;缺省 'inmemory') */
605
+ mode?: 'inmemory' | 'knowledge';
606
+ }
607
+ /** 归一引擎选项(clamp 单点;构造期一次。recallTimeoutMs 由引擎层解析 env——此处不归一) */
608
+ declare function resolveMemoryEngineOptions(opts: MemoryEngineOptions): {
609
+ store: MemoryStore;
610
+ resolveScope?: MemoryEngineOptions['resolveScope'];
611
+ topK: number;
612
+ maxCharsPerRecord: number;
613
+ caps: MemoryStoreCapabilities;
614
+ mode: 'inmemory' | 'knowledge';
615
+ };
616
+ /** per-half 召回计时(观测面:memory_recall.halves——恒发,零命中轮也可见成本构成) */
617
+ interface RecallHalfTiming {
618
+ status: 'ok' | 'skipped' | 'failed';
619
+ durMs: number;
620
+ }
621
+ interface RecallResult {
622
+ records: MemoryRecord[];
623
+ halves: {
624
+ search: RecallHalfTiming;
625
+ list: RecallHalfTiming;
626
+ };
627
+ /** B4 recall 缓存判定(getLastRecallCacheState 透传——negative = 零 HTTP 全短路)。
628
+ * 双半并发下 state 由最后完成的半写入:负缓存场景两半均写 negative → 恒 negative;
629
+ * search 真调用场景(有记忆)→ miss(整体仍有真实 HTTP,语义诚实)。 */
630
+ cache: RecallCacheState;
631
+ }
632
+ /**
633
+ * 混合配额召回(纯检索策略单点):
634
+ * - search 半:topK = ceil(topK/2);list 半:limit = topK;
635
+ * - per-half allSettled 降级 + 孤半独占全额;
636
+ * - per-half 计时(恒产出——half.status/durMs 随返回上浮,引擎恒发 memory_recall 用);
637
+ * - 调用方经 withDeadline 施加整体上界(MemoryStore 接口无 signal 面——abort 由
638
+ * deadline 有界等待 + 汇合点丢弃承载,S3 语义等价)。
639
+ */
640
+ declare function recallMemories(input: {
641
+ userId: string;
642
+ scope?: Record<string, string>;
643
+ query: string;
644
+ }, opts: Pick<MemoryEngineOptions, 'store' | 'topK'>): Promise<RecallResult>;
645
+ /**
646
+ * 记忆注入块(单一构造器,纯函数):
647
+ * - 空记录 → ''(零命中零注入);
648
+ * - 行格式 `- (id) [kind] content(MM-DD)`;
649
+ * - 记录字段(id/content)`<` → `\u003c`(INV-5——转义记录内容区,围栏标签自身为字面量不受影响)。
650
+ */
651
+ declare function buildMemoryReminder(records: MemoryRecord[], maxChars?: number): string;
652
+
653
+ /**
654
+ * 记忆召回前端表达事件序列(018 tool-debug,纯函数,不发射):
655
+ * - 合成 tool-call 序列 [START, ARGS, END, RESULT],toolCallName = MEMORY_TOOL_CALL_NAME;
656
+ * - args/result 经 contracts buildMemoryToolCallPayload 单点序列化(records text 截断内置);
657
+ * - 调用契约:RUN_STARTED 之后、模型流之前发射(前端 isGenerating 门控满足);
658
+ * post-hoc 单点合成(skill 先例)——避开 abort 残患与 RUN_FINISHED sweep 假 error;
659
+ * - 仅 toolDebug 开启时由调用方发射;不持久化、不进历史重建(隐私边界——debug 期间
660
+ * 实时可见、历史不可回看);
661
+ * - toolCallId 由调用方生成传入(可测性);RESULT.messageId 为 AG-UI 必填字段。
662
+ */
663
+ declare function buildMemoryRecallToolCallEvents(input: {
664
+ toolCallId: string;
665
+ messageId: string;
666
+ query: string;
667
+ status: 'hit' | 'miss' | 'degraded' | 'skipped';
668
+ records?: MemoryRecord[];
669
+ reason?: string;
670
+ error?: string;
671
+ durMs?: number;
672
+ }): ServerEvent[];
673
+
674
+ interface MemoryToolDeps {
675
+ store: MemoryStore;
676
+ caps: MemoryStoreCapabilities;
677
+ maxCharsPerRecord: number;
678
+ /** attributes → scope 解析(装配端注入;与 recall 同源规则) */
679
+ resolveScope?: (attributes: Record<string, unknown>) => Record<string, string> | undefined;
680
+ }
681
+ /**
682
+ * 创建记忆三工具(构造期单点;全按 caps 注册——L1 死能力零广告:不注册即不进
683
+ * 工具列表/提示词目录。SPEC-5「save 恒注册」与 SPEC-7「readonly 段不提 save」组合矛盾,
684
+ * 按 L1 收敛为按能力注册;匿名/长度校验为运行期分支,恒走优雅错误)。
685
+ * 返回空对象 = 引擎不合并任何记忆工具。
686
+ */
687
+ declare function createMemoryTools(deps: MemoryToolDeps): Record<string, AnyTool>;
688
+
689
+ declare const KNOWLEDGE_DEFAULT_BASE_URL = "https://o.tbox.cn";
690
+ /** 空 scope 哨兵(⚠ ES term 匹配不了空串——scopeKey 列空值写入/过滤均用此值) */
691
+ declare const KB_SCOPE_GLOBAL = "__global__";
692
+ /**
693
+ * 可过滤列(编译期防 typo——平台对 schema 外列**静默丢弃过滤**(实测),
694
+ * 列名错 = 跨用户隔离击穿;安全约束进类型系统)。
695
+ */
696
+ type MemoryFilterColumn = 'id' | 'userId' | 'scopeKey' | 'contentHash';
697
+ interface PreFilterTerm {
698
+ column: MemoryFilterColumn;
699
+ value: string;
700
+ }
701
+ interface SortTerm {
702
+ field: 'importance' | 'createdAt';
703
+ order: 'asc' | 'desc';
704
+ }
705
+ /** 检索命中(极简面:content = 行 JSON 真源;segmentId = 平台 id(⚠ ≠ mem_id,软删复活会换新 id)) */
706
+ interface SegmentHit {
707
+ content: string;
708
+ segmentId: string;
709
+ }
710
+ /** 传输层错误(纯诊断面:retryable 为 callApi 私有——抛出时重试已耗尽) */
711
+ declare class KnowledgeOpenapiError extends Error {
712
+ readonly detail: {
713
+ code: string | null;
714
+ msg: string | null;
715
+ traceId: string | null;
716
+ httpStatus: number | null;
717
+ };
718
+ constructor(detail: {
719
+ code: string | null;
720
+ msg: string | null;
721
+ traceId: string | null;
722
+ httpStatus: number | null;
723
+ }, message?: string);
724
+ }
725
+ interface KnowledgeTransport {
726
+ /** 语义检索(HYBRID 缺省)。preFilters 恒非空——store 层永不无过滤检索(INV-1)。 */
727
+ retrieveSemantic(input: {
728
+ kbId: string;
729
+ query: string;
730
+ preFilters: PreFilterTerm[];
731
+ topK?: number;
732
+ }): Promise<SegmentHit[]>;
733
+ /** FIELD_SORT 检索(list/查重/清扫通道)。sorts 省略 = 不依赖排序语义的调用。 */
734
+ retrieveSorted(input: {
735
+ kbId: string;
736
+ preFilters: PreFilterTerm[];
737
+ sorts?: SortTerm[];
738
+ limit?: number;
739
+ }): Promise<{
740
+ hits: SegmentHit[];
741
+ total: number;
742
+ }>;
743
+ /** ⚠ UPSERT:同 PK 三元组(userId+scopeKey+contentHash)复用既有 segmentId。 */
744
+ addSegment(input: {
745
+ documentId: string;
746
+ rowJson: string;
747
+ }): Promise<string>;
748
+ /** false = 不存在(not-exist terminal 归一——store 不见平台错误形态)。 */
749
+ deleteSegment(input: {
750
+ segmentId: string;
751
+ }): Promise<boolean>;
752
+ /** ⚠ 缺任一 id 整批失败(平台语义)——调用方保证 id 全存在或自兜底。 */
753
+ batchDeleteSegments(input: {
754
+ documentId: string;
755
+ segmentIds: string[];
756
+ }): Promise<number>;
757
+ createKnowledgeBase(input: {
758
+ name: string;
759
+ tableSchema: unknown;
760
+ indexColumns: string[];
761
+ csv: string;
762
+ }): Promise<{
763
+ documentId: string;
764
+ }>;
765
+ findKnowledgeBasesByName(name: string): Promise<Array<{
766
+ id: string;
767
+ name: string;
768
+ gmtCreate?: string;
769
+ }>>;
770
+ getKnowledgeBase(kbId: string): Promise<{
771
+ type: string;
772
+ columns: Array<{
773
+ name: string;
774
+ dataType?: string;
775
+ indexed?: boolean;
776
+ }>;
777
+ /** KB 下 document 列表(bootstrap 复用路径的 documentId 来源——descIndexedDocuments 响应面) */
778
+ documents: Array<{
779
+ id: string;
780
+ }>;
781
+ }>;
782
+ getDocumentPrimaryKeys(documentId: string): Promise<string[]>;
783
+ }
784
+ interface KnowledgeOpenapiTransportOptions {
785
+ /** 缺省 process.env.TBOX_API_KEY;两者皆无 → 构造期 throw(fail-fast,对齐 knowledge-client 先例) */
786
+ apiKey?: string;
787
+ /** 缺省 https://o.tbox.cn;预发联调 https://agtgw-pre.alipay.com */
788
+ baseUrl?: string;
789
+ /** 预发 ACE 管控 Cookie 透传(仅预发联调——生产不设) */
790
+ cookie?: string;
791
+ /** 单测注入(缺省 globalThis.fetch) */
792
+ fetchImpl?: typeof fetch;
793
+ }
794
+ declare function createKnowledgeOpenapiTransport(opts: KnowledgeOpenapiTransportOptions): KnowledgeTransport;
795
+
796
+ /**
797
+ * 记忆存储实现 B:agtsearch 知识库 adapter(017;TBOX_MEMORY_STORE=knowledge 时启用)。
798
+ *
799
+ * 平台缺口 #1/#2 已闭合(agtgw yizhe-memory,预发 7/7 gates 实证 2026-08-30)——
800
+ * transport 走 agtgw openapi 直连(knowledge-transport.ts),完整四方法实现生效。
801
+ *
802
+ * 数据映射(8 列 STRUCTURED,PK = userId+scopeKey+contentHash):
803
+ * - 行 JSON = 语义真源(id/userId/scopeKey/kind/content/contentHash/importance/createdAt);
804
+ * - scopeKey 列存 scopeToKey 派生键(空 scope 用 '__global__' 哨兵——ES term 匹配不了空串),
805
+ * scope 对象经 parseScopeKey 还原;
806
+ * - createdAt 恒 STRING 列(NUMBER 底层 scaled_float(1e9),13 位 ms epoch 溢出 ES long)。
807
+ *
808
+ * 契约对齐(与实现 A 零漂移):
809
+ * - save 读前查重合并:保首见 id/kind/content/createdAt,importance 取大
810
+ * (竞态窗口 <2.2s 索引可见性内退化 last-write,PK 保证绝不重复行——Agent Note 备案);
811
+ * - search topK 缺省 5;list 排序 importance desc / createdAt desc;
812
+ * - delete 三列过滤现查真实 segmentId(平台 id ≠ mem_id,软删复活换新 id——实测)。
813
+ *
814
+ * 能力门控:四方法入口 × 四契约错误码一一对应——capabilities=false 时结构化拒绝
815
+ * (HTTP 管理面按同码映射 501;缺省全 false,翻转条件 = 平台发产 + probe 生产复测,
816
+ * 见 docs/reference/runtime.md 缺口登记)。
817
+ *
818
+ * 安全不变量(INV-1):检索调用恒带非空 preFilters——永不无过滤检索(跨用户泄露面)。
819
+ */
820
+
821
+ /** 平台能力缺口/门控错误(结构化错误码;调用方按优雅错误降级) */
822
+ declare class MemoryStoreUnsupportedError extends Error {
823
+ readonly code: MemoryErrorCode;
824
+ constructor(code: MemoryErrorCode, message: string);
825
+ }
826
+ /**
827
+ * 缺省 capabilities 全 true(2026-09-01 翻转——平台侧 agtgw yizhe-memory 已发布生产,
828
+ * 预发 7/7 gates + live 7/7 + probe 复跑 7/7 实证)。
829
+ * 语义:knowledge 模式显式启用(KB_ID+DOC_ID+API_KEY 三件套齐备)即全能力可用;
830
+ * 未启用者零影响(缺省 inmemory 不变)。
831
+ * 生产启用前建议先跑 probe 生产复测(scripts/probe-memory-kb-pre.mjs,BASE 指
832
+ * https://o.tbox.cn)确认生产面形态一致;并建议 TBOX_MEMORY_KB_VALIDATE=1 启动校验。
833
+ * 历史锚点:缺口期全 false 诚实降级(2026-08-24~08-30),见 Agent Note 2026-08-30 系列。
834
+ */
835
+ declare const DEFAULT_KNOWLEDGE_MEMORY_CAPABILITIES: MemoryStoreCapabilities;
836
+ interface KnowledgeMemoryStoreOptions {
837
+ /** 传输层唯一注入点(凭证/重试/URL 全封 transport——组合归 resolve.ts) */
838
+ transport: KnowledgeTransport;
839
+ /** 记忆专用知识库 ID */
840
+ knowledgeBaseId: string;
841
+ /** 记忆 document ID(addSegment/容量淘汰通道入参——平台 doc id 为生成值,必填) */
842
+ documentId: string;
843
+ /** 能力覆写(缺省 = 全 false 保守值) */
844
+ capabilities?: MemoryStoreCapabilities;
845
+ }
846
+ declare function createKnowledgeMemoryStore(opts: KnowledgeMemoryStoreOptions): MemoryStore;
847
+
848
+ /**
849
+ * 记忆知识库幂等建库(长期记忆实现 B 生命周期)。
850
+ *
851
+ * 流程(probe S1 产品化):
852
+ * - existing(env 固化值 kbId+documentId)给定 → schema 校验通过 → 复用;
853
+ * 不一致 → SCHEMA_MISMATCH fail-fast(不自动重建——误配保护);
854
+ * - 未给定 → 按名精确发现(fuzzy 结果 name === kbName 过滤,防近似名串扰)→ 命中取
855
+ * gmtCreate 最新 → documentId 取自 KB desc 的 documents 列表(记忆 KB 恒单 doc)→ 校验复用;
856
+ * - 零命中 → 建库(种子 CSV 哨兵行)→ 再发现 → 校验 → created: true。
857
+ *
858
+ * 种子 CSV 含哨兵行:表头-only CSV 存在空 segment 索引缺陷链(probe 实证),
859
+ * 哨兵行 userId='__system__' 不进任何用户命名空间(残留 1 条无害,运行时清理面恒不触达)。
860
+ */
861
+
862
+ /**
863
+ * 8 列 STRUCTURED schema(PK = userId+scopeKey+contentHash;仅 content indexed;createdAt STRING)。
864
+ * ⚠ 逐字段对齐 probe MEMORY_SCHEMA(建库请求体真源):
865
+ * - createdAt 必须 STRING(NUMBER 底层 scaled_float(1e9),13 位 ms epoch 溢出 ES long);
866
+ * - indexed = 语义语料开关(仅该列值进 embedding/BM25——importance/createdAt 为纯排序列无需索引)。
867
+ */
868
+ declare const MEMORY_KB_SCHEMA: {
869
+ readonly name: "agent_memory";
870
+ readonly description: "tbox agent 长期记忆";
871
+ readonly columns: readonly [{
872
+ readonly name: "id";
873
+ readonly dataType: "STRING";
874
+ readonly required: true;
875
+ readonly order: 1;
876
+ }, {
877
+ readonly name: "userId";
878
+ readonly dataType: "STRING";
879
+ readonly required: true;
880
+ readonly primaryKey: true;
881
+ readonly order: 2;
882
+ }, {
883
+ readonly name: "scopeKey";
884
+ readonly dataType: "STRING";
885
+ readonly primaryKey: true;
886
+ readonly order: 3;
887
+ }, {
888
+ readonly name: "kind";
889
+ readonly dataType: "STRING";
890
+ readonly order: 4;
891
+ }, {
892
+ readonly name: "content";
893
+ readonly dataType: "STRING";
894
+ readonly indexed: true;
895
+ readonly order: 5;
896
+ }, {
897
+ readonly name: "contentHash";
898
+ readonly dataType: "STRING";
899
+ readonly primaryKey: true;
900
+ readonly order: 6;
901
+ }, {
902
+ readonly name: "importance";
903
+ readonly dataType: "NUMBER";
904
+ readonly order: 7;
905
+ }, {
906
+ readonly name: "createdAt";
907
+ readonly dataType: "STRING";
908
+ readonly order: 8;
909
+ }];
910
+ };
911
+ declare const MEMORY_KB_INDEX_COLUMNS: string[];
912
+ /** 种子 CSV(表头 + 哨兵行) */
913
+ declare const MEMORY_KB_SEED_CSV: string;
914
+ declare class KnowledgeBootstrapError extends Error {
915
+ readonly code: 'SCHEMA_MISMATCH' | 'DISCOVER_FAILED' | 'VALIDATE_TIMEOUT';
916
+ readonly detail?: Record<string, unknown> | undefined;
917
+ constructor(code: 'SCHEMA_MISMATCH' | 'DISCOVER_FAILED' | 'VALIDATE_TIMEOUT', message: string, detail?: Record<string, unknown> | undefined);
918
+ }
919
+ interface BootstrapMemoryKbOptions {
920
+ transport: KnowledgeTransport;
921
+ /** 缺省 'agent-memory'(多应用同租户时调用方应传应用身份后缀名防串扰) */
922
+ kbName?: string;
923
+ /** env 固化值(TBOX_MEMORY_KB_ID/DOC_ID)——跳过发现直接校验复用 */
924
+ existing?: {
925
+ kbId: string;
926
+ documentId: string;
927
+ };
928
+ }
929
+ interface BootstrapMemoryKbResult {
930
+ kbId: string;
931
+ documentId: string;
932
+ created: boolean;
933
+ }
934
+ /** 启动期校验(TBOX_MEMORY_KB_VALIDATE 时模板装配调用——防 kbId 运行时误配静默击穿 INV-1:
935
+ * 平台对 schema 外列**静默丢弃过滤**(实测),错配 KB 上过滤失效 = 跨用户泄露面)。
936
+ * 失败 throw KnowledgeBootstrapError——调用方(guard)决定 fail-fast 或降级。
937
+ * timeoutMs 给定 → 整体 deadline:显式 settle race(非 Promise.race——输方 rejection 必然
938
+ * 被处理)+ timer.unref(防校验挂起时 keep event loop alive 悬挂进程退出)+ 幂等 settle。 */
939
+ declare function validateMemoryKnowledgeBase(opts: {
940
+ transport: KnowledgeTransport;
941
+ kbId: string;
942
+ documentId: string;
943
+ timeoutMs?: number;
944
+ }): Promise<void>;
945
+ /** 幂等建库:existing 校验复用 / 按名发现复用 / 全新创建,产出 kbId + documentId。 */
946
+ declare function bootstrapMemoryKnowledgeBase(opts: BootstrapMemoryKbOptions): Promise<BootstrapMemoryKbResult>;
947
+
948
+ /**
949
+ * 记忆装配解析(017):env → store 工厂单点(模板装配层消费)。
950
+ *
951
+ * TBOX_MEMORY_STORE:
952
+ * - 未设置 / 'inmemory' → 内存实现(模板缺省开启);
953
+ * - 'off' → 逃生舱(完全关闭——工具/recall/提示词段/HTTP 面全部不装配);
954
+ * - 'knowledge' → 知识库实现(TBOX_MEMORY_KB_ID + TBOX_MEMORY_KB_DOC_ID + TBOX_API_KEY
955
+ * 三缺一 → warn 回退 inmemory;建库产出固化值经 scripts/bootstrap-memory-kb.mjs);
956
+ * - 非法值 → warn 回退 inmemory。
957
+ */
958
+
959
+ /** recall 整体 deadline 缺省(ms)——首字延迟预算的检索上限。
960
+ * B4:600 → 200(负缓存短路后零记忆用户 recallMs <10ms;真查询单 RTT 150-300ms——
961
+ * 200ms 覆盖单 RTT + decode 余量,超时降级跳过不再拖首字)。 */
962
+ declare const DEFAULT_MEMORY_RECALL_TIMEOUT_MS = 200;
963
+ interface ResolvedMemoryStore {
964
+ enabled: boolean;
965
+ mode: 'inmemory' | 'knowledge' | 'off';
966
+ store?: MemoryStore;
967
+ /** 校验模式(resolveMemoryStoreGuarded 统一填充——诊断零分支;直调 resolveMemoryStore 时缺席) */
968
+ validateMode?: MemoryValidateMode;
969
+ }
970
+ interface MemoryStoreEnv {
971
+ store?: string;
972
+ kbId?: string;
973
+ /** TBOX_MEMORY_KB_DOC_ID——记忆 document ID(addSegment/容量淘汰通道入参) */
974
+ kbDocId?: string;
975
+ /** TBOX_MEMORY_KB_BASE_URL——缺省 https://o.tbox.cn;预发联调 https://agtgw-pre.alipay.com */
976
+ kbBaseUrl?: string;
977
+ /** TBOX_MEMORY_KB_COOKIE——预发 ACE 管控透传(仅预发联调) */
978
+ kbCookie?: string;
979
+ /** 凭证覆写(缺省 TBOX_API_KEY) */
980
+ apiKey?: string;
981
+ }
982
+ /**
983
+ * 解析记忆存储(单点 + 非法值 warn 回退——确定性降级,对齐 resolveSkillMode 先例)。
984
+ */
985
+ declare function resolveMemoryStore(env: MemoryStoreEnv): ResolvedMemoryStore;
986
+ /**
987
+ * 解析 recall deadline(TBOX_MEMORY_RECALL_TIMEOUT_MS;缺省 200ms——B4;非法 → 缺省 + warn;
988
+ * 0 = 无限等待——不推荐,仅供诊断)。确定性:静默降级为缺省。
989
+ */
990
+ declare function resolveMemoryRecallTimeout(value?: string): number;
991
+ type MemoryValidateMode = 'off' | 'degrade' | 'strict';
992
+ declare const DEFAULT_MEMORY_VALIDATE_TIMEOUT_MS = 10000;
993
+ interface MemoryGuardEnv extends MemoryStoreEnv {
994
+ /** TBOX_MEMORY_KB_VALIDATE 原始值(resolver 内归一) */
995
+ validate?: string;
996
+ /** TBOX_MEMORY_KB_VALIDATE_TIMEOUT_MS 原始值 */
997
+ validateTimeoutMs?: string;
998
+ }
999
+ interface MemoryGuardDeps {
1000
+ /** 校验函数注入缝(单测 deferred / 未来自定义校验策略;缺省 validateMemoryKnowledgeBase) */
1001
+ validate?: typeof validateMemoryKnowledgeBase;
1002
+ }
1003
+ /** 解析校验模式(未设置/0/false/off → off;1/true → degrade;strict → strict;非法 → warn + off) */
1004
+ declare function resolveMemoryValidateMode(value?: string): MemoryValidateMode;
1005
+ /** 解析校验整体超时(缺省 10s;n>=1 且有限才接受,非法 warn 回退——对齐 resolveMemoryRecallTimeout 先例) */
1006
+ declare function resolveMemoryValidateTimeout(value?: string): number;
1007
+ /**
1008
+ * 统一记忆装配入口(模板单调用点):resolveMemoryStore + KB 校验三态组合。
1009
+ * - off / 非 knowledge → 直返(零 transport 构造零网络),validateMode 恒填充;
1010
+ * - strict → await 校验(timeoutMs 有界),失败 rethrow(模板顶层 await 拒绝 = 启动失败);
1011
+ * - degrade → 即返 gated store(listen 零阻塞,INV-D 装配照常),校验后台并发,
1012
+ * validation 永不 reject(async IIFE catch 归一)。
1013
+ * gate 单次创建:返回的 store 即唯一实例(ctx.memory 与引擎同源——context.ts 同源注释契约)。
1014
+ */
1015
+ declare function resolveMemoryStoreGuarded(env: MemoryGuardEnv, deps?: MemoryGuardDeps): Promise<ResolvedMemoryStore>;
1016
+
1017
+ /**
1018
+ * 记忆闸门 store(017 M4:KB 校验异步降级 S8 终态)。
1019
+ *
1020
+ * INV-D(装配不变量):降级只发生在调用执行时;装配面(三工具注册/引擎 recall/mall
1021
+ * guidance/平台提示词段/api/memory 路由/ctx.memory)在任何校验状态下恒定不变——因此本
1022
+ * 装饰器恒返回 store(存在性不变)且 capabilities 透传 inner(构造期门控四消费点依赖其
1023
+ * 值;置 false = 装配期拆工具/路由/提示词段,直接违背 INV-D,禁改)。
1024
+ *
1025
+ * INV-1(安全不变量):pending 期零 KB 触达(await 挡在 inner 前);failed 期数据面全禁
1026
+ * (抛 MemoryUnavailableError——不写错配 KB、不在错配 KB 上检索)。
1027
+ *
1028
+ * 降级语义归属消费端(gate 零 fail-value 分支):引擎 recall catch 跳过注入(既有);
1029
+ * 三工具结构化错误(既有);HTTP 管理面 503 + MEMORY_KB_VALIDATION_FAILED。
1030
+ */
1031
+
1032
+ /** 校验结果(promise 永不 reject——guard 内 catch 归一,杜绝 unhandledRejection) */
1033
+ type MemoryValidationOutcome = {
1034
+ ok: true;
1035
+ } | {
1036
+ ok: false;
1037
+ error: unknown;
1038
+ };
1039
+ /** 校验失败降级态错误(routes/memory.ts 按 name 匹配 → 503;对齐 MemoryStoreUnsupportedError 先例) */
1040
+ declare class MemoryUnavailableError extends Error {
1041
+ readonly cause?: unknown | undefined;
1042
+ readonly code: "MEMORY_KB_VALIDATION_FAILED";
1043
+ constructor(message: string, cause?: unknown | undefined);
1044
+ }
1045
+ /** 闸门包装:四方法同构——await validation → ok 委托 inner / failed 抛 MemoryUnavailableError */
1046
+ declare function createGatedMemoryStore(inner: MemoryStore, validation: Promise<MemoryValidationOutcome>): MemoryStore;
1047
+
1048
+ interface EngineRunInput {
1049
+ runId: string;
1050
+ threadKey: string;
1051
+ requestContext?: Readonly<RequestContext$1>;
1052
+ abortSignal: AbortSignal;
1053
+ }
1054
+ interface EngineStepControlInput extends EngineRunInput {
1055
+ requestId: string;
1056
+ sessionId: string;
1057
+ question: string;
1058
+ availableToolIds: readonly string[];
1059
+ maxSteps: number;
1060
+ /** Epoch milliseconds, measured on entry to the model path. */
1061
+ startedAt: number;
1062
+ }
1063
+ interface EngineModelStepInput extends EngineRunInput {
1064
+ /** One-based model step number. */
1065
+ stepNumber: number;
1066
+ availableToolIds: readonly string[];
1067
+ maxSteps: number;
1068
+ remainingSteps: number;
1069
+ }
1070
+ interface EngineToolCallInput extends EngineRunInput {
1071
+ stepNumber: number;
1072
+ toolCallId: string;
1073
+ toolName: string;
1074
+ args: unknown;
1075
+ }
1076
+ interface EngineToolResultInput extends EngineToolCallInput {
1077
+ output?: unknown;
1078
+ error?: unknown;
1079
+ }
1080
+ interface EngineStepResultInput extends EngineModelStepInput {
1081
+ text: string;
1082
+ toolCalls: readonly {
1083
+ toolCallId: string;
1084
+ toolName: string;
1085
+ args: unknown;
1086
+ }[];
1087
+ toolResults: readonly {
1088
+ toolCallId: string;
1089
+ toolName: string;
1090
+ output?: unknown;
1091
+ error?: unknown;
1092
+ }[];
1093
+ isFinal: boolean;
1094
+ finishReason: string;
1095
+ }
1096
+ interface EngineRunEndInput extends EngineRunInput {
1097
+ status: 'completed' | 'stopped' | 'cancelled' | 'error';
1098
+ reasonCode?: string;
1099
+ /** The transcript could not be safely continued; callers must establish a new session. */
1100
+ quarantine: boolean;
1101
+ }
1102
+ type EngineStepToolChoice = 'required' | {
1103
+ toolId: string;
1104
+ };
1105
+ interface EngineStepController {
1106
+ /** Optional hard wall-clock deadline. The SDK aborts the producer at this time. */
1107
+ deadlineAt?: number;
1108
+ beforeModelStep(input: EngineModelStepInput): Promise<{
1109
+ appendHint?: string;
1110
+ activeToolIds: readonly string[];
1111
+ summaryOnly?: boolean;
1112
+ toolChoice?: EngineStepToolChoice;
1113
+ }>;
1114
+ beforeToolCall(input: EngineToolCallInput): Promise<void | {
1115
+ proceed: false;
1116
+ output: unknown;
1117
+ }>;
1118
+ afterToolCall(input: EngineToolResultInput): Promise<void>;
1119
+ afterModelStep(input: EngineStepResultInput): Promise<{
1120
+ action: 'follow-runtime' | 'continue' | 'publish-final' | 'stop';
1121
+ reasonCode?: string;
1122
+ }>;
1123
+ onRunEnd(input: EngineRunEndInput): Promise<void>;
1124
+ }
1125
+ type EngineStepControlFactory = (input: EngineStepControlInput) => EngineStepController | Promise<EngineStepController>;
1126
+
1127
+ interface ChatEngineOptions {
1128
+ instructions: string;
1129
+ model: any;
1130
+ tools: Record<string, Tool>;
1131
+ /** 卡片注册表:cardType → CardMeta(capture 校验 + emit 校验共用) */
1132
+ cardRegistry: Record<string, CardMeta>;
1133
+ /** Optional run-local, domain-neutral model/tool control. Not used by deterministic or form paths. */
1134
+ stepControl?: EngineStepControlFactory;
1135
+ /** trace exporter(默认使用 SDK 内置单例) */
1136
+ traceExporter?: TboxTraceExporter;
1137
+ /** 文件 URL 前缀(content-builder 用) */
1138
+ fileUrlPrefix?: string;
1139
+ /** 模型名(用于日志) */
1140
+ modelName?: string;
1141
+ /**
1142
+ * 意图路由表(B21:业务意图表由应用源码提供,hybrid 模式 003 §3.3)。
1143
+ * 提供时 chat() 先 matchIntent;handler 缺省直接出卡/文字,也可用 continueWith 续接完整 Agent。
1144
+ */
1145
+ intentRoutes?: IntentRoute[];
1146
+ /** 意图命中后的业务分发(由组装端经 ctx.handlers.dispatch 提供) */
1147
+ handlerDispatch?: (route: IntentRoute, content: string, reqCtx?: RequestContext$1) => Promise<HandlerResult | undefined>;
1148
+ /**
1149
+ * 持久化回调:保存消息到外部对话服务。
1150
+ * 返回 savedMessageId(已持久化的标识)。
1151
+ * cards:本轮 run 下发的卡片快照(P3 W1,随消息同源提交,004 D1)。
1152
+ */
1153
+ saveMessage?: (args: {
1154
+ conversationId: string;
1155
+ query: string;
1156
+ answer: string;
1157
+ mediaItems?: SendMessageMediaItem[];
1158
+ outerBusinessId?: string;
1159
+ cards?: CardSnapshot[];
1160
+ /** 009 D10:本轮 injected 的 skill 加载记录(供历史表达重建,随消息持久化 inputs.skills) */
1161
+ skills?: SkillRecord[];
1162
+ /** 010:本轮预执行成功的工具记录(仅 done,供历史表达重建,随消息持久化 inputs.preTools) */
1163
+ preTools?: PreToolRecord[];
1164
+ }) => Promise<string | undefined>;
1165
+ /**
1166
+ * 本地 skill 模式(009 D2):accelerated(默认)/ progressive。
1167
+ * 全局配置、运行期恒定:accelerated → Agent 不注册 skill 工具,本地路由命中后 reminder 注入
1168
+ * user message(system prompt/工具列表恒定 → 前缀缓存稳定);progressive → 全量注册 InlineSkill。
1169
+ */
1170
+ skillMode?: SkillMode;
1171
+ /** 可用本地 skills(build-engine 合并模块声明 + 应用加载产物后传入) */
1172
+ skills?: LocalSkill[];
1173
+ /**
1174
+ * 可用前置工具声明(010:build-engine 合并模块声明 + 应用产物并校验 toolId 后传入)。
1175
+ * 空/缺省 → 全链路零开销。
1176
+ */
1177
+ preTools?: PreToolDef[];
1178
+ /** 单工具总预算 ms(resolve + execute 共享;缺省 DEFAULT_PRE_TOOL_TIMEOUT_MS;0 = 整体禁用) */
1179
+ preToolTimeoutMs?: number;
1180
+ /** 前置工具 resolve 入参的模块上下文(build-engine 传入 ctx;直调 createChatEngine 需自备) */
1181
+ preToolContext?: ServerContext;
1182
+ /**
1183
+ * 011 B3:卡片动作 token 签发器(模板装配注入闭包;缺省 = 不签发)。
1184
+ * payload 出卡前调用,按 cardType 匹配注册动作附加 actions/actionTokens;
1185
+ * sessionId 由引擎从 runCtx.scopeSessionId 登记供给。
1186
+ */
1187
+ cardActionAttacher?: (payload: _tbox_cn_app_contracts.TboxCardPayload, sessionId: string) => Promise<_tbox_cn_app_contracts.TboxCardPayload>;
1188
+ /**
1189
+ * 011 S5(runBudget):agent loop 步数预算。
1190
+ * maxSteps 缺省 8;0 = 禁用(不传 mastra maxSteps)。
1191
+ * 触界语义:不执行新工具调用(mastra maxSteps 语义),工具定义仍全量传入,
1192
+ * 孤儿 tool-call 轮以合成文案收尾(防空轮 + deepseek 空 tool-call 对 400)。
1193
+ */
1194
+ runBudget?: RunBudgetOptions;
1195
+ /**
1196
+ * 单轮出卡上限(缺省 DEFAULT_MAX_CARDS_PER_TURN=3;构造期 clamp ≥1)。
1197
+ * 与平台段提示词目录的 maxCards 构造性同源(build-engine 双喂同一值)。
1198
+ */
1199
+ maxCardsPerTurn?: number;
1200
+ /**
1201
+ * 长期记忆(017):store + 召回配置。未装配 = 全链路零开销(工具/recall/提示词段均不启用,
1202
+ * 未装配应用字节级回归)。意图命中轮/匿名 run 跳过 recall;注入经 mastra context 通道
1203
+ * (request-only——不进 history/saveMessage/事件流,三隔离)。
1204
+ */
1205
+ memory?: MemoryEngineOptions;
1206
+ /**
1207
+ * 018 tool-debug:工具调试视图(TBOX_TOOL_DEBUG env 单源解析,装配端经 resolveToolDebug
1208
+ * 传入)。开启时:memory 召回/silent preTool 以伪工具事件下发前端(不持久化)、
1209
+ * ws-server HELLO_ACK 携带 toolDebug 旗标解锁客户端 dev 视图。缺省 false = 零行为回归。
1210
+ */
1211
+ toolDebug?: boolean;
1212
+ /**
1213
+ * PR-2 尽早执行管线(缺省 false = 零行为):模型流中白名单工具参数完整即预执行
1214
+ * (fire-and-forget),mastra foreach 命中缓存返回。env TBOX_EARLY_TOOL_EXECUTION
1215
+ * 单源(装配端经 resolveEarlyToolExecution 解析)。多工具轮收益以 parallelToolCalls
1216
+ * 开启为前提;单工具轮行为等价现状。
1217
+ */
1218
+ earlyToolExecution?: boolean;
1219
+ /**
1220
+ * 流式标签卫生(stream-tag-engine)config 路径(测试注入;缺省与 provider 装配同链
1221
+ * DEFAULT_LLM_PROVIDER_CONFIG_PATH)。每请求热读 contentTagHygiene——off/extraTags
1222
+ * 变更即时生效,不改代码即可止血/回滚。
1223
+ */
1224
+ contentTagConfigPath?: string;
1225
+ /**
1226
+ * 出卡协议标签剥离(装配轴,缺省 true;构造期归一)——cards 收编统一引擎后的
1227
+ * 调试面开关。false = cards 标签可见 + decision 恒空(decideCards 走兜底池末张);
1228
+ * 卫生族(think/tool-call-text)不经此轴(config 轴 contentTagHygiene 专属)。
1229
+ */
1230
+ cardTagStripping?: boolean;
1231
+ }
1232
+ /** maxCardsPerTurn 归一(undefined → 缺省;非法值 → clamp ≥1 + warn;NaN/Infinity → 缺省) */
1233
+ declare function clampMaxCards(v?: number): number;
1234
+ /**
1235
+ * toolDebug 解析(018:TBOX_TOOL_DEBUG env 单源;装配端 app.ts 调用,对齐 resolveSkillMode /
1236
+ * resolvePreToolTimeout 先例):
1237
+ * - 显式值优先:'1'/'true' → 开;'0'/'false' → 关(本地关/部署态开的逃生舱双向可用);
1238
+ * - 缺省/非法 → warn(仅非法值)+ 缺省 = NODE_ENV !== 'production'
1239
+ * (对齐 dev-login 非 production 默认开启先例;容器部署 entrypoint 恒 production → 默认关)。
1240
+ */
1241
+ declare function resolveToolDebug(value?: string, nodeEnv?: string): boolean;
1242
+ /**
1243
+ * 尽早执行解析(PR-2:TBOX_EARLY_TOOL_EXECUTION env 单源;装配端 app.ts 调用):
1244
+ * 仅 '1'/'true' 开(显式 opt-in——管线为延迟优化非行为修正,恒缺省关 + 观测先行);
1245
+ * 其余('0'/非法/缺席)恒 false。非法值不 warn(对齐 TBOX_LLM_AFFINITY 宽松先例——
1246
+ * env 旋钮家族默错默对,不做告警噪音)。
1247
+ */
1248
+ declare function resolveEarlyToolExecution(value?: string): boolean;
1249
+ /** runBudget 配置(011 C4:禁用 toolChoice:'none',截断不用它) */
1250
+ interface RunBudgetOptions {
1251
+ /** 模型 loop 最大步数(缺省 8;0 = 禁用) */
1252
+ maxSteps?: number;
1253
+ }
1254
+ /**
1255
+ * runBudget 步数预算单源解析(对齐 clampMaxCards 装配先例,build-engine 双喂消费):
1256
+ * undefined → 缺省 8(预算恒生效);显式值透传(0 = 禁用;负数沿用既有透传语义,不 clamp)。
1257
+ * 双喂 = 平台段预算行(提示词说的数)+ agent.stream maxSteps(引擎执行的数)同值同源。
1258
+ */
1259
+ declare function resolveMaxSteps(runBudget?: RunBudgetOptions): number;
1260
+ /** 运行上下文(连接级身份 + 外部凭据),经 ws-server 从连接绑定传入 */
1261
+ interface RunContext {
1262
+ identity?: Identity;
1263
+ credentials?: ExternalCredentials;
1264
+ /** 011 S5:连接级 attributes(HELLO context 并入,如 mall scope),透传 mastra RequestContext */
1265
+ attributes?: Record<string, unknown>;
1266
+ /** 011 B3:HELLO bootstrap 的 scope 会话 id(卡片动作 token 签发用) */
1267
+ scopeSessionId?: string;
1268
+ }
1269
+ interface ChatEngine {
1270
+ /**
1271
+ * 对话入口。
1272
+ * @param threadKey 线程键(006 D5):conversationId(唯一会话键);匿名无会话时由
1273
+ * ws-server 传入连接级 fallback 键(服务端生成)。
1274
+ * @param conversationId 真实会话 ID(用于持久化 saveMessage 与 requestId);匿名缺省。
1275
+ * @param runCtx 运行上下文(连接级身份 + 外部凭据)。
1276
+ */
1277
+ chat(threadKey: string, content: string, onEvent: (event: ServerEvent) => void, mediaItems?: SendMessageMediaItem[], _inputMethod?: string, conversationId?: string, runCtx?: RunContext): Promise<void>;
1278
+ submitForm(threadKey: string, surfaceId: string, formId: string, formData: Record<string, unknown>, onEvent: (event: ServerEvent) => void, conversationId?: string, runCtx?: RunContext): Promise<void>;
1279
+ cancelRun(threadKey: string, runId?: string): void;
1280
+ /** Prevent unsafe transcript reuse and release this thread's in-memory execution state. */
1281
+ quarantineThread?(threadKey: string): void;
1282
+ emitCard(spec: {
1283
+ cardType: string;
1284
+ data: Record<string, unknown>;
1285
+ conversationId: string;
1286
+ messageId?: string;
1287
+ id?: string;
1288
+ }): void;
1289
+ registerSession(threadKey: string, onEvent: (event: ServerEvent) => void): void;
1290
+ unregisterSession(threadKey: string): void;
1291
+ /** 诊断(009):当前装配的本地 skills(名称/描述/路由词) */
1292
+ listSkills(): {
1293
+ name: string;
1294
+ description: string;
1295
+ routingTerms: string[];
1296
+ }[];
1297
+ /** 诊断(010):当前装配的前置工具(toolId/描述/路由形态) */
1298
+ listPreTools(): {
1299
+ toolId: string;
1300
+ description: string;
1301
+ routing: PreToolRouting;
1302
+ }[];
1303
+ }
1304
+ declare function createChatEngine(opts: ChatEngineOptions): ChatEngine;
1305
+
1306
+ /**
1307
+ * 流式标签卫生引擎(stream-tag-engine)——消费侧内容级防护主防线。
1308
+ *
1309
+ * 问题:模型退化(量化损失/网关负载)导致 special token 残缺/变体/同形字符替换,
1310
+ * 服务端协议解析按标准字节匹配漏识别 → think 推理体、tool-call 文本信封整段
1311
+ * 落入 content——泄露到前端正文、saveMessage 落库、TTS。本引擎在 chat-engine
1312
+ * 消费侧流式逐字符处置:匹配即剥(取证),失配即释放(G1 字节恒等)。
1313
+ *
1314
+ * 机制-数据分离:标签族以 TagSpec 声明式注册(构造器工厂 + Trie 编译),行为只由
1315
+ * body 位派生(decision=证据保全 / drop=痕迹清除),spec 不携带行为分支——消除非法
1316
+ * 组合空间。cards 协议(card-decision.ts)经同引擎收编(CARDS_SPEC = xmlTagDecision)。
1317
+ *
1318
+ * 不变量:
1319
+ * - G1 字节恒等:无匹配输出逐字符立即释放、零跨 push 缓冲;正文含 `<`/`<code>` 等
1320
+ * 第 2 字符失配即释放,零影响零观测。
1321
+ * - history 零触碰:rawText/fullReasoning 累加在引擎之外(chat-engine 接线保证),
1322
+ * agent history 三条入史路径字节不变(LLM 轨道真值原样)。
1323
+ * - 归一化仅比对:normalize 为 1:1 码点映射且恒不映射 `<`;held 恒存原文
1324
+ * (释放/hits.form 吐原文)。同实例内 specs 共享同一 normalize(trie 边键一致性)。
1325
+ * - 字面量约定:open/close 恒以 `<` 开头且不含空白字符(构造器保证)——
1326
+ * push 边界死族释放规则与 wait-gt 空白容忍的字节安全性前提。
1327
+ * - 死族透明:drop 族 body 超 DROP_BODY_SOFT_LIMIT 降级后,该族本流全部标签
1328
+ * 透明释放(防吞没失控),其余族不受影响(跨族隔离)。
1329
+ * - 死族 push 边界:push 结束于全死游走路径时立即释放 held——单 push 返回值与
1330
+ * 降级透传语义逐字节一致(cards 收编等价性守护点)。
1331
+ * - leading-zone 门控(仅 content 轨 + 仅 gated 族):zone 于流首/tool-result/
1332
+ * tool-error 边界开启,首个非空白可见字符释放时关闭;区内剥离、区外 fail-open
1333
+ * 释放 + hits(released)(开口与孤立闭合对称——防业务字面量「有头无尾」残缺)。
1334
+ */
1335
+ type TagBodyPolicy = 'drop' | 'decision';
1336
+ type TagTrack = 'content' | 'reasoning';
1337
+ type TagSeal = 'gt' | 'self';
1338
+ type TagSource = 'builtin' | 'extra';
1339
+ interface TagSpec {
1340
+ /** 族 id('cards' | 'think' | 'tool-call-text' | extra 名);降级/关停按族整体生效 */
1341
+ readonly family: string;
1342
+ /** 开口字面量(gt-seal 形态不含 '>';恒以 '<' 开头、不含空白) */
1343
+ readonly open: string;
1344
+ /** 闭合字面量(decision 族含 '>' 字节精确;gt-seal 族不含 '>') */
1345
+ readonly close: string;
1346
+ /** 唯一行为位:decision=证据保全(出卡);drop=痕迹清除(think/tool-call 卫生) */
1347
+ readonly body: TagBodyPolicy;
1348
+ /** gt=空白容忍等 '>';缺省 self(字面量即全形) */
1349
+ readonly openSeal?: TagSeal;
1350
+ readonly closeSeal?: TagSeal;
1351
+ /** 1:1 码点归一(仅比对;恒不映射 '<');同实例内 specs 必须共享同一实现 */
1352
+ readonly normalize?: (ch: string) => string;
1353
+ /** 唯一例外:think 族在 reasoning 轨 body 透传(保思考气泡,只剥标签) */
1354
+ readonly reasoningBody?: 'passthrough';
1355
+ /** 激活区门控(仅 content 轨生效):leading-zone = 流首 ∪ 工具边界后的思考相位 */
1356
+ readonly gate?: 'leading-zone';
1357
+ /** 取证来源标记(config extraTags 注入 = 'extra') */
1358
+ readonly source?: TagSource;
1359
+ }
1360
+ interface TagHit {
1361
+ family: string;
1362
+ /** stripped=已剥离;released=区外 fail-open 可见释放(G2 代价专属观测) */
1363
+ action: 'stripped' | 'released';
1364
+ /** 原始变体原文(≤64 字符)——变体名单扩展的唯一输入源 */
1365
+ form: string;
1366
+ /** body 字符数 */
1367
+ chars: number;
1368
+ track: TagTrack;
1369
+ source: TagSource;
1370
+ /** 流末未闭合 */
1371
+ unclosed?: boolean;
1372
+ /** body 上限触发降级 */
1373
+ degraded?: boolean;
1374
+ }
1375
+ interface TagEngineFinish {
1376
+ /** 流末未闭合残余的可见释放(decision 族现行语义;drop 族恒空串) */
1377
+ tail: string;
1378
+ /** decision 族闭合标签体(按出现序;chat-engine 侧按 family 过滤消费) */
1379
+ closedBodies: Array<{
1380
+ family: string;
1381
+ body: string;
1382
+ }>;
1383
+ /** 双轨取证(stripped/released × unclosed/degraded) */
1384
+ hits: TagHit[];
1385
+ }
1386
+ interface StreamTagEngine {
1387
+ /** 本段可见输出(可能为空串);终态后恒返空串 */
1388
+ push(delta: string): string;
1389
+ finish(): TagEngineFinish;
1390
+ /** 重开激活区(content 轨 tool-result/tool-error 边界接线;其余 no-op) */
1391
+ resetZone(): void;
1392
+ }
1393
+ /** decision 族 hold-back 上限(现行 CARD_DECISION_HOLD_LIMIT 值迁移;card-decision re-export 保 API) */
1394
+ declare const DECISION_HOLD_LIMIT = 4096;
1395
+ /** drop 族 body 吞没封顶(S1):超限降级——已吞保持、死族移除、后续正文恢复可见 */
1396
+ declare const DROP_BODY_SOFT_LIMIT = 32768;
1397
+ /** XML 标签族(drop + 双侧 gt-seal):`<name ...>` / `</name ...>` 空白容忍 */
1398
+ declare function xmlTag(family: string, name: string): TagSpec;
1399
+ /** 出卡决策标签族(decision + 开口 gt-seal + 闭合字节精确含 '>'——现行协议语义固化) */
1400
+ declare function xmlTagDecision(family: string, name: string): TagSpec;
1401
+ /** 词表信封族(drop + 双侧 self-seal + 可选 1:1 归一化):全/半角同形双容走 normalize */
1402
+ declare function envelopeTag(family: string, open: string, close: string, normalize?: (ch: string) => string): TagSpec;
1403
+ /** 卫生族同形归一:全角竖线/下标点 → 半角(1:1 码点,仅比对) */
1404
+ declare const HYGIENE_TAG_NORMALIZE: (ch: string) => string;
1405
+ /** 卫生族 XML 成员工厂:think 族继承 reasoningBody 透传 + leading-zone 门控 */
1406
+ declare function hygieneXmlTag(family: 'think' | 'tool-call-text', name: string): TagSpec;
1407
+ /** 内建卫生族成员名(resolveTagSpecs 组装 activeNames 单源;off 按族整体关停) */
1408
+ declare const BUILTIN_HYGIENE_NAMES: Readonly<Record<'think' | 'tool-call-text', readonly string[]>>;
1409
+ /** think 族:思考相位泄露防护(残缺 special token → content 泄露) */
1410
+ declare const THINK_SPECS: readonly TagSpec[];
1411
+ /**
1412
+ * tool-call 文本族:模型以文本形式输出工具调用信封(Qwen XML 形 + DeepSeek 词表形)。
1413
+ * 信封字面量以 TBOX_LOCAL_LOG=on 生产 .http 存档为核对真源(内嵌全角定界为观测主形)。
1414
+ */
1415
+ declare const TOOL_CALL_TEXT_SPECS: readonly TagSpec[];
1416
+ declare function createStreamTagEngine(specs: readonly TagSpec[], opts?: {
1417
+ track?: TagTrack;
1418
+ }): StreamTagEngine;
1419
+
1420
+ /**
1421
+ * 工具出卡协议单源(v2)。
1422
+ *
1423
+ * 作者契约:工具 execute 返回 `{ ...顶层答话事实, cards: [{cardType, data, note?}] }`——
1424
+ * `cards` 字段名为平台保留字(非出卡工具禁用此字段名承载其他语义)。
1425
+ *
1426
+ * capture 后模型可见面(模型上下文 / TOOL_CALL_RESULT 事件 / preTool reminder /
1427
+ * inputs.preTools 落库)四面统一为 stripped 形态:
1428
+ * `{ ...顶层, cards: [{id:"cN", cardType, note}] }`
1429
+ * 同一工具同一产出,模型 tool-result 与 preTool reminder 两路所见 payload 同构——
1430
+ * 由单点包装(wrapToolsForCardCapture)构造保证:两路执行同一 wrapped execute。
1431
+ *
1432
+ * 两层 id:
1433
+ * - ref(c1..cN):线程内单调的 occurrence 引用(descriptor.id 即 ref,按设计出现在上述四个
1434
+ * 模型可见面);不进出卡 payload(CUSTOM tbox:card)与历史快照;
1435
+ * - 实例 id(card_<ts>_<rand>):emit 时生成(CardEmitter 现状),出卡实例身份与历史快照主键。
1436
+ */
1437
+
1438
+ /** 出参 cards 字段名(平台保留字) */
1439
+ declare const TOOL_CARDS_FIELD = "cards";
1440
+ /** 出卡工具 description 标注关键词(平台段预告句共享——跨文件钉死断言防漂移) */
1441
+ declare const CARD_EMISSION_HINT_KEYWORD = "\u53EF\u5C55\u793A\u5361\u7247";
1442
+ /** 出卡工具 description 标注句基础形(withCardEmissionHint 单源) */
1443
+ declare const CARD_EMISSION_HINT_BASE = "\u547D\u4E2D\u6570\u636E\u65F6\u7ED3\u679C\u9644\u53EF\u5C55\u793A\u5361\u7247\uFF08cards\uFF09\u3002";
1444
+ /** 出卡工具 description 标注句动作卡后缀(卡上承载操作入口时追加) */
1445
+ declare const CARD_EMISSION_HINT_ACTIONS = "\u64CD\u4F5C\u5165\u53E3\u5728\u5361\u7247\u4E0A\u3002";
1446
+ /** descriptor 形状恒定(capture 后模型可见形态;供 outputSchema 组合,可选导出) */
1447
+ declare const TOOL_CARD_DESCRIPTOR_SCHEMA: z.ZodObject<{
1448
+ id: z.ZodString;
1449
+ cardType: z.ZodString;
1450
+ note: z.ZodString;
1451
+ }, "strip", z.ZodTypeAny, {
1452
+ id: string;
1453
+ cardType: string;
1454
+ note: string;
1455
+ }, {
1456
+ id: string;
1457
+ cardType: string;
1458
+ note: string;
1459
+ }>;
1460
+ /** 作者侧:工具 execute 出参中的卡条目 */
1461
+ interface ToolCardSpec {
1462
+ cardType: string;
1463
+ data: Record<string, unknown>;
1464
+ note?: string;
1465
+ }
1466
+ /** 模型侧:stripped 出参中的卡描述符 */
1467
+ interface ToolCardDescriptor {
1468
+ id: string;
1469
+ cardType: string;
1470
+ note: string;
1471
+ }
1472
+ /** 池条目(不可变:每个合法 cards occurrence 都是独立候选) */
1473
+ interface PoolEntry {
1474
+ ref: string;
1475
+ cardType: string;
1476
+ data: Record<string, unknown>;
1477
+ note: string;
1478
+ }
1479
+ interface CardPoolOptions {
1480
+ /** ChatEngine 使用线程级单调 ref;缺省时池内从 c1 开始。 */
1481
+ allocateRef?: () => string;
1482
+ }
1483
+ interface CardPool {
1484
+ /** 校验 + 注入;每个合法 occurrence 都创建独立 ref,校验失败 → null */
1485
+ add(spec: ToolCardSpec, registry: Record<string, CardMeta>): ToolCardDescriptor | null;
1486
+ /** ref 精确查找(大小写不敏感) */
1487
+ byRef(ref: string): PoolEntry | undefined;
1488
+ entries(): readonly PoolEntry[];
1489
+ size(): number;
1490
+ }
1491
+ /** 候选池工厂(每 run 一个;每个 occurrence 独立 ref) */
1492
+ declare function createCardPool(options?: CardPoolOptions): CardPool;
1493
+ /**
1494
+ * capture:校验 + 池注入 + 剥离(单函数三合一)。
1495
+ * - raw 非对象或无 cards 字段 → 原样返回(no-op,不出卡工具零开销);
1496
+ * - cards 非数组 → warn + 原样返回;
1497
+ * - 逐条校验(非对象 / cardType 非 string / 未注册 / dataSchema 失败 → skip + warn);
1498
+ * - 有效 ≥1 → `{ ...raw, cards: descriptors }`;全无效 → 浅拷贝删除 cards 键;
1499
+ * - 条目数 > CARDS_WARN_LIMIT → warn(不截断)。
1500
+ */
1501
+ declare function captureToolCards(raw: unknown, pool: CardPool, registry: Record<string, CardMeta>): unknown;
1502
+ /** run 级卡片池 ALS 上下文(chat/submitForm run 开始进入,finally 退出) */
1503
+ declare const toolCardScope: AsyncLocalStorage<{
1504
+ pool: CardPool;
1505
+ }>;
1506
+ /**
1507
+ * 单点包装:浅拷贝每个 tool 仅替换 execute(禁变异原实例);无 execute 的原样保留。
1508
+ * wrapped execute:双参 + 接收者透传(mastra 契约),产出经 captureToolCards
1509
+ * (ALS 无池 → 引擎外直调原样返回)。模型路径(Agent.tools)与 preTool 路径
1510
+ * (engine 按 id 替换执行体)共用同一 wrapped execute → 两路同构由构造保证。
1511
+ */
1512
+ declare function wrapToolsForCardCapture(tools: Record<string, Tool>, registry: Record<string, CardMeta>): Record<string, Tool>;
1513
+
1514
+ /**
1515
+ * 出卡决策协议(候选池 → 模型标签决策 → 多卡下发)。
1516
+ *
1517
+ * 工具/preTool 出参经 capture(tool-cards.ts)注入候选池并剥离为 descriptor;
1518
+ * 模型在回复正文末尾输出 `<agent-ui-cards>c1 c2</agent-ui-cards>`(ref 引用,空格序=展示序),
1519
+ * 引擎流式剥离标签(用户不可见)并按 decision 顺序解析出卡。协议仅存在于
1520
+ * server 侧(contracts 不含标签语法——客户端永远见不到标签)。
1521
+ * 出卡唯一触发 = 字节级精确标签(大小写宽容、开口空白容忍;闭合含 '>' 字节精确——
1522
+ * CARDS_SPEC 经 stream-tag-engine 的 xmlTagDecision 固化,闭合空白容忍是 think 族专属
1523
+ * 宽容,不泛化到此);漂移/信封形态一律普通文本(fail-visible)——观测见 model-dialect.ts
1524
+ * (detect-only;history 卫生已随缓存最大化裁定废除,2026-09-02:标签随 messageList
1525
+ * 真值原样回填,stale id 归 invalid-fallback 兜底)。
1526
+ */
1527
+
1528
+ /** 决策标签名(<agent-ui-cards>...</agent-ui-cards>) */
1529
+ declare const CARD_DECISION_TAG = "agent-ui-cards";
1530
+ /** 单轮出卡上限缺省值(提示词与引擎构造性同源的单一数值源) */
1531
+ declare const DEFAULT_MAX_CARDS_PER_TURN = 3;
1532
+ /**
1533
+ * stripper hold-back 缓冲上限:开口标签命中后若迟迟不闭合(模型退化性重复),
1534
+ * 释放已 hold 内容为可见文本并降级(本流不再识别标签),防缓冲膨胀与可见流停滞。
1535
+ * 值真源已迁 stream-tag-engine.DECISION_HOLD_LIMIT(cards 收编统一引擎),此处 re-export
1536
+ * 保 public API 面。
1537
+ * 精确边界(实测标定):held = 开口 + body + 闭合前缀逐字符累积,降级判于未命中字符
1538
+ * 且命中优先——body ≤ 4063 恒正常闭合;body = 4064 于闭合命中点恰达上限仍闭合;
1539
+ * body ≥ 4065 于 close 前缀中途降级。
1540
+ */
1541
+ declare const CARD_DECISION_HOLD_LIMIT = 4096;
1542
+ /** 出卡协议 spec(协议族唯一真源;chat-engine 统一引擎与适配器共用) */
1543
+ declare const CARDS_SPEC: TagSpec;
1544
+ /**
1545
+ * 流式标签剥离器(stream-tag-engine 适配器——cards 收编统一引擎后的薄壳;
1546
+ * 签名与行为与收编前状态机逐字节等价,双闸 card-decision.test.ts +
1547
+ * chat-engine-post-reply.test.ts 不改一字通过)。
1548
+ * push 返回本段可见文本(可能为空串);finish 是唯一解析点,
1549
+ * tail=流结束时未闭合的残余可见文本,decision=全部标签 token 按出现序【不去重】。
1550
+ * token 去重和上限截断由 decideCards 负责。
1551
+ */
1552
+ interface CardDecisionStripper {
1553
+ push(delta: string): string;
1554
+ finish(): {
1555
+ tail: string;
1556
+ decision: string[];
1557
+ };
1558
+ }
1559
+ /** 标签体 token 化:空白/中英文逗号/顿号分隔,trim 后丢弃空项,重复保留 */
1560
+ declare function tokenizeTagBody(body: string): string[];
1561
+ declare function createCardDecisionStripper(): CardDecisionStripper;
1562
+ interface CardDecisionPlan {
1563
+ entries: PoolEntry[];
1564
+ unmatched: string[];
1565
+ rejectedCardType: number;
1566
+ droppedByCap: number;
1567
+ fallback?: 'budget-fallback' | 'pool-fallback' | 'invalid-fallback';
1568
+ }
1569
+ /**
1570
+ * 纯决策计划:三规则矩阵(2026-09-01 多轮出卡稳定性)——
1571
+ * 1) 任一有效引用 → 出卡(none token 记 unmatched 噪音);
1572
+ * 2) 归一后恰为 ['none'] → 显式弃权(唯一无歧义免出通道;显式意图压过预算触界);
1573
+ * 3) 其余一切(零 token / 全 stale id / cardType 名 / none 混杂无效 token / 字面回声)
1574
+ * → 兜底出池末张。fallback 分型:budget=预算触界且零 token / pool=零 token 遗漏 /
1575
+ * invalid=有 token 但全无效(stale id、cardType 名、回声、none 混杂)。
1576
+ * 解析严格限当前池 ref(跨轮引用禁令);显式引用按模型标签序全保留 + ≤maxCardsPerTurn 截断
1577
+ * (同型更新语义由提示词条件引导,机制不做同型收敛——2026-09-02 多意图互补卡并列放宽)。
1578
+ * 失败模式全倒向安全侧:忘标签/垃圾 id/忘 none → 兜底;唯一定向出口是纯 none。
1579
+ * IO、发送和快照由 chat-engine flush 负责。
1580
+ */
1581
+ declare function decideCards(args: {
1582
+ decision: readonly string[];
1583
+ pool: CardPool;
1584
+ maxCardsPerTurn: number;
1585
+ budgetExceeded: boolean;
1586
+ }): CardDecisionPlan;
1587
+ /**
1588
+ * 兜底取卡:池末条(最新产出——与提示词「后出现 = 更新」排序语义一致)。
1589
+ * 空池 → undefined。
1590
+ */
1591
+ declare function pickFallbackCard(pool: CardPool): PoolEntry | undefined;
1592
+
1593
+ /**
1594
+ * 流式标签卫生 config 缺省路径(真源自 model-providers.ts 迁入单源——chat-engine 卫生
1595
+ * 引擎与 provider 装配同链同文件)。用 process.cwd() 相对路径,避免 import.meta.url
1596
+ * 在 tsup 打包后指向 dist/ 导致路径层级变化;dev/prod 的 cwd 均为 apps/server/。
1597
+ */
1598
+ declare const DEFAULT_LLM_PROVIDER_CONFIG_PATH: string;
1599
+ /** 卫生族 id(cards 为协议族,恒不参与 config 面——归装配轴 cardTagStripping) */
1600
+ type HygieneTagFamily = 'think' | 'tool-call-text';
1601
+ /**
1602
+ * 流式标签卫生配置(卫生轴,与出卡装配轴正交)。
1603
+ * off = 族级关停(回滚杠杆,热路径);extraTags = 字面量扩展(热路径止血——
1604
+ * 新变体名并入对应卫生族,禁任意正则防注入/误伤)。
1605
+ */
1606
+ interface ContentTagHygiene {
1607
+ off?: string[];
1608
+ extraTags?: Array<{
1609
+ name: string;
1610
+ family: HygieneTagFamily;
1611
+ }>;
1612
+ }
1613
+ interface ResolvedTagSpecs {
1614
+ /** 活跃卫生族 specs(cards 协议族恒不参与——归装配轴) */
1615
+ specs: TagSpec[];
1616
+ /** 活跃 XML 标签名(小写)——dialect residue 扫描排除面(N3 防自碰撞) */
1617
+ activeNames: string[];
1618
+ }
1619
+ type ThinkingControl = boolean | 'auto' | Record<string, unknown>;
1620
+ /** 并行工具调用控制(三态同构 thinking):true/false 注入请求体;'auto' = 不注入(走网关按模型默认) */
1621
+ type ParallelToolCallsControl = boolean | 'auto';
1622
+ /**
1623
+ * 流式标签卫生 specs 解析(每请求热读,WS 长连接热切——对齐 thinking/parallel 刻度)。
1624
+ * 组合 = 内建卫生族 − off ∪ extraTags;cards 协议族恒不参与(归装配轴 cardTagStripping)。
1625
+ * activeNames 供 dialect residue 扫描排除(N3 防自碰撞:已剥/已放行形态均有 hits 信号)。
1626
+ */
1627
+ declare function resolveTagSpecs(configPath: string): ResolvedTagSpecs;
1628
+
1629
+ /**
1630
+ * 平台段系统提示词(单源模板,确定性纯函数——同输入恒同输出字节,全业务通用)。
1631
+ *
1632
+ * 系统提示词 = 业务段(置前:agent.jsonc instructions [+ memoryInstructions(memory 装配态)]
1633
+ * 或 SDK 默认 DEFAULT_INSTRUCTIONS)+ 本平台规则段(后置,SDK 生成:通用行为(含安全拒答)[+ 预算行]
1634
+ * + 卡片协议规则 + few-shot 示例 + 注入块协议 [+ 记忆协议段(017,装配 memory 时)] + 冲突裁决)
1635
+ * (createEngineFromContext 拼接;两段以「# 平台规则」标题分界)。
1636
+ *
1637
+ * v2:不内嵌真实卡片目录——候选卡由工具出参 `cards` 字段运行期注入(id 引用),
1638
+ * 平台段对任意装配字节级恒定(参数 maxCards/maxSteps/memory 构造期定形),跨应用提示词/前缀缓存稳定。
1639
+ * 标签字面量经 CARD_DECISION_TAG 内插(单源)。
1640
+ * 跨轮语义(三条事实句,零行为指令):数据时效(通用行为——重问/追问更多 =
1641
+ * 期望当前时点数据)+ 卡片可见性(卡片协议——历史卡不随本轮重现,本轮出卡需本轮新 id)
1642
+ * + 展示决策按轮独立(只看本轮候选与当前意图,历史轮展示过相同内容不影响判断——
1643
+ * 机制事实:决策解析只看当前池,跨轮零记忆);共同消除「直答合法 + 出卡需本轮执行」
1644
+ * 组合下的重问不出卡盲区(含「已展示过→省略展示」反向误推),路径无关
1645
+ * (模型自主调用与 preTool 重跑两路径自动正确,答话可用面不受限——回忆类直答合法)。
1646
+ * 017:记忆段为条件拼接——未装配 memory 的应用平台段字节与 016 完全相等(前缀缓存不变);
1647
+ * 装配态内段字节恒定(caps 三元组构造期定形)。
1648
+ * 预算行:maxSteps 参数化(resolveMaxSteps 单源双喂,构造期定形——随每请求含 loop 每步下发);
1649
+ * 注入块协议:无条件拼接(「可能出现」措辞兜底无块轮,与记忆段条件拼接动机不同)。
1650
+ * 安全拒答(通用行为首条,2026-09-07):主语用审核类目词 +「有害内容」上位兜底,禁「底线安全」
1651
+ * 类行话(模型对齐语料无锚定,近邻误读向 InfoSec 安全基线);三不变式 = 不回答/不调用工具/
1652
+ * 不提供变通做法;居首 = 安全先于一切行为准则;类目为稳定集合,增删只动枚举(测试锚不变式不锚清单)。
1653
+ *
1654
+ * 自定义平台段的唯一定制点 = 绕过 createEngineFromContext 手工装配
1655
+ * (createSdkToolRuntime + createChatEngine 自备全量 instructions);
1656
+ * 不提供注入/覆写选项(保持协议规则的平台一致性)。
1657
+ */
1658
+
1659
+ /** 记忆段构造输入(装配态 capabilities 三元组——save/search/delete 工具可用性) */
1660
+ type MemoryPromptCaps = Pick<MemoryStoreCapabilities, 'save' | 'search' | 'delete'>;
1661
+ declare function buildPlatformInstructions(opts: {
1662
+ maxCards: number;
1663
+ /** 步数预算(resolveMaxSteps 单源产物;> 0 拼预算行,0 = 显式禁用不拼) */
1664
+ maxSteps?: number;
1665
+ /** 记忆装配态(017):缺省不拼接(未装配应用字节零变化) */
1666
+ memory?: MemoryPromptCaps;
1667
+ }): string;
1668
+ /**
1669
+ * 出卡决策轮级提醒块(W3,2026-09-01;v2.1 2026-09-02 因果链补强;v2.2 2026-09-03 空池事实句):
1670
+ * 每轮注入 user 消息最前部的 card-decision reminder。四分支骨架(结构即扩展面):
1671
+ * 来源事实 → 取得动作(条件门)→ 空池事实句 → 非空决策协议。
1672
+ * - 构造期 singleton:同 maxCards 输入字节恒定(跨轮/跨会话前缀缓存稳定);
1673
+ * - 取得动作句修复「数据类问题凭历史直答 → 池空 → 无卡」调用触发缺口(base 模板唯一轮级防线);
1674
+ * 单一条件对(意图「要展示卡片」∧ 状态「本轮还没有结果」)防过度调用;「(含注入块)」钉死
1675
+ * preTool 边界(与注入块协议「等价」句对齐);「仅凭历史内容作答,本轮不会有卡片」为机械真事实句
1676
+ * (池只从本轮 capture 填充),承接失效语义;
1677
+ * - 空池事实句(2026-09-03):堵协议盲区——原三句只管标签不管话术,池空轮模型仍可正文声称
1678
+ * 「已出卡/卡片里有」;句式为纯事实+禁声称协议边界(非行为指令——不命令调工具,R11 合规;
1679
+ * 回忆类直答不受限:只禁声称卡片存在);
1680
+ * - 无 preamble(纯系统文本——与 memory 块前导「(系统提醒,非用户输入)」的非对称是有意的:
1681
+ * memory 内容受用户影响需防御性声明,本块纯协议重申无需);
1682
+ * - 禁业务路由词(停车/券/楼层/积分等零出现——防污染 preTool decide 的 history 投影扫描);
1683
+ * - 不提兜底(防道德风险——模型知道有兜底会降低标签遵从);tie-break 句教自身判断缺省;
1684
+ * - 形态边界(防退化负向锚):不得退化为无条件/命令式调用指令——回忆类直答合法。
1685
+ */
1686
+ declare function buildCardDecisionReminder(maxCards: number): string;
1687
+
1688
+ /**
1689
+ * 插件工具引用(结构与 @tbox.cn/agent-plugin 的 LoadedPluginToolReference 一致,
1690
+ * 避免依赖未公开的 ./references 子路径)。
1691
+ */
1692
+ interface PluginToolReference {
1693
+ kind: 'plugin';
1694
+ pluginId: string;
1695
+ toolId: string;
1696
+ runtimeId: string;
1697
+ }
1698
+ interface SdkToolRuntime {
1699
+ /** LLM 装配工具(harden 后:sanitize preprocess + strict 缺省 false) */
1700
+ tools: Record<string, AnyTool>;
1701
+ /** 加固前合并工具集(注册表原始实例)——normalizePreTools D9 实例一致性校验对象(比对原件,
1702
+ * 禁对 harden 副本校验:副本≠声明原件会全员误报双实例分裂,preTool 静默失效) */
1703
+ rawTools: Record<string, AnyTool>;
1704
+ }
1705
+ /**
1706
+ * LLM 工具入参加固(装配单点,静态+插件全量覆盖):
1707
+ * 1. zod inputSchema → sanitize preprocess 包装(null/"null"/"undefined" 校验前清洗);
1708
+ * 2. strict 缺省 false —— Mastra ≥1.58 显式退出 strict schema 方言改写(OpenAI 层把
1709
+ * optional 改写为全量 required + 显式 null 的根因层);1.57 上惰性存留(wire 携带
1710
+ * 缺省等价 false,无害)。已显式声明 strict 的工具不覆盖。
1711
+ * 浅克隆仅替换两字段(v2 wrapToolsForCardCapture 同款惯用法,禁变异原实例)。
1712
+ */
1713
+ declare function hardenToolsForLlm(tools: Record<string, AnyTool>): Record<string, AnyTool>;
1714
+ interface SdkRuntimeOptions {
1715
+ /**
1716
+ * 插件工具加载(app 注入 pluginIntegration,保留 @tbox.cn/agent-plugin 接入层)。
1717
+ * 返回加载后的工具与插件 runtime id 引用。
1718
+ */
1719
+ loadPlugins?: () => Promise<{
1720
+ tools: Record<string, AnyTool>;
1721
+ references: PluginToolReference[];
1722
+ }>;
1723
+ }
1724
+ /**
1725
+ * 从 ServerContext 装配工具运行时(静态工具 + 插件工具)。
1726
+ * 供 ChatEngine 构建与 plugin-doctor/inspect 复用。
1727
+ * v2:出卡走工具出参 cards 字段(engine 内 capture),不再装配 tool→card resolver。
1728
+ */
1729
+ declare function createSdkToolRuntime(ctx: ServerContext, opts?: SdkRuntimeOptions): Promise<SdkToolRuntime>;
1730
+ interface BuildEngineOptions extends SdkRuntimeOptions {
1731
+ /**
1732
+ * 业务段系统提示词(agent.jsonc instructions 或 SDK 默认;首行身份句)。
1733
+ * 最终 instructions = 业务段 [+ memoryInstructions(memory 装配态)] + 平台规则段(SDK 后置生成)。
1734
+ */
1735
+ instructions: string;
1736
+ /**
1737
+ * 记忆域业务措辞(agent.jsonc memoryInstructions;仅 memory 装配态追加到业务段尾部,
1738
+ * 非装配态不拼接——死能力零广告,装配条件构造性归 SDK)。
1739
+ */
1740
+ memoryInstructions?: string;
1741
+ model: unknown;
1742
+ stepControl?: ChatEngineOptions['stepControl'];
1743
+ /** 模型名(日志用) */
1744
+ modelName?: string;
1745
+ /** 文件 URL 前缀(content-builder 用) */
1746
+ fileUrlPrefix?: string;
1747
+ /** trace exporter(默认 SDK 内置单例) */
1748
+ traceExporter?: TboxTraceExporter;
1749
+ /** 持久化回调(同 ChatEngineOptions.saveMessage) */
1750
+ saveMessage?: ChatEngineOptions['saveMessage'];
1751
+ /** 意图路由表(B21):chat() 先 matchIntent;handler 缺省直出,也可 continueWith 续接 Agent */
1752
+ intentRoutes?: IntentRoute[];
1753
+ /** 011 S5:runBudget 步数预算(透传 ChatEngine + 平台段预算行——resolveMaxSteps 单源双喂) */
1754
+ runBudget?: RunBudgetOptions;
1755
+ /** 011 B3:卡片动作 token 签发器(透传 ChatEngine) */
1756
+ cardActionAttacher?: ChatEngineOptions['cardActionAttacher'];
1757
+ /** 单轮出卡上限(透传 ChatEngine;与平台段 maxCards 构造性同源——同一 clamp 值双喂) */
1758
+ maxCardsPerTurn?: ChatEngineOptions['maxCardsPerTurn'];
1759
+ handlerDispatch?: (route: IntentRoute, content: string, reqCtx?: _tbox_cn_app_contracts.RequestContext) => Promise<HandlerResult | undefined>;
1760
+ /** 本地 skill 模式(009 D2):accelerated(默认)/ progressive,同 ChatEngineOptions.skillMode */
1761
+ skillMode?: SkillMode;
1762
+ /** 应用级本地 skills(模板 loadLocalSkills 产物;与模块声明合并,应用覆盖模块) */
1763
+ skills?: LocalSkill[];
1764
+ /** 应用级前置工具声明(010;与模块 ctx.preTools 合并,应用覆盖模块) */
1765
+ preTools?: PreToolDef[];
1766
+ /** 单工具总预算 ms(resolve+execute 共享;缺省 2000;0 = 禁用),同 ChatEngineOptions.preToolTimeoutMs */
1767
+ preToolTimeoutMs?: number;
1768
+ /**
1769
+ * 长期记忆(017):store + 召回配置(透传 ChatEngine;装配端经 resolveMemoryStore 解析 env)。
1770
+ * 未传 = 不装配(平台段零变化、零工具注册、零 recall)。
1771
+ */
1772
+ memory?: MemoryEngineOptions;
1773
+ /** 018 tool-debug:工具调试视图(透传 ChatEngine;装配端经 resolveToolDebug 解析 env) */
1774
+ toolDebug?: boolean;
1775
+ /** PR-2 尽早执行管线(透传 ChatEngine;装配端经 resolveEarlyToolExecution 解析 env;缺省 off) */
1776
+ earlyToolExecution?: boolean;
1777
+ }
1778
+ /**
1779
+ * 合并 skills(009 D8):模块声明(ctx.skills)先插、应用级(opts.skills)覆盖 + warn。
1780
+ * Map 按 name 去重 → 传给 ChatEngine 的数组无重名(accelerated 注入/去重以 name 为锚的前提)。
1781
+ */
1782
+ declare function mergeSkills(moduleSkills: LocalSkill[], appSkills: LocalSkill[]): LocalSkill[];
1783
+ /**
1784
+ * 合并 preTools(010):模块声明(ctx.preTools)先插、应用级(opts.preTools)覆盖 + warn。
1785
+ * Map 按 tool.id 去重 → 传给 ChatEngine 的数组无重名。
1786
+ */
1787
+ declare function mergePreTools(modulePreTools: PreToolDef[], appPreTools: PreToolDef[]): PreToolDef[];
1788
+ /**
1789
+ * 校验并归一 preTools(010):
1790
+ * - tool.id 必须命中合并后工具集(含插件工具),否则 warn 跳过;
1791
+ * - 实例一致性(D9):tools[id] !== def.tool → warn 跳过(防双实例分裂——005 v0.4.0 教训,
1792
+ * 发布态下 app-sdk 多副本时模块声明的工具引用与工具集实例不同源)。
1793
+ */
1794
+ declare function normalizePreTools(preTools: PreToolDef[], tools: Record<string, AnyTool>): PreToolDef[];
1795
+ /**
1796
+ * 从 ServerContext 构造 ChatEngine(自注册闭环组装端)。
1797
+ * 静态工具 = ctx.tools.getAll();卡片 registry = ctx.cards.getAll();
1798
+ * 插件工具由 app 注入 loadPlugins(apps/server/src/plugins/integration.ts 仍归 app)。
1799
+ * 工具出卡 capture 在 ChatEngine 构造期统一包装(tools/preTools 原始实例传入)。
1800
+ */
1801
+ declare function createEngineFromContext(ctx: ServerContext, opts: BuildEngineOptions): Promise<ChatEngine>;
1802
+
1803
+ /**
1804
+ * 消息 inputs 组装规则(010 下沉 S3):平台消息契约的「非空才加」字段规则属框架逻辑,
1805
+ * 模板不应手写。全空 → undefined(调用方省略 inputs 键);未来新增 inputs 字段只改此处。
1806
+ */
1807
+ declare function buildMessageInputs(input: {
1808
+ cards?: CardSnapshot[];
1809
+ skills?: SkillRecord[];
1810
+ preTools?: PreToolRecord[];
1811
+ }): Record<string, unknown> | undefined;
1812
+
1813
+ /**
1814
+ * WebSocket 网关(006 D6/D12 + 会话 β):管理连接、心跳、消息路由、鉴权与身份绑定。
1815
+ * - HELLO(携带 token)→ ws-auth 校验 → 连接级身份绑定(含可选外部凭据);零会话职责;
1816
+ * - 会话 β:conversationId 从客户端协议面退役——NEW_CONVERSATION(bootstrap 新开)/
1817
+ * RESUME_CONVERSATION(重连续接)由服务端建立会话并绑定为「连接当前会话」;
1818
+ * RUN/CANCEL_RUN/UI_ACTION 恒取连接当前会话(客户端携带的 conversationId 一律忽略——
1819
+ * 不提供即不可伪造,水平越权面协议级消灭);裸 RUN 无会话 → RUN_ERROR 严格拒绝;
1820
+ * - 顺序门控:业务事件(SEND_MESSAGE/UI_ACTION/CANCEL_RUN/NEW/RESUME)必须发生在身份绑定之后;
1821
+ * - 条件解绑:close 时仅释放本连接注册过的 emitter 键,防止误删其它连接的旁路通道;
1822
+ * - 多连接:同键后注册者接管 emitter(Map 覆盖,单活动连接语义);
1823
+ * 广播集合化(多连接推送)为演进预留(见 006 §9)。
1824
+ * - 匿名(optional 模式):HELLO 无 token → 服务端生成匿名身份绑定;不可建会话、写操作拒绝。
1825
+ * - 011 F2/F4:配置 scopeSessions 时 HELLO 携带 context → bootstrap 会话 + HelloAck 回发
1826
+ * (mall 白名单校验 + 会话级绑定);不配置则行为与 006 完全一致。
1827
+ */
1828
+ /** 结构化最小形状(会话 β 注入;ConversationService 结构兼容——模板装配懒代理/测试注入 fake) */
1829
+ interface WsConversationService {
1830
+ createConversation(agentId: string, userId: string): Promise<string>;
1831
+ getOrCreateConversation(agentId: string, userId: string): Promise<string>;
1832
+ }
1833
+ interface WsServerOptions {
1834
+ /** WS 鉴权器(由 createAuthRuntime 提供);不传则降级为匿名直连(仅限测试/自托管非生产) */
1835
+ auth?: WsAuthenticator;
1836
+ /**
1837
+ * 会话 β:会话建立服务(可选;装配端注入 ConversationService 结构化代理)。
1838
+ * 缺席/失败 → NEW/RESUME 走 notice 通道报错,RUN 恒严格拒绝(fail-closed——
1839
+ * 不静默降级为无会话直跑,「无会话即拒」协议不变量恒成立)。
1840
+ */
1841
+ conversationService?: WsConversationService;
1842
+ /** 会话建立用 agentId(缺省读 TBOX_APP_ID env;显式注入便于测试与多应用容器) */
1843
+ conversationAgentId?: string;
1844
+ /** 011 F2:scope 会话注册表(可选;装配时注入 createScopeSessionRegistry) */
1845
+ scopeSessions?: ScopeSessionRegistry;
1846
+ /** 011 F4:HelloAck chatConfig(可选;快捷指令 + settings 由装配端提供,形状真源 = contracts HelloAckChatConfig) */
1847
+ chatConfig?: HelloAckChatConfig;
1848
+ /** 011 E1:模块动作分发器(可选;装配端注入 createModuleActionDispatcher) */
1849
+ moduleActions?: ModuleActionBridge;
1850
+ /**
1851
+ * 默认 HELLO context(可选;装配端注入,如部署默认商圈)。
1852
+ * 仅 HELLO 完全未携带 context 时采用——显式(含部分)context 不覆盖,保形状错误可见性。
1853
+ */
1854
+ defaultContext?: Record<string, unknown>;
1855
+ /**
1856
+ * HELLO context 增强器(域中立注入点;上下文统一化扩展):
1857
+ * envelope 归一(含 defaultContext 兜底)之后、身份绑定/bootstrap 之前调用。
1858
+ * 返回值参与全链(attributes/scope/HelloAck 回显);async 支持(如按 mallId 拉取拓扑信息)。
1859
+ * fail-soft 契约:抛错/返回非对象 → 警告并使用原 context 继续(增强是增益不是闸门)。
1860
+ * 时序注意:增强期间的 await 会推迟串行队列中后续业务消息(顺序门控强序),
1861
+ * 实现方应自设有界等待。
1862
+ */
1863
+ enhanceContext?: (context: Record<string, unknown>) => Record<string, unknown> | Promise<Record<string, unknown>>;
1864
+ /**
1865
+ * 业务层 keepalive(可选;默认启用 30s 探测 / 90s 回收,timeout=3×interval 派生)。
1866
+ * 仅作用于业务层探测与 capable 连接回收;协议心跳(TCP 存活基线)不受此项影响。
1867
+ * 须在 createWsServer 时注入(连接建立后不重排);intervalMs 下限 100ms。
1868
+ */
1869
+ keepalive?: {
1870
+ enabled?: boolean;
1871
+ intervalMs?: number;
1872
+ };
1873
+ /**
1874
+ * 018 tool-debug:工具调试视图旗标(TBOX_TOOL_DEBUG env 单源,装配端经 resolveToolDebug
1875
+ * 解析后传入;与 engine.toolDebug 同值同源)。开启时 HELLO_ACK 携带 toolDebug: true
1876
+ * 解锁客户端 dev 工具视图(非 scope 部署亦发送 ack——base dev 视图通道)。
1877
+ * 关闭态:scope 部署行为与现状逐字节一致,非 scope 部署不发 ack。
1878
+ */
1879
+ toolDebug?: boolean;
1880
+ }
1881
+ /** 模块动作桥(011 E1:ws-server 与 dispatcher 的薄接口,避免 ws 直接依赖完整 dispatcher 类型) */
1882
+ interface ModuleActionBridge {
1883
+ dispatch(input: {
1884
+ token: string;
1885
+ actionId: string;
1886
+ sessionId: string;
1887
+ /** 动作来源卡实例 id(P0 原地更新目标;host-effect 回传缺省 '') */
1888
+ surfaceId?: string;
1889
+ ctx: _tbox_cn_app_contracts.RequestContext;
1890
+ formData?: unknown;
1891
+ emit: (event: ServerEvent) => void;
1892
+ }): Promise<unknown>;
1893
+ }
1894
+ declare function createWsServer(engine: ChatEngine, opts?: WsServerOptions): ws.Server<typeof WebSocket, typeof http.IncomingMessage>;
1895
+
1896
+ /**
1897
+ * 「LLM-driven 出卡型 tool」工厂(v2:出参 cards 契约)。
1898
+ *
1899
+ * 适用场景:tool 的 input 字段 = 卡片要渲染的字段(即数据完全由 LLM 从对话上下文
1900
+ * 提取,tool 不需要查询外部数据源)。
1901
+ *
1902
+ * 工厂强制约束:
1903
+ * 1. 出参 = { summary: input, cards: [{ cardType, data: input, note }] }
1904
+ * (工具出卡契约样板:顶层答话事实 + cards 数组;capture 后模型可见
1905
+ * cards 为 descriptor 形态,data 已剥离)
1906
+ * 2. execute 透传 input(agent 无法写错数据)
1907
+ */
1908
+ declare function coerceStringifiedFields(input: unknown): unknown;
1909
+ interface CreateCardToolOptions<TSchema extends ZodTypeAny> {
1910
+ id: string;
1911
+ description: string;
1912
+ inputSchema: TSchema;
1913
+ /** 目标卡片类型(CARD_REGISTRY key) */
1914
+ cardType: string;
1915
+ /** 卡片说明(模型可见 descriptor.note;缺省回退 meta.displayName) */
1916
+ note?: string;
1917
+ }
1918
+ declare function createCardTool<TSchema extends ZodTypeAny>(opts: CreateCardToolOptions<TSchema>): _mastra_core_tools.Tool<TSchema extends _mastra_core_schema.PublicSchema<any> ? _mastra_core_schema.InferPublicSchema<TSchema> : unknown, unknown, unknown, unknown, _mastra_core_tools.ToolExecutionContext<unknown, unknown, unknown>, string, unknown>;
1919
+
1920
+ /**
1921
+ * 表单提交虚拟 tool 的 id。
1922
+ * 单一来源,跨 chat-engine / registry / 客户端过滤逻辑共用。
1923
+ */
1924
+ declare const FORM_SUBMIT_TOOL_ID = "__a2uiFormSubmit";
1925
+ /**
1926
+ * 内部工具:卡片表单提交虚拟桥。
1927
+ *
1928
+ * 用户在卡片里点提交时,服务端通过 ChatEngine.submitForm() 把表单数据作为此工具的
1929
+ * "虚拟 tool result" 注入会话历史。模型从未主动调用此工具,仅在上下文中读到结果
1930
+ * 并据此继续响应。
1931
+ */
1932
+ declare const formSubmitTool: _mastra_core_tools.Tool<{
1933
+ surfaceId: string;
1934
+ formId: string;
1935
+ }, Record<string, unknown>, unknown, unknown, _mastra_core_tools.ToolExecutionContext<unknown, unknown, unknown>, "__a2uiFormSubmit", unknown>;
1936
+
1937
+ /**
1938
+ * 卡片快照恢复(001 §7.4 / 004 W1):
1939
+ * migrate(schemaVersion ?? 0) → dataSchema.safeParse
1940
+ * 失败 → { status: 'error', error: '卡片数据已不兼容' }(不白屏)
1941
+ * 成功 → isHistory: true(历史恢复卡片禁交互)
1942
+ * 由 conversation route 对每条消息的 inputs.cards 调用(服务端恢复,schema 迁移一期即启用)。
1943
+ */
1944
+ declare function restoreCardSnapshot(snapshot: CardSnapshot, registry: {
1945
+ resolve(cardType: string): CardMeta | undefined;
1946
+ }): TboxCardPayload;
1947
+ /** TboxCardPayload → CardSnapshot(写快照用) */
1948
+ declare function toCardSnapshot(payload: TboxCardPayload): CardSnapshot;
1949
+
1950
+ /**
1951
+ * 卡片持久化后端抽象(004 W1 / D1)。
1952
+ *
1953
+ * 双实现:
1954
+ * - MessageEmbeddedBackend(默认):卡片随 saveMessage 的 `inputs.cards` 持久化,
1955
+ * 与 query/answer 同源提交(外层 chat-engine 将本轮 run 缓冲折叠进 saveMessage)。
1956
+ * 本实现 save 为 no-op(卡片已随消息落库),load 返回空(恢复走平台消息回传)。
1957
+ * - FileCardPersistenceBackend(兜底):独立落盘,V1(平台拒绝扩展字段)失败时切换。
1958
+ *
1959
+ * 切换收敛为装配端一行:apps/server/src/app.ts 的 saveMessage handler 选择走 inputs 还是落盘。
1960
+ *
1961
+ * 006 评审 P2-1:`sessionId` 参数名为历史键名,**语义为会话键 = conversationId(006 D5,
1962
+ * 运行+持久化统一)**。接口名保留(第三方实现兼容),调用方传 conversationId/线程键。
1963
+ */
1964
+ interface CardPersistenceBackend {
1965
+ save(args: {
1966
+ sessionId: string;
1967
+ runId: string;
1968
+ cards: CardSnapshot[];
1969
+ }): Promise<void>;
1970
+ load(sessionId: string): Promise<CardSnapshot[]>;
1971
+ }
1972
+ /** MessageEmbedded:卡片折叠进 saveMessage(004 D1 默认策略) */
1973
+ declare class MessageEmbeddedBackend implements CardPersistenceBackend {
1974
+ save(_args: {
1975
+ sessionId: string;
1976
+ runId: string;
1977
+ cards: CardSnapshot[];
1978
+ }): Promise<void>;
1979
+ load(_sessionId: string): Promise<CardSnapshot[]>;
1980
+ }
1981
+ /** FileSnapshot:独立落盘兜底(V1 失败时切换) */
1982
+ declare class FileCardPersistenceBackend implements CardPersistenceBackend {
1983
+ private dir;
1984
+ constructor(dir?: string);
1985
+ private fileFor;
1986
+ save(args: {
1987
+ sessionId: string;
1988
+ runId: string;
1989
+ cards: CardSnapshot[];
1990
+ }): Promise<void>;
1991
+ load(sessionId: string): Promise<CardSnapshot[]>;
1992
+ }
1993
+
1994
+ /** 快捷指令(chat.json quickCommands 元素;独立真源——不再自组件配置面承载) */
1995
+ interface QuickCommand {
1996
+ label: string;
1997
+ query: string;
1998
+ [k: string]: unknown;
1999
+ }
2000
+ interface LoadedChatConfig {
2001
+ enableImageUpload: boolean;
2002
+ enableVideoUpload: boolean;
2003
+ enableTTS: boolean;
2004
+ enableVoiceInput: boolean;
2005
+ defaultInputMode: 'TEXT' | 'VOICE';
2006
+ quickCommands: readonly QuickCommand[];
2007
+ }
2008
+ declare function loadChatConfig(configDir: string): LoadedChatConfig;
2009
+ /** LoadedChatConfig → WS HELLO chatConfig(闭合形状,typecheck 恒守护):
2010
+ * query→prompt 映射 + 扩展字段剥离 + settings 五键 pick(白名单单点——演进规则见 contracts 注释)。
2011
+ * 纯函数零日志(build-app-image smoke canary 断言启动日志无 WARN [app-config])。 */
2012
+ declare function toWsChatConfig(cfg: LoadedChatConfig): HelloAckChatConfig;
2013
+
2014
+ /** SDK 默认业务段(agent.jsonc 未配置/坏档时的兜底;单行身份句) */
2015
+ declare const DEFAULT_INSTRUCTIONS = "\u4F60\u662F\u667A\u80FD\u52A9\u624B\uFF0C\u5E2E\u52A9\u7528\u6237\u5B8C\u6210\u65E5\u5E38\u95EE\u7B54\u4E0E\u4E1A\u52A1\u4E8B\u52A1\u3002";
2016
+ interface LoadedAgentPromptConfig {
2017
+ /** 恒有值:配置行数组拼接或 SDK 默认 */
2018
+ instructions: string;
2019
+ /** 可选:记忆域业务措辞(消费方 = build-engine memory 装配态追加;缺席 = 不追加) */
2020
+ memoryInstructions?: string;
2021
+ }
2022
+ declare function loadAgentPromptConfig(configDir: string): LoadedAgentPromptConfig;
2023
+
2024
+ /** 工具 execute 第二参的结构型投影(只声明读取器消费的形状) */
2025
+ interface ToolExecContextLike {
2026
+ requestContext?: {
2027
+ get(key: string): unknown;
2028
+ };
2029
+ toolCallId?: string;
2030
+ agent?: {
2031
+ toolCallId?: string;
2032
+ };
2033
+ }
2034
+ interface ToolRunMetadata {
2035
+ runId: string;
2036
+ threadKey: string;
2037
+ toolCallId: string;
2038
+ }
2039
+ /** Read trusted producer metadata from the execute context, never from model arguments. */
2040
+ declare function getToolRunMetadata(execCtx: ToolExecContextLike | undefined): Readonly<ToolRunMetadata> | undefined;
2041
+ /**
2042
+ * 从工具 execute 第二参读取运行上下文(散键组装)。
2043
+ * 返回 undefined 当 requestContext 缺失或 identity 键缺失(引擎外直调/匿名无身份)。
2044
+ */
2045
+ declare function getToolRequestContext(execCtx: ToolExecContextLike | undefined): Readonly<RequestContext$1> | undefined;
2046
+ /**
2047
+ * 严格变体:运行上下文缺失时抛 AUTH_FORBIDDEN(fail-visible——显式正确性优于静默降级)。
2048
+ * @param toolId 诊断信息(缺失文案指明哪个工具、怎么修)
2049
+ */
2050
+ declare function requireToolRequestContext(execCtx: ToolExecContextLike | undefined, toolId?: string): Readonly<RequestContext$1>;
2051
+ /**
2052
+ * 测试/直调助手:由 plain RequestContext 构造工具 execute 第二参形态。
2053
+ * 散键写入与引擎 buildRunRequestContext 同构(往返由 context-concurrency.test C2 锁定)。
2054
+ */
2055
+ declare function createToolExecContext(reqCtx: RequestContext$1): ToolExecContextLike;
2056
+
2057
+ interface SaveMessageParams {
2058
+ conversationId: string;
2059
+ agentId: string;
2060
+ query: string;
2061
+ answer: string;
2062
+ outerBusinessId?: string;
2063
+ multiModalInputs?: Record<string, unknown>;
2064
+ /** 平台消息 inputs(cards/skills/preTools 等)——宽松类型对齐 SDK MessageSaveRequest.inputs
2065
+ * (P3 W1:卡片快照随消息持久化,004 D1 MessageEmbedded) */
2066
+ inputs?: Record<string, unknown>;
2067
+ /** 兜底:平台拒绝 inputs 时以字符串承载(JSON 序列化卡片) */
2068
+ extraParams?: string;
2069
+ }
2070
+ interface ListMessagesParams {
2071
+ agentId: string;
2072
+ conversationId?: string;
2073
+ userId?: string;
2074
+ beforeId?: string;
2075
+ pageNo?: number;
2076
+ pageSize?: number;
2077
+ }
2078
+ declare class ConversationService {
2079
+ private client;
2080
+ constructor(apiKey: string);
2081
+ /** 查找用户已有会话,没有则创建新会话 */
2082
+ getOrCreateConversation(agentId: string, userId: string): Promise<string>;
2083
+ createConversation(agentId: string, userId: string): Promise<string>;
2084
+ saveMessage(params: SaveMessageParams): Promise<string>;
2085
+ listMessages(params: ListMessagesParams): Promise<node_modules__tbox_cn_app_sdk_server_src_upstream.PaginationResult<node_modules__tbox_cn_app_sdk_server_src_upstream.MessageInfo>>;
2086
+ }
2087
+
2088
+ interface PlatformApiRouterDeps {
2089
+ /** ServerContext:会话路由内部化卡片恢复(restoreCardSnapshot(snap, ctx.cards)) */
2090
+ ctx: ServerContext;
2091
+ /** 统一鉴权运行时(006):router(login/dev-login/me) */
2092
+ auth: AuthRuntime;
2093
+ /**
2094
+ * 长期记忆存储(017):传入则挂载 GET/DELETE /api/memory 管理面(与引擎同源实例)。
2095
+ * 缺省不挂载(未装配记忆的应用路由面零变化)。
2096
+ */
2097
+ memory?: MemoryStore;
2098
+ }
2099
+ /**
2100
+ * 平台 API 路由装配(003/006 平台轴)。
2101
+ * ⚠️ 挂载顺序契约(H2):本工厂**不挂全局 auth.middleware**——由组装端(apps/server/index.ts)
2102
+ * 先挂 `app.use('/api', auth.middleware)`,再挂 `/api/m`、`/api/action`,最后挂本路由,
2103
+ * 保证模块 API / 动作网关同样受全局鉴权约束,不产生鉴权缺口。
2104
+ * 本工厂只挂业务路由 + 404 兜底。
2105
+ */
2106
+ declare function createPlatformApiRouter(deps: PlatformApiRouterDeps): Router;
2107
+
2108
+ interface ConversationRouterDeps {
2109
+ /** ServerContext(卡片注册表):卡片快照恢复内部化——restoreCardSnapshot(snap, ctx.cards),闭包延迟解析 */
2110
+ ctx: ServerContext;
2111
+ }
2112
+ declare function createConversationRouter(deps: ConversationRouterDeps): Router;
2113
+
2114
+ /**
2115
+ * 记忆管理面 HTTP 路由(017 SPEC-8):GET/DELETE /api/memory——用户查看/删除自己的长期记忆。
2116
+ *
2117
+ * 设计要点:
2118
+ * - 挂载:createPlatformApiRouter({ ctx, auth, memory? })——memory 缺省不挂载(向后兼容);
2119
+ * - 鉴权:全局 authMiddleware 已注入身份(H2 挂载顺序契约);匿名 → 403(INV-3 HTTP 面);
2120
+ * - 能力门控:caps.list/delete=false → 501 + MEMORY_ERROR_CODES(不触达 store——缺口期诚实降级);
2121
+ * - scope query 参数:urlencoded JSON 防御解析(malformed → 400);
2122
+ * - kind 过滤:路由层对结果 filter(管理面分类查询——极简实现,不进契约);
2123
+ * - 归属校验:store.delete 按 userId+scope+id(INV-2;false → 200 + { deleted: false })。
2124
+ */
2125
+
2126
+ interface MemoryRouterDeps {
2127
+ /** 记忆存储(引擎同源实例——管理面与 run 期读写同一存储) */
2128
+ store: MemoryStore;
2129
+ }
2130
+ declare function createMemoryRouter(deps: MemoryRouterDeps): Router;
2131
+
2132
+ declare const healthRouter: Router;
2133
+
2134
+ declare const router: Router;
2135
+
2136
+ /**
2137
+ * TTS WebSocket proxy.
2138
+ * Client connects to /ws/tts, server proxies to mediafeature upstream.
2139
+ *
2140
+ * Flow: client START_TTS -> server fetches auth -> connects upstream -> sends init payload
2141
+ * -> upstream replies start_ack -> server forwards to client
2142
+ * -> client sends TTS_TEXT -> server forwards to upstream (only after start_ack)
2143
+ */
2144
+ declare function createTtsProxy(): ws.Server<typeof WebSocket, typeof http.IncomingMessage>;
2145
+
2146
+ /**
2147
+ * Get lazily-initialized TboxTtsClient.
2148
+ *
2149
+ * Uses TboxTtsClient.create() factory which internally calls
2150
+ * TboxAppClient.generateSession() to obtain sessionId + channel,
2151
+ * then constructs the client with proper session credentials
2152
+ * for fetchAuth() to work.
2153
+ */
2154
+ declare function getTtsClient(): Promise<TboxTtsClient>;
2155
+ /**
2156
+ * Reset cached TTS client so the next getTtsClient() call
2157
+ * creates a fresh one with a new session.
2158
+ */
2159
+ declare function resetTtsClient(): void;
2160
+
2161
+ interface ModelProviderOptions {
2162
+ /** llm_provider.json 路径(缺省 <cwd>/../../config/llm_provider.json) */
2163
+ configPath?: string;
2164
+ }
2165
+ interface ModelProvider {
2166
+ getModel(modelName: string): LanguageModel;
2167
+ /** 模型名单点解析(config modelName ?? env APP_AI_MODEL_NAME)——与 getModel 同链,装配端记录用 */
2168
+ resolveModelName(): string;
2169
+ }
2170
+ declare function createModelProvider(options?: ModelProviderOptions): ModelProvider;
2171
+
2172
+ /**
2173
+ * 宿主应用唯一的插件装配入口(平台轴)。公共包负责配置解析、元数据和执行协议;
2174
+ * 组装端只注入自己的配置路径与凭证,不在业务代码中直接创建 SDK client。
2175
+ *
2176
+ * config 路径用 process.cwd() 相对(dev 从 apps/server/ 跑 tsx,prod 从 apps/server/ 跑 node dist/index.js),
2177
+ * 避免 import.meta.url 在 tsup 打包后指向 dist/ 导致路径层级变化。
2178
+ * 扩展点:createPluginIntegration({ configPath, apiKey }) 覆盖配置路径与凭证函数。
2179
+ */
2180
+ interface PluginIntegrationOptions {
2181
+ /** plugins.json 路径(缺省 <cwd>/../../config/plugins.json) */
2182
+ configPath?: string;
2183
+ /** TBOX_API_KEY 读取函数(缺省 () => process.env.TBOX_API_KEY) */
2184
+ apiKey?: () => string | undefined;
2185
+ }
2186
+ interface LoadedPluginTools {
2187
+ tools: Record<string, AnyTool>;
2188
+ references: {
2189
+ kind: 'plugin';
2190
+ pluginId: string;
2191
+ toolId: string;
2192
+ runtimeId: string;
2193
+ }[];
2194
+ }
2195
+ declare function createPluginIntegration(options?: PluginIntegrationOptions): {
2196
+ /** 底层 @tbox.cn/agent-plugin 集成实例(cli 工具 / 高级场景用) */
2197
+ integration: _tbox_cn_agent_plugin.PluginIntegration;
2198
+ /** 插件配置读取(cli 工具用) */
2199
+ readConfig: () => _tbox_cn_agent_plugin.ParsedPluginsConfig;
2200
+ /** 业务 workflow 主动调用已配置插件工具的稳定入口 */
2201
+ runConfiguredTool: <T = unknown>(reference: ConfiguredPluginToolReference, input: Record<string, unknown>) => Promise<PluginRunResult<T>>;
2202
+ /**
2203
+ * 加载配置插件工具(自注册闭环的 loadPlugins 注入点)。
2204
+ * reservedToolIds 由组装端从 ctx.tools 计算,避免插件与静态工具 id 冲突。
2205
+ */
2206
+ loadTools: (opts: {
2207
+ reservedToolIds: string[];
2208
+ }) => Promise<LoadedPluginTools>;
2209
+ };
2210
+
2211
+ /** 安装器依赖(auth 只取 middleware——最小面) */
2212
+ interface InstallTboxDevDeps {
2213
+ ctx: ServerContext;
2214
+ auth: Pick<AuthRuntime, 'middleware'>;
2215
+ }
2216
+ declare function installTboxDev(app: Express, deps: InstallTboxDevDeps): void;
2217
+
2218
+ /**
2219
+ * dev 卡片预览纯核(零 express 依赖——node 直测前提)。
2220
+ *
2221
+ * - buildCatalog:ctx.cards 注册表真实态 → 预览目录(统一样本模型:初始态恒第一位 +
2222
+ * 逐样本 schema 校验 / shape 断言 / 信封投影,质量问题以 issues/envelopeError 承载不阻断);
2223
+ * - executePreviewAction:dev 端点直调 action.execute——**镜像 dispatcher 护栏语义,
2224
+ * 刻意跳过 grant/singleUse/幂等**(本地模拟语境下这些护栏无意义:token 由客户端铸造、
2225
+ * 无 WS 会话域);结果 update/card 经目标卡 dataSchema 校验 + project 重投影后
2226
+ * 返回完整 TboxCardPayload。
2227
+ */
2228
+
2229
+ /** dev 预览动作业务失败(安装器映射 HTTP status + code;code 表为页面契约,增删须回规格层) */
2230
+ declare class PreviewActionError extends Error {
2231
+ readonly status: number;
2232
+ readonly code: string;
2233
+ constructor(status: number, code: string, message: string);
2234
+ }
2235
+
2236
+ /**
2237
+ * 样本 shape 覆盖断言(dev 卡片预览配套):样本键 ⊆ dataSchema shape。
2238
+ *
2239
+ * 拦截面定位(刻意收窄):
2240
+ * - zod object 默认 strip 模式会**静默剥离** schema 外的键——safeParse 通过不代表
2241
+ * 样本全量生效;本函数抓「样本含 shape 外键」(BASE-spread 绕过 TS freshness
2242
+ * 检查的惯用漂移 + schema 宽松构造),供模块 samples.test.ts 与 buildCatalog 双消费;
2243
+ * - **不宣称完备**:union/record/intersection/lazy/tuple 及无法识别的节点整子树跳过并计入
2244
+ * blindSpots 报告(无法机械判定分支选择/开放键集——zod 3.25 起 ZodRecord 亦带 .element,
2245
+ * 以值形态区分:对象值记盲区),类型正确性仍由 TS + safeParse 兜底;
2246
+ * - passthrough object 的开放键会被误报为 violation(zod 3 无公开 duck 面可探测 unknownKeys,
2247
+ * 无法与 strip 区分)——当前全仓 CardMeta dataSchema 无 passthrough 使用面;真出现时以
2248
+ * safeParse 通过为准豁免该报告。
2249
+ *
2250
+ * 跨包安全(铁律):节点判定一律**结构探测(duck-typing)**——`'shape' in schema` /
2251
+ * `schema.unwrap?.()` / `schema.element` / `schema.options` / `schema.schema`;
2252
+ * **全禁 `instanceof z.*` 与 `_def` 私有字段**:pnpm 依赖隔离下模块与 SDK 可能各持
2253
+ * 一份 zod 副本(同版本 ≠ 同构造器),instanceof 必然误判;这是平台首个跨包
2254
+ * schema 结构内省,双 zod 实例行为由 sample-shape.test.ts 钉住。
2255
+ */
2256
+
2257
+ /** 样本含 shape 外键(会被 strip 静默剥离) */
2258
+ interface SampleShapeViolation {
2259
+ /** 样本名(sampleData 记为「初始态」) */
2260
+ label: string;
2261
+ /** 违规键所在路径(根为空串) */
2262
+ path: string;
2263
+ /** 违规键名 */
2264
+ key: string;
2265
+ }
2266
+ /** 无法机械判定的子树(报告不宣称完备的载体) */
2267
+ interface SampleShapeBlindSpot {
2268
+ label: string;
2269
+ path: string;
2270
+ reason: string;
2271
+ }
2272
+ interface SampleShapeReport {
2273
+ violations: SampleShapeViolation[];
2274
+ blindSpots: SampleShapeBlindSpot[];
2275
+ }
2276
+ /**
2277
+ * meta 级全样本断言:sampleData(记「初始态」)+ meta.samples 逐样本探测。
2278
+ * 返回 violations(须修)与 blindSpots(如实报告,不算失败)。
2279
+ */
2280
+ declare function findSampleShapeViolations(meta: CardMeta): SampleShapeReport;
2281
+
2282
+ export { type AnyTool, BROAD_ROUTING_TERMS, BUILTIN_HYGIENE_NAMES, type BootstrapMemoryKbOptions, type BootstrapMemoryKbResult, type BuildEngineOptions, CARDS_SPEC, CARD_DECISION_HOLD_LIMIT, CARD_DECISION_TAG, CARD_EMISSION_HINT_ACTIONS, CARD_EMISSION_HINT_BASE, CARD_EMISSION_HINT_KEYWORD, type CardDecisionPlan, type CardDecisionStripper, type CardPersistenceBackend, type CardPool, type CardPoolOptions, type ChatEngine, type ChatEngineOptions, type ContentPart, type ContentTagHygiene, type ConversationRouterDeps, ConversationService, DECISION_HOLD_LIMIT, DEFAULT_INSTRUCTIONS, DEFAULT_KNOWLEDGE_MEMORY_CAPABILITIES, DEFAULT_LIST_TTL_MS, DEFAULT_LLM_PROVIDER_CONFIG_PATH, DEFAULT_MAX_CARDS_PER_TURN, DEFAULT_MAX_ENTRIES, DEFAULT_MAX_PRE_TOOLS_PER_RUN, DEFAULT_MEMORY_MAX_CHARS_PER_RECORD, DEFAULT_MEMORY_RECALL_TIMEOUT_MS, DEFAULT_MEMORY_TOP_K, DEFAULT_MEMORY_VALIDATE_TIMEOUT_MS, DEFAULT_PRE_TOOL_TIMEOUT_MS, DEFAULT_SKILL_MODE, DROP_BODY_SOFT_LIMIT, EARLY_EXECUTION_MARKER, type EngineModelStepInput, type EngineRunEndInput, type EngineRunInput, type EngineStepControlFactory, type EngineStepControlInput, type EngineStepController, type EngineStepResultInput, type EngineStepToolChoice, type EngineToolCallInput, type EngineToolResultInput, FORM_SUBMIT_TOOL_ID, FileCardPersistenceBackend, HYGIENE_TAG_NORMALIZE, type HygieneTagFamily, INTERNAL_TOOL, type InstallTboxDevDeps, type IntentRoute, KB_SCOPE_GLOBAL, KNOWLEDGE_DEFAULT_BASE_URL, KnowledgeBootstrapError, type KnowledgeMemoryStoreOptions, KnowledgeOpenapiError, type KnowledgeOpenapiTransportOptions, type KnowledgeTransport, type LoadedAgentPromptConfig, type LoadedChatConfig, type LoadedPluginTools, MEMORY_IMPORTANCE_BASE, MEMORY_KB_INDEX_COLUMNS, MEMORY_KB_SCHEMA, MEMORY_KB_SEED_CSV, MEMORY_LIST_DEFAULT_LIMIT, MEMORY_LIST_MAX_LIMIT, MEMORY_MAX_PER_USER, type MemoryEngineOptions, type MemoryFilterColumn, type MemoryGuardDeps, type MemoryGuardEnv, type MemoryPromptCaps, type MemoryRouterDeps, type MemoryStoreEnv, MemoryStoreUnsupportedError, type MemoryToolDeps, MemoryUnavailableError, type MemoryValidateMode, type MemoryValidationOutcome, MessageEmbeddedBackend, type ModelProviderOptions, PRE_TOOL_HISTORY_LIMIT, type ParallelToolCallsControl, type PlatformApiRouterDeps, type PluginIntegrationOptions, type PoolEntry, type PreFilterTerm, type PreToolExecContext, PreToolTimeoutError, PreviewActionError, type QuickCommand, type RecallCacheOptions, type RecallCacheState, type ResolvedTagSpecs, type SampleShapeBlindSpot, type SampleShapeReport, type SampleShapeViolation, type SdkRuntimeOptions, type SdkToolRuntime, type SegmentHit, type SkillInjectionDecision, type SkillMode, type SortTerm, type StoredMemoryRecord, type StreamTagEngine, DEFAULT_FILE_URL_PREFIX as TBOX_FILE_URL_PREFIX, THINK_SPECS, TOOL_CALL_TEXT_SPECS, TOOL_CARDS_FIELD, TOOL_CARD_DESCRIPTOR_SCHEMA, type TagBodyPolicy, type TagEngineFinish, type TagHit, type TagSeal, type TagSource, type TagSpec, type TagTrack, TboxTraceExporter, type ThinkingControl, type ToolCardDescriptor, type ToolCardSpec, type ToolExecContextLike, type ToolRunMetadata, type TurnReminderBlocks, applySkillReminder, bootstrapMemoryKnowledgeBase, buildCardDecisionReminder, buildInjectedUserContent, buildMemoryRecallToolCallEvents, buildMemoryReminder, buildMessageInputs, buildPlatformInstructions, buildPreToolCallEndEvents, buildPreToolCallStartEvents, buildPreToolDirectives, buildRecapUserContent, buildSkillRecapReminder, buildSkillReminder, buildSkillToolCallEvents, buildUserContent, captureToolCards, clampMaxCards, clampMemoryMaxChars, clampMemoryTopK, coerceStringifiedFields, composeTurnUserContent, createCardDecisionStripper, createCardPool, createCardTool, createChatEngine, createConversationRouter, createEngineFromContext, createGatedMemoryStore, createInMemoryMemoryStore, createIntentDispatcher, createKnowledgeMemoryStore, createKnowledgeOpenapiTransport, createMemoryRouter, createMemoryTools, createModelProvider, createPlatformApiRouter, createPluginIntegration, createSdkToolRuntime, createStreamTagEngine, createToolExecContext, createTtsProxy, createWsServer, decideCards, decideSkillInjection, definePreTool, envelopeTag, executePreTool, extractImageUrls, findSampleShapeViolations, formSubmitTool, generateMemoryId, getLastRecallCacheState, getToolRequestContext, getToolRunMetadata, getTtsClient, hardenToolsForLlm, hashContent, healthRouter, hygieneXmlTag, installTboxDev, internalTool, loadAgentPromptConfig, loadChatConfig, loadLocalSkills, loadModuleSkills, matchIntent, memoryStoreCapabilities, mergePreTools, mergeSkills, normalizePreTools, omitInternal, pickFallbackCard, projectHistory, recallMemories, requireToolRequestContext, resetTtsClient, resolveEarlyToolExecution, resolveMaxSteps, resolveMemoryEngineOptions, resolveMemoryRecallTimeout, resolveMemoryStore, resolveMemoryStoreGuarded, resolveMemoryValidateMode, resolveMemoryValidateTimeout, resolvePreToolTimeout, resolveSkillMode, resolveTagSpecs, resolveToolDebug, restoreCardSnapshot, sanitizeLlmToolInput, scanInjectedSkills, scopeToKey, selectPreTools, selectSkill, stableStringify, stripSystemReminderBlocks, router as tboxSessionRouter, tboxTraceExporter, toCardSnapshot, toMastraSkill, toWsChatConfig, tokenizeTagBody, toolCardScope, validateMemoryKnowledgeBase, withCardEmissionHint, withDeadline, withEarlyExecution, withLlmInputSanitize, withRecallCache, wrapToolsForCardCapture, xmlTag, xmlTagDecision };