@tbox.cn/app-sdk-server 0.21.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,2179 @@
1
+ import * as _tbox_cn_app_contracts from '@tbox.cn/app-contracts';
2
+ import { CardMeta, Identity, ExternalCredentials, TboxCardPayload, RequestContext, ServerEvent, AuthenticatedTransport, ProviderCredential, IdentityExchange, ProviderErrorCode, ProviderInstance, ProviderTemplateDeclaration, DeploymentInstance, ProviderInstanceDeclarations, IntegrationsConfig, ProviderCatalog, CardActionResult, ScopeAssemblyContract, MemoryStore, TboxNoticePayload, AuthErrorCode, TokenPayload, ModuleConfig, ExchangeRequest, ExchangeResult } from '@tbox.cn/app-contracts';
3
+ export { HostEffect, SKILL_NAME_PATTERN, assertNoInlineSecrets, parseIntegrationsConfig } from '@tbox.cn/app-contracts';
4
+ import { Router, Request, RequestHandler } from 'express';
5
+ import { AsyncLocalStorage } from 'node:async_hooks';
6
+ import { TboxLogger, LogContext } from '@tbox.cn/app-sdk-core';
7
+ export { InferModuleCards, LogContext, LogLevel, TboxLogger, createLogger } from '@tbox.cn/app-sdk-core';
8
+ import { z } from 'zod';
9
+ export { buildOwnershipMap, loadProviderCatalog } from '@tbox.cn/app-toolkit';
10
+
11
+ type EventMap = Record<string, unknown>;
12
+ interface TypedBus<TMap extends EventMap> {
13
+ on<K extends keyof TMap>(event: K, handler: (payload: TMap[K]) => void): () => void;
14
+ /** 同步派发(fire-and-forget;异步 handler 不阻塞) */
15
+ emit<K extends keyof TMap>(event: K, payload: TMap[K]): void;
16
+ off<K extends keyof TMap>(event: K, handler: (payload: TMap[K]) => void): void;
17
+ clear(): void;
18
+ /** publish = async emit(B1:Promise.allSettled 聚合,await 全部异步 handler) */
19
+ publish<K extends keyof TMap>(event: K, payload: TMap[K]): Promise<void>;
20
+ /** subscribe = on,返回取消订阅函数 */
21
+ subscribe<K extends keyof TMap>(event: K, handler: (payload: TMap[K]) => void | Promise<void>): () => void;
22
+ }
23
+ declare function createTypedBus<TMap extends EventMap>(): TypedBus<TMap>;
24
+
25
+ declare class ServiceRegistry {
26
+ private services;
27
+ register<T>(id: string, impl: T): void;
28
+ resolve<T>(id: string): T | undefined;
29
+ clear(): void;
30
+ getAll(): Record<string, unknown>;
31
+ }
32
+ declare function registerService<T>(id: string, impl: T): void;
33
+ declare function resolveService<T>(id: string): T | undefined;
34
+ declare function clearServices(): void;
35
+
36
+ /**
37
+ * 注册表工具结构类型(通用侧,零 mastra):
38
+ * agent 工具工厂(mastra createTool 等)产出物结构兼容本接口——存储/协议面只认结构,
39
+ * marker(INTERNAL_TOOL/EARLY_EXECUTION_MARKER 等 symbol 键)经 Map 原样透传,类型面不声明。
40
+ * mastra 泛型擦除别名 AnyTool 在 agent 包(app-agent-sdk-server create-module-tool.ts)。
41
+ */
42
+ interface RegistryTool {
43
+ id: string;
44
+ description?: string;
45
+ /** standard schema(zod 等;由 agent 工具工厂产出;mastra 1.59 Tool 上为可选属性) */
46
+ inputSchema?: unknown;
47
+ /**
48
+ * 存储面(注册表/装配校验)从不调用执行;签名用方法双变 + never 参数声明,
49
+ * 兼容 mastra 具体签名(真实调用在 agent 侧执行段,直调具体 tool 实例)。
50
+ */
51
+ execute?(args: never, context: never): unknown;
52
+ }
53
+ /**
54
+ * ToolRegistry:LLM function calling 工具注册(无状态)。
55
+ * 模块在 registerServer(ctx) 内 ctx.tools.register(tool),
56
+ * ChatEngine 构建时经 getAll() 聚合(agent 侧负责向 mastra 形状收敛)。
57
+ */
58
+ declare class ToolRegistry {
59
+ private tools;
60
+ private disabled;
61
+ /** 禁止某工具进入运行时工具集;由 provider 在模块注册前声明能力边界。 */
62
+ disable(toolId: string): void;
63
+ register(tool: RegistryTool): void;
64
+ registerAll(tools: RegistryTool[]): void;
65
+ resolve(id: string): RegistryTool | undefined;
66
+ getAll(): Record<string, RegistryTool>;
67
+ has(id: string): boolean;
68
+ get size(): number;
69
+ }
70
+
71
+ /**
72
+ * CardRegistry:卡片元数据注册(cardType → CardMeta,无状态)。
73
+ * 模块在 registerServer(ctx) 内 ctx.cards.register(meta) 注册数据契约。
74
+ */
75
+ declare class CardRegistry {
76
+ private cards;
77
+ private disabled;
78
+ /** 属主记账(cardType → moduleId;registerServerModules 逐模块写入) */
79
+ private owners;
80
+ /** 禁止某卡型进入服务端候选池;可由 provider 在模块注册前声明能力边界。 */
81
+ disable(cardType: string): void;
82
+ register(meta: CardMeta): void;
83
+ registerAll(metas: CardMeta[]): void;
84
+ /**
85
+ * 按 map 批量注册(模块 serverModule.cards 形态)。
86
+ * key 约定 = meta.cardType;不一致时告警并仍按 meta.cardType 注册
87
+ * (doctor 规则 card-type-consistent 会对 key !== cardType 报 error,此处仅运行时兜底)。
88
+ */
89
+ registerMap(metas: Record<string, CardMeta>): void;
90
+ resolve(cardType: string): CardMeta | undefined;
91
+ /**
92
+ * 属主记账(dev 卡片预览页消费):键 = meta.cardType(与 registerMap 同语义——
93
+ * key≠cardType 时仍按 meta.cardType 注册,此处必须对齐否则属主错位)。
94
+ * 幂等覆盖(同 cardType 后写胜出,与 register 覆盖语义对齐);disable 不清表
95
+ * (disabled 卡不进 getAll,无消费面)。
96
+ */
97
+ recordOwner(cardType: string, moduleId: string): void;
98
+ /** 读取属主模块 id(未记账返回 undefined;消费端兜底 '(未声明)') */
99
+ ownerOf(cardType: string): string | undefined;
100
+ getAll(): Record<string, CardMeta>;
101
+ has(cardType: string): boolean;
102
+ get size(): number;
103
+ }
104
+
105
+ /**
106
+ * Skill 领域类型面(通用侧,零 mastra / 零 IO):
107
+ * LocalSkill / 资源限额 / 名称强校验同源 re-export。
108
+ * 自 skill-loader.ts 拆出(agent-sdk 拆分准备):模块系统(ServerContext.skills、
109
+ * SkillRegistry、module-assembly 校验)仅依赖本类型面;文件加载与 mastra 转换
110
+ * (loadLocalSkills/toMastraSkill/loadModuleSkills)留 skill-loader.ts(agent 侧)。
111
+ */
112
+
113
+ /**
114
+ * 本地 Skill 领域类型(009:LocalSkill 一统文件 loader 与模块声明产出)。
115
+ * mastra 类型(InlineSkill/SkillInput)完全封在 skill-loader 模块,模块/模板零感知。
116
+ */
117
+ interface LocalSkill {
118
+ /** skill 名(^[a-z0-9-]{1,64}$,reminder 开标签解析安全锚) */
119
+ name: string;
120
+ /** 描述(≤ SKILL_LIMITS.description) */
121
+ description: string;
122
+ /** 本地打分路由词(accelerated 模式命中依据;空 → warn,不可命中) */
123
+ routingTerms: string[];
124
+ /** SKILL.md 正文(SOP;超 SKILL_LIMITS.instructions → warn) */
125
+ instructions: string;
126
+ /** 参考资料(key = 相对 references/ 的路径,以 .md 结尾;随 skill 内存化加载) */
127
+ references: Record<string, string>;
128
+ }
129
+ /** 资源限额(超限 warn 不阻断;运行期恒等加载,与路径无关) */
130
+ declare const SKILL_LIMITS: {
131
+ readonly description: 1024;
132
+ readonly instructions: number;
133
+ readonly references: 64;
134
+ readonly referenceSize: number;
135
+ };
136
+
137
+ /**
138
+ * SkillRegistry:本地 skill 注册表(模块声明式主通道 009 D6,与 CardRegistry 对齐)。
139
+ * - name 非法(非 ^[a-z0-9-]{1,64}$)→ warn 跳过(reminder 解析安全锚);
140
+ * - 重名 → warn 覆盖(模块先插、应用覆盖由 build-engine 合并保证,此处仅兜底);
141
+ * - references key 非 .md 结尾 → warn(skill_read 引用键约定)。
142
+ */
143
+ declare class SkillRegistry {
144
+ private skills;
145
+ register(skill: LocalSkill): void;
146
+ registerAll(skills: LocalSkill[]): void;
147
+ /** 按 map 批量注册(模块 serverModule.skills 形态;key 约定 = skill.name) */
148
+ registerMap(skills: Record<string, LocalSkill>): void;
149
+ getAll(): LocalSkill[];
150
+ has(name: string): boolean;
151
+ get size(): number;
152
+ }
153
+
154
+ /**
155
+ * 前置工具声明类型面(通用侧,零 mastra):
156
+ * PreToolDef / 路由 / 决策 / decide 入参 / 历史投影 / 用户与地理位置扩展。
157
+ * 自 pre-tool-router.ts 拆出(agent-sdk 拆分准备):模块系统(ServerContext.preTools、
158
+ * PreToolRegistry、module-assembly 校验)仅依赖本类型面;score/decide/execute 执行段
159
+ * 留 pre-tool-router.ts(agent 侧)。
160
+ *
161
+ * args 类型参数化(TArgs):mastra 泛型提取版推断在 agent 侧 definePreTool
162
+ * (pre-tool-router.ts InferToolArgsMastra——1.57 实证不能走 inputSchema 属性推导);
163
+ * 手写 PreToolDef 场景缺省 Record<string, unknown>。
164
+ */
165
+
166
+ /**
167
+ * 前置工具声明(模块 serverModule.preTools / 应用级 BuildEngineOptions.preTools)。
168
+ * tool 引用工具实例 = 单一真源(id/description 派生,D1);key 约定 = tool.id(与 cards key=cardType 对齐)。
169
+ */
170
+ interface PreToolDef<T extends RegistryTool = RegistryTool, TArgs extends Record<string, unknown> = Record<string, unknown>> {
171
+ /** 工具实例引用(build-engine 校验 tools[def.tool.id] === def.tool 实例一致性,D9) */
172
+ tool: T;
173
+ /**
174
+ * 结构化路由(D2):
175
+ * - { mode: 'always' }:必选候选(每轮进入 decide;执行与否由 decide 门控——慎用,防噪音);
176
+ * - { mode: 'keywords'; terms }: 宽召回词表(与 skill 同源打分),命中 score > 0 才候选。
177
+ */
178
+ routing: PreToolRouting;
179
+ /**
180
+ * 决策即构造(D3):返回 { decision: 'run', args } → 预执行该工具;
181
+ * { decision: 'skip', reason? } → 本轮不生效(reason 仅 span 观测,不刷日志)。
182
+ * 运行期(run 窗口内)调用;不得抛(SDK 兜底 warn + skip);args 必须 JSON 可序列化;
183
+ * 坏形状返回(非对象/run 缺 args)→ warn + skip(D10)。
184
+ */
185
+ decide: (input: PreToolDecideInput) => PreToolDecision<TArgs> | Promise<PreToolDecision<TArgs>>;
186
+ /**
187
+ * 静默前置工具(011 D2/D9,FAQ 检索通道):
188
+ * - 不发 START/ARGS/END 前端事件(无「自动查询中」spinner);
189
+ * - 结果不落 inputs.preTools(历史不重建 tool-call 表达);
190
+ * - 仅本轮 `<system-reminder pre-tool="...">` 数据块注入 LLM 上下文。
191
+ */
192
+ silent?: boolean;
193
+ /**
194
+ * 会话内入参去重(B3,session-args dedup):
195
+ * - 键 = `${tool.id}\u0000${stableStringify(args)}`(decide 产出 args 序列化——**按入参去重,
196
+ * 出参不进键**;mallId 等上下文入参化后「结果由入参决定」是去重前提不变量);
197
+ * - 同 thread 会话内已落键 → decide 照跑(保留 span 观测)但 execute 跳过(journal
198
+ * outcome='skip' reason='session-dedup');
199
+ * - 落键时点 = history.push 之后(不变量:preToolDone 键集 ⊆ history 实际注入块——
200
+ * 注入前 abort 不落键,重试语义干净);
201
+ * - accepts(可选):落键前对 stripped result 验收(如空结果 false 不落键 → 下轮重试)。
202
+ * 只影响落键,不影响本轮注入(空结果照常注入,模型按注入块协议降级)。
203
+ * - 适用前提(文档契约):结果会话级稳定的字典类数据(mall-context 等);时效敏感工具禁配。
204
+ * staleness 边界 = 会话时长 + provider 缓存 TTL(显式接受,无 TTL 兜底)。
205
+ * - 并发假设:同 thread 单活跃 run(abortControllers 单条目/线程)——无锁 check→set 安全。
206
+ */
207
+ dedup?: {
208
+ accepts?: (result: unknown) => boolean;
209
+ };
210
+ }
211
+ /** 路由判别联合(D2):字符串字面量,非 enum */
212
+ type PreToolRouting = {
213
+ mode: 'always';
214
+ } | {
215
+ mode: 'keywords';
216
+ terms: string[];
217
+ };
218
+ /** 决策结果判别联合(D3):skip = 不执行(reason 仅 span 观测);run = 执行 + 强类型参数 */
219
+ type PreToolDecision<Args extends Record<string, unknown>> = {
220
+ decision: 'skip';
221
+ reason?: string;
222
+ } | {
223
+ decision: 'run';
224
+ args: Args;
225
+ };
226
+ /**
227
+ * 从工具类型提取输入参数类型(通用兜底版,standard-schema 协议):
228
+ * mastra 泛型参数提取版在 agent 侧(pre-tool-router.ts InferToolArgsMastra)——
229
+ * 1.57.0 实证 inputSchema 属性推导不可靠,本版仅服务 standard-schema 形状的工具。
230
+ */
231
+ type InferToolArgs<T extends RegistryTool> = T['inputSchema'] extends {
232
+ '~types': {
233
+ output: infer O;
234
+ };
235
+ } ? O extends Record<string, unknown> ? O : Record<string, unknown> : Record<string, unknown>;
236
+ /** 决策入参(运行期,与 handle 同级) */
237
+ interface PreToolDecideInput {
238
+ /** 原始用户文本(与打分同源) */
239
+ text: string;
240
+ /**
241
+ * 多轮对话历史投影(只读、不含本轮):text part 过滤拼接 + 截断
242
+ * PRE_TOOL_HISTORY_LIMIT(decide 工程化决策上下文,非模型上下文)。
243
+ */
244
+ history: readonly PreToolHistoryTurn[];
245
+ /** 会话标识(threadKey;匿名连接 fallback) */
246
+ conversationId?: string;
247
+ /**
248
+ * 模块上下文(build-engine 装配路径恒有);ctx.auth 已拆除(0.11.0)——
249
+ * 身份类决策用 identity、领域属性用 attributes;createChatEngine 直调路径可不传
250
+ * (decide 内对 ctx 使用需自行判空)。
251
+ */
252
+ ctx?: ServerContext;
253
+ /** per-run 显式身份(并发安全首选) */
254
+ identity?: Identity;
255
+ /** 外部凭据(同 runCtx 透传) */
256
+ credentials?: ExternalCredentials;
257
+ /**
258
+ * 连接级领域属性(上下文统一化 Stage 1,源自 runCtx.attributes):decide 内经
259
+ * 领域 slot 读取(如 mallSlot.read(input.attributes))——替代旧 ctx.auth 全局读取。
260
+ */
261
+ attributes?: Record<string, unknown>;
262
+ /** 当前用户信息(平台注入扩展点;缺省 undefined) */
263
+ user?: PreToolUserContext;
264
+ /** 地理位置(平台注入扩展点;缺省 undefined) */
265
+ location?: PreToolLocationContext;
266
+ }
267
+ /** 当前用户信息(平台注入扩展点;形状由平台方定义,模块按需读取) */
268
+ interface PreToolUserContext {
269
+ userId: string;
270
+ [key: string]: unknown;
271
+ }
272
+ /** 地理位置(平台注入扩展点;形状由平台方定义,模块按需读取) */
273
+ interface PreToolLocationContext {
274
+ city?: string;
275
+ [key: string]: unknown;
276
+ }
277
+ /** 历史投影单轮(轻量文本化:role + content,不含工具 part) */
278
+ interface PreToolHistoryTurn {
279
+ role: 'user' | 'assistant';
280
+ content: string;
281
+ }
282
+
283
+ /**
284
+ * PreToolRegistry:前置工具声明注册表(010,与 SkillRegistry 对齐)。
285
+ * - tool.id 非法(非 ^[A-Za-z0-9_-]{1,64}$)→ warn 跳过;
286
+ * - keywords 路由空 terms → warn 跳过(恒不命中,声明错误早暴露);
287
+ * - 重名(tool.id)→ warn 覆盖(模块先插、应用覆盖由 build-engine 合并保证,此处兜底)。
288
+ */
289
+ declare class PreToolRegistry {
290
+ private preTools;
291
+ register(def: PreToolDef): void;
292
+ registerAll(defs: PreToolDef[]): void;
293
+ /** 按 map 批量注册(模块 serverModule.preTools 形态;key 约定 = tool.id) */
294
+ registerMap(map: Record<string, PreToolDef>): void;
295
+ getAll(): PreToolDef[];
296
+ has(toolId: string): boolean;
297
+ get size(): number;
298
+ }
299
+
300
+ /**
301
+ * ApiRouteRegistry:后端 HTTP API 路由注册。
302
+ * 模块注册的 basePath 强制落在 `/api/m/<moduleId>/` 命名空间(001 §4.2)。
303
+ *
304
+ * register() 直接写入内部共享 root Router——组装端可在 registerAll 前先
305
+ * app.use('/api/m', ctx.routes.mount()),模块随后注册仍即时生效(无需动态分发)。
306
+ */
307
+ declare class ApiRouteRegistry {
308
+ private root;
309
+ private moduleIds;
310
+ /** moduleId 如 "member" / "points-parking",router 内定义 `/xxx` 子路径 */
311
+ register(moduleId: string, router: Router): void;
312
+ /** 挂载到应用:app.use('/api/m', ctx.routes.mount())。返回共享 root,后续注册即时生效。 */
313
+ mount(): Router;
314
+ getModuleIds(): string[];
315
+ }
316
+
317
+ /**
318
+ * CardSnapshotStore 接口:卡片快照持久化。
319
+ * 业务模块可提供实现,SDK 默认提供内存实现。
320
+ * 006 评审 P2-1:`sessionId` 键语义 = 会话键(conversationId,006 D5);接口名保留兼容。
321
+ */
322
+ interface CardSnapshotStore {
323
+ save(sessionId: string, card: TboxCardPayload): Promise<void>;
324
+ load(sessionId: string): Promise<TboxCardPayload[]>;
325
+ clear(sessionId: string): Promise<void>;
326
+ }
327
+ /** 内存实现(默认) */
328
+ declare class InMemoryCardSnapshotStore implements CardSnapshotStore {
329
+ private store;
330
+ save(sessionId: string, card: TboxCardPayload): Promise<void>;
331
+ load(sessionId: string): Promise<TboxCardPayload[]>;
332
+ clear(sessionId: string): Promise<void>;
333
+ }
334
+
335
+ /**
336
+ * 幂等存储(004 W2 C3)。
337
+ * 接口化 + InMemory(键 → 结果缓存,TTL + LRU 上限),可换 Redis。
338
+ * 语义:幂等 = "写几次"(业务一致性);幂等键命中且 payload 一致 → 返回首次结果(200-cached)。
339
+ */
340
+ interface IdempotencyStore {
341
+ /** 尝试占位幂等键:不存在则占位成功(返回 undefined);存在则返回已缓存结果 */
342
+ tryAcquire(key: string, payloadHash: string): Promise<{
343
+ acquired: true;
344
+ } | {
345
+ acquired: false;
346
+ result: unknown;
347
+ }>;
348
+ /** 完成后写入结果 */
349
+ commit(key: string, result: unknown): Promise<void>;
350
+ /** 检查键当前占位的 payloadHash(网关 409 判定用;可选能力) */
351
+ getPayloadHash?(key: string): string | undefined;
352
+ /** 释放占位(校验失败时回滚;可选能力) */
353
+ release?(key: string): void;
354
+ }
355
+ declare class InMemoryIdempotencyStore implements IdempotencyStore {
356
+ private store;
357
+ private readonly ttlMs;
358
+ private readonly maxEntries;
359
+ constructor(opts?: {
360
+ ttlMs?: number;
361
+ maxEntries?: number;
362
+ });
363
+ tryAcquire(key: string, payloadHash: string): Promise<{
364
+ acquired: true;
365
+ } | {
366
+ acquired: false;
367
+ result: unknown;
368
+ }>;
369
+ commit(key: string, result: unknown): Promise<void>;
370
+ /** 检查键当前占位的 payloadHash(网关 409 判定用) */
371
+ getPayloadHash(key: string): string | undefined;
372
+ /** 释放占位(校验失败时回滚) */
373
+ release(key: string): void;
374
+ private evict;
375
+ clear(): void;
376
+ }
377
+ declare function hashPayload(payload: unknown): string;
378
+
379
+ /**
380
+ * 业务动作网关(004 D3 / W2 C2):卡片/业务写操作的全局分发器。
381
+ * - POST /api/action:SDK 黑盒唯一写入口(新增写动作自动进入校验链,不可绕过)
382
+ * - 校验链槽位化、策略随动作注册:幂等槽 P3 落地;签名/时效槽 P4 填(API 预留不破坏)
383
+ * - 匿名写拒绝(006 D11):identity.source=anonymous 的写操作一律 403,**不随 AUTH_MODE 变**
384
+ * - 工厂形态(消灭 P2 模块级单例):多实例/测试互不污染
385
+ *
386
+ * 错误语义:400(缺参)/ 403(校验失败 / 匿名写)/ 404(未知 action)/ 409(幂等键被不同 payload 复用)/
387
+ * 500(handler 异常)/ 幂等键命中且 payload 一致 → 200 返回缓存结果(非 403)
388
+ */
389
+ type ActionHandler = (payload: unknown, ctx: ActionContext) => Promise<ActionResult>;
390
+ interface ActionContext {
391
+ sessionId: string;
392
+ /** 006 D8:当前请求的运行上下文(authMiddleware 注入;未鉴权为 undefined) */
393
+ requestContext?: RequestContext;
394
+ emit: (event: ServerEvent) => void;
395
+ }
396
+ interface ActionResult {
397
+ success: boolean;
398
+ data?: unknown;
399
+ error?: string;
400
+ }
401
+ /** 校验链槽位(签名/时效/主体槽 P4 填) */
402
+ interface ActionCheck {
403
+ check: (req: Request) => Promise<{
404
+ ok: boolean;
405
+ code: number;
406
+ message: string;
407
+ }>;
408
+ }
409
+ interface ActionPolicy {
410
+ /** 是否写操作(true 时幂等槽生效:缺 idempotencyKey → 400) */
411
+ write?: boolean;
412
+ /** 幂等槽(P3 落地):命中且 payload 一致 → 200-cached;不同 payload → 409 */
413
+ idempotent?: boolean;
414
+ /** 校验槽(P4 填签名/时效/主体) */
415
+ checks?: ActionCheck[];
416
+ }
417
+ interface ActionGateway {
418
+ registerAction(action: string, handler: ActionHandler, policy?: ActionPolicy): void;
419
+ /** POST /api/action 中间件(组装端一次挂载) */
420
+ middleware(): RequestHandler;
421
+ /** 可组合校验链(供模块 REST 端点按需挂载:webhook/上传/demo) */
422
+ validateAction(policy?: ActionPolicy): RequestHandler;
423
+ /** 服务端内部分发(demo 路由 / 测试复用;幂等语义同 middleware) */
424
+ dispatch(action: string, payload: unknown, opts?: {
425
+ sessionId?: string;
426
+ idempotencyKey?: string;
427
+ identity?: _tbox_cn_app_contracts.Identity;
428
+ /**
429
+ * 完整运行上下文(上下文统一化 Stage 1):identity 超集——HTTP 路由直接透传
430
+ * getRequestContext(req)(含 credentials/attributes);提供时优先于 identity。
431
+ */
432
+ requestContext?: _tbox_cn_app_contracts.RequestContext;
433
+ }): Promise<ActionResult>;
434
+ getActions(): ReadonlyMap<string, {
435
+ handler: ActionHandler;
436
+ policy: ActionPolicy;
437
+ }>;
438
+ }
439
+ declare function createActionGateway(opts?: {
440
+ idempotencyStore?: IdempotencyStore;
441
+ }): ActionGateway;
442
+
443
+ /**
444
+ * 服务端日志壳:run 级 ALS 上下文 + ServerLogger(span 经 ServerSpanSink 出口,通用侧零 mastra)
445
+ * + recordCall 计时原语 + withCallLog 外部传输观测。
446
+ *
447
+ * 上下文传播:chat()/submitForm()(引擎 run)与 auth.middleware(HTTP 请求)各自
448
+ * runWithLogContext 开作用域 → 作用域内所有日志行自动携带 req=/conv= 尾缀;
449
+ * requestId === TBOX_TRACE 的 requestId === runId(单一 trace 锚点,一次 grep 串全)。
450
+ * 作用域外(启动期/注册期)日志照常输出,无尾缀。
451
+ *
452
+ * span 出口倒置(agent-sdk 拆分准备):通用侧仅构造 ServerSpanPayload 调 spanSink
453
+ * (缺省 no-op);agent 侧 trace-exporter 模块顶层 setServerSpanSink 注册 mastra
454
+ * emitCustomSpan(type: SpanType.GENERIC 由注册方注入)——H5 等纯通用消费者零 mastra。
455
+ */
456
+
457
+ interface ServerLogScope extends LogContext {
458
+ threadKey?: string;
459
+ }
460
+ /** run 级日志作用域(toolCardScope 同款 ALS 模式;emit 时读取——跨请求复用安全) */
461
+ declare const runLogScope: AsyncLocalStorage<ServerLogScope>;
462
+ declare function runWithLogContext<T>(scope: ServerLogScope, fn: () => Promise<T>): Promise<T>;
463
+ /** 结构化 span 载荷(通用侧形状;mastra type 字段由 agent 侧 sink 注册方注入) */
464
+ interface ServerSpanPayload {
465
+ spanId: string;
466
+ traceId: string;
467
+ name: string;
468
+ startTime: Date;
469
+ endTime: Date;
470
+ metadata?: Record<string, unknown>;
471
+ errorInfo?: {
472
+ message: string;
473
+ type?: string;
474
+ stack?: string;
475
+ };
476
+ requestId: string;
477
+ conversationId?: string;
478
+ sessionId?: string;
479
+ }
480
+ /** span 出口(缺省 no-op;agent 侧 trace-exporter 顶层注册接管) */
481
+ type ServerSpanSink = (payload: ServerSpanPayload) => void;
482
+ /** 注册 span 出口(agent 侧装配期调用;重复注册以最后一次为准) */
483
+ declare function setServerSpanSink(sink: ServerSpanSink): void;
484
+ interface ServerLogger extends TboxLogger {
485
+ /** 结构化 span(→ ServerSpanSink 出口;req/conv 经 ALS 自动关联) */
486
+ span(name: string, payload?: {
487
+ metadata?: Record<string, unknown>;
488
+ error?: unknown;
489
+ }): void;
490
+ }
491
+ /** 服务端 logger(SDK 内部 + ctx.logger 注入共用出口);模块侧经 register 期 ctx 获取 */
492
+ declare function createServerLogger(tag: string): ServerLogger;
493
+ /** 外部调用慢阈值(毫秒):响应行升 WARN——info 档一眼定位慢厂商 */
494
+ declare const EXTERNAL_SLOW_MS = 3000;
495
+ type CallKind = 'tool' | 'external' | 'op';
496
+ /**
497
+ * 统一计时原语:计时 → ok/fail 行(含 durMs)→ 按需 span → 失败原样 rethrow(控制流零变化)。
498
+ * kind 决定行形态:tool 附 args/result 详情;external 由 withCallLog 自管行序;op 仅 durMs。
499
+ */
500
+ declare function recordCall<T>(kind: CallKind, name: string, fn: () => Promise<T>, opts?: {
501
+ logger?: TboxLogger;
502
+ detail?: {
503
+ args?: unknown;
504
+ };
505
+ emitSpan?: boolean;
506
+ onDone?: (durMs: number) => void;
507
+ }): Promise<T>;
508
+ /**
509
+ * 外部接口传输观测(单方法包装):请求行先于 await(调用挂起可见"只出不进"),
510
+ * 响应行带 durMs(>EXTERNAL_SLOW_MS 升 WARN),body 脱敏+截断;logger 缺席直通(单测路径)。
511
+ * run 作用域内额外发 external-call span(D2 纪律:trace 平面只属引擎 run——作用域外只发行不发 span)。
512
+ */
513
+ declare function withCallLog(logger: TboxLogger | undefined, transport: AuthenticatedTransport): AuthenticatedTransport;
514
+
515
+ /**
516
+ * 组件状态存储基元(011 H1/H2):
517
+ * get / put / compareAndSet / consume + TTL + 深冻结。
518
+ *
519
+ * - 默认 memory 实现(单实例边界明示:多副本需 shared 实现,等真实需求,011 H2);
520
+ * - CAS revision 从 1 递增,用于 ActionGrant 签发竞态与幂等;
521
+ * - consume 原子读删(single-use token 消费语义)。
522
+ */
523
+
524
+ interface StoredEntry<T> {
525
+ value: Readonly<T>;
526
+ revision: number;
527
+ /** 过期时间(ms epoch);缺省永不过期 */
528
+ expiresAt?: number;
529
+ }
530
+ interface ComponentStateStore {
531
+ get<T>(namespace: string, ref: string): Promise<Readonly<T> | null>;
532
+ /** 读取条目(含 revision/expiresAt;CAS 前置读取用) */
533
+ getEntry<T>(namespace: string, ref: string): Promise<Readonly<StoredEntry<T>> | null>;
534
+ put<T>(namespace: string, ref: string, value: T, ttlMs: number): Promise<boolean>;
535
+ compareAndSet<T>(namespace: string, ref: string, expectedRevision: number, value: T, ttlMs: number): Promise<boolean>;
536
+ consume<T>(namespace: string, ref: string): Promise<Readonly<T> | null>;
537
+ }
538
+ declare function createInMemoryStateStore(now?: () => Date): ComponentStateStore;
539
+ /** 幂等键 hash(011:跨模块写操作幂等键规范化,与现有 hashPayload 对齐) */
540
+ declare function hashStateRef(input: string): string;
541
+
542
+ /**
543
+ * Provider 认证策略(011 G7):credentialType → apply 注册点。
544
+ * - SDK 内置 'static-headers-v1'(静态头注入);
545
+ * - 模块自定义(如 joycity 签名算法)经注册点注入,SDK 不 import 模块。
546
+ */
547
+
548
+ interface ProviderAuthStrategyInput {
549
+ method: string;
550
+ url: string;
551
+ body?: unknown;
552
+ credential: Readonly<ProviderCredential>;
553
+ /** 请求附加头(gateway 经 extraHeaders 注入,如 token/memberId/appId)——参与签名的头签名侧读取 */
554
+ headers?: Readonly<Record<string, string>>;
555
+ }
556
+ interface ProviderAuthStrategy {
557
+ /** 匹配 ProviderTemplateDeclaration.credentialType */
558
+ credentialType: string;
559
+ /**
560
+ * 认证产出放置(缺省 'header'):'query' = 追加到 URL query(GET 携签厂商,如 wanda
561
+ * sign/timestamp);apply 输入 url 不含认证参数——签名基于业务参数计算后再追加。
562
+ */
563
+ readonly placement?: 'header' | 'query' | 'body';
564
+ /**
565
+ * 产出认证参数(键值对;按 placement 放 header / URL query / JSON Body);抛错 = 认证构造失败(计入熔断)。
566
+ * 'body' 语义(万达 C 端网关对齐):POST/PUT → 合并进 JSON Body(业务字段前置,sign/timestamp 追加末尾——
567
+ * 服务端按字段出现顺序重组 dataStr,与签名侧一致);GET/DELETE → 追加 URL query。
568
+ */
569
+ apply(input: ProviderAuthStrategyInput): Record<string, string>;
570
+ }
571
+ declare const STATIC_HEADERS_CREDENTIAL_TYPE = "static-headers-v1";
572
+ /** 内置静态头策略:credential.value 原样映射为请求头 */
573
+ declare const staticHeadersStrategy: ProviderAuthStrategy;
574
+ /** 011 B2:可变认证策略注册表——模块 register 期注册(如 joycity-c-signed-v1),transportFactory 动态查 */
575
+ interface AuthStrategyRegistry {
576
+ get(credentialType: string): ProviderAuthStrategy | undefined;
577
+ /** 重复注册同名策略 → 后者覆盖 + warn(模块双装配场景) */
578
+ register(strategy: ProviderAuthStrategy): void;
579
+ /** 快照(诊断用) */
580
+ list(): readonly ProviderAuthStrategy[];
581
+ }
582
+ declare function createAuthStrategyRegistry(strategies?: readonly ProviderAuthStrategy[]): AuthStrategyRegistry;
583
+
584
+ /**
585
+ * 换码器注册表(provider 拆包 F0):可变 + 惰性查找。
586
+ *
587
+ * 背景(第五轮评审发现):options.exchanges 静态注入在 createAuthRuntime 构造期展开——
588
+ * provider 包 register(registerServerModules 内)晚于构造,其 authExchanges.register
589
+ * 静默断裂。本注册表持引用惰性查找:登录请求期才 get(platform),register 晚于构造仍生效。
590
+ *
591
+ * 三层解析(F2 模板中立化):get(platform, context?) 按「注册通道」分层归属(非谓词形态)——
592
+ * ① 显式 scoped 候选:register 注册且声明 matches,注册序 first-match;
593
+ * ② 显式无条件候选:register 注册且无 matches(兜底位),最早注册者优先;
594
+ * ③ 构造期 initial 填充(内置 alipay/weapp)恒最后——内置永不遮蔽显式候选。
595
+ * 显式层内分槽:无条件候选(无 matches)每 provider 键至多一条,重复注册原位替换
596
+ * (保序 + 旧覆盖语义);scoped 候选(有 matches)同 provider 多条共存(first-match,
597
+ * 多厂商按 mall 等域并存的前提)。层归属由注册通道决定:构造期内置声明 matches
598
+ * 也不会升入显式层。
599
+ *
600
+ * 接线链(模板装配职责):authRuntime.exchanges → createServerContext({ authExchanges }) →
601
+ * 模块/provider register 期 ctx.authExchanges.register(...) → 登录请求期 login 路由惰性命中
602
+ * (context 为归一化登录上下文,供 scoped 谓词做 mall 等域路由决策)。
603
+ */
604
+
605
+ interface ScopedIdentityExchange extends IdentityExchange {
606
+ /**
607
+ * 谓词路由(F2):纯函数——只读归一化 context、零 IO、不得抛;返回 false = 本候选不命中。
608
+ * 缺省 = 无条件候选(落第②层兜底位)。
609
+ *
610
+ * 统一范式(商圈 provider 候选):业务域依赖缺失(如未选择商场/未指定作用域)时
611
+ * 应命中自身换码器(返回 true),由 exchangeByCode 显性抛配置/选择错误——否则未命中
612
+ * 会落第③层内置候选(本地 alipay/weapp),其缺 env 报错会误导部署面排查。
613
+ * 仅当域值在场但本候选不绑定时才返回 false(继续 fallback,多厂商并存语义)。
614
+ */
615
+ matches?(context?: Readonly<Record<string, unknown>>): boolean;
616
+ /**
617
+ * mock 物料口(可选):返回本厂商 mock 场景外部凭证(config 物料经集成配置求值注入,
618
+ * env/实例配置于调用期懒读——测试可变、运行期可控)。
619
+ * 契约:接收与 matches/exchangeByCode 相同的归一化 context,可同步或异步返回;
620
+ * 返回 undefined = 本厂商声明无物料——调用方不得回退其他厂商;
621
+ * token/provider/attributes 形状归厂商包自持(本 SDK 零 vendor 知识)。
622
+ */
623
+ mockCredentials?(context?: Readonly<Record<string, unknown>>): ExternalCredentials | undefined | Promise<ExternalCredentials | undefined>;
624
+ /**
625
+ * guest 登录声明口(可选):browser 轴 auto 档是否允许签发随机访客身份(guest_<32hex>)。
626
+ * 纯函数/同步;违约视为 false(fail-safe)。缺省 = 不开放(auto 档落 mock/off 判定)。
627
+ * mock provider 与内置换码器声明 true(裸跑即完整演示);真实厂商默认不声明。
628
+ */
629
+ allowsGuestLogin?(context?: Readonly<Record<string, unknown>>): boolean;
630
+ /**
631
+ * browser 轴档位口(可选):browser 登录互斥链档位——'auto' | 'guest' | 'mock' | 'off'。
632
+ * 典型实现 = 读登录槽 config(支持 ${VAR:-default} 展开);违约/缺席视为 'auto'。
633
+ */
634
+ browserLoginMode?(context?: Readonly<Record<string, unknown>>): 'auto' | 'guest' | 'mock' | 'off' | undefined;
635
+ }
636
+ interface AuthExchangeRegistry {
637
+ /**
638
+ * 注册显式候选(key = exchange.provider):scoped 候选(有 matches)多条共存;
639
+ * 无条件候选同键原位替换保序。
640
+ */
641
+ register(exchange: ScopedIdentityExchange): void;
642
+ /** 惰性查找(登录请求期调用);context = 归一化登录上下文(scoped 谓词路由输入)。
643
+ * 返回收宽为 ScopedIdentityExchange:可选能力口成员(matches/mockCredentials/
644
+ * allowsGuestLogin/browserLoginMode)在内置候选上可缺席——调用方以
645
+ * `typeof x.m === 'function'` 守卫,缺席即无该能力。 */
646
+ get(platform: string, context?: Readonly<Record<string, unknown>>): ScopedIdentityExchange | undefined;
647
+ /** 快照(诊断用):explicit 在前、builtins 在后拍平 */
648
+ list(): readonly IdentityExchange[];
649
+ }
650
+ declare function createAuthExchangeRegistry(initial?: Record<string, IdentityExchange>): AuthExchangeRegistry;
651
+
652
+ /**
653
+ * 环境机密解析(011 G5):credentialRef → ProviderCredential。
654
+ * - credentialRef 形态 'secret://{env}/{seg...}'({env} 为部署环境键,剩余为分段路径);
655
+ * - 生产 credentialRef 缺失 → fail-fast(PROVIDER_CREDENTIAL_REF_MISSING);
656
+ * - scope 严格匹配(凭证 scope 与实例 scope 键值一致才可用);
657
+ * - 头名白名单(应用后即弃,禁止落日志)。
658
+ */
659
+
660
+ declare class ProviderError extends Error {
661
+ readonly code: ProviderErrorCode;
662
+ constructor(code: ProviderErrorCode, message: string);
663
+ }
664
+ /** 机密来源:环境键 → 值(模板注入 process.env 快照) */
665
+ type SecretSource = Readonly<Record<string, string | undefined>>;
666
+ interface EnvironmentSecretProvider {
667
+ resolve(credentialRef: string, expectedScope: Record<string, string>): Readonly<ProviderCredential>;
668
+ }
669
+ interface EnvironmentSecretProviderOptions {
670
+ /** 环境键快照(禁止直接读 process.env——测试可注入) */
671
+ source: SecretSource;
672
+ /**
673
+ * 凭证文件目录(可选;文件 > env 优先):credentialRef 键 → 文件名派生
674
+ * (小写、'-'→'_'、追加 .json——与 .real-env README 派生公式互逆)。命中即读文件内容
675
+ * (JSON 文本),miss 回退 source。镜像场景:凭据文件挂载直读,免 env 展开。
676
+ */
677
+ files?: string;
678
+ /** 头名白名单(静态头注入凭证)。缺省空 = 拒绝静态头 */
679
+ allowedHeaderNames?: readonly string[];
680
+ /** 生产标志:true 时 credentialRef 缺失 fail-fast;false 时可用 dev fixture 兜底 */
681
+ production?: boolean;
682
+ }
683
+ declare function createEnvironmentSecretProvider(opts: EnvironmentSecretProviderOptions): EnvironmentSecretProvider;
684
+
685
+ /**
686
+ * 认证传输层工厂(011 G2/G4):熔断 + 超时 + 1MB 上限 + 强制 HTTPS + X-Trace-Id。
687
+ *
688
+ * 缓存责任在 registry(key = templateId + stable(scope) + credentialVersion),
689
+ * 本工厂产出单实例 transport(credentialVersion 变更 → registry 重建)。
690
+ */
691
+
692
+ interface CircuitBreakerConfig {
693
+ /** 连续失败阈值(缺省 3) */
694
+ failureThreshold?: number;
695
+ /** 开闸时长 ms(缺省 30s) */
696
+ openMs?: number;
697
+ }
698
+ interface TransportFactoryOptions {
699
+ strategies: AuthStrategyRegistry;
700
+ secretProvider: EnvironmentSecretProvider;
701
+ circuitBreaker?: CircuitBreakerConfig;
702
+ /** 响应体上限字节(缺省 1MB) */
703
+ maxResponseBytes?: number;
704
+ /** 超时上限(缺省 15s;opts.timeoutMs 不覆盖此上限) */
705
+ maxTimeoutMs?: number;
706
+ /** 时钟注入(测试用) */
707
+ now?: () => number;
708
+ /** 观测 logger:在场时 [transport] 最终请求预览走 logger.debug(统一行格式+级别控制);
709
+ * 缺席静默(直构/测试路径零输出,原 console.log 行为移除)。 */
710
+ logger?: TboxLogger;
711
+ }
712
+ interface TransportFactory {
713
+ create(instance: ProviderInstance, template: ProviderTemplateDeclaration): AuthenticatedTransport;
714
+ }
715
+ declare function createAuthenticatedTransportFactory(opts: TransportFactoryOptions): TransportFactory;
716
+
717
+ /**
718
+ * Integrations 注册表(integrations v6):service slot → (provider, implementation) → binding 解析轴。
719
+ *
720
+ * 旧 ProviderRegistry(templateId + scope 双键)已删除(全仓零消费实证)——本轴是唯一解析面;
721
+ * 原旁路消费(换码器 transport 直连)已迁本轴:
722
+ * - resolveLoginExchange:换码 transport 级解析(无请求上下文/无 adapter 语义);
723
+ * - hasProviderBinding:presence 点查(路由谓词——effective 求值后比对 provider+implementation)。
724
+ * 声明式槽解析主链:
725
+ * - 配置真源 integrations.json(IntegrationsConfig:root → modules[owner] → service → instance;
726
+ * v6 所有权模型——ownerOf 归属表由装配期显式注入,domains 键已退役);
727
+ * - effective 求值单源 = contracts resolveEffectiveService(绑定组最特异层整组取
728
+ * inst > slot > modules[owner] > root;组内 implementation 缺席经 supplies 派生;
729
+ * enabled 缺省 true;层序优先于 scope 特异度);
730
+ * - 供给真源 provider catalog(嵌套 providers[vendor][impl];loadProviderCatalog 聚合;
731
+ * 构造期 buildSupplyLookup 展平为派生查表——求值期 O(1));
732
+ * - adapter 可变注册表((provider, implementation) 双键;provider 包 register 期注册,
733
+ * 晚于本工厂构造——惰性查找);
734
+ * - 实例级绑定组覆盖(instance.provider/implementation 成组;implementation 缺席 = 组内派生,
735
+ * 按 mall 差异化,不算槽冲突);
736
+ * - local 短路(catalog 条目 local:true → InMemory transport,免凭据/认证/credentialRef);
737
+ * - transport 缓存键 = service + instanceId + provider + implementation(派生 impl 自动入键;
738
+ * 换绑后旧 transport 留存复用——熔断半开自恢复;integrations 配置无热轮换,重载即重启进程);
739
+ * - provider 实例声明通道(declareProviderInstances——COW 拷贝冻结快照;域中立存储,
740
+ * SDK 不解释实例内容,域装配惰性融合消费)。
741
+ *
742
+ * SDK 零领域语义铁律:instanceId 提取器注入(instanceIdOf;mall 场景模板层注入
743
+ * (scope) => scope.mallId),缺省 stableSerializeScope。错误上下文统一 `service@instanceId`。
744
+ */
745
+
746
+ /** adapter 构造输入(provider 包 factory 的唯一依赖面) */
747
+ interface ServiceAdapterInput {
748
+ transport: AuthenticatedTransport;
749
+ config: Readonly<Record<string, unknown>>;
750
+ credentialRef?: string;
751
+ scope: Readonly<Record<string, string>>;
752
+ instanceId: string;
753
+ request: RequestContext;
754
+ /** 本次解析的 service 槽 id(017 槽位原子化):guide 等多槽共享工厂按此分支返回
755
+ * 单 Port 产物;其余工厂忽略。 */
756
+ service: string;
757
+ /**
758
+ * 惰性凭据 getter(v2 T2.4 起):调用才解析(ref → 文件/环境),未调用零成本
759
+ * (local 短路/无凭据槽 factory 不触)。返回 ProviderCredential(含 value 机密)。
760
+ * credentialRef 缺席 → undefined(调用方按自身语义降级)。
761
+ */
762
+ credential?: () => Readonly<ProviderCredential>;
763
+ }
764
+ /** adapter 工厂(provider 包 register 期注册;产物请求级——模块 service 请求级构造模式) */
765
+ type ServiceAdapterFactory = (input: ServiceAdapterInput) => unknown;
766
+ /** 换码解析产物(resolveLoginExchange):transport 级——登录换码器直接消费认证 transport。
767
+ * providerId 字段 = effective implementation('id@version';展示/诊断用途,模块不消费)。 */
768
+ interface LoginExchangeResolution {
769
+ transport: AuthenticatedTransport;
770
+ config: Readonly<Record<string, unknown>>;
771
+ providerId: string;
772
+ }
773
+ interface IntegrationsRegistry {
774
+ /** 注册 adapter(provider 包 register 期;双键 = provider 厂商名 + implementation 'id@version';
775
+ * 重复后者覆盖 + warn) */
776
+ registerAdapter(provider: string, implementation: string, factory: ServiceAdapterFactory): void;
777
+ /** 槽解析(模块 ports 运行期调用;错误上下文 service@instanceId) */
778
+ resolveService(input: {
779
+ service: string;
780
+ scope: Record<string, string>;
781
+ request: RequestContext;
782
+ }): Promise<unknown>;
783
+ /** 换码 transport 级解析(登录场景专用:无请求上下文/无 adapter 语义)。
784
+ * 错误码族与 resolveService 同源(SERVICE_NOT_CONFIGURED/INSTANCE_NOT_FOUND/
785
+ * INSTANCE_DISABLED/BINDING_UNRESOLVED/PROVIDER_NOT_FOUND);调用方(provider 包换码器)按域转译。
786
+ * transport 缓存与 resolveService 共池(同 service@instanceId@provider@impl 键)。 */
787
+ resolveLoginExchange(input: {
788
+ service: string;
789
+ scope: Record<string, string>;
790
+ }): Promise<LoginExchangeResolution>;
791
+ /** presence 点查:该槽该 scope 的有效 (provider, implementation)(effective 求值后)
792
+ * === 入参双字段。内联声明形态恒 false(无实现可比);纯配置读取,无 transport/凭据副作用。 */
793
+ hasProviderBinding(service: string, scope: Record<string, string>, provider: string, implementation: string): boolean;
794
+ /** 声明 provider 的隐式部署实例(provider 包 register 期调用;域中立存储——SDK 只存取
795
+ * DeploymentInstance 通用类型,不解释实例内容;融合规则归 TIER1 投影器如 mallControlPlaneOf)。
796
+ * 空数组 no-op;结构非法 fail-fast(id 非空、禁 '*' 通配保留字、name 须非空 string);
797
+ * 同 provider 重复声明覆盖 + warn(对齐 registerAdapter 先例)。
798
+ * 存入前拷贝并冻结快照(调用方后续原地改写不影响已声明内容——ref 不变即声明未变)。 */
799
+ declareProviderInstances(provider: string, instances: readonly DeploymentInstance[]): void;
800
+ /** 当前声明快照(COW 冻结拷贝;无声明 = 共享冻结空记录常量)。域装配惰性融合消费——
801
+ * 快照引用变更即「声明发生变化」信号(调用方据此失效投影缓存)。 */
802
+ providerInstanceDeclarations(): ProviderInstanceDeclarations;
803
+ /** 诊断快照(doctor/调试用) */
804
+ listAdapters(): readonly string[];
805
+ /**
806
+ * 原始装载产物(W1-④ 中立通道):zod 解析产物 + 源定位原样透传——
807
+ * 装配消费(app-config modules 资源节自动装配;域装配投影如 mallControlPlaneOf(raw.config))。
808
+ * SDK 零域语义:不解释 config 内容,只透传。
809
+ */
810
+ readonly raw: IntegrationsRaw;
811
+ }
812
+ /** integrations 原始装载产物(raw 通道形状)。 */
813
+ interface IntegrationsRaw {
814
+ /** zod 解析产物(域投影/资源节消费;占位展开已完成) */
815
+ readonly config: IntegrationsConfig;
816
+ /** 配置源路径(同源旅行锚:dirname 派生台账目录等;直构缺省 undefined) */
817
+ readonly source?: string;
818
+ }
819
+ interface IntegrationsRegistryOptions {
820
+ integrations: IntegrationsConfig;
821
+ catalog: ProviderCatalog;
822
+ authStrategies: AuthStrategyRegistry;
823
+ secretProvider: EnvironmentSecretProvider;
824
+ /** transport 工厂注入(缺省经 authStrategies + secretProvider 构造 authenticated 工厂) */
825
+ transportFactory?: TransportFactory;
826
+ /** instanceId 提取器(缺省 stableSerializeScope;mall 场景模板层注入 (scope) => scope.mallId) */
827
+ instanceIdOf?: (scope: Record<string, string>) => string;
828
+ /** 日志器(缺省静默;在场时 factory 收到的 transport 包 withCallLog 外部调用观测) */
829
+ logger?: TboxLogger;
830
+ /** 配置源路径(W1-④ raw 通道:装配消费如 app-config 台账目录派生;缺省 undefined) */
831
+ source?: string;
832
+ /**
833
+ * v6 服务归属表(service → moduleId;buildOwnershipMap 产物——装配期显式注入)。
834
+ * 缺席 = 无模块层语义(≡ v5 文件形态;文件含 modules 级绑定/配置时 resolveEffectiveService
835
+ * 显式 fail-visible,不静默跳过)。服务无主 → 级联跳过 modules 层(平台槽语义)。
836
+ */
837
+ ownerOf?: Record<string, string>;
838
+ }
839
+ declare function createIntegrationsRegistry(opts: IntegrationsRegistryOptions): IntegrationsRegistry;
840
+
841
+ /**
842
+ * Scope 会话注册表(011 F2/F3/F5):
843
+ * 会话 id 生成 + scope 键绑定 + 请求匹配护栏。
844
+ *
845
+ * SDK 参数化(011 B3):extractScopeKey/validateScope 由装配层注入
846
+ * (mall 场景经 contracts-mall createMallRuntimeAssembly),本文件零领域语义。
847
+ *
848
+ * 实现说明:连接级短命状态(TTL 30min,重启即连接全断),
849
+ * 自持同步内存 Map + 可注入时钟(测试用);不做跨实例共享(多副本场景等真实需求)。
850
+ */
851
+
852
+ interface ScopeSession {
853
+ sessionId: string;
854
+ /** scope 键(extractScopeKey 产物,如 mallId) */
855
+ scopeKey: string;
856
+ /** 完整 attributes 快照(审计用) */
857
+ scope: Record<string, unknown>;
858
+ /** 011 D1:领域扁平 scope(HelloAck 回显 + ActionGrant 签发/校验的单一来源) */
859
+ scopeFlat: Record<string, string>;
860
+ createdAt: number;
861
+ expiresAt: number;
862
+ }
863
+ interface ScopeSessionRegistry {
864
+ /** HELLO 后引导会话:校验 scope → 生成 sessionId → 绑定 */
865
+ bootstrap(ctx: RequestContext): ScopeSession;
866
+ /** 按 sessionId 读取(过期返回 null) */
867
+ get(sessionId: string): Readonly<ScopeSession> | null;
868
+ /** 断言当前会话:sessionId 不存在 / scopeKey 不匹配 → 抛错(WS 层转「会话已失效」) */
869
+ assertCurrent(sessionId: string, scopeKey: string): Readonly<ScopeSession>;
870
+ /** 测试/运维辅助:过期条目清理 */
871
+ sweep(): void;
872
+ }
873
+ interface ScopeSessionRegistryOptions {
874
+ /** scope 键提取(如 mallId);缺失 → 抛错 */
875
+ extractScopeKey(ctx: RequestContext): string;
876
+ /** scope 白名单校验(接收 ctx.attributes 原样;注入方自行解析,如 parseMallScope) */
877
+ validateScope(attributes: Record<string, unknown>): boolean;
878
+ /** 011 D1:领域扁平 scope 构建(如 { miniAppId, mallId };回显 + grant 校验单一来源) */
879
+ buildScope(attributes: Record<string, unknown>): Record<string, string>;
880
+ /** 会话 TTL(缺省 30min) */
881
+ ttlMs?: number;
882
+ /** 时钟注入(测试用) */
883
+ now?: () => number;
884
+ }
885
+ declare class ScopeSessionError extends Error {
886
+ readonly code: 'SCOPE_INVALID' | 'SESSION_NOT_FOUND' | 'SESSION_SCOPE_MISMATCH';
887
+ constructor(message: string, code: 'SCOPE_INVALID' | 'SESSION_NOT_FOUND' | 'SESSION_SCOPE_MISMATCH');
888
+ }
889
+ declare function createScopeSessionRegistry(opts: ScopeSessionRegistryOptions): ScopeSessionRegistry;
890
+
891
+ interface ActionGrantService {
892
+ issue(input: {
893
+ moduleId: string;
894
+ actionId: string;
895
+ cardType: string;
896
+ /** 目标卡实例 id(P0 原地更新授权锚定:token 只能作用于该卡;hidden 回调签发缺省) */
897
+ cardId?: string;
898
+ sessionId: string;
899
+ scope: Record<string, string>;
900
+ input?: unknown;
901
+ singleUse?: boolean;
902
+ ttlMs?: number;
903
+ }): Promise<string>;
904
+ authorize(token: string, expected: {
905
+ actionId: string;
906
+ sessionId: string;
907
+ scope: Record<string, string>;
908
+ /** 期望目标卡实例 id(P0:undefined 表示签发时未锚定——hidden 回调路径) */
909
+ cardId?: string;
910
+ }): Promise<Readonly<GrantRecord>>;
911
+ /** 失败(execute 抛错)后恢复 single-use 令牌(业务可重试) */
912
+ restore(token: string): Promise<void>;
913
+ }
914
+ interface GrantRecord {
915
+ /** 011 I5 修复:grant 唯一 id(同参数重签互不覆盖消费标记) */
916
+ grantId: string;
917
+ moduleId: string;
918
+ actionId: string;
919
+ cardType: string;
920
+ /** 目标卡实例 id(P0 原地更新授权锚定;进 HMAC 规范串防篡改) */
921
+ cardId?: string;
922
+ sessionId: string;
923
+ scope: Record<string, string>;
924
+ input?: unknown;
925
+ singleUse: boolean;
926
+ expiresAt: number;
927
+ }
928
+ declare class ActionGrantError extends Error {
929
+ readonly code: 'TOKEN_INVALID' | 'TOKEN_EXPIRED' | 'GRANT_MISMATCH' | 'TOKEN_CONSUMED';
930
+ constructor(code: 'TOKEN_INVALID' | 'TOKEN_EXPIRED' | 'GRANT_MISMATCH' | 'TOKEN_CONSUMED', message: string);
931
+ }
932
+ declare const ACTION_GRANT_MAX_TTL_MS: number;
933
+ interface ActionGrantOptions {
934
+ store: ComponentStateStore;
935
+ /** 主密钥(≥32 字节;缺省走统一密钥链:ACTION_TOKEN_SECRET → AUTH_TOKEN_SECRET → TBOX_API_KEY → dev 随机) */
936
+ secret?: Uint8Array;
937
+ now?: () => number;
938
+ }
939
+ declare function deriveActionGrantKey(secret: Uint8Array): Uint8Array;
940
+ declare function createActionGrantService(opts: ActionGrantOptions): ActionGrantService;
941
+
942
+ /**
943
+ * 宿主效果运行时(011 E5/E6;015 P3 纯化):
944
+ * - 类型封闭集合 + navigation 白名单;协议单源 import 自 contracts(015 P1)
945
+ * - 纯投影:效果 → tbox:effect CUSTOM 事件下行,无宿主处理器(011 占位 handler 已删,015 G1)
946
+ * - payment/authorization 回调补签在 dispatcher step7(component-action.ts,015 P2)
947
+ * 无 custom 槽位(011 I14)——新效果类型须走提案扩展 contracts 联合。
948
+ */
949
+
950
+ interface EffectRuntime {
951
+ /** 动作结果 → 宿主效果事件(纯函数:白名单/形状校验 + 下行投影,无副作用) */
952
+ project(result: {
953
+ effects?: unknown[];
954
+ }): ServerEvent[];
955
+ }
956
+ interface EffectRuntimeOptions {
957
+ /** navigation 路由白名单(模块注册集合;015:本期零发射者,协议词汇保留) */
958
+ routeWhitelist?: ReadonlySet<string>;
959
+ }
960
+ declare class EffectError extends Error {
961
+ constructor(message: string);
962
+ }
963
+ declare function createEffectRuntime(opts?: EffectRuntimeOptions): EffectRuntime;
964
+
965
+ /**
966
+ * 模块动作域错误类型(单点定义):component-action 与 notice-text 双向消费,
967
+ * 独立成文件避免循环导入(notice-text 的错误文案映射需要 instanceof 判别)。
968
+ */
969
+ declare class ModuleActionError extends Error {
970
+ readonly code: 'ACTION_NOT_FOUND' | 'SESSION_INVALID' | 'GRANT_INVALID' | 'INPUT_INVALID' | 'RESULT_INVALID' | 'CALLBACK_INVALID';
971
+ constructor(code: 'ACTION_NOT_FOUND' | 'SESSION_INVALID' | 'GRANT_INVALID' | 'INPUT_INVALID' | 'RESULT_INVALID' | 'CALLBACK_INVALID', message: string);
972
+ }
973
+
974
+ interface RegisteredModuleAction {
975
+ actionId: string;
976
+ moduleId: string;
977
+ /** 声明此动作的卡片类型(dispatch 时核对授权记录的 cardType) */
978
+ cardType: string;
979
+ /** 按钮文案(payload.actions[].label) */
980
+ label?: string;
981
+ /** 按钮呈现(P1:kind/style/enabled 等透传 payload.actions;缺省 kind=moduleAction) */
982
+ kind?: 'moduleAction' | 'sendMessage' | 'openLink';
983
+ value?: string;
984
+ visible?: boolean;
985
+ url?: string;
986
+ style?: 'primary' | 'secondary' | 'link';
987
+ enabled?: boolean;
988
+ disabledReason?: string;
989
+ /** 效果回调动作(015 P5):不进按钮条;grant 由 dispatcher 补签 */
990
+ hidden?: boolean;
991
+ inputSchema?: z.ZodTypeAny;
992
+ singleUse?: boolean;
993
+ /**
994
+ * 服务端执行体。moduleAction 动作必填(register 断言拦截缺失);
995
+ * 纯客户端 kind(sendMessage/openLink)按钮点击不进 dispatch(客户端本地语义),
996
+ * execute 可省——类型正解替代 unreachable stub。
997
+ */
998
+ execute?(input: unknown, ctx: RequestContext): Promise<CardActionResult>;
999
+ }
1000
+ interface ModuleActionDispatcher {
1001
+ register(action: RegisteredModuleAction): void;
1002
+ get(actionId: string): Readonly<RegisteredModuleAction> | undefined;
1003
+ dispatch(input: {
1004
+ token: string;
1005
+ actionId: string;
1006
+ /** WS 连接绑定的 scope 会话 id(HELLO bootstrap 产物) */
1007
+ sessionId: string;
1008
+ /** 动作来源卡实例 id(P0 原地更新目标;host-effect 回传缺省 '') */
1009
+ surfaceId?: string;
1010
+ ctx: RequestContext;
1011
+ formData?: unknown;
1012
+ emit: (event: ServerEvent) => void;
1013
+ }): Promise<CardActionResult>;
1014
+ }
1015
+ interface ModuleActionDispatcherOptions {
1016
+ grants: ActionGrantService;
1017
+ sessions: ScopeSessionRegistry;
1018
+ state: ComponentStateStore;
1019
+ effects: EffectRuntime;
1020
+ /** 卡片动作注册表(011 B3:结果卡签发 token 用) */
1021
+ actions: CardActionRegistry;
1022
+ /** 卡片 meta 注册表(CardEmitter 校验 schema 用) */
1023
+ cardRegistry: Record<string, _tbox_cn_app_contracts.CardMeta>;
1024
+ /** scope 键提取(与 sessions 同源注入,如 mallId) */
1025
+ extractScopeKey(ctx: RequestContext): string;
1026
+ }
1027
+ declare function createModuleActionDispatcher(opts: ModuleActionDispatcherOptions): ModuleActionDispatcher;
1028
+
1029
+ /**
1030
+ * 域装配注册表(单一模板统一化 W1-③):域模块 register 期注册、消费点运行期惰性查表。
1031
+ *
1032
+ * 消费点(全部运行期查表——register 顺序无关:registerAll 先于 listen;
1033
+ * authExchanges 同款「晚于构造仍生效」先例):
1034
+ * - SDK ctx.scopeDefaults 读取视图(scopeAssembly().scopeDefaults——SDK 唯一直接消费面);
1035
+ * - 模板装配点:validateContext / scopeSessions / instanceIdOf 等由域装配消费方按
1036
+ * TIER1 具体形状(如 contracts-mall 装配组合)resolve 读取。
1037
+ *
1038
+ * SDK 零域语义:本注册表不 import 任何 TIER1;kind 词汇经 TIER0 contracts
1039
+ * (SCOPE_ASSEMBLY_KIND)。
1040
+ */
1041
+
1042
+ declare class DomainAssemblyRegistry {
1043
+ private assemblies;
1044
+ register(kind: string, assembly: unknown): void;
1045
+ resolve<T = unknown>(kind: string): T | undefined;
1046
+ /** scope-assembly 便捷读取(ctx.scopeDefaults 视图消费;缺失 → undefined)。 */
1047
+ scopeAssembly(): ScopeAssemblyContract | undefined;
1048
+ get size(): number;
1049
+ }
1050
+
1051
+ interface FlowStateStore {
1052
+ get<T>(sessionId: string, key: string): T | undefined;
1053
+ set(sessionId: string, key: string, value: unknown): void;
1054
+ clear(sessionId: string): void;
1055
+ }
1056
+ /**
1057
+ * 卡片动作注册表(011 E7:模块声明式 CardAction 收集处)。
1058
+ * 装配端把 cardActions.getAll() 交给 ModuleActionDispatcher + 卡片出卡时签发 token。
1059
+ */
1060
+ interface CardActionRegistry {
1061
+ register(action: RegisteredModuleAction): void;
1062
+ get(actionId: string): Readonly<RegisteredModuleAction> | undefined;
1063
+ getAll(): ReadonlyMap<string, RegisteredModuleAction>;
1064
+ }
1065
+ /**
1066
+ * ServerContext:模块 registerServer(ctx) / Handler.handle(ctx) 共用的上下文。
1067
+ *
1068
+ * 注册期(registerServer 内):只能 register / registerService / bus.subscribe / 路由挂载,
1069
+ * 不得 resolveService(doctor 注册期纯净规则)。
1070
+ * 运行期(handle / 事件回调内):可 resolveService、读 flowStates;运行身份经显式
1071
+ * 通道(handle 第四参 reqCtx / 工具 execute 第二参读取器——上下文统一化 0.11.0)。
1072
+ */
1073
+ interface ServerContext {
1074
+ /** Handler 注册表(无状态路由) */
1075
+ handlers: HandlerRegistry;
1076
+ /** LLM function calling 工具注册表 */
1077
+ tools: ToolRegistry;
1078
+ /** 卡片元数据注册表(cardType → CardMeta) */
1079
+ cards: CardRegistry;
1080
+ /** 本地 skill 注册表(009:模块声明式主通道,build-engine 合并进 ChatEngine) */
1081
+ skills: SkillRegistry;
1082
+ /** 前置工具声明注册表(010:模块声明式主通道,build-engine 合并进 ChatEngine) */
1083
+ preTools: PreToolRegistry;
1084
+ /** HTTP API 路由注册表(/api/m/<moduleId>/) */
1085
+ routes: ApiRouteRegistry;
1086
+ /** Service 注册表(Port 接口实现) */
1087
+ services: ServiceRegistry;
1088
+ /** 类型化事件总线(跨模块异步通知) */
1089
+ bus: TypedBus<EventMap>;
1090
+ /** 卡片快照存储 */
1091
+ snapshotStore: CardSnapshotStore;
1092
+ /** 业务动作网关(004 D3/C2):registerAction(action, handler, policy);组装端一次挂载 POST /api/action */
1093
+ actions: ActionGateway;
1094
+ /** 结构类型子集接口查找(= services.resolve;参数 = 服务 id——v7 词汇统一) */
1095
+ resolveService<T>(id: string): T | undefined;
1096
+ /** 业务自管的分会话状态(ALS DeviceContext 简化版) */
1097
+ flowStates: FlowStateStore;
1098
+ /** 组件状态存储基元(011 H1):CAS/TTL/consume;默认内存单实例边界 */
1099
+ state: ComponentStateStore;
1100
+ /**
1101
+ * Agent 长期记忆存储(017,可选装配)。应用引擎与业务模块共享同一实例,模块仅在运行期
1102
+ * 按可信身份与 scope 读写;未装配或 memory-off 时为 undefined。
1103
+ */
1104
+ memory?: MemoryStore;
1105
+ /** 卡片写动作注册表(011 E7):模块 CardAction 声明收集 */
1106
+ cardActions: CardActionRegistry;
1107
+ /** 011 B2:Provider 认证策略注册表(模块 register 期注册;与 transportFactory 同引用) */
1108
+ authStrategies: AuthStrategyRegistry;
1109
+ /**
1110
+ * 换码器注册表(provider 拆包 F0 惰性查找):模块/provider register 期注册登录换码器
1111
+ * (key = exchange.provider,如 alipay)。模板装配应传 authRuntime.exchanges 同引用——
1112
+ * 缺省独立空注册表(直构 ctx 不炸,但注册不达登录路由)。
1113
+ */
1114
+ authExchanges: AuthExchangeRegistry;
1115
+ /**
1116
+ * 域事实中立注入件读取视图(F2 模板中立化;W1-③ getter 化):域装配注册表
1117
+ * (scope-assembly.scopeDefaults)惰性读取优先,装配 opts.scopeDefaults 静态回落。
1118
+ * provider 包经 getter 登录期求值读取(register 期零读——域模块注册晚于 provider
1119
+ * register 仍生效,F1 反例修复);缺省空视图(读取 undefined)。
1120
+ */
1121
+ scopeDefaults?: Readonly<Record<string, unknown>>;
1122
+ /**
1123
+ * 域装配注册表(W1-③):域模块 register 期注册(如
1124
+ * `ctx.domainAssemblies.register(SCOPE_ASSEMBLY_KIND, assembly)`),消费点运行期
1125
+ * 惰性查表(register 顺序无关)。SDK 只消费 scopeDefaults 成员(scopeDefaults 视图);
1126
+ * 其余成员由模板装配点按 TIER1 形状读取。
1127
+ */
1128
+ domainAssemblies: DomainAssemblyRegistry;
1129
+ /**
1130
+ * Integrations 注册表(provider 拆包 F2 槽位解析轴):provider 包 register 期注册 adapter
1131
+ * (ctx.integrations.registerAdapter),模块 ports 运行期 resolveService({service, scope, request})。
1132
+ * 模板装配应传 createIntegrationsRegistry 产物同引用;缺省 undefined(探测链回退——旧链路兼容)。
1133
+ */
1134
+ integrations?: IntegrationsRegistry;
1135
+ /**
1136
+ * 模块日志器(registerServerModules 逐模块注入,tag=module:<moduleId>;可选——
1137
+ * 旧 SDK 混装/直构 ctx 时缺省,模块侧用可选链 ctx.logger?.warn(...))。
1138
+ * 规范见 docs/reference/modules.md「模块日志规范」:只经 register 期 ctx 闭包获取,禁顶层 createLogger。
1139
+ */
1140
+ logger?: ServerLogger;
1141
+ }
1142
+ /**
1143
+ * 模块注册函数签名:模块包 server 入口 export 的 registerServer(兼容老形态)。
1144
+ */
1145
+ type ModuleServerRegister = (ctx: ServerContext) => void | Promise<void>;
1146
+ /**
1147
+ * 模块描述对象(服务端):模块包 server 入口 export 的 serverModule。
1148
+ *
1149
+ * - cards:卡片 meta 声明 map(key 约定 = meta.cardType;数据 + 类型源,
1150
+ * 供 `InferModuleCards` 从装配数组自动推导 app 端 CardType)。
1151
+ * - register(ctx):注册期自注册(tools/cards/handlers/services/bus/路由/事件),
1152
+ * 只注册不解析(resolveService 仅 handle/事件回调内调用)。
1153
+ *
1154
+ * 与客户端 `ClientModule` 逐行对称;组装端遍历 modules 调 register(ctx)。
1155
+ * register 为函数签名声明:method shorthand 经 `satisfies` 检查(TS 方法 bivariance——
1156
+ * 放行比契约更窄的参数,运行时无危害;缺字段的过宽参数会被拦截)。
1157
+ * cards 为必填属性:无卡片模块写 `cards: {}`(keyof = never,不污染装配类型)。
1158
+ */
1159
+ interface ServerModule<C extends Record<string, CardMeta> = Record<string, CardMeta>> {
1160
+ cards: C;
1161
+ /**
1162
+ * 模块声明(011 K:moduleId;014 起能力门控移除——能力 = 模块 add/remove,代码即事实)。
1163
+ */
1164
+ declaration?: {
1165
+ moduleId: string;
1166
+ };
1167
+ /**
1168
+ * 模块 skill 声明(009 D6,与 cards 对齐):key 约定 = skill.name(纯数据,零 mastra 依赖)。
1169
+ * 装配端 registerAll 自动注册(ctx.skills.registerAll),register 内无需代码;
1170
+ * 命令式 ctx.skills.register(...) 兜底。
1171
+ */
1172
+ skills?: Record<string, LocalSkill>;
1173
+ /**
1174
+ * 模块前置工具声明(010,与 skills/cards 对齐):key 约定 = tool.id(纯数据 + 一个 decide 函数,
1175
+ * 零 mastra 依赖)。装配端 registerServerModules 自动注册,register 内无需代码。
1176
+ * 铁律:仅只读/幂等工具;tool 引用工具实例(单一真源);decide 决策即构造
1177
+ * ({ decision:'run', args } = 预执行 / { decision:'skip' } = 不生效)、不得抛、
1178
+ * args 必须 JSON 可序列化;身份经入参 identity 显式获取(per-run 并发安全)。
1179
+ */
1180
+ preTools?: Record<string, PreToolDef>;
1181
+ register: (ctx: ServerContext) => void | Promise<void>;
1182
+ }
1183
+ /**
1184
+ * 创建 ServerContext(组装端调用一次)。
1185
+ * 注入件(011 S2):state(缺省 memory)。
1186
+ */
1187
+ declare function createServerContext(opts?: {
1188
+ snapshotStore?: CardSnapshotStore;
1189
+ idempotencyStore?: IdempotencyStore;
1190
+ state?: ComponentStateStore;
1191
+ /** Agent 长期记忆存储;应与 createEngineFromContext 的 memory.store 传入同一实例 */
1192
+ memory?: MemoryStore;
1193
+ authStrategies?: AuthStrategyRegistry;
1194
+ /** 换码器注册表(模板装配传 authRuntime.exchanges 同引用;缺省独立空注册表) */
1195
+ authExchanges?: AuthExchangeRegistry;
1196
+ /** 域事实中立注入件(F2):控制面域默认值(如 { defaultMallId });缺省 undefined */
1197
+ scopeDefaults?: Readonly<Record<string, unknown>>;
1198
+ /** Integrations 注册表(模板装配传 createIntegrationsRegistry 产物;缺省 undefined 探测链回退) */
1199
+ integrations?: IntegrationsRegistry;
1200
+ }): ServerContext;
1201
+
1202
+ /**
1203
+ * Handler:平台统一执行单元(001 §3.2)。
1204
+ * 平台不区分"Service Flow"和"Agent Skill",业务以 Handler 形式注册,
1205
+ * 由 HandlerRegistry.dispatch 无状态路由到 handle。
1206
+ */
1207
+ interface HandlerResult {
1208
+ cards: CardEmit[];
1209
+ text?: string;
1210
+ /**
1211
+ * 确定性 handler 完成写操作后,继续进入本轮完整 Agent 流程。
1212
+ * content 仅作为服务端续问进入模型上下文;用户消息与持久化 query 仍保留原始输入。
1213
+ * text 为即时回显文案:进前端事件流与 answer 落库(显示一致性),不进 LLM 上下文
1214
+ * (方案 B,2026-09-02——非 LLM token 入 history 会破坏前缀缓存)。
1215
+ */
1216
+ continueWith?: {
1217
+ content: string;
1218
+ };
1219
+ }
1220
+ interface CardEmit {
1221
+ cardType: string;
1222
+ data: Record<string, unknown>;
1223
+ messageId?: string;
1224
+ id?: string;
1225
+ }
1226
+ interface HandlerDefinition {
1227
+ /** 业务唯一标识,如 "rental" / "purchase" / "points-parking" */
1228
+ id: string;
1229
+ /**
1230
+ * 意图声明(011 D7/D8:意图与处理器同处定义)。
1231
+ * 装配端从注册 handlers 收集构造 intentRoutes(chat 先 matchIntent——确定性档
1232
+ * exact/prefix 优先,BM25 语义档兜底;缺省零 LLM,continueWith 可续接 Agent;
1233
+ * match:'exact' 整句全等 / 'prefix' 模板句头前缀(均不入 BM25 词袋);
1234
+ * **顶层意图声明只允许确定性档(exact/prefix)**——BM25 语义分类职责归 skill 路由与
1235
+ * LLM 工具编排(单标签硬短路截断复合句),缺省 bm25 为 legacy 装配期 warn;
1236
+ * 重叠 = doctor warning,不阻断)。
1237
+ */
1238
+ intents?: {
1239
+ patterns: string[];
1240
+ match?: 'exact' | 'prefix' | 'bm25';
1241
+ }[];
1242
+ /**
1243
+ * 处理 action,返回要下发的卡片 / 文字。
1244
+ * @param reqCtx 运行上下文(上下文统一化 Stage 1:chat-engine run 内分发时传入;
1245
+ * 意图路径身份/凭据/attributes 的显式来源——替代旧 ctx.auth 全局读取)。
1246
+ */
1247
+ handle(action: string, payload: unknown, ctx: ServerContext, reqCtx?: RequestContext): Promise<HandlerResult>;
1248
+ }
1249
+ /** 从已注册 handlers 收集意图路由(011 D7:装配端调用;match 透传——exact/prefix 走洋葱确定性档) */
1250
+ declare function collectIntentRoutes(handlers: ReadonlyMap<string, HandlerDefinition> | Record<string, HandlerDefinition>): {
1251
+ id: string;
1252
+ keywords: string[];
1253
+ handlerId: string;
1254
+ action: string;
1255
+ match?: 'exact' | 'prefix' | 'bm25';
1256
+ }[];
1257
+ /**
1258
+ * HandlerRegistry:无状态路由表(001 §3.4)。
1259
+ * - 无实例池 / 无 sessionId 参数 / 无 createInstance / destroy —— 状态归业务(ctx.flowStates)
1260
+ */
1261
+ declare class HandlerRegistry {
1262
+ private handlers;
1263
+ register(def: HandlerDefinition): void;
1264
+ resolve(id: string): HandlerDefinition | undefined;
1265
+ getAll(): Record<string, HandlerDefinition>;
1266
+ has(id: string): boolean;
1267
+ get size(): number;
1268
+ dispatch(handlerId: string, action: string, payload: unknown, ctx: ServerContext, reqCtx?: RequestContext): Promise<HandlerResult>;
1269
+ }
1270
+
1271
+ interface EmitCardSpec {
1272
+ cardType: string;
1273
+ data: Record<string, unknown>;
1274
+ /** 目标会话(006 D5:conversationId 唯一会话键) */
1275
+ conversationId: string;
1276
+ messageId?: string;
1277
+ id?: string;
1278
+ }
1279
+ /**
1280
+ * CardEmitter:卡片下发机制(001 §2.4 / 003 §4.2 独立化)。
1281
+ * - emit:按 CardRegistry 校验 data schema 后下发 CUSTOM('tbox:card') 事件;
1282
+ * 填充 schemaVersion + meta.createdAt(P3 W1,供快照持久化与迁移使用)。
1283
+ * - 返回下发后的 TboxCardPayload(含填充字段),chat-engine 据此写入本轮 run 的卡片缓冲
1284
+ * (004 W1:写入缓冲而非即时落库)。
1285
+ */
1286
+ declare class CardEmitter {
1287
+ private cardRegistry;
1288
+ constructor(cardRegistry: Record<string, CardMeta>);
1289
+ emit(spec: EmitCardSpec, onEvent: (event: ServerEvent) => void): TboxCardPayload | undefined;
1290
+ /** 011 B3:两段式——只校验 + 构造 payload(不发送);token 签发等预处理后经 send 下发 */
1291
+ build(spec: EmitCardSpec): TboxCardPayload | undefined;
1292
+ /** 发送 CUSTOM('tbox:card') 事件(build 产物;dispatcher 直发同用) */
1293
+ send(payload: TboxCardPayload, onEvent: (event: ServerEvent) => void): TboxCardPayload;
1294
+ }
1295
+
1296
+ /**
1297
+ * 防重放存储(004 W2 C3)。
1298
+ * 接口化 + InMemory LRU(TTL + 上限),可换 Redis。
1299
+ * 语义:时间窗内同一 key 的重复请求视为重放。
1300
+ */
1301
+ interface ReplayStore {
1302
+ /** 记录 key(TTL 窗口内有效),窗口内重复返回 true */
1303
+ checkAndSet(key: string, ttlMs?: number): Promise<boolean>;
1304
+ }
1305
+ /** InMemory LRU:Map 迭代序即插入序(近似 LRU),超过上限时淘汰最旧 */
1306
+ declare class InMemoryLruReplayStore implements ReplayStore {
1307
+ private store;
1308
+ private readonly ttlMs;
1309
+ private readonly maxEntries;
1310
+ constructor(opts?: {
1311
+ ttlMs?: number;
1312
+ maxEntries?: number;
1313
+ });
1314
+ checkAndSet(key: string, ttlMs?: number): Promise<boolean>;
1315
+ private evict;
1316
+ clear(): void;
1317
+ }
1318
+
1319
+ /**
1320
+ * 服务端模块装配框架(010 下沉 S1):遍历模块 + 声明式字段自动注册 + register。
1321
+ * - skills(009)/ preTools(010)声明式字段在此自动注册,模块 register 内无需代码;
1322
+ * - 未来新增声明式字段只在此处加一行,模板装配零改动;
1323
+ * - `await m.register(ctx)`:模块 register 可为 async——模板旧装配为 sync 循环不等待
1324
+ * (隐性缺陷),下沉时顺带修正(sync 模块行为不变)。
1325
+ * - 模块级 logger 注入:每模块浅拷贝 ctx(注册表共享引用不变)挂 logger
1326
+ * (tag=module:<moduleId>);模块闭包捕获即获 tag + req/conv 关联(对象注入
1327
+ * 免疫多 SDK 副本,模块不 import SDK 单例——与"禁 import SDK 全局单例"铁律一致)。
1328
+ * - app-config 自动装配(W1-④):模块资源消费入口无条件注册(与控制面正交——防无控制面
1329
+ * 启动静默丢失;参数经 ctx.integrations.raw 派生:modules 资源节 + 源目录台账锚,
1330
+ * registry 缺席 → 空资源零 IO)。显式注册优先(过渡期模板自注册在位不拆)。
1331
+ */
1332
+ declare function registerServerModules(ctx: ServerContext, modules: readonly ServerModule[]): Promise<void>;
1333
+
1334
+ /** 服务端统一响应封装 */
1335
+ interface SdkResponse<T = unknown> {
1336
+ /** 是否成功 */
1337
+ success: boolean;
1338
+ /** 响应数据 */
1339
+ data?: T;
1340
+ /** 错误码 */
1341
+ errorCode?: string;
1342
+ /** 错误信息 */
1343
+ errorMsg?: string;
1344
+ /** 链路追踪 ID */
1345
+ traceId?: string;
1346
+ }
1347
+ /** C端 Session 鉴权信息(generateSession 获取) */
1348
+ interface SessionAuth {
1349
+ /** 会话 ID(通过 generateSession 获取) */
1350
+ sessionId: string;
1351
+ /** 登录渠道(通过 generateSession 获取) */
1352
+ channel: string;
1353
+ /** 百宝箱应用 ID */
1354
+ appId: string;
1355
+ }
1356
+ /** C端客户端配置(通过 Session 鉴权) */
1357
+ interface TboxSessionClientConfig {
1358
+ /** C端 Session 鉴权信息 */
1359
+ session: SessionAuth;
1360
+ /** 自定义 base URL(可选,默认 TBOX_BASE_URL) */
1361
+ baseUrl?: string;
1362
+ /** 请求超时时间(毫秒,可选) */
1363
+ timeout?: number;
1364
+ }
1365
+ /** B端客户端配置(通过 apiKey 鉴权) */
1366
+ interface TboxApiKeyClientConfig {
1367
+ /** API Key(通过 Authorization 头传递) */
1368
+ apiKey: string;
1369
+ /** 自定义 base URL(可选,默认 TBOX_BASE_URL) */
1370
+ baseUrl?: string;
1371
+ /** 请求超时时间(毫秒,可选) */
1372
+ timeout?: number;
1373
+ }
1374
+ /** 用户信息条目(key-value 形式) */
1375
+ interface UserInfo {
1376
+ /** 信息类型,枚举值如:name、phone、email 等 */
1377
+ infoType: string;
1378
+ /** 信息值 */
1379
+ infoValue: string;
1380
+ }
1381
+ /** 设备信息 */
1382
+ interface DeviceInfo {
1383
+ productType?: string;
1384
+ appName?: string;
1385
+ appVersion?: string;
1386
+ platform?: string;
1387
+ system?: string;
1388
+ deviceId?: string;
1389
+ deviceName?: string;
1390
+ deviceModel?: string;
1391
+ deviceBrand?: string;
1392
+ }
1393
+ /** 生成 Session 请求 */
1394
+ interface AppGenerateSessionRequest {
1395
+ /** 百宝箱应用 ID */
1396
+ appId: string;
1397
+ /** 用户 ID */
1398
+ userId: string;
1399
+ /** 请求来源(可选) */
1400
+ source?: string;
1401
+ /** 发布渠道(可选) */
1402
+ fromSource?: string;
1403
+ /** 请求的链接类型(可选) */
1404
+ type?: string;
1405
+ /** 用户信息列表(可选) */
1406
+ userInfo?: UserInfo[];
1407
+ /** 设备信息(可选) */
1408
+ deviceInfo?: DeviceInfo;
1409
+ }
1410
+ /** 生成 Session 响应 */
1411
+ interface AppSessionResult {
1412
+ /** 会话 ID,用于免登录访问百宝箱应用 */
1413
+ sessionId?: string;
1414
+ /** 登录渠道,固定值 third_platform_sdk_login */
1415
+ channel?: string;
1416
+ }
1417
+ /** 分页查询结果 */
1418
+ interface PaginationResult<T> {
1419
+ /** 数据列表(服务端字段名:data) */
1420
+ data?: T[];
1421
+ /** 总条数(服务端字段名:totalCount) */
1422
+ totalCount?: number;
1423
+ /** 当前页码(服务端字段名:currentPage) */
1424
+ currentPage?: number;
1425
+ /** 每页条数 */
1426
+ pageSize?: number;
1427
+ }
1428
+ /** 创建会话请求 */
1429
+ interface ConversationCreateRequest {
1430
+ /** 百宝箱应用 ID(agentId) */
1431
+ agentId: string;
1432
+ /** 用户 ID */
1433
+ userId: string;
1434
+ }
1435
+ /** 查询会话列表请求 */
1436
+ interface ConversationQueryRequest {
1437
+ agentId?: string;
1438
+ userId?: string;
1439
+ fromSource?: string;
1440
+ pageNum?: number;
1441
+ pageSize?: number;
1442
+ [key: string]: unknown;
1443
+ }
1444
+ /** 会话信息 */
1445
+ interface ConversationInfo {
1446
+ /** 会话 ID(服务端字段名:id) */
1447
+ id?: string;
1448
+ appId?: string;
1449
+ fromEndUserId?: string;
1450
+ fromSource?: string;
1451
+ gmtCreate?: string;
1452
+ [key: string]: unknown;
1453
+ }
1454
+ /** 查询消息列表请求 */
1455
+ interface MessageQueryRequest {
1456
+ conversationId?: string;
1457
+ /** 百宝箱应用 ID(必填,服务端校验非空) */
1458
+ agentId: string;
1459
+ userId?: string;
1460
+ fromSource?: string;
1461
+ beforeId?: string;
1462
+ pageNo?: number;
1463
+ pageSize?: number;
1464
+ }
1465
+ /** 消息信息 */
1466
+ interface MessageInfo {
1467
+ messageId?: string;
1468
+ conversationId?: string;
1469
+ query?: string;
1470
+ answer?: string;
1471
+ mediaType?: string;
1472
+ generateState?: string;
1473
+ outerBusinessId?: string;
1474
+ createTime?: number;
1475
+ [key: string]: unknown;
1476
+ }
1477
+ /** 保存会话消息请求 */
1478
+ interface MessageSaveRequest {
1479
+ /** 百宝箱应用 ID(必填,服务端鉴权需要) */
1480
+ agentId: string;
1481
+ /** 会话 ID */
1482
+ conversationId: string;
1483
+ query?: string;
1484
+ answer?: string;
1485
+ mediaType?: string;
1486
+ generateState?: string;
1487
+ outerBusinessId?: string;
1488
+ inputs?: Record<string, unknown>;
1489
+ multiModalInputs?: Record<string, unknown>;
1490
+ extraParams?: string;
1491
+ }
1492
+ /** C端语音识别请求 */
1493
+ interface AsrRecognizeRequest {
1494
+ /** Base64 编码的音频数据(必填) */
1495
+ base64_audio: string;
1496
+ /** 采样率,默认 '16000' */
1497
+ sample_rate?: string;
1498
+ /** 音频格式,默认 'webm' */
1499
+ audio_format?: string;
1500
+ }
1501
+ /** C端语音识别响应 */
1502
+ interface AsrRecognizeResponse {
1503
+ /** 识别出的文本 */
1504
+ text: string;
1505
+ }
1506
+ /** 文件类型 */
1507
+ type FileType = 'image' | 'video' | 'audio' | 'file';
1508
+ /** C端文件上传请求(POST /api/files/afts/upload,FormData) */
1509
+ interface FileUploadRequest {
1510
+ /** 文件 Blob 或 File 对象 */
1511
+ file: Blob | File;
1512
+ /** 文件类型 */
1513
+ fileType: FileType;
1514
+ /** 文件名(可选,默认 'upload') */
1515
+ fileName?: string;
1516
+ }
1517
+ /** C端文件上传响应 */
1518
+ interface FileUploadResponse {
1519
+ /** 上传后的文件 ID */
1520
+ fileId: string;
1521
+ /** 是否通过安全审核 */
1522
+ safed: boolean;
1523
+ }
1524
+ /** 反馈类型 */
1525
+ type FeedbackValue = 'LIKE' | 'DISLIKE' | 'CANCEL';
1526
+ /** C端反馈请求(POST /agent/v1/plugin/proxy) */
1527
+ interface FeedbackRequest {
1528
+ /** 消息请求 ID(来自对话事件的 chat_id) */
1529
+ requestId: string;
1530
+ /** 反馈类型 */
1531
+ feedback: FeedbackValue;
1532
+ }
1533
+ /** C端反馈响应 */
1534
+ interface FeedbackResponse {
1535
+ success: boolean;
1536
+ }
1537
+ /** TTS 语音/音频配置 */
1538
+ interface TtsVoiceConfig {
1539
+ /** 发音人代码,默认 'lingyue' */
1540
+ voiceCode?: string;
1541
+ /** 发音人类型,默认 'SYSTEM' */
1542
+ voiceType?: string;
1543
+ /** 采样率(Hz),默认 24000 */
1544
+ sampleRate?: number;
1545
+ /** 音量(0-100),默认 50 */
1546
+ volume?: number;
1547
+ /** 语速调节,默认 0 */
1548
+ speechRate?: number;
1549
+ /** 音调调节,默认 0 */
1550
+ pitchRate?: number;
1551
+ }
1552
+ /** TTS 鉴权结果(fetchAuth 返回 data) */
1553
+ interface TtsAuthResult {
1554
+ /** 服务端时间戳 */
1555
+ timestamp: string;
1556
+ /** HMAC 签名摘要 */
1557
+ digest: string;
1558
+ }
1559
+ /** TboxTtsClient 配置(TTS 鉴权走 C端 Session 体系) */
1560
+ interface TboxTtsClientConfig {
1561
+ /** 百宝箱应用 ID(对应 X-Tbox-AppId 请求头) */
1562
+ appId: string;
1563
+ /** TTS 服务的 appkey */
1564
+ appkey: string;
1565
+ /** TTS 鉴权接口完整 URL */
1566
+ authUrl: string;
1567
+ /** C端会话 ID(对应 TBOXSESSIONID 请求头) */
1568
+ sessionId?: string;
1569
+ /** 登录渠道(对应 X-Tbox-Channel 请求头) */
1570
+ channel?: string;
1571
+ /** 上游 TTS WebSocket 地址(可选,默认 wss://mediafeature.alipay.com:443/tts_stream) */
1572
+ upstreamUrl?: string;
1573
+ /** 自定义 base URL(可选,默认 TBOX_BASE_URL) */
1574
+ baseUrl?: string;
1575
+ /** 请求超时时间(毫秒,可选) */
1576
+ timeout?: number;
1577
+ }
1578
+ /** TboxTtsClient.create() 便捷工厂参数(B端 apiKey 自动获取 session) */
1579
+ interface CreateTtsClientOptions {
1580
+ /** B端 API Key(用于调用 generateSession) */
1581
+ apiKey: string;
1582
+ /** 百宝箱应用 ID */
1583
+ appId: string;
1584
+ /** 用户 ID */
1585
+ userId: string;
1586
+ /** TTS 服务的 appkey */
1587
+ appkey: string;
1588
+ /** TTS 鉴权接口完整 URL */
1589
+ authUrl: string;
1590
+ /** 登录渠道(可选,未提供时从 session 获取) */
1591
+ channel?: string;
1592
+ /** 上游 TTS WebSocket 地址(可选) */
1593
+ upstreamUrl?: string;
1594
+ /** 自定义 base URL(可选) */
1595
+ baseUrl?: string;
1596
+ /** 请求超时时间(毫秒,可选) */
1597
+ timeout?: number;
1598
+ }
1599
+
1600
+ /**
1601
+ * 百宝箱应用服务客户端(/openapi/v1/app)
1602
+ */
1603
+ declare class TboxAppClient {
1604
+ private http;
1605
+ constructor(config: TboxApiKeyClientConfig);
1606
+ /**
1607
+ * 根据用户信息生成 sessionId 和 channel
1608
+ * 接口:POST /openapi/v1/app/generate_session
1609
+ */
1610
+ generateSession(request: AppGenerateSessionRequest): Promise<SdkResponse<AppSessionResult>>;
1611
+ }
1612
+
1613
+ /**
1614
+ * 百宝箱会话管理客户端
1615
+ */
1616
+ declare class TboxConversationClient {
1617
+ private http;
1618
+ constructor(config: TboxApiKeyClientConfig);
1619
+ /** 创建新会话:POST /openapi/v1/conversation/create */
1620
+ createConversation(request: ConversationCreateRequest): Promise<SdkResponse<string>>;
1621
+ /** 查询会话列表(分页):POST /openapi/v1/conversation/list */
1622
+ listConversations(request: ConversationQueryRequest): Promise<SdkResponse<PaginationResult<ConversationInfo>>>;
1623
+ /** 查询消息列表(分页):POST /openapi/v1/conversation/message/list */
1624
+ listMessages(request: MessageQueryRequest): Promise<SdkResponse<PaginationResult<MessageInfo>>>;
1625
+ /** 新增会话消息:POST /openapi/v1/conversation/message/save */
1626
+ saveMessage(request: MessageSaveRequest): Promise<SdkResponse<string>>;
1627
+ }
1628
+
1629
+ /**
1630
+ * 百宝箱 C端文件上传客户端(/api/files/afts/upload;C端鉴权三头)
1631
+ */
1632
+ declare class TboxUploadClient {
1633
+ private http;
1634
+ /** 使用 C端 Session 鉴权构造 */
1635
+ constructor(config: TboxSessionClientConfig);
1636
+ /** C端文件上传:POST /api/files/afts/upload(FormData) */
1637
+ upload(request: FileUploadRequest): Promise<SdkResponse<FileUploadResponse>>;
1638
+ }
1639
+
1640
+ /** TTS 语音/音频默认配置 */
1641
+ declare const TTS_DEFAULTS: {
1642
+ readonly voiceCode: "lingyue";
1643
+ readonly voiceType: "SYSTEM";
1644
+ readonly sampleRate: 24000;
1645
+ readonly volume: 50;
1646
+ readonly speechRate: 0;
1647
+ readonly pitchRate: 0;
1648
+ };
1649
+ /**
1650
+ * 百宝箱 C端文字转语音客户端
1651
+ *
1652
+ * TTS 使用 WebSocket 与上游 Alipay TTS 服务通信,客户端负责:
1653
+ * 1. 鉴权(fetchAuth → timestamp + digest)
1654
+ * 2. 构建上游 WSS URL(带 HMAC 签名参数)
1655
+ * 3. 构建 WS 消息 payload(start / text / stop)
1656
+ *
1657
+ * WebSocket 连接本身由消费者管理。
1658
+ */
1659
+ declare class TboxTtsClient {
1660
+ appId: string;
1661
+ appkey: string;
1662
+ authUrl: string;
1663
+ sessionId?: string;
1664
+ channel?: string;
1665
+ upstreamUrl: string;
1666
+ timeout?: number;
1667
+ constructor(config: TboxTtsClientConfig);
1668
+ /** 便捷工厂方法:通过 B端 apiKey 自动获取 session,提取 channel 后构造 TTS 客户端 */
1669
+ static create(options: CreateTtsClientOptions): Promise<TboxTtsClient>;
1670
+ /**
1671
+ * 获取 TTS 鉴权信息(timestamp + digest),用于连接上游 WebSocket
1672
+ * POST {authUrl};Headers: TBOXSESSIONID + X-Tbox-Channel + X-Tbox-AppId;Body: { appkey }
1673
+ */
1674
+ fetchAuth(): Promise<SdkResponse<TtsAuthResult>>;
1675
+ /** 构建上游 TTS WebSocket URL(带 Alipay HMAC 签名参数) */
1676
+ buildUpstreamUrl(auth: TtsAuthResult): string;
1677
+ /** 构建上游 WS 初始化 payload(start action) */
1678
+ static buildPayload(voiceConfig?: TtsVoiceConfig): Record<string, unknown>;
1679
+ /** 构建发送文本的上游 payload(JSON 字符串,直接通过 WS 发送) */
1680
+ static buildTextPayload(text: string): string;
1681
+ /** 构建停止 TTS 流的上游 payload */
1682
+ static buildStopPayload(): string;
1683
+ /** 生成 32 位十六进制任务 ID */
1684
+ static generateTaskId(): string;
1685
+ }
1686
+
1687
+ /**
1688
+ * 百宝箱 C端语音识别客户端
1689
+ */
1690
+ declare class TboxAsrClient {
1691
+ private http;
1692
+ /** 使用 C端 Session 鉴权构造 */
1693
+ constructor(config: TboxSessionClientConfig);
1694
+ /**
1695
+ * C端语音识别(Base64 音频输入):POST /agent/v1/plugin/asrBase64
1696
+ */
1697
+ recognize(request: AsrRecognizeRequest): Promise<SdkResponse<AsrRecognizeResponse>>;
1698
+ }
1699
+
1700
+ /**
1701
+ * 百宝箱 C端反馈客户端(点赞/点踩/取消;/agent/v1/plugin/proxy;C端鉴权三头)
1702
+ */
1703
+ declare class TboxFeedbackClient {
1704
+ private http;
1705
+ /** 使用 C端 Session 鉴权构造 */
1706
+ constructor(config: TboxSessionClientConfig);
1707
+ /** 点赞/点踩/取消反馈:POST /agent/v1/plugin/proxy */
1708
+ addTag(request: FeedbackRequest): Promise<SdkResponse<FeedbackResponse>>;
1709
+ }
1710
+
1711
+ /** notice 文案上限(超长截断,防 toast 刷屏) */
1712
+ declare const NOTICE_TEXT_MAX_LEN = 200;
1713
+ /** 截断至上限(dispatcher text 补位与本文件错误映射共用单源) */
1714
+ declare function truncateNoticeText(text: string): string;
1715
+ declare function toNoticeText(err: unknown): TboxNoticePayload;
1716
+
1717
+ /**
1718
+ * 鉴权错误(006 错误码体系)。status 由 authCodeToStatus 映射。
1719
+ */
1720
+
1721
+ declare class AuthError extends Error {
1722
+ readonly code: AuthErrorCode;
1723
+ readonly status: number;
1724
+ constructor(code: AuthErrorCode, message?: string);
1725
+ static unauthorized(message?: string): AuthError;
1726
+ static tokenExpired(message?: string): AuthError;
1727
+ static forbidden(message?: string): AuthError;
1728
+ static methodRequired(message?: string): AuthError;
1729
+ static browserLoginDisabled(message?: string): AuthError;
1730
+ static externalError(message?: string): AuthError;
1731
+ static missingSecret(message?: string): AuthError;
1732
+ }
1733
+
1734
+ interface TokenServiceOptions {
1735
+ /** HS256 共享密钥(至少 32 字节;来自 AUTH_TOKEN_SECRET → TBOX_API_KEY → dev 临时) */
1736
+ secret: string;
1737
+ issuer?: string;
1738
+ ttlMs?: number;
1739
+ clockToleranceSec?: number;
1740
+ /** 是否允许签发携带 external claim(AUTH_EMBED_EXTERNAL_TOKEN,默认开) */
1741
+ embedExternalToken?: boolean;
1742
+ /**
1743
+ * external 原始 token 上限(bytes,评审 P1-H)。
1744
+ * external claim 使自有 JWT 膨胀 ~1.4x(base64url),大 token 会逼近网关/代理 header 上限
1745
+ * (nginx 单 header 默认 8KB;Node http 默认 16KB)。超限拒签(防发出必败请求 + 网关日志泄漏)。
1746
+ * 默认 16KB,可经 AUTH_EXTERNAL_TOKEN_MAX_BYTES 调整。
1747
+ */
1748
+ maxExternalTokenBytes?: number;
1749
+ }
1750
+ interface IssueOptions {
1751
+ /** 外部原始凭据(门控 embedExternalToken) */
1752
+ external?: ExternalCredentials;
1753
+ /** 测试注入时间(ms epoch) */
1754
+ now?: number;
1755
+ }
1756
+ interface TokenService {
1757
+ issue(identity: Identity, opts?: IssueOptions): Promise<{
1758
+ token: string;
1759
+ expiresAt: number;
1760
+ }>;
1761
+ /** 校验并返回 payload;非法/过期抛 AuthError(AUTH_UNAUTHORIZED / AUTH_TOKEN_EXPIRED) */
1762
+ verify(token: string): Promise<TokenPayload>;
1763
+ /**
1764
+ * 续签校验(previousToken 轨):忽略过期(仍验签名/issuer/alg 白名单/sub/source/前缀一致性)。
1765
+ * 仅登录路由续签使用——重签窗(30d)判定归调用方,本方法不裁窗。
1766
+ */
1767
+ verifyIgnoringExpiration(token: string): Promise<TokenPayload>;
1768
+ }
1769
+ declare function createTokenService(opts: TokenServiceOptions): TokenService;
1770
+
1771
+ /**
1772
+ * 共享身份/上下文解析内核(上下文统一化 Stage 1)。
1773
+ *
1774
+ * HTTP 中间件与 WS HELLO 鉴权的共同提取:resolveBearerAuth 统一 Bearer token 三态
1775
+ * (合法 / optional 缺失 → 匿名 / required 缺失或非法 → AuthError),消除双实现漂移;
1776
+ * normalizeContextEnvelope 统一 context 信封归一(plain object + ≤4KB),三入口共用
1777
+ * (WS HELLO / HTTP body.context / login body.context)——超限丢弃走 warn(防静默 scope 交换)。
1778
+ */
1779
+
1780
+ /** 身份解析结果(HTTP 中间件与 WS HELLO 共用形态) */
1781
+ interface ResolvedAuth {
1782
+ identity: Identity;
1783
+ credentials?: ExternalCredentials;
1784
+ }
1785
+ /**
1786
+ * 统一 Bearer 身份解析(middleware.ts 与 ws-auth.ts 的共同内核):
1787
+ * - token 非法 → AuthError(HTTP 层转 401;WS 层转 close 4001)
1788
+ * - token 缺失 + optional → 匿名身份(服务端生成,不签发 JWT)
1789
+ * - token 缺失 + required → AuthError.unauthorized
1790
+ */
1791
+ declare function resolveBearerAuth(tokenService: TokenService, token: string | undefined, mode: 'required' | 'optional'): Promise<ResolvedAuth>;
1792
+ /** context 信封上限(与 login/HELLO context 体积约束同数量级,UTF-8 字节) */
1793
+ declare const CONTEXT_ENVELOPE_MAX_BYTES = 4096;
1794
+ /**
1795
+ * 统一 context 信封归一:plain object 且序列化 ≤4KB(UTF-8)才透传,否则
1796
+ * undefined(fail-soft——非法 context 不阻断主链路)+ 丢弃 warn(可观测:
1797
+ * 客户端意图 scope 不被静默替换)。
1798
+ */
1799
+ declare function normalizeContextEnvelope(raw: unknown): Record<string, unknown> | undefined;
1800
+
1801
+ /**
1802
+ * HTTP 鉴权中间件(006 D7)。
1803
+ * - 读取 `Authorization: Bearer <token>`,校验后把 RequestContext 挂到 req(tboxAuthContext)。
1804
+ * - AUTH_MODE=optional 时缺失 token → 服务端生成匿名身份(不签发 JWT)。
1805
+ * - 白名单路径(登录/健康等)直接放行。
1806
+ * - [HTTP] 访问日志(006 日志轴):reqId 锚点(入站 X-Request-ID 清洗后优先)+ 回写响应头
1807
+ * + runLogScope ALS(请求内全部日志行自动带 req= 尾缀)+ finish 访问行。挂载于 /api 最前,
1808
+ * 单点覆盖全部 API face(含 404);健康探测降 debug。HTTP 面不发 TBOX_TRACE span
1809
+ * (trace 平面只属引擎 run——平台按 conv/req 拉取语义不被污染)。
1810
+ */
1811
+
1812
+ type AuthMode = 'required' | 'optional';
1813
+ interface AuthMiddlewareOptions {
1814
+ mode?: AuthMode;
1815
+ /** 放行路径前缀(如 /api/auth/login、/api/auth/dev-login、/api/health) */
1816
+ publicPaths?: string[];
1817
+ /**
1818
+ * 域校验钩子(上下文统一化 Stage 1):装配端注入(如 mall 白名单——
1819
+ * createAuthRuntime validateContext 转发)。仅当请求携带 context(POST body.context
1820
+ * 归一通过)时调用;拒绝 → 403 AUTH_FORBIDDEN(scope 伪冒防线)。
1821
+ */
1822
+ validateContext?: (attributes: Record<string, unknown>) => boolean;
1823
+ }
1824
+ declare function setRequestContext(req: Request, ctx: RequestContext): void;
1825
+ /** 读取当前请求的运行上下文(authMiddleware 之后可用;未鉴权为 undefined) */
1826
+ declare function getRequestContext(req: Request): RequestContext | undefined;
1827
+ /** 匿名身份(optional 模式 / 缺失 token 时服务端生成;不签发 JWT) */
1828
+ declare function createAnonymousIdentity(now?: number): Identity;
1829
+ declare function createAuthMiddleware(tokenService: TokenService, opts?: AuthMiddlewareOptions): RequestHandler;
1830
+
1831
+ /**
1832
+ * WebSocket 鉴权(006 D6/D7/D12)。
1833
+ * - HELLO 消息体携带 token(不拼 URL,防日志/Referer 泄漏)。
1834
+ * - 校验成功后返回连接级身份(Identity + 可选外部凭据),由 ws-server 绑定到连接。
1835
+ * - optional 模式:无 token 的 HELLO → 匿名身份(服务端生成,不签发 JWT)。
1836
+ * - 身份解析统一走 resolveBearerAuth(与 HTTP 中间件共享内核,消除双实现漂移)。
1837
+ */
1838
+
1839
+ interface AuthenticatedAuth {
1840
+ identity: Identity;
1841
+ credentials?: ExternalCredentials;
1842
+ }
1843
+ interface WsAuthenticator {
1844
+ /** token 校验;缺失/非法抛 AuthError(optional 下缺失 → 匿名身份) */
1845
+ authenticate(token?: string): Promise<AuthenticatedAuth>;
1846
+ }
1847
+ interface WsAuthOptions {
1848
+ mode?: 'required' | 'optional';
1849
+ }
1850
+ declare function createWsAuthenticator(tokenService: TokenService, opts?: WsAuthOptions): WsAuthenticator;
1851
+
1852
+ /**
1853
+ * Provider dev fixture + 内存传输测试工具(011 G6):
1854
+ * - registerDevProviderFixture:非生产挂载点(模块注册假数据处理器);
1855
+ * - createInMemoryTransport:测试工具(脚本化响应/请求记录/故障注入)。
1856
+ */
1857
+
1858
+ interface FixtureHandler {
1859
+ (req: {
1860
+ path: string;
1861
+ body?: unknown;
1862
+ }): unknown;
1863
+ }
1864
+ declare function registerDevProviderFixture(templateId: string, handler: FixtureHandler): void;
1865
+ declare function clearDevProviderFixtures(): void;
1866
+ declare function hasDevProviderFixture(templateId: string): boolean;
1867
+ declare function runDevProviderFixture(templateId: string, req: {
1868
+ path: string;
1869
+ body?: unknown;
1870
+ }): unknown;
1871
+ /** fixture 传输工厂:命中 fixture 的 templateId 走 fixture,其余走真实工厂 */
1872
+ declare function createFixtureTransportFactory(real: TransportFactory): TransportFactory;
1873
+ /** 内存传输测试工具:脚本化响应 / 请求记录 / 故障注入(011 G6) */
1874
+ interface InMemoryTransport extends AuthenticatedTransport {
1875
+ mock(path: string, respond: (body: unknown) => unknown): void;
1876
+ requests(): Array<{
1877
+ path: string;
1878
+ body?: unknown;
1879
+ }>;
1880
+ failNext(error: Error): void;
1881
+ }
1882
+ declare function createInMemoryTransport(): InMemoryTransport;
1883
+
1884
+ /**
1885
+ * 卡片动作 token 签发(011 E7/B3 修复):出卡时按 cardType 匹配注册动作,
1886
+ * 附加 payload.actions(声明)与 payload.actionTokens(HMAC 授权 token)。
1887
+ * - 单一签发点:chat-engine 出卡与 dispatcher 结果卡/原地更新共用本函数;
1888
+ * - 无匹配动作 → 原样返回(零开销);
1889
+ * - 签发失败(如密钥缺失)→ warn + 跳过该动作(不阻断出卡);
1890
+ * - P1 富形状:kind/style/enabled 等呈现字段透传 payload.actions;仅 moduleAction
1891
+ * (含缺省)签发 token——sendMessage/openLink 为纯客户端语义,不进授权链。
1892
+ */
1893
+
1894
+ interface AttachCardActionTokensInput {
1895
+ payload: TboxCardPayload;
1896
+ actions: CardActionRegistry;
1897
+ grants: ActionGrantService;
1898
+ sessionId: string;
1899
+ scope: Record<string, string>;
1900
+ }
1901
+ declare function attachCardActionTokens(input: AttachCardActionTokensInput): Promise<TboxCardPayload>;
1902
+
1903
+ interface KnowledgeHit {
1904
+ content: string;
1905
+ score: number;
1906
+ /** 来源文件名 */
1907
+ originFileName?: string;
1908
+ documentId?: string;
1909
+ metadata?: Record<string, unknown>;
1910
+ }
1911
+ interface KnowledgeClient {
1912
+ search(input: {
1913
+ datasetId: string;
1914
+ query: string;
1915
+ topK?: number;
1916
+ scoreThreshold?: number;
1917
+ }): Promise<KnowledgeHit[]>;
1918
+ }
1919
+ interface KnowledgeClientOptions {
1920
+ apiKey?: string;
1921
+ appId?: string;
1922
+ /** 缺省绑定 datasetId(search 未传时使用) */
1923
+ datasetId?: string;
1924
+ topK?: number;
1925
+ }
1926
+ declare class KnowledgeError extends Error {
1927
+ readonly code: 'MISSING_CREDENTIAL' | 'API_ERROR' | 'EMPTY_RESULT';
1928
+ constructor(code: 'MISSING_CREDENTIAL' | 'API_ERROR' | 'EMPTY_RESULT', message: string);
1929
+ }
1930
+ declare function createKnowledgeClient(opts?: KnowledgeClientOptions): KnowledgeClient;
1931
+
1932
+ /**
1933
+ * 平台支付客户端(011 A3:首期纳入支付,SDK 通道层,业务闭环二期)。
1934
+ * 支付宝收银台薄客户端:创建收银台 + 结果查询。
1935
+ * 平台支付 API 未就绪前 createCashier 抛「未装配」;就绪后经平台接口对接。
1936
+ */
1937
+ interface CashierResult {
1938
+ cashierUrl: string;
1939
+ }
1940
+ type PaymentStatus = 'PAID' | 'PENDING' | 'FAILED' | 'UNKNOWN';
1941
+ interface PaymentClient {
1942
+ createCashier(input: {
1943
+ orderRef: string;
1944
+ amountCents: number;
1945
+ subject: string;
1946
+ }): Promise<CashierResult>;
1947
+ queryResult(input: {
1948
+ orderRef: string;
1949
+ }): Promise<{
1950
+ status: PaymentStatus;
1951
+ }>;
1952
+ }
1953
+ interface PaymentClientOptions {
1954
+ /** 宿主注入处理器(模板装配点):对接平台收银台 API */
1955
+ createCashierHandler?: (input: {
1956
+ orderRef: string;
1957
+ amountCents: number;
1958
+ subject: string;
1959
+ }) => Promise<CashierResult>;
1960
+ queryResultHandler?: (input: {
1961
+ orderRef: string;
1962
+ }) => Promise<{
1963
+ status: PaymentStatus;
1964
+ }>;
1965
+ }
1966
+ declare class PaymentError extends Error {
1967
+ readonly code: 'NOT_CONFIGURED' | 'API_ERROR';
1968
+ constructor(code: 'NOT_CONFIGURED' | 'API_ERROR', message: string);
1969
+ }
1970
+ declare function createPaymentClient(opts?: PaymentClientOptions): PaymentClient;
1971
+
1972
+ /**
1973
+ * 模块资源 resolver(integrations v5:modules 节内存源求值)。
1974
+ * 分层归位:wire 类型 = contracts(ResourceSpec/ModuleConfig);zod = integrations-config.ts;
1975
+ * 本文件只做 IO 密封——knowledge.json 台账 ref 展开(锚 = integrations.json 所在目录,与数据同源旅行)。
1976
+ * 预计算模型:构造期一次算清(ref-miss/参数问题 warn 一次打在启动日志),调用期纯 Map 查表。
1977
+ * 资源级 fail-soft:miss → 资源缺席(模块占位回退,与缺键同语义)。
1978
+ */
1979
+
1980
+ /** 求值产物(ref 已展开;datasetId 必填——resolver/占位常量保证) */
1981
+ type ResolvedResource = {
1982
+ type: 'knowledge';
1983
+ datasetId: string;
1984
+ topK?: number;
1985
+ scoreThreshold?: number;
1986
+ };
1987
+ /** resolver 服务契约(app-config 服务注册物;键 = 模块 install id) */
1988
+ type ModuleResourceResolver = (moduleId: string) => Readonly<Record<string, ResolvedResource>>;
1989
+ /** 占位 datasetId 哨兵单源(模块占位常量 + smoke R1 判定共用;'faq'/'mall-knowledge' 历史值) */
1990
+ declare const KNOWLEDGE_PLACEHOLDER_DATASET_IDS: readonly ["faq", "mall-knowledge"];
1991
+ /**
1992
+ * 预计算工厂。modules 缺席(裸跑态/无资源应用)→ 空 resolver 零 IO;
1993
+ * 无 ref 声明 → 跳过台账读(模板态/直填态零额外 IO)。
1994
+ * knowledgeDir = integrations.json 所在目录(ref 台账与数据同源——TBOX_INTEGRATIONS_FILE 逃生舱防 split-brain)。
1995
+ */
1996
+ declare function createModuleResourceResolver(modules: Record<string, ModuleConfig> | undefined, knowledgeDir: string): ModuleResourceResolver;
1997
+
1998
+ interface KnowledgeBaseEntry {
1999
+ datasetId: string;
2000
+ topK?: number;
2001
+ scoreThreshold?: number;
2002
+ }
2003
+ interface KnowledgeRegistry {
2004
+ /** name → 展平条目(retrieve_config 已并入) */
2005
+ bases: Readonly<Record<string, KnowledgeBaseEntry>>;
2006
+ /** 台账全局缺省参数(仅 ref 展开期参与兜底) */
2007
+ defaults: {
2008
+ topK?: number;
2009
+ scoreThreshold?: number;
2010
+ };
2011
+ }
2012
+ /**
2013
+ * 读取 config/knowledge.json(configDir 与组件 json 同目录)。
2014
+ * 缺文件静默空(模板态常态);解析/校验失败 warn + 空(fail-soft)。
2015
+ */
2016
+ declare function loadKnowledgeRegistry(configDir: string): KnowledgeRegistry;
2017
+
2018
+ interface EnvExpansionErrorInfo {
2019
+ file: string;
2020
+ missing: string[];
2021
+ }
2022
+ /** 展开配置文本;缺失变量 → throw(信息含文件 + 缺失清单 + source 指引,不含值) */
2023
+ declare function expandEnvVars(text: string, env?: Readonly<Record<string, string | undefined>>, file?: string): string;
2024
+
2025
+ type Environment = Readonly<Record<string, string | undefined>>;
2026
+ interface AlipayAuthorizedUserProfile {
2027
+ readonly userId: string;
2028
+ readonly mobile?: string;
2029
+ readonly displayName?: string;
2030
+ readonly avatarUrl?: string;
2031
+ readonly gender?: 'male' | 'female' | 'unknown';
2032
+ readonly birthday?: string;
2033
+ }
2034
+ interface AlipayUserAuthorization {
2035
+ authorizeUserProfile(authCode: string): Promise<AlipayAuthorizedUserProfile>;
2036
+ }
2037
+ declare function createAlipayUserAuthorization(environment?: Environment, fetchImplementation?: typeof fetch): AlipayUserAuthorization;
2038
+ declare function formatAlipayTimestamp(date: Date): string;
2039
+ declare function toPem(raw: string, kind: 'PRIVATE' | 'PUBLIC'): string;
2040
+ declare function signAlipayParams(params: Readonly<Record<string, string>>, privateKey: string): string;
2041
+
2042
+ interface AuthConfig {
2043
+ secret: string;
2044
+ /** HS256 密钥链来源(日志/提醒用):platform | apiKey | dev-temp */
2045
+ secretSource: 'platform' | 'apiKey' | 'dev-temp';
2046
+ /** required=强制鉴权;optional=缺失 token 时匿名(降级,不放开写通道) */
2047
+ mode: 'required' | 'optional';
2048
+ issuer?: string;
2049
+ ttlMs?: number;
2050
+ /** 是否内嵌外部原始 token(external claim) */
2051
+ embedExternalToken: boolean;
2052
+ /** external 原始 token 上限(bytes,防 header 膨胀;缺省 16KB) */
2053
+ externalTokenMaxBytes?: number;
2054
+ /** 外部 provider 配置(换发用),未配置则走本地换码 */
2055
+ external?: {
2056
+ exchangeUrl: string;
2057
+ secret: string;
2058
+ provider: string;
2059
+ timeoutMs: number;
2060
+ /** 外部已签 JWT 验签公钥(PEM, RS256):`{ jwt }` 响应无 identity 时解 sub */
2061
+ jwtPublicKey?: string;
2062
+ };
2063
+ }
2064
+ declare function readAuthConfig(env?: NodeJS.ProcessEnv): AuthConfig;
2065
+ /** 由配置装配 TokenService(单一装配点:createAuthRuntime(readAuthConfig())) */
2066
+ declare function createTokenServiceFromConfig(config: AuthConfig): TokenService;
2067
+
2068
+ /**
2069
+ * 统一鉴权装配点(006 §2 平台轴 + 业务轴):createAuthRuntime(readAuthConfig())。
2070
+ * 产出:tokenService(签发/校验)+ middleware(HTTP Bearer)+ router(login/me)
2071
+ * + wsAuth(WS HELLO 鉴权)。
2072
+ * 扩展点(B4):options.exchanges 注入自定义/覆盖本地换码器(注入优先于内置 alipay/weapp)。
2073
+ */
2074
+
2075
+ interface AuthRuntime {
2076
+ config: AuthConfig;
2077
+ tokenService: TokenService;
2078
+ /** HTTP Bearer 鉴权中间件(全局 /api,白名单放行 login/health) */
2079
+ middleware: RequestHandler;
2080
+ /** 登录/身份路由(POST /api/auth/login、GET /api/auth/me) */
2081
+ router: Router;
2082
+ /** WS HELLO 鉴权器 */
2083
+ wsAuth: WsAuthenticator;
2084
+ /** 是否启用外部 provider 换发 */
2085
+ externalEnabled: boolean;
2086
+ /**
2087
+ * 换码器注册表(F0 惰性查找):登录请求期 get(platform)。模板装配应将其传入
2088
+ * createServerContext({ authExchanges })——模块/provider register 期注册晚于本构造仍生效。
2089
+ */
2090
+ exchanges: AuthExchangeRegistry;
2091
+ }
2092
+ interface AuthRuntimeOptions {
2093
+ /** 自定义/覆盖本地换码器(key = platform,如 alipay/weapp;注入优先于内置) */
2094
+ exchanges?: Record<string, IdentityExchange>;
2095
+ /**
2096
+ * 域校验钩子(上下文统一化 Stage 1):转发给全局 HTTP 中间件的 validateContext
2097
+ * (POST body.context 归一通过后调用;拒绝 → 403)。只注入全局面——login/dev-login
2098
+ * 的 body.context 有独立归一化(login-routes)+ 换码器 scoped 路由语义,不重复治理。
2099
+ */
2100
+ validateContext?: (attributes: Record<string, unknown>) => boolean;
2101
+ }
2102
+ declare function createAuthRuntime(envOrConfig?: NodeJS.ProcessEnv | AuthConfig, options?: AuthRuntimeOptions): AuthRuntime;
2103
+
2104
+ /** 微信 jscode2session:code → openid */
2105
+ declare class LocalWeappExchange implements IdentityExchange {
2106
+ readonly provider = "weapp";
2107
+ /** 裸/demo 域默认开放 guest 登录(browser 轴 auto 档 → guest 签发) */
2108
+ allowsGuestLogin(): boolean;
2109
+ exchangeByCode({ code }: ExchangeRequest): Promise<ExchangeResult>;
2110
+ }
2111
+ /** 支付宝 alipay.system.oauth.token:code → userId */
2112
+ declare class LocalAlipayExchange implements IdentityExchange {
2113
+ readonly provider = "alipay";
2114
+ /** 裸/demo 域默认开放 guest 登录(browser 轴 auto 档 → guest 签发) */
2115
+ allowsGuestLogin(): boolean;
2116
+ exchangeByCode({ code }: ExchangeRequest): Promise<ExchangeResult>;
2117
+ }
2118
+
2119
+ /**
2120
+ * 外部身份字段映射(006 D4 修订):外部返回的原始身份对象 → 自有 Identity。
2121
+ * - **userId 原样保留**(不加 ext_ 前缀、不做前缀归一化——外部系统自管命名空间,
2122
+ * 平台不改造外部 id,便于与外部体系直接对应);
2123
+ * - source 恒为 'external'(来源由 source 字段区分,不依赖 userId 前缀);
2124
+ * - displayName/avatar 可选透传;
2125
+ * - 字段名覆盖常见外部语义(userId/openId/uid/id/unionId),自定义映射由业务方扩展。
2126
+ */
2127
+
2128
+ interface ExternalRawIdentity {
2129
+ userId?: string;
2130
+ openId?: string;
2131
+ openid?: string;
2132
+ uid?: string;
2133
+ id?: string;
2134
+ unionId?: string;
2135
+ displayName?: string;
2136
+ nickname?: string;
2137
+ name?: string;
2138
+ avatar?: string;
2139
+ avatarUrl?: string;
2140
+ [k: string]: unknown;
2141
+ }
2142
+ declare function mapExternalIdentity(raw: ExternalRawIdentity): Identity;
2143
+
2144
+ interface ExternalExchangeOptions {
2145
+ exchangeUrl: string;
2146
+ secret: string;
2147
+ provider: string;
2148
+ timeoutMs?: number;
2149
+ /** 自定义外部响应 → 身份映射(缺省 mapExternalIdentity) */
2150
+ mapIdentity?: (raw: ExternalRawIdentity) => Identity;
2151
+ /** 外部已签 JWT 验签器(配置 AUTH_EXTERNAL_JWT_PUBLIC_KEY 时由 runtime 装配);解出 payload 后提取 sub */
2152
+ verifyJwt?: (jwt: string) => Promise<{
2153
+ sub: string;
2154
+ displayName?: string;
2155
+ avatar?: string;
2156
+ }>;
2157
+ }
2158
+ declare class ExternalIdentityExchange implements IdentityExchange {
2159
+ private readonly opts;
2160
+ readonly provider: string;
2161
+ constructor(opts: ExternalExchangeOptions);
2162
+ exchangeByCode({ code, platform }: ExchangeRequest): Promise<ExchangeResult>;
2163
+ private postOnce;
2164
+ /**
2165
+ * 重试语义(评审 P0-1 修复):HTTP 4xx 不重试(外部业务拒绝);
2166
+ * HTTP 5xx / 网络错误(fetch reject)/ 超时(AbortError)→ 单次重试。
2167
+ * 换码幂等,重试安全;timestamp/sign 复用不影响(防重放窗口 5min >> 重试间隔)。
2168
+ */
2169
+ private postWithRetry;
2170
+ /** 三态收敛:任意响应形态 → ExchangeResult */
2171
+ private converge;
2172
+ /** jwt 形态身份提取(三级,见文件头;sub 原样保留,不包前缀) */
2173
+ private resolveJwtIdentity;
2174
+ /** 无外部 id 时的 opaque 回退派生 id:opaque_<sha256>(opaque token 会话内稳定;轮换则身份漂移,外部应提供 identity) */
2175
+ private deriveFallbackId;
2176
+ private mapIdentity;
2177
+ }
2178
+
2179
+ export { ACTION_GRANT_MAX_TTL_MS, type ActionCheck, type ActionContext, type ActionGateway, ActionGrantError, type ActionGrantOptions, type ActionGrantService, type ActionHandler, type ActionPolicy, type ActionResult, type AlipayAuthorizedUserProfile, type AlipayUserAuthorization, ApiRouteRegistry, type AttachCardActionTokensInput, type AuthConfig, AuthError, type AuthExchangeRegistry, type AuthMiddlewareOptions, type AuthMode, type AuthRuntime, type AuthRuntimeOptions, type AuthenticatedAuth, CONTEXT_ENVELOPE_MAX_BYTES, type CardActionRegistry, type CardEmit, CardEmitter, CardRegistry, type CardSnapshotStore, type CashierResult, type CircuitBreakerConfig, type ComponentStateStore, DomainAssemblyRegistry, EXTERNAL_SLOW_MS, EffectError, type EffectRuntime, type EffectRuntimeOptions, type EmitCardSpec, type EnvExpansionErrorInfo, type EnvironmentSecretProvider, type EventMap, type ExternalExchangeOptions, ExternalIdentityExchange, type ExternalRawIdentity, type FlowStateStore, type GrantRecord, type HandlerDefinition, HandlerRegistry, type HandlerResult, type IdempotencyStore, InMemoryCardSnapshotStore, InMemoryIdempotencyStore, InMemoryLruReplayStore, type InMemoryTransport, type InferToolArgs, type IntegrationsRaw, type IntegrationsRegistry, type IntegrationsRegistryOptions, type IssueOptions, KNOWLEDGE_PLACEHOLDER_DATASET_IDS, type KnowledgeBaseEntry, type KnowledgeClient, type KnowledgeClientOptions, KnowledgeError, type KnowledgeHit, type KnowledgeRegistry, LocalAlipayExchange, type LocalSkill, LocalWeappExchange, type LoginExchangeResolution, type ModuleActionDispatcher, type ModuleActionDispatcherOptions, ModuleActionError, type ModuleResourceResolver, type ModuleServerRegister, NOTICE_TEXT_MAX_LEN, type PaymentClient, type PaymentClientOptions, PaymentError, type PaymentStatus, type PreToolDecideInput, type PreToolDecision, type PreToolDef, type PreToolHistoryTurn, type PreToolLocationContext, PreToolRegistry, type PreToolRouting, type PreToolUserContext, type ProviderAuthStrategy, type ProviderAuthStrategyInput, ProviderError, type RegisteredModuleAction, type RegistryTool, type ReplayStore, type ResolvedAuth, type ResolvedResource, SKILL_LIMITS, STATIC_HEADERS_CREDENTIAL_TYPE, type ScopeSession, ScopeSessionError, type ScopeSessionRegistry, type ScopeSessionRegistryOptions, type SecretSource, type ServerContext, type ServerLogScope, type ServerLogger, type ServerModule, type ServerSpanPayload, type ServerSpanSink, type ServiceAdapterFactory, type ServiceAdapterInput, ServiceRegistry, SkillRegistry, type StoredEntry, TTS_DEFAULTS, TboxAppClient, TboxAsrClient, TboxConversationClient, TboxFeedbackClient, TboxTtsClient, TboxUploadClient, type TokenService, type TokenServiceOptions, ToolRegistry, type TransportFactory, type TransportFactoryOptions, type TtsVoiceConfig, type TypedBus, type WsAuthOptions, type WsAuthenticator, attachCardActionTokens, clearDevProviderFixtures, clearServices, collectIntentRoutes, createActionGateway, createActionGrantService, createAlipayUserAuthorization, createAnonymousIdentity, createAuthExchangeRegistry, createAuthMiddleware, createAuthRuntime, createAuthStrategyRegistry, createAuthenticatedTransportFactory, createEffectRuntime, createEnvironmentSecretProvider, createFixtureTransportFactory, createInMemoryStateStore, createInMemoryTransport, createIntegrationsRegistry, createKnowledgeClient, createModuleActionDispatcher, createModuleResourceResolver, createPaymentClient, createScopeSessionRegistry, createServerContext, createServerLogger, createTokenService, createTokenServiceFromConfig, createTypedBus, createWsAuthenticator, deriveActionGrantKey, expandEnvVars, formatAlipayTimestamp, getRequestContext, hasDevProviderFixture, hashPayload, hashStateRef, loadKnowledgeRegistry, mapExternalIdentity, normalizeContextEnvelope, readAuthConfig, recordCall, registerDevProviderFixture, registerServerModules, registerService, resolveBearerAuth, resolveService, runDevProviderFixture, runLogScope, runWithLogContext, setRequestContext, setServerSpanSink, signAlipayParams, staticHeadersStrategy, toNoticeText, toPem, truncateNoticeText, withCallLog };